From 427f75c716d1d148eee8f4ee398917e5e750781f Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 21:52:20 -0600 Subject: [PATCH] fix(id/web): validate UPDATE and CURSOR frame fields in collab handleMessage (#7873) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The collab socket is a trust boundary, but handleMessage shape-trusted the UPDATE and CURSOR families: a malformed UPDATE threw inside the step-apply try and was misclassified as desync (close 4001 + reconnect churn), and a malformed CURSOR was stored verbatim in plugin state, feeding NaN positions into decoration/coords code. - UPDATE: drop the frame (log + return, session intact) when steps is not an array, clientIDs is not an array, their lengths differ, or a step fails Step.fromJSON parsing. Step parsing now happens in its own try before the apply try, so only genuine apply failures of well-shaped steps take the existing reconnect path. - CURSOR: drop when clientID is not a string/number, head/anchor are not finite numbers, or name is present and not a string/null. idleSecs is advisory: ignored unless a finite number. - CURSOR_REMOVE: drop when clientID is not a string/number. Seven regression tests in collab.test.ts cover each malformed frame (dropped with editor/session intact — no close, no new socket, no cursor stored) and that a following valid frame still applies. The prose in #7873's probe (malformed UPDATE teardown, phantom cursor) is now pinned as fixtures. collab.test.ts: 31/31 pass. Full web suite: 718 passed, 1 failed — search-panel role=search accessibility, failing identically on pristine main (pre-existing, unrelated). Typecheck clean. --- pkgs/id/web/src/collab.test.ts | 130 +++++++++++++++++++++++++++++++++ pkgs/id/web/src/collab.ts | 69 +++++++++++++---- 2 files changed, 185 insertions(+), 14 deletions(-) diff --git a/pkgs/id/web/src/collab.test.ts b/pkgs/id/web/src/collab.test.ts index 8e3d14202d..6aaff377b9 100644 --- a/pkgs/id/web/src/collab.test.ts +++ b/pkgs/id/web/src/collab.test.ts @@ -1,4 +1,7 @@ import { Packr, Unpackr } from "msgpackr"; +import { Fragment, Slice } from "prosemirror-model"; +import { ReplaceStep } from "prosemirror-transform"; +import type { EditorView } from "prosemirror-view"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { MAX_STEPS_MESSAGE_BYTES, @@ -8,6 +11,7 @@ import { stepBatch, stepWireSize, } from "./collab"; +import { cursorPluginKey } from "./cursors"; import { getSendableSteps, getVersion } from "./editor"; // Same MessagePack configuration as collab.ts @@ -17,6 +21,9 @@ const unpackr = new Unpackr({ useRecords: false, structuredClone: true }); const MSG_AUTH = 8; const MSG_AUTH_OK = 9; const MSG_INIT = 0; +const MSG_UPDATE = 2; +const MSG_CURSOR = 4; +const MSG_CURSOR_REMOVE = 6; /** Minimal WebSocket stand-in: records sent frames, lets the test drive * open/message/close by hand. No real network is involved. */ @@ -455,3 +462,126 @@ describe("buildCollabWsUrl (#2830)", () => { vi.useRealTimers(); }); }); + +describe("UPDATE/CURSOR frame validation (#7873)", () => { + beforeEach(() => { + vi.useFakeTimers(); + FakeWebSocket.instances = []; + vi.stubGlobal("WebSocket", FakeWebSocket); + }); + + afterEach(() => { + while (liveConnections.length > 0) { + liveConnections.pop()?.disconnect(); + } + vi.unstubAllGlobals(); + vi.useRealTimers(); + document.body.innerHTML = ""; + }); + + function openInitialized() { + const onEditorReady = vi.fn(); + const { conn, socket } = openCollab(onEditorReady); + vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "warn").mockImplementation(() => {}); + socket.deliver(validInit()); + expect(conn.editor).not.toBeNull(); + return { conn, socket }; + } + + /** The session must be untouched: socket open, no reconnect scheduled. */ + function expectSessionIntact(socket: FakeWebSocket) { + expect(socket.readyState).toBe(FakeWebSocket.OPEN); + vi.advanceTimersByTime(10_000); + expect(FakeWebSocket.instances).toHaveLength(1); + } + + function insertStepJson(view: EditorView, text: string): unknown { + const { schema } = view.state; + const step = new ReplaceStep(1, 1, new Slice(Fragment.from(schema.text(text)), 0, 0)); + return step.toJSON(); + } + + it("drops an UPDATE whose steps field is not an array, session intact", () => { + const { conn, socket } = openInitialized(); + socket.deliver([MSG_UPDATE, "not-an-array", [1]]); + expectSessionIntact(socket); + expect(getVersion(conn.editor!.view.state)).toBe(0); + + // A following valid frame still applies. + socket.deliver([MSG_UPDATE, [insertStepJson(conn.editor!.view, "hi")], [4242]]); + expect(conn.editor!.view.state.doc.textContent).toBe("hi"); + }); + + it("drops an UPDATE whose clientIDs field is not an array, session intact", () => { + const { conn, socket } = openInitialized(); + socket.deliver([MSG_UPDATE, [], "not-an-array"]); + socket.deliver([MSG_UPDATE, [insertStepJson(conn.editor!.view, "hi")], "not-an-array"]); + expectSessionIntact(socket); + expect(conn.editor!.view.state.doc.textContent).toBe(""); + }); + + it("drops an UPDATE whose steps/clientIDs lengths differ, session intact", () => { + const { conn, socket } = openInitialized(); + socket.deliver([MSG_UPDATE, [insertStepJson(conn.editor!.view, "hi")], []]); + socket.deliver([MSG_UPDATE, [], [4242]]); + expectSessionIntact(socket); + expect(conn.editor!.view.state.doc.textContent).toBe(""); + }); + + it("drops an UPDATE with an unparseable step instead of reconnecting, session intact", () => { + const { conn, socket } = openInitialized(); + // Pre-fix this threw inside the apply try and tore the session down + // with close(4001) + reconnect; a shape error is a bad frame. + socket.deliver([MSG_UPDATE, [123], [999]]); + socket.deliver([MSG_UPDATE, [{ stepType: "no-such-step" }], [999]]); + expectSessionIntact(socket); + expect(getVersion(conn.editor!.view.state)).toBe(0); + + socket.deliver([MSG_UPDATE, [insertStepJson(conn.editor!.view, "ok")], [4242]]); + expect(conn.editor!.view.state.doc.textContent).toBe("ok"); + }); + + it("drops a malformed CURSOR instead of storing a phantom cursor", () => { + const { conn, socket } = openInitialized(); + // The probe frame from #7873: object head, string anchor, object name. + socket.deliver([MSG_CURSOR, 4242, { x: 1 }, "abc", { evil: 1 }, "zzz"]); + socket.deliver([MSG_CURSOR, { bad: 1 }, 1, 1, "ada"]); + socket.deliver([MSG_CURSOR, 4242, Number.NaN, 1, "ada"]); + socket.deliver([MSG_CURSOR, 4242, 1, Number.POSITIVE_INFINITY, "ada"]); + socket.deliver([MSG_CURSOR, 4242, 1, 1, 42]); + + const state = cursorPluginKey.getState(conn.editor!.view.state); + expect(state?.cursors.has(4242)).toBe(false); + expect(state?.cursors.size).toBe(0); + expectSessionIntact(socket); + }); + + it("stores a well-formed CURSOR and tolerates a non-finite idleSecs", () => { + const { conn, socket } = openInitialized(); + socket.deliver([MSG_CURSOR, 4242, 1, 1, "ada", "zzz"]); + const state = cursorPluginKey.getState(conn.editor!.view.state); + const cursor = state?.cursors.get(4242); + expect(cursor?.head).toBe(1); + expect(cursor?.anchor).toBe(1); + expect(cursor?.name).toBe("ada"); + expectSessionIntact(socket); + }); + + it("drops a malformed CURSOR_REMOVE and still honors a valid one", () => { + const { conn, socket } = openInitialized(); + socket.deliver([MSG_CURSOR, 4242, 1, 1, "ada"]); + expect(cursorPluginKey.getState(conn.editor!.view.state)?.cursors.has(4242)).toBe(true); + + socket.deliver([MSG_CURSOR_REMOVE, { bad: 1 }]); + socket.deliver([MSG_CURSOR_REMOVE, null]); + const afterBad = cursorPluginKey.getState(conn.editor!.view.state); + expect(afterBad?.cursors.get(4242)?.pendingRemovalAt).toBeUndefined(); + expectSessionIntact(socket); + + socket.deliver([MSG_CURSOR_REMOVE, 4242]); + const afterValid = cursorPluginKey.getState(conn.editor!.view.state); + expect(afterValid?.cursors.get(4242)?.pendingRemovalAt).toBeTypeOf("number"); + }); +}); diff --git a/pkgs/id/web/src/collab.ts b/pkgs/id/web/src/collab.ts index 785eedab31..9b3b69539d 100644 --- a/pkgs/id/web/src/collab.ts +++ b/pkgs/id/web/src/collab.ts @@ -372,20 +372,38 @@ export function initCollab( break; } - const steps = msg[1] as unknown[]; - const clientIDs = msg[2] as number[]; + const steps = msg[1]; + const clientIDs = msg[2]; + + // Frame-boundary validation (#7873): a malformed UPDATE is a + // bad frame, not a desync — drop it and keep the session. Only + // a failure to *apply* well-shaped steps means the editor state + // has diverged and needs the reconnect path below. + if (!Array.isArray(steps) || !Array.isArray(clientIDs) || steps.length !== clientIDs.length) { + console.error("[collab] Dropping malformed UPDATE frame: steps/clientIDs are not matching arrays"); + break; + } - if (steps && clientIDs && steps.length > 0) { + if (steps.length > 0) { console.log("[collab] Received update with", steps.length, "steps, clientIDs:", clientIDs); + // Use the schema from the editor instance (mode-aware) + const editorSchema = editorInstance.view.state.schema; + let parsedSteps; + try { + parsedSteps = steps.map((s) => Step.fromJSON(editorSchema, s)); + } catch (err) { + // A step that fails to parse is a shape error in the + // frame, not an apply failure: drop the frame. + console.error("[collab] Dropping malformed UPDATE frame: step failed to parse:", err); + break; + } + try { // Pass ALL steps to receiveTransaction - it will: // 1. Recognize and confirm our own steps (matching our clientID) // 2. Apply remote steps from other clients // 3. Rebase any unconfirmed local steps over remote steps - // Use the schema from the editor instance (mode-aware) - const editorSchema = editorInstance.view.state.schema; - const parsedSteps = steps.map((s) => Step.fromJSON(editorSchema, s)); const tr = receiveTransaction(editorInstance.view.state, parsedSteps, clientIDs); editorInstance.view.dispatch(tr); console.log("[collab] Applied transaction, new version:", getVersion(editorInstance.view.state)); @@ -414,11 +432,28 @@ export function initCollab( // [4, clientID, head, anchor, name?, idleSecs?] if (!editorInstance) break; - const clientID = msg[1] as number; - const head = msg[2] as number; - const anchor = msg[3] as number; - const name = msg[4] as string | null; - const idleSecs = msg[5] as number | null | undefined; + const clientID = msg[1]; + const head = msg[2]; + const anchor = msg[3]; + const name = msg[4]; + const idleSecs = msg[5]; + + // Frame-boundary validation (#7873): drop malformed cursors + // instead of storing unvalidated values in plugin state, where + // they feed NaN positions into decoration/coords code. + if ( + (typeof clientID !== "string" && typeof clientID !== "number") || + typeof head !== "number" || + !Number.isFinite(head) || + typeof anchor !== "number" || + !Number.isFinite(anchor) || + (name !== undefined && name !== null && typeof name !== "string") + ) { + console.error("[collab] Dropping malformed CURSOR frame"); + break; + } + // idleSecs is advisory only: ignore it unless it is a finite number. + const idle = typeof idleSecs === "number" && Number.isFinite(idleSecs) ? idleSecs : undefined; // Mark cursor as fresh for reconnect cleanup (including own cursor) markCursorFresh(editorInstance.view, clientID); @@ -431,10 +466,10 @@ export function initCollab( clientID, "at", head, - idleSecs ? `(idle ${idleSecs}s)` : "", + idle ? `(idle ${idle}s)` : "", clientID === myClientID ? "(own)" : "", ); - updateCursor(editorInstance.view, clientID, head, anchor, name ?? undefined, idleSecs ?? undefined); + updateCursor(editorInstance.view, clientID, head, anchor, name ?? undefined, idle); break; } @@ -470,7 +505,13 @@ export function initCollab( // [6, clientID] if (!editorInstance) break; - const clientID = msg[1] as number; + const clientID = msg[1]; + + // Frame-boundary validation (#7873), as for CURSOR. + if (typeof clientID !== "string" && typeof clientID !== "number") { + console.error("[collab] Dropping malformed CURSOR_REMOVE frame"); + break; + } // Don't remove our own cursor on disconnect notification if (clientID === myClientID) break;