π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
enhance(AppLock):initalization-improvements-enhanced-functions-steamlined-passphrase-lock-setup
Aswin Asok9d6a7ba79ef2
diff --git a/web/apps/photos/src/components/Sidebar.tsx b/web/apps/photos/src/components/Sidebar.tsxindex 6d5a33f4a1..894804565e 100644--- a/web/apps/photos/src/components/Sidebar.tsx+++ b/web/apps/photos/src/components/Sidebar.tsx@@ -72,8 +72,8 @@ 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 { ShapeIcon } from "ente-new/photos/components/icons/ShapeIcon";+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";diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsxindex 6657a5d1c6..09446dcb71 100644--- a/web/apps/photos/src/pages/_app.tsx+++ b/web/apps/photos/src/pages/_app.tsx@@ -9,7 +9,6 @@ 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 {@@ -25,8 +24,10 @@ import {} from "ente-base/components/utils/hooks-app";import { photosTheme } from "ente-base/components/utils/theme";import { BaseContext, deriveBaseContext } from "ente-base/context";+import { subscribeMainWindowFocus } from "ente-base/electron";import log from "ente-base/log";import { logStartupBanner } from "ente-base/log-web";+import { updateSessionFromElectronSafeStorageIfNeeded } from "ente-base/session";import type { AppUpdate } from "ente-base/types/ipc";import {initVideoProcessing,@@ -40,8 +41,12 @@ 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 {+ initAppLock,+ lock,+ refreshAppLockStateFromSession,+} from "ente-new/photos/services/app-lock";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";@@ -68,6 +73,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {const { loadingBarRef, showLoadingBar, hideLoadingBar } = useLoadingBar();const [watchFolderView, setWatchFolderView] = useState(false);+ const [isAppLockReady, setIsAppLockReady] = useState(() => !isDesktop);const appLock = useAppLockSnapshot();const autoLockTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -75,7 +81,23 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {useEffect(() => {logStartupBanner(savedLocalUser()?.id);+ const isElectron = !!globalThis.electron;+ const isAppLockEnabled =+ localStorage.getItem("appLock.enabled") === "true";+initAppLock();+ if (!isElectron || !isAppLockEnabled) {+ setIsAppLockReady(true);+ }+ void (async () => {+ if (!isElectron || !isAppLockEnabled) return;+ try {+ await updateSessionFromElectronSafeStorageIfNeeded();+ } finally {+ refreshAppLockStateFromSession();+ setIsAppLockReady(true);+ }+ })();void isLocalStorageAndIndexedDBMismatch().then((mismatch) => {if (mismatch) {log.error("Logging out (IndexedDB and local storage mismatch)");@@ -241,7 +263,7 @@ const App: React.FC<AppProps> = ({ Component, pageProps }) => {{isDesktop && <WindowTitlebar>{title}</WindowTitlebar>}<BaseContext value={baseContext}><PhotosAppContext value={appContext}>- {!isI18nReady ? (+ {!isI18nReady || !isAppLockReady ? (<LoadingIndicator />) : (<>diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsxindex bc82e63b19..cd889c0feb 100644--- a/web/apps/photos/src/pages/gallery.tsx+++ b/web/apps/photos/src/pages/gallery.tsx@@ -418,7 +418,7 @@ const Page: React.FC = () => {useEffect(() => {const electron = globalThis.electron;let syncIntervalID: ReturnType<typeof setInterval> | undefined;- let unsubscribeMainWindowFocus = () => {};+ let unsubscribeMainWindowFocus = () => undefined;void (async () => {if (!haveMasterKeyInSession() || !(await savedAuthToken())) {diff --git a/web/apps/photos/src/pages/index.tsx b/web/apps/photos/src/pages/index.tsxindex f0e888ae7d..d990a5d273 100644--- a/web/apps/photos/src/pages/index.tsx+++ b/web/apps/photos/src/pages/index.tsx@@ -24,7 +24,6 @@ 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";@@ -128,9 +127,6 @@ const Page: React.FC = () => {});} else {await updateSessionFromElectronSafeStorageIfNeeded();- if (globalThis.electron) {- refreshAppLockStateFromSession();- }if ((await masterKeyFromSession()) &&(await savedAuthToken())diff --git a/web/apps/photos/src/services/logout.ts b/web/apps/photos/src/services/logout.tsindex 1ed62c70dc..fb2685b4d4 100644--- a/web/apps/photos/src/services/logout.ts+++ b/web/apps/photos/src/services/logout.ts@@ -58,6 +58,12 @@ export const photosLogout = async () => {ignoreError("Settings", e);}+ try {+ await logoutAppLock();+ } catch (e) {+ ignoreError("App lock", e);+ }+try {logoutUserDetails();} catch (e) {@@ -104,12 +110,6 @@ 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.tsindex 8b9fe9aab8..98d34e0399 100644--- a/web/packages/base/electron.ts+++ b/web/packages/base/electron.ts@@ -44,7 +44,10 @@ const attachMainWindowFocusBridgeIfNeeded = () => {};const detachMainWindowFocusBridgeIfNeeded = () => {- if (!hasAttachedMainWindowFocusBridge || mainWindowFocusListeners.size > 0) {+ if (+ !hasAttachedMainWindowFocusBridge ||+ mainWindowFocusListeners.size > 0+ ) {return;}diff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsxindex ef2d148e21..2f046d4bb4 100644--- a/web/packages/new/photos/components/AppLockOverlay.tsx+++ b/web/packages/new/photos/components/AppLockOverlay.tsx@@ -32,6 +32,7 @@ import React, {useState,} from "react";import {+ appLockCooldownDurationMs,attemptDeviceLockUnlock,attemptUnlock,type DeviceLockUnlockResult,@@ -745,11 +746,6 @@ interface CooldownScreenProps {deviceLockLoading?: boolean;}-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,@@ -758,13 +754,13 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({onDeviceLockUnlock,deviceLockLoading,}) => {- const durationMs = cooldownDurationMs(attemptCount);+ const durationMs = appLockCooldownDurationMs(attemptCount);const progress =durationMs > 0? Math.min(100, ((durationMs - remainingMs) / durationMs) * 100): 0;const nextAttemptCount = attemptCount + 1;- const nextCooldownMs = cooldownDurationMs(nextAttemptCount);+ const nextCooldownMs = appLockCooldownDurationMs(nextAttemptCount);const nextAttemptMessage =nextAttemptCount >= 10? t("one_more_wrong_attempt_logout")diff --git a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx b/web/packages/new/photos/components/sidebar/AppLockSettings.tsxindex 46aa2570d7..db188c00c9 100644--- a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx+++ b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx@@ -7,6 +7,13 @@ import {TextField,Typography,} from "@mui/material";+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 {RowButton,RowButtonDivider,@@ -14,16 +21,11 @@ import {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 { 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 { t } from "i18next";+import React, { useCallback, useEffect, useRef, useState } from "react";import {disableAppLock,setAutoLockTime,@@ -31,13 +33,13 @@ import {setupPassword,setupPin,} from "../../services/app-lock";-import { t } from "i18next";-import React, { useCallback, useEffect, useRef, useState } from "react";import { useAppLockSnapshot } from "../utils/use-snapshot";-export const AppLockSettings: React.FC<- NestedSidebarDrawerVisibilityProps-> = ({ open, onClose, onRootClose }) => {+export const AppLockSettings: React.FC<NestedSidebarDrawerVisibilityProps> = ({+ open,+ onClose,+ onRootClose,+}) => {const state = useAppLockSnapshot();const [pinDialogOpen, setPinDialogOpen] = useState(false);@@ -93,7 +95,9 @@ export const AppLockSettings: React.FC<);} catch (e) {log.error("Failed to set up device lock app lock", e);- showMiniDialog(errorDialogAttributes(t("device_lock_setup_failed")));+ showMiniDialog(+ errorDialogAttributes(t("device_lock_setup_failed")),+ );} finally {setIsSettingDeviceLock(false);}@@ -128,7 +132,11 @@ export const AppLockSettings: React.FC<<Stack><Typographyvariant="small"- sx={{ px: 1, pb: "6px", color: "text.muted" }}+ sx={{+ px: 1,+ pb: "6px",+ color: "text.muted",+ }}>{t("lock_type")}</Typography>@@ -138,7 +146,9 @@ export const AppLockSettings: React.FC<endIcon={state.lockType === "pin" ? (<CheckIcon- sx={{ color: "accent.main" }}+ sx={{+ color: "accent.main",+ }}/>) : undefined}@@ -150,7 +160,9 @@ export const AppLockSettings: React.FC<endIcon={state.lockType === "password" ? (<CheckIcon- sx={{ color: "accent.main" }}+ sx={{+ color: "accent.main",+ }}/>) : undefined}@@ -168,7 +180,9 @@ export const AppLockSettings: React.FC<endIcon={state.deviceLockEnabled ? (<CheckIcon- sx={{ color: "accent.main" }}+ sx={{+ color: "accent.main",+ }}/>) : undefined}@@ -256,6 +270,24 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({const inputRefs = useRef<(HTMLInputElement | null)[]>([]);const confirmInputRefs = useRef<(HTMLInputElement | null)[]>([]);+ const focusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const queueFocus = useCallback((fn: () => void, delay: number) => {+ if (focusTimerRef.current) {+ clearTimeout(focusTimerRef.current);+ }+ focusTimerRef.current = setTimeout(fn, delay);+ }, []);++ useEffect(+ () => () => {+ if (focusTimerRef.current) {+ clearTimeout(focusTimerRef.current);+ focusTimerRef.current = null;+ }+ },+ [],+ );const resetState = useCallback(() => {setStep("enter");@@ -310,15 +342,15 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({const handleNext = useCallback(() => {if (pin.some((d) => !d)) return;setStep("confirm");- setTimeout(() => confirmInputRefs.current[0]?.focus(), 50);- }, [pin]);+ queueFocus(() => confirmInputRefs.current[0]?.focus(), 50);+ }, [pin, queueFocus]);const handleBack = useCallback(() => {setStep("enter");setConfirmPin(["", "", "", ""]);setError("");- setTimeout(() => inputRefs.current[0]?.focus(), 50);- }, []);+ queueFocus(() => inputRefs.current[0]?.focus(), 50);+ }, [queueFocus]);const handleConfirm = useCallback(async () => {const pinStr = pin.join("");@@ -326,13 +358,13 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({if (pinStr !== confirmStr) {setError(t("pin_mismatch"));setConfirmPin(["", "", "", ""]);- setTimeout(() => confirmInputRefs.current[0]?.focus(), 50);+ queueFocus(() => confirmInputRefs.current[0]?.focus(), 50);return;}await setupPin(pinStr);onComplete();resetState();- }, [pin, confirmPin, onComplete, resetState]);+ }, [pin, confirmPin, onComplete, queueFocus, resetState]);const renderPinInputs = (values: string[],@@ -390,7 +422,9 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({<Stack sx={{ gap: 1.5, py: 0 }}>{step === "enter" ? (<>- <Typography sx={{ color: "text.muted", textAlign: "left" }}>+ <Typography+ sx={{ color: "text.muted", textAlign: "left" }}+ >{t("enter_pin")}</Typography>{renderPinInputs(pin, inputRefs, false)}@@ -405,14 +439,24 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({</>) : (<>- <Typography sx={{ color: "text.muted", textAlign: "left" }}>+ <Typography+ sx={{ color: "text.muted", textAlign: "left" }}+ >{t("confirm_pin")}</Typography>- {renderPinInputs(confirmPin, confirmInputRefs, true, !!error)}+ {renderPinInputs(+ confirmPin,+ confirmInputRefs,+ true,+ !!error,+ )}{error && (<Typographyvariant="small"- sx={{ color: "critical.main", textAlign: "left" }}+ sx={{+ color: "critical.main",+ textAlign: "left",+ }}>{error}</Typography>@@ -457,12 +501,30 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({const passwordInputRef = useRef<HTMLInputElement>(null);const confirmPasswordInputRef = useRef<HTMLInputElement>(null);+ const focusTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const queueFocus = useCallback((fn: () => void, delay: number) => {+ if (focusTimerRef.current) {+ clearTimeout(focusTimerRef.current);+ }+ focusTimerRef.current = setTimeout(fn, delay);+ }, []);++ useEffect(+ () => () => {+ if (focusTimerRef.current) {+ clearTimeout(focusTimerRef.current);+ focusTimerRef.current = null;+ }+ },+ [],+ );useEffect(() => {if (open) {- setTimeout(() => passwordInputRef.current?.focus(), 300);+ queueFocus(() => passwordInputRef.current?.focus(), 300);}- }, [open]);+ }, [open, queueFocus]);const resetState = useCallback(() => {setStep("enter");@@ -481,15 +543,15 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({const handleNext = useCallback(() => {if (!password) return;setStep("confirm");- setTimeout(() => confirmPasswordInputRef.current?.focus(), 300);- }, [password]);+ queueFocus(() => confirmPasswordInputRef.current?.focus(), 300);+ }, [password, queueFocus]);const handleBack = useCallback(() => {setStep("enter");setConfirmPassword("");setError("");- setTimeout(() => passwordInputRef.current?.focus(), 300);- }, []);+ queueFocus(() => passwordInputRef.current?.focus(), 300);+ }, [queueFocus]);const handleConfirm = useCallback(async () => {if (password !== confirmPassword) {@@ -525,9 +587,7 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({setError("");}}slotProps={{- htmlInput: {- ref: passwordInputRef,- },+ htmlInput: { ref: passwordInputRef },input: {endAdornment: (<ShowHidePasswordInputAdornment@@ -563,9 +623,7 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({setError("");}}slotProps={{- htmlInput: {- ref: confirmPasswordInputRef,- },+ htmlInput: { ref: confirmPasswordInputRef },input: {endAdornment: (<ShowHidePasswordInputAdornment@@ -619,11 +677,25 @@ const AutoLockDialog: React.FC<AutoLockDialogProps> = ({onClose,currentValue,}) => {- const currentIndex = autoLockOptions.findIndex(+ 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);@@ -631,6 +703,8 @@ const AutoLockDialog: React.FC<AutoLockDialogProps> = ({const firstLabel = t(autoLockOptions[0]!.labelKey);const lastLabel = t(autoLockOptions[autoLockOptions.length - 1]!.labelKey);+ const selectedOption =+ autoLockOptions[selectedIndex] ?? autoLockOptions[0]!;return (<TitledMiniDialog open={open} onClose={onClose} title={t("auto_lock")}>@@ -640,16 +714,17 @@ const AutoLockDialog: React.FC<AutoLockDialogProps> = ({color="accent.main"textAlign="center">- {autoLockLabel(currentValue)}+ {t(selectedOption.labelKey)}</Typography><Stack sx={{ px: 1 }}><Slider- value={currentIndex === -1 ? 0 : currentIndex}+ value={selectedIndex}min={0}max={autoLockOptions.length - 1}step={null}marks={autoLockMarks}onChange={handleChange}+ onChangeCommitted={handleChangeCommitted}sx={{color: "accent.main","& .MuiSlider-markActive": {@@ -672,11 +747,7 @@ const AutoLockDialog: React.FC<AutoLockDialogProps> = ({</Stack></Stack><DialogActions>- <FocusVisibleButton- fullWidth- color="accent"- onClick={onClose}- >+ <FocusVisibleButton fullWidth color="accent" 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 2d13b50153..1a8b4a6cec 100644--- a/web/packages/new/photos/services/app-lock.ts+++ b/web/packages/new/photos/services/app-lock.ts@@ -128,56 +128,139 @@ const webAuthnChallengeBytes = 32;const userVerifiedFlag = 0x04;const deviceLockEnablePromptReason = "Enable device lock for Ente";const deviceLockUnlockPromptReason = "Unlock Ente";+const maxInvalidUnlockAttempts = 10;+const cooldownStartsAtAttempt = 5;+const cooldownBaseSeconds = 30;+const unlockAttemptLockName = "ente-app-lock-unlock-attempt";++/**+ * Return the cooldown duration for a failed-attempt count.+ *+ * This policy is shared by both lockout enforcement and cooldown UI.+ */+export const appLockCooldownDurationMs = (attemptCount: number): number => {+ if (attemptCount < cooldownStartsAtAttempt) return 0;+ return (+ Math.pow(2, attemptCount - cooldownStartsAtAttempt) *+ cooldownBaseSeconds *+ 1000+ );+};// -- BroadcastChannel for multi-tab sync ---const _channel = new BroadcastChannel("ente-app-lock");+const _channel =+ typeof BroadcastChannel != "undefined"+ ? new BroadcastChannel("ente-app-lock")+ : undefined;++interface AppLockConfigSyncMessage {+ type: "config-updated";+ enabled: AppLockState["enabled"];+ lockType: AppLockState["lockType"];+ deviceLockEnabled: AppLockState["deviceLockEnabled"];+ autoLockTimeMs: AppLockState["autoLockTimeMs"];+}++interface AppLockBruteForceSyncMessage {+ type: "bruteforce-updated";+ invalidAttemptCount: AppLockState["invalidAttemptCount"];+ cooldownExpiresAt: AppLockState["cooldownExpiresAt"];+}++type AppLockChannelMessage =+ | { type: "lock" }+ | { type: "unlock" }+ | AppLockConfigSyncMessage+ | AppLockBruteForceSyncMessage;++const postChannelMessage = (payload: AppLockChannelMessage) => {+ _channel?.postMessage(payload);+};-_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") {+const appLockConfigFromSnapshot = (+ snapshot: AppLockState,+): Omit<AppLockConfigSyncMessage, "type"> => ({+ enabled: snapshot.enabled,+ lockType: snapshot.lockType,+ deviceLockEnabled: snapshot.deviceLockEnabled,+ autoLockTimeMs: snapshot.autoLockTimeMs,+});++const syncConfigAcrossTabs = (snapshot: AppLockState) => {+ const payload: AppLockConfigSyncMessage = {+ type: "config-updated",+ ...appLockConfigFromSnapshot(snapshot),+ };+ postChannelMessage(payload);+};++const syncBruteForceAcrossTabs = (+ invalidAttemptCount: number,+ cooldownExpiresAt: number,+) => {+ const payload: AppLockBruteForceSyncMessage = {+ type: "bruteforce-updated",+ invalidAttemptCount,+ cooldownExpiresAt,+ };+ postChannelMessage(payload);+};++const setBruteForceSnapshot = (+ invalidAttemptCount: number,+ cooldownExpiresAt: number,+ shouldBroadcast = false,+) => {+ if (+ _state.snapshot.invalidAttemptCount !== invalidAttemptCount ||+ _state.snapshot.cooldownExpiresAt !== cooldownExpiresAt+ ) {setSnapshot({..._state.snapshot,- isLocked: false,- invalidAttemptCount: 0,- cooldownExpiresAt: 0,+ invalidAttemptCount,+ cooldownExpiresAt,});- stopBruteForceStateHydration();+ }+ if (shouldBroadcast) {+ syncBruteForceAcrossTabs(invalidAttemptCount, cooldownExpiresAt);}};-// -- Public API --+const readBruteForceStateFromKV = async () => {+ const [invalidAttempts, cooldownExpiry] = await Promise.all([+ getKVN(kvKeyInvalidAttempts),+ getKVN(kvKeyCooldownExpiresAt),+ ]);-/**- * 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 = () => {+ return {+ invalidAttemptCount: Math.max(0, invalidAttempts ?? 0),+ cooldownExpiresAt: Math.max(0, cooldownExpiry ?? 0),+ };+};++const normalizeLockType = (lockType: string): AppLockState["lockType"] =>+ lockType === "pin" || lockType === "password" || lockType === "none"+ ? lockType+ : "none";++const clampNonNegativeInt = (value: number) =>+ Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;++interface PersistedAppLockConfig {+ enabled: boolean;+ lockType: AppLockState["lockType"];+ deviceLockEnabled: boolean;+ autoLockTimeMs: number;+}++const readPersistedAppLockConfig = (): PersistedAppLockConfig => {const enabled = localStorage.getItem(lsKeyEnabled) === "true";const lockTypeRaw = localStorage.getItem(lsKeyLockType);- 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");@@ -187,21 +270,147 @@ export const initAppLock = () => {// Remove stale key from removed "hide content when switching apps" setting.localStorage.removeItem("appLock.hideContentOnBlur");- const isLocked = enabled && haveMasterKeyInSession();+ return {+ enabled,+ lockType: normalizeLockType(lockTypeRaw ?? "none"),+ deviceLockEnabled: hasDeviceLockFlag || hasLegacyDeviceLockType,+ autoLockTimeMs: clampNonNegativeInt(+ Number(localStorage.getItem(lsKeyAutoLockTimeMs) ?? "0"),+ ),+ };+};+const setSnapshotFromPersistedConfig = (+ config: PersistedAppLockConfig,+ isLocked: boolean,+) => {setSnapshot({..._state.snapshot,- enabled,- lockType,- deviceLockEnabled,+ enabled: config.enabled,+ lockType: config.lockType,+ deviceLockEnabled: config.deviceLockEnabled,isLocked,- autoLockTimeMs,+ autoLockTimeMs: config.autoLockTimeMs,});-- // Restore brute-force state from KV DB so cooldowns survive page refresh.hydrateBruteForceStateIfNeeded();};+let _localUnlockAttemptQueue = Promise.resolve();++const withLocalUnlockAttemptLock = async <T>(fn: () => Promise<T>) => {+ const previous = _localUnlockAttemptQueue;+ let releaseCurrent: (() => void) | undefined;++ _localUnlockAttemptQueue = new Promise<void>((resolve) => {+ releaseCurrent = resolve;+ });++ await previous;+ try {+ return await fn();+ } finally {+ releaseCurrent?.();+ }+};++const withUnlockAttemptLock = async <T>(fn: () => Promise<T>) => {+ const locks =+ typeof navigator == "undefined"+ ? undefined+ : (navigator as Navigator & { locks?: LockManager }).locks;++ if (locks && typeof locks.request == "function") {+ const result: unknown = await locks.request(+ unlockAttemptLockName,+ { mode: "exclusive" },+ fn,+ );+ return result as T;+ }++ return withLocalUnlockAttemptLock(fn);+};++if (_channel) {+ _channel.onmessage = (event: MessageEvent) => {+ const data = event.data as AppLockChannelMessage;++ switch (data.type) {+ case "lock":+ setSnapshot({ ..._state.snapshot, isLocked: true });+ hydrateBruteForceStateIfNeeded();+ break;+ case "unlock":+ setSnapshot({+ ..._state.snapshot,+ isLocked: false,+ invalidAttemptCount: 0,+ cooldownExpiresAt: 0,+ });+ stopBruteForceStateHydration();+ break;+ case "config-updated": {+ const lockType = normalizeLockType(data.lockType);+ const autoLockTimeMs = clampNonNegativeInt(data.autoLockTimeMs);++ if (!data.enabled) {+ setSnapshot({+ ..._state.snapshot,+ enabled: false,+ lockType: "none",+ deviceLockEnabled: false,+ autoLockTimeMs,+ isLocked: false,+ invalidAttemptCount: 0,+ cooldownExpiresAt: 0,+ });+ stopBruteForceStateHydration();+ break;+ }++ setSnapshot({+ ..._state.snapshot,+ enabled: data.enabled,+ lockType,+ deviceLockEnabled: data.deviceLockEnabled,+ autoLockTimeMs,+ });+ hydrateBruteForceStateIfNeeded();+ break;+ }+ case "bruteforce-updated":+ setBruteForceSnapshot(+ clampNonNegativeInt(data.invalidAttemptCount),+ clampNonNegativeInt(data.cooldownExpiresAt),+ );+ break;+ }+ };+}++// -- 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. On desktop startup, it locks+ * pessimistically while safe-storage hydration is in flight.+ *+ * 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 config = readPersistedAppLockConfig();+ const hasSession = haveMasterKeyInSession();++ // On desktop, lock pessimistically while safe-storage hydration is in flight.+ const isLocked = config.enabled && (hasSession || !!globalThis.electron);++ setSnapshotFromPersistedConfig(config, isLocked);+};+/*** Restore the brute-force attempt count and cooldown expiry from KV DB into* the in-memory snapshot.@@ -211,28 +420,14 @@ export const initAppLock = () => {*/const restoreBruteForceState = async (generation: number) => {try {- const [invalidAttempts, cooldownExpiry] = await Promise.all([- getKVN(kvKeyInvalidAttempts),- getKVN(kvKeyCooldownExpiresAt),- ]);+ const { invalidAttemptCount, cooldownExpiresAt } =+ await readBruteForceStateFromKV();if (generation !== _bruteForceStateHydrationGeneration) {return;}- const invalidAttemptCount = invalidAttempts ?? 0;- const cooldownExpiresAt = cooldownExpiry ?? 0;-- if (- _state.snapshot.invalidAttemptCount !== invalidAttemptCount ||- _state.snapshot.cooldownExpiresAt !== cooldownExpiresAt- ) {- setSnapshot({- ..._state.snapshot,- invalidAttemptCount,- cooldownExpiresAt,- });- }+ setBruteForceSnapshot(invalidAttemptCount, cooldownExpiresAt);} catch (e) {log.error("Failed to restore brute-force state from KV DB", e);}@@ -336,6 +531,34 @@ const isUserVerified = (authenticatorData: ArrayBuffer) => {return (flags & userVerifiedFlag) !== 0;};+const isArrayBuffer = (value: unknown): value is ArrayBuffer =>+ value instanceof ArrayBuffer;++const assertionResponseFromCredential = (credential: PublicKeyCredential) => {+ const response = credential.response as+ | AuthenticatorAssertionResponse+ | undefined;+ if (!response) return undefined;++ if (+ !isArrayBuffer(response.clientDataJSON) ||+ !isArrayBuffer(response.authenticatorData) ||+ !isArrayBuffer(response.signature)+ ) {+ return undefined;+ }++ if (+ response.clientDataJSON.byteLength === 0 ||+ response.authenticatorData.byteLength === 0 ||+ response.signature.byteLength === 0+ ) {+ return undefined;+ }++ return response;+};+const clearPassphraseMaterial = async () =>Promise.all([removeKV(kvKeyHash),@@ -344,11 +567,13 @@ const clearPassphraseMaterial = async () =>removeKV(kvKeyMemLimit),]);-const resetBruteForceState = async () =>- Promise.all([+const resetBruteForceState = async (shouldBroadcast = false) => {+ await Promise.all([setKV(kvKeyInvalidAttempts, 0),setKV(kvKeyCooldownExpiresAt, 0),]);+ setBruteForceSnapshot(0, 0, shouldBroadcast);+};const unlockLocally = () => {setSnapshot({@@ -358,7 +583,7 @@ const unlockLocally = () => {cooldownExpiresAt: 0,});stopBruteForceStateHydration();- _channel.postMessage({ type: "unlock" });+ postChannelMessage({ type: "unlock" });};/**@@ -368,7 +593,9 @@ const unlockLocally = () => {* Call this after desktop safe-storage restore to prevent auto-login bypass.*/export const refreshAppLockStateFromSession = () => {- initAppLock();+ const config = readPersistedAppLockConfig();+ const isLocked = config.enabled && haveMasterKeyInSession();+ setSnapshotFromPersistedConfig(config, isLocked);};/**@@ -386,56 +613,42 @@ export type SetupDeviceLockResult = "success" | "not-supported" | "failed";* 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);+const setupPassphraseLock = async (+ lockType: Extract<AppLockState["lockType"], "pin" | "password">,+ input: string,+) => {+ const derived = await deriveInteractiveKey(input);await Promise.all([setKV(kvKeyHash, derived.key),setKV(kvKeySalt, derived.salt),setKV(kvKeyOpsLimit, derived.opsLimit),setKV(kvKeyMemLimit, derived.memLimit),- resetBruteForceState(),+ resetBruteForceState(true),]);- localStorage.setItem(lsKeyLockType, "pin");+ localStorage.setItem(lsKeyLockType, lockType);localStorage.setItem(lsKeyEnabled, "true");setSnapshot({..._state.snapshot,enabled: true,- lockType: "pin",+ lockType,invalidAttemptCount: 0,cooldownExpiresAt: 0,});stopBruteForceStateHydration();+ syncConfigAcrossTabs(_state.snapshot);};+export const setupPin = async (pin: string) => setupPassphraseLock("pin", 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 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");-- setSnapshot({- ..._state.snapshot,- enabled: true,- lockType: "password",- invalidAttemptCount: 0,- cooldownExpiresAt: 0,- });- stopBruteForceStateHydration();-};+export const setupPassword = async (password: string) =>+ setupPassphraseLock("password", password);/*** Set up local WebAuthn device lock authentication for app lock.@@ -459,7 +672,7 @@ export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {);if (!unlocked) return "failed";- await resetBruteForceState();+ await resetBruteForceState(true);localStorage.setItem(lsKeyDeviceLockEnabled, "true");localStorage.setItem(lsKeyEnabled, "true");@@ -472,6 +685,7 @@ export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {cooldownExpiresAt: 0,});stopBruteForceStateHydration();+ syncConfigAcrossTabs(_state.snapshot);return "success";}@@ -522,7 +736,7 @@ export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {await Promise.all([setKV(kvKeyWebAuthnCredentialID, credentialID),- resetBruteForceState(),+ resetBruteForceState(true),]);localStorage.setItem(lsKeyDeviceLockEnabled, "true");@@ -536,6 +750,7 @@ export const setupDeviceLock = async (): Promise<SetupDeviceLockResult> => {cooldownExpiresAt: 0,});stopBruteForceStateHydration();+ syncConfigAcrossTabs(_state.snapshot);return "success";} catch (e) {@@ -563,6 +778,11 @@ 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.+ *+ * Security note: This flow uses browser-provided credential APIs and validates+ * challenge/type/origin/credential-id/user-verification locally. It is+ * designed as a local app-lock boundary, not as a replacement for server-side+ * WebAuthn authentication ceremonies.*/export const attemptDeviceLockUnlock =async (): Promise<DeviceLockUnlockResult> => {@@ -623,8 +843,25 @@ export const attemptDeviceLockUnlock =return "failed";}- const response =- credential.response as AuthenticatorAssertionResponse;+ if (credential.type !== "public-key") {+ log.error("Device lock unlock credential type mismatch");+ return "failed";+ }+ if (!(credential.rawId instanceof ArrayBuffer)) {+ log.error("Device lock unlock credential rawId missing");+ return "failed";+ }+ if (credential.rawId.byteLength === 0) {+ log.error("Device lock unlock credential rawId is empty");+ return "failed";+ }++ const response = assertionResponseFromCredential(credential);+ if (!response) {+ log.error("Device lock unlock response is malformed");+ return "failed";+ }+const clientData = parseClientDataJSON(response.clientDataJSON);if (!clientData) {return "failed";@@ -685,73 +922,77 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {return "failed";}- // Ensure persisted lockout state has been rehydrated before enforcing.- await ensureBruteForceStateHydrated();+ return withUnlockAttemptLock<UnlockResult>(async () => {+ // Ensure persisted lockout state has been rehydrated before enforcing.+ await ensureBruteForceStateHydrated();- // 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);+ // Refresh lockout state from KV so stale tabs cannot reset counters.+ const persistedState = await readBruteForceStateFromKV();+ const invalidAttemptCount = Math.max(+ _state.snapshot.invalidAttemptCount,+ persistedState.invalidAttemptCount,+ );+ const cooldownExpiresAt = Math.max(+ _state.snapshot.cooldownExpiresAt,+ persistedState.cooldownExpiresAt,+ );+ setBruteForceSnapshot(invalidAttemptCount, cooldownExpiresAt);- if (!salt || !storedHash || !opsLimit || !memLimit) {- log.error("App lock credentials missing from KV DB");- return "failed";- }+ // Check cooldown from in-memory state.+ if (+ _state.snapshot.cooldownExpiresAt > 0 &&+ Date.now() < _state.snapshot.cooldownExpiresAt+ ) {+ return "cooldown";+ }- // Derive key from input using the stored parameters.- const derivedKey = await deriveKey(input, salt, opsLimit, memLimit);+ // 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 (derivedKey === storedHash) {- // Correct input: reset attempts, unlock.- await resetBruteForceState();- unlockLocally();- return "success";- }+ if (!salt || !storedHash || !opsLimit || !memLimit) {+ log.error("App lock credentials missing from KV DB");+ return "failed";+ }- // Incorrect input: increment attempts.- const count = _state.snapshot.invalidAttemptCount + 1;- await setKV(kvKeyInvalidAttempts, count);+ // Derive key from input using the stored parameters.+ const derivedKey = await deriveKey(input, salt, opsLimit, memLimit);- if (count >= 10) {- // Too many attempts: signal logout.- await setKV(kvKeyCooldownExpiresAt, 0);- setSnapshot({- ..._state.snapshot,- invalidAttemptCount: count,- cooldownExpiresAt: 0,- });- return "logout";- }+ if (derivedKey === storedHash) {+ // Correct input: reset attempts, unlock.+ await resetBruteForceState(true);+ unlockLocally();+ return "success";+ }- 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);+ // Incorrect input: increment attempts.+ const count = invalidAttemptCount + 1;+ await setKV(kvKeyInvalidAttempts, count);- setSnapshot({- ..._state.snapshot,- invalidAttemptCount: count,- cooldownExpiresAt: expiresAt,- });+ if (count >= maxInvalidUnlockAttempts) {+ // Too many attempts: signal logout.+ await setKV(kvKeyCooldownExpiresAt, 0);+ setBruteForceSnapshot(count, 0, true);+ return "logout";+ }- // The current failed attempt has triggered cooldown, so surface the- // cooldown state immediately to callers/UI.- return "cooldown";- } else {- setSnapshot({ ..._state.snapshot, invalidAttemptCount: count });- }+ if (count >= cooldownStartsAtAttempt) {+ // Enforce cooldown with exponential backoff.+ const expiresAt = Date.now() + appLockCooldownDurationMs(count);+ await setKV(kvKeyCooldownExpiresAt, expiresAt);+ setBruteForceSnapshot(count, expiresAt, true);++ // The current failed attempt has triggered cooldown, so surface the+ // cooldown state immediately to callers/UI.+ return "cooldown";+ } else {+ setBruteForceSnapshot(count, 0, true);+ }- return "failed";+ return "failed";+ });};/**@@ -760,7 +1001,7 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {export const lock = () => {setSnapshot({ ..._state.snapshot, isLocked: true });hydrateBruteForceStateIfNeeded();- _channel.postMessage({ type: "lock" });+ postChannelMessage({ type: "lock" });};/**@@ -784,14 +1025,19 @@ export const logoutAppLock = async () => {stopBruteForceStateHydration();_state = new AppLockModuleState();+ syncConfigAcrossTabs(_state.snapshot);+ syncBruteForceAcrossTabs(0, 0);+ postChannelMessage({ type: "unlock" });};/*** Update the auto-lock delay.*/export const setAutoLockTime = (ms: number) => {- localStorage.setItem(lsKeyAutoLockTimeMs, String(ms));- setSnapshot({ ..._state.snapshot, autoLockTimeMs: ms });+ const autoLockTimeMs = clampNonNegativeInt(ms);+ localStorage.setItem(lsKeyAutoLockTimeMs, String(autoLockTimeMs));+ setSnapshot({ ..._state.snapshot, autoLockTimeMs });+ syncConfigAcrossTabs(_state.snapshot);};/**@@ -822,4 +1068,6 @@ export const disableAppLock = async () => {cooldownExpiresAt: 0,});stopBruteForceStateHydration();+ syncConfigAcrossTabs(_state.snapshot);+ syncBruteForceAcrossTabs(0, 0);};