Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(ws-do): worker entry + durable object with session-only auth

Gener95d341ab92bf
diff --git a/src/ws-do/src/index.ts b/src/ws-do/src/index.ts
index 1e30d9f63..481affca2 100644
--- a/src/ws-do/src/index.ts
+++ b/src/ws-do/src/index.ts
@@ -1,4 +1,21 @@
+export { WebSocketDurableObject } from "./ws-durable"
+
export default {
- async fetch() { return new Response("ws-do") },
+ async fetch(request: Request, env: Env): Promise<Response> {
+ const url = new URL(request.url)
+
+ const userBroadcast = url.pathname.match(/^\/broadcast\/user\/(.+)$/)
+ if (userBroadcast && request.method === "POST") {
+ const userId = userBroadcast[1]
+ const doId = env.WS_DO.idFromName("user:" + userId)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(new Request("http://internal/broadcast", { method: "POST", body: request.body }))
+ }
+
+ const userId = url.searchParams.get("userId")
+ if (!userId) return new Response("userId required", { status: 400 })
+ const doId = env.WS_DO.idFromName("user:" + userId)
+ const stub = env.WS_DO.get(doId)
+ return stub.fetch(request)
+ },
}
-export class WebSocketDurableObject {}
diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.ts
new file mode 100644
index 000000000..549f0bfdb
--- /dev/null
+++ b/src/ws-do/src/ws-durable.ts
@@ -0,0 +1,84 @@
+import { DurableObject } from "cloudflare:workers"
+import { createDb, queries } from "@alook/shared"
+
+interface ConnectionState {
+ userId: string
+ authenticated: boolean
+}
+
+export class WebSocketDurableObject extends DurableObject<Env> {
+ async fetch(request: Request): Promise<Response> {
+ const url = new URL(request.url)
+
+ if (url.pathname === "/broadcast" && request.method === "POST") {
+ const body = await request.text()
+ this.broadcast(body)
+ return new Response("ok")
+ }
+
+ if (request.headers.get("Upgrade") !== "websocket") {
+ return new Response("Expected WebSocket", { status: 426 })
+ }
+
+ const pair = new WebSocketPair()
+ const [client, server] = Object.values(pair)
+
+ 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)
+
+ this.ctx.setWebSocketAutoResponse(
+ new WebSocketRequestResponsePair("ping", "pong")
+ )
+
+ return new Response(null, { status: 101, webSocket: client })
+ }
+
+ async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
+ if (typeof message !== "string") return
+
+ let parsed: unknown
+ try { parsed = JSON.parse(message) } catch { ws.close(1008, "Invalid JSON"); return }
+
+ const state = ws.deserializeAttachment() as ConnectionState
+
+ const msg = parsed as { type: string; token?: string }
+ if (msg.type === "auth") {
+ const userId = await this.validateToken(msg.token!)
+ if (!userId) { ws.close(1008, "Unauthorized"); return }
+ ws.serializeAttachment({ userId, authenticated: true } as ConnectionState)
+ ws.send(JSON.stringify({ type: "auth.ok" }))
+ return
+ }
+
+ if (!state.authenticated) {
+ ws.close(1008, "Not authenticated")
+ return
+ }
+ }
+
+ async webSocketClose(): Promise<void> {}
+
+ async webSocketError(ws: WebSocket, error: unknown): Promise<void> {
+ console.error("WS error:", error)
+ try { ws.close(1011, "Internal error") } catch {}
+ }
+
+ private broadcast(message: string): void {
+ for (const ws of this.ctx.getWebSockets()) {
+ const state = ws.deserializeAttachment() as ConnectionState
+ if (state.authenticated && ws.readyState === WebSocket.OPEN) {
+ ws.send(message)
+ }
+ }
+ }
+
+ private async validateToken(token: string): Promise<string | null> {
+ const db = createDb(this.env.DB)
+ return queries.session.getValidSession(db, token)
+ }
+}