Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

fix(appLock):using-persisted-storage

Aswin Asoke4124e3370cd
diff --git a/desktop/src/main/ipc.ts b/desktop/src/main/ipc.ts
index 22c07e34ca..fff5f4410b 100644
--- a/desktop/src/main/ipc.ts
+++ b/desktop/src/main/ipc.ts
@@ -16,6 +16,7 @@ import type {
FFmpegCommand,
FolderWatch,
PendingUploads,
+ PersistedAppLockConfig,
UtilityProcessType,
ZipItem,
} from "../types/ipc";
@@ -53,8 +54,12 @@ import {
import { convertToJPEG, generateImageThumbnail } from "./services/image";
import { logout } from "./services/logout";
import {
+ appLockConfigFromSafeStorage,
+ clearAppLockConfigFromSafeStorage,
+ isSafeStorageAvailable,
lastShownChangelogVersion,
masterKeyFromSafeStorage,
+ saveAppLockConfigInSafeStorage,
saveMasterKeyInSafeStorage,
setLastShownChangelogVersion,
} from "./services/store";
@@ -76,6 +81,32 @@ import {
} from "./services/watch";
import { triggerCreateUtilityProcess } from "./services/workers";
+const parsePersistedAppLockConfig = (
+ config: unknown,
+): PersistedAppLockConfig => {
+ if (!config || typeof config !== "object") {
+ throw new Error("Invalid persisted app lock config");
+ }
+
+ const { enabled, lockType, autoLockTimeMs } = config as Record<
+ string,
+ unknown
+ >;
+ if (
+ typeof enabled !== "boolean" ||
+ (lockType !== "pin" &&
+ lockType !== "password" &&
+ lockType !== "device" &&
+ lockType !== "none") ||
+ typeof autoLockTimeMs !== "number" ||
+ !Number.isFinite(autoLockTimeMs)
+ ) {
+ throw new Error("Invalid persisted app lock config");
+ }
+
+ return { enabled, lockType, autoLockTimeMs };
+};
+
/**
* Listen for IPC events sent/invoked by the renderer process, and route them to
* their correct handlers.
@@ -120,6 +151,20 @@ export const attachIPCHandlers = () => {
saveMasterKeyInSafeStorage(masterKey),
);
+ ipcMain.handle("isSafeStorageAvailable", () => isSafeStorageAvailable());
+
+ ipcMain.handle("appLockConfigFromSafeStorage", () =>
+ appLockConfigFromSafeStorage(),
+ );
+
+ ipcMain.handle("saveAppLockConfigInSafeStorage", (_, config: unknown) =>
+ saveAppLockConfigInSafeStorage(parsePersistedAppLockConfig(config)),
+ );
+
+ ipcMain.handle("clearAppLockConfigFromSafeStorage", () =>
+ clearAppLockConfigFromSafeStorage(),
+ );
+
ipcMain.handle("lastShownChangelogVersion", () =>
lastShownChangelogVersion(),
);
diff --git a/desktop/src/main/services/store.ts b/desktop/src/main/services/store.ts
index 227fe691c6..15e0166d01 100644
--- a/desktop/src/main/services/store.ts
+++ b/desktop/src/main/services/store.ts
@@ -1,4 +1,5 @@
import { safeStorage } from "electron/main";
+import type { PersistedAppLockConfig } from "../../types/ipc";
import { safeStorageStore } from "../stores/safe-storage";
import { uploadStatusStore } from "../stores/upload-status";
import { userPreferences } from "../stores/user-preferences";
@@ -37,6 +38,63 @@ export const masterKeyFromSafeStorage = (): string | undefined => {
return safeStorage.decryptString(encryptedKeyBuffer);
};
+const encryptStringForSafeStorageStore = (value: string) => {
+ return Buffer.from(safeStorage.encryptString(value)).toString("base64");
+};
+
+const decryptStringFromSafeStorageStore = (value: string) => {
+ return safeStorage.decryptString(Buffer.from(value, "base64"));
+};
+
+const parsePersistedAppLockConfig = (json: string): PersistedAppLockConfig => {
+ const parsed: unknown = JSON.parse(json);
+ if (!parsed || typeof parsed !== "object") {
+ throw new Error("Invalid persisted app lock config");
+ }
+
+ const { enabled, lockType, autoLockTimeMs } = parsed as Record<
+ string,
+ unknown
+ >;
+ if (
+ typeof enabled !== "boolean" ||
+ (lockType !== "pin" &&
+ lockType !== "password" &&
+ lockType !== "device" &&
+ lockType !== "none") ||
+ typeof autoLockTimeMs !== "number" ||
+ !Number.isFinite(autoLockTimeMs)
+ ) {
+ throw new Error("Invalid persisted app lock config");
+ }
+
+ return { enabled, lockType, autoLockTimeMs };
+};
+
+export const saveAppLockConfigInSafeStorage = (
+ config: PersistedAppLockConfig,
+) => {
+ const encryptedConfig = encryptStringForSafeStorageStore(
+ JSON.stringify(config),
+ );
+ safeStorageStore.set("appLockConfig", encryptedConfig);
+};
+
+export const appLockConfigFromSafeStorage = ():
+ | PersistedAppLockConfig
+ | undefined => {
+ const encryptedConfig = safeStorageStore.get("appLockConfig");
+ if (!encryptedConfig) return undefined;
+
+ return parsePersistedAppLockConfig(
+ decryptStringFromSafeStorageStore(encryptedConfig),
+ );
+};
+
+export const clearAppLockConfigFromSafeStorage = () => {
+ safeStorageStore.delete("appLockConfig");
+};
+
export const lastShownChangelogVersion = (): number | undefined =>
userPreferences.get("lastShownChangelogVersion");
diff --git a/desktop/src/main/stores/safe-storage.ts b/desktop/src/main/stores/safe-storage.ts
index e2af2900a5..93d2381b85 100644
--- a/desktop/src/main/stores/safe-storage.ts
+++ b/desktop/src/main/stores/safe-storage.ts
@@ -2,10 +2,12 @@ import Store, { Schema } from "electron-store";
interface SafeStorageStore {
encryptionKey?: string;
+ appLockConfig?: string;
}
const safeStorageSchema: Schema<SafeStorageStore> = {
encryptionKey: { type: "string" },
+ appLockConfig: { type: "string" },
};
export const safeStorageStore = new Store({
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index f714900ad8..adb3252293 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -70,6 +70,7 @@ import type {
FolderWatch,
NativeDeviceLockCapability,
PendingUploads,
+ PersistedAppLockConfig,
UtilityProcessType,
ZipItem,
} from "./types/ipc";
@@ -120,6 +121,19 @@ const masterKeyFromSafeStorage = () =>
const saveMasterKeyInSafeStorage = (masterKey: string) =>
ipcRenderer.invoke("saveMasterKeyInSafeStorage", masterKey);
+const isSafeStorageAvailable = (): Promise<boolean> =>
+ ipcRenderer.invoke("isSafeStorageAvailable");
+
+const appLockConfigFromSafeStorage = (): Promise<
+ PersistedAppLockConfig | undefined
+> => ipcRenderer.invoke("appLockConfigFromSafeStorage");
+
+const saveAppLockConfigInSafeStorage = (config: PersistedAppLockConfig) =>
+ ipcRenderer.invoke("saveAppLockConfigInSafeStorage", config);
+
+const clearAppLockConfigFromSafeStorage = () =>
+ ipcRenderer.invoke("clearAppLockConfigFromSafeStorage");
+
const lastShownChangelogVersion = () =>
ipcRenderer.invoke("lastShownChangelogVersion");
@@ -387,6 +401,10 @@ contextBridge.exposeInMainWorld("electron", {
logout,
masterKeyFromSafeStorage,
saveMasterKeyInSafeStorage,
+ isSafeStorageAvailable,
+ appLockConfigFromSafeStorage,
+ saveAppLockConfigInSafeStorage,
+ clearAppLockConfigFromSafeStorage,
lastShownChangelogVersion,
setLastShownChangelogVersion,
isAutoLaunchEnabled,
diff --git a/desktop/src/types/ipc.ts b/desktop/src/types/ipc.ts
index 51fc284062..2c4de053bd 100644
--- a/desktop/src/types/ipc.ts
+++ b/desktop/src/types/ipc.ts
@@ -41,6 +41,18 @@ export interface NativeDeviceLockCapability {
reason?: NativeDeviceLockUnavailableReason;
}
+/**
+ * Persisted desktop app-lock configuration.
+ *
+ * This excludes the passphrase hash material, which continues to live in the
+ * renderer KV DB.
+ */
+export interface PersistedAppLockConfig {
+ enabled: boolean;
+ lockType: "pin" | "password" | "device" | "none";
+ autoLockTimeMs: number;
+}
+
export interface FolderWatch {
collectionMapping: CollectionMapping;
folderPath: string;
diff --git a/web/packages/base/components/RowButton.tsx b/web/packages/base/components/RowButton.tsx
index a66bec3e42..88686f0eee 100644
--- a/web/packages/base/components/RowButton.tsx
+++ b/web/packages/base/components/RowButton.tsx
@@ -323,6 +323,10 @@ interface RowSwitchProps {
* The state of the contained {@link EnteSwitch}.
*/
checked?: boolean;
+ /**
+ * If true, then the contained {@link EnteSwitch} will be disabled.
+ */
+ disabled?: boolean;
/**
* Called when the user activates the contained {@link EnteSwitch}.
*/
@@ -346,6 +350,7 @@ interface RowSwitchProps {
*/
export const RowSwitch: React.FC<RowSwitchProps> = ({
checked,
+ disabled,
label,
onClick,
}) => (
@@ -359,10 +364,17 @@ export const RowSwitch: React.FC<RowSwitchProps> = ({
pr: "12px",
}}
>
- <Typography sx={{ py: "14px", px: "2px", fontWeight: "medium" }}>
+ <Typography
+ sx={{
+ py: "14px",
+ px: "2px",
+ fontWeight: "medium",
+ ...(disabled ? { color: "text.muted" } : undefined),
+ }}
+ >
{label}
</Typography>
- <EnteSwitch {...{ checked, onClick }} />
+ <EnteSwitch {...{ checked, disabled, onClick }} />
</Stack>
);
diff --git a/web/packages/base/types/ipc.ts b/web/packages/base/types/ipc.ts
index 6b82a7ad7b..795ae3d239 100644
--- a/web/packages/base/types/ipc.ts
+++ b/web/packages/base/types/ipc.ts
@@ -33,6 +33,18 @@ export interface NativeDeviceLockCapability {
reason?: NativeDeviceLockUnavailableReason;
}
+/**
+ * Persisted desktop app-lock configuration.
+ *
+ * This excludes the passphrase hash material, which continues to live in the
+ * renderer KV DB.
+ */
+export interface PersistedAppLockConfig {
+ enabled: boolean;
+ lockType: "pin" | "password" | "device" | "none";
+ autoLockTimeMs: number;
+}
+
/**
* Extra APIs provided by our Node.js layer when our code is running inside our
* desktop (Electron) app.
@@ -130,6 +142,31 @@ export interface Electron {
*/
saveMasterKeyInSafeStorage: (masterKey: string) => Promise<void>;
+ /**
+ * Return true when the desktop app can currently use OS safe storage.
+ */
+ isSafeStorageAvailable: () => Promise<boolean>;
+
+ /**
+ * Return the persisted desktop app-lock configuration from safe storage, if
+ * any.
+ */
+ appLockConfigFromSafeStorage: () => Promise<
+ PersistedAppLockConfig | undefined
+ >;
+
+ /**
+ * Save the given desktop app-lock configuration to safe storage.
+ */
+ saveAppLockConfigInSafeStorage: (
+ config: PersistedAppLockConfig,
+ ) => Promise<void>;
+
+ /**
+ * Remove any persisted desktop app-lock configuration from safe storage.
+ */
+ clearAppLockConfigFromSafeStorage: () => Promise<void>;
+
/**
* Set or clear the callback {@link cb} to invoke whenever the app comes
* into the foreground. More precisely, the callback gets invoked when the
diff --git a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
index a76ee0cd0d..c1cb255ae3 100644
--- a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
+++ b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
@@ -13,6 +13,7 @@ import {
RowButtonDivider,
RowButtonEndActivityIndicator,
RowButtonGroup,
+ RowButtonGroupHint,
RowSwitch,
} from "ente-base/components/RowButton";
import { errorDialogAttributes } from "ente-base/components/utils/dialog";
@@ -58,6 +59,11 @@ export const AppLockSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({
const { showMiniDialog } = useBaseContext();
useEffect(() => {
+ if (!state.supported) {
+ setShowDeviceLockOption(false);
+ return;
+ }
+
isDeviceLockOptionRequestCancelled.current = false;
void (async () => {
@@ -80,7 +86,7 @@ export const AppLockSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({
return () => {
isDeviceLockOptionRequestCancelled.current = true;
};
- }, []);
+ }, [state.supported]);
useEffect(() => {
if (!open) {
@@ -135,6 +141,8 @@ export const AppLockSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({
}, [isSettingDeviceLock, showMiniDialog]);
const handleToggleEnabled = useCallback(() => {
+ if (!state.supported) return;
+
if (state.enabled) {
showMiniDialog({
title: t("disable"),
@@ -189,9 +197,17 @@ export const AppLockSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({
<RowSwitch
label={t("enabled")}
checked={state.enabled}
+ disabled={!state.supported}
onClick={handleToggleEnabled}
/>
</RowButtonGroup>
+ {!state.supported && (
+ <RowButtonGroupHint>
+ {t("app_lock_not_supported", {
+ defaultValue: "App lock is not supported",
+ })}
+ </RowButtonGroupHint>
+ )}
{state.enabled && (
<>
@@ -884,14 +900,18 @@ const AutoLockOptionsDrawer: React.FC<AutoLockOptionsDrawerProps> = ({
if (pendingAutoLockMs !== null || ms === currentValue) return;
setPendingAutoLockMs(ms);
- try {
- setAutoLockTime(ms);
- onClose();
- } finally {
- setPendingAutoLockMs((pending) =>
- pending === ms ? null : pending,
- );
- }
+ void (async () => {
+ try {
+ await setAutoLockTime(ms);
+ onClose();
+ } catch (e) {
+ log.error("Failed to update app lock auto-lock time", e);
+ } finally {
+ setPendingAutoLockMs((pending) =>
+ pending === ms ? null : pending,
+ );
+ }
+ })();
},
[pendingAutoLockMs, currentValue, onClose],
);
diff --git a/web/packages/new/photos/components/utils/use-app-lock.ts b/web/packages/new/photos/components/utils/use-app-lock.ts
index 5db32e84ca..c487f3fa1f 100644
--- a/web/packages/new/photos/components/utils/use-app-lock.ts
+++ b/web/packages/new/photos/components/utils/use-app-lock.ts
@@ -5,6 +5,7 @@ import {
import { updateSessionFromElectronSafeStorageIfNeeded } from "ente-base/session";
import { useEffect, useRef, useState } from "react";
import {
+ appLockSnapshot,
clearAutoLockBlurSuppression,
initAppLock,
lock,
@@ -22,15 +23,13 @@ export const useSetupAppLock = () => {
const [isAppLockReady, setIsAppLockReady] = useState(false);
useEffect(() => {
- const isAppLockEnabled =
- localStorage.getItem("appLock.enabled") === "true";
- initAppLock();
- if (!isAppLockEnabled) {
- setIsAppLockReady(true);
- return;
- }
-
void (async () => {
+ await initAppLock();
+ if (!appLockSnapshot().enabled) {
+ setIsAppLockReady(true);
+ return;
+ }
+
try {
/**
* The current session's master key might be already existing in the OS's safe
@@ -44,7 +43,7 @@ export const useSetupAppLock = () => {
* The app lock config is actually persisted across sessions, and for refreshing this
* the user must haveMasterKeyInSession().
*/
- refreshAppLockStateFromSession();
+ await refreshAppLockStateFromSession();
setIsAppLockReady(true);
}
})();
diff --git a/web/packages/new/photos/services/app-lock.ts b/web/packages/new/photos/services/app-lock.ts
index 33ac80ad0f..35cbceadc8 100644
--- a/web/packages/new/photos/services/app-lock.ts
+++ b/web/packages/new/photos/services/app-lock.ts
@@ -21,15 +21,18 @@ import { haveMasterKeyInSession } from "ente-base/session";
import type {
NativeDeviceLockCapability,
NativeDeviceLockUnavailableReason,
+ PersistedAppLockConfig,
} from "ente-base/types/ipc";
/**
* In-memory state for the app lock feature.
*
- * Some values are persisted to localStorage (synchronous, for cold-start reads)
- * and some to IndexedDB via KV DB (async, for tamper resistance).
+ * Desktop config is persisted only in Electron safe storage, while passphrase
+ * and brute-force state live in IndexedDB via KV DB.
*/
export interface AppLockState {
+ /** Whether app lock is supported in the current desktop environment. */
+ supported: boolean;
/** Whether app lock is enabled. */
enabled: boolean;
/** Active lock type. */
@@ -47,6 +50,7 @@ export interface AppLockState {
}
const createDefaultState = (): AppLockState => ({
+ supported: false,
enabled: false,
lockType: "none",
lockScreenMode: "lock",
@@ -131,13 +135,6 @@ const setSnapshot = (snapshot: AppLockState) => {
});
};
-// -- localStorage keys (synchronous, for cold-start reads) --
-// lsKey => localStorageKey
-
-const lsKeyEnabled = "appLock.enabled";
-// Stores the selected app-lock method ("pin" | "password" | "device" | "none").
-const lsKeyAppLockMethod = "appLock.lockType";
-const lsKeyAutoLockTimeMs = "appLock.autoLockTimeMs";
const ssKeySuppressNextSessionRefreshLock =
"appLock.suppressNextSessionRefreshLock";
@@ -188,7 +185,7 @@ export const clearAutoLockBlurSuppression = () => {
*/
export const suppressAppLockRefreshFromSessionForTrustedReload = () => {
try {
- if (localStorage.getItem(lsKeyEnabled) !== "true") return;
+ if (!appLockSnapshot().enabled) return;
sessionStorage.setItem(ssKeySuppressNextSessionRefreshLock, "true");
} catch {
// Ignore storage write errors; fallback to regular app-lock behavior.
@@ -275,62 +272,101 @@ const readBruteForceStateFromKV = async () => {
};
};
+/**
+ *
+ * @param value the autoLockTimeMS
+ * @returns clampedNonNegativeFinite integer value
+ *
+ * So this function is bascially a normalization function, to update the
+ * value of the autoLockTimeMs in case it becomes any non-negative/non-finite
+ * number like -4 or NaN in-case of some corruption or unexpected case.
+ */
const clampNonNegativeInt = (value: number) =>
Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
-const isDesktopMacOS = () =>
- !!globalThis.electron &&
- typeof navigator != "undefined" &&
- navigator.userAgent.toUpperCase().includes("MAC");
-
-const normalizeDeviceLockType = (lockType: AppLockState["lockType"]) =>
- lockType === "device" && !isDesktopMacOS() ? "none" : lockType;
+const defaultPersistedAppLockConfig = (): PersistedAppLockConfig => ({
+ enabled: false,
+ lockType: "none",
+ autoLockTimeMs: 0,
+});
/**
- * Shape of app-lock settings persisted in localStorage.
+ * Validates and retrieves the Electron app lock API from the global scope.
+ *
+ * Checks if the Electron API is available and has all required app lock
+ * related functions before returning it. This ensures safe access to
+ * Electron's secure storage capabilities for app lock configuration.
*
- * Used to initialize or refresh the in-memory snapshot.
+ * @returns {Object | undefined} The Electron API object with app lock methods
+ * if all required functions are available,
+ * otherwise undefined.
*/
-interface PersistedAppLockConfig {
- enabled: boolean;
- lockType: AppLockState["lockType"];
- autoLockTimeMs: number;
-}
-
-const readPersistedAppLockConfig = (): PersistedAppLockConfig => {
- let enabled = localStorage.getItem(lsKeyEnabled) === "true";
-
- // Read the currently persisted app-lock method.
- const persistedLockType = localStorage.getItem(lsKeyAppLockMethod);
- const parsedLockType: AppLockState["lockType"] =
- persistedLockType === "pin" ||
- persistedLockType === "password" ||
- persistedLockType === "device" ||
- persistedLockType === "none"
- ? persistedLockType
- : "none";
-
- // Coerce missing values to "none" and gate "device" to supported platforms.
- const lockType = normalizeDeviceLockType(parsedLockType);
-
- if (enabled && lockType === "none") {
- enabled = false;
- localStorage.setItem(lsKeyEnabled, "false");
+const appLockElectron = () => {
+ const electron = globalThis.electron;
+ if (
+ !electron ||
+ typeof electron.isSafeStorageAvailable != "function" ||
+ typeof electron.appLockConfigFromSafeStorage != "function" ||
+ typeof electron.saveAppLockConfigInSafeStorage != "function" ||
+ typeof electron.clearAppLockConfigFromSafeStorage != "function"
+ ) {
+ return undefined;
}
- if (lockType === "none") {
- localStorage.removeItem(lsKeyAppLockMethod);
- } else if (persistedLockType !== lockType) {
- localStorage.setItem(lsKeyAppLockMethod, lockType);
+ return electron;
+};
+
+const isAppLockSupported = async () => {
+ const electron = appLockElectron();
+ if (!electron) return false;
+
+ try {
+ return await electron.isSafeStorageAvailable();
+ } catch (e) {
+ log.warn("Failed to query safe storage support for app lock", e);
+ return false;
}
+};
- return {
- enabled,
- lockType,
- autoLockTimeMs: clampNonNegativeInt(
- Number(localStorage.getItem(lsKeyAutoLockTimeMs) ?? "0"),
- ),
+const readPersistedAppLockConfig =
+ async (): Promise<PersistedAppLockConfig> => {
+ const electron = appLockElectron();
+ if (!electron) {
+ throw new Error("App lock is not supported");
+ }
+
+ const persistedConfig = await electron.appLockConfigFromSafeStorage();
+ if (!persistedConfig) {
+ return defaultPersistedAppLockConfig();
+ }
+
+ return {
+ enabled: persistedConfig.enabled,
+ lockType: persistedConfig.lockType,
+ autoLockTimeMs: clampNonNegativeInt(persistedConfig.autoLockTimeMs),
+ };
};
+
+const savePersistedAppLockConfig = async (config: PersistedAppLockConfig) => {
+ const electron = appLockElectron();
+ if (!electron || !(await isAppLockSupported())) {
+ throw new Error("App lock is not supported");
+ }
+
+ await electron.saveAppLockConfigInSafeStorage({
+ enabled: config.enabled,
+ lockType: config.lockType,
+ autoLockTimeMs: clampNonNegativeInt(config.autoLockTimeMs),
+ });
+};
+
+const clearPersistedAppLockConfig = async () => {
+ const electron = appLockElectron();
+ if (!electron) {
+ throw new Error("App lock is not supported");
+ }
+
+ await electron.clearAppLockConfigFromSafeStorage();
};
/**
@@ -342,10 +378,12 @@ const readPersistedAppLockConfig = (): PersistedAppLockConfig => {
const setSnapshotFromPersistedConfig = (
config: PersistedAppLockConfig,
isLocked: boolean,
+ supported = true,
) => {
const snapshot = appLockState().snapshot;
setSnapshot({
...snapshot,
+ supported,
enabled: config.enabled,
lockType: config.lockType,
lockScreenMode: "lock",
@@ -405,24 +443,30 @@ const withUnlockAttemptLock = async <T>(fn: () => Promise<T>) => {
// -- Public API --
/**
- * Initialize app lock state from localStorage on cold start.
+ * Initialize app lock state from persistent storage on cold start.
*
- * Reads localStorage synchronously so the overlay can render immediately
- * without a flash of unlocked content. On desktop startup, it locks
- * pessimistically while safe-storage hydration is in flight.
+ * On desktop, this restores the config from Electron safe storage before
+ * gating rendering, then locks pessimistically while session hydration is in
+ * flight.
*
- * After the synchronous snapshot, asynchronously restores the brute-force
+ * After the initial snapshot, asynchronously restores the brute-force
* attempt count and cooldown expiry from KV DB so that a page refresh cannot
* bypass the cooldown.
*/
-export const initAppLock = () => {
- const config = readPersistedAppLockConfig();
+export const initAppLock = async () => {
+ if (!(await isAppLockSupported())) {
+ setSnapshot(createDefaultState());
+ stopBruteForceStateHydration();
+ return;
+ }
+
+ const config = await readPersistedAppLockConfig();
const hasSession = haveMasterKeyInSession();
// On desktop, lock pessimistically while safe-storage hydration is in flight.
const isLocked = config.enabled && (hasSession || !!globalThis.electron);
- setSnapshotFromPersistedConfig(config, isLocked);
+ setSnapshotFromPersistedConfig(config, isLocked, true);
};
/**
@@ -536,6 +580,8 @@ const resolveDeviceLockCapability = async (): Promise<DeviceLockCapability> => {
* not enrolled).
*/
export const shouldShowDeviceLockOption = async () => {
+ if (!appLockSnapshot().supported) return false;
+
const capability = await nativeDeviceLockCapability();
if (capability.available) return true;
@@ -605,15 +651,21 @@ export const cancelReauthentication = () => {
*
* Call this after desktop safe-storage restore to prevent auto-login bypass.
*/
-export const refreshAppLockStateFromSession = () => {
- const config = readPersistedAppLockConfig();
+export const refreshAppLockStateFromSession = async () => {
+ if (!(await isAppLockSupported())) {
+ setSnapshot(createDefaultState());
+ stopBruteForceStateHydration();
+ return;
+ }
+
+ const config = await readPersistedAppLockConfig();
const shouldSuppressLockForTrustedReload =
consumeAppLockRefreshSuppressionFromSession();
const isLocked =
config.enabled &&
haveMasterKeyInSession() &&
!shouldSuppressLockForTrustedReload;
- setSnapshotFromPersistedConfig(config, isLocked);
+ setSnapshotFromPersistedConfig(config, isLocked, true);
};
/**
@@ -638,6 +690,10 @@ const setupPassphraseLock = async (
lockType: Extract<AppLockState["lockType"], "pin" | "password">,
input: string,
) => {
+ if (!(await isAppLockSupported())) {
+ throw new Error("App lock is not supported");
+ }
+
const derived = await deriveInteractiveKey(input);
await Promise.all([
setKV(kvKeyHash, derived.key),
@@ -647,10 +703,12 @@ const setupPassphraseLock = async (
resetBruteForceState(),
]);
- localStorage.setItem(lsKeyAppLockMethod, lockType);
- localStorage.setItem(lsKeyEnabled, "true");
-
const snapshot = appLockState().snapshot;
+ await savePersistedAppLockConfig({
+ enabled: true,
+ lockType,
+ autoLockTimeMs: snapshot.autoLockTimeMs,
+ });
setSnapshot({
...snapshot,
enabled: true,
@@ -675,6 +733,10 @@ export const setupPassword = async (password: string) =>
* Set up native device lock authentication for app lock (macOS only).
*/
export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {
+ if (!(await isAppLockSupported())) {
+ return { status: "failed", reason: "unknown" };
+ }
+
// Resolve whether native device lock is currently usable in this environment.
// Flow: resolveDeviceLockCapability() -> nativeDeviceLockCapability() ->
// globalThis.electron.getNativeDeviceLockCapability().
@@ -703,12 +765,13 @@ export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {
// Reset brute-force lockout/cooldown state in KV and in memory.
await resetBruteForceState();
- // Save the selected app-lock method and enabled state in localStorage.
- localStorage.setItem(lsKeyAppLockMethod, "device");
- localStorage.setItem(lsKeyEnabled, "true");
-
// Update the in-memory app-lock snapshot.
const snapshot = appLockState().snapshot;
+ await savePersistedAppLockConfig({
+ enabled: true,
+ lockType: "device",
+ autoLockTimeMs: snapshot.autoLockTimeMs,
+ });
setSnapshot({
...snapshot,
enabled: true,
@@ -952,13 +1015,13 @@ export const lock = (
/**
* Clear all app lock data on logout.
*
- * Removes all localStorage and KV DB keys, and resets in-memory state to
+ * Removes all persisted config and KV DB keys, and resets in-memory state to
* defaults.
*/
export const logoutAppLock = async () => {
- localStorage.removeItem(lsKeyEnabled);
- localStorage.removeItem(lsKeyAppLockMethod);
- localStorage.removeItem(lsKeyAutoLockTimeMs);
+ if (appLockElectron()) {
+ await clearPersistedAppLockConfig();
+ }
await Promise.all([
clearPassphraseMaterial(),
@@ -974,10 +1037,18 @@ export const logoutAppLock = async () => {
/**
* Update the auto-lock delay.
*/
-export const setAutoLockTime = (ms: number) => {
+export const setAutoLockTime = async (ms: number) => {
+ if (!(await isAppLockSupported())) {
+ throw new Error("App lock is not supported");
+ }
+
const autoLockTimeMs = clampNonNegativeInt(ms);
- localStorage.setItem(lsKeyAutoLockTimeMs, String(autoLockTimeMs));
const snapshot = appLockState().snapshot;
+ await savePersistedAppLockConfig({
+ enabled: snapshot.enabled,
+ lockType: snapshot.lockType,
+ autoLockTimeMs,
+ });
setSnapshot({ ...snapshot, autoLockTimeMs });
};
@@ -985,19 +1056,25 @@ export const setAutoLockTime = (ms: number) => {
* Disable app lock entirely.
*
* Clears all stored credentials from KV DB, resets attempts and cooldown, and
- * updates localStorage and in-memory state.
+ * updates persisted config and in-memory state.
*/
export const disableAppLock = async () => {
+ if (!(await isAppLockSupported())) {
+ throw new Error("App lock is not supported");
+ }
+
await Promise.all([
clearPassphraseMaterial(),
removeKV(kvKeyInvalidAttempts),
removeKV(kvKeyCooldownExpiresAt),
]);
- localStorage.setItem(lsKeyEnabled, "false");
- localStorage.removeItem(lsKeyAppLockMethod);
-
const snapshot = appLockState().snapshot;
+ await savePersistedAppLockConfig({
+ enabled: false,
+ lockType: "none",
+ autoLockTimeMs: snapshot.autoLockTimeMs,
+ });
setSnapshot({
...snapshot,
enabled: false,