Skip to content

armgit / ente

Public Imported from GitHub
0

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

refactor(AppLock): remove legacy device lock support checks and improve code clarity

Aswin Asokcd05bd008982
diff --git a/desktop/src/main/ipc.ts b/desktop/src/main/ipc.ts
index 89abe36c44..cbf4f3d7a1 100644
--- a/desktop/src/main/ipc.ts
+++ b/desktop/src/main/ipc.ts
@@ -29,7 +29,6 @@ import {
import autoLauncher from "./services/auto-launcher";
import {
getNativeDeviceLockCapability,
- isDeviceLockSupported,
promptDeviceLock,
} from "./services/device-lock";
import {
@@ -145,10 +144,6 @@ export const attachIPCHandlers = () => {
getNativeDeviceLockCapability(),
);
- // Returns a simple yes/no for whether native device lock can be used on
- // this machine. Useful for quick feature gating in settings.
- ipcMain.handle("isDeviceLockSupported", () => isDeviceLockSupported());
-
// Triggers the OS-native authentication prompt (Touch ID / Windows Hello /
// etc.) and returns the auth result back to the renderer.
ipcMain.handle("promptDeviceLock", (_, reason: string) =>
diff --git a/desktop/src/main/services/device-lock.ts b/desktop/src/main/services/device-lock.ts
index abf0b30c27..35870b500a 100644
--- a/desktop/src/main/services/device-lock.ts
+++ b/desktop/src/main/services/device-lock.ts
@@ -41,14 +41,6 @@ export const getNativeDeviceLockCapability = (): NativeDeviceLockCapability => {
}
};
-/**
- * Legacy compatibility helper used by older renderer flows.
- *
- * Prefer {@link getNativeDeviceLockCapability}.
- */
-export const isDeviceLockSupported = () =>
- getNativeDeviceLockCapability().available;
-
/**
* Prompt the user to unlock using native device authentication.
*
diff --git a/desktop/src/preload.ts b/desktop/src/preload.ts
index f25695e8a4..e50257a7da 100644
--- a/desktop/src/preload.ts
+++ b/desktop/src/preload.ts
@@ -133,8 +133,6 @@ const toggleAutoLaunch = () => ipcRenderer.invoke("toggleAutoLaunch");
const getNativeDeviceLockCapability = (): Promise<NativeDeviceLockCapability> =>
ipcRenderer.invoke("getNativeDeviceLockCapability");
-const isDeviceLockSupported = () => ipcRenderer.invoke("isDeviceLockSupported");
-
const minDeviceLockPromptIntervalMs = 1_500;
let lastDeviceLockPromptTimeMs = 0;
@@ -389,7 +387,6 @@ contextBridge.exposeInMainWorld("electron", {
isAutoLaunchEnabled,
toggleAutoLaunch,
getNativeDeviceLockCapability,
- isDeviceLockSupported,
promptDeviceLock,
onMainWindowFocus,
onOpenEnteURL,
diff --git a/web/packages/new/photos/components/AppLockOverlay.tsx b/web/packages/new/photos/components/AppLockOverlay.tsx
index 696da19e42..0d2070d583 100644
--- a/web/packages/new/photos/components/AppLockOverlay.tsx
+++ b/web/packages/new/photos/components/AppLockOverlay.tsx
@@ -172,6 +172,11 @@ const AppLockCard: React.FC<React.PropsWithChildren> = ({ children }) => (
/**
* Format remaining cooldown seconds into a human-readable string.
+ *
+ * Input is in milliseconds, so convert it to minutes and seconds for display.
+ *
+ * - "Xm Ys" if at least 1 minute
+ * - "Xs" if under a minute
*/
const formatCooldown = (remainingMs: number): string => {
const totalSeconds = Math.ceil(remainingMs / 1000);
@@ -183,6 +188,18 @@ const formatCooldown = (remainingMs: number): string => {
return `${String(seconds)}s`;
};
+/**
+ * Move the caret to the end of the current input value.
+ */
+const moveCaretToInputEnd = (input: HTMLInputElement) => {
+ try {
+ const caretPosition = input.value.length;
+ input.setSelectionRange(caretPosition, caretPosition);
+ } catch {
+ // Ignore if selection range isn't supported.
+ }
+};
+
/**
* Hook that returns remaining cooldown time state, updating every second.
*/
@@ -276,16 +293,18 @@ 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.
+
+ /**
+ * Focus the PIN field at the given index, then place the caret at the end.
+ */
+ const focusPinInput = useCallback((pinIndex: number) => {
+ const input = inputRefs.current[pinIndex];
+ if (!input) {
+ return;
}
+
+ input.focus({ preventScroll: true });
+ moveCaretToInputEnd(input);
}, []);
const focusFirstEmptyPinInput = useCallback(() => {
const firstEmptyIndex = pin.findIndex((digit) => !digit);
@@ -298,6 +317,11 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
setLoading(true);
try {
const result: UnlockResult = await attemptUnlock(fullPin);
+
+ /**
+ * The result can be "success", "failed", "cooldown", or "logout".
+ * Apply the corresponding UI updates for each case.
+ */
handleUnlockResult(result, setError, setLoading, logout);
} catch (e) {
log.error("Unlock attempt failed", e);
@@ -305,7 +329,7 @@ const PinUnlockForm: React.FC<UnlockFormProps> = ({ appLock, onLogout }) => {
setLoading(false);
}
- // Clear PIN on any non-success.
+ // Clear PIN after each attempt and refocus the first field.
setPin(["", "", "", ""]);
focusPinInput(0);
}, [fullPin, loading, logout, focusPinInput]);
@@ -681,14 +705,6 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({
durationMs > 0
? Math.min(100, ((durationMs - remainingMs) / durationMs) * 100)
: 0;
- const nextAttemptCount = attemptCount + 1;
- const nextCooldownMs = appLockCooldownDurationMs(nextAttemptCount);
- const nextAttemptMessage =
- nextAttemptCount >= 10
- ? t("one_more_wrong_attempt_logout")
- : t("next_wrong_attempt_wait", {
- time: formatCooldown(nextCooldownMs),
- });
return (
<Stack
@@ -748,19 +764,6 @@ const CooldownScreen: React.FC<CooldownScreenProps> = ({
<Typography variant="small" color="text.muted" textAlign="center">
{t("wrong_unlock_code", { count: attemptCount })}
</Typography>
- <Typography
- variant="mini"
- color="text.muted"
- textAlign="center"
- sx={{
- width: "100%",
- pt: 0.75,
- borderTop: "1px solid var(--mui-palette-divider)",
- opacity: 0.9,
- }}
- >
- {nextAttemptMessage}
- </Typography>
<FocusVisibleButton
fullWidth
color="secondary"
@@ -786,9 +789,6 @@ const handleUnlockResult = (
) => {
switch (result) {
case "success":
- setError(undefined);
- setLoading(false);
- break;
case "cooldown":
setError(undefined);
setLoading(false);
diff --git a/web/packages/new/photos/services/app-lock.ts b/web/packages/new/photos/services/app-lock.ts
index 80f86311b0..8d1f1f2000 100644
--- a/web/packages/new/photos/services/app-lock.ts
+++ b/web/packages/new/photos/services/app-lock.ts
@@ -545,15 +545,6 @@ const resolveDeviceLockCapability = async (): Promise<DeviceLockCapability> => {
};
};
-/**
- * Return true if the current environment supports native device lock app
- * unlocks.
- */
-export const isDeviceLockSupported = async () => {
- const capability = await resolveDeviceLockCapability();
- return capability.usable;
-};
-
/**
* Return true if the current environment should show "Device lock" in the
* lock-type picker.
@@ -774,6 +765,10 @@ export const attemptDeviceLockUnlock =
* attempts, signals that the caller should force-logout the user.
*/
export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
+ /**
+ * This flow applies only to PIN and password locks.
+ * Guard against being called for any other lock type.
+ */
const isPassphraseLock =
_state.snapshot.lockType === "pin" ||
_state.snapshot.lockType === "password";
@@ -785,7 +780,12 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
// Ensure persisted lockout state has been rehydrated before enforcing.
await ensureBruteForceStateHydrated();
- // Refresh lockout state from KV so stale tabs cannot reset counters.
+ /**
+ * Refresh lockout state from KV so stale tabs cannot reset counters.
+ *
+ * If multiple tabs attempt to unlock at the same time, sync from KV DB
+ * before validation so all tabs use the latest attempt/cooldown state.
+ */
const persistedState = await readBruteForceStateFromKV();
const invalidAttemptCount = Math.max(
_state.snapshot.invalidAttemptCount,
@@ -795,6 +795,8 @@ export const attemptUnlock = async (input: string): Promise<UnlockResult> => {
_state.snapshot.cooldownExpiresAt,
persistedState.cooldownExpiresAt,
);
+
+ // Update the snapshot with the latest values.
setBruteForceSnapshot(invalidAttemptCount, cooldownExpiresAt);
// Check cooldown from in-memory state.