π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix(AppLock):added-reauthentication-with-applock-enhance-lock-supression
Aswin Asok05ed30b5ecd5
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsxindex 699c9e47d2..936c69894e 100644--- a/web/apps/photos/src/components/Sidebar.tsx+++ b/web/apps/photos/src/components/Sidebar.tsx@@ -89,6 +89,7 @@ import {} from "ente-new/photos/services/collection-summary";import exportService from "ente-new/photos/services/export";import { isMLSupported } from "ente-new/photos/services/ml";+import { reauthenticateWithAppLock } from "ente-new/photos/services/app-lock";import {performSidebarAction as performSidebarRegistryAction,type SidebarActionContext,@@ -996,7 +997,12 @@ const Account: React.FC<AccountProps> = ({}, [onRootClose]);const handleActiveSessions = useCallback(async () => {- await onAuthenticateUser();+ if (isDesktop) {+ const didAuthenticateWithAppLock = await reauthenticateWithAppLock();+ if (!didAuthenticateWithAppLock) await onAuthenticateUser();+ } else {+ await onAuthenticateUser();+ }showSessions();}, [onAuthenticateUser, showSessions]);diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsxindex fdaac7c035..5e444d3a2e 100644--- a/web/apps/photos/src/pages/gallery.tsx+++ b/web/apps/photos/src/pages/gallery.tsx@@ -27,6 +27,7 @@ import {import { stashRedirect } from "ente-accounts/services/redirect";import { isSessionInvalid } from "ente-accounts/services/session";import { ensureLocalUser } from "ente-accounts/services/user";+import { isDesktop } from "ente-base/app";import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";import { NavbarBase } from "ente-base/components/Navbar";import { SingleInputDialog } from "ente-base/components/SingleInputDialog";@@ -58,6 +59,7 @@ import {hasPendingAlbumToJoin,processPendingAlbumJoin,} from "ente-new/albums/services/join-album";+import { reauthenticateWithAppLock } from "ente-new/photos/services/app-lock";import { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";import {CollectionSelector,@@ -323,7 +325,7 @@ const Page: React.FC = () => {undefined,);- const authenticateUser = useCallback(+ const authenticateUserWithPasswordModal = useCallback(() =>new Promise<void>((resolve, reject) => {onAuthenticateCallback.current = resolve;@@ -333,6 +335,15 @@ const Page: React.FC = () => {[],);+ const authenticateUser = useCallback(async () => {+ if (!isDesktop) return authenticateUserWithPasswordModal();++ const didAuthenticateWithAppLock = await reauthenticateWithAppLock();+ if (didAuthenticateWithAppLock) return;++ return authenticateUserWithPasswordModal();+ }, [authenticateUserWithPasswordModal]);+const handleCloseAuthenticateUser = useCallback(() => {authenticateUserVisibilityProps.onClose();// Reject the pending authentication promise so the caller knowsdiff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsxindex fb7cf29024..c0c6b6f4ee 100644--- a/web/packages/new/photos/components/AppLockOverlay.tsx+++ b/web/packages/new/photos/components/AppLockOverlay.tsx@@ -50,9 +50,71 @@ export const AppLockOverlay: React.FC = () => {const appLock = useAppLockSnapshot();const { logout } = useBaseContext();const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);+ const isReauthentication = appLock.lockScreenMode === "reauthenticate";++ useEffect(() => {+ if (!appLock.isLocked) setShowLogoutConfirm(false);+ }, [appLock.isLocked]);if (!appLock.isLocked) return null;+ const unlockForm =+ appLock.lockType === "pin" ? (+ <PinUnlockForm+ appLock={appLock}+ isReauthentication={isReauthentication}+ onLogout={() => setShowLogoutConfirm(true)}+ />+ ) : appLock.lockType === "password" ? (+ <PasswordUnlockForm+ appLock={appLock}+ isReauthentication={isReauthentication}+ onLogout={() => setShowLogoutConfirm(true)}+ />+ ) : appLock.lockType === "device" ? (+ <DeviceLockUnlockForm isReauthentication={isReauthentication} />+ ) : (+ <PinUnlockForm+ appLock={appLock}+ isReauthentication={isReauthentication}+ onLogout={() => setShowLogoutConfirm(true)}+ />+ );++ if (isReauthentication) {+ return (+ <Modal+ open+ disableEscapeKeyDown+ aria-label={t("authenticate")}+ sx={{ zIndex: "calc(var(--mui-zIndex-modal) + 1)" }}+ >+ <Box+ sx={{+ position: "fixed",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ p: 2,+ outline: "none",+ }}+ style={+ { WebkitAppRegion: "no-drag" } as React.CSSProperties+ }+ >+ {unlockForm}+ {showLogoutConfirm && (+ <LogoutConfirmation+ onConfirm={logout}+ onCancel={() => setShowLogoutConfirm(false)}+ />+ )}+ </Box>+ </Modal>+ );+ }+return (<Modalopen@@ -113,24 +175,7 @@ export const AppLockOverlay: React.FC = () => {</Box>{/* Centered form content */}- {appLock.lockType === "pin" ? (- <PinUnlockForm- appLock={appLock}- onLogout={() => setShowLogoutConfirm(true)}- />- ) : appLock.lockType === "password" ? (- <PasswordUnlockForm- appLock={appLock}- onLogout={() => setShowLogoutConfirm(true)}- />- ) : appLock.lockType === "device" ? (- <DeviceLockUnlockForm />- ) : (- <PinUnlockForm- appLock={appLock}- onLogout={() => setShowLogoutConfirm(true)}- />- )}+ {unlockForm}{/* Logout confirmation overlays on top */}{showLogoutConfirm && (@@ -148,6 +193,7 @@ export const AppLockOverlay: React.FC = () => {interface UnlockFormProps {appLock: ReturnType<typeof useAppLockSnapshot>;+ isReauthentication: boolean;onLogout: () => void;}@@ -255,7 +301,11 @@ const deviceLockErrorText = (result: DeviceLockUnlockResult) => {// -- PIN unlock form ---const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {+const PinUnlockForm: React.FC<UnlockFormProps> = ({+ appLock,+ isReauthentication,+ onLogout,+}) => {const { logout } = useBaseContext();const [pin, setPin] = useState(["", "", "", ""]);@@ -362,7 +412,9 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {sx={{ maxWidth: 340, width: "100%" }}><LockOutlinedIcon sx={{ fontSize: 48, color: "text.muted" }} />- <Typography variant="h3">{t("app_locked")}</Typography>+ <Typography variant="h3">+ {isReauthentication ? t("authenticate") : t("app_locked")}+ </Typography><Typography variant="small" color="text.muted" sx={{ mb: 1 }}>{t("enter_pin")}</Typography>@@ -426,6 +478,7 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {const PasswordUnlockForm: React.FC<UnlockFormProps> = ({appLock,+ isReauthentication,onLogout,}) => {const { logout } = useBaseContext();@@ -482,7 +535,9 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({sx={{ maxWidth: 340, width: "100%" }}><LockOutlinedIcon sx={{ fontSize: 48, color: "text.muted" }} />- <Typography variant="h3">{t("app_locked")}</Typography>+ <Typography variant="h3">+ {isReauthentication ? t("password") : t("app_locked")}+ </Typography><Typography variant="small" color="text.muted">{t("app_lock_enter_password")}</Typography>@@ -500,7 +555,11 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({setError(undefined);}}disabled={loading}- placeholder={t("app_lock_password")}+ placeholder={+ isReauthentication+ ? t("password")+ : t("app_lock_password")+ }autoComplete="off"slotProps={{input: {@@ -520,7 +579,7 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({color="accent"disabled={!password || loading}>- {t("unlock")}+ {isReauthentication ? t("authenticate") : t("unlock")}</FocusVisibleButton><ErrorMessage@@ -534,7 +593,9 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({// -- Device lock unlock form ---const DeviceLockUnlockForm: React.FC = () => {+const DeviceLockUnlockForm: React.FC<{ isReauthentication: boolean }> = ({+ isReauthentication,+}) => {const [error, setError] = useState<string>();const [loading, setLoading] = useState(false);const isUnlockInProgress = useRef(false);@@ -566,7 +627,9 @@ const DeviceLockUnlockForm: React.FC = () => {sx={{ maxWidth: 340, width: "100%" }}><FingerprintIcon sx={{ fontSize: 48, color: "text.muted" }} />- <Typography variant="h3">{t("app_locked")}</Typography>+ <Typography variant="h3">+ {isReauthentication ? t("authenticate") : t("app_locked")}+ </Typography><Typographyvariant="small"color="text.muted"@@ -585,6 +648,8 @@ const DeviceLockUnlockForm: React.FC = () => {>{loading ? (<CircularProgress size={18} color="inherit" />+ ) : isReauthentication ? (+ t("authenticate")) : (t("device_lock_login"))}diff --git a/web/packages/new/photos/components/utils/use-app-lock.ts b/web/packages/new/photos/components/utils/use-app-lock.tsindex 692aa04dfe..5db32e84ca 100644--- a/web/packages/new/photos/components/utils/use-app-lock.ts+++ b/web/packages/new/photos/components/utils/use-app-lock.ts@@ -5,9 +5,11 @@ import {import { updateSessionFromElectronSafeStorageIfNeeded } from "ente-base/session";import { useEffect, useRef, useState } from "react";import {+ clearAutoLockBlurSuppression,initAppLock,lock,refreshAppLockStateFromSession,+ shouldSuppressAutoLockOnBlur,type AppLockState,} from "../../services/app-lock";@@ -94,6 +96,7 @@ export const useAutoLockWhenBackgrounded = (// Starts auto-lock unless the app is already locked.const startAutoLockTimer = () => {if (isLocked) return;+ if (shouldSuppressAutoLockOnBlur()) return;const existingDeadline = autoLockDueAtTimestampRef.current;if (existingDeadline !== null && Date.now() < existingDeadline) {@@ -118,6 +121,7 @@ export const useAutoLockWhenBackgrounded = (// On foreground, lock immediately if the deadline passed; otherwise clear pending timer.const handleAppForegrounded = () => {+ clearAutoLockBlurSuppression();if (lockIfDeadlineElapsed()) return;clearAutoLockTimer();};diff --git a/web/packages/new/photos/services/app-lock.ts b/web/packages/new/photos/services/app-lock.tsindex 6e38a4a54e..5523cb832e 100644--- a/web/packages/new/photos/services/app-lock.ts+++ b/web/packages/new/photos/services/app-lock.ts@@ -29,6 +29,8 @@ export interface AppLockState {enabled: boolean;/** Active lock type. */lockType: "pin" | "password" | "device" | "none";+ /** Why the lock screen is currently shown. */+ lockScreenMode: "lock" | "reauthenticate";/** Whether the app is currently locked. */isLocked: boolean;/** Consecutive failed attempts in current lockout cycle. */@@ -42,6 +44,7 @@ export interface AppLockState {const createDefaultState = (): AppLockState => ({enabled: false,lockType: "none",+ lockScreenMode: "lock",isLocked: false,invalidAttemptCount: 0,cooldownExpiresAt: 0,@@ -147,6 +150,34 @@ const maxInvalidUnlockAttempts = 10;const cooldownStartsAtAttempt = 5;const cooldownBaseSeconds = 30;const unlockAttemptLockName = "ente-app-lock-unlock-attempt";+const trustedPromptAutoLockSuppressionMs = 5 * 1e3;+let suppressAutoLockOnBlurUntil = 0;++/**+ * Temporarily suppress auto-lock on blur for trusted app-initiated prompts.+ *+ * This is used for native device authentication prompts that can transiently+ * blur the app window even though the user hasn't backgrounded the app.+ */+export const suppressAutoLockOnBlurForTrustedPrompt = () => {+ suppressAutoLockOnBlurUntil = Math.max(+ suppressAutoLockOnBlurUntil,+ Date.now() + trustedPromptAutoLockSuppressionMs,+ );+};++/**+ * Return true if blur-triggered auto-lock should currently be suppressed.+ */+export const shouldSuppressAutoLockOnBlur = () =>+ Date.now() < suppressAutoLockOnBlurUntil;++/**+ * Clear any pending blur auto-lock suppression.+ */+export const clearAutoLockBlurSuppression = () => {+ suppressAutoLockOnBlurUntil = 0;+};export type DeviceLockMode = "native";@@ -284,6 +315,7 @@ const setSnapshotFromPersistedConfig = (...snapshot,enabled: config.enabled,lockType: config.lockType,+ lockScreenMode: "lock",isLocked,autoLockTimeMs: config.autoLockTimeMs,});@@ -496,6 +528,7 @@ const unlockLocally = () => {const snapshot = appLockState().snapshot;setSnapshot({...snapshot,+ lockScreenMode: "lock",isLocked: false,invalidAttemptCount: 0,cooldownExpiresAt: 0,@@ -586,6 +619,10 @@ export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {}try {+ // Ignore blur auto-lock caused by this trusted, app-initiated native+ // prompt.+ suppressAutoLockOnBlurForTrustedPrompt();+// Trigger the OS-native authentication prompt (for example, Touch ID).const unlocked = await globalThis.electron?.promptDeviceLock(deviceLockEnablePromptReason,@@ -776,12 +813,51 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {});};+/**+ * Perform an explicit reauthentication using app lock.+ *+ * Returns `true` when app lock was successfully used for reauthentication.+ * Returns `false` when app lock is unavailable or cannot be started, so callers+ * can fall back to an alternate flow (for example, master password prompt).+ */+export const reauthenticateWithAppLock = async (): Promise<boolean> => {+ try {+ const snapshot = appLockSnapshot();+ let canUseAppLock = snapshot.enabled && snapshot.lockType !== "none";+ if (canUseAppLock && snapshot.lockType === "device") {+ // For device lock, ensure native auth is actually usable right now.+ // If unavailable (e.g. Touch ID disabled), fall back to password flow.+ const capability = await resolveDeviceLockCapability();+ canUseAppLock = capability.usable;+ }+ if (!canUseAppLock) return false;++ return await new Promise<boolean>((resolve) => {+ const unsubscribe = appLockSubscribe(() => {+ if (!appLockSnapshot().isLocked) {+ unsubscribe();+ resolve(true);+ }+ });++ lock("reauthenticate");+ if (!appLockSnapshot().isLocked) {+ unsubscribe();+ resolve(false);+ }+ });+ } catch (e) {+ log.error("Failed to start app lock reauthentication", e);+ return false;+ }+};+/*** Lock the app.*/-export const lock = () => {+export const lock = (lockScreenMode: AppLockState["lockScreenMode"] = "lock") => {const snapshot = appLockState().snapshot;- setSnapshot({ ...snapshot, isLocked: true });+ setSnapshot({ ...snapshot, lockScreenMode, isLocked: true });hydrateBruteForceStateIfNeeded();};@@ -837,6 +913,7 @@ export const disableAppLock = async () => {...snapshot,enabled: false,lockType: "none",+ lockScreenMode: "lock",isLocked: false,invalidAttemptCount: 0,cooldownExpiresAt: 0,