diff --git a/excalidraw-app/collab/Collab.tsx b/excalidraw-app/collab/Collab.tsx index a7694e9ba5..681c59f9d4 100644 --- a/excalidraw-app/collab/Collab.tsx +++ b/excalidraw-app/collab/Collab.tsx @@ -604,7 +604,8 @@ class Collab extends PureComponent { // valid INIT can still initialize the room if ( !decryptedData.payload || - typeof decryptedData.payload !== "object" + typeof decryptedData.payload !== "object" || + !Array.isArray(decryptedData.payload.elements) ) { return; } diff --git a/excalidraw-app/data/firebase.ts b/excalidraw-app/data/firebase.ts index 7381429945..4474c9c999 100644 --- a/excalidraw-app/data/firebase.ts +++ b/excalidraw-app/data/firebase.ts @@ -116,15 +116,14 @@ const decryptElements = async ( ); // the payload authenticated with the room key, but its contents may still - // be malformed. Treat it as an empty scene so the room can self-heal on - // the next save instead of failing forever. - try { - const elements = JSON.parse(decodedData); - return Array.isArray(elements) ? elements : []; - } catch (error: any) { - console.error("Failed to parse stored scene", error); - return []; + // be unreadable (corrupted, or a format we don't understand). Throw rather + // than treating it as an empty scene, as the next save would otherwise + // reconcile against nothing and irrecoverably replace the stored scene. + const elements = JSON.parse(decodedData); + if (!Array.isArray(elements)) { + throw new Error("Stored scene is not an array of elements"); } + return elements; }; class FirebaseSceneVersionCache { diff --git a/excalidraw-app/tests/collab.test.tsx b/excalidraw-app/tests/collab.test.tsx index e9a42fe547..b10ac27191 100644 --- a/excalidraw-app/tests/collab.test.tsx +++ b/excalidraw-app/tests/collab.test.tsx @@ -291,6 +291,10 @@ describe("collaboration", () => { await emitBroadcast(42); await emitBroadcast({ type: "SCENE_INIT" }); await emitBroadcast({ type: "SCENE_INIT", payload: null }); + await emitBroadcast({ type: "SCENE_INIT", payload: {} }); + await emitBroadcast({ type: "SCENE_INIT", payload: { elements: {} } }); + await emitBroadcast({ type: "SCENE_INIT", payload: { elements: "x" } }); + await emitBroadcast({ type: "SCENE_INIT", payload: { elements: null } }); await emitBroadcast({ type: "SCENE_UPDATE" }); expect(window.collab.portal.socketInitialized).toBe(false); @@ -306,6 +310,18 @@ describe("collaboration", () => { expect(scene?.elements).toEqual([expect.objectContaining({ id: "A" })]); }); + it("should initialize an empty room from SCENE_INIT", async () => { + const { scenePromise } = await joinRoom(); + + await emitBroadcast({ type: "SCENE_INIT", payload: { elements: [] } }); + + await expect(scenePromise).resolves.toEqual({ + elements: [], + scrollToContent: true, + }); + expect(window.collab.portal.socketInitialized).toBe(true); + }); + it("should fall back to firebase when processing SCENE_INIT throws", async () => { const { scenePromise } = await joinRoom();