Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(appLock):inital-implementation

Aswin Asok74344f3d3679
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsx
index 58f0b698d2..8a3ef25708 100644
--- a/web/apps/photos/src/components/Sidebar.tsx
+++ b/web/apps/photos/src/components/Sidebar.tsx
@@ -70,6 +70,7 @@ import {
} from "ente-gallery/services/video";
import { DeleteAccount } from "ente-new/photos/components/DeleteAccount";
import { DropdownInput } from "ente-new/photos/components/DropdownInput";
+import { AppLockSettings } from "ente-new/photos/components/sidebar/AppLockSettings";
import { MLSettings } from "ente-new/photos/components/sidebar/MLSettings";
import { SessionsSettings } from "ente-new/photos/components/sidebar/SessionsSettings";
import { TwoFactorSettings } from "ente-new/photos/components/sidebar/TwoFactorSettings";
@@ -956,6 +957,8 @@ const Account: React.FC<AccountProps> = ({
useModalVisibility();
const { show: showDeleteAccount, props: deleteAccountVisibilityProps } =
useModalVisibility();
+ const { show: showAppLock, props: appLockVisibilityProps } =
+ useModalVisibility();
const handleRootClose = () => {
onClose();
@@ -979,6 +982,11 @@ const Account: React.FC<AccountProps> = ({
showSessions();
}, [onAuthenticateUser, showSessions]);
+ const handleAppLock = useCallback(async () => {
+ await onAuthenticateUser();
+ showAppLock();
+ }, [onAuthenticateUser, showAppLock]);
+
useEffect(() => {
if (!open || !pendingAction) return;
switch (pendingAction) {
@@ -1050,6 +1058,14 @@ const Account: React.FC<AccountProps> = ({
onClick={handleActiveSessions}
/>
</RowButtonGroup>
+ {isDesktop && (
+ <RowButtonGroup>
+ <RowButton
+ label={t("app_lock")}
+ onClick={handleAppLock}
+ />
+ </RowButtonGroup>
+ )}
<RowButtonGroup>
<RowButton
label={t("change_password")}
@@ -1085,6 +1101,10 @@ const Account: React.FC<AccountProps> = ({
{...deleteAccountVisibilityProps}
{...{ onAuthenticateUser }}
/>
+ <AppLockSettings
+ {...appLockVisibilityProps}
+ onRootClose={onRootClose}
+ />
</TitledNestedSidebarDrawer>
);
};
diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsx
index 018e98efbb..9732ea5353 100644
--- a/web/apps/photos/src/pages/_app.tsx
+++ b/web/apps/photos/src/pages/_app.tsx
@@ -9,6 +9,7 @@ import {
savedPartialLocalUser,
} from "ente-accounts/services/accounts-db";
import { isDesktop, staticAppTitle } from "ente-base/app";
+import { subscribeMainWindowFocus } from "ente-base/electron";
import { CenteredRow } from "ente-base/components/containers";
import { CustomHeadPhotosOrAlbums } from "ente-base/components/Head";
import {
@@ -31,6 +32,7 @@ import {
initVideoProcessing,
isHLSGenerationSupported,
} from "ente-gallery/services/video";
+import { AppLockOverlay } from "ente-new/photos/components/AppLockOverlay";
import { Notification } from "ente-new/photos/components/Notification";
import { ThemedLoadingBar } from "ente-new/photos/components/ThemedLoadingBar";
import {
@@ -38,6 +40,8 @@ import {
updateReadyToInstallDialogAttributes,
} from "ente-new/photos/components/utils/download";
import { useLoadingBar } from "ente-new/photos/components/utils/use-loading-bar";
+import { initAppLock, lock } from "ente-new/photos/services/app-lock";
+import { useAppLockSnapshot } from "ente-new/photos/components/utils/use-snapshot";
import { resumeExportsIfNeeded } from "ente-new/photos/services/export";
import { runMigrations } from "ente-new/photos/services/migration";
import { initML, isMLSupported } from "ente-new/photos/services/ml";
@@ -46,7 +50,7 @@ import { PhotosAppContext } from "ente-new/photos/types/context";
import { t } from "i18next";
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { photosLogout } from "services/logout";
import "photoswipe/dist/photoswipe.css";
@@ -64,11 +68,14 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
const { loadingBarRef, showLoadingBar, hideLoadingBar } = useLoadingBar();
const [watchFolderView, setWatchFolderView] = useState(false);
+ const appLock = useAppLockSnapshot();
+ const autoLockTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const logout = useCallback(() => void photosLogout(), []);
useEffect(() => {
logStartupBanner(savedLocalUser()?.id);
+ if (isDesktop) initAppLock();
void isLocalStorageAndIndexedDBMismatch().then((mismatch) => {
if (mismatch) {
log.error("Logging out (IndexedDB and local storage mismatch)");
@@ -156,6 +163,73 @@ 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).
+ useEffect(() => {
+ if (!isDesktop || !appLock.enabled) return;
+
+ const handleVisibilityChange = () => {
+ if (document.hidden && !appLock.isLocked) {
+ autoLockTimerRef.current = setTimeout(() => {
+ lock();
+ }, appLock.autoLockTimeMs);
+ }
+ if (!document.hidden && autoLockTimerRef.current) {
+ clearTimeout(autoLockTimerRef.current);
+ autoLockTimerRef.current = null;
+ }
+ };
+
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ return () => {
+ document.removeEventListener(
+ "visibilitychange",
+ handleVisibilityChange,
+ );
+ if (autoLockTimerRef.current) {
+ clearTimeout(autoLockTimerRef.current);
+ autoLockTimerRef.current = null;
+ }
+ };
+ }, [appLock.enabled, appLock.isLocked, appLock.autoLockTimeMs]);
+
+ // Blur main content when tab is hidden to prevent content from appearing
+ // in tab previews and Alt+Tab thumbnails (desktop only).
+ useEffect(() => {
+ if (!isDesktop || !appLock.hideContentOnBlur) return;
+
+ const el = document.getElementById("__next");
+ if (!el) return;
+
+ const handleVisibilityChange = () => {
+ el.style.filter = document.hidden ? "blur(30px)" : "";
+ };
+
+ handleVisibilityChange();
+
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ return () => {
+ document.removeEventListener(
+ "visibilitychange",
+ handleVisibilityChange,
+ );
+ el.style.filter = "";
+ };
+ }, [appLock.hideContentOnBlur]);
+
+ // On Electron, clear the auto-lock timer when the main window regains focus.
+ useEffect(() => {
+ if (!appLock.enabled) return;
+
+ const handleFocus = () => {
+ if (autoLockTimerRef.current) {
+ clearTimeout(autoLockTimerRef.current);
+ autoLockTimerRef.current = null;
+ }
+ };
+
+ return subscribeMainWindowFocus(handleFocus);
+ }, [appLock.enabled]);
+
const baseContext = useMemo(
() => deriveBaseContext({ logout, showMiniDialog }),
[logout, showMiniDialog],
@@ -197,6 +271,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {
<>
{isChangingRoute && <TranslucentLoadingOverlay />}
<Component {...pageProps} />
+ {isDesktop && <AppLockOverlay />}
</>
)}
</PhotosAppContext>
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 46798dad27..073e6391b0 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -35,6 +35,7 @@ import { errorDialogAttributes } from "ente-base/components/utils/dialog";
import { useIsSmallWidth } from "ente-base/components/utils/hooks";
import { useModalVisibility } from "ente-base/components/utils/modal";
import { useBaseContext } from "ente-base/context";
+import { subscribeMainWindowFocus } from "ente-base/electron";
import log from "ente-base/log";
import {
clearSessionStorage,
@@ -374,6 +375,7 @@ const Page: React.FC = () => {
useEffect(() => {
const electron = globalThis.electron;
let syncIntervalID: ReturnType<typeof setInterval> | undefined;
+ let unsubscribeMainWindowFocus = () => {};
void (async () => {
if (!haveMasterKeyInSession() || !(await savedAuthToken())) {
@@ -467,7 +469,7 @@ const Page: React.FC = () => {
);
if (electron) {
- electron.onMainWindowFocus(() => {
+ unsubscribeMainWindowFocus = subscribeMainWindowFocus(() => {
remotePull({ silent: true });
void watcher.checkAccessibility();
});
@@ -477,7 +479,7 @@ const Page: React.FC = () => {
return () => {
clearInterval(syncIntervalID);
- if (electron) electron.onMainWindowFocus(undefined);
+ unsubscribeMainWindowFocus();
};
}, []);
diff --git a/web/apps/photos/src/services/logout.ts b/web/apps/photos/src/services/logout.ts
index 47c069be0e..1ed62c70dc 100644
--- a/web/apps/photos/src/services/logout.ts
+++ b/web/apps/photos/src/services/logout.ts
@@ -8,6 +8,7 @@ import { downloadManager } from "ente-gallery/services/download";
import { clearFilesDB } from "ente-gallery/services/files-db";
import { resetUploadState } from "ente-gallery/services/upload";
import { resetVideoState } from "ente-gallery/services/video";
+import { logoutAppLock } from "ente-new/photos/services/app-lock";
import exportService from "ente-new/photos/services/export";
import { logoutML, terminateMLWorker } from "ente-new/photos/services/ml";
import { logoutSearch } from "ente-new/photos/services/search";
@@ -103,6 +104,12 @@ export const photosLogout = async () => {
const electron = globalThis.electron;
if (electron) {
+ try {
+ await logoutAppLock();
+ } catch (e) {
+ ignoreError("App lock", e);
+ }
+
try {
await logoutML();
} catch (e) {
diff --git a/web/packages/base/electron.ts b/web/packages/base/electron.ts
index d7af86c47b..8b9fe9aab8 100644
--- a/web/packages/base/electron.ts
+++ b/web/packages/base/electron.ts
@@ -23,3 +23,51 @@ export const ensureElectron = (): Electron => {
"Attempting to assert globalThis.electron in a non-electron context",
);
};
+
+type MainWindowFocusListener = () => void;
+
+const mainWindowFocusListeners = new Set<MainWindowFocusListener>();
+let hasAttachedMainWindowFocusBridge = false;
+
+const emitMainWindowFocus = () => {
+ for (const listener of mainWindowFocusListeners) {
+ listener();
+ }
+};
+
+const attachMainWindowFocusBridgeIfNeeded = () => {
+ if (hasAttachedMainWindowFocusBridge) return;
+ const electron = globalThis.electron;
+ if (!electron) return;
+ electron.onMainWindowFocus(emitMainWindowFocus);
+ hasAttachedMainWindowFocusBridge = true;
+};
+
+const detachMainWindowFocusBridgeIfNeeded = () => {
+ if (!hasAttachedMainWindowFocusBridge || mainWindowFocusListeners.size > 0) {
+ return;
+ }
+
+ const electron = globalThis.electron;
+ if (electron) {
+ electron.onMainWindowFocus(undefined);
+ }
+ hasAttachedMainWindowFocusBridge = false;
+};
+
+/**
+ * Subscribe to main window focus events on Electron.
+ *
+ * This helper multiplexes listeners over Electron's single-callback API,
+ * allowing multiple consumers to listen concurrently.
+ */
+export const subscribeMainWindowFocus = (
+ listener: MainWindowFocusListener,
+): (() => void) => {
+ mainWindowFocusListeners.add(listener);
+ attachMainWindowFocusBridgeIfNeeded();
+ return () => {
+ mainWindowFocusListeners.delete(listener);
+ detachMainWindowFocusBridgeIfNeeded();
+ };
+};
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index ef6d80e56e..f2a069b3c1 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -811,5 +811,28 @@
"add_location": "Add location",
"add_location_button": "Add",
"save_location": "Save location",
- "search_location": "Search for a location"
+ "search_location": "Search for a location",
+ "app_lock": "App lock",
+ "app_locked": "App locked",
+ "enter_pin": "Enter your PIN",
+ "enter_password": "Enter your password",
+ "confirm_pin": "Confirm your PIN",
+ "confirm": "Confirm",
+ "incorrect_pin_or_password": "Incorrect PIN or password",
+ "too_many_attempts": "Too many attempts.",
+ "try_again_in": "Try again in {{time}}.",
+ "too_many_wrong_attempts": "Too many wrong attempts. Please log out and log in again.",
+ "app_lock_disable_confirm": "Are you sure you want to disable app lock?",
+ "lock_type": "Lock type",
+ "auto_lock": "Auto-lock",
+ "auto_lock_hint": "Automatically lock the app after a period of inactivity",
+ "hide_content_on_blur": "Hide content when switching apps",
+ "pin_mismatch": "PINs don't match",
+ "password_mismatch": "Passwords don't match",
+ "app_lock_password": "App lock password",
+ "app_lock_enter_password": "Enter your app lock password",
+ "app_lock_confirm_password": "Confirm your app lock password",
+ "app_lock_set_password": "Set app lock password",
+ "app_lock_password_mismatch": "App lock passwords don't match",
+ "app_lock_incorrect": "Incorrect PIN or app lock password"
}
diff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsx
new file mode 100644
index 0000000000..02bad5667b
--- /dev/null
+++ b/web/packages/new/photos/components/AppLockOverlay.tsx
@@ -0,0 +1,703 @@
+/**
+ * @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.
+ */
+
+import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
+import {
+ Backdrop,
+ Box,
+ CircularProgress,
+ Paper,
+ Portal,
+ Stack,
+ TextField,
+ Typography,
+} from "@mui/material";
+import { EnteLogo } from "ente-base/components/EnteLogo";
+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
+import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
+import { useBaseContext } from "ente-base/context";
+import { subscribeMainWindowFocus } from "ente-base/electron";
+import log from "ente-base/log";
+import { t } from "i18next";
+import React, {
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import {
+ attemptUnlock,
+ 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.
+ *
+ * Renders nothing when the app is not locked.
+ */
+export const AppLockOverlay: React.FC = () => {
+ const appLock = useAppLockSnapshot();
+ const { logout, showMiniDialog } = useBaseContext();
+ const [now, setNow] = useState(() => Date.now());
+
+ const handleLogout = useCallback(
+ () =>
+ showMiniDialog({
+ message: t("logout_message"),
+ continue: {
+ text: t("logout"),
+ color: "critical",
+ action: logout,
+ },
+ buttonDirection: "row",
+ }),
+ [logout, showMiniDialog],
+ );
+
+ useEffect(() => {
+ if (appLock.cooldownExpiresAt <= Date.now()) {
+ setNow(Date.now());
+ return;
+ }
+
+ const interval = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(interval);
+ }, [appLock.cooldownExpiresAt]);
+
+ const isInCooldown = appLock.cooldownExpiresAt > now;
+
+ if (!appLock.isLocked) return null;
+
+ return (
+ <Portal>
+ <Backdrop
+ open
+ role="dialog"
+ aria-modal="true"
+ aria-label={t("app_lock")}
+ style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}
+ sx={{
+ zIndex: "calc(var(--mui-zIndex-tooltip) + 1)",
+ backgroundColor: "var(--mui-palette-background-default)",
+ flexDirection: "column",
+ pointerEvents: "auto",
+ }}
+ >
+ {/* Top bar: logo centered, logout button at top-right */}
+ <Box
+ sx={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ right: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ p: 3,
+ }}
+ >
+ <EnteLogo />
+ {!isInCooldown && (
+ <FocusVisibleButton
+ variant="text"
+ color="secondary"
+ size="small"
+ onClick={handleLogout}
+ sx={{
+ textTransform: "none",
+ position: "absolute",
+ right: 24,
+ color: "text.muted",
+ }}
+ >
+ {t("logout")}
+ </FocusVisibleButton>
+ )}
+ </Box>
+
+ {/* Centered form content */}
+ {appLock.lockType === "pin" ? (
+ <PinUnlockForm appLock={appLock} onLogout={handleLogout} />
+ ) : (
+ <PasswordUnlockForm
+ appLock={appLock}
+ onLogout={handleLogout}
+ />
+ )}
+ </Backdrop>
+ </Portal>
+ );
+};
+
+// -- Shared types and helpers --
+
+interface UnlockFormProps {
+ appLock: ReturnType<typeof useAppLockSnapshot>;
+ onLogout: () => void;
+}
+
+const AppLockCard: React.FC<React.PropsWithChildren> = ({ children }) => (
+ <Paper
+ elevation={0}
+ sx={{
+ width: "min(420px, 85vw)",
+ minHeight: "375px",
+ px: { xs: 3, sm: 5 },
+ py: 5,
+ borderRadius: "20px",
+ boxShadow: "var(--mui-palette-boxShadow-paper)",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ {children}
+ </Paper>
+);
+
+/**
+ * Format remaining cooldown seconds into a human-readable string.
+ */
+const formatCooldown = (remainingMs: number): string => {
+ const totalSeconds = Math.ceil(remainingMs / 1000);
+ const minutes = Math.floor(totalSeconds / 60);
+ const seconds = totalSeconds % 60;
+ if (minutes > 0) {
+ return `${String(minutes)}m ${String(seconds)}s`;
+ }
+ return `${String(seconds)}s`;
+};
+
+/**
+ * Hook that returns remaining cooldown time state, updating every second.
+ */
+const useCooldownState = (
+ cooldownExpiresAt: number,
+): { remainingMs: number; text: string | undefined } => {
+ const [remaining, setRemaining] = useState<number>(
+ Math.max(0, cooldownExpiresAt - Date.now()),
+ );
+
+ useEffect(() => {
+ if (cooldownExpiresAt <= 0) {
+ setRemaining(0);
+ return;
+ }
+
+ const update = () => {
+ const r = Math.max(0, cooldownExpiresAt - Date.now());
+ setRemaining(r);
+ };
+ update();
+
+ const interval = setInterval(update, 1000);
+ return () => clearInterval(interval);
+ }, [cooldownExpiresAt]);
+
+ return {
+ remainingMs: remaining,
+ text: remaining > 0 ? formatCooldown(remaining) : undefined,
+ };
+};
+
+/**
+ * Keep an input focused (with a visible caret) across mount and window/tab
+ * visibility/focus transitions.
+ */
+const useRestoreInputFocus = (
+ getInput: () => HTMLInputElement | null | undefined,
+) => {
+ useEffect(() => {
+ const focusInput = () => {
+ const input = getInput();
+ if (!input) return;
+
+ input.focus({ preventScroll: true });
+ // Explicitly place caret to avoid "focused but no cursor" states
+ // seen after window minimize/restore in desktop.
+ try {
+ const pos = input.value.length;
+ input.setSelectionRange(pos, pos);
+ } catch {
+ // Some input modes/types may not support selection APIs.
+ }
+ };
+
+ const refocus = () => {
+ focusInput();
+ requestAnimationFrame(focusInput);
+ setTimeout(focusInput, 0);
+ };
+
+ const timer = setTimeout(refocus, 100);
+ const handleVisibilityChange = () => {
+ if (document.visibilityState === "visible") {
+ refocus();
+ }
+ };
+
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ window.addEventListener("focus", refocus);
+ window.addEventListener("pageshow", refocus);
+ const unsubscribeMainWindowFocus = subscribeMainWindowFocus(refocus);
+
+ return () => {
+ clearTimeout(timer);
+ document.removeEventListener(
+ "visibilitychange",
+ handleVisibilityChange,
+ );
+ window.removeEventListener("focus", refocus);
+ window.removeEventListener("pageshow", refocus);
+ unsubscribeMainWindowFocus();
+ };
+ }, [getInput]);
+};
+
+// -- PIN unlock form --
+
+const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
+ const { logout } = useBaseContext();
+
+ const [pin, setPin] = useState(["", "", "", ""]);
+ const [error, setError] = useState<string>();
+ const [loading, setLoading] = useState(false);
+ const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
+ const cooldown = useCooldownState(appLock.cooldownExpiresAt);
+ const cooldownText = cooldown.text;
+
+ useRestoreInputFocus(
+ useCallback(() => inputRefs.current[0], []),
+ );
+
+ const handlePinChange = useCallback(
+ (index: number, value: string) => {
+ // Extract the last digit, ignoring non-digit characters.
+ const digit = value.replace(/\D/g, "").slice(-1);
+
+ const newPin = [...pin];
+ newPin[index] = digit;
+ setPin(newPin);
+ setError(undefined);
+
+ // Auto-advance to next field.
+ if (digit && index < 3) {
+ inputRefs.current[index + 1]?.focus();
+ }
+ },
+ [pin],
+ );
+
+ const handleKeyDown = useCallback(
+ (index: number, e: React.KeyboardEvent) => {
+ if (e.key === "Backspace" && !pin[index] && index > 0) {
+ inputRefs.current[index - 1]?.focus();
+ }
+ },
+ [pin],
+ );
+
+ const fullPin = useMemo(() => pin.join(""), [pin]);
+ const focusPinInput = useCallback(
+ (index: number) => {
+ const input = inputRefs.current[index];
+ if (!input) return;
+ input.focus({ preventScroll: true });
+ try {
+ const pos = input.value.length;
+ input.setSelectionRange(pos, pos);
+ } catch {
+ // Ignore if selection range isn't supported.
+ }
+ },
+ [],
+ );
+ const focusFirstEmptyPinInput = useCallback(() => {
+ const firstEmptyIndex = pin.findIndex((digit) => !digit);
+ focusPinInput(firstEmptyIndex === -1 ? 0 : firstEmptyIndex);
+ }, [pin, focusPinInput]);
+
+ const handleSubmit = useCallback(async () => {
+ if (fullPin.length !== 4 || loading) return;
+
+ setLoading(true);
+ try {
+ const result: UnlockResult = await attemptUnlock(fullPin);
+ handleUnlockResult(result, setError, setLoading, logout);
+ } catch (e) {
+ log.error("Unlock attempt failed", e);
+ setError(t("generic_error"));
+ setLoading(false);
+ }
+
+ // Clear PIN on any non-success.
+ setPin(["", "", "", ""]);
+ focusPinInput(0);
+ }, [fullPin, loading, logout, focusPinInput]);
+
+ // Auto-submit when all 4 digits are entered.
+ useEffect(() => {
+ if (fullPin.length === 4) {
+ void handleSubmit();
+ }
+ }, [fullPin, handleSubmit]);
+
+ if (cooldownText) {
+ return (
+ <AppLockCard>
+ <CooldownScreen
+ remainingMs={cooldown.remainingMs}
+ cooldownText={cooldownText}
+ attemptCount={appLock.invalidAttemptCount}
+ onLogout={onLogout}
+ />
+ </AppLockCard>
+ );
+ }
+
+ return (
+ <AppLockCard>
+ <Stack
+ spacing={2}
+ alignItems="center"
+ sx={{ maxWidth: 340, width: "100%" }}
+ >
+ <LockOutlinedIcon sx={{ fontSize: 48, color: "text.muted" }} />
+ <Typography variant="h3">{t("app_locked")}</Typography>
+ <Typography variant="small" color="text.muted" sx={{ mb: 1 }}>
+ {t("enter_pin")}
+ </Typography>
+
+ <Stack
+ direction="row"
+ spacing={1.5}
+ justifyContent="center"
+ onClick={focusFirstEmptyPinInput}
+ >
+ {pin.map((digit, i) => (
+ <TextField
+ key={i}
+ hiddenLabel
+ inputRef={(el: HTMLInputElement | null) => {
+ inputRefs.current[i] = el;
+ }}
+ value={digit}
+ onChange={(e) => handlePinChange(i, e.target.value)}
+ onKeyDown={(e) => handleKeyDown(i, e)}
+ disabled={loading}
+ slotProps={{
+ htmlInput: {
+ maxLength: 1,
+ inputMode: "numeric",
+ pattern: "[0-9]",
+ autoComplete: "off",
+ style: {
+ textAlign: "center",
+ fontSize: "1.25rem",
+ padding: "12px 0",
+ WebkitTextSecurity: "disc",
+ },
+ "aria-label": `PIN digit ${String(i + 1)}`,
+ },
+ }}
+ sx={{
+ width: 48,
+ "& .MuiOutlinedInput-root.Mui-focused .MuiOutlinedInput-notchedOutline":
+ {
+ borderColor: "accent.main",
+ borderWidth: 2,
+ },
+ }}
+ />
+ ))}
+ </Stack>
+
+ <ErrorMessage
+ error={error}
+ attemptCount={appLock.invalidAttemptCount}
+ />
+ </Stack>
+ </AppLockCard>
+ );
+};
+
+// -- Password unlock form --
+
+const PasswordUnlockForm: React.FC<UnlockFormProps> = ({
+ appLock,
+ onLogout,
+}) => {
+ const { logout } = useBaseContext();
+
+ const [password, setPassword] = useState("");
+ const [showPassword, setShowPassword] = useState(false);
+ const [error, setError] = useState<string>();
+ const [loading, setLoading] = useState(false);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const cooldown = useCooldownState(appLock.cooldownExpiresAt);
+ const cooldownText = cooldown.text;
+
+ useRestoreInputFocus(useCallback(() => inputRef.current, []));
+
+ const handleSubmit = useCallback(
+ async (e?: React.FormEvent) => {
+ e?.preventDefault();
+ if (!password || loading) return;
+
+ setLoading(true);
+ try {
+ const result: UnlockResult = await attemptUnlock(password);
+ handleUnlockResult(result, setError, setLoading, logout);
+ } catch (e) {
+ log.error("Unlock attempt failed", e);
+ setError(t("generic_error"));
+ setLoading(false);
+ }
+
+ setPassword("");
+ },
+ [password, loading, logout],
+ );
+
+ if (cooldownText) {
+ return (
+ <AppLockCard>
+ <CooldownScreen
+ remainingMs={cooldown.remainingMs}
+ cooldownText={cooldownText}
+ attemptCount={appLock.invalidAttemptCount}
+ onLogout={onLogout}
+ />
+ </AppLockCard>
+ );
+ }
+
+ return (
+ <AppLockCard>
+ <Stack
+ component="form"
+ onSubmit={(e: React.FormEvent) => void handleSubmit(e)}
+ spacing={3}
+ alignItems="center"
+ sx={{ maxWidth: 340, width: "100%" }}
+ >
+ <LockOutlinedIcon sx={{ fontSize: 48, color: "text.muted" }} />
+ <Typography variant="h3">{t("app_locked")}</Typography>
+ <Typography variant="small" color="text.muted">
+ {t("app_lock_enter_password")}
+ </Typography>
+
+ <TextField
+ inputRef={inputRef}
+ fullWidth
+ hiddenLabel
+ type={showPassword ? "text" : "password"}
+ value={password}
+ onChange={(e) => {
+ setPassword(e.target.value);
+ setError(undefined);
+ }}
+ disabled={loading}
+ placeholder={t("app_lock_password")}
+ autoComplete="off"
+ slotProps={{
+ input: {
+ endAdornment: (
+ <ShowHidePasswordInputAdornment
+ showPassword={showPassword}
+ onToggle={() => setShowPassword((s) => !s)}
+ />
+ ),
+ },
+ }}
+ />
+
+ <FocusVisibleButton
+ type="submit"
+ fullWidth
+ color="accent"
+ disabled={!password || loading}
+ >
+ {t("unlock")}
+ </FocusVisibleButton>
+
+ <ErrorMessage
+ error={error}
+ attemptCount={appLock.invalidAttemptCount}
+ />
+ </Stack>
+ </AppLockCard>
+ );
+};
+
+// -- Shared sub-components --
+
+interface ErrorMessageProps {
+ error: string | undefined;
+ attemptCount: number;
+}
+
+const ErrorMessage: React.FC<ErrorMessageProps> = ({
+ error,
+ attemptCount,
+}) => {
+ if (error) {
+ return (
+ <Typography variant="small" color="critical.main" textAlign="center">
+ {error}
+ {attemptCount > 0 &&
+ ` (${String(attemptCount)}/10)`}
+ </Typography>
+ );
+ }
+ return null;
+};
+
+interface CooldownScreenProps {
+ remainingMs: number;
+ cooldownText: string;
+ attemptCount: number;
+ onLogout: () => void;
+}
+
+const cooldownDurationMs = (attemptCount: number): number => {
+ if (attemptCount < 5) return 0;
+ return Math.pow(2, attemptCount - 5) * 30 * 1000;
+};
+
+const CooldownScreen: React.FC<CooldownScreenProps> = ({
+ remainingMs,
+ cooldownText,
+ attemptCount,
+ onLogout,
+}) => {
+ const durationMs = cooldownDurationMs(attemptCount);
+ const progress =
+ durationMs > 0
+ ? Math.min(100, ((durationMs - remainingMs) / durationMs) * 100)
+ : 0;
+ const nextAttemptCount = attemptCount + 1;
+ const nextCooldownMs = cooldownDurationMs(nextAttemptCount);
+ const attemptsLabel = attemptCount === 1 ? "time" : "times";
+ const nextAttemptMessage =
+ nextAttemptCount >= 10
+ ? "One more wrong attempt will log you out."
+ : `After the next wrong attempt, you'll need to wait ${formatCooldown(nextCooldownMs)}.`;
+
+ return (
+ <Stack
+ spacing={1.25}
+ useFlexGap
+ alignItems="center"
+ justifyContent="center"
+ sx={{ maxWidth: 340, width: "100%", px: 2 }}
+ >
+ <Typography
+ variant="h3"
+ color="text.primary"
+ textAlign="center"
+ sx={{ mb: 2.5 }}
+ >
+ {t("app_locked")}
+ </Typography>
+
+ <Box sx={{ position: "relative", display: "inline-flex", mb: 2 }}>
+ <CircularProgress
+ variant="determinate"
+ value={100}
+ size={112}
+ thickness={2.2}
+ sx={{ color: "var(--mui-palette-fill-faint)" }}
+ />
+ <CircularProgress
+ variant="determinate"
+ value={progress}
+ size={112}
+ thickness={2.6}
+ sx={{
+ position: "absolute",
+ left: 0,
+ color: "critical.main",
+ }}
+ />
+ <Box
+ sx={{
+ position: "absolute",
+ inset: 0,
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ }}
+ >
+ <Typography variant="body" color="critical.main" textAlign="center">
+ {cooldownText}
+ </Typography>
+ </Box>
+ </Box>
+
+ <Typography variant="small" color="text.muted" textAlign="center">
+ {`You've entered the wrong unlock code ${String(attemptCount)} ${attemptsLabel}.`}
+ </Typography>
+ <Typography
+ variant="mini"
+ color="text.muted"
+ textAlign="center"
+ sx={{
+ width: "100%",
+ pt: 0.75,
+ borderTop: "1px solid var(--mui-palette-divider)",
+ opacity: 0.9,
+ }}
+ >
+ {nextAttemptMessage}
+ </Typography>
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ onClick={onLogout}
+ sx={{ mt: 1 }}
+ >
+ {t("logout")}
+ </FocusVisibleButton>
+ </Stack>
+ );
+};
+
+// -- Helpers --
+
+/**
+ * Handle the result of an unlock attempt, updating UI state accordingly.
+ */
+const handleUnlockResult = (
+ result: UnlockResult,
+ setError: (error: string | undefined) => void,
+ setLoading: (loading: boolean) => void,
+ logout: () => void,
+) => {
+ switch (result) {
+ case "success":
+ setError(undefined);
+ setLoading(false);
+ break;
+ case "cooldown":
+ setError(undefined);
+ setLoading(false);
+ break;
+ case "logout":
+ void Promise.resolve(logout());
+ setLoading(false);
+ break;
+ case "failed":
+ setError(t("app_lock_incorrect"));
+ setLoading(false);
+ break;
+ }
+};
diff --git a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
new file mode 100644
index 0000000000..11f0ac534a
--- /dev/null
+++ b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx
@@ -0,0 +1,610 @@
+import CheckIcon from "@mui/icons-material/Check";
+import ChevronRightIcon from "@mui/icons-material/ChevronRight";
+import {
+ DialogActions,
+ Stack,
+ TextField,
+ Typography,
+} from "@mui/material";
+import {
+ RowButton,
+ RowButtonDivider,
+ RowButtonGroup,
+ RowButtonGroupHint,
+ RowSwitch,
+} from "ente-base/components/RowButton";
+import { TitledMiniDialog } from "ente-base/components/MiniDialog";
+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
+import { ShowHidePasswordInputAdornment } from "ente-base/components/mui/PasswordInputAdornment";
+import {
+ TitledNestedSidebarDrawer,
+ type NestedSidebarDrawerVisibilityProps,
+} from "ente-base/components/mui/SidebarDrawer";
+import { useBaseContext } from "ente-base/context";
+import {
+ setupPin,
+ setupPassword,
+ disableAppLock,
+ setAutoLockTime,
+ setHideContentOnBlur,
+} from "../../services/app-lock";
+import { t } from "i18next";
+import React, { useCallback, useRef, useState } from "react";
+import { useAppLockSnapshot } from "../utils/use-snapshot";
+
+export const AppLockSettings: React.FC<
+ NestedSidebarDrawerVisibilityProps
+> = ({ open, onClose, onRootClose }) => {
+ const state = useAppLockSnapshot();
+
+ const [pinDialogOpen, setPinDialogOpen] = useState(false);
+ const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);
+ const [autoLockDialogOpen, setAutoLockDialogOpen] = useState(false);
+
+ const { showMiniDialog } = useBaseContext();
+
+ const handleRootClose = () => {
+ onClose();
+ onRootClose();
+ };
+
+ const handleToggleEnabled = useCallback(() => {
+ if (state.enabled) {
+ showMiniDialog({
+ title: t("disable"),
+ message: t("app_lock_disable_confirm"),
+ continue: {
+ text: t("disable"),
+ color: "critical",
+ action: () => void disableAppLock(),
+ },
+ });
+ } else {
+ // When enabling, default to PIN setup.
+ setPinDialogOpen(true);
+ }
+ }, [state.enabled, showMiniDialog]);
+
+ const handleSelectPin = useCallback(() => {
+ setPinDialogOpen(true);
+ }, []);
+
+ const handleSelectPassword = useCallback(() => {
+ setPasswordDialogOpen(true);
+ }, []);
+
+ const handlePinSetupComplete = useCallback(() => {
+ setPinDialogOpen(false);
+ }, []);
+
+ const handlePasswordSetupComplete = useCallback(() => {
+ setPasswordDialogOpen(false);
+ }, []);
+
+ const handleToggleHideContent = useCallback(() => {
+ setHideContentOnBlur(!state.hideContentOnBlur);
+ }, [state.hideContentOnBlur]);
+
+ return (
+ <>
+ <TitledNestedSidebarDrawer
+ {...{ open, onClose }}
+ onRootClose={handleRootClose}
+ title={t("app_lock")}
+ >
+ <Stack sx={{ px: "16px", py: "20px", gap: "24px" }}>
+ <RowButtonGroup>
+ <RowSwitch
+ label={t("enabled")}
+ checked={state.enabled}
+ onClick={handleToggleEnabled}
+ />
+ </RowButtonGroup>
+
+ {state.enabled && (
+ <>
+ <Stack>
+ <Typography
+ variant="small"
+ sx={{ px: 1, pb: "6px", color: "text.muted" }}
+ >
+ {t("lock_type")}
+ </Typography>
+ <RowButtonGroup>
+ <RowButton
+ label="PIN"
+ endIcon={
+ state.lockType === "pin" ? (
+ <CheckIcon
+ sx={{ color: "accent.main" }}
+ />
+ ) : undefined
+ }
+ onClick={handleSelectPin}
+ />
+ <RowButtonDivider />
+ <RowButton
+ label={t("app_lock_password")}
+ endIcon={
+ state.lockType === "password" ? (
+ <CheckIcon
+ sx={{ color: "accent.main" }}
+ />
+ ) : undefined
+ }
+ onClick={handleSelectPassword}
+ />
+ </RowButtonGroup>
+ </Stack>
+
+ <Stack>
+ <RowButtonGroup>
+ <RowButton
+ label={t("auto_lock")}
+ endIcon={<ChevronRightIcon />}
+ caption={autoLockLabel(
+ state.autoLockTimeMs,
+ )}
+ onClick={() =>
+ setAutoLockDialogOpen(true)
+ }
+ />
+ </RowButtonGroup>
+ <RowButtonGroupHint>
+ {t("auto_lock_hint")}
+ </RowButtonGroupHint>
+ </Stack>
+ </>
+ )}
+
+ <RowButtonGroup>
+ <RowSwitch
+ label={t("hide_content_on_blur")}
+ checked={state.hideContentOnBlur}
+ onClick={handleToggleHideContent}
+ />
+ </RowButtonGroup>
+ </Stack>
+ </TitledNestedSidebarDrawer>
+
+ <PinSetupDialog
+ open={pinDialogOpen}
+ onClose={() => setPinDialogOpen(false)}
+ onComplete={handlePinSetupComplete}
+ />
+ <PasswordSetupDialog
+ open={passwordDialogOpen}
+ onClose={() => setPasswordDialogOpen(false)}
+ onComplete={handlePasswordSetupComplete}
+ />
+ <AutoLockDialog
+ open={autoLockDialogOpen}
+ onClose={() => setAutoLockDialogOpen(false)}
+ currentValue={state.autoLockTimeMs}
+ />
+ </>
+ );
+};
+
+// -- Auto-lock duration helpers --
+
+const autoLockOptions: { label: string; ms: number }[] = [
+ { label: "Immediately", ms: 0 },
+ { label: "5 seconds", ms: 5_000 },
+ { label: "15 seconds", ms: 15_000 },
+ { label: "1 minute", ms: 60_000 },
+ { label: "5 minutes", ms: 300_000 },
+ { label: "30 minutes", ms: 1_800_000 },
+];
+
+const autoLockLabel = (ms: number): string => {
+ const option = autoLockOptions.find((o) => o.ms === ms);
+ return option?.label ?? "Immediately";
+};
+
+// -- PIN Setup Dialog --
+
+interface SetupDialogProps {
+ open: boolean;
+ onClose: () => void;
+ onComplete: () => void;
+}
+
+const PinSetupDialog: React.FC<SetupDialogProps> = ({
+ open,
+ onClose,
+ onComplete,
+}) => {
+ const [step, setStep] = useState<"enter" | "confirm">("enter");
+ const [pin, setPin] = useState(["", "", "", ""]);
+ const [confirmPin, setConfirmPin] = useState(["", "", "", ""]);
+ const [error, setError] = useState("");
+
+ const inputRefs = useRef<(HTMLInputElement | null)[]>([]);
+ const confirmInputRefs = useRef<(HTMLInputElement | null)[]>([]);
+
+ const resetState = useCallback(() => {
+ setStep("enter");
+ setPin(["", "", "", ""]);
+ setConfirmPin(["", "", "", ""]);
+ setError("");
+ }, []);
+
+ const handleClose = useCallback(() => {
+ resetState();
+ onClose();
+ }, [resetState, onClose]);
+
+ const handlePinDigitChange = (
+ index: number,
+ value: string,
+ isConfirm: boolean,
+ ) => {
+ const digit = value.replace(/\D/g, "").slice(-1);
+ if (isConfirm) {
+ const next = [...confirmPin];
+ next[index] = digit;
+ setConfirmPin(next);
+ if (digit && index < 3) {
+ confirmInputRefs.current[index + 1]?.focus();
+ }
+ } else {
+ const next = [...pin];
+ next[index] = digit;
+ setPin(next);
+ if (digit && index < 3) {
+ inputRefs.current[index + 1]?.focus();
+ }
+ }
+ setError("");
+ };
+
+ const handlePinKeyDown = (
+ index: number,
+ e: React.KeyboardEvent,
+ isConfirm: boolean,
+ ) => {
+ if (e.key === "Backspace") {
+ const current = isConfirm ? confirmPin : pin;
+ if (!current[index] && index > 0) {
+ const refs = isConfirm ? confirmInputRefs : inputRefs;
+ refs.current[index - 1]?.focus();
+ }
+ }
+ };
+
+ const handleNext = useCallback(() => {
+ if (pin.some((d) => !d)) return;
+ setStep("confirm");
+ setTimeout(() => confirmInputRefs.current[0]?.focus(), 50);
+ }, [pin]);
+
+ const handleBack = useCallback(() => {
+ setStep("enter");
+ setConfirmPin(["", "", "", ""]);
+ setError("");
+ setTimeout(() => inputRefs.current[0]?.focus(), 50);
+ }, []);
+
+ const handleConfirm = useCallback(async () => {
+ const pinStr = pin.join("");
+ const confirmStr = confirmPin.join("");
+ if (pinStr !== confirmStr) {
+ setError(t("pin_mismatch"));
+ setConfirmPin(["", "", "", ""]);
+ setTimeout(() => confirmInputRefs.current[0]?.focus(), 50);
+ return;
+ }
+ await setupPin(pinStr);
+ onComplete();
+ resetState();
+ }, [pin, confirmPin, onComplete, resetState]);
+
+ const renderPinInputs = (
+ values: string[],
+ refs: React.RefObject<(HTMLInputElement | null)[]>,
+ isConfirm: boolean,
+ ) => (
+ <Stack
+ direction="row"
+ sx={{ gap: 1.5, width: "100%", justifyContent: "space-between" }}
+ >
+ {values.map((digit, i) => (
+ <TextField
+ key={i}
+ hiddenLabel
+ value={digit}
+ onChange={(e) =>
+ handlePinDigitChange(i, e.target.value, isConfirm)
+ }
+ onKeyDown={(e) => handlePinKeyDown(i, e, isConfirm)}
+ inputRef={(el: HTMLInputElement | null) => {
+ refs.current[i] = el;
+ }}
+ type="password"
+ slotProps={{
+ htmlInput: {
+ maxLength: 1,
+ inputMode: "numeric",
+ autoComplete: "off",
+ style: {
+ textAlign: "center",
+ fontSize: "1.25rem",
+ padding: "12px 0",
+ },
+ "aria-label": `PIN digit ${String(i + 1)}`,
+ },
+ }}
+ sx={{ flex: 1, minWidth: 0 }}
+ />
+ ))}
+ </Stack>
+ );
+
+ return (
+ <TitledMiniDialog
+ open={open}
+ onClose={handleClose}
+ title="Set PIN"
+ sx={{
+ "& .MuiDialogTitle-root": { pb: 0 },
+ "& .MuiDialogTitle-root + .MuiDialogContent-root": { pt: 0 },
+ }}
+ >
+ <Stack sx={{ gap: 1.5, py: 0 }}>
+ {step === "enter" ? (
+ <>
+ <Typography sx={{ color: "text.muted", textAlign: "left" }}>
+ {t("enter_pin")}
+ </Typography>
+ {renderPinInputs(pin, inputRefs, false)}
+ <FocusVisibleButton
+ fullWidth
+ color="accent"
+ disabled={pin.some((d) => !d)}
+ onClick={handleNext}
+ >
+ {t("next")}
+ </FocusVisibleButton>
+ </>
+ ) : (
+ <>
+ <Typography sx={{ color: "text.muted", textAlign: "left" }}>
+ {t("confirm_pin")}
+ </Typography>
+ {renderPinInputs(confirmPin, confirmInputRefs, true)}
+ {error && (
+ <Typography
+ variant="small"
+ sx={{ color: "critical.main", textAlign: "left" }}
+ >
+ {error}
+ </Typography>
+ )}
+ <Stack direction="row" sx={{ gap: 1.5, width: "100%" }}>
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ onClick={handleBack}
+ >
+ {t("go_back")}
+ </FocusVisibleButton>
+ <FocusVisibleButton
+ fullWidth
+ color="accent"
+ disabled={confirmPin.some((d) => !d)}
+ onClick={() => void handleConfirm()}
+ >
+ {t("confirm")}
+ </FocusVisibleButton>
+ </Stack>
+ </>
+ )}
+ </Stack>
+ </TitledMiniDialog>
+ );
+};
+
+// -- Password Setup Dialog --
+
+const PasswordSetupDialog: React.FC<SetupDialogProps> = ({
+ open,
+ onClose,
+ onComplete,
+}) => {
+ const [step, setStep] = useState<"enter" | "confirm">("enter");
+ const [password, setPassword] = useState("");
+ const [confirmPassword, setConfirmPassword] = useState("");
+ const [showPassword, setShowPassword] = useState(false);
+ const [showConfirmPassword, setShowConfirmPassword] = useState(false);
+ const [error, setError] = useState("");
+
+ const resetState = useCallback(() => {
+ setStep("enter");
+ setPassword("");
+ setConfirmPassword("");
+ setShowPassword(false);
+ setShowConfirmPassword(false);
+ setError("");
+ }, []);
+
+ const handleClose = useCallback(() => {
+ resetState();
+ onClose();
+ }, [resetState, onClose]);
+
+ const handleNext = useCallback(() => {
+ if (!password) return;
+ setStep("confirm");
+ }, [password]);
+
+ const handleBack = useCallback(() => {
+ setStep("enter");
+ setConfirmPassword("");
+ setError("");
+ }, []);
+
+ const handleConfirm = useCallback(async () => {
+ if (password !== confirmPassword) {
+ setError(t("app_lock_password_mismatch"));
+ setConfirmPassword("");
+ return;
+ }
+ await setupPassword(password);
+ onComplete();
+ resetState();
+ }, [password, confirmPassword, onComplete, resetState]);
+
+ return (
+ <TitledMiniDialog
+ open={open}
+ onClose={handleClose}
+ title={t("app_lock_set_password")}
+ >
+ <Stack sx={{ gap: 2, py: 1 }}>
+ {step === "enter" ? (
+ <>
+ <Typography sx={{ color: "text.muted" }}>
+ {t("app_lock_enter_password")}
+ </Typography>
+ <TextField
+ fullWidth
+ type={showPassword ? "text" : "password"}
+ value={password}
+ onChange={(e) => {
+ setPassword(e.target.value);
+ setError("");
+ }}
+ autoFocus
+ slotProps={{
+ input: {
+ endAdornment: (
+ <ShowHidePasswordInputAdornment
+ showPassword={showPassword}
+ onToggle={() =>
+ setShowPassword((s) => !s)
+ }
+ />
+ ),
+ },
+ }}
+ />
+ <FocusVisibleButton
+ fullWidth
+ color="accent"
+ disabled={!password}
+ onClick={handleNext}
+ >
+ {t("next")}
+ </FocusVisibleButton>
+ </>
+ ) : (
+ <>
+ <Typography sx={{ color: "text.muted" }}>
+ {t("app_lock_confirm_password")}
+ </Typography>
+ <TextField
+ fullWidth
+ type={showConfirmPassword ? "text" : "password"}
+ value={confirmPassword}
+ onChange={(e) => {
+ setConfirmPassword(e.target.value);
+ setError("");
+ }}
+ autoFocus
+ slotProps={{
+ input: {
+ endAdornment: (
+ <ShowHidePasswordInputAdornment
+ showPassword={showConfirmPassword}
+ onToggle={() =>
+ setShowConfirmPassword(
+ (s) => !s,
+ )
+ }
+ />
+ ),
+ },
+ }}
+ />
+ {error && (
+ <Typography
+ variant="small"
+ sx={{
+ color: "critical.main",
+ textAlign: "center",
+ }}
+ >
+ {error}
+ </Typography>
+ )}
+ <Stack direction="row" sx={{ gap: 1.5, width: "100%" }}>
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ onClick={handleBack}
+ >
+ {t("go_back")}
+ </FocusVisibleButton>
+ <FocusVisibleButton
+ fullWidth
+ color="accent"
+ disabled={!confirmPassword}
+ onClick={() => void handleConfirm()}
+ >
+ {t("confirm")}
+ </FocusVisibleButton>
+ </Stack>
+ </>
+ )}
+ </Stack>
+ </TitledMiniDialog>
+ );
+};
+
+// -- Auto-Lock Duration Dialog --
+
+interface AutoLockDialogProps {
+ open: boolean;
+ onClose: () => void;
+ currentValue: number;
+}
+
+const AutoLockDialog: React.FC<AutoLockDialogProps> = ({
+ open,
+ onClose,
+ currentValue,
+}) => {
+ const handleSelect = (ms: number) => {
+ setAutoLockTime(ms);
+ onClose();
+ };
+
+ return (
+ <TitledMiniDialog open={open} onClose={onClose} title={t("auto_lock")}>
+ <Stack sx={{ gap: 0.5, py: 1 }}>
+ {autoLockOptions.map(({ label, ms }) => (
+ <RowButton
+ key={ms}
+ label={label}
+ endIcon={
+ currentValue === ms ? (
+ <CheckIcon sx={{ color: "accent.main" }} />
+ ) : undefined
+ }
+ onClick={() => handleSelect(ms)}
+ />
+ ))}
+ </Stack>
+ <DialogActions>
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ onClick={onClose}
+ >
+ {t("cancel")}
+ </FocusVisibleButton>
+ </DialogActions>
+ </TitledMiniDialog>
+ );
+};
diff --git a/web/packages/new/photos/components/utils/use-snapshot.ts b/web/packages/new/photos/components/utils/use-snapshot.ts
index 21073d6155..0b76c01b3a 100644
--- a/web/packages/new/photos/components/utils/use-snapshot.ts
+++ b/web/packages/new/photos/components/utils/use-snapshot.ts
@@ -3,6 +3,7 @@ import {
hlsGenerationStatusSubscribe,
} from "ente-gallery/services/video";
import { useSyncExternalStore } from "react";
+import { appLockSnapshot, appLockSubscribe } from "../../services/app-lock";
import {
mlStatusSnapshot,
mlStatusSubscribe,
@@ -15,6 +16,13 @@ import {
userDetailsSubscribe,
} from "../../services/user-details";
+/**
+ * A convenience hook that returns {@link appLockSnapshot}, and also subscribes
+ * to updates.
+ */
+export const useAppLockSnapshot = () =>
+ useSyncExternalStore(appLockSubscribe, appLockSnapshot, appLockSnapshot);
+
/**
* A convenience hook that returns {@link settingsSnapshot}, and also
* subscribes to updates.
diff --git a/web/packages/new/photos/services/app-lock.ts b/web/packages/new/photos/services/app-lock.ts
new file mode 100644
index 0000000000..422b344baf
--- /dev/null
+++ b/web/packages/new/photos/services/app-lock.ts
@@ -0,0 +1,424 @@
+/**
+ * @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.
+ *
+ * See: [Note: Snapshots and useSyncExternalStore].
+ */
+
+import { deriveInteractiveKey, deriveKey } 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";
+
+/**
+ * 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).
+ */
+export interface AppLockState {
+ /** Whether app lock is enabled. */
+ enabled: boolean;
+ /** Active lock type. */
+ lockType: "pin" | "password" | "none";
+ /** Whether the app is currently locked. */
+ isLocked: boolean;
+ /** Consecutive failed attempts in current lockout cycle. */
+ invalidAttemptCount: number;
+ /** Epoch ms when cooldown expires (0 = no cooldown). */
+ cooldownExpiresAt: number;
+ /** Auto-lock delay in milliseconds. */
+ autoLockTimeMs: number;
+ /** Whether to blur content when tab/window is hidden. */
+ hideContentOnBlur: boolean;
+}
+
+const createDefaultState = (): AppLockState => ({
+ enabled: false,
+ lockType: "none",
+ isLocked: false,
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
+ autoLockTimeMs: 0,
+ hideContentOnBlur: false,
+});
+
+/**
+ * Internal in-memory state shared by the functions in this module.
+ *
+ * This entire object will be reset on logout.
+ */
+class AppLockModuleState {
+ constructor() {
+ this.snapshot = createDefaultState();
+ }
+
+ /**
+ * Subscriptions to {@link AppLockState} updates attached using
+ * {@link appLockSubscribe}.
+ */
+ listeners: (() => void)[] = [];
+
+ /**
+ * Snapshot of the {@link AppLockState} returned by
+ * {@link appLockSnapshot}.
+ */
+ snapshot: AppLockState;
+}
+
+/** State shared by the functions in this module. */
+let _state = new AppLockModuleState();
+
+/**
+ * A function that can be used to subscribe to updates to {@link AppLockState}.
+ *
+ * See: [Note: Snapshots and useSyncExternalStore].
+ */
+export const appLockSubscribe = (onChange: () => void): (() => void) => {
+ _state.listeners.push(onChange);
+ return () => {
+ _state.listeners = _state.listeners.filter((l) => l != onChange);
+ };
+};
+
+/**
+ * Return the last known, cached {@link AppLockState}.
+ *
+ * See also {@link appLockSubscribe}.
+ */
+export const appLockSnapshot = () => _state.snapshot;
+
+const setSnapshot = (snapshot: AppLockState) => {
+ _state.snapshot = snapshot;
+ _state.listeners.forEach((l) => l());
+};
+
+// -- localStorage keys (synchronous, for cold-start reads) --
+
+const lsKeyEnabled = "appLock.enabled";
+const lsKeyLockType = "appLock.lockType";
+const lsKeyAutoLockTimeMs = "appLock.autoLockTimeMs";
+const lsKeyHideContentOnBlur = "appLock.hideContentOnBlur";
+
+// -- KV DB keys (IndexedDB, async) --
+
+const kvKeyHash = "appLock.hash";
+const kvKeySalt = "appLock.salt";
+const kvKeyOpsLimit = "appLock.opsLimit";
+const kvKeyMemLimit = "appLock.memLimit";
+const kvKeyInvalidAttempts = "appLock.invalidAttempts";
+const kvKeyCooldownExpiresAt = "appLock.cooldownExpiresAt";
+
+// -- BroadcastChannel for multi-tab sync --
+
+const _channel = new BroadcastChannel("ente-app-lock");
+
+_channel.onmessage = (event: MessageEvent) => {
+ const data = event.data as { type: string };
+ if (data.type === "lock") {
+ setSnapshot({ ..._state.snapshot, isLocked: true });
+ } else if (data.type === "unlock") {
+ setSnapshot({
+ ..._state.snapshot,
+ isLocked: false,
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
+ });
+ }
+};
+
+// -- Public API --
+
+/**
+ * Initialize app lock state from localStorage on cold start.
+ *
+ * Reads localStorage synchronously so the overlay can render immediately
+ * without a flash of unlocked content. Sets isLocked = true if app lock is
+ * enabled and the user is logged in.
+ *
+ * After the synchronous 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 enabled = localStorage.getItem(lsKeyEnabled) === "true";
+ const lockTypeRaw = localStorage.getItem(lsKeyLockType);
+ const lockType: AppLockState["lockType"] =
+ lockTypeRaw === "pin" || lockTypeRaw === "password"
+ ? lockTypeRaw
+ : "none";
+ const autoLockTimeMs = Number(
+ localStorage.getItem(lsKeyAutoLockTimeMs) ?? "0",
+ );
+ const hideContentOnBlur =
+ localStorage.getItem(lsKeyHideContentOnBlur) === "true";
+
+ const isLocked = enabled && haveMasterKeyInSession();
+
+ setSnapshot({
+ ..._state.snapshot,
+ enabled,
+ lockType,
+ isLocked,
+ autoLockTimeMs,
+ hideContentOnBlur,
+ });
+
+ // Restore brute-force state from KV DB (async) so cooldowns survive
+ // page refresh.
+ if (isLocked) {
+ void restoreBruteForceState();
+ }
+};
+
+/**
+ * Restore the brute-force attempt count and cooldown expiry from KV DB into
+ * the in-memory snapshot.
+ *
+ * Called during {@link initAppLock} to ensure that cooldown timers persist
+ * across page refreshes.
+ */
+const restoreBruteForceState = async () => {
+ try {
+ const [invalidAttempts, cooldownExpiry] = await Promise.all([
+ getKVN(kvKeyInvalidAttempts),
+ getKVN(kvKeyCooldownExpiresAt),
+ ]);
+
+ const invalidAttemptCount = invalidAttempts ?? 0;
+ const cooldownExpiresAt = cooldownExpiry ?? 0;
+
+ // Only update if there is actually persisted brute-force state.
+ if (invalidAttemptCount > 0 || cooldownExpiresAt > 0) {
+ setSnapshot({
+ ..._state.snapshot,
+ invalidAttemptCount,
+ cooldownExpiresAt,
+ });
+ }
+ } catch (e) {
+ log.error("Failed to restore brute-force state from KV DB", e);
+ }
+};
+
+/**
+ * Set up a PIN for app lock.
+ *
+ * Derives a key from the PIN using Argon2id with interactive limits, stores
+ * the hash and derivation parameters in KV DB, and enables the lock.
+ */
+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);
+
+ localStorage.setItem(lsKeyLockType, "pin");
+ localStorage.setItem(lsKeyEnabled, "true");
+
+ setSnapshot({
+ ..._state.snapshot,
+ enabled: true,
+ lockType: "pin",
+ });
+};
+
+/**
+ * Set up a password for app lock.
+ *
+ * Same as {@link setupPin} but sets the lock type to "password".
+ */
+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);
+
+ localStorage.setItem(lsKeyLockType, "password");
+ localStorage.setItem(lsKeyEnabled, "true");
+
+ setSnapshot({
+ ..._state.snapshot,
+ enabled: true,
+ lockType: "password",
+ });
+};
+
+/**
+ * The result of an unlock attempt.
+ *
+ * - `"success"` - The input was correct; the app is now unlocked.
+ * - `"failed"` - The input was incorrect.
+ * - `"cooldown"` - Too many recent attempts; currently in cooldown.
+ * - `"logout"` - Too many total attempts (>= 10); caller should force logout.
+ */
+export type UnlockResult = "success" | "failed" | "cooldown" | "logout";
+
+/**
+ * Attempt to unlock the app with the given PIN or password.
+ *
+ * Implements brute-force protection: after 5 failed attempts, a cooldown
+ * period is enforced (exponential backoff starting at 30s). After 10 failed
+ * attempts, signals that the caller should force-logout the user.
+ */
+export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
+ // Check cooldown from in-memory state.
+ if (
+ _state.snapshot.cooldownExpiresAt > 0 &&
+ Date.now() < _state.snapshot.cooldownExpiresAt
+ ) {
+ return "cooldown";
+ }
+
+ // Read stored derivation parameters and hash from KV DB.
+ const salt = await getKVS(kvKeySalt);
+ const storedHash = await getKVS(kvKeyHash);
+ const opsLimit = await getKVN(kvKeyOpsLimit);
+ const memLimit = await getKVN(kvKeyMemLimit);
+
+ if (!salt || !storedHash || !opsLimit || !memLimit) {
+ log.error("App lock credentials missing from KV DB");
+ return "failed";
+ }
+
+ // Derive key from input using the stored parameters.
+ const derivedKey = await deriveKey(input, salt, opsLimit, memLimit);
+
+ 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" });
+ return "success";
+ }
+
+ // Incorrect input: increment attempts.
+ const count = _state.snapshot.invalidAttemptCount + 1;
+ await setKV(kvKeyInvalidAttempts, count);
+
+ if (count >= 10) {
+ // Too many attempts: signal logout.
+ await setKV(kvKeyCooldownExpiresAt, 0);
+ setSnapshot({
+ ..._state.snapshot,
+ invalidAttemptCount: count,
+ cooldownExpiresAt: 0,
+ });
+ return "logout";
+ }
+
+ if (count >= 5) {
+ // Enforce cooldown with exponential backoff.
+ const cooldownSeconds = Math.pow(2, count - 5) * 30;
+ const expiresAt = Date.now() + cooldownSeconds * 1000;
+ await setKV(kvKeyCooldownExpiresAt, expiresAt);
+
+ setSnapshot({
+ ..._state.snapshot,
+ invalidAttemptCount: count,
+ cooldownExpiresAt: expiresAt,
+ });
+
+ // The current failed attempt has triggered cooldown, so surface the
+ // cooldown state immediately to callers/UI.
+ return "cooldown";
+ } else {
+ setSnapshot({
+ ..._state.snapshot,
+ invalidAttemptCount: count,
+ });
+ }
+
+ return "failed";
+};
+
+/**
+ * Lock the app and broadcast to other tabs.
+ */
+export const lock = () => {
+ setSnapshot({ ..._state.snapshot, isLocked: true });
+ _channel.postMessage({ type: "lock" });
+};
+
+/**
+ * Clear all app lock data on logout.
+ *
+ * Removes all localStorage and KV DB keys, and resets in-memory state to
+ * defaults.
+ */
+export const logoutAppLock = async () => {
+ localStorage.removeItem(lsKeyEnabled);
+ localStorage.removeItem(lsKeyLockType);
+ localStorage.removeItem(lsKeyAutoLockTimeMs);
+ localStorage.removeItem(lsKeyHideContentOnBlur);
+
+ await removeKV(kvKeyHash);
+ await removeKV(kvKeySalt);
+ await removeKV(kvKeyOpsLimit);
+ await removeKV(kvKeyMemLimit);
+ await removeKV(kvKeyInvalidAttempts);
+ await removeKV(kvKeyCooldownExpiresAt);
+
+ _state = new AppLockModuleState();
+};
+
+/**
+ * Update the auto-lock delay.
+ */
+export const setAutoLockTime = (ms: number) => {
+ localStorage.setItem(lsKeyAutoLockTimeMs, String(ms));
+ setSnapshot({ ..._state.snapshot, autoLockTimeMs: ms });
+};
+
+/**
+ * Update the hide-content-on-blur preference.
+ */
+export const setHideContentOnBlur = (enabled: boolean) => {
+ if (enabled) {
+ localStorage.setItem(lsKeyHideContentOnBlur, "true");
+ } else {
+ localStorage.removeItem(lsKeyHideContentOnBlur);
+ }
+ setSnapshot({ ..._state.snapshot, hideContentOnBlur: enabled });
+};
+
+/**
+ * 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.
+ */
+export const disableAppLock = async () => {
+ await removeKV(kvKeyHash);
+ await removeKV(kvKeySalt);
+ await removeKV(kvKeyOpsLimit);
+ await removeKV(kvKeyMemLimit);
+ await removeKV(kvKeyInvalidAttempts);
+ await removeKV(kvKeyCooldownExpiresAt);
+
+ localStorage.setItem(lsKeyEnabled, "false");
+ localStorage.removeItem(lsKeyLockType);
+
+ setSnapshot({
+ ..._state.snapshot,
+ enabled: false,
+ lockType: "none",
+ isLocked: false,
+ invalidAttemptCount: 0,
+ cooldownExpiresAt: 0,
+ });
+};
diff --git a/web/packages/wasm/Cargo.lock b/web/packages/wasm/Cargo.lock
index 80fabb4abb..6347f292e6 100644
--- a/web/packages/wasm/Cargo.lock
+++ b/web/packages/wasm/Cargo.lock
@@ -285,6 +285,7 @@ dependencies = [
"base64",
"blake2b_simd",
"crypto_secretstream",
+ "getrandom 0.2.16",
"hex",
"md-5",
"rand_core 0.6.4",