Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(spreadsheet,canvas): address automated review feedback
Elian Doran53482d921287
diff --git a/apps/client/src/services/image_upload.spec.ts b/apps/client/src/services/image_upload.spec.tsindex 29050d4b55..4057a3ff07 100644--- a/apps/client/src/services/image_upload.spec.ts+++ b/apps/client/src/services/image_upload.spec.ts@@ -35,6 +35,11 @@ describe("dataUrlToImageFile", () => {it("returns null when the input is not a base64 data URL", () => {expect(dataUrlToImageFile("https://example.com/a.png")).toBeNull();});++ it("returns null for a malformed base64 payload instead of throwing", () => {+ // atob throws a DOMException on invalid base64; the decode must be guarded.+ expect(dataUrlToImageFile("data:image/png;base64,@@@not-base64@@@")).toBeNull();+ });});describe("uploadImageAttachment", () => {diff --git a/apps/client/src/services/image_upload.ts b/apps/client/src/services/image_upload.tsindex 8bf20b332a..4b66529efd 100644--- a/apps/client/src/services/image_upload.ts+++ b/apps/client/src/services/image_upload.ts@@ -27,7 +27,12 @@ export function dataUrlToImageFile(dataUrl: string): File | null {const parsed = parseImageDataUrl(dataUrl);if (!parsed) return null;- const binary = atob(parsed.base64);+ let binary: string;+ try {+ binary = atob(parsed.base64);+ } catch {+ return null; // malformed base64 — atob throws a DOMException+ }const bytes = new Uint8Array(binary.length);for (let i = 0; i < binary.length; i++) {bytes[i] = binary.charCodeAt(i);diff --git a/apps/client/src/widgets/type_widgets/canvas/persistence.ts b/apps/client/src/widgets/type_widgets/canvas/persistence.tsindex 9416fb4c32..61b44a82ad 100644--- a/apps/client/src/widgets/type_widgets/canvas/persistence.ts+++ b/apps/client/src/widgets/type_widgets/canvas/persistence.ts@@ -46,6 +46,11 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte// its attachment for deletion (mirrors the library-item cleanup above).const persistedImageFileIds = useRef<Set<string>>(new Set());+ // The note being loaded by the latest onContentChange. Async loads below capture the id they+ // started for and bail if the user switched notes before they resolved, so a stale load can't+ // inject the previous note's images or overwrite the new note's owned-fileId set.+ const activeNoteIdRef = useRef<string | null>(null);+const appStateToCompare = useRef<Partial<ImportantAppState>>({});const spacedUpdate = useEditorSpacedUpdate({@@ -60,6 +65,10 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConteattachmentMetadata.current = [];persistedImageFileIds.current = new Set();+ // The note this load run belongs to; async results below are ignored if it's superseded.+ const loadedNoteId = note.noteId;+ activeNoteIdRef.current = loadedNoteId;+// load saved content into excalidraw canvaslet content: CanvasContent = {elements: [],@@ -80,6 +89,7 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte// data URLs and inject them so elements referencing those fileIds render. Legacy notes// that still carry inline images in `content.files` were already loaded by loadData().loadImageAttachments(note).then(({ files, metadata }) => {+ if (activeNoteIdRef.current !== loadedNoteId) return; // note switched mid-loadif (files.length > 0) {api.addFiles(files);}@@ -91,6 +101,7 @@ export default function useCanvasPersistence(note: FNote, noteContext: NoteConte// load the library stateloadLibrary(note).then(({ libraryItems, metadata }) => {+ if (activeNoteIdRef.current !== loadedNoteId) return; // note switched mid-load// Update the library and save to independent variablesapi.updateLibrary({ libraryItems, merge: false });diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/export.tsxindex c903218828..292d728f8e 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/export.tsx@@ -118,11 +118,16 @@ async function resolveSpreadsheetImage(source: string): Promise<ResolvedImage |const dataUrl = source.startsWith("data:") ? source : await fetchAsDataUrl(source);if (!dataUrl) return null;- const match = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/s.exec(dataUrl);- if (!match) return null;-- const extension = imageExtensionForMime(match[1]);- return extension ? { base64: match[2], extension } : null;+ // Parse `data:<mime>;base64,<payload>` with plain string ops — a regex with a nested+ // quantifier over the `;` parameters can backtrack exponentially (ReDoS).+ const comma = dataUrl.indexOf(",");+ if (comma < 0) return null;+ const header = dataUrl.slice(0, comma);+ if (!/;base64$/i.test(header)) return null; // only base64 payloads++ const mime = header.slice("data:".length).split(";")[0];+ const extension = imageExtensionForMime(mime);+ return extension ? { base64: dataUrl.slice(comma + 1), extension } : null;} catch {return null;}diff --git a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsxindex ba74c24141..4b5608d17f 100644--- a/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx+++ b/apps/client/src/widgets/type_widgets/spreadsheet/persistence.tsx@@ -1,3 +1,4 @@+import { SHEET_DRAWING_RESOURCE } from "@triliumnext/commons/src/lib/spreadsheet/workbook_model";import { CommandType, FUniver, IDisposable, IWorkbookData, LocaleType } from "@univerjs/presets";import { MutableRef, useEffect, useRef } from "preact/hooks";@@ -302,9 +303,6 @@ export function slimWorkbookData(workbookData: IWorkbookData): Partial<IWorkbookreturn slimmed;}-/** Univer's resource key under which the sheet drawing (image) layer is serialized in the workbook. */-const DRAWING_RESOURCE_NAME = "SHEET_DRAWING_PLUGIN";-/*** Uploads newly inserted base64 images in a saved workbook as Trilium attachments and rewrites their* drawing-resource `source` from the inline data URL to the returned `api/attachments/...` URL (with@@ -415,7 +413,7 @@ function forEachBase64DrawingImage(}// Floating images: serialized in the SHEET_DRAWING_PLUGIN resource.- const resource = workbookData.resources?.find((r) => r.name === DRAWING_RESOURCE_NAME);+ const resource = workbookData.resources?.find((r) => r.name === SHEET_DRAWING_RESOURCE);if (!resource?.data) return null;let drawingData: unknown;diff --git a/apps/server/src/services/notes.spec.ts b/apps/server/src/services/notes.spec.tsindex 302935c997..57944bd5a0 100644--- a/apps/server/src/services/notes.spec.ts+++ b/apps/server/src/services/notes.spec.ts@@ -41,6 +41,12 @@ describe("collectCanvasImageFileIds", () => {expect(collectCanvasImageFileIds("not json")).toEqual(new Set());expect(collectCanvasImageFileIds(JSON.stringify({}))).toEqual(new Set());});++ it("returns an empty set when the JSON shape is unexpected (null / non-array elements)", () => {+ expect(collectCanvasImageFileIds(JSON.stringify(null))).toEqual(new Set());+ expect(collectCanvasImageFileIds(JSON.stringify({ elements: 5 }))).toEqual(new Set());+ expect(collectCanvasImageFileIds(JSON.stringify({ elements: "oops" }))).toEqual(new Set());+ });});describe("findBookmarks", () => {diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex f9b66e305d..0cf8f13251 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -558,8 +558,9 @@ export function collectCanvasImageFileIds(content: string): Set<string> {try {const parsed = JSON.parse(content) as { elements?: { fileId?: string }[] };- for (const element of parsed.elements ?? []) {- if (element.fileId) {+ const elements = Array.isArray(parsed?.elements) ? parsed.elements : [];+ for (const element of elements) {+ if (element?.fileId) {fileIds.add(element.fileId);}}