π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
refrator(AppLock):device-lock-handling-update-auto-lock-logic
Aswin Asok5f850737aae6
diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsxindex 09446dcb71..25555f2f77 100644--- a/web/apps/photos/src/pages/_app.tsx+++ b/web/apps/photos/src/pages/_app.tsx@@ -76,6 +76,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {const [isAppLockReady, setIsAppLockReady] = useState(() => !isDesktop);const appLock = useAppLockSnapshot();const autoLockTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const autoLockDeadlineRef = useRef<number | null>(null);const logout = useCallback(() => void photosLogout(), []);@@ -185,48 +186,97 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {// eslint-disable-next-line react-hooks/exhaustive-deps}, []);- // Auto-lock when the tab/window becomes hidden.+ // Auto-lock when the tab/window is backgrounded (hidden or unfocused).useEffect(() => {if (!appLock.enabled) return;- const handleVisibilityChange = () => {- if (document.hidden && !appLock.isLocked) {- autoLockTimerRef.current = setTimeout(() => {- lock();- }, appLock.autoLockTimeMs);- }- if (!document.hidden && autoLockTimerRef.current) {+ const clearAutoLockTimer = () => {+ if (autoLockTimerRef.current) {clearTimeout(autoLockTimerRef.current);autoLockTimerRef.current = null;}+ autoLockDeadlineRef.current = null;};- document.addEventListener("visibilitychange", handleVisibilityChange);- return () => {- document.removeEventListener(- "visibilitychange",- handleVisibilityChange,- );+ const lockIfDeadlineElapsed = () => {+ const deadline = autoLockDeadlineRef.current;+ if (deadline === null) return false;+ if (Date.now() < deadline) return false;++ clearAutoLockTimer();+ lock();+ return true;+ };++ const startAutoLockTimer = () => {+ if (appLock.isLocked) return;++ // Avoid extending the countdown when blur + visibility events both+ // fire for a single background transition.+ const existingDeadline = autoLockDeadlineRef.current;+ if (existingDeadline !== null && Date.now() < existingDeadline) {+ return;+ }++ if (appLock.autoLockTimeMs <= 0) {+ clearAutoLockTimer();+ lock();+ return;+ }+if (autoLockTimerRef.current) {clearTimeout(autoLockTimerRef.current);- autoLockTimerRef.current = null;}+ autoLockDeadlineRef.current = Date.now() + appLock.autoLockTimeMs;+ autoLockTimerRef.current = setTimeout(() => {+ autoLockDeadlineRef.current = null;+ lock();+ }, appLock.autoLockTimeMs);};- }, [appLock.enabled, appLock.isLocked, appLock.autoLockTimeMs]);- // On Electron, clear the auto-lock timer when the main window regains focus.- useEffect(() => {- if (!appLock.enabled) return;+ const handleAppForegrounded = () => {+ if (lockIfDeadlineElapsed()) return;+ clearAutoLockTimer();+ };- const handleFocus = () => {- if (autoLockTimerRef.current) {- clearTimeout(autoLockTimerRef.current);- autoLockTimerRef.current = null;+ const handleVisibilityChange = () => {+ if (document.hidden) {+ startAutoLockTimer();+ } else {+ handleAppForegrounded();}};- return subscribeMainWindowFocus(handleFocus);- }, [appLock.enabled]);+ const handleWindowBlur = () => {+ if (!document.hidden) {+ startAutoLockTimer();+ }+ };++ const handleWindowFocus = () => {+ handleAppForegrounded();+ };++ let unsubscribeMainWindowFocus: (() => void) | undefined;+ if (globalThis.electron) {+ unsubscribeMainWindowFocus =+ subscribeMainWindowFocus(handleAppForegrounded);+ }++ document.addEventListener("visibilitychange", handleVisibilityChange);+ window.addEventListener("blur", handleWindowBlur);+ window.addEventListener("focus", handleWindowFocus);+ return () => {+ document.removeEventListener(+ "visibilitychange",+ handleVisibilityChange,+ );+ window.removeEventListener("blur", handleWindowBlur);+ window.removeEventListener("focus", handleWindowFocus);+ unsubscribeMainWindowFocus?.();+ clearAutoLockTimer();+ };+ }, [appLock.enabled, appLock.isLocked, appLock.autoLockTimeMs]);const baseContext = useMemo(() => deriveBaseContext({ logout, showMiniDialog }),diff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsxindex a3bcc9cffd..696da19e42 100644--- a/web/packages/new/photos/components/AppLockOverlay.tsx+++ b/web/packages/new/photos/components/AppLockOverlay.tsx@@ -123,7 +123,7 @@ export const AppLockOverlay: React.FC = () => {appLock={appLock}onLogout={() => setShowLogoutConfirm(true)}/>- ) : appLock.deviceLockEnabled ? (+ ) : appLock.lockType === "device" ? (<DeviceLockUnlockForm />) : (<PinUnlockForm@@ -244,8 +244,6 @@ 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;@@ -312,24 +310,6 @@ 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) {@@ -345,12 +325,6 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {cooldownText={cooldownText}attemptCount={appLock.invalidAttemptCount}onLogout={onLogout}- onDeviceLockUnlock={- appLock.deviceLockEnabled- ? () => void handleDeviceLockUnlock()- : undefined- }- deviceLockLoading={deviceLockLoading}/></AppLockCard>);@@ -419,22 +393,6 @@ 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>);@@ -452,8 +410,6 @@ 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;@@ -479,24 +435,6 @@ 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>@@ -505,12 +443,6 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({cooldownText={cooldownText}attemptCount={appLock.invalidAttemptCount}onLogout={onLogout}- onDeviceLockUnlock={- appLock.deviceLockEnabled- ? () => void handleDeviceLockUnlock()- : undefined- }- deviceLockLoading={deviceLockLoading}/></AppLockCard>);@@ -566,22 +498,6 @@ 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>- )}<ErrorMessageerror={error}@@ -752,8 +668,6 @@ interface CooldownScreenProps {cooldownText: string;attemptCount: number;onLogout: () => void;- onDeviceLockUnlock?: () => void;- deviceLockLoading?: boolean;}const CooldownScreen: React.FC<CooldownScreenProps> = ({@@ -761,8 +675,6 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({cooldownText,attemptCount,onLogout,- onDeviceLockUnlock,- deviceLockLoading,}) => {const durationMs = appLockCooldownDurationMs(attemptCount);const progress =@@ -849,21 +761,6 @@ 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>- )}<FocusVisibleButtonfullWidthcolor="secondary"diff --git a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx b/web/packages/new/photos/components/sidebar/AppLockSettings.tsxindex da64829e5f..de90ec178b 100644--- a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx+++ b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx@@ -2,7 +2,6 @@ import CheckIcon from "@mui/icons-material/Check";import ChevronRightIcon from "@mui/icons-material/ChevronRight";import {DialogActions,- Slider,Stack,TextField,Typography,@@ -205,7 +204,8 @@ export const AppLockSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({}disabled={isSettingDeviceLock}endIcon={- state.deviceLockEnabled ? (+ state.lockType ===+ "device" ? (<CheckIconsx={{color: "accent.main",@@ -711,7 +711,7 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({);};-// -- Auto-Lock Dialog with Slider --+// -- Auto-Lock Dialog --interface AutoLockDialogProps {open: boolean;@@ -719,84 +719,44 @@ interface AutoLockDialogProps {currentValue: number;}-const autoLockMarks = autoLockOptions.map((_, i) => ({ value: i }));-const AutoLockDialog: React.FC<AutoLockDialogProps> = ({open,onClose,currentValue,}) => {- const persistedIndex = autoLockOptions.findIndex(- (o) => o.ms === currentValue,- );- const defaultIndex = persistedIndex === -1 ? 0 : persistedIndex;- const [selectedIndex, setSelectedIndex] = useState(defaultIndex);-- useEffect(() => {- if (!open) return;- setSelectedIndex(defaultIndex);- }, [open, defaultIndex]);-- const handleChange = (_: Event, newValue: number | number[]) => {- setSelectedIndex(newValue as number);- };-- const handleChangeCommitted = (- _: Event | React.SyntheticEvent,- newValue: number | number[],- ) => {- const index = newValue as number;- const option = autoLockOptions[index];- if (option) setAutoLockTime(option.ms);- };-- const firstLabel = t(autoLockOptions[0]!.labelKey);- const lastLabel = t(autoLockOptions[autoLockOptions.length - 1]!.labelKey);- const selectedOption =- autoLockOptions[selectedIndex] ?? autoLockOptions[0]!;+ const selectedMs = autoLockOptions.some((o) => o.ms === currentValue)+ ? currentValue+ : autoLockOptions[0]!.ms;return (<TitledMiniDialog open={open} onClose={onClose} title={t("auto_lock")}>- <Stack sx={{ gap: 2, py: 1 }}>- <Typography- variant="small"- color="accent.main"- textAlign="center"- >- {t(selectedOption.labelKey)}- </Typography>- <Stack sx={{ px: 1 }}>- <Slider- value={selectedIndex}- min={0}- max={autoLockOptions.length - 1}- step={null}- marks={autoLockMarks}- onChange={handleChange}- onChangeCommitted={handleChangeCommitted}- sx={{- color: "accent.main",- "& .MuiSlider-markActive": {- backgroundColor: "accent.main",- },- }}- />- <Stack- direction="row"- justifyContent="space-between"- sx={{ mt: -0.5 }}- >- <Typography variant="mini" color="text.faint">- {firstLabel}- </Typography>- <Typography variant="mini" color="text.faint">- {lastLabel}- </Typography>- </Stack>- </Stack>+ <Stack sx={{ gap: 1.25, pt: 0.25, pb: 0.5, mt: -0.75 }}>+ <RowButtonGroup>+ {autoLockOptions.map((option, index) => (+ <React.Fragment key={option.ms}>+ {index > 0 && <RowButtonDivider />}+ <RowButton+ label={t(option.labelKey)}+ endIcon={+ selectedMs === option.ms ? (+ <CheckIcon+ sx={{ color: "accent.main" }}+ />+ ) : undefined+ }+ onClick={() => setAutoLockTime(option.ms)}+ />+ </React.Fragment>+ ))}+ </RowButtonGroup></Stack>- <DialogActions>- <FocusVisibleButton fullWidth color="accent" onClick={onClose}>+ <DialogActions sx={{ px: 0, mx: "-16px", pt: 0.75, pb: 0 }}>+ <FocusVisibleButton+ fullWidth+ color="accent"+ sx={{ minHeight: 48 }}+ onClick={onClose}+ >{t("done")}</FocusVisibleButton></DialogActions>diff --git a/web/packages/new/photos/services/app-lock.ts b/web/packages/new/photos/services/app-lock.tsindex 91865a0475..9f6ffdecb6 100644--- a/web/packages/new/photos/services/app-lock.ts+++ b/web/packages/new/photos/services/app-lock.ts@@ -24,10 +24,8 @@ import type { NativeDeviceLockCapability } from "ente-base/types/ipc";export interface AppLockState {/** Whether app lock is enabled. */enabled: boolean;- /** Active passphrase lock type. */- lockType: "pin" | "password" | "none";- /** Whether local native device lock is enabled. */- deviceLockEnabled: boolean;+ /** Active lock type. */+ lockType: "pin" | "password" | "device" | "none";/** Whether the app is currently locked. */isLocked: boolean;/** Consecutive failed attempts in current lockout cycle. */@@ -41,7 +39,6 @@ export interface AppLockState {const createDefaultState = (): AppLockState => ({enabled: false,lockType: "none",- deviceLockEnabled: false,isLocked: false,invalidAttemptCount: 0,cooldownExpiresAt: 0,@@ -104,8 +101,9 @@ const setSnapshot = (snapshot: AppLockState) => {const lsKeyEnabled = "appLock.enabled";const lsKeyLockType = "appLock.lockType";-const lsKeyDeviceLockEnabled = "appLock.deviceLockEnabled";const lsKeyAutoLockTimeMs = "appLock.autoLockTimeMs";+// Removed config key from older app-lock implementation; clear it on resets.+const lsKeyDeviceLockEnabled = "appLock.deviceLockEnabled";// -- KV DB keys (IndexedDB, async) --@@ -179,7 +177,6 @@ interface AppLockConfigSyncMessage {type: "config-updated";enabled: AppLockState["enabled"];lockType: AppLockState["lockType"];- deviceLockEnabled: AppLockState["deviceLockEnabled"];autoLockTimeMs: AppLockState["autoLockTimeMs"];}@@ -204,7 +201,6 @@ const appLockConfigFromSnapshot = (): Omit<AppLockConfigSyncMessage, "type"> => ({enabled: snapshot.enabled,lockType: snapshot.lockType,- deviceLockEnabled: snapshot.deviceLockEnabled,autoLockTimeMs: snapshot.autoLockTimeMs,});@@ -261,7 +257,10 @@ const readBruteForceStateFromKV = async () => {};const normalizeLockType = (lockType: string): AppLockState["lockType"] =>- lockType === "pin" || lockType === "password" || lockType === "none"+ lockType === "pin" ||+ lockType === "password" ||+ lockType === "device" ||+ lockType === "none"? lockType: "none";@@ -273,49 +272,40 @@ const isDesktopMacOS = () =>typeof navigator != "undefined" &&navigator.userAgent.toUpperCase().includes("MAC");-const normalizeDeviceLockEnabled = (enabled: boolean) =>- isDesktopMacOS() ? enabled : false;+const normalizeDeviceLockType = (lockType: AppLockState["lockType"]) =>+ lockType === "device" && !isDesktopMacOS() ? "none" : lockType;interface PersistedAppLockConfig {enabled: boolean;lockType: AppLockState["lockType"];- deviceLockEnabled: boolean;autoLockTimeMs: number;}const readPersistedAppLockConfig = (): PersistedAppLockConfig => {let enabled = localStorage.getItem(lsKeyEnabled) === "true";const lockTypeRaw = localStorage.getItem(lsKeyLockType);- const hasLegacyDeviceLockType =- lockTypeRaw === "biometric" || lockTypeRaw === "deviceLock";- const hasDeviceLockFlag =- localStorage.getItem(lsKeyDeviceLockEnabled) === "true";-- if (hasLegacyDeviceLockType) {- localStorage.setItem(lsKeyDeviceLockEnabled, "true");- localStorage.removeItem(lsKeyLockType);- }// Remove stale key from removed "hide content when switching apps" setting.localStorage.removeItem("appLock.hideContentOnBlur");- const lockType = normalizeLockType(lockTypeRaw ?? "none");- const deviceLockEnabled = normalizeDeviceLockEnabled(- hasDeviceLockFlag || hasLegacyDeviceLockType,+ const lockType = normalizeDeviceLockType(+ normalizeLockType(lockTypeRaw ?? "none"),);- if (!deviceLockEnabled) {- localStorage.removeItem(lsKeyDeviceLockEnabled);- if (enabled && lockType === "none") {- enabled = false;- localStorage.setItem(lsKeyEnabled, "false");- }+ if (enabled && lockType === "none") {+ enabled = false;+ localStorage.setItem(lsKeyEnabled, "false");+ }++ if (lockType === "none") {+ localStorage.removeItem(lsKeyLockType);+ } else if (lockTypeRaw !== lockType) {+ localStorage.setItem(lsKeyLockType, lockType);}return {enabled,lockType,- deviceLockEnabled,autoLockTimeMs: clampNonNegativeInt(Number(localStorage.getItem(lsKeyAutoLockTimeMs) ?? "0"),),@@ -330,7 +320,6 @@ const setSnapshotFromPersistedConfig = (..._state.snapshot,enabled: config.enabled,lockType: config.lockType,- deviceLockEnabled: config.deviceLockEnabled,isLocked,autoLockTimeMs: config.autoLockTimeMs,});@@ -400,7 +389,6 @@ if (_channel) {..._state.snapshot,enabled: false,lockType: "none",- deviceLockEnabled: false,autoLockTimeMs,isLocked: false,invalidAttemptCount: 0,@@ -413,10 +401,7 @@ if (_channel) {setSnapshot({..._state.snapshot,enabled: data.enabled,- lockType,- deviceLockEnabled: normalizeDeviceLockEnabled(- data.deviceLockEnabled,- ),+ lockType: normalizeDeviceLockType(lockType),autoLockTimeMs,});hydrateBruteForceStateIfNeeded();@@ -483,7 +468,10 @@ const stopBruteForceStateHydration = () => {};const hydrateBruteForceStateIfNeeded = () => {- if (!_state.snapshot.isLocked || _state.snapshot.lockType === "none") {+ const isPassphraseLock =+ _state.snapshot.lockType === "pin" ||+ _state.snapshot.lockType === "password";+ if (!_state.snapshot.isLocked || !isPassphraseLock) {stopBruteForceStateHydration();return;}@@ -681,13 +669,13 @@ export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {await resetBruteForceState(true);- localStorage.setItem(lsKeyDeviceLockEnabled, "true");+ localStorage.setItem(lsKeyLockType, "device");localStorage.setItem(lsKeyEnabled, "true");setSnapshot({..._state.snapshot,enabled: true,- deviceLockEnabled: true,+ lockType: "device",invalidAttemptCount: 0,cooldownExpiresAt: 0,});@@ -756,7 +744,10 @@ export const attemptDeviceLockUnlock =* attempts, signals that the caller should force-logout the user.*/export const attemptUnlock = async (input: string): Promise<UnlockResult> => {- if (_state.snapshot.lockType === "none") {+ const isPassphraseLock =+ _state.snapshot.lockType === "pin" ||+ _state.snapshot.lockType === "password";+ if (!isPassphraseLock) {return "failed";}@@ -851,8 +842,8 @@ export const lock = () => {export const logoutAppLock = async () => {localStorage.removeItem(lsKeyEnabled);localStorage.removeItem(lsKeyLockType);- localStorage.removeItem(lsKeyDeviceLockEnabled);localStorage.removeItem(lsKeyAutoLockTimeMs);+ localStorage.removeItem(lsKeyDeviceLockEnabled);await Promise.all([clearPassphraseMaterial(),@@ -898,7 +889,6 @@ export const disableAppLock = async () => {..._state.snapshot,enabled: false,lockType: "none",- deviceLockEnabled: false,isLocked: false,invalidAttemptCount: 0,cooldownExpiresAt: 0,