Skip to content

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

Add 2FA TOTP code editor to mobile app (#1391)

Leendert de Borstb85589610804
diff --git a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
index 9d45b9ab3..132404e0f 100644
--- a/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
+++ b/apps/mobile-app/app/(tabs)/credentials/add-edit.tsx
@@ -12,7 +12,7 @@ import { StyleSheet, View, Alert, Keyboard, Platform, ScrollView, KeyboardAvoidi
import Toast from 'react-native-toast-message';
import { CreateIdentityGenerator, CreateUsernameEmailGenerator, Gender, Identity, IdentityHelperUtils, convertAgeRangeToBirthdateOptions } from '@/utils/dist/shared/identity-generator';
-import type { Attachment, Credential } from '@/utils/dist/shared/models/vault';
+import type { Attachment, Credential, TotpCode } from '@/utils/dist/shared/models/vault';
import type { FaviconExtractModel } from '@/utils/dist/shared/models/webapi';
import { CreatePasswordGenerator, PasswordGenerator } from '@/utils/dist/shared/password-generator';
import emitter from '@/utils/EventEmitter';
@@ -23,6 +23,7 @@ import { useColors } from '@/hooks/useColorScheme';
import { useVaultMutate } from '@/hooks/useVaultMutate';
import { AttachmentUploader } from '@/components/credentials/details/AttachmentUploader';
+import { TotpEditor } from '@/components/credentials/details/TotpEditor';
import { AdvancedPasswordField } from '@/components/form/AdvancedPasswordField';
import { EmailDomainField } from '@/components/form/EmailDomainField';
import { ValidatedFormField, ValidatedFormFieldRef } from '@/components/form/ValidatedFormField';
@@ -56,6 +57,8 @@ export default function AddEditCredentialScreen() : React.ReactNode {
const [isSaveDisabled, setIsSaveDisabled] = useState(false);
const [attachments, setAttachments] = useState<Attachment[]>([]);
const [originalAttachmentIds, setOriginalAttachmentIds] = useState<string[]>([]);
+ const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);
+ const [originalTotpCodeIds, setOriginalTotpCodeIds] = useState<string[]>([]);
const [passkeyMarkedForDeletion, setPasskeyMarkedForDeletion] = useState(false);
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
const { t } = useTranslation();
@@ -164,6 +167,11 @@ export default function AddEditCredentialScreen() : React.ReactNode {
// Load attachments for this credential
const credentialAttachments = await dbContext.sqliteClient!.getAttachmentsForCredential(id);
setAttachments(credentialAttachments);
+
+ // Load TOTP codes for this credential
+ const credentialTotpCodes = await dbContext.sqliteClient!.getTotpCodesForCredential(id);
+ setTotpCodes(credentialTotpCodes);
+ setOriginalTotpCodeIds(credentialTotpCodes.map(tc => tc.Id));
setOriginalAttachmentIds(credentialAttachments.map(a => a.Id));
}
} catch (err) {
@@ -388,14 +396,14 @@ export default function AddEditCredentialScreen() : React.ReactNode {
await executeVaultMutation(async () => {
if (isEditMode) {
- await dbContext.sqliteClient!.updateCredentialById(credentialToSave, originalAttachmentIds, attachments);
+ await dbContext.sqliteClient!.updateCredentialById(credentialToSave, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes);
// Delete passkeys if marked for deletion
if (passkeyMarkedForDeletion) {
await dbContext.sqliteClient!.deletePasskeysByCredentialId(credentialToSave.Id);
}
} else {
- const credentialId = await dbContext.sqliteClient!.createCredential(credentialToSave, attachments);
+ const credentialId = await dbContext.sqliteClient!.createCredential(credentialToSave, attachments, totpCodes);
credentialToSave.Id = credentialId;
}
@@ -458,7 +466,7 @@ export default function AddEditCredentialScreen() : React.ReactNode {
setIsSaveDisabled(false);
}
});
- }, [isEditMode, id, serviceUrl, router, executeVaultMutation, dbContext.sqliteClient, mode, generateRandomAlias, webApi, watch, setIsSaveDisabled, setIsSyncing, isSaveDisabled, t, originalAttachmentIds, attachments, passkeyMarkedForDeletion]);
+ }, [isEditMode, id, serviceUrl, router, executeVaultMutation, dbContext.sqliteClient, mode, generateRandomAlias, webApi, watch, setIsSaveDisabled, setIsSyncing, isSaveDisabled, t, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyMarkedForDeletion]);
/**
* Generate a random username based on current identity fields, or completely random if fields are empty.
@@ -1032,7 +1040,14 @@ export default function AddEditCredentialScreen() : React.ReactNode {
numberOfLines={4}
textAlignVertical="top"
/>
- {/* TODO: Add TOTP management */}
+ </View>
+
+ <View style={styles.section}>
+ <TotpEditor
+ totpCodes={totpCodes}
+ onTotpCodesChange={setTotpCodes}
+ originalTotpCodeIds={originalTotpCodeIds}
+ />
</View>
<View style={styles.section}>
diff --git a/apps/mobile-app/components/credentials/details/TotpEditor.tsx b/apps/mobile-app/components/credentials/details/TotpEditor.tsx
new file mode 100644
index 000000000..196ddf7e0
--- /dev/null
+++ b/apps/mobile-app/components/credentials/details/TotpEditor.tsx
@@ -0,0 +1,462 @@
+import MaterialIcons from '@expo/vector-icons/MaterialIcons';
+import * as OTPAuth from 'otpauth';
+import React, { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { View, StyleSheet, Alert, TextInput, Modal, TouchableOpacity, ScrollView } from 'react-native';
+
+import type { TotpCode } from '@/utils/dist/shared/models/vault';
+
+import { useColors } from '@/hooks/useColorScheme';
+
+import { ThemedText } from '@/components/themed/ThemedText';
+import { ThemedView } from '@/components/themed/ThemedView';
+import { Ionicons } from '@expo/vector-icons';
+
+type TotpFormData = {
+ name: string;
+ secretKey: string;
+}
+
+type TotpEditorProps = {
+ totpCodes: TotpCode[];
+ onTotpCodesChange: (totpCodes: TotpCode[]) => void;
+ originalTotpCodeIds: string[];
+}
+
+/**
+ * Component for editing TOTP codes for a credential.
+ */
+export const TotpEditor: React.FC<TotpEditorProps> = ({
+ totpCodes,
+ onTotpCodesChange,
+ originalTotpCodeIds
+}) => {
+ const { t } = useTranslation();
+ const colors = useColors();
+ const [isAddFormVisible, setIsAddFormVisible] = useState(false);
+ const [formData, setFormData] = useState<TotpFormData>({ name: '', secretKey: '' });
+ const [formError, setFormError] = useState<string | null>(null);
+
+ /**
+ * Sanitizes the secret key by extracting it from a TOTP URI if needed
+ */
+ const sanitizeSecretKey = (secretKeyInput: string, nameInput: string): { secretKey: string, name: string } => {
+ let secretKey = secretKeyInput.trim();
+ let name = nameInput.trim();
+
+ // Check if it's a TOTP URI
+ if (secretKey.toLowerCase().startsWith('otpauth://totp/')) {
+ try {
+ const uri = OTPAuth.URI.parse(secretKey);
+ if (uri instanceof OTPAuth.TOTP) {
+ secretKey = uri.secret.base32;
+ // If name is empty, use the label from the URI
+ if (!name && uri.label) {
+ name = uri.label;
+ }
+ }
+ } catch {
+ throw new Error(t('totp.errors.invalidSecretKey'));
+ }
+ }
+
+ // Remove spaces from the secret key
+ secretKey = secretKey.replace(/\s/g, '');
+
+ // Validate the secret key format (base32)
+ if (!/^[A-Z2-7]+=*$/i.test(secretKey)) {
+ throw new Error(t('totp.errors.invalidSecretKey'));
+ }
+
+ return { secretKey, name: name || 'Authenticator' };
+ };
+
+ /**
+ * Shows the add form
+ */
+ const showAddForm = (): void => {
+ setFormData({ name: '', secretKey: '' });
+ setFormError(null);
+ setIsAddFormVisible(true);
+ };
+
+ /**
+ * Hides the add form
+ */
+ const hideAddForm = (): void => {
+ setIsAddFormVisible(false);
+ setFormData({ name: '', secretKey: '' });
+ setFormError(null);
+ };
+
+ /**
+ * Handles adding a new TOTP code
+ */
+ const handleAddTotpCode = (): void => {
+ setFormError(null);
+
+ // Validate required fields
+ if (!formData.secretKey) {
+ setFormError(t('validation.required'));
+ return;
+ }
+
+ try {
+ // Sanitize the secret key
+ const { secretKey, name } = sanitizeSecretKey(formData.secretKey, formData.name);
+
+ // Create new TOTP code
+ const newTotpCode: TotpCode = {
+ Id: crypto.randomUUID().toUpperCase(),
+ Name: name,
+ SecretKey: secretKey,
+ CredentialId: '' // Will be set when saving the credential
+ };
+
+ // Add to the list
+ const updatedTotpCodes = [...totpCodes, newTotpCode];
+ onTotpCodesChange(updatedTotpCodes);
+
+ // Hide the form
+ hideAddForm();
+ } catch (error) {
+ if (error instanceof Error) {
+ setFormError(error.message);
+ } else {
+ setFormError(t('common.errors.unknownErrorTryAgain'));
+ }
+ }
+ };
+
+ /**
+ * Initiates the delete process for a TOTP code
+ */
+ const initiateTotpDelete = (totpCode: TotpCode): void => {
+ Alert.alert(
+ t('common.deleteItemConfirmTitle'),
+ t('common.deleteItemConfirmDescription'),
+ [
+ {
+ text: t('common.cancel'),
+ style: 'cancel'
+ },
+ {
+ text: t('common.delete'),
+ style: 'destructive',
+ onPress: () => confirmDeleteTotpCode(totpCode)
+ }
+ ]
+ );
+ };
+
+ /**
+ * Confirms deletion of a TOTP code
+ */
+ const confirmDeleteTotpCode = (totpCode: TotpCode): void => {
+ // Check if this TOTP code was part of the original set
+ const wasOriginal = originalTotpCodeIds.includes(totpCode.Id);
+
+ let updatedTotpCodes: TotpCode[];
+ if (wasOriginal) {
+ // Mark as deleted (soft delete for syncing)
+ updatedTotpCodes = totpCodes.map(tc =>
+ tc.Id === totpCode.Id
+ ? { ...tc, IsDeleted: true }
+ : tc
+ );
+ } else {
+ // Hard delete (remove from array)
+ updatedTotpCodes = totpCodes.filter(tc => tc.Id !== totpCode.Id);
+ }
+
+ onTotpCodesChange(updatedTotpCodes);
+ };
+
+ // Filter out deleted TOTP codes for display
+ const activeTotpCodes = totpCodes.filter(tc => !tc.IsDeleted);
+ const hasActiveTotpCodes = activeTotpCodes.length > 0;
+
+ const styles = StyleSheet.create({
+ addButton: {
+ alignItems: 'center',
+ backgroundColor: colors.primary,
+ borderRadius: 8,
+ height: 35,
+ justifyContent: 'center',
+ marginTop: 8,
+ width: '100%',
+ },
+ addButtonCompact: {
+ alignItems: 'center',
+ backgroundColor: colors.primary,
+ borderRadius: 8,
+ height: 35,
+ justifyContent: 'center',
+ width: 35,
+ },
+ addButtonText: {
+ color: colors.primarySurfaceText,
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ codeItem: {
+ alignItems: 'center',
+ backgroundColor: colors.background,
+ borderRadius: 8,
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ marginTop: 8,
+ padding: 12,
+ },
+ codeName: {
+ color: colors.text,
+ fontSize: 14,
+ fontWeight: '600',
+ },
+ deleteButton: {
+ padding: 4,
+ },
+ errorText: {
+ color: colors.errorText,
+ fontSize: 12,
+ marginTop: 4,
+ },
+ header: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ marginBottom: 8,
+ },
+ helperText: {
+ color: colors.textMuted,
+ fontSize: 12,
+ marginTop: 4,
+ },
+ input: {
+ backgroundColor: colors.background,
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ color: colors.text,
+ fontSize: 14,
+ marginTop: 8,
+ padding: 12,
+ },
+ inputError: {
+ borderColor: colors.errorBorder,
+ },
+ label: {
+ color: colors.text,
+ fontSize: 14,
+ fontWeight: '600',
+ marginTop: 12,
+ },
+ modalButtons: {
+ flexDirection: 'row',
+ gap: 12,
+ marginTop: 24,
+ },
+ modalCancelButton: {
+ alignItems: 'center',
+ backgroundColor: colors.accentBackground,
+ borderRadius: 8,
+ flex: 1,
+ padding: 14,
+ },
+ modalCancelButtonText: {
+ color: colors.text,
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ modalCloseButton: {
+ padding: 4,
+ },
+ modalBackdrop: {
+ flex: 1,
+ },
+ modalContainer: {
+ backgroundColor: 'rgba(0, 0, 0, 0.5)',
+ flex: 1,
+ justifyContent: 'flex-end',
+ },
+ modalContent: {
+ backgroundColor: colors.accentBackground,
+ borderTopLeftRadius: 16,
+ borderTopRightRadius: 16,
+ maxHeight: '90%',
+ paddingTop: 20,
+ paddingHorizontal: 20,
+ paddingBottom: 20,
+ },
+ modalHeader: {
+ alignItems: 'center',
+ flexDirection: 'row',
+ justifyContent: 'space-between',
+ marginBottom: 12,
+ },
+ modalSaveButton: {
+ alignItems: 'center',
+ backgroundColor: colors.primary,
+ borderRadius: 8,
+ flex: 1,
+ padding: 14,
+ },
+ modalSaveButtonText: {
+ color: colors.primarySurfaceText,
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ modalTitle: {
+ color: colors.text,
+ fontSize: 18,
+ fontWeight: '700',
+ },
+ saveToViewText: {
+ color: colors.textMuted,
+ fontSize: 12,
+ },
+ sectionTitle: {
+ color: colors.text,
+ fontSize: 16,
+ fontWeight: '600',
+ },
+ });
+
+ return (
+ <View>
+ <View style={styles.header}>
+ <ThemedText style={styles.sectionTitle}>
+ {t('common.twoFactorAuthentication')}
+ </ThemedText>
+ {hasActiveTotpCodes && (
+ <TouchableOpacity
+ style={styles.addButtonCompact}
+ onPress={showAddForm}
+ >
+ <Ionicons name="add" size={24} color={colors.background} />
+ </TouchableOpacity>
+ )}
+ </View>
+
+ {!hasActiveTotpCodes && (
+ <TouchableOpacity
+ style={styles.addButton}
+ onPress={showAddForm}
+ >
+ <Ionicons name="add" size={24} color={colors.background} />
+ </TouchableOpacity>
+ )}
+
+ {hasActiveTotpCodes && (
+ <View>
+ {activeTotpCodes.map(totpCode => (
+ <View key={totpCode.Id} style={styles.codeItem}>
+ <View style={{ flex: 1 }}>
+ <ThemedText style={styles.codeName}>
+ {totpCode.Name}
+ </ThemedText>
+ <ThemedText style={styles.saveToViewText}>
+ {t('totp.saveToViewCode')}
+ </ThemedText>
+ </View>
+ <TouchableOpacity
+ style={styles.deleteButton}
+ onPress={() => initiateTotpDelete(totpCode)}
+ >
+ <Ionicons name="trash" size={20} color={colors.errorText} />
+ </TouchableOpacity>
+ </View>
+ ))}
+ </View>
+ )}
+
+ {/* Add TOTP Modal */}
+ <Modal
+ visible={isAddFormVisible}
+ transparent
+ animationType="fade"
+ onRequestClose={hideAddForm}
+ >
+ <View style={styles.modalContainer}>
+ <TouchableOpacity
+ style={styles.modalBackdrop}
+ activeOpacity={1}
+ onPress={hideAddForm}
+ />
+ <View style={styles.modalContent}>
+ <ScrollView
+ keyboardShouldPersistTaps="handled"
+ showsVerticalScrollIndicator={false}
+ >
+ <View style={styles.modalHeader}>
+ <ThemedText style={styles.modalTitle}>
+ {t('totp.addCode')}
+ </ThemedText>
+ <TouchableOpacity
+ style={styles.modalCloseButton}
+ onPress={hideAddForm}
+ >
+ <MaterialIcons name="close" size={24} color={colors.textMuted} />
+ </TouchableOpacity>
+ </View>
+
+ <ThemedText style={styles.helperText}>
+ {t('totp.instructions')}
+ </ThemedText>
+
+ <ThemedText style={styles.label}>
+ {t('totp.nameOptional')}
+ </ThemedText>
+ <TextInput
+ style={styles.input}
+ placeholder={t('totp.nameOptional')}
+ placeholderTextColor={colors.textMuted}
+ value={formData.name}
+ onChangeText={(text) => setFormData({ ...formData, name: text })}
+ autoCapitalize="words"
+ />
+
+ <ThemedText style={styles.label}>
+ {t('totp.secretKey')}
+ </ThemedText>
+ <TextInput
+ style={[styles.input, formError && styles.inputError]}
+ placeholderTextColor={colors.textMuted}
+ value={formData.secretKey}
+ onChangeText={(text) => setFormData({ ...formData, secretKey: text })}
+ autoCapitalize="characters"
+ autoCorrect={false}
+ multiline
+ />
+
+ {formError && (
+ <ThemedText style={styles.errorText}>
+ {formError}
+ </ThemedText>
+ )}
+
+ <View style={styles.modalButtons}>
+ <TouchableOpacity
+ style={styles.modalCancelButton}
+ onPress={hideAddForm}
+ >
+ <ThemedText style={styles.modalCancelButtonText}>
+ {t('common.cancel')}
+ </ThemedText>
+ </TouchableOpacity>
+ <TouchableOpacity
+ style={styles.modalSaveButton}
+ onPress={handleAddTotpCode}
+ >
+ <ThemedText style={styles.modalSaveButtonText}>
+ {t('common.save')}
+ </ThemedText>
+ </TouchableOpacity>
+ </View>
+ </ScrollView>
+ </View>
+ </View>
+ </Modal>
+ </View>
+ );
+};
diff --git a/apps/mobile-app/components/credentials/details/TotpSection.tsx b/apps/mobile-app/components/credentials/details/TotpSection.tsx
index df8d5f2a3..6d2d0d5b1 100644
--- a/apps/mobile-app/components/credentials/details/TotpSection.tsx
+++ b/apps/mobile-app/components/credentials/details/TotpSection.tsx
@@ -111,7 +111,7 @@ export const TotpSection: React.FC<TotpSectionProps> = ({ credential }) : React.
};
loadTotpCodes();
- }, [credential.Id, dbContext?.sqliteClient]);
+ }, [credential, dbContext?.sqliteClient]);
useEffect(() => {
/**
diff --git a/apps/mobile-app/i18n/locales/en.json b/apps/mobile-app/i18n/locales/en.json
index 9a79a3de5..aecb5dd49 100644
--- a/apps/mobile-app/i18n/locales/en.json
+++ b/apps/mobile-app/i18n/locales/en.json
@@ -20,6 +20,9 @@
"notice": "Notice",
"enabled": "Enabled",
"disabled": "Disabled",
+ "twoFactorAuthentication": "Two-Factor Authentication",
+ "deleteItemConfirmTitle": "Delete Item",
+ "deleteItemConfirmDescription": "Are you sure you want to delete this item?",
"errors": {
"unknownError": "An unknown error occurred. Please try again.",
"unknownErrorTryAgain": "An unknown error occurred. Please try again.",
@@ -203,6 +206,16 @@
"passkeyMarkedForDeletion": "Passkey marked for deletion",
"passkeyWillBeDeleted": "This passkey will be deleted when you save this credential."
},
+ "totp": {
+ "addCode": "Add 2FA Code",
+ "nameOptional": "Name (optional)",
+ "secretKey": "Secret Key",
+ "instructions": "Enter the secret key from your authenticator app, or paste the full otpauth:// URI.",
+ "saveToViewCode": "Save to view code",
+ "errors": {
+ "invalidSecretKey": "Invalid secret key format. Please enter a valid base32-encoded key or otpauth:// URI."
+ }
+ },
"settings": {
"title": "Settings",
"autofill": "Autofill & Passkeys",
diff --git a/apps/mobile-app/utils/SqliteClient.tsx b/apps/mobile-app/utils/SqliteClient.tsx
index 9b4c44a7f..ef42df140 100644
--- a/apps/mobile-app/utils/SqliteClient.tsx
+++ b/apps/mobile-app/utils/SqliteClient.tsx
@@ -579,7 +579,7 @@ class SqliteClient {
* @param attachments The attachments to insert
* @returns The ID of the newly created credential
*/
- public async createCredential(credential: Credential, attachments: Attachment[]): Promise<string> {
+ public async createCredential(credential: Credential, attachments: Attachment[], totpCodes: TotpCode[] = []): Promise<string> {
try {
await NativeVaultManager.beginTransaction();
@@ -682,6 +682,27 @@ class SqliteClient {
]);
}
+ // 6. Insert TOTP codes
+ for (const totpCode of totpCodes) {
+ // Skip deleted codes
+ if (totpCode.IsDeleted) {
+ continue;
+ }
+
+ const totpCodeQuery = `
+ INSERT INTO TotpCodes (Id, Name, SecretKey, CredentialId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`;
+ await this.executeUpdate(totpCodeQuery, [
+ totpCode.Id || crypto.randomUUID().toUpperCase(),
+ totpCode.Name,
+ totpCode.SecretKey,
+ credentialId,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ }
+
await NativeVaultManager.commitTransaction();
return credentialId;
@@ -891,9 +912,11 @@ class SqliteClient {
* @param credential The credential object to update
* @param originalAttachmentIds The IDs of the original attachments
* @param attachments The attachments to update
+ * @param originalTotpCodeIds The IDs of the original TOTP codes
+ * @param totpCodes The TOTP codes to update
* @returns The number of rows modified
*/
- public async updateCredentialById(credential: Credential, originalAttachmentIds: string[], attachments: Attachment[]): Promise<number> {
+ public async updateCredentialById(credential: Credential, originalAttachmentIds: string[], attachments: Attachment[], originalTotpCodeIds: string[], totpCodes: TotpCode[]): Promise<number> {
try {
await NativeVaultManager.beginTransaction();
const currentDateTime = dateFormatter.now();
@@ -1070,6 +1093,72 @@ class SqliteClient {
}
}
+ // 6. Handle TOTP Codes
+ if (totpCodes) {
+ // Get current TOTP code IDs to track what needs to be deleted
+ const currentTotpCodeIds = totpCodes.filter(tc => !tc.IsDeleted).map(tc => tc.Id);
+
+ // Delete TOTP codes that were removed (in originalTotpCodeIds but not in current codes)
+ const totpCodesToDelete = originalTotpCodeIds.filter(id => !currentTotpCodeIds.includes(id));
+ for (const totpCodeId of totpCodesToDelete) {
+ const deleteQuery = `
+ UPDATE TotpCodes
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+ await this.executeUpdate(deleteQuery, [currentDateTime, totpCodeId]);
+ }
+
+ // Process each TOTP code
+ for (const totpCode of totpCodes) {
+ // Skip codes marked as deleted
+ if (totpCode.IsDeleted) {
+ // If it was an original code, mark it as deleted in DB
+ if (originalTotpCodeIds.includes(totpCode.Id)) {
+ const deleteQuery = `
+ UPDATE TotpCodes
+ SET IsDeleted = 1,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+ await this.executeUpdate(deleteQuery, [currentDateTime, totpCode.Id]);
+ }
+ continue;
+ }
+
+ const isExistingTotpCode = originalTotpCodeIds.includes(totpCode.Id);
+
+ if (!isExistingTotpCode) {
+ // Insert new TOTP code
+ const insertQuery = `
+ INSERT INTO TotpCodes (Id, Name, SecretKey, CredentialId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ?, ?)`;
+ await this.executeUpdate(insertQuery, [
+ totpCode.Id,
+ totpCode.Name,
+ totpCode.SecretKey,
+ credential.Id,
+ currentDateTime,
+ currentDateTime,
+ 0
+ ]);
+ } else {
+ // Update existing TOTP code
+ const updateQuery = `
+ UPDATE TotpCodes
+ SET Name = ?,
+ SecretKey = ?,
+ UpdatedAt = ?
+ WHERE Id = ?`;
+ await this.executeUpdate(updateQuery, [
+ totpCode.Name,
+ totpCode.SecretKey,
+ currentDateTime,
+ totpCode.Id
+ ]);
+ }
+ }
+ }
+
await NativeVaultManager.commitTransaction();
return 1;
diff --git a/apps/mobile-app/utils/dist/shared/models/vault/index.d.ts b/apps/mobile-app/utils/dist/shared/models/vault/index.d.ts
index 17fbf2f77..8362233b7 100644
--- a/apps/mobile-app/utils/dist/shared/models/vault/index.d.ts
+++ b/apps/mobile-app/utils/dist/shared/models/vault/index.d.ts
@@ -50,6 +50,8 @@ type TotpCode = {
SecretKey: string;
/** The credential ID this TOTP code belongs to */
CredentialId: string;
+ /** Whether the TOTP code has been deleted (soft delete) */
+ IsDeleted?: boolean;
};
/**