Repository navigation
feat(relay): relay2 — canonical Durable Objects relay on PartyKit (tunnel v2) - #6165
Conversation
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
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdded 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. ChangesRelay Worker
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
Possibly related PRs
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
🧪 Generate unit tests (beta)
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. Comment |
Greptile SummaryThis PR adds an experimental Cloudflare Worker and per-host Durable Object implementation of the existing relay protocol.
Confidence Score: 4/5The 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
|
| 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
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
| // 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"); |
There was a problem hiding this 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
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.
🧹 Preview Cleanup CompleteThe following preview resources have been cleaned up:
Thank you for your contribution! 🎉 |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
apps/relay-do/src/host-tunnel.ts (2)
349-355: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winFail the pending request when the host send fails.
sendToHostswallows the send error.proxyHttpawaits its promise, so a failed send leaves the caller blocked for the fullREQUEST_TIMEOUT_MSof 30 seconds before it returns 502. Report the failure to the caller soproxyHttpcan 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 valueBatch the registration storage writes.
Lines 130-131 issue two sequential
putcalls. A singleputwith 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
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (11)
apps/relay-do/README.mdapps/relay-do/package.jsonapps/relay-do/src/access.tsapps/relay-do/src/api-client.tsapps/relay-do/src/auth.tsapps/relay-do/src/host-tunnel.tsapps/relay-do/src/index.tsapps/relay-do/src/trpc-error.tsapps/relay-do/src/types.tsapps/relay-do/tsconfig.jsonapps/relay-do/wrangler.jsonc
| 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, | ||
| }); |
There was a problem hiding this comment.
🗄️ 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);
JSRepository: 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.
| if (!access.ok) { | ||
| return acceptAndClose(`Forbidden: ${accessDenialMessage(access.reason)}`); |
There was a problem hiding this comment.
🩺 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.
There was a problem hiding this comment.
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)
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Prod canary results (2026-08-04, sandbox host on Azure, client in SF)Same host, same PTY, same test script, head-to-head:
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 — 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: |
There was a problem hiding this comment.
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
| if (isTrpcPath(pathAfterHost(c))) { | ||
| return trpcErrorResponse( | ||
| c, | ||
| result.status === 403 ? "FORBIDDEN" : "UNAUTHORIZED", |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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(() => { |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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>
| return; | ||
| } | ||
| if (ping.type !== "ping") return; | ||
| if (ping.token) void this.refreshToken(ping.token); |
There was a problem hiding this comment.
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.)
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>
| 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, | |
| ); | |
| }); | |
| } |
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
There was a problem hiding this comment.
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
| ): Promise<AuthContext | null> { | ||
| try { | ||
| const { payload } = await jwtVerify(token, getJWKS(authUrl), { | ||
| issuer: authUrl, |
There was a problem hiding this comment.
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>
What
apps/relay2— a ground-up relay on Cloudflare Workers + Durable Objects (PartyKit'spartyserver), with a new host↔relay protocol designed around what a globally-addressable DO makes possible. Superseded and replaced the wire-compatibleapps/relay-doprototype 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
/healthat startup to pick a protocol (anything withoutproto: 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.
getServerByName(hostId)ws:open/ws:frame/ws:closeJSON envelopes, base64 binary, correlation mapspartysocketHTTP 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.tsruns the realTunnelClientV2against a deployed Worker — ALL PASS on every deploy, including regression tests for two bugs found in review: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 deploymid-session recovered in ≤10s.Review findings fixed
Two rounds of adversarial review; every finding fixed and re-verified:
/v2/dialaccepted unknown tickets and left the socket open forever — unauthenticated callers could spin up DOs and leak sockets. Now closed 1008.setWebSocketAutoResponseswallowed tunneled frames matching the keepalive payload, silently breaking verbatim splice. Keepalives now handled per-connection for the host only.content-encoding/content-lengthforwarded 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.shcutover via Cloudflare for SaaS, then deleteapps/relayand rename.wrangler/workers-typesaligned with relay2 — v4 and v5 coexisting split@cloudflaretype identity and broke that app's typecheck plus sherif.Before merging
relay2 has no CI deploy workflow yet (needs a
CLOUDFLARE_API_TOKENsecret) — deploys are manualwrangler deployuntil 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