Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(appLock):adding-device-lock

Aswin Asok5de1dde63265
diff --git a/desktop/src/main/ipc.ts b/desktop/src/main/ipc.ts
index ce977a5088..b029437e54 100644
--- a/desktop/src/main/ipc.ts
+++ b/desktop/src/main/ipc.ts
@@ -27,6 +27,10 @@ import {
updateOnNextRestart,
} from "./services/app-update";
import autoLauncher from "./services/auto-launcher";
+import {
+ isDeviceLockSupported,
+ promptDeviceLock,
+} from "./services/device-lock";
import {
openDirectory,
openLogDirectory,
@@ -128,6 +132,12 @@ export const attachIPCHandlers = () => {
ipcMain.handle("toggleAutoLaunch", () => autoLauncher.toggleAutoLaunch());
+ ipcMain.handle("isDeviceLockSupported", () => isDeviceLockSupported());
+
+ ipcMain.handle("promptDeviceLock", (_, reason: string) =>
+ promptDeviceLock(reason),
+ );
+
// - App update
ipcMain.on("updateAndRestart", () => updateAndRestart());
diff --git a/desktop/src/main/services/device-lock.ts b/desktop/src/main/services/device-lock.ts
new file mode 100644
index 0000000000..a3559f655f
--- /dev/null
+++ b/desktop/src/main/services/device-lock.ts
@@ -0,0 +1,36 @@
+import { systemPreferences } from "electron/main";
+import log from "../log";
+
+/**
+ * Return true if native device lock authentication is available.
+ *
+ * Currently this uses macOS Touch ID prompt APIs from Electron.
+ */
+export const isDeviceLockSupported = () => {
+ if (process.platform !== "darwin") return false;
+
+ try {
+ return systemPreferences.canPromptTouchID();
+ } catch (e) {
+ log.warn("Failed to determine native device lock availability", e);
+ return false;
+ }
+};
+
+/**
+ * Prompt the user to unlock using native device authentication.
+ *
+ * Returns true on successful authentication. Returns false if unavailable,
+ * cancelled, or failed.
+ */
+export const promptDeviceLock = async (reason: string) => {
+ if (!isDeviceLockSupported()) return false;
+
+ try {
+ await systemPreferences.promptTouchID(reason);
+ return true;
+ } catch (e) {
+ log.info("Native device lock prompt not completed", e);
+ return false;
+ }
+};
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index ea6a7af7b2..61b81e11c4 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -129,6 +129,11 @@ const isAutoLaunchEnabled = () => ipcRenderer.invoke("isAutoLaunchEnabled");
const toggleAutoLaunch = () => ipcRenderer.invoke("toggleAutoLaunch");
+const isDeviceLockSupported = () => ipcRenderer.invoke("isDeviceLockSupported");
+
+const promptDeviceLock = (reason: string) =>
+ ipcRenderer.invoke("promptDeviceLock", reason);
+
const onMainWindowFocus = (cb: (() => void) | undefined) => {
ipcRenderer.removeAllListeners("mainWindowFocus");
if (cb) ipcRenderer.on("mainWindowFocus", cb);
@@ -365,6 +370,8 @@ contextBridge.exposeInMainWorld("electron", {
setLastShownChangelogVersion,
isAutoLaunchEnabled,
toggleAutoLaunch,
+ isDeviceLockSupported,
+ promptDeviceLock,
onMainWindowFocus,
onOpenEnteURL,
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsx
index 8a3ef25708..195bfde25d 100644
--- a/web/apps/photos/src/components/Sidebar.tsx
+++ b/web/apps/photos/src/components/Sidebar.tsx
@@ -1058,14 +1058,9 @@ const Account: React.FC<AccountProps> = ({
onClick={handleActiveSessions}
/>
</RowButtonGroup>
- {isDesktop && (
- <RowButtonGroup>
- <RowButton
- label={t("app_lock")}
- onClick={handleAppLock}
- />
- </RowButtonGroup>
- )}
+ <RowButtonGroup>
+ <RowButton label={t("app_lock")} onClick={handleAppLock} />
+ </RowButtonGroup>
<RowButtonGroup>
<RowButton
label={t("change_password")}
diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsx
index 7a16cb66dc..6657a5d1c6 100644
--- a/web/apps/photos/src/pages/_app.tsx
+++ b/web/apps/photos/src/pages/_app.tsx
@@ -75,7 +75,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
useEffect(() => {
logStartupBanner(savedLocalUser()?.id);
- if (isDesktop) initAppLock();
+ initAppLock();
void isLocalStorageAndIndexedDBMismatch().then((mismatch) => {
if (mismatch) {
log.error("Logging out (IndexedDB and local storage mismatch)");
@@ -163,9 +163,9 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
- // Auto-lock when the tab/window becomes hidden (desktop only).
+ // Auto-lock when the tab/window becomes hidden.
useEffect(() => {
- if (!isDesktop || !appLock.enabled) return;
+ if (!appLock.enabled) return;
const handleVisibilityChange = () => {
if (document.hidden && !appLock.isLocked) {
@@ -247,7 +247,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
<>
{isChangingRoute && <TranslucentLoadingOverlay />}
<Component {...pageProps} />
- {isDesktop && <AppLockOverlay />}
+ <AppLockOverlay />
</>
)}
</PhotosAppContext>
diff --git a/web/apps/photos/src/pages/index.tsx b/web/apps/photos/src/pages/index.tsx
index d990a5d273..f0e888ae7d 100644
--- a/web/apps/photos/src/pages/index.tsx
+++ b/web/apps/photos/src/pages/index.tsx
@@ -24,6 +24,7 @@ import {
type JoinAlbumContext,
} from "ente-new/albums/services/join-album";
import { DevSettings } from "ente-new/photos/components/DevSettings";
+import { refreshAppLockStateFromSession } from "ente-new/photos/services/app-lock";
import { t } from "i18next";
import { useRouter } from "next/router";
import React, { useCallback, useEffect, useRef, useState } from "react";
@@ -127,6 +128,9 @@ const Page: React.FC = () => {
});
} else {
await updateSessionFromElectronSafeStorageIfNeeded();
+ if (globalThis.electron) {
+ refreshAppLockStateFromSession();
+ }
if (
(await masterKeyFromSession()) &&
(await savedAuthToken())
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index 2706e27bc5..313f4dc75a 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -835,6 +835,13 @@
"app_lock_password_mismatch": "App lock passwords don't match",
"app_lock_incorrect": "Incorrect PIN or app lock password",
"app_lock_set_pin": "Set PIN",
+ "device_lock": "Device lock",
+ "device_lock_not_supported": "Device lock is not supported on this device",
+ "device_lock_setup_failed": "Could not enable device lock",
+ "device_lock_login_failed": "Device lock verification failed",
+ "device_lock_login_instructions": "Use your device lock (PIN, password, or biometrics) to unlock.",
+ "device_lock_login": "Unlock with device lock",
+ "device_lock_verify_description": "Verify your device lock to continue.",
"PIN": "PIN",
"auto_lock_immediately": "Immediately",
"auto_lock_5_seconds": "5 seconds",
diff --git a/web/packages/base/types/ipc.ts b/web/packages/base/types/ipc.ts
index 2aeb233b0c..d03d07db2f 100644
--- a/web/packages/base/types/ipc.ts
+++ b/web/packages/base/types/ipc.ts
@@ -158,6 +158,18 @@ export interface Electron {
*/
toggleAutoLaunch: () => Promise<void>;
+ /**
+ * Return true if native device lock authentication is available.
+ */
+ isDeviceLockSupported: () => Promise<boolean>;
+
+ /**
+ * Prompt native device lock authentication.
+ *
+ * Returns true on successful authentication.
+ */
+ promptDeviceLock: (reason: string) => Promise<boolean>;
+
// - App update
/**
diff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsx
index 71b4014566..ef2d148e21 100644
--- a/web/packages/new/photos/components/AppLockOverlay.tsx
+++ b/web/packages/new/photos/components/AppLockOverlay.tsx
@@ -2,10 +2,12 @@
* @file Full-viewport lock screen overlay for the app lock feature.
*
* Renders as a sibling of the page Component in _app.tsx, covering all content
- * when the app is locked. Supports PIN (4-digit) and password input modes,
- * with brute-force cooldown display and a logout escape hatch.
+ * when the app is locked. Supports PIN (4-digit), password, and local
+ * WebAuthn device lock unlock modes, with brute-force cooldown display and a
+ * logout escape hatch.
*/
+import FingerprintIcon from "@mui/icons-material/Fingerprint";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import {
Box,
@@ -29,12 +31,17 @@ import React, {
useRef,
useState,
} from "react";
-import { attemptUnlock, type UnlockResult } from "../services/app-lock";
+import {
+ attemptDeviceLockUnlock,
+ attemptUnlock,
+ type DeviceLockUnlockResult,
+ type UnlockResult,
+} from "../services/app-lock";
import { useAppLockSnapshot } from "./utils/use-snapshot";
/**
* A full-viewport overlay that blocks interaction with the app until the user
- * authenticates with their PIN or password.
+ * authenticates with their PIN, password, or local device lock challenge.
*
* Renders nothing when the app is not locked.
*/
@@ -110,11 +117,18 @@ export const AppLockOverlay: React.FC = () => {
appLock={appLock}
onLogout={() => setShowLogoutConfirm(true)}
/>
- ) : (
+ ) : appLock.lockType === "password" ? (
<PasswordUnlockForm
appLock={appLock}
onLogout={() => setShowLogoutConfirm(true)}
/>
+ ) : appLock.deviceLockEnabled ? (
+ <DeviceLockUnlockForm />
+ ) : (
+ <PinUnlockForm
+ appLock={appLock}
+ onLogout={() => setShowLogoutConfirm(true)}
+ />
)}
{/* Logout confirmation overlays on top */}
@@ -200,6 +214,17 @@ const useCooldownState = (
};
};
+const deviceLockErrorText = (result: DeviceLockUnlockResult) => {
+ switch (result) {
+ case "not-supported":
+ return t("device_lock_not_supported");
+ case "failed":
+ return t("device_lock_login_failed");
+ case "success":
+ return undefined;
+ }
+};
+
// -- PIN unlock form --
const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
@@ -208,6 +233,8 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
const [pin, setPin] = useState(["", "", "", ""]);
const [error, setError] = useState<string>();
const [loading, setLoading] = useState(false);
+ const [deviceLockLoading, setDeviceLockLoading] = useState(false);
+ const isDeviceLockUnlockInProgress = useRef(false);
const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
const cooldown = useCooldownState(appLock.cooldownExpiresAt);
const cooldownText = cooldown.text;
@@ -274,6 +301,24 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
focusPinInput(0);
}, [fullPin, loading, logout, focusPinInput]);
+ const handleDeviceLockUnlock = useCallback(async () => {
+ if (isDeviceLockUnlockInProgress.current) return;
+ isDeviceLockUnlockInProgress.current = true;
+ setDeviceLockLoading(true);
+ setError(undefined);
+
+ try {
+ const result = await attemptDeviceLockUnlock();
+ setError(deviceLockErrorText(result));
+ } catch (e) {
+ log.error("Device lock unlock attempt failed", e);
+ setError(t("generic_error"));
+ } finally {
+ setDeviceLockLoading(false);
+ isDeviceLockUnlockInProgress.current = false;
+ }
+ }, []);
+
// Auto-submit when all 4 digits are entered.
useEffect(() => {
if (fullPin.length === 4) {
@@ -289,6 +334,12 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
cooldownText={cooldownText}
attemptCount={appLock.invalidAttemptCount}
onLogout={onLogout}
+ onDeviceLockUnlock={
+ appLock.deviceLockEnabled
+ ? () => void handleDeviceLockUnlock()
+ : undefined
+ }
+ deviceLockLoading={deviceLockLoading}
/>
</AppLockCard>
);
@@ -357,6 +408,22 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
error={error}
attemptCount={appLock.invalidAttemptCount}
/>
+ {appLock.deviceLockEnabled && (
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ disabled={loading || deviceLockLoading}
+ onClick={() => {
+ void handleDeviceLockUnlock();
+ }}
+ >
+ {deviceLockLoading ? (
+ <CircularProgress size={18} color="inherit" />
+ ) : (
+ t("device_lock_login")
+ )}
+ </FocusVisibleButton>
+ )}
</Stack>
</AppLockCard>
);
@@ -374,6 +441,8 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({
const [showPassword, setShowPassword] = useState(false);
const [error, setError] = useState<string>();
const [loading, setLoading] = useState(false);
+ const [deviceLockLoading, setDeviceLockLoading] = useState(false);
+ const isDeviceLockUnlockInProgress = useRef(false);
const inputRef = useRef<HTMLInputElement | null>(null);
const cooldown = useCooldownState(appLock.cooldownExpiresAt);
const cooldownText = cooldown.text;
@@ -399,6 +468,24 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({
[password, loading, logout],
);
+ const handleDeviceLockUnlock = useCallback(async () => {
+ if (isDeviceLockUnlockInProgress.current) return;
+ isDeviceLockUnlockInProgress.current = true;
+ setDeviceLockLoading(true);
+ setError(undefined);
+
+ try {
+ const result = await attemptDeviceLockUnlock();
+ setError(deviceLockErrorText(result));
+ } catch (e) {
+ log.error("Device lock unlock attempt failed", e);
+ setError(t("generic_error"));
+ } finally {
+ setDeviceLockLoading(false);
+ isDeviceLockUnlockInProgress.current = false;
+ }
+ }, []);
+
if (cooldownText) {
return (
<AppLockCard>
@@ -407,6 +494,12 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({
cooldownText={cooldownText}
attemptCount={appLock.invalidAttemptCount}
onLogout={onLogout}
+ onDeviceLockUnlock={
+ appLock.deviceLockEnabled
+ ? () => void handleDeviceLockUnlock()
+ : undefined
+ }
+ deviceLockLoading={deviceLockLoading}
/>
</AppLockCard>
);
@@ -462,6 +555,22 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({
>
{t("unlock")}
</FocusVisibleButton>
+ {appLock.deviceLockEnabled && (
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ disabled={loading || deviceLockLoading}
+ onClick={() => {
+ void handleDeviceLockUnlock();
+ }}
+ >
+ {deviceLockLoading ? (
+ <CircularProgress size={18} color="inherit" />
+ ) : (
+ t("device_lock_login")
+ )}
+ </FocusVisibleButton>
+ )}
<ErrorMessage
error={error}
@@ -472,6 +581,76 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({
);
};
+// -- Device lock unlock form --
+
+const DeviceLockUnlockForm: React.FC = () => {
+ const [error, setError] = useState<string>();
+ const [loading, setLoading] = useState(false);
+ const isUnlockInProgress = useRef(false);
+
+ const handleDeviceLockUnlock = useCallback(async () => {
+ if (isUnlockInProgress.current) return;
+ isUnlockInProgress.current = true;
+ setLoading(true);
+ setError(undefined);
+
+ try {
+ const result: DeviceLockUnlockResult =
+ await attemptDeviceLockUnlock();
+ setError(deviceLockErrorText(result));
+ } catch (e) {
+ log.error("Device lock unlock attempt failed", e);
+ setError(t("generic_error"));
+ } finally {
+ setLoading(false);
+ isUnlockInProgress.current = false;
+ }
+ }, []);
+
+ return (
+ <AppLockCard>
+ <Stack
+ spacing={3}
+ alignItems="center"
+ sx={{ maxWidth: 340, width: "100%" }}
+ >
+ <FingerprintIcon sx={{ fontSize: 48, color: "text.muted" }} />
+ <Typography variant="h3">{t("app_locked")}</Typography>
+ <Typography
+ variant="small"
+ color="text.muted"
+ textAlign="center"
+ >
+ {t("device_lock_login_instructions")}
+ </Typography>
+
+ <FocusVisibleButton
+ fullWidth
+ color="accent"
+ disabled={loading}
+ onClick={() => {
+ void handleDeviceLockUnlock();
+ }}
+ >
+ {loading ? (
+ <CircularProgress size={18} color="inherit" />
+ ) : (
+ t("device_lock_login")
+ )}
+ </FocusVisibleButton>
+
+ <Typography
+ variant="small"
+ color={error ? "critical.main" : "text.muted"}
+ textAlign="center"
+ >
+ {error ?? t("device_lock_verify_description")}
+ </Typography>
+ </Stack>
+ </AppLockCard>
+ );
+};
+
// -- Shared sub-components --
interface ErrorMessageProps {
@@ -562,6 +741,8 @@ interface CooldownScreenProps {
cooldownText: string;
attemptCount: number;
onLogout: () => void;
+ onDeviceLockUnlock?: () => void;
+ deviceLockLoading?: boolean;
}
const cooldownDurationMs = (attemptCount: number): number => {
@@ -574,6 +755,8 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({
cooldownText,
attemptCount,
onLogout,
+ onDeviceLockUnlock,
+ deviceLockLoading,
}) => {
const durationMs = cooldownDurationMs(attemptCount);
const progress =
@@ -660,6 +843,21 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({
>
{nextAttemptMessage}
</Typography>
+ {onDeviceLockUnlock && (
+ <FocusVisibleButton
+ fullWidth
+ color="accent"
+ onClick={onDeviceLockUnlock}
+ disabled={deviceLockLoading}
+ sx={{ mt: 1 }}
+ >
+ {deviceLockLoading ? (
+ <CircularProgress size={18} color="inherit" />
+ ) : (
+ t("device_lock_login")
+ )}
+ </FocusVisibleButton>
+ )}
<FocusVisibleButton
fullWidth
color="secondary"
@@ -693,7 +891,7 @@ const handleUnlockResult = (
setLoading(false);
break;
case "logout":
- void Promise.resolve(logout());
+ logout();
setLoading(false);
break;
case "failed":
diff --git a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
index 3391140a21..46aa2570d7 100644
--- a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
+++ b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
@@ -17,16 +17,19 @@ import {
import { TitledMiniDialog } from "ente-base/components/MiniDialog";
import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
+import { errorDialogAttributes } from "ente-base/components/utils/dialog";
import {
TitledNestedSidebarDrawer,
type NestedSidebarDrawerVisibilityProps,
} from "ente-base/components/mui/SidebarDrawer";
import { useBaseContext } from "ente-base/context";
+import log from "ente-base/log";
import {
- setupPin,
- setupPassword,
disableAppLock,
setAutoLockTime,
+ setupDeviceLock,
+ setupPassword,
+ setupPin,
} from "../../services/app-lock";
import { t } from "i18next";
import React, { useCallback, useEffect, useRef, useState } from "react";
@@ -39,6 +42,7 @@ export const AppLockSettings: React.FC<
const [pinDialogOpen, setPinDialogOpen] = useState(false);
const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
+ const [isSettingDeviceLock, setIsSettingDeviceLock] = useState(false);
const [autoLockDialogOpen, setAutoLockDialogOpen] = useState(false);
const { showMiniDialog } = useBaseContext();
@@ -72,6 +76,29 @@ export const AppLockSettings: React.FC<
setPasswordDialogOpen(true);
}, []);
+ const handleSelectDeviceLock = useCallback(async () => {
+ if (isSettingDeviceLock) return;
+
+ setIsSettingDeviceLock(true);
+ try {
+ const result = await setupDeviceLock();
+ if (result === "success") return;
+
+ showMiniDialog(
+ errorDialogAttributes(
+ result === "not-supported"
+ ? t("device_lock_not_supported")
+ : t("device_lock_setup_failed"),
+ ),
+ );
+ } catch (e) {
+ log.error("Failed to set up device lock app lock", e);
+ showMiniDialog(errorDialogAttributes(t("device_lock_setup_failed")));
+ } finally {
+ setIsSettingDeviceLock(false);
+ }
+ }, [isSettingDeviceLock, showMiniDialog]);
+
const handlePinSetupComplete = useCallback(() => {
setPinDialogOpen(false);
}, []);
@@ -129,6 +156,26 @@ export const AppLockSettings: React.FC<
}
onClick={handleSelectPassword}
/>
+ <RowButtonDivider />
+ <RowButton
+ label={t("device_lock")}
+ caption={
+ isSettingDeviceLock
+ ? t("loading")
+ : undefined
+ }
+ disabled={isSettingDeviceLock}
+ endIcon={
+ state.deviceLockEnabled ? (
+ <CheckIcon
+ sx={{ color: "accent.main" }}
+ />
+ ) : undefined
+ }
+ onClick={() =>
+ void handleSelectDeviceLock()
+ }
+ />
</RowButtonGroup>
</Stack>
diff --git a/web/packages/new/photos/services/app-lock.ts b/web/packages/new/photos/services/app-lock.ts
index f4a01cbb91..2d13b50153 100644
--- a/web/packages/new/photos/services/app-lock.ts
+++ b/web/packages/new/photos/services/app-lock.ts
@@ -2,14 +2,19 @@
* @file Service for the app lock feature.
*
* App lock is a purely client-side feature that prevents unauthorized access to
- * the app after it has been authenticated. It supports PIN and password lock
- * types, uses Argon2id for hashing, and syncs lock state across tabs via
- * BroadcastChannel.
+ * the app after it has been authenticated. It supports PIN, password, and
+ * local WebAuthn device lock types, uses Argon2id for passphrase hashing, and
+ * syncs lock state across tabs via BroadcastChannel.
*
* See: [Note: Snapshots and useSyncExternalStore].
*/
-import { deriveInteractiveKey, deriveKey } from "ente-base/crypto";
+import {
+ deriveInteractiveKey,
+ deriveKey,
+ fromB64URLSafeNoPadding,
+ toB64URLSafeNoPadding,
+} from "ente-base/crypto";
import { getKVN, getKVS, removeKV, setKV } from "ente-base/kv";
import log from "ente-base/log";
import { haveMasterKeyInSession } from "ente-base/session";
@@ -23,8 +28,10 @@ import { haveMasterKeyInSession } from "ente-base/session";
export interface AppLockState {
/** Whether app lock is enabled. */
enabled: boolean;
- /** Active lock type. */
+ /** Active passphrase lock type. */
lockType: "pin" | "password" | "none";
+ /** Whether local WebAuthn device lock is enabled. */
+ deviceLockEnabled: boolean;
/** Whether the app is currently locked. */
isLocked: boolean;
/** Consecutive failed attempts in current lockout cycle. */
@@ -38,6 +45,7 @@ export interface AppLockState {
const createDefaultState = (): AppLockState => ({
enabled: false,
lockType: "none",
+ deviceLockEnabled: false,
isLocked: false,
invalidAttemptCount: 0,
cooldownExpiresAt: 0,
@@ -69,6 +77,8 @@ class AppLockModuleState {
/** State shared by the functions in this module. */
let _state = new AppLockModuleState();
+let _bruteForceStateHydration = Promise.resolve();
+let _bruteForceStateHydrationGeneration = 0;
/**
* A function that can be used to subscribe to updates to {@link AppLockState}.
@@ -98,6 +108,7 @@ const setSnapshot = (snapshot: AppLockState) => {
const lsKeyEnabled = "appLock.enabled";
const lsKeyLockType = "appLock.lockType";
+const lsKeyDeviceLockEnabled = "appLock.deviceLockEnabled";
const lsKeyAutoLockTimeMs = "appLock.autoLockTimeMs";
// -- KV DB keys (IndexedDB, async) --
@@ -108,6 +119,15 @@ const kvKeyOpsLimit = "appLock.opsLimit";
const kvKeyMemLimit = "appLock.memLimit";
const kvKeyInvalidAttempts = "appLock.invalidAttempts";
const kvKeyCooldownExpiresAt = "appLock.cooldownExpiresAt";
+const kvKeyWebAuthnCredentialID = "appLock.webAuthnCredentialID";
+
+// -- WebAuthn constants --
+
+const webAuthnTimeoutMs = 60_000;
+const webAuthnChallengeBytes = 32;
+const userVerifiedFlag = 0x04;
+const deviceLockEnablePromptReason = "Enable device lock for Ente";
+const deviceLockUnlockPromptReason = "Unlock Ente";
// -- BroadcastChannel for multi-tab sync --
@@ -117,6 +137,7 @@ _channel.onmessage = (event: MessageEvent) => {
const data = event.data as { type: string };
if (data.type === "lock") {
setSnapshot({ ..._state.snapshot, isLocked: true });
+ hydrateBruteForceStateIfNeeded();
} else if (data.type === "unlock") {
setSnapshot({
..._state.snapshot,
@@ -124,6 +145,7 @@ _channel.onmessage = (event: MessageEvent) => {
invalidAttemptCount: 0,
cooldownExpiresAt: 0,
});
+ stopBruteForceStateHydration();
}
};
@@ -143,14 +165,25 @@ _channel.onmessage = (event: MessageEvent) => {
export const initAppLock = () => {
const enabled = localStorage.getItem(lsKeyEnabled) === "true";
const lockTypeRaw = localStorage.getItem(lsKeyLockType);
- const lockType: AppLockState["lockType"] =
- lockTypeRaw === "pin" || lockTypeRaw === "password"
- ? lockTypeRaw
- : "none";
+ const hasPassphraseLockType =
+ lockTypeRaw === "pin" || lockTypeRaw === "password";
+ const hasLegacyDeviceLockType =
+ lockTypeRaw === "biometric" || lockTypeRaw === "deviceLock";
+ const hasDeviceLockFlag =
+ localStorage.getItem(lsKeyDeviceLockEnabled) === "true";
+ const lockType: AppLockState["lockType"] = hasPassphraseLockType
+ ? lockTypeRaw
+ : "none";
+ const deviceLockEnabled = hasDeviceLockFlag || hasLegacyDeviceLockType;
const autoLockTimeMs = Number(
localStorage.getItem(lsKeyAutoLockTimeMs) ?? "0",
);
+ if (hasLegacyDeviceLockType) {
+ localStorage.setItem(lsKeyDeviceLockEnabled, "true");
+ localStorage.removeItem(lsKeyLockType);
+ }
+
// Remove stale key from removed "hide content when switching apps" setting.
localStorage.removeItem("appLock.hideContentOnBlur");
@@ -160,15 +193,13 @@ export const initAppLock = () => {
..._state.snapshot,
enabled,
lockType,
+ deviceLockEnabled,
isLocked,
autoLockTimeMs,
});
- // Restore brute-force state from KV DB (async) so cooldowns survive
- // page refresh.
- if (isLocked) {
- void restoreBruteForceState();
- }
+ // Restore brute-force state from KV DB so cooldowns survive page refresh.
+ hydrateBruteForceStateIfNeeded();
};
/**
@@ -178,18 +209,24 @@ export const initAppLock = () => {
* Called during {@link initAppLock} to ensure that cooldown timers persist
* across page refreshes.
*/
-const restoreBruteForceState = async () => {
+const restoreBruteForceState = async (generation: number) => {
try {
const [invalidAttempts, cooldownExpiry] = await Promise.all([
getKVN(kvKeyInvalidAttempts),
getKVN(kvKeyCooldownExpiresAt),
]);
+ if (generation !== _bruteForceStateHydrationGeneration) {
+ return;
+ }
+
const invalidAttemptCount = invalidAttempts ?? 0;
const cooldownExpiresAt = cooldownExpiry ?? 0;
- // Only update if there is actually persisted brute-force state.
- if (invalidAttemptCount > 0 || cooldownExpiresAt > 0) {
+ if (
+ _state.snapshot.invalidAttemptCount !== invalidAttemptCount ||
+ _state.snapshot.cooldownExpiresAt !== cooldownExpiresAt
+ ) {
setSnapshot({
..._state.snapshot,
invalidAttemptCount,
@@ -201,6 +238,148 @@ const restoreBruteForceState = async () => {
}
};
+const stopBruteForceStateHydration = () => {
+ _bruteForceStateHydrationGeneration += 1;
+ _bruteForceStateHydration = Promise.resolve();
+};
+
+const hydrateBruteForceStateIfNeeded = () => {
+ if (!_state.snapshot.isLocked || _state.snapshot.lockType === "none") {
+ stopBruteForceStateHydration();
+ return;
+ }
+
+ const generation = ++_bruteForceStateHydrationGeneration;
+ _bruteForceStateHydration = restoreBruteForceState(generation);
+};
+
+const ensureBruteForceStateHydrated = async () => {
+ await _bruteForceStateHydration;
+};
+
+const hasWebAuthnSupport = () =>
+ (() => {
+ if (
+ typeof window == "undefined" ||
+ !window.isSecureContext ||
+ typeof PublicKeyCredential == "undefined"
+ ) {
+ return false;
+ }
+
+ const credentials: CredentialsContainer | undefined =
+ "credentials" in navigator ? navigator.credentials : undefined;
+
+ return typeof credentials != "undefined";
+ })();
+
+/**
+ * Return true if the current environment can use a platform authenticator for
+ * local device lock app unlocks.
+ */
+export const isDeviceLockSupported = async () => {
+ if (globalThis.electron) {
+ try {
+ const nativeSupported =
+ await globalThis.electron.isDeviceLockSupported();
+ if (nativeSupported) return true;
+ } catch (e) {
+ log.warn("Failed to query native device lock support", e);
+ }
+ }
+
+ if (!hasWebAuthnSupport()) return false;
+
+ if (
+ typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable !=
+ "function"
+ ) {
+ return true;
+ }
+
+ try {
+ return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
+ } catch (e) {
+ log.warn("Failed to query platform authenticator availability", e);
+ return false;
+ }
+};
+
+const randomBytes = (length: number) => {
+ const bytes = new Uint8Array(length);
+ crypto.getRandomValues(bytes);
+ return bytes;
+};
+
+const normalizeB64URLNoPadding = (value: string) =>
+ value.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+
+const parseClientDataJSON = (clientDataJSON: ArrayBuffer) => {
+ try {
+ const json = new TextDecoder().decode(clientDataJSON);
+ return JSON.parse(json) as {
+ type?: string;
+ challenge?: string;
+ origin?: string;
+ };
+ } catch (e) {
+ log.error("Failed to parse WebAuthn clientDataJSON", e);
+ return undefined;
+ }
+};
+
+const isUserVerified = (authenticatorData: ArrayBuffer) => {
+ const data = new Uint8Array(authenticatorData);
+ const flagsOffset = 32;
+ if (data.length <= flagsOffset) return false;
+ const flags = data[flagsOffset] ?? 0;
+ return (flags & userVerifiedFlag) !== 0;
+};
+
+const clearPassphraseMaterial = async () =>
+ Promise.all([
+ removeKV(kvKeyHash),
+ removeKV(kvKeySalt),
+ removeKV(kvKeyOpsLimit),
+ removeKV(kvKeyMemLimit),
+ ]);
+
+const resetBruteForceState = async () =>
+ Promise.all([
+ setKV(kvKeyInvalidAttempts, 0),
+ setKV(kvKeyCooldownExpiresAt, 0),
+ ]);
+
+const unlockLocally = () => {
+ setSnapshot({
+ ..._state.snapshot,
+ isLocked: false,
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
+ });
+ stopBruteForceStateHydration();
+ _channel.postMessage({ type: "unlock" });
+};
+
+/**
+ * Recompute and refresh whether the app should currently be locked based on
+ * session availability.
+ *
+ * Call this after desktop safe-storage restore to prevent auto-login bypass.
+ */
+export const refreshAppLockStateFromSession = () => {
+ initAppLock();
+};
+
+/**
+ * The result of a device lock setup attempt.
+ *
+ * - `"success"` - Device lock setup completed and app lock configured.
+ * - `"not-supported"` - Platform authenticator is not available.
+ * - `"failed"` - Setup failed or was cancelled.
+ */
+export type SetupDeviceLockResult = "success" | "not-supported" | "failed";
+
/**
* Set up a PIN for app lock.
*
@@ -209,10 +388,13 @@ const restoreBruteForceState = async () => {
*/
export const setupPin = async (pin: string) => {
const derived = await deriveInteractiveKey(pin);
- await setKV(kvKeyHash, derived.key);
- await setKV(kvKeySalt, derived.salt);
- await setKV(kvKeyOpsLimit, derived.opsLimit);
- await setKV(kvKeyMemLimit, derived.memLimit);
+ await Promise.all([
+ setKV(kvKeyHash, derived.key),
+ setKV(kvKeySalt, derived.salt),
+ setKV(kvKeyOpsLimit, derived.opsLimit),
+ setKV(kvKeyMemLimit, derived.memLimit),
+ resetBruteForceState(),
+ ]);
localStorage.setItem(lsKeyLockType, "pin");
localStorage.setItem(lsKeyEnabled, "true");
@@ -221,7 +403,10 @@ export const setupPin = async (pin: string) => {
..._state.snapshot,
enabled: true,
lockType: "pin",
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
});
+ stopBruteForceStateHydration();
};
/**
@@ -231,10 +416,13 @@ export const setupPin = async (pin: string) => {
*/
export const setupPassword = async (password: string) => {
const derived = await deriveInteractiveKey(password);
- await setKV(kvKeyHash, derived.key);
- await setKV(kvKeySalt, derived.salt);
- await setKV(kvKeyOpsLimit, derived.opsLimit);
- await setKV(kvKeyMemLimit, derived.memLimit);
+ await Promise.all([
+ setKV(kvKeyHash, derived.key),
+ setKV(kvKeySalt, derived.salt),
+ setKV(kvKeyOpsLimit, derived.opsLimit),
+ setKV(kvKeyMemLimit, derived.memLimit),
+ resetBruteForceState(),
+ ]);
localStorage.setItem(lsKeyLockType, "password");
localStorage.setItem(lsKeyEnabled, "true");
@@ -243,7 +431,117 @@ export const setupPassword = async (password: string) => {
..._state.snapshot,
enabled: true,
lockType: "password",
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
});
+ stopBruteForceStateHydration();
+};
+
+/**
+ * Set up local WebAuthn device lock authentication for app lock.
+ *
+ * On desktop Electron, this first tries native OS authentication; if that's
+ * unavailable, it falls back to a local WebAuthn credential flow.
+ *
+ * The WebAuthn fallback creates a platform credential locally using
+ * `navigator.credentials` without any backend ceremony. The created credential
+ * ID is stored in KV DB and used for future local unlock requests.
+ */
+export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {
+ try {
+ if (globalThis.electron) {
+ try {
+ const nativeSupported =
+ await globalThis.electron.isDeviceLockSupported();
+ if (nativeSupported) {
+ const unlocked = await globalThis.electron.promptDeviceLock(
+ deviceLockEnablePromptReason,
+ );
+ if (!unlocked) return "failed";
+
+ await resetBruteForceState();
+
+ localStorage.setItem(lsKeyDeviceLockEnabled, "true");
+ localStorage.setItem(lsKeyEnabled, "true");
+
+ setSnapshot({
+ ..._state.snapshot,
+ enabled: true,
+ deviceLockEnabled: true,
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
+ });
+ stopBruteForceStateHydration();
+
+ return "success";
+ }
+ } catch (e) {
+ log.warn(
+ "Native device lock setup unavailable, trying WebAuthn fallback",
+ e,
+ );
+ }
+ }
+
+ if (!hasWebAuthnSupport()) {
+ return "not-supported";
+ }
+
+ const challenge = randomBytes(webAuthnChallengeBytes);
+ const userID = randomBytes(webAuthnChallengeBytes);
+
+ const credential = (await navigator.credentials.create({
+ publicKey: {
+ challenge,
+ rp: { name: "Ente Photos App Lock" },
+ user: {
+ id: userID,
+ name: "ente-app-lock",
+ displayName: "Ente App Lock",
+ },
+ pubKeyCredParams: [
+ { type: "public-key", alg: -7 },
+ { type: "public-key", alg: -257 },
+ ],
+ authenticatorSelection: {
+ authenticatorAttachment: "platform",
+ userVerification: "required",
+ },
+ timeout: webAuthnTimeoutMs,
+ attestation: "none",
+ },
+ })) as PublicKeyCredential | null;
+
+ if (!credential) {
+ return "failed";
+ }
+
+ const credentialID = await toB64URLSafeNoPadding(
+ new Uint8Array(credential.rawId),
+ );
+
+ await Promise.all([
+ setKV(kvKeyWebAuthnCredentialID, credentialID),
+ resetBruteForceState(),
+ ]);
+
+ localStorage.setItem(lsKeyDeviceLockEnabled, "true");
+ localStorage.setItem(lsKeyEnabled, "true");
+
+ setSnapshot({
+ ..._state.snapshot,
+ enabled: true,
+ deviceLockEnabled: true,
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
+ });
+ stopBruteForceStateHydration();
+
+ return "success";
+ } catch (e) {
+ log.error("Failed to set up device lock app lock", e);
+ return "failed";
+ }
};
/**
@@ -256,6 +554,125 @@ export const setupPassword = async (password: string) => {
*/
export type UnlockResult = "success" | "failed" | "cooldown" | "logout";
+/**
+ * The result of a device lock unlock attempt.
+ */
+export type DeviceLockUnlockResult = "success" | "failed" | "not-supported";
+
+/**
+ * Attempt to unlock the app with a local WebAuthn device lock check.
+ *
+ * This is a fully local verification flow and does not call any backend API.
+ */
+export const attemptDeviceLockUnlock =
+ async (): Promise<DeviceLockUnlockResult> => {
+ if (globalThis.electron) {
+ try {
+ const nativeSupported =
+ await globalThis.electron.isDeviceLockSupported();
+ if (nativeSupported) {
+ const unlocked = await globalThis.electron.promptDeviceLock(
+ deviceLockUnlockPromptReason,
+ );
+ if (!unlocked) return "failed";
+
+ await resetBruteForceState();
+ unlockLocally();
+ return "success";
+ }
+ } catch (e) {
+ log.warn(
+ "Native device lock unlock unavailable, trying WebAuthn fallback",
+ e,
+ );
+ }
+ }
+
+ if (!hasWebAuthnSupport()) {
+ return "not-supported";
+ }
+
+ const storedCredentialID = await getKVS(kvKeyWebAuthnCredentialID);
+ if (!storedCredentialID) {
+ log.error("Device lock app lock credential missing from KV DB");
+ return "failed";
+ }
+
+ try {
+ const challengeBytes = randomBytes(webAuthnChallengeBytes);
+ const challengeB64 = await toB64URLSafeNoPadding(challengeBytes);
+ const storedCredentialIDBytes =
+ await fromB64URLSafeNoPadding(storedCredentialID);
+
+ const credential = (await navigator.credentials.get({
+ publicKey: {
+ challenge: challengeBytes,
+ allowCredentials: [
+ {
+ id: storedCredentialIDBytes,
+ type: "public-key",
+ transports: ["internal"],
+ },
+ ],
+ timeout: webAuthnTimeoutMs,
+ userVerification: "required",
+ },
+ })) as PublicKeyCredential | null;
+
+ if (!credential) {
+ return "failed";
+ }
+
+ const response =
+ credential.response as AuthenticatorAssertionResponse;
+ const clientData = parseClientDataJSON(response.clientDataJSON);
+ if (!clientData) {
+ return "failed";
+ }
+
+ const challengeMatches =
+ normalizeB64URLNoPadding(clientData.challenge ?? "") ===
+ challengeB64;
+ if (!challengeMatches || clientData.type !== "webauthn.get") {
+ log.error("Device lock unlock challenge verification failed");
+ return "failed";
+ }
+
+ if (clientData.origin !== window.location.origin) {
+ log.error("Device lock unlock origin verification failed");
+ return "failed";
+ }
+
+ const credentialIDMatches =
+ normalizeB64URLNoPadding(
+ await toB64URLSafeNoPadding(
+ new Uint8Array(credential.rawId),
+ ),
+ ) === normalizeB64URLNoPadding(storedCredentialID);
+ if (!credentialIDMatches) {
+ log.error("Device lock unlock credential ID mismatch");
+ return "failed";
+ }
+
+ if (!isUserVerified(response.authenticatorData)) {
+ log.error("Device lock unlock missing user verification");
+ return "failed";
+ }
+
+ await resetBruteForceState();
+ unlockLocally();
+ return "success";
+ } catch (e) {
+ // User cancellation and timeout surface as NotAllowedError.
+ if (e instanceof DOMException && e.name === "NotAllowedError") {
+ return "failed";
+ }
+
+ log.error("Failed device lock unlock attempt", e);
+ return "failed";
+ }
+ };
+
/**
* Attempt to unlock the app with the given PIN or password.
*
@@ -264,6 +681,13 @@ export type UnlockResult = "success" | "failed" | "cooldown" | "logout";
* attempts, signals that the caller should force-logout the user.
*/
export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
+ if (_state.snapshot.lockType === "none") {
+ return "failed";
+ }
+
+ // Ensure persisted lockout state has been rehydrated before enforcing.
+ await ensureBruteForceStateHydrated();
+
// Check cooldown from in-memory state.
if (
_state.snapshot.cooldownExpiresAt > 0 &&
@@ -288,17 +712,8 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
if (derivedKey === storedHash) {
// Correct input: reset attempts, unlock.
- await setKV(kvKeyInvalidAttempts, 0);
- await setKV(kvKeyCooldownExpiresAt, 0);
-
- setSnapshot({
- ..._state.snapshot,
- isLocked: false,
- invalidAttemptCount: 0,
- cooldownExpiresAt: 0,
- });
-
- _channel.postMessage({ type: "unlock" });
+ await resetBruteForceState();
+ unlockLocally();
return "success";
}
@@ -333,10 +748,7 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
// cooldown state immediately to callers/UI.
return "cooldown";
} else {
- setSnapshot({
- ..._state.snapshot,
- invalidAttemptCount: count,
- });
+ setSnapshot({ ..._state.snapshot, invalidAttemptCount: count });
}
return "failed";
@@ -347,6 +759,7 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
*/
export const lock = () => {
setSnapshot({ ..._state.snapshot, isLocked: true });
+ hydrateBruteForceStateIfNeeded();
_channel.postMessage({ type: "lock" });
};
@@ -359,15 +772,17 @@ export const lock = () => {
export const logoutAppLock = async () => {
localStorage.removeItem(lsKeyEnabled);
localStorage.removeItem(lsKeyLockType);
+ localStorage.removeItem(lsKeyDeviceLockEnabled);
localStorage.removeItem(lsKeyAutoLockTimeMs);
- await removeKV(kvKeyHash);
- await removeKV(kvKeySalt);
- await removeKV(kvKeyOpsLimit);
- await removeKV(kvKeyMemLimit);
- await removeKV(kvKeyInvalidAttempts);
- await removeKV(kvKeyCooldownExpiresAt);
+ await Promise.all([
+ clearPassphraseMaterial(),
+ removeKV(kvKeyInvalidAttempts),
+ removeKV(kvKeyCooldownExpiresAt),
+ removeKV(kvKeyWebAuthnCredentialID),
+ ]);
+ stopBruteForceStateHydration();
_state = new AppLockModuleState();
};
@@ -382,26 +797,29 @@ export const setAutoLockTime = (ms: number) => {
/**
* Disable app lock entirely.
*
- * Clears the stored hash, salt, and derivation parameters from KV DB, resets
- * attempts and cooldown, and updates localStorage and in-memory state.
+ * Clears all stored credentials from KV DB, resets attempts and cooldown, and
+ * updates localStorage and in-memory state.
*/
export const disableAppLock = async () => {
- await removeKV(kvKeyHash);
- await removeKV(kvKeySalt);
- await removeKV(kvKeyOpsLimit);
- await removeKV(kvKeyMemLimit);
- await removeKV(kvKeyInvalidAttempts);
- await removeKV(kvKeyCooldownExpiresAt);
+ await Promise.all([
+ clearPassphraseMaterial(),
+ removeKV(kvKeyInvalidAttempts),
+ removeKV(kvKeyCooldownExpiresAt),
+ removeKV(kvKeyWebAuthnCredentialID),
+ ]);
localStorage.setItem(lsKeyEnabled, "false");
localStorage.removeItem(lsKeyLockType);
+ localStorage.removeItem(lsKeyDeviceLockEnabled);
setSnapshot({
..._state.snapshot,
enabled: false,
lockType: "none",
+ deviceLockEnabled: false,
isLocked: false,
invalidAttemptCount: 0,
cooldownExpiresAt: 0,
});
+ stopBruteForceStateHydration();
};