Skip to content

Commit ed5c39d

Browse files
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.
1 parent 5a59aa0 commit ed5c39d

File tree

1 file changed

+30
-7
lines changed

1 file changed

+30
-7
lines changed

src/popup/sections/GeneralPart.jsx

Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -568,13 +568,36 @@ export function GeneralPart({ config, updateConfig, setTabIndex }) {
568568
input.click()
569569
})
570570
if (!file) return
571-
const data = await new Promise((resolve) => {
572-
const reader = new FileReader()
573-
reader.onload = (e) => resolve(JSON.parse(e.target.result))
574-
reader.readAsText(file)
575-
})
576-
await importDataIntoStorage(Browser.storage.local, data)
577-
window.location.reload()
571+
try {
572+
const fileContent =
573+
typeof file.text === 'function'
574+
? await file.text()
575+
: await new Promise((resolve, reject) => {
576+
const reader = new FileReader()
577+
reader.onload = () => resolve(reader.result)
578+
reader.onerror = () => reject(reader.error)
579+
reader.readAsText(file)
580+
})
581+
const parsedData = JSON.parse(fileContent)
582+
const isPlainObject =
583+
parsedData !== null && typeof parsedData === 'object' && !Array.isArray(parsedData)
584+
585+
if (!isPlainObject) {
586+
throw new Error('Invalid backup file')
587+
}
588+
589+
await importDataIntoStorage(Browser.storage.local, parsedData)
590+
window.location.reload()
591+
} catch (error) {
592+
console.error('[popup] Failed to import data', error)
593+
const rawMessage =
594+
error instanceof SyntaxError
595+
? 'Invalid backup file'
596+
: error instanceof Error
597+
? error.message
598+
: String(error ?? '')
599+
window.alert(rawMessage ? `${t('Error')}: ${rawMessage}` : t('Error'))
600+
}
578601
}}
579602
>
580603
{t('Import All Data')}

0 commit comments

Comments
 (0)