Skip to content

Latest commit

 

History

History
689 lines (602 loc) · 42.3 KB

relay.md

File metadata and controls

689 lines (602 loc) · 42.3 KB

The blind relay

How a phone reaches a box from anywhere with nothing opened and nothing trusted in between. This is the "outbound-dialing blind relay" that connectivity.md settles on, built as a Cloudflare Worker you deploy once (relay/), a client in the sidecar that dials out to it, and a transport in the app that speaks to the box through it. The relay forwards bytes it cannot read; everything that matters happens end to end between phone and box.

This file is the protocol, version 2. The three parts are built separately and meet here, so every byte on the wire is specified below and the shared shapes live in shared/src/relay.ts. Change the protocol by changing this file and that module together, and by bumping RELAY_PROTOCOL. An addition that an older peer can ignore without harm — the sealed bye, the box's proofs and proven, a phone's ?wait=1 — is unversioned, and says so where it is described.

Who is who

  • Box. The machine running herdr and the sidecar. It has a permanent Ed25519 keypair, generated once and kept in the sidecar's SQLite (identity.ts). Its serverId is base64url(sha256(publicKey)) — 43 characters that cannot be guessed and cannot be claimed by anyone without the private key. (This replaces the random UUID; a box that upgrades gets a new id and its phones pair again — there is no compatibility path, per CLAUDE.md.)
  • Relay. One Worker, one Durable Object per serverId. It authenticates boxes (so nobody can sit on someone else's id) and forwards frames between a box and its phones. It never sees a key, a passcode, a request path or a byte of a terminal. What it does see, and Cloudflare with it: both ends' IP addresses; the serverId (in the box's URL, so in request analytics) and the box's public key; a presence timeline (the box pings every twenty seconds); each phone's deviceId or pairing-code hash, in the clear in its hello; how many phones a box has; which links the box says proved their secret (proven, below, which their traffic after the hello showed anyway); and the size and timing of every frame. The default relay is relay.getshahi.dev, run by Shahi's author.
  • Phone. Holds, per box, a deviceId and a 32-byte device secret handed to it at pairing, in the Keychain. Before pairing it holds only the 32-byte pairing secret from the QR.

What the relay does (relay ↔ box, relay ↔ phone)

Two WebSocket endpoints on the relay, both plain WSS with no relay-level secrets for phones:

  • wss://<relay>/v1/box/<serverId> — the box's persistent connection. On open the relay sends {"t":"challenge","nonce":"<base64url 32 bytes>"}. The box answers {"t":"auth","pub":"<base64url 32>","sig":"<base64url 64>","proofs":true} where sig is Ed25519 over the UTF-8 bytes of "shahi-relay-box-v1" + serverId + nonce, and proofs (optional, unsigned, only ever true) promises the proven control below. The relay checks base64url(sha256(pub)) == serverId and the signature, then sends {"t":"ready"}. Anything else, or ten seconds of silence, closes with 4401. A second box connection for the same id replaces the first (the old one is closed with 4409): a restarted sidecar must not be locked out by its own zombie. Replacement happens only on a proven auth, never on connect. At most eight unauthenticated box sockets may wait per serverId. A ninth closes the longest-waiting pending one, if it has waited at least a second, with 4429 "too many pending boxes"; if all eight are younger than that, the newcomer gets the close instead. An authenticated box is never evicted by this. Refusing the newcomer outright, as the relay once did, let anyone who knew a serverId hold all eight slots with silent sockets and keep the real computer's reconnect out.
  • wss://<relay>/v1/phone/<serverId> — a phone's connection. If no box is connected the relay closes it at once with 4404 ("box offline"); the app shows that in words. A phone that adds ?wait=1 is held instead, until the box arrives (below, "Waiting for the box"). Otherwise the relay assigns a link number and tells the box {"t":"open","link":n}; when the phone goes it tells the box {"t":"close","link":n}; the box can end a link with the same message. Once a link has sent a sealed frame that opened on the box — proof that it holds the secret its hello named — a box that sent "proofs":true tells the relay {"t":"proven","link":n}, once per link. The relay uses it for one thing, choosing which link may be closed for a newcomer (below). Both are additive and unversioned: a relay that predates them ignores the field and drops the control, as it drops every box control but close, and a relay that has them treats a box whose auth lacks "proofs":true as one that will never send proven.

The relay cannot ping a box (a Durable Object cannot originate one), so the box sends the text frame ping every twenty seconds once ready; the relay answers pong without waking and closes a box silent for five minutes, whose phones then see 4404. Both words are plain text, not JSON, and are the only text frames on a box socket that are not control messages. The pings only prove the box can write, so the box also watches its read side, as the phone does: if no frame — not even a pong — arrives within 60 seconds, it drops the socket and redials. A five-second watchdog checks this deadline, so a silent route is normally detected within 60–65 seconds of the last received frame.

The watchdog also runs during connection setup and retry waits. If its clock jumps backward or a tick arrives over 15 seconds late (for example, after sleep), the computer discards the old socket and immediately starts a fresh connection. This does not depend on a close event or on whether buffered messages arrive first. If the network is still unavailable, retries continue indefinitely with jittered exponential delays capped at 30 seconds. Stable connections reset the backoff. Signing identity and paired-device credentials survive these reconnects; in-flight requests are not blindly replayed.

This cannot keep a sleeping computer online or reconnect through an ongoing internet outage. It restores the tunnel once the process is running and the relay is reachable. Tests suspend an isolated process with real WebSockets, resume it with and without a network route, and cycle availability repeatedly. Physical sleep/wake and router-specific behavior remain device checks.

Data is binary frames. On the phone side a frame is the payload as is. On the box side every data frame is link(4 bytes, big-endian) ‖ payload, so one box socket carries every phone. Text frames are relay control only, as above.

Limits, enforced by the relay: payload ≤ 1 MiB, at most 8 phones per box, at most 64 KiB/s sustained per phone with a burst of 1 MiB (a reader window is ~15 KB; a photo upload is the reason for the burst), and idle phone sockets closed after 10 minutes without a frame. Every phone frame, text included, is charged at least 256 bytes against that bucket, so a phone gets at most 256 frames a second sustained and 4,096 in a burst: each frame wakes the Durable Object, and charging bytes alone let 1-byte frames through at about 65,000 a second. Phone text frames are charged and then dropped, never forwarded.

The relay keeps no history: a frame that arrives while the box is disconnected is dropped and the phone's socket is closed with 4404, which is honest — the phone reconnects and asks again.

Waiting for the box. A refused phone retries on a backoff that reaches thirty seconds, so once a computer had been away for a minute its phones learned it was back up to thirty seconds late. Measured on build 32: the computer's service was on the relay again 1.1 s after a restart, and the app stayed OFFLINE for another 16–22 s. Polling faster would cost a relay request each time, for as long as the computer is away. So a phone may ask to wait, by dialling wss://<relay>/v1/phone/<serverId>?wait=1:

  • With a ready box, nothing changes: the phone gets a link.
  • With no ready box, the relay holds the socket and sends it the text frame {"t":"waiting"} — the only text a relay sends a phone. The phone's hello, sent on open before it could know, is dropped; any further frame closes the socket with 4404, as if it had not asked. The phone's ping is answered pong by the runtime without waking the object, and the phone sends one every twenty seconds, so its route stays open, and drops a waiting socket that hears nothing for seventy seconds.
  • When the box authenticates, the relay closes every waiting socket with 4200 ("box online"). The phone dials again at once, without its backoff, and its hello reaches the box. A waiting socket closed by anything else is retried on the ordinary backoff.

A held socket hibernates and sets no alarm, so waiting costs one connection per wait instead of one per backoff interval. At most eight phones wait per box; a ninth closes the longest-waiting one that has waited at least a second, with 4404, or is refused itself if none has. A waiting phone that is closed this way is back on the backoff, which is all any phone had before, so a stranger who knows the serverId cannot lock the owner's phone out this way. The relay records a held phone as the refused "box offline" it replaces.

Additive and unversioned. An older relay reads only the path, ignores the query and refuses with 4404; a phone that never asks is never held. Only a paired device asks: a pairing link lives for one claim and is closed on its first failure.

What the box and phone do (end to end, opaque to the relay)

Hello. The first frame from the phone is a binary frame whose bytes are this JSON — binary because the relay forwards only data frames and drops text from phones (text is relay control). The box answers the same way: its hello is the first data frame back. Nothing else on a link is unsealed.

{"t":"hello","v":2,"pub":"<base64url X25519 ephemeral public key>",
 "auth":{"kind":"device","deviceId":"…"}}

or, before it has paired,

{"t":"hello","v":2,"pub":"…","auth":{"kind":"pairing","id":"<base64url sha256(pairing secret)>"}}

The secret itself never travels: the box finds the shared secret by deviceId (the device secret) or by the hash of a pairing code it minted and has not yet seen claimed. The box answers {"t":"hello","v":2,"pub":"<its ephemeral>"}. Both sides then derive a session exactly as shared/src/e2e.ts does — clientSession on the phone, serverSession on the box — with the shared secret as the pairing secret argument. A relay, or anyone, who does not hold that secret derives different keys, and the first sealed frame fails to open; the box ends the link. It does the same, without answering, to a hello naming a deviceId or pairing id it does not know, or one that is malformed. The box cannot choose the phone's close code: ending a link is the close control above, which the relay delivers to the phone as 1000 "closed by box" in every one of these cases. A deviceId the box knows but has revoked is the exception: the box answers its hello, keyed from the revoked row's retained secret, sends one sealed bye (below) and then ends the link. Every frame after hello is a sealed message from e2e.ts (counter ‖ ciphertext), each direction on its own key, counters never reused, a replayed frame refused.

Inside a sealed frame is UTF-8 JSON, one of:

  • {"t":"req","id":n,"method":"GET","path":"/api/session","headers":{…},"body":null} from the phone; body is base64url of the request bytes when there is one. headers carries content-type and x-shahi-api; the box adds the session.
  • {"t":"res","id":n,"status":200,"headers":{…},"body":"<base64url>"} from the box, headers limited to RELAY_RESPONSE_HEADERS in shared/src/relay.ts: content-type, etag, cache-control, content-range and x-shahi-file-version. The last two are what ranged file downloads (512 KiB ranges, answered 206) read; the list stopped at the first three until the September 2026 pre-release review, so every PDF, Save / Share and web download through the relay failed while SSH worked. The hosted browser fixture filters by the same constant.
  • {"t":"ws","data":<SocketMessage>} from the box — the same messages the /ws socket pushes (session, frame, prompt, status, log_changed, ping) — and {"t":"ws","data":{"type":"watch","paneId":"…"}} / {"type":"unwatch"} from the phone. One link is therefore both the request channel and the dashboard stream; the app opens exactly one.
  • {"t":"bye"} from the box: this device is no longer paired, so the phone signs out and stops reconnecting, the mirror of a /ws close with 4001. It has to be a sealed message rather than a close code because the relay flattens a box-driven close to 1000, which the phone would retry; without it a revoked phone reconnected on a backoff loop forever, cut off but never told to sign out. It goes to a device revoked while its link is open, to one revoked between its hello and its first sealed frame, and to one revoked while its link was down, which is told on its next connection: the box keys that link from the revoked row's retained secret, which authorizes nothing and is used only for this. It does not go to a link whose own session token merely expired (the heartbeat's 4001): that link just ends, and the phone reconnects and gets a new token, because a bye there erased a valid pairing. Logout over the relay revokes the link's token before the device, so that link also ends without a bye; both clients sign out locally anyway. Anything still queued for the link is dropped, and the bye goes ahead of the delivery window. Additive and unversioned: an older box never sends it, an older phone ignores an unknown t.

Authentication inside the box. A plaintext hello naming a device is not authentication. The link must prove possession of its secret by sending a valid sealed message within fifteen seconds of opening. Both clients immediately send a sealed watch/unwatch after deriving device-session keys; a pairing client sends its sealed metadata request. The deadline is cleared only by a successfully opened message, never by the hello or outbound heartbeats. Before proof, the box issues no session and attaches no stream. It rechecks device revocation at proof time, and answers a device revoked in the meantime with a sealed bye.

The relay holds at most eight phones per box. When all eight slots are full, a new phone closes a link that has not shown it belongs there, with 4429 "too many phones", provided that link has been open at least a second; if none qualifies, the newcomer gets that close. The link closed is the longest-silent one, a phone that has sent no frame yet; failing that, on a box that sent "proofs":true, the longest-waiting link the box has not reported proven. A proven link is never closed for a newcomer.

A hello is only a claim. The box ends a link whose hello is malformed or names a device or code it does not know within a round trip, but it answers a hello naming a real device id and then waits the full fifteen seconds for a sealed frame, since only that frame can show whether the sender holds the secret. Until the relay learned of proofs, such a link kept its slot for all fifteen seconds, so anyone who knew one device id and not its secret — a revoked phone that had once listed the devices, for one — could hold all eight slots at about one connection every two seconds and keep the owner's phones out (pre-release review 2026-09-22, F33). For a box that never sends "proofs":true, a sidecar older than this, the relay keeps that old rule, because it cannot tell such a box's owner phone from a stranger's hello, and that box stays open to this lockout until it is updated.

What remains is a denial of service by anyone who can name the serverId. Holding every pending-box slot means keeping eight sockets younger than one second at all times: eight new connections a second, sustained, to one serverId. Under CONNECT_LIMIT (below) that takes at least three IPv4 addresses or IPv6 /64s, and it keeps a reconnecting box out. Phone slots work the same way, except that a proven phone's slot is out of reach: keeping a new phone out means keeping every other slot filled with sockets under a second old, which is eight connections a second while none of the owner's phones is connected and one fewer for each that is. An attacker at such a rate who also knows a device id can close a new phone that has not yet proven itself, which takes it about two round trips after it opens, once its second of grace is up and every older unproven link has been replaced. None of this binds the relay operator, who runs the pipe and can drop any socket it likes.

After proof, a device link mints a session token bound to the device id for the link and attaches it to every request it dispatches, so the sidecar's HTTP layer — the gate, revocation on every request, the 426 check, the routes — runs unchanged. Revoking the device closes its links. A link that opened with auth.kind == "pairing" may call exactly two routes: GET /api/meta, so the phone can check the serverId in the code against the box it reached before it hands over the secret, and POST /api/pair/claim, which consumes the code as today and now also answers {"ok":true,"deviceId":"…","deviceSecret":"<base64url 32>"}; the phone stores both and reconnects as a device. Any other path on a pairing link is 403.

Dispatch. The box turns a req into an in-process Request for its own handler (URL http://relay.local + path, the headers above plus the session cookie) and turns the Response into a res. The Origin check is satisfied (no Origin); the rate limiter sees no peer address and keys relay traffic as relay:<deviceId>.

Where the pieces live

  • relay/ — the Worker and its Durable Object, wrangler.toml, tests that run under wrangler dev with no account. Deploy: cd relay && bunx wrangler deploy. Anyone may run their own; the app takes the relay address from the pairing code.
  • server/lib/identity.ts (the keypair and serverId), server/lib/relay-client.ts (dial out, authenticate, hold links, hello, seal/open, dispatch), started by server/index.ts when RELAY_URL is set. A box without one mints no pairing codes.
  • shared/src/relay-client.ts — the phone side both clients share: one socket, hello, sealed request/response with ids, acknowledgments and recovery. mobile/src/lib/relay.ts folds the dashboard stream into the native app's SessionSocket, and api.ts routes through it whenever the stored connection is a relay one; the web client uses it from web/src/connection.ts.

What this deliberately does not do

  • No relay-level auth for phones: a phone that knows a serverId can open a link and will be refused by the box at the first frame. The id is 256 bits of hash; the relay's per-phone quota bounds the cost of guessing anyway. Every such attempt does instantiate a Durable Object for the id it names. A phone with no box is refused with refuse(), which writes nothing and schedules nothing (2026-09-02 review, R7). A box connection, though, is accepted and challenged, and that schedules a ten-second auth-timeout alarm — one storage write per attempt (2026-09-02 pentest, L3). Both are bounded by Cloudflare's own limits and by the per-source front-door limiter (an IPv4 address, or an IPv6 /64); neither accumulates, since an unauthenticated box is dropped at the timeout.
  • No history, no store-and-forward, no direct WebRTC. The relay is a pipe.
  • No protection of frame sizes and timing, addresses or identifiers from the relay. That is the metadata a blind pipe still sees; the list is under "Who is who".

Operating the relay

The relay is relay/: a Worker, one Durable Object class (RelayBox, one instance per serverId), and nothing else — no KV, no database, no secrets. It supports Cloudflare's free plan. Sockets hibernate and the object can be evicted between frames; request, alarm, storage, and telemetry usage still count against the account's applicable limits. Verify the actual account plan and usage.

Deploy. Once, from a machine with a Cloudflare account:

cd relay
bunx wrangler login       # opens the browser; once per machine
bunx wrangler deploy      # prints the address it is reachable at

That address is the relay. Every later bunx wrangler deploy upgrades it in place; connected boxes are dropped for a second and reconnect. There is nothing to configure in the Worker itself — the serverId in the URL is all it needs.

Use a domain you own. wrangler.toml here carries a [[routes]] entry with custom_domain = true, which is how the shared relay answers on relay.getshahi.dev. Two reasons to copy that rather than live on workers.dev: the URL is a trust anchor baked into every install and pairing code, and only a domain you own can be repointed at another host later; and Cloudflare's WAF and rate-limiting rules apply to zones you own, so a rule on /v1/* is not expressible for a workers.dev subdomain at all.

Both workers_dev and preview_urls are explicitly false. Only the owned hostname is public, so alternate Worker addresses cannot bypass controls scoped to that hostname. Update boxes to the canonical relay before deploying this restriction. Devices paired to the retired shahi-relay.yasserd99.workers.dev address need a fresh pairing; the address is stored with each pairing.

Point a box at it. The herdr plugin's service dials Shahi's relay unless its .env has a RELAY_URL line — empty for direct-only, or your Worker's address. By hand, the sidecar dials out when RELAY_URL is set:

RELAY_URL=https://relay.example.com   # what `wrangler deploy` prints; the box speaks wss to it

in the sidecar's environment (the plugin's .env is at herdr plugin config-dir shahi). Pairing codes minted after that carry the relay, and the app connects through it from anywhere. Nothing on the box needs a port opened.

Run one yourself. Anyone may: the app takes the relay address from the pairing code, so a box and its phones agree on whichever relay the box was told about. The relay never holds a key, a passcode or a readable byte, so running it for other people costs them nothing in trust beyond what a blind pipe sees — frame sizes and timing.

Run it locally, with no account:

cd relay && bunx wrangler dev      # http://localhost:8787, workerd on this machine
bun run test:relay                 # starts and stops its own wrangler dev on 8787

wrangler dev runs the real runtime (workerd) with Durable Objects, hibernation and alarms, which is why the test suite needs no mocks: it opens sockets as a box and as phones and checks every close code in the table below. The suite starts and stops its own wrangler dev, on 8787 or SHAHI_TEST_RELAY_PORT, and keeps its Durable Objects in a temporary --persist-to directory it deletes, so nothing lands in relay/.wrangler/state. It fails at once if the port is already taken rather than testing whatever holds it. To test against a wrangler dev you left running, set SHAHI_TEST_RELAY_EXTERNAL=1; that relay must answer /health as shahi-relay.

Liveness. The Workers runtime cannot send WebSocket ping frames from a Durable Object, so a dead box is detected the other way round: a box sends the text frame ping every twenty seconds. The runtime answers pong from outside the object (setWebSocketAutoResponse), so a healthy idle box never wakes it; an alarm every five minutes reads the timestamp of the last such answer and closes any box not heard from in five minutes (code 1000, reason silent), which closes that box's phones with 4404. A box that does not ping is therefore dropped every five minutes: the sidecar's relay client must ping. Phones may ping too and get the same pong. Only a phone waiting for its box depends on it, to keep its route open; a phone with a link is closed after the ten-minute idle limit regardless.

What it logs. Nothing about frames. The relay records one Workers Analytics Engine data point per lifecycle event, and writes the same fields as one structured line to Workers Logs (relay/src/telemetry.ts). Automatic invocation logs, which would carry raw request URLs, and tracing are off in wrangler.toml. It stays as blind here as on the wire.

HTTPS. Every relay response served over HTTPS carries Strict-Transport-Security: max-age=31536000; includeSubDomains, the WebSocket 101 included; nothing is sent over plain HTTP, where a host must not send it. Plain HTTP is served only on the machine running the relay, to wrangler dev and the tests, whose requests carry a loopback cf-connecting-ip or none; the same rule exempts them from the connect limiter. A request that reached Cloudflare's edge over HTTP is answered 301 to the same URL over HTTPS before it is routed, so a cleartext WebSocket upgrade fails instead of opening a link. The URL cannot make that distinction: wrangler dev presents the route's own host over http:. Until the pre-release bug hunt (B51) the relay left this to the zone, whose Always Use HTTPS was off: http://relay.getshahi.dev/health answered 200 and a ws:// upgrade opened.

Two settings of the zone the relay is deployed in must remain enabled, because code cannot make them: Always Use HTTPS on (SSL/TLS → Edge Certificates), which does the same redirect at the edge for every hostname in the zone, the website included; and Minimum TLS Version at 1.2 (SSL/TLS → Edge Certificates), because the default of 1.0 accepts TLS 1.0 and 1.1 handshakes that RFC 8996 retired. On 25 September 2026 the first was off and the second at 1.0 (pre-release bug hunt, B51 and B52). Both were corrected through the signed-in dashboard on 26 September. The site, relay and review hosts then redirected HTTP with 301, refused TLS 1.0/1.1 and accepted TLS 1.2. Check them after changing the zone, and after deploying the relay:

curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://relay.getshahi.dev/health   # 301 https://relay.getshahi.dev/health
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://getshahi.dev/pwa/          # 301 https://getshahi.dev/pwa/
openssl s_client -connect relay.getshahi.dev:443 -servername relay.getshahi.dev -tls1_1 -cipher 'DEFAULT:@SECLEVEL=0' </dev/null   # must fail to handshake
openssl s_client -connect getshahi.dev:443 -servername getshahi.dev -tls1_1 -cipher 'DEFAULT:@SECLEVEL=0' </dev/null               # must fail to handshake

Observability

The relay is the one place with a fleet view, because it is your infrastructure and already sees the metadata (who is connected, how a connection ended, from where) while it reads not one byte of a session. relay/src/telemetry.ts writes one Analytics Engine point per event to the shahi_relay dataset. Recorded: the event kind, the serverId (a stable pseudonymous key hash), a close reason or refusal cause, a close code or live phone count, and the Cloudflare colo. Never recorded: a request path, a frame body, or a raw client IP (Cloudflare's own analytics and WAF hold per-IP data transiently; the dataset does not).

The schema (Analytics Engine columns): blob1 kind (box_auth, box_gone, phone_open, phone_close, refused, connect, rate_limited), blob2 serverId, blob3 detail, blob4 colo, blob5 synthetic-probe marker, double1 value (a close code, a phone count, or 1), double2 uploaded bytes, double3 downloaded bytes, double4 uploaded frames, double5 downloaded frames, double6 duration in milliseconds, index1 kind. The additional kinds are traffic, box_presence, auth_failed and internal_error. Every box connection is recorded once when it ends: box_gone if it had authenticated, auth_failed if it never did, with the reason (unauthorized, auth timeout, gone, control too large, too many pending boxes and so on), the close code and how long it had been open. Only unauthorized was recorded before the pre-release bug hunt (B107), so a box that timed out was invisible; a pending box closed to make room for a newcomer was recorded as refused and now counts here, while a newcomer turned away for want of room is still refused. detail is one of a fixed list of close and refusal reasons (anything else is recorded empty); too many pending boxes joined it with the pending-box limit. Traffic is aggregated on socket attachments and flushed on alarms/close, not per frame. Authenticated synthetic probes are tagged and excluded from fleet summaries. Presence includes already-connected boxes, rather than counting recent handshakes alone. Last-ten-minute presence remains an estimate: disconnected boxes age out, and Analytics Engine can sample or drop events.

Queries. Run these in the dashboard (Workers → the Worker → your dataset → the SQL query box), or via the SQL API. Each sums _sample_interval so counts stay right under Analytics Engine's sampling.

-- boxes seen online in the last 10 minutes (a live-ish estimate)
SELECT COUNT(DISTINCT blob2) FROM shahi_relay
WHERE blob5 != 'probe' AND blob1 IN ('box_auth', 'box_presence') AND timestamp > NOW() - INTERVAL '10' MINUTE;

-- what is happening, by event, in the last hour
SELECT blob1 AS kind, SUM(_sample_interval) AS n FROM shahi_relay
WHERE blob5 != 'probe' AND timestamp > NOW() - INTERVAL '1' HOUR GROUP BY kind ORDER BY n DESC;

-- why links are closing (watch for a spike in one code)
SELECT double1 AS close_code, SUM(_sample_interval) AS n FROM shahi_relay
WHERE blob5 != 'probe' AND blob1 = 'phone_close' AND timestamp > NOW() - INTERVAL '1' HOUR
GROUP BY close_code ORDER BY n DESC;

-- refusals, by cause (box offline vs too many phones vs rate)
SELECT blob3 AS reason, SUM(_sample_interval) AS n FROM shahi_relay
WHERE blob5 != 'probe' AND blob1 = 'refused' AND timestamp > NOW() - INTERVAL '1' HOUR
GROUP BY reason ORDER BY n DESC;

-- a box that reconnects too often is failing; find it
SELECT blob2 AS serverId, SUM(_sample_interval) AS reconnects FROM shahi_relay
WHERE blob5 != 'probe' AND blob1 = 'box_auth' AND timestamp > NOW() - INTERVAL '1' HOUR
GROUP BY serverId HAVING reconnects > 20 ORDER BY reconnects DESC;

A live /stats endpoint (optional). GET /stats returns those figures as JSON, gated so it discloses nothing by default. Set three secrets to turn it on and let it read:

cd relay
bunx wrangler secret put STATS_TOKEN        # a bearer the caller must send
bunx wrangler secret put CF_ACCOUNT_ID      # your account id
bunx wrangler secret put CF_ANALYTICS_TOKEN # an API token with Account Analytics Read

Then curl -H "Authorization: Bearer <STATS_TOKEN>" https://<relay>/stats. With no STATS_TOKEN the endpoint is a 404; with it but no query credentials it is a 503 that says so.

Abuse limits and alerts. The CONNECT_LIMIT binding allows thirty connection attempts per source per ten seconds at each edge location, counting an IPv4 source by its address and an IPv6 source by its /64. The full IPv6 address used to be the key, and one host normally holds a whole /64, so binding each connection to a fresh address gave each its own budget. A source with a larger delegation (/56, /48) still gets one bucket per /64, so the binding alone cannot bound one host's IPv6 abuse; the optional zone WAF rule below is the control for that. The limiter is eventually consistent and is not a global traffic or billing ceiling; see Cloudflare's locality and accuracy documentation. Retiring alternate hostnames does not itself configure a WAF rule. Review the actual account's limits and set these controls in the Cloudflare dashboard:

  • Error/availability monitoring for shahi-relay through monitoring available to the account. A Workers-specific error alert was not offered in the checked account's Notifications catalog on 5 September 2026.
  • A spend / usage notification — so an abuse spike on the paid plan arrives as a message, not a surprise bill.
  • Optionally a WAF rate-limit rule on /v1/* keyed on client IP, a second limit ahead of Worker and Durable Object execution, and the one that can group a larger IPv6 delegation. Distributed floods remain an availability risk even with per-source limits.

What the relay still cannot tell you is a box that is up but wedged (herdr down behind a healthy socket); that needs a status byte in the box's ping, which lives in the sidecar, not here — a deliberate next step.

Close codes, as sent by this relay:

code reason to when
4401 unauthorized box bad auth, or anything that is not one
4401 auth timeout box ten seconds after the challenge with no auth
4409 replaced box another connection proved the same key
4429 too many pending boxes box a ninth unauthenticated box connection: the longest-waiting pending one (at least 1 s old) is closed, or the newcomer if all eight are younger
1000 silent box five minutes without a frame or a ping
4429 control too large either a text frame over 4 KiB, counted in UTF-8 bytes
4404 box offline phone no ready box on connect, on send, or box went away; a waiting phone that sent more than its hello, or made room for a newer one
4200 box online phone a phone waiting with ?wait=1, the moment its box authenticates: dial again now
4429 too many phones phone a ninth phone: the longest-silent phone open at least 1 s is closed with this, or else, on a box that sent "proofs":true, the longest-waiting one it has not reported proven; the newcomer if neither exists
4429 frame too large phone a data frame over 1 MiB, sent by the phone or by the box for this link; either way the box is told close for the link, and the box and its other phones stay connected
4429 rate phone the token bucket (64 KiB/s, 1 MiB burst) ran dry; every phone frame, text included, costs at least 256 bytes, so at most 256 frames/s sustained and 4,096 in a burst
1000 no hello phone fifteen seconds after opening without a frame
1000 idle phone ten minutes without a frame either way
1000 closed by box phone the box sent close for the link: a failed proof, an unknown or malformed hello, a revoked device after its bye, or any other end the box chose

Telemetry events are retained by Analytics Engine for three months. The stable server identifier can correlate a box's events. The public policy documents the fields and retention in docs/privacy-policy.md. Omitting STATS_TOKEN hides /stats but does not stop collection; remove the TELEMETRY binding to stop Shahi event collection on a self-hosted relay.

Delivery bounds (protocol 2)

Phones acknowledge every accumulated 64 KiB of received encrypted frames with an encrypted { t: "ack", bytes }. Counts include the 24-byte encryption overhead and exclude the initial clear hello. A sidecar sends at most 2 MiB unacknowledged per link. Frames beyond that window are held, in order and unsealed, up to (maxRequestsPerLink + 1) × maxFrameBytes = 5 MiB, and leave as acknowledgments arrive; they are sealed only as they leave, so counters stay in sequence. Ending the link at the window, as the sidecar once did, cost a phone its link and every request on it whenever a few large answers came back together. A request keeps its slot until its answer has left, so excess work still gets 429 rather than a queue. A phone that stops acknowledging fills the held frames and loses only its own link. The bye skips the queue. The relay cannot forge acknowledgments. Do not drop a sealed frame and continue the same link: strict crypto counters would reject everything that follows it.

Pending client work is capped at 16 requests and 2 MiB of bodies. The sidecar runs at most four requests per link and sixteen across the relay, and its HTTP surface admits at most 32 handlers and two concurrent upload/file handlers. Excess work receives 429/503 and is never silently queued. Responses are read with a byte limit, cancelled at the limit, and answered with 413. Single-frame limits still apply: this does not add 100 MB attachments.

Updated clients and computers negotiate /api/uploads/limits and support 32 MiB per uploaded file using sequential 64 KiB chunks. Each request stays inside the existing encrypted frame/body limits. The server journals accepted offsets, rejects conflicting retries, checks the final SHA-256 and atomically publishes the completed file. Lost chunk/finalization replies can be retried without duplicating the file. No upload contents are stored at Cloudflare.

One unfinished upload per device and two per computer reserve at most 64 MiB of partial file space. Sessions expire after one hour, with periodic cleanup; completed receipts are bounded to 128 per computer within that lifetime, and a computer at that bound says so and when a place opens, rather than "Another file is uploading". Revoking a device or signing out discards its unfinished uploads at once. Completed attachments retain the existing 14-day cleanup policy. Clients use 60-second per-request deadlines, a bounded reconnect retry and a 55-minute overall transfer deadline. Closing the picker/cancelling stops subsequent chunks; expiry cleans up partials when the computer cannot receive cancellation.

The bandwidth rate remains 64 KiB/s per phone, with existing backpressure limits. Chunk scheduling reserves room for chat/control traffic before sealing, and counts in-flight chunks as bulk traffic. A 32 MiB upload can take around 12–15 minutes depending on latency; the higher size limit is not a speed increase. Mobile process termination requires selecting the file again; this release resumes transient connections while the upload task remains alive.

Older computers retain the 779,264-byte (761 KiB) single-file relay limit, inside 783,360 bytes of multipart body capacity. SSH/direct uploads remain capped at 32 MiB. The pre-change file-transfer verification records those older boundaries. See the new transfer report for implementation status and validation limits.

Reconnects use exponential backoff with equal jitter (half to all of the delay, capped at 30 seconds). Polling respects scheduled retries. Only 30 seconds of stable connection resets the backoff. Protocol 2 requires updated sidecar, web and native clients; the /v1/ routing namespace and box-auth signature prefix are unchanged because their relay-side contract is unchanged.

See operations.md for metrics, alert thresholds and the local 1,000-phone load test. The public per-IP rate limits still apply to clients behind one office/VPN address; a paid Workers plan does not remove them.

Recovering from network changes

A pairing is durable; its WebSocket is replaceable. Opening a saved computer after an offline launch retries automatically. Regaining or changing the network starts a fresh connection immediately, while repeated notifications share the same new attempt. The native app reconnects once per change of network or of whether it is usable, not on each step of reachability: a new network arrives with reachability unknown and then known, which reconnected everything twice, and the first report at launch is not a change at all. Ordinary polling still respects the retry backoff, and each saved computer recovers independently.

Returning to the foreground differs by client. The native app starts a fresh connection immediately, but only on a return from the background. iOS reports "inactive" for Control Center, Notification Center, the app switcher and system alerts, and reconnecting on the way back from those dropped healthy links and failed sends that had probably reached herdr, and an edited retry, under a new operation id, could run one twice. The links' own watchdogs notice anything a glance could break. The hosted web app keeps any relay link that can show it is alive: a socket already closed, or silent past the shared silence limit, is replaced at once without backoff; a link that looks live gets one /api/meta probe, and only ten seconds of silence replaces it. Replacing every link on every return dropped whatever was in flight through it — an agent start that takes minutes, a prompt, a file transfer — each time someone switched tabs or apps.

RelayLink.close() is final. A request on a closed link rejects with "The connection through was closed." instead of reopening it; only ensureConnected() reopens one. A request once did reopen it, so after sign-out, revocation or a bye the web client redialled the relay for a computer it had just left. It now also retires the computer before closing that computer's link.

Connection establishment has a 15-second deadline, including the first authenticated response. A stuck CONNECTING/CLOSING socket, send failure, or missing close callback cannot stop recovery: Shahi detaches the old connection locally, rejects its pending requests, and retries with fresh encryption keys. Late callbacks from the old connection cannot affect the replacement. An uncertain write is never automatically replayed by the transport.

Quiet phones acknowledge each encrypted heartbeat, using protocol 2's existing ACK frame. The computer releases a phone after 150 seconds without authenticated traffic, checked every 30 seconds, so dead connections cannot retain relay slots forever just because the computer keeps sending dashboard updates. Older clients remain compatible through their ordinary authenticated requests and ACKs.

Tests model missing open/close callbacks, stale session keys, repeated network changes, and phone-slot cleanup. Browser and native fixtures also blackhole a live connection without closing it, then verify foreground recovery and an offline cold launch without re-pairing or duplicate prompts.

Use the ASCII xn-- form of an international relay domain in RELAY_URL; native pairing refuses a non-ASCII origin. Unfinished uploads are discarded after ten idle minutes or when that device starts another, with one hour as the hard cap. Revocation/logout discard that owner’s unfinished transfers.