fix(restore): reset non-finite scroll and zoom values

The viewport comes from untrusted input, and a non-finite `scrollX`,
`scrollY` or zoom leaves the canvas unrenderable with no way for the
user to recover. Fall back to the defaults for those, accepting numeric
strings.

The zoom was already normalized by `getNormalizedZoom`, but it clamps
with `Math.min`/`Math.max`, which pass `NaN` straight through, so the
value is now checked before it gets there.

Signed-off-by: Mark Tolmacs <mark@lazycat.hu>
This commit is contained in:
Mark Tolmacs committed 2026-10-21 08:20:42 +00:00
1 parent b9ddae13ed
commit 28adc14480
2 files changed
+47 -3

No files matched your search

+9 -3
View File
@@ -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:
@@ -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", () => {