Skip to content

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

feat: experimental feature for encrypt sensitive information in the local storage

Ilian Sapundshievf789bc711569
diff --git a/src/main/credentialCipher.ts b/src/main/credentialCipher.ts
new file mode 100644
index 000000000..3b1dd3553
--- /dev/null
+++ b/src/main/credentialCipher.ts
@@ -0,0 +1,104 @@
+/**
+ * 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/>.
+ *
+ */
+
+/**
+ * Synchronous AES-256-GCM for at-rest encryption of credential strings.
+ *
+ * Pure Node `crypto` — no `electron` import — so this module loads in the
+ * Playwright unit harness and is testable with a fixed key. GCM provides the
+ * authentication tag for free, so no separate HMAC is needed.
+ *
+ * Wire format (after the prefix): b64(iv12) "." b64(tag16) "." b64(ct)
+ *
+ * The 256-bit key is high-entropy random (see secureStorage.ts), so there is
+ * deliberately NO password KDF here — this runs on every redux-persist write.
+ */
+
+import crypto from 'crypto';
+
+export const RAWENC_PREFIX = 'tsenc:v1:';
+
+const IV_BYTES = 12; // GCM standard nonce length
+const TAG_BYTES = 16;
+const KEY_BYTES = 32; // AES-256
+
+export function isRawEncrypted(v: unknown): v is string {
+ return typeof v === 'string' && v.startsWith(RAWENC_PREFIX);
+}
+
+export function encryptWithKey(plaintext: string, key: Buffer): string {
+ if (!Buffer.isBuffer(key) || key.length !== KEY_BYTES) {
+ throw new Error('credentialCipher: invalid key');
+ }
+ const iv = crypto.randomBytes(IV_BYTES);
+ // Normalize Buffers to Uint8Array at the crypto boundary: the pinned
+ // @types/node (20.x) types `Buffer` without the array-buffer generic that
+ // TS 5.9's lib `Uint8Array<TArrayBuffer>` / `crypto` overloads expect.
+ const cipher = crypto.createCipheriv(
+ 'aes-256-gcm',
+ new Uint8Array(key),
+ new Uint8Array(iv),
+ );
+ const ct = Buffer.concat([
+ new Uint8Array(cipher.update(plaintext, 'utf8')),
+ new Uint8Array(cipher.final()),
+ ]);
+ const tag = cipher.getAuthTag();
+ return `${RAWENC_PREFIX}${iv.toString('base64')}.${tag.toString(
+ 'base64',
+ )}.${ct.toString('base64')}`;
+}
+
+/** Returns the plaintext, or undefined on tamper / wrong key / malformed. */
+export function decryptWithKey(
+ ciphertext: string,
+ key: Buffer,
+): string | undefined {
+ try {
+ if (
+ !isRawEncrypted(ciphertext) ||
+ !Buffer.isBuffer(key) ||
+ key.length !== KEY_BYTES
+ ) {
+ return undefined;
+ }
+ const parts = ciphertext.slice(RAWENC_PREFIX.length).split('.');
+ if (parts.length !== 3) {
+ return undefined;
+ }
+ const iv = Buffer.from(parts[0], 'base64');
+ const tag = Buffer.from(parts[1], 'base64');
+ const ct = Buffer.from(parts[2], 'base64');
+ if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) {
+ return undefined;
+ }
+ const decipher = crypto.createDecipheriv(
+ 'aes-256-gcm',
+ new Uint8Array(key),
+ new Uint8Array(iv),
+ );
+ decipher.setAuthTag(new Uint8Array(tag));
+ const pt = Buffer.concat([
+ new Uint8Array(decipher.update(new Uint8Array(ct))),
+ new Uint8Array(decipher.final()),
+ ]);
+ return pt.toString('utf8');
+ } catch (e) {
+ return undefined;
+ }
+}
diff --git a/src/main/mainEvents.ts b/src/main/mainEvents.ts
index f0da12bc9..24145e88c 100644
--- a/src/main/mainEvents.ts
+++ b/src/main/mainEvents.ts
@@ -45,6 +45,7 @@ import {
readMacOSTags,
} from './util';
import os from 'os';
+import registerSecureStorageEvents from './secureStorage';
//let watcher: FSWatcher;
const progress = {};
@@ -57,6 +58,8 @@ function isSafePath(filePath) {
}
export default function loadMainEvents() {
+ registerSecureStorageEvents();
+
ipcMain.on('reloadWindow', () => {
const mainWindow = BrowserWindow.getAllWindows();
if (mainWindow.length > 0) {
diff --git a/src/main/preload.ts b/src/main/preload.ts
index e7cca6bc5..8bafde022 100644
--- a/src/main/preload.ts
+++ b/src/main/preload.ts
@@ -83,6 +83,11 @@ export type Channels =
| 'startup-finished'
| 'getAuthor'
| 'cancelRequest'
+ | 'encryptCredentials'
+ | 'decryptCredentials'
+ | 'getCredentialKeyStatus'
+ | 'getWindowCount'
+ | 'flushStorageData'
| 'fetchTile';
const electronHandler = {
diff --git a/src/main/secureStorage.ts b/src/main/secureStorage.ts
new file mode 100644
index 000000000..ca50a4832
--- /dev/null
+++ b/src/main/secureStorage.ts
@@ -0,0 +1,193 @@
+/**
+ * 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/>.
+ *
+ */
+
+/**
+ * Owns the at-rest credential data key. The key is generated once, sealed
+ * with Electron `safeStorage` (OS keychain — macOS Keychain / Windows DPAPI
+ * / Linux libsecret) and kept in `userData/credkey.bin`.
+ *
+ * The unsealed key NEVER leaves the main process: the renderer's synchronous
+ * redux-persist transform calls `encryptCredentials` / `decryptCredentials`
+ * over `sendSync`, and only the resulting strings cross the IPC boundary.
+ *
+ * Failure policy (data-loss avoidance): if `safeStorage` is unavailable, or
+ * an existing sealed file cannot be unsealed, return `null` and report
+ * `available:false` — never regenerate over an existing sealed file (that
+ * would make already-encrypted credentials permanently unrecoverable).
+ */
+
+import { app, safeStorage, ipcMain, BrowserWindow } from 'electron';
+import fs from 'fs';
+import path from 'path';
+import crypto from 'crypto';
+import { encryptWithKey, decryptWithKey } from './credentialCipher';
+
+const KEY_FILENAME = 'credkey.bin';
+const KEY_BYTES = 32;
+
+let cachedKey: Buffer | null = null;
+// Negative cache so a persistently-failing keychain isn't hit on every
+// redux-persist write. Cleared by the status check so the user can retry
+// after unlocking their keyring.
+let negativeCache = false;
+
+function keyFilePath(): string {
+ return path.join(app.getPath('userData'), KEY_FILENAME);
+}
+
+function isWeakBackend(): boolean {
+ try {
+ if (
+ process.platform === 'linux' &&
+ typeof (safeStorage as any).getSelectedStorageBackend === 'function'
+ ) {
+ return (safeStorage as any).getSelectedStorageBackend() === 'basic_text';
+ }
+ } catch (e) {
+ /* ignore */
+ }
+ return false;
+}
+
+/**
+ * Returns the cached 32-byte data key, generating + sealing it on first use.
+ * Returns null when unavailable / unsealable (see failure policy above).
+ */
+export function loadOrCreateKey(): Buffer | null {
+ if (cachedKey) {
+ return cachedKey;
+ }
+ if (negativeCache) {
+ return null;
+ }
+ try {
+ if (!safeStorage.isEncryptionAvailable()) {
+ console.warn('secureStorage: safeStorage encryption not available');
+ negativeCache = true;
+ return null;
+ }
+ const p = keyFilePath();
+ if (fs.existsSync(p)) {
+ try {
+ const sealed = fs.readFileSync(p);
+ const b64 = safeStorage.decryptString(sealed);
+ const key = Buffer.from(b64, 'base64');
+ if (key.length !== KEY_BYTES) {
+ console.warn('secureStorage: unsealed key has wrong length');
+ negativeCache = true;
+ return null;
+ }
+ cachedKey = key;
+ return cachedKey;
+ } catch (e) {
+ // Keychain reset / different OS user / corrupt — do NOT regenerate.
+ console.warn('secureStorage: could not unseal credential key', e);
+ negativeCache = true;
+ return null;
+ }
+ }
+ // First run — generate and seal.
+ const key = crypto.randomBytes(KEY_BYTES);
+ const sealed = safeStorage.encryptString(key.toString('base64'));
+ // new Uint8Array(): pinned @types/node 20.x `Buffer` lacks the
+ // array-buffer generic TS 5.9's fs typings expect.
+ fs.writeFileSync(p, new Uint8Array(sealed), { mode: 0o600 });
+ cachedKey = key;
+ return cachedKey;
+ } catch (e) {
+ console.warn('secureStorage: unexpected error acquiring key', e);
+ negativeCache = true;
+ return null;
+ }
+}
+
+export default function registerSecureStorageEvents(): void {
+ // Batched synchronous encrypt — one round-trip per persisted slice.
+ ipcMain.on('encryptCredentials', (event, values: string[]) => {
+ try {
+ const key = loadOrCreateKey();
+ if (!key || !Array.isArray(values)) {
+ event.returnValue = { available: false };
+ return;
+ }
+ event.returnValue = {
+ available: true,
+ values: values.map((v) =>
+ typeof v === 'string' ? encryptWithKey(v, key) : v,
+ ),
+ };
+ } catch (e) {
+ event.returnValue = { available: false };
+ }
+ });
+
+ // Batched synchronous decrypt — failed elements come back as null so the
+ // renderer can blank just that field (never crash rehydrate).
+ ipcMain.on('decryptCredentials', (event, values: string[]) => {
+ try {
+ const key = loadOrCreateKey();
+ if (!key || !Array.isArray(values)) {
+ event.returnValue = { available: false };
+ return;
+ }
+ event.returnValue = {
+ available: true,
+ values: values.map((v) =>
+ typeof v === 'string' ? (decryptWithKey(v, key) ?? null) : null,
+ ),
+ };
+ } catch (e) {
+ event.returnValue = { available: false };
+ }
+ });
+
+ // Drives the Settings toggle enable/disable + tooltip. Clears the negative
+ // cache first so a re-check retries after the user unlocks their keyring.
+ ipcMain.handle('getCredentialKeyStatus', () => {
+ try {
+ negativeCache = false;
+ const key = loadOrCreateKey();
+ return { available: !!key, weak: !!key && isWeakBackend() };
+ } catch (e) {
+ return { available: false, weak: false };
+ }
+ });
+
+ // Single-window guard for the activation / scrub flow.
+ ipcMain.handle('getWindowCount', () => {
+ try {
+ return BrowserWindow.getAllWindows().filter((w) => !w.isDestroyed())
+ .length;
+ } catch (e) {
+ return 1;
+ }
+ });
+
+ // Push DOM storage to disk after the migration scrub.
+ ipcMain.handle('flushStorageData', (event) => {
+ try {
+ const ses = event.sender?.session;
+ if (ses && typeof ses.flushStorageData === 'function') {
+ ses.flushStorageData();
+ }
+ return true;
+ } catch (e) {
+ return false;
+ }
+ });
+}
diff --git a/src/renderer/components/dialogs/components/SettingsGeneral.tsx b/src/renderer/components/dialogs/components/SettingsGeneral.tsx
index 7a235c22f..0f740a5df 100644
--- a/src/renderer/components/dialogs/components/SettingsGeneral.tsx
+++ b/src/renderer/components/dialogs/components/SettingsGeneral.tsx
@@ -46,6 +46,7 @@ import { Pro } from '-/pro';
import { AppDispatch } from '-/reducers/app';
import {
actions as SettingsActions,
+ getEncryptCredentialsAtRest,
getFileNameTagPlace,
getMapTileServers,
getMaxCollectedTag,
@@ -54,6 +55,11 @@ import {
isDevMode,
isHideProFeatures,
} from '-/reducers/settings';
+import { actions as LocationActions } from '-/reducers/locations';
+import {
+ getPersistorRef,
+ setEncryptAtRestEnabled,
+} from '-/services/encryptAtRestState';
import { isWorkerAvailable, setLanguage } from '-/services/utils-io';
import { TS } from '-/tagspaces.namespace';
import { clearAllURLParams } from '-/utils/dom';
@@ -95,10 +101,16 @@ function SettingsGeneral() {
// --- Advanced settings imports ---
const maxCollectedTag = useSelector(getMaxCollectedTag);
- const { openConfirmDialog } = useNotificationContext();
+ const { openConfirmDialog, showNotification } = useNotificationContext();
const { delAllHistory } = useHistoryContext();
const devMode = useSelector(isDevMode);
const hideProFeatures = useSelector(isHideProFeatures);
+ const encryptAtRest = useSelector(getEncryptCredentialsAtRest);
+ const [credKeyStatus, setCredKeyStatus] = useState<{
+ available: boolean;
+ weak: boolean;
+ }>({ available: false, weak: false });
+ const [encryptBusy, setEncryptBusy] = useState<boolean>(false);
const tileServers: Array<TS.MapTileServer> = useSelector(getMapTileServers);
const [tileServerDialog, setTileServerDialog] = useState<any>(undefined);
const wsAlive = useRef<boolean>(null);
@@ -119,6 +131,121 @@ function SettingsGeneral() {
}
}, [settings.enableWS]);
+ useEffect(() => {
+ if (AppConfig.isElectron && window.electronIO?.ipcRenderer) {
+ window.electronIO.ipcRenderer
+ .invoke('getCredentialKeyStatus')
+ .then((status: { available: boolean; weak: boolean }) => {
+ if (status) {
+ setCredKeyStatus(status);
+ }
+ })
+ .catch(() => {
+ setCredKeyStatus({ available: false, 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.
+ */
+ const handleToggleEncryptAtRest = async () => {
+ if (encryptBusy) {
+ return;
+ }
+ const enabling = !encryptAtRest;
+ const persistor = getPersistorRef();
+ if (!persistor) {
+ showNotification(t('core:credentialsEncryptionUnavailable'), 'error');
+ return;
+ }
+ if (enabling && !credKeyStatus.available) {
+ showNotification(t('core:credentialsEncryptionUnavailable'), 'error');
+ return;
+ }
+ if (AppConfig.isElectron && window.electronIO?.ipcRenderer) {
+ try {
+ const count =
+ await window.electronIO.ipcRenderer.invoke('getWindowCount');
+ if (typeof count === 'number' && count > 1) {
+ showNotification(
+ t('core:credentialsEncryptionSingleWindow'),
+ 'warning',
+ );
+ return;
+ }
+ } catch (e) {
+ /* fall through — guard is best-effort */
+ }
+ }
+ 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 ---
const toggleDefaultTagBackgroundColorPicker = () => {
setDisplayColorPicker(!displayColorPicker);
@@ -1438,6 +1565,40 @@ function SettingsGeneral() {
</ListItem>
),
},
+ AppConfig.isElectron && {
+ label: t('core:encryptCredentialsAtRest'),
+ jsx: (
+ <ListItem
+ title={
+ !credKeyStatus.available
+ ? t('core:credentialsEncryptionUnavailable')
+ : ''
+ }
+ >
+ <ListItemText
+ primary={
+ <>
+ {t('core:encryptCredentialsAtRest')}
+ <BetaLabel />
+ <InfoIcon
+ tooltip={
+ credKeyStatus.weak
+ ? t('core:encryptCredentialsAtRestWeakTooltip')
+ : t('core:encryptCredentialsAtRestTooltip')
+ }
+ />
+ </>
+ }
+ />
+ <TsSwitch
+ data-tid="settingsEncryptCredentialsAtRest"
+ disabled={!credKeyStatus.available || encryptBusy}
+ onClick={handleToggleEncryptAtRest}
+ checked={encryptAtRest}
+ />
+ </ListItem>
+ ),
+ },
{
label: t('Danger Zone') + ' ' + t('core:resetSettings'),
jsx: (
diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.json
index c450048d0..aefdc1d11 100644
--- a/src/renderer/locales/en/core.json
+++ b/src/renderer/locales/en/core.json
@@ -147,6 +147,17 @@
"selectWhatToExport": "Select what to export",
"selectWhatToImport": "Select what to import",
"encryptExport": "Encrypt export with a password",
+ "encryptCredentialsAtRest": "Encrypt stored credentials",
+ "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.",
+ "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.",
"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/index.ts b/src/renderer/reducers/index.ts
index aaab93cea..e836851c3 100644
--- a/src/renderer/reducers/index.ts
+++ b/src/renderer/reducers/index.ts
@@ -16,6 +16,7 @@
*
*/
import AppConfig from '-/AppConfig';
+import { credentialsTransform } from '-/services/credentialsTransform';
import { loadJSONString } from '@tagspaces/tagspaces-common/utils-io';
import { persistCombineReducers, PersistConfig } from 'redux-persist';
import getStoredStateMigrateV4 from 'redux-persist/lib/integration/getStoredStateMigrateV4';
@@ -254,6 +255,7 @@ const rootPersistConfig: PersistConfig = {
storage,
version: 2,
blacklist,
+ transforms: [credentialsTransform],
debug: false,
};
diff --git a/src/renderer/reducers/locations.ts b/src/renderer/reducers/locations.ts
index 465d141ee..a752699ad 100644
--- a/src/renderer/reducers/locations.ts
+++ b/src/renderer/reducers/locations.ts
@@ -28,6 +28,11 @@ export const types = {
MOVE_DOWN_LOCATION: 'APP/MOVE_DOWN_LOCATION',
EDIT_LOCATION: 'APP/EDIT_LOCATION',
REMOVE_LOCATION: 'APP/REMOVE_LOCATION',
+ // No-op that returns a fresh array reference. Used to force redux-persist
+ // to re-serialize the (unchanged) locations slice through the
+ // credentials transform when toggling at-rest encryption — its persistoid
+ // skips slices whose reference did not change.
+ TOUCH_LOCATIONS: 'APP/TOUCH_LOCATIONS',
};
export const initialState = [];
@@ -136,6 +141,10 @@ export default (state: Array<TS.S3Location> = initialState, action: any) => {
}
return state;
}
+ case types.TOUCH_LOCATIONS: {
+ // Fresh reference, identical contents — see TOUCH_LOCATIONS comment.
+ return [...state];
+ }
default: {
return state;
}
@@ -169,6 +178,7 @@ export const actions = {
type: types.REMOVE_LOCATION,
locationId,
}),
+ touchLocations: () => ({ type: types.TOUCH_LOCATIONS }),
};
// Selectors
diff --git a/src/renderer/reducers/settings-default.ts b/src/renderer/reducers/settings-default.ts
index b0b8ac2f2..9ae298f76 100644
--- a/src/renderer/reducers/settings-default.ts
+++ b/src/renderer/reducers/settings-default.ts
@@ -100,6 +100,7 @@ export default {
addTagsToLibrary: true,
interfaceLanguage: 'en',
useTrashCan: true,
+ encryptCredentialsAtRest: false,
useOCR: false,
useTextExtraction: false,
useGenerateThumbnails: true,
diff --git a/src/renderer/reducers/settings.ts b/src/renderer/reducers/settings.ts
index 09ea6a69c..a113a2075 100644
--- a/src/renderer/reducers/settings.ts
+++ b/src/renderer/reducers/settings.ts
@@ -46,6 +46,7 @@ export const types = {
SET_USEONLYTAGSFROMTAGLIBRARY: 'SETTINGS/SET_USEONLYTAGSFROMTAGLIBRARY',
SET_DEVMODE: 'SETTINGS/SET_DEVMODE',
SET_ENABLE_WS: 'SETTINGS/SET_ENABLE_WS',
+ SET_ENCRYPT_CREDENTIALS_AT_REST: 'SETTINGS/SET_ENCRYPT_CREDENTIALS_AT_REST',
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',
@@ -232,6 +233,12 @@ export default (state: any = defaultSettings, action: any) => {
case types.SET_ENABLE_WS: {
return { ...state, enableWS: action.enableWS };
}
+ case types.SET_ENCRYPT_CREDENTIALS_AT_REST: {
+ return {
+ ...state,
+ encryptCredentialsAtRest: action.encryptCredentialsAtRest,
+ };
+ }
case types.WARNING_OPENING_FILES_EXTERNALLY: {
return {
...state,
@@ -738,6 +745,10 @@ export const actions = {
type: types.SET_ENABLE_WS,
enableWS,
}),
+ setEncryptCredentialsAtRest: (encryptCredentialsAtRest: boolean) => ({
+ type: types.SET_ENCRYPT_CREDENTIALS_AT_REST,
+ encryptCredentialsAtRest,
+ }),
setWarningOpeningFilesExternally: (
warningOpeningFilesExternally: boolean,
) => ({
@@ -1077,6 +1088,8 @@ export const getLastLinkType = (state: any): 'ts' | 'relative' => {
return state.settings.lastLinkType === 'ts' ? 'ts' : 'relative';
};
export const getEnableWS = (state: any) => state.settings.enableWS;
+export const getEncryptCredentialsAtRest = (state: any) =>
+ state.settings.encryptCredentialsAtRest === true;
export const getDesktopMode = (state: any) => {
if (typeof AppConfig.ExtDisplayMode === 'undefined') {
return state.settings.desktopMode;
diff --git a/src/renderer/services/credentialsTransform.ts b/src/renderer/services/credentialsTransform.ts
new file mode 100644
index 000000000..74b305fc6
--- /dev/null
+++ b/src/renderer/services/credentialsTransform.ts
@@ -0,0 +1,218 @@
+/**
+ * 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/>.
+ *
+ */
+
+/**
+ * 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.
+ *
+ * - 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.
+ *
+ * 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 { notifyUser } from '-/services/globalErrorHandlers';
+
+// Mirrors RAWENC_PREFIX in src/main/credentialCipher.ts (no shared module
+// between renderer and main).
+const PREFIX = 'tsenc:v1:';
+
+type Registry = {
+ [sliceKey: string]: {
+ /** When set, the slice is an object and the array lives at this key. */
+ nestedArray?: string;
+ /** Sensitive string fields on each array entry. */
+ fields: string[];
+ };
+};
+
+const REGISTRY: Registry = {
+ locations: {
+ fields: [
+ 'secretAccessKey',
+ 'accessKeyId',
+ 'sessionToken',
+ 'encryptionKey',
+ 'password',
+ ],
+ },
+ settings: {
+ nestedArray: 'mapTileServers',
+ fields: ['serverURL', 'serverInfo'],
+ },
+};
+
+type SyncResult = { available: boolean; values?: (string | null)[] } | null;
+export type SyncFn = (channel: string, values: string[]) => SyncResult;
+
+const defaultSync: SyncFn = (channel, values) => {
+ const io = (window as any).electronIO?.ipcRenderer;
+ if (!AppConfig.isElectron || !io || typeof io.getSync !== 'function') {
+ return null;
+ }
+ try {
+ return io.getSync(channel, values) as SyncResult;
+ } catch (e) {
+ console.warn('credentialsTransform: sync IPC failed', e);
+ return null;
+ }
+};
+
+function notifyDecryptFailure(names: string[]): void {
+ let msg: string;
+ try {
+ // Lazy require so this module has no eager i18n dependency.
+ // eslint-disable-next-line @typescript-eslint/no-var-requires, global-require
+ const i18n = require('-/services/i18n').default;
+ msg = i18n.t('core:credentialsCouldNotBeUnlocked', {
+ names: names.join(', '),
+ });
+ } catch {
+ msg = `Could not unlock saved credentials for: ${names.join(
+ ', ',
+ )}. Please re-enter them or import from an encrypted backup.`;
+ }
+ notifyUser(msg, 'warning', 'credentialUnlockTID');
+}
+
+/**
+ * Encrypt (inbound) or decrypt (outbound) the sensitive fields of one slice.
+ * Returns a new slice (copy-on-write) or the original when there is nothing
+ * to do / on an aborted encryption.
+ */
+export function transformSlice(
+ subState: any,
+ key: string,
+ mode: 'encrypt' | 'decrypt',
+ syncFn: SyncFn,
+): any {
+ const reg = REGISTRY[key];
+ if (!reg) {
+ return subState;
+ }
+
+ let containers: any[];
+ if (reg.nestedArray) {
+ const arr = subState && subState[reg.nestedArray];
+ if (!Array.isArray(arr) || arr.length === 0) {
+ return subState;
+ }
+ containers = arr;
+ } else {
+ if (!Array.isArray(subState)) {
+ return subState;
+ }
+ containers = subState;
+ }
+
+ const picks: { ci: number; f: string; v: string }[] = [];
+ containers.forEach((c, ci) => {
+ if (!c) {
+ return;
+ }
+ reg.fields.forEach((f) => {
+ const v = c[f];
+ if (typeof v !== 'string' || v.length === 0) {
+ return;
+ }
+ const isEnc = v.startsWith(PREFIX);
+ if (mode === 'encrypt' && isEnc) {
+ return; // idempotent — already encrypted
+ }
+ if (mode === 'decrypt' && !isEnc) {
+ return; // legacy plaintext passthrough
+ }
+ picks.push({ ci, f, v });
+ });
+ });
+ if (picks.length === 0) {
+ return subState;
+ }
+
+ const channel =
+ mode === 'encrypt' ? 'encryptCredentials' : 'decryptCredentials';
+ const res = syncFn(
+ channel,
+ picks.map((p) => p.v),
+ );
+
+ if (mode === 'encrypt') {
+ // All-or-nothing: never write a partial plaintext/ciphertext mix.
+ if (
+ !res ||
+ res.available !== true ||
+ !Array.isArray(res.values) ||
+ res.values.length !== picks.length
+ ) {
+ return subState;
+ }
+ }
+
+ const newContainers = containers.map((c) => (c ? { ...c } : c));
+ const failed: string[] = [];
+
+ picks.forEach((p, idx) => {
+ if (mode === 'encrypt') {
+ newContainers[p.ci][p.f] = (res as any).values[idx];
+ } else {
+ 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;
+ const c = newContainers[p.ci];
+ failed.push(c.name || c.uuid || '?');
+ } else {
+ newContainers[p.ci][p.f] = dec;
+ }
+ }
+ });
+
+ if (mode === 'decrypt' && failed.length > 0) {
+ notifyDecryptFailure(failed);
+ }
+
+ if (reg.nestedArray) {
+ return { ...subState, [reg.nestedArray]: newContainers };
+ }
+ return newContainers;
+}
+
+export function createCredentialsTransform(syncFn: SyncFn = defaultSync) {
+ return createTransform(
+ // inbound: store → persisted
+ (subState: any, key: any) => {
+ if (!AppConfig.isElectron || !isEncryptAtRestEnabled()) {
+ return subState;
+ }
+ return transformSlice(subState, key as string, 'encrypt', syncFn);
+ },
+ // outbound: persisted → store (flag-independent)
+ (subState: any, key: any) =>
+ transformSlice(subState, key as string, 'decrypt', syncFn),
+ { whitelist: Object.keys(REGISTRY) },
+ );
+}
+
+export const credentialsTransform = createCredentialsTransform();
diff --git a/src/renderer/services/encryptAtRestState.ts b/src/renderer/services/encryptAtRestState.ts
new file mode 100644
index 000000000..ec7c35c48
--- /dev/null
+++ b/src/renderer/services/encryptAtRestState.ts
@@ -0,0 +1,49 @@
+/**
+ * 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/>.
+ *
+ */
+
+/**
+ * Synchronous accessors for the "encrypt stored credentials" feature.
+ *
+ * The redux-persist transform runs synchronously and only receives a single
+ * slice, so it cannot read the opt-in flag from the store. A store
+ * subscription (wired in configureStore) keeps `enabled` in sync with
+ * `settings.encryptCredentialsAtRest`; the Settings activation handler also
+ * sets it explicitly before flushing to remove ordering ambiguity.
+ *
+ * The persistor reference is parked here so the Settings dialog (deep in the
+ * tree, with no persistor context) can flush during enable/disable + scrub.
+ */
+
+let enabled = false;
+let persistorRef: any = null;
+
+export function setEncryptAtRestEnabled(value: boolean): void {
+ enabled = !!value;
+}
+
+export function isEncryptAtRestEnabled(): boolean {
+ return enabled;
+}
+
+export function setPersistorRef(persistor: any): void {
+ persistorRef = persistor;
+}
+
+export function getPersistorRef(): any {
+ return persistorRef;
+}
diff --git a/src/renderer/services/export-import-validators.ts b/src/renderer/services/export-import-validators.ts
index 6ccad20fb..2690f8bda 100644
--- a/src/renderer/services/export-import-validators.ts
+++ b/src/renderer/services/export-import-validators.ts
@@ -77,6 +77,10 @@ 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.
+ 'encryptCredentialsAtRest',
];
function isNonEmptyString(v: any): boolean {
diff --git a/src/renderer/services/globalErrorHandlers.ts b/src/renderer/services/globalErrorHandlers.ts
index da8f5e60a..9fbf4bfa4 100644
--- a/src/renderer/services/globalErrorHandlers.ts
+++ b/src/renderer/services/globalErrorHandlers.ts
@@ -28,8 +28,46 @@ let installed = false;
let errorListener: ((event: ErrorEvent) => void) | null = null;
let rejectionListener: ((event: PromiseRejectionEvent) => void) | null = null;
+type PendingNotice = {
+ text: string;
+ type: 'default' | 'info' | 'warning' | 'error';
+ tid: string;
+};
+const pendingNotices: PendingNotice[] = [];
+
export function setGlobalErrorNotifier(fn: Notifier | null) {
currentNotifier = fn;
+ if (fn && pendingNotices.length > 0) {
+ const queued = pendingNotices.splice(0, pendingNotices.length);
+ queued.forEach((n) => {
+ try {
+ fn(n.text, n.type, true, n.tid);
+ } catch (e) {
+ console.error('globalErrorHandlers: notifier threw', e);
+ }
+ });
+ }
+}
+
+/**
+ * Surface a user notification from non-React code. If no notifier is
+ * registered yet (e.g. during redux-persist rehydrate, before the
+ * NotificationContext mounts), the notice is queued and flushed once one is.
+ */
+export function notifyUser(
+ text: string,
+ type: 'default' | 'info' | 'warning' | 'error' = 'warning',
+ tid = 'globalNoticeTID',
+) {
+ if (currentNotifier) {
+ try {
+ currentNotifier(text, type, true, tid);
+ return;
+ } catch (e) {
+ console.error('globalErrorHandlers: notifier threw', e);
+ }
+ }
+ pendingNotices.push({ text, type, tid });
}
function notify(message: string) {
diff --git a/src/renderer/store/configureStore.dev.ts b/src/renderer/store/configureStore.dev.ts
index dc6bbd2fc..5a26f8108 100644
--- a/src/renderer/store/configureStore.dev.ts
+++ b/src/renderer/store/configureStore.dev.ts
@@ -24,6 +24,11 @@ import { createLogger } from 'redux-logger';
import AppConfig from '-/AppConfig';
import rootReducer from '../reducers';
import onlineListener from '../services/onlineListener';
+import { getEncryptCredentialsAtRest } from '../reducers/settings';
+import {
+ setEncryptAtRestEnabled,
+ setPersistorRef,
+} from '../services/encryptAtRestState';
const configureStore = (initialState) => {
// Redux Configuration
@@ -64,6 +69,16 @@ const configureStore = (initialState) => {
onlineListener(store.dispatch);
+ const syncEncryptFlag = () => {
+ try {
+ setEncryptAtRestEnabled(getEncryptCredentialsAtRest(store.getState()));
+ } catch (e) {
+ /* ignore */
+ }
+ };
+ syncEncryptFlag();
+ store.subscribe(syncEncryptFlag);
+
const persistor = persistStore(store, null, () => {
// languageChanged event is not handled in main process on store loaded (App is not ready)
setTimeout(() => {
@@ -80,6 +95,8 @@ const configureStore = (initialState) => {
// console.log('Store rehydrated.');
});
+ setPersistorRef(persistor);
+
if (module.hot) {
module.hot.accept(
'../reducers',
diff --git a/src/renderer/store/configureStore.prod.ts b/src/renderer/store/configureStore.prod.ts
index b3dfaf8b7..86dd2ad70 100644
--- a/src/renderer/store/configureStore.prod.ts
+++ b/src/renderer/store/configureStore.prod.ts
@@ -22,6 +22,11 @@ import thunk from 'redux-thunk';
import AppConfig from '-/AppConfig';
import rootReducer from '../reducers';
import onlineListener from '../services/onlineListener';
+import { getEncryptCredentialsAtRest } from '../reducers/settings';
+import {
+ setEncryptAtRestEnabled,
+ setPersistorRef,
+} from '../services/encryptAtRestState';
const enhancer = compose(
applyMiddleware(thunk), // , router)
@@ -31,6 +36,15 @@ const enhancer = compose(
function configureStore(initialState) {
const store = createStore(rootReducer, initialState, enhancer);
onlineListener(store.dispatch);
+ const syncEncryptFlag = () => {
+ try {
+ setEncryptAtRestEnabled(getEncryptCredentialsAtRest(store.getState()));
+ } catch (e) {
+ /* ignore */
+ }
+ };
+ syncEncryptFlag();
+ store.subscribe(syncEncryptFlag);
const persistor = persistStore(store, null, () => {
// document.dispatchEvent(new Event('storeLoaded'));
// console.log('Store rehydrated.');
@@ -44,6 +58,7 @@ function configureStore(initialState) {
}
}, 500);
});
+ setPersistorRef(persistor);
return { store, persistor };
}
diff --git a/tests/unit/credentialsTransform.test.js b/tests/unit/credentialsTransform.test.js
new file mode 100644
index 000000000..fa81df0c3
--- /dev/null
+++ b/tests/unit/credentialsTransform.test.js
@@ -0,0 +1,235 @@
+import { describe, expect, test } from '@playwright/test';
+import crypto from 'crypto';
+import {
+ transformSlice,
+ createCredentialsTransform,
+} from '-/services/credentialsTransform';
+import {
+ encryptWithKey,
+ decryptWithKey,
+ isRawEncrypted,
+ RAWENC_PREFIX,
+} from '../../src/main/credentialCipher';
+
+const PREFIX = 'tsenc:v1:';
+
+// Reversible fake of the main-process sync IPC: encrypt = prefix+base64,
+// decrypt = inverse (null when not decryptable).
+function makeFakeSync(opts = {}) {
+ const calls = [];
+ const fn = (channel, values) => {
+ calls.push({ channel, values });
+ if (opts.unavailable) {
+ return { available: false };
+ }
+ if (opts.nullResult) {
+ return null;
+ }
+ if (channel === 'encryptCredentials') {
+ let out = values.map(
+ (v) => PREFIX + Buffer.from(String(v), 'utf8').toString('base64'),
+ );
+ if (opts.shortEncrypt) {
+ out = out.slice(0, -1);
+ }
+ return { available: true, values: out };
+ }
+ return {
+ available: true,
+ values: values.map((v) => {
+ if (typeof v === 'string' && v.startsWith(PREFIX)) {
+ try {
+ return Buffer.from(v.slice(PREFIX.length), 'base64').toString(
+ 'utf8',
+ );
+ } catch (e) {
+ return null;
+ }
+ }
+ return null; // undecryptable
+ }),
+ };
+ };
+ fn.calls = calls;
+ return fn;
+}
+
+describe('credentialCipher (main, Node crypto)', () => {
+ const key = crypto.randomBytes(32);
+
+ test('round-trips and tags with the prefix', () => {
+ const secret = 'AKIA-super-secret-value/with+chars=';
+ const enc = encryptWithKey(secret, key);
+ expect(enc.startsWith(RAWENC_PREFIX)).toBe(true);
+ expect(isRawEncrypted(enc)).toBe(true);
+ expect(enc.includes(secret)).toBe(false);
+ expect(decryptWithKey(enc, key)).toBe(secret);
+ });
+
+ test('wrong key → undefined (no throw)', () => {
+ const enc = encryptWithKey('hello', key);
+ expect(decryptWithKey(enc, crypto.randomBytes(32))).toBeUndefined();
+ });
+
+ test('tampered ciphertext is rejected (GCM auth)', () => {
+ const enc = encryptWithKey('hello world', key);
+ const parts = enc.slice(RAWENC_PREFIX.length).split('.');
+ const ct = Buffer.from(parts[2], 'base64');
+ ct[Math.floor(ct.length / 2)] ^= 0xff;
+ parts[2] = ct.toString('base64');
+ const tampered = RAWENC_PREFIX + parts.join('.');
+ expect(decryptWithKey(tampered, key)).toBeUndefined();
+ });
+
+ test('malformed input → undefined; isRawEncrypted guards', () => {
+ expect(decryptWithKey('not-encrypted', key)).toBeUndefined();
+ expect(isRawEncrypted('plain')).toBe(false);
+ expect(isRawEncrypted(123)).toBe(false);
+ });
+});
+
+describe('credentialsTransform.transformSlice', () => {
+ const loc = () => [
+ {
+ uuid: 'l1',
+ name: 'My S3',
+ accessKeyId: 'AKIA123',
+ secretAccessKey: 'sshh',
+ sessionToken: 'tok',
+ encryptionKey: 'enc',
+ password: 'pw',
+ bucketName: 'bucket',
+ region: 'eu',
+ endpointURL: 'https://s3',
+ },
+ ];
+
+ test('locations encrypt→decrypt round-trip; non-secret fields untouched', () => {
+ const sync = makeFakeSync();
+ const enc = transformSlice(loc(), 'locations', 'encrypt', sync);
+ [
+ 'accessKeyId',
+ 'secretAccessKey',
+ 'sessionToken',
+ 'encryptionKey',
+ 'password',
+ ].forEach((f) => expect(enc[0][f].startsWith(PREFIX)).toBe(true));
+ expect(enc[0].name).toBe('My S3');
+ expect(enc[0].bucketName).toBe('bucket');
+ expect(enc[0].region).toBe('eu');
+ expect(enc[0].endpointURL).toBe('https://s3');
+
+ const dec = transformSlice(enc, 'locations', 'decrypt', sync);
+ expect(dec[0].secretAccessKey).toBe('sshh');
+ expect(dec[0].accessKeyId).toBe('AKIA123');
+ expect(dec[0].password).toBe('pw');
+ });
+
+ test('settings.mapTileServers round-trip; input not mutated; other keys kept', () => {
+ const settings = {
+ interfaceLanguage: 'en',
+ mapTileServers: [
+ {
+ uuid: 's1',
+ name: 'MapTiler',
+ serverURL: 'https://tiles?key=SECRET',
+ serverInfo: 'info-secret',
+ },
+ ],
+ };
+ const original = JSON.parse(JSON.stringify(settings));
+ const sync = makeFakeSync();
+ const enc = transformSlice(settings, 'settings', 'encrypt', sync);
+ expect(enc).not.toBe(settings);
+ expect(enc.mapTileServers).not.toBe(settings.mapTileServers);
+ expect(settings).toEqual(original); // live object untouched (COW)
+ expect(enc.interfaceLanguage).toBe('en');
+ expect(enc.mapTileServers[0].name).toBe('MapTiler');
+ expect(enc.mapTileServers[0].serverURL.startsWith(PREFIX)).toBe(true);
+ expect(enc.mapTileServers[0].serverInfo.startsWith(PREFIX)).toBe(true);
+
+ const dec = transformSlice(enc, 'settings', 'decrypt', sync);
+ expect(dec.mapTileServers[0].serverURL).toBe('https://tiles?key=SECRET');
+ expect(dec.mapTileServers[0].serverInfo).toBe('info-secret');
+ });
+
+ test('legacy plaintext passes through decrypt unchanged', () => {
+ const sync = makeFakeSync();
+ const out = transformSlice(loc(), 'locations', 'decrypt', sync);
+ expect(out[0].secretAccessKey).toBe('sshh');
+ expect(sync.calls.length).toBe(0); // nothing prefixed → no IPC
+ });
+
+ test('empty/undefined sensitive fields are skipped', () => {
+ const sync = makeFakeSync();
+ const input = [{ uuid: 'l', name: 'n', secretAccessKey: '', password: undefined }];
+ const out = transformSlice(input, 'locations', 'encrypt', sync);
+ expect(out).toBe(input);
+ expect(sync.calls.length).toBe(0);
+ });
+
+ test('encrypt is idempotent (already-prefixed skipped)', () => {
+ const sync = makeFakeSync();
+ const enc1 = transformSlice(loc(), 'locations', 'encrypt', sync);
+ const enc2 = transformSlice(enc1, 'locations', 'encrypt', sync);
+ expect(enc2).toBe(enc1); // nothing left to encrypt → same ref
+ });
+
+ test('all-or-nothing: short/unavailable encrypt result leaves slice unchanged', () => {
+ const input = loc();
+ expect(transformSlice(input, 'locations', 'encrypt', makeFakeSync({ shortEncrypt: true }))).toBe(input);
+ expect(transformSlice(input, 'locations', 'encrypt', makeFakeSync({ unavailable: true }))).toBe(input);
+ expect(transformSlice(input, 'locations', 'encrypt', makeFakeSync({ nullResult: true }))).toBe(input);
+ });
+
+ test('undecryptable element → that field undefined, location otherwise intact', () => {
+ const enc = [
+ {
+ uuid: 'l1',
+ name: 'L1',
+ accessKeyId: PREFIX + 'this-is-not-valid-base64-decryptable!!!',
+ bucketName: 'b',
+ },
+ ];
+ const sync = (channel, values) => ({
+ available: true,
+ values: values.map(() => null), // decrypt fails
+ });
+ const out = transformSlice(enc, 'locations', 'decrypt', sync);
+ expect(out[0].accessKeyId).toBeUndefined();
+ expect(out[0].name).toBe('L1');
+ expect(out[0].bucketName).toBe('b');
+ });
+
+ test('settings without mapTileServers → unchanged, no IPC', () => {
+ const sync = makeFakeSync();
+ const s = { interfaceLanguage: 'en' };
+ expect(transformSlice(s, 'settings', 'encrypt', sync)).toBe(s);
+ expect(transformSlice({ ...s, mapTileServers: [] }, 'settings', 'encrypt', sync))
+ .toEqual({ ...s, mapTileServers: [] });
+ expect(sync.calls.length).toBe(0);
+ });
+});
+
+describe('credentialsTransform factory', () => {
+ test('outbound decrypts (flag-independent); inbound is no-op off Electron', () => {
+ const sync = makeFakeSync();
+ const t = createCredentialsTransform(sync);
+ const encrypted = [
+ {
+ uuid: 'l1',
+ name: 'L1',
+ secretAccessKey:
+ PREFIX + Buffer.from('plain-secret', 'utf8').toString('base64'),
+ },
+ ];
+ // outbound runs regardless of Electron/flag
+ const out = t.out(encrypted, 'locations');
+ expect(out[0].secretAccessKey).toBe('plain-secret');
+
+ // inbound: AppConfig.isElectron is false under Node → pass-through
+ const plain = [{ uuid: 'l', name: 'n', secretAccessKey: 'raw' }];
+ const back = t.in(plain, 'locations');
+ expect(back).toBe(plain);
+ });
+});