Skip to content

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

Refactor mobile app to use aliasvault core libs via direct link (#2159)

Leendert de Borst8eea80566e06
diff --git a/apps/mobile-app/.gitignore b/apps/mobile-app/.gitignore
index 6d26df642..ff64aa880 100644
--- a/apps/mobile-app/.gitignore
+++ b/apps/mobile-app/.gitignore
@@ -6,7 +6,6 @@ node_modules/
# Expo
.expo/
dist/
-!utils/dist
web-build/
expo-env.d.ts
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultSql.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultSql.kt
index fe686454a..de4d29516 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultSql.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/models/VaultSql.kt
@@ -1430,13 +1430,14 @@ CREATE INDEX "IX_Attachments_ManifestId_ItemId" ON "Attachments" ("ManifestId",
CREATE TABLE "ef_temp_Attachments" (
"ManifestId" TEXT COLLATE NOCASE NOT NULL,
"Id" TEXT COLLATE NOCASE NOT NULL,
- "Blob" BLOB NOT NULL,
+ "Blob" BLOB NULL,
"CreatedAt" TEXT NOT NULL,
"Filename" TEXT NOT NULL,
"IsDeleted" INTEGER NOT NULL,
"ItemId" TEXT COLLATE NOCASE NOT NULL,
"UpdatedAt" TEXT NOT NULL,
CONSTRAINT "PK_Attachments" PRIMARY KEY ("ManifestId", "Id"),
+ CONSTRAINT "CK_Attachments_Blob_Tombstone" CHECK ("IsDeleted" = 1 OR "Blob" IS NOT NULL),
CONSTRAINT "FK_Attachments_Items_ManifestId_ItemId" FOREIGN KEY ("ManifestId", "ItemId") REFERENCES "Items" ("ManifestId", "Id") ON DELETE CASCADE
);
@@ -1782,7 +1783,7 @@ CREATE INDEX "IX_EncryptionKeys_ManifestId_IsPrimary" ON "EncryptionKeys" ("Mani
COMMIT;
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20260910094359_2.1.0-ManifestScopedStorage', '10.0.10');
+VALUES ('20260913090000_2.1.0-ManifestScopedStorage', '10.0.10');
BEGIN TRANSACTION;
CREATE TRIGGER IF NOT EXISTS "TR_Items_ResyncChildManifestIds"
@@ -1803,7 +1804,7 @@ COMMIT;
PRAGMA foreign_keys = ON;
INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
-VALUES ('20260910094449_2.1.1-ItemChildManifestTrigger', '10.0.10');
+VALUES ('20260913090100_2.1.1-ItemChildManifestTrigger', '10.0.10');
""".trimIndent()
/**
diff --git a/apps/mobile-app/app/(tabs)/emails/index.tsx b/apps/mobile-app/app/(tabs)/emails/index.tsx
index 66d7ffd3e..9235a614c 100644
--- a/apps/mobile-app/app/(tabs)/emails/index.tsx
+++ b/apps/mobile-app/app/(tabs)/emails/index.tsx
@@ -5,7 +5,6 @@ import { StyleSheet, Platform, View, ScrollView, RefreshControl, Animated, Touch
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Toast from 'react-native-toast-message';
-import type { MailboxBulkRequest, MailboxBulkResponse, MailboxEmail } from '@/utils/dist/core/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
import emitter from '@/utils/EventEmitter';
import { HapticsUtility } from '@/utils/HapticsUtility';
@@ -22,6 +21,8 @@ import { TitleContainer } from '@/components/ui/TitleContainer';
import { useDb } from '@/context/DbContext';
import { useWebApi } from '@/context/WebApiContext';
+import type { MailboxBulkRequest, MailboxBulkResponse, MailboxEmail } from '@aliasvault/models/webapi';
+
/**
* Emails screen.
*/
@@ -63,7 +64,7 @@ export default function EmailsScreen() : React.ReactNode {
}
// Get unique email addresses from all items
- const emailAddresses = await dbContext.sqliteClient.items.getAllEmailAddresses();
+ const emailAddresses = await dbContext.sqliteClient.items.getRoutableEmailAddresses();
try {
const data = await webApi.post<MailboxBulkRequest, MailboxBulkResponse>('EmailBox/bulk', {
@@ -73,10 +74,10 @@ export default function EmailsScreen() : React.ReactNode {
});
// Decrypt emails locally using private key associated with the email address
- const encryptionKeys = await dbContext.sqliteClient.getAllEncryptionKeys();
+ const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
// Decrypt emails locally using public/private key pairs
- const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, encryptionKeys);
+ const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
if (reset) {
setEmails(decryptedEmails);
@@ -121,7 +122,7 @@ export default function EmailsScreen() : React.ReactNode {
setIsLoadingMore(true);
setError(null);
- const emailAddresses = await dbContext.sqliteClient.items.getAllEmailAddresses();
+ const emailAddresses = await dbContext.sqliteClient.items.getRoutableEmailAddresses();
const nextPage = currentPage + 1;
const data = await webApi.post<MailboxBulkRequest, MailboxBulkResponse>('EmailBox/bulk', {
@@ -131,8 +132,8 @@ export default function EmailsScreen() : React.ReactNode {
});
// Decrypt emails locally
- const encryptionKeys = await dbContext.sqliteClient.getAllEncryptionKeys();
- const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, encryptionKeys);
+ const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
+ const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
// Append to existing emails
setEmails((prevEmails) => [...prevEmails, ...decryptedEmails]);
diff --git a/apps/mobile-app/app/(tabs)/items/add-edit.tsx b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
index 06c3ac58f..b75610109 100644
--- a/apps/mobile-app/app/(tabs)/items/add-edit.tsx
+++ b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
@@ -1,5 +1,6 @@
import { Buffer } from 'buffer';
+import * as RustCore from '@aliasvault/client/rust/RustCore';
import { IdentityHelperUtils } from '@aliasvault/models/identity';
import { ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType, FieldCategories, FieldTypes } from '@aliasvault/models/vault';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
@@ -11,12 +12,8 @@ import { useTranslation } from 'react-i18next';
import { StyleSheet, View, Keyboard, Platform, ScrollView, KeyboardAvoidingView, TouchableOpacity } from 'react-native';
import Toast from 'react-native-toast-message';
-import type { Folder } from '@/utils/db/repositories/FolderRepository';
import emitter from '@/utils/EventEmitter';
-import { selectFaviconTarget } from '@/utils/FaviconUtility';
import { HapticsUtility } from '@/utils/HapticsUtility';
-import * as IdentityGenerator from '@/utils/IdentityGeneratorUtility';
-import * as PasswordGenerator from '@/utils/PasswordGeneratorUtility';
import { extractServiceNameFromUrl, sanitizeServiceUrl } from '@/utils/UrlUtility';
import { useColors } from '@/hooks/useColorScheme';
@@ -44,6 +41,7 @@ import { RobustPressable } from '@/components/ui/RobustPressable';
import { useDb } from '@/context/DbContext';
import { useWebApi } from '@/context/WebApiContext';
+import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
import type { Identity } from '@aliasvault/models/identity';
import type { Attachment, Item, ItemField, TotpCode, ItemType, FieldType, PasswordSettings } from '@aliasvault/models/vault';
import type { FaviconExtractModel } from '@aliasvault/models/webapi';
@@ -273,11 +271,11 @@ export default function AddEditItemScreen(): React.ReactNode {
* Generate a random identity.
*/
const generateRandomIdentity = useCallback(async (): Promise<Identity> => {
- const identityLanguage = await dbContext.sqliteClient!.getEffectiveIdentityLanguage();
- const genderPreference = await dbContext.sqliteClient!.getDefaultIdentityGender();
- const ageRange = await dbContext.sqliteClient!.getDefaultIdentityAgeRange();
+ const identityLanguage = await dbContext.sqliteClient!.settings.getEffectiveIdentityLanguage();
+ const genderPreference = await dbContext.sqliteClient!.settings.getDefaultIdentityGender();
+ const ageRange = await dbContext.sqliteClient!.settings.getDefaultIdentityAgeRange();
- return IdentityGenerator.generateIdentity({
+ return RustCore.generateIdentity({
language: identityLanguage,
gender: genderPreference,
ageRange
@@ -288,9 +286,9 @@ export default function AddEditItemScreen(): React.ReactNode {
* Generate a random alias and password.
*/
const generateRandomAlias = useCallback(async (): Promise<void> => {
- const passwordSettings = await dbContext.sqliteClient!.getPasswordSettings();
+ const passwordSettings = await dbContext.sqliteClient!.settings.getPasswordSettings();
const identity = await generateRandomIdentity();
- const password = await PasswordGenerator.generatePassword(passwordSettings);
+ const password = await RustCore.generatePassword(passwordSettings);
const defaultEmailDomain = await dbContext.sqliteClient!.getDefaultEmailDomain();
const email = defaultEmailDomain ? `${identity.emailPrefix}@${defaultEmailDomain}` : identity.emailPrefix;
@@ -349,7 +347,7 @@ export default function AddEditItemScreen(): React.ReactNode {
const randomIdentity = await generateRandomIdentity();
username = randomIdentity.nickName;
} else {
- username = await IdentityGenerator.generateIdentityUsername({ firstName, lastName, birthDate });
+ username = await RustCore.generateIdentityUsername({ firstName, lastName, birthDate });
}
handleFieldChange('login.username', username);
@@ -372,10 +370,10 @@ export default function AddEditItemScreen(): React.ReactNode {
if (!firstName.trim() && !lastName.trim()) {
// No alias identity fields filled in, fall back to random prefix.
- prefix = await IdentityGenerator.generateRandomEmailPrefix();
+ prefix = await RustCore.generateRandomEmailPrefix();
} else {
const birthDate = (fieldValues['alias.birthdate'] as string) || '';
- prefix = await IdentityGenerator.generateIdentityEmailPrefix({ firstName, lastName, birthDate });
+ prefix = await RustCore.generateIdentityEmailPrefix({ firstName, lastName, birthDate });
}
const defaultEmailDomain = await dbContext.sqliteClient!.getDefaultEmailDomain();
@@ -390,7 +388,7 @@ export default function AddEditItemScreen(): React.ReactNode {
* has no persona fields to base the email on.
*/
const handleGenerateRandomEmail = useCallback(async () => {
- const prefix = await IdentityGenerator.generateRandomEmailPrefix();
+ const prefix = await RustCore.generateRandomEmailPrefix();
const defaultEmailDomain = await dbContext.sqliteClient!.getDefaultEmailDomain();
const email = defaultEmailDomain ? `${prefix}@${defaultEmailDomain}` : prefix;
@@ -453,7 +451,7 @@ export default function AddEditItemScreen(): React.ReactNode {
setInitiallyVisibleFields(fieldsWithValues);
// Load attachments for this item
- const itemAttachments = await dbContext.sqliteClient!.settings.getAttachmentsForItem(id);
+ const itemAttachments = await dbContext.sqliteClient!.items.getAttachmentsForItem(id);
setAttachments(itemAttachments);
setOriginalAttachmentIds(itemAttachments.map(a => a.Id));
if (itemAttachments.length > 0) {
@@ -461,7 +459,7 @@ export default function AddEditItemScreen(): React.ReactNode {
}
// Load TOTP codes for this item
- const itemTotpCodes = await dbContext.sqliteClient!.settings.getTotpCodesForItem(id);
+ const itemTotpCodes = await dbContext.sqliteClient!.items.getTotpCodesForItem(id);
setTotpCodes(itemTotpCodes);
setOriginalTotpCodeIds(itemTotpCodes.map(tc => tc.Id));
if (itemTotpCodes.length > 0) {
@@ -503,7 +501,7 @@ export default function AddEditItemScreen(): React.ReactNode {
if (isEditMode) {
// Load password settings BEFORE loading item so it's available when components render
try {
- const settings = await dbContext.sqliteClient!.getPasswordSettings();
+ const settings = await dbContext.sqliteClient!.settings.getPasswordSettings();
setPasswordSettings(settings);
} catch (err) {
console.error('Error loading password settings:', err);
@@ -512,7 +510,7 @@ export default function AddEditItemScreen(): React.ReactNode {
} else {
// Create mode
try {
- const settings = await dbContext.sqliteClient!.getPasswordSettings();
+ const settings = await dbContext.sqliteClient!.settings.getPasswordSettings();
setPasswordSettings(settings);
} catch (err) {
console.error('Error loading password settings:', err);
@@ -827,11 +825,11 @@ export default function AddEditItemScreen(): React.ReactNode {
};
// Extract favicon from URL if present.
- const faviconTarget = await selectFaviconTarget(fieldValues['login.url']);
+ const faviconTarget = await RustCore.selectFaviconTarget(RustCore.toUrlList(fieldValues['login.url']));
if (faviconTarget && dbContext.sqliteClient) {
// Only fetch favicon if no logo exists for this source (deduplication)
- const hasExistingLogo = await dbContext.sqliteClient.logos.hasLogoForSource(faviconTarget.source);
+ const hasExistingLogo = await dbContext.sqliteClient.logos.hasFaviconForSource(faviconTarget.source);
if (!hasExistingLogo) {
// Only show loading indicator when fetching favicon
@@ -870,7 +868,7 @@ export default function AddEditItemScreen(): React.ReactNode {
// Delete passkeys if marked for deletion
if (passkeyIdsMarkedForDeletion.length > 0) {
for (const passkeyId of passkeyIdsMarkedForDeletion) {
- await dbContext.sqliteClient!.passkeys.delete(passkeyId);
+ await dbContext.sqliteClient!.passkeys.deleteById(passkeyId);
}
}
} else {
diff --git a/apps/mobile-app/app/(tabs)/items/deleted.tsx b/apps/mobile-app/app/(tabs)/items/deleted.tsx
index 6bf7ed916..430f1bac5 100644
--- a/apps/mobile-app/app/(tabs)/items/deleted.tsx
+++ b/apps/mobile-app/app/(tabs)/items/deleted.tsx
@@ -10,7 +10,6 @@ import {
} from 'react-native';
import Toast from 'react-native-toast-message';
-import type { ItemWithDeletedAt } from '@/utils/db/mappers/ItemMapper';
import emitter from '@/utils/EventEmitter';
import { useColors } from '@/hooks/useColorScheme';
@@ -24,6 +23,8 @@ import { ThemedText } from '@/components/themed/ThemedText';
import { TRASH_RETENTION_DAYS } from '@/constants/vault';
import { useDb } from '@/context/DbContext';
+import type { ItemWithDeletedAt } from '@aliasvault/client/database/mappers/ItemMapper';
+
/**
* Calculate days remaining until permanent deletion.
* @param deletedAt - ISO timestamp when item was deleted
diff --git a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
index d8e660066..76acba44a 100644
--- a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
@@ -1,3 +1,5 @@
+import { canHaveSubfolders, getRecursiveItemCount } from '@aliasvault/client/items/FolderUtils';
+import { applyTypeFilter, isItemTypeFilter, parseItemFilterType, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
import { getFieldValue, FieldKey, ItemTypes } from '@aliasvault/models/vault';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useNavigation, useRouter, useLocalSearchParams } from 'expo-router';
@@ -7,12 +9,8 @@ import { StyleSheet, Platform, View, Text, TextInput, TouchableOpacity, RefreshC
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Toast from 'react-native-toast-message';
-import type { Folder } from '@/utils/db/repositories/FolderRepository';
-import type { CredentialSortOrder } from '@/utils/db/repositories/SettingsRepository';
import emitter from '@/utils/EventEmitter';
-import { canHaveSubfolders, getRecursiveItemCount } from '@/utils/FolderUtils';
import { HapticsUtility } from '@/utils/HapticsUtility';
-import { applyTypeFilter, isItemTypeFilter, parseItemFilterType, type ItemFilterType } from '@/utils/ItemFilters';
import { VaultAuthenticationError } from '@/utils/types/errors/VaultAuthenticationError';
import { useColors } from '@/hooks/useColorScheme';
@@ -39,6 +37,8 @@ import { useDb } from '@/context/DbContext';
import { useDialog } from '@/context/DialogContext';
import type { FolderWithCount } from '@/components/folders/FolderPill';
+import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
+import type { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import type { Item, ItemType } from '@aliasvault/models/vault';
/**
diff --git a/apps/mobile-app/app/(tabs)/items/index.tsx b/apps/mobile-app/app/(tabs)/items/index.tsx
index 72050db1f..f183908f3 100644
--- a/apps/mobile-app/app/(tabs)/items/index.tsx
+++ b/apps/mobile-app/app/(tabs)/items/index.tsx
@@ -1,3 +1,4 @@
+import { applyTypeFilter, isItemTypeFilter, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
import { getFieldValue, FieldKey, ItemTypes } from '@aliasvault/models/vault';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useNavigation, useRouter, useLocalSearchParams } from 'expo-router';
@@ -7,11 +8,8 @@ import { StyleSheet, Text, Platform, Animated, TextInput, TouchableOpacity, View
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Toast from 'react-native-toast-message';
-import type { Folder } from '@/utils/db/repositories/FolderRepository';
-import type { CredentialSortOrder } from '@/utils/db/repositories/SettingsRepository';
import emitter from '@/utils/EventEmitter';
import { HapticsUtility } from '@/utils/HapticsUtility';
-import { applyTypeFilter, isItemTypeFilter, type ItemFilterType } from '@/utils/ItemFilters';
import { VaultAuthenticationError } from '@/utils/types/errors/VaultAuthenticationError';
import { useAppReviewPrompt } from '@/hooks/useAppReviewPrompt';
@@ -39,6 +37,8 @@ import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
import { LocalPreferencesService } from '@/services/LocalPreferencesService';
+import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
+import type { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import type { Item, ItemType } from '@aliasvault/models/vault';
/**
diff --git a/apps/mobile-app/app/(tabs)/settings/identity-generator-language.tsx b/apps/mobile-app/app/(tabs)/settings/identity-generator-language.tsx
index 65a54d2e8..03010ad92 100644
--- a/apps/mobile-app/app/(tabs)/settings/identity-generator-language.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/identity-generator-language.tsx
@@ -1,3 +1,4 @@
+import { getIdentityLanguages } from '@aliasvault/client/rust/RustCore';
import { getLanguageInfo } from '@aliasvault/models/defaults';
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect, useRouter } from 'expo-router';
@@ -5,8 +6,6 @@ import { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, TouchableOpacity } from 'react-native';
-import { getIdentityLanguages } from '@/utils/IdentityGeneratorUtility';
-
import { useColors } from '@/hooks/useColorScheme';
import { useVaultMutate } from '@/hooks/useVaultMutate';
@@ -43,7 +42,7 @@ export default function IdentityGeneratorLanguageScreen(): React.ReactNode {
const loadSettings = async (): Promise<void> => {
try {
const [currentLanguage, availableLanguages] = await Promise.all([
- dbContext.sqliteClient!.getEffectiveIdentityLanguage(),
+ dbContext.sqliteClient!.settings.getEffectiveIdentityLanguage(),
getIdentityLanguages()
]);
@@ -73,7 +72,7 @@ export default function IdentityGeneratorLanguageScreen(): React.ReactNode {
try {
await executeVaultMutation(async () => {
- await dbContext.sqliteClient!.updateSetting('DefaultIdentityLanguage', pendingChanges.current.language!);
+ await dbContext.sqliteClient!.settings.updateSetting('DefaultIdentityLanguage', pendingChanges.current.language!);
});
pendingChanges.current = {};
} catch (error) {
diff --git a/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx b/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx
index 03985ded4..726a5cc5d 100644
--- a/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/identity-generator.tsx
@@ -1,3 +1,4 @@
+import { getIdentityAgeRanges } from '@aliasvault/client/rust/RustCore';
import { getLanguageInfo } from '@aliasvault/models/defaults';
import { Ionicons } from '@expo/vector-icons';
import { useFocusEffect, useRouter } from 'expo-router';
@@ -5,8 +6,6 @@ import { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, TouchableOpacity } from 'react-native';
-import { getIdentityAgeRanges } from '@/utils/IdentityGeneratorUtility';
-
import { useColors } from '@/hooks/useColorScheme';
import { useVaultMutate } from '@/hooks/useVaultMutate';
@@ -50,9 +49,9 @@ export default function IdentityGeneratorSettingsScreen(): React.ReactNode {
const loadSettings = async (): Promise<void> => {
try {
const [currentLanguage, currentGender, currentAgeRange, availableAgeRanges] = await Promise.all([
- dbContext.sqliteClient!.getEffectiveIdentityLanguage(),
- dbContext.sqliteClient!.getDefaultIdentityGender(),
- dbContext.sqliteClient!.getDefaultIdentityAgeRange(),
+ dbContext.sqliteClient!.settings.getEffectiveIdentityLanguage(),
+ dbContext.sqliteClient!.settings.getDefaultIdentityGender(),
+ dbContext.sqliteClient!.settings.getDefaultIdentityAgeRange(),
getIdentityAgeRanges()
]);
@@ -90,10 +89,10 @@ export default function IdentityGeneratorSettingsScreen(): React.ReactNode {
// Save all pending changes in a single vault mutation (language is managed in subview)
await executeVaultMutation(async () => {
if (pendingChanges.current.gender !== undefined) {
- await dbContext.sqliteClient!.updateSetting('DefaultIdentityGender', pendingChanges.current.gender);
+ await dbContext.sqliteClient!.settings.updateSetting('DefaultIdentityGender', pendingChanges.current.gender);
}
if (pendingChanges.current.ageRange !== undefined) {
- await dbContext.sqliteClient!.updateSetting('DefaultIdentityAgeRange', pendingChanges.current.ageRange);
+ await dbContext.sqliteClient!.settings.updateSetting('DefaultIdentityAgeRange', pendingChanges.current.ageRange);
}
});
diff --git a/apps/mobile-app/app/(tabs)/settings/import-export.tsx b/apps/mobile-app/app/(tabs)/settings/import-export.tsx
index a238f2b97..12943660d 100644
--- a/apps/mobile-app/app/(tabs)/settings/import-export.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/import-export.tsx
@@ -125,7 +125,7 @@ export default function ImportExportScreen(): React.ReactNode {
*/
for (const item of items) {
// Get TOTP codes for this item
- const totpCodes = await dbContext.sqliteClient?.settings.getTotpCodesForItem(item.Id) ?? [];
+ const totpCodes = await dbContext.sqliteClient?.items.getTotpCodesForItem(item.Id) ?? [];
const totpSecret = totpCodes.length > 0 ? totpCodes[0].SecretKey : '';
/*
diff --git a/apps/mobile-app/app/(tabs)/settings/index.tsx b/apps/mobile-app/app/(tabs)/settings/index.tsx
index bea3d5a46..212711789 100644
--- a/apps/mobile-app/app/(tabs)/settings/index.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/index.tsx
@@ -1,3 +1,4 @@
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { Ionicons } from '@expo/vector-icons';
import { router, useFocusEffect, useNavigation } from 'expo-router';
import { useEffect, useRef, useState, useCallback } from 'react';
@@ -5,7 +6,6 @@ import { StyleSheet, View, ScrollView, TouchableOpacity, Animated, Platform, Lin
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useApiUrl } from '@/utils/ApiUrlUtility';
-import { AppInfo } from '@/utils/AppInfo';
import { AppUnlockUtility } from '@/utils/AppUnlockUtility';
import { useColors } from '@/hooks/useColorScheme';
diff --git a/apps/mobile-app/app/(tabs)/settings/password-generator.tsx b/apps/mobile-app/app/(tabs)/settings/password-generator.tsx
index e9b0543df..b6536b281 100644
--- a/apps/mobile-app/app/(tabs)/settings/password-generator.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/password-generator.tsx
@@ -41,7 +41,7 @@ export default function PasswordGeneratorSettingsScreen(): React.ReactNode {
*/
const loadSettings = async (): Promise<void> => {
try {
- const passwordSettings = await dbContext.sqliteClient!.getPasswordSettings();
+ const passwordSettings = await dbContext.sqliteClient!.settings.getPasswordSettings();
setSettings(passwordSettings);
latestSettings.current = passwordSettings;
persistedJson.current = JSON.stringify(passwordSettings);
@@ -66,7 +66,7 @@ export default function PasswordGeneratorSettingsScreen(): React.ReactNode {
}
executeVaultMutation(async () => {
- await dbContext.sqliteClient!.updateSetting('PasswordGenerationSettings', currentJson);
+ await dbContext.sqliteClient!.settings.updateSetting('PasswordGenerationSettings', currentJson);
}).then(() => {
persistedJson.current = currentJson;
}).catch((error) => {
diff --git a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
index 7a42b14cd..f7eba800f 100644
--- a/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/security/delete-account.tsx
@@ -1,12 +1,11 @@
import { Buffer } from 'buffer';
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import { router } from 'expo-router';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, KeyboardAvoidingView, Platform } from 'react-native';
-import { SrpUtility } from '@/utils/SrpUtility';
-
import { useColors } from '@/hooks/useColorScheme';
import LoadingOverlay from '@/components/LoadingOverlay';
@@ -167,7 +166,7 @@ export default function DeleteAccountScreen(): React.ReactNode {
const currentPasswordHashString = Buffer.from(currentPasswordHashBase64, 'base64').toString('hex').toUpperCase();
// Derive the SRP client proof to authenticate the deletion with the server.
- const clientProof = await SrpUtility.deriveClientProof(
+ const clientProof = await SrpAuthService.deriveClientProof(
currentSalt,
srpIdentity,
currentPasswordHashString,
diff --git a/apps/mobile-app/app/_layout.tsx b/apps/mobile-app/app/_layout.tsx
index 3c28ae7ad..aa8418125 100644
--- a/apps/mobile-app/app/_layout.tsx
+++ b/apps/mobile-app/app/_layout.tsx
@@ -8,6 +8,7 @@ import 'react-native-get-random-values';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { install } from 'react-native-quick-crypto';
+import '@/platform/MobilePlatform';
import { resolveDeepLink } from '@/utils/DeepLinkResolver';
import { useColors, useColorScheme } from '@/hooks/useColorScheme';
diff --git a/apps/mobile-app/app/login-settings.tsx b/apps/mobile-app/app/login-settings.tsx
index 40a449130..1bcfdb7fd 100644
--- a/apps/mobile-app/app/login-settings.tsx
+++ b/apps/mobile-app/app/login-settings.tsx
@@ -1,10 +1,9 @@
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useNavigation, useRouter } from 'expo-router';
import { useState, useEffect, useCallback, useMemo, useLayoutEffect } from 'react';
import { StyleSheet, View, Text, TextInput, ActivityIndicator, KeyboardAvoidingView, Platform } from 'react-native';
-import { AppInfo } from '@/utils/AppInfo';
-
import { useColors } from '@/hooks/useColorScheme';
import { useTranslation } from '@/hooks/useTranslation';
diff --git a/apps/mobile-app/app/login.tsx b/apps/mobile-app/app/login.tsx
index adb0c17d4..990396241 100644
--- a/apps/mobile-app/app/login.tsx
+++ b/apps/mobile-app/app/login.tsx
@@ -1,5 +1,9 @@
import { Buffer } from 'buffer';
+import { ApiAuthError } from '@aliasvault/client/api/errors/ApiAuthError';
+import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
+import { SrpLoginService } from '@aliasvault/client/auth/SrpLoginService';
import { MaterialIcons } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import { router, useFocusEffect } from 'expo-router';
@@ -9,11 +13,7 @@ import { SafeAreaView } from 'react-native-safe-area-context';
import { useApiUrl } from '@/utils/ApiUrlUtility';
import { AppUnlockUtility } from '@/utils/AppUnlockUtility';
-import ConversionUtility from '@/utils/ConversionUtility';
import EncryptionUtility from '@/utils/EncryptionUtility';
-import { SrpUtility } from '@/utils/SrpUtility';
-import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';
-import { ClientUpgradeRequiredError } from '@/utils/types/errors/ClientUpgradeRequiredError';
import { LocalAuthError } from '@/utils/types/errors/LocalAuthError';
import { useColors } from '@/hooks/useColorScheme';
@@ -154,7 +154,7 @@ export default function LoginScreen() : React.ReactNode {
const webApi = useWebApi();
const { syncVault } = useVaultSync();
- const srpUtil = new SrpUtility(webApi);
+ const srpUtil = new SrpLoginService(webApi);
/**
* Process the vault response by storing the vault and logging in the user.
@@ -257,7 +257,7 @@ export default function LoginScreen() : React.ReactNode {
* Store auth tokens and encryption credentials. syncVault will download
* the vault and store it (including metadata) through native code.
*/
- await authContext.setAuthTokens(ConversionUtility.normalizeUsername(credentials.username), token, refreshToken);
+ await authContext.setAuthTokens(SrpAuthService.normalizeUsername(credentials.username), token, refreshToken);
await dbContext.storeEncryptionKeyDerivationParams(encryptionKeyDerivationParams);
/*
@@ -277,7 +277,7 @@ export default function LoginScreen() : React.ReactNode {
const hasExistingVault = await NativeVaultManager.hasEncryptedDatabase();
if (hasExistingVault) {
const storedUsername = await NativeVaultManager.getUsername();
- const normalizedLoginUsername = ConversionUtility.normalizeUsername(credentials.username);
+ const normalizedLoginUsername = SrpAuthService.normalizeUsername(credentials.username);
if (storedUsername && storedUsername !== normalizedLoginUsername) {
// Different user: clear vault and download fresh
@@ -385,7 +385,7 @@ export default function LoginScreen() : React.ReactNode {
await new Promise(resolve => requestAnimationFrame(resolve));
try {
- const initiateLoginResponse = await srpUtil.initiateLogin(ConversionUtility.normalizeUsername(credentials.username));
+ const initiateLoginResponse = await srpUtil.initiateLogin(SrpAuthService.normalizeUsername(credentials.username));
const passwordHash = await EncryptionUtility.deriveKeyFromPassword(
credentials.password,
@@ -400,7 +400,7 @@ export default function LoginScreen() : React.ReactNode {
setLoginStatus(t('auth.validatingCredentials'));
await new Promise(resolve => requestAnimationFrame(resolve));
const validationResponse = await srpUtil.validateLogin(
- ConversionUtility.normalizeUsername(credentials.username),
+ SrpAuthService.normalizeUsername(credentials.username),
passwordHashString,
true,
initiateLoginResponse
@@ -471,7 +471,7 @@ export default function LoginScreen() : React.ReactNode {
}
const validationResponse = await srpUtil.validateLogin2Fa(
- ConversionUtility.normalizeUsername(credentials.username),
+ SrpAuthService.normalizeUsername(credentials.username),
passwordHashString,
true,
initiateLoginResponse,
diff --git a/apps/mobile-app/app/unlock.tsx b/apps/mobile-app/app/unlock.tsx
index c06c90809..537d3eaa8 100644
--- a/apps/mobile-app/app/unlock.tsx
+++ b/apps/mobile-app/app/unlock.tsx
@@ -1,3 +1,4 @@
+import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import * as Haptics from 'expo-haptics';
import { LinearGradient } from 'expo-linear-gradient';
import { router } from 'expo-router';
@@ -7,7 +8,6 @@ import { StyleSheet, View, KeyboardAvoidingView, Platform, ScrollView, Dimension
import { AppUnlockUtility } from '@/utils/AppUnlockUtility';
import { HapticsUtility } from '@/utils/HapticsUtility';
import { AppErrorCode, getAppErrorCode, getErrorTranslationKey, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';
-import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
import { useColors } from '@/hooks/useColorScheme';
import { useLogout } from '@/hooks/useLogout';
diff --git a/apps/mobile-app/components/EmailCard.tsx b/apps/mobile-app/components/EmailCard.tsx
index 41ffd0e78..7447b6464 100644
--- a/apps/mobile-app/components/EmailCard.tsx
+++ b/apps/mobile-app/components/EmailCard.tsx
@@ -42,7 +42,8 @@ export function EmailCard({ email }: EmailCardProps) : React.ReactNode {
}
const emailAddress = `${email.toLocal}@${email.toDomain}`;
- const item = await dbContext.sqliteClient.items.getByEmail(emailAddress);
+ const match = await dbContext.sqliteClient.items.findIdByEmail(emailAddress);
+ const item = match ? await dbContext.sqliteClient.items.getById(match.Id) : null;
setAssociatedItem(item);
};
diff --git a/apps/mobile-app/components/folders/FolderBreadcrumb.tsx b/apps/mobile-app/components/folders/FolderBreadcrumb.tsx
index ede616a85..229e3c213 100644
--- a/apps/mobile-app/components/folders/FolderBreadcrumb.tsx
+++ b/apps/mobile-app/components/folders/FolderBreadcrumb.tsx
@@ -4,7 +4,7 @@ import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
-import { getFolderIdPath, getFolderPath } from '@/utils/FolderUtils';
+import { getFolderIdPath, getFolderPath } from '@aliasvault/client/items/FolderUtils';
import { useColors } from '@/hooks/useColorScheme';
import { useDb } from '@/context/DbContext';
diff --git a/apps/mobile-app/components/form/AdvancedPasswordField.tsx b/apps/mobile-app/components/form/AdvancedPasswordField.tsx
index 207b3c118..b5ea78bc1 100644
--- a/apps/mobile-app/components/form/AdvancedPasswordField.tsx
+++ b/apps/mobile-app/components/form/AdvancedPasswordField.tsx
@@ -7,8 +7,8 @@ import { View, TextInput, TextInputProps, StyleSheet, Platform, TouchableOpacity
import type { PasswordSettings } from '@aliasvault/models/vault';
import { MIN_WORD_COUNT, MAX_WORD_COUNT, DEFAULT_WORD_COUNT } from '@aliasvault/models/defaults';
import { HapticsUtility } from '@/utils/HapticsUtility';
-import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@/utils/PasswordLengthSlider';
-import * as PasswordGenerator from '@/utils/PasswordGeneratorUtility';
+import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@aliasvault/client/utilities/PasswordLengthSlider';
+import * as RustCore from '@aliasvault/client/rust/RustCore';
import { useColors } from '@/hooks/useColorScheme';
@@ -90,7 +90,7 @@ const AdvancedPasswordFieldComponent = forwardRef<AdvancedPasswordFieldRef, Adva
const loadSettings = async () => {
try {
if (dbContext.sqliteClient) {
- const settings = await dbContext.sqliteClient.getPasswordSettings();
+ const settings = await dbContext.sqliteClient.settings.getPasswordSettings();
setCurrentSettings(settings);
if (!hasSetInitialLength.current) {
setSliderValue(lengthToSlider(settings.Length));
@@ -131,7 +131,7 @@ const AdvancedPasswordFieldComponent = forwardRef<AdvancedPasswordFieldRef, Adva
*/
const generatePassword = useCallback(async (settings: PasswordSettings): Promise<string> => {
try {
- return await PasswordGenerator.generatePassword(settings);
+ return await RustCore.generatePassword(settings);
} catch (error) {
console.error('Error generating password:', error);
return '';
diff --git a/apps/mobile-app/components/form/PasswordGeneratorPanel.tsx b/apps/mobile-app/components/form/PasswordGeneratorPanel.tsx
index a93444ca0..a04f2b749 100644
--- a/apps/mobile-app/components/form/PasswordGeneratorPanel.tsx
+++ b/apps/mobile-app/components/form/PasswordGeneratorPanel.tsx
@@ -6,8 +6,8 @@ import { Platform, StyleSheet, TouchableOpacity, View } from 'react-native';
import type { PasswordSettings, DicewareCapitalization, DicewareSeparator, DicewareSalt } from '@aliasvault/models/vault';
import { MIN_WORD_COUNT, MAX_WORD_COUNT, DEFAULT_WORD_COUNT, getLanguageInfo, resolveDefaultLanguage } from '@aliasvault/models/defaults';
-import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@/utils/PasswordLengthSlider';
-import * as PasswordGenerator from '@/utils/PasswordGeneratorUtility';
+import { sliderToLength, lengthToSlider, SLIDER_MIN, SLIDER_MAX } from '@aliasvault/client/utilities/PasswordLengthSlider';
+import * as RustCore from '@aliasvault/client/rust/RustCore';
import { useColors } from '@/hooks/useColorScheme';
@@ -52,7 +52,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr
const generatePreview = useCallback(async (currentSettings: PasswordSettings, seed: string): Promise<void> => {
try {
- const password = await PasswordGenerator.generatePassword(currentSettings, seed);
+ const password = await RustCore.generatePassword(currentSettings, seed);
setPreviewPassword(password);
onPreviewChange?.(password);
} catch (error) {
@@ -62,10 +62,10 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr
// Initialize the seed + preview on mount, and load the available languages.
useEffect(() => {
- seedRef.current = PasswordGenerator.generateSeed();
+ seedRef.current = RustCore.generateSeed();
void generatePreview(initialSettings, seedRef.current);
let cancelled = false;
- void PasswordGenerator.getDicewareLanguages().then((languages) => {
+ void RustCore.getDicewareLanguages().then((languages) => {
if (!cancelled) {
setDicewareLanguages(languages);
}
@@ -93,7 +93,7 @@ export function PasswordGeneratorPanel({ initialSettings, onSettingsChange, onPr
* Draw a fresh seed and regenerate the preview (a genuinely new password).
*/
const handleRefreshPreview = useCallback((): void => {
- seedRef.current = PasswordGenerator.generateSeed();
+ seedRef.current = RustCore.generateSeed();
void generatePreview(settings, seedRef.current);
}, [generatePreview, settings]);
diff --git a/apps/mobile-app/components/items/ItemCard.tsx b/apps/mobile-app/components/items/ItemCard.tsx
index 9e60e407b..ee9abbfc6 100644
--- a/apps/mobile-app/components/items/ItemCard.tsx
+++ b/apps/mobile-app/components/items/ItemCard.tsx
@@ -169,7 +169,7 @@ export function ItemCard({ item, onItemDelete, onItemDuplicate, showFolderPath =
{
if (dbContext?.sqliteClient) {
try {
- const totpCodes = await dbContext.sqliteClient.settings.getTotpCodesForItem(item.Id);
+ const totpCodes = await dbContext.sqliteClient.items.getTotpCodesForItem(item.Id);
const activeTotp = totpCodes.find(tc => !tc.IsDeleted);
if (activeTotp) {
const code = await generateTotpCode(activeTotp.SecretKey, activeTotp);
diff --git a/apps/mobile-app/components/items/ItemFilterMenu.tsx b/apps/mobile-app/components/items/ItemFilterMenu.tsx
index 8e6c4a9fe..91db32455 100644
--- a/apps/mobile-app/components/items/ItemFilterMenu.tsx
+++ b/apps/mobile-app/components/items/ItemFilterMenu.tsx
@@ -4,7 +4,7 @@ import { Platform, StyleSheet, TouchableOpacity, View } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { ItemTypes, type ItemType } from '@aliasvault/models/vault';
-import type { ItemFilterType } from '@/utils/ItemFilters';
+import type { ItemFilterType } from '@aliasvault/client/items/ItemFilters';
import { useColors } from '@/hooks/useColorScheme';
diff --git a/apps/mobile-app/components/items/SortMenu.tsx b/apps/mobile-app/components/items/SortMenu.tsx
index 1331e3c85..906946c6c 100644
--- a/apps/mobile-app/components/items/SortMenu.tsx
+++ b/apps/mobile-app/components/items/SortMenu.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from 'react-i18next';
import { StyleSheet, TouchableOpacity, View, Platform } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
-import type { CredentialSortOrder } from '@/utils/db/repositories/SettingsRepository';
+import type { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import { useColors } from '@/hooks/useColorScheme';
import { SORT_OPTIONS } from '@/hooks/useItemSort';
diff --git a/apps/mobile-app/components/items/details/AttachmentSection.tsx b/apps/mobile-app/components/items/details/AttachmentSection.tsx
index e6b7119a9..32f069bc1 100644
--- a/apps/mobile-app/components/items/details/AttachmentSection.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentSection.tsx
@@ -51,7 +51,7 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
if (typeof attachment.Blob === 'string') {
file.write(attachment.Blob, { encoding: 'base64' });
} else {
- file.write(attachment.Blob as unknown as Uint8Array);
+ file.write((attachment.Blob ?? new Uint8Array(0)) as unknown as Uint8Array);
}
await openAttachment({ filePath: file.uri, fileName: sanitizedFilename });
@@ -70,7 +70,7 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
}
try {
- const attachmentList = await dbContext.sqliteClient.settings.getAttachmentsForItem(item.Id);
+ const attachmentList = await dbContext.sqliteClient.items.getAttachmentsForItem(item.Id);
setAttachments(attachmentList);
} catch (error) {
console.error('Error loading attachments:', error);
diff --git a/apps/mobile-app/components/items/details/EmailPreview.tsx b/apps/mobile-app/components/items/details/EmailPreview.tsx
index b06e73695..e8565a770 100644
--- a/apps/mobile-app/components/items/details/EmailPreview.tsx
+++ b/apps/mobile-app/components/items/details/EmailPreview.tsx
@@ -4,8 +4,8 @@ import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity, Linking, AppState } from 'react-native';
-import { AppInfo } from '@/utils/AppInfo';
-import type { ApiErrorResponse, MailboxEmail } from '@/utils/dist/core/models/webapi';
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
+import type { ApiErrorResponse, MailboxEmail } from '@aliasvault/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
import { useColors } from '@/hooks/useColorScheme';
@@ -171,12 +171,12 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
try {
// Get all encryption keys
- const encryptionKeys = await dbContext.sqliteClient.getAllEncryptionKeys();
+ const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
// Use single emailbox operator instead of bulk
const response = await webApi.authFetch(`EmailBox/${email}`, { method: 'GET' }, true, false);
try {
- const data = response as { mails: MailboxEmail[] };
+ const data = response as { mails: MailboxEmail[]; publicKeys: string[] };
// Store all emails, sorted by date
const allMails = data.mails
@@ -186,6 +186,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
// Loop through all emails and decrypt them locally
const decryptedEmails = await EncryptionUtility.decryptEmailList(
allMails,
+ data.publicKeys,
encryptionKeys
);
diff --git a/apps/mobile-app/components/items/details/TotpEditor.tsx b/apps/mobile-app/components/items/details/TotpEditor.tsx
index 5fa0fbf92..c5aadb750 100644
--- a/apps/mobile-app/components/items/details/TotpEditor.tsx
+++ b/apps/mobile-app/components/items/details/TotpEditor.tsx
@@ -12,7 +12,7 @@ import { useColors } from '@/hooks/useColorScheme';
import NativeVaultManager from '@/specs/NativeVaultManager';
import type { TotpCode } from '@aliasvault/models/vault';
import { TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
-import { buildOtpAuthUri, parseOtpAuthUri } from '@/utils/TotpUtility';
+import { buildOtpAuthUri, parseOtpAuthUri } from '@aliasvault/client/items/OtpAuthUri';
type TotpFormData = {
name: string;
@@ -109,7 +109,7 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({
if (scannedData) {
// Parse the otpauth:// URL
const parsed = parseOtpAuthUri(scannedData);
- if (parsed && parsed.type === 'totp') {
+ if (parsed) {
const secretKey = parsed.secret.replace(/\s/g, '').replace(/=+$/, '');
const name = parsed.label || '';
@@ -164,7 +164,7 @@ export const TotpEditor: React.FC<TotpEditorProps> = ({
// Check if it's a TOTP URI
if (secretKey.toLowerCase().startsWith('otpauth://totp/')) {
const parsed = parseOtpAuthUri(secretKey);
- if (!parsed || parsed.type !== 'totp') {
+ if (!parsed) {
throw new Error(t('totp.errors.invalidSecretKey'));
}
secretKey = parsed.secret;
diff --git a/apps/mobile-app/components/items/details/TotpSection.tsx b/apps/mobile-app/components/items/details/TotpSection.tsx
index 7b99ae632..249585856 100644
--- a/apps/mobile-app/components/items/details/TotpSection.tsx
+++ b/apps/mobile-app/components/items/details/TotpSection.tsx
@@ -91,7 +91,7 @@ export const TotpSection: React.FC<TotpSectionProps> = ({ item }) : React.ReactN
}
try {
- const codes = await dbContext.sqliteClient.settings.getTotpCodesForItem(item.Id);
+ const codes = await dbContext.sqliteClient.items.getTotpCodesForItem(item.Id);
setTotpCodes(codes);
} catch (error) {
console.error('Error loading TOTP codes:', error);
diff --git a/apps/mobile-app/hooks/useAppReviewPrompt.ts b/apps/mobile-app/hooks/useAppReviewPrompt.ts
index b0ae5a9da..bde08ac1d 100644
--- a/apps/mobile-app/hooks/useAppReviewPrompt.ts
+++ b/apps/mobile-app/hooks/useAppReviewPrompt.ts
@@ -2,7 +2,7 @@ import AsyncStorage from '@react-native-async-storage/async-storage';
import { useCallback, useEffect, useState } from 'react';
import { AppState } from 'react-native';
-import { AppInfo } from '@/utils/AppInfo';
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import NativeVaultManager from '@/specs/NativeVaultManager';
diff --git a/apps/mobile-app/hooks/useItemSort.ts b/apps/mobile-app/hooks/useItemSort.ts
index df8c88057..ef14bd860 100644
--- a/apps/mobile-app/hooks/useItemSort.ts
+++ b/apps/mobile-app/hooks/useItemSort.ts
@@ -1,6 +1,6 @@
import { useState, useMemo, useCallback } from 'react';
-import type { CredentialSortOrder } from '@/utils/db/repositories/SettingsRepository';
+import type { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import type { Item } from '@aliasvault/models/vault';
/**
diff --git a/apps/mobile-app/hooks/useVaultMutate.ts b/apps/mobile-app/hooks/useVaultMutate.ts
index 973ffc316..f35ab94cf 100644
--- a/apps/mobile-app/hooks/useVaultMutate.ts
+++ b/apps/mobile-app/hooks/useVaultMutate.ts
@@ -8,12 +8,12 @@ import type { EncryptionKeyDerivationParams } from '@aliasvault/models/metadata'
import type { PasswordChangeInitiateResponse, Vault, VaultPasswordChangeRequest } from '@aliasvault/models/webapi';
import { FieldKey, getFieldValue } from '@aliasvault/models/vault';
import EncryptionUtility from '@/utils/EncryptionUtility';
-import { SrpUtility } from '@/utils/SrpUtility';
+import { SrpAuthService } from '@aliasvault/client/auth/SrpAuthService';
import { useVaultSync } from '@/hooks/useVaultSync';
import { AppErrorCode, formatErrorWithCode } from '@/utils/types/errors/AppErrorCodes';
-import { PayloadTooLargeError } from '@/utils/types/errors/PayloadTooLargeError';
+import { PayloadTooLargeError } from '@aliasvault/client/api/errors/PayloadTooLargeError';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
@@ -203,7 +203,7 @@ export function useVaultMutate() : {
const srpIdentity = data.srpIdentity ?? username;
// Derive the SRP client proof for the current password to authorize the change.
- const currentClientProof = await SrpUtility.deriveClientProof(
+ const currentClientProof = await SrpAuthService.deriveClientProof(
currentSalt,
srpIdentity,
currentPasswordHashString,
@@ -211,7 +211,7 @@ export function useVaultMutate() : {
);
// Generate salt and verifier for new password using native SRP
- const newSalt = await SrpUtility.generateSalt();
+ const newSalt = await SrpAuthService.generateSalt();
const newPasswordHash = await EncryptionUtility.deriveKeyFromPassword(newPasswordPlainText, newSalt, data.encryptionType, data.encryptionSettings);
const newPasswordHashString = Buffer.from(newPasswordHash).toString('hex').toUpperCase();
@@ -242,7 +242,7 @@ export function useVaultMutate() : {
}
// Generate SRP password change data (verifier for the new password) using native SRP
- const newVerifier = await SrpUtility.deriveVerifier(newSalt, srpIdentity, newPasswordHashString);
+ const newVerifier = await SrpAuthService.deriveVerifier(await SrpAuthService.derivePrivateKey(newSalt, srpIdentity, newPasswordHashString));
// Prepare vault for password change
const vault = await prepareVaultForPasswordChange();
diff --git a/apps/mobile-app/hooks/useVaultSync.ts b/apps/mobile-app/hooks/useVaultSync.ts
index 7e65cc81f..4a1bd3b58 100644
--- a/apps/mobile-app/hooks/useVaultSync.ts
+++ b/apps/mobile-app/hooks/useVaultSync.ts
@@ -6,7 +6,7 @@ import { useTranslation } from '@/hooks/useTranslation';
import { useApp } from '@/context/AppContext';
import { useDb } from '@/context/DbContext';
import NativeVaultManager from '@/specs/NativeVaultManager';
-import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
+import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import {
AppErrorCode,
getAppErrorCode,
@@ -132,9 +132,10 @@ export const useVaultSync = (): {
if (!result.success) {
// Check for specific error conditions
if (result.error) {
+ console.error(`[useVaultSync] Sync failed (${result.error}): ${result.errorMessage ?? 'no detail'}`);
const errorCode = extractErrorCode(result.error) ?? getAppErrorCode(result.error);
if (errorCode) {
- return await handleSyncError(result.error, errorCode, app, dbContext, t, onError, onOffline);
+ return await handleSyncError(result.errorMessage, errorCode, app, dbContext, t, onError, onOffline);
}
}
@@ -264,11 +265,9 @@ export const useVaultSync = (): {
* For critical errors requiring logout (auth, version), we ALWAYS use app.logout(message)
* which shows a native Alert.alert that persists through navigation on both platforms.
* The onError callback is only used for non-critical errors that don't require logout.
- *
- * Error codes are included in messages to help users report issues for debugging.
*/
async function handleSyncError(
- _err: unknown,
+ detail: unknown,
errorCode: AppErrorCode,
app: ReturnType<typeof useApp>,
dbContext: ReturnType<typeof useDb>,
@@ -312,7 +311,15 @@ async function handleSyncError(
// All other errors - show error with code for debugging
default:
- onError?.(messageWithCode);
+ onError?.(withTechnicalDetail(messageWithCode, detail));
return false;
}
}
+
+/**
+ * Append the technical detail of a failure to its translated message if available.
+ */
+function withTechnicalDetail(message: string, detail: unknown): string {
+ const text = typeof detail === 'string' ? detail : detail instanceof Error ? detail.message : '';
+ return text && text !== message ? `${message}\n${text}` : message;
+}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift b/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift
index f8b50d336..b6598fc86 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/WebApiService.swift
@@ -26,8 +26,8 @@ public class WebApiService {
private let refreshTokenKey = "refreshToken"
private let customProxyHeadersKey = "customProxyHeaders"
- // Default API URL
- private let defaultApiUrl = "https://app.aliasvault.com/api"
+ // Default API URL, shared by every client (generated from the models package).
+ private let defaultApiUrl = AppInfo.defaultApiUrl
/// Shared UserDefaults for communication between main app and extension
private let userDefaults = UserDefaults(suiteName: VaultConstants.userDefaultsSuite)!
@@ -103,6 +103,12 @@ public class WebApiService {
/**
* Get the base URL with /v1/ appended
*/
+ private func getApiRootUrl() -> String {
+ let apiUrl = getApiUrl()
+ let trimmedUrl = apiUrl.hasSuffix("/") ? String(apiUrl.dropLast()) : apiUrl
+ return "\(trimmedUrl)/"
+ }
+
private func getBaseUrl() -> String {
let apiUrl = getApiUrl()
let trimmedUrl = apiUrl.hasSuffix("/") ? String(apiUrl.dropLast()) : apiUrl
@@ -153,7 +159,8 @@ public class WebApiService {
endpoint: String,
body: String?,
headers: [String: String],
- requiresAuth: Bool
+ requiresAuth: Bool,
+ versioned: Bool = false
) async throws -> WebApiResponse {
var requestHeaders = headers
@@ -170,7 +177,8 @@ public class WebApiService {
method: method,
endpoint: endpoint,
body: body,
- headers: requestHeaders
+ headers: requestHeaders,
+ versioned: versioned
)
// Handle 401 Unauthorized - attempt token refresh
@@ -186,7 +194,8 @@ public class WebApiService {
method: method,
endpoint: endpoint,
body: body,
- headers: retryHeaders
+ headers: retryHeaders,
+ versioned: versioned
)
return retryResponse
@@ -200,6 +209,20 @@ public class WebApiService {
return response
}
+ /**
+ * Execute a request whose path carries its own API version segment (e.g. `v2/Vault`), with
+ * authentication and token refresh. This is what the Rust sync engine's HTTP commands go through.
+ */
+ public func executeVersionedRequest(
+ method: String,
+ path: String,
+ body: String?,
+ headers: [String: String],
+ requiresAuth: Bool
+ ) async throws -> WebApiResponse {
+ return try await executeRequest(method: method, endpoint: path, body: body, headers: headers, requiresAuth: requiresAuth, versioned: true)
+ }
+
/**
* Execute a raw HTTP request without token refresh logic
*/
@@ -207,9 +230,10 @@ public class WebApiService {
method: String,
endpoint: String,
body: String?,
- headers: [String: String]
+ headers: [String: String],
+ versioned: Bool = false
) async throws -> WebApiResponse {
- let baseUrl = getBaseUrl()
+ let baseUrl = versioned ? getApiRootUrl() : getBaseUrl()
let urlString = "\(baseUrl)\(endpoint)"
guard let url = URL(string: urlString) else {
@@ -279,7 +303,7 @@ public class WebApiService {
}
/**
- * Refresh the access token using the refresh token
+ * Refresh the access token using the refresh token.
*/
private func refreshAccessToken() async throws -> String? {
guard let refreshToken = getRefreshToken() else {
@@ -307,34 +331,33 @@ public class WebApiService {
]
headers["X-AliasVault-Client"] = getClientVersionHeader()
- do {
- let response = try await executeRawRequest(
- method: "POST",
- endpoint: "Auth/refresh",
- body: jsonString,
- headers: headers
- )
-
- guard response.statusCode == 200 else {
- return nil
- }
-
- // Parse the response JSON
- guard let data = response.body.data(using: .utf8),
- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let newToken = json["token"] as? String,
- let newRefreshToken = json["refreshToken"] as? String else {
- return nil
- }
+ let response = try await executeRawRequest(
+ method: "POST",
+ endpoint: "Auth/refresh",
+ body: jsonString,
+ headers: headers
+ )
- // Update stored tokens
- try setAuthTokens(accessToken: newToken, refreshToken: newRefreshToken)
+ if response.statusCode == 401 || response.statusCode == 403 {
+ return nil
+ }
+ guard response.statusCode == 200 else {
+ print("WebApiService: Token refresh failed with status \(response.statusCode), treating the server as unreachable")
+ throw URLError(.badServerResponse)
+ }
- return newToken
- } catch {
- print("WebApiService: Token refresh failed: \(error)")
+ // Parse the response JSON
+ guard let data = response.body.data(using: .utf8),
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let newToken = json["token"] as? String,
+ let newRefreshToken = json["refreshToken"] as? String else {
return nil
}
+
+ // Update stored tokens
+ try setAuthTokens(accessToken: newToken, refreshToken: newRefreshToken)
+
+ return newToken
}
// MARK: - Helper Methods
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
index 429ec7baa..9f9879f74 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore+Pin.swift
@@ -114,8 +114,8 @@ extension VaultStore {
try storePinFailedAttemptsInKeychain(0)
markSuccessfulAuth()
- // Return the decrypted vault encryption key as base64
- return decryptedKey.base64EncodedString()
+ // Return the decrypted vault encryption key as base64.
+ return resolveStoredUnlockKey(base64Key: decryptedKey.base64EncodedString())
} catch {
// Increment failed attempts
let currentAttempts = getPinFailedAttempts()
diff --git a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
index ccee24d0e..61310e066 100644
--- a/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/VaultStore.swift
@@ -33,6 +33,9 @@ public class VaultStore {
/// The encryption key for the vault.
internal var encryptionKey: Data?
+ /// The account private key (JWK) of the unlocked session.
+ internal var accountPrivateKey: String?
+
/// Last successful biometric/PIN auth operation.
private var lastSuccessfulAuthAt: TimeInterval?
diff --git a/apps/mobile-app/metro.config.js b/apps/mobile-app/metro.config.js
index a23998a77..8a19d3979 100644
--- a/apps/mobile-app/metro.config.js
+++ b/apps/mobile-app/metro.config.js
@@ -5,9 +5,9 @@ const { transformer, resolver } = require('react-native-svg-transformer');
const config = getDefaultConfig(__dirname);
-// The @aliasvault/models and @aliasvault/vault packages are linked as source so let Metro watch them.
+// The @aliasvault/client, @aliasvault/models and @aliasvault/vault packages are linked as source so let Metro watch them.
const coreRoot = path.resolve(__dirname, '../../core');
-config.watchFolders = [...(config.watchFolders ?? []), path.join(coreRoot, 'models'), path.join(coreRoot, 'vault')];
+config.watchFolders = [...(config.watchFolders ?? []), path.join(coreRoot, 'client'), path.join(coreRoot, 'models'), path.join(coreRoot, 'vault')];
config.transformer = {
...config.transformer,
diff --git a/apps/mobile-app/migrations/0.29.7-LegacyApiUrlMigration.ts b/apps/mobile-app/migrations/0.29.7-LegacyApiUrlMigration.ts
index d628169df..88290436b 100644
--- a/apps/mobile-app/migrations/0.29.7-LegacyApiUrlMigration.ts
+++ b/apps/mobile-app/migrations/0.29.7-LegacyApiUrlMigration.ts
@@ -1,4 +1,4 @@
-import { AppInfo } from '@/utils/AppInfo';
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import NativeVaultManager from '@/specs/NativeVaultManager';
diff --git a/apps/mobile-app/package-lock.json b/apps/mobile-app/package-lock.json
index 8374500cb..c5a17b971 100644
--- a/apps/mobile-app/package-lock.json
+++ b/apps/mobile-app/package-lock.json
@@ -7,7 +7,9 @@
"": {
"name": "aliasvault-mobile-app",
"version": "0.0.0",
+ "hasInstallScript": true,
"dependencies": {
+ "@aliasvault/client": "file:../../core/client",
"@aliasvault/models": "file:../../core/models",
"@aliasvault/vault": "file:../../core/vault",
"@expo/vector-icons": "^15.0.2",
@@ -86,6 +88,29 @@
"node": ">=20"
}
},
+ "../../core/client": {
+ "name": "@aliasvault/client",
+ "version": "0.31.0",
+ "license": "AGPL-3.0",
+ "dependencies": {
+ "@aliasvault/models": "file:../models",
+ "@aliasvault/vault": "file:../vault",
+ "otpauth": "^9.3.6",
+ "sql.js": "^1.12.0"
+ },
+ "devDependencies": {
+ "@types/sql.js": "^1.4.9",
+ "@typescript-eslint/eslint-plugin": "^8.65.0",
+ "@typescript-eslint/parser": "^8.65.0",
+ "eslint": "^9.39.5",
+ "eslint-import-resolver-typescript": "^4.4.3",
+ "eslint-plugin-import": "^2.31.0",
+ "eslint-plugin-jsdoc": "^50.6.3",
+ "globals": "^16.5.0",
+ "typescript": "^5.6.3",
+ "vitest": "^4.1.8"
+ }
+ },
"../../core/models": {
"name": "@aliasvault/models",
"version": "1.0.0",
@@ -121,6 +146,10 @@
"integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==",
"license": "MIT"
},
+ "node_modules/@aliasvault/client": {
+ "resolved": "../../core/client",
+ "link": true
+ },
"node_modules/@aliasvault/models": {
"resolved": "../../core/models",
"link": true
diff --git a/apps/mobile-app/package.json b/apps/mobile-app/package.json
index d6b56b1cb..0967b93ca 100644
--- a/apps/mobile-app/package.json
+++ b/apps/mobile-app/package.json
@@ -9,7 +9,8 @@
"web": "expo start --web",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
- "compile": "tsc --noEmit"
+ "compile": "tsc --noEmit",
+ "preinstall": "node ../../core/scripts/install-linked-deps.mjs"
},
"codegenConfig": {
"name": "NativeVaultManagerSpec",
@@ -25,6 +26,7 @@
}
},
"dependencies": {
+ "@aliasvault/client": "file:../../core/client",
"@aliasvault/models": "file:../../core/models",
"@aliasvault/vault": "file:../../core/vault",
"@expo/vector-icons": "^15.0.2",
diff --git a/apps/mobile-app/utils/ApiUrlUtility.ts b/apps/mobile-app/utils/ApiUrlUtility.ts
index f316e6a4c..a9fb8237c 100644
--- a/apps/mobile-app/utils/ApiUrlUtility.ts
+++ b/apps/mobile-app/utils/ApiUrlUtility.ts
@@ -1,6 +1,6 @@
import { useState } from 'react';
-import { AppInfo } from '@/utils/AppInfo';
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import NativeVaultManager from '@/specs/NativeVaultManager';
/**
diff --git a/apps/mobile-app/utils/AppInfo.ts b/apps/mobile-app/utils/AppInfo.ts
index 4e8aac516..540a7bee3 100644
--- a/apps/mobile-app/utils/AppInfo.ts
+++ b/apps/mobile-app/utils/AppInfo.ts
@@ -1,28 +1,18 @@
import { Platform } from 'react-native';
-import { DEFAULT_API_URL, DEFAULT_CLIENT_URL } from '@aliasvault/models/defaults';
-
/**
- * AppInfo class which contains information about the application version
- * and default server URLs.
+ * How the mobile app identifies itself to the client core (registered in platform/MobilePlatform.ts). Everything
+ * else about the app and its defaults is read from the client core's AppInfo. The version scripts in /scripts
+ * update the VERSION line in this file.
*/
-export class AppInfo {
+export class MobileAppIdentity {
/**
* The current mobile app version. This should be updated with each release of the mobile app.
*/
public static readonly VERSION = '0.31.0-alpha';
- /**
- * The API version to send to the server (base semver without stage suffixes).
- * Apple app store requires semver format without stage suffixes.
- */
- public static readonly API_VERSION = (() => {
- return AppInfo.VERSION.split('-')[0];
- })();
-
/**
* The client name to use in the X-AliasVault-Client header.
- * Detects the specific browser being used.
*/
public static readonly CLIENT_NAME = (() : 'ios' | 'android' | 'app' => {
const os = Platform.OS;
@@ -38,16 +28,6 @@ export class AppInfo {
return 'app';
})();
- /**
- * The default AliasVault client URL (shared by every client, see AppDefaults in the models package).
- */
- public static readonly DEFAULT_CLIENT_URL = DEFAULT_CLIENT_URL;
-
- /**
- * The default AliasVault web API URL (shared by every client, see AppDefaults in the models package).
- */
- public static readonly DEFAULT_API_URL = DEFAULT_API_URL;
-
/**
* Prevent instantiation of this utility class
*/
diff --git a/apps/mobile-app/utils/ConversionUtility.ts b/apps/mobile-app/utils/ConversionUtility.ts
index a9c18d39f..a35406990 100644
--- a/apps/mobile-app/utils/ConversionUtility.ts
+++ b/apps/mobile-app/utils/ConversionUtility.ts
@@ -64,15 +64,6 @@ class ConversionUtility {
return '';
}
}
-
- /**
- * Normalize a username by converting it to lowercase and trimming whitespace.
- * @param username The username to normalize.
- * @returns The normalized username.
- */
- public normalizeUsername(username: string): string {
- return username.toLowerCase().trim();
- }
}
export default new ConversionUtility();
diff --git a/apps/mobile-app/utils/DateFormatter.ts b/apps/mobile-app/utils/DateFormatter.ts
deleted file mode 100644
index 36ed8800b..000000000
--- a/apps/mobile-app/utils/DateFormatter.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-/**
- * Centralized utility for formatting Date values consistently across the client application.
- * All dates are stored in UTC with the format: "yyyy-MM-dd HH:mm:ss.fff" (23 characters).
- * This format ensures:
- * - SQLite native support for date functions
- * - No timezone ambiguity (all dates are UTC)
- * - Consistent precision with milliseconds for accurate sorting/comparison
- * - Readable space separator instead of 'T'
- * - Lexicographic sorting works correctly
- */
-
-/**
- * Formats a Date to the standard format string: "yyyy-MM-dd HH:mm:ss.fff" (23 characters).
- * @param date - The Date to format
- * @returns Formatted date-time string in format "yyyy-MM-dd HH:mm:ss.fff"
- */
-export function toStandardFormat(date: Date): string {
- return date.toISOString()
- .replace('T', ' ')
- .replace('Z', '')
- .substring(0, 23);
-}
-
-/**
- * Formats the current UTC time to the standard format string.
- * @returns Formatted current UTC date-time string
- */
-export function now(): string {
- return toStandardFormat(new Date());
-}
-
-/**
- * Formats a Date to the birth date format (no milliseconds, time set to 00:00:00).
- * Format: "yyyy-MM-dd 00:00:00" (19 characters).
- * @param date - The Date to format
- * @returns Formatted date string in format "yyyy-MM-dd 00:00:00"
- */
-export function toBirthDateFormat(date: Date): string {
- const isoString = date.toISOString();
- const datePart = isoString.substring(0, 10); // yyyy-MM-dd
- return `${datePart} 00:00:00`;
-}
diff --git a/apps/mobile-app/utils/EncryptionUtility.ts b/apps/mobile-app/utils/EncryptionUtility.ts
index 0168c3ef2..2c3670ca6 100644
--- a/apps/mobile-app/utils/EncryptionUtility.ts
+++ b/apps/mobile-app/utils/EncryptionUtility.ts
@@ -4,8 +4,26 @@ import { gunzipSync, strFromU8 } from 'fflate';
import AesGcmCrypto from 'react-native-aes-gcm-crypto';
import NativeVaultManager from '@/specs/NativeVaultManager';
-import type { EncryptionKey } from '@/utils/dist/core/models/vault';
-import type { Email, MailboxEmail } from '@/utils/dist/core/models/webapi';
+import type { EncryptionKey } from '@aliasvault/models/vault';
+import type { Email, EmailDecryptionKey, MailboxEmail } from '@aliasvault/models/webapi';
+import { parseEmailSource, type ParsedEmailAttachment } from '@aliasvault/client/rust/RustCore';
+
+/**
+ * An email after decryption: the metadata fields decrypted in place, and the bodies and attachments the Rust
+ * parser derived from the raw RFC 822 source.
+ */
+export type DecryptedEmail = {
+ /** The email with its metadata fields decrypted. */
+ email: Email;
+ /** The html body parsed out of the source, null when the message has no html part. */
+ htmlBody: string | null;
+ /** The plain text body parsed out of the source, null when the message has no text part. */
+ textBody: string | null;
+ /** The attachments contained in the source, in the index order `extractEmailAttachment` expects. */
+ attachments: ParsedEmailAttachment[];
+ /** The decrypted source bytes. */
+ sourceBytes: Uint8Array | null;
+};
/**
* Utility class for encryption operations including:
@@ -280,26 +298,41 @@ class EncryptionUtility {
}
/**
- * Decrypts an individual email based on the provided public/private key pairs.
+ * Finds the decryption key of an email's symmetric key that one of the locally held keypairs can open. An email
+ * carries one decryption key per manifest keypair the caller holds; it names its public key by index into the
+ * publicKeys table the API sends once per response.
+ */
+ private static resolveEmailDecryptionKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): { encryptionKey: EncryptionKey, encryptedSymmetricKey: string } {
+ for (const decryptionKey of decryptionKeys) {
+ const publicKey = publicKeys[decryptionKey.keyIndex];
+ const key = publicKey ? encryptionKeys.find(k => k.PublicKey === publicKey) : undefined;
+ if (key) {
+ return { encryptionKey: key, encryptedSymmetricKey: decryptionKey.encryptedSymmetricKey };
+ }
+ }
+
+ throw new Error('Encryption key not found');
+ }
+
+ /**
+ * Decrypts the symmetric key an email's contents are encrypted with, as base64.
+ */
+ private static async resolveEmailSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<string> {
+ const match = EncryptionUtility.resolveEmailDecryptionKey(decryptionKeys, publicKeys, encryptionKeys);
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(match.encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(match.encryptedSymmetricKey, privateKey);
+ return Buffer.from(symmetricKey).toString('base64');
+ }
+
+ /**
+ * Decrypts an individual email based on the provided public/private key pairs and parses its source.
*/
public static async decryptEmail(
email: Email,
encryptionKeys: EncryptionKey[]
- ): Promise<Email> {
+ ): Promise<DecryptedEmail> {
try {
- const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);
-
- if (!encryptionKey) {
- throw new Error('Encryption key not found');
- }
-
- // Decrypt symmetric key with asymmetric private key
- const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
- email.encryptedSymmetricKey,
- privateKey
- );
- const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
+ const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);
// Create a new object to avoid mutating the original
const decryptedEmail = { ...email };
@@ -310,46 +343,42 @@ class EncryptionUtility {
decryptedEmail.fromDomain = await EncryptionUtility.symmetricDecrypt(email.fromDomain, symmetricKeyBase64);
decryptedEmail.fromLocal = await EncryptionUtility.symmetricDecrypt(email.fromLocal, symmetricKeyBase64);
- if (email.messageHtml) {
- decryptedEmail.messageHtml = await EncryptionUtility.symmetricDecrypt(email.messageHtml, symmetricKeyBase64);
- }
- if (email.messagePlain) {
- decryptedEmail.messagePlain = await EncryptionUtility.symmetricDecrypt(email.messagePlain, symmetricKeyBase64);
- }
- if (email.messageSource) {
- // The raw source is optionally gzip compressed before encryption by 0.31+ API.
- decryptedEmail.messageSource = await EncryptionUtility.symmetricDecryptMaybeCompressed(email.messageSource, symmetricKeyBase64);
+ const sourceBytes = email.messageSource ? await EncryptionUtility.symmetricDecryptBytes(Uint8Array.from(atob(email.messageSource), c => c.charCodeAt(0)), symmetricKeyBase64) : null;
+ decryptedEmail.messageSource = '';
+
+ let htmlBody: string | null = null;
+ let textBody: string | null = null;
+ let attachments: ParsedEmailAttachment[] = [];
+ if (sourceBytes) {
+ try {
+ const parsed = await parseEmailSource(sourceBytes);
+ htmlBody = parsed.htmlBody;
+ textBody = parsed.textBody;
+ attachments = parsed.attachments;
+ } catch (err) {
+ // A parse failure costs the bodies, not the email: the raw source view renders without the parser.
+ console.warn(`[Email] Could not parse the source of email ${email.id}:`, err);
+ }
}
- return decryptedEmail;
+ return { email: decryptedEmail, htmlBody, textBody, attachments, sourceBytes };
} catch (err) {
throw new Error(err instanceof Error ? err.message : 'Failed to decrypt email');
}
}
/**
- * Decrypts a list of emails based on the provided public/private key pairs.
+ * Decrypts a list of emails based on the provided public/private key pairs. The publicKeys table is the one the
+ * API sent alongside the emails; each email's decryption keys reference it by index.
*/
public static async decryptEmailList(
emails: MailboxEmail[],
+ publicKeys: string[],
encryptionKeys: EncryptionKey[]
): Promise<MailboxEmail[]> {
return Promise.all(emails.map(async email => {
try {
- const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);
-
- if (!encryptionKey) {
- throw new Error('Encryption key not found');
- }
-
- // Decrypt symmetric key with asymmetric private key
- const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
- email.encryptedSymmetricKey,
- privateKey
- );
-
- const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
+ const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, publicKeys, encryptionKeys);
// Create a new object to avoid mutating the original
const decryptedEmail = { ...email };
@@ -380,21 +409,7 @@ class EncryptionUtility {
encryptionKeys: EncryptionKey[]
): Promise<Uint8Array> {
try {
- const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);
-
- if (!encryptionKey) {
- throw new Error('Encryption key not found');
- }
-
- // Decrypt the symmetric key using private key (returns raw bytes)
- const privateKey = await EncryptionUtility.getPrivateKeyObject(encryptionKey);
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(
- email.encryptedSymmetricKey,
- privateKey
- );
-
- // Convert symmetric key to base64 string if symmetricDecrypt expects it
- const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
+ const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);
// Decrypt the attachment using raw bytes
return await EncryptionUtility.symmetricDecryptBytes(encryptedBytes, symmetricKeyBase64);
diff --git a/apps/mobile-app/utils/FaviconUtility.ts b/apps/mobile-app/utils/FaviconUtility.ts
deleted file mode 100644
index ab3455411..000000000
--- a/apps/mobile-app/utils/FaviconUtility.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * Typed wrapper around the native Rust core for favicon URL selection.
- */
-import NativeVaultManager from '@/specs/NativeVaultManager';
-
-/**
- * The URL a favicon is fetched from, paired with the `Logos.Source` key it is stored under.
- */
-export type FaviconTarget = {
- url: string;
- source: string;
-};
-
-/**
- * Read an item's URL field values in display order.
- * @param urlValue The URL field value (single string or multi-value array).
- * @returns The non-empty URLs, in order.
- */
-export function toUrlList(urlValue: string | string[] | undefined | null): string[] {
- if (!urlValue) {
- return [];
- }
-
- const urlList = Array.isArray(urlValue) ? urlValue : [urlValue];
- return urlList.filter((url): url is string => Boolean(url?.trim()));
-}
-
-/**
- * Pick which of an item's URLs a favicon should be fetched from.
- * @param urlValue The URL field value (single string or multi-value array).
- * @returns The target, or null when no valid URL is found.
- */
-export async function selectFaviconTarget(urlValue: string | string[] | undefined | null): Promise<FaviconTarget | null> {
- const urls = toUrlList(urlValue);
- if (urls.length === 0) {
- return null;
- }
-
- const targetJson = await NativeVaultManager.selectFaviconTarget(urls);
- return targetJson ? JSON.parse(targetJson) as FaviconTarget : null;
-}
diff --git a/apps/mobile-app/utils/FolderUtils.ts b/apps/mobile-app/utils/FolderUtils.ts
deleted file mode 100644
index 7d8478160..000000000
--- a/apps/mobile-app/utils/FolderUtils.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-import type { Folder } from './db/repositories/FolderRepository';
-
-/**
- * Maximum allowed folder nesting depth.
- * Structure: Root (0) > Level 1 (1) > Level 2 (2) > Level 3 (3) > Level 4 (4)
- * Folders at depth 4 cannot have subfolders.
- */
-export const MAX_FOLDER_DEPTH = 4;
-
-/**
- * Get folder depth in the hierarchy.
- * @param folderId - The folder ID to check
- * @param folders - Flat array of all folders
- * @returns Depth (0 = root, 1 = one level deep, etc.) or null if folder not found
- */
-export function getFolderDepth(folderId: string, folders: Folder[]): number | null {
- const folder = folders.find(f => f.Id === folderId);
- if (!folder) {
- return null;
- }
-
- let depth = 0;
- let currentId: string | null = folderId;
-
- // Traverse up to root, counting levels
- while (currentId) {
- const current = folders.find(f => f.Id === currentId);
- if (!current || !current.ParentFolderId) {
- break;
- }
- depth++;
- currentId = current.ParentFolderId;
-
- // Prevent infinite loops
- if (depth > MAX_FOLDER_DEPTH) {
- break;
- }
- }
-
- return depth;
-}
-
-/**
- * Get the full path of folder names from root to the specified folder.
- * @param folderId - The folder ID
- * @param folders - Flat array of all folders
- * @returns Array of folder names from root to current folder, or empty array if not found
- */
-export function getFolderPath(folderId: string | null, folders: Folder[]): string[] {
- if (!folderId) {
- return [];
- }
-
- const path: string[] = [];
- let currentId: string | null = folderId;
- let iterations = 0;
-
- // Build path by traversing up to root
- while (currentId && iterations < MAX_FOLDER_DEPTH + 1) {
- const folder = folders.find(f => f.Id === currentId);
- if (!folder) {
- break;
- }
- path.unshift(folder.Name); // Add to beginning of array
- currentId = folder.ParentFolderId;
- iterations++;
- }
-
- return path;
-}
-
-/**
- * Get the full path of folder IDs from root to the specified folder.
- * @param folderId - The folder ID
- * @param folders - Flat array of all folders
- * @returns Array of folder IDs from root to current folder, or empty array if not found
- */
-export function getFolderIdPath(folderId: string | null, folders: Folder[]): string[] {
- if (!folderId) {
- return [];
- }
-
- const path: string[] = [];
- let currentId: string | null = folderId;
- let iterations = 0;
-
- // Build path by traversing up to root
- while (currentId && iterations < MAX_FOLDER_DEPTH + 1) {
- const folder = folders.find(f => f.Id === currentId);
- if (!folder) {
- break;
- }
- path.unshift(folder.Id); // Add to beginning of array
- currentId = folder.ParentFolderId;
- iterations++;
- }
-
- return path;
-}
-
-/**
- * Format folder path for display with separator.
- * @param pathSegments - Array of folder names
- * @param separator - Separator string (default: " > ")
- * @returns Formatted folder path string
- */
-export function formatFolderPath(
- pathSegments: string[],
- separator: string = ' > '
-): string {
- return pathSegments.join(separator);
-}
-
-/**
- * Check if a folder can have subfolders (not at max depth).
- * @param folderId - The folder ID to check
- * @param folders - Flat array of all folders
- * @returns True if folder can have children, false otherwise
- */
-export function canHaveSubfolders(folderId: string, folders: Folder[]): boolean {
- const depth = getFolderDepth(folderId, folders);
- return depth !== null && depth < MAX_FOLDER_DEPTH;
-}
-
-/**
- * Get all descendant folder IDs (children, grandchildren, etc.).
- * @param folderId - The parent folder ID
- * @param folders - Flat array of all folders
- * @returns Array of descendant folder IDs
- */
-export function getDescendantFolderIds(folderId: string, folders: Folder[]): string[] {
- const descendants: string[] = [];
-
- /**
- * Traverse a folder tree and get all descendant folder IDs.
- */
- const traverse = (parentId: string): void => {
- folders
- .filter(f => f.ParentFolderId === parentId)
- .forEach(child => {
- descendants.push(child.Id);
- traverse(child.Id);
- });
- };
-
- traverse(folderId);
- return descendants;
-}
-
-/**
- * Get all direct child folder IDs.
- * @param parentFolderId - The parent folder ID (null for root)
- * @param folders - Flat array of all folders
- * @returns Array of direct child folder IDs
- */
-export function getDirectChildFolderIds(parentFolderId: string | null, folders: Folder[]): string[] {
- return folders
- .filter(f => f.ParentFolderId === parentFolderId)
- .map(f => f.Id);
-}
-
-/**
- * Get total count of items in a folder and all its subfolders.
- * @param folderId - The folder ID to count items for
- * @param allItems - All items in the vault
- * @param allFolders - All folders in the vault
- * @returns Total item count including subfolders
- */
-export function getRecursiveItemCount(
- folderId: string,
- allItems: Array<{ FolderId?: string | null }>,
- allFolders: Folder[]
-): number {
- // Get all descendant folder IDs
- const descendantIds = getDescendantFolderIds(folderId, allFolders);
- const allFolderIds = [folderId, ...descendantIds];
-
- // Count items in current folder and all descendants
- return allItems.filter(item => item.FolderId && allFolderIds.includes(item.FolderId)).length;
-}
diff --git a/apps/mobile-app/utils/IdentityGeneratorUtility.ts b/apps/mobile-app/utils/IdentityGeneratorUtility.ts
deleted file mode 100644
index 473eddb88..000000000
--- a/apps/mobile-app/utils/IdentityGeneratorUtility.ts
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * Typed wrapper around the native Rust core for identity (alias persona) generation.
- */
-import NativeVaultManager from '@/specs/NativeVaultManager';
-import type { Identity } from '@aliasvault/models/identity';
-
-/**
- * Request for {@link generateIdentity}. All fields except `language` are optional.
- */
-export type IdentityRequest = {
- /** Dictionary language code (e.g. 'en'); unknown codes fall back to English. */
- language: string;
- /** Gender preference: 'male', 'female' or 'random' (default). */
- gender?: string;
- /** Age range preference as stored in settings (e.g. '21-25' or 'random'). */
- ageRange?: string;
-};
-
-/**
- * Name and birth date input for identity-based username/email prefix generation.
- */
-export type IdentityNameInput = {
- firstName: string;
- lastName: string;
- /** Birth date; only the leading yyyy year part is used. */
- birthDate: string;
-};
-
-/**
- * Generate a random identity (alias persona) in the Rust core.
- *
- * @param request The identity request (language, gender, ageRange).
- * @returns The generated identity with a yyyy-MM-dd birth date string.
- */
-export async function generateIdentity(request: IdentityRequest): Promise<Identity> {
- const identityJson = await NativeVaultManager.generateIdentity(JSON.stringify(request));
- return JSON.parse(identityJson) as Identity;
-}
-
-/**
- * Generate a username from persona name fields (alphanumeric, 6-20 characters).
- *
- * @param input The name input (firstName, lastName, birthDate).
- * @returns The generated username.
- */
-export async function generateIdentityUsername(input: IdentityNameInput): Promise<string> {
- return NativeVaultManager.generateIdentityUsername(JSON.stringify(input));
-}
-
-/**
- * Generate an email prefix from persona name fields (6-20 characters).
- *
- * @param input The name input (firstName, lastName, birthDate).
- * @returns The generated email prefix.
- */
-export async function generateIdentityEmailPrefix(input: IdentityNameInput): Promise<string> {
- return NativeVaultManager.generateIdentityEmailPrefix(JSON.stringify(input));
-}
-
-/**
- * Generate a random alphanumeric email prefix that is not based on any identity.
- * Used for login-type credentials where no persona fields are available.
- *
- * @param length The desired prefix length.
- * @returns The generated prefix.
- */
-export async function generateRandomEmailPrefix(length: number = 14): Promise<string> {
- return NativeVaultManager.generateRandomEmailPrefix(length);
-}
-
-/**
- * Get the list of bundled identity dictionary language ISO codes.
- * The set is owned by the Rust core; unknown codes fall back to English during generation.
- *
- * @returns The available language codes.
- */
-export async function getIdentityLanguages(): Promise<string[]> {
- const languages = await NativeVaultManager.getIdentityLanguages();
- return languages.length > 0 ? languages : ['en'];
-}
-
-/**
- * Get the list of identity age range option values ('random' plus 5-year ranges).
- *
- * @returns The available age range values.
- */
-export async function getIdentityAgeRanges(): Promise<string[]> {
- return NativeVaultManager.getIdentityAgeRanges();
-}
diff --git a/apps/mobile-app/utils/ItemFilters.ts b/apps/mobile-app/utils/ItemFilters.ts
deleted file mode 100644
index 0b97f0e03..000000000
--- a/apps/mobile-app/utils/ItemFilters.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import type { Item, ItemType } from '@aliasvault/models/vault';
-import { ItemTypes } from '@aliasvault/models/vault';
-
-/**
- * Filter types for the items list.
- * - 'all': Show all items
- * - 'passkeys': Show only items with passkeys
- * - 'attachments': Show only items with attachments
- * - 'totp': Show only items with 2FA codes
- * - ItemType values: Filter by specific item type (Login, Alias, CreditCard, Note)
- */
-export type ItemFilterType = 'all' | 'passkeys' | 'attachments' | 'totp' | ItemType;
-
-/**
- * Check if a filter is an item type filter (Login, Alias, CreditCard, Note).
- */
-export function isItemTypeFilter(filter: ItemFilterType): filter is ItemType {
- return Object.values(ItemTypes).includes(filter as ItemType);
-}
-
-/**
- * Parse a filter value from a URL/route param. Returns 'all' if the value is missing
- * or doesn't match a known filter, so an unexpected param can't break the screen.
- */
-export function parseItemFilterType(value: string | null | undefined): ItemFilterType {
- if (!value) {
- return 'all';
- }
- if (value === 'all' || value === 'passkeys' || value === 'attachments' || value === 'totp') {
- return value;
- }
- if (isItemTypeFilter(value as ItemFilterType)) {
- return value as ItemType;
- }
- return 'all';
-}
-
-/**
- * Apply the active type/feature filter to a list of items.
- * Used both for the visible item list and for computing folder badge counts so they
- * stay consistent — when a filter is active, folder counts only include matching items.
- */
-export function applyTypeFilter(items: Item[], filterType: ItemFilterType): Item[] {
- if (filterType === 'all') {
- return items;
- }
-
- return items.filter((item: Item) => {
- if (filterType === 'passkeys') {
- return item.HasPasskey === true;
- }
- if (filterType === 'attachments') {
- return item.HasAttachment === true;
- }
- if (filterType === 'totp') {
- return item.HasTotp === true;
- }
- if (isItemTypeFilter(filterType)) {
- return item.ItemType === filterType;
- }
- return true;
- });
-}
diff --git a/apps/mobile-app/utils/PasswordGeneratorUtility.ts b/apps/mobile-app/utils/PasswordGeneratorUtility.ts
deleted file mode 100644
index 76c3efa98..000000000
--- a/apps/mobile-app/utils/PasswordGeneratorUtility.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Typed wrapper around the native Rust core for password/passphrase generation.
- */
-import NativeVaultManager from '@/specs/NativeVaultManager';
-import { resolveDefaultLanguage } from '@aliasvault/models/defaults';
-import type { PasswordSettings } from '@aliasvault/models/vault';
-
-/**
- * Generate a password or passphrase from the given settings.
- *
- * @param settings The password settings.
- * @param seed Optional 64-character hex RNG seed for deterministic generation.
- * @returns The generated password/passphrase.
- */
-export async function generatePassword(settings: PasswordSettings, seed?: string): Promise<string> {
- const effective = await applyEffectiveDicewareLanguage(settings);
- const payload = seed ? { ...effective, Seed: seed } : effective;
- return NativeVaultManager.generatePassword(JSON.stringify(payload));
-}
-
-/**
- * Resolve the effective Diceware passphrase language when none is explicitly chosen.
- *
- * @param settings The password settings.
- * @returns The settings with a concrete Diceware language when one needed resolving.
- */
-async function applyEffectiveDicewareLanguage(settings: PasswordSettings): Promise<PasswordSettings> {
- if (settings.Type !== 'diceware' || (settings.Language && settings.Language.trim().length > 0)) {
- return settings;
- }
- const codes = await getDicewareLanguages();
- const { default: i18n } = await import('@/i18n');
- return { ...settings, Language: resolveDefaultLanguage(i18n.language, codes) };
-}
-
-/**
- * Get the list of bundled Diceware wordlist language ISO codes (first is the default, English/'en').
- * @returns The available language codes.
- */
-export async function getDicewareLanguages(): Promise<string[]> {
- const languages = await NativeVaultManager.getDicewareLanguages();
- return languages.length > 0 ? languages : ['en'];
-}
-
-/**
- * Generate a random 32-byte seed as a 64-character hex string, suitable for the `seed` argument.
- * @returns A 64-character hex string.
- */
-export function generateSeed(): string {
- const bytes = new Uint8Array(32);
- crypto.getRandomValues(bytes);
- return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
-}
diff --git a/apps/mobile-app/utils/PasswordLengthSlider.ts b/apps/mobile-app/utils/PasswordLengthSlider.ts
deleted file mode 100644
index cbdf7bf0b..000000000
--- a/apps/mobile-app/utils/PasswordLengthSlider.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Utility functions for password length slider with non-linear scaling.
- *
- * The slider uses a power curve to provide fine-grained control at lower values
- * (where most users operate, e.g., 12-32 chars) and coarser control at higher values
- * (64-256 chars).
- *
- * This makes it easy to select common password lengths while still allowing
- * very long passwords when needed.
- */
-import { MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH } from '@aliasvault/models/defaults';
-
-/** Slider minimum value (internal representation) */
-export const SLIDER_MIN = 0;
-
-/** Slider maximum value (internal representation) */
-export const SLIDER_MAX = 100;
-
-/**
- * Exponent for the power curve.
- * Higher values = more precision at lower lengths.
- * 2.0 gives a good balance where ~50% slider = ~70 chars
- */
-const EXPONENT = 2.0;
-
-/**
- * Convert a slider position (0-100) to an actual password length (8-256).
- * Uses a power curve for non-linear scaling.
- *
- * @param sliderValue - The slider position (0-100)
- * @returns The password length (8-256)
- */
-export function sliderToLength(sliderValue: number): number {
- const normalized = Math.max(0, Math.min(1, sliderValue / SLIDER_MAX));
- const curved = Math.pow(normalized, EXPONENT);
- const length = MIN_PASSWORD_LENGTH + curved * (MAX_PASSWORD_LENGTH - MIN_PASSWORD_LENGTH);
- return Math.round(length);
-}
-
-/**
- * Convert a password length (8-256) to a slider position (0-100).
- * Inverse of sliderToLength.
- *
- * @param length - The password length (8-256)
- * @returns The slider position (0-100)
- */
-export function lengthToSlider(length: number): number {
- const clampedLength = Math.max(MIN_PASSWORD_LENGTH, Math.min(MAX_PASSWORD_LENGTH, length));
- const normalized = (clampedLength - MIN_PASSWORD_LENGTH) / (MAX_PASSWORD_LENGTH - MIN_PASSWORD_LENGTH);
- const curved = Math.pow(normalized, 1 / EXPONENT);
- return curved * SLIDER_MAX;
-}
diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.ts
index 9f9071a37..e58ef9869 100644
--- a/apps/mobile-app/utils/SqliteClient.ts
+++ b/apps/mobile-app/utils/SqliteClient.ts
@@ -1,84 +1,67 @@
-import { Buffer } from 'buffer';
-
-import type { EncryptionKeyDerivationParams, VaultMetadata } from '@/utils/dist/core/models/metadata';
-import type { EncryptionKey, PasswordSettings } from '@/utils/dist/core/models/vault';
-import { DEFAULT_PASSWORD_LENGTH } from '@/utils/dist/core/models/defaults';
-import { VaultSqlGenerator, VaultVersion, checkVersionCompatibility, extractVersionFromMigrationId } from '@/utils/dist/core/vault';
-import { VaultVersionIncompatibleError } from '@/utils/types/errors/VaultVersionIncompatibleError';
+import type { EncryptionKeyDerivationParams, VaultMetadata } from '@aliasvault/models/metadata';
+import { asyncRepository } from '@aliasvault/client/database/DbOp';
+import { EncryptionKeyRepository } from '@aliasvault/client/database/repositories/EncryptionKeyRepository';
+import { FolderRepository } from '@aliasvault/client/database/repositories/FolderRepository';
+import { ItemRepository } from '@aliasvault/client/database/repositories/ItemRepository';
+import { ItemStatsRepository } from '@aliasvault/client/database/repositories/ItemStatsRepository';
+import { LogoRepository } from '@aliasvault/client/database/repositories/LogoRepository';
+import { PasskeyRepository } from '@aliasvault/client/database/repositories/PasskeyRepository';
+import { SettingsRepository } from '@aliasvault/client/database/repositories/SettingsRepository';
+import { VaultSqlGenerator, VaultVersion, checkVersionCompatibility, extractVersionFromMigrationId } from '@aliasvault/vault';
+import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/VaultVersionIncompatibleError';
import NativeVaultManager from '@/specs/NativeVaultManager';
-import { ItemRepository } from '@/utils/db/repositories/ItemRepository';
-import { SettingsRepository } from '@/utils/db/repositories/SettingsRepository';
-import { LogoRepository } from '@/utils/db/repositories/LogoRepository';
-import { FolderRepository } from '@/utils/db/repositories/FolderRepository';
-import { PasskeyRepository } from '@/utils/db/repositories/PasskeyRepository';
-import type { IDatabaseClient, SqliteBindValue } from '@/utils/db/BaseRepository';
-
-type SQLiteBindValue = string | number | null | Uint8Array;
+import { NativeDatabaseClient } from '@/platform/NativeDatabaseClient';
/**
- * Client for interacting with the SQLite database through native code.
- * Implements IDatabaseClient interface for repository pattern.
+ * The vault as the app reads and writes it: the client core's repositories over the native vault store, plus the
+ * vault metadata and key storage that only exist natively.
*/
-class SqliteClient implements IDatabaseClient {
- // Lazy-initialized repositories
- private _items: ItemRepository | null = null;
- private _passkeys: PasskeyRepository | null = null;
- private _folders: FolderRepository | null = null;
- private _settings: SettingsRepository | null = null;
- private _logos: LogoRepository | null = null;
+class SqliteClient {
+ /**
+ * The native vault store, as the client core's database client.
+ */
+ private readonly database = new NativeDatabaseClient();
+
+ /**
+ * The logo repository itself, which the item and folder repositories call into.
+ */
+ private readonly logoRepository = new LogoRepository(this.database);
/**
* Repository for Item CRUD operations.
*/
- public get items(): ItemRepository {
- if (!this._items) {
- this._items = new ItemRepository(this);
- // Set the logo repository for logo handling in item updates
- this._items.setLogoRepository(this.logos);
- }
- return this._items;
- }
+ public readonly items = asyncRepository(new ItemRepository(this.database, this.logoRepository), this.database);
+
+ /**
+ * Repository for Folder operations.
+ */
+ public readonly folders = asyncRepository(new FolderRepository(this.database, this.logoRepository), this.database);
+
+ /**
+ * Repository for item logo operations.
+ */
+ public readonly logos = asyncRepository(this.logoRepository, this.database);
/**
* Repository for Passkey operations.
*/
- public get passkeys(): PasskeyRepository {
- if (!this._passkeys) {
- this._passkeys = new PasskeyRepository(this);
- }
- return this._passkeys;
- }
+ public readonly passkeys = asyncRepository(new PasskeyRepository(this.database), this.database);
/**
- * Repository for Folder operations.
+ * Repository for the vault's user preferences.
*/
- public get folders(): FolderRepository {
- if (!this._folders) {
- this._folders = new FolderRepository(this);
- }
- return this._folders;
- }
+ public readonly settings = asyncRepository(new SettingsRepository(this.database), this.database);
/**
- * Repository for Settings and auxiliary data operations.
+ * Repository for the per-manifest keypairs that receive mail.
*/
- public get settings(): SettingsRepository {
- if (!this._settings) {
- this._settings = new SettingsRepository(this);
- }
- return this._settings;
- }
+ public readonly encryptionKeys = asyncRepository(new EncryptionKeyRepository(this.database), this.database);
/**
- * Repository for Logo management operations.
+ * Repository for per-item usage statistics.
*/
- public get logos(): LogoRepository {
- if (!this._logos) {
- this._logos = new LogoRepository(this);
- }
- return this._logos;
- }
+ public readonly itemStats = asyncRepository(new ItemStatsRepository(this.database), this.database);
/**
* Store the vault metadata via the native code implementation.
@@ -147,7 +130,7 @@ class SqliteClient implements IDatabaseClient {
};
// Get the default email domain from vault settings
- const defaultEmailDomain = await this.getSetting('DefaultEmailDomain');
+ const defaultEmailDomain = await this.settings.getDefaultEmailDomain();
// First check if the default domain that is configured in the vault is still valid (not hidden)
if (defaultEmailDomain && isValidDomain(defaultEmailDomain)) {
@@ -228,207 +211,6 @@ class SqliteClient implements IDatabaseClient {
}
}
- /**
- * Execute a SELECT query
- */
- public async executeQuery<T>(query: string, params: SQLiteBindValue[] = []): Promise<T[]> {
- try {
- /*
- * Convert any Uint8Array parameters to base64 strings as the Native wrapper
- * communication requires everything to be a string.
- */
- const convertedParams = params.map(param => {
- if (param instanceof Uint8Array) {
- /*
- * We prefix the base64 string with "av-base64:" to indicate that it is a base64 encoded Uint8Array.
- * So the receiving end knows that it should convert this value back to a Uint8Array before using it in the query.
- */
- return 'av-base64-to-blob:' + Buffer.from(param).toString('base64');
- }
- return param;
- });
-
- const results = await NativeVaultManager.executeQuery(query, convertedParams);
- return results as T[];
- } catch (error) {
- const originalMessage = error instanceof Error ? error.message : String(error);
- const queryPreview = query.trim().substring(0, 200);
- const enrichedError = new Error(originalMessage);
- enrichedError.stack = `SQL: ${queryPreview}\n\n${error instanceof Error && error.stack ? error.stack : ''}`;
- console.error('Error executing query:', enrichedError.message);
- throw enrichedError;
- }
- }
-
- /**
- * Execute an INSERT, UPDATE, or DELETE query
- */
- public async executeUpdate(query: string, params: SQLiteBindValue[] = []): Promise<number> {
- try {
- /*
- * Convert any Uint8Array parameters to base64 strings as the Native wrapper
- * communication requires everything to be a string.
- */
- const convertedParams = params.map(param => {
- if (param instanceof Uint8Array) {
- /*
- * We prefix the base64 string with "av-base64-to-blob:" to indicate that it is a base64 encoded Uint8Array.
- * So the receiving end knows that it should convert this value back to a Uint8Array before using it in the query.
- */
- return 'av-base64-to-blob:' + Buffer.from(param).toString('base64');
- }
- return param;
- });
-
- const result = await NativeVaultManager.executeUpdate(query, convertedParams);
- return result as number;
- } catch (error) {
- const originalMessage = error instanceof Error ? error.message : String(error);
- const queryPreview = query.trim().substring(0, 200);
- const enrichedError = new Error(originalMessage);
- enrichedError.stack = `SQL: ${queryPreview}\n\n${error instanceof Error && error.stack ? error.stack : ''}`;
- console.error('Error executing update:', enrichedError.message);
- throw enrichedError;
- }
- }
-
- /**
- * Fetch all encryption keys.
- */
- public async getAllEncryptionKeys(): Promise<EncryptionKey[]> {
- return this.executeQuery<EncryptionKey>(`SELECT
- x.PublicKey,
- x.PrivateKey,
- x.IsPrimary
- FROM EncryptionKeys x`);
- }
-
- /**
- * Get setting from database for a given key.
- * Returns default value (empty string by default) if setting is not found.
- */
- public async getSetting(key: string, defaultValue: string = ''): Promise<string> {
- const results = await this.executeQuery<{ Value: string }>(`SELECT
- s.Value
- FROM Settings s
- WHERE s.Key = ?`, [key]);
-
- return results.length > 0 ? results[0].Value : defaultValue;
- }
-
- /**
- * Get the default identity language from the database.
- * Returns the stored override value if set, otherwise returns empty string to indicate no explicit preference.
- * Use getEffectiveIdentityLanguage() to get the language with smart defaults based on UI language.
- */
- public async getDefaultIdentityLanguage(): Promise<string> {
- return this.getSetting('DefaultIdentityLanguage');
- }
-
- /**
- * Get the effective identity generator language to use.
- * If user has explicitly set a language preference, use that.
- * Otherwise, intelligently match the UI language to an available identity generator language.
- * Falls back to "en" if no match is found.
- */
- public async getEffectiveIdentityLanguage(): Promise<string> {
- const explicitLanguage = await this.getDefaultIdentityLanguage();
-
- // If user has explicitly set a language preference, use it
- if (explicitLanguage) {
- return explicitLanguage;
- }
-
- // Otherwise, match the UI language to one of the identity generator's available languages using
- // the shared region-variant alternative-code table (e.g. "de-CH" -> "de").
- const { getIdentityLanguages } = await import('@/utils/IdentityGeneratorUtility');
- const { matchAvailableLanguage } = await import('@/utils/dist/core/models/defaults');
- const { default: i18n } = await import('@/i18n');
-
- const uiLanguage = i18n.language;
- const mappedLanguage = matchAvailableLanguage(uiLanguage, await getIdentityLanguages());
-
- // Return the mapped language, or fall back to "en" if no match found
- return mappedLanguage ?? 'en';
- }
-
- /**
- * Get the default identity gender preference from the database.
- */
- public async getDefaultIdentityGender(): Promise<string> {
- return this.getSetting('DefaultIdentityGender', 'random');
- }
-
- /**
- * Get the default identity age range from the database.
- */
- public async getDefaultIdentityAgeRange(): Promise<string> {
- return this.getSetting('DefaultIdentityAgeRange', 'random');
- }
-
- /**
- * Update a setting in the database.
- * @param key The setting key
- * @param value The setting value
- */
- public async updateSetting(key: string, value: string): Promise<void> {
- await NativeVaultManager.beginTransaction();
-
- const currentDateTime = new Date().toISOString()
- .replace('T', ' ')
- .replace('Z', '')
- .substring(0, 23);
-
- // First check if the setting already exists
- const checkQuery = `SELECT COUNT(*) as count FROM Settings WHERE Key = ?`;
- const checkResults = await this.executeQuery<{ count: number }>(checkQuery, [key]);
- const exists = checkResults[0]?.count > 0;
-
- if (exists) {
- // Update existing record
- const updateQuery = `
- UPDATE Settings
- SET Value = ?, UpdatedAt = ?
- WHERE Key = ?`;
- await this.executeUpdate(updateQuery, [value, currentDateTime, key]);
- } else {
- // Insert new record
- const insertQuery = `
- INSERT INTO Settings (Key, Value, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?)`;
- await this.executeUpdate(insertQuery, [key, value, currentDateTime, currentDateTime, 0]);
- }
-
- await NativeVaultManager.commitTransaction();
- }
-
- /**
- * Get the password settings from the database.
- */
- public async getPasswordSettings(): Promise<PasswordSettings> {
- const settingsJson = await this.getSetting('PasswordGenerationSettings');
-
- // Default settings if none found or parsing fails
- const defaultSettings: PasswordSettings = {
- Length: DEFAULT_PASSWORD_LENGTH,
- UseLowercase: true,
- UseUppercase: true,
- UseNumbers: true,
- UseSpecialChars: true,
- UseNonAmbiguousChars: false
- };
-
- try {
- if (settingsJson) {
- return { ...defaultSettings, ...JSON.parse(settingsJson) };
- }
- } catch (error) {
- console.warn('Failed to parse password settings:', error);
- }
-
- return defaultSettings;
- }
-
/**
* Get the current database version from the migrations history.
* Returns the internal version information that matches the current database version.
@@ -436,7 +218,7 @@ class SqliteClient implements IDatabaseClient {
*/
public async getDatabaseVersion(): Promise<VaultVersion> {
// Query the migrations history table for the latest migration
- const results = await this.executeQuery<{ MigrationId: string }>(`
+ const results = await this.database.executeQuery<{ MigrationId: string }>(`
SELECT MigrationId
FROM __EFMigrationsHistory
ORDER BY MigrationId DESC
@@ -494,4 +276,4 @@ class SqliteClient implements IDatabaseClient {
}
}
-export default SqliteClient;
\ No newline at end of file
+export default SqliteClient;
diff --git a/apps/mobile-app/utils/SrpUtility.ts b/apps/mobile-app/utils/SrpUtility.ts
deleted file mode 100644
index 817f19118..000000000
--- a/apps/mobile-app/utils/SrpUtility.ts
+++ /dev/null
@@ -1,205 +0,0 @@
-import type { LoginResponse, ValidateLoginRequest2Fa, ValidateLoginResponse, BadRequestResponse } from '@aliasvault/models/webapi';
-import { ApiAuthError } from '@/utils/types/errors/ApiAuthError';
-import { WebApiService } from '@/utils/WebApiService';
-import NativeVaultManager from '@/specs/NativeVaultManager';
-
-/**
- * An SRP client proof for authenticating against the server: the client public ephemeral
- * and the session proof (M1), both uppercase hex strings.
- */
-export type SrpClientProof = {
- clientPublicEphemeral: string;
- clientSessionProof: string;
-};
-
-/**
- * Utility class for SRP login and validation operations.
- * Uses native Rust SRP implementation via NativeVaultManager.
- */
-export class SrpUtility {
- private webApiService: WebApiService;
-
- /**
- * Constructor
- */
- public constructor(webApiService: WebApiService) {
- this.webApiService = webApiService;
- }
-
- /**
- * Derive an SRP client proof to authenticate against the server with the current password.
- *
- * Wraps the native Rust SRP primitives (generate ephemeral, derive private key, derive session)
- * that are shared used in multiple places.
- *
- * @param salt The user's SRP salt (uppercase hex).
- * @param identity The SRP identity (srpIdentity from the server, or the username).
- * @param passwordHashHex The Argon2id-derived password hash as uppercase hex.
- * @param serverEphemeral The server's public ephemeral from the initiate response.
- * @returns The client public ephemeral and session proof to send to the server.
- */
- public static async deriveClientProof(
- salt: string,
- identity: string,
- passwordHashHex: string,
- serverEphemeral: string
- ): Promise<SrpClientProof> {
- const clientEphemeral = await NativeVaultManager.srpGenerateEphemeral();
- const privateKey = await NativeVaultManager.srpDerivePrivateKey(salt, identity, passwordHashHex);
- const session = await NativeVaultManager.srpDeriveSession(
- clientEphemeral.secret,
- serverEphemeral,
- salt,
- identity,
- privateKey
- );
- return {
- clientPublicEphemeral: clientEphemeral.public,
- clientSessionProof: session.proof,
- };
- }
-
- /**
- * Generate a fresh 32-byte SRP salt as an uppercase hex string (for a new/changed password).
- * @returns The generated salt.
- */
- public static async generateSalt(): Promise<string> {
- return NativeVaultManager.srpGenerateSalt();
- }
-
- /**
- * Derive the SRP verifier for a (new) password: the value the server stores to authenticate
- * future logins. Used when registering or changing a password.
- * @param salt The salt the new password hash was derived against (uppercase hex).
- * @param identity The SRP identity (srpIdentity from the server, or the username).
- * @param passwordHashHex The Argon2id-derived password hash as uppercase hex.
- * @returns The SRP verifier (uppercase hex).
- */
- public static async deriveVerifier(
- salt: string,
- identity: string,
- passwordHashHex: string
- ): Promise<string> {
- const privateKey = await NativeVaultManager.srpDerivePrivateKey(salt, identity, passwordHashHex);
- return NativeVaultManager.srpDeriveVerifier(privateKey);
- }
-
- /**
- * Initiates the login process with the server
- */
- public async initiateLogin(username: string): Promise<LoginResponse> {
- const response = await this.webApiService.rawFetch('Auth/login', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({ username: username.toLowerCase().trim() }),
- });
-
- // Check if response is a bad request (400)
- if (response.status === 400) {
- const badRequestResponse = await response.json() as BadRequestResponse;
- throw new ApiAuthError(badRequestResponse.title);
- }
-
- // For other responses, try to parse as LoginResponse
- const loginResponse = await response.json() as LoginResponse;
- return loginResponse;
- }
-
- /**
- * Validates the login with the server using SRP protocol
- */
- public async validateLogin(
- username: string,
- passwordHash: string,
- rememberMe: boolean,
- loginResponse: LoginResponse
- ): Promise<ValidateLoginResponse> {
- /**
- * Use srpIdentity from server response if available, otherwise fall back to username.
- * Note: the fallback can be removed in the future after 0.26.0+ is deployed.
- */
- const srpIdentity = loginResponse.srpIdentity ?? username;
-
- const clientProof = await SrpUtility.deriveClientProof(
- loginResponse.salt,
- srpIdentity,
- passwordHash,
- loginResponse.serverEphemeral
- );
-
- const response = await this.webApiService.rawFetch('Auth/validate', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- username: username.toLowerCase().trim(),
- rememberMe,
- clientPublicEphemeral: clientProof.clientPublicEphemeral,
- clientSessionProof: clientProof.clientSessionProof,
- }),
- });
-
- // Check if response is a bad request (400)
- if (response.status === 400) {
- const badRequestResponse = await response.json() as BadRequestResponse;
- throw new ApiAuthError(badRequestResponse.title);
- }
-
- // For other responses, try to parse as ValidateLoginResponse
- const validateResponse = await response.json() as ValidateLoginResponse;
- return validateResponse;
- }
-
- /**
- * Validates 2FA code with the server
- */
- public async validateLogin2Fa(
- username: string,
- passwordHash: string,
- rememberMe: boolean,
- loginResponse: LoginResponse,
- twoFactorCode: number
- ): Promise<ValidateLoginResponse> {
- /**
- * Use srpIdentity from server response if available, otherwise fall back to username.
- * Note: the fallback can be removed in the future after 0.26.0+ is deployed.
- */
- const srpIdentity = loginResponse.srpIdentity ?? username;
-
- const clientProof = await SrpUtility.deriveClientProof(
- loginResponse.salt,
- srpIdentity,
- passwordHash,
- loginResponse.serverEphemeral
- );
-
- const model: ValidateLoginRequest2Fa = {
- username: username.toLowerCase().trim(),
- rememberMe,
- clientPublicEphemeral: clientProof.clientPublicEphemeral,
- clientSessionProof: clientProof.clientSessionProof,
- code2Fa: twoFactorCode,
- };
-
- const response = await this.webApiService.rawFetch('Auth/validate-2fa', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify(model),
- });
-
- // Check if response is a bad request (400)
- if (response.status === 400) {
- const badRequestResponse = await response.json() as BadRequestResponse;
- throw new ApiAuthError(badRequestResponse.title);
- }
-
- // For other responses, try to parse as ValidateLoginResponse
- const validateResponse = await response.json() as ValidateLoginResponse;
- return validateResponse;
- }
-}
diff --git a/apps/mobile-app/utils/TotpUtility.ts b/apps/mobile-app/utils/TotpUtility.ts
index 0f3becefc..3e1430fcf 100644
--- a/apps/mobile-app/utils/TotpUtility.ts
+++ b/apps/mobile-app/utils/TotpUtility.ts
@@ -1,17 +1,8 @@
-import NativeVaultManager from '@/specs/NativeVaultManager';
-import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod, TOTP_DEFAULT_ALGORITHM, TOTP_DEFAULT_DIGITS, TOTP_DEFAULT_PERIOD } from '@aliasvault/models/vault';
+import { normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod } from '@aliasvault/models/vault';
-/**
- * The RFC 6238 parameters a TOTP code was created with, as stored on the vault row.
- */
-export type TotpParameters = {
- /** HMAC algorithm: "SHA1", "SHA256" or "SHA512". */
- Algorithm?: string;
- /** Number of digits in the generated code. */
- Digits?: number;
- /** Time step in seconds. */
- Period?: number;
-};
+import type { TotpParameters } from '@aliasvault/client/items/TotpUtility';
+
+import NativeVaultManager from '@/specs/NativeVaultManager';
/**
* Generates the current TOTP code for the given secret key.
@@ -38,107 +29,3 @@ export async function generateTotpCode(secretKey: string, parameters?: TotpParam
return '';
}
}
-
-/**
- * Parsed `otpauth://` URI components.
- */
-export type OtpAuthUri = {
- /** "totp" or "hotp" — only "totp" is supported elsewhere in the app. */
- type: 'totp' | 'hotp';
- /** URL-decoded path component, typically "Issuer:account". */
- label: string;
- /** Base32 secret from the `secret` query parameter. */
- secret: string;
- /** Optional `issuer` query parameter. */
- issuer?: string;
- /** HMAC algorithm from the `algorithm` parameter, normalized; SHA1 when absent or unsupported. */
- algorithm: string;
- /** Code length from the `digits` parameter, normalized; 6 when absent or out of range. */
- digits: number;
- /** Time step from the `period` parameter, normalized; 30 when absent or out of range. */
- period: number;
-};
-
-/**
- * Parse an `otpauth://` URI per
- * https://github.com/google/google-authenticator/wiki/Key-Uri-Format.
- *
- * Returns null when the input is not a valid `otpauth://` URI or is missing
- * a `secret` parameter. Does NOT validate the Base32 alphabet of the secret —
- * callers (e.g. `sanitizeSecretKey` in TotpEditor) handle that separately.
- */
-export function parseOtpAuthUri(uri: string): OtpAuthUri | null {
- const trimmed = uri.trim();
- const prefix = 'otpauth://';
- if (trimmed.toLowerCase().slice(0, prefix.length) !== prefix) {
- return null;
- }
-
- const afterScheme = trimmed.slice(prefix.length);
- const slashIdx = afterScheme.indexOf('/');
- if (slashIdx < 0) {
- return null;
- }
-
- const typeRaw = afterScheme.slice(0, slashIdx).toLowerCase();
- if (typeRaw !== 'totp' && typeRaw !== 'hotp') {
- return null;
- }
-
- const rest = afterScheme.slice(slashIdx + 1);
- const queryIdx = rest.indexOf('?');
- const labelEncoded = queryIdx >= 0 ? rest.slice(0, queryIdx) : rest;
- const queryString = queryIdx >= 0 ? rest.slice(queryIdx + 1) : '';
-
- let label: string;
- try {
- label = decodeURIComponent(labelEncoded);
- } catch {
- label = labelEncoded;
- }
-
- const params = new URLSearchParams(queryString);
- const secret = params.get('secret');
- if (!secret) {
- return null;
- }
-
- const issuer = params.get('issuer');
- return {
- type: typeRaw,
- label,
- secret,
- ...(issuer ? { issuer } : {}),
- algorithm: normalizeTotpAlgorithm(params.get('algorithm')),
- digits: normalizeTotpDigits(params.get('digits')),
- period: normalizeTotpPeriod(params.get('period')),
- };
-}
-
-/**
- * Serialize a TOTP code back to an `otpauth://` URI. Non-default parameters are written out so an
- * exported or re-scanned URI reproduces the same codes.
- *
- * @param label - URL-encoded label, typically "Issuer:account"
- * @param secret - Base32 secret
- * @param issuer - Issuer name
- * @param parameters - Stored algorithm/digits/period
- * @returns The otpauth:// URI
- */
-export function buildOtpAuthUri(label: string, secret: string, issuer: string, parameters?: TotpParameters): string {
- const algorithm = normalizeTotpAlgorithm(parameters?.Algorithm);
- const digits = normalizeTotpDigits(parameters?.Digits);
- const period = normalizeTotpPeriod(parameters?.Period);
-
- let uri = `otpauth://totp/${label}?secret=${secret}&issuer=${encodeURIComponent(issuer)}`;
- if (algorithm !== TOTP_DEFAULT_ALGORITHM) {
- uri += `&algorithm=${algorithm}`;
- }
- if (digits !== TOTP_DEFAULT_DIGITS) {
- uri += `&digits=${digits}`;
- }
- if (period !== TOTP_DEFAULT_PERIOD) {
- uri += `&period=${period}`;
- }
- return uri;
-}
diff --git a/apps/mobile-app/utils/ValidationSchema.ts b/apps/mobile-app/utils/ValidationSchema.ts
deleted file mode 100644
index 9cf6193b0..000000000
--- a/apps/mobile-app/utils/ValidationSchema.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import * as Yup from 'yup';
-
-/**
- * Credential add/edit form validation schema used by react-hook-form.
- * @param t - Translation function
- */
-// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
-export const createCredentialSchema = (t: (key: string) => string) => Yup.object().shape({
- Id: Yup.string().optional(),
- ServiceName: Yup.string().required(t('validation.serviceNameRequired')),
- ServiceUrl: Yup.string().nullable().notRequired(),
- Alias: Yup.object().shape({
- FirstName: Yup.string().nullable().notRequired(),
- LastName: Yup.string().nullable().notRequired(),
- NickName: Yup.string().nullable().notRequired(),
- BirthDate: Yup.string()
- .nullable()
- .notRequired()
- .test(
- 'is-valid-date-format',
- t('validation.invalidDateFormat'),
- value => {
- if (!value) {
- return true;
- } // allow empty
- return /^\d{4}-\d{2}-\d{2}$/.test(value);
- },
- ),
- Gender: Yup.string().nullable().notRequired(),
- Email: Yup.string().email(t('validation.invalidEmailFormat')).nullable().notRequired()
- }),
- Username: Yup.string().nullable().notRequired(),
- Password: Yup.string().nullable().notRequired(),
- Notes: Yup.string().nullable().notRequired()
-});
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index 675e1e309..8253f27f2 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -1,13 +1,13 @@
import { Buffer } from 'buffer';
-import { AppInfo } from '@/utils/AppInfo';
+import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import type { StatusResponse, VaultResponse, AuthLogModel, RefreshToken } from '@aliasvault/models/webapi';
import i18n from '@/i18n';
-import { ClientUpgradeRequiredError } from './types/errors/ClientUpgradeRequiredError';
+import { ClientUpgradeRequiredError } from '@aliasvault/client/api/errors/ClientUpgradeRequiredError';
import { LocalAuthError } from './types/errors/LocalAuthError';
-import { PayloadTooLargeError } from './types/errors/PayloadTooLargeError';
+import { PayloadTooLargeError } from '@aliasvault/client/api/errors/PayloadTooLargeError';
import { logoutEventEmitter } from '@/events/LogoutEventEmitter';
import NativeVaultManager from '@/specs/NativeVaultManager';
@@ -365,7 +365,7 @@ export class WebApiService {
/**
* Get the currently configured API URL from native storage.
*/
- private async getApiUrl(): Promise<string> {
+ public async getApiUrl(): Promise<string> {
try {
const apiUrl = await NativeVaultManager.getApiUrl();
return apiUrl || AppInfo.DEFAULT_API_URL;
diff --git a/apps/mobile-app/utils/db/BaseRepository.ts b/apps/mobile-app/utils/db/BaseRepository.ts
deleted file mode 100644
index 94660d7c2..000000000
--- a/apps/mobile-app/utils/db/BaseRepository.ts
+++ /dev/null
@@ -1,140 +0,0 @@
-import * as dateFormatter from '@/utils/DateFormatter';
-
-import NativeVaultManager from '@/specs/NativeVaultManager';
-
-export type SqliteBindValue = string | number | null | Uint8Array;
-
-/**
- * Interface for the core database operations needed by repositories.
- * Mobile app version is async as it communicates with native modules.
- */
-export interface IDatabaseClient {
- executeQuery<T>(query: string, params?: SqliteBindValue[]): Promise<T[]>;
- executeUpdate(query: string, params?: SqliteBindValue[]): Promise<number>;
-}
-
-/**
- * Base repository class with common database operations.
- * Provides transaction handling, soft delete, and other shared functionality.
- *
- * Mobile-specific: All operations are async as they communicate with native modules.
- */
-export abstract class BaseRepository {
- /**
- * Constructor for the BaseRepository class.
- * @param client - The database client to use for the repository
- */
- public constructor(protected client: IDatabaseClient) {}
-
- /**
- * Execute a function within a transaction.
- * Automatically handles begin, commit, and rollback.
- * @param fn - The function to execute within the transaction
- * @returns The result of the function
- */
- protected async withTransaction<T>(fn: () => T | Promise<T>): Promise<T> {
- await NativeVaultManager.beginTransaction();
- try {
- const result = await fn();
- await NativeVaultManager.commitTransaction();
- return result;
- } catch (error) {
- await NativeVaultManager.rollbackTransaction();
- throw error;
- }
- }
-
- /**
- * Soft delete a record by setting IsDeleted = 1.
- * @param table - The table name
- * @param id - The record ID
- * @returns Number of rows affected
- */
- protected async softDelete(table: string, id: string): Promise<number> {
- const now = dateFormatter.now();
- return this.client.executeUpdate(
- `UPDATE ${table} SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?`,
- [now, id]
- );
- }
-
- /**
- * Soft delete records by a foreign key.
- * @param table - The table name
- * @param foreignKey - The foreign key column name
- * @param foreignKeyValue - The foreign key value
- * @returns Number of rows affected
- */
- protected async softDeleteByForeignKey(table: string, foreignKey: string, foreignKeyValue: string): Promise<number> {
- const now = dateFormatter.now();
- return this.client.executeUpdate(
- `UPDATE ${table} SET IsDeleted = 1, UpdatedAt = ? WHERE ${foreignKey} = ?`,
- [now, foreignKeyValue]
- );
- }
-
- /**
- * Hard delete a record permanently.
- * @param table - The table name
- * @param id - The record ID
- * @returns Number of rows affected
- */
- protected async hardDelete(table: string, id: string): Promise<number> {
- return this.client.executeUpdate(`DELETE FROM ${table} WHERE Id = ?`, [id]);
- }
-
- /**
- * Hard delete records by a foreign key.
- * @param table - The table name
- * @param foreignKey - The foreign key column name
- * @param foreignKeyValue - The foreign key value
- * @returns Number of rows affected
- */
- protected async hardDeleteByForeignKey(table: string, foreignKey: string, foreignKeyValue: string): Promise<number> {
- return this.client.executeUpdate(
- `DELETE FROM ${table} WHERE ${foreignKey} = ?`,
- [foreignKeyValue]
- );
- }
-
- /**
- * Check if a table exists in the database.
- * @param tableName - The name of the table to check
- * @returns True if the table exists
- */
- protected async tableExists(tableName: string): Promise<boolean> {
- const results = await this.client.executeQuery<{ name: string }>(
- `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
- [tableName]
- );
- return results.length > 0;
- }
-
- /**
- * Generate a new id.
- * @returns A new UUID string
- */
- protected generateId(): string {
- return crypto.randomUUID();
- }
-
- /**
- * Get the current timestamp in the standard format.
- * @returns Current timestamp string
- */
- protected now(): string {
- return dateFormatter.now();
- }
-
- /**
- * Build a parameterized IN clause for SQL queries.
- * @param values - Array of values for the IN clause
- * @returns Object with placeholders string and values array
- */
- protected buildInClause(values: string[]): { placeholders: string; values: string[] } {
- return {
- placeholders: values.map(() => '?').join(','),
- values
- };
- }
-}
diff --git a/apps/mobile-app/utils/db/index.ts b/apps/mobile-app/utils/db/index.ts
deleted file mode 100644
index f9c9f3a32..000000000
--- a/apps/mobile-app/utils/db/index.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-// Base
-export { BaseRepository, type IDatabaseClient, type SqliteBindValue } from './BaseRepository';
-
-// Mappers
-export { FieldMapper, type FieldRow } from './mappers/FieldMapper';
-export { ItemMapper, type ItemRow, type TagRow, type ItemWithDeletedAt } from './mappers/ItemMapper';
-
-// Queries
-export {
- ItemQueries,
- FieldValueQueries,
- FieldDefinitionQueries
-} from './queries/ItemQueries';
-
-// Repositories
-export { ItemRepository } from './repositories/ItemRepository';
-export { SettingsRepository } from './repositories/SettingsRepository';
-export { LogoRepository } from './repositories/LogoRepository';
diff --git a/apps/mobile-app/utils/db/mappers/FieldMapper.ts b/apps/mobile-app/utils/db/mappers/FieldMapper.ts
deleted file mode 100644
index 80e277b9a..000000000
--- a/apps/mobile-app/utils/db/mappers/FieldMapper.ts
+++ /dev/null
@@ -1,208 +0,0 @@
-import type { ItemField, FieldType } from '@aliasvault/models/vault';
-import { FieldTypes, getSystemField } from '@aliasvault/models/vault';
-
-/**
- * Raw field row from database query.
- */
-export type FieldRow = {
- ItemId: string;
- FieldKey: string | null;
- FieldDefinitionId: string | null;
- CustomLabel: string | null;
- CustomFieldType: string | null;
- CustomIsHidden: number | null;
- CustomEnableHistory: number | null;
- Value: string;
- DisplayOrder: number;
-};
-
-/**
- * Intermediate field representation before grouping.
- */
-export type ProcessedField = {
- ItemId: string;
- FieldKey: string;
- Label: string;
- FieldType: string;
- IsHidden: number;
- Value: string;
- DisplayOrder: number;
- IsCustomField: boolean;
- EnableHistory: boolean;
-};
-
-/**
- * Mapper class for processing database field rows into ItemField objects.
- * Handles both system fields (with FieldKey) and custom fields (with FieldDefinitionId).
- */
-export class FieldMapper {
- /**
- * Process raw field rows from database into a map of ItemId -> ItemField[].
- * Handles system vs custom fields and multi-value field grouping.
- * @param rows - Raw field rows from database
- * @returns Map of ItemId to array of ItemField objects
- */
- public static processFieldRows(rows: FieldRow[]): Map<string, ItemField[]> {
- // First, convert rows to processed fields with proper metadata
- const processedFields = rows.map(row => this.processFieldRow(row));
-
- // Group by ItemId and FieldKey (to handle multi-value fields)
- const fieldsByItem = new Map<string, ItemField[]>();
- const fieldValuesByKey = new Map<string, string[]>();
-
- for (const field of processedFields) {
- const key = `${field.ItemId}_${field.FieldKey}`;
-
- // Accumulate values for the same field
- if (!fieldValuesByKey.has(key)) {
- fieldValuesByKey.set(key, []);
- }
- fieldValuesByKey.get(key)!.push(field.Value);
-
- // Create ItemField entry only once per unique FieldKey per item
- if (!fieldsByItem.has(field.ItemId)) {
- fieldsByItem.set(field.ItemId, []);
- }
-
- const itemFields = fieldsByItem.get(field.ItemId)!;
- const existingField = itemFields.find(f => f.FieldKey === field.FieldKey);
-
- if (!existingField) {
- itemFields.push({
- FieldKey: field.FieldKey,
- Label: field.Label,
- FieldType: field.FieldType as FieldType,
- Value: '', // Will be set below
- IsHidden: field.IsHidden === 1,
- DisplayOrder: field.DisplayOrder,
- IsCustomField: field.IsCustomField,
- EnableHistory: field.EnableHistory
- });
- }
- }
-
- // Set Values (single value or array for multi-value fields)
- for (const [itemId, fields] of fieldsByItem) {
- for (const field of fields) {
- const key = `${itemId}_${field.FieldKey}`;
- const values = fieldValuesByKey.get(key) || [];
-
- if (values.length === 1) {
- field.Value = values[0];
- } else {
- field.Value = values;
- }
- }
- }
-
- return fieldsByItem;
- }
-
- /**
- * Process a single field row to extract proper metadata.
- * System fields use FieldKey and get metadata from SystemFieldRegistry.
- * Custom fields use FieldDefinitionId and get metadata from the row.
- * @param row - Raw field row
- * @returns Processed field with proper metadata
- */
- private static processFieldRow(row: FieldRow): ProcessedField {
- if (row.FieldKey) {
- // System field: has FieldKey, get metadata from SystemFieldRegistry
- const systemField = getSystemField(row.FieldKey);
- return {
- ItemId: row.ItemId,
- FieldKey: row.FieldKey,
- Label: row.FieldKey, // Use FieldKey as label; UI layer translates via fieldLabels.*
- FieldType: systemField?.FieldType || FieldTypes.Text,
- IsHidden: systemField?.IsHidden ? 1 : 0,
- Value: row.Value,
- DisplayOrder: systemField?.DefaultDisplayOrder ?? row.DisplayOrder,
- IsCustomField: false,
- EnableHistory: systemField?.EnableHistory ?? false
- };
- } else {
- // Custom field: has FieldDefinitionId, get metadata from FieldDefinitions
- return {
- ItemId: row.ItemId,
- FieldKey: row.FieldDefinitionId || '', // Use FieldDefinitionId (UUID) as the key for custom fields
- Label: row.CustomLabel || '',
- FieldType: row.CustomFieldType || FieldTypes.Text,
- IsHidden: row.CustomIsHidden || 0,
- Value: row.Value,
- DisplayOrder: row.DisplayOrder,
- IsCustomField: true,
- EnableHistory: row.CustomEnableHistory === 1
- };
- }
- }
-
- /**
- * Process field rows for a single item (without ItemId in result).
- * Used when fetching a single item by ID.
- * @param rows - Raw field rows for a single item
- * @returns Array of ItemField objects
- */
- public static processFieldRowsForSingleItem(rows: Omit<FieldRow, 'ItemId'>[]): ItemField[] {
- const fieldValuesByKey = new Map<string, string[]>();
- const uniqueFields = new Map<string, {
- FieldKey: string;
- Label: string;
- FieldType: string;
- IsHidden: number;
- DisplayOrder: number;
- IsCustomField: boolean;
- EnableHistory: boolean;
- }>();
-
- for (const row of rows) {
- const fieldKey = row.FieldKey || row.FieldDefinitionId || '';
-
- // Accumulate values
- if (!fieldValuesByKey.has(fieldKey)) {
- fieldValuesByKey.set(fieldKey, []);
- }
- fieldValuesByKey.get(fieldKey)!.push(row.Value);
-
- // Store field metadata (only once per FieldKey)
- if (!uniqueFields.has(fieldKey)) {
- if (row.FieldKey) {
- // System field
- const systemField = getSystemField(row.FieldKey);
- uniqueFields.set(fieldKey, {
- FieldKey: row.FieldKey,
- Label: row.FieldKey, // Use FieldKey as label; UI layer translates via fieldLabels.*
- FieldType: systemField?.FieldType || FieldTypes.Text,
- IsHidden: systemField?.IsHidden ? 1 : 0,
- DisplayOrder: systemField?.DefaultDisplayOrder ?? row.DisplayOrder,
- IsCustomField: false,
- EnableHistory: systemField?.EnableHistory ?? false
- });
- } else {
- // Custom field
- uniqueFields.set(fieldKey, {
- FieldKey: fieldKey,
- Label: row.CustomLabel || '',
- FieldType: row.CustomFieldType || FieldTypes.Text,
- IsHidden: row.CustomIsHidden || 0,
- DisplayOrder: row.DisplayOrder,
- IsCustomField: true,
- EnableHistory: row.CustomEnableHistory === 1
- });
- }
- }
- }
-
- // Build fields array with proper single/multi values
- return Array.from(uniqueFields.entries()).map(([fieldKey, metadata]) => {
- const values = fieldValuesByKey.get(fieldKey) || [];
- return {
- ...metadata,
- FieldType: metadata.FieldType as FieldType,
- Value: values.length === 1 ? values[0] : values,
- IsHidden: metadata.IsHidden === 1,
- IsCustomField: metadata.IsCustomField,
- EnableHistory: metadata.EnableHistory
- };
- });
- }
-}
diff --git a/apps/mobile-app/utils/db/mappers/ItemMapper.ts b/apps/mobile-app/utils/db/mappers/ItemMapper.ts
deleted file mode 100644
index df9b69108..000000000
--- a/apps/mobile-app/utils/db/mappers/ItemMapper.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import type { Item, ItemField, ItemTagRef, ItemType } from '@aliasvault/models/vault';
-
-/**
- * Item with optional DeletedAt field for recently deleted items.
- */
-export type ItemWithDeletedAt = Item & { DeletedAt?: string };
-
-/**
- * Item with its ArchivedAt timestamp, for the archived list.
- */
-export type ItemWithArchivedAt = Item & { ArchivedAt?: string };
-
-/**
- * Raw item row from database query.
- */
-export type ItemRow = {
- Id: string;
- ManifestId: string;
- Name: string;
- ItemType: string;
- FolderId: string | null;
- Logo: Uint8Array | null;
- HasPasskey: number;
- HasAttachment: number;
- HasTotp: number;
- CreatedAt: string;
- UpdatedAt: string;
- DeletedAt?: string | null;
- ArchivedAt?: string | null;
-};
-
-/**
- * Raw tag row from database query.
- */
-export type TagRow = {
- ItemId: string;
- Id: string;
- Name: string;
- Color: string | null;
-};
-
-/**
- * Mapper class for converting database rows to Item objects.
- */
-export class ItemMapper {
- /**
- * Map a single database row to an Item object.
- * @param row - Raw item row from database
- * @param fields - Processed fields for this item
- * @param tags - Tags for this item
- * @param folderPath - Calculated folder path array (optional)
- * @returns Item object
- */
- public static mapRow(
- row: ItemRow,
- fields: ItemField[] = [],
- tags: ItemTagRef[] = [],
- folderPath?: string[] | null
- ): Item {
- return {
- Id: row.Id,
- ManifestId: row.ManifestId,
- Name: row.Name,
- ItemType: row.ItemType as ItemType,
- Logo: row.Logo ?? undefined,
- FolderId: row.FolderId,
- FolderPath: folderPath || undefined,
- Tags: tags,
- Fields: fields,
- HasPasskey: row.HasPasskey === 1,
- HasAttachment: row.HasAttachment === 1,
- HasTotp: row.HasTotp === 1,
- CreatedAt: row.CreatedAt,
- UpdatedAt: row.UpdatedAt
- };
- }
-
- /**
- * Map multiple database rows to Item objects with their fields and tags.
- * @param rows - Raw item rows from database
- * @param fieldsByItem - Map of ItemId to array of fields
- * @param tagsByItem - Map of ItemId to array of tags
- * @param folderPathsByFolderId - Map of FolderId to folder path array (optional)
- * @returns Array of Item objects
- */
- public static mapRows(
- rows: ItemRow[],
- fieldsByItem: Map<string, ItemField[]>,
- tagsByItem: Map<string, ItemTagRef[]>,
- folderPathsByFolderId?: Map<string, string[]>
- ): Item[] {
- return rows.map(row => {
- const folderPath = row.FolderId && folderPathsByFolderId
- ? folderPathsByFolderId.get(row.FolderId) || undefined
- : undefined;
-
- return this.mapRow(
- row,
- fieldsByItem.get(row.Id) || [],
- tagsByItem.get(row.Id) || [],
- folderPath
- );
- });
- }
-
- /**
- * Group tag rows by ItemId into a map.
- * @param tagRows - Raw tag rows from database
- * @returns Map of ItemId to array of ItemTagRef
- */
- public static groupTagsByItem(tagRows: TagRow[]): Map<string, ItemTagRef[]> {
- const tagsByItem = new Map<string, ItemTagRef[]>();
-
- for (const tag of tagRows) {
- if (!tagsByItem.has(tag.ItemId)) {
- tagsByItem.set(tag.ItemId, []);
- }
- tagsByItem.get(tag.ItemId)!.push({
- Id: tag.Id,
- Name: tag.Name,
- Color: tag.Color || undefined
- });
- }
-
- return tagsByItem;
- }
-
- /**
- * Map tag rows to ItemTagRef array (for single item).
- * @param tagRows - Raw tag rows without ItemId
- * @returns Array of ItemTagRef
- */
- public static mapTagRows(tagRows: Omit<TagRow, 'ItemId'>[]): ItemTagRef[] {
- return tagRows.map(tag => ({
- Id: tag.Id,
- Name: tag.Name,
- Color: tag.Color || undefined
- }));
- }
-
- /**
- * Map a single item row for recently deleted items (includes DeletedAt).
- * @param row - Raw item row with DeletedAt
- * @param fields - Processed fields for this item
- * @param folderPath - Calculated folder path array (optional)
- * @returns Item object with DeletedAt
- */
- public static mapDeletedItemRow(
- row: ItemRow & { DeletedAt: string },
- fields: ItemField[] = [],
- folderPath?: string[] | null
- ): ItemWithDeletedAt {
- return {
- Id: row.Id,
- ManifestId: row.ManifestId,
- Name: row.Name,
- ItemType: row.ItemType as ItemType,
- Logo: row.Logo ? new Uint8Array(row.Logo) : undefined,
- FolderId: row.FolderId,
- FolderPath: folderPath || undefined,
- DeletedAt: row.DeletedAt,
- HasPasskey: row.HasPasskey === 1,
- HasAttachment: row.HasAttachment === 1,
- HasTotp: row.HasTotp === 1,
- Fields: fields,
- CreatedAt: row.CreatedAt,
- UpdatedAt: row.UpdatedAt
- };
- }
-}
diff --git a/apps/mobile-app/utils/db/queries/ItemQueries.ts b/apps/mobile-app/utils/db/queries/ItemQueries.ts
deleted file mode 100644
index 9ca59c436..000000000
--- a/apps/mobile-app/utils/db/queries/ItemQueries.ts
+++ /dev/null
@@ -1,442 +0,0 @@
-/**
- * SQL query constants for Item operations.
- * Centralizes all item-related queries to avoid duplication.
- * Mirrors the browser extension implementation.
- */
-export class ItemQueries {
- /**
- * Base SELECT for items with common fields.
- * Includes LEFT JOIN to Logos and subqueries for HasPasskey/HasAttachment/HasTotp.
- */
- public static readonly BASE_SELECT = `
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.ArchivedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id`;
-
- /**
- * Get all active items (not deleted, not in trash, not archived).
- *
- * This is the source list for both the main item list and autofill, so archived items are excluded
- * from both by this single predicate.
- */
- public static readonly GET_ALL_ACTIVE = `
- ${ItemQueries.BASE_SELECT}
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL
- ORDER BY i.CreatedAt DESC`;
-
- /**
- * Get all archived items. Trashed items are excluded: an item that is both archived and trashed
- * belongs in "Recently Deleted", which is the more urgent of the two states.
- */
- public static readonly GET_ARCHIVED = `
- ${ItemQueries.BASE_SELECT}
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NOT NULL
- ORDER BY i.ArchivedAt DESC`;
-
- /**
- * Count of archived items.
- */
- public static readonly COUNT_ARCHIVED = `
- SELECT COUNT(*) as count
- FROM Items
- WHERE IsDeleted = 0 AND DeletedAt IS NULL AND ArchivedAt IS NOT NULL`;
-
- /**
- * Get a single item by ID.
- */
- public static readonly GET_BY_ID = `
- SELECT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.ArchivedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- WHERE i.Id = ? AND i.IsDeleted = 0`;
-
- /**
- * Get field values for multiple items.
- * @param itemCount - Number of items (for placeholder generation)
- * @returns Query with placeholders
- */
- public static getFieldValuesForItems(itemCount: number): string {
- const placeholders = Array(itemCount).fill('?').join(',');
- return `
- SELECT
- fv.ItemId,
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId IN (${placeholders})
- AND fv.IsDeleted = 0
- ORDER BY fv.ItemId, fv.Weight`;
- }
-
- /**
- * Get field values for a single item.
- */
- public static readonly GET_FIELD_VALUES_FOR_ITEM = `
- SELECT
- fv.FieldKey,
- fv.FieldDefinitionId,
- fd.Label as CustomLabel,
- fd.FieldType as CustomFieldType,
- fd.IsHidden as CustomIsHidden,
- fd.EnableHistory as CustomEnableHistory,
- fv.Value,
- fv.Weight as DisplayOrder
- FROM FieldValues fv
- LEFT JOIN FieldDefinitions fd ON fv.FieldDefinitionId = fd.Id
- WHERE fv.ItemId = ? AND fv.IsDeleted = 0
- ORDER BY fv.Weight`;
-
- /**
- * Get all unique email addresses from field values.
- */
- public static readonly GET_ALL_EMAIL_ADDRESSES = `
- SELECT DISTINCT fv.Value as Email
- FROM FieldValues fv
- INNER JOIN Items i ON fv.ItemId = i.Id
- WHERE fv.FieldKey = ?
- AND fv.Value IS NOT NULL
- AND fv.Value != ''
- AND fv.IsDeleted = 0
- AND i.IsDeleted = 0
- AND i.DeletedAt IS NULL`;
-
- /**
- * Get an item by email address (case-insensitive).
- * Used to find items associated with a specific email address.
- */
- public static readonly GET_BY_EMAIL = `
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- INNER JOIN FieldValues fv ON fv.ItemId = i.Id
- WHERE LOWER(fv.Value) = LOWER(?)
- AND fv.FieldKey = ?
- AND fv.IsDeleted = 0
- AND i.IsDeleted = 0
- AND i.DeletedAt IS NULL
- LIMIT 1`;
-
- /**
- * Get all recently deleted items (in trash).
- */
- public static readonly GET_RECENTLY_DELETED = `
- SELECT DISTINCT
- i.Id,
- i.Name,
- i.ItemType,
- i.FolderId,
- l.FileData as Logo,
- CASE WHEN EXISTS (SELECT 1 FROM Passkeys pk WHERE pk.ItemId = i.Id AND pk.IsDeleted = 0) THEN 1 ELSE 0 END as HasPasskey,
- CASE WHEN EXISTS (SELECT 1 FROM Attachments att WHERE att.ItemId = i.Id AND att.IsDeleted = 0) THEN 1 ELSE 0 END as HasAttachment,
- CASE WHEN EXISTS (SELECT 1 FROM TotpCodes tc WHERE tc.ItemId = i.Id AND tc.IsDeleted = 0) THEN 1 ELSE 0 END as HasTotp,
- i.CreatedAt,
- i.UpdatedAt,
- i.DeletedAt
- FROM Items i
- LEFT JOIN Logos l ON i.LogoId = l.Id
- WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
- ORDER BY i.DeletedAt DESC`;
-
- /**
- * Count of recently deleted items.
- */
- public static readonly COUNT_RECENTLY_DELETED = `
- SELECT COUNT(*) as count
- FROM Items
- WHERE IsDeleted = 0 AND DeletedAt IS NOT NULL`;
-
- /**
- * Insert a new item.
- */
- public static readonly INSERT_ITEM = `
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
-
- /**
- * Update an existing item (preserves LogoId if null is passed).
- */
- public static readonly UPDATE_ITEM = `
- UPDATE Items
- SET Name = ?,
- ItemType = ?,
- FolderId = ?,
- LogoId = COALESCE(?, LogoId),
- UpdatedAt = ?
- WHERE Id = ?`;
-
- /**
- * Update an existing item with explicit LogoId setting (can clear LogoId to null).
- */
- public static readonly UPDATE_ITEM_WITH_LOGO = `
- UPDATE Items
- SET Name = ?,
- ItemType = ?,
- FolderId = ?,
- LogoId = ?,
- UpdatedAt = ?
- WHERE Id = ?`;
-
- /**
- * Move item to trash (set DeletedAt).
- */
- public static readonly TRASH_ITEM = `
- UPDATE Items
- SET DeletedAt = ?,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0`;
-
- /**
- * Restore item from trash (clear DeletedAt).
- */
- public static readonly RESTORE_ITEM = `
- UPDATE Items
- SET DeletedAt = NULL,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0 AND DeletedAt IS NOT NULL`;
-
- /**
- * Archive an item (set ArchivedAt).
- */
- public static readonly ARCHIVE_ITEM = `
- UPDATE Items
- SET ArchivedAt = ?,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0 AND ArchivedAt IS NULL`;
-
- /**
- * Unarchive an item (clear ArchivedAt).
- */
- public static readonly UNARCHIVE_ITEM = `
- UPDATE Items
- SET ArchivedAt = NULL,
- UpdatedAt = ?
- WHERE Id = ? AND IsDeleted = 0 AND ArchivedAt IS NOT NULL`;
-
- /**
- * Convert item to tombstone for permanent deletion.
- */
- public static readonly TOMBSTONE_ITEM = `
- UPDATE Items
- SET IsDeleted = 1,
- Name = NULL,
- LogoId = NULL,
- FolderId = NULL,
- ArchivedAt = NULL,
- UpdatedAt = ?
- WHERE Id = ?`;
-}
-
-/**
- * SQL query constants for FieldValue operations.
- */
-export class FieldValueQueries {
- /**
- * Get existing field values for an item.
- */
- public static readonly GET_EXISTING_FOR_ITEM = `
- SELECT Id, FieldKey, FieldDefinitionId, Value, Weight
- FROM FieldValues
- WHERE ItemId = ? AND IsDeleted = 0`;
-
- /**
- * Insert a new field value.
- */
- public static readonly INSERT = `
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
-
- /**
- * Update an existing field value.
- */
- public static readonly UPDATE = `
- UPDATE FieldValues
- SET Value = ?,
- Weight = ?,
- UpdatedAt = ?
- WHERE Id = ?`;
-
- /**
- * Soft delete a field value.
- */
- public static readonly SOFT_DELETE = `
- UPDATE FieldValues
- SET IsDeleted = 1,
- UpdatedAt = ?
- WHERE Id = ?`;
-}
-
-/**
- * SQL query constants for FieldDefinition operations.
- */
-export class FieldDefinitionQueries {
- /**
- * Check if a field definition exists.
- */
- public static readonly EXISTS = `
- SELECT Id FROM FieldDefinitions WHERE Id = ?`;
-
- /**
- * Check if a field definition exists and is not deleted.
- */
- public static readonly EXISTS_ACTIVE = `
- SELECT Id FROM FieldDefinitions WHERE Id = ? AND IsDeleted = 0`;
-
- /**
- * Insert a new field definition.
- */
- public static readonly INSERT = `
- INSERT INTO FieldDefinitions (Id, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
-
- /**
- * Update an existing field definition.
- */
- public static readonly UPDATE = `
- UPDATE FieldDefinitions
- SET Label = ?,
- FieldType = ?,
- IsHidden = ?,
- Weight = ?,
- UpdatedAt = ?
- WHERE Id = ?`;
-}
-
-/**
- * SQL query constants for FieldHistory operations.
- */
-export class FieldHistoryQueries {
- /**
- * Insert a history record.
- */
- public static readonly INSERT = `
- INSERT INTO FieldHistories (Id, ItemId, FieldDefinitionId, FieldKey, ValueSnapshot, ChangedAt, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
-
- /**
- * Get history records for a field.
- */
- public static readonly GET_FOR_FIELD = `
- SELECT
- Id,
- ItemId,
- FieldKey,
- ValueSnapshot,
- ChangedAt,
- CreatedAt,
- UpdatedAt
- FROM FieldHistories
- WHERE ItemId = ? AND FieldKey = ? AND IsDeleted = 0
- ORDER BY ChangedAt DESC
- LIMIT ?`;
-
- /**
- * Get field values for history comparison (before update).
- */
- public static readonly GET_FOR_HISTORY = `
- SELECT FieldKey, Value
- FROM FieldValues
- WHERE ItemId = ? AND IsDeleted = 0`;
-
- /**
- * Get all history records for pruning.
- */
- public static readonly GET_FOR_PRUNING = `
- SELECT Id, ChangedAt
- FROM FieldHistories
- WHERE ItemId = ? AND FieldKey = ? AND IsDeleted = 0
- ORDER BY ChangedAt DESC`;
-
- /**
- * Soft delete old history records.
- * @param count - Number of records to delete
- * @returns Query with placeholders
- */
- public static softDeleteOld(count: number): string {
- const placeholders = Array(count).fill('?').join(',');
- return `
- UPDATE FieldHistories
- SET IsDeleted = 1, UpdatedAt = ?
- WHERE Id IN (${placeholders})`;
- }
-
- /**
- * Soft delete a single history record.
- */
- public static readonly SOFT_DELETE = `
- UPDATE FieldHistories
- SET IsDeleted = 1, UpdatedAt = ?
- WHERE Id = ?`;
-}
-
-/**
- * SQL query constants for Tag operations.
- */
-export class TagQueries {
- /**
- * Get tags for multiple items.
- * @param itemCount - Number of items (for placeholder generation)
- * @returns Query with placeholders
- */
- public static getTagsForItems(itemCount: number): string {
- const placeholders = Array(itemCount).fill('?').join(',');
- return `
- SELECT it.ItemId, t.Id, t.Name, t.Color
- FROM ItemTags it
- INNER JOIN Tags t ON it.TagId = t.Id
- WHERE it.ItemId IN (${placeholders})
- AND it.IsDeleted = 0
- AND t.IsDeleted = 0
- ORDER BY t.DisplayOrder`;
- }
-
- /**
- * Get tags for a single item.
- */
- public static readonly GET_TAGS_FOR_ITEM = `
- SELECT t.Id, t.Name, t.Color
- FROM ItemTags it
- INNER JOIN Tags t ON it.TagId = t.Id
- WHERE it.ItemId = ?
- AND it.IsDeleted = 0
- AND t.IsDeleted = 0
- ORDER BY t.DisplayOrder`;
-}
diff --git a/apps/mobile-app/utils/db/repositories/FolderRepository.ts b/apps/mobile-app/utils/db/repositories/FolderRepository.ts
deleted file mode 100644
index fee80f0ba..000000000
--- a/apps/mobile-app/utils/db/repositories/FolderRepository.ts
+++ /dev/null
@@ -1,329 +0,0 @@
-import { BaseRepository } from '../BaseRepository';
-
-/**
- * Folder entity type.
- */
-export type Folder = {
- Id: string;
- Name: string;
- ParentFolderId: string | null;
- Weight: number;
-}
-
-/**
- * SQL query constants for Folder operations.
- */
-const FolderQueries = {
- /**
- * Get all active folders.
- */
- GET_ALL: `
- SELECT Id, Name, ParentFolderId, Weight
- FROM Folders
- WHERE IsDeleted = 0
- ORDER BY Weight, Name`,
-
- /**
- * Get folder by ID.
- */
- GET_BY_ID: `
- SELECT Id, Name, ParentFolderId
- FROM Folders
- WHERE Id = ? AND IsDeleted = 0`,
-
- /**
- * Insert a new folder.
- */
- INSERT: `
- INSERT INTO Folders (Id, Name, ParentFolderId, Weight, IsDeleted, CreatedAt, UpdatedAt)
- VALUES (?, ?, ?, 0, 0, ?, ?)`,
-
- /**
- * Update folder name.
- */
- UPDATE_NAME: `
- UPDATE Folders
- SET Name = ?,
- UpdatedAt = ?
- WHERE Id = ?`,
-
- /**
- * Soft delete folder.
- */
- SOFT_DELETE: `
- UPDATE Folders
- SET IsDeleted = 1,
- UpdatedAt = ?
- WHERE Id = ?`,
-
- /**
- * Clear folder reference from items.
- */
- CLEAR_ITEMS_FOLDER: `
- UPDATE Items
- SET FolderId = NULL,
- UpdatedAt = ?
- WHERE FolderId = ?`,
-
- /**
- * Move items to a specific folder.
- */
- MOVE_ITEMS_TO_FOLDER: `
- UPDATE Items
- SET FolderId = ?,
- UpdatedAt = ?
- WHERE FolderId = ?`,
-
- /**
- * Update parent folder for child folders.
- */
- UPDATE_PARENT_FOLDER: `
- UPDATE Folders
- SET ParentFolderId = ?,
- UpdatedAt = ?
- WHERE ParentFolderId = ?`,
-
- /**
- * Get direct child folder IDs.
- */
- GET_CHILD_FOLDER_IDS: `
- SELECT Id
- FROM Folders
- WHERE ParentFolderId = ? AND IsDeleted = 0`,
-
- /**
- * Trash items in folder.
- */
- TRASH_ITEMS_IN_FOLDER: `
- UPDATE Items
- SET DeletedAt = ?,
- UpdatedAt = ?,
- FolderId = NULL
- WHERE FolderId = ? AND IsDeleted = 0 AND DeletedAt IS NULL`,
-
- /**
- * Move item to folder.
- */
- MOVE_ITEM: `
- UPDATE Items
- SET FolderId = ?,
- UpdatedAt = ?
- WHERE Id = ?`
-};
-
-/**
- * Repository for Folder CRUD operations.
- */
-export class FolderRepository extends BaseRepository {
- /**
- * Create a new folder.
- * @param name - The name of the folder
- * @param parentFolderId - Optional parent folder ID for nested folders
- * @returns The ID of the created folder
- */
- public async create(name: string, parentFolderId?: string | null): Promise<string> {
- return this.withTransaction(async () => {
- const folderId = this.generateId();
- const currentDateTime = this.now();
-
- await this.client.executeUpdate(FolderQueries.INSERT, [
- folderId,
- name,
- parentFolderId || null,
- currentDateTime,
- currentDateTime
- ]);
-
- return folderId;
- });
- }
-
- /**
- * Get all folders.
- * @returns Array of folder objects (empty array if Folders table doesn't exist yet)
- */
- public async getAll(): Promise<Folder[]> {
- try {
- // Check if table exists first
- if (!await this.tableExists('Folders')) {
- return [];
- }
- return this.client.executeQuery<Folder>(FolderQueries.GET_ALL);
- } catch (error) {
- // Table may not exist in older vault versions - return empty array
- if (error instanceof Error && error.message.includes('no such table')) {
- return [];
- }
- throw error;
- }
- }
-
- /**
- * Get a folder by ID.
- * @param folderId - The ID of the folder
- * @returns Folder object or null if not found
- */
- public async getById(folderId: string): Promise<Omit<Folder, 'Weight'> | null> {
- const results = await this.client.executeQuery<Omit<Folder, 'Weight'>>(
- FolderQueries.GET_BY_ID,
- [folderId]
- );
- return results.length > 0 ? results[0] : null;
- }
-
- /**
- * Update a folder's name.
- * @param folderId - The ID of the folder to update
- * @param name - The new name for the folder
- * @returns The number of rows updated
- */
- public async update(folderId: string, name: string): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
- return this.client.executeUpdate(FolderQueries.UPDATE_NAME, [
- name,
- currentDateTime,
- folderId
- ]);
- });
- }
-
- /**
- * Get all child folder IDs recursively.
- * @param folderId - The parent folder ID
- * @returns Array of all descendant folder IDs
- */
- private async getAllChildFolderIds(folderId: string): Promise<string[]> {
- const directChildren = await this.client.executeQuery<{ Id: string }>(
- FolderQueries.GET_CHILD_FOLDER_IDS,
- [folderId]
- );
-
- const allChildIds: string[] = [];
-
- for (const child of directChildren) {
- allChildIds.push(child.Id);
- // Recursively get all descendants
- const descendants = await this.getAllChildFolderIds(child.Id);
- allChildIds.push(...descendants);
- }
-
- return allChildIds;
- }
-
- /**
- * Delete a folder (soft delete).
- * Handles child folders and items:
- * - Items in this folder only are moved to the parent folder (or root if no parent)
- * - Items in child folders stay in their respective folders (since child folders are moved to parent)
- * - All direct child folders are moved to the parent of the deleted folder
- * @param folderId - The ID of the folder to delete
- * @returns The number of rows updated
- */
- public async delete(folderId: string): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
-
- // Get the parent folder of the folder being deleted
- const folder = await this.getById(folderId);
- const targetParentId = folder?.ParentFolderId || null;
-
- // Move only items in this folder to the parent folder (or root if no parent)
- if (targetParentId) {
- // Has parent: move items to parent folder
- await this.client.executeUpdate(FolderQueries.MOVE_ITEMS_TO_FOLDER, [
- targetParentId,
- currentDateTime,
- folderId
- ]);
- } else {
- // No parent: move items to root (NULL)
- await this.client.executeUpdate(FolderQueries.CLEAR_ITEMS_FOLDER, [
- currentDateTime,
- folderId
- ]);
- }
-
- // Move direct child folders to the parent of the deleted folder
- await this.client.executeUpdate(FolderQueries.UPDATE_PARENT_FOLDER, [
- targetParentId,
- currentDateTime,
- folderId
- ]);
-
- // Soft delete the folder
- return this.client.executeUpdate(FolderQueries.SOFT_DELETE, [
- currentDateTime,
- folderId
- ]);
- });
- }
-
- /**
- * Delete a folder and all items within it (soft delete both folder and items).
- * Recursively handles child folders:
- * - All items in this folder and child folders are moved to "Recently Deleted" (trash)
- * - All child folders are also deleted
- * @param folderId - The ID of the folder to delete
- * @returns The number of items trashed
- */
- public async deleteWithContents(folderId: string): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
-
- // Get all child folder IDs recursively
- const allChildFolderIds = await this.getAllChildFolderIds(folderId);
-
- let totalItemsDeleted = 0;
-
- // Move all items in this folder to trash
- totalItemsDeleted += await this.client.executeUpdate(FolderQueries.TRASH_ITEMS_IN_FOLDER, [
- currentDateTime,
- currentDateTime,
- folderId
- ]);
-
- // Move all items in child folders to trash
- for (const childFolderId of allChildFolderIds) {
- totalItemsDeleted += await this.client.executeUpdate(FolderQueries.TRASH_ITEMS_IN_FOLDER, [
- currentDateTime,
- currentDateTime,
- childFolderId
- ]);
- }
-
- // Soft delete all child folders
- for (const childFolderId of allChildFolderIds) {
- await this.client.executeUpdate(FolderQueries.SOFT_DELETE, [
- currentDateTime,
- childFolderId
- ]);
- }
-
- // Soft delete the parent folder
- await this.client.executeUpdate(FolderQueries.SOFT_DELETE, [
- currentDateTime,
- folderId
- ]);
-
- return totalItemsDeleted;
- });
- }
-
- /**
- * Move an item to a folder.
- * @param itemId - The ID of the item to move
- * @param folderId - The ID of the destination folder (null to remove from folder)
- * @returns The number of rows updated
- */
- public async moveItem(itemId: string, folderId: string | null): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
- return this.client.executeUpdate(FolderQueries.MOVE_ITEM, [
- folderId,
- currentDateTime,
- itemId
- ]);
- });
- }
-}
diff --git a/apps/mobile-app/utils/db/repositories/ItemRepository.ts b/apps/mobile-app/utils/db/repositories/ItemRepository.ts
deleted file mode 100644
index 4b2de6b89..000000000
--- a/apps/mobile-app/utils/db/repositories/ItemRepository.ts
+++ /dev/null
@@ -1,1108 +0,0 @@
-import type { Item, ItemField, TotpCode, Attachment, FieldHistory } from '@/utils/dist/core/models/vault';
-import { FieldKey, MAX_FIELD_HISTORY_RECORDS, normalizeTotpAlgorithm, normalizeTotpDigits, normalizeTotpPeriod } from '@/utils/dist/core/models/vault';
-import { selectFaviconTarget } from '@/utils/FaviconUtility';
-
-import { BaseRepository } from '../BaseRepository';
-import { ItemQueries, FieldValueQueries, FieldDefinitionQueries, FieldHistoryQueries, TagQueries } from '../queries/ItemQueries';
-import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';
-import { ItemMapper, type ItemRow, type TagRow, type ItemWithArchivedAt, type ItemWithDeletedAt } from '../mappers/ItemMapper';
-import type { LogoRepository } from './LogoRepository';
-
-/**
- * Repository for Item CRUD operations.
- * Handles fetching, creating, updating, and deleting items with their related data.
- */
-export class ItemRepository extends BaseRepository {
- private logoRepository: LogoRepository | null = null;
-
- /**
- * Set the logo repository for logo handling operations.
- * @param logoRepository - The logo repository instance
- */
- public setLogoRepository(logoRepository: LogoRepository): void {
- this.logoRepository = logoRepository;
- }
-
- /**
- * Build folder paths for all folders.
- * Returns a map of FolderId -> path array.
- * @returns Map of folder ID to folder path array
- */
- private async buildFolderPaths(): Promise<Map<string, string[]>> {
- const folderPathMap = new Map<string, string[]>();
-
- try {
- // Check if Folders table exists
- if (!await this.tableExists('Folders')) {
- return folderPathMap;
- }
-
- // Get all folders from database
- const folderQuery = 'SELECT Id, Name, ParentFolderId FROM Folders WHERE IsDeleted = 0';
- const folderResults = await this.client.executeQuery<{
- Id: string;
- Name: string;
- ParentFolderId: string | null;
- }>(folderQuery);
-
- if (folderResults.length === 0) {
- return folderPathMap;
- }
-
- // Helper function to build path for a specific folder
- const getFolderPath = (folderId: string): string[] => {
- const path: string[] = [];
- let currentId: string | null = folderId;
- let iterations = 0;
- const maxIterations = 10; // Prevent infinite loops
-
- while (currentId && iterations < maxIterations) {
- const folder = folderResults.find(f => f.Id === currentId);
- if (!folder) break;
-
- path.unshift(folder.Name); // Add to beginning
- currentId = folder.ParentFolderId;
- iterations++;
- }
-
- return path;
- };
-
- // Build paths for all folders
- for (const folder of folderResults) {
- const path = getFolderPath(folder.Id);
- if (path.length > 0) {
- folderPathMap.set(folder.Id, path);
- }
- }
-
- return folderPathMap;
- } catch (error) {
- // Folders table may not exist in older vault versions
- console.error('Error building folder paths:', error);
- return folderPathMap;
- }
- }
-
- /**
- * Fetch all active items (not deleted, not in trash) with their fields and tags.
- * @returns Array of Item objects
- */
- public async getAll(): Promise<Item[]> {
- // 1. Fetch all item rows
- const itemRows = await this.client.executeQuery<ItemRow>(ItemQueries.GET_ALL_ACTIVE);
-
- if (itemRows.length === 0) {
- return [];
- }
-
- // 2. Fetch field values for all items
- const itemIds = itemRows.map(row => row.Id);
- const fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.length);
- const fieldRows = await this.client.executeQuery<FieldRow>(fieldQuery, itemIds);
-
- // 3. Process fields into a map by ItemId
- const fieldsByItem = FieldMapper.processFieldRows(fieldRows);
-
- // 4. Fetch tags for all items
- let tagsByItem = new Map<string, { Id: string; Name: string; Color?: string }[]>();
- if (await this.tableExists('ItemTags')) {
- const tagQuery = TagQueries.getTagsForItems(itemIds.length);
- const tagRows = await this.client.executeQuery<TagRow>(tagQuery, itemIds);
- tagsByItem = ItemMapper.groupTagsByItem(tagRows);
- }
-
- // 5. Build folder paths
- const folderPaths = await this.buildFolderPaths();
-
- // 6. Map rows to Item objects
- return ItemMapper.mapRows(itemRows, fieldsByItem, tagsByItem, folderPaths);
- }
-
- /**
- * Fetch a single item by ID with its fields and tags.
- * @param itemId - The ID of the item to fetch
- * @returns Item object or null if not found
- */
- public async getById(itemId: string): Promise<Item | null> {
- // 1. Fetch item row
- const itemRows = await this.client.executeQuery<ItemRow>(ItemQueries.GET_BY_ID, [itemId]);
-
- if (itemRows.length === 0) {
- return null;
- }
-
- const itemRow = itemRows[0];
-
- // 2. Fetch field values
- const fieldRows = await this.client.executeQuery<Omit<FieldRow, 'ItemId'>>(
- ItemQueries.GET_FIELD_VALUES_FOR_ITEM,
- [itemId]
- );
- const fields = FieldMapper.processFieldRowsForSingleItem(fieldRows);
-
- // 3. Fetch tags
- let tags: { Id: string; Name: string; Color?: string }[] = [];
- if (await this.tableExists('ItemTags')) {
- const tagRows = await this.client.executeQuery<Omit<TagRow, 'ItemId'>>(
- TagQueries.GET_TAGS_FOR_ITEM,
- [itemId]
- );
- tags = ItemMapper.mapTagRows(tagRows);
- }
-
- // 4. Build folder paths and get folder path for this item
- const folderPaths = await this.buildFolderPaths();
- const folderPath = itemRow.FolderId ? folderPaths.get(itemRow.FolderId) : undefined;
-
- // 5. Map to Item object
- return ItemMapper.mapRow(itemRow, fields, tags, folderPath);
- }
-
- /**
- * Fetch all unique email addresses from field values.
- * @returns Array of email addresses
- */
- public async getAllEmailAddresses(): Promise<string[]> {
- const results = await this.client.executeQuery<{ Email: string }>(
- ItemQueries.GET_ALL_EMAIL_ADDRESSES,
- [FieldKey.LoginEmail]
- );
- return results.map(row => row.Email);
- }
-
- /**
- * Fetch an item by its email address (case-insensitive).
- * @param email - The email address to search for
- * @returns Item object or null if not found
- */
- public async getByEmail(email: string): Promise<Item | null> {
- // 1. Fetch item row by email
- const itemRows = await this.client.executeQuery<ItemRow>(
- ItemQueries.GET_BY_EMAIL,
- [email, FieldKey.LoginEmail]
- );
-
- if (itemRows.length === 0) {
- return null;
- }
-
- const itemRow = itemRows[0];
-
- // 2. Fetch field values
- const fieldRows = await this.client.executeQuery<Omit<FieldRow, 'ItemId'>>(
- ItemQueries.GET_FIELD_VALUES_FOR_ITEM,
- [itemRow.Id]
- );
- const fields = FieldMapper.processFieldRowsForSingleItem(fieldRows);
-
- // 3. Build folder paths and get folder path for this item
- const folderPaths = await this.buildFolderPaths();
- const folderPath = itemRow.FolderId ? folderPaths.get(itemRow.FolderId) : undefined;
-
- // 4. Map to Item object
- return ItemMapper.mapRow(itemRow, fields, [], folderPath);
- }
-
- /**
- * Get recently deleted items (in trash).
- * @returns Array of items with DeletedAt field
- */
- public async getRecentlyDeleted(): Promise<ItemWithDeletedAt[]> {
- const itemRows = await this.client.executeQuery<ItemRow & { DeletedAt: string }>(
- ItemQueries.GET_RECENTLY_DELETED
- );
-
- if (itemRows.length === 0) {
- return [];
- }
-
- // Fetch fields for deleted items
- const itemIds = itemRows.map(row => row.Id);
- const fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.length);
- const fieldRows = await this.client.executeQuery<FieldRow>(fieldQuery, itemIds);
- const fieldsByItem = FieldMapper.processFieldRows(fieldRows);
-
- // Build folder paths
- const folderPaths = await this.buildFolderPaths();
-
- return itemRows.map(row => {
- const folderPath = row.FolderId ? folderPaths.get(row.FolderId) : undefined;
- return ItemMapper.mapDeletedItemRow(row, fieldsByItem.get(row.Id) || [], folderPath);
- });
- }
-
- /**
- * Get count of items in trash.
- * @returns Number of items in trash
- */
- public async getRecentlyDeletedCount(): Promise<number> {
- const results = await this.client.executeQuery<{ count: number }>(ItemQueries.COUNT_RECENTLY_DELETED);
- return results.length > 0 ? results[0].count : 0;
- }
-
- /**
- * Get archived items.
- * @returns Array of items with ArchivedAt field
- */
- public async getArchived(): Promise<ItemWithArchivedAt[]> {
- const itemRows = await this.client.executeQuery<ItemRow & { ArchivedAt: string }>(ItemQueries.GET_ARCHIVED);
-
- if (itemRows.length === 0) {
- return [];
- }
-
- // Fetch fields for archived items
- const itemIds = itemRows.map(row => row.Id);
- const fieldQuery = ItemQueries.getFieldValuesForItems(itemIds.length);
- const fieldRows = await this.client.executeQuery<FieldRow>(fieldQuery, itemIds);
- const fieldsByItem = FieldMapper.processFieldRows(fieldRows);
-
- // Fetch tags
- let tagsByItem = new Map<string, { Id: string; Name: string; Color?: string }[]>();
- if (await this.tableExists('ItemTags')) {
- const tagQuery = TagQueries.getTagsForItems(itemIds.length);
- const tagRows = await this.client.executeQuery<TagRow>(tagQuery, itemIds);
- tagsByItem = ItemMapper.groupTagsByItem(tagRows);
- }
-
- // Build folder paths
- const folderPaths = await this.buildFolderPaths();
-
- return itemRows.map(row => {
- const folderPath = row.FolderId ? folderPaths.get(row.FolderId) : undefined;
- const item = ItemMapper.mapRow(row, fieldsByItem.get(row.Id) || [], tagsByItem.get(row.Id) || [], folderPath);
- return { ...item, ArchivedAt: row.ArchivedAt };
- });
- }
-
- /**
- * Get count of archived items.
- * @returns Number of archived items
- */
- public async getArchivedCount(): Promise<number> {
- const results = await this.client.executeQuery<{ count: number }>(ItemQueries.COUNT_ARCHIVED);
- return results.length > 0 ? results[0].count : 0;
- }
-
- /**
- * Get field history for a specific field.
- * @param itemId - The ID of the item
- * @param fieldKey - The field key to get history for
- * @returns Array of field history records
- */
- public async getFieldHistory(itemId: string, fieldKey: string): Promise<FieldHistory[]> {
- const results = await this.client.executeQuery<{
- Id: string;
- ItemId: string;
- FieldKey: string;
- ValueSnapshot: string;
- ChangedAt: string;
- CreatedAt: string;
- UpdatedAt: string;
- }>(FieldHistoryQueries.GET_FOR_FIELD, [itemId, fieldKey, MAX_FIELD_HISTORY_RECORDS]);
-
- return results.map(row => ({
- Id: row.Id,
- ItemId: row.ItemId,
- FieldKey: row.FieldKey,
- ValueSnapshot: row.ValueSnapshot,
- ChangedAt: row.ChangedAt,
- CreatedAt: row.CreatedAt,
- UpdatedAt: row.UpdatedAt
- }));
- }
-
- /**
- * Delete a specific field history record.
- * @param historyId - The ID of the history record to delete
- * @returns Number of rows affected
- */
- public async deleteFieldHistory(historyId: string): Promise<number> {
- return this.withTransaction(async () => {
- const now = this.now();
- return this.client.executeUpdate(FieldHistoryQueries.SOFT_DELETE, [
- now,
- historyId
- ]);
- });
- }
-
- /**
- * Move an item to trash (set DeletedAt timestamp).
- * @param itemId - The ID of the item to trash
- * @returns Number of rows affected
- */
- public async trash(itemId: string): Promise<number> {
- const now = this.now();
- return this.withTransaction(async () => {
- return this.client.executeUpdate(ItemQueries.TRASH_ITEM, [now, now, itemId]);
- });
- }
-
- /**
- * Restore an item from trash (clear DeletedAt).
- * @param itemId - The ID of the item to restore
- * @returns Number of rows affected
- */
- public async restore(itemId: string): Promise<number> {
- const now = this.now();
- return this.withTransaction(async () => {
- return this.client.executeUpdate(ItemQueries.RESTORE_ITEM, [now, itemId]);
- });
- }
-
- /**
- * Archive an item: it disappears from the main list and from autofill, but keeps all of its data
- * and its email aliases, and is never auto-pruned.
- * @param itemId - The ID of the item to archive
- * @returns Number of rows affected
- */
- public async archive(itemId: string): Promise<number> {
- const now = this.now();
- return this.withTransaction(async () => {
- return this.client.executeUpdate(ItemQueries.ARCHIVE_ITEM, [now, now, itemId]);
- });
- }
-
- /**
- * Unarchive an item, returning it to the main list and to autofill.
- * @param itemId - The ID of the item to unarchive
- * @returns Number of rows affected
- */
- public async unarchive(itemId: string): Promise<number> {
- const now = this.now();
- return this.withTransaction(async () => {
- return this.client.executeUpdate(ItemQueries.UNARCHIVE_ITEM, [now, itemId]);
- });
- }
-
- /**
- * Permanently delete an item (tombstone).
- * Converts item to tombstone and hard deletes all related data.
- * @param itemId - The ID of the item to permanently delete
- * @returns Number of rows affected
- */
- public async permanentlyDelete(itemId: string): Promise<number> {
- return this.withTransaction(async () => {
- const now = this.now();
-
- // Soft delete related FieldValues
- await this.softDeleteByForeignKey('FieldValues', 'ItemId', itemId);
-
- // Soft delete related data
- await this.softDeleteByForeignKey('TotpCodes', 'ItemId', itemId);
-
- // Soft delete attachments AND zero their blob bytes — tombstone stays for
- // sync but storage is reclaimed immediately. X'' is SQLite's empty-blob literal.
- await this.client.executeUpdate(
- `UPDATE Attachments SET IsDeleted = 1, Blob = X'', UpdatedAt = ? WHERE ItemId = ? AND IsDeleted = 0`,
- [now, itemId]
- );
-
- await this.softDeleteByForeignKey('Passkeys', 'ItemId', itemId);
- if (await this.tableExists('ItemTags')) {
- await this.softDeleteByForeignKey('ItemTags', 'ItemId', itemId);
- }
- if (await this.tableExists('FieldHistories')) {
- await this.softDeleteByForeignKey('FieldHistories', 'ItemId', itemId);
- }
-
- // Convert item to tombstone
- return this.client.executeUpdate(ItemQueries.TOMBSTONE_ITEM, [now, itemId]);
- });
- }
-
- /**
- * Create a new item with its fields and related entities.
- * @param item - The item to create
- * @param attachments - Array of attachments to create
- * @param totpCodes - Array of TOTP codes to create
- * @param logoRepository - Optional logo repository for logo handling
- * @returns The ID of the created item
- */
- public async create(
- item: Item,
- attachments: Attachment[] = [],
- totpCodes: TotpCode[] = []
- ): Promise<string> {
- return this.withTransaction(async () => {
- const now = this.now();
- const itemId = item.Id || this.generateId();
-
- // 1. Resolve the logo.
- const logoId = await this.resolveLogoId(item, now);
-
- // 2. Insert Item
- await this.client.executeUpdate(ItemQueries.INSERT_ITEM, [
- itemId,
- item.Name,
- item.ItemType,
- logoId,
- item.FolderId || null,
- now,
- now,
- 0
- ]);
-
- // 3. Insert FieldValues
- await this.insertFieldValues(itemId, item.Fields, item.ItemType, now);
-
- // 4. Insert TOTP codes
- for (const totp of totpCodes) {
- if (totp.IsDeleted) continue;
-
- await this.client.executeUpdate(`
- INSERT INTO TotpCodes (Id, Name, SecretKey, Algorithm, Digits, Period, ItemId, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- [totp.Id || this.generateId(), totp.Name, totp.SecretKey, normalizeTotpAlgorithm(totp.Algorithm), normalizeTotpDigits(totp.Digits), normalizeTotpPeriod(totp.Period), itemId, now, now, 0]);
- }
-
- // 5. Insert Attachments
- for (const attachment of attachments) {
- await this.client.executeUpdate(`
- INSERT INTO Attachments (Id, Filename, Blob, ItemId, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?)`,
- [attachment.Id, attachment.Filename, attachment.Blob as Uint8Array, itemId, now, now, 0]);
- }
-
- return itemId;
- });
- }
-
- /**
- * Duplicate an item including all fields except passkeys and field history.
- * @param itemId - The ID of the item to duplicate
- * @returns The ID of the newly created item
- */
- public async duplicate(itemId: string): Promise<string | null> {
- return this.withTransaction(async () => {
- const now = this.now();
- const newItemId = this.generateId();
-
- const sourceRows = await this.client.executeQuery<{ Name: string | null }>(
- `SELECT Name FROM Items WHERE Id = ? AND IsDeleted = 0`,
- [itemId]
- );
- if (sourceRows.length === 0) {
- throw new Error(`Item not found: ${itemId}`);
- }
-
- const existingNames = await this.client.executeQuery<{ Name: string | null }>(
- `SELECT Name FROM Items WHERE IsDeleted = 0 AND DeletedAt IS NULL`
- );
- const newName = ItemRepository.generateCopyName(
- sourceRows[0].Name,
- existingNames.map(row => row.Name)
- );
-
- // 1. Copy the item row itself (same logo, folder and type).
- await this.client.executeUpdate(`
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, ItemType, LogoId, FolderId, ?, ?, 0 FROM Items WHERE Id = ?`,
- [newItemId, newName, now, now, itemId]);
-
- // 2. Copy custom field definitions so later edits to the duplicate's
- // custom fields don't affect the original item.
- const definitionRows = await this.client.executeQuery<{ Id: string }>(
- `SELECT DISTINCT FieldDefinitionId as Id FROM FieldValues
- WHERE ItemId = ? AND IsDeleted = 0 AND FieldDefinitionId IS NOT NULL`,
- [itemId]
- );
- const definitionIdMap = new Map<string, string>();
- for (const definition of definitionRows) {
- const newDefinitionId = this.generateId();
- definitionIdMap.set(definition.Id, newDefinitionId);
- await this.client.executeUpdate(`
- INSERT INTO FieldDefinitions (Id, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, ?, ?, 0 FROM FieldDefinitions WHERE Id = ?`,
- [newDefinitionId, now, now, definition.Id]);
- }
-
- // 3. Copy field values, remapping custom fields to the copied definitions.
- const fieldValueRows = await this.client.executeQuery<{ Id: string; FieldDefinitionId: string | null }>(
- `SELECT Id, FieldDefinitionId FROM FieldValues WHERE ItemId = ? AND IsDeleted = 0`,
- [itemId]
- );
- for (const row of fieldValueRows) {
- await this.client.executeUpdate(`
- INSERT INTO FieldValues (Id, ItemId, FieldDefinitionId, FieldKey, Value, Weight, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, ?, FieldKey, Value, Weight, ?, ?, 0 FROM FieldValues WHERE Id = ?`,
- [
- this.generateId(),
- newItemId,
- row.FieldDefinitionId ? definitionIdMap.get(row.FieldDefinitionId) ?? null : null,
- now,
- now,
- row.Id
- ]);
- }
-
- // 4. Copy remaining child rows with fresh IDs.
- const childCopies = [
- {
- table: 'TotpCodes',
- sql: `INSERT INTO TotpCodes (Id, ItemId, Name, SecretKey, Algorithm, Digits, Period, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, Name, SecretKey, Algorithm, Digits, Period, ?, ?, 0 FROM TotpCodes WHERE Id = ?`,
- },
- {
- table: 'Attachments',
- sql: `INSERT INTO Attachments (Id, ItemId, Filename, Blob, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, Filename, Blob, ?, ?, 0 FROM Attachments WHERE Id = ?`,
- },
- {
- table: 'ItemTags',
- sql: `INSERT INTO ItemTags (Id, ItemId, TagId, CreatedAt, UpdatedAt, IsDeleted)
- SELECT ?, ?, TagId, ?, ?, 0 FROM ItemTags WHERE Id = ?`,
- optional: true,
- },
- ];
-
- for (const copy of childCopies) {
- if (copy.optional && !(await this.tableExists(copy.table))) {
- continue;
- }
-
- const rows = await this.client.executeQuery<{ Id: string }>(
- `SELECT Id FROM ${copy.table} WHERE ItemId = ? AND IsDeleted = 0`,
- [itemId]
- );
- for (const row of rows) {
- await this.client.executeUpdate(copy.sql, [this.generateId(), newItemId, now, now, row.Id]);
- }
- }
-
- return newItemId;
- });
- }
-
- /**
- * Generate a unique name for a duplicated item: "Name (1)", "Name (2)", etc.
- * If the source name already ends with a "(n)" suffix, the counter is incremented
- * instead of stacking suffixes.
- */
- private static generateCopyName(sourceName: string | null, existingNames: (string | null)[]): string | null {
- if (!sourceName) {
- return sourceName;
- }
-
- const base = sourceName.replace(/ \(\d+\)$/, '');
- const taken = new Set(existingNames.filter((name): name is string => name !== null));
-
- let candidate = `${base} (1)`;
- for (let counter = 2; taken.has(candidate); counter++) {
- candidate = `${base} (${counter})`;
- }
- return candidate;
- }
-
- /**
- * Update an existing item with its fields and related entities.
- * @param item - The item to update
- * @param originalAttachmentIds - IDs of attachments that existed before edit
- * @param attachments - Current attachments (new and existing)
- * @param originalTotpCodeIds - IDs of TOTP codes that existed before edit
- * @param totpCodes - Current TOTP codes (new and existing)
- * @returns Number of rows affected
- */
- public async update(
- item: Item,
- originalAttachmentIds: string[] = [],
- attachments: Attachment[] = [],
- originalTotpCodeIds: string[] = [],
- totpCodes: TotpCode[] = []
- ): Promise<number> {
- return this.withTransaction(async () => {
- const now = this.now();
-
- // 1. Handle Logo - resolve new logoId based on item.Logo
- const logoId = await this.resolveLogoId(item, now);
-
- // 2. Update Item only if item-level fields changed
- const existing = await this.client.executeQuery<{
- Name: string | null;
- ItemType: string | null;
- FolderId: string | null;
- LogoId: string | null;
- }>(`SELECT Name, ItemType, FolderId, LogoId FROM Items WHERE Id = ?`, [item.Id]);
-
- if (existing.length > 0) {
- const existingItem = existing[0];
- const nameChanged = item.Name !== existingItem.Name;
- const itemTypeChanged = String(item.ItemType) !== String(existingItem.ItemType);
- const folderIdChanged = (item.FolderId || null) !== existingItem.FolderId;
- // Logo changed if: we have a new logo ID, OR we're clearing the logo (item.Logo is undefined and existing has logo)
- const logoIdChanged = logoId !== existingItem.LogoId;
-
- if (nameChanged || itemTypeChanged || folderIdChanged || logoIdChanged) {
- // Use UPDATE_ITEM_WITH_LOGO to allow explicit clearing of LogoId
- await this.client.executeUpdate(ItemQueries.UPDATE_ITEM_WITH_LOGO, [
- item.Name,
- item.ItemType,
- item.FolderId || null,
- logoId,
- now,
- item.Id
- ]);
- }
- }
-
- // 2. Track history for fields that have EnableHistory=true before updating
- await this.trackFieldHistory(item.Id, item.Fields, now);
-
- // 3. Update FieldValues using preserve-and-track strategy
- await this.updateFieldValues(item.Id, item.Fields, item.ItemType, now);
-
- // 4. Handle TOTP codes (insert new, update existing, soft-delete removed)
- await this.syncRelatedEntities(
- 'TotpCodes',
- 'ItemId',
- item.Id,
- originalTotpCodeIds,
- totpCodes.filter(tc => !tc.IsDeleted),
- (totp) => [totp.Id || this.generateId(), totp.Name, totp.SecretKey, normalizeTotpAlgorithm(totp.Algorithm), normalizeTotpDigits(totp.Digits), normalizeTotpPeriod(totp.Period), item.Id, now, now, 0],
- `INSERT INTO TotpCodes (Id, Name, SecretKey, Algorithm, Digits, Period, ItemId, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- `UPDATE TotpCodes SET Name = ?, SecretKey = ?, Algorithm = ?, Digits = ?, Period = ?, UpdatedAt = ? WHERE Id = ?`,
- (totp) => [totp.Name, totp.SecretKey, normalizeTotpAlgorithm(totp.Algorithm), normalizeTotpDigits(totp.Digits), normalizeTotpPeriod(totp.Period), now, totp.Id]
- );
-
- // 5. Handle Attachments (insert new, update existing, soft-delete removed).
- // Override the default soft-delete SQL so removed attachments also have
- // their Blob bytes cleared. The tombstone row remains for LWW sync, but
- // storage drops on next save.
- await this.syncRelatedEntities(
- 'Attachments',
- 'ItemId',
- item.Id,
- originalAttachmentIds,
- attachments,
- (att) => [att.Id, att.Filename, att.Blob as Uint8Array, item.Id, now, now, 0],
- `INSERT INTO Attachments (Id, Filename, Blob, ItemId, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, ?, ?)`,
- `UPDATE Attachments SET Filename = ?, Blob = ?, UpdatedAt = ? WHERE Id = ?`,
- (att) => [att.Filename, att.Blob as Uint8Array, now, att.Id],
- `UPDATE Attachments SET IsDeleted = 1, Blob = X'', UpdatedAt = ? WHERE Id = ?`
- );
-
- return 1;
- });
- }
-
- /**
- * Insert field values for an item.
- * Also creates history records for fields with EnableHistory=true.
- */
- private async insertFieldValues(itemId: string, fields: ItemField[], itemType: string, now: string): Promise<void> {
- for (let i = 0; i < fields.length; i++) {
- const field = fields[i];
- const values = Array.isArray(field.Value) ? field.Value : [field.Value];
- const filteredValues = values.filter(v => v !== undefined && v !== null && v !== '');
-
- // Skip empty system fields, but always persist custom fields (even if empty)
- if (filteredValues.length === 0 && !field.IsCustomField) {
- continue;
- }
-
- // For custom fields with no values, use empty string to preserve the field
- const valuesToInsert = field.IsCustomField && filteredValues.length === 0
- ? ['']
- : filteredValues;
-
- let fieldDefinitionId: string | null = null;
-
- // For custom fields, create or get FieldDefinition first
- if (field.IsCustomField) {
- fieldDefinitionId = await this.ensureFieldDefinition(field, itemType, now);
- }
-
- for (let j = 0; j < valuesToInsert.length; j++) {
- const value = valuesToInsert[j];
-
- await this.client.executeUpdate(FieldValueQueries.INSERT, [
- this.generateId(),
- itemId,
- fieldDefinitionId, // FieldDefinitionId for custom, null for system
- field.IsCustomField ? null : field.FieldKey, // FieldKey for system, null for custom
- value,
- (i * 100) + j, // Weight for ordering
- now,
- now,
- 0
- ]);
- }
-
- // Create history record for fields with EnableHistory=true
- if (field.EnableHistory && filteredValues.length > 0) {
- // Check if FieldHistories table exists
- if (await this.tableExists('FieldHistories')) {
- const historyId = this.generateId();
- const valueSnapshot = JSON.stringify(filteredValues);
-
- await this.client.executeUpdate(FieldHistoryQueries.INSERT, [
- historyId,
- itemId,
- null,
- field.FieldKey,
- valueSnapshot,
- now,
- now,
- now,
- 0
- ]);
- }
- }
- }
- }
-
- /**
- * Ensure a field definition exists for a custom field.
- * Creates the definition if it doesn't exist.
- * @returns The field definition ID (which is the field's FieldKey/tempId)
- */
- private async ensureFieldDefinition(
- field: ItemField,
- itemType: string,
- currentDateTime: string
- ): Promise<string> {
- const existingDef = await this.client.executeQuery<{ Id: string }>(
- FieldDefinitionQueries.EXISTS,
- [field.FieldKey]
- );
-
- if (existingDef.length === 0) {
- await this.client.executeUpdate(FieldDefinitionQueries.INSERT, [
- field.FieldKey,
- field.FieldType,
- field.Label,
- 0, // IsMultiValue
- field.IsHidden ? 1 : 0,
- 0, // EnableHistory
- field.DisplayOrder ?? 0,
- itemType,
- currentDateTime,
- currentDateTime,
- 0
- ]);
- }
-
- return field.FieldKey;
- }
-
- /**
- * Ensure a field definition exists and is up-to-date.
- * Creates the definition if it doesn't exist, or updates it if it does.
- * @returns The field definition ID (which is the field's FieldKey/tempId)
- */
- private async ensureOrUpdateFieldDefinition(
- field: ItemField,
- itemType: string,
- currentDateTime: string
- ): Promise<string> {
- const existingDef = await this.client.executeQuery<{ Id: string }>(
- FieldDefinitionQueries.EXISTS_ACTIVE,
- [field.FieldKey]
- );
-
- if (existingDef.length === 0) {
- await this.client.executeUpdate(FieldDefinitionQueries.INSERT, [
- field.FieldKey,
- field.FieldType,
- field.Label,
- 0, // IsMultiValue
- field.IsHidden ? 1 : 0,
- 0, // EnableHistory
- field.DisplayOrder ?? 0,
- itemType,
- currentDateTime,
- currentDateTime,
- 0
- ]);
- } else {
- // Update existing field definition (label, type, etc. may have changed)
- await this.client.executeUpdate(FieldDefinitionQueries.UPDATE, [
- field.Label,
- field.FieldType,
- field.IsHidden ? 1 : 0,
- field.DisplayOrder ?? 0,
- currentDateTime,
- field.FieldKey
- ]);
- }
-
- return field.FieldKey;
- }
-
- /**
- * Update field values using preserve-and-track strategy.
- * Preserves existing field value IDs when possible for stable merge behavior.
- */
- private async updateFieldValues(itemId: string, fields: ItemField[], itemType: string, now: string): Promise<void> {
- // 1. Get existing field values
- const existingFields = await this.client.executeQuery<{
- Id: string;
- FieldKey: string | null;
- FieldDefinitionId: string | null;
- Value: string;
- Weight: number;
- }>(FieldValueQueries.GET_EXISTING_FOR_ITEM, [itemId]);
-
- // 2. Build lookup by composite key (FieldKey or FieldDefinitionId + index)
- const existingByKey = new Map<string, { Id: string; Value: string; Weight: number }[]>();
- for (const existing of existingFields) {
- const key = existing.FieldKey || existing.FieldDefinitionId || '';
- if (!existingByKey.has(key)) {
- existingByKey.set(key, []);
- }
- existingByKey.get(key)!.push({ Id: existing.Id, Value: existing.Value, Weight: existing.Weight });
- }
-
- // 3. Track which existing IDs we've processed
- const processedIds = new Set<string>();
-
- // 4. Process each field
- for (let i = 0; i < fields.length; i++) {
- const field = fields[i];
- const values = Array.isArray(field.Value) ? field.Value : [field.Value];
- const existingForKey = existingByKey.get(field.FieldKey) || [];
-
- // Skip empty system fields, but always persist custom fields (even if empty)
- const filteredValues = values.filter(v => v !== undefined && v !== null && v !== '');
- if (filteredValues.length === 0 && !field.IsCustomField) {
- continue;
- }
-
- // For custom fields with no values, use empty string to preserve the field
- const valuesToProcess = field.IsCustomField && filteredValues.length === 0
- ? ['']
- : filteredValues;
-
- let fieldDefinitionId: string | null = null;
-
- // For custom fields, ensure FieldDefinition exists and is up-to-date
- if (field.IsCustomField) {
- fieldDefinitionId = await this.ensureOrUpdateFieldDefinition(field, itemType, now);
- }
-
- for (let j = 0; j < valuesToProcess.length; j++) {
- const value = valuesToProcess[j];
- const newWeight = field.DisplayOrder ?? 0;
-
- const existingEntry = existingForKey[j];
-
- if (existingEntry) {
- // Update existing if value or weight changed
- processedIds.add(existingEntry.Id);
- if (existingEntry.Value !== value || existingEntry.Weight !== newWeight) {
- await this.client.executeUpdate(FieldValueQueries.UPDATE, [
- value,
- newWeight,
- now,
- existingEntry.Id
- ]);
- }
- } else {
- // Insert new field value
- await this.client.executeUpdate(FieldValueQueries.INSERT, [
- this.generateId(),
- itemId,
- fieldDefinitionId, // FieldDefinitionId for custom, null for system
- field.IsCustomField ? null : field.FieldKey, // FieldKey for system, null for custom
- value,
- newWeight,
- now,
- now,
- 0
- ]);
- }
- }
- }
-
- // 5. Soft delete removed fields
- for (const existing of existingFields) {
- if (!processedIds.has(existing.Id)) {
- await this.client.executeUpdate(FieldValueQueries.SOFT_DELETE, [now, existing.Id]);
- }
- }
- }
-
- /**
- * Sync related entities (TOTP codes, attachments) with insert/update/delete tracking.
- * - Deletes entities that were removed (in originalIds but not in current).
- * - Updates existing entities (in both originalIds and current) when updateQuery and toUpdateParams are provided.
- * - Inserts new entities (in current but not in originalIds).
- */
- private async syncRelatedEntities<T extends { Id: string }>(
- tableName: string,
- foreignKey: string,
- foreignKeyValue: string,
- originalIds: string[],
- currentEntities: T[],
- toParams: (entity: T) => (string | number | null | Uint8Array)[],
- insertQuery: string,
- updateQuery?: string,
- toUpdateParams?: (entity: T) => (string | number | null | Uint8Array)[],
- // Optional override for the soft-delete SQL. Useful for tables that carry
- // blob payloads (e.g. Attachments) and want the bytes cleared in the same
- // statement. Must accept params [updatedAt, id] in that order.
- softDeleteSql?: string
- ): Promise<void> {
- const now = this.now();
- const currentIds = currentEntities.map(e => e.Id);
-
- const deleteSql = softDeleteSql
- ?? `UPDATE ${tableName} SET IsDeleted = 1, UpdatedAt = ? WHERE Id = ?`;
-
- // Delete entities that were removed
- const toDelete = originalIds.filter(id => !currentIds.includes(id));
- for (const id of toDelete) {
- await this.client.executeUpdate(deleteSql, [now, id]);
- }
-
- // Update existing entities when their data changed
- if (updateQuery && toUpdateParams) {
- for (const entity of currentEntities) {
- if (originalIds.includes(entity.Id)) {
- await this.client.executeUpdate(updateQuery, toUpdateParams(entity));
- }
- }
- }
-
- // Insert new entities
- for (const entity of currentEntities) {
- if (!originalIds.includes(entity.Id)) {
- await this.client.executeUpdate(insertQuery, toParams(entity));
- }
- }
- }
-
- /**
- * Track field history for fields with EnableHistory=true.
- * Compares old values with new values and creates history records.
- *
- * This saves the NEW value to history on every change. Since each value is saved
- * when it's set, we don't need to save the old value (it was already saved when
- * it was first set). This ensures that during merge conflicts, no values are ever
- * lost since history records sync independently via LWW and each has a unique ID.
- */
- private async trackFieldHistory(
- itemId: string,
- newFields: ItemField[],
- currentDateTime: string
- ): Promise<void> {
- // Check if FieldHistories table exists
- if (!(await this.tableExists('FieldHistories'))) {
- return;
- }
-
- const existingFields = await this.client.executeQuery<{ FieldKey: string; Value: string }>(
- FieldHistoryQueries.GET_FOR_HISTORY,
- [itemId]
- );
-
- // Create a map of existing values by FieldKey
- const existingValuesMap: { [key: string]: string[] } = {};
- for (const field of existingFields) {
- if (!existingValuesMap[field.FieldKey]) {
- existingValuesMap[field.FieldKey] = [];
- }
- existingValuesMap[field.FieldKey].push(field.Value);
- }
-
- for (const newField of newFields) {
- /**
- * Check if history tracking is enabled for this field.
- * EnableHistory comes from SystemFieldRegistry for system fields,
- * or from the FieldDefinitions table for custom fields.
- */
- if (!newField.EnableHistory) {
- continue;
- }
-
- const oldValues = existingValuesMap[newField.FieldKey] || [];
- const newValues = Array.isArray(newField.Value) ? newField.Value : [newField.Value];
-
- // Filter out empty values for comparison
- const filteredNewValues = newValues.filter(v => v && v.trim() !== '');
-
- const valuesChanged = oldValues.length !== filteredNewValues.length ||
- !oldValues.every((val, idx) => val === filteredNewValues[idx]);
-
- // Save new values to history when they change (ensures they survive merge conflicts)
- if (valuesChanged && filteredNewValues.length > 0) {
- const historyId = this.generateId();
- const valueSnapshot = JSON.stringify(filteredNewValues);
-
- await this.client.executeUpdate(FieldHistoryQueries.INSERT, [
- historyId,
- itemId,
- null,
- newField.FieldKey,
- valueSnapshot,
- currentDateTime,
- currentDateTime,
- currentDateTime,
- 0
- ]);
-
- await this.pruneFieldHistory(itemId, newField.FieldKey, currentDateTime);
- }
- }
- }
-
- /**
- * Prune old field history records.
- * Keeps only the most recent MAX_FIELD_HISTORY_RECORDS records.
- */
- private async pruneFieldHistory(
- itemId: string,
- fieldKey: string,
- currentDateTime: string
- ): Promise<void> {
- const matchingHistory = await this.client.executeQuery<{ Id: string; ChangedAt: string }>(
- FieldHistoryQueries.GET_FOR_PRUNING,
- [itemId, fieldKey]
- );
-
- if (matchingHistory.length > MAX_FIELD_HISTORY_RECORDS) {
- const recordsToDelete = matchingHistory.slice(MAX_FIELD_HISTORY_RECORDS);
- const idsToDelete = recordsToDelete.map(r => r.Id);
-
- if (idsToDelete.length > 0) {
- await this.client.executeUpdate(
- FieldHistoryQueries.softDeleteOld(idsToDelete.length),
- [currentDateTime, ...idsToDelete]
- );
- }
- }
- }
-
- /**
- * Resolve the logo ID for an item (create new or reuse existing).
- * If item.Logo is undefined, returns null to clear any existing logo.
- * @param item - The item to resolve logo for
- * @param currentDateTime - The current timestamp
- * @returns The logo ID, or null if no logo
- */
- private async resolveLogoId(item: Item, currentDateTime: string): Promise<string | null> {
- if (!this.logoRepository) {
- return null;
- }
-
- // Derive the source key from the same URL the favicon was fetched for.
- const urlField = item.Fields?.find(f => f.FieldKey === 'login.url');
- const target = await selectFaviconTarget(urlField?.Value);
-
- // No valid URL found: clear any existing logo.
- if (!target) {
- return null;
- }
-
- // If item has Logo data, create or reuse a logo entry
- if (item.Logo) {
- const logoData = this.logoRepository.convertLogoToUint8Array(item.Logo);
- return logoData ? this.logoRepository.getOrCreate(target.source, logoData, currentDateTime) : null;
- }
-
- // No logo data provided, but we have a valid URL. Try to find any logo for this source.
- return this.logoRepository.getIdForSource(target.source);
- }
-}
diff --git a/apps/mobile-app/utils/db/repositories/LogoRepository.ts b/apps/mobile-app/utils/db/repositories/LogoRepository.ts
deleted file mode 100644
index a4447d554..000000000
--- a/apps/mobile-app/utils/db/repositories/LogoRepository.ts
+++ /dev/null
@@ -1,176 +0,0 @@
-import { Buffer } from 'buffer';
-
-import { BaseRepository } from '../BaseRepository';
-
-/**
- * SQL query constants for Logo operations.
- */
-const LogoQueries = {
- /**
- * Check if logo exists for source.
- */
- GET_ID_FOR_SOURCE: `
- SELECT Id FROM Logos
- WHERE Source = ? AND IsDeleted = 0
- LIMIT 1`,
-
- /**
- * Look up a logo by source regardless of IsDeleted state.
- */
- GET_BY_SOURCE_INCLUDING_DELETED: `
- SELECT Id, IsDeleted FROM Logos
- WHERE Source = ?
- LIMIT 1`,
-
- /**
- * Insert new logo.
- */
- INSERT: `
- INSERT INTO Logos (Id, Source, FileData, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?)`,
-
- /**
- * Restore a soft-deleted logo and refill its FileData in one statement.
- */
- RESTORE_WITH_FILE_DATA: `
- UPDATE Logos
- SET IsDeleted = 0,
- FileData = ?,
- UpdatedAt = ?
- WHERE Id = ?`,
-
- /**
- * Count items using a logo.
- */
- COUNT_USAGE: `
- SELECT COUNT(*) as count FROM Items
- WHERE LogoId = ? AND IsDeleted = 0`,
-
- /**
- * Hard delete logo.
- */
- HARD_DELETE: `
- DELETE FROM Logos WHERE Id = ?`
-};
-
-/**
- * Repository for Logo management operations.
- */
-export class LogoRepository extends BaseRepository {
- /**
- * Check if a logo exists for the given source domain.
- * @param source The normalized source domain (e.g., 'github.com')
- * @returns True if a logo exists for this source
- */
- public async hasLogoForSource(source: string): Promise<boolean> {
- const existingLogos = await this.client.executeQuery<{ Id: string }>(
- LogoQueries.GET_ID_FOR_SOURCE,
- [source]
- );
- return existingLogos.length > 0;
- }
-
- /**
- * Get the logo ID for a given source domain if it exists.
- * @param source The normalized source domain (e.g., 'github.com')
- * @returns The logo ID if found, null otherwise
- */
- public async getIdForSource(source: string): Promise<string | null> {
- const existingLogos = await this.client.executeQuery<{ Id: string }>(
- LogoQueries.GET_ID_FOR_SOURCE,
- [source]
- );
- return existingLogos.length > 0 ? existingLogos[0].Id : null;
- }
-
- /**
- * Get or create a logo ID for the given source domain.
- * If a logo for this source already exists, returns its ID.
- * Otherwise, creates a new logo entry and returns its ID.
- * @param source The normalized source domain (e.g., 'github.com')
- * @param logoData The logo image data as Uint8Array
- * @param currentDateTime The current date/time string for timestamps
- * @returns The logo ID (existing or newly created)
- */
- public async getOrCreate(source: string, logoData: Uint8Array, currentDateTime: string): Promise<string> {
- const existing = await this.client.executeQuery<{ Id: string; IsDeleted: number }>(
- LogoQueries.GET_BY_SOURCE_INCLUDING_DELETED,
- [source]
- );
-
- if (existing.length > 0) {
- const row = existing[0];
- if (row.IsDeleted === 1) {
- // Restore a previously soft-deleted record and refill its FileData.
- await this.client.executeUpdate(LogoQueries.RESTORE_WITH_FILE_DATA, [
- logoData,
- currentDateTime,
- row.Id
- ]);
- }
- return row.Id;
- }
-
- // Create new logo entry
- const logoId = this.generateId();
- await this.client.executeUpdate(LogoQueries.INSERT, [
- logoId,
- source,
- logoData,
- currentDateTime,
- currentDateTime,
- 0
- ]);
-
- return logoId;
- }
-
- /**
- * Clean up orphaned logo if no items reference it.
- * @param logoId - The ID of the logo to potentially clean up
- */
- public async cleanupOrphanedLogo(logoId: string): Promise<void> {
- const usageResult = await this.client.executeQuery<{ count: number }>(
- LogoQueries.COUNT_USAGE,
- [logoId]
- );
- const usageCount = usageResult.length > 0 ? usageResult[0].count : 0;
-
- if (usageCount === 0) {
- await this.client.executeUpdate(LogoQueries.HARD_DELETE, [logoId]);
- console.debug(`[LogoRepository] Deleted orphaned logo: ${logoId}`);
- }
- }
-
- /**
- * Convert logo data from various formats to Uint8Array.
- * @param logo The logo data in various possible formats
- * @returns Uint8Array of logo data, or null if conversion fails
- */
- public convertLogoToUint8Array(logo: unknown): Uint8Array | null {
- if (!logo) {
- return null;
- }
-
- try {
- // Handle base64 string (from native SQLite query results - both iOS and Android
- // return BLOB data as plain base64 strings through the React Native bridge)
- if (typeof logo === 'string') {
- return new Uint8Array(Buffer.from(logo, 'base64'));
- }
- // Handle object-like array conversion (from JSON deserialization)
- if (typeof logo === 'object' && !ArrayBuffer.isView(logo) && !Array.isArray(logo)) {
- const values = Object.values(logo as Record<string, number>);
- return new Uint8Array(values);
- }
- // Handle existing array types
- if (Array.isArray(logo) || logo instanceof ArrayBuffer || logo instanceof Uint8Array) {
- return new Uint8Array(logo as ArrayLike<number>);
- }
- } catch (error) {
- console.warn('Failed to convert logo to Uint8Array:', error);
- }
-
- return null;
- }
-}
diff --git a/apps/mobile-app/utils/db/repositories/PasskeyRepository.ts b/apps/mobile-app/utils/db/repositories/PasskeyRepository.ts
deleted file mode 100644
index ef91397d3..000000000
--- a/apps/mobile-app/utils/db/repositories/PasskeyRepository.ts
+++ /dev/null
@@ -1,252 +0,0 @@
-import type { Passkey } from '@/utils/dist/core/models/vault';
-
-import { BaseRepository } from '../BaseRepository';
-
-/**
- * Extended passkey type with item metadata.
- */
-export type PasskeyWithItemInfo = Passkey & {
- Username?: string | null;
- ItemName?: string | null;
-};
-
-/**
- * SQL query constants for Passkey operations.
- */
-const PasskeyQueries = {
- /**
- * Get all passkeys for a specific relying party (rpId).
- * Joins with Items and FieldValues to get item name and username.
- */
- GET_BY_RP_ID: `
- SELECT
- p.Id,
- p.ItemId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.DisplayName,
- p.PrfKey,
- p.AdditionalData,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted,
- i.Name as ItemName,
- fv.Value as Username
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- LEFT JOIN FieldValues fv ON fv.ItemId = i.Id AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0
- WHERE p.RpId = ? AND p.IsDeleted = 0
- ORDER BY p.CreatedAt DESC`,
-
- /**
- * Get a passkey by its ID.
- * Joins with Items and FieldValues to get item name and username.
- */
- GET_BY_ID: `
- SELECT
- p.Id,
- p.ItemId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.DisplayName,
- p.PrfKey,
- p.AdditionalData,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted,
- i.Name as ItemName,
- fv.Value as Username
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- LEFT JOIN FieldValues fv ON fv.ItemId = i.Id AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0
- WHERE p.Id = ? AND p.IsDeleted = 0`,
-
- /**
- * Get all passkeys for a specific item.
- * Joins with Items and FieldValues to get item name and username.
- */
- GET_BY_ITEM_ID: `
- SELECT
- p.Id,
- p.ItemId,
- p.RpId,
- p.UserHandle,
- p.PublicKey,
- p.PrivateKey,
- p.DisplayName,
- p.PrfKey,
- p.AdditionalData,
- p.CreatedAt,
- p.UpdatedAt,
- p.IsDeleted,
- i.Name as ItemName,
- fv.Value as Username
- FROM Passkeys p
- INNER JOIN Items i ON p.ItemId = i.Id AND i.IsDeleted = 0 AND i.DeletedAt IS NULL
- LEFT JOIN FieldValues fv ON fv.ItemId = i.Id AND fv.FieldKey = 'login.username' AND fv.IsDeleted = 0
- WHERE p.ItemId = ? AND p.IsDeleted = 0
- ORDER BY p.CreatedAt DESC`,
-
- /**
- * Insert a new passkey.
- */
- INSERT: `
- INSERT INTO Passkeys (
- Id, ItemId, RpId, PublicKey, PrivateKey,
- PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted
- )
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
-
- /**
- * Soft delete a passkey by ID.
- */
- SOFT_DELETE: `
- UPDATE Passkeys
- SET IsDeleted = 1,
- UpdatedAt = ?
- WHERE Id = ?`,
-
- /**
- * Update passkey display name.
- */
- UPDATE_DISPLAY_NAME: `
- UPDATE Passkeys
- SET DisplayName = ?,
- UpdatedAt = ?
- WHERE Id = ?`
-};
-
-/**
- * Repository for Passkey CRUD operations.
- */
-export class PasskeyRepository extends BaseRepository {
- /**
- * Get all passkeys for a specific relying party (rpId).
- * @param rpId - The relying party identifier (domain)
- * @returns Array of passkey objects with item info
- */
- public async getByRpId(rpId: string): Promise<PasskeyWithItemInfo[]> {
- const results = await this.client.executeQuery(PasskeyQueries.GET_BY_RP_ID, [rpId]);
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return results.map((row: any) => this.mapRow(row));
- }
-
- /**
- * Get a passkey by its ID.
- * @param passkeyId - The passkey ID
- * @returns The passkey object or null if not found
- */
- public async getById(passkeyId: string): Promise<PasskeyWithItemInfo | null> {
- const results = await this.client.executeQuery(PasskeyQueries.GET_BY_ID, [passkeyId]);
-
- if (results.length === 0) {
- return null;
- }
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return this.mapRow(results[0] as any);
- }
-
- /**
- * Get all passkeys for a specific item.
- * @param itemId - The item ID
- * @returns Array of passkey objects with item info
- */
- public async getByItemId(itemId: string): Promise<PasskeyWithItemInfo[]> {
- const results = await this.client.executeQuery(PasskeyQueries.GET_BY_ITEM_ID, [itemId]);
-
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return results.map((row: any) => this.mapRow(row));
- }
-
- /**
- * Create a new passkey linked to an item.
- * @param passkey - The passkey object to create (without timestamps and IsDeleted)
- */
- public async create(passkey: Omit<Passkey, 'CreatedAt' | 'UpdatedAt' | 'IsDeleted'>): Promise<void> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
-
- // Convert PrfKey to Uint8Array if it's a number array
- let prfKeyData: Uint8Array | null = null;
- if (passkey.PrfKey) {
- prfKeyData = passkey.PrfKey instanceof Uint8Array ? passkey.PrfKey : new Uint8Array(passkey.PrfKey);
- }
-
- await this.client.executeUpdate(PasskeyQueries.INSERT, [
- passkey.Id,
- passkey.ItemId,
- passkey.RpId,
- passkey.PublicKey,
- passkey.PrivateKey,
- prfKeyData,
- passkey.DisplayName,
- passkey.AdditionalData ?? null,
- currentDateTime,
- currentDateTime,
- 0
- ]);
- });
- }
-
- /**
- * Delete a passkey by its ID (soft delete).
- * @param passkeyId - The ID of the passkey to delete
- * @returns The number of rows updated
- */
- public async delete(passkeyId: string): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
- return this.client.executeUpdate(PasskeyQueries.SOFT_DELETE, [
- currentDateTime,
- passkeyId
- ]);
- });
- }
-
- /**
- * Update a passkey's display name.
- * @param passkeyId - The ID of the passkey to update
- * @param displayName - The new display name
- * @returns The number of rows updated
- */
- public async updateDisplayName(passkeyId: string, displayName: string): Promise<number> {
- return this.withTransaction(async () => {
- const currentDateTime = this.now();
- return this.client.executeUpdate(PasskeyQueries.UPDATE_DISPLAY_NAME, [
- displayName,
- currentDateTime,
- passkeyId
- ]);
- });
- }
-
- /**
- * Map a database row to a PasskeyWithItemInfo object.
- * @param row - Raw database row
- * @returns PasskeyWithItemInfo object
- */
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- private mapRow(row: any): PasskeyWithItemInfo {
- return {
- Id: row.Id,
- ItemId: row.ItemId,
- RpId: row.RpId,
- PublicKey: row.PublicKey,
- PrivateKey: row.PrivateKey,
- DisplayName: row.DisplayName,
- PrfKey: row.PrfKey,
- AdditionalData: row.AdditionalData,
- CreatedAt: row.CreatedAt,
- UpdatedAt: row.UpdatedAt,
- IsDeleted: row.IsDeleted,
- Username: row.Username,
- ItemName: row.ItemName
- };
- }
-}
diff --git a/apps/mobile-app/utils/db/repositories/SettingsRepository.ts b/apps/mobile-app/utils/db/repositories/SettingsRepository.ts
deleted file mode 100644
index 15d9b2f78..000000000
--- a/apps/mobile-app/utils/db/repositories/SettingsRepository.ts
+++ /dev/null
@@ -1,258 +0,0 @@
-import type { EncryptionKey, PasswordSettings, TotpCode, Attachment } from '@/utils/dist/core/models/vault';
-import { DEFAULT_PASSWORD_LENGTH, DEFAULT_WORD_COUNT } from '@/utils/dist/core/models/defaults';
-
-import { BaseRepository } from '../BaseRepository';
-
-/**
- * Sort order options for credentials list.
- * Values must match the C# CredentialSortOrder enum in the Blazor client for cross-platform sync.
- */
-export type CredentialSortOrder = 'OldestFirst' | 'NewestFirst' | 'Alphabetical';
-
-/**
- * SQL query constants for Settings and related operations.
- */
-const SettingsQueries = {
- /**
- * Get setting by key.
- */
- GET_SETTING: `
- SELECT s.Value
- FROM Settings s
- WHERE s.Key = ?`,
-
- /**
- * Get all encryption keys.
- */
- GET_ENCRYPTION_KEYS: `
- SELECT
- x.PublicKey,
- x.PrivateKey,
- x.IsPrimary
- FROM EncryptionKeys x`,
-
- /**
- * Get TOTP codes for an item.
- */
- GET_TOTP_FOR_ITEM: `
- SELECT
- Id,
- Name,
- SecretKey,
- Algorithm,
- Digits,
- Period,
- ItemId
- FROM TotpCodes
- WHERE ItemId = ? AND IsDeleted = 0`,
-
- /**
- * Get attachments for an item.
- */
- GET_ATTACHMENTS_FOR_ITEM: `
- SELECT
- Id,
- Filename,
- Blob,
- ItemId,
- CreatedAt,
- UpdatedAt,
- IsDeleted
- FROM Attachments
- WHERE ItemId = ? AND IsDeleted = 0`
-};
-
-/**
- * Repository for Settings and auxiliary data operations.
- */
-export class SettingsRepository extends BaseRepository {
- /**
- * Get setting from database for a given key.
- * Returns default value (empty string by default) if setting is not found.
- * @param key - The setting key
- * @param defaultValue - Default value if setting not found
- * @returns The setting value
- */
- public async getSetting(key: string, defaultValue: string = ''): Promise<string> {
- const results = await this.client.executeQuery<{ Value: string }>(
- SettingsQueries.GET_SETTING,
- [key]
- );
- return results.length > 0 ? results[0].Value : defaultValue;
- }
-
- /**
- * Get the default identity language from the database.
- * @returns The stored override value if set, otherwise empty string
- */
- public async getDefaultIdentityLanguage(): Promise<string> {
- return this.getSetting('DefaultIdentityLanguage');
- }
-
- /**
- * Get the default identity gender preference from the database.
- * @returns The gender preference or 'random' if not set
- */
- public async getDefaultIdentityGender(): Promise<string> {
- return this.getSetting('DefaultIdentityGender', 'random');
- }
-
- /**
- * Get the default identity age range from the database.
- * @returns The age range preference or 'random' if not set
- */
- public async getDefaultIdentityAgeRange(): Promise<string> {
- return this.getSetting('DefaultIdentityAgeRange', 'random');
- }
-
- /**
- * Get the password settings from the database.
- * @returns Password settings object
- */
- public async getPasswordSettings(): Promise<PasswordSettings> {
- const settingsJson = await this.getSetting('PasswordGenerationSettings');
-
- const defaultSettings: PasswordSettings = {
- Length: DEFAULT_PASSWORD_LENGTH,
- UseLowercase: true,
- UseUppercase: true,
- UseNumbers: true,
- UseSpecialChars: true,
- UseNonAmbiguousChars: false,
- Type: 'basic',
- WordCount: DEFAULT_WORD_COUNT,
- // Empty = "auto": the passphrase language is resolved from the app language at runtime.
- Language: '',
- Capitalization: 'Lowercase',
- Separator: 'Dash',
- Salt: 'None'
- };
-
- try {
- if (settingsJson) {
- return { ...defaultSettings, ...JSON.parse(settingsJson) };
- }
- } catch (error) {
- console.warn('Failed to parse password settings:', error);
- }
-
- return defaultSettings;
- }
-
- /**
- * Persist the password generator settings as a JSON blob.
- * Mirrors the `PasswordGenerationSettings` key used by the other AliasVault clients.
- * @param settings - The password settings to store.
- */
- public async setPasswordSettings(settings: PasswordSettings): Promise<void> {
- await this.updateSetting('PasswordGenerationSettings', JSON.stringify(settings));
- }
-
- /**
- * Fetch all encryption keys.
- * @returns Array of encryption keys
- */
- public async getAllEncryptionKeys(): Promise<EncryptionKey[]> {
- return this.client.executeQuery<EncryptionKey>(SettingsQueries.GET_ENCRYPTION_KEYS);
- }
-
- /**
- * Get TOTP codes for an item.
- * @param itemId - The ID of the item to get TOTP codes for
- * @returns Array of TotpCode objects
- */
- public async getTotpCodesForItem(itemId: string): Promise<TotpCode[]> {
- try {
- if (!await this.tableExists('TotpCodes')) {
- return [];
- }
-
- return this.client.executeQuery<TotpCode>(SettingsQueries.GET_TOTP_FOR_ITEM, [itemId]);
- } catch (error) {
- console.error('Error getting TOTP codes for item:', error);
- return [];
- }
- }
-
- /**
- * Get attachments for an item.
- * @param itemId - The ID of the item
- * @returns Array of attachments for the item
- */
- public async getAttachmentsForItem(itemId: string): Promise<Attachment[]> {
- try {
- if (!await this.tableExists('Attachments')) {
- return [];
- }
-
- return this.client.executeQuery<Attachment>(
- SettingsQueries.GET_ATTACHMENTS_FOR_ITEM,
- [itemId]
- );
- } catch (error) {
- console.error('Error getting attachments for item:', error);
- return [];
- }
- }
-
- /**
- * Get the default email domain for new aliases.
- * @returns The default email domain or empty string if not set
- */
- public async getDefaultEmailDomain(): Promise<string> {
- return this.getSetting('DefaultEmailDomain');
- }
-
- /**
- * Update or insert a setting.
- * @param key - The setting key
- * @param value - The setting value
- */
- public async updateSetting(key: string, value: string): Promise<void> {
- await this.withTransaction(async () => {
- const now = this.now();
-
- // Check if setting exists
- const results = await this.client.executeQuery<{ count: number }>(
- `SELECT COUNT(*) as count FROM Settings WHERE Key = ?`,
- [key]
- );
- const exists = results[0]?.count > 0;
-
- if (exists) {
- await this.client.executeUpdate(
- `UPDATE Settings SET Value = ?, UpdatedAt = ? WHERE Key = ?`,
- [value, now, key]
- );
- } else {
- await this.client.executeUpdate(
- `INSERT INTO Settings (Key, Value, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?)`,
- [key, value, now, now, 0]
- );
- }
- });
- }
-
- /**
- * Get the credentials sort order preference.
- * Uses the same key the other clients use for cross-platform sync.
- * @returns The sort order preference
- */
- public async getCredentialsSortOrder(): Promise<CredentialSortOrder> {
- const value = await this.getSetting('CredentialsSortOrder', 'NewestFirst');
- // Validate the value is a valid sort order
- if (value === 'OldestFirst' || value === 'NewestFirst' || value === 'Alphabetical') {
- return value;
- }
- return 'NewestFirst';
- }
-
- /**
- * Set the credentials sort order preference.
- * Uses the same key the other clients use for cross-platform sync.
- * @param order - The sort order to set
- */
- public async setCredentialsSortOrder(order: CredentialSortOrder): Promise<void> {
- await this.updateSetting('CredentialsSortOrder', order);
- }
-}
diff --git a/apps/mobile-app/utils/types/errors/ApiAuthError.ts b/apps/mobile-app/utils/types/errors/ApiAuthError.ts
deleted file mode 100644
index 83b91b46a..000000000
--- a/apps/mobile-app/utils/types/errors/ApiAuthError.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * Custom error class for API authentication-related errors.
- */
-export class ApiAuthError extends Error {
- /**
- * Creates a new instance of ApiAuthError.
- *
- * @param message - The error message.
- */
- public constructor(message: string) {
- super(message);
- this.name = 'ApiAuthError';
- }
-}
diff --git a/apps/mobile-app/utils/types/errors/AppErrorCodes.ts b/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
index f20e92caf..35c82381d 100644
--- a/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
+++ b/apps/mobile-app/utils/types/errors/AppErrorCodes.ts
@@ -24,6 +24,9 @@ export enum AppErrorCode {
// Generic errors (E-0xx) - from AppError.kt
UNKNOWN_ERROR = 'E-001',
PARSE_ERROR = 'E-002',
+ SYNC_RESPONSE_INVALID = 'E-003', // Sync engine: a server response is not the JSON shape the client expects
+ SYNC_CODEC_FAILED = 'E-004', // Sync engine: the core library (codec, merge or crypto) refused the vault data
+ SYNC_ENGINE_FAILED = 'E-005', // Sync engine: a state it has no rule for (the detail says which)
// Authentication errors (E-1xx) - from AppError.kt
AUTHENTICATION_FAILED = 'E-101',
@@ -34,6 +37,7 @@ export enum AppErrorCode {
SERVER_UNAVAILABLE = 'E-201',
NETWORK_ERROR = 'E-202',
TIMEOUT = 'E-203',
+ SERVER_ERROR = 'E-204', // The server answered a sync request with an unexpected HTTP failure
// Version/compatibility errors (E-3xx) - from AppError.kt
CLIENT_VERSION_NOT_SUPPORTED = 'E-301',
@@ -44,6 +48,7 @@ export enum AppErrorCode {
VAULT_MERGE_REQUIRED = 'E-401',
VAULT_OUTDATED = 'E-402',
VAULT_NOT_FOUND = 'E-403', // VaultSync.kt: no local vault for merge
+ SYNC_VAULT_FETCH_FAILED = 'E-404', // Sync engine: the server's vault snapshot cannot be assembled
// Decryption/Encryption errors (E-5xx) - from AppError.kt
VAULT_DECRYPT_FAILED = 'E-501',
@@ -64,6 +69,9 @@ export enum AppErrorCode {
BIOMETRIC_LOCKOUT = 'E-516', // iOS: biometric locked out due to too many failed attempts
// Database/Storage errors (E-6xx) - from VaultSync.kt
+ STORAGE_READ_FAILED = 'E-601', // Sync engine: a state, database or at-rest vault read failed
+ STORAGE_WRITE_FAILED = 'E-602', // Sync engine: a state, database or at-rest vault write failed
+ DATABASE_INIT_FAILED = 'E-603', // Sync engine: the staging database could not be opened
VAULT_STORE_FAILED = 'E-604', // AppError: failed to store vault
// Merge errors (E-7xx) - from VaultSync.kt
@@ -77,6 +85,7 @@ export enum AppErrorCode {
// Native module/retry errors (E-9xx)
MAX_RETRIES_REACHED = 'E-901', // AppError: max sync retries reached
NATIVE_UNLOCK_FAILED = 'E-902', // useVaultSync.ts: vault unlock failed
+ MIGRATION_CHECK_FAILED = 'E-903', // Sync engine: the vault migration check failed
}
/**
@@ -195,6 +204,9 @@ export function getErrorTranslationKey(code: AppErrorCode): string {
// Generic errors
[AppErrorCode.UNKNOWN_ERROR]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.PARSE_ERROR]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.SYNC_RESPONSE_INVALID]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.SYNC_CODEC_FAILED]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.SYNC_ENGINE_FAILED]: 'common.errors.unknownErrorTryAgain',
// Authentication errors
[AppErrorCode.AUTHENTICATION_FAILED]: 'auth.errors.sessionExpired',
@@ -205,6 +217,7 @@ export function getErrorTranslationKey(code: AppErrorCode): string {
[AppErrorCode.SERVER_UNAVAILABLE]: 'auth.errors.serverError',
[AppErrorCode.NETWORK_ERROR]: 'auth.errors.networkError',
[AppErrorCode.TIMEOUT]: 'auth.errors.networkError',
+ [AppErrorCode.SERVER_ERROR]: 'auth.errors.serverError',
// Version errors
[AppErrorCode.CLIENT_VERSION_NOT_SUPPORTED]: 'vault.errors.versionNotSupported',
@@ -215,6 +228,7 @@ export function getErrorTranslationKey(code: AppErrorCode): string {
[AppErrorCode.VAULT_MERGE_REQUIRED]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.VAULT_OUTDATED]: 'vault.errors.vaultOutdated',
[AppErrorCode.VAULT_NOT_FOUND]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.SYNC_VAULT_FETCH_FAILED]: 'common.errors.unknownErrorTryAgain',
// Decryption/Encryption errors
[AppErrorCode.VAULT_DECRYPT_FAILED]: 'common.errors.unknownErrorTryAgain',
@@ -235,6 +249,9 @@ export function getErrorTranslationKey(code: AppErrorCode): string {
[AppErrorCode.BIOMETRIC_LOCKOUT]: 'common.errors.unknownErrorTryAgain',
// Database/Storage errors
+ [AppErrorCode.STORAGE_READ_FAILED]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.STORAGE_WRITE_FAILED]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.DATABASE_INIT_FAILED]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.VAULT_STORE_FAILED]: 'common.errors.unknownErrorTryAgain',
// Merge errors
@@ -248,6 +265,7 @@ export function getErrorTranslationKey(code: AppErrorCode): string {
// Native module/retry errors
[AppErrorCode.MAX_RETRIES_REACHED]: 'common.errors.unknownErrorTryAgain',
[AppErrorCode.NATIVE_UNLOCK_FAILED]: 'common.errors.unknownErrorTryAgain',
+ [AppErrorCode.MIGRATION_CHECK_FAILED]: 'common.errors.unknownErrorTryAgain',
};
return codeToKeyMap[code] || 'common.errors.unknownErrorTryAgain';
diff --git a/apps/mobile-app/utils/types/errors/ClientUpgradeRequiredError.ts b/apps/mobile-app/utils/types/errors/ClientUpgradeRequiredError.ts
deleted file mode 100644
index c003f0535..000000000
--- a/apps/mobile-app/utils/types/errors/ClientUpgradeRequiredError.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-/**
- * Thrown when the server rejects the request with HTTP 426 because this app version is too old to
- * access the account.
- */
-export class ClientUpgradeRequiredError extends Error {
- /**
- * Creates a new instance of ClientUpgradeRequiredError.
- */
- public constructor() {
- super('HTTP 426: client version no longer supported by the server');
- this.name = 'ClientUpgradeRequiredError';
- }
-}
diff --git a/apps/mobile-app/utils/types/errors/PayloadTooLargeError.ts b/apps/mobile-app/utils/types/errors/PayloadTooLargeError.ts
deleted file mode 100644
index c2418c0e3..000000000
--- a/apps/mobile-app/utils/types/errors/PayloadTooLargeError.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-/**
- * Thrown when the server rejects a request with HTTP 413 (Request Entity Too Large).
- * For vault uploads this signals the encrypted vault exceeds the server's MAX_UPLOAD_SIZE_MB limit.
- */
-export class PayloadTooLargeError extends Error {
- /**
- * Creates a new instance of PayloadTooLargeError.
- *
- * @param message - The error message.
- */
- public constructor(message: string) {
- super(message);
- this.name = 'PayloadTooLargeError';
- }
-}
diff --git a/apps/mobile-app/utils/types/errors/VaultAuthenticationError.ts b/apps/mobile-app/utils/types/errors/VaultAuthenticationError.ts
index add11c020..9b0e6d6bc 100644
--- a/apps/mobile-app/utils/types/errors/VaultAuthenticationError.ts
+++ b/apps/mobile-app/utils/types/errors/VaultAuthenticationError.ts
@@ -13,8 +13,7 @@ export class VaultAuthenticationError extends Error {
this.name = 'VaultAuthenticationError';
// Maintains proper stack trace for where our error was thrown (only available on V8)
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, VaultAuthenticationError);
- }
+ const errorWithTrace = Error as { captureStackTrace?: (target: object, constructor: unknown) => void };
+ errorWithTrace.captureStackTrace?.(this, VaultAuthenticationError);
}
}
diff --git a/apps/mobile-app/utils/types/errors/VaultVersionIncompatibleError.ts b/apps/mobile-app/utils/types/errors/VaultVersionIncompatibleError.ts
deleted file mode 100644
index 08b7a986c..000000000
--- a/apps/mobile-app/utils/types/errors/VaultVersionIncompatibleError.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-/**
- * Custom error class for vault version incompatibility issues.
- * Thrown when the mobile app is outdated and cannot handle the vault version.
- */
-export class VaultVersionIncompatibleError extends Error {
- /**
- * Creates a new instance of the VaultVersionIncompatibleError class.
- * @param message - The error message.
- */
- public constructor(message: string) {
- super(message);
- this.name = 'VaultVersionIncompatibleError';
-
- // Maintains proper stack trace for where our error was thrown (only available on V8)
- if (Error.captureStackTrace) {
- Error.captureStackTrace(this, VaultVersionIncompatibleError);
- }
- }
-}