Skip to content

TagSpaces is an offline, open source, document manager with tagging support

feat: added encryption of sensitive data with a password as fallback for absend of OS-key or the web version with e2e test

Ilian Sapundshievbb13d51c15c6
diff --git a/scripts/extconfig-credentials-encryption.js b/scripts/extconfig-credentials-encryption.js
new file mode 100644
index 000000000..5ad3f26f5
--- /dev/null
+++ b/scripts/extconfig-credentials-encryption.js
@@ -0,0 +1,13 @@
+// Extconfig used by tests/e2e/credentials-encryption-web.pw.e2e.js (TST91).
+//
+// The test creates its own S3 location at runtime and then exercises the
+// at-rest credentials-encryption feature, so we deliberately:
+// • set `ExtSaveLocationsInBrowser=true` so the `locations` redux slice
+// is persisted on web (the encryption feature only matters then), and
+// • do NOT set `ExtLocations` — when that is set, the locations reducer
+// becomes a constant function and the test can't add/encrypt
+// credentials.
+window.ExtIsFirstRun = false;
+window.ExtCheckForUpdatesOnStartup = false;
+window.ExtUseGenerateThumbnails = true;
+window.ExtSaveLocationsInBrowser = true;
diff --git a/src/renderer/components/UnlockScreen.tsx b/src/renderer/components/UnlockScreen.tsx
new file mode 100644
index 000000000..355ac7470
--- /dev/null
+++ b/src/renderer/components/UnlockScreen.tsx
@@ -0,0 +1,279 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2026-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/>.
+ *
+ */
+
+/**
+ * Pre-store password gate. Rendered by `index.tsx` BEFORE `configureStore`
+ * when `probeBootstrap()` says password mode is active and encrypted data
+ * exists.
+ *
+ * The store doesn't exist yet, so we can't use `Ts*` wrappers (they rely
+ * on `useSelector(isDesktopMode)`). Instead we read the persisted theme
+ * settings synchronously and wrap the screen in the TagSpaces MUI theme
+ * (`createTSTheme`), then style raw MUI primitives with the same
+ * conventions (`AppConfig.defaultCSSRadius`, outlined surfaces, the
+ * TagSpaces brand mark) so the visual feel matches the rest of the app.
+ */
+
+import React, { useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { StyledEngineProvider, ThemeProvider } from '@mui/material/styles';
+import useMediaQuery from '@mui/material/useMediaQuery';
+import Box from '@mui/material/Box';
+import Paper from '@mui/material/Paper';
+import Typography from '@mui/material/Typography';
+import TextField from '@mui/material/TextField';
+import Button from '@mui/material/Button';
+import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
+import LogoIcon from '-/assets/icons/icon.png';
+import AppConfig from '-/AppConfig';
+import { setCredentialKey, setKeySource } from '-/services/encryptAtRestState';
+import { checkVerifier, deriveRawKey } from '-/services/secure-crypto';
+import {
+ readPersistedThemeSettings,
+ resetCredentialEncryptionStorage,
+ type KdfMeta,
+} from '-/services/credentialsBootstrap';
+import { createTSTheme } from '-/utils/Themes';
+
+export type UnlockScreenProps = {
+ kdf: KdfMeta;
+ verifierBlob: string;
+ onUnlocked: () => void;
+ onReset: () => void;
+};
+
+function UnlockScreenInner({
+ kdf,
+ verifierBlob,
+ onUnlocked,
+ onReset,
+}: UnlockScreenProps) {
+ const { t } = useTranslation();
+ const [password, setPassword] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const submit = async () => {
+ if (busy || password.length === 0) {
+ return;
+ }
+ setBusy(true);
+ setError(null);
+ try {
+ const rawKey = await deriveRawKey(password, kdf.saltB64, kdf.iter);
+ if (!checkVerifier(rawKey, verifierBlob)) {
+ setError(t('core:credentialsUnlockWrongPassword'));
+ setBusy(false);
+ return;
+ }
+ setCredentialKey(rawKey);
+ setKeySource('password');
+ onUnlocked();
+ } catch (e) {
+ setError(t('core:credentialsUnlockWrongPassword'));
+ setBusy(false);
+ }
+ };
+
+ const reset = () => {
+ // eslint-disable-next-line no-alert
+ const ok = window.confirm(t('core:credentialsUnlockResetConfirm'));
+ if (!ok) {
+ return;
+ }
+ resetCredentialEncryptionStorage();
+ setCredentialKey(null);
+ setKeySource('off');
+ onReset();
+ };
+
+ const r = AppConfig.defaultCSSRadius || '10px';
+
+ return (
+ <Box
+ sx={{
+ position: 'fixed',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: 2,
+ bgcolor: 'background.default',
+ color: 'text.primary',
+ }}
+ >
+ <Paper
+ variant="outlined"
+ sx={{
+ p: 3,
+ maxWidth: 440,
+ width: '100%',
+ borderRadius: '15px',
+ bgcolor: 'background.paper',
+ }}
+ >
+ <Box
+ sx={{
+ display: 'flex',
+ alignItems: 'center',
+ gap: 1.5,
+ mb: 2,
+ }}
+ >
+ <Box
+ sx={{
+ width: 44,
+ height: 44,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ borderRadius: r,
+ bgcolor: 'primary.main',
+ color: 'primary.contrastText',
+ }}
+ >
+ <LockOutlinedIcon />
+ </Box>
+ <Box sx={{ flexGrow: 1, minWidth: 0 }}>
+ <Typography variant="h6" sx={{ lineHeight: 1.1 }}>
+ TagSpaces
+ </Typography>
+ <Typography
+ variant="body2"
+ color="text.secondary"
+ sx={{ lineHeight: 1.1 }}
+ >
+ {t('core:credentialsUnlockTitle')}
+ </Typography>
+ </Box>
+ <Box
+ component="img"
+ src={LogoIcon}
+ alt="TagSpaces"
+ sx={{
+ width: 36,
+ height: 36,
+ flexShrink: 0,
+ display: 'block',
+ userSelect: 'none',
+ }}
+ draggable={false}
+ />
+ </Box>
+ <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
+ {t('core:credentialsUnlockSubtitle')}
+ </Typography>
+ <TextField
+ autoFocus
+ fullWidth
+ margin="normal"
+ size="small"
+ type="password"
+ label={t('core:aesPassword')}
+ value={password}
+ error={!!error}
+ helperText={error || ' '}
+ onChange={(e) => {
+ setPassword(e.target.value);
+ if (error) {
+ setError(null);
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') {
+ submit();
+ }
+ }}
+ disabled={busy}
+ data-tid="credentialsUnlockPasswordTID"
+ slotProps={{
+ input: {
+ autoCorrect: 'off',
+ autoCapitalize: 'none',
+ sx: { borderRadius: r },
+ },
+ }}
+ />
+ <Box sx={{ display: 'flex', gap: 1, mt: 1, alignItems: 'center' }}>
+ <Button
+ variant="contained"
+ disableElevation
+ onClick={submit}
+ disabled={busy || password.length === 0}
+ data-tid="credentialsUnlockButtonTID"
+ sx={{ borderRadius: r, textTransform: 'none' }}
+ >
+ {t('core:credentialsUnlockButton')}
+ </Button>
+ <Box sx={{ flex: 1 }} />
+ <Button
+ variant="text"
+ color="error"
+ size="small"
+ onClick={reset}
+ disabled={busy}
+ data-tid="credentialsUnlockResetTID"
+ sx={{ textTransform: 'none' }}
+ >
+ {t('core:credentialsUnlockForgot')}
+ </Button>
+ </Box>
+ </Paper>
+ </Box>
+ );
+}
+
+export default function UnlockScreen({
+ kdf,
+ verifierBlob,
+ onUnlocked,
+ onReset,
+}: UnlockScreenProps) {
+ // Read theme settings from persist:root synchronously (we're pre-store)
+ // and rebuild the same MUI theme the app will use after rehydration.
+ // `useMediaQuery` is React-context-only (window.matchMedia under the
+ // hood) — it works fine without a Redux store.
+ const themeSettings = useMemo(() => readPersistedThemeSettings(), []);
+ const systemDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
+ const theme = useMemo(() => {
+ const lightTheme = createTSTheme(themeSettings.currentRegularTheme, false);
+ const darkTheme = createTSTheme(themeSettings.currentDarkTheme, true);
+ switch (themeSettings.currentTheme) {
+ case 'dark':
+ return darkTheme;
+ case 'system':
+ return systemDarkMode ? darkTheme : lightTheme;
+ case 'light':
+ default:
+ return lightTheme;
+ }
+ }, [themeSettings, systemDarkMode]);
+
+ return (
+ <StyledEngineProvider injectFirst>
+ <ThemeProvider theme={theme}>
+ <UnlockScreenInner
+ kdf={kdf}
+ verifierBlob={verifierBlob}
+ onUnlocked={onUnlocked}
+ onReset={onReset}
+ />
+ </ThemeProvider>
+ </StyledEngineProvider>
+ );
+}
diff --git a/src/renderer/components/dialogs/CredentialsPasswordSetupDialog.tsx b/src/renderer/components/dialogs/CredentialsPasswordSetupDialog.tsx
new file mode 100644
index 000000000..a9ff59766
--- /dev/null
+++ b/src/renderer/components/dialogs/CredentialsPasswordSetupDialog.tsx
@@ -0,0 +1,189 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2026-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/>.
+ *
+ */
+
+/**
+ * Modal that asks the user to create a password for at-rest credential
+ * encryption (web; or Electron fallback when keychain is unavailable).
+ * Mirrors the password fields + strength meter already used in
+ * ExportImportPanel — reuses `evaluatePasswordStrength`.
+ *
+ * The dialog only collects the password and hands it to the parent, which
+ * runs the actual enable flow (KDF, KDF-meta storage, key-source toggle,
+ * flush + scrub).
+ */
+
+import React, { useEffect, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import useMediaQuery from '@mui/material/useMediaQuery';
+import Dialog from '@mui/material/Dialog';
+import DialogContent from '@mui/material/DialogContent';
+import Paper from '@mui/material/Paper';
+import LinearProgress from '@mui/material/LinearProgress';
+import Box from '@mui/material/Box';
+import Typography from '@mui/material/Typography';
+import AppConfig from '-/AppConfig';
+import DraggablePaper from '-/components/DraggablePaper';
+import TsButton from '-/components/TsButton';
+import TsTextField from '-/components/TsTextField';
+import TsDialogActions from '-/components/dialogs/components/TsDialogActions';
+import TsDialogTitle from '-/components/dialogs/components/TsDialogTitle';
+import { evaluatePasswordStrength } from '-/services/export-import-validators';
+
+export type CredentialsPasswordSetupDialogProps = {
+ open: boolean;
+ busy?: boolean;
+ onCancel: () => void;
+ onSubmit: (password: string) => void;
+};
+
+const STRENGTH_COLOR: Record<
+ 'weak' | 'fair' | 'good' | 'strong',
+ 'error' | 'warning' | 'info' | 'success'
+> = {
+ weak: 'error',
+ fair: 'warning',
+ good: 'info',
+ strong: 'success',
+};
+
+export default function CredentialsPasswordSetupDialog({
+ open,
+ busy,
+ onCancel,
+ onSubmit,
+}: CredentialsPasswordSetupDialogProps) {
+ const { t } = useTranslation();
+ const smallScreen = useMediaQuery('(max-width: 700px)');
+ const [password, setPassword] = useState('');
+ const [confirm, setConfirm] = useState('');
+
+ const strength = useMemo(
+ () => evaluatePasswordStrength(password),
+ [password],
+ );
+ const mismatch = confirm.length > 0 && confirm !== password;
+ const canSubmit = !busy && password.length > 0 && !mismatch && strength.ok;
+
+ const reset = () => {
+ setPassword('');
+ setConfirm('');
+ };
+
+ // Clear local state every time the dialog closes (any path: submit,
+ // cancel, parent dismiss). Otherwise reopening would still show the
+ // previous password text.
+ useEffect(() => {
+ if (!open) {
+ reset();
+ }
+ }, [open]);
+
+ const submit = () => {
+ if (!canSubmit) {
+ return;
+ }
+ onSubmit(password);
+ };
+
+ const cancel = () => {
+ reset();
+ onCancel();
+ };
+
+ return (
+ <Dialog
+ open={open}
+ fullScreen={smallScreen}
+ keepMounted
+ scroll="paper"
+ PaperComponent={smallScreen ? Paper : DraggablePaper}
+ onClose={cancel}
+ >
+ <TsDialogTitle
+ dialogTitle={t('core:credentialsSetupTitle')}
+ closeButtonTestId="closeCredentialsSetupTID"
+ onClose={cancel}
+ />
+ <DialogContent sx={{ minWidth: smallScreen ? undefined : 420 }}>
+ <Typography variant="body2" color="text.secondary" gutterBottom>
+ {t('core:credentialsSetupSubtitle')}
+ </Typography>
+ <TsTextField
+ name="credentialsPassword"
+ autoFocus
+ label={t('core:aesPassword')}
+ type="password"
+ value={password}
+ onChange={(e: any) => setPassword(e.target.value)}
+ data-tid="credentialsPasswordTID"
+ slotProps={{
+ input: { autoCorrect: 'off', autoCapitalize: 'none' },
+ }}
+ />
+ <Box sx={{ mt: 1, mb: 1 }}>
+ <LinearProgress
+ variant="determinate"
+ value={Math.min(100, (strength.score / 4) * 100)}
+ color={STRENGTH_COLOR[strength.label]}
+ sx={{ height: 6, borderRadius: 3 }}
+ />
+ <Typography
+ variant="caption"
+ color={strength.ok ? 'text.secondary' : 'error'}
+ >
+ {!strength.ok && password.length > 0
+ ? t('core:credentialsPasswordTooWeak')
+ : ' '}
+ </Typography>
+ </Box>
+ <TsTextField
+ name="credentialsPasswordConfirm"
+ label={t('core:retypePassword')}
+ type="password"
+ value={confirm}
+ error={mismatch}
+ helperText={mismatch ? t('core:credentialsPasswordsMismatch') : ' '}
+ onChange={(e: any) => setConfirm(e.target.value)}
+ data-tid="credentialsPasswordConfirmTID"
+ slotProps={{
+ input: { autoCorrect: 'off', autoCapitalize: 'none' },
+ }}
+ onKeyDown={(e: React.KeyboardEvent) => {
+ if (e.key === 'Enter') {
+ submit();
+ }
+ }}
+ />
+ </DialogContent>
+ <TsDialogActions>
+ <TsButton data-tid="cancelCredentialsSetupTID" onClick={cancel}>
+ {t('core:cancel')}
+ </TsButton>
+ <TsButton
+ variant="contained"
+ data-tid="submitCredentialsSetupTID"
+ onClick={submit}
+ disabled={!canSubmit}
+ sx={{ marginLeft: AppConfig.defaultSpaceBetweenButtons }}
+ >
+ {t('core:credentialsSetupConfirmButton')}
+ </TsButton>
+ </TsDialogActions>
+ </Dialog>
+ );
+}
diff --git a/src/renderer/components/dialogs/components/SettingsGeneral.tsx b/src/renderer/components/dialogs/components/SettingsGeneral.tsx
index 0f740a5df..6ddb93e27 100644
--- a/src/renderer/components/dialogs/components/SettingsGeneral.tsx
+++ b/src/renderer/components/dialogs/components/SettingsGeneral.tsx
@@ -58,8 +58,18 @@ import {
import { actions as LocationActions } from '-/reducers/locations';
import {
getPersistorRef,
+ setCredentialKey,
setEncryptAtRestEnabled,
+ setKeySource,
} from '-/services/encryptAtRestState';
+import {
+ defaultKdfIterations,
+ deriveRawKey,
+ makeKdfSalt,
+ makeVerifier,
+} from '-/services/secure-crypto';
+import { isAnotherTabOpen } from '-/services/credentialsTabGuard';
+import CredentialsPasswordSetupDialog from '-/components/dialogs/CredentialsPasswordSetupDialog';
import { isWorkerAvailable, setLanguage } from '-/services/utils-io';
import { TS } from '-/tagspaces.namespace';
import { clearAllURLParams } from '-/utils/dom';
@@ -111,6 +121,7 @@ function SettingsGeneral() {
weak: boolean;
}>({ available: false, weak: false });
const [encryptBusy, setEncryptBusy] = useState<boolean>(false);
+ const [passwordSetupOpen, setPasswordSetupOpen] = useState<boolean>(false);
const tileServers: Array<TS.MapTileServer> = useSelector(getMapTileServers);
const [tileServerDialog, setTileServerDialog] = useState<any>(undefined);
const wsAlive = useRef<boolean>(null);
@@ -138,19 +149,152 @@ function SettingsGeneral() {
.then((status: { available: boolean; weak: boolean }) => {
if (status) {
setCredKeyStatus(status);
+ } else if (typeof window.crypto?.subtle !== 'undefined') {
+ // Electron without a usable keychain → password fallback is
+ // still available because Web Crypto subtle works.
+ setCredKeyStatus({ available: true, weak: true });
}
})
.catch(() => {
- setCredKeyStatus({ available: false, weak: false });
+ // safeStorage IPC failed: fall back to password mode iff Web
+ // Crypto subtle is available (e.g. unsigned macOS build).
+ setCredKeyStatus({
+ available: typeof window.crypto?.subtle !== 'undefined',
+ weak: true,
+ });
});
+ } else {
+ // Web (or any non-Electron): password mode only. Availability is
+ // gated on Web Crypto subtle being usable.
+ setCredKeyStatus({
+ available: typeof window.crypto?.subtle !== 'undefined',
+ weak: false,
+ });
}
}, []);
/**
- * Opt-in credential encryption. Enabling migrates the live store to
- * ciphertext and actively scrubs the now-obsolete plaintext — but only
- * when exactly one TagSpaces window is open (no concurrent localStorage
- * writer). Disabling rewrites everything back as plaintext.
+ * Best-effort multi-writer guard: Electron uses the existing
+ * getWindowCount IPC; web uses a BroadcastChannel handshake. Returns
+ * true when it's safe to mutate persist:root (only this tab/window).
+ */
+ const multiWriterOk = async (): Promise<boolean> => {
+ if (AppConfig.isElectron && window.electronIO?.ipcRenderer) {
+ try {
+ const count =
+ await window.electronIO.ipcRenderer.invoke('getWindowCount');
+ if (typeof count === 'number' && count > 1) {
+ return false;
+ }
+ } catch (e) {
+ /* best-effort */
+ }
+ return true;
+ }
+ try {
+ return !(await isAnotherTabOpen());
+ } catch (e) {
+ return true;
+ }
+ };
+
+ /**
+ * Run the enable flow for a given key source. `rawKey` is required for
+ * password mode (already derived by the password-setup dialog).
+ */
+ const performEnable = async (
+ targetKeySource: 'keychain' | 'password',
+ rawKey: Uint8Array | null,
+ ): Promise<void> => {
+ const persistor = getPersistorRef();
+ if (!persistor) {
+ showNotification(t('core:credentialsEncryptionUnavailable'), 'error');
+ return;
+ }
+ setEncryptBusy(true);
+ try {
+ // Set singletons BEFORE flushing so the transform sees the right
+ // mode immediately on the next persist write.
+ if (targetKeySource === 'password' && rawKey) {
+ setCredentialKey(rawKey);
+ }
+ setKeySource(targetKeySource);
+ setEncryptAtRestEnabled(true);
+ dispatch(SettingsActions.setEncryptCredentialsAtRest(true));
+ dispatch(SettingsActions.setEncryptCredentialsKeySource(targetKeySource));
+ // Force a fresh reference on the locations slice so redux-persist
+ // re-serializes it through the now-active transform (its
+ // persistoid skips slices whose reference did not change).
+ dispatch(LocationActions.touchLocations());
+ await persistor.flush();
+ // Active scrub of the obsolete plaintext, IF the flush produced
+ // any ciphertext. (Multi-writer guard already passed.)
+ // redux-persist v5: pause() stops writes, persist() resumes.
+ // A "no tsenc: present" outcome here is legitimate: either the
+ // user has no whitelisted data yet, or the persisted slices that
+ // hold secrets are blacklisted on this platform (e.g. `locations`
+ // on web). Future writes will be encrypted by the transform as
+ // soon as there is something to encrypt — no revert needed.
+ const enc = localStorage.getItem('persist:root');
+ if (enc && enc.indexOf('tsenc:') !== -1) {
+ persistor.pause();
+ localStorage.removeItem('persist:root');
+ localStorage.setItem('persist:root', enc);
+ persistor.persist();
+ }
+ if (AppConfig.isElectron && window.electronIO?.ipcRenderer) {
+ try {
+ await window.electronIO.ipcRenderer.invoke('flushStorageData');
+ } catch (e) {
+ /* best-effort */
+ }
+ }
+ showNotification(t('core:credentialsEncryptionEnabled'), 'info', false);
+ } catch (e) {
+ console.error('encrypt-at-rest enable failed', e);
+ showNotification(t('core:credentialsEncryptionFailed'), 'error');
+ } finally {
+ setEncryptBusy(false);
+ }
+ };
+
+ /** Disable: rewrite plaintext, clear web password artifacts + key. */
+ const performDisable = async (): Promise<void> => {
+ const persistor = getPersistorRef();
+ if (!persistor) {
+ showNotification(t('core:credentialsEncryptionUnavailable'), 'error');
+ return;
+ }
+ setEncryptBusy(true);
+ try {
+ setEncryptAtRestEnabled(false);
+ setKeySource('off');
+ setCredentialKey(null);
+ dispatch(SettingsActions.setEncryptCredentialsAtRest(false));
+ dispatch(SettingsActions.setEncryptCredentialsKeySource('off'));
+ dispatch(LocationActions.touchLocations());
+ await persistor.flush();
+ try {
+ localStorage.removeItem('tsCredKdf');
+ localStorage.removeItem('tsCredVerify');
+ } catch (e) {
+ /* best-effort */
+ }
+ showNotification(t('core:credentialsEncryptionDisabled'), 'info');
+ } catch (e) {
+ console.error('encrypt-at-rest disable failed', e);
+ showNotification(t('core:credentialsEncryptionFailed'), 'error');
+ } finally {
+ setEncryptBusy(false);
+ }
+ };
+
+ /**
+ * Opt-in credential encryption. Enabling picks the strongest available
+ * key source (Electron `safeStorage` when usable, otherwise a
+ * user-defined password) and migrates the live store to ciphertext
+ * with a one-time plaintext scrub. Multi-writer guard ensures no
+ * concurrent window/tab races.
*/
const handleToggleEncryptAtRest = async () => {
if (encryptBusy) {
@@ -166,84 +310,72 @@ function SettingsGeneral() {
showNotification(t('core:credentialsEncryptionUnavailable'), 'error');
return;
}
- if (AppConfig.isElectron && window.electronIO?.ipcRenderer) {
+ if (!(await multiWriterOk())) {
+ showNotification(t('core:credentialsEncryptionSingleWindow'), 'warning');
+ return;
+ }
+ if (!enabling) {
+ openConfirmDialog(
+ t('core:confirm'),
+ t('core:credentialsEncryptionDisableConfirm'),
+ async (result: boolean) => {
+ if (result) {
+ await performDisable();
+ }
+ },
+ );
+ return;
+ }
+ // Enable: pick mode.
+ const electronKeychain =
+ AppConfig.isElectron &&
+ !!window.electronIO?.ipcRenderer &&
+ credKeyStatus.available &&
+ !credKeyStatus.weak;
+ if (electronKeychain) {
+ openConfirmDialog(
+ t('core:confirm'),
+ t('core:credentialsEncryptionEnableConfirm'),
+ async (result: boolean) => {
+ if (result) {
+ await performEnable('keychain', null);
+ }
+ },
+ );
+ } else {
+ // Web (or Electron without a usable keychain — e.g. unsigned macOS
+ // builds with hardenedRuntime). Collect a password, derive a key,
+ // then enable.
+ setPasswordSetupOpen(true);
+ }
+ };
+
+ const submitPasswordSetup = async (password: string) => {
+ setEncryptBusy(true);
+ try {
+ const saltB64 = makeKdfSalt();
+ const iter = defaultKdfIterations();
+ const rawKey = await deriveRawKey(password, saltB64, iter);
+ const verifierBlob = makeVerifier(rawKey);
try {
- const count =
- await window.electronIO.ipcRenderer.invoke('getWindowCount');
- if (typeof count === 'number' && count > 1) {
- showNotification(
- t('core:credentialsEncryptionSingleWindow'),
- 'warning',
- );
- return;
- }
+ localStorage.setItem(
+ 'tsCredKdf',
+ JSON.stringify({ saltB64, iter, algo: 'PBKDF2-SHA256' }),
+ );
+ localStorage.setItem('tsCredVerify', verifierBlob);
} catch (e) {
- /* fall through — guard is best-effort */
+ showNotification(t('core:credentialsEncryptionFailed'), 'error');
+ setEncryptBusy(false);
+ return;
}
+ setPasswordSetupOpen(false);
+ setEncryptBusy(false); // performEnable sets it again
+ await performEnable('password', rawKey);
+ } catch (e) {
+ console.error('credentialsSetup: deriveRawKey failed', e);
+ showNotification(t('core:credentialsEncryptionFailed'), 'error');
+ setEncryptBusy(false);
}
- openConfirmDialog(
- t('core:confirm'),
- enabling
- ? t('core:credentialsEncryptionEnableConfirm')
- : t('core:credentialsEncryptionDisableConfirm'),
- async (result) => {
- if (!result) {
- return;
- }
- setEncryptBusy(true);
- try {
- // Set the singleton before flushing so the redux-persist
- // transform sees the new mode immediately.
- setEncryptAtRestEnabled(enabling);
- dispatch(SettingsActions.setEncryptCredentialsAtRest(enabling));
- // The settings slice changed (the flag) so redux-persist will
- // re-serialize it, but the locations array reference did not —
- // its persistoid skips unchanged slices. Force a fresh reference
- // so locations are re-serialized through the transform too.
- dispatch(LocationActions.touchLocations());
- // Flush so the staged ciphertext reaches localStorage, then
- // pause so nothing rewrites plaintext during the scrub.
- await persistor.flush();
- if (enabling) {
- const enc = localStorage.getItem('persist:root');
- if (!enc || enc.indexOf('tsenc:v1:') === -1) {
- // Encryption did not take effect — revert, keep plaintext.
- setEncryptAtRestEnabled(false);
- dispatch(SettingsActions.setEncryptCredentialsAtRest(false));
- await persistor.flush();
- showNotification(t('core:credentialsEncryptionFailed'), 'error');
- return;
- }
- // Active one-time scrub of the obsolete plaintext (single
- // window guaranteed; in-memory state is the recovery source).
- // redux-persist v5: pause() stops writes, persist() resumes.
- persistor.pause();
- localStorage.removeItem('persist:root');
- localStorage.setItem('persist:root', enc);
- persistor.persist();
- if (window.electronIO?.ipcRenderer) {
- try {
- await window.electronIO.ipcRenderer.invoke('flushStorageData');
- } catch (e) {
- /* best-effort */
- }
- }
- showNotification(
- t('core:credentialsEncryptionEnabled'),
- 'info',
- false,
- );
- } else {
- showNotification(t('core:credentialsEncryptionDisabled'), 'info');
- }
- } catch (e) {
- console.error('encrypt-at-rest toggle failed', e);
- showNotification(t('core:credentialsEncryptionFailed'), 'error');
- } finally {
- setEncryptBusy(false);
- }
- },
- );
};
// --- Advanced settings handlers ---
@@ -1565,7 +1697,7 @@ function SettingsGeneral() {
</ListItem>
),
},
- AppConfig.isElectron && {
+ {
label: t('core:encryptCredentialsAtRest'),
jsx: (
<ListItem
@@ -1751,6 +1883,12 @@ function SettingsGeneral() {
isDefault={tileServerDialog.isDefault}
/>
)}
+ <CredentialsPasswordSetupDialog
+ open={passwordSetupOpen}
+ busy={encryptBusy}
+ onCancel={() => setPasswordSetupOpen(false)}
+ onSubmit={submitPasswordSetup}
+ />
</List>
</>
);
diff --git a/src/renderer/index.tsx b/src/renderer/index.tsx
index 88b1efb56..858db989d 100644
--- a/src/renderer/index.tsx
+++ b/src/renderer/index.tsx
@@ -20,11 +20,16 @@ import { createRoot } from 'react-dom/client';
// import Root from './containers/Root';
import configureStore from './store/configureStore';
import { installGlobalErrorHandlers } from './services/globalErrorHandlers';
+import {
+ probeBootstrap,
+ seedKeySourceFromProbe,
+} from './services/credentialsBootstrap';
+import { installTabGuardListener } from './services/credentialsTabGuard';
+import UnlockScreen from './components/UnlockScreen';
import './app.global.css';
installGlobalErrorHandlers();
-
-const { store, persistor } = configureStore({});
+installTabGuardListener();
document.addEventListener('contextmenu', (event) => event.preventDefault());
@@ -36,9 +41,42 @@ if (process.env.NODE_ENV === 'production') {
const container = document.getElementById('root') as HTMLElement;
const root = createRoot(container);
-// https://github.com/electron-react-boilerplate/electron-react-boilerplate/issues/2395#issuecomment-651328378
-const Root = require('./containers/Root').default;
-root.render(<Root store={store} persistor={persistor} />);
+
+// Synchronous: seed the at-rest key-source singleton BEFORE configureStore
+// so redux-persist's outbound transform sees the right provider during
+// rehydration. Critical for shipped Electron-keychain users — without
+// this, their encrypted credentials would be blanked on first run after
+// this build's upgrade.
+const credBootstrap = probeBootstrap();
+seedKeySourceFromProbe(credBootstrap);
+
+function bootApp() {
+ // Re-probe in case the unlock/reset flow modified storage. Idempotent
+ // and cheap (sync localStorage reads only).
+ seedKeySourceFromProbe(probeBootstrap());
+ const { store, persistor } = configureStore({});
+ // https://github.com/electron-react-boilerplate/electron-react-boilerplate/issues/2395#issuecomment-651328378
+ const Root = require('./containers/Root').default;
+ root.render(<Root store={store} persistor={persistor} />);
+}
+
+if (
+ credBootstrap.needsUnlock &&
+ credBootstrap.kdf &&
+ credBootstrap.verifierBlob
+) {
+ const { kdf, verifierBlob } = credBootstrap;
+ root.render(
+ <UnlockScreen
+ kdf={kdf}
+ verifierBlob={verifierBlob}
+ onUnlocked={bootApp}
+ onReset={bootApp}
+ />,
+ );
+} else {
+ bootApp();
+}
/*// calling IPC exposed from preload script
window.electron.ipcRenderer.once('ipc-example', (arg) => {
diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.json
index aefdc1d11..ac2fecc44 100644
--- a/src/renderer/locales/en/core.json
+++ b/src/renderer/locales/en/core.json
@@ -151,13 +151,24 @@
"encryptCredentialsAtRestTooltip": "Encrypts location credentials (S3 keys) and map tile server URLs stored on this device, using your operating system's keychain. Desktop only.",
"encryptCredentialsAtRestWeakTooltip": "Your system keyring is unavailable, so the key is only weakly protected (obfuscated). For strong protection, unlock your GNOME Keyring / KWallet.",
"credentialsEncryptionUnavailable": "Credential encryption is not available on this system.",
- "credentialsEncryptionSingleWindow": "Please close all other TagSpaces windows before changing this setting.",
+ "credentialsEncryptionSingleWindow": "Please close all other TagSpaces windows or tabs before changing this setting.",
"credentialsEncryptionEnableConfirm": "Stored credentials will be encrypted using this device's keychain and the existing plaintext will be scrubbed. The encrypted data cannot be moved to another machine (use the encrypted export/import for that). Continue?",
"credentialsEncryptionDisableConfirm": "Stored credentials will be written back to disk unencrypted. Continue?",
"credentialsEncryptionEnabled": "Stored credentials are now encrypted. Note: a previous backup may still contain plaintext — consider rotating the affected keys for maximum safety.",
"credentialsEncryptionDisabled": "Stored credentials are no longer encrypted.",
"credentialsEncryptionFailed": "Could not enable credential encryption. Your credentials were left unchanged.",
"credentialsCouldNotBeUnlocked": "Could not unlock saved credentials for: {{names}}. Please re-enter them or import from an encrypted backup.",
+ "credentialsUnlockTitle": "Unlock stored credentials",
+ "credentialsUnlockSubtitle": "Enter the password you used to encrypt your stored credentials on this device.",
+ "credentialsUnlockButton": "Unlock",
+ "credentialsUnlockWrongPassword": "Incorrect password.",
+ "credentialsUnlockForgot": "Forgot password? Reset and continue",
+ "credentialsUnlockResetConfirm": "Resetting will delete the encrypted credentials stored on this device. Your other settings and data are kept, but you will need to re-enter the affected credentials (or import from an encrypted backup). Continue?",
+ "credentialsSetupTitle": "Set a password for stored credentials",
+ "credentialsSetupSubtitle": "Stored credentials will be encrypted on this device using this password. There is no recovery option — keep the password safe.",
+ "credentialsSetupConfirmButton": "Set password and encrypt",
+ "credentialsPasswordsMismatch": "Passwords do not match.",
+ "credentialsPasswordTooWeak": "Choose a stronger password.",
"encryptionRecommended": "Encryption is recommended because the selection contains credentials",
"disableEncryptionWarning": "Warning: the export will contain unencrypted credentials",
"passwordStrength": "Password strength",
diff --git a/src/renderer/reducers/settings-default.ts b/src/renderer/reducers/settings-default.ts
index 9ae298f76..90d247cda 100644
--- a/src/renderer/reducers/settings-default.ts
+++ b/src/renderer/reducers/settings-default.ts
@@ -101,6 +101,7 @@ export default {
interfaceLanguage: 'en',
useTrashCan: true,
encryptCredentialsAtRest: false,
+ encryptCredentialsKeySource: 'off',
useOCR: false,
useTextExtraction: false,
useGenerateThumbnails: true,
diff --git a/src/renderer/reducers/settings.ts b/src/renderer/reducers/settings.ts
index a113a2075..55ecc3069 100644
--- a/src/renderer/reducers/settings.ts
+++ b/src/renderer/reducers/settings.ts
@@ -47,6 +47,8 @@ export const types = {
SET_DEVMODE: 'SETTINGS/SET_DEVMODE',
SET_ENABLE_WS: 'SETTINGS/SET_ENABLE_WS',
SET_ENCRYPT_CREDENTIALS_AT_REST: 'SETTINGS/SET_ENCRYPT_CREDENTIALS_AT_REST',
+ SET_ENCRYPT_CREDENTIALS_KEY_SOURCE:
+ 'SETTINGS/SET_ENCRYPT_CREDENTIALS_KEY_SOURCE',
WARNING_OPENING_FILES_EXTERNALLY: 'SETTINGS/WARNING_OPENING_FILES_EXTERNALLY',
SET_SAVE_TAGS_IN_LOCATION: 'SETTINGS/SET_SAVE_TAGS_IN_LOCATION',
SET_TAG_DELIMITER: 'SETTINGS/SET_TAG_DELIMITER',
@@ -239,6 +241,12 @@ export default (state: any = defaultSettings, action: any) => {
encryptCredentialsAtRest: action.encryptCredentialsAtRest,
};
}
+ case types.SET_ENCRYPT_CREDENTIALS_KEY_SOURCE: {
+ return {
+ ...state,
+ encryptCredentialsKeySource: action.encryptCredentialsKeySource,
+ };
+ }
case types.WARNING_OPENING_FILES_EXTERNALLY: {
return {
...state,
@@ -749,6 +757,12 @@ export const actions = {
type: types.SET_ENCRYPT_CREDENTIALS_AT_REST,
encryptCredentialsAtRest,
}),
+ setEncryptCredentialsKeySource: (
+ encryptCredentialsKeySource: 'off' | 'keychain' | 'password',
+ ) => ({
+ type: types.SET_ENCRYPT_CREDENTIALS_KEY_SOURCE,
+ encryptCredentialsKeySource,
+ }),
setWarningOpeningFilesExternally: (
warningOpeningFilesExternally: boolean,
) => ({
@@ -1090,6 +1104,12 @@ export const getLastLinkType = (state: any): 'ts' | 'relative' => {
export const getEnableWS = (state: any) => state.settings.enableWS;
export const getEncryptCredentialsAtRest = (state: any) =>
state.settings.encryptCredentialsAtRest === true;
+export const getEncryptCredentialsKeySource = (
+ state: any,
+): 'off' | 'keychain' | 'password' => {
+ const v = state.settings.encryptCredentialsKeySource;
+ return v === 'keychain' || v === 'password' ? v : 'off';
+};
export const getDesktopMode = (state: any) => {
if (typeof AppConfig.ExtDisplayMode === 'undefined') {
return state.settings.desktopMode;
diff --git a/src/renderer/services/credentialsBootstrap.ts b/src/renderer/services/credentialsBootstrap.ts
new file mode 100644
index 000000000..04e21718c
--- /dev/null
+++ b/src/renderer/services/credentialsBootstrap.ts
@@ -0,0 +1,302 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2026-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/>.
+ *
+ */
+
+/**
+ * Pre-store bootstrap probe for the at-rest credential encryption feature.
+ *
+ * Runs SYNCHRONOUSLY in index.tsx BEFORE `configureStore` so the
+ * `encryptAtRestState` singleton has the right `keySource` by the time
+ * redux-persist rehydration calls the transform's outbound. Critical: a
+ * shipped Electron-keychain user with `encryptCredentialsAtRest=true` and
+ * no `encryptCredentialsKeySource` yet must be inferred as `'keychain'`
+ * here — otherwise the gate sees `'off'`, the keychain provider isn't
+ * picked, and rehydrate would blank every saved credential.
+ */
+
+import AppConfig from '-/AppConfig';
+import { type KeySource, setKeySource } from '-/services/encryptAtRestState';
+
+const PERSIST_ROOT_KEY = 'persist:root';
+const KDF_LS_KEY = 'tsCredKdf';
+const VERIFIER_LS_KEY = 'tsCredVerify';
+
+/**
+ * Single inference rule shared between the pre-store probe and the
+ * post-rehydrate store subscription, so the singleton stays consistent
+ * across the boot sequence. Shipped Electron-keychain users (flag=true,
+ * source missing from their saved settings) are inferred as 'keychain'.
+ */
+export function inferKeySource(
+ enabled: boolean,
+ explicitSource: string | undefined,
+ isElectron: boolean,
+): KeySource {
+ if (!enabled) {
+ return 'off';
+ }
+ if (explicitSource === 'keychain' || explicitSource === 'password') {
+ return explicitSource as KeySource;
+ }
+ return isElectron ? 'keychain' : 'off';
+}
+
+export type KdfMeta = {
+ saltB64: string;
+ iter: number;
+ algo: string;
+};
+
+export type BootstrapProbe = {
+ hasEncryptedData: boolean;
+ /** Inferred mode from persisted state + platform. */
+ inferredSource: KeySource;
+ /** True if password mode is active and the unlock screen is required. */
+ needsUnlock: boolean;
+ /** PBKDF2 params + verifier blob — only present in password mode. */
+ kdf?: KdfMeta;
+ verifierBlob?: string;
+};
+
+/** Safe localStorage.getItem (web/Electron only — no-op if unavailable). */
+function readLs(key: string): string | null {
+ try {
+ if (typeof window === 'undefined' || !window.localStorage) {
+ return null;
+ }
+ return window.localStorage.getItem(key);
+ } catch (e) {
+ return null;
+ }
+}
+
+/** Parse JSON, returning undefined on failure (never throws). */
+function safeJson<T = any>(text: string | null | undefined): T | undefined {
+ if (!text) {
+ return undefined;
+ }
+ try {
+ return JSON.parse(text) as T;
+ } catch (e) {
+ return undefined;
+ }
+}
+
+/**
+ * Read the persisted `settings` substate from `persist:root` without going
+ * through redux-persist (we're pre-store). redux-persist v5 stores each
+ * slice as a JSON-encoded string inside an outer JSON object.
+ */
+function readPersistedSettings(): any | undefined {
+ const root = safeJson<Record<string, string>>(readLs(PERSIST_ROOT_KEY));
+ if (!root || typeof root.settings !== 'string') {
+ return undefined;
+ }
+ return safeJson(root.settings);
+}
+
+/**
+ * Quick string scan: any `tsenc:` prefix anywhere inside `persist:root`
+ * means there is encrypted data in localStorage. Robust against the
+ * exact serialization shape (settings vs locations slice).
+ */
+function persistRootContainsEncrypted(): boolean {
+ const raw = readLs(PERSIST_ROOT_KEY);
+ return typeof raw === 'string' && raw.indexOf('tsenc:') !== -1;
+}
+
+function readKdf(): { kdf?: KdfMeta; verifierBlob?: string } {
+ const kdf = safeJson<KdfMeta>(readLs(KDF_LS_KEY));
+ const verifierBlob = readLs(VERIFIER_LS_KEY) || undefined;
+ if (!kdf || typeof kdf.saltB64 !== 'string' || typeof kdf.iter !== 'number') {
+ return {};
+ }
+ return { kdf, verifierBlob: verifierBlob || undefined };
+}
+
+/**
+ * Synchronous probe — no async, no IPC. Reads localStorage only.
+ * Determines the at-rest mode the app should boot in BEFORE the store is
+ * created so rehydrate works correctly.
+ */
+export function probeBootstrap(): BootstrapProbe {
+ const settings = readPersistedSettings();
+ const enabled = settings?.encryptCredentialsAtRest === true;
+ const explicit = settings?.encryptCredentialsKeySource;
+ const hasEncryptedData = persistRootContainsEncrypted();
+ const inferredSource = inferKeySource(
+ enabled,
+ explicit,
+ AppConfig.isElectron,
+ );
+
+ if (inferredSource !== 'password') {
+ return { hasEncryptedData, inferredSource, needsUnlock: false };
+ }
+ const { kdf, verifierBlob } = readKdf();
+ const needsUnlock = hasEncryptedData && !!kdf && !!verifierBlob;
+ return {
+ hasEncryptedData,
+ inferredSource: 'password',
+ needsUnlock,
+ kdf,
+ verifierBlob,
+ };
+}
+
+/**
+ * Apply the probe's inferred mode to the singleton. Call once, right
+ * before `configureStore`. The store subscription installed in
+ * configureStore will keep the singleton in sync from then on.
+ */
+export function seedKeySourceFromProbe(probe: BootstrapProbe): void {
+ setKeySource(probe.inferredSource);
+}
+
+export type PersistedThemeSettings = {
+ currentTheme: 'light' | 'dark' | 'system';
+ currentRegularTheme: string;
+ currentDarkTheme: string;
+};
+
+/**
+ * Read the persisted theme settings synchronously — used by the
+ * pre-store UnlockScreen so it can wrap itself in the TagSpaces MUI
+ * theme that matches the app the user will boot into. Falls back to
+ * sensible defaults if persist:root is unreadable.
+ */
+export function readPersistedThemeSettings(): PersistedThemeSettings {
+ const fallback: PersistedThemeSettings = {
+ currentTheme: 'light',
+ currentRegularTheme: 'legacy',
+ currentDarkTheme: 'darklegacy',
+ };
+ const settings = readPersistedSettings();
+ if (!settings) {
+ return fallback;
+ }
+ const ct = settings.currentTheme;
+ return {
+ currentTheme:
+ ct === 'light' || ct === 'dark' || ct === 'system' ? ct : 'light',
+ currentRegularTheme:
+ typeof settings.currentRegularTheme === 'string'
+ ? settings.currentRegularTheme
+ : fallback.currentRegularTheme,
+ currentDarkTheme:
+ typeof settings.currentDarkTheme === 'string'
+ ? settings.currentDarkTheme
+ : fallback.currentDarkTheme,
+ };
+}
+
+/**
+ * Fields the credentialsTransform encrypts — duplicated here for the
+ * pre-store reset path (cannot import the transform's REGISTRY without
+ * pulling in redux-persist + i18n side effects this early).
+ */
+const LOCATION_SECRET_FIELDS = [
+ 'secretAccessKey',
+ 'accessKeyId',
+ 'sessionToken',
+ 'encryptionKey',
+ 'password',
+];
+const TILE_SECRET_FIELDS = ['serverURL', 'serverInfo'];
+
+function scrubEncryptedFields(sub: any, sliceKey: string): any {
+ if (sliceKey === 'locations' && Array.isArray(sub)) {
+ return sub.map((loc: any) => {
+ if (!loc || typeof loc !== 'object') {
+ return loc;
+ }
+ const out = { ...loc };
+ LOCATION_SECRET_FIELDS.forEach((f) => {
+ if (typeof out[f] === 'string' && out[f].startsWith('tsenc:')) {
+ out[f] = '';
+ }
+ });
+ return out;
+ });
+ }
+ if (
+ sliceKey === 'settings' &&
+ sub &&
+ typeof sub === 'object' &&
+ Array.isArray(sub.mapTileServers)
+ ) {
+ return {
+ ...sub,
+ mapTileServers: sub.mapTileServers.map((srv: any) => {
+ if (!srv || typeof srv !== 'object') {
+ return srv;
+ }
+ const out = { ...srv };
+ TILE_SECRET_FIELDS.forEach((f) => {
+ if (typeof out[f] === 'string' && out[f].startsWith('tsenc:')) {
+ out[f] = '';
+ }
+ });
+ return out;
+ }),
+ };
+ }
+ return sub;
+}
+
+/**
+ * "Forgot password" reset path used by the UnlockScreen. Strips every
+ * `tsenc:*` value from the persisted whitelisted slices (locations
+ * credential fields + `settings.mapTileServers[*].serverURL/.serverInfo`),
+ * deletes the KDF metadata + verifier, and turns the feature flag off in
+ * the persisted settings — so the next boot is clean, unencrypted, and
+ * does NOT hit the unlock screen. Other settings and data are preserved.
+ */
+export function resetCredentialEncryptionStorage(): void {
+ try {
+ if (typeof window === 'undefined' || !window.localStorage) {
+ return;
+ }
+ const rawRoot = window.localStorage.getItem(PERSIST_ROOT_KEY);
+ const root = safeJson<Record<string, string>>(rawRoot);
+ if (root && typeof root === 'object') {
+ ['locations', 'settings'].forEach((sliceKey) => {
+ if (typeof root[sliceKey] !== 'string') {
+ return;
+ }
+ const parsed = safeJson<any>(root[sliceKey]);
+ if (parsed === undefined) {
+ return;
+ }
+ root[sliceKey] = JSON.stringify(scrubEncryptedFields(parsed, sliceKey));
+ });
+ if (typeof root.settings === 'string') {
+ const settings = safeJson<any>(root.settings);
+ if (settings && typeof settings === 'object') {
+ settings.encryptCredentialsAtRest = false;
+ settings.encryptCredentialsKeySource = 'off';
+ root.settings = JSON.stringify(settings);
+ }
+ }
+ window.localStorage.setItem(PERSIST_ROOT_KEY, JSON.stringify(root));
+ }
+ window.localStorage.removeItem(KDF_LS_KEY);
+ window.localStorage.removeItem(VERIFIER_LS_KEY);
+ } catch (e) {
+ /* best-effort */
+ }
+}
diff --git a/src/renderer/services/credentialsTabGuard.ts b/src/renderer/services/credentialsTabGuard.ts
new file mode 100644
index 000000000..2c3c3b4fa
--- /dev/null
+++ b/src/renderer/services/credentialsTabGuard.ts
@@ -0,0 +1,118 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2026-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/>.
+ *
+ */
+
+/**
+ * Best-effort multi-tab handshake for the web enable/disable + scrub flow.
+ * Electron has `getWindowCount` IPC for the same purpose; the web fallback
+ * is a `BroadcastChannel` ping/pong: each tab listens for pings and
+ * responds with a pong; an active tab issues a ping and refuses to enable
+ * if any other tab pongs within a short window.
+ *
+ * Implementation note: we use a SINGLE channel per tab for both the
+ * responder and the prober. The BroadcastChannel spec exempts the same
+ * channel instance from receiving its own messages, so this tab can't
+ * ping itself. If we used two instances (one for responder, one for
+ * prober) the responder would happily pong the prober within the same
+ * tab — a false positive that would block enable on a single-tab session.
+ */
+
+const CHANNEL_NAME = 'ts-encrypt-tabs';
+const PING_TIMEOUT_MS = 120;
+
+type Msg = { type: 'ping' | 'pong'; id: string };
+
+let channel: BroadcastChannel | null = null;
+
+function ensureChannel(): BroadcastChannel | null {
+ if (channel) {
+ return channel;
+ }
+ if (typeof BroadcastChannel === 'undefined') {
+ return null;
+ }
+ try {
+ const ch = new BroadcastChannel(CHANNEL_NAME);
+ ch.addEventListener('message', (event: MessageEvent<Msg>) => {
+ const data = event?.data;
+ if (data && data.type === 'ping' && typeof data.id === 'string') {
+ try {
+ ch.postMessage({ type: 'pong', id: data.id });
+ } catch (e) {
+ /* ignore */
+ }
+ }
+ });
+ channel = ch;
+ return channel;
+ } catch (e) {
+ channel = null;
+ return null;
+ }
+}
+
+/** Idempotently install the responder listener (call once at app bootstrap). */
+export function installTabGuardListener(): void {
+ ensureChannel();
+}
+
+/**
+ * Returns true if another tab on the same origin responded within the
+ * timeout. Best-effort: returns false if BroadcastChannel is unavailable
+ * or no other tab pongs in time.
+ */
+export async function isAnotherTabOpen(): Promise<boolean> {
+ const ch = ensureChannel();
+ if (!ch) {
+ return false;
+ }
+ return new Promise<boolean>((resolve) => {
+ let timer: any = null;
+ let listener: ((event: MessageEvent<Msg>) => void) | null = null;
+ const id = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const done = (result: boolean) => {
+ if (timer) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ if (listener) {
+ try {
+ ch.removeEventListener('message', listener as any);
+ } catch (e) {
+ /* ignore */
+ }
+ listener = null;
+ }
+ resolve(result);
+ };
+ try {
+ listener = (event: MessageEvent<Msg>) => {
+ const data = event?.data;
+ if (data && data.type === 'pong' && data.id === id) {
+ done(true);
+ }
+ };
+ ch.addEventListener('message', listener as any);
+ // The same channel instance never receives its own postMessage,
+ // so this can't be answered by our own responder in this tab.
+ ch.postMessage({ type: 'ping', id });
+ timer = setTimeout(() => done(false), PING_TIMEOUT_MS);
+ } catch (e) {
+ done(false);
+ }
+ });
+}
diff --git a/src/renderer/services/credentialsTransform.ts b/src/renderer/services/credentialsTransform.ts
index 74b305fc6..ae869b7c4 100644
--- a/src/renderer/services/credentialsTransform.ts
+++ b/src/renderer/services/credentialsTransform.ts
@@ -17,27 +17,40 @@
*/
/**
- * redux-persist transform that encrypts credential fields at rest (Electron,
- * opt-in). The master key never enters the renderer — encrypt/decrypt run in
- * the main process via synchronous IPC; only the resulting strings cross.
+ * redux-persist transform that encrypts credential fields at rest (opt-in).
+ * Synchronous; uses a pluggable provider:
*
- * - inbound (store → localStorage): encrypt, only if Electron AND the opt-in
- * flag is on. All-or-nothing per slice (never write a partial mix).
- * - outbound (localStorage → store): always attempt to decrypt tagged values
- * (flag-independent) so disabling the feature / loading after a previous
- * enable still works. Legacy plaintext passes through untouched.
+ * - **Keychain** (Electron): a 256-bit key sealed in `safeStorage` lives in
+ * the main process; the transform calls `getSync('encrypt|decryptCredentials')`.
+ * Wire prefix `tsenc:v1:` (AES-256-GCM via Node crypto in main).
+ * - **Password** (web; or Electron fallback): a 64-byte raw key derived once
+ * from the user password at unlock lives in a renderer module singleton;
+ * the transform encrypts/decrypts in-process via the sync raw-key cipher.
+ * Wire prefix `tsenc:p1:` (AES-256-CBC + HMAC-SHA256 via CryptoJS).
+ *
+ * - inbound (store → localStorage): encrypt ONLY when the opt-in flag is on
+ * AND a provider is available. All-or-nothing per slice.
+ * - outbound (localStorage → store): always attempt to decrypt anything
+ * carrying a `tsenc:` prefix; non-`tsenc:` (legacy plaintext) passes
+ * through. The provider returns null for values it can't unlock; that
+ * field is blanked (never crashes rehydrate).
*
* Scope is a declarative registry — one entry per persisted slice.
*/
import { createTransform } from 'redux-persist';
import AppConfig from '-/AppConfig';
-import { isEncryptAtRestEnabled } from '-/services/encryptAtRestState';
+import {
+ getCredentialKey,
+ getKeySource,
+ hasCredentialKey,
+ isEncryptAtRestEnabled,
+} from '-/services/encryptAtRestState';
+import { decryptWithRawKey, encryptWithRawKey } from '-/services/secure-crypto';
import { notifyUser } from '-/services/globalErrorHandlers';
-// Mirrors RAWENC_PREFIX in src/main/credentialCipher.ts (no shared module
-// between renderer and main).
-const PREFIX = 'tsenc:v1:';
+/** Any value carrying any at-rest scheme prefix. */
+const ENC_PREFIX = 'tsenc:';
type Registry = {
[sliceKey: string]: {
@@ -67,7 +80,13 @@ const REGISTRY: Registry = {
type SyncResult = { available: boolean; values?: (string | null)[] } | null;
export type SyncFn = (channel: string, values: string[]) => SyncResult;
-const defaultSync: SyncFn = (channel, values) => {
+/* -------------------------- providers ------------------------------ */
+
+/**
+ * Electron-keychain provider — the SHIPPED path. Behavior must remain
+ * byte-for-byte identical: route every batch through the existing sync IPC.
+ */
+function keychainSync(channel: string, values: string[]): SyncResult {
const io = (window as any).electronIO?.ipcRenderer;
if (!AppConfig.isElectron || !io || typeof io.getSync !== 'function') {
return null;
@@ -78,8 +97,53 @@ const defaultSync: SyncFn = (channel, values) => {
console.warn('credentialsTransform: sync IPC failed', e);
return null;
}
+}
+
+/**
+ * In-process password provider. Uses the in-memory raw key + the
+ * synchronous AES-256-CBC + HMAC cipher in secure-crypto.ts.
+ */
+function passwordSync(channel: string, values: string[]): SyncResult {
+ const key = getCredentialKey();
+ if (!key || !Array.isArray(values)) {
+ return { available: false };
+ }
+ try {
+ if (channel === 'encryptCredentials') {
+ return {
+ available: true,
+ values: values.map((v) =>
+ typeof v === 'string' ? encryptWithRawKey(v, key) : v,
+ ),
+ };
+ }
+ // decrypt
+ return {
+ available: true,
+ values: values.map((v) =>
+ typeof v === 'string' ? (decryptWithRawKey(v, key) ?? null) : null,
+ ),
+ };
+ } catch (e) {
+ console.warn('credentialsTransform: password provider failed', e);
+ return { available: false };
+ }
+}
+
+/** Resolve the active provider. */
+const defaultSync: SyncFn = (channel, values) => {
+ const source = getKeySource();
+ if (source === 'keychain') {
+ return keychainSync(channel, values);
+ }
+ if (source === 'password' && hasCredentialKey()) {
+ return passwordSync(channel, values);
+ }
+ return null;
};
+/* -------------------------- transform ------------------------------ */
+
function notifyDecryptFailure(names: string[]): void {
let msg: string;
try {
@@ -137,9 +201,9 @@ export function transformSlice(
if (typeof v !== 'string' || v.length === 0) {
return;
}
- const isEnc = v.startsWith(PREFIX);
+ const isEnc = v.startsWith(ENC_PREFIX);
if (mode === 'encrypt' && isEnc) {
- return; // idempotent — already encrypted
+ return; // idempotent — already encrypted (any scheme)
}
if (mode === 'decrypt' && !isEnc) {
return; // legacy plaintext passthrough
@@ -180,7 +244,11 @@ export function transformSlice(
const ok = !!res && res.available === true && Array.isArray(res.values);
const dec = ok ? (res as any).values[idx] : null;
if (dec === null || dec === undefined) {
- newContainers[p.ci][p.f] = undefined;
+ // Decrypt failed (key lost / wrong key / unsupported scheme).
+ // Use an empty string instead of undefined so downstream consumers
+ // (Leaflet templates, AWS SDK auth, etc.) don't crash on a missing
+ // value. The user is notified below and can re-enter or restore.
+ newContainers[p.ci][p.f] = '';
const c = newContainers[p.ci];
failed.push(c.name || c.uuid || '?');
} else {
@@ -199,16 +267,29 @@ export function transformSlice(
return newContainers;
}
+/** Probe whether a usable provider exists right now (for inbound gate). */
+function providerAvailable(): boolean {
+ const source = getKeySource();
+ if (source === 'keychain') {
+ const io = (window as any).electronIO?.ipcRenderer;
+ return !!(AppConfig.isElectron && io && typeof io.getSync === 'function');
+ }
+ if (source === 'password') {
+ return hasCredentialKey();
+ }
+ return false;
+}
+
export function createCredentialsTransform(syncFn: SyncFn = defaultSync) {
return createTransform(
// inbound: store → persisted
(subState: any, key: any) => {
- if (!AppConfig.isElectron || !isEncryptAtRestEnabled()) {
+ if (!isEncryptAtRestEnabled() || !providerAvailable()) {
return subState;
}
return transformSlice(subState, key as string, 'encrypt', syncFn);
},
- // outbound: persisted → store (flag-independent)
+ // outbound: persisted → store (flag-independent; tries any tsenc: value)
(subState: any, key: any) =>
transformSlice(subState, key as string, 'decrypt', syncFn),
{ whitelist: Object.keys(REGISTRY) },
diff --git a/src/renderer/services/encryptAtRestState.ts b/src/renderer/services/encryptAtRestState.ts
index ec7c35c48..26da45791 100644
--- a/src/renderer/services/encryptAtRestState.ts
+++ b/src/renderer/services/encryptAtRestState.ts
@@ -27,10 +27,19 @@
*
* The persistor reference is parked here so the Settings dialog (deep in the
* tree, with no persistor context) can flush during enable/disable + scrub.
+ *
+ * `keySource` and `credentialKey` carry the at-rest mode and (when password
+ * mode) the derived 64-byte key for the current tab. The key is in-memory
+ * only — never persisted, never written to sessionStorage — so a fresh tab
+ * or a hard refresh forces the Unlock screen.
*/
+export type KeySource = 'off' | 'keychain' | 'password';
+
let enabled = false;
let persistorRef: any = null;
+let keySource: KeySource = 'off';
+let credentialKey: Uint8Array | null = null;
export function setEncryptAtRestEnabled(value: boolean): void {
enabled = !!value;
@@ -47,3 +56,30 @@ export function setPersistorRef(persistor: any): void {
export function getPersistorRef(): any {
return persistorRef;
}
+
+export function setKeySource(source: KeySource): void {
+ // NOTE: do NOT auto-clear `credentialKey` here. The store subscription
+ // can briefly set source='off' during the gap between dispatching the
+ // `encryptCredentialsAtRest` and `encryptCredentialsKeySource` actions;
+ // if we cleared the key on that transient downgrade, the next persist
+ // write would find no provider and write plaintext. Callers that
+ // genuinely leave password mode (disable flow, UnlockScreen reset)
+ // clear the key explicitly via `setCredentialKey(null)`.
+ keySource = source === 'keychain' || source === 'password' ? source : 'off';
+}
+
+export function getKeySource(): KeySource {
+ return keySource;
+}
+
+export function setCredentialKey(rawKey: Uint8Array | null): void {
+ credentialKey = rawKey instanceof Uint8Array ? rawKey : null;
+}
+
+export function getCredentialKey(): Uint8Array | null {
+ return credentialKey;
+}
+
+export function hasCredentialKey(): boolean {
+ return credentialKey !== null;
+}
diff --git a/src/renderer/services/export-import-validators.ts b/src/renderer/services/export-import-validators.ts
index 2690f8bda..a60b6f2a2 100644
--- a/src/renderer/services/export-import-validators.ts
+++ b/src/renderer/services/export-import-validators.ts
@@ -77,10 +77,11 @@ export const NON_IMPORTABLE_SETTINGS_KEYS = [
'supportedThemes',
'supportedGeoTagging',
'extensionsFound',
- // device-bound: encryption is keyed to this machine's OS keychain, so an
- // imported envelope must never silently flip a machine into "encrypted"
- // mode without its key.
+ // device-bound: encryption is keyed to this machine's OS keychain (or a
+ // password held in memory), so an imported envelope must never silently
+ // flip a machine into "encrypted" mode without its key.
'encryptCredentialsAtRest',
+ 'encryptCredentialsKeySource',
];
function isNonEmptyString(v: any): boolean {
diff --git a/src/renderer/services/secure-crypto.ts b/src/renderer/services/secure-crypto.ts
index 040c70e9d..9d62185b0 100644
--- a/src/renderer/services/secure-crypto.ts
+++ b/src/renderer/services/secure-crypto.ts
@@ -308,3 +308,166 @@ export async function decryptString(
return undefined;
}
}
+
+/* ------------------------------------------------------------------ */
+/* Synchronous raw-key cipher — used by the redux-persist credentials */
+/* transform on every write. The raw key is derived from the user */
+/* password ONCE at unlock/enable (see `deriveRawKey` below); no */
+/* PBKDF2 per write. Distinct prefix so a value carries its scheme. */
+/* ------------------------------------------------------------------ */
+
+/** Prefix for password-based at-rest credential encryption (CBC + HMAC). */
+export const PWENC_PREFIX = 'tsenc:p1:';
+/** Fixed plaintext the verifier blob encrypts — proves the right password. */
+const VERIFIER_SENTINEL = 'tsenc-verifier-v1';
+
+/** Default PBKDF2 iteration count for the available KDF backend. */
+export function defaultKdfIterations(): number {
+ return getSubtle() ? PBKDF2_ITER_SUBTLE : PBKDF2_ITER_CRYPTOJS;
+}
+
+/** Random 16-byte base64 salt for PBKDF2 (not secret; stored alongside). */
+export function makeKdfSalt(): string {
+ return bytesToB64(randomBytes(16));
+}
+
+/** Copy a CryptoJS WordArray's leading bytes into a Uint8Array. */
+function wordArrayToBytes(wa: CryptoJS.lib.WordArray, len: number): Uint8Array {
+ 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;
+}
+
+/**
+ * PBKDF2 → 64-byte raw key (32 for AES-256-CBC + 32 for HMAC-SHA256).
+ * Async by necessity (PBKDF2 is expensive); call ONCE at unlock/enable.
+ */
+export async function deriveRawKey(
+ password: string,
+ saltB64: string,
+ iterations: number,
+): Promise<Uint8Array> {
+ const salt = b64ToBytes(saltB64);
+ const subtle = getSubtle();
+ if (subtle) {
+ const km = await subtle.importKey(
+ 'raw',
+ ab(new TextEncoder().encode(password)),
+ 'PBKDF2',
+ false,
+ ['deriveBits'],
+ );
+ const bits = await subtle.deriveBits(
+ { name: 'PBKDF2', salt: ab(salt), iterations, hash: 'SHA-256' },
+ km,
+ 512,
+ );
+ return new Uint8Array(bits);
+ }
+ // CryptoJS fallback — produces the same 64-byte material via PBKDF2-SHA256.
+ const { encKey, macKey } = deriveCryptoJsKeys(
+ password,
+ bytesToWordArray(salt),
+ iterations,
+ );
+ const out = new Uint8Array(64);
+ out.set(wordArrayToBytes(encKey, 32), 0);
+ out.set(wordArrayToBytes(macKey, 32), 32);
+ return out;
+}
+
+function splitRawKey(rawKey: Uint8Array): {
+ encWa: CryptoJS.lib.WordArray;
+ macWa: CryptoJS.lib.WordArray;
+} {
+ if (!(rawKey instanceof Uint8Array) || rawKey.length !== 64) {
+ throw new Error('secure-crypto: invalid raw key');
+ }
+ return {
+ encWa: bytesToWordArray(rawKey.subarray(0, 32)),
+ macWa: bytesToWordArray(rawKey.subarray(32, 64)),
+ };
+}
+
+/**
+ * AES-256-CBC + HMAC-SHA256 (encrypt-then-MAC), synchronous.
+ *
+ * Wire format after the prefix:
+ * ivB64 "." ctB64 "." macHex
+ */
+export function encryptWithRawKey(
+ plaintext: string,
+ rawKey: Uint8Array,
+): string {
+ const { encWa, macWa } = splitRawKey(rawKey);
+ const iv = randomBytes(16);
+ const ivWa = bytesToWordArray(iv);
+ const enc = CryptoJS.AES.encrypt(plaintext, encWa, {
+ iv: ivWa,
+ mode: CryptoJS.mode.CBC,
+ padding: CryptoJS.pad.Pkcs7,
+ });
+ const ivB64 = bytesToB64(iv);
+ const ctB64 = enc.ciphertext.toString(CryptoJS.enc.Base64);
+ const mac = CryptoJS.HmacSHA256(`${ivB64}.${ctB64}`, macWa).toString();
+ return `${PWENC_PREFIX}${ivB64}.${ctB64}.${mac}`;
+}
+
+/** Returns the plaintext, or undefined on tamper / wrong key / malformed. */
+export function decryptWithRawKey(
+ ciphertext: string,
+ rawKey: Uint8Array,
+): string | undefined {
+ try {
+ if (
+ typeof ciphertext !== 'string' ||
+ !ciphertext.startsWith(PWENC_PREFIX)
+ ) {
+ return undefined;
+ }
+ const parts = ciphertext.slice(PWENC_PREFIX.length).split('.');
+ if (parts.length !== 3) {
+ return undefined;
+ }
+ const [ivB64, ctB64, mac] = parts;
+ const { encWa, macWa } = splitRawKey(rawKey);
+ const expected = CryptoJS.HmacSHA256(`${ivB64}.${ctB64}`, macWa).toString();
+ if (!constantTimeEqual(expected, mac)) {
+ return undefined;
+ }
+ const ivWa = bytesToWordArray(b64ToBytes(ivB64));
+ const decrypted = CryptoJS.AES.decrypt(
+ CryptoJS.lib.CipherParams.create({
+ ciphertext: CryptoJS.enc.Base64.parse(ctB64),
+ }),
+ encWa,
+ { iv: ivWa, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 },
+ );
+ const txt = decrypted.toString(CryptoJS.enc.Utf8);
+ return txt || undefined;
+ } catch (e) {
+ return undefined;
+ }
+}
+
+/**
+ * Build a verifier blob for the given derived key — encrypts a fixed
+ * sentinel string. Stored alongside the salt so a wrong password can be
+ * detected without touching credential data.
+ */
+export function makeVerifier(rawKey: Uint8Array): string {
+ return encryptWithRawKey(VERIFIER_SENTINEL, rawKey);
+}
+
+/** True iff `blob` decrypts under `rawKey` to the verifier sentinel. */
+export function checkVerifier(rawKey: Uint8Array, blob: string): boolean {
+ const out = decryptWithRawKey(blob, rawKey);
+ return typeof out === 'string' && constantTimeEqual(out, VERIFIER_SENTINEL);
+}
+
+/** True if the value is encrypted under any at-rest scheme (`tsenc:*:`). */
+export function isAnyRawEncrypted(v: unknown): v is string {
+ return typeof v === 'string' && /^tsenc:[a-z0-9]+:/i.test(v);
+}
diff --git a/src/renderer/store/configureStore.dev.ts b/src/renderer/store/configureStore.dev.ts
index 5a26f8108..c5d3ebccc 100644
--- a/src/renderer/store/configureStore.dev.ts
+++ b/src/renderer/store/configureStore.dev.ts
@@ -27,8 +27,10 @@ import onlineListener from '../services/onlineListener';
import { getEncryptCredentialsAtRest } from '../reducers/settings';
import {
setEncryptAtRestEnabled,
+ setKeySource,
setPersistorRef,
} from '../services/encryptAtRestState';
+import { inferKeySource } from '../services/credentialsBootstrap';
const configureStore = (initialState) => {
// Redux Configuration
@@ -69,15 +71,32 @@ const configureStore = (initialState) => {
onlineListener(store.dispatch);
- const syncEncryptFlag = () => {
+ const syncEncryptState = () => {
try {
- setEncryptAtRestEnabled(getEncryptCredentialsAtRest(store.getState()));
+ const state: any = store.getState();
+ // CRITICAL: persistStore() synchronously dispatches PERSIST before
+ // the async REHYDRATE arrives. Without this gate, the subscription
+ // would fire on PERSIST while state.settings still holds defaults
+ // (flag=false, source='off'), overwrite the probe seed to 'off',
+ // and then transform.out during REHYDRATE would have no provider
+ // and blank every `tsenc:*:` value. Skip until rehydration is done.
+ if (!state._persist?.rehydrated) {
+ return;
+ }
+ const enabled = getEncryptCredentialsAtRest(state);
+ // Read raw so an undefined value (shipped users without the new
+ // field) takes the back-compat path inside `inferKeySource`.
+ const explicit = state.settings?.encryptCredentialsKeySource;
+ setEncryptAtRestEnabled(enabled);
+ setKeySource(inferKeySource(enabled, explicit, AppConfig.isElectron));
} catch (e) {
/* ignore */
}
};
- syncEncryptFlag();
- store.subscribe(syncEncryptFlag);
+ // The probe in index.tsx already seeded the singleton based on the
+ // persisted settings; the subscription only takes over once rehydration
+ // has run (the gate above).
+ store.subscribe(syncEncryptState);
const persistor = persistStore(store, null, () => {
// languageChanged event is not handled in main process on store loaded (App is not ready)
diff --git a/src/renderer/store/configureStore.prod.ts b/src/renderer/store/configureStore.prod.ts
index 86dd2ad70..f2f706286 100644
--- a/src/renderer/store/configureStore.prod.ts
+++ b/src/renderer/store/configureStore.prod.ts
@@ -25,8 +25,10 @@ import onlineListener from '../services/onlineListener';
import { getEncryptCredentialsAtRest } from '../reducers/settings';
import {
setEncryptAtRestEnabled,
+ setKeySource,
setPersistorRef,
} from '../services/encryptAtRestState';
+import { inferKeySource } from '../services/credentialsBootstrap';
const enhancer = compose(
applyMiddleware(thunk), // , router)
@@ -36,15 +38,32 @@ const enhancer = compose(
function configureStore(initialState) {
const store = createStore(rootReducer, initialState, enhancer);
onlineListener(store.dispatch);
- const syncEncryptFlag = () => {
+ const syncEncryptState = () => {
try {
- setEncryptAtRestEnabled(getEncryptCredentialsAtRest(store.getState()));
+ const state: any = store.getState();
+ // CRITICAL: persistStore() synchronously dispatches PERSIST before
+ // the async REHYDRATE arrives. Without this gate, the subscription
+ // would fire on PERSIST while state.settings still holds defaults
+ // (flag=false, source='off'), overwrite the probe seed to 'off',
+ // and then transform.out during REHYDRATE would have no provider
+ // and blank every `tsenc:*:` value. Skip until rehydration is done.
+ if (!state._persist?.rehydrated) {
+ return;
+ }
+ const enabled = getEncryptCredentialsAtRest(state);
+ // Read raw so an undefined value (shipped users without the new
+ // field) takes the back-compat path inside `inferKeySource`.
+ const explicit = state.settings?.encryptCredentialsKeySource;
+ setEncryptAtRestEnabled(enabled);
+ setKeySource(inferKeySource(enabled, explicit, AppConfig.isElectron));
} catch (e) {
/* ignore */
}
};
- syncEncryptFlag();
- store.subscribe(syncEncryptFlag);
+ // The probe in index.tsx already seeded the singleton based on the
+ // persisted settings; the subscription only takes over once rehydration
+ // has run (the gate above).
+ store.subscribe(syncEncryptState);
const persistor = persistStore(store, null, () => {
// document.dispatchEvent(new Event('storeLoaded'));
// console.log('Store rehydrated.');
diff --git a/tests/e2e/credentials-encryption-web.pw.e2e.js b/tests/e2e/credentials-encryption-web.pw.e2e.js
new file mode 100644
index 000000000..e5a685341
--- /dev/null
+++ b/tests/e2e/credentials-encryption-web.pw.e2e.js
@@ -0,0 +1,194 @@
+/* Copyright (c) 2016-present - TagSpaces GmbH. All rights reserved. */
+import { expect, test } from './fixtures';
+import {
+ clickOn,
+ expectElementExist,
+ setInputValue,
+} from './general.helpers';
+import { createLocation } from './general.helpers';
+import { startTestingApp, stopApp } from './hook';
+import { clearDataStorage, closeWelcomePlaywright } from './welcome.helpers';
+
+/**
+ * Web-only coverage for the at-rest credentials encryption feature.
+ *
+ * Flow exercised:
+ * 1. create an S3 location (its credentials end up in `state.locations`,
+ * persisted because `extconfig.js` has `ExtSaveLocationsInBrowser=true`)
+ * 2. enable encryption from Settings → set a password → password-setup
+ * dialog closes, toggle shows ON
+ * 3. read raw `localStorage.persist:root` and assert it contains a
+ * `tsenc:p1:` blob for the location's `secretAccessKey` AND that no
+ * plaintext access key leaks
+ * 4. reload the tab → UnlockScreen appears → enter the password → app
+ * hydrates → location is back in the location manager
+ * 5. disable encryption from Settings → assert plaintext returns to
+ * localStorage and the KDF/verifier keys are gone
+ * 6. reload the tab → no UnlockScreen (feature off) → location still
+ * loads.
+ *
+ * Test data IDs come from CredentialsPasswordSetupDialog.tsx,
+ * UnlockScreen.tsx, and the toggle in SettingsGeneral.tsx.
+ */
+
+const TEST_PASSWORD = 'correct horse battery staple';
+const LOCATION_NAME = 'TST91-Encrypted-S3';
+const PERSIST_KEY = 'persist:root';
+const KDF_KEY = 'tsCredKdf';
+const VERIFIER_KEY = 'tsCredVerify';
+
+async function reloadWebApp() {
+ await global.client.reload();
+ await global.client.waitForLoadState('load');
+ await closeWelcomePlaywright();
+}
+
+async function readLs(key) {
+ return global.client.evaluate((k) => localStorage.getItem(k), key);
+}
+
+async function openSettings() {
+ await clickOn('[data-tid=settings]');
+ await global.client.waitForSelector(
+ '[data-tid=settingsEncryptCredentialsAtRest]',
+ { state: 'visible', timeout: 5000 },
+ );
+}
+
+async function closeSettings() {
+ await clickOn('[data-tid=closeSettingsDialog]');
+}
+
+async function enableEncryptionWithPassword(password) {
+ await openSettings();
+ await clickOn('[data-tid=settingsEncryptCredentialsAtRest]');
+ await global.client.waitForSelector('[data-tid=credentialsPasswordTID]', {
+ state: 'visible',
+ timeout: 5000,
+ });
+ await setInputValue('[data-tid=credentialsPasswordTID] input', password);
+ await setInputValue(
+ '[data-tid=credentialsPasswordConfirmTID] input',
+ password,
+ );
+ await clickOn('[data-tid=submitCredentialsSetupTID]');
+ // Dialog closes on submit; wait until it's gone before continuing.
+ await global.client.waitForSelector('[data-tid=credentialsPasswordTID]', {
+ state: 'hidden',
+ timeout: 5000,
+ });
+ await closeSettings();
+}
+
+async function disableEncryption() {
+ await openSettings();
+ await clickOn('[data-tid=settingsEncryptCredentialsAtRest]');
+ // Confirm dialog: click the default confirm action.
+ await clickOn('[data-tid=confirmDialogTID]');
+ await closeSettings();
+}
+
+async function unlock(password) {
+ await global.client.waitForSelector(
+ '[data-tid=credentialsUnlockPasswordTID]',
+ { state: 'visible', timeout: 8000 },
+ );
+ await setInputValue(
+ '[data-tid=credentialsUnlockPasswordTID] input',
+ password,
+ );
+ await clickOn('[data-tid=credentialsUnlockButtonTID]');
+ // UnlockScreen unmounts when the app boots.
+ await global.client.waitForSelector(
+ '[data-tid=credentialsUnlockPasswordTID]',
+ { state: 'hidden', timeout: 8000 },
+ );
+}
+
+test.afterEach(async () => {
+ await clearDataStorage();
+ await stopApp();
+});
+
+test.beforeEach(async ({ isWeb, isS3, webServerPort }, testInfo) => {
+ test.skip(!isWeb, 'TST91 covers the web-only password mode');
+ // Custom extconfig: ExtSaveLocationsInBrowser=true (locations persisted)
+ // and no `ExtLocations` (so the locations reducer is the regular one and
+ // the test can add an S3 location to encrypt). See
+ // `scripts/extconfig-credentials-encryption.js`.
+ await startTestingApp(
+ { isWeb, isS3, webServerPort, testInfo },
+ 'extconfig-credentials-encryption.js',
+ );
+ await closeWelcomePlaywright();
+});
+
+test.describe('TST91 - Credentials encryption on web (password mode):', () => {
+ test('TST9101 - Encrypt, reload + unlock, then disable + reload [web,s3]', async ({
+ isS3,
+ }) => {
+ // Step 1: create an S3 location whose credentials we will encrypt.
+ await createLocation(
+ { isS3, testDataDir: '' },
+ '',
+ LOCATION_NAME,
+ false,
+ false,
+ null, // no folder-exists assertion: the bucket path lookup is not
+ // part of this test
+ );
+
+ // Sanity check: pre-encrypt the location is in persist:root in
+ // plaintext (the access keys we used in createS3Location). The TID
+ // for the location entry is `location_<name>`.
+ await expectElementExist(`[data-tid=location_${LOCATION_NAME}]`, true);
+ const beforeEnc = await readLs(PERSIST_KEY);
+ expect(beforeEnc, 'persist:root must exist on web (ExtSaveLocationsInBrowser=true)')
+ .toBeTruthy();
+ expect(beforeEnc).toContain('secretAccessKey');
+ expect(beforeEnc).not.toContain('tsenc:');
+
+ // Step 2: enable encryption with a password.
+ await enableEncryptionWithPassword(TEST_PASSWORD);
+
+ // Step 3: persist:root contains tsenc:p1: blobs for the credential
+ // fields; no plaintext access key remains.
+ const afterEnc = await readLs(PERSIST_KEY);
+ expect(afterEnc, 'persist:root after enable').toBeTruthy();
+ expect(afterEnc).toContain('tsenc:p1:');
+ // The literal "test" access key we set in createS3Location should
+ // not be present anywhere in the persisted root (it's been replaced
+ // by a tsenc:p1: blob).
+ expect(afterEnc.includes('"accessKeyId":"test"')).toBeFalsy();
+ expect(afterEnc.includes('"secretAccessKey":"test"')).toBeFalsy();
+ // KDF metadata + verifier are written to dedicated keys.
+ expect(await readLs(KDF_KEY)).toBeTruthy();
+ expect(await readLs(VERIFIER_KEY)).toBeTruthy();
+
+ // Step 4: reload → UnlockScreen → enter password → app loads, the
+ // location is back in the manager.
+ await reloadWebApp();
+ await unlock(TEST_PASSWORD);
+ await expectElementExist(`[data-tid=location_${LOCATION_NAME}]`, true);
+
+ // Step 5: disable encryption. Plaintext returns to localStorage and
+ // the KDF/verifier helpers are removed.
+ await disableEncryption();
+ const afterDisable = await readLs(PERSIST_KEY);
+ expect(afterDisable, 'persist:root after disable').toBeTruthy();
+ expect(afterDisable).not.toContain('tsenc:');
+ expect(afterDisable).toContain('secretAccessKey');
+ expect(await readLs(KDF_KEY)).toBeFalsy();
+ expect(await readLs(VERIFIER_KEY)).toBeFalsy();
+
+ // Step 6: reload — no UnlockScreen (feature off), location still
+ // loads from plaintext.
+ await reloadWebApp();
+ await expectElementExist(
+ '[data-tid=credentialsUnlockPasswordTID]',
+ false,
+ 3000,
+ );
+ await expectElementExist(`[data-tid=location_${LOCATION_NAME}]`, true);
+ });
+});
diff --git a/tests/unit/credentialsTransform.test.js b/tests/unit/credentialsTransform.test.js
index fa81df0c3..e61b00fd2 100644
--- a/tests/unit/credentialsTransform.test.js
+++ b/tests/unit/credentialsTransform.test.js
@@ -4,6 +4,18 @@ import {
transformSlice,
createCredentialsTransform,
} from '-/services/credentialsTransform';
+import {
+ PWENC_PREFIX,
+ checkVerifier,
+ decryptWithRawKey,
+ defaultKdfIterations,
+ deriveRawKey,
+ encryptWithRawKey,
+ isAnyRawEncrypted,
+ makeKdfSalt,
+ makeVerifier,
+} from '-/services/secure-crypto';
+import { inferKeySource } from '-/services/credentialsBootstrap';
import {
encryptWithKey,
decryptWithKey,
@@ -182,7 +194,7 @@ describe('credentialsTransform.transformSlice', () => {
expect(transformSlice(input, 'locations', 'encrypt', makeFakeSync({ nullResult: true }))).toBe(input);
});
- test('undecryptable element → that field undefined, location otherwise intact', () => {
+ test('undecryptable element → that field becomes "" (safe for downstream), location otherwise intact', () => {
const enc = [
{
uuid: 'l1',
@@ -196,7 +208,9 @@ describe('credentialsTransform.transformSlice', () => {
values: values.map(() => null), // decrypt fails
});
const out = transformSlice(enc, 'locations', 'decrypt', sync);
- expect(out[0].accessKeyId).toBeUndefined();
+ // Empty string — not undefined — so consumers (Leaflet templates,
+ // AWS SDK auth, etc.) won't crash on a missing value.
+ expect(out[0].accessKeyId).toBe('');
expect(out[0].name).toBe('L1');
expect(out[0].bucketName).toBe('b');
});
@@ -233,3 +247,154 @@ describe('credentialsTransform factory', () => {
expect(back).toBe(plain);
});
});
+
+describe('secure-crypto raw-key cipher (password mode)', () => {
+ const saltB64 = makeKdfSalt();
+ const iter = Math.min(defaultKdfIterations(), 5000); // fast for tests
+
+ test('deriveRawKey + encrypt/decrypt round-trip', async () => {
+ const key = await deriveRawKey('correct horse battery staple', saltB64, iter);
+ expect(key).toBeInstanceOf(Uint8Array);
+ expect(key.length).toBe(64);
+
+ const plain = 'AKIA-secret-value/+=';
+ const enc = encryptWithRawKey(plain, key);
+ expect(enc.startsWith(PWENC_PREFIX)).toBe(true);
+ expect(enc.includes(plain)).toBe(false);
+ expect(isAnyRawEncrypted(enc)).toBe(true);
+ expect(decryptWithRawKey(enc, key)).toBe(plain);
+ });
+
+ test('wrong password derives a different key → decrypt returns undefined', async () => {
+ const k1 = await deriveRawKey('right', saltB64, iter);
+ const k2 = await deriveRawKey('wrong', saltB64, iter);
+ const enc = encryptWithRawKey('hello', k1);
+ expect(decryptWithRawKey(enc, k2)).toBeUndefined();
+ });
+
+ test('tampered MAC is rejected', async () => {
+ const key = await deriveRawKey('pw', saltB64, iter);
+ const enc = encryptWithRawKey('hello', key);
+ const parts = enc.slice(PWENC_PREFIX.length).split('.');
+ // Flip the last char of the MAC hex.
+ parts[2] = parts[2].slice(0, -1) + (parts[2].slice(-1) === '0' ? '1' : '0');
+ const tampered = PWENC_PREFIX + parts.join('.');
+ expect(decryptWithRawKey(tampered, key)).toBeUndefined();
+ });
+
+ test('verifier accepts right key, rejects wrong key', async () => {
+ const right = await deriveRawKey('pw1', saltB64, iter);
+ const wrong = await deriveRawKey('pw2', saltB64, iter);
+ const blob = makeVerifier(right);
+ expect(checkVerifier(right, blob)).toBe(true);
+ expect(checkVerifier(wrong, blob)).toBe(false);
+ });
+
+ test('isAnyRawEncrypted detects v1 + p1, rejects plain', () => {
+ expect(isAnyRawEncrypted('tsenc:v1:abc')).toBe(true);
+ expect(isAnyRawEncrypted('tsenc:p1:abc')).toBe(true);
+ expect(isAnyRawEncrypted('plain')).toBe(false);
+ expect(isAnyRawEncrypted(undefined)).toBe(false);
+ expect(isAnyRawEncrypted(42)).toBe(false);
+ });
+});
+
+describe('inferKeySource (bootstrap back-compat)', () => {
+ test('flag off → off', () => {
+ expect(inferKeySource(false, undefined, true)).toBe('off');
+ expect(inferKeySource(false, 'password', true)).toBe('off');
+ });
+
+ test('explicit keychain / password is honored', () => {
+ expect(inferKeySource(true, 'keychain', true)).toBe('keychain');
+ expect(inferKeySource(true, 'password', false)).toBe('password');
+ });
+
+ test('shipped Electron-keychain back-compat: flag on, no explicit, Electron → keychain', () => {
+ expect(inferKeySource(true, undefined, true)).toBe('keychain');
+ expect(inferKeySource(true, 'off', true)).toBe('keychain');
+ });
+
+ test('non-Electron without explicit → off', () => {
+ expect(inferKeySource(true, undefined, false)).toBe('off');
+ });
+});
+
+describe('credentialsTransform with a password-style provider', () => {
+ // Round-trip-compatible fake using the real sync raw-key cipher
+ // construction (but with a non-derived key for speed).
+ const rawKey = Uint8Array.from(crypto.randomBytes(64));
+ const pwSync = (channel, values) => {
+ if (channel === 'encryptCredentials') {
+ return {
+ available: true,
+ values: values.map((v) => encryptWithRawKey(String(v), rawKey)),
+ };
+ }
+ return {
+ available: true,
+ values: values.map((v) =>
+ typeof v === 'string' ? (decryptWithRawKey(v, rawKey) ?? null) : null,
+ ),
+ };
+ };
+
+ test('locations round-trip uses tsenc:p1: and decrypts back', () => {
+ const input = [
+ {
+ uuid: 'l1',
+ name: 'L1',
+ accessKeyId: 'AKIA',
+ secretAccessKey: 'shhh',
+ },
+ ];
+ const enc = transformSlice(input, 'locations', 'encrypt', pwSync);
+ expect(enc[0].accessKeyId.startsWith('tsenc:p1:')).toBe(true);
+ expect(enc[0].secretAccessKey.startsWith('tsenc:p1:')).toBe(true);
+ const dec = transformSlice(enc, 'locations', 'decrypt', pwSync);
+ expect(dec[0].accessKeyId).toBe('AKIA');
+ expect(dec[0].secretAccessKey).toBe('shhh');
+ });
+
+ test('mapTileServers round-trip uses tsenc:p1: and decrypts back', () => {
+ const settings = {
+ mapTileServers: [
+ { uuid: 's1', name: 'M', serverURL: 'https://x?k=K', serverInfo: 'I' },
+ ],
+ };
+ const enc = transformSlice(settings, 'settings', 'encrypt', pwSync);
+ expect(enc.mapTileServers[0].serverURL.startsWith('tsenc:p1:')).toBe(true);
+ expect(enc.mapTileServers[0].serverInfo.startsWith('tsenc:p1:')).toBe(true);
+ const dec = transformSlice(enc, 'settings', 'decrypt', pwSync);
+ expect(dec.mapTileServers[0].serverURL).toBe('https://x?k=K');
+ expect(dec.mapTileServers[0].serverInfo).toBe('I');
+ });
+
+ test('mixed-scheme decrypt: p1 values blank-but-string when only keychain sync is wired (cross-mode safety)', () => {
+ // Same shape we'd see if a user switched key sources without disabling
+ // first: the persistor still holds tsenc:p1: values but the active
+ // provider only knows tsenc:v1:. decryptWithRawKey on a non-PWENC
+ // prefix returns undefined → provider null → field set to "" (not
+ // undefined — protects downstream consumers).
+ const v1Only = (channel, values) => {
+ // Mimic the keychain provider: returns null for anything it can't
+ // decrypt.
+ if (channel === 'decryptCredentials') {
+ return { available: true, values: values.map(() => null) };
+ }
+ return { available: false };
+ };
+ const enc = [
+ {
+ uuid: 'l1',
+ name: 'L1',
+ accessKeyId: encryptWithRawKey('AKIA', rawKey), // tsenc:p1:
+ bucketName: 'b',
+ },
+ ];
+ const out = transformSlice(enc, 'locations', 'decrypt', v1Only);
+ expect(out[0].accessKeyId).toBe('');
+ expect(out[0].bucketName).toBe('b');
+ expect(out[0].name).toBe('L1');
+ });
+});