From ed5c39df9e72fefa4a1afb406bfa6fc0b33718a0 Mon Sep 17 00:00:00 2001 From: Peter Dave Hello Date: Mon, 16 Mar 2026 01:34:23 +0800 Subject: [PATCH] Guard popup import flow against invalid backups and read errors Importing data in the popup assumed file reads, JSON parsing, and storage writes would always succeed, leaving failures unhandled and giving users no feedback. Catch errors across the import flow and validate that parsed backup data is a plain object before writing it to storage, so invalid files fail clearly without changing the successful restore path. --- src/popup/sections/GeneralPart.jsx | 37 ++++++++++++++++++++++++------ 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/src/popup/sections/GeneralPart.jsx b/src/popup/sections/GeneralPart.jsx index 11e72a40..22b46513 100644 --- a/src/popup/sections/GeneralPart.jsx +++ b/src/popup/sections/GeneralPart.jsx @@ -568,13 +568,36 @@ export function GeneralPart({ config, updateConfig, setTabIndex }) { input.click() }) if (!file) return - const data = await new Promise((resolve) => { - const reader = new FileReader() - reader.onload = (e) => resolve(JSON.parse(e.target.result)) - reader.readAsText(file) - }) - await importDataIntoStorage(Browser.storage.local, data) - window.location.reload() + try { + const fileContent = + typeof file.text === 'function' + ? await file.text() + : await new Promise((resolve, reject) => { + const reader = new FileReader() + reader.onload = () => resolve(reader.result) + reader.onerror = () => reject(reader.error) + reader.readAsText(file) + }) + const parsedData = JSON.parse(fileContent) + const isPlainObject = + parsedData !== null && typeof parsedData === 'object' && !Array.isArray(parsedData) + + if (!isPlainObject) { + throw new Error('Invalid backup file') + } + + await importDataIntoStorage(Browser.storage.local, parsedData) + window.location.reload() + } catch (error) { + console.error('[popup] Failed to import data', error) + const rawMessage = + error instanceof SyntaxError + ? 'Invalid backup file' + : error instanceof Error + ? error.message + : String(error ?? '') + window.alert(rawMessage ? `${t('Error')}: ${rawMessage}` : t('Error')) + } }} > {t('Import All Data')}