Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
117 changes: 117 additions & 0 deletions pkgs/id/web/src/collab.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
stepBatch,
stepWireSize,
} from "./collab";
import { cursorPluginKey } from "./cursors";
import { getSendableSteps, getVersion } from "./editor";

// Same MessagePack configuration as collab.ts
Expand Down Expand Up @@ -525,6 +526,122 @@ describe("step chunking over a live connection (#4324)", () => {
});
});

describe("UPDATE/CURSOR frame validation (#7873)", () => {
const MSG_UPDATE = 2;
const MSG_CURSOR = 4;
const MSG_CURSOR_REMOVE = 6;

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 openAndInit() {
const { conn, socket } = openCollab();
socket.deliver(validInit());
return { conn, socket, view: conn.editor!.view };
}

// The session-intact oracle for a dropped frame: socket never
// closed (no 4001 teardown), no reconnect socket appears even
// after timers run, and the collab version does not move.
function expectSessionIntact(
socket: FakeWebSocket,
view: ReturnType<typeof openAndInit>["view"],
version: number,
) {
expect(socket.readyState).toBe(FakeWebSocket.OPEN);
vi.advanceTimersByTime(120_000);
expect(FakeWebSocket.instances).toHaveLength(1);
expect(getVersion(view.state)).toBe(version);
}

function remoteStepJson(view: ReturnType<typeof openAndInit>["view"]) {
return view.state.tr.insertText("x", 1).steps[0].toJSON();
}

it("drops an UPDATE whose steps is not an array, with the session intact", () => {
const { socket, view } = openAndInit();
const v0 = getVersion(view.state);
socket.deliver([MSG_UPDATE, "not-an-array", [1]]);
expectSessionIntact(socket, view, v0);
// A following valid UPDATE still applies.
socket.deliver([MSG_UPDATE, [remoteStepJson(view)], [9999]]);
expect(getVersion(view.state)).toBe(v0 + 1);
expect(view.state.doc.textContent).toContain("x");
});

it("drops an UPDATE whose clientIDs is not an array or whose lengths differ", () => {
const { socket, view } = openAndInit();
const v0 = getVersion(view.state);
const step = remoteStepJson(view);
socket.deliver([MSG_UPDATE, [step], "not-an-array"]);
expectSessionIntact(socket, view, v0);
socket.deliver([MSG_UPDATE, [step, step], [9999]]);
expectSessionIntact(socket, view, v0);
socket.deliver([MSG_UPDATE, [], "not-an-array"]);
expectSessionIntact(socket, view, v0);
});

it("drops an UPDATE with an unparseable step instead of reconnecting", () => {
const { socket, view } = openAndInit();
const v0 = getVersion(view.state);
socket.deliver([MSG_UPDATE, [123], [999]]);
expectSessionIntact(socket, view, v0);
socket.deliver([MSG_UPDATE, [{ stepType: "bogus" }], [999]]);
expectSessionIntact(socket, view, v0);
// A following valid UPDATE still applies.
socket.deliver([MSG_UPDATE, [remoteStepJson(view)], [9999]]);
expect(getVersion(view.state)).toBe(v0 + 1);
});

it("stores a valid CURSOR and drops malformed CURSOR frames as phantoms", () => {
const { socket, view } = openAndInit();
const cursors = () => cursorPluginKey.getState(view.state)?.cursors;
socket.deliver([MSG_CURSOR, 4242, 1, 1, "bob", 5]);
expect(cursors()?.get(4242)?.head).toBe(1);
// The probe frame from #7873: object head, string anchor,
// object name, string idleSecs - dropped whole, nothing stored.
socket.deliver([MSG_CURSOR, 5151, { x: 1 }, "abc", { evil: 1 }, "zzz"]);
expect(cursors()?.has(5151)).toBe(false);
// Bad clientID and non-string name are dropped too.
socket.deliver([MSG_CURSOR, { bad: 1 }, 1, 1, "eve"]);
expect(cursors()?.size).toBe(1);
socket.deliver([MSG_CURSOR, 6161, 1, 1, 42]);
expect(cursors()?.has(6161)).toBe(false);
// A string clientID with a null name is a valid cursor.
socket.deliver([MSG_CURSOR, "peer-7", 1, 1, null]);
expect(cursors()?.has("peer-7")).toBe(true);
expect(cursors()?.size).toBe(2);
});

it("CURSOR_REMOVE validates the clientID before removing", () => {
const { socket, view } = openAndInit();
const cursors = () => cursorPluginKey.getState(view.state)?.cursors;
socket.deliver([MSG_CURSOR, 4242, 1, 1, "bob"]);
expect(cursors()?.has(4242)).toBe(true);
socket.deliver([MSG_CURSOR_REMOVE, { bad: 1 }]);
// Not even marked pending removal: still present after timers run.
vi.advanceTimersByTime(60_000);
expect(cursors()?.has(4242)).toBe(true);
socket.deliver([MSG_CURSOR_REMOVE, 4242]);
// removeCursor defers: the cursor is fully removed only after
// the pending-removal grace period (PENDING_REMOVAL_MS).
vi.advanceTimersByTime(60_000);
expect(cursors()?.has(4242)).toBe(false);
});
});

describe("large text insertion collaboration (#4119)", () => {
beforeEach(() => {
vi.useFakeTimers();
Expand Down
73 changes: 61 additions & 12 deletions pkgs/id/web/src/collab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,20 +396,39 @@ export function initCollab(
break;
}

const steps = msg[1] as unknown[];
const clientIDs = msg[2] as number[];
const steps = msg[1];
const clientIDs = msg[2];

// #7873: the frame is shape-checked at the boundary, like Init
// (#2824). A malformed Update is dropped with the session
// intact - it must not reach the step-apply path, whose catch
// treats any throw as desync and tears the session down.
if (!Array.isArray(steps) || !Array.isArray(clientIDs) || steps.length !== clientIDs.length) {
console.error("[collab] Dropping malformed Update message: steps/clientIDs shape mismatch");
break;
}

if (steps && clientIDs && steps.length > 0) {
if (steps.length > 0) {
console.log("[collab] Received update with", steps.length, "steps, clientIDs:", clientIDs);

// Parse every step before applying any: a step that fails
// Step.fromJSON is a shape error in the frame, so the whole
// frame is dropped. Only a failure applying well-shaped
// steps (below) is a genuine desync.
const editorSchema = editorInstance.view.state.schema;
let parsedSteps: Step[];
try {
parsedSteps = steps.map((s) => Step.fromJSON(editorSchema, s));
} catch (err) {
console.error("[collab] Dropping malformed Update message: unparseable step:", 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));
Expand Down Expand Up @@ -438,11 +457,33 @@ 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 rawName = msg[4];
const rawIdleSecs = msg[5];

// #7873: validate at the boundary, like Init (#2824). An
// unchecked Cursor frame was stored verbatim as a phantom
// cursor whose non-numeric positions fed NaN into the
// decoration/coords code. clientID is string | number in
// the cursor state; head/anchor must be finite numbers;
// name, when present, must be a string or null; idleSecs is
// only meaningful as a finite number and is ignored otherwise.
if (
(typeof clientID !== "string" && typeof clientID !== "number") ||
typeof head !== "number" ||
!Number.isFinite(head) ||
typeof anchor !== "number" ||
!Number.isFinite(anchor) ||
(rawName !== undefined && rawName !== null && typeof rawName !== "string")
) {
console.error("[collab] Dropping malformed Cursor message: invalid cursor fields");
break;
}
const name = rawName as string | null | undefined;
const idleSecs =
typeof rawIdleSecs === "number" && Number.isFinite(rawIdleSecs) ? rawIdleSecs : undefined;

// Mark cursor as fresh for reconnect cleanup (including own cursor)
markCursorFresh(editorInstance.view, clientID);
Expand Down Expand Up @@ -494,7 +535,15 @@ export function initCollab(
// [6, clientID]
if (!editorInstance) break;

const clientID = msg[1] as number;
const clientID = msg[1];

// #7873: same boundary validation as Cursor - the clientID
// keys the cursor map, so a non-string/number value can only
// be a malformed frame.
if (typeof clientID !== "string" && typeof clientID !== "number") {
console.error("[collab] Dropping malformed CursorRemove message: invalid clientID");
break;
}

// Don't remove our own cursor on disconnect notification
if (clientID === myClientID) break;
Expand Down
Loading