Skip to content

feat(relay): relay2 — canonical Durable Objects relay on PartyKit (tunnel v2) - #6165

Merged
saddlepaddle merged 16 commits into
mainfrom
relay-do-prototype
Aug 5, 2026
Merged

saddlepaddle merged 16 commits into
mainfrom
relay-do-prototype

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Aug 4, 2026 •

Copy link
Copy Markdown
Member

What

apps/relay2 — a ground-up relay on Cloudflare Workers + Durable Objects (PartyKit's partyserver), with a new host↔relay protocol designed around what a globally-addressable DO makes possible. Superseded and replaced the wire-compatible apps/relay-do prototype this PR started as.

Nothing in production changes on merge. relay2 is additive; hosts keep using the Fly relay until an operator points them elsewhere. The only behavioral change to shipped code is that host-service probes the relay's /health at startup to pick a protocol (anything without proto: 2 → today's v1 client).

The protocol (tunnel v2)

One small JSON control channel per host. For each stream, the relay issues a one-time ticket, the host dials back a fresh WebSocket, and the DO splices bytes verbatim.

Fly relay relay2
Upstash directory + Lua register/unregister/sweep getServerByName(hostId)
fly-replay routing + 6PN cross-machine WS bridge (deleted)
ws:open/ws:frame/ws:close JSON envelopes, base64 binary, correlation maps raw spliced sockets, binary passthrough
hand-rolled reconnect/backoff/watchdog on both ends partysocket
SIGTERM drain choreography + in-band drain frames DO restart → ~1s reconnect
7 always-on performance-2x/4GB machines usage-priced; hibernation makes idle tunnels ~free

HTTP stays (as an isolated http-exchange.ts): the SDK, MCP, and the API's Slack path call hosts from serverless runtimes that can't hold a WebSocket.

Verification

apps/relay2/scripts/e2e-probe.ts runs the real TunnelClientV2 against a deployed Worker — ALL PASS on every deploy, including regression tests for two bugs found in review:

PASS  _whoowns 200
PASS  client WS opens
PASS  10 text echoes — rtt min=43 median=49 max=131ms
PASS  ping-shaped frame splices verbatim
PASS  64KB binary echo intact
PASS  HTTP proxy round-trip + host-secret injection
PASS  bogus dial ticket refused — close=1008
PASS  _whoowns 503 after close

Also driven end-to-end from the desktop app against a deployed Worker on real Durable Objects: all orgs negotiated v2, terminals/diffs/event bus healthy.

Prior prototype measurements on the same host: keystroke echo 121–125ms vs Fly's 124ms, 1.49MB PTY burst clean (max frame 12.4KB, well under the 1MB DO limit), wrangler deploy mid-session recovered in ≤10s.

Review findings fixed

Two rounds of adversarial review; every finding fixed and re-verified:

  • /v2/dial accepted unknown tickets and left the socket open forever — unauthenticated callers could spin up DOs and leak sockets. Now closed 1008.
  • DO-wide setWebSocketAutoResponse swallowed tunneled frames matching the keepalive payload, silently breaking verbatim splice. Keepalives now handled per-connection for the host only.
  • Host-reconnect race (state set after evicting the replacement; teardown keyed off state instead of synchronous tags) — the same class as the gray-dot presence bug seen in prod.
  • Non-atomic read-then-write on presence version and on the session token.
  • Orphaned dial sockets, content-encoding/content-length forwarded over an already-decompressed body, unchunked bodies vs the DO per-message ceiling, silent frame drops on overflow, unsendable close codes.

Also here

  • plans/20260804-1815-relay2-durable-objects-canonical.md — the ExecPlan, with the Decision Log (D-1…D-19) recording why each call was made. Remaining milestones: resumable streams, API-served endpoint config, relay.superset.sh cutover via Cloudflare for SaaS, then delete apps/relay and rename.
  • electric-proxy's wrangler/workers-types aligned with relay2 — v4 and v5 coexisting split @cloudflare type identity and broke that app's typecheck plus sherif.

Before merging

relay2 has no CI deploy workflow yet (needs a CLOUDFLARE_API_TOKEN secret) — deploys are manual wrangler deploy until that lands. Given the July outage came from a silently-failing deploy, the workflow should fail loudly to Slack when it's added.

https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G

Wire-compatible port of apps/relay to Workers + Durable Objects. One DO
per hostId replaces the Upstash directory, fly-replay routing, and 6PN
WS bridging; hibernation keeps idle tunnels out of billable duration.
Canary via the relay-url-override PostHog flag; no client changes.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Added a Cloudflare Durable Objects relay Worker. It authenticates JWTs, checks host access, manages host and client WebSocket tunnels, proxies HTTP and tRPC requests, tracks host liveness, and includes deployment configuration, documentation, CSP support, and a relay2 rollout plan.

Changes

Relay Worker

Layer / File(s) Summary
Relay contracts and authorization
apps/relay-do/src/types.ts, apps/relay-do/src/auth.ts, apps/relay-do/src/api-client.ts, apps/relay-do/src/access.ts, apps/relay-do/src/trpc-error.ts
Defines relay environment and tunnel protocol types. Adds JWT verification, API-backed host authorization with bounded caches, and serialized tRPC error responses.
HostTunnel transport
apps/relay-do/src/host-tunnel.ts
Adds Durable Object host registration, client channels, HTTP proxying, WebSocket forwarding, and tunnel message handling.
HostTunnel lifecycle management
apps/relay-do/src/host-tunnel.ts
Adds session cleanup, liveness alarms, pending-request rejection, channel closure, and retried host online-status updates.
Worker wiring and deployment setup
apps/relay-do/src/index.ts, apps/relay-do/package.json, apps/relay-do/tsconfig.json, apps/relay-do/wrangler.jsonc, apps/relay-do/README.md, apps/desktop/src/renderer/index.html
Adds Worker routes, package and deployment configuration, prototype documentation, and the relay endpoint in the desktop CSP allowlist.
Relay2 rollout plan
plans/20260804-1815-relay2-durable-objects-canonical.md
Documents the planned protocol, resumability, endpoint selection, rollout milestones, validation commands, and relay decommissioning steps.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant RelayWorker
  participant AuthAccess
  participant HostTunnel
  participant Host
  Client->>RelayWorker: Send tunnel or host request
  RelayWorker->>AuthAccess: Verify JWT and check host access
  AuthAccess-->>RelayWorker: Return authorization result
  RelayWorker->>HostTunnel: Forward registration or proxied request
  HostTunnel->>Host: Send tunnel message
  Host-->>HostTunnel: Return response or WebSocket frame
  HostTunnel-->>RelayWorker: Return proxied result
  RelayWorker-->>Client: Return HTTP or WebSocket response
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The pull request has no author-provided description, so it omits the required change summary, testing details, and checklist. Add the What & why, How I tested it, and Checklist sections with accurate implementation details and validation results.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the relay2 Durable Objects and tunnel v2 work, although the PartyKit reference is not reflected in the implemented Cloudflare Worker changes.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch relay-do-prototype

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds an experimental Cloudflare Worker and per-host Durable Object implementation of the existing relay protocol.

  • Verifies JWTs and host access at the Worker edge before routing requests to a host-specific Durable Object.
  • Multiplexes host control traffic, proxied tRPC requests, and client WebSocket channels through the Durable Object.
  • Persists host session and liveness state across hibernation and reports presence through the existing API.
  • Adds Wrangler deployment configuration, package metadata, and prototype deployment documentation.

Confidence Score: 4/5

The replacement-socket teardown race should be fixed before merging because a routine host reconnect can dismantle the newly registered session.

Closing the previous control socket can schedule a stale close callback that unconditionally deletes shared session and alarm state belonging to its replacement, leaving an open host socket marked offline and without liveness supervision.

Files Needing Attention: apps/relay-do/src/host-tunnel.ts

Important Files Changed

Filename Overview
apps/relay-do/src/host-tunnel.ts Implements Durable Object session, channel, HTTP proxy, and liveness handling, but replacement socket events can tear down the newly installed session.
apps/relay-do/src/index.ts Defines the Worker’s health, tunnel, preflight, authenticated tRPC, and WebSocket routes and dispatches requests to host-specific Durable Objects.
apps/relay-do/src/access.ts Ports the existing relay’s organization and host authorization checks with equivalent per-isolate allow and deny caching.
apps/relay-do/src/auth.ts Verifies relay JWT issuer, audience, signature, and required identity claims using the API JWKS endpoint.
apps/relay-do/wrangler.jsonc Configures the Worker entrypoint, Durable Object binding and migration, API URL, compatibility date, and observability.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Worker as Relay Worker
  participant API
  participant DO as HostTunnel Durable Object
  participant Host as Host Service

  Host->>Worker: GET /tunnel (JWT, hostId)
  Worker->>API: host.checkAccess
  API-->>Worker: allowed
  Worker->>DO: /register
  DO-->>Host: Control WebSocket

  Client->>Worker: "/hosts/:hostId/*"
  Worker->>API: host.checkAccess
  API-->>Worker: allowed
  Worker->>DO: /connect or /http
  DO->>Host: Multiplexed tunnel frame
  Host-->>DO: Response/frame
  DO-->>Client: HTTP response or WebSocket frame
Loading
Prompt To Fix All With AI
### Issue 1
apps/relay-do/src/host-tunnel.ts:116-121
**Stale close tears down replacement**

When a host reconnect replaces an existing control socket, the old socket's later close callback unconditionally tears down the shared state now owned by the replacement, deleting its session and alarm, closing its client channels, rejecting pending requests, and marking the connected host offline.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "feat(relay): add Cloudflare Durable Obje..." | Re-trigger Greptile

Comment thread apps/relay-do/src/host-tunnel.ts Outdated
Comment on lines +116 to +121
// so tear the old session down inline (without the setOnline(false)
// write — we're about to write true for the new socket).
this.teardownSession("Replaced by new tunnel");
for (const ws of this.ctx.getWebSockets(HOST_TAG)) {
try {
ws.close(1000, "Replaced by new tunnel");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Stale close tears down replacement

When a host reconnect replaces an existing control socket, the old socket's later close callback unconditionally tears down the shared state now owned by the replacement, deleting its session and alarm, closing its client channels, rejecting pending requests, and marking the connected host offline.

Knowledge Base Used: Relay and Electric Proxy: Remote Host Connectivity

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/relay-do/src/host-tunnel.ts
Line: 116-121

Comment:
**Stale close tears down replacement**

When a host reconnect replaces an existing control socket, the old socket's later close callback unconditionally tears down the shared state now owned by the replacement, deleting its session and alarm, closing its client channels, rejecting pending requests, and marking the connected host offline.

**Knowledge Base Used:** [Relay and Electric Proxy: Remote Host Connectivity](https://app.greptile.com/personal-org-6810/-/custom-context/knowledge-base/superset-sh/superset/-/docs/relay-streams.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ✅ Neon database branch

Thank you for your contribution! 🎉

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (2)
apps/relay-do/src/host-tunnel.ts (2)

349-355: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Fail the pending request when the host send fails.

sendToHost swallows the send error. proxyHttp awaits its promise, so a failed send leaves the caller blocked for the full REQUEST_TIMEOUT_MS of 30 seconds before it returns 502. Report the failure to the caller so proxyHttp can reject immediately.

♻️ Proposed refactor: return the send result
-	private sendToHost(host: WebSocket, message: TunnelRequest): void {
+	private sendToHost(host: WebSocket, message: TunnelRequest): boolean {
 		try {
 			host.send(JSON.stringify(message));
+			return true;
 		} catch {
 			// Socket died between hostWs() and send; close/error handler cleans up.
+			return false;
 		}
 	}

Then reject the pending request in proxyHttp:

 					this.pendingRequests.set(id, { resolve, reject, timer });
-					this.sendToHost(host, {
+					const sent = this.sendToHost(host, {
 						type: "http",
 						id,
 						method: payload.method,
 						path: payload.path,
 						headers: payload.headers,
 						body: payload.body,
 					});
+					if (!sent) {
+						clearTimeout(timer);
+						this.pendingRequests.delete(id);
+						reject(new Error("Tunnel send failed"));
+					}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/relay-do/src/host-tunnel.ts` around lines 349 - 355, Update sendToHost
to report whether host.send succeeds instead of swallowing failure, then update
proxyHttp to reject or otherwise fail the pending request immediately when the
send fails. Preserve the existing cleanup behavior while ensuring callers
receive the 502 path without waiting for REQUEST_TIMEOUT_MS.

129-132: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Batch the registration storage writes.

Lines 130-131 issue two sequential put calls. A single put with an object writes both keys in one operation and reduces registration latency.

♻️ Proposed refactor
 		const session: HostSession = { hostId, token };
-		await this.ctx.storage.put("session", session);
-		await this.ctx.storage.put("lastPongAt", Date.now());
+		await this.ctx.storage.put({ session, lastPongAt: Date.now() });
 		await this.ctx.storage.setAlarm(Date.now() + PING_INTERVAL_MS);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/relay-do/src/host-tunnel.ts` around lines 129 - 132, Batch the
registration writes in the host session initialization flow by replacing the
separate storage.put calls for "session" and "lastPongAt" with one storage.put
operation using both key-value entries, while keeping the existing alarm
scheduling unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/relay-do/src/host-tunnel.ts`:
- Around line 218-228: Update webSocketMessage so channel frames preserve binary
payloads by forwarding ArrayBuffer data with encoding: "base64" instead of
decoding it as UTF-8. For non-channel frames, continue decoding binary messages
to text before forwarding, while leaving string messages unchanged.
- Around line 276-296: Update handleSocketGone to verify that the closing host
WebSocket still owns the active session before calling teardownSession, deleting
the alarm/session, or invoking setOnline(false). Ignore stale close events from
replaced host sockets while preserving channel handling and normal teardown for
the current host.

In `@apps/relay-do/src/index.ts`:
- Around line 74-75: Update the access-denial handling around checkHostAccess in
both the shown branch and the equivalent /tunnel branch so access.reason ===
"error" returns the existing service-unavailable response behavior (HTTP 503 or
WebSocket SERVICE_UNAVAILABLE), while other denial reasons continue returning
the current forbidden response.

---

Nitpick comments:
In `@apps/relay-do/src/host-tunnel.ts`:
- Around line 349-355: Update sendToHost to report whether host.send succeeds
instead of swallowing failure, then update proxyHttp to reject or otherwise fail
the pending request immediately when the send fails. Preserve the existing
cleanup behavior while ensuring callers receive the 502 path without waiting for
REQUEST_TIMEOUT_MS.
- Around line 129-132: Batch the registration writes in the host session
initialization flow by replacing the separate storage.put calls for "session"
and "lastPongAt" with one storage.put operation using both key-value entries,
while keeping the existing alarm scheduling unchanged.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: d324d6c3-8acb-40ea-bdec-ad8218d18187

📥 Commits

Reviewing files that changed from the base of the PR and between 9a485c9 and 417ad26.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (11)
  • apps/relay-do/README.md
  • apps/relay-do/package.json
  • apps/relay-do/src/access.ts
  • apps/relay-do/src/api-client.ts
  • apps/relay-do/src/auth.ts
  • apps/relay-do/src/host-tunnel.ts
  • apps/relay-do/src/index.ts
  • apps/relay-do/src/trpc-error.ts
  • apps/relay-do/src/types.ts
  • apps/relay-do/tsconfig.json
  • apps/relay-do/wrangler.jsonc

Comment thread apps/relay-do/src/host-tunnel.ts Outdated
Comment on lines +218 to +228
const text =
typeof message === "string" ? message : new TextDecoder().decode(message);

if (attachment.kind === "channel") {
const host = this.hostWs();
if (!host) return;
this.sendToHost(host, {
type: "ws:frame",
id: attachment.id,
data: text,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check the tunnel protocol contract and host-side ws:frame handling for base64 support.
set -euo pipefail

fd -t f 'tunnel-protocol.ts' --exec sed -n '1,120p' {}

rg -nP -C 6 "ws:frame" --type=ts -g '!apps/relay-do/**'

Repository: superset-sh/superset

Length of output: 1585


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Tracked files matching host-tunnel.ts or tunnel-protocol.ts:"
git ls-files | rg 'host-tunnel\.ts|tunnel-protocol\.ts|apps/relay-do'

echo
echo "Relevant host-tunnel.ts around lines 200-270:"
sed -n '200,270p' apps/relay-do/src/host-tunnel.ts

echo
echo "Locate TunnelWsFrame consumers/usages outside relay-do:"
rg -nC 5 "TunnelWsFrame|ws:frame|encoding\\?:" --type=ts -g '!apps/relay-do/**'

Repository: superset-sh/superset

Length of output: 2427


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "host-tunnel.ts sendToHost implementation:"
rg -nC 12 "sendToHost|base64ToArrayBuffer|TunnelRequest" apps/relay-do/src/host-tunnel.ts packages/shared/src/tunnel-protocol.ts

echo
echo "Read-only UTF-8 probe for binary ArrayBuffer with invalid UTF-8 sequence:"
node - <<'JS'
const invalidUtf8 = new Uint8Array([0xff, 0xfe]);
const decoded = new TextDecoder().decode(invalidUtf8);
console.log(JSON.stringify(decoded));
console.log(decoded.length);
console.log(decoded.codePointAt(0) === 0xfffd);
JS

Repository: superset-sh/superset

Length of output: 16095


Preserve binary client frames instead of decoding them as UTF-8.

webSocketMessage() decodes every client ArrayBuffer before forwarding channel frames, and invalid UTF-8 byte sequences become �. Forward binary client frames with encoding: "base64", and decode them before forwarding text frames when not a channel frame.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/relay-do/src/host-tunnel.ts` around lines 218 - 228, Update
webSocketMessage so channel frames preserve binary payloads by forwarding
ArrayBuffer data with encoding: "base64" instead of decoding it as UTF-8. For
non-channel frames, continue decoding binary messages to text before forwarding,
while leaving string messages unchanged.

Comment thread apps/relay-do/src/host-tunnel.ts Resolved
Comment thread apps/relay-do/src/index.ts Outdated
Comment on lines +74 to +75
if (!access.ok) {
return acceptAndClose(`Forbidden: ${accessDenialMessage(access.reason)}`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Preserve transient access-check failures.

checkHostAccess uses reason: "error" when the API request fails. These branches convert that result into a forbidden response.

Clients can treat 403 or WebSocket close code 1008 as a permanent denial. Return 503 or SERVICE_UNAVAILABLE for this reason, as the _whoowns route already does.

Proposed fix
 if (!access.ok) {
 	const detail = `Forbidden: ${accessDenialMessage(access.reason)}`;
+	if (access.reason === "error") {
+		return wantsTrpc
+			? trpcErrorResponse(c, "SERVICE_UNAVAILABLE", "Access check failed")
+			: c.json({ error: "Access check failed" }, 503);
+	}
 	return wantsTrpc
 		? trpcErrorResponse(c, "FORBIDDEN", detail)
 		: c.json({ error: detail }, 403);
 }

Apply equivalent retryable handling to /tunnel.

Also applies to: 145-149

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/relay-do/src/index.ts` around lines 74 - 75, Update the access-denial
handling around checkHostAccess in both the shown branch and the equivalent
/tunnel branch so access.reason === "error" returns the existing
service-unavailable response behavior (HTTP 503 or WebSocket
SERVICE_UNAVAILABLE), while other denial reasons continue returning the current
forbidden response.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 12 files

Architecture diagram
sequenceDiagram
    participant Client as Client (CLI/Desktop)
    participant Worker as Worker (Edge)
    participant AuthSvc as Auth Service (JWKS)
    participant APISvc as API Service (TRPC)
    participant DurableObject as HostTunnel (Durable Object)
    participant HostSvc as Host-Service (Host WS)

    Note over Client,HostSvc: Tunnel Registration (Host connects)
    HostSvc->>Worker: GET /tunnel?hostId=X (WS upgrade + Bearer token)
    Worker->>AuthSvc: verifyJWT (JWKS fetch + verify)
    AuthSvc-->>Worker: Auth context (sub, orgIds)
    Worker->>APISvc: checkHostAccess (TRPC: host.checkAccess)
    APISvc-->>Worker: allowed=true/false
    alt Access Denied
        Worker-->>HostSvc: 101 WebSocket upgrade + close 1008 (Forbidden)
    else Access Allowed
        Worker->>DurableObject: Forward WS upgrade (idFromName(hostId))
        DurableObject->>DurableObject: Register host (store session, set alarm)
        DurableObject-->>HostSvc: 101 WebSocket (host control channel)
        DurableObject->>APISvc: setOnline(true) (async, retry up to 3x)
    end

    Note over Client,HostSvc: Client Channel Connection (user opens terminal)
    Client->>Worker: GET /hosts/:hostId/* (WS upgrade + Bearer token)
    Worker->>AuthSvc: verifyJWT
    AuthSvc-->>Worker: Auth context
    Worker->>APISvc: checkHostAccess (TRPC: host.checkAccess)
    APISvc-->>Worker: allowed=true/false
    alt Access Denied
        Worker-->>Client: 403 Forbidden (or 401 for missing token)
    else Access Allowed
        Worker->>DurableObject: Forward WS upgrade (idFromName(hostId))
        DurableObject->>DurableObject: Create client channel (assign ID)
        DurableObject->>HostSvc: Send ws:open frame (id, path, query)
        DurableObject-->>Client: 101 WebSocket (client channel)
    end

    Note over Client,HostSvc: Frame Routing (during session)
    Client->>DurableObject: Send text/binary frame
    DurableObject->>HostSvc: Forward as ws:frame (id, data)
    HostSvc->>DurableObject: Send pong / ws:frame / http:response
    alt pong received
        DurableObject->>DurableObject: Update lastPongAt in storage
    else ws:frame from host
        DurableObject->>Client: Forward frame (decode base64 if needed)
    else http:response
        DurableObject->>DurableObject: Resolve pending request via ID
    end

    Note over DurableObject: Liveness Check (Alarm)
    loop Every 30s (alarm)
        DurableObject->>DurableObject: Check lastPongAt vs now
        alt Pong within 90s
            DurableObject->>HostSvc: Send ping frame
            DurableObject->>DurableObject: Set next alarm in 30s
        else Pong timeout
            DurableObject->>HostSvc: Close WS (1001)
            DurableObject->>DurableObject: Teardown session (reject pending, close channels)
            DurableObject->>APISvc: setOnline(false)
        end
    end

    Note over Client,HostSvc: HTTP Proxy (TRPC calls to host)
    Client->>Worker: POST /hosts/:hostId/trpc/* (REST)
    Worker->>AuthSvc: verifyJWT
    Worker->>APISvc: checkHostAccess
    Worker->>DurableObject: POST /http (JSON: method, path, headers, body)
    DurableObject->>DurableObject: Create pending request (timeout 30s, max 1000)
    DurableObject->>HostSvc: Send http frame (id, method, path, headers, body)
    HostSvc-->>DurableObject: http:response (id, status, headers, body)
    DurableObject-->>Worker: JSON response (status, headers, body)
    alt Tunnel error
        Worker-->>Client: TRPC error (SERVICE_UNAVAILABLE / BAD_GATEWAY)
    else Success
        Worker-->>Client: Forwarded HTTP response
    end

    Note over HostSvc,DurableObject: Disconnect / Reconnect
    HostSvc->>DurableObject: WS closed (host disconnects)
    DurableObject->>DurableObject: Teardown session (reject pending, close channels)
    DurableObject->>APISvc: setOnline(false)
    DurableObject->>DurableObject: Delete alarm + session from storage
    Note over HostSvc: Host reconnects on ~1s backoff
    HostSvc->>Worker: GET /tunnel (new WS upgrade)
    Worker->>AuthSvc: verifyJWT
    Worker->>APISvc: checkHostAccess
    Worker->>DurableObject: Forward WS (new registration)
    DurableObject->>DurableObject: Close old socket (last-write-wins), register new
    DurableObject->>APISvc: setOnline(true)
Loading

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread apps/relay-do/README.md Resolved
@saddlepaddle

Copy link
Copy Markdown
Member Author

Prod canary results (2026-08-04, sandbox host on Azure, client in SF)

Same host, same PTY, same test script, head-to-head:

Metric Fly relay DO relay
WS connect (cold) 149ms ~800ms
Keystroke echo RTT (median of 10) 124ms 121–125ms
Keystroke min / max 80 / 149ms 84 / 156ms
1.49MB output burst 560ms (2.6 MB/s) 777ms (1.9 MB/s)
Largest WS frame observed 4.1KB 12.4KB

Also verified end-to-end through the DO relay: host register/unregister (clean setOnline writes), CLI → API → relay → host tRPC (~0.5s incl. CLI boot), project create with git clone, terminal create/send/read, and redeploy survival — wrangler deploy restarted the DO mid-session and the host was reconnected and serving within ≤10s with no intervention.

Verdict on the three risks: keystroke latency is a wash (the headline risk is cleared); the 1MB DO frame limit is a non-issue (PTY frames chunk at ~12KB); deploy-drop recovery is fast. Cold connect is ~650ms slower (Worker-edge JWT verify + uncached access check + DO wake) — optimizable, and irrelevant once attached. Burst throughput trails Fly ~40% but both are far above terminal needs.

Operational notes from the run: superset start --daemon does not propagate RELAY_URL from the caller's env to the daemonized process (foreground start does); and one daemon restart failed to pick up the flag override for reasons not yet explained (first start and API-side evaluation both worked) — worth a look before any real rollout.

https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 18 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/relay2/src/index.ts">

<violation number="1" location="apps/relay2/src/index.ts:150">
P2: Access-check outages are returned to tRPC callers as `UNAUTHORIZED`/401, causing the host client to refresh a valid JWT and report an auth failure instead of a service-unavailable response. Map `status: 500` to `SERVICE_UNAVAILABLE` while preserving the existing 401 and 403 mappings.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread apps/relay2/src/index.ts
if (isTrpcPath(pathAfterHost(c))) {
return trpcErrorResponse(
c,
result.status === 403 ? "FORBIDDEN" : "UNAUTHORIZED",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Access-check outages are returned to tRPC callers as UNAUTHORIZED/401, causing the host client to refresh a valid JWT and report an auth failure instead of a service-unavailable response. Map status: 500 to SERVICE_UNAVAILABLE while preserving the existing 401 and 403 mappings.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/relay2/src/index.ts, line 150:

<comment>Access-check outages are returned to tRPC callers as `UNAUTHORIZED`/401, causing the host client to refresh a valid JWT and report an auth failure instead of a service-unavailable response. Map `status: 500` to `SERVICE_UNAVAILABLE` while preserving the existing 401 and 403 mappings.</comment>

<file context>
@@ -100,76 +113,48 @@ app.get("/v2/dial", async (c) => {
+		if (isTrpcPath(pathAfterHost(c))) {
+			return trpcErrorResponse(
+				c,
+				result.status === 403 ? "FORBIDDEN" : "UNAUTHORIZED",
+				result.message,
+			);
</file context>

…rim relay2 comments

workers-types 4.x + 5.x coexisting split @cloudflare type identity and
broke electric-proxy's drizzle table types (23 errors) plus sherif.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G
…ugh, races

- /v2/dial rejects unknown/expired/consumed tickets (was: accepted and left
  open forever, letting unauthenticated callers spin up DOs and leak sockets)
- keepalives handled in onMessage for host connections only; the DO-wide
  setWebSocketAutoResponse intercepted a matching payload on *every* socket,
  so a tunneled frame equal to it was swallowed instead of spliced
- host state set before evicting the replaced socket, and teardown keys off
  tags (synchronous) not state, so a reconnect can't close its own
  replacement and mark presence offline
- presence version is an in-instance counter, not a read-then-write on
  storage that two writers could interleave
- unpaired dial sockets get an expiry instead of lingering
- host refreshes the relay's stored token on each ping, so the presence write
  at disconnect can't fail on an expired JWT
- strip content-encoding/length (fetch already decompressed) and chunk HTTP
  bodies below the DO per-message ceiling
- pipe() closes on buffer overflow instead of dropping frames, and maps
  unsendable close codes (1005/1006) to 1011

Probe gains regression tests for the ping-shaped frame and bogus tickets;
ALL PASS locally and against the deployed Worker.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G
…hine

Routes this machine's own workspaces through the relay instead of
127.0.0.1, so relay protocol changes can be tested end-to-end in dev
without a second machine or a packaged build.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 issues found across 9 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/relay2/src/presence.ts">

<violation number="1" location="apps/relay2/src/presence.ts:26">
P1: A stale offline retry can mark a live host offline after the Durable Object is reconstructed because this gate relies on the in-memory `presenceSeq`, which resets, and `setOnline` has no API-side ordering check. Persist the sequence in DO storage or send a monotonic version through `setOnline` and enforce it server-side so the reconnect race remains protected across hibernation/restarts.</violation>
</file>

<file name="packages/host-service/src/tunnel/tunnel-client-v2.ts">

<violation number="1" location="packages/host-service/src/tunnel/tunnel-client-v2.ts:109">
P2: When `getAuthToken()` rejects, this fallback silently keeps the relay alive with its previous JWT; if that JWT expires before disconnect, the offline presence write fails and stale online presence can remain. Logging the failure with host/tunnel context (and considering a reconnect when token refresh remains unavailable) would make this degraded state observable.</violation>
</file>

<file name="apps/relay2/src/host-tunnel.ts">

<violation number="1" location="apps/relay2/src/host-tunnel.ts:202">
P2: Malformed control frames are not safely handled: the cast does not validate a non-null object or string token, so `null` can throw in the message handler and an object token can corrupt the stored session credential. Validate the parsed payload shape before checking `type` or refreshing the token.</violation>

<violation number="2" location="apps/relay2/src/host-tunnel.ts:207">
P2: Token refresh is fire-and-forget, so a rejected Durable Object storage read/write becomes an unhandled rejection; attach a catch that logs the host context before discarding it.

(Based on your team's feedback about handling async failures.)</violation>

<violation number="3" location="apps/relay2/src/host-tunnel.ts:316">
P1: Presence updates can still be applied out of order: the supersession check does not cancel an already in-flight API mutation, so a late offline write can overwrite a newer online write. Serializing these writes or making `setOnline` conditional on the version would preserve the host's actual liveness.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

isOnline: boolean;
}): Promise<void> {
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
if (isSuperseded(version)) return;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: A stale offline retry can mark a live host offline after the Durable Object is reconstructed because this gate relies on the in-memory presenceSeq, which resets, and setOnline has no API-side ordering check. Persist the sequence in DO storage or send a monotonic version through setOnline and enforce it server-side so the reconnect race remains protected across hibernation/restarts.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/relay2/src/presence.ts, line 26:

<comment>A stale offline retry can mark a live host offline after the Durable Object is reconstructed because this gate relies on the in-memory `presenceSeq`, which resets, and `setOnline` has no API-side ordering check. Persist the sequence in DO storage or send a monotonic version through `setOnline` and enforce it server-side so the reconnect race remains protected across hibernation/restarts.</comment>

<file context>
@@ -3,30 +3,27 @@ import { createApiClient } from "./api-client";
-	await storage.put("onlineVersion", version);
 	for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
-		if ((await storage.get<number>("onlineVersion")) !== version) return;
+		if (isSuperseded(version)) return;
 		try {
 			await createApiClient(token, apiUrl).host.setOnline.mutate({
</file context>

isOnline: boolean,
): Promise<void> {
return writePresence({
version: ++this.presenceSeq,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Presence updates can still be applied out of order: the supersession check does not cancel an already in-flight API mutation, so a late offline write can overwrite a newer online write. Serializing these writes or making setOnline conditional on the version would preserve the host's actual liveness.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/relay2/src/host-tunnel.ts, line 316:

<comment>Presence updates can still be applied out of order: the supersession check does not cancel an already in-flight API mutation, so a late offline write can overwrite a newer online write. Serializing these writes or making `setOnline` conditional on the version would preserve the host's actual liveness.</comment>

<file context>
@@ -244,13 +297,24 @@ export class HostTunnel extends Server<RelayEnv> {
 	): Promise<void> {
 		return writePresence({
-			storage: this.ctx.storage,
+			version: ++this.presenceSeq,
+			isSuperseded: (version) => version !== this.presenceSeq,
 			apiUrl: this.env.NEXT_PUBLIC_API_URL,
</file context>

control.send(JSON.stringify({ type: "ping", token }));
}
})
.catch(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: When getAuthToken() rejects, this fallback silently keeps the relay alive with its previous JWT; if that JWT expires before disconnect, the offline presence write fails and stale online presence can remain. Logging the failure with host/tunnel context (and considering a reconnect when token refresh remains unavailable) would make this degraded state observable.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/host-service/src/tunnel/tunnel-client-v2.ts, line 109:

<comment>When `getAuthToken()` rejects, this fallback silently keeps the relay alive with its previous JWT; if that JWT expires before disconnect, the offline presence write fails and stale online presence can remain. Logging the failure with host/tunnel context (and considering a reconnect when token refresh remains unavailable) would make this degraded state observable.</comment>

<file context>
@@ -85,9 +95,22 @@ export class TunnelClientV2 {
+						control.send(JSON.stringify({ type: "ping", token }));
+					}
+				})
+				.catch(() => {
+					if (control.readyState === WebSocket.OPEN) {
+						control.send('{"type":"ping"}');
</file context>

if (typeof message !== "string") return;
let ping: ControlPing;
try {
ping = JSON.parse(message) as ControlPing;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Malformed control frames are not safely handled: the cast does not validate a non-null object or string token, so null can throw in the message handler and an object token can corrupt the stored session credential. Validate the parsed payload shape before checking type or refreshing the token.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/relay2/src/host-tunnel.ts, line 202:

<comment>Malformed control frames are not safely handled: the cast does not validate a non-null object or string token, so `null` can throw in the message handler and an object token can corrupt the stored session credential. Validate the parsed payload shape before checking `type` or refreshing the token.</comment>

<file context>
@@ -162,7 +189,25 @@ export class HostTunnel extends Server<RelayEnv> {
+			if (typeof message !== "string") return;
+			let ping: ControlPing;
+			try {
+				ping = JSON.parse(message) as ControlPing;
+			} catch {
+				return;
</file context>

Comment thread apps/relay2/src/host-tunnel.ts Outdated
return;
}
if (ping.type !== "ping") return;
if (ping.token) void this.refreshToken(ping.token);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Token refresh is fire-and-forget, so a rejected Durable Object storage read/write becomes an unhandled rejection; attach a catch that logs the host context before discarding it.

(Based on your team's feedback about handling async failures.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/relay2/src/host-tunnel.ts, line 207:

<comment>Token refresh is fire-and-forget, so a rejected Durable Object storage read/write becomes an unhandled rejection; attach a catch that logs the host context before discarding it.

(Based on your team's feedback about handling async failures.) </comment>

<file context>
@@ -162,7 +189,25 @@ export class HostTunnel extends Server<RelayEnv> {
+				return;
+			}
+			if (ping.type !== "ping") return;
+			if (ping.token) void this.refreshToken(ping.token);
+			conn.send('{"type":"pong"}');
+			return;
</file context>
Suggested change
if (ping.token) void this.refreshToken(ping.token);
if (ping.token) {
void this.refreshToken(ping.token).catch((error) => {
console.warn(
`[relay2] token refresh failed for ${this.name}`,
error,
);
});
}

Comment thread apps/relay2/src/host-tunnel.ts Resolved
A ping already in flight from a replaced host socket could read the
session after the replacement wrote its fresh token and put back its own
stale one, breaking presence writes until the next ping. The host id now
rides the connection state, so the live host writes {hostId, token}
unconditionally and a replaced socket writes nothing.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G
Lets a deployed relay verify tokens from an API that is reachable at a
different address than the one it issues for — a local API behind a
tunnel — which is what makes testing a deployed Worker against a dev
stack possible.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G
FORCE_RELAY_ROUTING and the JWT issuer override existed only to test a
relay from a single machine; trivial to reintroduce when needed.

Claude-Session: https://claude.ai/code/session_01A2JifsfA63nWthegPwNt8G

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 6 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="apps/relay2/src/auth.ts">

<violation number="1" location="apps/relay2/src/auth.ts:24">
P2: Relay2 now rejects valid JWTs when the API is accessed through a URL different from the token issuer, such as a tunneled local API, because `authUrl` is forced into both `iss` and `aud`. Keep a distinct configurable issuer for claim validation while using `authUrl` only for JWKS retrieval.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

Comment thread apps/relay2/src/auth.ts
): Promise<AuthContext | null> {
try {
const { payload } = await jwtVerify(token, getJWKS(authUrl), {
issuer: authUrl,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Relay2 now rejects valid JWTs when the API is accessed through a URL different from the token issuer, such as a tunneled local API, because authUrl is forced into both iss and aud. Keep a distinct configurable issuer for claim validation while using authUrl only for JWKS retrieval.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/relay2/src/auth.ts, line 24:

<comment>Relay2 now rejects valid JWTs when the API is accessed through a URL different from the token issuer, such as a tunneled local API, because `authUrl` is forced into both `iss` and `aud`. Keep a distinct configurable issuer for claim validation while using `authUrl` only for JWKS retrieval.</comment>

<file context>
@@ -15,21 +15,14 @@ function getJWKS(authUrl: string): ReturnType<typeof createRemoteJWKSet> {
 		const { payload } = await jwtVerify(token, getJWKS(authUrl), {
-			issuer,
-			audience: issuer,
+			issuer: authUrl,
+			audience: authUrl,
 		});
</file context>

This branch was previously deployed

2 inactive (1 outdated) deployments
preview — da75e445 Deployed Aug 5, 2026 by saddlepaddle via Deploy Web #7162
production — 35a9d379 Deployed Aug 5, 2026 by saddlepaddle via build / Build - macOS (x64) #762
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant