mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 03:50:30 +00:00
feat(native): an app lock with Face ID, Touch ID or the device passcode
A switch in the account settings, inside the app on a device that can unlock that way (iOS LocalAuthentication, Android BiometricPrompt with the screen lock as fallback). Turning it on asks once, so nobody locks themselves out. With it on, TREK asks at launch and after half a minute in the background before showing anything, and the app switcher shows a blurred cover (iOS) or no snapshot (Android) instead of the screen. The setting stays on the device, not the account.
This commit is contained in:
@@ -33,6 +33,7 @@ import { registerSyncTriggers, unregisterSyncTriggers } from './sync/syncTrigger
|
||||
import OfflineBanner from './components/Layout/OfflineBanner'
|
||||
import NewVersionNotice from './components/Layout/NewVersionNotice'
|
||||
import NativeUpdateNotice from './components/Layout/NativeUpdateNotice'
|
||||
import AppLockGate from './components/Layout/AppLockGate'
|
||||
import { SystemNoticeHost } from './components/SystemNotices/SystemNoticeHost.js'
|
||||
import HelpPanel from './components/Help/HelpPanel'
|
||||
// Notice action registrations (side-effect imports):
|
||||
@@ -444,6 +445,7 @@ export default function App() {
|
||||
<ErrorBoundary boundaryId="widget:offline-banner" fallback={null}><OfflineBanner /></ErrorBoundary>
|
||||
<ErrorBoundary boundaryId="widget:new-version" fallback={null}><NewVersionNotice /></ErrorBoundary>
|
||||
<ErrorBoundary boundaryId="widget:native-update" fallback={null}><NativeUpdateNotice /></ErrorBoundary>
|
||||
<ErrorBoundary boundaryId="widget:app-lock" fallback={null}><AppLockGate /></ErrorBoundary>
|
||||
{/* One boundary for all route chunks, above <Routes> so it stays mounted
|
||||
across navigations. react-router runs location updates inside a transition,
|
||||
so a mounted boundary keeps the current page on screen instead of flashing
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { App } from '@capacitor/app';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
|
||||
import { isAppLockEnabled, unlockApp } from '../../native/appLock';
|
||||
import AppLockGate from './AppLockGate';
|
||||
|
||||
vi.mock('@capacitor/app', () => ({ App: { addListener: vi.fn(() => Promise.resolve({ remove: vi.fn() })) } }));
|
||||
vi.mock('../../native/appLock', () => ({
|
||||
RELOCK_AFTER_MS: 30_000,
|
||||
isAppLockEnabled: vi.fn(),
|
||||
unlockApp: vi.fn(),
|
||||
}));
|
||||
|
||||
function stateListener(): (state: { isActive: boolean }) => void {
|
||||
const call = vi.mocked(App.addListener).mock.calls.find(([name]) => name === 'appStateChange');
|
||||
if (!call) throw new Error('no appStateChange listener');
|
||||
return call[1] as unknown as (state: { isActive: boolean }) => void;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(isAppLockEnabled).mockReturnValue(true);
|
||||
vi.mocked(unlockApp).mockResolvedValue(false);
|
||||
});
|
||||
|
||||
describe('AppLockGate', () => {
|
||||
it('covers the app at launch and asks at once; a successful unlock lifts it', async () => {
|
||||
render(<AppLockGate />);
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
await waitFor(() => expect(unlockApp).toHaveBeenCalledTimes(1));
|
||||
|
||||
vi.mocked(unlockApp).mockResolvedValue(true);
|
||||
fireEvent.click(screen.getByRole('button'));
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
});
|
||||
|
||||
it('locks again after half a minute in the background, not after a glance away', async () => {
|
||||
vi.mocked(unlockApp).mockResolvedValue(true);
|
||||
const now = vi.spyOn(Date, 'now');
|
||||
render(<AppLockGate />);
|
||||
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
|
||||
|
||||
vi.mocked(unlockApp).mockResolvedValue(false);
|
||||
now.mockReturnValue(1_000);
|
||||
act(() => stateListener()({ isActive: false }));
|
||||
now.mockReturnValue(10_000);
|
||||
act(() => stateListener()({ isActive: true }));
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
|
||||
|
||||
act(() => stateListener()({ isActive: false }));
|
||||
now.mockReturnValue(60_000);
|
||||
act(() => stateListener()({ isActive: true }));
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument();
|
||||
now.mockRestore();
|
||||
});
|
||||
|
||||
it('is nothing while the lock is off', () => {
|
||||
vi.mocked(isAppLockEnabled).mockReturnValue(false);
|
||||
const { container } = render(<AppLockGate />);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
expect(unlockApp).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* AppLockGate: covers TREK until Face ID, Touch ID or the passcode unlocks it,
|
||||
* when the app lock is on (native/appLock.ts). It locks at launch and again
|
||||
* after the app spent more than half a minute in the background, and asks at
|
||||
* once rather than waiting for a tap; the button is there for a second try.
|
||||
* Rendered once in App; outside the app, or with the lock off, it is nothing.
|
||||
*/
|
||||
import { App } from '@capacitor/app';
|
||||
import { Lock } from 'lucide-react';
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { RELOCK_AFTER_MS, isAppLockEnabled, unlockApp } from '../../native/appLock';
|
||||
import { useNativeCapabilities } from '../../native/capabilities';
|
||||
|
||||
export default function AppLockGate(): React.ReactElement | null {
|
||||
const { t } = useTranslation();
|
||||
// Re-read once the binary has said what it can do.
|
||||
const { caps } = useNativeCapabilities();
|
||||
const [locked, setLocked] = useState(false);
|
||||
const asking = useRef(false);
|
||||
const backgroundSince = useRef<number | null>(null);
|
||||
|
||||
const ask = useCallback(async () => {
|
||||
if (asking.current) return;
|
||||
asking.current = true;
|
||||
const ok = await unlockApp(t('native.lock.reason'));
|
||||
asking.current = false;
|
||||
if (ok) setLocked(false);
|
||||
}, [t]);
|
||||
|
||||
// At launch, once the capabilities are known.
|
||||
useEffect(() => {
|
||||
if (!isAppLockEnabled()) return;
|
||||
setLocked(true);
|
||||
void ask();
|
||||
}, [caps, ask]);
|
||||
|
||||
// Back from the background after a while.
|
||||
useEffect(() => {
|
||||
if (!isAppLockEnabled()) return;
|
||||
const listener = App.addListener('appStateChange', ({ isActive }) => {
|
||||
if (!isActive) {
|
||||
backgroundSince.current = Date.now();
|
||||
return;
|
||||
}
|
||||
const since = backgroundSince.current;
|
||||
backgroundSince.current = null;
|
||||
if (since != null && Date.now() - since > RELOCK_AFTER_MS) {
|
||||
setLocked(true);
|
||||
void ask();
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
void listener.then((handle) => handle.remove());
|
||||
};
|
||||
}, [caps, ask]);
|
||||
|
||||
if (!locked) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t('native.lock.title')}
|
||||
className="fixed inset-0 z-[100001] flex flex-col items-center justify-center gap-5 bg-surface p-8 text-center backdrop-blur-2xl"
|
||||
>
|
||||
<span className="flex h-16 w-16 items-center justify-center rounded-full bg-surface-card text-content shadow-lg">
|
||||
<Lock size={26} strokeWidth={2} aria-hidden="true" />
|
||||
</span>
|
||||
<p className="text-title font-semibold text-content">{t('native.lock.title')}</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void ask()}
|
||||
className="rounded-full bg-accent px-6 py-3 text-body font-semibold text-accent-text transition-transform active:scale-[.98]"
|
||||
>
|
||||
{t('native.lock.unlock')}
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { fireEvent, render, screen, waitFor } from '../../../../tests/helpers/render';
|
||||
import {
|
||||
appLockSupported,
|
||||
biometryAvailable,
|
||||
isAppLockEnabled,
|
||||
setAppLockEnabled,
|
||||
unlockApp,
|
||||
} from '../../../native/appLock';
|
||||
import MAppLockCard from './MAppLockCard';
|
||||
|
||||
vi.mock('../../../native/appLock', () => ({
|
||||
appLockSupported: vi.fn(),
|
||||
biometryAvailable: vi.fn(),
|
||||
isAppLockEnabled: vi.fn(),
|
||||
setAppLockEnabled: vi.fn(async () => {}),
|
||||
unlockApp: vi.fn(),
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(appLockSupported).mockReturnValue(true);
|
||||
vi.mocked(biometryAvailable).mockResolvedValue({ available: true, type: 'faceID' });
|
||||
vi.mocked(isAppLockEnabled).mockReturnValue(false);
|
||||
vi.mocked(unlockApp).mockResolvedValue(true);
|
||||
});
|
||||
|
||||
describe('MAppLockCard', () => {
|
||||
it('turns the lock on only after one successful unlock', async () => {
|
||||
render(<MAppLockCard />);
|
||||
const toggle = await screen.findByRole('switch');
|
||||
vi.mocked(unlockApp).mockResolvedValueOnce(false);
|
||||
fireEvent.click(toggle);
|
||||
await waitFor(() => expect(unlockApp).toHaveBeenCalledTimes(1));
|
||||
expect(setAppLockEnabled).not.toHaveBeenCalled();
|
||||
|
||||
fireEvent.click(toggle);
|
||||
await waitFor(() => expect(setAppLockEnabled).toHaveBeenCalledWith(true));
|
||||
});
|
||||
|
||||
it('turns it off without asking', async () => {
|
||||
vi.mocked(isAppLockEnabled).mockReturnValue(true);
|
||||
render(<MAppLockCard />);
|
||||
fireEvent.click(await screen.findByRole('switch'));
|
||||
await waitFor(() => expect(setAppLockEnabled).toHaveBeenCalledWith(false));
|
||||
expect(unlockApp).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('is not offered on a device without Face ID, Touch ID or a passcode', async () => {
|
||||
vi.mocked(biometryAvailable).mockResolvedValue({ available: false, type: 'none' });
|
||||
const { container } = render(<MAppLockCard />);
|
||||
await waitFor(() => expect(biometryAvailable).toHaveBeenCalled());
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import { ScanFace } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import {
|
||||
appLockSupported,
|
||||
biometryAvailable,
|
||||
isAppLockEnabled,
|
||||
setAppLockEnabled,
|
||||
unlockApp,
|
||||
} from '../../../native/appLock';
|
||||
import MToggle from '../../components/MToggle';
|
||||
import { MSetCard, MSetRow } from './MSettingsUi';
|
||||
|
||||
/**
|
||||
* The app lock switch, inside the app on a device that can unlock with Face ID,
|
||||
* Touch ID or its passcode. Turning it on asks once, so nobody locks themselves
|
||||
* out with a lock that does not work on this phone.
|
||||
*/
|
||||
export default function MAppLockCard() {
|
||||
const { t } = useTranslation();
|
||||
const [available, setAvailable] = useState(false);
|
||||
const [enabled, setEnabled] = useState(isAppLockEnabled);
|
||||
|
||||
useEffect(() => {
|
||||
if (!appLockSupported()) return;
|
||||
void biometryAvailable().then((info) => setAvailable(info.available));
|
||||
}, []);
|
||||
|
||||
if (!available) return null;
|
||||
|
||||
const toggle = async () => {
|
||||
if (enabled) {
|
||||
await setAppLockEnabled(false);
|
||||
setEnabled(false);
|
||||
return;
|
||||
}
|
||||
if (!(await unlockApp(t('native.lock.reason')))) return;
|
||||
await setAppLockEnabled(true);
|
||||
setEnabled(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<MSetCard title={t('native.lock.settingTitle')} icon={ScanFace} className="mt-3">
|
||||
<div className="-mt-[4px]">
|
||||
<MSetRow
|
||||
first
|
||||
label={t('native.lock.setting')}
|
||||
sub={t('native.lock.settingHint')}
|
||||
trailing={<MToggle checked={enabled} onChange={() => void toggle()} ariaLabel={t('native.lock.setting')} />}
|
||||
/>
|
||||
</div>
|
||||
</MSetCard>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { useTranslation } from '../../../i18n'
|
||||
import { MSetCard, MSetEyebrow, MSetInput, MSetButton, MSetHint } from './MSettingsUi'
|
||||
import MConfirmSheet from './MConfirmSheet'
|
||||
import MAppLockCard from './MAppLockCard'
|
||||
import PasswordChecklist from '../../../components/shared/PasswordChecklist'
|
||||
import { fmtDate, usePasskeys } from '../../../components/Settings/usePasskeys'
|
||||
import { stripTrailingSlashes, useAccountSettings } from '../../../components/Settings/useAccountSettings'
|
||||
@@ -179,6 +180,9 @@ export default function MSettingsAccount() {
|
||||
)}
|
||||
|
||||
{/* ── Two-factor authentication ───────────────────────────── */}
|
||||
{/* The app lock, inside the app only (Face ID, Touch ID or the passcode). */}
|
||||
<MAppLockCard />
|
||||
|
||||
<MSetCard title={t('settings.mfa.title')} icon={KeyRound} className="mt-3">
|
||||
{mfaRequiredByPolicy && (
|
||||
<div className="mb-3 flex gap-2 rounded-xl border border-[color:var(--m-rowbr)] bg-[color:var(--m-ic)] p-3">
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { appLockSupported, biometryAvailable, isAppLockEnabled, setAppLockEnabled, unlockApp } from './appLock';
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { isNativeApp } from './platform';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
vi.mock('./platform', () => ({ isNativeApp: vi.fn() }));
|
||||
vi.mock('./capabilities', () => ({ hasNativeFeature: vi.fn() }));
|
||||
vi.mock('./trekShell', () => ({
|
||||
TrekShell: { setPrivacyCover: vi.fn(), biometryInfo: vi.fn(), authenticateBiometric: vi.fn() },
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear();
|
||||
vi.mocked(isNativeApp).mockReturnValue(true);
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(true);
|
||||
vi.mocked(TrekShell.setPrivacyCover).mockReset().mockResolvedValue();
|
||||
vi.mocked(TrekShell.biometryInfo).mockReset().mockResolvedValue({ available: true, type: 'faceID' });
|
||||
vi.mocked(TrekShell.authenticateBiometric).mockReset().mockResolvedValue({ ok: true });
|
||||
});
|
||||
|
||||
describe('appLock', () => {
|
||||
it('is only offered in a binary with the feature', () => {
|
||||
expect(appLockSupported()).toBe(true);
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(false);
|
||||
expect(appLockSupported()).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps the switch on the device and tells the native side for the app-switcher cover', async () => {
|
||||
expect(isAppLockEnabled()).toBe(false);
|
||||
await setAppLockEnabled(true);
|
||||
expect(isAppLockEnabled()).toBe(true);
|
||||
expect(TrekShell.setPrivacyCover).toHaveBeenLastCalledWith({ enabled: true });
|
||||
await setAppLockEnabled(false);
|
||||
expect(isAppLockEnabled()).toBe(false);
|
||||
expect(TrekShell.setPrivacyCover).toHaveBeenLastCalledWith({ enabled: false });
|
||||
});
|
||||
|
||||
it('reads off as off without the feature, whatever is stored', async () => {
|
||||
await setAppLockEnabled(true);
|
||||
vi.mocked(hasNativeFeature).mockReturnValue(false);
|
||||
expect(isAppLockEnabled()).toBe(false);
|
||||
expect(await biometryAvailable()).toEqual({ available: false, type: 'none' });
|
||||
});
|
||||
|
||||
it('unlocks on success and stays locked on a cancel or a failure', async () => {
|
||||
expect(await unlockApp('Unlock TREK')).toBe(true);
|
||||
vi.mocked(TrekShell.authenticateBiometric).mockRejectedValue({ code: 'CANCELLED' });
|
||||
expect(await unlockApp('Unlock TREK')).toBe(false);
|
||||
vi.mocked(TrekShell.authenticateBiometric).mockRejectedValue({ code: 'FAILED' });
|
||||
expect(await unlockApp('Unlock TREK')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
import { hasNativeFeature } from './capabilities';
|
||||
import { isNativeApp } from './platform';
|
||||
import { reportNativeFailure } from './reportFailure';
|
||||
import { TrekShell } from './trekShell';
|
||||
|
||||
/**
|
||||
* The app lock: Face ID, Touch ID or the device passcode before TREK shows
|
||||
* anything, at launch and after a while in the background, with a blurred
|
||||
* cover in the app switcher meanwhile.
|
||||
*
|
||||
* The setting belongs to the device, not the account (another phone of the
|
||||
* same user may well not want it), so it lives in local storage, and the
|
||||
* native side keeps its own copy for the app-switcher cover, which has to be
|
||||
* up before the UI could run.
|
||||
*/
|
||||
const KEY = 'trek.appLock';
|
||||
/** Back from the background after this long, the app asks again. */
|
||||
export const RELOCK_AFTER_MS = 30_000;
|
||||
|
||||
export function appLockSupported(): boolean {
|
||||
return isNativeApp() && hasNativeFeature('biometricLock');
|
||||
}
|
||||
|
||||
export function isAppLockEnabled(): boolean {
|
||||
if (!appLockSupported()) return false;
|
||||
try {
|
||||
return window.localStorage.getItem(KEY) === '1';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function setAppLockEnabled(enabled: boolean): Promise<void> {
|
||||
try {
|
||||
if (enabled) window.localStorage.setItem(KEY, '1');
|
||||
else window.localStorage.removeItem(KEY);
|
||||
} catch {
|
||||
// Storage refused: the lock then stays off, which the toggle shows.
|
||||
}
|
||||
await TrekShell.setPrivacyCover({ enabled }).catch(reportNativeFailure);
|
||||
}
|
||||
|
||||
export async function biometryAvailable(): Promise<{ available: boolean; type: string }> {
|
||||
if (!appLockSupported()) return { available: false, type: 'none' };
|
||||
try {
|
||||
return await TrekShell.biometryInfo();
|
||||
} catch (err) {
|
||||
reportNativeFailure(err);
|
||||
return { available: false, type: 'none' };
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks for Face ID, Touch ID or the passcode. True once unlocked. */
|
||||
export async function unlockApp(reason: string): Promise<boolean> {
|
||||
try {
|
||||
await TrekShell.authenticateBiometric({ reason });
|
||||
return true;
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string } | null)?.code;
|
||||
if (code !== 'CANCELLED' && code !== 'FAILED') reportNativeFailure(err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,12 @@ export interface TrekShellPlugin {
|
||||
getTileCacheUsage(): Promise<{ bytes: number; limit: number }>;
|
||||
/** iOS, feature tileCache: empties the map tile store. */
|
||||
clearTileCache(): Promise<void>;
|
||||
/** Feature biometricLock: which biometry the device offers for the app lock. */
|
||||
biometryInfo(): Promise<{ available: boolean; type: string }>;
|
||||
/** Feature biometricLock: Face ID, Touch ID or the passcode. Rejects with CANCELLED or FAILED. */
|
||||
authenticateBiometric(options: { reason: string }): Promise<{ ok: true }>;
|
||||
/** Feature biometricLock: a blurred cover in the app switcher while the lock is on. */
|
||||
setPrivacyCover(options: { enabled: boolean }): Promise<void>;
|
||||
}
|
||||
|
||||
export const TrekShell = registerPlugin<TrekShellPlugin>('TrekShell');
|
||||
|
||||
Reference in New Issue
Block a user