TagSpaces is an offline, open source, document manager with tagging support
feat: new implementation of the import/export functionality
Ilian Sapundshieva71a96ca8146
diff --git a/src/renderer/components/LocationManager.tsx b/src/renderer/components/LocationManager.tsxindex 162a890a9..7ddc255cf 100644--- a/src/renderer/components/LocationManager.tsx+++ b/src/renderer/components/LocationManager.tsx@@ -19,6 +19,7 @@import LocationView from '-/components/LocationView';import TsButton from '-/components/TsButton';import { useCreateEditLocationDialogContext } from '-/components/dialogs/hooks/useCreateEditLocationDialogContext';+import ExportImportDialog from '-/components/dialogs/ExportImportDialog';import LocationContextMenu from '-/components/menus/LocationContextMenu';import LocationManagerMenu from '-/components/menus/LocationManagerMenu';import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';@@ -54,12 +55,6 @@ function LocationManager(props: Props) {useState<boolean>(false);const [importFile, setImportFile] = useState<File>(undefined);- const ExportLocationsDialog =- Pro && Pro.UI ? Pro.UI.ExportLocationsDialog : false;-- const ImportLocationsDialog =- Pro && Pro.UI ? Pro.UI.ImportLocationsDialog : false;-const workSpacesContext = Pro?.contextProviders?.WorkSpacesContext? useContext<TS.WorkSpacesContextData>(Pro.contextProviders.WorkSpacesContext,@@ -211,17 +206,21 @@ function LocationManager(props: Props) {type="file"onChange={handleFileInputChange}/>- {ExportLocationsDialog && isExportLocationsDialogOpened && (- <ExportLocationsDialog+ {isExportLocationsDialogOpened && (+ <ExportImportDialogopen={isExportLocationsDialogOpened}+ mode="export"+ scope="locations"onClose={() => setExportLocationsDialogOpened(false)}/>)}- {ImportLocationsDialog && importFile && (- <ImportLocationsDialog+ {importFile && (+ <ExportImportDialogopen={Boolean(importFile)}- onClose={() => setImportFile(undefined)}+ mode="import"+ scope="locations"importFile={importFile}+ onClose={() => setImportFile(undefined)}/>)}</Box>diff --git a/src/renderer/components/StoredSearches.tsx b/src/renderer/components/StoredSearches.tsxindex 0bf299d28..3cd371de2 100644--- a/src/renderer/components/StoredSearches.tsx+++ b/src/renderer/components/StoredSearches.tsx@@ -52,6 +52,7 @@ import { useTranslation } from 'react-i18next';import { connect } from 'react-redux';import { bindActionCreators } from 'redux';import { Pro } from '../pro';+import ExportImportDialog from './dialogs/ExportImportDialog';import SidePanelTitle from './SidePanelTitle';interface Props {@@ -97,11 +98,6 @@ function StoredSearches(props: Props) {const menuHistoryKey = useRef<string>(undefined);const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);- const ExportSearchesDialog =- Pro && Pro.UI ? Pro.UI.ExportSearchesDialog : false;- const ImportSearchesDialog =- Pro && Pro.UI ? Pro.UI.ImportSearchesDialog : false;-const handleSearchMenu = (event: any) => {setSearchMenuAnchorEl(event.currentTarget);};@@ -504,19 +500,21 @@ function StoredSearches(props: Props) {type="file"onChange={handleFileInputChange}/>- {ExportSearchesDialog && isExportSearchesDialogOpened && (- <ExportSearchesDialog+ {isExportSearchesDialogOpened && (+ <ExportImportDialogopen={isExportSearchesDialogOpened}+ mode="export"+ scope="searches"onClose={() => setExportSearchesDialogOpened(false)}- searches={searches}/>)}- {ImportSearchesDialog && importFile && (- <ImportSearchesDialog+ {importFile && (+ <ExportImportDialogopen={Boolean(importFile)}- onClose={() => setImportFile(undefined)}+ mode="import"+ scope="searches"importFile={importFile}- searches={searches}+ onClose={() => setImportFile(undefined)}/>)}</Box>diff --git a/src/renderer/components/dialogs/ExportImportDialog.tsx b/src/renderer/components/dialogs/ExportImportDialog.tsxnew file mode 100644index 000000000..e6059d361--- /dev/null+++ b/src/renderer/components/dialogs/ExportImportDialog.tsx@@ -0,0 +1,75 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import DraggablePaper from '-/components/DraggablePaper';+import ExportImportPanel from '-/components/dialogs/ExportImportPanel';+import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';+import { TransferSection } from '-/services/export-import-utils';+import Dialog from '@mui/material/Dialog';+import DialogContent from '@mui/material/DialogContent';+import Paper from '@mui/material/Paper';+import { useTheme } from '@mui/material/styles';+import useMediaQuery from '@mui/material/useMediaQuery';+import { useTranslation } from 'react-i18next';++type Props = {+ open: boolean;+ mode: 'export' | 'import';+ scope?: TransferSection;+ importFile?: File;+ onClose: () => void;+};++function ExportImportDialog(props: Props) {+ const { open, mode, scope, importFile, onClose } = props;+ const { t } = useTranslation();+ const theme = useTheme();+ const smallScreen = useMediaQuery(theme.breakpoints.down('md'));++ return (+ <Dialog+ open={open}+ onClose={onClose}+ fullScreen={smallScreen}+ keepMounted+ PaperComponent={smallScreen ? Paper : DraggablePaper}+ scroll="paper"+ >+ <TsDialogTitle+ dialogTitle={+ mode === 'export'+ ? t('core:startExportButton')+ : t('core:startImportButton')+ }+ closeButtonTestId="closeExportImportTID"+ onClose={onClose}+ />+ <DialogContent sx={{ minWidth: smallScreen ? 'unset' : '420px' }}>+ <ExportImportPanel+ mode={mode}+ scope={scope}+ importFile={importFile}+ onDone={onClose}+ onCancel={onClose}+ />+ </DialogContent>+ </Dialog>+ );+}++export default ExportImportDialog;diff --git a/src/renderer/components/dialogs/ExportImportPanel.tsx b/src/renderer/components/dialogs/ExportImportPanel.tsxnew file mode 100644index 000000000..65f0d2d80--- /dev/null+++ b/src/renderer/components/dialogs/ExportImportPanel.tsx@@ -0,0 +1,748 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import AppConfig from '-/AppConfig';+import { ProLabel } from '-/components/HelperComponents';+import TsButton from '-/components/TsButton';+import TsSwitch from '-/components/TsSwitch';+import TsTextField from '-/components/TsTextField';+import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';+import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';+import { useNotificationContext } from '-/hooks/useNotificationContext';+import { useSavedSearchesContext } from '-/hooks/useSavedSearchesContext';+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import { Pro } from '-/pro';+import { AppDispatch } from '-/reducers/app';+import { getLocations } from '-/reducers/locations';+import { actions as SettingsActions, getSettings } from '-/reducers/settings';+import {+ TransferEnvelope,+ TransferSection,+ buildEnvelope,+ decryptEnvelope,+ downloadEnvelope,+ evaluatePasswordStrength,+ locationsHaveCredentials,+ normalizeEnvelope,+ parseEnvelope,+ readImportFile,+ validateLocations,+ validateSearches,+ validateSettings,+ validateTagGroups,+} from '-/services/export-import-utils';+import { prepareTagGroupsForExport } from '-/services/taglibrary-utils';+import { TS } from '-/tagspaces.namespace';+import { CommonLocation } from '-/utils/CommonLocation';+import Checkbox from '@mui/material/Checkbox';+import Divider from '@mui/material/Divider';+import FormControl from '@mui/material/FormControl';+import FormControlLabel from '@mui/material/FormControlLabel';+import FormHelperText from '@mui/material/FormHelperText';+import LinearProgress from '@mui/material/LinearProgress';+import Typography from '@mui/material/Typography';+import { EXPORT_VERSION } from '-/services/export-import-utils';+import { useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useDispatch, useSelector } from 'react-redux';++type Mode = 'export' | 'import';++type Props = {+ mode: Mode;+ scope?: TransferSection;+ importFile?: File;+ /** Called once the action finished (export written / import applied). */+ onDone: () => void;+ /** Cancel / close without doing anything. */+ onCancel: () => void;+};++type ItemRow = { id: string; label: string };++const ALL_SECTIONS: TransferSection[] = [+ 'settings',+ 'tagGroups',+ 'searches',+ 'locations',+];++function ExportImportPanel(props: Props) {+ const { mode, scope, importFile, onDone, onCancel } = props;+ const { t } = useTranslation();+ const { showNotification } = useNotificationContext();+ const dispatch: AppDispatch = useDispatch();++ const settings = useSelector(getSettings);+ const allLocations: TS.Location[] = useSelector(getLocations);+ const { tagGroups } = useEditedTagLibraryContext();+ const { searches, addSearches } = useSavedSearchesContext();+ const { importTagGroups } = useTaggingActionsContext();+ const { addLocations } = useCurrentLocationContext();++ const hasPro = Boolean(Pro && Pro.UI);+ const sectionIsPro = (s: TransferSection) =>+ s === 'locations' || s === 'searches';+ const sectionEnabled = (s: TransferSection) => !sectionIsPro(s) || hasPro;++ // Locations available for export (mirrors the former ExportLocationsDialog).+ const editableLocations = useMemo(+ () => allLocations.filter((l) => !l.isNotEditable),+ [allLocations],+ );++ /* --------------------------- import parsing ---------------------------- */+ const [importPhase, setImportPhase] = useState<+ 'loading' | 'password' | 'preview'+ >(mode === 'import' ? 'loading' : 'preview');+ const [rawText, setRawText] = useState<string>(undefined);+ const [isEncrypted, setIsEncrypted] = useState<boolean>(false);+ const [aesPassword, setAesPassword] = useState<string>('');+ const [decryptError, setDecryptError] = useState<boolean>(false);+ const [envelope, setEnvelope] = useState<TransferEnvelope>(undefined);+ // True while the (slow) password-based KDF + cipher runs.+ const [busy, setBusy] = useState<boolean>(false);++ useEffect(() => {+ if (mode !== 'import' || !importFile) {+ return;+ }+ readImportFile(importFile)+ .then(({ rawText: txt, isEncrypted: enc }) => {+ setRawText(txt);+ setIsEncrypted(enc);+ if (enc) {+ setImportPhase('password');+ } else {+ const obj = parseEnvelope(txt);+ const env = normalizeEnvelope(obj);+ if (!env) {+ showNotification(t('core:invalidImportFile'), 'warning', true);+ onCancel();+ return;+ }+ setEnvelope(env);+ setImportPhase('preview');+ }+ return undefined;+ })+ .catch((e) => {+ if (e && e.message === 'too-large') {+ showNotification(t('core:importFileTooLarge'), 'error', true);+ } else {+ showNotification(t('core:invalidImportFile'), 'warning', true);+ }+ onCancel();+ });+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [importFile, mode]);++ const handleDecrypt = async () => {+ if (!aesPassword || busy) {+ return;+ }+ setBusy(true);+ try {+ const obj = await decryptEnvelope(rawText, aesPassword);+ const env = obj ? normalizeEnvelope(obj) : undefined;+ if (!env) {+ setDecryptError(true);+ return;+ }+ setDecryptError(false);+ setEnvelope(env);+ setImportPhase('preview');+ } finally {+ setBusy(false);+ }+ };++ /* ----------------------- validated import data ------------------------- */+ const validated = useMemo(() => {+ if (mode !== 'import' || !envelope) {+ return {} as Record<TransferSection, any>;+ }+ return {+ settings: validateSettings(envelope.settings),+ locations: validateLocations(envelope.locations),+ tagGroups: validateTagGroups(envelope.tagGroups),+ searches: validateSearches(envelope.searches),+ } as Record<TransferSection, any>;+ }, [mode, envelope]);++ // A section present in the file but rejected by validation.+ const invalidSections: TransferSection[] = useMemo(() => {+ if (mode !== 'import' || !envelope) {+ return [];+ }+ const out: TransferSection[] = [];+ (+ ['settings', 'locations', 'tagGroups', 'searches'] as TransferSection[]+ ).forEach((s) => {+ const present =+ s === 'settings'+ ? envelope.settings !== undefined+ : Array.isArray((envelope as any)[s]);+ if (present && !validated[s]) {+ out.push(s);+ }+ });+ return out;+ }, [mode, envelope, validated]);++ /* ------------------------- per-section model --------------------------- */+ const itemsFor = (s: TransferSection): ItemRow[] => {+ if (mode === 'export') {+ if (s === 'locations') {+ return editableLocations.map((l) => ({ id: l.uuid, label: l.name }));+ }+ if (s === 'tagGroups') {+ return (tagGroups || []).map((g) => ({ id: g.uuid, label: g.title }));+ }+ if (s === 'searches') {+ return (searches || []).map((q) => ({ id: q.uuid, label: q.title }));+ }+ return [];+ }+ // import: items come from the validated envelope+ if (s === 'locations' && validated.locations) {+ return validated.locations.map((l: TS.S3Location) => ({+ id: l.uuid,+ label: l.name,+ }));+ }+ if (s === 'tagGroups' && validated.tagGroups) {+ return validated.tagGroups.map((g: TS.TagGroup) => ({+ id: g.uuid || (g as any).key,+ label: g.title,+ }));+ }+ if (s === 'searches' && validated.searches) {+ return validated.searches.map((q: TS.SearchQuery) => ({+ id: q.uuid,+ label: q.title,+ }));+ }+ return [];+ };++ // sectionOn: user wants this section. picked: selected item ids per section.+ const [sectionOn, setSectionOn] = useState<Record<string, boolean>>({});+ const [picked, setPicked] = useState<Record<string, Set<string>>>({});++ // Default selection: everything in `scope` (or all when no scope), all items.+ useEffect(() => {+ const on: Record<string, boolean> = {};+ const pick: Record<string, Set<string>> = {};+ ALL_SECTIONS.forEach((s) => {+ const available =+ sectionEnabled(s) &&+ (mode === 'export'+ ? s === 'settings' || itemsFor(s).length > 0+ : s === 'settings'+ ? validated.settings !== undefined+ : Boolean(validated[s]));+ on[s] = available && (scope ? s === scope : true);+ pick[s] = new Set(itemsFor(s).map((i) => i.id));+ });+ setSectionOn(on);+ setPicked(pick);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [mode, scope, hasPro, envelope, editableLocations, tagGroups, searches]);++ const toggleSection = (s: TransferSection, checked: boolean) =>+ setSectionOn((prev) => ({ ...prev, [s]: checked }));++ const toggleItem = (s: TransferSection, id: string, checked: boolean) =>+ setPicked((prev) => {+ const next = new Set(prev[s] || []);+ if (checked) {+ next.add(id);+ } else {+ next.delete(id);+ }+ return { ...prev, [s]: next };+ });++ const toggleSelectAll = (s: TransferSection) =>+ setPicked((prev) => {+ const all = itemsFor(s);+ const cur = prev[s] || new Set<string>();+ const next =+ cur.size === all.length+ ? new Set<string>()+ : new Set(all.map((i) => i.id));+ return { ...prev, [s]: next };+ });++ /* ----------------------------- encryption ------------------------------ */+ const selectedExportLocations = useMemo(+ () =>+ editableLocations.filter(+ (l) => sectionOn.locations && picked.locations?.has(l.uuid),+ ) as TS.S3Location[],+ [editableLocations, sectionOn, picked],+ );++ const credentialsInSelection =+ mode === 'export' &&+ sectionOn.locations &&+ locationsHaveCredentials(selectedExportLocations);++ const [encrypt, setEncrypt] = useState<boolean>(false);+ const [exportPassword, setExportPassword] = useState<string>('');+ const [retypePassword, setRetypePassword] = useState<string>('');++ // Default encryption ON whenever the selection carries credentials.+ useEffect(() => {+ if (mode === 'export') {+ setEncrypt(Boolean(credentialsInSelection));+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [credentialsInSelection, mode]);++ const passwordMismatch =+ encrypt && retypePassword.length > 0 && exportPassword !== retypePassword;++ const pwStrength = useMemo(+ () => evaluatePasswordStrength(exportPassword),+ [exportPassword],+ );+ const passwordTooWeak =+ encrypt && exportPassword.length > 0 && !pwStrength.ok;++ /* ------------------------------- export -------------------------------- */+ const collectExportSection = (s: TransferSection) => {+ if (!sectionOn[s]) {+ return undefined;+ }+ if (s === 'settings') {+ return settings;+ }+ const ids = picked[s] || new Set<string>();+ if (s === 'locations') {+ const prep = Pro?.UI?.prepareLocationForExport;+ const sel = editableLocations.filter((l) => ids.has(l.uuid));+ return prep ? sel.map((l) => prep(l)) : undefined;+ }+ if (s === 'tagGroups') {+ const sel = (tagGroups || []).filter((g) => ids.has(g.uuid));+ return prepareTagGroupsForExport(sel);+ }+ if (s === 'searches') {+ return (searches || []).filter((q) => ids.has(q.uuid));+ }+ return undefined;+ };++ const exportSelectionEmpty = ALL_SECTIONS.every((s) => {+ if (!sectionOn[s]) {+ return true;+ }+ return s === 'settings' ? false : (picked[s]?.size || 0) === 0;+ });++ const handleExport = async () => {+ if (exportSelectionEmpty || busy) {+ if (exportSelectionEmpty) {+ showNotification(t('core:nothingSelectedToExport'), 'warning', true);+ }+ return;+ }+ if (encrypt && (!exportPassword || passwordMismatch || !pwStrength.ok)) {+ return;+ }+ const env = buildEnvelope({+ settings: collectExportSection('settings'),+ locations: collectExportSection('locations'),+ tagGroups: collectExportSection('tagGroups'),+ searches: collectExportSection('searches'),+ });+ setBusy(true);+ try {+ await downloadEnvelope(env, encrypt ? exportPassword : undefined);+ } finally {+ setBusy(false);+ }+ showNotification(t('core:successfullyExported'), 'default', true);+ onDone();+ };++ /* ------------------------------- import -------------------------------- */+ const importSelectionEmpty = ALL_SECTIONS.every((s) => {+ if (!sectionOn[s] || !validated[s]) {+ return true;+ }+ return s === 'settings' ? false : (picked[s]?.size || 0) === 0;+ });++ const handleImport = () => {+ if (importSelectionEmpty) {+ showNotification(t('core:nothingSelectedToImport'), 'warning', true);+ return;+ }+ if (+ typeof envelope?.exportVersion === 'number' &&+ envelope.exportVersion > EXPORT_VERSION+ ) {+ showNotification(t('core:importVersionNewerWarning'), 'warning', true);+ }++ let appliedAny = false;++ // 1. Settings+ if (sectionOn.settings && validated.settings) {+ const v = validated.settings;+ if (v && Object.keys(v).length > 0) {+ dispatch(SettingsActions.importSettings(v));+ appliedAny = true;+ }+ }+ // 2. Tag groups+ if (sectionOn.tagGroups && Array.isArray(validated.tagGroups)) {+ const sel = validated.tagGroups.filter((g: TS.TagGroup) =>+ picked.tagGroups?.has(g.uuid || (g as any).key),+ );+ if (sel.length > 0) {+ importTagGroups(sel);+ appliedAny = true;+ }+ }+ // 3. Saved searches+ if (sectionOn.searches && Array.isArray(validated.searches)) {+ const sel = validated.searches.filter((q: TS.SearchQuery) =>+ picked.searches?.has(q.uuid),+ );+ if (sel.length > 0) {+ addSearches(sel);+ appliedAny = true;+ }+ }+ // 4. Locations+ if (sectionOn.locations && Array.isArray(validated.locations)) {+ const sel = validated.locations.filter((l: TS.S3Location) =>+ picked.locations?.has(l.uuid),+ );+ if (sel.length > 0) {+ addLocations(sel.map((l) => new CommonLocation(l)));+ appliedAny = true;+ }+ }++ if (!appliedAny) {+ showNotification(t('core:nothingSelectedToImport'), 'warning', true);+ return;+ }+ if (invalidSections.length > 0) {+ showNotification(t('core:sectionInvalidSkipped'), 'warning', true);+ }+ showNotification(t('core:successfullyImported'), 'default', true);+ onDone();+ };++ /* ------------------------------- render -------------------------------- */+ const sectionLabel: Record<TransferSection, string> = {+ settings: t('core:settings'),+ locations: t('core:sectionLocations'),+ tagGroups: t('core:tagLibrary'),+ searches: t('core:savedSearchesTitle'),+ };++ const renderSection = (s: TransferSection) => {+ const enabledHere = sectionEnabled(s);+ const isInvalid = mode === 'import' && invalidSections.includes(s);+ const presentInImport =+ mode === 'import' &&+ (s === 'settings'+ ? envelope?.settings !== undefined+ : Array.isArray((envelope as any)?.[s]));+ if (mode === 'import' && !presentInImport && !isInvalid) {+ return null; // section simply not in the file+ }+ const rows = itemsFor(s);+ const allPicked = rows.length > 0 && (picked[s]?.size || 0) === rows.length;++ return (+ <FormControl+ key={s}+ fullWidth+ sx={{ marginBottom: '4px' }}+ disabled={!enabledHere || isInvalid}+ >+ <FormControlLabel+ control={+ <Checkbox+ checked={Boolean(sectionOn[s]) && !isInvalid}+ disabled={!enabledHere || isInvalid}+ onChange={(e) => toggleSection(s, e.target.checked)}+ data-tid={'sectionToggle_' + s}+ />+ }+ label={+ <span>+ {sectionLabel[s]}+ {sectionIsPro(s) && !hasPro && <ProLabel />}+ </span>+ }+ />+ {isInvalid && (+ <FormHelperText sx={{ color: 'error.main' }}>+ {t('core:sectionInvalidSkipped')}+ </FormHelperText>+ )}+ {sectionIsPro(s) && !hasPro && (+ <FormHelperText>{t('core:proFeatureSection')}</FormHelperText>+ )}+ {enabledHere && !isInvalid && sectionOn[s] && s !== 'settings' && (+ <div style={{ paddingLeft: 28 }}>+ {rows.length > 1 && (+ <TsButton+ onClick={() => toggleSelectAll(s)}+ data-tid={'selectAll_' + s}+ style={{ marginBottom: 4 }}+ >+ {allPicked ? t('core:deselectAll') : t('core:selectAll')}+ </TsButton>+ )}+ {rows.map((row) => (+ <FormControlLabel+ key={row.id}+ sx={{ display: 'flex' }}+ control={+ <Checkbox+ size="small"+ checked={Boolean(picked[s]?.has(row.id))}+ onChange={(e) => toggleItem(s, row.id, e.target.checked)}+ />+ }+ label={row.label}+ />+ ))}+ </div>+ )}+ </FormControl>+ );+ };++ // ---- import: password phase ----+ if (mode === 'import' && importPhase !== 'preview') {+ return (+ <div>+ {importPhase === 'loading' && (+ <Typography>{t('core:loading')}</Typography>+ )}+ {importPhase === 'password' && (+ <>+ <Typography sx={{ marginBottom: '8px' }}>+ {t('core:decryptFile')}+ </Typography>+ <FormControl fullWidth error={decryptError}>+ <TsTextField+ name="aesPassword"+ autoFocus+ slotProps={{+ input: {+ autoCorrect: 'off',+ autoCapitalize: 'none',+ type: 'password',+ },+ }}+ label={t('core:aesPassword')}+ onChange={(event: any) => setAesPassword(event.target.value)}+ data-tid="aesPasswordTID"+ />+ </FormControl>+ {decryptError && (+ <FormHelperText sx={{ color: 'error.main' }}>+ {t('core:wrongPasswordError')}+ </FormHelperText>+ )}+ <div+ style={{+ marginTop: 12,+ display: 'flex',+ justifyContent: 'flex-end',+ gap: AppConfig.defaultSpaceBetweenButtons,+ }}+ >+ <TsButton onClick={onCancel}>{t('core:cancel')}</TsButton>+ <TsButton+ onClick={handleDecrypt}+ data-tid="decryptFileTID"+ variant="contained"+ disabled={!aesPassword || busy}+ >+ {t('core:decryptFile')}+ </TsButton>+ </div>+ </>+ )}+ </div>+ );+ }++ const confirmDisabled =+ mode === 'export'+ ? exportSelectionEmpty ||+ (encrypt && (!exportPassword || passwordMismatch || !pwStrength.ok))+ : importSelectionEmpty;++ return (+ <div data-tid="unifiedExportImportPanelTID">+ <Typography sx={{ marginBottom: '8px' }}>+ {mode === 'export'+ ? t('core:selectWhatToExport')+ : t('core:selectWhatToImport')}+ </Typography>++ {ALL_SECTIONS.map(renderSection)}++ {mode === 'export' && (+ <>+ <Divider sx={{ margin: '8px 0' }} />+ <FormControl fullWidth>+ <FormControlLabel+ labelPlacement="start"+ sx={{+ marginLeft: 0,+ marginRight: 0,+ justifyContent: 'space-between',+ }}+ control={+ <TsSwitch+ checked={encrypt}+ onClick={() => setEncrypt(!encrypt)}+ data-tid="encryptExportTID"+ />+ }+ label={t('core:encryptExport')}+ />+ </FormControl>+ {credentialsInSelection && !encrypt && (+ <FormHelperText sx={{ color: 'error.main' }}>+ {t('core:disableEncryptionWarning')}+ </FormHelperText>+ )}+ {credentialsInSelection && encrypt && (+ <FormHelperText>{t('core:encryptionRecommended')}</FormHelperText>+ )}+ {encrypt && (+ <>+ <FormControl fullWidth sx={{ paddingTop: '10px' }}>+ <TsTextField+ name="exportPassword"+ autoFocus+ slotProps={{+ input: { autoCorrect: 'off', autoCapitalize: 'none' },+ }}+ label={t('core:aesPassword')}+ type="password"+ onChange={(event: any) =>+ setExportPassword(event.target.value)+ }+ updateValue={(value: string) => setExportPassword(value)}+ retrieveValue={() => exportPassword}+ data-tid="exportPasswordTID"+ />+ </FormControl>+ {exportPassword.length > 0 && (+ <div+ data-tid="passwordStrengthTID"+ style={{ marginTop: 4, marginBottom: 4 }}+ >+ <LinearProgress+ variant="determinate"+ value={(pwStrength.score / 4) * 100}+ color={+ pwStrength.label === 'weak'+ ? 'error'+ : pwStrength.label === 'fair'+ ? 'warning'+ : pwStrength.label === 'good'+ ? 'info'+ : 'success'+ }+ sx={{ borderRadius: AppConfig.defaultCSSRadius }}+ />+ <Typography+ variant="caption"+ sx={{+ color: passwordTooWeak ? 'error.main' : 'text.secondary',+ }}+ >+ {t('core:passwordStrength')}:{' '}+ {t('core:pwStrength_' + pwStrength.label)}+ </Typography>+ </div>+ )}+ {passwordTooWeak && (+ <FormHelperText sx={{ color: 'error.main' }}>+ {t('core:passwordTooWeak')}+ </FormHelperText>+ )}+ <FormControl fullWidth error={passwordMismatch}>+ <TsTextField+ name="retypePassword"+ slotProps={{+ input: { autoCorrect: 'off', autoCapitalize: 'none' },+ }}+ label={t('core:retypePassword')}+ type="password"+ onChange={(event: any) =>+ setRetypePassword(event.target.value)+ }+ data-tid="retypePasswordTID"+ />+ </FormControl>+ {passwordMismatch && (+ <FormHelperText sx={{ color: 'error.main' }}>+ {t('core:retypePasswordDiffError')}+ </FormHelperText>+ )}+ </>+ )}+ </>+ )}++ <div+ style={{+ marginTop: 16,+ display: 'flex',+ justifyContent: 'flex-end',+ gap: AppConfig.defaultSpaceBetweenButtons,+ }}+ >+ <TsButton onClick={onCancel} data-tid="cancelExportImportTID">+ {t('core:cancel')}+ </TsButton>+ <TsButton+ onClick={mode === 'export' ? handleExport : handleImport}+ data-tid="exportImportConfirmTID"+ variant="contained"+ disabled={confirmDisabled || busy}+ >+ {mode === 'export'+ ? t('core:startExportButton')+ : t('core:startImportButton')}+ </TsButton>+ </div>+ </div>+ );+}++export default ExportImportPanel;diff --git a/src/renderer/components/dialogs/ImportExportTagGroupsDialog.tsx b/src/renderer/components/dialogs/ImportExportTagGroupsDialog.tsxdeleted file mode 100644index 6a246aec6..000000000--- a/src/renderer/components/dialogs/ImportExportTagGroupsDialog.tsx+++ /dev/null@@ -1,189 +0,0 @@-/**- * TagSpaces - universal file and folder organizer- * Copyright (C) 2017-present TagSpaces GmbH- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License (version 3) as- * published by the Free Software Foundation.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <https://www.gnu.org/licenses/>.- *- */--import DraggablePaper from '-/components/DraggablePaper';-import TsButton from '-/components/TsButton';-import TsDialogActions from '-/components/dialogs/components/TsDialogActions';-import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';-import { useCurrentLocationContext } from '-/hooks/useCurrentLocationContext';-import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';-import { exportTagGroups } from '-/services/taglibrary-utils';-import { TS } from '-/tagspaces.namespace';-import { CommonLocation } from '-/utils/CommonLocation';-import Checkbox from '@mui/material/Checkbox';-import Dialog from '@mui/material/Dialog';-import DialogContent from '@mui/material/DialogContent';-import FormControl from '@mui/material/FormControl';-import FormControlLabel from '@mui/material/FormControlLabel';-import FormGroup from '@mui/material/FormGroup';-import Paper from '@mui/material/Paper';-import { useTheme } from '@mui/material/styles';-import useMediaQuery from '@mui/material/useMediaQuery';-import { isFunc } from '@tagspaces/tagspaces-common/misc';-import { useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import TagContainer from '../TagContainer';-import TagGroupContainer from '../TagGroupContainer';--interface Props {- open: boolean;- tagGroups: Array<any>;- onClose: () => void;- dialogModeImport: boolean;- showNotification?: (text: string) => void;-}--function ImportExportTagGroupsDialog(props: Props) {- const { importTagGroups } = useTaggingActionsContext();- const { findLocation } = useCurrentLocationContext();- const { t } = useTranslation();- const selectedAll = useRef(true);- const [tagGroupList, setTagGroupList] = useState<Array<any>>(- props.tagGroups.map((entry) => ({- ...entry,- selected: selectedAll.current,- })),- );-- const handleToggleSelectAll = () => {- selectedAll.current = !selectedAll.current;- setTagGroupList(- tagGroupList.map((entry) => ({- ...entry,- selected: selectedAll.current,- })),- );- };-- const isSelected = () => tagGroupList.some((n) => n.selected === true);-- const handleTagGroup = (tagGroup: any, checked: boolean, index) => {- setTagGroupList([- ...tagGroupList.slice(0, index),- {- ...tagGroupList[index],- selected: !checked,- },- ...tagGroupList.slice(index + 1),- ]);- };-- const onConfirm = () => {- const { showNotification } = props;- const groupList = tagGroupList.filter((tagGroup) => tagGroup.selected);- props.onClose();- if (props.dialogModeImport) {- importTagGroups(groupList);- if (isFunc(showNotification)) {- showNotification(t('core:successfullyImportedGroupTags'));- }- } else {- exportTagGroups(groupList);- if (isFunc(showNotification)) {- showNotification(t('core:successfullyExportedGroupTags'));- }- }- };-- function getLocationName(locationId: string) {- if (locationId) {- const location: CommonLocation = findLocation(locationId);- if (location) {- return ' (' + location.name + ')';- }- }- return '';- }-- const renderTagGroups = (tagGroup, index) => (- <div key={tagGroup.uuid || tagGroup.key}>- <FormControl component="fieldset">- <FormGroup>- <FormControlLabel- control={- <Checkbox- id={tagGroup.uuid || tagGroup.key}- checked={tagGroup.selected}- onClick={(e) => handleTagGroup(e, tagGroup.selected, index)}- value={tagGroup.title}- name={tagGroup.title}- />- }- label={tagGroup.title + getLocationName(tagGroup.locationId)}- />- </FormGroup>- </FormControl>- <TagGroupContainer taggroup={tagGroup}>- {tagGroup.children &&- tagGroup.children.map((tag: TS.Tag) => (- <TagContainer tag={tag} tagMode="display" />- ))}- </TagGroupContainer>- </div>- );-- const { onClose, open } = props;- const theme = useTheme();- const smallScreen = useMediaQuery(theme.breakpoints.down('md'));- const confirmButton = (- <TsButton- disabled={!isSelected()}- onClick={onConfirm}- data-tid="confirmImportExport"- variant="contained"- >- {props.dialogModeImport ? 'Import' : 'Export'}- </TsButton>- );- return (- <Dialog- open={open}- fullScreen={smallScreen}- onClose={onClose}- PaperComponent={smallScreen ? Paper : DraggablePaper}- // onEnterKey={(event) => onEnterKeyHandler(event, this.onConfirm)}- >- <TsDialogTitle- dialogTitle={- props.dialogModeImport- ? t('core:importGroupTagsTitle')- : t('core:exportGroupTagsTitle')- }- closeButtonTestId="closeIETagGroupsTID"- onClose={onClose}- actionSlot={confirmButton}- />- <DialogContent>- <TsButton onClick={handleToggleSelectAll}>- {t('core:selectAllTagGroups')}- </TsButton>- <FormControl fullWidth={true}>- {tagGroupList.map(renderTagGroups)}- </FormControl>- </DialogContent>- {!smallScreen && (- <TsDialogActions>- <TsButton onClick={props.onClose}>{t('core:cancel')}</TsButton>- {confirmButton}- </TsDialogActions>- )}- </Dialog>- );-}--export default ImportExportTagGroupsDialog;diff --git a/src/renderer/components/dialogs/SettingsDialog.tsx b/src/renderer/components/dialogs/SettingsDialog.tsxindex 03fc16f0f..f80142d3d 100644--- a/src/renderer/components/dialogs/SettingsDialog.tsx+++ b/src/renderer/components/dialogs/SettingsDialog.tsx@@ -18,6 +18,7 @@import {AIIcon,AdvancedSettingsIcon,+ ExportImportIcon,ExtensionIcon,FileIcon,KeyboardIcon,@@ -29,6 +30,7 @@ import { BetaLabel } from '-/components/HelperComponents';import TsButton from '-/components/TsButton';import SettingsAI from '-/components/dialogs/components/SettingsAI';import SettingsAdvanced from '-/components/dialogs/components/SettingsAdvanced';+import SettingsBackupRestore from '-/components/dialogs/components/SettingsBackupRestore';import SettingsExtensions from '-/components/dialogs/components/SettingsExtensions';import SettingsFileTypes from '-/components/dialogs/components/SettingsFileTypes';import SettingsGeneral from '-/components/dialogs/components/SettingsGeneral';@@ -58,6 +60,7 @@ export enum SettingsTab {Extensions = 'extensions',Perspectives = 'perspectives',Advanced = 'advanced',+ BackupRestore = 'backupRestore',AI = 'ai',}@@ -198,6 +201,17 @@ function SettingsDialog(props: Props) {data-tid="advancedSettingsDialogTID"label={t('core:advancedSettingsTab')}/>+ <Tab+ value={SettingsTab.BackupRestore}+ sx={{+ textTransform: 'unset',+ justifyContent: 'flex-start',+ }}+ iconPosition="start"+ icon={smallScreen ? '' : <ExportImportIcon />}+ data-tid="backupRestoreSettingsDialog"+ label={t('core:backupRestoreSettingsTab')}+ /><Tabvalue={SettingsTab.AI}sx={{@@ -230,6 +244,7 @@ function SettingsDialog(props: Props) {{currentTab === SettingsTab.Extensions && <SettingsExtensions />}{currentTab === SettingsTab.Perspectives && <SettingsPerspectives />}{currentTab === SettingsTab.Advanced && <SettingsAdvanced />}+ {currentTab === SettingsTab.BackupRestore && <SettingsBackupRestore />}{currentTab === SettingsTab.AI && (<SettingsAI closeSettings={onClose} />)}diff --git a/src/renderer/components/dialogs/components/SettingsBackupRestore.tsx b/src/renderer/components/dialogs/components/SettingsBackupRestore.tsxnew file mode 100644index 000000000..9d91fe86a--- /dev/null+++ b/src/renderer/components/dialogs/components/SettingsBackupRestore.tsx@@ -0,0 +1,106 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import AppConfig from '-/AppConfig';+import { ExportIcon, ImportIcon } from '-/components/CommonIcons';+import TsButton from '-/components/TsButton';+import ExportImportPanel from '-/components/dialogs/ExportImportPanel';+import List from '@mui/material/List';+import ListItem from '@mui/material/ListItem';+import ListItemText from '@mui/material/ListItemText';+import { useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++function SettingsBackupRestore() {+ const { t } = useTranslation();+ const fileInputRef = useRef<HTMLInputElement>(null);+ const [mode, setMode] = useState<'export' | 'import'>(undefined);+ const [importFile, setImportFile] = useState<File>(undefined);++ const reset = () => {+ setMode(undefined);+ setImportFile(undefined);+ };++ function handleFileInputChange(selection: any) {+ const target = selection.currentTarget;+ const file = target.files[0];+ if (file) {+ setImportFile(file);+ setMode('import');+ }+ target.value = null;+ }++ return (+ <List+ sx={{+ overflowX: 'hidden',+ overflowY: 'auto',+ height: 'calc(100% - 18px)',+ }}+ >+ <ListItem>+ <ListItemText+ primary={t('core:exportImportTitle')}+ secondary={t('core:selectWhatToExport')}+ />+ <TsButton+ data-tid="settingsExportTID"+ startIcon={<ExportIcon />}+ onClick={() => {+ setImportFile(undefined);+ setMode('export');+ }}+ >+ {t('core:startExportButton')}+ </TsButton>+ <TsButton+ data-tid="settingsImportTID"+ startIcon={<ImportIcon />}+ sx={{ marginLeft: AppConfig.defaultSpaceBetweenButtons }}+ onClick={() => fileInputRef.current?.click()}+ >+ {t('core:startImportButton')}+ </TsButton>+ </ListItem>+ {mode && (+ <ListItem>+ <div style={{ width: '100%' }}>+ <ExportImportPanel+ key={mode + (importFile ? importFile.name : '')}+ mode={mode}+ importFile={importFile}+ onDone={reset}+ onCancel={reset}+ />+ </div>+ </ListItem>+ )}+ <input+ style={{ display: 'none' }}+ ref={fileInputRef}+ accept="*"+ type="file"+ onChange={handleFileInputChange}+ />+ </List>+ );+}++export default SettingsBackupRestore;diff --git a/src/renderer/components/menus/TagLibraryMenu.tsx b/src/renderer/components/menus/TagLibraryMenu.tsxindex c0b161509..9b25a8a44 100644--- a/src/renderer/components/menus/TagLibraryMenu.tsx+++ b/src/renderer/components/menus/TagLibraryMenu.tsx@@ -27,7 +27,6 @@ import {import { ProLabel, ProTooltip } from '-/components/HelperComponents';import TsMenuList from '-/components/TsMenuList';import { useEditedTagLibraryContext } from '-/hooks/useEditedTagLibraryContext';-import { useNotificationContext } from '-/hooks/useNotificationContext';import { Pro } from '-/pro';import { getSaveTagInLocation } from '-/reducers/settings';import { openURLExternally } from '-/services/utils-io';@@ -40,7 +39,7 @@ import Links from 'assets/links';import { useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { useSelector } from 'react-redux';-import ImportExportTagGroupsDialog from '../dialogs/ImportExportTagGroupsDialog';+import ExportImportDialog from '../dialogs/ExportImportDialog';interface Props {classes?: any;@@ -52,66 +51,49 @@ interface Props {function TagLibraryMenu(props: Props) {const { t } = useTranslation();- const { showNotification } = useNotificationContext();- const { tagGroups, refreshTagLibrary } = useEditedTagLibraryContext();+ const { refreshTagLibrary } = useEditedTagLibraryContext();const saveTagInLocation: boolean = useSelector(getSaveTagInLocation);const fileInput = useRef<HTMLInputElement>(null);- const tagGroupsImported = useRef([]);- // const [tagGroups, setTagGroups] = useState(null);- const [- isImportExportTagGroupDialogOpened,- setIsImportExportTagGroupDialogOpened,- ] = useState(false);- const [dialogModeImport, setDialogModeImport] = useState(false);-- function handleCloseDialogs() {- setIsImportExportTagGroupDialogOpened(false);- }+ const [isExportTagGroupsOpened, setExportTagGroupsOpened] = useState(false);+ const [importFile, setImportFile] = useState<File>(undefined);function handleExportTagGroup() {props.onClose();- setDialogModeImport(false);- // setTagGroups(props.tagGroups);- setIsImportExportTagGroupDialogOpened(true);+ setExportTagGroupsOpened(true);}function handleImportTagGroup() {props.onClose();- setDialogModeImport(true);fileInput.current.click();}function handleFileInputChange(selection: any) {const target = selection.currentTarget;const file = target.files[0];- const reader: any = new FileReader();-- reader.onload = () => {- try {- const jsonObj = JSON.parse(reader.result);- if (jsonObj.tagGroups) {- tagGroupsImported.current = jsonObj.tagGroups;- setIsImportExportTagGroupDialogOpened(true);- } else {- showNotification(t('core:invalidImportFile'), 'warning', true);- }- } catch (e) {- showNotification(t('core:invalidImportFile'), 'warning', true);- }- };- reader.readAsText(file);+ if (file) {+ setImportFile(file);+ }target.value = null;}return (<Box sx={{ overflowY: 'hidden' }}>- {isImportExportTagGroupDialogOpened && (- <ImportExportTagGroupsDialog- open={isImportExportTagGroupDialogOpened}- onClose={handleCloseDialogs}- tagGroups={dialogModeImport ? tagGroupsImported.current : tagGroups}- dialogModeImport={dialogModeImport}+ {isExportTagGroupsOpened && (+ <ExportImportDialog+ open={isExportTagGroupsOpened}+ mode="export"+ scope="tagGroups"+ onClose={() => setExportTagGroupsOpened(false)}+ />+ )}+ {importFile && (+ <ExportImportDialog+ open={Boolean(importFile)}+ mode="import"+ scope="tagGroups"+ importFile={importFile}+ onClose={() => setImportFile(undefined)}/>)}<Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.jsonindex 6f1f9b8be..9c6f73129 100644--- a/src/renderer/locales/en/core.json+++ b/src/renderer/locales/en/core.json@@ -81,14 +81,11 @@"exportLocationTitle": "Export Location Configuration","importLocationTitle": "Import Location Configuration","closeAllLocations": "Close All Locations",- "addAES": "Encrypt with AES","aesPassword": "Encryption password","retypePassword": "Retype password","decryptFile": "Decrypt file","wrongPasswordError": "Wrong password","retypePasswordDiffError": "Passwords does not match",- "locationExist": "Location already exist, it will be replaced with this one",- "notImportedLocation": "Location will not be imported","createLocationPath": "Location Path","chooseFolder": "Choose folder","createLocationName": "Location Name",@@ -111,8 +108,6 @@"hideProFeatures": "Hide Pro Features","autoSaveDescription": "Auto-save description changes","reloadDocument": "Reload Document",- "selectAllTagGroups": "Select/Deselect All Tag Groups",- "selectAllLocations": "Select/Deselect All Locations","closeViewer": "Close Document","saveDocument": "Save Document","nextDocument": "Next Document",@@ -146,11 +141,30 @@"useTrashCan": "Move deleted files or folders to trash bin if available","useTrashCanInfo": "Files and folders from e.g. S3 buckets will be deleted directly since there is no trash bin support","invalidImportFile": "The imported file has invalid format",+ "backupRestoreSettingsTab": "Backup Settings",+ "exportImportTitle": "Export & Import",+ "sectionLocations": "Locations",+ "selectWhatToExport": "Select what to export",+ "selectWhatToImport": "Select what to import",+ "encryptExport": "Encrypt export with a password",+ "encryptionRecommended": "Encryption is recommended because the selection contains credentials",+ "disableEncryptionWarning": "Warning: the export will contain unencrypted credentials",+ "passwordStrength": "Password strength",+ "pwStrength_weak": "Weak",+ "pwStrength_fair": "Fair",+ "pwStrength_good": "Good",+ "pwStrength_strong": "Strong",+ "passwordTooWeak": "Choose a stronger password: at least 10 characters with mixed character types, or a long passphrase",+ "importFileTooLarge": "The selected file is too large to import",+ "importVersionNewerWarning": "This file was created with a newer version of TagSpaces; some data may not import correctly",+ "nothingSelectedToExport": "Select at least one item to export",+ "nothingSelectedToImport": "Select at least one item to import",+ "sectionInvalidSkipped": "Some data in the file was invalid and was skipped",+ "proFeatureSection": "This section requires TagSpaces Pro",+ "successfullyExported": "Export completed successfully",+ "successfullyImported": "Import completed successfully",+ "deselectAll": "Deselect all","invalidPath": "Invalid Path",- "importGroupTagsTitle": "Import tags from file",- "exportGroupTagsTitle": "Export Tags Groups from TagSpaces",- "successfullyImportedGroupTags": "TagGroups are successfully imported",- "successfullyExportedGroupTags": "TagGroups are successfully exported","confirmSaveButton": "Save","useGenerateThumbnails": "Enable thumbnails generation","interfaceLanguage": "Interface Language",@@ -559,10 +573,7 @@"updateAllLocationIndexes": "Update all location indexes","exportSavedSearch": "Export Stored Search Queries","importSavedSearch": "Import Stored Search Queries",- "selectAllSearches": "Select All Queries","noSavedSearches": "No stored search queries found",- "notImportedSearches": "Searches will not be imported",- "searchExist": "Search already exist, it will be replaced with this one","searchEditBtn": "Update Stored Search","searchQueryName": "Search Query Name","createNewSavedSearchTitle": "Create Search Query",diff --git a/src/renderer/reducers/settings.ts b/src/renderer/reducers/settings.tsindex d7efa041b..09ea6a69c 100644--- a/src/renderer/reducers/settings.ts+++ b/src/renderer/reducers/settings.ts@@ -27,6 +27,7 @@ import {setZoomFactorElectron,updateByProp,} from '-/services/utils-io';+import { mergeImportedSettings } from '-/services/export-import-validators';import { TS } from '-/tagspaces.namespace';import versionMeta from '-/version.json';import { getUuid } from '@tagspaces/tagspaces-common/utils-io';@@ -36,6 +37,7 @@ import defaultSettings from './settings-default';export const types = {UPGRADE_SETTINGS: 'SETTINGS/UPGRADE_SETTINGS',+ IMPORT_SETTINGS: 'SETTINGS/IMPORT_SETTINGS',SET_LANGUAGE: 'SETTINGS/SET_LANGUAGE',TOGGLE_SHOWUNIXHIDDENENTRIES: 'SETTINGS/TOGGLE_SHOWUNIXHIDDENENTRIES',TOGGLE_SHOWSYMBOLICLINKS: 'SETTINGS/TOGGLE_SHOWSYMBOLICLINKS',@@ -182,6 +184,15 @@ export default (state: any = defaultSettings, action: any) => {}),};}+ case types.IMPORT_SETTINGS: {+ // Merge imported settings over the current (trusted) state — never over+ // defaults — so a partial/old file can't wipe local-only preferences.+ return mergeImportedSettings(+ state,+ action.settings,+ defaultSettings.keyBindings,+ );+ }case types.TOGGLE_SHOWUNIXHIDDENENTRIES: {return { ...state, showUnixHiddenEntries: !state.showUnixHiddenEntries };}@@ -965,6 +976,10 @@ export const actions = {upgradeSettings: () => ({type: types.UPGRADE_SETTINGS,}),+ importSettings: (settings: Record<string, any>) => ({+ type: types.IMPORT_SETTINGS,+ settings,+ }),setLastPublishedVersion: (lastPublishedVersion: string) => ({type: types.SET_LAST_PUBLISHED_VERSION,lastPublishedVersion,diff --git a/src/renderer/services/export-import-utils.ts b/src/renderer/services/export-import-utils.tsnew file mode 100644index 000000000..6a1f52484--- /dev/null+++ b/src/renderer/services/export-import-utils.ts@@ -0,0 +1,162 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import { decryptString, encryptString } from '-/services/secure-crypto';+import { saveAsTextFile } from '-/services/utils-io';+import { TS } from '-/tagspaces.namespace';+import versionMeta from '-/version.json';+import { formatDateTime4Tag } from '@tagspaces/tagspaces-common/misc';+import {+ EXPORT_VERSION,+ TransferEnvelope,+ cleanSearchesForExport,+ stripNonImportableSettings,+} from '-/services/export-import-validators';++// Re-export the pure logic so existing call sites keep one import surface.+export {+ EXPORT_VERSION,+ NON_IMPORTABLE_SETTINGS_KEYS,+ cleanSearchesForExport,+ evaluatePasswordStrength,+ locationsHaveCredentials,+ mergeImportedSettings,+ normalizeEnvelope,+ stripNonImportableSettings,+ validateLocations,+ validateSearches,+ validateSettings,+ validateTagGroups,+} from '-/services/export-import-validators';+export type {+ PasswordStrength,+ TransferEnvelope,+ TransferSection,+} from '-/services/export-import-validators';++/** Hard cap on the size of a file we will attempt to import. */+export const MAX_IMPORT_BYTES = 8 * 1024 * 1024; // 8 MB++export function buildEnvelope(parts: {+ settings?: Record<string, any>;+ locations?: TS.S3Location[];+ tagGroups?: TS.TagGroup[];+ searches?: TS.SearchQuery[];+}): TransferEnvelope {+ const env: TransferEnvelope = {+ appName: versionMeta.name,+ appVersion: versionMeta.version,+ exportVersion: EXPORT_VERSION,+ exportDate: new Date().toISOString(),+ };+ if (parts.settings && Object.keys(parts.settings).length > 0) {+ env.settings = stripNonImportableSettings(parts.settings);+ }+ if (parts.locations && parts.locations.length > 0) {+ env.locations = parts.locations;+ }+ if (parts.tagGroups && parts.tagGroups.length > 0) {+ env.tagGroups = parts.tagGroups;+ }+ if (parts.searches && parts.searches.length > 0) {+ env.searches = cleanSearchesForExport(parts.searches);+ }+ return env;+}++/**+ * Serialize the envelope. With a password the whole JSON is encrypted with a+ * slow KDF + authenticated cipher (see secure-crypto) → `.tsec`; otherwise+ * pretty JSON → `.json`.+ */+export async function serializeEnvelope(+ env: TransferEnvelope,+ aesPassword?: string,+): Promise<{ blob: Blob; ext: '.tsec' | '.json' }> {+ if (aesPassword) {+ const payload = await encryptString(JSON.stringify(env), aesPassword);+ return {+ blob: new Blob([payload], { type: 'application/octet-stream' }),+ ext: '.tsec',+ };+ }+ return {+ blob: new Blob([JSON.stringify(env, null, 2)], {+ type: 'application/json',+ }),+ ext: '.json',+ };+}++export async function downloadEnvelope(+ env: TransferEnvelope,+ aesPassword?: string,+): Promise<void> {+ const { blob, ext } = await serializeEnvelope(env, aesPassword);+ const dateTimeTag = formatDateTime4Tag(new Date(), true);+ saveAsTextFile(blob, 'tagspaces-export [' + dateTimeTag + ']' + ext);+}++export function readImportFile(+ file: File,+): Promise<{ rawText: string; isEncrypted: boolean }> {+ return new Promise((resolve, reject) => {+ if (!file) {+ reject(new Error('no-file'));+ return;+ }+ if (file.size > MAX_IMPORT_BYTES) {+ reject(new Error('too-large'));+ return;+ }+ const reader = new FileReader();+ reader.onload = () =>+ resolve({+ rawText: String(reader.result),+ isEncrypted: file.name.toLowerCase().endsWith('.tsec'),+ });+ reader.onerror = () => reject(reader.error || new Error('read-failed'));+ reader.readAsText(file);+ });+}++/** Decrypt + parse. Returns undefined on any failure (wrong password). */+export async function decryptEnvelope(+ rawText: string,+ aesPassword: string,+): Promise<any | undefined> {+ const txt = await decryptString(rawText, aesPassword);+ if (!txt) {+ return undefined;+ }+ try {+ return JSON.parse(txt);+ } catch (e) {+ return undefined;+ }+}++/** Parse JSON. Returns undefined on failure (never throws). */+export function parseEnvelope(rawText: string): any | undefined {+ try {+ const obj = JSON.parse(rawText);+ return obj && typeof obj === 'object' ? obj : undefined;+ } catch (e) {+ return undefined;+ }+}diff --git a/src/renderer/services/export-import-validators.ts b/src/renderer/services/export-import-validators.tsnew file mode 100644index 000000000..caf83aaaf--- /dev/null+++ b/src/renderer/services/export-import-validators.ts@@ -0,0 +1,350 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++/**+ * Pure, dependency-free export/import logic: validators, the settings+ * strip/merge rules and the backward-compat envelope shim. Kept free of any+ * renderer/IO import so it stays unit-testable in a plain Node environment and+ * so the settings reducer can reuse the merge without an import cycle.+ */++import type { TS } from '-/tagspaces.namespace';++/** Bump on a breaking change to the envelope schema. `0` = legacy file. */+export const EXPORT_VERSION = 1;++export type TransferSection =+ | 'settings'+ | 'locations'+ | 'tagGroups'+ | 'searches';++export interface TransferEnvelope {+ appName: string;+ appVersion: string;+ exportVersion: number;+ exportDate: string;+ settings?: Record<string, any>;+ locations?: TS.S3Location[];+ tagGroups?: TS.TagGroup[];+ searches?: TS.SearchQuery[];+}++/**+ * Settings keys that must never travel through an export/import: volatile+ * runtime/session state and environment-derived static lists.+ */+export const NON_IMPORTABLE_SETTINGS_KEYS = [+ // system / volatile+ 'appDataPath',+ 'contentHash',+ 'isUpdateInProgress',+ 'isUpdateAvailable',+ 'loggedIn',+ 'userId',+ 'error',+ 'isOnline',+ // static / environment-derived+ 'supportedLanguages',+ 'supportedFileTypes',+ 'supportedThemes',+ 'supportedGeoTagging',+ 'extensionsFound',+];++function isNonEmptyString(v: any): boolean {+ return typeof v === 'string' && v.length > 0;+}++/**+ * JSON.stringify replacer ported from the former ExportSearchesDialog: drops+ * the volatile `currentDirectory` and empty `fileTypes` arrays from a saved+ * search so exported searches stay portable.+ */+function searchesReplacer(key: string, value: any) {+ if (key !== 'currentDirectory' && value !== null && value !== '') {+ if (+ key !== 'fileTypes' ||+ (Array.isArray(value) && value.join('').length > 0)+ ) {+ return value;+ }+ }+ return undefined;+}++export function cleanSearchesForExport(+ searches: TS.SearchQuery[],+): TS.SearchQuery[] {+ try {+ return JSON.parse(JSON.stringify(searches, searchesReplacer));+ } catch (e) {+ console.error('cleanSearchesForExport failed', e);+ return searches;+ }+}++/** Remove non-portable keys from a settings object. */+export function stripNonImportableSettings(+ settings: Record<string, any>,+): Record<string, any> {+ const out: Record<string, any> = {};+ Object.keys(settings || {}).forEach((k) => {+ if (!NON_IMPORTABLE_SETTINGS_KEYS.includes(k)) {+ out[k] = settings[k];+ }+ });+ return out;+}++/** True when any selected location carries a secret that must be encrypted. */+export function locationsHaveCredentials(+ locations: TS.S3Location[] = [],+): boolean {+ return locations.some(+ (l) =>+ l &&+ Boolean(+ l.secretAccessKey ||+ l.accessKeyId ||+ l.sessionToken ||+ l.encryptionKey ||+ l.password,+ ),+ );+}++/**+ * Accept current envelopes as-is and wrap legacy single-type files (old+ * `{appName,appVersion,locations}` / `{...,tagGroups}` / `{...,searches}` and+ * decrypted legacy `.tsec` location files) as `exportVersion: 0` so they still+ * import.+ */+export function normalizeEnvelope(obj: any): TransferEnvelope | undefined {+ if (!obj || typeof obj !== 'object') {+ return undefined;+ }+ if (typeof obj.exportVersion === 'number') {+ return obj as TransferEnvelope;+ }+ const hasLegacy =+ Array.isArray(obj.locations) ||+ Array.isArray(obj.tagGroups) ||+ Array.isArray(obj.searches);+ if (!hasLegacy) {+ return undefined;+ }+ return {+ appName: obj.appName || 'TagSpaces',+ appVersion: obj.appVersion || '',+ exportVersion: 0,+ exportDate: obj.exportDate || '',+ settings: undefined,+ locations: Array.isArray(obj.locations) ? obj.locations : undefined,+ tagGroups: Array.isArray(obj.tagGroups) ? obj.tagGroups : undefined,+ searches: Array.isArray(obj.searches) ? obj.searches : undefined,+ };+}++/* ----------------------------- validators -------------------------------- *+ * Each is pure, never throws, drops invalid items, and returns undefined when+ * nothing usable survives. Callers must guard with these before dispatching so+ * a corrupt/empty section can never wipe good state (see CLAUDE.md data-loss+ * notes).+ * ------------------------------------------------------------------------- */++export function validateLocations(x: any): TS.S3Location[] | undefined {+ if (!Array.isArray(x)) {+ return undefined;+ }+ const valid = x.filter(+ (l) =>+ l &&+ typeof l === 'object' &&+ isNonEmptyString(l.uuid) &&+ isNonEmptyString(l.name) &&+ (typeof l.type === 'string' || typeof l.type === 'number'),+ );+ return valid.length > 0 ? valid : undefined;+}++export function validateSearches(x: any): TS.SearchQuery[] | undefined {+ if (!Array.isArray(x)) {+ return undefined;+ }+ const valid = x.filter(+ (s) =>+ s &&+ typeof s === 'object' &&+ isNonEmptyString(s.uuid) &&+ isNonEmptyString(s.title),+ );+ return valid.length > 0 ? valid : undefined;+}++export function validateTagGroups(x: any): TS.TagGroup[] | undefined {+ if (!Array.isArray(x)) {+ return undefined;+ }+ const valid = x.filter(+ (g) =>+ g &&+ typeof g === 'object' &&+ (isNonEmptyString(g.uuid) || isNonEmptyString((g as any).key)) &&+ isNonEmptyString(g.title) &&+ Array.isArray(g.children),+ );+ return valid.length > 0 ? valid : undefined;+}++export function validateSettings(x: any): Record<string, any> | undefined {+ if (!x || typeof x !== 'object' || Array.isArray(x)) {+ return undefined;+ }+ const out = stripNonImportableSettings(x);+ // light type sanity for a few critical keys — drop only the bad ones+ if ('keyBindings' in out && !Array.isArray(out.keyBindings)) {+ delete out.keyBindings;+ }+ if ('aiProviders' in out && !Array.isArray(out.aiProviders)) {+ delete out.aiProviders;+ }+ if ('tagDelimiter' in out && typeof out.tagDelimiter !== 'string') {+ delete out.tagDelimiter;+ }+ if ('interfaceLanguage' in out && typeof out.interfaceLanguage !== 'string') {+ delete out.interfaceLanguage;+ }+ return Object.keys(out).length > 0 ? out : undefined;+}++/**+ * Pure settings merge used by the IMPORT_SETTINGS reducer case. Merges the+ * incoming (file) settings over the current trusted state — never over+ * defaults — strips non-portable keys, applies the sensitive `aiProviders` /+ * `author` only when present in the file, and name-merges keyBindings against+ * the defaults so an unknown/removed binding can't break the app.+ */+export function mergeImportedSettings(+ state: Record<string, any>,+ incomingRaw: Record<string, any>,+ defaultKeyBindings: Array<{ name: string }>,+): Record<string, any> {+ const incoming = { ...(incomingRaw || {}) };+ NON_IMPORTABLE_SETTINGS_KEYS.forEach((k) => {+ delete incoming[k];+ });+ if (!('aiProviders' in incoming)) {+ delete incoming.aiProviders;+ }+ if (!('author' in incoming)) {+ delete incoming.author;+ }+ let mergedKeyBindings = state.keyBindings;+ if (Array.isArray(incoming.keyBindings)) {+ const stateKb = Array.isArray(state.keyBindings) ? state.keyBindings : [];+ mergedKeyBindings = (defaultKeyBindings || []).map((x) =>+ Object.assign(+ {},+ x,+ stateKb.find((y: any) => y && y.name === x.name),+ incoming.keyBindings.find((y: any) => y && y.name === x.name),+ ),+ );+ delete incoming.keyBindings;+ }+ return {+ ...state,+ ...incoming,+ keyBindings: mergedKeyBindings,+ };+}++/* -------------------------- password strength ---------------------------- */++export interface PasswordStrength {+ /** 0 (weak) … 4 (strong). */+ score: 0 | 1 | 2 | 3 | 4;+ /** Whether the password is strong enough to encrypt a credential export. */+ ok: boolean;+ label: 'weak' | 'fair' | 'good' | 'strong';+}++// Substrings that should hard-cap the score regardless of length/variety.+const WEAK_SUBSTRINGS = [+ 'password',+ 'passwort',+ 'tagspaces',+ 'qwerty',+ 'qwertz',+ 'letmein',+ 'iloveyou',+ 'admin',+ 'welcome',+ '123456',+ '12345678',+ '111111',+ 'abc123',+];++/**+ * Dependency-free passphrase assessment. The export KDF is deliberately slow+ * (PBKDF2 600k), so the real risk is short/dictionary passwords — this gates+ * those out while still letting a long multi-word passphrase through even if+ * it uses a single character class.+ */+export function evaluatePasswordStrength(pw: string): PasswordStrength {+ const toLabel = (s: number): PasswordStrength['label'] =>+ s <= 1 ? 'weak' : s === 2 ? 'fair' : s === 3 ? 'good' : 'strong';++ if (!pw) {+ return { score: 0, ok: false, label: 'weak' };+ }+ const len = pw.length;+ let score = 0;+ if (len >= 8) score += 1;+ if (len >= 12) score += 1;+ if (len >= 16) score += 1;++ const classes =+ (/[a-z]/.test(pw) ? 1 : 0) ++ (/[A-Z]/.test(pw) ? 1 : 0) ++ (/[0-9]/.test(pw) ? 1 : 0) ++ (/[^A-Za-z0-9]/.test(pw) ? 1 : 0);+ if (classes >= 3) score += 1;++ // Penalties+ if (len < 8) {+ score = 0;+ }+ if (/^(.)\1+$/.test(pw)) {+ score = 0; // a single repeated character+ }+ const lower = pw.toLowerCase();+ if (WEAK_SUBSTRINGS.some((w) => lower.includes(w))) {+ score = Math.min(score, 1);+ }++ const clamped = Math.max(0, Math.min(4, score)) as PasswordStrength['score'];+ return {+ score: clamped,+ // Require a long passphrase or a varied 10+ char password.+ ok: clamped >= 3 && len >= 10,+ label: toLabel(clamped),+ };+}diff --git a/src/renderer/services/secure-crypto.ts b/src/renderer/services/secure-crypto.tsnew file mode 100644index 000000000..f151aa16e--- /dev/null+++ b/src/renderer/services/secure-crypto.ts@@ -0,0 +1,307 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2017-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++/**+ * Password-based encryption for export files (credentials inside).+ *+ * Threat model: an attacker obtains the exported `.tsec` file and runs an+ * offline dictionary/brute-force attack against the user's passphrase. The+ * defenses are a slow KDF (PBKDF2) and authenticated encryption.+ *+ * Format (cleartext JSON header so we always know how to read it back):+ * { tsenc: 2, cipher, kdf, iter, salt, iv, ct, mac? }+ *+ * - cipher "AES-256-GCM": AES-GCM via Web Crypto (auth tag in `ct`). Preferred.+ * - cipher "AES-256-CBC-HMAC-SHA256": CryptoJS fallback for environments+ * without a usable `crypto.subtle` (e.g. Cordova file://). Encrypt-then-MAC.+ * - Legacy v1 files (raw CryptoJS `U2FsdGVkX1...` from the old locations+ * export) are still decryptable so existing `.tsec` files keep working.+ *+ * Both v2 variants use PBKDF2-SHA256 with a random 16-byte salt; the iteration+ * count is stored in the header so future tuning never breaks old files.+ */++import CryptoJS from 'crypto-js';++const TSENC_VERSION = 2;+// OWASP-class iteration counts. Web Crypto is native (fast); the CryptoJS+// fallback is pure-JS and far slower, so it uses a lower but still strong count.+const PBKDF2_ITER_SUBTLE = 600000;+const PBKDF2_ITER_CRYPTOJS = 120000;++function getSubtle(): SubtleCrypto | undefined {+ try {+ const c: any =+ typeof globalThis !== 'undefined'+ ? (globalThis as any).crypto+ : undefined;+ return c && c.subtle ? (c.subtle as SubtleCrypto) : undefined;+ } catch (e) {+ return undefined;+ }+}++function randomBytes(len: number): Uint8Array {+ const c: any = (globalThis as any).crypto;+ if (c && typeof c.getRandomValues === 'function') {+ return c.getRandomValues(new Uint8Array(len));+ }+ // Fallback: CryptoJS CSPRNG+ const wa = CryptoJS.lib.WordArray.random(len);+ const out = new Uint8Array(len);+ for (let i = 0; i < len; i += 1) {+ out[i] = (wa.words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;+ }+ return out;+}++function bytesToB64(bytes: Uint8Array): string {+ let bin = '';+ for (let i = 0; i < bytes.length; i += 1) {+ bin += String.fromCharCode(bytes[i]);+ }+ return btoa(bin);+}++function b64ToBytes(b64: string): Uint8Array {+ const bin = atob(b64);+ const out = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i += 1) {+ out[i] = bin.charCodeAt(i);+ }+ return out;+}++/** Standalone ArrayBuffer copy — satisfies Web Crypto's BufferSource type. */+function ab(bytes: Uint8Array): ArrayBuffer {+ return bytes.buffer.slice(+ bytes.byteOffset,+ bytes.byteOffset + bytes.byteLength,+ ) as ArrayBuffer;+}++function bytesToWordArray(bytes: Uint8Array): CryptoJS.lib.WordArray {+ const words: number[] = [];+ for (let i = 0; i < bytes.length; i += 1) {+ words[i >>> 2] |= bytes[i] << (24 - (i % 4) * 8);+ }+ return CryptoJS.lib.WordArray.create(words, bytes.length);+}++/** Length-safe constant-time string compare (defends MAC verification). */+function constantTimeEqual(a: string, b: string): boolean {+ if (a.length !== b.length) {+ return false;+ }+ let diff = 0;+ for (let i = 0; i < a.length; i += 1) {+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i);+ }+ return diff === 0;+}++/* ----------------------------- Web Crypto ------------------------------- */++async function deriveAesGcmKey(+ password: string,+ salt: Uint8Array,+ iterations: number,+): Promise<CryptoKey> {+ const subtle = getSubtle();+ const keyMaterial = await subtle.importKey(+ 'raw',+ ab(new TextEncoder().encode(password)),+ 'PBKDF2',+ false,+ ['deriveKey'],+ );+ return subtle.deriveKey(+ { name: 'PBKDF2', salt: ab(salt), iterations, hash: 'SHA-256' },+ keyMaterial,+ { name: 'AES-GCM', length: 256 },+ false,+ ['encrypt', 'decrypt'],+ );+}++/* ------------------------- CryptoJS fallback ---------------------------- */++function deriveCryptoJsKeys(+ password: string,+ saltWa: CryptoJS.lib.WordArray,+ iterations: number,+) {+ // 64 bytes: 32 for AES-256, 32 for HMAC-SHA256.+ const dk = CryptoJS.PBKDF2(password, saltWa, {+ keySize: 64 / 4,+ iterations,+ hasher: CryptoJS.algo.SHA256,+ });+ const encKey = CryptoJS.lib.WordArray.create(dk.words.slice(0, 8), 32);+ const macKey = CryptoJS.lib.WordArray.create(dk.words.slice(8, 16), 32);+ return { encKey, macKey };+}++/* ------------------------------- API ------------------------------------ */++export function isEncryptedEnvelope(text: string): boolean {+ try {+ const o = JSON.parse(text);+ return o && typeof o === 'object' && o.tsenc === TSENC_VERSION;+ } catch (e) {+ // Legacy v1 (raw CryptoJS OpenSSL base64) is not JSON.+ return /^U2FsdGVk/.test(text.trim());+ }+}++export async function encryptString(+ plaintext: string,+ password: string,+): Promise<string> {+ const subtle = getSubtle();+ const salt = randomBytes(16);++ if (subtle) {+ const iv = randomBytes(12);+ const key = await deriveAesGcmKey(password, salt, PBKDF2_ITER_SUBTLE);+ const ctBuf = await subtle.encrypt(+ { name: 'AES-GCM', iv: ab(iv) },+ key,+ ab(new TextEncoder().encode(plaintext)),+ );+ return JSON.stringify({+ tsenc: TSENC_VERSION,+ cipher: 'AES-256-GCM',+ kdf: 'PBKDF2-SHA256',+ iter: PBKDF2_ITER_SUBTLE,+ salt: bytesToB64(salt),+ iv: bytesToB64(iv),+ ct: bytesToB64(new Uint8Array(ctBuf)),+ });+ }++ // Fallback: PBKDF2 + AES-CBC + HMAC-SHA256 (encrypt-then-MAC).+ const saltWa = bytesToWordArray(salt);+ const ivBytes = randomBytes(16);+ const ivWa = bytesToWordArray(ivBytes);+ const { encKey, macKey } = deriveCryptoJsKeys(+ password,+ saltWa,+ PBKDF2_ITER_CRYPTOJS,+ );+ const enc = CryptoJS.AES.encrypt(plaintext, encKey, {+ iv: ivWa,+ mode: CryptoJS.mode.CBC,+ padding: CryptoJS.pad.Pkcs7,+ });+ const saltB64 = bytesToB64(salt);+ const ivB64 = bytesToB64(ivBytes);+ const ctB64 = enc.ciphertext.toString(CryptoJS.enc.Base64);+ const mac = CryptoJS.HmacSHA256(+ saltB64 + '.' + ivB64 + '.' + ctB64,+ macKey,+ ).toString();+ return JSON.stringify({+ tsenc: TSENC_VERSION,+ cipher: 'AES-256-CBC-HMAC-SHA256',+ kdf: 'PBKDF2-SHA256',+ iter: PBKDF2_ITER_CRYPTOJS,+ salt: saltB64,+ iv: ivB64,+ ct: ctB64,+ mac,+ });+}++/** Decrypt v2 (GCM or CBC-HMAC) or legacy v1. undefined on any failure. */+export async function decryptString(+ text: string,+ password: string,+): Promise<string | undefined> {+ let header: any;+ try {+ header = JSON.parse(text);+ } catch (e) {+ header = undefined;+ }++ // ---- v2 ----+ if (header && header.tsenc === TSENC_VERSION) {+ try {+ const salt = b64ToBytes(header.salt);+ const iter = Number(header.iter) || PBKDF2_ITER_SUBTLE;++ if (header.cipher === 'AES-256-GCM') {+ const subtle = getSubtle();+ if (!subtle) {+ return undefined; // GCM file on a platform without Web Crypto+ }+ const key = await deriveAesGcmKey(password, salt, iter);+ const ptBuf = await subtle.decrypt(+ { name: 'AES-GCM', iv: ab(b64ToBytes(header.iv)) },+ key,+ ab(b64ToBytes(header.ct)),+ );+ return new TextDecoder().decode(ptBuf);+ }++ if (header.cipher === 'AES-256-CBC-HMAC-SHA256') {+ const { encKey, macKey } = deriveCryptoJsKeys(+ password,+ bytesToWordArray(salt),+ iter,+ );+ const expectedMac = CryptoJS.HmacSHA256(+ header.salt + '.' + header.iv + '.' + header.ct,+ macKey,+ ).toString();+ if (+ typeof header.mac !== 'string' ||+ !constantTimeEqual(expectedMac, header.mac)+ ) {+ return undefined; // tampered or wrong password+ }+ const decrypted = CryptoJS.AES.decrypt(+ CryptoJS.lib.CipherParams.create({+ ciphertext: CryptoJS.enc.Base64.parse(header.ct),+ }),+ encKey,+ {+ iv: bytesToWordArray(b64ToBytes(header.iv)),+ mode: CryptoJS.mode.CBC,+ padding: CryptoJS.pad.Pkcs7,+ },+ );+ const txt = decrypted.toString(CryptoJS.enc.Utf8);+ return txt || undefined;+ }+ return undefined; // unknown cipher+ } catch (e) {+ return undefined;+ }+ }++ // ---- legacy v1: raw CryptoJS OpenSSL (old locations .tsec) ----+ try {+ const bytes = CryptoJS.AES.decrypt(text.trim(), password);+ const txt = bytes.toString(CryptoJS.enc.Utf8);+ return txt || undefined;+ } catch (e) {+ return undefined;+ }+}diff --git a/src/renderer/services/taglibrary-utils.ts b/src/renderer/services/taglibrary-utils.tsindex feb3351b5..06507b694 100644--- a/src/renderer/services/taglibrary-utils.ts+++ b/src/renderer/services/taglibrary-utils.ts@@ -78,11 +78,28 @@ export function getAllTags();}+/**+ * Run each tag group through prepareTagGroupForExport and keep only the ones+ * with a title + uuid. Shared by the legacy exporter and the unified+ * export/import dialog so both produce an identical tag-group payload.+ */+export function prepareTagGroupsForExport(+ entry: Array<TS.TagGroup>,+): TS.TagGroup[] {+ const allTagGroups: TS.TagGroup[] = [];+ (entry || []).forEach((value) => {+ const preparedTagGroup = prepareTagGroupForExport(value);+ if (preparedTagGroup.title && preparedTagGroup.uuid) {+ allTagGroups.push(preparedTagGroup);+ }+ });+ return allTagGroups;+}+export function exportTagGroups(entry: Array<TS.TagGroup>,settingsVersion = 3,) {- const tagLibrary = entry;const jsonFormat ='{ "appName": "' +versionMeta.name +@@ -91,13 +108,7 @@ export function exportTagGroups('", "settingsVersion": ' +settingsVersion +', "tagGroups": ';- const allTagGroups = [];- tagLibrary.forEach((value) => {- const preparedTagGroup = prepareTagGroupForExport(value);- if (preparedTagGroup.title && preparedTagGroup.uuid) {- allTagGroups.push(preparedTagGroup);- }- });+ const allTagGroups = prepareTagGroupsForExport(entry);const blob = new Blob([jsonFormat + JSON.stringify(allTagGroups, null, 2) + '}'],diff --git a/tests/unit/exportImport.test.js b/tests/unit/exportImport.test.jsnew file mode 100644index 000000000..fd1500e7e--- /dev/null+++ b/tests/unit/exportImport.test.js@@ -0,0 +1,281 @@+import { describe, expect, test } from '@playwright/test';+import {+ NON_IMPORTABLE_SETTINGS_KEYS,+ cleanSearchesForExport,+ evaluatePasswordStrength,+ locationsHaveCredentials,+ mergeImportedSettings,+ normalizeEnvelope,+ stripNonImportableSettings,+ validateLocations,+ validateSearches,+ validateSettings,+ validateTagGroups,+} from '-/services/export-import-validators';++describe('export-import validators', () => {+ describe('validateLocations', () => {+ test('keeps valid items, drops malformed ones', () => {+ const out = validateLocations([+ { uuid: 'a', name: 'Loc A', type: '1' },+ { uuid: '', name: 'no uuid', type: '0' },+ { name: 'missing uuid', type: '0' },+ { uuid: 'b', name: 'Loc B', type: 0 },+ null,+ 'not an object',+ ]);+ expect(out).toHaveLength(2);+ expect(out.map((l) => l.uuid)).toEqual(['a', 'b']);+ });++ test('non-array → undefined', () => {+ expect(validateLocations(undefined)).toBeUndefined();+ expect(validateLocations({})).toBeUndefined();+ });++ test('all invalid → undefined (never an empty array)', () => {+ expect(validateLocations([{ name: 'x' }, {}])).toBeUndefined();+ });+ });++ describe('validateSearches', () => {+ test('requires uuid + title', () => {+ const out = validateSearches([+ { uuid: 's1', title: 'Search 1' },+ { uuid: 's2' },+ { title: 'no uuid' },+ ]);+ expect(out).toHaveLength(1);+ expect(out[0].uuid).toBe('s1');+ });++ test('non-array → undefined', () => {+ expect(validateSearches('nope')).toBeUndefined();+ });+ });++ describe('validateTagGroups', () => {+ test('requires uuid|key + title + children array', () => {+ const out = validateTagGroups([+ { uuid: 'g1', title: 'G1', children: [] },+ { key: 'legacy', title: 'Legacy', children: [{ title: 't' }] },+ { uuid: 'g3', title: 'no children' },+ { uuid: 'g4', children: [] },+ ]);+ expect(out).toHaveLength(2);+ expect(out.map((g) => g.title)).toEqual(['G1', 'Legacy']);+ });++ test('all invalid → undefined', () => {+ expect(validateTagGroups([{ title: 'x' }])).toBeUndefined();+ });+ });++ describe('validateSettings', () => {+ test('strips non-importable keys', () => {+ const out = validateSettings({+ interfaceLanguage: 'de_DE',+ appDataPath: '/secret/path',+ userId: 'u1',+ supportedThemes: ['light'],+ tagDelimiter: ' ',+ });+ expect(out).toEqual({ interfaceLanguage: 'de_DE', tagDelimiter: ' ' });+ expect('appDataPath' in out).toBe(false);+ expect('userId' in out).toBe(false);+ expect('supportedThemes' in out).toBe(false);+ });++ test('drops only the bad-typed critical keys', () => {+ const out = validateSettings({+ interfaceLanguage: 5,+ keyBindings: 'not-array',+ aiProviders: {},+ tagDelimiter: ' ',+ });+ expect(out).toEqual({ tagDelimiter: ' ' });+ });++ test('non-object or empty-after-strip → undefined', () => {+ expect(validateSettings(null)).toBeUndefined();+ expect(validateSettings([1, 2])).toBeUndefined();+ expect(validateSettings({ appDataPath: '/x', userId: 'y' })).toBeUndefined();+ });+ });++ describe('normalizeEnvelope', () => {+ test('passes a versioned envelope through unchanged', () => {+ const env = { exportVersion: 1, settings: { a: 1 } };+ expect(normalizeEnvelope(env)).toBe(env);+ });++ test('wraps a legacy single-type file as exportVersion 0', () => {+ const out = normalizeEnvelope({+ appName: 'TagSpaces',+ appVersion: '6.0.0',+ tagGroups: [{ uuid: 'g', title: 'G', children: [] }],+ });+ expect(out.exportVersion).toBe(0);+ expect(out.tagGroups).toHaveLength(1);+ expect(out.settings).toBeUndefined();+ });++ test('junk → undefined', () => {+ expect(normalizeEnvelope(null)).toBeUndefined();+ expect(normalizeEnvelope({ foo: 'bar' })).toBeUndefined();+ });+ });++ describe('stripNonImportableSettings / cleanSearchesForExport', () => {+ test('strip removes every blacklisted key', () => {+ const input = {};+ NON_IMPORTABLE_SETTINGS_KEYS.forEach((k) => {+ input[k] = 'x';+ });+ input.keepMe = true;+ expect(stripNonImportableSettings(input)).toEqual({ keepMe: true });+ });++ test('clean drops currentDirectory and empty fileTypes', () => {+ const out = cleanSearchesForExport([+ {+ uuid: 's',+ title: 'S',+ currentDirectory: '/should/be/removed',+ fileTypes: [],+ textQuery: 'keep',+ },+ ]);+ expect(out[0].currentDirectory).toBeUndefined();+ expect(out[0].fileTypes).toBeUndefined();+ expect(out[0].textQuery).toBe('keep');+ });+ });++ describe('locationsHaveCredentials', () => {+ test('true when a secret is present', () => {+ expect(+ locationsHaveCredentials([{ uuid: 'a', secretAccessKey: 'sk' }]),+ ).toBe(true);+ expect(locationsHaveCredentials([{ uuid: 'a', password: 'p' }])).toBe(+ true,+ );+ });++ test('false for plain local locations', () => {+ expect(+ locationsHaveCredentials([{ uuid: 'a', name: 'local', type: '0' }]),+ ).toBe(false);+ expect(locationsHaveCredentials([])).toBe(false);+ });+ });++ describe('mergeImportedSettings', () => {+ const defaultKb = [+ { name: 'saveDocument', command: 'ctrl+s' },+ { name: 'openParentDir', command: 'backspace' },+ ];++ test('merges over current state, never over defaults; keeps local-only keys', () => {+ const state = {+ interfaceLanguage: 'en',+ localOnlyPref: 42,+ keyBindings: defaultKb,+ };+ const out = mergeImportedSettings(+ state,+ { interfaceLanguage: 'de_DE' },+ defaultKb,+ );+ expect(out.interfaceLanguage).toBe('de_DE');+ expect(out.localOnlyPref).toBe(42); // not wiped+ });++ test('strips system keys and applies aiProviders/author only if present', () => {+ const state = { author: 'me', aiProviders: [{ id: '1' }], x: 1 };+ const out = mergeImportedSettings(+ state,+ { appDataPath: '/evil', x: 2 },+ defaultKb,+ );+ expect(out.appDataPath).toBeUndefined();+ expect(out.x).toBe(2);+ expect(out.author).toBe('me'); // untouched (absent in file)+ expect(out.aiProviders).toEqual([{ id: '1' }]);+ });++ test('applies aiProviders/author when present in the file', () => {+ const state = { author: 'old', aiProviders: [] };+ const out = mergeImportedSettings(+ state,+ { author: 'new', aiProviders: [{ id: '2' }] },+ defaultKb,+ );+ expect(out.author).toBe('new');+ expect(out.aiProviders).toEqual([{ id: '2' }]);+ });++ test('name-merges keyBindings against defaults (unknown bindings dropped)', () => {+ const state = { keyBindings: defaultKb };+ const out = mergeImportedSettings(+ state,+ {+ keyBindings: [+ { name: 'saveDocument', command: 'cmd+s' },+ { name: 'totallyUnknown', command: 'f13' },+ ],+ },+ defaultKb,+ );+ expect(out.keyBindings).toHaveLength(2); // only known defaults+ const save = out.keyBindings.find((k) => k.name === 'saveDocument');+ expect(save.command).toBe('cmd+s'); // overridden from file+ const parent = out.keyBindings.find((k) => k.name === 'openParentDir');+ expect(parent.command).toBe('backspace'); // kept from default/state+ expect(+ out.keyBindings.find((k) => k.name === 'totallyUnknown'),+ ).toBeUndefined();+ });+ });++ describe('evaluatePasswordStrength', () => {+ test('empty / very short → weak, not ok', () => {+ expect(evaluatePasswordStrength('')).toMatchObject({+ score: 0,+ ok: false,+ label: 'weak',+ });+ expect(evaluatePasswordStrength('Ab1!')).toMatchObject({+ ok: false,+ label: 'weak',+ });+ });++ test('common / repeated passwords are capped', () => {+ expect(evaluatePasswordStrength('password').ok).toBe(false);+ expect(evaluatePasswordStrength('Password123!').ok).toBe(false); // contains "password"+ expect(evaluatePasswordStrength('aaaaaaaaaaaa')).toMatchObject({+ score: 0,+ ok: false,+ });+ expect(evaluatePasswordStrength('TagSpaces2024!').ok).toBe(false);+ });++ test('varied 12+ char password passes', () => {+ const s = evaluatePasswordStrength('Tr0ub4dour&3xy');+ expect(s.ok).toBe(true);+ expect(['good', 'strong']).toContain(s.label);+ });++ test('long single-class passphrase passes', () => {+ const s = evaluatePasswordStrength('correcthorsebatterystaple');+ expect(s.ok).toBe(true);+ expect(s.score).toBeGreaterThanOrEqual(3);+ });++ test('short-but-complex stays below the gate', () => {+ // 9 chars, all classes, but under the 10-char floor+ expect(evaluatePasswordStrength('Ab1!cd2?').ok).toBe(false);+ });+ });+});diff --git a/tests/unit/secureCrypto.test.js b/tests/unit/secureCrypto.test.jsnew file mode 100644index 000000000..0327c588a--- /dev/null+++ b/tests/unit/secureCrypto.test.js@@ -0,0 +1,65 @@+import { describe, expect, test } from '@playwright/test';+import CryptoJS from 'crypto-js';+import {+ decryptString,+ encryptString,+ isEncryptedEnvelope,+} from '-/services/secure-crypto';++describe('secure-crypto', () => {+ const secret = JSON.stringify({ token: 'super-secret', n: 42 });+ const password = 'correct horse battery staple';++ test('round-trips through encrypt/decrypt', async () => {+ const blob = await encryptString(secret, password);+ expect(isEncryptedEnvelope(blob)).toBe(true);+ const header = JSON.parse(blob);+ expect(header.tsenc).toBe(2);+ expect(header.kdf).toBe('PBKDF2-SHA256');+ expect(header.iter).toBeGreaterThanOrEqual(120000);+ // ciphertext must not leak the plaintext+ expect(blob).not.toContain('super-secret');+ const out = await decryptString(blob, password);+ expect(out).toBe(secret);+ });++ test('wrong password → undefined (no throw)', async () => {+ const blob = await encryptString(secret, password);+ const out = await decryptString(blob, 'wrong password');+ expect(out).toBeUndefined();+ });++ test('tampered ciphertext is rejected (authenticated)', async () => {+ const blob = await encryptString(secret, password);+ const header = JSON.parse(blob);+ // flip the last base64 char of the ciphertext+ const ct = header.ct;+ header.ct = ct.slice(0, -2) + (ct.slice(-2, -1) === 'A' ? 'B' : 'A') + ct.slice(-1);+ const out = await decryptString(JSON.stringify(header), password);+ expect(out).toBeUndefined();+ });++ test('isEncryptedEnvelope detects v2 and legacy, rejects plain json', () => {+ const legacy = CryptoJS.AES.encrypt('hello', 'pw').toString();+ expect(isEncryptedEnvelope(legacy)).toBe(true); // U2FsdGVk...+ expect(isEncryptedEnvelope('{"settings":{}}')).toBe(false);+ expect(isEncryptedEnvelope('not json at all')).toBe(false);+ });++ test('legacy v1 (raw CryptoJS) still decrypts', async () => {+ // Mirrors the old LocationsTransfer.exportLocations format.+ const legacyPayload = JSON.stringify({+ appName: 'TagSpaces',+ appVersion: '6.0.0',+ locations: [{ uuid: 'l1', name: 'L1', type: '1' }],+ });+ const legacyBlob = CryptoJS.AES.encrypt(+ legacyPayload,+ 'oldpass',+ ).toString();+ const out = await decryptString(legacyBlob, 'oldpass');+ expect(JSON.parse(out).locations[0].uuid).toBe('l1');+ const bad = await decryptString(legacyBlob, 'nope');+ expect(bad).toBeUndefined();+ });+});