carlos / platform Public

design: tunnel WebSockets (#471), spec rev 1

Upgrades cross the fleet tunnel as one ordinary HTTP/2 stream carrying
the HTTP/1.1 upgrade verbatim (Carlos-Tunnel-Upgrade marker, in-band 101,
shim in tunnelclient.Mark), gated by a registration capability so no
release floor is needed. The hub stays the one enforcement point and
CloseAccountUpgrades closes a real socket end to end. Per-box cap of 128
upgrades and a 160 MiB box connection window keep plain traffic from
being starved. Options A (RFC 8441, off by default in x/net) and C
(dedicated channel) considered and rejected. Five open questions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 92fb3af34714a8367d026f8709d99da5573e3940 parent 65fd806
1 file changed, +819 −0
  • docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md +819 −0
diff --git a/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
new file mode 100644
index 000000000..c3bd2c6a1
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-30-tunnel-websockets-design.md
@@ -0,0 +1,819 @@
+# Tunnel WebSockets: upgraded connections through the fleet tunnel
+
+Status: DRAFT rev 1, 2026-10-30. Discussion: amadan carlos/platform #471.
+Branch `design-tunnel-websockets-471`, cut from main `65fd8060` (fleet
+public routes, #457 Phase 1a). Every repo file:line below is on that
+commit. Library lines are `golang.org/x/net v0.60.0` (`go.mod:28`) and the
+Go 1.26.10 standard library.
+
+Review history: none yet. Round budget per AGENTS.md "Stopping rules":
+stop at the first round with no P1; a fourth round needs Paul.
+
+## 0. Status
+
+Rev 1, written for Paul and one Astra round. Five open questions (§11),
+each with a recommendation.
+
+## 1. Intent
+
+A fleet app answers at its public URL through the hub since v0.32.0 on dev.
+Plain HTTP works. A WebSocket does not: the hub answers every handshake for
+a fleet-placed route with 502. Rails apps lose Action Cable, so the rootfs
+sample `examples/rails-shop` (Solid Cable, live at
+`https://shop.bab.dev.oncarlos.com`) gets no live updates.
+
+After this change a WebSocket handshake to a fleet app gets the app's own
+101, and the socket stays open across the tunnel with the same rules a
+platform-hosted app has today: the hub limits it once, the fleet box's
+password gate guards it, and a throttle closes it for real.
+
+Checked on dev, read-only, 2026-10-30 20:29Z:
+
+ curl -s -o /dev/null -w '%{http_code}\n' https://shop.bab.dev.oncarlos.com/up
+ 200
+ curl -s --http1.1 -i -H 'Connection: Upgrade' -H 'Upgrade: websocket' \
+ -H 'Sec-WebSocket-Version: 13' -H 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==' \
+ -H 'Sec-WebSocket-Protocol: actioncable-v1-json' \
+ -H 'Origin: https://shop.bab.dev.oncarlos.com' https://shop.bab.dev.oncarlos.com/cable
+ HTTP/1.1 502 Bad Gateway
+
+Acceptance is the same handshake answering `101 Switching Protocols`,
+followed by Action Cable's `{"type":"welcome"}` frame and its 3-second
+pings (§8.3).
+
+## 2. Goals and non-goals
+
+Goals:
+
+1. Any HTTP/1.1 upgrade (WebSocket in practice) to a route the hub serves
+ through `TunnelHub` crosses the tunnel and reaches the app on the box.
+ That covers `ArmForward`, `ArmFleet` and `ArmTunnel` rows, since all
+ three share one transport (§3.4).
+2. The hub stays the one enforcement point: rate limit, plan throttle,
+ upgrade tracking, and `CloseAccountUpgrades` closing a real open socket
+ end to end, app side included.
+3. The fleet box keeps the password gate, and the gate guards the
+ handshake.
+4. Tunnel loss, box restart, hub restart, re-registration, detach, swaps
+ and overlap deploys all close or drain upgraded sockets, in bounded
+ time, with no leaked state on either side.
+5. Open WebSockets can never starve a box's plain HTTP traffic across the
+ tunnel (stream slots and flow-control windows, §4.8).
+6. No bucket requests, no release floor, no switch.
+
+Non-goals:
+
+- WebSockets over HTTP/2 from browsers (RFC 8441 at the public listener).
+ Browsers already fall back to HTTP/1.1 for WebSockets everywhere on the
+ platform.
+- Metering upgraded bytes. No edge meters them today (§3.7); this keeps
+ parity.
+- Idle timeouts on upgraded sockets. No edge has one today (§4.8).
+- Plan 6 sessions (`carlos run -it`, `carlos console`). §9 says how they
+ relate.
+- #432 (edge-held SSE streams). SSE already crosses the tunnel as an
+ ordinary streamed HTTP/2 response.
+- The client address a fleet app sees (§10.1). Found while writing this;
+ separate.
+
+## 3. What happens today
+
+### 3.1 How the tunnel is built
+
+A fleet box dials out. `tunnelLoop` (`internal/host/tunnel_client.go:35-58`)
+reads `CARLOS_TUNNEL_URL`, `_NAME` and `_TOKEN` and runs
+`tunnelclient.Loop` with the box's whole edge as the handler
+(`go tunnelLoop(e)`, `internal/host/agent.go:1026`).
+
+`tunnelclient.Dial` (`internal/tunnelclient/tunnelclient.go:190-262`) opens
+TLS to the hub's :443 with ALPN pinned to `http/1.1` (`:206-209`) and sends
+
+ GET /register
+ Authorization: Bearer <token>
+ Carlos-Tunnel-Name: <fleet>/<label>
+ Connection: Upgrade
+ Upgrade: carlos-tunnel/1
+
+(`:228-238`). The hub (`TunnelHub.ServeHTTP`, `internal/edge/tunnel.go:122-217`)
+authenticates the name and token against its static map or the fleet
+table (`:133-163`), checks the protocol token (`:172-176`), hijacks the
+conn, writes its own 101 (`:197`), and then **inverts the roles**: the hub
+becomes the HTTP/2 client (`http2.Transport{}.NewClientConn(conn)`,
+`:202-203`) and the box serves HTTP/2 on the same conn
+(`tunnelclient.Serve`, `tunnelclient.go:291-293`, a zero-value
+`http2.Server`). The file's header records the choice: reverse h2 rather
+than a WebSocket port of titogo's tunnel, because x/net already supplies
+the mux, flow control and pings (`tunnel.go:1-8`).
+
+So the tunnel's only multiplexer is HTTP/2. There is no mux of CARLOS's
+own and no stream type besides an HTTP/2 request. Streams are opened by
+the hub only: the box is the HTTP/2 server.
+
+Liveness: the hub pings every 5 s with a 5 s deadline on fleet channels
+(`tunnel.go:58-59`, `pingLoop` `:225-247`). A failed ping closes the raw
+conn. A re-registration under the same name closes the old conn
+(`:210-211`). Detach (`SetDynamicAuth`, `:314-324`) force-closes a channel
+through `CloseChannel` (`:333-346`); rotation leaves it open.
+
+### 3.2 Where the refusal happens
+
+1. The hub's `ServeHTTP` sends a handshake down its upgrade branch
+ (`internal/edge/edge.go:2117-2143`): `trackUpgrade`, `planUpgradeAdmit`,
+ `rateAdmit` with a `slotWriter`, then `up.proxy.ServeHTTP`.
+2. `up.proxy` for a fleet-placed row is `fleetProxy` (`edge.go:3243-3274`;
+ bound at `:852-856` for `ArmForward` and `:922-926` for `ArmFleet`), or
+ `tunnelProxy` for a `-tunnel` row (`:3187-3200`, bound at `:894-898`).
+3. The stdlib reverse proxy strips hop-by-hop headers and adds back
+ `Connection: Upgrade` and `Upgrade: websocket`
+ (`net/http/httputil/reverseproxy.go:477-497`).
+4. Its transport is `hub.transportFor(name)` (`tunnel.go:393-401`;
+ `fleetProxy` reaches it at `edge.go:3258`), which calls
+ `http2.ClientConn.RoundTrip`.
+5. x/net refuses any request carrying `Upgrade`
+ (`internal/httpcommon/request.go:299-301`, `checkConnHeaders`): "http2:
+ invalid Upgrade request header".
+6. `fleetProxy`'s ErrorHandler logs it, notes `CauseTunnel`
+ (`tunnelCause`, `edge.go:642-647`) and answers a bare 502
+ (`edge.go:3270-3272`).
+
+The box never sees the request. This is true for every fleet-placed and
+`-tunnel` route since the tunnel was written; 1a only made more of them.
+`TestForwardUpgradeIsLimitedAtTheHub`
+(`internal/edge/fleetforward_policy_test.go:175-197`) pins the 502.
+
+### 3.3 Other users of the tunnel and its credential
+
+| user | transport | direction |
+|---|---|---|
+| fleet and forward routes (`fleetProxy`) | HTTP/2 stream on the tunnel | hub to box |
+| `-tunnel` routes (`tunnelProxy`, static channels such as an office box) | HTTP/2 stream on the tunnel | hub to box |
+| the store door (`internal/edge/storedoor.go:1-20`, client `internal/fleetapi/fleetapi.go:46-126`) | ordinary HTTPS to the tunnel hostname, same bearer and `Carlos-Tunnel-Name` headers, `VerifyDynamic` (`storedoor.go:123`) | box to hub, separate connection |
+| registration (`/register`) | HTTP/1.1, then the conn becomes the tunnel | box to hub |
+| Plan 6 interactive sessions and fleet `carlos run` (not built) | a WebSocket the box dials to the console's box door, over ordinary HTTPS (`docs/superpowers/plans/2026-10-24-rootfs-apps-6-interactive.md:7`, `:54-59`) | box to console |
+
+Nothing carries a bidirectional stream over the tunnel today. What
+crosses is request and response: request bodies stream up, and response
+bodies stream down with flushes (SSE works this way). No caller opens a
+full-duplex stream.
+
+### 3.4 One transport for three arms
+
+`ArmForward`, `ArmFleet` and `ArmTunnel` all end in `transportFor`
+(`tunnel.go:393-401`). A fix there serves all three, and nothing else in
+the edge reaches a tunnel.
+
+### 3.5 Request policy for an upgrade at the hub
+
+From 1a's Task 5 (fleet public routes spec §4.8):
+
+- `trackUpgrade` (`internal/edge/planthrottle.go:102-128`) wraps the
+ request context in a cancel registered under the account, for an
+ instance or a forward row on a plan-governed account.
+- `planUpgradeAdmit` (`planthrottle.go:85-92`) refuses an awake-throttled
+ account's upgrade with 429.
+- `rateAdmit` (`internal/edge/ratelimit.go:124-131`) holds a slot until the
+ 101; `slotWriter.Hijack` gives it back (`ratelimit.go:231-240`).
+- `CloseAccountUpgrades` (`planthrottle.go:132-141`) cancels those
+ contexts. The agent calls it when an account becomes awake-throttled
+ (`internal/host/agent.go:1054-1059`).
+- The stdlib proxy closes the backend side of an upgraded connection when
+ the request context is done (`reverseproxy.go:860-870`). That is the
+ whole close mechanism: cancel the context, and the proxy closes
+ `backConn`.
+
+The fleet edge exempts tunneled requests from the rate limit, plan
+throttle, guard and request records (`fromTunnel`: `ratelimit.go:130`,
+`planthrottle.go:60`, `edge.go:2027`, `reqrecords.go:64`).
+
+Today `TestForwardPlanThrottleAndUpgradeClose`
+(`fleetforward_policy_test.go:199-258`) can only show the close at the
+instant of the handshake, because no socket stays open across the tunnel.
+
+### 3.6 The gate on the fleet box
+
+The hub does no gate work for a forward host (1a §4.8, R2-1). On the box,
+`gate.Admit` runs before the upgrade branch (`edge.go:2083-2104`), so a
+handshake without the cookie gets the gate's answer, and `Admit` strips
+the cookie before the app.
+
+### 3.7 What else an upgrade touches on a platform box
+
+- Hijack passes through the usage meter (`countingWriter.Hijack`,
+ `internal/edge/usagemeter.go:138-144`), the rate limit's `slotWriter`
+ and the recorder. The meter counts the 101 and nothing after it.
+- The activator counts an open socket as in flight, which keeps a
+ hibernating instance awake (`internal/activator/activator.go:552-557`).
+- A swap retires a generation: the edge closes the retiring pool's idle
+ connections (`internal/edge/genproxy.go:185-188`), and the retiring
+ process drains under its own SIGTERM, bounded by `actStopTimeout`
+ (`internal/activator/swap.go:728-747`). A hijacked socket is not in a
+ pool; it ends when the retiring process exits.
+- The edge has no read or write timeouts, on purpose, so proxied
+ WebSockets live (`edge.go:3940-3942`). On shutdown, hijacked
+ connections are not drained; they die with the process and the client
+ reconnects (`edge.go:4152-4161`).
+
+### 3.8 Limits the tunnel already has
+
+- Stream slots. The box's `http2.Server{}` advertises the x/net default of
+ 250 concurrent streams (`x/net/http2/server.go:62`, `config.go:101`).
+ The hub has exactly one `ClientConn` per channel, and a request beyond
+ the limit waits for a slot (`transport.go:1411-1413`). **250 open
+ WebSockets on one box would freeze every other request to that box.**
+- Flow control, hub to box. The box's receive windows are the server
+ defaults: 1 MiB per stream and **1 MiB per connection**
+ (`config.go:105-110`). Unread data on one stream holds connection
+ window. **One upgraded socket whose app stops reading would pin the
+ whole window and stall every request body on that tunnel.**
+- Flow control, box to hub. The hub's receive windows are the transport
+ defaults: 4 MiB per stream and 1 GiB per connection
+ (`transport.go:42-47`). No head-of-line risk; memory at the hub is
+ bounded per stream.
+
+Neither of the first two bites today, because every stream is short. A
+WebSocket is not.
+
+### 3.9 Extended CONNECT in this x/net
+
+x/net v0.60.0 has RFC 8441 on both sides, but turns it off by default for
+the whole process (`http2/http2.go:42-49`, enabled only by
+`GODEBUG=http2xconnect=1`, `:62-64`). The comment cites Go issue #71128:
+with it on, browsers try WebSockets over HTTP/2 and break servers whose
+WebSocket code cannot handle it. The box's public listener is such a
+server.
+
+## 4. Design
+
+### 4.1 In one paragraph
+
+An upgrade crosses the tunnel as **one ordinary HTTP/2 stream carrying the
+HTTP/1.1 upgrade verbatim**. The hub sends the handshake as an HTTP/2
+request with `Connection` and `Upgrade` replaced by one header,
+`Carlos-Tunnel-Upgrade: <protocol>`, and a request body that stays open.
+On the box, a small shim inside `tunnelclient.Mark` turns that back into
+an HTTP/1.1 upgrade request and hands the box's edge a hijackable writer
+built on the stream. The box's edge runs exactly the code it runs for a
+platform client: gate, activator, reverse proxy to the app, 101, splice.
+When the box's proxy hijacks, the shim answers the stream with HTTP/2
+`200` plus `Carlos-Tunnel-Upgraded: 1`, and from then on the stream's
+DATA frames are the raw bytes the box's proxy writes: first the app's
+HTTP/1.1 101, then the WebSocket bytes. The hub reads that 101 off the
+stream and hands its own reverse proxy a `101` response whose body is the
+stream, so the hub's proxy hijacks the client and splices, as it does for
+a local app. Both halves live in `internal/tunnelclient`, the leaf
+package both sides already import. A box says it speaks this in its
+registration, so an old box keeps today's 502 and no floor is needed.
+
+### 4.2 Why this shape (options)
+
+**Option A: RFC 8441 extended CONNECT over the existing tunnel.** The hub
+sends `CONNECT` with `:protocol websocket`; the box answers 200; the
+stream carries WebSocket frames.
+
+- Needs `GODEBUG=http2xconnect=1` in the box's process, which is global
+ (§3.9). That turns extended CONNECT on for the box's public listener
+ too, the failure #71128 describes. The hub would need it as well.
+- The handshake changes meaning. RFC 8441 drops `Sec-WebSocket-Key` and
+ `Sec-WebSocket-Accept` and answers 200, not 101. The hub must
+ synthesize a 101 and its own `Accept` for the browser, and the box must
+ synthesize an HTTP/1.1 handshake with a fresh key for the app and check
+ the app's `Accept`. Two translators, each a place to get the handshake
+ subtly wrong.
+- WebSocket only. Any other upgrade token still fails.
+- Gains nothing over B: same stream, same flow control.
+
+**Option B: the HTTP/1.1 upgrade carried verbatim in one HTTP/2 stream
+(recommended).** As §4.1.
+
+- No GODEBUG, no change to the box's public listener, no protocol
+ version bump: the stream is an ordinary HTTP/2 request on the existing
+ `carlos-tunnel/1` connection.
+- The handshake is end to end. The browser's key reaches the app, the
+ app's `Accept`, subprotocol (`actioncable-v1-json`) and extensions
+ (`permessage-deflate`) reach the browser, and neither edge parses
+ WebSocket frames.
+- Both edges keep the stdlib proxy's own upgrade path unchanged: the hub
+ sees a 101 with a read-write body, the box sees a hijackable writer.
+ Gate, activator, swap and close behaviour on the box are the code
+ platform boxes already run.
+- Costs: one marker header pair with a trust rule (§4.4), and the flow
+ control and slot work (§4.8), which any option needs.
+
+**Option C: a dedicated upgrade channel.** For each upgrade, the hub asks
+the box (over the tunnel) to dial a fresh TLS connection back to the hub
+carrying a one-time ticket, and splices the client onto it. Or a second
+long-lived raw mux (yamux) beside the HTTP/2 one.
+
+- A TLS dial and a ticket round trip per socket, so slower handshakes
+ and a new credential with its own replay and expiry rules.
+- No head-of-line coupling with plain traffic, which is its one real
+ advantage. §4.8 gets the same property inside one connection.
+- The second-mux variant is a new protocol version on both ends and a
+ second liveness story. That is the rewrite `tunnel.go:1-8` chose to
+ avoid.
+
+**Recommendation: B.** It is the smallest change that keeps the
+handshake end to end and reuses, on both edges, the upgrade path every
+platform app already runs.
+
+### 4.3 The handshake, step by step
+
+1. Browser to hub: HTTP/1.1 `GET /cable` with `Connection: Upgrade`,
+ `Upgrade: websocket`, `Sec-WebSocket-*`, `Origin`, `Cookie`.
+2. Hub `ServeHTTP` (unchanged): guard, geo, forwarded key, lookup to the
+ forward row, then the upgrade branch (§4.6): `trackUpgrade`,
+ `planUpgradeAdmit`, `rateAdmit`, `fleetProxy`.
+3. Hub `fleetProxy.Rewrite` (unchanged, plus one scrub, §4.4): sets
+ `X-Forwarded-*`, geo, `Host`, scrubs `Carlos-Purge`.
+4. Hub `transportFor(name)` sees an upgrade (`Connection` carries the
+ `Upgrade` token and `Upgrade` is set; the same predicate the stdlib
+ proxy uses) and calls `tunnelclient.RoundTripUpgrade(cc, req)` instead
+ of `cc.RoundTrip(req)`, after two gates: the channel advertised the
+ capability (§4.9), and the channel is under its upgrade cap (§4.8).
+5. `RoundTripUpgrade`:
+ - clones the request; deletes `Connection` and `Upgrade`; sets
+ `Carlos-Tunnel-Upgrade: <token>` (one RFC 7230 token, printable, at
+ most 64 bytes, else refused before any stream opens);
+ - sets the body to the read end of a pipe (unknown length, so HTTP/2
+ sends HEADERS without END_STREAM);
+ - `cc.RoundTrip`.
+6. Box: the HTTP/2 server hands the stream to `Mark`'s handler. The shim
+ sees `Carlos-Tunnel-Upgrade`, deletes it, sets `Connection: Upgrade`
+ and `Upgrade: <token>`, takes the request body for itself and gives
+ the edge `http.NoBody` with `ContentLength` 0, and wraps the writer
+ with `Hijack`.
+7. Box `ServeHTTP` (unchanged): `fromTunnel` exemptions, gate (§4.5),
+ upgrade branch, activator (a hibernating native instance wakes),
+ reverse proxy to the app socket. The app answers 101.
+8. Box proxy hijacks the shim's writer. The shim sets
+ `Carlos-Tunnel-Upgraded: 1`, writes HTTP/2 `200`, flushes, and returns
+ a `net.Conn` whose `Read` is the request body and whose `Write` is
+ write-and-flush on the response. The proxy writes the app's 101 to it
+ (`reverseproxy.go`, `res.Write(brw)`) and starts the splice.
+9. Hub: `cc.RoundTrip` returns the `200` with the marker.
+ `RoundTripUpgrade` reads one HTTP/1.1 response from the stream body
+ (`http.ReadResponse`, header bytes capped at 64 KiB, 10 s deadline),
+ requires `101` with the requested `Upgrade` token, and returns that
+ response with `Body` set to an `io.ReadWriteCloser`: reads drain the
+ buffered reader and then the stream, writes go to the pipe, `Close`
+ ends both (§4.7). It implements `CloseWrite` (ends the pipe, which
+ sends END_STREAM) so the proxy's half-close reaches the box.
+10. Hub proxy (unchanged): `ModifyResponse` runs on the 101
+ (`reverseproxy.go:589`), the upgrade types match, it hijacks the
+ browser's conn through `slotWriter` (the rate-limit slot goes back),
+ writes the 101, and splices.
+
+If the box answers without the marker (the gate's login page or 302, a
+404, a 502 because the app is down, any refusal), step 9 returns that
+response untouched and the hub's proxy copies it to the browser as an
+ordinary answer. The browser's WebSocket fails exactly as it would
+against a platform box.
+
+### 4.4 Headers
+
+Hub to box, on the HTTP/2 request:
+
+| header | handling |
+|---|---|
+| `Connection`, `Upgrade` | removed by `RoundTripUpgrade`; the token travels as `Carlos-Tunnel-Upgrade` (HTTP/2 forbids both) |
+| other hop-by-hop (`Keep-Alive`, `TE`, `Transfer-Encoding`, `Proxy-*`, `Trailer`) | already removed by the stdlib proxy (`reverseproxy.go:482`) |
+| `Sec-WebSocket-Key`, `-Version`, `-Protocol`, `-Extensions`, `Origin` | passed unchanged: end to end between browser and app |
+| `Cookie`, `Authorization` | passed unchanged; the box's gate reads and strips its cookie (§4.5) |
+| `X-Forwarded-For`, `-Host`, `-Proto`, geo, the forwarded proof | as for any tunneled request today; the box's proxy recomputes `X-Forwarded-*` for the app (§4.4.1) |
+| `Host` / `:authority` | the public name, as `fleetProxy` sets it (`edge.go:3249-3250`) |
+| `Carlos-Tunnel-Upgrade`, `Carlos-Tunnel-Upgraded` arriving **from the client** | **deleted** in `fleetProxy` and `tunnelProxy` `Rewrite`, beside `scrubInboundPurgeHeader`, on every request |
+
+Box to hub: HTTP/2 `200` with `Carlos-Tunnel-Upgraded: 1` and no other
+meaning; everything the app said is in the in-band 101 (`Sec-WebSocket-Accept`,
+`Sec-WebSocket-Protocol`, `Set-Cookie`, and so on). On a response the box
+did not hijack, the shim deletes any `Carlos-Tunnel-Upgraded` the app set,
+so an app cannot make the hub read its body as a 101.
+
+**The trust rule, stated once.** A stream leaving the hub carries
+`Carlos-Tunnel-Upgrade` if and only if the hub's upgrade branch admitted
+the request. It holds because:
+
+- `RoundTripUpgrade` is the only writer of the header, and `transportFor`
+ calls it only for a request the stdlib proxy marked as an upgrade;
+- the stdlib proxy marks a request as an upgrade on the same predicate
+ as `isUpgradeRequest` (`Connection` token `Upgrade`, every line;
+ `edge.go:2286-2293`, `reverseproxy.go:828-833`), so such a request
+ went through the upgrade branch;
+- the scrub above removes a client's copy before `Rewrite` returns, so a
+ plain GET carrying the header reaches the box as a plain GET.
+
+Without the scrub, a client could open a socket that skipped
+`trackUpgrade`, `planUpgradeAdmit` and the cap. The marker grants nothing
+on the box that a real `Upgrade` header would not: the box exempts
+tunneled requests from limits either way. The shim honours the header
+only on the tunnel's serving path (`Mark`); on the box's public listener
+it is an ordinary header, and the box's edge deletes it from every
+inbound request so no app ever sees it.
+
+#### 4.4.1 What the app sees
+
+The box's proxy deletes inbound `X-Forwarded-*` and recomputes them
+(`setForwarded`, `homemap.go:1428-1446`): `X-Forwarded-Host` is the public
+name and `X-Forwarded-Proto` comes from the tunnel conn's TLS state
+(`x/net/http2/server.go:336-338`, `:2207-2209`): `https`, because the box
+dialed TLS. Action Cable accepts a handshake when `Origin` equals the
+request's scheme and host (`allow_same_origin_as_host`), so this is
+load-bearing for any Rails app without `config.assume_ssl`. The shop sets
+`assume_ssl` (`examples/rails-shop/config/environments/production.rb:28`);
+the witness (§8.2) checks the general case. Upgrades get exactly the
+headers plain tunneled requests get. §10 notes two pre-existing gaps in
+those headers.
+
+### 4.5 The gate cookie
+
+Unchanged and end to end. The cookie is host-only and `Secure` for the
+public name (1a §4.8). The browser sends it on the handshake; the hub
+passes it; the box's `gate.Admit` runs before the box's upgrade branch
+(`edge.go:2083-2104`) and strips it. A handshake without it gets the
+gate's answer as an ordinary response (§4.3, last paragraph), never a
+101. The witness logs in through the hub and then upgrades.
+
+### 4.6 One enforcement point, and `CloseAccountUpgrades` on a real socket
+
+The hub's upgrade branch does not change: `trackUpgrade`,
+`planUpgradeAdmit` and `rateAdmit` already apply to forward rows (1a
+Task 5). What changes is that the proxied call no longer fails, so the
+request context registered by `trackUpgrade` now lives as long as the
+socket.
+
+The close path for an awake-throttled account:
+
+1. The agent calls `CloseAccountUpgrades(account)` (`agent.go:1054-1059`);
+ it cancels every registered context (`planthrottle.go:132-141`).
+2. The hub's proxy sees the context done and closes `backConn`
+ (`reverseproxy.go:860-870`), which is `RoundTripUpgrade`'s body.
+3. That `Close` closes the pipe and the stream's response body, which
+ resets the stream (`RST_STREAM CANCEL`). The hub's splice ends and its
+ deferred `conn.Close()` closes the browser's socket.
+4. On the box the reset cancels the stream's request context and fails
+ the shim's `Read`. The box's proxy, in the same handler, closes the
+ app's socket the same way (`reverseproxy.go:860-870`) and returns, and
+ the handler's return ends the stream.
+
+So one cancel at the hub closes the browser's socket, the stream and the
+app's socket. The witness checks all three, the app side within 2 s.
+
+Per-channel cap (§4.8) is checked in `transportFor` after the upgrade
+branch has admitted the request. A refusal there is 503 (§4.8), and the
+rate-limit slot it held is released by the handler's deferred release as
+for any refused request.
+
+The box keeps exempting tunneled requests, unchanged. Nothing on the box
+enforces anything new.
+
+### 4.7 Lifetimes: what closes an upgraded socket
+
+| event | what happens | bound |
+|---|---|---|
+| browser closes | hub splice reads EOF; `CloseWrite` on the stream sends END_STREAM; the box's proxy reads EOF and half-closes the app socket; the app closes; the box handler returns; the hub's other copy ends | the app's close handshake |
+| app closes (including a retiring generation's process exiting after SIGTERM in a swap or overlap deploy) | the box's proxy reads EOF; the handler returns; the stream ends; the hub reads EOF and closes the browser's socket | `actStopTimeout` for a retiring generation, as on a platform box |
+| `CloseAccountUpgrades` | §4.6 | one round trip |
+| tunnel dies (ping failure, network, the box's agent restarts) | the hub's raw conn closes, every stream on it fails, each hub splice ends and closes its browser; on the box every handler's body read fails and each proxy closes its app socket (or the process is gone) | about 10 s for a silent death (fleet ping cadence, `tunnel.go:58-59`); immediate for a reset |
+| re-registration under the same name (`tunnel.go:210-211`) | the old conn is closed: as tunnel death | immediate |
+| detach (`SetDynamicAuth` to `CloseChannel`) | as tunnel death. Revocation reaches open sockets too | immediate |
+| rotation | nothing; sockets live on the old conn until the box redials, as plain traffic does | the box's next redial |
+| hub restart (edge roll) | hijacked browser sockets die with the process (`edge.go:4152-4161`); the tunnel conn dies; boxes close their app sockets as above and redial | the hub's restart; boxes redial in 0.25 to 2 s (`tunnelclient.go:42-44`) |
+| fleet dark | a new handshake gets 503 `Retry-After: 2` (`errFleetDark`), as plain requests do | |
+
+Action Cable's client reconnects on its own with backoff, so every row
+above recovers without a page reload.
+
+Counters never leak: the per-channel upgrade count (§4.8) lives on the
+`tunnelConn`, not on the name, and is decremented by the upgrade body's
+`Close`, which runs exactly once on every path above (the proxy always
+closes `backConn`). A replaced conn takes its count with it.
+
+Hibernation on the box is unchanged: an open socket is in flight for the
+activator (§3.7), as on a platform box. The hub never manages a forward
+row.
+
+### 4.8 Backpressure and limits
+
+Three numbers, and the invariant they keep: **open upgraded sockets alone
+can never take the stream slots or the connection window that the box's
+plain requests need.**
+
+1. **Stream slots.** `tunnelclient.Serve` sets `MaxConcurrentStreams`
+ explicitly to 250 (today's default, pinned so a library change cannot
+ move it). The hub caps open upgrade streams **per channel connection
+ at 128**. Plain requests always have at least 122 slots. The 129th
+ upgrade gets 503 with `Retry-After: 5`, cause `tunnel_busy` (§7). The
+ cap is per box, so a fleet's ceiling is 128 times its connected boxes.
+2. **Hub-to-box window (box receive).** `tunnelclient.Serve` keeps the
+ per-stream window at today's 1 MiB and raises the per-connection
+ window from 1 MiB to **160 MiB** (`>= 128 x 1 MiB + 32 MiB`). A stalled
+ socket holds at most its own 1 MiB; 128 stalled sockets still leave
+ 32 MiB for everything else. Box memory is spent only for bytes
+ actually buffered, and only an app that stops reading its own sockets
+ can make the box buffer them.
+3. **Box-to-hub window (hub receive).** Unchanged: 4 MiB per stream,
+ 1 GiB per connection. 128 sockets whose browsers stop reading cost the
+ hub at most 512 MiB for that channel. That is no worse than today's
+ 250 slow plain downloads (1 GiB), so v1 leaves it; §11 Q2 offers the
+ tightening.
+
+Why 128 and not more: raising the slot count above 250 raises the hub's
+worst case in point 3 for plain and upgraded traffic alike. 128 keeps
+every existing worst case where it is. Q1 asks Paul.
+
+Idle timeouts: none, as on every edge today (`edge.go:3940-3942`). Dead
+peers are covered by the tunnel's 5 s pings on the box side and TCP
+keepalive on the hub's listener on the browser side, and Action Cable
+pings every 3 s anyway.
+
+The rate limit's slot is held only until the 101 (§3.5), so an open
+socket does not count against the app's request concurrency, as on a
+platform box.
+
+### 4.9 Old boxes: a capability on registration
+
+The box adds one header to `/register`:
+
+ Carlos-Tunnel-Caps: upgrade/1
+
+The hub records it on the `tunnelConn` (`tunnel.go:72-79`, set at `:213`).
+`transportFor` sends an upgrade only to a conn that advertised it. Every
+other combination behaves exactly as today:
+
+| hub | box | an upgrade to that box |
+|---|---|---|
+| old | old | 502 |
+| old | new | 502 (the old hub ignores the header and x/net refuses as today) |
+| new | old | 502, cause `tunnel_upgrade_unsupported` (§7), logged once per channel per hour |
+| new | new | 101 |
+
+The channel picked for an upgrade is the one `fleetChannelFor` picks for
+any request (bound box, else the first connected box). An upgrade is
+never steered to a different box because the bound one is old: a socket
+should land where the page came from.
+
+The `carlos-tunnel/1` token does not change. The header is additive in
+both directions (AGENTS.md: wire-shape changes are additive), so no
+release floor is needed.
+
+### 4.10 Where the code goes
+
+- `internal/tunnelclient` (leaf package, stdlib plus x/net only, as its
+ header requires, `tunnelclient.go:1-14`):
+ - `RoundTripUpgrade(cc *http2.ClientConn, req *http.Request) (*http.Response, error)`,
+ the hub half;
+ - the shim inside `Mark` (`tunnelclient.go:279-288`), the box half;
+ - `Dial` sends `Carlos-Tunnel-Caps` (`:228-238`);
+ - `Serve` builds its `http2.Server` with the §4.8 numbers (`:291-293`).
+- `internal/edge/tunnel.go`: `tunnelConn` gains `caps` and an open-upgrade
+ count; `ServeHTTP` records the caps; `transportFor` branches on an
+ upgrade, checks caps and cap, and calls `RoundTripUpgrade`.
+- `internal/edge/edge.go`: `fleetProxy` and `tunnelProxy` scrub the two
+ marker headers in `Rewrite`, and their error handlers answer the two
+ new sentinels (§7); `ServeHTTP` deletes `Carlos-Tunnel-Upgrade` from
+ inbound requests.
+- `internal/apperr/availability.go`: two causes (§7).
+- No change in `internal/host`: `tunnelLoop` already passes the edge to
+ `tunnelclient.Loop`, which applies `Mark`.
+
+The edge's acceptance test can drive the real client loop because
+`tunnelclient` is a leaf (`tunnelclient.go:8-14`), so both halves are
+tested together through production wiring (§8.2).
+
+## 5. Provider boundary
+
+No cloud API. The tunnel, the hub and the box are provider-neutral
+today, and this changes only bytes on an existing connection. A
+self-hosted deployment with a MinIO bucket and no AWS gets the same
+behaviour.
+
+## 6. Request budget
+
+Steady state, per box per day, nothing changing: **zero** added bucket
+requests on every box, hub and fleet box alike. The capability travels in
+the registration handshake, the counts live in memory, and no new object
+is read or written. No reader, no poll, no change-index scope.
+
+Test: the witness (§8.2) wires a counting store into both edges and
+asserts that a full upgrade lifecycle (handshake, 100 messages each way,
+a throttle close, a tunnel drop) adds zero store calls over a run with
+plain requests only.
+
+## 7. Census, copy and docs
+
+Census. `internal/edge` and `internal/tunnelclient` are both in the root
+binary's scope (`GOOS=linux go list -deps .` lists both, checked on
+`65fd8060`), so `TestPlan14RootReadCensus` fails on this branch and needs
+a card. Expected classes:
+
+- `body`: `TunnelHub.ServeHTTP`, `TunnelHub.transportFor`, `fleetProxy`,
+ `tunnelProxy`, `Edge.ServeHTTP` (one header delete), `tunnelclient.Dial`,
+ `tunnelclient.Serve`, `markedHandler.ServeHTTP`;
+- `new`: `tunnelclient.RoundTripUpgrade` and its conn type, the shim's
+ writer and conn, the two error sentinels;
+- `envelope`: `internal/edge`, `internal/tunnelclient`,
+ `internal/apperr`;
+- no `reads`: nothing reads a file or root-owned state. The edge runs as
+ the agent, and the only new input is bytes on the tunnel, which the box
+ already trusts the hub for and the hub already trusts the box for (1a).
+
+The reviewer is Astra (Claude author), recorded on #280.
+
+Copy. Two new cause descriptions in `internal/apperr/availability.go`
+(shown where causes are shown today), and the 503 body for the cap:
+
+| id | where | draft |
+|---|---|---|
+| TWS-C01 | `tunnel_busy` description | the fleet box has too many open connections |
+| TWS-C02 | `tunnel_upgrade_unsupported` description | the fleet box runs a release that cannot carry WebSockets |
+| TWS-C03 | 503 body on the cap | Too many open connections to this app's box. Try again shortly. |
+
+They go through the copy review before they are written to any file.
+
+Docs. None needed. The Rails guide already tells people to use Solid
+Cable (`docs/site/rails.md:11`, `:45`); this makes that true for fleet
+apps. `docs/site/plans.md:88` ("open live connections are closed") becomes
+true for fleet apps too.
+
+## 8. Tests
+
+### 8.1 Unit, `internal/tunnelclient` (both halves over an in-memory h2 pair)
+
+1. Round trip: the box shim sees `Connection: Upgrade` and
+ `Upgrade: websocket`, no `Carlos-Tunnel-Upgrade`, `Body` empty; bytes
+ flow both ways after a 101; `Sec-WebSocket-*` arrive unchanged.
+2. No hijack: a 302, a 404 and a 502 from the box come back to the hub as
+ ordinary responses with their bodies; an app-set
+ `Carlos-Tunnel-Upgraded` is deleted.
+3. Refusals before a stream opens: an `Upgrade` token that is not a
+ token, or is over 64 bytes.
+4. The in-band 101: over 64 KiB of headers, no 101 within 10 s, a non-101
+ status, and a mismatched `Upgrade` token each end the stream and
+ return an error (502 at the hub).
+5. Close: `Close` on the hub's body resets the stream; the box's conn
+ `Read` fails and its handler returns. `CloseWrite` delivers EOF to the
+ box with the other direction still open.
+6. Registration carries `Carlos-Tunnel-Caps: upgrade/1`; `Serve`'s server
+ advertises 250 streams and the §4.8 windows (read from the SETTINGS
+ frame).
+
+### 8.2 The production-wired witness, `internal/edge`
+
+One test, `TestTunnelWebSocketEndToEnd`, built like `forwardHubAndBox`
+(`fleetforward_test.go:64`) but over TLS and with the real loop:
+
+- **real hub**: `New` + `EnableTunnels` + `Reload`, the forward row minted
+ through `PutForward`, served by an `http.Server` on a TLS listener (the
+ production listener's shape, so hijack happens on a real TLS conn);
+- **real tunnel**: `tunnelclient.Loop` (the loop the agent runs) dialing
+ the hub over `https`, authenticated as a fleet box through the fleet
+ table;
+- **real fleet edge**: `New` with an instance row on a unix socket and a
+ `Gate`, served by `Loop` exactly as `tunnelLoop` serves it;
+- **a real WebSocket app**: an `x/net/websocket` server (already in the
+ module) on that unix socket, speaking Action Cable's shape: it accepts
+ only subprotocol `actioncable-v1-json`, accepts only when `Origin`
+ equals `X-Forwarded-Proto + "://" + Host` (Action Cable's same-origin
+ rule), sends `{"type":"welcome"}`, sends `{"type":"ping"}` on a short
+ timer, answers `subscribe` with `confirm_subscription`, and broadcasts
+ a message on a side channel the test triggers;
+- **the client**: an `x/net/websocket` client against the hub's public
+ name, with `Origin`.
+
+Cases, each against the same scene:
+
+1. Without the gate cookie: the handshake gets the gate's answer, not a
+ 101; the app saw nothing.
+2. Log in through the hub (`POST /.carlos/gate`), then the handshake: 101
+ with the app's `Sec-WebSocket-Accept` and `actioncable-v1-json`;
+ welcome, pings, subscribe and confirm, a broadcast, and 100 echoes
+ each way, byte for byte; the app never saw the gate cookie and saw
+ `X-Forwarded-Proto: https`.
+3. `CloseAccountUpgrades(owner)` returns 1 while the socket is open; the
+ client sees the close and the app sees its socket closed within 2 s;
+ a second call returns 0.
+4. Plan throttle on: a new handshake gets 429 from the hub and the app
+ sees nothing.
+5. Rate limit: the hub's limit refuses the third handshake, and the box's
+ lower limit never applies (the existing 1a scene, now with 101s).
+6. The app closes the socket (a retiring generation's shape): the client
+ sees the close.
+7. Tunnel loss: cancel the box's `Loop` context; client and app both see
+ their sockets close within the ping bound; after the loop restarts a
+ new handshake succeeds.
+8. Re-registration and detach close open sockets; rotation does not.
+9. Hub restart: close the hub's server; the app's socket closes.
+10. A plain GET carrying `Carlos-Tunnel-Upgrade: websocket` reaches the
+ app as a plain GET with no `Upgrade` and no marker; the hub's upgrade
+ branch counter did not move.
+11. An old box (a `Loop` built without the caps header): 502 with cause
+ `tunnel_upgrade_unsupported`; plain GETs unaffected.
+12. Cap: with the cap lowered to 4 for the test, the fifth handshake gets
+ 503 `Retry-After: 5`; plain GETs still answer while 4 sockets are
+ open; closing one admits the next.
+13. Head-of-line: an app that stops reading one socket while the client
+ writes 4 MiB into it; a 2 MiB POST to the same box over the same
+ tunnel completes.
+14. Request budget: the counting store sees zero calls (§6).
+
+The 1a tests `TestForwardUpgradeIsLimitedAtTheHub` and
+`TestForwardPlanThrottleAndUpgradeClose` change from "101 or 502" to 101,
+and the second closes a socket that is really open. That also clears the
+deferred minor on the vacuous `ups > 2` check
+(`docs/superpowers/reviews/fleet-public-routes-deferred-minors.md:8`).
+
+A `-tunnel` row (`ArmTunnel`) gets case 2 once, so the third arm is
+covered.
+
+### 8.3 Live check on dev
+
+After the release reaches sophie (the hub) and r10r's box-1:
+
+1. `curl -s -o /dev/null -w '%{http_code}\n' https://shop.bab.dev.oncarlos.com/up`:
+ 200, as before.
+2. The §1 handshake with `curl --http1.1 -i -N --max-time 10`: `HTTP/1.1
+ 101 Switching Protocols`, `Sec-WebSocket-Protocol: actioncable-v1-json`,
+ then the bytes of `{"type":"welcome"}` and a `{"type":"ping",...}` about
+ every 3 s. Rails mounts Action Cable at `/cable` by default. The
+ sample has no `app/channels` today; if its Rails falls back to the
+ base connection class this step needs no app change, and if it does
+ not, the step waits for Q4's change. The plan checks which before the
+ roll, locally, with `carlos ship --check`'s image.
+3. With Q4's sample change: open the shop's page in a browser, press
+ "Enqueue a job", and see the count change without a reload.
+4. `railsdemo.bab.dev.oncarlos.com` (a hand `ArmFleet` row) answers as
+ before.
+
+## 9. Interaction with Plan 6
+
+Plan 6 does not use the tunnel. A box dials out to the console's box door
+for each session, over ordinary HTTPS, because the console process has no
+door into the hub's `TunnelHub`, the tunnel serves the box's edge rather
+than its agent, and platform boxes have no tunnel at all
+(`2026-10-24-rootfs-apps-6-interactive.md:54-59`). That WebSocket ends at
+the console, a local route on the hub, and already works today.
+
+So this design neither serves nor blocks Plan 6. Two notes for whoever
+builds it:
+
+- If Plan 6 ever wanted console-to-box sessions over the tunnel (for a
+ fleet box whose firewall lets only the tunnel host through, its failure
+ mode 4, `:92`), the stream shape here is that transport: a
+ hub-initiated, full-duplex stream with end-to-end close and a capped
+ slot count. It would need a door from the console into `TunnelHub`,
+ which is Plan 6's call.
+- Box-to-console traffic cannot use this. Streams on the tunnel are
+ opened by the hub only.
+
+## 10. Related findings (not fixed here)
+
+1. **A fleet app sees the hub's address as the client.** On the box, a
+ tunneled request's `RemoteAddr` is the hub, and the box's proxy
+ replaces `X-Forwarded-For` with it (`homemap.go:1428-1446`; the hub's
+ chain is trusted only on a verified hop, `:1441`). Rails'
+ `request.remote_ip` is the hub for every fleet app. Applies to plain
+ and upgraded requests. Recommend its own discussion.
+2. **`bufferedConn` can hide the tunnel's TLS state.** When the box's
+ handshake read over-reads past the 101, `Dial` returns a
+ `bufferedConn` (`tunnelclient.go:173-178`, `:258-259`) that does not
+ expose `ConnectionState`, so the box's HTTP/2 server sees no TLS
+ (`x/net/http2/server.go:336`) and `X-Forwarded-Proto` becomes `http`
+ for that session. Rare (the 101 and the preface are separate TLS
+ records), but a timing bug. A two-line fix (forward
+ `ConnectionState`); it can ride this plan as a task because §8.2 case
+ 2 asserts the header.
+
+## 11. Open questions for Paul
+
+1. **Cap of 128 open WebSockets per fleet box.** It keeps every existing
+ worst case where it is (§4.8). A busier box needs the hub's receive
+ window tightened first (Q2). *Recommend: 128 for v1, raise with
+ measurement.*
+2. **Tighten the hub's per-stream receive window from 4 MiB to 1 MiB?**
+ It bounds the hub's memory for slow readers on plain and upgraded
+ traffic alike, at some cost to single large downloads from distant
+ boxes. *Recommend: not in this change; a follow-up if a box ever needs
+ more than 128 sockets.*
+3. **`-tunnel` hand rows get WebSockets too.** Same transport, no extra
+ code, and no hub policy for those kinds, as on platform boxes.
+ *Recommend: yes.*
+4. **Add an Action Cable channel to `examples/rails-shop`** (a
+ `PingsChannel` streaming "pings", and a page subscription) so "Enqueue
+ a job" updates live: the guide's demo, and a fuller live check (§8.3
+ step 3). Needs a reship of shop on dev. *Recommend: yes, as the last
+ task.*
+5. **File §10.1 (client address on fleet apps) as its own discussion.**
+ *Recommend: yes.*
+
+## 12. Rollout
+
+- **No switch, no dormancy.** It is on as soon as both ends run it, and
+ the first thing it does is visible: the shop's `/cable` answers 101
+ (rule 6).
+- **No release floor.** §4.9: every mixed pair behaves as today.
+- **Order:** the usual dev-first roll. The hub alone changes nothing
+ until box-1 runs the release; box-1 alone changes nothing until the hub
+ does. Then §8.3. Flagship has no fleets; it takes the release with the
+ next flagship roll, no extra step.
+- **Rollback:** roll back the release. No state, no object, no record to
+ clean up.