Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(ws-do): enforce user DO identity binding (#433)
Gener772fda4bb227
diff --git a/src/ws-do/src/internal-user-broadcast.ts b/src/ws-do/src/internal-user-broadcast.tsnew file mode 100644index 000000000..9c5e507d2--- /dev/null+++ b/src/ws-do/src/internal-user-broadcast.ts@@ -0,0 +1,27 @@+export const INTERNAL_USER_TARGET_HEADER = "x-alook-internal-user-target"++export function createInternalUserBroadcastRequest(+ targetUserId: string,+ body: BodyInit | null,+ sourceHeaders?: Headers,+ streamingBody = false,+): Request {+ const headers = new Headers()+ const contentType = sourceHeaders?.get("content-type")+ if (contentType) headers.set("content-type", contentType)+ headers.set(INTERNAL_USER_TARGET_HEADER, targetUserId)++ const init = {+ method: "POST",+ headers,+ body,+ } as RequestInit & { duplex?: "half" }+ if (streamingBody) init.duplex = "half"++ return new Request("http://internal/broadcast", init)+}++export function getInternalUserTarget(request: Request): string | null {+ const targetUserId = request.headers.get(INTERNAL_USER_TARGET_HEADER)?.trim()+ return targetUserId || null+}diff --git a/src/ws-do/src/routes/audit-broadcast.test.ts b/src/ws-do/src/routes/audit-broadcast.test.tsindex 738bed915..ea9463b16 100644--- a/src/ws-do/src/routes/audit-broadcast.test.ts+++ b/src/ws-do/src/routes/audit-broadcast.test.ts@@ -6,6 +6,7 @@ import {type RouterHandler,type RouterTestContext,} from "./test-harness"+import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"const sharedMocks = getSharedMocks()const mockHashCredential = sharedMocks.hashCredential@@ -73,6 +74,7 @@ describe("ws-do router", () => {expect(doMock.idFromName).toHaveBeenCalledWith("user:owner_1")const stubReq = doMock.stubFetch.mock.calls[0][0] as Requestexpect(stubReq.url).toBe("http://internal/broadcast")+ expect(stubReq.headers.get(INTERNAL_USER_TARGET_HEADER)).toBe("owner_1")const body = JSON.parse(await stubReq.text()) as Record<string, unknown>// Matches the shape ws-durable.ts emits for daemon-originating frames.expect(body.type).toBe("community:bot.audit_event")diff --git a/src/ws-do/src/routes/audit-broadcast.ts b/src/ws-do/src/routes/audit-broadcast.tsindex c473169a9..887459e21 100644--- a/src/ws-do/src/routes/audit-broadcast.ts+++ b/src/ws-do/src/routes/audit-broadcast.ts@@ -1,5 +1,6 @@import { WS_EVENTS } from "@alook/shared"import type { RouterContext } from "../router-context"+import { createInternalUserBroadcastRequest } from "../internal-user-broadcast"export async function handleAuditBroadcast({ request, env, url, log }: RouterContext): Promise<Response | null> {// POST /internal/broadcast-bot-audit-event — the wake-worker calls this@@ -65,11 +66,11 @@ export async function handleAuditBroadcast({ request, env, url, log }: RouterConconst stub = env.WS_DO.get(doId)try {await stub.fetch(- new Request("http://internal/broadcast", {- method: "POST",- headers: { "content-type": "application/json" },- body: JSON.stringify(frame),- }),+ createInternalUserBroadcastRequest(+ b.ownerUserId,+ JSON.stringify(frame),+ new Headers({ "content-type": "application/json" }),+ ),)} catch (err) {log.warn("internal_broadcast_bot_audit_event_failed", {diff --git a/src/ws-do/src/routes/broadcast.test.ts b/src/ws-do/src/routes/broadcast.test.tsindex bebc44788..b645ab6dd 100644--- a/src/ws-do/src/routes/broadcast.test.ts+++ b/src/ws-do/src/routes/broadcast.test.ts@@ -6,6 +6,7 @@ import {type RouterHandler,type RouterTestContext,} from "./test-harness"+import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"const sharedMocks = getSharedMocks()const mockHashCredential = sharedMocks.hashCredential@@ -80,11 +81,12 @@ describe("ws-do router", () => {expect(await res.text()).toBe("daemon-ok")})- it("forwards POST /broadcast/user/:userId to correct DO instance", async () => {+ it("forwards POST /broadcast/user/:userId with a router-owned target marker", async () => {doMock.stubFetch.mockResolvedValue(new Response("ok"))const body = JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" })const req = new Request("http://localhost/broadcast/user/user-123", {method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "attacker-spoof" },body,})@@ -96,6 +98,7 @@ describe("ws-do router", () => {const stubReq = doMock.stubFetch.mock.calls[0][0] as Requestexpect(stubReq.url).toBe("http://internal/broadcast")expect(stubReq.method).toBe("POST")+ expect(stubReq.headers.get(INTERNAL_USER_TARGET_HEADER)).toBe("user-123")expect(await stubReq.text()).toBe(body)expect(res.status).toBe(200)})@@ -205,6 +208,9 @@ describe("ws-do router", () => {"http://internal/broadcast",])expect(internalRequests.map((internal) => internal.method)).toEqual(["POST", "POST"])+ expect(internalRequests.map((internal) => (+ internal.headers.get(INTERNAL_USER_TARGET_HEADER)+ ))).toEqual(["u2", "u3"])await expect(Promise.all(internalRequests.map((internal) => internal.text()))).resolves.toEqual([JSON.stringify({ type: "event", value: 7 }),JSON.stringify({ type: "event", value: 7 }),diff --git a/src/ws-do/src/routes/broadcast.ts b/src/ws-do/src/routes/broadcast.tsindex c35cc421f..d4a46e79e 100644--- a/src/ws-do/src/routes/broadcast.ts+++ b/src/ws-do/src/routes/broadcast.ts@@ -1,4 +1,5 @@import type { RouterContext } from "../router-context"+import { createInternalUserBroadcastRequest } from "../internal-user-broadcast"const maxBulkUserIds = 1000const bulkBatchSize = 40@@ -40,10 +41,7 @@ async function broadcastToBulkTarget(): Promise<BulkTargetResult> {const doId = env.WS_DO.idFromName("user:" + userId)const stub = env.WS_DO.get(doId)- const response = await stub.fetch(new Request("http://internal/broadcast", {- method: "POST",- body: messageBody,- }))+ const response = await stub.fetch(createInternalUserBroadcastRequest(userId, messageBody))if (!response.ok) return { ok: false, failureKind: "non-ok", status: response.status }let payload: unknown@@ -87,7 +85,9 @@ export async function handleUserBroadcast({ request, env, url, traceId, log }: Rconst 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, duplex: "half" } as RequestInit))+ return stub.fetch(+ createInternalUserBroadcastRequest(userId, request.body, request.headers, true),+ )}export async function handleUsersBroadcast({ request, env, url, traceId, log }: RouterContext): Promise<Response | null> {diff --git a/src/ws-do/src/ws-durable.ts b/src/ws-do/src/ws-durable.tsindex 1c45cbdf2..9fa3a17b3 100644--- a/src/ws-do/src/ws-durable.ts+++ b/src/ws-do/src/ws-durable.ts@@ -90,7 +90,10 @@ export class WebSocketDurableObject extends DurableObject<Env> {return acceptCommunityMachineWebSocket(this.domainContext(), authHeader.slice(7).trim())}- return acceptUserWebSocket(this.domainContext())+ return acceptUserWebSocket(+ this.domainContext(),+ url.searchParams.get("userId") ?? undefined,+ )}async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {diff --git a/src/ws-do/src/ws-durable/internal.ts b/src/ws-do/src/ws-durable/internal.tsindex 55bf12ad3..8b4d87fdd 100644--- a/src/ws-do/src/ws-durable/internal.ts+++ b/src/ws-do/src/ws-durable/internal.ts@@ -1,7 +1,14 @@import type { Logger } from "@alook/shared"export type ConnectionState =- | { type: "user"; userId: string; authenticated: boolean; name?: string; discriminator?: string }+ | {+ type: "user"+ userId: string+ targetUserId?: string+ authenticated: boolean+ name?: string+ discriminator?: string+ }| { type: "daemon"; daemonId: string; userId: string; authenticated: boolean }| {type: "community-machine"diff --git a/src/ws-do/src/ws-durable/presence-typing.test.ts b/src/ws-do/src/ws-durable/presence-typing.test.tsindex a23a74fe3..6a0869129 100644--- a/src/ws-do/src/ws-durable/presence-typing.test.ts+++ b/src/ws-do/src/ws-durable/presence-typing.test.ts@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { readFileSync } from "node:fs"import { createMockWebSocket } from "../__mocks__/cf"+import { INTERNAL_USER_TARGET_HEADER } from "../internal-user-broadcast"import {CFResponse,cleanupHarness,@@ -40,6 +41,7 @@ import {mockListThreadParticipantUserIds,mockMarkMachineOffline,mockMarkMachineOnlineIfOffline,+ mockLogWarn,mockReconcileBotActivityFromRunningAgents,mockResolveScopeMemberUserIds,mockResolveChannelRecipientUserIds,@@ -71,6 +73,7 @@ describe("WebSocketDurableObject", () => {const req = new Request("http://internal/broadcast", {method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "u1" },body: JSON.stringify({ type: "runtime.status", daemonId: "d1", workspaceId: "w1", status: "online" }),})@@ -90,6 +93,7 @@ describe("WebSocketDurableObject", () => {const req = new Request("http://internal/broadcast", {method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "u1" },body: '{"type":"test"}',})@@ -111,6 +115,7 @@ describe("WebSocketDurableObject", () => {const req = new Request("http://internal/broadcast", {method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "u1" },body: '{"type":"test"}',})@@ -120,6 +125,81 @@ describe("WebSocketDurableObject", () => {expect(wsClosed.send).toHaveBeenCalled()expect(await res.json()).toEqual({ sent: 1 })})++ it("sweeps an authenticated historical mismatch before sending", async () => {+ const { durable, ctx } = createDO()+ const attacker = createMockWebSocket()+ attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker])++ const res = await durable.fetch(new Request("http://internal/broadcast", {+ method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "victim" },+ body: '{"type":"private.event"}',+ }))++ expect(await res.json()).toEqual({ sent: 0 })+ expect(attacker.send).not.toHaveBeenCalled()+ expect(attacker.deserializeAttachment()).toEqual({+ type: "user",+ userId: "attacker",+ authenticated: false,+ })+ expect(attacker.close).toHaveBeenCalledWith(1008, "Unauthorized")+ expect(mockLogWarn).toHaveBeenCalledWith("historical user websocket target mismatch", {+ source: "broadcast",+ targetUserId: "victim",+ authenticatedUserId: "attacker",+ })++ await durable.webSocketClose(attacker as any)+ await flushAsyncWork()++ expect(mockGetCoMemberUserIds).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ })++ it("sends only to the matching user while sweeping mixed historical sockets", async () => {+ const { durable, ctx } = createDO()+ const victim = createMockWebSocket()+ victim.serializeAttachment({ type: "user", userId: "victim", authenticated: true })+ const attacker = createMockWebSocket()+ attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker, victim])++ const res = await durable.fetch(new Request("http://internal/broadcast", {+ method: "POST",+ headers: { [INTERNAL_USER_TARGET_HEADER]: "victim" },+ body: '{"type":"private.event"}',+ }))++ expect(await res.json()).toEqual({ sent: 1 })+ expect(victim.send).toHaveBeenCalledWith('{"type":"private.event"}')+ expect(victim.close).not.toHaveBeenCalled()+ expect(attacker.send).not.toHaveBeenCalled()+ expect(attacker.close).toHaveBeenCalledWith(1008, "Unauthorized")+ })++ it("keeps markerless daemon broadcasts working", async () => {+ const { durable, ctx } = createDO()+ const daemon = createMockWebSocket()+ daemon.serializeAttachment({+ type: "daemon",+ daemonId: "daemon-1",+ userId: "owner-1",+ authenticated: true,+ })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([daemon])++ const res = await durable.fetch(new Request("http://internal/broadcast", {+ method: "POST",+ body: '{"type":"command"}',+ }))++ expect(await res.json()).toEqual({ sent: 1 })+ expect(daemon.send).toHaveBeenCalledWith('{"type":"command"}')+ expect(daemon.close).not.toHaveBeenCalled()+ })})@@ -193,7 +273,7 @@ describe("WebSocketDurableObject", () => {expect(mockIsBotOnline).not.toHaveBeenCalled()})- it("falls back to the live-socket check when userId is missing entirely", async () => {+ it("fails closed and sweeps user sockets when userId is missing entirely", async () => {const { durable, ctx } = createDO()const wsAuth = createMockWebSocket()wsAuth.serializeAttachment({ type: "user", userId: "u1", authenticated: true })@@ -201,10 +281,42 @@ describe("WebSocketDurableObject", () => {const res = await durable.fetch(new Request("http://internal/check-user-online"))- expect(await res.json()).toEqual({ online: true })+ expect(await res.json()).toEqual({ online: false })+ expect(wsAuth.deserializeAttachment()).toEqual({+ type: "user",+ userId: "u1",+ authenticated: false,+ })+ expect(wsAuth.close).toHaveBeenCalledWith(1008, "Unauthorized")expect(mockGetUserInternal).not.toHaveBeenCalled()})+ it("sweeps a historical mismatch and never reports the victim online", async () => {+ const { durable, ctx } = createDO()+ mockGetUserInternal.mockResolvedValue({ isBot: false } as any)+ const attacker = createMockWebSocket()+ attacker.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([attacker])++ const res = await durable.fetch(+ new Request("http://internal/check-user-online?userId=victim"),+ )++ expect(await res.json()).toEqual({ online: false })+ expect(attacker.deserializeAttachment()).toEqual({+ type: "user",+ userId: "attacker",+ authenticated: false,+ })+ expect(attacker.close).toHaveBeenCalledWith(1008, "Unauthorized")++ await durable.webSocketClose(attacker as any)+ await flushAsyncWork()++ expect(mockGetCoMemberUserIds).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ })+it("degrades to { online: false, stale: true } when D1 throws on the bot-online lookup", async () => {// Fail-closed via `readOrStale`: getUserInternal (or isBotOnline)// throwing on retry-exhaust must NOT surface as a 500 — the caller@@ -318,7 +430,12 @@ describe("WebSocketDurableObject", () => {}),}))const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })+ ws.serializeAttachment({+ type: "user",+ userId: "",+ targetUserId: "user-1",+ authenticated: false,+ })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))await flushAsyncWork()diff --git a/src/ws-do/src/ws-durable/presence-typing.ts b/src/ws-do/src/ws-durable/presence-typing.tsindex 4a6bb1d85..96e7be5a9 100644--- a/src/ws-do/src/ws-durable/presence-typing.ts+++ b/src/ws-do/src/ws-durable/presence-typing.ts@@ -5,6 +5,7 @@ import {WS_EVENTS,} from "@alook/shared"import type { UserConnectionState, WsDurableContext } from "./internal"+import { createInternalUserBroadcastRequest } from "../internal-user-broadcast"export function handleClientTypingStart(context: WsDurableContext,@@ -66,10 +67,9 @@ export async function notifyUserDO(const userDoId = context.env.WS_DO.idFromName("user:" + userId)const userStub = context.env.WS_DO.get(userDoId)try {- await userStub.fetch(new Request("http://internal/broadcast", {- method: "POST",- body: JSON.stringify(payload),- }))+ await userStub.fetch(+ createInternalUserBroadcastRequest(userId, JSON.stringify(payload)),+ )} catch (err) {context.log.error("notifyUserDO: owner notify failed", { err: String(err), userId })}@@ -131,10 +131,9 @@ export async function fanOutTyping(batch.map((userId) => {const doId = context.env.WS_DO.idFromName("user:" + userId)const stub = context.env.WS_DO.get(doId)- return stub.fetch(new Request("http://internal/broadcast", {- method: "POST",- body: event,- })).catch(() => { })+ return stub.fetch(+ createInternalUserBroadcastRequest(userId, event),+ ).catch(() => { })}))}@@ -171,10 +170,9 @@ export async function fanOutTypingStop(batch.map((userId) => {const doId = context.env.WS_DO.idFromName("user:" + userId)const stub = context.env.WS_DO.get(doId)- return stub.fetch(new Request("http://internal/broadcast", {- method: "POST",- body,- })).catch(() => { })+ return stub.fetch(+ createInternalUserBroadcastRequest(userId, body),+ ).catch(() => { })}))}@@ -202,10 +200,7 @@ export async function broadcastToAudience(batch.map((memberId) => {const doId = context.env.WS_DO.idFromName("user:" + memberId)const stub = context.env.WS_DO.get(doId)- return stub.fetch(new Request("http://internal/broadcast", {- method: "POST",- body,- }))+ return stub.fetch(createInternalUserBroadcastRequest(memberId, body))}))}diff --git a/src/ws-do/src/ws-durable/user-auth.test.ts b/src/ws-do/src/ws-durable/user-auth.test.tsindex a312115a5..583c39c6f 100644--- a/src/ws-do/src/ws-durable/user-auth.test.ts+++ b/src/ws-do/src/ws-durable/user-auth.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { createMockWebSocket } from "../__mocks__/cf"+import { handleUpgrade } from "../routes/upgrade"import {CFResponse,cleanupHarness,@@ -39,6 +40,7 @@ import {mockListThreadParticipantUserIds,mockMarkMachineOffline,mockMarkMachineOnlineIfOffline,+ mockLogWarn,mockReconcileBotActivityFromRunningAgents,mockResolveScopeMemberUserIds,mockStubFetch,@@ -87,7 +89,12 @@ describe("WebSocketDurableObject", () => {const acceptCall = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0]const serverWs = acceptCall[0]- expect(serverWs.deserializeAttachment()).toEqual({ type: "user", userId: "", authenticated: false })+ expect(serverWs.deserializeAttachment()).toEqual({+ type: "user",+ userId: "",+ targetUserId: "u1",+ authenticated: false,+ })})})@@ -98,13 +105,25 @@ describe("WebSocketDurableObject", () => {mockGetValidSessionWithIdentity.mockResolvedValue({ userId: "user-42", name: "Ana", discriminator: "0012" })const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })+ ws.serializeAttachment({+ type: "user",+ userId: "",+ targetUserId: "user-42",+ authenticated: false,+ })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))expect(mockGetValidSessionWithIdentity).toHaveBeenCalledWith({}, "valid-token")expect(ws.send).toHaveBeenCalledWith(JSON.stringify({ type: "auth.ok" }))- expect(ws.deserializeAttachment()).toEqual({ type: "user", userId: "user-42", authenticated: true, name: "Ana", discriminator: "0012" })+ expect(ws.deserializeAttachment()).toEqual({+ type: "user",+ userId: "user-42",+ targetUserId: "user-42",+ authenticated: true,+ name: "Ana",+ discriminator: "0012",+ })})it("first authenticated user connection broadcasts online presence and starts a snapshot", async () => {@@ -119,7 +138,12 @@ describe("WebSocketDurableObject", () => {),)const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })+ ws.serializeAttachment({+ type: "user",+ userId: "",+ targetUserId: "user-42",+ authenticated: false,+ })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))await flushAsyncWork()@@ -138,7 +162,12 @@ describe("WebSocketDurableObject", () => {existing.serializeAttachment({ type: "user", userId: "user-42", authenticated: true });(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([existing])const ws = createMockWebSocket()- ws.serializeAttachment({ type: "user", userId: "", authenticated: false })+ ws.serializeAttachment({+ type: "user",+ userId: "",+ targetUserId: "user-42",+ authenticated: false,+ })await durable.webSocketMessage(ws as any, JSON.stringify({ type: "auth", token: "valid-token" }))await flushAsyncWork()@@ -148,6 +177,122 @@ describe("WebSocketDurableObject", () => {expect(requests.some((request) => request.method === "GET" && request.url.includes("/check-user-online"))).toBe(true)})+ it("closes an attacker token before auth.ok across router and victim-target DO", async () => {+ const { durable, ctx, env } = createDO()+ mockGetValidSessionWithIdentity.mockResolvedValue({+ userId: "attacker",+ name: "Attacker",+ discriminator: "0066",+ })+ ;(env.WS_DO.get as ReturnType<typeof vi.fn>).mockReturnValue({+ fetch: (request: Request) => durable.fetch(request),+ })+ const request = new Request("http://localhost/?userId=victim", {+ headers: { Upgrade: "websocket" },+ })+ const requestLog = { info: vi.fn() }++ await handleUpgrade({+ request,+ env,+ url: new URL(request.url),+ traceId: "trace-pr0",+ log: { child: vi.fn(() => requestLog) } as any,+ })+ const accepted = (ctx.acceptWebSocket as ReturnType<typeof vi.fn>).mock.calls[0][0]++ await durable.webSocketMessage(+ accepted,+ JSON.stringify({ type: "auth", token: "attacker-session-token" }),+ )+ await flushAsyncWork()++ expect(accepted.close).toHaveBeenCalledWith(1008, "Unauthorized")+ expect(accepted.send).not.toHaveBeenCalled()+ expect(mockGetCoMemberUserIds).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ expect(env.WS_DO.idFromName).toHaveBeenCalledWith("user:victim")+ expect(mockLogWarn).toHaveBeenCalledWith("user websocket target mismatch", {+ source: "auth",+ targetUserId: "victim",+ authenticatedUserId: "attacker",+ })+ expect(JSON.stringify(mockLogWarn.mock.calls)).not.toContain("attacker-session-token")+ })++ it("invalidates a historical authenticated mismatch before re-auth close", async () => {+ const { durable, ctx } = createDO()+ mockGetValidSessionWithIdentity.mockResolvedValue({+ userId: "attacker",+ name: "Attacker",+ discriminator: "0066",+ })+ const ws = createMockWebSocket()+ ws.serializeAttachment({ type: "user", userId: "attacker", authenticated: true })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])++ await durable.webSocketMessage(+ ws as any,+ JSON.stringify({ type: "auth", token: "attacker-session-token" }),+ )++ expect(ws.deserializeAttachment()).toEqual({+ type: "user",+ userId: "attacker",+ authenticated: false,+ })+ expect(ws.close).toHaveBeenCalledWith(1008, "Unauthorized")++ await durable.webSocketClose(ws as any)+ await flushAsyncWork()++ expect(mockGetCoMemberUserIds).not.toHaveBeenCalled()+ expect(mockStubFetch).not.toHaveBeenCalled()+ })++ it("keeps a correctly bound socket authenticated until mismatch close handling", async () => {+ const { durable, ctx } = createDO()+ mockGetValidSessionWithIdentity.mockResolvedValue({+ userId: "attacker",+ name: "Attacker",+ discriminator: "0066",+ })+ mockGetCoMemberUserIds.mockResolvedValue(["friend-1"])+ mockStubFetch.mockResolvedValue(+ new (globalThis.Response as any)(JSON.stringify({ sent: 1 })),+ )+ const ws = createMockWebSocket()+ ws.serializeAttachment({+ type: "user",+ userId: "victim",+ targetUserId: "victim",+ authenticated: true,+ })+ ;(ctx.getWebSockets as ReturnType<typeof vi.fn>).mockReturnValue([ws])++ await durable.webSocketMessage(+ ws as any,+ JSON.stringify({ type: "auth", token: "attacker-session-token" }),+ )++ expect(ws.deserializeAttachment()).toEqual({+ type: "user",+ userId: "victim",+ targetUserId: "victim",+ authenticated: true,+ })++ await durable.webSocketClose(ws as any)+ await flushAsyncWork()++ const [request] = mockStubFetch.mock.calls[0] as [Request]+ expect(await request.clone().json()).toEqual({+ type: "community:presence.update",+ userId: "victim",+ online: false,+ })+ })+it("closes with 1008 on invalid token", async () => {const { durable } = createDO()mockGetValidSessionWithIdentity.mockResolvedValue(null)diff --git a/src/ws-do/src/ws-durable/user-auth.ts b/src/ws-do/src/ws-durable/user-auth.tsindex dac8329ca..7f6f43057 100644--- a/src/ws-do/src/ws-durable/user-auth.ts+++ b/src/ws-do/src/ws-durable/user-auth.ts@@ -10,6 +10,7 @@ import {notifyUserDO,sendPresenceSnapshot,} from "./presence-typing"+import { getInternalUserTarget } from "../internal-user-broadcast"export async function handleUserFetch(context: WsDurableContext,@@ -18,7 +19,7 @@ export async function handleUserFetch(): Promise<Response | null> {if (url.pathname === "/broadcast" && request.method === "POST") {const body = await request.text()- const sent = broadcast(context, body)+ const sent = broadcast(context, body, getInternalUserTarget(request))return new Response(JSON.stringify({ sent }), {headers: { "Content-Type": "application/json" },})@@ -36,10 +37,16 @@ export async function handleUserFetch(if (url.pathname === "/check-user-online") {const targetUserId = url.searchParams.get("userId")- const hasAuthUser = context.ctx.getWebSockets().some(ws => {- const s = ws.deserializeAttachment() as ConnectionState- return s?.type === "user" && s.authenticated- })+ let hasAuthUser = false+ for (const ws of context.ctx.getWebSockets()) {+ const state = ws.deserializeAttachment() as ConnectionState+ if (state?.type !== "user" || !state.authenticated) continue+ if (targetUserId && state.userId === targetUserId) {+ hasAuthUser = true+ } else {+ invalidateMismatchedUserSocket(context, ws, state, targetUserId, "online-check")+ }+ }if (hasAuthUser) {return new Response(JSON.stringify({ online: true }), {headers: { "Content-Type": "application/json" },@@ -78,13 +85,21 @@ export async function handleUserFetch(return null}-export function acceptUserWebSocket(context: WsDurableContext): Response {+export function acceptUserWebSocket(+ context: WsDurableContext,+ targetUserId?: string,+): Response {const pair = new WebSocketPair()const [client, server] = Object.values(pair)context.ctx.acceptWebSocket(server)- server.serializeAttachment({ type: "user", userId: "", authenticated: false } as ConnectionState)+ server.serializeAttachment({+ type: "user",+ userId: "",+ targetUserId,+ authenticated: false,+ } as ConnectionState)context.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong")@@ -146,8 +161,32 @@ export async function handleWebSocketMessage(return}const { userId, name, discriminator } = identity+ const targetUserId = state?.type === "user" ? state.targetUserId : undefined+ if (!targetUserId || userId !== targetUserId) {+ if (+ state?.type === "user"+ && state.authenticated+ && (!state.targetUserId || state.userId !== state.targetUserId)+ ) {+ ws.serializeAttachment({ ...state, authenticated: false } as ConnectionState)+ }+ context.log.warn("user websocket target mismatch", {+ source: "auth",+ targetUserId: targetUserId ?? null,+ authenticatedUserId: userId,+ })+ ws.close(1008, "Unauthorized")+ return+ }const wasOnline = countAuthenticatedUserConnections(context, userId) > 0- ws.serializeAttachment({ type: "user", userId, authenticated: true, name, discriminator } as ConnectionState)+ ws.serializeAttachment({+ type: "user",+ userId,+ targetUserId,+ authenticated: true,+ name,+ discriminator,+ } as ConnectionState)context.log.info("websocket authenticated", { userId })ws.send(JSON.stringify({ type: "auth.ok" }))if (!wasOnline) {@@ -213,20 +252,49 @@ export async function handleWebSocketError(try { ws.close(1011, "Internal error") } catch { }}-function broadcast(context: WsDurableContext, message: string): number {+function broadcast(+ context: WsDurableContext,+ message: string,+ targetUserId: string | null,+): number {let sent = 0for (const ws of context.ctx.getWebSockets()) {const state = ws.deserializeAttachment() as ConnectionState- if (state.authenticated) {- try {- ws.send(message)- sent++- } catch { }+ if (!state?.authenticated) continue+ if (state.type === "user") {+ if (!targetUserId || state.userId !== targetUserId) {+ invalidateMismatchedUserSocket(context, ws, state, targetUserId, "broadcast")+ continue+ }+ } else if (targetUserId) {+ continue}+ try {+ ws.send(message)+ sent+++ } catch { }}return sent}+function invalidateMismatchedUserSocket(+ context: WsDurableContext,+ ws: WebSocket,+ state: Extract<ConnectionState, { type: "user" }>,+ targetUserId: string | null,+ source: "broadcast" | "online-check",+): void {+ ws.serializeAttachment({ ...state, authenticated: false } as ConnectionState)+ context.log.warn("historical user websocket target mismatch", {+ source,+ targetUserId,+ authenticatedUserId: state.userId,+ })+ try {+ ws.close(1008, "Unauthorized")+ } catch { }+}+function countAuthenticatedUserConnections(context: WsDurableContext, userId: string): number {let count = 0for (const ws of context.ctx.getWebSockets()) {