Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Update mobile app QR unlock models and flow (#2159)

Leendert de Borstee6f48e458a4
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
index 82aae5459..25890754b 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/NativeVaultManager.kt
@@ -389,9 +389,9 @@ class NativeVaultManager(reactContext: ReactApplicationContext) :
* @param promise The promise to resolve
*/
@ReactMethod
- override fun encryptDecryptionKeyForMobileLogin(publicKeyJWK: String, promise: Promise) {
+ override fun encryptUnlockKeyForMobileLogin(publicKeyJWK: String, promise: Promise) {
try {
- val encryptedKey = vaultStore.encryptDecryptionKeyForMobileLogin(publicKeyJWK)
+ val encryptedKey = vaultStore.encryptUnlockKeyForMobileLogin(publicKeyJWK)
promise.resolve(encryptedKey)
} catch (e: Exception) {
Log.e(TAG, "Error encrypting key for mobile login", e)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
index f79798e5b..9a1fc42db 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultCrypto.kt
@@ -455,7 +455,7 @@ class VaultCrypto(
* Encrypts the unlock key using an RSA public key for mobile login. The receiving
* client opens the account key chain with it, exactly as after a password login.
*/
- fun encryptDecryptionKeyForMobileLogin(publicKeyJWK: String, authMethods: String): String {
+ fun encryptUnlockKeyForMobileLogin(publicKeyJWK: String, authMethods: String): String {
var result: String? = null
var error: Exception? = null
val latch = java.util.concurrent.CountDownLatch(1)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
index 64da5ac0c..33b4039dd 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultStore.kt
@@ -265,8 +265,8 @@ class VaultStore(
/**
* Encrypts the unlock key using an RSA public key for mobile login.
*/
- fun encryptDecryptionKeyForMobileLogin(publicKeyJWK: String): String {
- return crypto.encryptDecryptionKeyForMobileLogin(publicKeyJWK, auth.getAuthMethods())
+ fun encryptUnlockKeyForMobileLogin(publicKeyJWK: String): String {
+ return crypto.encryptUnlockKeyForMobileLogin(publicKeyJWK, auth.getAuthMethods())
}
/**
diff --git a/apps/mobile-app/app/(tabs)/settings/_layout.tsx b/apps/mobile-app/app/(tabs)/settings/_layout.tsx
index 32a8307fb..0871b1c1d 100644
--- a/apps/mobile-app/app/(tabs)/settings/_layout.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/_layout.tsx
@@ -174,7 +174,7 @@ export default function SettingsLayout(): React.ReactNode {
}}
/>
<Stack.Screen
- name="mobile-unlock/[id]"
+ name="mobile-unlock/confirm"
options={{
title: t('settings.qrScanner.mobileLogin.confirmTitle'),
...defaultHeaderOptions,
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
deleted file mode 100644
index fb2e4667f..000000000
--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/[id].tsx
+++ /dev/null
@@ -1,272 +0,0 @@
-import { router, useLocalSearchParams } from 'expo-router';
-import { useState, useEffect } from 'react';
-import { View, StyleSheet } from 'react-native';
-import { useSafeAreaInsets } from 'react-native-safe-area-context';
-
-import EncryptionUtility from '@/utils/EncryptionUtility';
-import { VaultUnlockHelper } from '@/utils/VaultUnlockHelper';
-
-import { useColors } from '@/hooks/useColorScheme';
-import { useTranslation } from '@/hooks/useTranslation';
-
-import LoadingIndicator from '@/components/LoadingIndicator';
-import { ThemedButton } from '@/components/themed/ThemedButton';
-import { ThemedContainer } from '@/components/themed/ThemedContainer';
-import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
-import { ThemedText } from '@/components/themed/ThemedText';
-import { UsernameDisplay } from '@/components/ui/UsernameDisplay';
-import { useDialog } from '@/context/DialogContext';
-import { useWebApi } from '@/context/WebApiContext';
-import NativeVaultManager from '@/specs/NativeVaultManager';
-
-/**
- * QR Code confirmation screen for mobile login.
- */
-export default function MobileUnlockConfirmScreen() : React.ReactNode {
- const colors = useColors();
- const { t } = useTranslation();
- const { showAlert } = useDialog();
- const webApi = useWebApi();
- const insets = useSafeAreaInsets();
- const { id, pk } = useLocalSearchParams<{ id: string; pk?: string }>();
- const [isProcessing, setIsProcessing] = useState(false);
- const [isValidating, setIsValidating] = useState(true);
-
- /*
- * Validate request on component mount
- */
- useEffect(() => {
- if (!id) {
- showAlert(t('common.error'), t('common.errors.unknownErrorTryAgain'), () => router.back());
- return;
- }
-
- /**
- * Validate the mobile login request.
- */
- const validateRequest = async () : Promise<void> => {
- try {
- // Check server version compatibility first
- const isVersionSupported = await NativeVaultManager.isServerVersionGreaterThanOrEqualTo('0.25.0');
-
- if (!isVersionSupported) {
- showAlert(t('common.error'), t('common.errors.serverVersionTooOld'), () => router.back());
- return;
- }
-
- // Validate the request exists by fetching from server
- await webApi.authFetch<{ clientPublicKey: string }>(
- `auth/mobile-login/request/${id}`,
- { method: 'GET' }
- );
-
- // Request is valid
- setIsValidating(false);
- } catch (error) {
- console.error('Request validation error:', error);
- let errorMsg = t('common.errors.unknownErrorTryAgain');
-
- if (error instanceof Error && error.message.includes('404')) {
- errorMsg = t('settings.qrScanner.mobileLogin.requestExpired');
- }
-
- showAlert(t('common.error'), errorMsg, () => router.back());
- }
- };
-
- validateRequest();
- }, [id, webApi, showAlert, t]);
-
- /**
- * Handle mobile login QR code.
- * @param requestId - The request ID from the QR code
- * @param expectedPublicKeyHash - Optional public key hash from QR code for security verification
- */
- const handleMobileLogin = async (requestId: string, expectedPublicKeyHash?: string) : Promise<void> => {
- try {
- // Fetch the public key from server
- const response = await webApi.authFetch<{ clientPublicKey: string }>(
- `auth/mobile-login/request/${requestId}`,
- { method: 'GET' }
- );
-
- const publicKeyJWK = response.clientPublicKey;
-
- /*
- * Security verification: if QR code contained a public key hash, verify it matches what
- * the server provided.
- */
- if (expectedPublicKeyHash) {
- const computedHash = await EncryptionUtility.computeSha256Hash(publicKeyJWK);
- if (computedHash !== expectedPublicKeyHash) {
- console.error('Public key hash mismatch - possible security attack');
- throw new Error('PUBLIC_KEY_MISMATCH');
- }
- }
- /*
- * TODO: In v1.0+, remove backwards compatibility and require public key hash verification
- * for all QR codes.
- */
- // Encrypt the decryption key using native module
- const encryptedKey = await NativeVaultManager.encryptDecryptionKeyForMobileLogin(publicKeyJWK);
-
- // Submit the encrypted key to the server
- await webApi.authFetch(
- 'auth/mobile-login/submit',
- {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- requestId: requestId,
- encryptedDecryptionKey: encryptedKey,
- }),
- }
- );
-
- // Success! Navigate to result page
- router.replace({
- pathname: '/(tabs)/settings/mobile-unlock/result',
- params: {
- success: 'true',
- message: t('settings.qrScanner.mobileLogin.successDescription'),
- },
- });
- } catch (error) {
- console.error('Mobile login error:', error);
-
- // Error! Navigate to result page
- router.replace({
- pathname: '/(tabs)/settings/mobile-unlock/result',
- params: {
- success: 'false',
- message: t('common.errors.unknownErrorTryAgain'),
- },
- });
- }
- };
-
- /**
- * Handle confirmation - authenticate user first, then process the scanned QR code.
- */
- const handleConfirm = async () : Promise<void> => {
- if (!id) {
- return;
- }
-
- setIsProcessing(true);
-
- try {
- // Re-auth user for mobile login confirm if user has not authenticated within the last 10 seconds.
- const authenticated = await VaultUnlockHelper.authenticateForAction(
- t('settings.qrScanner.mobileLogin.confirmTitle'),
- t('settings.qrScanner.mobileLogin.confirmSubtitle'),
- null,
- null,
- 10
- );
-
- if (!authenticated) {
- setIsProcessing(false);
- return;
- }
-
- // Process the mobile login with optional public key hash verification
- await handleMobileLogin(id as string, pk);
- } catch (error) {
- console.error('Authentication or QR code processing error:', error);
- showAlert(t('common.error'), error instanceof Error ? error.message : t('common.errors.unknownError'));
- } finally {
- setIsProcessing(false);
- }
- };
-
- /**
- * Handle dismiss - navigate to settings tab.
- * Uses replace to handle cases where this page is the first in the navigation stack (deep link).
- */
- const handleDismiss = () : void => {
- router.replace('/(tabs)/settings');
- };
-
- const styles = StyleSheet.create({
- confirmationContainer: {
- alignItems: 'center',
- flex: 1,
- justifyContent: 'center',
- padding: 20,
- },
- confirmationTitle: {
- fontSize: 24,
- fontWeight: 'bold',
- marginBottom: 20,
- textAlign: 'center',
- },
- confirmationText: {
- fontSize: 16,
- lineHeight: 24,
- marginBottom: 16,
- textAlign: 'center',
- },
- usernameDisplayContainer: {
- marginBottom: 12,
- width: '100%',
- },
- buttonContainer: {
- gap: 12,
- marginTop: 20,
- paddingBottom: insets.bottom + 80,
- paddingHorizontal: 20,
- },
- button: {
- width: '100%',
- },
- cancelButton: {
- backgroundColor: colors.secondary,
- },
- });
-
- // Show loading during validation or processing
- if (isValidating || isProcessing) {
- return (
- <ThemedContainer>
- <View style={styles.confirmationContainer}>
- <LoadingIndicator />
- </View>
- </ThemedContainer>
- );
- }
-
- // Show confirmation screen
- return (
- <ThemedContainer>
- <ThemedScrollView contentContainerStyle={{ flexGrow: 1 }}>
- <View style={styles.confirmationContainer}>
- <ThemedText style={styles.confirmationTitle}>
- {t('settings.qrScanner.mobileLogin.confirmTitle')}
- </ThemedText>
- <ThemedText style={styles.confirmationText}>
- {t('settings.qrScanner.mobileLogin.confirmMessage')}
- </ThemedText>
- <View style={styles.usernameDisplayContainer}>
- <UsernameDisplay />
- </View>
- </View>
-
- <View style={styles.buttonContainer}>
- <ThemedButton
- title={t('common.confirm')}
- onPress={handleConfirm}
- style={styles.button}
- />
- <ThemedButton
- title={t('common.cancel')}
- onPress={handleDismiss}
- style={StyleSheet.flatten([styles.button, styles.cancelButton])}
- />
- </View>
- </ThemedScrollView>
- </ThemedContainer>
- );
-}
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
new file mode 100644
index 000000000..7fad52e39
--- /dev/null
+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/confirm.tsx
@@ -0,0 +1,352 @@
+import { ApiRequestError } from '@aliasvault/client/api/errors/ApiRequestError';
+import { MobileLoginProtocol } from '@aliasvault/client/auth/MobileLoginProtocol';
+import { Ionicons } from '@expo/vector-icons';
+import { router } from 'expo-router';
+import { useState, useEffect, useRef } from 'react';
+import { View, StyleSheet } from 'react-native';
+import { useSafeAreaInsets } from 'react-native-safe-area-context';
+
+import { MobileLoginScanHandoff, type PendingMobileLoginRequest } from '@/utils/MobileLoginScanHandoff';
+import { VaultUnlockHelper } from '@/utils/VaultUnlockHelper';
+
+import { useColors } from '@/hooks/useColorScheme';
+import { useTranslation } from '@/hooks/useTranslation';
+
+import LoadingIndicator from '@/components/LoadingIndicator';
+import { ThemedContainer } from '@/components/themed/ThemedContainer';
+import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
+import { ThemedText } from '@/components/themed/ThemedText';
+import { AccountChip } from '@/components/ui/AccountChip';
+import { RobustPressable } from '@/components/ui/RobustPressable';
+import { useDialog } from '@/context/DialogContext';
+import { useWebApi } from '@/context/WebApiContext';
+import NativeVaultManager from '@/specs/NativeVaultManager';
+
+import type { MobileLoginDetailsResponse, MobileLoginRequestReference, MobileLoginSubmitRequest } from '@aliasvault/models/webapi';
+
+/**
+ * A mobile login request whose public key was checked against the scanned QR code.
+ */
+type VerifiedRequest = {
+ details: MobileLoginDetailsResponse;
+ verificationCode: string;
+ codeChoices: string[];
+}
+
+const CODE_CHOICE_COUNT = 4;
+
+const RECENT_UNLOCK_GRACE_SECONDS = 10;
+
+/**
+ * The numbers the user picks from, which includes the real code as well as fakes that are shown on the originating device's screen,
+ * this requires the user to visually verify the originating device with the mobile app unlock attempt.
+ */
+function buildCodeChoices(verificationCode: string) : string[] {
+ const choices = new Set([verificationCode]);
+ while (choices.size < CODE_CHOICE_COUNT) {
+ const fake = Math.floor(Math.random() * 10 ** MobileLoginProtocol.VERIFICATION_CODE_LENGTH);
+ choices.add(fake.toString().padStart(MobileLoginProtocol.VERIFICATION_CODE_LENGTH, '0'));
+ }
+ return [...choices].sort(() => Math.random() - 0.5);
+}
+
+/**
+ * Show the result page.
+ */
+function showResult(success: boolean, reason?: 'codeMismatch') : void {
+ router.replace({
+ pathname: '/(tabs)/settings/mobile-unlock/result',
+ params: { success: success ? 'true' : 'false', ...(reason ? { reason } : {}) },
+ });
+}
+
+/**
+ * Confirmation screen for a mobile login request.
+ */
+export default function MobileUnlockConfirmScreen() : React.ReactNode {
+ const colors = useColors();
+ const { t } = useTranslation();
+ const { showAlert } = useDialog();
+ const webApi = useWebApi();
+ const insets = useSafeAreaInsets();
+ const [scan] = useState<PendingMobileLoginRequest | null>(() => MobileLoginScanHandoff.take());
+ const [request, setRequest] = useState<VerifiedRequest | null>(null);
+ const [isProcessing, setIsProcessing] = useState(false);
+ const hasLoadedRequest = useRef(false);
+
+ /*
+ * Load the request and verify its public key on mount.
+ */
+ useEffect(() => {
+ if (hasLoadedRequest.current) {
+ return;
+ }
+ hasLoadedRequest.current = true;
+
+ if (!scan) {
+ // Opened without a pending request, e.g. through a plain route link. There is nothing to approve.
+ router.replace('/(tabs)/settings');
+ return;
+ }
+
+ /**
+ * Fetch the request and accept it only when its public key is the one the QR code was made for.
+ */
+ const loadRequest = async () : Promise<void> => {
+ try {
+ const details = await webApi.post<MobileLoginRequestReference, MobileLoginDetailsResponse>('auth/mobile-login/details', { requestId: scan.requestId });
+
+ if (!await MobileLoginProtocol.isExpectedPublicKey(details.clientPublicKey, scan.publicKeyHash)) {
+ console.error('Mobile login public key does not match the scanned QR code');
+ showResult(false);
+ return;
+ }
+
+ const verificationCode = await MobileLoginProtocol.computeVerificationCode(details.clientPublicKey);
+ setRequest({ details, verificationCode, codeChoices: buildCodeChoices(verificationCode) });
+ } catch (error) {
+ console.error('Mobile login request validation error:', error);
+ const isExpired = error instanceof ApiRequestError && error.statusCode === 404;
+ showAlert(t('common.error'), isExpired ? t('settings.qrScanner.mobileLogin.requestExpired') : t('common.errors.unknownErrorTryAgain'), () => router.replace('/(tabs)/settings'));
+ }
+ };
+
+ loadRequest();
+ }, [scan, webApi, showAlert, t]);
+
+ /**
+ * Decline the request.
+ */
+ const declineRequest = async () : Promise<void> => {
+ if (!scan) {
+ return;
+ }
+ try {
+ await webApi.post<MobileLoginRequestReference, void>('auth/mobile-login/decline', { requestId: scan.requestId }, false);
+ } catch (error) {
+ console.error('Failed to decline mobile login request:', error);
+ }
+ };
+
+ /**
+ * Handle a tapped number: check it, re-authenticate the user, then hand over the unlock key.
+ */
+ const handleCodeChoice = async (chosenCode: string) : Promise<void> => {
+ if (!scan || !request) {
+ return;
+ }
+
+ setIsProcessing(true);
+
+ try {
+ // A wrong confirmation number results in a automatic decline for the mobile login request attempt.
+ if (chosenCode !== request.verificationCode) {
+ await declineRequest();
+ showResult(false, 'codeMismatch');
+ return;
+ }
+
+ const authenticated = await VaultUnlockHelper.authenticateForAction(
+ t('settings.qrScanner.mobileLogin.confirmTitle'),
+ t('settings.qrScanner.mobileLogin.confirmSubtitle'),
+ null,
+ null,
+ RECENT_UNLOCK_GRACE_SECONDS
+ );
+
+ if (!authenticated) {
+ return;
+ }
+
+ // Encrypt with the public key that was verified against the QR code.
+ const encryptedUnlockKey = await NativeVaultManager.encryptUnlockKeyForMobileLogin(request.details.clientPublicKey);
+ await webApi.post<MobileLoginSubmitRequest, void>('auth/mobile-login/submit', { requestId: scan.requestId, encryptedUnlockKey }, false);
+
+ showResult(true);
+ } catch (error) {
+ console.error('Mobile login error:', error);
+ showResult(false);
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ /**
+ * Handle decline: refuse the request and return to settings.
+ */
+ const handleDecline = async () : Promise<void> => {
+ setIsProcessing(true);
+ await declineRequest();
+ router.replace('/(tabs)/settings');
+ };
+
+ const styles = StyleSheet.create({
+ loadingContainer: {
+ alignItems: 'center',
+ flex: 1,
+ justifyContent: 'center',
+ },
+ content: {
+ alignItems: 'center',
+ flexGrow: 1,
+ paddingBottom: insets.bottom + 80,
+ paddingHorizontal: 6,
+ paddingTop: 8,
+ },
+ accountChip: {
+ marginBottom: 20,
+ },
+ message: {
+ color: colors.textMuted,
+ fontSize: 15,
+ lineHeight: 22,
+ marginBottom: 24,
+ textAlign: 'center',
+ },
+ linkWarning: {
+ alignItems: 'center',
+ backgroundColor: colors.warningBackground,
+ borderRadius: 12,
+ flexDirection: 'row',
+ gap: 12,
+ marginBottom: 16,
+ padding: 12,
+ width: '100%',
+ },
+ linkWarningText: {
+ flex: 1,
+ fontSize: 14,
+ lineHeight: 20,
+ },
+ detailsContainer: {
+ backgroundColor: colors.accentBackground,
+ borderColor: colors.accentBorder,
+ borderRadius: 12,
+ borderWidth: 1,
+ gap: 14,
+ marginBottom: 32,
+ padding: 16,
+ width: '100%',
+ },
+ detailRow: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ gap: 12,
+ },
+ detailText: {
+ flex: 1,
+ fontSize: 15,
+ lineHeight: 20,
+ },
+ codePrompt: {
+ fontSize: 17,
+ fontWeight: '600',
+ lineHeight: 24,
+ marginBottom: 16,
+ textAlign: 'center',
+ },
+ codeChoiceRow: {
+ flexDirection: 'row',
+ gap: 14,
+ justifyContent: 'center',
+ marginBottom: 32,
+ width: '100%',
+ },
+ codeChoice: {
+ alignItems: 'center',
+ aspectRatio: 1,
+ backgroundColor: colors.accentBackground,
+ borderColor: colors.primary,
+ borderRadius: 999,
+ borderWidth: 2,
+ flex: 1,
+ justifyContent: 'center',
+ maxWidth: 72,
+ },
+ codeChoiceText: {
+ fontSize: 24,
+ fontWeight: 'bold',
+ lineHeight: 30,
+ },
+ declineButton: {
+ alignItems: 'center',
+ backgroundColor: colors.destructive + '10',
+ borderColor: colors.destructive,
+ borderRadius: 8,
+ borderWidth: 1,
+ marginTop: 'auto',
+ paddingVertical: 12,
+ width: '100%',
+ },
+ declineButtonText: {
+ color: colors.destructive,
+ fontSize: 16,
+ fontWeight: '500',
+ },
+ });
+
+ // Show loading during validation or processing
+ if (!request || isProcessing) {
+ return (
+ <ThemedContainer>
+ <View style={styles.loadingContainer}>
+ <LoadingIndicator />
+ </View>
+ </ThemedContainer>
+ );
+ }
+
+ const { details } = request;
+ const clientDescription = [details.clientName, [details.browser, details.operatingSystem].filter(Boolean).join(', ')].filter(Boolean).join(' · ');
+ const ipDescription = [details.ipAddress, details.location ? `(${details.location})` : null].filter(Boolean).join(' ');
+
+ // Show confirmation screen
+ return (
+ <ThemedContainer>
+ <ThemedScrollView contentContainerStyle={styles.content}>
+ <AccountChip style={styles.accountChip} />
+ <ThemedText style={styles.message}>
+ {t('settings.qrScanner.mobileLogin.confirmMessage')}
+ </ThemedText>
+ {/* TODO: Show an additional warning if the request was opened from a link (e.g. native camera app) as this could be a phishing attempt. */}
+ {scan?.source === 'link' && (
+ <View style={styles.linkWarning}>
+ <Ionicons name="warning" size={20} color={colors.warning} />
+ <ThemedText style={styles.linkWarningText}>{t('settings.qrScanner.mobileLogin.openedFromLink')}</ThemedText>
+ </View>
+ )}
+ <View style={styles.detailsContainer}>
+ {clientDescription.length > 0 && (
+ <View style={styles.detailRow}>
+ <Ionicons name="desktop-outline" size={20} color={colors.textMuted} />
+ <ThemedText style={styles.detailText}>{clientDescription}</ThemedText>
+ </View>
+ )}
+ {ipDescription.length > 0 && (
+ <View style={styles.detailRow}>
+ <Ionicons name="globe-outline" size={20} color={colors.textMuted} />
+ <ThemedText style={styles.detailText}>{ipDescription}</ThemedText>
+ </View>
+ )}
+ <View style={styles.detailRow}>
+ <Ionicons name="time-outline" size={20} color={colors.textMuted} />
+ <ThemedText style={styles.detailText}>{new Date(details.createdAt).toLocaleTimeString()}</ThemedText>
+ </View>
+ </View>
+ <ThemedText style={styles.codePrompt}>
+ {t('settings.qrScanner.mobileLogin.selectCode')}
+ </ThemedText>
+ <View style={styles.codeChoiceRow}>
+ {request.codeChoices.map(choice => (
+ <RobustPressable key={choice} style={styles.codeChoice} onPress={() => handleCodeChoice(choice)} testID={`mobile-login-code-choice-${choice}`}>
+ <ThemedText style={styles.codeChoiceText}>{choice}</ThemedText>
+ </RobustPressable>
+ ))}
+ </View>
+ <RobustPressable style={styles.declineButton} onPress={handleDecline} testID="mobile-login-decline">
+ <ThemedText style={styles.declineButtonText}>{t('sharing.family.decline')}</ThemedText>
+ </RobustPressable>
+ </ThemedScrollView>
+ </ThemedContainer>
+ );
+}
diff --git a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/result.tsx b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/result.tsx
index f91c8c587..3a6c77c3d 100644
--- a/apps/mobile-app/app/(tabs)/settings/mobile-unlock/result.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/mobile-unlock/result.tsx
@@ -20,10 +20,15 @@ export default function MobileUnlockResultScreen() : React.ReactNode {
const { t } = useTranslation();
const navigation = useNavigation();
const insets = useSafeAreaInsets();
- const { success, message } = useLocalSearchParams<{ success: string; message?: string }>();
+ const { success, reason } = useLocalSearchParams<{ success: string; reason?: string }>();
const isSuccess = success === 'true';
+ let message = isSuccess ? t('settings.qrScanner.mobileLogin.successDescription') : t('common.errors.unknownErrorTryAgain');
+ if (!isSuccess && reason === 'codeMismatch') {
+ message = t('settings.qrScanner.mobileLogin.codeMismatch');
+ }
+
// Set dynamic header title based on success/error state
useEffect(() => {
navigation.setOptions({
@@ -99,9 +104,7 @@ export default function MobileUnlockResultScreen() : React.ReactNode {
: t('common.error')}
</ThemedText>
<ThemedText style={styles.message}>
- {message || (isSuccess
- ? t('settings.qrScanner.mobileLogin.successDescription')
- : t('common.errors.unknownErrorTryAgain'))}
+ {message}
</ThemedText>
</View>
</View>
diff --git a/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx b/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx
index 8e003d908..06cb03086 100644
--- a/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/qr-scanner.tsx
@@ -1,7 +1,10 @@
-import { Href, router, useLocalSearchParams } from 'expo-router';
+import { MobileLoginProtocol } from '@aliasvault/client/auth/MobileLoginProtocol';
+import { router } from 'expo-router';
import { useEffect, useCallback, useRef } from 'react';
import { View, StyleSheet, Platform } from 'react-native';
+import { MobileLoginScanHandoff } from '@/utils/MobileLoginScanHandoff';
+
import { useColors } from '@/hooks/useColorScheme';
import { useTranslation } from '@/hooks/useTranslation';
@@ -11,65 +14,11 @@ import { ThemedText } from '@/components/themed/ThemedText';
import { useDialog } from '@/context/DialogContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
-// QR Code type prefixes
-const QR_CODE_PREFIXES = {
- MOBILE_UNLOCK: 'aliasvault://open/mobile-unlock/',
- /*
- * Future actions:
- * PASSKEY_AUTH: 'aliasvault://open/passkey-auth/',
- * SHARE_CREDENTIAL: 'aliasvault://open/share-credential/',
- */
-} as const;
-
-type QRCodeType = keyof typeof QR_CODE_PREFIXES;
-
-/**
- * Scanned QR code data.
+/*
+ * Prefixes the native scanner accepts. Future actions get their own prefix here, e.g.
+ * 'aliasvault://open/passkey-auth/' or 'aliasvault://open/share-credential/'.
*/
-type ScannedQRCode = {
- type: QRCodeType | null;
- payload: string;
- rawData: string;
- /** Public key hash from QR code for security verification (if present) */
- publicKeyHash?: string;
-}
-
-/**
- * Parse QR code data and determine its type.
- * Extracts public key hash from query parameter if present for security verification.
- */
-function parseQRCode(data: string): ScannedQRCode {
- for (const [type, prefix] of Object.entries(QR_CODE_PREFIXES)) {
- if (data.startsWith(prefix)) {
- const afterPrefix = data.substring(prefix.length);
-
- /*
- * Parse the path and query parameters
- * Format: {requestId} or {requestId}?pk={hash}
- */
- const queryIndex = afterPrefix.indexOf('?');
- let payload: string;
- let publicKeyHash: string | undefined;
-
- if (queryIndex !== -1) {
- payload = afterPrefix.substring(0, queryIndex);
- const queryString = afterPrefix.substring(queryIndex + 1);
- const params = new URLSearchParams(queryString);
- publicKeyHash = params.get('pk') ?? undefined;
- } else {
- payload = afterPrefix;
- }
-
- return {
- type: type as QRCodeType,
- payload,
- rawData: data,
- publicKeyHash,
- };
- }
- }
- return { type: null, payload: data, rawData: data };
-}
+const QR_CODE_PREFIXES = [MobileLoginProtocol.QR_PREFIX];
/**
* General QR code scanner screen for AliasVault.
@@ -78,41 +27,26 @@ export default function QRScannerScreen() : React.ReactNode {
const colors = useColors();
const { t } = useTranslation();
const { showAlert } = useDialog();
- const { url } = useLocalSearchParams<{ url?: string }>();
- const hasProcessedUrl = useRef(false);
- const processedUrls = useRef(new Set<string>());
const hasLaunchedScanner = useRef(false);
/*
- * Handle barcode scanned - parse and navigate to appropriate page.
- * Native scanner already filters by prefix, so we only get AliasVault QR codes here.
- * Validation is handled by the destination page.
+ * Handle a scanned QR code. Only codes read by the in-app camera get here: this screen takes no URL or route
+ * params.
*/
const handleQRCodeScanned = useCallback((data: string) : void => {
- // Prevent processing the same URL multiple times
- if (processedUrls.current.has(data)) {
+ const mobileLoginRequest = MobileLoginProtocol.parseQrPayload(data);
+ if (!mobileLoginRequest) {
+ showAlert(t('common.error'), t('common.errors.unknownErrorTryAgain'), () => router.back());
return;
}
- // Mark this URL as processed
- processedUrls.current.add(data);
-
- // Parse the QR code to determine its type
- const parsedData = parseQRCode(data);
-
/*
- * Navigate to the appropriate page based on QR code type
- * Use push instead of replace to navigate while scanner is still dismissing
- * This creates a smoother transition without returning to settings first
+ * Hand the request over in memory. Use push instead of replace to navigate while the scanner is still
+ * dismissing, which gives a smoother transition without returning to settings first.
*/
- if (parsedData.type === 'MOBILE_UNLOCK') {
- // Pass public key hash as query parameter if present for security verification
- const route = parsedData.publicKeyHash
- ? `/(tabs)/settings/mobile-unlock/${parsedData.payload}?pk=${parsedData.publicKeyHash}`
- : `/(tabs)/settings/mobile-unlock/${parsedData.payload}`;
- router.push(route as Href);
- }
- }, []);
+ MobileLoginScanHandoff.set(mobileLoginRequest, 'scan');
+ router.push('/(tabs)/settings/mobile-unlock/confirm');
+ }, [showAlert, t]);
/**
* Launch the native QR scanner.
@@ -126,9 +60,8 @@ export default function QRScannerScreen() : React.ReactNode {
try {
// Pass prefixes to native scanner for filtering and translated status text
- const prefixes = Object.values(QR_CODE_PREFIXES);
const statusText = t('settings.qrScanner.scanningMessage');
- const scannedData = await NativeVaultManager.scanQRCode(prefixes, statusText);
+ const scannedData = await NativeVaultManager.scanQRCode(QR_CODE_PREFIXES, statusText);
if (scannedData) {
handleQRCodeScanned(scannedData);
@@ -142,23 +75,6 @@ export default function QRScannerScreen() : React.ReactNode {
}
}, [handleQRCodeScanned, showAlert, t]);
- /**
- * Reset hasProcessedUrl when URL changes to allow processing new URLs.
- */
- useEffect(() => {
- hasProcessedUrl.current = false;
- }, [url]);
-
- /**
- * Handle QR code URL passed from deep link (e.g., from native camera).
- */
- useEffect(() => {
- if (url && typeof url === 'string' && !hasProcessedUrl.current) {
- hasProcessedUrl.current = true;
- handleQRCodeScanned(url);
- }
- }, [url, handleQRCodeScanned]);
-
/**
* Launch scanner when component mounts (Android/iOS only).
*/
diff --git a/apps/mobile-app/app/open/[...path].tsx b/apps/mobile-app/app/open/[...path].tsx
index 83c482cd5..cfbccf74a 100644
--- a/apps/mobile-app/app/open/[...path].tsx
+++ b/apps/mobile-app/app/open/[...path].tsx
@@ -30,7 +30,7 @@ function buildHref(target: ResolvedTarget): Href {
* URL structure: aliasvault://open/[action]/[...params]
*
* Supported actions:
- * - mobile-unlock/[requestId] - Mobile device unlock via QR code
+ * - mobile-unlock/[requestId]?pk=[hash] - Opens the mobile login confirmation.
* - __debug__/set-offline/[true|false] - (DEV only) Toggle offline mode for E2E testing
* - __debug__/set-api-url/[encoded-url] - (DEV only) Set API URL for E2E testing
*
diff --git a/apps/mobile-app/components/ui/AccountChip.tsx b/apps/mobile-app/components/ui/AccountChip.tsx
new file mode 100644
index 000000000..e0a76ecd1
--- /dev/null
+++ b/apps/mobile-app/components/ui/AccountChip.tsx
@@ -0,0 +1,50 @@
+import { StyleSheet, View, type StyleProp, type ViewStyle } from 'react-native';
+
+import { useColors } from '@/hooks/useColorScheme';
+
+import { ThemedText } from '@/components/themed/ThemedText';
+import { useAuth } from '@/context/AuthContext';
+
+import { Avatar } from './Avatar';
+
+type AccountChipProps = {
+ style?: StyleProp<ViewStyle>;
+};
+
+/**
+ * Compact pill with the avatar and username of the logged in account.
+ */
+export function AccountChip({ style }: AccountChipProps): React.ReactNode {
+ const colors = useColors();
+ const { username } = useAuth();
+
+ const styles = StyleSheet.create({
+ chip: {
+ alignItems: 'center',
+ alignSelf: 'center',
+ backgroundColor: colors.accentBackground,
+ borderColor: colors.accentBorder,
+ borderRadius: 999,
+ borderWidth: 1,
+ flexDirection: 'row',
+ gap: 8,
+ maxWidth: '100%',
+ paddingLeft: 4,
+ paddingRight: 14,
+ paddingVertical: 4,
+ },
+ username: {
+ color: colors.text,
+ flexShrink: 1,
+ fontSize: 15,
+ fontWeight: '500',
+ },
+ });
+
+ return (
+ <View style={[styles.chip, style]}>
+ <Avatar size={28} />
+ <ThemedText style={styles.username} numberOfLines={1}>{username}</ThemedText>
+ </View>
+ );
+}
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 39e4e6c96..e9d76726d 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -332,7 +332,10 @@
"mobileLogin": {
"confirmTitle": "Confirm Login Request",
"confirmSubtitle": "Re-authenticate to approve login on another device.",
- "confirmMessage": "You are about to log in on a remote device with your account. This other device will have full access to your vault. Only proceed if you trust this device.",
+ "confirmMessage": "Another device is asking to log in with your account. It will get full access to your vault. Only continue if you started this login yourself.",
+ "selectCode": "Tap the number shown on the other device",
+ "openedFromLink": "Only continue if you just scanned this QR code with your own camera. If you got here by tapping a link or a button, decline.",
+ "codeMismatch": "The number does not match. The login request was declined.",
"successDescription": "The remote device has been successfully logged in.",
"requestExpired": "This login request has expired. Please generate a new QR code."
}
diff --git a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
index e1df698c8..12232b8b4 100644
--- a/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
+++ b/apps/mobile-app/ios/NativeVaultManager/RCTNativeVaultManager.mm
@@ -359,8 +359,8 @@
// MARK: - Mobile Login
-- (void)encryptDecryptionKeyForMobileLogin:(NSString *)publicKeyJWK resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
- [vaultManager encryptDecryptionKeyForMobileLogin:publicKeyJWK resolver:resolve rejecter:reject];
+- (void)encryptUnlockKeyForMobileLogin:(NSString *)publicKeyJWK resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
+ [vaultManager encryptUnlockKeyForMobileLogin:publicKeyJWK resolver:resolve rejecter:reject];
}
// MARK: - Re-authentication
diff --git a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
index 804f1cb4a..3dddb0fbd 100644
--- a/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/VaultManager.swift
@@ -1140,12 +1140,12 @@ public class VaultManager: NSObject {
}
@objc
- func encryptDecryptionKeyForMobileLogin(_ publicKeyJWK: String,
+ func encryptUnlockKeyForMobileLogin(_ publicKeyJWK: String,
resolver resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock) {
do {
// Get the encryption key and encrypt it with the provided public key
- let encryptedData = try vaultStore.encryptDecryptionKeyForMobileLogin(publicKeyJWK: publicKeyJWK)
+ let encryptedData = try vaultStore.encryptUnlockKeyForMobileLogin(publicKeyJWK: publicKeyJWK)
// Return the encrypted data as base64 string
let base64Encrypted = encryptedData.base64EncodedString()
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift
index 773853b83..118b4df97 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+PublicKeyCrypto.swift
@@ -7,7 +7,7 @@ extension VaultStore {
/// The receiving client opens the account key chain with it.
/// - Parameter publicKeyJWK: The RSA public key in JWK format (JSON string)
/// - Returns: The encrypted unlock key
- public func encryptDecryptionKeyForMobileLogin(publicKeyJWK: String) throws -> Data {
+ public func encryptUnlockKeyForMobileLogin(publicKeyJWK: String) throws -> Data {
// Get the unlock key from the vault store
// This will only work if the vault is unlocked (unlock key is in memory)
let unlockKey = try getUnlockKey()
diff --git a/apps/mobile-app/specs/NativeVaultManager.ts b/apps/mobile-app/specs/NativeVaultManager.ts
index f080f9bc7..bd4fe2ed8 100644
--- a/apps/mobile-app/specs/NativeVaultManager.ts
+++ b/apps/mobile-app/specs/NativeVaultManager.ts
@@ -144,7 +144,7 @@ export interface Spec extends TurboModule {
showPasswordUnlock(title: string | null, subtitle: string | null, buttonText: string | null): Promise<boolean | null>;
// Mobile login methods
- encryptDecryptionKeyForMobileLogin(publicKeyJWK: string): Promise<string>;
+ encryptUnlockKeyForMobileLogin(publicKeyJWK: string): Promise<string>;
// Re-authentication methods
// Authenticate user with biometric or PIN. If title/subtitle are null/empty, defaults to "Unlock Vault" context.
diff --git a/apps/mobile-app/utils/DeepLinkResolver.ts b/apps/mobile-app/utils/DeepLinkResolver.ts
index 5822bab8c..74ecde00a 100644
--- a/apps/mobile-app/utils/DeepLinkResolver.ts
+++ b/apps/mobile-app/utils/DeepLinkResolver.ts
@@ -1,3 +1,7 @@
+import { MobileLoginProtocol } from '@aliasvault/client/auth/MobileLoginProtocol';
+
+import { MobileLoginScanHandoff } from '@/utils/MobileLoginScanHandoff';
+
import NativeVaultManager from '@/specs/NativeVaultManager';
declare const __DEV__: boolean;
@@ -28,18 +32,14 @@ export async function resolveOpenAction(
switch (action) {
case 'mobile-unlock': {
- const requestId = rest[0];
- if (!requestId) {
- return null;
- }
- const params: Record<string, string> = {};
- if (queryParams.pk) {
- params.pk = queryParams.pk;
+ // This is what the system camera opens after reading a mobile login QR code.
+ // Note: this link could also be opened from a different app or website, so the confirmation screen warns about potential phishing attempts.
+ const request = MobileLoginProtocol.parseQrPayload(`${MobileLoginProtocol.QR_PREFIX}${rest.join('/')}?pk=${queryParams.pk ?? ''}`);
+ if (!request) {
+ return { path: '/(tabs)/settings/qr-scanner' };
}
- return {
- path: `/(tabs)/settings/mobile-unlock/${requestId}`,
- params: Object.keys(params).length > 0 ? params : undefined,
- };
+ MobileLoginScanHandoff.set(request, 'link');
+ return { path: '/(tabs)/settings/mobile-unlock/confirm' };
}
case '__debug__':
diff --git a/apps/mobile-app/utils/EncryptionUtility.ts b/apps/mobile-app/utils/EncryptionUtility.ts
index 2bbc583fc..68febb37d 100644
--- a/apps/mobile-app/utils/EncryptionUtility.ts
+++ b/apps/mobile-app/utils/EncryptionUtility.ts
@@ -423,19 +423,6 @@ class EncryptionUtility {
throw new Error(err instanceof Error ? err.message : 'Failed to decrypt attachment');
}
}
-
- /**
- * Computes a SHA-256 hash of a string and returns the first 16 characters of the hex digest.
- * Used for verifying public key integrity in mobile login QR codes.
- */
- public static async computeSha256Hash(data: string): Promise<string> {
- const encoder = new TextEncoder();
- const dataBytes = encoder.encode(data);
- const hashBuffer = await crypto.subtle.digest('SHA-256', dataBytes);
- const hashArray = Array.from(new Uint8Array(hashBuffer));
- const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
- return hashHex.substring(0, 16);
- }
}
export default EncryptionUtility;
diff --git a/apps/mobile-app/utils/MobileLoginScanHandoff.ts b/apps/mobile-app/utils/MobileLoginScanHandoff.ts
new file mode 100644
index 000000000..e40fbd3fc
--- /dev/null
+++ b/apps/mobile-app/utils/MobileLoginScanHandoff.ts
@@ -0,0 +1,38 @@
+import type { MobileLoginQrPayload } from '@aliasvault/client/auth/MobileLoginProtocol';
+
+/**
+ * How a mobile login request reached the app: read by the in-app scanner, or carried by an `aliasvault://` link.
+ */
+export type MobileLoginRequestSource = 'scan' | 'link';
+
+export type PendingMobileLoginRequest = MobileLoginQrPayload & {
+ source: MobileLoginRequestSource;
+}
+
+const MAX_AGE_MS = 3 * 60 * 1000;
+
+let pendingRequest: (PendingMobileLoginRequest & { receivedAt: number }) | null = null;
+
+/**
+ * Hands a mobile login request to the confirmation screen through memory instead of route params.
+ */
+export const MobileLoginScanHandoff = {
+ /**
+ * Store a validated request for the confirmation screen.
+ */
+ set(payload: MobileLoginQrPayload, source: MobileLoginRequestSource): void {
+ pendingRequest = { ...payload, source, receivedAt: Date.now() };
+ },
+
+ /**
+ * Take the pending request.
+ */
+ take(): PendingMobileLoginRequest | null {
+ const request = pendingRequest;
+ pendingRequest = null;
+ if (!request || Date.now() - request.receivedAt > MAX_AGE_MS) {
+ return null;
+ }
+ return { requestId: request.requestId, publicKeyHash: request.publicKeyHash, source: request.source };
+ },
+};