Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): bypass OpenNext for /api/ws/* upgrades so WSS works in prod

Generf645c8ad2995
diff --git a/src/email-worker/wrangler.toml b/src/email-worker/wrangler.toml
index dff1742ae..257d39556 100644
--- a/src/email-worker/wrangler.toml
+++ b/src/email-worker/wrangler.toml
@@ -11,6 +11,7 @@ enabled = true
[dev]
port = 8787
+inspector_port = 9231
[[d1_databases]]
binding = "DB"
diff --git a/src/web/custom-worker.ts b/src/web/custom-worker.ts
new file mode 100644
index 000000000..772dcf8b8
--- /dev/null
+++ b/src/web/custom-worker.ts
@@ -0,0 +1,28 @@
+// The import below is generated by `opennextjs-cloudflare build` and doesn't
+// exist at typecheck time. The build step creates it before wrangler bundles.
+// @ts-expect-error — generated at build time
+import openNextHandler from "./.open-next/worker.js"
+
+// @ts-expect-error — generated at build time
+export { DOQueueHandler } from "./.open-next/worker.js"
+
+const handler: ExportedHandler<CloudflareEnv> = {
+ async fetch(request, env, ctx) {
+ const url = new URL(request.url)
+ const isWsUpgrade = request.headers.get("Upgrade")?.toLowerCase() === "websocket"
+ const isWsPath = url.pathname === "/api/ws" || url.pathname.startsWith("/api/ws/")
+
+ // Forward WebSocket upgrades on /api/ws/* directly to the ws-do worker.
+ // OpenNext drops Response.webSocket when wrapping Next.js route handlers
+ // (opennextjs-cloudflare#784), so we intercept before Next.js sees it.
+ // /api/ws/token is a plain HTTP endpoint — it has no Upgrade header and
+ // falls through to OpenNext.
+ if (isWsUpgrade && isWsPath) {
+ return env.WS_DO_WORKER.fetch(request)
+ }
+
+ return (openNextHandler as ExportedHandler<CloudflareEnv>).fetch!(request, env, ctx)
+ },
+}
+
+export default handler
diff --git a/src/web/src/app/api/ws/route.ts b/src/web/src/app/api/ws/route.ts
deleted file mode 100644
index 56b72eb14..000000000
--- a/src/web/src/app/api/ws/route.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createAuth } from "@/lib/auth"
-
-export async function GET(request: Request) {
- const url = new URL(request.url)
- const agentId = url.searchParams.get("agentId")
- if (!agentId) return new Response("agentId required", { status: 400 })
-
- const { env } = getCloudflareContext()
- const wsEnv = env as Env
-
- const auth = createAuth(wsEnv)
- const session = await auth.api.getSession({ headers: request.headers })
- if (!session) return new Response("Unauthorized", { status: 401 })
-
- const userId = session.user.id
- const doUrl = new URL(request.url)
- doUrl.searchParams.set("userId", userId)
- const doRequest = new Request(doUrl.toString(), request)
- doRequest.headers.set("X-Authenticated-User", userId)
- return wsEnv.WS_DO_WORKER.fetch(doRequest)
-}
diff --git a/src/web/src/app/api/ws/user/route.ts b/src/web/src/app/api/ws/user/route.ts
deleted file mode 100644
index 01da981d8..000000000
--- a/src/web/src/app/api/ws/user/route.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { getCloudflareContext } from "@opennextjs/cloudflare"
-import { createAuth } from "@/lib/auth"
-
-export async function GET(request: Request) {
- const { env } = getCloudflareContext()
- const wsEnv = env as Env
-
- const auth = createAuth(wsEnv)
- const session = await auth.api.getSession({ headers: request.headers })
- if (!session) return new Response("Unauthorized", { status: 401 })
-
- const userId = session.user.id
- const doUrl = new URL(request.url)
- doUrl.searchParams.set("userId", userId)
- const doRequest = new Request(doUrl.toString(), request)
- doRequest.headers.set("X-Authenticated-User", userId)
- return wsEnv.WS_DO_WORKER.fetch(doRequest)
-}
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 44397fb0b..7528af8f0 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -17,25 +17,28 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
onMessageRef.current = onMessage
const connect = useCallback(async () => {
- let url: string
- let authToken: string | null = null
-
- if (isDev) {
- // Dev: connect directly to ws-do worker, authenticate via auth message
- try {
- const res = await fetch("/api/ws/token")
- if (!res.ok) return
- const { userId, token } = await res.json() as { userId: string; token: string }
- url = `ws://localhost:${WS_DO_PORT}/?userId=${userId}`
- authToken = token
- } catch {
- return
- }
- } else {
- // Production: go through Next.js API route (service binding handles WS upgrade)
- url = `${location.origin.replace("http", "ws")}/api/ws/user`
+ // Unified flow for dev and prod:
+ // 1. Fetch /api/ws/token over HTTP (cookie-authenticated Next.js route).
+ // 2. Open WebSocket with ?userId= and authenticate via {type:"auth",token}.
+ // The custom OpenNext wrapper (src/web/custom-worker.ts) forwards /api/ws/*
+ // upgrade requests directly to the ws-do worker in prod; in dev we connect
+ // to the ws-do worker on localhost directly.
+ let userId: string
+ let authToken: string
+ try {
+ const res = await fetch("/api/ws/token")
+ if (!res.ok) return
+ const body = await res.json() as { userId: string; token: string }
+ userId = body.userId
+ authToken = body.token
+ } catch {
+ return
}
+ const url = isDev
+ ? `ws://localhost:${WS_DO_PORT}/?userId=${userId}`
+ : `${location.origin.replace("http", "ws")}/api/ws/user?userId=${userId}`
+
let ws: WebSocket
try {
ws = new WebSocket(url)
@@ -46,9 +49,7 @@ export function useUserWs(onMessage: (msg: WsMessage) => void) {
ws.onopen = () => {
reconnectDelay.current = WS_RECONNECT_INIT
- if (authToken) {
- ws.send(JSON.stringify({ type: "auth", token: authToken }))
- }
+ ws.send(JSON.stringify({ type: "auth", token: authToken }))
}
ws.onmessage = (e) => {
diff --git a/src/web/src/lib/use-ws.ts b/src/web/src/lib/use-ws.ts
index 2b8534304..e0a55a8cf 100644
--- a/src/web/src/lib/use-ws.ts
+++ b/src/web/src/lib/use-ws.ts
@@ -17,25 +17,23 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)
onMessageRef.current = onMessage
const connect = useCallback(async () => {
- let url: string
- let authToken: string | null = null
-
- if (isDev) {
- // Dev: connect directly to ws-do worker, authenticate via auth message
- try {
- const res = await fetch("/api/ws/token")
- if (!res.ok) return
- const { token } = await res.json() as { token: string }
- url = `ws://localhost:${WS_DO_PORT}/?agentId=${agentId}`
- authToken = token
- } catch {
- return
- }
- } else {
- // Production: go through Next.js API route (service binding handles WS upgrade)
- url = `${location.origin.replace("http", "ws")}/api/ws?agentId=${agentId}`
+ // Unified dev/prod flow — see use-user-ws.ts for rationale.
+ let userId: string
+ let authToken: string
+ try {
+ const res = await fetch("/api/ws/token")
+ if (!res.ok) return
+ const body = await res.json() as { userId: string; token: string }
+ userId = body.userId
+ authToken = body.token
+ } catch {
+ return
}
+ const url = isDev
+ ? `ws://localhost:${WS_DO_PORT}/?userId=${userId}&agentId=${agentId}`
+ : `${location.origin.replace("http", "ws")}/api/ws?userId=${userId}&agentId=${agentId}`
+
let ws: WebSocket
try {
ws = new WebSocket(url)
@@ -46,9 +44,7 @@ export function useAgentWs(agentId: string, onMessage: (msg: WsMessage) => void)
ws.onopen = () => {
reconnectDelay.current = WS_RECONNECT_INIT
- if (authToken) {
- ws.send(JSON.stringify({ type: "auth", token: authToken }))
- }
+ ws.send(JSON.stringify({ type: "auth", token: authToken }))
}
ws.onmessage = (e) => {
diff --git a/src/web/src/test/e2e/ws.test.ts b/src/web/src/test/e2e/ws.test.ts
new file mode 100644
index 000000000..9f688a028
--- /dev/null
+++ b/src/web/src/test/e2e/ws.test.ts
@@ -0,0 +1,131 @@
+import { describe, it, expect, beforeAll, afterAll } from "vitest"
+import { randomUUID } from "crypto"
+import { signUp, signIn, sessionRequest } from "../helpers/auth"
+import { sql } from "../helpers/db"
+
+const WS_DO_PORT = Number(process.env.NEXT_PUBLIC_WS_DO_PORT) || 8789
+const WS_DO_HTTP = `http://localhost:${WS_DO_PORT}`
+const WS_DO_WS = `ws://localhost:${WS_DO_PORT}`
+
+const testEmail = `e2e_ws_${randomUUID().slice(0, 8)}@test.local`
+const testPassword = "TestPassword123!"
+const testName = "E2E WS User"
+
+async function wsReachable(): Promise<boolean> {
+ try {
+ // Any non-WS GET returns 400 ("userId required") — we just want a TCP RST-free response.
+ const res = await fetch(WS_DO_HTTP, { method: "GET" })
+ return res.status < 500
+ } catch {
+ return false
+ }
+}
+
+function waitForMessage<T = unknown>(
+ ws: WebSocket,
+ predicate: (msg: T) => boolean,
+ timeoutMs = 3000,
+): Promise<T> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ ws.removeEventListener("message", handler)
+ reject(new Error(`waitForMessage timed out after ${timeoutMs}ms`))
+ }, timeoutMs)
+ const handler = (e: MessageEvent) => {
+ try {
+ const msg = JSON.parse(e.data as string) as T
+ if (predicate(msg)) {
+ clearTimeout(timer)
+ ws.removeEventListener("message", handler)
+ resolve(msg)
+ }
+ } catch { /* ignore non-JSON */ }
+ }
+ ws.addEventListener("message", handler)
+ })
+}
+
+function waitForClose(ws: WebSocket, timeoutMs = 3000): Promise<CloseEvent> {
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error("close timed out")), timeoutMs)
+ ws.addEventListener("close", (e) => {
+ clearTimeout(timer)
+ resolve(e)
+ })
+ })
+}
+
+function openWs(userId: string): Promise<WebSocket> {
+ return new Promise((resolve, reject) => {
+ const ws = new WebSocket(`${WS_DO_WS}/?userId=${userId}`)
+ const onError = () => reject(new Error("ws failed to open"))
+ ws.addEventListener("open", () => {
+ ws.removeEventListener("error", onError)
+ resolve(ws)
+ }, { once: true })
+ ws.addEventListener("error", onError, { once: true })
+ })
+}
+
+describe("ws (dev direct to ws-do)", () => {
+ let cookie: string
+ let userId: string
+ let token: string
+ let available = false
+
+ beforeAll(async () => {
+ available = await wsReachable()
+ if (!available) return
+
+ await signUp(testEmail, testPassword, testName)
+ cookie = await signIn(testEmail, testPassword)
+
+ const res = await sessionRequest("/api/ws/token", cookie)
+ expect(res.status).toBe(200)
+ const body = await res.json() as { userId: string; token: string }
+ userId = body.userId
+ token = body.token
+ })
+
+ afterAll(() => {
+ try {
+ sql(`DELETE FROM "session" WHERE userId IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)
+ sql(`DELETE FROM "account" WHERE userId IN (SELECT id FROM "user" WHERE email = '${testEmail}')`)
+ sql(`DELETE FROM "user" WHERE email = '${testEmail}'`)
+ } catch { /* ignore */ }
+ })
+
+ it("authenticates with valid token and receives broadcast", async () => {
+ if (!available) return
+
+ const ws = await openWs(userId)
+ ws.send(JSON.stringify({ type: "auth", token }))
+
+ const ack = await waitForMessage<{ type: string }>(ws, (m) => m.type === "auth.ok")
+ expect(ack.type).toBe("auth.ok")
+
+ const payload = { type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }
+ const recv = waitForMessage<typeof payload>(ws, (m) => m.type === "runtime.status")
+
+ const broadcastRes = await fetch(`${WS_DO_HTTP}/broadcast/user/${userId}`, {
+ method: "POST",
+ body: JSON.stringify(payload),
+ })
+ expect(broadcastRes.status).toBe(200)
+
+ const received = await recv
+ expect(received).toEqual(payload)
+
+ ws.close()
+ })
+
+ it("closes with 1008 on invalid token", async () => {
+ if (!available) return
+
+ const ws = await openWs(userId)
+ ws.send(JSON.stringify({ type: "auth", token: "not-a-real-token" }))
+
+ const closeEvent = await waitForClose(ws)
+ expect(closeEvent.code).toBe(1008)
+ })
+})
diff --git a/src/web/wrangler.toml b/src/web/wrangler.toml
index fa33212b4..159363089 100644
--- a/src/web/wrangler.toml
+++ b/src/web/wrangler.toml
@@ -1,7 +1,11 @@
name = "alook-web"
-main = ".open-next/worker.js"
+main = "custom-worker.ts"
compatibility_date = "2026-04-09"
compatibility_flags = ["nodejs_compat"]
+# Disable esbuild keep_names — otherwise __name(...) wrappers leak into
+# stringified inline scripts (ThemeScript, next-themes) and throw
+# "__name is not defined" at runtime in the browser.
+keep_names = false
[observability]
enabled = true
diff --git a/src/ws-do/src/ws-durable.test.ts b/src/ws-do/src/ws-durable.test.ts
index 40f278587..dd8fda508 100644
--- a/src/ws-do/src/ws-durable.test.ts
+++ b/src/ws-do/src/ws-durable.test.ts
@@ -119,18 +119,17 @@ describe("WebSocketDurableObject", () => {
expect(res.status).toBe(426)
})
- it("pre-authenticates when X-Authenticated-User header is present", async () => {
+ it("attaches an unauthenticated ConnectionState on upgrade", async () => {
const { durable, ctx } = createDO()
const req = new Request("http://internal/?userId=u1", {
- headers: { Upgrade: "websocket", "X-Authenticated-User": "user-99" },
+ headers: { Upgrade: "websocket" },
})
await durable.fetch(req)
- // Check that acceptWebSocket was called and the server WS has authenticated state
const acceptCall = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0]
const serverWs = acceptCall[0]
- expect(serverWs.deserializeAttachment()).toEqual({ userId: "user-99", authenticated: true })
+ expect(serverWs.deserializeAttachment()).toEqual({ userId: "", authenticated: false })
})
})
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
index c4772cd6c..f639b2d86 100644
--- a/src/ws-do/src/ws-durable.ts
+++ b/src/ws-do/src/ws-durable.ts
@@ -27,15 +27,9 @@ export class WebSocketDurableObject extends DurableObject<Env> {
this.ctx.acceptWebSocket(server)
- const preAuthUserId = request.headers.get("X-Authenticated-User")
- const state: ConnectionState = preAuthUserId
- ? { userId: preAuthUserId, authenticated: true }
- : { userId: "", authenticated: false }
- server.serializeAttachment(state)
-
- if (preAuthUserId) {
- log.info("websocket connected (pre-auth)", { userId: preAuthUserId })
- }
+ // Connections start unauthenticated. Client must send {type:"auth",token}
+ // before any other message. See webSocketMessage below.
+ server.serializeAttachment({ userId: "", authenticated: false } as ConnectionState)
this.ctx.setWebSocketAutoResponse(
new WebSocketRequestResponsePair("ping", "pong")