π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix(AppLock):fixing-ui-styles
Aswin Asok13636a2d892c
diff --git a/mobile/apps/photos/docs/APP_LOCK_IMPLEMENTATION.md b/mobile/apps/photos/docs/APP_LOCK_IMPLEMENTATION.mdnew file mode 100644index 0000000000..f6d2e6c88d--- /dev/null+++ b/mobile/apps/photos/docs/APP_LOCK_IMPLEMENTATION.md@@ -0,0 +1,622 @@+# App Lock Implementation - Ente Photos (Flutter Mobile)++> yo so you're a frontend dev tryna port the app lock to desktop and you've never touched Flutter? say less. i gotchu. this doc breaks down *exactly* how the mobile app lock works, no cap. every file, every flow, every crypto detail -- all here. think of Flutter widgets like React components and you'll be fine.++---++## Table of Contents++1. [Architecture Overview](#1-architecture-overview)+2. [Server Involvement](#2-server-involvement)+3. [Lock Types & Mutual Exclusivity](#3-lock-types--mutual-exclusivity)+4. [Key Files & Classes](#4-key-files--classes)+5. [Lifecycle & Flow](#5-lifecycle--flow)+ - [Cold Start](#51-cold-start)+ - [Background to Foreground (Auto-Lock)](#52-background--foreground-auto-lock)+ - [Unlock Flow](#53-unlock-flow)+6. [Cryptography & Hashing](#6-cryptography--hashing)+7. [On-Device Storage](#7-on-device-storage)+8. [Brute-Force Protection](#8-brute-force-protection)+9. [Settings UI & Configuration](#9-settings-ui--configuration)+10. [External Packages](#10-external-packages)+11. [Shared `lock_screen` Package (Newer Refactor)](#11-shared-lock_screen-package-newer-refactor)+12. [Desktop Considerations](#12-desktop-considerations)++---++## 1. Architecture Overview++okay so the whole app lock is **purely client-side**. zero server calls. nada. it's basically four layers stacked on top of each other, kinda like how you'd nest context providers in React but Flutter-style:++```++-----------------------------------------------------++| AppLock Widget (lib/ui/tools/app_lock.dart) | <-- the big wrapper+| wraps the ENTIRE app. watches app lifecycle. |+| starts a timer when you background the app. |++-----------------------------------------------------++| LockScreen Widget (lib/ui/tools/lock_screen.dart) | <-- the actual lock UI+| lock icon, "Tap to Unlock", cooldown timer, |+| logout button -- the whole vibe |++-----------------------------------------------------++| Auth Dispatch (lib/utils/auth_util.dart) | <-- the router+| decides: show PIN screen? password screen? |+| or just use the phone's biometrics? |++-----------------------------------------------------++| LockScreenSettings (lib/utils/lock_screen_settings | <-- the storage brain+| .dart) - secure storage + shared prefs |++-----------------------------------------------------++```++quick flutter 101 for the React folks:+- **StatefulWidget** = a component with its own `useState`-like internal state+- **Singleton** = basically a global instance, like a module-level export you import everywhere+- **SharedPreferences** = think `localStorage` but for mobile+- **FlutterSecureStorage** = like `localStorage` but encrypted (keychain on iOS, keystore on Android)+- **`build()` method** = literally the `render()` / return JSX of Flutter+- **`initState()`** = your `useEffect(() => {}, [])` -- runs once when the widget mounts+- **`dispose()`** = the cleanup function returned from `useEffect`+- **`setState()`** = yep, same concept as React's `setState`, triggers a re-render+- **`Navigator.push/pop`** = like `router.push()` / `router.back()` in Next.js+- **`context`** = kinda like React context but it's passed around everywhere in Flutter automatically++---++## 2. Server Involvement++**literally none.** the whole thing lives on the device. no fetch calls, no REST, no GraphQL, no nothing.++- PIN/password hashes, salt, and prefs? all on-device.+- locking and unlocking? local only.+- the **one** exception: if someone fails authentication **10 times in a row**, it calls `Configuration.instance.logout()` which does hit the server to kill the session. but that's a "you messed up too many times" security nuke, not part of the lock feature itself.++tldr: you don't need to touch any API routes for this. it's all local state management.++---++## 3. Lock Types & Mutual Exclusivity++there are three ways to lock the app. but here's the thing -- **you can only have ONE active at a time**. they're mutually exclusive. no mixing and matching. it's giving radio buttons, not checkboxes.++```dart+// lib/ui/settings/lock_screen/lock_screen_options.dart:24+enum LockType { device, pin, password }+```++| Lock Type | what it actually does | where it's stored |+|-----------|-----------|---------|+| `device` | uses your phone's own biometric/passcode (Face ID, fingerprint, device PIN) via the `local_auth` package | `SharedPreferences["should_show_lock_screen"] = true` |+| `pin` | custom in-app 4-digit PIN, hashed with Argon2id (fancy crypto stuff, more on that later) | `FlutterSecureStorage["ls_pin"]` (the hash) + `["ls_salt"]` |+| `password` | custom in-app password, also hashed with Argon2id | `FlutterSecureStorage["ls_password"]` (the hash) + `["ls_salt"]` |++**and when you set one, the other gets yeeted:**++```dart+// lock_screen_settings.dart:114 (inside setPin)+await _secureStorage.delete(key: password); // bye bye password++// lock_screen_settings.dart:142 (inside setPassword)+await _secureStorage.delete(key: pin); // bye bye PIN+```++so if a user switches from PIN to password, the old PIN hash is straight up deleted from secure storage. clean slate every time.++**the routing logic** (`auth_util.dart:21`) is basically a big if-else:+- got a PIN or password hash saved? -> show the custom in-app PIN/Password screen+- got nothing saved but lock is enabled? -> fall through to `LocalAuthentication().authenticate()` which pops up the OS biometric/passcode dialog (like when your banking app asks for Face ID)++---++## 4. Key Files & Classes++### Core Lock Mechanism (the important ones)++here's your file map. if you're used to a React project, think of these as your core hooks + providers + pages:++| File | Class/Function | what it does (fr fr) |+|------|----------------|------|+| `lib/ui/tools/app_lock.dart` | `AppLock` (StatefulWidget) | **the wrapper component.** imagine wrapping your entire `<App />` in a `<LockProvider>`. this thing listens for when the app goes to background/foreground (like `visibilitychange` event in web). starts a timer on background; shows lock screen when timer fires. also blocks the back button with `PopScope(canPop: false)` so users can't just swipe away the lock. |+| `lib/ui/tools/lock_screen.dart` | `LockScreen` (StatefulWidget) | **the lock screen page itself.** shows the lock icon, a circular progress indicator (for the cooldown timer), "Tap to Unlock" text, a countdown when you've failed too many times, and a logout button. handles the invalid attempt counting and the "ok you failed 10 times, you're logged out" logic. |+| `lib/utils/auth_util.dart` | `requestAuthentication()` | **the central dispatcher.** this is the function that decides which auth method to use. reads saved PIN/password from secure storage, then routes accordingly. also kills any stale biometric prompts before starting a new one (prevents ghost dialogs). think of it as your auth middleware. |+| `lib/services/local_authentication_service.dart` | `LocalAuthenticationService` | **service layer.** bridges the UI and auth logic. has three main methods: one for in-app sensitive actions (like "verify before showing recovery key"), one for the actual lock screen auth, and one for toggling system biometric on/off. singleton pattern (one global instance). |+| `lib/utils/lock_screen_settings.dart` | `LockScreenSettings` (Singleton) | **the data layer.** manages `FlutterSecureStorage` for the crypto stuff (hashed PIN, hashed password, salt) and `SharedPreferences` for everything else (attempt counters, auto-lock time, flags). also does the actual Argon2id hashing. this is where the real storage magic happens. |+| `lib/core/configuration.dart` | `Configuration` | **app-wide config.** has `shouldShowLockScreen()`, `shouldShowSystemLockScreen()`, and `setSystemLockScreen()`. the first one is the master check -- returns `true` if ANY lock method is enabled. |++### Settings UI Pages (the screens the user actually sees)++| File | Class | what the user sees |+|------|-------|------|+| `lib/ui/settings/lock_screen/lock_screen_options.dart` | `LockScreenOptions` | the main settings page. toggle app lock on/off, pick between Device/PIN/Password, set auto-lock time, toggle "hide content in app switcher". it's the settings dashboard. |+| `lib/ui/settings/lock_screen/lock_screen_pin.dart` | `LockScreenPin` | PIN entry screen. dual purpose -- used for both *setting* a new PIN and *verifying* an existing one. 4-digit input using the `Pinput` package (pretty nice looking tbh). |+| `lib/ui/settings/lock_screen/lock_screen_confirm_pin.dart` | `LockScreenConfirmPin` | "type your PIN again to confirm" screen. classic double-entry pattern. if it matches, hash it and store it. |+| `lib/ui/settings/lock_screen/lock_screen_password.dart` | `LockScreenPassword` | same thing but for passwords. uses a `TextInputWidget` instead of a PIN pad. has a "Next" FAB (floating action button -- those round buttons that float in the corner). |+| `lib/ui/settings/lock_screen/lock_screen_confirm_password.dart` | `LockScreenConfirmPassword` | password confirmation screen. "Confirm" FAB. match = hash and store, mismatch = haptic buzz + error. |+| `lib/ui/settings/lock_screen/lock_screen_auto_lock.dart` | `LockScreenAutoLock` | a picker screen for "how long after backgrounding should the lock kick in?" six options from instant to 30 min. |+| `lib/ui/settings/lock_screen/custom_pin_keypad.dart` | `CustomPinKeypad` | phone-style number pad (1-9, 0, backspace). looks like the dialer on your phone. only used on mobile -- desktop uses the regular keyboard. |++### Entry Points (where users get INTO the lock settings)++| File | Class | the vibe |+|------|-------|------|+| `lib/main.dart` | `main()` / `_runInForeground()` | the app's entry point. wraps the entire app in `AppLock`. decides `enabled` based on `shouldShowLockScreen() \|\| isOnGuestView()`. this is your `_app.tsx` equivalent. |+| `lib/ui/settings/security_section_widget.dart` | `SecuritySectionWidget` | older settings page entry. tapping "App Lock" first makes you authenticate (gotta prove you're you), THEN navigates to `LockScreenOptions`. |+| `lib/ui/settings/security/security_settings_page.dart` | `SecuritySettingsPage` | newer, redesigned version. same flow, better UI. |++---++## 5. Lifecycle & Flow++ok this is the juicy part. let's walk through what happens in different scenarios. if you understand component lifecycle in React, this will click.++### 5.1 Cold Start++this is what happens when you open the app from scratch (killed process, fresh launch):++```+main()+ -> _runInForeground()+ -> _init() (initializes LockScreenSettings, all the services, etc.)+ -> runApp(AppLock(+ builder: (args) => EnteApp(...), // the actual app+ lockScreen: const LockScreen(), // the lock screen widget+ enabled: await Configuration.instance.shouldShowLockScreen()+ || localSettings.isOnGuestView(),+ ...+ ))+```++think of `runApp(AppLock(...))` like `ReactDOM.render(<LockProvider><App /></LockProvider>)`. the lock screen wraps everything.++**`AppLock.initState()`** (`app_lock.dart:67-75`) -- the "component did mount":+- if `enabled = true`: sets `_didUnlockForAppLaunch = false` (meaning "user hasn't proven they're legit yet")+- `build()` renders `MaterialApp(home: _lockScreen)` -- so the lock screen is literally the FIRST thing you see. the actual app isn't even rendered yet.+- lock screen is wrapped in `PopScope(canPop: false)` which is Flutter's way of saying "you CANNOT go back from this screen". no escape.++**`LockScreen.initState()`** (`lock_screen.dart:43-58`) -- the lock screen mounts:+- reads the persisted `invalidAttemptCount` from storage (in case the user was mid-lockout and killed the app)+- after the first frame renders, calls `_showLockScreen()` which triggers the authentication flow++**on successful auth** (`lock_screen.dart:344-352`):+- calls `AppLock.of(context)!.didUnlock()` -- this is how the lock screen tells the wrapper "we're good, let them in"+- `didUnlock()` -> `_didUnlockOnAppLaunch()` -> `pushReplacementNamed('/unlocked')` -- this **replaces** the lock screen route with the actual app. key word: *replaces*. the lock screen isn't sitting behind the app on the navigation stack. it's gone gone. user literally cannot navigate back to it.++### 5.2 Background -> Foreground (Auto-Lock)++this is the "user switches to Instagram for 30 seconds then comes back" flow. Flutter has lifecycle states kinda like the Page Visibility API in browsers.++**when the app goes to background** (`app_lock.dart:83-89`):+```dart+if (state == AppLifecycleState.paused &&+ (!this._isLocked && this._didUnlockForAppLaunch)) {+ this._backgroundLockLatencyTimer = Timer(+ Duration(milliseconds: LockScreenSettings.instance.getAutoLockTime()),+ () => this.showLockScreen(),+ );+}+```++in React terms, this is like:+```js+// pseudocode equivalent+useEffect(() => {+ const handleVisibilityChange = () => {+ if (document.hidden && !isLocked && hasUnlockedOnce) {+ timerRef.current = setTimeout(() => showLockScreen(), autoLockTime);+ }+ if (!document.hidden) {+ clearTimeout(timerRef.current);+ }+ };+ document.addEventListener('visibilitychange', handleVisibilityChange);+ return () => document.removeEventListener('visibilitychange', handleVisibilityChange);+}, []);+```++- a `Timer` starts with the configured auto-lock delay (default 5 seconds)+- two guard conditions: (a) lock screen isn't already showing, (b) user has already done the initial unlock (prevents the timer from starting during the very first lock screen)++**when the app returns to foreground** (`app_lock.dart:91-93`):+```dart+if (state == AppLifecycleState.resumed) {+ this._backgroundLockLatencyTimer?.cancel();+}+```++- came back fast enough? timer cancelled. no lock. you're good.+- timer already fired? lock screen is already there waiting. authenticate to get back in.++**the auto-lock duration options** (`lock_screen_settings.dart:25-32`):+```dart+static const List<Duration> autoLockDurations = [+ Duration(milliseconds: 650), // "Immediately" (basically instant)+ Duration(seconds: 5), // default+ Duration(seconds: 15),+ Duration(minutes: 1),+ Duration(minutes: 5),+ Duration(minutes: 30),+];+```++**on successful unlock after background** (`app_lock.dart:206-209`):+- `didUnlock()` -> `_didUnlockOnAppPaused()` -> `pop()`. this time it's a `pop()` (not `pushReplacement`) because the main app is still on the navigation stack underneath. just removes the lock screen overlay. like closing a modal.++### 5.3 Unlock Flow++here's the full step-by-step of what happens when someone taps "Tap to unlock":++```+User taps "Tap to unlock" on LockScreen+ |+ v+_showLockScreen() [lock_screen.dart:321]+ |+ +-- Check cooldown: if lastInvalidAttemptTime > now+ | -> start countdown timer, skip auth entirely (you're in timeout bestie)+ |+ v+requestAuthentication() [auth_util.dart:10]+ |+ +-- LocalAuthentication().stopAuthentication() <-- kill any zombie biometric dialogs+ |+ +-- Read savedPin & savedPassword from FlutterSecureStorage+ |+ +-- IF savedPassword OR savedPin exists:+ | +-- LocalAuthenticationService.requestEnteAuthForLockScreen()+ | +-- IF savedPassword != null -> Navigate to LockScreenPassword+ | | +-- User types password -> hash with Argon2id -> compare with stored hash+ | +-- IF savedPin != null -> Navigate to LockScreenPin+ | +-- User types 4-digit PIN -> hash with Argon2id -> compare with stored hash+ |+ +-- ELSE (device lock, no custom PIN/password):+ +-- LocalAuthentication().authenticate() <-- OS biometric/passcode dialog+ (Face ID, fingerprint, device PIN -- whatever the phone supports)+```++**on success** (`lock_screen.dart:344-352`):+- records `lastAuthenticatingTime` (used for a 5-second debounce to prevent the lock from re-triggering during the unlock animation -- smart edge case handling)+- calls `AppLock.of(context)!.didUnlock()` -- we're in+- resets `invalidAttemptCount` to 0 -- clean slate++**on failure** (`lock_screen.dart:353-374`):+- see [Brute-Force Protection](#8-brute-force-protection) below. it gets spicy.++---++## 6. Cryptography & Hashing++alright this part is important. PINs and passwords are **never stored in plaintext**. they're hashed using **Argon2id v1.3** via libsodium's `crypto_pwhash`. if you've used bcrypt or scrypt in Node.js, Argon2id is the newer, fancier version that won a password hashing competition. it's the gold standard.++### Setting a PIN/Password++here's what happens when a user sets their PIN or password:++```+User enters PIN/password (String)+ -> utf8.encode(input) -> Uint8List (byte array, like a Buffer in Node)+ -> Generate 16-byte random salt via Sodium.randombytesBuf(Sodium.cryptoPwhashSaltbytes)+ -> Argon2id v1.3:+ output length = 32 bytes (Sodium.cryptoSecretboxKeybytes)+ opsLimit = Interactive (Sodium.cryptoPwhashOpslimitInteractive)+ memLimit = Interactive (Sodium.cryptoPwhashMemlimitInteractive)+ -> base64Encode(salt) -> FlutterSecureStorage["ls_salt"]+ -> base64Encode(hash) -> FlutterSecureStorage["ls_pin" or "ls_password"]+ -> Delete the opposite key (PIN <-> password are mutually exclusive)+```++for the web devs: this is similar to doing `await argon2.hash(password, { salt, type: argon2id })` and storing the result. except here it's using libsodium's C bindings through Flutter.++**actual code** (`lock_screen_settings.dart:98-117`):+```dart+Future<void> setPin(String userPin) async {+ await _secureStorage.delete(key: saltKey);+ final salt = _generateSalt(); // 16 random bytes+ final hash = cryptoPwHash({+ "password": utf8.encode(userPin),+ "salt": salt,+ "opsLimit": Sodium.cryptoPwhashOpslimitInteractive,+ "memLimit": Sodium.cryptoPwhashMemlimitInteractive,+ });+ await _secureStorage.write(key: saltKey, value: base64Encode(salt));+ await _secureStorage.write(key: pin, value: base64Encode(hash));+ await _secureStorage.delete(key: password); // mutual exclusivity+}+```++### Verifying a PIN/Password++when the user tries to unlock, this happens:++```+Retrieve stored salt from FlutterSecureStorage["ls_salt"]+ -> base64Decode -> Uint8List (16 bytes)+User enters PIN/password+ -> utf8.encode(input)+ -> Argon2id v1.3 (exact same parameters as when it was set)+ -> base64Encode(new_hash) == stored_hash ?+ +-- MATCH: reset invalid count, let them in+ +-- NO MATCH: phone vibrates, increment attempts, maybe start cooldown+```++it's the classic "hash the input, compare the hashes" pattern. same thing you'd do with bcrypt in a Node backend, except it's all happening locally on the device.++**actual code** (`lock_screen_pin.dart:63-72`):+```dart+final Uint8List? salt = await _lockscreenSetting.getSalt();+final hash = cryptoPwHash({+ "password": utf8.encode(code),+ "salt": salt,+ "opsLimit": Sodium.cryptoPwhashOpslimitInteractive,+ "memLimit": Sodium.cryptoPwhashMemlimitInteractive,+});+if (widget.authPin == base64Encode(hash)) { ... } // hash comparison+```++### The `cryptoPwHash` Function++this is the actual wrapper around libsodium. lives in the internal `ente_crypto` plugin.++**location:** `plugins/ente_crypto/lib/src/crypto.dart:36-45`++```dart+Uint8List cryptoPwHash(Map<String, dynamic> args) {+ return Sodium.cryptoPwhash(+ Sodium.cryptoSecretboxKeybytes, // 32 bytes output+ args["password"], // UTF-8 encoded input+ args["salt"], // 16-byte random salt+ args["opsLimit"],+ args["memLimit"],+ Sodium.cryptoPwhashAlgArgon2id13, // Argon2id v1.3 algorithm+ );+}+```++---++## 7. On-Device Storage++two storage systems. think of it as having both a vault and a regular cabinet:++### FlutterSecureStorage (the vault -- encrypted, sensitive stuff)++this is the encrypted keychain/keystore. on iOS it's the actual Keychain, on Android it's the EncryptedSharedPreferences backed by the Keystore. your PIN hash, password hash, and salt live here because if someone gets access to the device filesystem, they shouldn't be able to read these.++| Key | Type | what's in there |+|-----|------|-------------|+| `"ls_pin"` | String | base64-encoded Argon2id hash of the user's PIN |+| `"ls_password"` | String | base64-encoded Argon2id hash of the user's password |+| `"ls_salt"` | String | base64-encoded 16-byte random salt (regenerated every time a new PIN/password is set) |++### SharedPreferences (the cabinet -- non-sensitive settings)++this is just key-value storage. like `localStorage` on the web. not encrypted, but it doesn't need to be -- none of this data is sensitive enough to require encryption.++| Key | Type | Default | what it's for |+|-----|------|---------|-------------|+| `"ls_invalid_attempts"` | int | 0 | how many times in a row the user failed to authenticate |+| `"ls_last_invalid_attempt_time"` | int | 0 | **this name is a lie.** it's actually the *lockout EXPIRY timestamp* (epoch ms). the time when the lockout ENDS, not when the last attempt happened. classic misleading variable name moment. |+| `"ls_hide_app_content"` | bool | false | whether to blur/hide app content in the app switcher (task manager) |+| `"ls_auto_lock_time"` | int | 5000 | auto-lock delay in milliseconds (how long after backgrounding before lock kicks in) |+| `"should_show_lock_screen"` | bool | false | whether the device/system lock is enabled (stored by `Configuration`, not `LockScreenSettings`) |++---++## 8. Brute-Force Protection++this is where the security gets real. you can't just guess PINs forever. the app fights back with **exponential backoff** -- each failure makes you wait longer, and eventually it just logs you out entirely.++### Invalid Attempt Escalation++cooldown kicks in **after the 4th failed attempt** (i.e., on your 5th L):++| attempt # | the math | how long you're locked out |+|-----------|---------|----------|+| 1-4 | -- | nothing, try again |+| 5 | 2^(5-5) x 30 = 30 | **30 seconds** |+| 6 | 2^(6-5) x 30 = 60 | **1 minute** |+| 7 | 2^(7-5) x 30 = 120 | **2 minutes** |+| 8 | 2^(8-5) x 30 = 240 | **4 minutes** |+| 9 | 2^(9-5) x 30 = 480 | **8 minutes** |+| 10+ | -- | **auto-logout. session nuked. start over.** |++the formula is `2^(attemptCount - 5) * 30` seconds. exponential growth go brrr.++### the code (`lock_screen.dart:353-374`)++```dart+// on failure:+if (invalidAttemptCount > 9) {+ _autoLogoutOnMaxInvalidAttempts(); // calls Configuration.instance.logout()+ return; // game over+}+lockedTimeInSeconds = pow(2, invalidAttemptCount - 5).toInt() * 30;+await _lockscreenSetting.setLastInvalidAttemptTime(+ DateTime.now().millisecondsSinceEpoch + lockedTimeInSeconds * 1000,+);+await startLockTimer(lockedTimeInSeconds);+```++### Cooldown Persistence++the lockout expiry timestamp gets saved to `SharedPreferences["ls_last_invalid_attempt_time"]`. this is clutch because it means:+- **cooldowns survive app kills.** you can't just force-quit and reopen to bypass the timer. it checks the stored timestamp on relaunch.+- on resume or relaunch, the remaining lockout time is recalculated from `storedExpiry - Date.now()`.++### Timer UI++while you're in the penalty box, the lock screen shows:+- a circular progress indicator that fills up as the cooldown elapses (looks clean ngl)+- a crossfade animation: "Too many incorrect attempts" text fades out, replaced by a countdown timer like "4m 30s"+- tapping during cooldown does **nothing** -- `result` is set to `false` directly without even attempting auth. you just gotta wait.++---++## 9. Settings UI & Configuration++### Lock Screen Options (`lock_screen_options.dart`)++the settings page has four sections. here's the layout:++#### 1. App Lock Toggle (always visible)+- big on/off switch at the top. the master control.+- **flipping ON:** enables device lock by default, calls `AppLock.of(context)!.setEnabled(true)` (tells the lifecycle wrapper to start watching)+- **flipping OFF:** deletes stored PIN/password from secure storage, disables system lock screen, calls `AppLock.of(context)!.setEnabled(false)`. full cleanup.++#### 2. Lock Type Selection (only shows when app lock is ON)+three options, radio-button style with a checkmark on the active one:+- **Device Lock:** yeets any saved PIN/password, turns on system lock screen. uses whatever your phone has (Face ID, fingerprint, device PIN).+- **PIN Lock:** navigates to `LockScreenPin` -> `LockScreenConfirmPin`. on success, turns OFF system lock screen (because your custom PIN is now the boss).+- **Password Lock:** navigates to `LockScreenPassword` -> `LockScreenConfirmPassword`. same deal, turns off system lock.++#### 3. Auto Lock (only shows when app lock is ON)+- shows the current auto-lock time with a chevron. tap to go to the duration picker.+- options: Immediately (650ms), 5s, 15s, 1m, 5m, 30m++#### 4. Hide Content in App Switcher (ALWAYS visible, independent of app lock)+- toggle switch. when ON, the app switcher (recent apps screen) won't show the app's actual content -- it'll be blurred or blanked out.+- uses the `privacy_screen` package under the hood+- **Android:** sets `FLAG_SECURE` window flag (same thing banking apps use)+- **iOS:** applies a blur effect triggered on `didEnterBackground`++### PIN Setup Flow++```+LockScreenOptions -> [Tap "PIN Lock"]+ -> LockScreenPin (set mode)+ -> User enters 4-digit PIN on the custom keypad+ -> LockScreenConfirmPin+ -> User re-enters same PIN+ -> IF match: hash with Argon2id, store in FlutterSecureStorage, pop x2 back to Options+ -> IF mismatch: phone vibrates, input clears, try again+```++### Password Setup Flow++```+LockScreenOptions -> [Tap "Password Lock"]+ -> LockScreenPassword (set mode)+ -> User types password, taps the "Next" floating button+ -> LockScreenConfirmPassword+ -> User re-types password, taps "Confirm" floating button+ -> IF match: hash with Argon2id, store in FlutterSecureStorage, pop x2 back to Options+ -> IF mismatch: phone vibrates, error shown, try again+```++### Accessing Settings (how users even GET to this page)++both `SecuritySectionWidget` (old) and `SecuritySettingsPage` (new) make you **authenticate BEFORE you can touch lock settings**. smart -- can't have someone changing your lock settings if they're not you.++1. check `LocalAuthentication().isDeviceSupported()` -- does this device even have biometrics/passcode?+2. if yes: call `requestAuthentication()` -> on success, navigate to `LockScreenOptions`+3. if no: show an error dialog telling the user to set up a device passcode first++---++## 10. External Packages++### the dependency lineup (directly used for app lock)++| Package | Version | what it does | where it's used |+|---------|---------|---------|---------|+| **`local_auth`** | `^2.1.5` | talks to the OS biometric system -- Face ID, fingerprint, device PIN. like the Web Authentication API but for mobile. | `auth_util.dart`, `local_authentication_service.dart` |+| **`local_auth_android`** | (comes with local_auth) | android-specific localized strings for the biometric dialog ("Touch the fingerprint sensor", etc.) | `auth_util.dart:33-51` |+| **`local_auth_ios`** | (comes with local_auth) | iOS-specific strings for Face ID / Touch ID prompts | `auth_util.dart:52-59` |+| **`flutter_secure_storage`** | `9.0.0` (PINNED - do not upgrade) | encrypted key-value store. iOS Keychain, Android EncryptedSharedPreferences. where the PIN/password hashes live. | `lock_screen_settings.dart` |+| **`flutter_sodium`** | git fork | dart bindings for libsodium (the crypto library). provides Argon2id hashing + random byte generation. | `lock_screen_settings.dart` |+| **`ente_crypto`** | internal plugin | thin wrapper around flutter_sodium. exports the `cryptoPwHash()` function that does the actual hashing. | `lock_screen_settings.dart`, `lock_screen_pin.dart`, `lock_screen_password.dart` |+| **`pinput`** | `^5.0.0` | slick 4-digit PIN input widget. supports custom theming, error states, obscured text. think of it as a fancy `<input type="password" maxlength="4">` but way prettier. | `lock_screen_pin.dart`, `lock_screen_confirm_pin.dart` |+| **`privacy_screen`** | git fork (`v2-only`) | hides app content in the app switcher / recent apps. prevents screenshots of the app content. | `lock_screen_settings.dart` |+| **`shared_preferences`** | `^2.0.5` | persistent key-value storage for non-sensitive stuff. literally `localStorage` for Flutter. | `lock_screen_settings.dart`, `configuration.dart` |+| **`flutter_animate`** | `^4.1.0` | animation library. used for the smooth crossfade between "Too many attempts" and the countdown timer on the lock screen. | `lock_screen.dart` |++### heads up about `flutter_secure_storage`++it's pinned at **exactly 9.0.0** on purpose. version 9.2.4 has a bug where iOS keychain items survive app reinstallation ([issue #870](https://github.com/juliansteenbakker/flutter_secure_storage/issues/870)). meaning if a user uninstalls and reinstalls the app, their old lock screen PIN hash would still be there in the keychain, but the app wouldn't know about it. bad vibes. so we stay on 9.0.0.++---++## 11. Shared `lock_screen` Package (Newer Refactor)++there's a **newer, refactored version** of all this code at `mobile/packages/lock_screen/`. it's designed to be shared across all Ente apps (Photos, Auth, Locker) instead of being photos-specific. same architecture, but decoupled and abstracted.++### how it's different from the photos app version++| what changed | Photos App (the OG) | Shared Package (the glow-up) |+|--------|-----------------|---------------------|+| crypto backend | `flutter_sodium` (FFI, C bindings) | `ente_crypto_api` (abstract interface -- plug in any backend) |+| Argon2 opsLimit | `Interactive` (faster) | **`Sensitive`** (slower, more secure, ~2x CPU time) |+| i18n / localization | `AppLocalizations.of(context)` (standard Flutter) | `context.strings` (custom `ente_strings` extension -- shared across apps) |+| configuration | `Configuration.instance` (photos-specific singleton) | `BaseConfiguration` (abstract class, injected -- any app can provide its own) |+| where lock state lives | split between `Configuration` + `LockScreenSettings` (messy) | **all in `LockScreenSettings`** (clean, single source of truth) |+| Linux support | nope | yes, via `flutter_local_authentication` + platform checks |+| desktop support | nope | yes -- `PlatformDetector.isDesktop()` guards, uses native keyboard instead of custom keypad, has `PlatformUtil.refocusWindows()` |+| manual lock | not a thing | `showManualLockScreen()` + `_suppressAutoPrompt` flag (user can manually lock the app) |+| default "hide content" | `false` | **`true`** (more privacy-first by default) |+| sign-out cleanup | manual (you gotta remember to clear stuff) | automatic via `Bus.instance.on<SignedOutEvent>()` (event-driven, just works) |+| fresh install cleanup | none | `_clearLsDataInKeychainIfFreshInstall()` for iOS/macOS (handles that keychain persistence issue) |+| migration logic | none | `runLockScreenChangesMigration()` (handles upgrading from old settings format) |+| debug mode shortcut | none | 60-second auth cooldown skip in debug mode (quality of life for devs) |++### the abstraction layer (how different apps plug in)++the shared package uses dependency injection so any Ente app can use it:++1. **`BaseConfiguration` injection** -- your app subclasses `BaseConfiguration` and passes it to `LockScreenSettings.init()` and `LockScreen()`. provides `isLoggedIn()` and `logout()`.+2. **`ente_crypto_api`** -- abstract crypto interface. register your `CryptoApi` implementation (flutter_sodium adapter, Rust adapter, WebCrypto adapter, whatever).+3. **`ente_strings`** -- shared localization. all text uses `context.strings.xxx` instead of app-specific localizations.+4. **`ente_ui`** -- shared component library (MenuItemWidget, ToggleSwitchWidget, DynamicFAB, TextInputWidget, etc.). like your design system package.+5. **`AppLock` builder pattern** -- wrap your app: `AppLock(builder: ..., lockScreen: ..., ...)`. clean composition.++### the deps++| Package | Version | why |+|---------|---------|---------|+| `ente_accounts` | path | `UserService` for logout |+| `ente_configuration` | path | `BaseConfiguration` interface |+| `ente_crypto_api` | path | `CryptoUtil` for hashing |+| `ente_events` | path | `Bus` + `SignedOutEvent` (event bus pattern) |+| `ente_pure_utils` | path | `PlatformDetector` (isMobile/isDesktop checks) |+| `ente_strings` | path | shared localization strings |+| `ente_ui` | path | shared UI components (the design system) |+| `ente_utils` | path | `PlatformUtil.refocusWindows()` |+| `flutter_local_authentication` | git ref `1ac346a` | Linux biometric auth |+| `flutter_secure_storage` | `9.0.0` (pinned) | encrypted storage |+| `local_auth` | `^2.3.0` | iOS/Android biometric |+| `pinput` | `^5.0.0` | PIN input widget |+| `privacy_screen` | `^0.0.8` | app switcher privacy |+| `shared_preferences` | `^2.5.3` | settings persistence |++> **important:** the photos app does **NOT** use the shared package yet. it still runs its own implementation in `lib/`. the shared package exists but hasn't been wired in.++---++## 12. Desktop Considerations++ok so you're building this for desktop. here's the real talk on what works out of the box and what needs work:++### what you can basically copy-paste (conceptually)+- the `AppLock` lifecycle wrapper pattern (though "background" means something different on desktop vs mobile -- more on that below)+- the `LockScreenSettings` storage layer (`FlutterSecureStorage` + `SharedPreferences` both work on desktop)+- Argon2id hashing via `ente_crypto_api` (already abstracted, doesn't care about platform)+- PIN/password entry and verification flow (same logic, different UI)+- brute-force protection (cooldown timers, auto-logout -- all platform-agnostic logic)++### what needs actual work+- **biometrics:** `local_auth` works on macOS (Touch ID) but not Linux/Windows. the shared package adds Linux support via `flutter_local_authentication`. Windows is... complicated. might need to skip biometrics on Windows or find a Windows Hello package.+- **privacy screen / hide content:** `PrivacyScreen` is mobile-only. the shared package already skips it on desktop via `PlatformDetector.isDesktop()`. for desktop you'd need native window management to hide content (minimize to tray? blur window on focus loss?). different beast.+- **auto-lock trigger:** on mobile it's `AppLifecycleState.paused` (app goes to background). on desktop, apps don't really "go to background" the same way. you'll want to listen for **window focus/blur events**, **screen lock/unlock**, or maybe an **idle timeout** (no mouse/keyboard activity for X minutes). totally different paradigm.+- **custom PIN keypad:** not needed on desktop. users have a real keyboard. the shared package already handles this -- it checks `isPlatformDesktop` and skips the `CustomPinKeypad`, using native keyboard input instead.+- **window refocus:** the shared package already has `PlatformUtil.refocusWindows()` for desktop. this is called after auth dialogs to bring the window back to focus (because system auth dialogs can steal focus on desktop).+- **macOS keychain weirdness:** macOS Keychain items can persist after app deletion (same issue as iOS). the shared package has `_clearLsDataInKeychainIfFreshInstall()` to handle this.++### the recommendation++use the **shared `lock_screen` package** (`mobile/packages/lock_screen/`) as your starting point, not the photos-app-specific code. it already has:+- desktop platform detection and guards+- abstract crypto API (no direct flutter_sodium dependency to wrestle with)+- consolidated settings (no confusing split between `Configuration` and `LockScreenSettings`)+- Linux biometric support scaffolding+- manual lock support (`showManualLockScreen()`)+- native keyboard support on desktop++you'll still need to adapt the lifecycle stuff (auto-lock triggers) and potentially the biometric layer for your target platforms, but the core logic -- storage, hashing, attempt counting, cooldowns -- is all ready to go. just wire it up.++good luck king, you got this.diff --git a/web/apps/photos/docs/APP_LOCK_ARCHITECTURE.md b/web/apps/photos/docs/APP_LOCK_ARCHITECTURE.mdnew file mode 100644index 0000000000..bba08bed55--- /dev/null+++ b/web/apps/photos/docs/APP_LOCK_ARCHITECTURE.md@@ -0,0 +1,737 @@+# App Lock Architecture - Ente Photos (Web/Desktop)++> Architecture document for implementing the app lock feature in `web/apps/photos/`, ported from the Flutter mobile implementation. Covers browser and Electron desktop targets.++---++## Table of Contents++1. [Executive Summary](#1-executive-summary)+2. [Platform Feasibility](#2-platform-feasibility)+3. [Component Hierarchy](#3-component-hierarchy)+4. [State Management](#4-state-management)+5. [Storage Strategy](#5-storage-strategy)+6. [Cryptography](#6-cryptography)+7. [Lock Trigger Mechanism](#7-lock-trigger-mechanism)+8. [Lock Screen UI](#8-lock-screen-ui)+9. [Settings UI](#9-settings-ui)+10. [Data Flow Diagrams](#10-data-flow-diagrams)+11. [Multi-Tab Synchronization](#11-multi-tab-synchronization)+12. [Brute-Force Protection](#12-brute-force-protection)+13. [Integration Points](#13-integration-points)+14. [Security Model](#14-security-model)+15. [Accessibility](#15-accessibility)+16. [New & Modified Files](#16-new--modified-files)+17. [MVP Implementation Order](#17-mvp-implementation-order)+18. [Deferred Features](#18-deferred-features)++---++## 1. Executive Summary++The app lock is a **purely client-side** feature that prevents unauthorized access to the app after it has been authenticated. It supports two lock types (PIN and password), is independent of the user's master key, and reuses the existing Argon2id crypto infrastructure already in the codebase.++- **Browser:** Lock is a UX convenience feature (prevents casual shoulder-surfing). A determined user with DevTools access can bypass it. This is an acceptable trade-off.+- **Electron desktop:** Lock provides meaningful security. Production builds don't expose DevTools, and credentials can be stored in OS-level secure storage (Keychain/DPAPI/libsecret).++---++## 2. Platform Feasibility++### Feature Matrix++| Feature | Chrome/Firefox/Safari | Electron macOS | Electron Windows | Electron Linux |+|---------|----------------------|----------------|------------------|----------------|+| PIN/Password lock | YES | YES | YES | YES |+| Argon2id hashing | YES (WASM) | YES (WASM) | YES (WASM) | YES (WASM) |+| Biometric unlock | NO | YES (Touch ID) | YES (Windows Hello) | NO |+| Auto-lock on tab/window switch | PARTIAL (visibilitychange) | YES (window blur + focus) | YES (window blur + focus) | YES (window blur + focus) |+| Auto-lock on system idle | NO | YES (powerMonitor) | YES (powerMonitor) | YES (powerMonitor) |+| Auto-lock on screen lock | NO | YES (powerMonitor) | YES (powerMonitor) | YES (powerMonitor) |+| Secure PIN storage | NO (IndexedDB only) | YES (Keychain) | YES (DPAPI) | PARTIAL (libsecret) |+| Tamper-resistant lock state | NO | YES (main process) | YES (main process) | YES (main process) |++### Existing Infrastructure++The codebase already provides the key building blocks:++| Need | Existing Solution | Location |+|------|-------------------|----------|+| Argon2id hashing | `deriveInteractiveKey` via libsodium WASM | `web/packages/base/crypto/libsodium.ts:848-857` |+| Web Worker crypto | Comlink-based worker delegation | `web/packages/base/crypto/worker.ts` |+| Visibility detection | Page Visibility API | Already used in `useJoinAlbum.ts:80` |+| Window focus events | `electron.onMainWindowFocus` IPC | `web/packages/base/types/ipc.ts:104-113` |+| Electron safe storage | `safeStorage.encryptString/decryptString` | `desktop/src/main/services/store.ts:27-38` |+| KV storage (IndexedDB) | `getKV/setKV/getKVS` | `web/packages/base/kv.ts` |+| Re-auth pattern | `AuthenticateUser` component | `web/packages/new/photos/components/AuthenticateUser.tsx` |+| Settings drawer pattern | `TitledNestedSidebarDrawer` | Used by `TwoFactorSettings`, `MLSettings`, etc. |++### Mobile vs Web Threat Model++| Aspect | Mobile (Flutter) | Browser | Electron Desktop |+|--------|-----------------|---------|-------------------|+| App sandbox | YES (OS-enforced) | NO | PARTIAL (process-level) |+| Secure storage | FlutterSecureStorage (Keychain/Keystore) | None | safeStorage (Keychain/DPAPI/libsecret) |+| DevTools access | NO (release builds) | YES (always) | NO (production) |+| Biometric auth | Native APIs | WebAuthn only (needs server) | Touch ID / Windows Hello |+| Background detection | App lifecycle events | Page Visibility only | Window focus + powerMonitor |+| Lock state tamper | Very difficult | Trivial via DevTools | Difficult (main process) |++---++## 3. Component Hierarchy++The lock overlay renders as a **sibling** alongside the page `Component` in `_app.tsx`, not as a wrapper. This avoids unnecessary re-renders of the entire component tree.++```+ThemeProvider+ CustomHead, CssBaseline, LoadingBar+ BaseContext+ PhotosAppContext+ Component (pages/*) <-- existing+ AppLockOverlay <-- NEW (conditional, sibling)+```++**Why an overlay, not route-based?** The app uses Next.js file-based routing. A route-based lock (`/lock`) would require guarding every page with redirects and would break browser history. A fixed-position overlay covers everything without modifying the route stack -- the same pattern the mobile app uses with its `AppLock` widget.++**Why not a React portal?** The existing `TranslucentLoadingOverlay` in `_app.tsx` renders directly as a sibling and works fine. No portal needed.++**Insertion point in `_app.tsx` (~line 192):**++```tsx+<ThemeProvider theme={photosTheme}>+ ...+ <BaseContext value={baseContext}>+ <PhotosAppContext value={appContext}>+ {!isI18nReady ? (+ <LoadingIndicator />+ ) : (+ <>+ {isChangingRoute && <TranslucentLoadingOverlay />}+ <Component {...pageProps} />+ <AppLockOverlay /> {/* NEW */}+ </>+ )}+ </PhotosAppContext>+ </BaseContext>+</ThemeProvider>+```++**Cold-start flash prevention:** The lock enabled check reads from `localStorage` (synchronous), so the overlay renders immediately on mount without a flash of unlocked content. The async IndexedDB read (for hash/salt) only happens when the user submits their PIN/password.++---++## 4. State Management++Follows the existing `useSyncExternalStore` / snapshot pattern used by `settings.ts` (`web/packages/new/photos/services/settings.ts:232-252`). This avoids React context re-render issues.++### State Shape++```typescript+export interface AppLockState {+ /** Whether app lock is enabled */+ enabled: boolean;+ /** Active lock type: "pin" | "password" | "none" */+ 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;+}+```++### Access Pattern++```typescript+// Module-level state (in app-lock.ts)+let _state: AppLockState = { ... };+const _listeners = new Set<() => void>();++export const appLockSubscribe = (listener: () => void) => { ... };+export const appLockSnapshot = () => _state;++// React hook (in use-snapshot.ts or app-lock.ts)+export const useAppLockSnapshot = () =>+ useSyncExternalStore(appLockSubscribe, appLockSnapshot);+```++### Imperative API++```typescript+export function lock(): void;+export function attemptUnlock(input: string): Promise<boolean>;+export function setAppLockEnabled(enabled: boolean): void;+export function setLockType(type: "pin" | "password"): void;+export function setAutoLockTime(ms: number): void;+export function setHideContentOnBlur(enabled: boolean): void;+export function setupPin(pin: string): Promise<void>;+export function setupPassword(password: string): Promise<void>;+export function logoutAppLock(): void;+```++---++## 5. Storage Strategy++Three categories, each using the appropriate existing storage mechanism:++| Data | Storage | Why | Key |+|------|---------|-----|-----|+| Hashed PIN/password (base64) | IndexedDB via `setKV`/`getKV` | Async, survives refresh, matches auth token pattern | `"appLock.hash"` |+| Salt (base64) | IndexedDB via `setKV`/`getKV` | Must pair with hash | `"appLock.salt"` |+| Lock type | `localStorage` | Synchronous read needed on cold start | `"appLock.lockType"` |+| Enabled flag | `localStorage` | Synchronous read needed on cold start | `"appLock.enabled"` |+| Auto-lock time (ms) | `localStorage` | Non-sensitive preference | `"appLock.autoLockTimeMs"` |+| Hide content on blur | `localStorage` | Non-sensitive preference | `"appLock.hideContentOnBlur"` |+| Invalid attempt count | IndexedDB via `setKV` | Harder to tamper than localStorage | `"appLock.invalidAttempts"` |+| Cooldown expiry timestamp | IndexedDB via `setKV` | Harder to tamper than localStorage | `"appLock.cooldownExpiresAt"` |++### Electron Enhancement (Post-MVP)++On desktop, the hash and salt should additionally be stored in OS safe storage via a new IPC method, following the existing `saveMasterKeyInSafeStorage` pattern in `desktop/src/main/services/store.ts`. This prevents bypass by clearing IndexedDB.++### Logout Cleanup++Add `logoutAppLock()` call to `photosLogout()` in `web/apps/photos/src/services/logout.ts`. This clears all app lock keys from both localStorage and KV DB, following the existing pattern of `logoutSettings()`, `logoutUserDetails()`, etc.++---++## 6. Cryptography++Reuse the existing libsodium infrastructure. No new crypto dependencies needed.++### Setting a PIN/Password++```typescript+import { generateDeriveKeySalt } from "ente-base/crypto";+import { deriveInteractiveKey } from "ente-base/crypto/libsodium";++async function setupPin(pin: string): Promise<void> {+ const salt = await generateDeriveKeySalt(); // 16-byte random salt+ // Argon2id with INTERACTIVE limits: opsLimit=2, memLimit=64MB+ // Runs in Web Worker via comlink -- zero UI jank, ~200ms+ const derivedKey = await deriveInteractiveKey(pin, salt);+ await setKV("appLock.salt", salt);+ await setKV("appLock.hash", derivedKey.key);+ localStorage.setItem("appLock.lockType", "pin");+ localStorage.setItem("appLock.enabled", "true");+}+```++### Verifying a PIN/Password++```typescript+async function verifyInput(input: string): Promise<boolean> {+ const salt = await getKVS("appLock.salt");+ const storedHash = await getKVS("appLock.hash");+ if (!salt || !storedHash) return false;+ const derivedKey = await deriveInteractiveKey(input, salt);+ return derivedKey.key === storedHash;+}+```++### Why INTERACTIVE Limits?++Same rationale as the mobile app: lock screen auth is interactive and must be responsive. `OPSLIMIT_INTERACTIVE` / `MEMLIMIT_INTERACTIVE` (64MB) completes in ~100-500ms. The mobile app uses these same parameters.++### Why Independent from Master Key?++The app lock is a local-only feature. Using a separate Argon2id hash keeps security domains cleanly separated. A compromised app lock PIN should not expose the user's master key.++---++## 7. Lock Trigger Mechanism++### Browser (Tab-Based)++```typescript+// In _app.tsx useEffect:+const handleVisibilityChange = () => {+ if (document.hidden && !isLocked && hasUnlockedOnce) {+ autoLockTimerRef.current = window.setTimeout(() => {+ lock();+ }, autoLockTimeMs);+ }+ if (!document.hidden) {+ if (autoLockTimerRef.current) {+ clearTimeout(autoLockTimerRef.current);+ autoLockTimerRef.current = null;+ }+ }+};+document.addEventListener("visibilitychange", handleVisibilityChange);+```++### Electron (Desktop)++Uses the existing `electron.onMainWindowFocus` callback. Requires adding a new `onMainWindowBlur` IPC method:++```typescript+if (electron) {+ electron.onMainWindowBlur(() => {+ // Filter: don't trigger if focus moved to another Electron window+ autoLockTimerRef.current = window.setTimeout(lock, autoLockTimeMs);+ });+ electron.onMainWindowFocus(() => {+ if (autoLockTimerRef.current) {+ clearTimeout(autoLockTimerRef.current);+ }+ });+}+```++**Important:** The blur listener must check if focus moved to another Electron window in the same process (e.g., image viewer, export dialog). If so, the lock timer should NOT trigger.++### Auto-Lock Durations (Matching Mobile)++```typescript+export const autoLockDurations = [+ { label: "immediately", ms: 0 },+ { label: "5_seconds", ms: 5000 },+ { label: "15_seconds", ms: 15000 },+ { label: "1_minute", ms: 60000 },+ { label: "5_minutes", ms: 300000 },+ { label: "30_minutes", ms: 1800000 },+];+```++---++## 8. Lock Screen UI++### Layout++Full-viewport fixed-position overlay. Uses MUI z-index convention: `calc(var(--mui-zIndex-tooltip) + 1)`.++```++----------------------------------------------------++| |+| [Ente Logo, small] |+| |+| [Lock Icon, large] |+| |+| +------------------------------------------+ |+| | PIN: 4 individual TextField inputs | |+| | OR | |+| | Password: TextField with show/hide | |+| +------------------------------------------+ |+| |+| [Error message / cooldown timer] |+| |+| [Unlock button] |+| |+| [Logout link, small, at bottom] |+| |++----------------------------------------------------++```++### Key Design Decisions++1. **Full viewport overlay:** `position: fixed; inset: 0;` with `zIndex: calc(var(--mui-zIndex-tooltip) + 1)`. Above all MUI dialogs.++2. **Reuses existing MUI components:**+ - `TextField` for password input (same as `VerifyMasterPasswordForm`)+ - `FocusVisibleButton` for the unlock button+ - `ShowHidePasswordInputAdornment` for password visibility toggle+ - PIN input: 4 individual `TextField` components with `maxLength: 1`, auto-advancing focus on input++3. **Cooldown timer:** Shows "Too many attempts. Try again in Xm Ys" with a `setInterval` countdown.++4. **Privacy screen:** When `hideContentOnBlur` is enabled and `document.hidden` is true, apply `filter: blur(30px)` on the main content container. Prevents content from appearing in tab previews and Alt+Tab thumbnails.++5. **No dismiss:** Cannot be closed except through authentication or logout. No Escape key handling. No click-outside dismiss.++6. **Logout link:** Calls the existing `logout()` from `BaseContext`. Shows a confirmation dialog before proceeding (matching the existing `handleLogout` pattern in `Sidebar.tsx:266-278`).++---++## 9. Settings UI++Located in the **Account section** of the Sidebar, alongside "Recovery Key", "Two Factor", "Change Password". This is where security-related settings live.++### Sidebar Entry Point++Add to `Sidebar.tsx` Account section:++```tsx+<RowButtonGroup>+ <RowButton+ label={t("app_lock")}+ endIcon={<ChevronRightIcon />}+ onClick={showAppLockSettings}+ />+</RowButtonGroup>+```++**Requires re-authentication** before opening (same pattern as "Active Sessions" at `Sidebar.tsx:977-980`).++### Settings Drawer Layout++Uses `TitledNestedSidebarDrawer` (same as `TwoFactorSettings`, `MLSettings`, `SessionsSettings`):++```++----------------------------------------------------++| <- App Lock |++----------------------------------------------------++| |+| [Toggle: Enable App Lock] [RowSwitch] |+| |+| --- (shown only when enabled) --- |+| |+| Lock Type: |+| +--------------------------------------------+ |+| | PIN [checkmark] | |+| |-------------------------------------------- | |+| | Password | |+| +--------------------------------------------+ |+| |+| Auto-Lock: |+| +--------------------------------------------+ |+| | [Selection: Immediately / 5s / 15s / ...] | |+| +--------------------------------------------+ |+| |+| --- (always shown, independent of lock) --- |+| |+| +--------------------------------------------+ |+| | Hide content when switching tabs [RowSwitch]| |+| +--------------------------------------------+ |+| Hint: Blurs app content in tab previews |+| |++----------------------------------------------------++```++### PIN/Password Setup Flow++When user selects a lock type, show a dialog (using existing `TitledMiniDialog` pattern):++```+Select "PIN" -> Enter 4-digit PIN -> Confirm PIN -> Hash & store+Select "Password" -> Enter password -> Confirm password -> Hash & store+```++Switching lock type generates a new salt and overwrites the old hash (mutual exclusivity, matching mobile).++---++## 10. Data Flow Diagrams++### 10.1 Cold Start (Page Load)++```+User opens app / refreshes page+ |+ v+_app.tsx renders+ |+ +-- Read localStorage("appLock.enabled") [SYNC]+ | Read localStorage("appLock.lockType") [SYNC]+ |+ +-- IF enabled AND haveMasterKeyInSession():+ | Set isLocked = true (in-memory)+ | AppLockOverlay renders immediately (full-screen)+ | |+ | +-- Read KV("appLock.cooldownExpiresAt") [ASYNC]+ | | IF now < expiresAt: show cooldown timer+ | |+ | +-- User enters PIN/password+ | | -> Read salt from KV DB [ASYNC]+ | | -> deriveInteractiveKey(input, salt) [Web Worker]+ | | -> Compare with hash from KV DB+ | | -> Match: set isLocked = false, reset attempts+ | | -> No match: increment attempts, maybe start cooldown+ | |+ | v+ | Overlay removed, app content interactive+ |+ +-- IF NOT enabled OR not logged in:+ App renders normally (no overlay)+```++### 10.2 Tab Hidden -> Visible (Browser)++```+User switches to another tab+ |+ v+document.visibilitychange fires (hidden)+ |+ v+Start auto-lock timer (setTimeout with autoLockTimeMs)+ |+ +-- User returns BEFORE timer fires:+ | clearTimeout, no lock+ |+ +-- Timer fires WHILE tab is hidden:+ | Set isLocked = true+ | Broadcast "lock" via BroadcastChannel+ |+ v+document.visibilitychange fires (visible)+ |+ v+IF isLocked:+ AppLockOverlay showing, user must authenticate+ELSE:+ Normal operation resumes+```++### 10.3 Unlock Flow++```+AppLockOverlay is showing+ |+ v+User enters PIN (4 digits) or password+ |+ v+attemptUnlock(input) called+ |+ +-- Check cooldown: IF Date.now() < cooldownExpiresAt+ | Reject immediately, show remaining time+ | RETURN+ |+ +-- Check session: IF !haveMasterKeyInSession()+ | Session expired while locked, call logout()+ | RETURN+ |+ +-- salt = await getKVS("appLock.salt")+ +-- storedHash = await getKVS("appLock.hash")+ |+ +-- inputHash = await deriveInteractiveKey(input, salt)+ |+ +-- IF inputHash.key === storedHash:+ | Set isLocked = false+ | Set invalidAttemptCount = 0+ | Clear cooldownExpiresAt+ | Save to KV DB+ | Broadcast "unlock" via BroadcastChannel+ | Overlay unmounts+ |+ +-- IF inputHash.key !== storedHash:+ invalidAttemptCount+++ IF count >= 10:+ Call logout() (security auto-logout)+ ELSE IF count >= 5:+ cooldownSeconds = 2^(count-5) * 30+ cooldownExpiresAt = Date.now() + cooldownSeconds*1000+ Save to KV DB+ Start countdown timer UI+ Show error: "Incorrect PIN/password"+```++### 10.4 Settings Change Flow++```+User opens Sidebar -> Account -> "App Lock"+ |+ v+onAuthenticateUser() triggers master password re-auth+ |+ +-- Auth succeeds: AppLockSettings drawer opens+ +-- Auth cancelled: nothing happens+ |+ v+Toggle "Enable App Lock" ON+ |+ +-- Default lockType = "pin"+ +-- Show PIN setup dialog (enter + confirm)+ +-- On confirm:+ | salt = generateDeriveKeySalt()+ | hash = deriveInteractiveKey(pin, salt)+ | Store hash + salt in KV DB+ | Store lockType + enabled in localStorage+ | Update in-memory state, notify subscribers+ |+ v+Change lock type (e.g., PIN -> Password)+ |+ +-- Show password setup dialog (enter + confirm)+ +-- On confirm:+ | Generate NEW salt (overwrites old)+ | Hash password, store in KV DB (overwrites old hash)+ | Update lockType in localStorage+ |+ v+Toggle "Enable App Lock" OFF+ |+ +-- Clear hash + salt from KV DB+ +-- Clear lockType + enabled from localStorage+ +-- Clear attempt counters from KV DB+ +-- Set isLocked = false+ +-- Notify subscribers+```++---++## 11. Multi-Tab Synchronization++Use the `BroadcastChannel` API to synchronize lock/unlock events across browser tabs.++```typescript+const channel = new BroadcastChannel("ente-app-lock");++// When locking:+channel.postMessage({ type: "lock" });++// When unlocking:+channel.postMessage({ type: "unlock" });++// Listen for events from other tabs:+channel.onmessage = (event) => {+ if (event.data.type === "lock") lock();+ if (event.data.type === "unlock") unlockWithoutAuth(); // other tab already verified+};+```++**Behavior:**+- Tab A locks -> Tab B also locks (both show overlay)+- Tab A unlocks -> Tab B also unlocks (both hide overlay)+- Opening a new tab while locked: new tab reads `enabled` from localStorage on mount, starts locked++---++## 12. Brute-Force Protection++Matches the mobile implementation:++| Attempt # | Cooldown | Action |+|-----------|----------|--------|+| 1-4 | None | Try again |+| 5 | 30 seconds | `2^(5-5) * 30 = 30s` |+| 6 | 1 minute | `2^(6-5) * 30 = 60s` |+| 7 | 2 minutes | `2^(7-5) * 30 = 120s` |+| 8 | 4 minutes | `2^(8-5) * 30 = 240s` |+| 9 | 8 minutes | `2^(9-5) * 30 = 480s` |+| 10+ | -- | **Auto-logout. Session terminated.** |++Formula: `2^(attemptCount - 5) * 30` seconds.++**Persistence:** Attempt count and cooldown expiry stored in IndexedDB KV store (not localStorage). This makes them slightly harder to tamper with than localStorage, though still clearable by a determined browser user.++**Cooldowns survive refresh:** On page load/lock screen mount, read `cooldownExpiresAt` from KV DB. If `Date.now() < expiresAt`, show the remaining cooldown timer immediately.++---++## 13. Integration Points++### Independent from Master Key++The app lock uses a **separate** Argon2id hash with its own salt. It does NOT interact with:+- `AuthenticateUser` (which verifies the master password via SRP)+- The master key in `sessionStorage`+- Any server API++### Session Management++- On cold start, the lock overlay checks `haveMasterKeyInSession()`. If no master key (user not logged in), the overlay doesn't render.+- On unlock attempt, verify the session is still valid. If the auth token expired during lock, redirect to login via `logout()`.++### Logout Flow++The lock screen includes a "Logout" link. Clicking it:+1. Shows a confirmation dialog (matching existing `handleLogout` pattern)+2. Calls `logout()` from `BaseContext`+3. `photosLogout()` calls `logoutAppLock()`, which clears all app lock storage++---++## 14. Security Model++### Browser (Known Limitations)++The browser app lock is a **UX convenience feature**, not a security boundary:+- localStorage and IndexedDB are readable/clearable via DevTools+- Lock state in memory can be manipulated via console+- The master key in sessionStorage is accessible to anyone with DevTools++This is acceptable. The lock prevents:+- Casual shoulder-surfing when stepping away from a shared computer+- Accidental access by someone opening your browser tabs++### Electron Desktop++The Electron app lock provides **meaningful security against casual physical access**:+- Production builds don't expose DevTools+- PIN hash can be stored in OS safe storage (Keychain/DPAPI/libsecret)+- Lock state can be enforced in the main process++### PIN Entropy++4-digit PIN = 10,000 combinations. With Argon2id interactive limits (~200ms per hash), exhaustive brute force takes ~33 minutes. Combined with exponential backoff (locked out after 4 failures) and auto-logout after 10 attempts, this is adequate for a local lock.++### Session Isolation++- Each browser tab has its own in-memory lock state+- localStorage and IndexedDB are shared across tabs (same origin)+- BroadcastChannel syncs lock/unlock events across tabs+- Opening a new tab while locked: the new tab starts locked++---++## 15. Accessibility++The lock screen overlay must be fully accessible:++- **Focus trapping:** Use `aria-modal="true"` and `role="dialog"` on the overlay. Tab key cycles within the overlay only.+- **Keyboard navigation:** Tab to PIN/password input, Enter to submit. Escape does nothing (locked).+- **Screen reader:** Announce "App is locked. Enter your PIN to unlock." via `aria-label` on the dialog.+- **Error announcements:** Failed attempts announced via `aria-live="polite"` region.+- **Cooldown timer:** Timer updates announced to screen readers.++Use MUI's `<Backdrop>` or `<Dialog>` with `disableEscapeKeyDown` for built-in focus trapping.++---++## 16. New & Modified Files++### New Files++| File | Purpose |+|------|---------|+| `web/packages/new/photos/services/app-lock.ts` | State management (subscribe/snapshot), storage ops, hashing, brute-force logic, BroadcastChannel sync |+| `web/packages/new/photos/components/AppLockOverlay.tsx` | Lock screen UI (overlay, PIN/password input, cooldown timer, logout, accessibility) |+| `web/packages/new/photos/components/sidebar/AppLockSettings.tsx` | Settings drawer (enable/disable, lock type, auto-lock time, privacy toggle) |++### Modified Files++| File | Change |+|------|--------|+| `web/apps/photos/src/pages/_app.tsx` | Render `AppLockOverlay` as sibling, add visibility/timer event listeners via `useEffect` |+| `web/apps/photos/src/components/Sidebar.tsx` | Add "App Lock" entry in Account section |+| `web/apps/photos/src/services/logout.ts` | Add `logoutAppLock()` call in `photosLogout()` |+| `web/packages/base/types/ipc.ts` | Add `onMainWindowBlur` callback (Electron, post-MVP) |+| `desktop/src/main.ts` | Wire up `onMainWindowBlur` IPC event (Electron, post-MVP) |+| `desktop/src/preload.ts` | Bridge `onMainWindowBlur` (Electron, post-MVP) |++---++## 17. MVP Implementation Order++| Priority | Component | Complexity | Description |+|----------|-----------|------------|-------------|+| 1 | `app-lock.ts` service | Medium | Core state machine, hash/verify, lock/unlock, timer management, BroadcastChannel |+| 2 | `AppLockOverlay.tsx` | Medium | PIN/password input, cooldown display, logout link, focus trapping, accessibility |+| 3 | `AppLockSettings.tsx` | Low | Enable/disable toggle, lock type selection, PIN/password setup dialogs, auto-lock picker |+| 4 | `_app.tsx` + `Sidebar.tsx` integration | Low | Wire up overlay rendering, visibility event listeners, sidebar entry |+| 5 | Multi-tab sync | Low | BroadcastChannel lock/unlock synchronization |++---++## 18. Deferred Features++These are not part of the MVP but should be considered for future iterations:++| Feature | Complexity | Notes |+|---------|------------|-------|+| Electron `onMainWindowBlur` IPC | Medium | Cross-package change (web + desktop). Must filter blur events from other Electron windows. |+| Electron safeStorage-backed hash | Medium | Store hash/salt in OS secure storage in addition to IndexedDB. Prevents DevTools bypass on desktop. |+| Biometric unlock (Touch ID / Windows Hello) | High | Requires new IPC methods + platform-specific APIs. Touch ID via `systemPreferences.promptTouchID()`. |+| System idle auto-lock | Medium | Electron `powerMonitor.getSystemIdleTime()`. Not available in browser. |+| Screen lock detection | Low | Electron `powerMonitor.on('lock-screen')`. Auto-lock when OS screen locks. |+| Storage key versioning | Low | Version keys (e.g., `appLock_v1_hash`) for future migration paths. |diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.jsonindex f2a069b3c1..9751c7c490 100644--- a/web/packages/base/locales/en-US/translation.json+++ b/web/packages/base/locales/en-US/translation.json@@ -834,5 +834,17 @@"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"+ "app_lock_incorrect": "Incorrect PIN or app lock password",+ "app_lock_set_pin": "Set PIN",+ "PIN": "PIN",+ "auto_lock_immediately": "Immediately",+ "auto_lock_5_seconds": "5 seconds",+ "auto_lock_15_seconds": "15 seconds",+ "auto_lock_1_minute": "1 minute",+ "auto_lock_5_minutes": "5 minutes",+ "auto_lock_30_minutes": "30 minutes",+ "wrong_unlock_code_one": "You've entered the wrong unlock code {{count}} time.",+ "wrong_unlock_code_other": "You've entered the wrong unlock code {{count}} times.",+ "one_more_wrong_attempt_logout": "One more wrong attempt will log you out.",+ "next_wrong_attempt_wait": "You'll need to wait {{time}} if this attempt is wrong."}diff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsxindex 02bad5667b..71b4014566 100644--- a/web/packages/new/photos/components/AppLockOverlay.tsx+++ b/web/packages/new/photos/components/AppLockOverlay.tsx@@ -8,11 +8,10 @@import LockOutlinedIcon from "@mui/icons-material/LockOutlined";import {- Backdrop,Box,CircularProgress,+ Modal,Paper,- Portal,Stack,TextField,Typography,@@ -21,7 +20,6 @@ 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, {@@ -31,10 +29,7 @@ import React, {useRef,useState,} from "react";-import {- attemptUnlock,- type UnlockResult,-} from "../services/app-lock";+import { attemptUnlock, type UnlockResult } from "../services/app-lock";import { useAppLockSnapshot } from "./utils/use-snapshot";/**@@ -45,51 +40,37 @@ import { useAppLockSnapshot } from "./utils/use-snapshot";*/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;+ const { logout } = useBaseContext();+ const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);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}+ <Modal+ open+ disableEscapeKeyDown+ aria-label={t("app_lock")}+ slotProps={{+ backdrop: {+ sx: {+ backgroundColor:+ "var(--mui-palette-background-default)",+ },+ },+ }}+ sx={{ zIndex: "calc(var(--mui-zIndex-tooltip) + 1)" }}+ >+ <Boxsx={{- zIndex: "calc(var(--mui-zIndex-tooltip) + 1)",- backgroundColor: "var(--mui-palette-background-default)",+ position: "fixed",+ inset: 0,+ display: "flex",flexDirection: "column",- pointerEvents: "auto",+ alignItems: "center",+ justifyContent: "center",+ outline: "none",}}+ style={{ WebkitAppRegion: "no-drag" } as React.CSSProperties}>{/* Top bar: logo centered, logout button at top-right */}<Box@@ -105,12 +86,12 @@ export const AppLockOverlay: React.FC = () => {}}><EnteLogo />- {!isInCooldown && (+ {!showLogoutConfirm && (<FocusVisibleButtonvariant="text"color="secondary"size="small"- onClick={handleLogout}+ onClick={() => setShowLogoutConfirm(true)}sx={{textTransform: "none",position: "absolute",@@ -125,15 +106,26 @@ export const AppLockOverlay: React.FC = () => {{/* Centered form content */}{appLock.lockType === "pin" ? (- <PinUnlockForm appLock={appLock} onLogout={handleLogout} />+ <PinUnlockForm+ appLock={appLock}+ onLogout={() => setShowLogoutConfirm(true)}+ />) : (<PasswordUnlockFormappLock={appLock}- onLogout={handleLogout}+ onLogout={() => setShowLogoutConfirm(true)}/>)}- </Backdrop>- </Portal>++ {/* Logout confirmation overlays on top */}+ {showLogoutConfirm && (+ <LogoutConfirmation+ onConfirm={logout}+ onCancel={() => setShowLogoutConfirm(false)}+ />+ )}+ </Box>+ </Modal>);};@@ -208,60 +200,6 @@ const useCooldownState = (};};-/**- * 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 }) => {@@ -274,10 +212,6 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {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.@@ -306,20 +240,17 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {);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 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);@@ -386,6 +317,8 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {<TextFieldkey={i}hiddenLabel+ autoFocus={i === 0}+ error={!!error}inputRef={(el: HTMLInputElement | null) => {inputRefs.current[i] = el;}}@@ -445,8 +378,6 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({const cooldown = useCooldownState(appLock.cooldownExpiresAt);const cooldownText = cooldown.text;- useRestoreInputFocus(useCallback(() => inputRef.current, []));-const handleSubmit = useCallback(async (e?: React.FormEvent) => {e?.preventDefault();@@ -463,6 +394,7 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({}setPassword("");+ inputRef.current?.focus();},[password, loading, logout],);@@ -499,6 +431,8 @@ const PasswordUnlockForm: React.FC<UnlockFormProps> = ({inputRef={inputRef}fullWidthhiddenLabel+ autoFocus+ error={!!error}type={showPassword ? "text" : "password"}value={password}onChange={(e) => {@@ -545,22 +479,84 @@ interface ErrorMessageProps {attemptCount: number;}-const ErrorMessage: React.FC<ErrorMessageProps> = ({- error,- attemptCount,-}) => {+const ErrorMessage: React.FC<ErrorMessageProps> = ({ error, attemptCount }) => {if (error) {return (- <Typography variant="small" color="critical.main" textAlign="center">+ <Typography+ variant="small"+ color="critical.main"+ textAlign="center"+ >{error}- {attemptCount > 0 &&- ` (${String(attemptCount)}/10)`}+ {attemptCount > 0 && ` (${String(attemptCount)}/10)`}</Typography>);}return null;};+interface LogoutConfirmationProps {+ onConfirm: () => void;+ onCancel: () => void;+}++const LogoutConfirmation: React.FC<LogoutConfirmationProps> = ({+ onConfirm,+ onCancel,+}) => (+ <Box+ sx={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ backgroundColor: "rgba(0,0,0,0.5)",+ zIndex: 1,+ }}+ onClick={onCancel}+ >+ <Paper+ elevation={0}+ sx={{+ width: "min(420px, 85vw)",+ px: { xs: 3, sm: 5 },+ py: 4,+ borderRadius: "20px",+ boxShadow: "var(--mui-palette-boxShadow-paper)",+ }}+ onClick={(e) => e.stopPropagation()}+ >+ <Stack spacing={3} alignItems="center" sx={{ width: "100%" }}>+ <Typography variant="h3">{t("logout")}</Typography>+ <Typography+ variant="small"+ color="text.muted"+ textAlign="center"+ >+ {t("logout_message")}+ </Typography>+ <Stack direction="row" spacing={1.5} sx={{ width: "100%" }}>+ <FocusVisibleButton+ fullWidth+ color="secondary"+ onClick={onCancel}+ >+ {t("cancel")}+ </FocusVisibleButton>+ <FocusVisibleButton+ fullWidth+ color="critical"+ onClick={onConfirm}+ >+ {t("logout")}+ </FocusVisibleButton>+ </Stack>+ </Stack>+ </Paper>+ </Box>+);+interface CooldownScreenProps {remainingMs: number;cooldownText: string;@@ -586,11 +582,12 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({: 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)}.`;+ ? t("one_more_wrong_attempt_logout")+ : t("next_wrong_attempt_wait", {+ time: formatCooldown(nextCooldownMs),+ });return (<Stack@@ -598,7 +595,7 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({useFlexGapalignItems="center"justifyContent="center"- sx={{ maxWidth: 340, width: "100%", px: 2 }}+ sx={{ maxWidth: 380, width: "100%", px: 2 }}><Typographyvariant="h3"@@ -637,14 +634,18 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({justifyContent: "center",}}>- <Typography variant="body" color="critical.main" textAlign="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}.`}+ {t("wrong_unlock_code", { count: attemptCount })}</Typography><Typographyvariant="mini"diff --git a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx b/web/packages/new/photos/components/sidebar/AppLockSettings.tsxindex 11f0ac534a..390ff0dff3 100644--- a/web/packages/new/photos/components/sidebar/AppLockSettings.tsx+++ b/web/packages/new/photos/components/sidebar/AppLockSettings.tsx@@ -2,6 +2,7 @@ import CheckIcon from "@mui/icons-material/Check";import ChevronRightIcon from "@mui/icons-material/ChevronRight";import {DialogActions,+ Slider,Stack,TextField,Typography,@@ -29,7 +30,7 @@ import {setHideContentOnBlur,} from "../../services/app-lock";import { t } from "i18next";-import React, { useCallback, useRef, useState } from "react";+import React, { useCallback, useEffect, useRef, useState } from "react";import { useAppLockSnapshot } from "../utils/use-snapshot";export const AppLockSettings: React.FC<@@ -40,7 +41,6 @@ export const AppLockSettings: React.FC<const [pinDialogOpen, setPinDialogOpen] = useState(false);const [passwordDialogOpen, setPasswordDialogOpen] = useState(false);const [autoLockDialogOpen, setAutoLockDialogOpen] = useState(false);-const { showMiniDialog } = useBaseContext();const handleRootClose = () => {@@ -112,7 +112,7 @@ export const AppLockSettings: React.FC<</Typography><RowButtonGroup><RowButton- label="PIN"+ label={t("PIN")}endIcon={state.lockType === "pin" ? (<CheckIcon@@ -188,18 +188,18 @@ export const AppLockSettings: React.FC<// -- 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 autoLockOptions: { labelKey: string; ms: number }[] = [+ { labelKey: "auto_lock_immediately", ms: 0 },+ { labelKey: "auto_lock_5_seconds", ms: 5_000 },+ { labelKey: "auto_lock_15_seconds", ms: 15_000 },+ { labelKey: "auto_lock_1_minute", ms: 60_000 },+ { labelKey: "auto_lock_5_minutes", ms: 300_000 },+ { labelKey: "auto_lock_30_minutes", ms: 1_800_000 },];const autoLockLabel = (ms: number): string => {const option = autoLockOptions.find((o) => o.ms === ms);- return option?.label ?? "Immediately";+ return t(option?.labelKey ?? "auto_lock_immediately");};// -- PIN Setup Dialog --@@ -304,6 +304,7 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({values: string[],refs: React.RefObject<(HTMLInputElement | null)[]>,isConfirm: boolean,+ hasError?: boolean,) => (<Stackdirection="row"@@ -313,6 +314,7 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({<TextFieldkey={i}hiddenLabel+ error={hasError}value={digit}onChange={(e) =>handlePinDigitChange(i, e.target.value, isConfirm)@@ -345,7 +347,7 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({<TitledMiniDialogopen={open}onClose={handleClose}- title="Set PIN"+ title={t("app_lock_set_pin")}sx={{"& .MuiDialogTitle-root": { pb: 0 },"& .MuiDialogTitle-root + .MuiDialogContent-root": { pt: 0 },@@ -372,7 +374,7 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({<Typography sx={{ color: "text.muted", textAlign: "left" }}>{t("confirm_pin")}</Typography>- {renderPinInputs(confirmPin, confirmInputRefs, true)}+ {renderPinInputs(confirmPin, confirmInputRefs, true, !!error)}{error && (<Typographyvariant="small"@@ -381,14 +383,7 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({{error}</Typography>)}- <Stack direction="row" sx={{ gap: 1.5, width: "100%" }}>- <FocusVisibleButton- fullWidth- color="secondary"- onClick={handleBack}- >- {t("go_back")}- </FocusVisibleButton>+ <Stack sx={{ gap: 1.5, width: "100%" }}><FocusVisibleButtonfullWidthcolor="accent"@@ -397,6 +392,13 @@ const PinSetupDialog: React.FC<SetupDialogProps> = ({>{t("confirm")}</FocusVisibleButton>+ <FocusVisibleButton+ fullWidth+ color="secondary"+ onClick={handleBack}+ >+ {t("go_back")}+ </FocusVisibleButton></Stack></>)}@@ -419,6 +421,15 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({const [showConfirmPassword, setShowConfirmPassword] = useState(false);const [error, setError] = useState("");+ const passwordInputRef = useRef<HTMLInputElement>(null);+ const confirmPasswordInputRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ if (open) {+ setTimeout(() => passwordInputRef.current?.focus(), 300);+ }+ }, [open]);+const resetState = useCallback(() => {setStep("enter");setPassword("");@@ -436,12 +447,14 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({const handleNext = useCallback(() => {if (!password) return;setStep("confirm");+ setTimeout(() => confirmPasswordInputRef.current?.focus(), 300);}, [password]);const handleBack = useCallback(() => {setStep("enter");setConfirmPassword("");setError("");+ setTimeout(() => passwordInputRef.current?.focus(), 300);}, []);const handleConfirm = useCallback(async () => {@@ -460,23 +473,27 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({open={open}onClose={handleClose}title={t("app_lock_set_password")}+ sx={{+ "& .MuiDialogTitle-root": { pb: 0 },+ "& .MuiDialogTitle-root + .MuiDialogContent-root": { pt: 0 },+ }}><Stack sx={{ gap: 2, py: 1 }}>{step === "enter" ? (<>- <Typography sx={{ color: "text.muted" }}>- {t("app_lock_enter_password")}- </Typography><TextFieldfullWidth+ label={t("app_lock_enter_password")}type={showPassword ? "text" : "password"}value={password}onChange={(e) => {setPassword(e.target.value);setError("");}}- autoFocusslotProps={{+ htmlInput: {+ ref: passwordInputRef,+ },input: {endAdornment: (<ShowHidePasswordInputAdornment@@ -500,19 +517,21 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({</>) : (<>- <Typography sx={{ color: "text.muted" }}>- {t("app_lock_confirm_password")}- </Typography><TextFieldfullWidth+ label={t("app_lock_confirm_password")}type={showConfirmPassword ? "text" : "password"}value={confirmPassword}+ error={!!error}+ helperText={error || undefined}onChange={(e) => {setConfirmPassword(e.target.value);setError("");}}- autoFocusslotProps={{+ htmlInput: {+ ref: confirmPasswordInputRef,+ },input: {endAdornment: (<ShowHidePasswordInputAdornment@@ -527,25 +546,7 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({},}}/>- {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>+ <Stack sx={{ gap: 1.5, width: "100%" }}><FocusVisibleButtonfullWidthcolor="accent"@@ -554,6 +555,13 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({>{t("confirm")}</FocusVisibleButton>+ <FocusVisibleButton+ fullWidth+ color="secondary"+ onClick={handleBack}+ >+ {t("go_back")}+ </FocusVisibleButton></Stack></>)}@@ -562,7 +570,7 @@ const PasswordSetupDialog: React.FC<SetupDialogProps> = ({);};-// -- Auto-Lock Duration Dialog --+// -- Auto-Lock Dialog with Slider --interface AutoLockDialogProps {open: boolean;@@ -570,39 +578,72 @@ interface AutoLockDialogProps {currentValue: number;}+const autoLockMarks = autoLockOptions.map((_, i) => ({ value: i }));+const AutoLockDialog: React.FC<AutoLockDialogProps> = ({open,onClose,currentValue,}) => {- const handleSelect = (ms: number) => {- setAutoLockTime(ms);- onClose();+ const currentIndex = autoLockOptions.findIndex(+ (o) => o.ms === currentValue,+ );++ const handleChange = (_: Event, 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);+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 sx={{ gap: 2, py: 1 }}>+ <Typography+ variant="small"+ color="accent.main"+ textAlign="center"+ >+ {autoLockLabel(currentValue)}+ </Typography>+ <Stack sx={{ px: 1 }}>+ <Slider+ value={currentIndex === -1 ? 0 : currentIndex}+ min={0}+ max={autoLockOptions.length - 1}+ step={null}+ marks={autoLockMarks}+ onChange={handleChange}+ 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><DialogActions><FocusVisibleButtonfullWidth- color="secondary"+ color="accent"onClick={onClose}>- {t("cancel")}+ {t("done")}</FocusVisibleButton></DialogActions></TitledMiniDialog>