diff --git a/packages/excalidraw/data/restore.ts b/packages/excalidraw/data/restore.ts index aef9d9194a..8283b0c09c 100644 --- a/packages/excalidraw/data/restore.ts +++ b/packages/excalidraw/data/restore.ts @@ -1924,12 +1924,18 @@ export const restoreAppState = ( lastActiveTool: null, locked: nextAppState.activeTool.locked ?? false, }, + // the viewport is untrusted input, and a non-finite value here leaves the + // canvas unrenderable with no way for the user to recover + scrollX: toFiniteNumber(nextAppState.scrollX) ?? defaultAppState.scrollX, + scrollY: toFiniteNumber(nextAppState.scrollY) ?? defaultAppState.scrollY, // Migrates from previous version where appState.zoom was a number zoom: { + // `getNormalizedZoom` clamps with Math.min/Math.max, which pass NaN + // straight through, so the value has to be checked before it gets there value: getNormalizedZoom( - isFiniteNumber(appState.zoom) - ? appState.zoom - : appState.zoom?.value ?? defaultAppState.zoom.value, + toFiniteNumber(appState.zoom) ?? + toFiniteNumber(appState.zoom?.value) ?? + defaultAppState.zoom.value, ), }, openSidebar: diff --git a/packages/excalidraw/tests/data/restore.test.ts b/packages/excalidraw/tests/data/restore.test.ts index aedf9c442b..7a971398cb 100644 --- a/packages/excalidraw/tests/data/restore.test.ts +++ b/packages/excalidraw/tests/data/restore.test.ts @@ -2312,6 +2312,44 @@ describe("restoreAppState", () => { expect(restoredAppState.zoom).toMatchObject(getDefaultAppState().zoom); }); + + it("when the zoom value of imported data state is not finite", () => { + for (const value of ["abc", NaN, Infinity, null, {}]) { + const restoredAppState = restore.restoreAppState( + { zoom: { value } } as any, + null, + ); + expect(restoredAppState.zoom).toEqual(getDefaultAppState().zoom); + } + }); + + it("when the zoom of imported data state is a numeric string", () => { + expect( + restore.restoreAppState({ zoom: { value: "2" } } as any, null).zoom + .value, + ).toBe(2); + expect( + restore.restoreAppState({ zoom: "2" } as any, null).zoom.value, + ).toBe(2); + }); + }); + + it("should reset non-finite scroll values to defaults", () => { + for (const value of ["abc", NaN, Infinity, -Infinity, null, {}]) { + const restoredAppState = restore.restoreAppState( + { scrollX: value, scrollY: value } as any, + null, + ); + expect(restoredAppState.scrollX).toBe(getDefaultAppState().scrollX); + expect(restoredAppState.scrollY).toBe(getDefaultAppState().scrollY); + } + + expect( + restore.restoreAppState({ scrollX: 10, scrollY: -20 } as any, null), + ).toMatchObject({ scrollX: 10, scrollY: -20 }); + expect( + restore.restoreAppState({ scrollX: "10", scrollY: "-20" } as any, null), + ).toMatchObject({ scrollX: 10, scrollY: -20 }); }); it("should handle appState.openSidebar legacy values", () => {