Skip to content

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

Update logo and attachment handling to prevent React dev tooling slowdown (#2159)

Leendert de Borstb2730abb5224
diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsx
index 2e6b425b6..940fb9b9c 100644
--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx
@@ -1,16 +1,18 @@
+import { Buffer } from 'buffer';
+
+import { decodeEmailSource, extractEmailAttachment, type ParsedEmailAttachment } from '@aliasvault/client/rust/RustCore';
import { Ionicons } from '@expo/vector-icons';
import { File, Paths } from 'expo-file-system';
import { useLocalSearchParams, useRouter, useNavigation, Stack } from 'expo-router';
-import React, { useEffect, useMemo, useState, useCallback } from 'react';
+import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { StyleSheet, View, ActivityIndicator, useColorScheme, Linking, Text, TextInput, Platform } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { WebView, type WebViewNavigation } from 'react-native-webview';
import ConversionUtility from '@/utils/ConversionUtility';
-import type { Item } from '@/utils/dist/core/models/vault';
-import type { Email } from '@/utils/dist/core/models/webapi';
-import EncryptionUtility from '@/utils/EncryptionUtility';
+import type { DisplayItem } from '@/utils/DisplayItem';
+import EncryptionUtility, { type DecryptedEmail } from '@/utils/EncryptionUtility';
import emitter from '@/utils/EventEmitter';
import { useAttachmentViewer } from '@/hooks/useAttachmentViewer';
@@ -25,6 +27,8 @@ import { RobustPressable } from '@/components/ui/RobustPressable';
import { useDb } from '@/context/DbContext';
import { useWebApi } from '@/context/WebApiContext';
+import type { Email } from '@aliasvault/models/webapi';
+
/**
* Email details screen.
*/
@@ -39,14 +43,22 @@ export default function EmailDetailsScreen() : React.ReactNode {
const { openAttachment, viewerElement } = useAttachmentViewer();
const insets = useSafeAreaInsets();
const [error, setError] = useState<string | null>(null);
- const [email, setEmail] = useState<Email | null>(null);
+ // The source bytes stay in a ref, out of state; decrypted only records whether there are any.
+ const [decrypted, setDecrypted] = useState<(Omit<DecryptedEmail, 'sourceBytes'> & { hasSource: boolean }) | null>(null);
+ const sourceBytesRef = useRef<Uint8Array | null>(null);
+ const [sourceText, setSourceText] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isMetadataMaximized, setMetadataMaximized] = useState(false);
const [viewMode, setViewMode] = useState<'html' | 'plain' | 'source'>('html');
const isDarkMode = useColorScheme() === 'dark';
- const [associatedItem, setAssociatedItem] = useState<Item | null>(null);
+ const [associatedItem, setAssociatedItem] = useState<DisplayItem | null>(null);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
+ const email = decrypted?.email ?? null;
+ const htmlBody = decrypted?.htmlBody ?? null;
+ const textBody = decrypted?.textBody ?? null;
+ const hasSource = decrypted?.hasSource ?? false;
+
/**
* Load the email.
*/
@@ -69,23 +81,27 @@ export default function EmailDetailsScreen() : React.ReactNode {
const response = await webApi.get<Email>(`Email/${id}`);
// Decrypt email locally using public/private key pairs
- const encryptionKeys = await dbContext.sqliteClient.getAllEncryptionKeys();
+ const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
const decryptedEmail = await EncryptionUtility.decryptEmail(response, encryptionKeys);
- setEmail(decryptedEmail);
+ const { sourceBytes, ...parsedEmail } = decryptedEmail;
+ sourceBytesRef.current = sourceBytes;
+ setDecrypted({ ...parsedEmail, hasSource: sourceBytes !== null });
+ setSourceText(null);
// Look up associated item
- if (decryptedEmail.toLocal && decryptedEmail.toDomain) {
- const emailAddress = `${decryptedEmail.toLocal}@${decryptedEmail.toDomain}`;
- const item = await dbContext.sqliteClient.items.getByEmail(emailAddress);
+ if (decryptedEmail.email.toLocal && decryptedEmail.email.toDomain) {
+ const emailAddress = `${decryptedEmail.email.toLocal}@${decryptedEmail.email.toDomain}`;
+ const match = await dbContext.sqliteClient.items.findIdByEmail(emailAddress);
+ const item = match ? await dbContext.sqliteClient.items.getById(match.Id) : null;
setAssociatedItem(item);
}
- // Set initial view mode based on content — prefer HTML, fall back to plain, then source.
- if (decryptedEmail.messageHtml && decryptedEmail.messageHtml.length > 0) {
+ // Set initial view mode based on content: prefer HTML, fall back to plain, then source.
+ if (decryptedEmail.htmlBody) {
setViewMode('html');
- } else if (decryptedEmail.messagePlain) {
+ } else if (decryptedEmail.textBody) {
setViewMode('plain');
- } else if (decryptedEmail.messageSource) {
+ } else if (decryptedEmail.sourceBytes) {
setViewMode('source');
}
} catch (err) {
@@ -109,6 +125,19 @@ export default function EmailDetailsScreen() : React.ReactNode {
loadEmail();
}, [id, loadEmail]);
+ /*
+ * The raw source is decoded on demand, the first time the source view is opened.
+ */
+ useEffect(() => {
+ const sourceBytes = sourceBytesRef.current;
+ if (viewMode !== 'source' || sourceText !== null || !decrypted?.hasSource || !sourceBytes) {
+ return;
+ }
+ decodeEmailSource(sourceBytes)
+ .then(decoded => setSourceText(Buffer.from(decoded).toString('utf8')))
+ .catch(err => setError(err instanceof Error ? err.message : t('common.errors.unknownError')));
+ }, [viewMode, sourceText, decrypted, t]);
+
/**
* Handle the delete button press.
*/
@@ -143,31 +172,26 @@ export default function EmailDetailsScreen() : React.ReactNode {
}, []);
/**
- * Handle the download attachment button press.
+ * Handle the download attachment button press: the bytes come out of the parsed source, a detached part is
+ * fetched and decrypted first.
*/
- const handleDownloadAttachment = async (attachment: Email['attachments'][0]) : Promise<void> => {
+ const handleDownloadAttachment = async (attachment: ParsedEmailAttachment, index: number) : Promise<void> => {
try {
- const encryptedBytes = await webApi.downloadBlob(
- `Email/${id}/attachments/${attachment.id}`
- );
-
- if (!dbContext?.sqliteClient || !email) {
+ const sourceBytes = sourceBytesRef.current;
+ if (!dbContext?.sqliteClient || !email || !sourceBytes) {
setError(t('common.errors.unknownError'));
return;
}
- const encryptionKeys = await dbContext.sqliteClient.getAllEncryptionKeys();
- const decryptedBytes = await EncryptionUtility.decryptAttachment(
- encryptedBytes,
- email,
- encryptionKeys
- );
-
- if (!decryptedBytes) {
- setError(t('common.errors.unknownError'));
- return;
+ let detachedBody: Uint8Array | undefined;
+ if (attachment.detached && attachment.partIndex !== null) {
+ const encryptedPart = await webApi.downloadBlob(`Email/${id}/parts/${attachment.partIndex}`);
+ const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
+ detachedBody = await EncryptionUtility.decryptAttachment(encryptedPart, email, encryptionKeys);
}
+ const decryptedBytes = await extractEmailAttachment(sourceBytes, index, detachedBody);
+
const tempFile = new File(Paths.cache, attachment.filename);
if (tempFile.exists) {
tempFile.delete();
@@ -220,29 +244,26 @@ export default function EmailDetailsScreen() : React.ReactNode {
}
};
- // Only offer formats the server actually provided. Source comes from the raw MessageSource column.
+ // Only offer the formats the parsed source actually holds.
const availableModes = useMemo<Array<'html' | 'plain' | 'source'>>(() => {
- if (!email) {
- return [];
- }
const modes: Array<'html' | 'plain' | 'source'> = [];
- if (email.messageHtml) {
+ if (htmlBody) {
modes.push('html');
}
- if (email.messagePlain) {
+ if (textBody) {
modes.push('plain');
}
- if (email.messageSource) {
+ if (hasSource) {
modes.push('source');
}
return modes;
- }, [email]);
+ }, [htmlBody, textBody, hasSource]);
/*
- * Emails stored by newer server versions only contain the raw source. Until this client can
- * render those itself we show the source verbatim plus a notice to update.
+ * A source the parser found no body in is shown verbatim plus a notice to update the app, in case a newer
+ * server stores a shape this parser does not know yet.
*/
- const isSourceOnly = Boolean(email?.messageSource) && !email?.messageHtml && !email?.messagePlain;
+ const isSourceOnly = hasSource && !htmlBody && !textBody;
const formatLabels = useMemo<Record<'html' | 'plain' | 'source', string>>(() => ({
html: t('emails.formatHtml'),
@@ -573,9 +594,9 @@ export default function EmailDetailsScreen() : React.ReactNode {
}
let emailView = null;
- if (viewMode === 'html' && email.messageHtml) {
+ if (viewMode === 'html' && htmlBody) {
// Sanitize HTML
- const sanitizedHtml = ConversionUtility.sanitizeHtmlForEmailViewing(email.messageHtml);
+ const sanitizedHtml = ConversionUtility.sanitizeHtmlForEmailViewing(htmlBody);
emailView = (
<WebView
style={styles.webView}
@@ -588,7 +609,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
);
} else {
const isSource = viewMode === 'source';
- const text = (isSource ? email.messageSource : email.messagePlain) ?? '';
+ const text = (isSource ? sourceText ?? t('common.loading') : textBody) ?? '';
const textStyle = [
styles.plainText,
isSource ? styles.sourceText : null,
@@ -625,18 +646,18 @@ export default function EmailDetailsScreen() : React.ReactNode {
</View>
)}
{emailView}
- {email.attachments && email.attachments.length > 0 && (
+ {decrypted && decrypted.attachments.length > 0 && (
<View style={styles.attachments}>
<ThemedText style={styles.attachmentsTitle}>{t('emails.attachments')}</ThemedText>
- {email.attachments.map((attachment) => (
+ {decrypted.attachments.map((attachment, index) => (
<RobustPressable
- key={attachment.id}
+ key={`${index}-${attachment.filename}`}
style={styles.attachment}
- onPress={() => handleDownloadAttachment(attachment)}
+ onPress={() => handleDownloadAttachment(attachment, index)}
>
<Ionicons name="attach" size={20} color="#666" />
<ThemedText style={styles.attachmentName}>
- {attachment.filename} ({Math.ceil(attachment.filesize / 1024)} {t('emails.sizeKB')})
+ {attachment.filename} ({Math.ceil(attachment.size / 1024)} {t('emails.sizeKB')})
</ThemedText>
</RobustPressable>
))}
diff --git a/apps/mobile-app/app/(tabs)/items/[id].tsx b/apps/mobile-app/app/(tabs)/items/[id].tsx
index f67c8baf5..03abcaa2d 100644
--- a/apps/mobile-app/app/(tabs)/items/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/items/[id].tsx
@@ -8,6 +8,7 @@ import ContextMenu from 'react-native-context-menu-view';
import Toast from 'react-native-toast-message';
import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';
+import type { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { useColors } from '@/hooks/useColorScheme';
@@ -32,7 +33,6 @@ import { RobustPressable } from '@/components/ui/RobustPressable';
import { useDb } from '@/context/DbContext';
import { LocalPreferencesService } from '@/services/LocalPreferencesService';
-import type { Item } from '@aliasvault/models/vault';
import type { NativeSyntheticEvent } from 'react-native';
import type { ContextMenuOnPressNativeEvent } from 'react-native-context-menu-view';
@@ -41,7 +41,7 @@ import type { ContextMenuOnPressNativeEvent } from 'react-native-context-menu-vi
*/
export default function ItemDetailsScreen() : React.ReactNode {
const { id } = useLocalSearchParams();
- const [item, setItem] = useState<Item | null>(null);
+ const [item, setItem] = useState<DisplayItem | null>(null);
const [isLoading, setIsLoading] = useState(true);
const dbContext = useDb();
const navigation = useNavigation();
diff --git a/apps/mobile-app/app/(tabs)/items/add-edit.tsx b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
index b75610109..68cda96ea 100644
--- a/apps/mobile-app/app/(tabs)/items/add-edit.tsx
+++ b/apps/mobile-app/app/(tabs)/items/add-edit.tsx
@@ -12,6 +12,7 @@ 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 { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { HapticsUtility } from '@/utils/HapticsUtility';
import { extractServiceNameFromUrl, sanitizeServiceUrl } from '@/utils/UrlUtility';
@@ -82,8 +83,10 @@ export default function AddEditItemScreen(): React.ReactNode {
const [isSaving, setIsSaving] = useState(false);
const [saveStatus, setSaveStatus] = useState('');
const [isSaveDisabled, setIsSaveDisabled] = useState(false);
- const [attachments, setAttachments] = useState<Attachment[]>([]);
+ const [attachments, setAttachments] = useState<Omit<Attachment, 'Blob'>[]>([]);
const [originalAttachmentIds, setOriginalAttachmentIds] = useState<string[]>([]);
+ // The bytes of newly picked attachments by id, kept out of state until save.
+ const attachmentBlobsRef = useRef(new Map<string, Uint8Array>());
const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);
const [originalTotpCodeIds, setOriginalTotpCodeIds] = useState<string[]>([]);
const totpShowAddFormRef = useRef<(() => void) | null>(null);
@@ -96,7 +99,7 @@ export default function AddEditItemScreen(): React.ReactNode {
const [pendingNavigationAction, setPendingNavigationAction] = useState<NavigationAction | null>(null);
// Item state
- const [item, setItem] = useState<Item | null>(null);
+ const [item, setItem] = useState<DisplayItem | null>(null);
// Form state for dynamic fields - key is FieldKey, value is the field value
const [fieldValues, setFieldValues] = useState<Record<string, string | string[]>>({});
@@ -452,7 +455,8 @@ export default function AddEditItemScreen(): React.ReactNode {
// Load attachments for this item
const itemAttachments = await dbContext.sqliteClient!.items.getAttachmentsForItem(id);
- setAttachments(itemAttachments);
+ // A saved attachment is only ever kept or removed on save, so its bytes are not needed here.
+ setAttachments(itemAttachments.map(({ Blob: _blob, ...attachment }) => attachment));
setOriginalAttachmentIds(itemAttachments.map(a => a.Id));
if (itemAttachments.length > 0) {
setShowAttachments(true);
@@ -730,6 +734,13 @@ export default function AddEditItemScreen(): React.ReactNode {
}
}, [totpCodes]);
+ /**
+ * Keep the bytes of a newly picked attachment until save.
+ */
+ const handleAttachmentRead = useCallback((attachmentId: string, bytes: Uint8Array): void => {
+ attachmentBlobsRef.current.set(attachmentId, bytes);
+ }, []);
+
/**
* Show the attachments section.
*/
@@ -856,6 +867,9 @@ export default function AddEditItemScreen(): React.ReactNode {
itemToSave.Logo = undefined;
}
+ // Only newly picked attachments are inserted, so only they need their bytes back.
+ const attachmentsToSave = attachments.map(attachment => ({ ...attachment, Blob: attachmentBlobsRef.current.get(attachment.Id) ?? null }));
+
/*
* Execute mutation - local save + background sync (non-blocking).
* Navigate immediately after local save; sync happens in background via ServerSyncIndicator.
@@ -863,7 +877,7 @@ export default function AddEditItemScreen(): React.ReactNode {
try {
await executeVaultMutation(async () => {
if (isEditMode) {
- await dbContext.sqliteClient!.items.update(itemToSave, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes);
+ await dbContext.sqliteClient!.items.update(itemToSave, originalAttachmentIds, attachmentsToSave, originalTotpCodeIds, totpCodes);
// Delete passkeys if marked for deletion
if (passkeyIdsMarkedForDeletion.length > 0) {
@@ -872,7 +886,7 @@ export default function AddEditItemScreen(): React.ReactNode {
}
}
} else {
- await dbContext.sqliteClient!.items.create(itemToSave, attachments, totpCodes);
+ await dbContext.sqliteClient!.items.create(itemToSave, attachmentsToSave, totpCodes);
}
});
@@ -1627,6 +1641,7 @@ export default function AddEditItemScreen(): React.ReactNode {
<AttachmentUploader
attachments={attachments}
onAttachmentsChange={setAttachments}
+ onAttachmentRead={handleAttachmentRead}
/>
</FormSection>
)}
diff --git a/apps/mobile-app/app/(tabs)/items/autofill-link-existing.tsx b/apps/mobile-app/app/(tabs)/items/autofill-link-existing.tsx
index b0a6a4c29..334d12a2e 100644
--- a/apps/mobile-app/app/(tabs)/items/autofill-link-existing.tsx
+++ b/apps/mobile-app/app/(tabs)/items/autofill-link-existing.tsx
@@ -12,6 +12,7 @@ import { useTranslation } from 'react-i18next';
import { FlatList, Platform, StyleSheet, TextInput, TouchableOpacity, View, type ListRenderItem } from 'react-native';
import Toast from 'react-native-toast-message';
+import type { DisplayItem } from '@/utils/DisplayItem';
import { sanitizeServiceUrl } from '@/utils/UrlUtility';
import { useColors } from '@/hooks/useColorScheme';
@@ -55,7 +56,7 @@ export default function AutofillLinkExistingScreen(): React.ReactNode {
}
}, [itemUrl]);
- const [items, setItems] = useState<Item[]>([]);
+ const [items, setItems] = useState<DisplayItem[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const [isSaving, setIsSaving] = useState(false);
@@ -116,7 +117,7 @@ export default function AutofillLinkExistingScreen(): React.ReactNode {
* Append the autofill URL/package to the chosen item's `login.url`
* multi-value field and persist via the vault mutation pipeline.
*/
- const linkItem = useCallback(async (item: Item): Promise<void> => {
+ const linkItem = useCallback(async (item: DisplayItem): Promise<void> => {
if (!decodedAppInfo) {
return;
}
@@ -197,7 +198,7 @@ export default function AutofillLinkExistingScreen(): React.ReactNode {
/**
* Confirm with the user before mutating the credential.
*/
- const handleSelectItem = useCallback((item: Item) => {
+ const handleSelectItem = useCallback((item: DisplayItem) => {
if (isSaving) {
return;
}
@@ -301,7 +302,7 @@ export default function AutofillLinkExistingScreen(): React.ReactNode {
/**
* Render an individual credential row.
*/
- const renderItem: ListRenderItem<Item> = useCallback((info) => {
+ const renderItem: ListRenderItem<DisplayItem> = useCallback((info) => {
const row = info.item;
const username = getFieldValue(row, FieldKey.LoginUsername);
const email = getFieldValue(row, FieldKey.LoginEmail);
diff --git a/apps/mobile-app/app/(tabs)/items/deleted.tsx b/apps/mobile-app/app/(tabs)/items/deleted.tsx
index 430f1bac5..189a0c351 100644
--- a/apps/mobile-app/app/(tabs)/items/deleted.tsx
+++ b/apps/mobile-app/app/(tabs)/items/deleted.tsx
@@ -10,6 +10,7 @@ import {
} from 'react-native';
import Toast from 'react-native-toast-message';
+import type { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { useColors } from '@/hooks/useColorScheme';
@@ -48,7 +49,7 @@ export default function RecentlyDeletedScreen(): React.ReactNode {
const dbContext = useDb();
const { executeVaultMutation } = useVaultMutate();
- const [items, setItems] = useState<ItemWithDeletedAt[]>([]);
+ const [items, setItems] = useState<DisplayItem<ItemWithDeletedAt>[]>([]);
const [isLoadingItems, setIsLoadingItems] = useState(true);
const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
const [showConfirmDelete, setShowConfirmDelete] = useState(false);
@@ -269,7 +270,7 @@ export default function RecentlyDeletedScreen(): React.ReactNode {
/**
* Render an item card.
*/
- const renderItem = (item: ItemWithDeletedAt): React.ReactElement => {
+ const renderItem = (item: DisplayItem<ItemWithDeletedAt>): React.ReactElement => {
const daysRemaining = item.DeletedAt ? getDaysRemaining(item.DeletedAt) : TRASH_RETENTION_DAYS;
return (
diff --git a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
index 76acba44a..c59915175 100644
--- a/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/items/folder/[id].tsx
@@ -9,6 +9,7 @@ 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 { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { HapticsUtility } from '@/utils/HapticsUtility';
import { VaultAuthenticationError } from '@/utils/types/errors/VaultAuthenticationError';
@@ -39,7 +40,7 @@ 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';
+import type { ItemType } from '@aliasvault/models/vault';
/**
* Item type filter option configuration.
@@ -73,10 +74,10 @@ export default function FolderViewScreen(): React.ReactNode {
const router = useRouter();
const navigate = useNavigationDebounce();
const insets = useSafeAreaInsets();
- const flatListRef = useRef<FlatList<Item | null>>(null);
+ const flatListRef = useRef<FlatList<DisplayItem | null>>(null);
- const [itemsList, setItemsList] = useState<Item[]>([]);
- const [allItemsInVault, setAllItemsInVault] = useState<Item[]>([]);
+ const [itemsList, setItemsList] = useState<DisplayItem[]>([]);
+ const [allItemsInVault, setAllItemsInVault] = useState<DisplayItem[]>([]);
const [folder, setFolder] = useState<Folder | null>(null);
const [canCreateSubfolder, setCanCreateSubfolder] = useState(false);
const [allFolders, setAllFolders] = useState<Folder[]>([]);
@@ -210,7 +211,7 @@ export default function FolderViewScreen(): React.ReactNode {
dbContext.sqliteClient!.settings.getCredentialsSortOrder()
]);
// Filter to only items in this folder
- const folderItems = items.filter((item: Item) => item.FolderId === folderId);
+ const folderItems = items.filter((item: DisplayItem) => item.FolderId === folderId);
setItemsList(folderItems);
setAllItemsInVault(items);
diff --git a/apps/mobile-app/app/(tabs)/items/index.tsx b/apps/mobile-app/app/(tabs)/items/index.tsx
index f183908f3..a69134608 100644
--- a/apps/mobile-app/app/(tabs)/items/index.tsx
+++ b/apps/mobile-app/app/(tabs)/items/index.tsx
@@ -8,6 +8,7 @@ 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 { DisplayItem } from '@/utils/DisplayItem';
import emitter from '@/utils/EventEmitter';
import { HapticsUtility } from '@/utils/HapticsUtility';
import { VaultAuthenticationError } from '@/utils/types/errors/VaultAuthenticationError';
@@ -39,7 +40,7 @@ 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';
+import type { ItemType } from '@aliasvault/models/vault';
/**
* Item type filter option configuration.
@@ -71,11 +72,11 @@ export default function ItemsScreen(): React.ReactNode {
const [scrollY] = useState(() => new Animated.Value(0));
const navigation = useNavigation();
const insets = useSafeAreaInsets();
- const flatListRef = useRef<Animated.FlatList<Item | null>>(null);
+ const flatListRef = useRef<Animated.FlatList<DisplayItem | null>>(null);
const [isTabFocused, setIsTabFocused] = useState(false);
const router = useRouter();
const { itemUrl } = useLocalSearchParams<{ itemUrl?: string }>();
- const [itemsList, setItemsList] = useState<Item[]>([]);
+ const [itemsList, setItemsList] = useState<DisplayItem[]>([]);
const [folders, setFolders] = useState<Folder[]>([]);
const [isLoadingItems, setIsLoadingItems] = useMinDurationLoading(false, 200);
const [hasLoadedItems, setHasLoadedItems] = useState(false);
@@ -192,7 +193,7 @@ export default function ItemsScreen(): React.ReactNode {
*/
const getRecursiveItemCount = (folderId: string): number => {
// Get items directly in this folder
- const directItems = itemsForCount.filter((item: Item) => item.FolderId === folderId);
+ const directItems = itemsForCount.filter((item: DisplayItem) => item.FolderId === folderId);
// Get all child folders
const childFolders = folders.filter(f => f.ParentFolderId === folderId);
@@ -245,7 +246,7 @@ export default function ItemsScreen(): React.ReactNode {
* This is used to show a helpful message when the user has imported credentials that were all in folders.
*/
const hasItemsInFoldersOnly = useMemo(() => {
- return itemsList.length > 0 && itemsList.every((item: Item) => item.FolderId !== null);
+ return itemsList.length > 0 && itemsList.every((item: DisplayItem) => item.FolderId !== null);
}, [itemsList]);
/**
diff --git a/apps/mobile-app/components/EmailCard.tsx b/apps/mobile-app/components/EmailCard.tsx
index 7447b6464..2ffb50b6e 100644
--- a/apps/mobile-app/components/EmailCard.tsx
+++ b/apps/mobile-app/components/EmailCard.tsx
@@ -2,7 +2,7 @@ import { router } from 'expo-router';
import { useEffect, useState } from 'react';
import { StyleSheet, View } from 'react-native';
-import type { Item } from '@aliasvault/models/vault';
+import type { DisplayItem } from '@/utils/DisplayItem';
import type { MailboxEmail } from '@aliasvault/models/webapi';
import { useColors } from '@/hooks/useColorScheme';
@@ -27,7 +27,7 @@ export function EmailCard({ email }: EmailCardProps) : React.ReactNode {
const { t } = useTranslation();
const navigate = useNavigationDebounce();
const dbContext = useDb();
- const [associatedItem, setAssociatedItem] = useState<Item | null>(null);
+ const [associatedItem, setAssociatedItem] = useState<DisplayItem | null>(null);
/**
* Load the associated item for this email.
diff --git a/apps/mobile-app/components/items/ItemCard.tsx b/apps/mobile-app/components/items/ItemCard.tsx
index ee9abbfc6..6aac271e8 100644
--- a/apps/mobile-app/components/items/ItemCard.tsx
+++ b/apps/mobile-app/components/items/ItemCard.tsx
@@ -16,11 +16,11 @@ import { generateTotpCode } from '@/utils/TotpUtility';
import { useColors } from '@/hooks/useColorScheme';
import { useNavigationDebounce } from '@/hooks/useNavigationDebounce';
import { copyToClipboardWithExpiration } from '@/utils/ClipboardUtility';
-import type { Item } from '@aliasvault/models/vault';
+import type { DisplayItem } from '@/utils/DisplayItem';
import { getFieldValue, FieldKey } from '@aliasvault/models/vault';
type ItemCardProps = {
- item: Item;
+ item: DisplayItem;
onItemDelete?: (itemId: string) => Promise<void>;
onItemDuplicate?: (itemId: string) => Promise<void>;
showFolderPath?: boolean;
@@ -41,7 +41,7 @@ export function ItemCard({ item, onItemDelete, onItemDuplicate, showFolderPath =
* Get the display text for an item, showing username by default,
* falling back to email only if username is null/undefined/empty
*/
- const getItemDisplayText = (itm: Item): string => {
+ const getItemDisplayText = (itm: DisplayItem): string => {
// Show username if available
const username = getFieldValue(itm, FieldKey.LoginUsername);
if (username) {
@@ -62,7 +62,7 @@ export function ItemCard({ item, onItemDelete, onItemDuplicate, showFolderPath =
/**
* Get the item name, trimming it to maximum length so it doesn't overflow the UI.
*/
- const getItemName = (itm: Item): string => {
+ const getItemName = (itm: DisplayItem): string => {
const returnValue = itm.Name || t('items.untitled');
// Trim the return value to max. 33 characters.
diff --git a/apps/mobile-app/components/items/ItemIcon.tsx b/apps/mobile-app/components/items/ItemIcon.tsx
index 7007f8da1..bec4d716c 100644
--- a/apps/mobile-app/components/items/ItemIcon.tsx
+++ b/apps/mobile-app/components/items/ItemIcon.tsx
@@ -1,15 +1,16 @@
import { Buffer } from 'buffer';
+import { useMemo } from 'react';
import { Image, ImageStyle, StyleSheet, View } from 'react-native';
import { SvgXml } from 'react-native-svg';
-import type { Item } from '@aliasvault/models/vault';
import {
ItemTypes,
FieldKey,
} from '@aliasvault/models/vault';
import servicePlaceholder from '@/assets/images/service-placeholder.webp';
+import type { DisplayItem } from '@/utils/DisplayItem';
// Import centralized icon components (auto-generated from core/models/src/icons/ItemTypeIcons.ts)
import {
@@ -20,13 +21,15 @@ import {
} from './ItemTypeIconComponents';
/**
- * Item icon props - supports both legacy logo-only mode and new item-based mode.
+ * The start of an SVG logo's data URI.
+ */
+const SVG_DATA_URI_PREFIX = 'data:image/svg+xml;base64,';
+
+/**
+ * Item icon props.
*/
type ItemIconProps = {
- /** Legacy: Logo bytes for Login/Alias items */
- logo?: Uint8Array | number[] | string | null;
- /** New: Full item object for type-aware icon rendering */
- item?: Item;
+ item: DisplayItem;
style?: ImageStyle;
};
@@ -55,59 +58,42 @@ const getCardIconComponent = (cardNumber: string | undefined) => {
};
/**
- * Item icon component - supports both item-based and legacy logo-based rendering.
+ * Item icon component: a type icon for notes and cards, the item's logo otherwise.
*/
-export function ItemIcon({ logo, item, style }: ItemIconProps) : React.ReactNode {
+export function ItemIcon({ item, style }: ItemIconProps) : React.ReactNode {
const width = Number(style?.width ?? styles.logo.width);
const height = Number(style?.height ?? styles.logo.height);
- // New item-based rendering mode
- if (item) {
- // For Note type, always show note icon
- if (item.ItemType === ItemTypes.Note) {
- return (
- <View style={[styles.iconContainer, style]}>
- <NoteIcon width={width} height={height} />
- </View>
- );
- }
-
- // For CreditCard type, detect card brand and show appropriate icon
- if (item.ItemType === ItemTypes.CreditCard) {
- const cardNumberField = item.Fields?.find(f => f.FieldKey === FieldKey.CardNumber);
- const cardNumber = cardNumberField?.Value
- ? (Array.isArray(cardNumberField.Value) ? cardNumberField.Value[0] : cardNumberField.Value)
- : undefined;
-
- const CardIcon = getCardIconComponent(cardNumber);
+ // For Note type, always show note icon
+ if (item.ItemType === ItemTypes.Note) {
+ return (
+ <View style={[styles.iconContainer, style]}>
+ <NoteIcon width={width} height={height} />
+ </View>
+ );
+ }
- return (
- <View style={[styles.iconContainer, style]}>
- <CardIcon width={width} height={height} />
- </View>
- );
- }
+ // For CreditCard type, detect card brand and show appropriate icon
+ if (item.ItemType === ItemTypes.CreditCard) {
+ const cardNumberField = item.Fields?.find(f => f.FieldKey === FieldKey.CardNumber);
+ const cardNumber = cardNumberField?.Value
+ ? (Array.isArray(cardNumberField.Value) ? cardNumberField.Value[0] : cardNumberField.Value)
+ : undefined;
- // For Login/Alias types, use Logo if available, otherwise placeholder
- const logoData = item.Logo;
- if (logoData && logoData.length > 0) {
- return renderLogo(logoData, style);
- }
+ const CardIcon = getCardIconComponent(cardNumber);
- // Default placeholder for Login/Alias without logo
return (
<View style={[styles.iconContainer, style]}>
- <PlaceholderIcon width={width} height={height} />
+ <CardIcon width={width} height={height} />
</View>
);
}
- // Legacy logo-only rendering mode
- if (logo && (typeof logo === 'string' || logo.length > 0)) {
- return renderLogo(logo, style);
+ // For Login/Alias types, use the logo if available, otherwise placeholder
+ if (item.LogoDataUri) {
+ return <LogoImage dataUri={item.LogoDataUri} style={style} />;
}
- // Fallback to placeholder
return (
<View style={[styles.iconContainer, style]}>
<PlaceholderIcon width={width} height={height} />
@@ -116,106 +102,67 @@ export function ItemIcon({ logo, item, style }: ItemIconProps) : React.ReactNode
}
/**
- * Render logo from binary data.
+ * Render a logo from its data URI.
*/
-function renderLogo(
- logoData: Uint8Array | number[] | string,
- style?: ImageStyle
-): React.ReactNode {
- /**
- * Get the logo source. For SVGs, returns the raw XML string so SvgXml can
- * render it safely with fallback/onError support. For other formats, returns
- * a data URI for the Image component.
- */
- const getLogoSource = (data: Uint8Array | number[] | string | null | undefined) : { type: 'image' | 'svg', source: string | number } => {
- if (!data) {
- return { type: 'image', source: servicePlaceholder };
- }
-
- try {
- // If logo is already a base64 string (from iOS SQLite query result)
- if (typeof data === 'string') {
- const mimeType = detectMimeTypeFromBase64(data);
- if (mimeType === 'image/svg+xml') {
- // Decode base64 to raw SVG XML for SvgXml component
- return { type: 'svg', source: Buffer.from(data, 'base64').toString('utf-8') };
- }
- return { type: 'image', source: `data:${mimeType};base64,${data}` };
- }
-
- // Handle binary data (from Android or other sources)
- const logoBytes = toUint8Array(data);
- const mimeType = detectMimeType(logoBytes);
- if (mimeType === 'image/svg+xml') {
- // Decode bytes to raw SVG XML for SvgXml component
- return { type: 'svg', source: new TextDecoder().decode(logoBytes) };
- }
- const base64Logo = Buffer.from(logoBytes).toString('base64');
- return { type: 'image', source: `data:${mimeType};base64,${base64Logo}` };
- } catch (error) {
- console.error('Error converting logo:', error);
- return { type: 'image', source: servicePlaceholder };
- }
- };
-
- const logoSource = getLogoSource(logoData);
-
- if (logoSource.type === 'svg') {
- /*
- * Use SvgXml instead of SvgUri to render SVG logos. SvgXml accepts raw XML
- * and supports onError/fallback props, which lets us gracefully handle
- * malformed SVGs that would otherwise crash the native renderer
- * (e.g. zero-dimension SVGs triggering UIGraphicsBeginImageContext failures).
- */
- const svgWidth = Number(style?.width ?? styles.logo.width);
- const svgHeight = Number(style?.height ?? styles.logo.height);
-
- const svgXml = sanitizeSvg(logoSource.source as string, svgWidth, svgHeight);
-
- // If sanitization failed (returned null), fall back to placeholder
- if (!svgXml) {
- return (
- <Image
- source={servicePlaceholder}
- style={[styles.logo, style]}
- />
- );
+function LogoImage({ dataUri, style }: { dataUri: string; style?: ImageStyle }): React.ReactNode {
+ const svgWidth = Number(style?.width ?? styles.logo.width);
+ const svgHeight = Number(style?.height ?? styles.logo.height);
+ const isSvg = dataUri.startsWith(SVG_DATA_URI_PREFIX);
+
+ // Decode and sanitize an SVG once per logo and size, not on every render.
+ const svgXml = useMemo(() => {
+ if (!isSvg) {
+ return null;
}
+ return sanitizeSvg(Buffer.from(dataUri.slice(SVG_DATA_URI_PREFIX.length), 'base64').toString('utf-8'), svgWidth, svgHeight);
+ }, [dataUri, isSvg, svgWidth, svgHeight]);
- const fallback = (
+ if (!isSvg) {
+ return (
<Image
- source={servicePlaceholder}
+ source={{ uri: dataUri }}
style={[styles.logo, style]}
- />
- );
-
- return (
- <SvgXml
- xml={svgXml}
- width={svgWidth}
- height={svgHeight}
- onError={() => {
- console.warn('SvgXml failed to render SVG logo');
- }}
- fallback={fallback}
- style={{
- borderRadius: styles.logo.borderRadius,
- width: svgWidth,
- height: svgHeight,
- marginLeft: Number(style?.marginLeft ?? 0),
- marginRight: Number(style?.marginRight ?? 0),
- marginTop: Number(style?.marginTop ?? 0),
- marginBottom: Number(style?.marginBottom ?? 0),
- }}
+ defaultSource={servicePlaceholder}
/>
);
}
- return (
+ const fallback = (
<Image
- source={typeof logoSource.source === 'string' ? { uri: logoSource.source } : logoSource.source}
+ source={servicePlaceholder}
style={[styles.logo, style]}
- defaultSource={servicePlaceholder}
+ />
+ );
+
+ // If sanitization failed (returned null), fall back to placeholder
+ if (!svgXml) {
+ return fallback;
+ }
+
+ /*
+ * Use SvgXml instead of SvgUri to render SVG logos. SvgXml accepts raw XML
+ * and supports onError/fallback props, which lets us gracefully handle
+ * malformed SVGs that would otherwise crash the native renderer
+ * (e.g. zero-dimension SVGs triggering UIGraphicsBeginImageContext failures).
+ */
+ return (
+ <SvgXml
+ xml={svgXml}
+ width={svgWidth}
+ height={svgHeight}
+ onError={() => {
+ console.warn('SvgXml failed to render SVG logo');
+ }}
+ fallback={fallback}
+ style={{
+ borderRadius: styles.logo.borderRadius,
+ width: svgWidth,
+ height: svgHeight,
+ marginLeft: Number(style?.marginLeft ?? 0),
+ marginRight: Number(style?.marginRight ?? 0),
+ marginTop: Number(style?.marginTop ?? 0),
+ marginBottom: Number(style?.marginBottom ?? 0),
+ }}
/>
);
}
@@ -321,83 +268,6 @@ function sanitizeSvg(xml: string, targetWidth: number, targetHeight: number): st
}
}
-/**
- * Detect MIME type from base64 string by decoding first few bytes
- */
-function detectMimeTypeFromBase64(base64: string): string {
- try {
- const binaryString = atob(base64.slice(0, 8));
- const bytes = new Uint8Array(binaryString.length);
- for (let i = 0; i < binaryString.length; i++) {
- bytes[i] = binaryString.charCodeAt(i);
- }
- return detectMimeType(bytes);
- } catch (error) {
- console.warn('Error detecting mime type from base64:', error);
- return 'image/x-icon';
- }
-}
-
-/**
- * Detect MIME type from file signature (magic numbers)
- */
-function detectMimeType(bytes: Uint8Array): string {
- /**
- * Check if the file is an SVG.
- */
- const isSvg = (): boolean => {
- const header = new TextDecoder().decode(bytes.slice(0, 5)).toLowerCase();
- return header.includes('<?xml') || header.includes('<svg');
- };
-
- /**
- * Check if the file is an ICO.
- */
- const isIco = (): boolean => {
- return bytes[0] === 0x00 && bytes[1] === 0x00 && bytes[2] === 0x01 && bytes[3] === 0x00;
- };
-
- /**
- * Check if the file is a PNG.
- */
- const isPng = (): boolean => {
- return bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47;
- };
-
- if (isSvg()) {
- return 'image/svg+xml';
- }
- if (isIco()) {
- return 'image/x-icon';
- }
- if (isPng()) {
- return 'image/png';
- }
-
- return 'image/x-icon';
-}
-
-/**
- * Convert various binary data formats to Uint8Array
- */
-function toUint8Array(buffer: Uint8Array | number[] | {[key: number]: number}): Uint8Array {
- if (buffer instanceof Uint8Array) {
- return buffer;
- }
-
- if (Array.isArray(buffer)) {
- return new Uint8Array(buffer);
- }
-
- const length = Object.keys(buffer).length;
- const arr = new Uint8Array(length);
- for (let i = 0; i < length; i++) {
- arr[i] = buffer[i];
- }
-
- return arr;
-}
-
const styles = StyleSheet.create({
logo: {
borderRadius: 4,
diff --git a/apps/mobile-app/components/items/details/AttachmentSection.tsx b/apps/mobile-app/components/items/details/AttachmentSection.tsx
index 32f069bc1..47c09e13a 100644
--- a/apps/mobile-app/components/items/details/AttachmentSection.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentSection.tsx
@@ -1,6 +1,6 @@
import { MaterialIcons } from '@expo/vector-icons';
import { Directory, File, Paths } from 'expo-file-system';
-import React, { useState, useEffect, useCallback } from 'react';
+import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
@@ -23,7 +23,8 @@ type AttachmentSectionProps = {
* Attachment section component.
*/
export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): React.ReactNode => {
- const [attachments, setAttachments] = useState<Attachment[]>([]);
+ const [attachments, setAttachments] = useState<Omit<Attachment, 'Blob'>[]>([]);
+ const blobsRef = useRef(new Map<string, Attachment['Blob']>());
const colors = useColors();
const dbContext = useDb();
const { t } = useTranslation();
@@ -33,7 +34,7 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
/**
* Handle attachment action - preview or download.
*/
- const handleAttachment = async (attachment: Attachment): Promise<void> => {
+ const handleAttachment = async (attachment: Omit<Attachment, 'Blob'>): Promise<void> => {
try {
// Sanitize filename
const sanitizedFilename = attachment.Filename.replace(/[/\\]/g, '_');
@@ -48,10 +49,11 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
}
file.create();
- if (typeof attachment.Blob === 'string') {
- file.write(attachment.Blob, { encoding: 'base64' });
+ const blob = blobsRef.current.get(attachment.Id);
+ if (typeof blob === 'string') {
+ file.write(blob, { encoding: 'base64' });
} else {
- file.write((attachment.Blob ?? new Uint8Array(0)) as unknown as Uint8Array);
+ file.write((blob ?? new Uint8Array(0)) as unknown as Uint8Array);
}
await openAttachment({ filePath: file.uri, fileName: sanitizedFilename });
@@ -71,7 +73,8 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
try {
const attachmentList = await dbContext.sqliteClient.items.getAttachmentsForItem(item.Id);
- setAttachments(attachmentList);
+ blobsRef.current = new Map(attachmentList.map(attachment => [attachment.Id, attachment.Blob]));
+ setAttachments(attachmentList.map(({ Blob: _blob, ...attachment }) => attachment));
} catch (error) {
console.error('Error loading attachments:', error);
}
diff --git a/apps/mobile-app/components/items/details/AttachmentUploader.tsx b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
index a54dc9310..bc2574b56 100644
--- a/apps/mobile-app/components/items/details/AttachmentUploader.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
@@ -11,8 +11,11 @@ import { useColors } from '@/hooks/useColorScheme';
import type { Attachment } from '@aliasvault/models/vault';
type AttachmentUploaderProps = {
- attachments: Attachment[];
- onAttachmentsChange: (attachments: Attachment[]) => void;
+ /** The attachments without their bytes, which never go into the list. */
+ attachments: Omit<Attachment, 'Blob'>[];
+ onAttachmentsChange: (attachments: Omit<Attachment, 'Blob'>[]) => void;
+ /** Receives the bytes of each picked file. */
+ onAttachmentRead: (attachmentId: string, bytes: Uint8Array) => void;
}
/**
@@ -23,6 +26,7 @@ type AttachmentUploaderProps = {
export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
attachments,
onAttachmentsChange,
+ onAttachmentRead,
}) => {
const { t } = useTranslation();
const colors = useColors();
@@ -63,12 +67,12 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
sourceFile = tempFile;
}
- const byteArray = await sourceFile.bytes();
+ const attachmentId = crypto.randomUUID();
+ onAttachmentRead(attachmentId, await sourceFile.bytes());
- const attachment: Attachment = {
- Id: crypto.randomUUID(),
+ const attachment: Omit<Attachment, 'Blob'> = {
+ Id: attachmentId,
Filename: file.name,
- Blob: byteArray,
ItemId: '', // Will be set when saving item
CreatedAt: new Date().toISOString(),
UpdatedAt: new Date().toISOString(),
@@ -106,7 +110,7 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
* Deletes an attachment immediately from the list (pending save).
* The actual database deletion happens when the parent item is saved.
*/
- const deleteAttachment = (attachmentToDelete: Attachment): void => {
+ const deleteAttachment = (attachmentToDelete: Omit<Attachment, 'Blob'>): void => {
const updatedAttachments = attachments.filter(a => a.Id !== attachmentToDelete.Id);
onAttachmentsChange(updatedAttachments);
};
diff --git a/apps/mobile-app/hooks/useItemSort.ts b/apps/mobile-app/hooks/useItemSort.ts
index ef14bd860..d77b4b8ec 100644
--- a/apps/mobile-app/hooks/useItemSort.ts
+++ b/apps/mobile-app/hooks/useItemSort.ts
@@ -101,7 +101,7 @@ export function useItemSort(initialSortOrder: CredentialSortOrder = 'NewestFirst
* @param sortOrder - The sort order to apply
* @returns Memoized sorted items array
*/
-export function useSortedItems(filteredItems: Item[], sortOrder: CredentialSortOrder): Item[] {
+export function useSortedItems<T extends Item>(filteredItems: T[], sortOrder: CredentialSortOrder): T[] {
return useMemo(() => {
const itemsCopy = [...filteredItems];
switch (sortOrder) {
diff --git a/apps/mobile-app/utils/DisplayItem.ts b/apps/mobile-app/utils/DisplayItem.ts
new file mode 100644
index 000000000..a3e642608
--- /dev/null
+++ b/apps/mobile-app/utils/DisplayItem.ts
@@ -0,0 +1,117 @@
+import { Buffer } from 'buffer';
+
+import type { AsyncRepository } from '@aliasvault/client/database/DbOp';
+import type { ItemWithArchivedAt, ItemWithDeletedAt } from '@aliasvault/client/database/mappers/ItemMapper';
+import type { ItemRepository } from '@aliasvault/client/database/repositories/ItemRepository';
+import type { Item } from '@aliasvault/models/vault';
+
+/*
+ * Screens keep items in React state and pass them down as props, so an item must not carry its logo as a byte array:
+ * React's dev tooling walks a typed array entry by entry, and every copy of the item copies the bytes. The logo
+ * travels as a data URI instead, one immutable string that an Image source takes as is. This way we avoid issue
+ * with React's dev tooling causing a major slowdown (even though release builds are unaffected).
+ */
+
+/**
+ * An item as the screens hold it: its logo as a data URI instead of image bytes.
+ */
+export type DisplayItem<T extends Item = Item> = Omit<T, 'Logo'> & {
+ /** The logo as a data URI, absent when the item has no logo image. */
+ LogoDataUri?: string;
+};
+
+/**
+ * The item repository reads that return items.
+ */
+type ItemReads = 'getAll' | 'getById' | 'getArchived' | 'getRecentlyDeleted';
+
+/**
+ * The item repository as the app uses it: every item read returns display items.
+ */
+export type DisplayItemRepository = Omit<AsyncRepository<ItemRepository>, ItemReads> & {
+ getAll(): Promise<DisplayItem[]>;
+ getById(itemId: string, manifestId?: string): Promise<DisplayItem | null>;
+ getArchived(): Promise<DisplayItem<ItemWithArchivedAt>[]>;
+ getRecentlyDeleted(): Promise<DisplayItem<ItemWithDeletedAt>[]>;
+};
+
+/**
+ * Wrap the item repository so that no item read hands logo bytes to a screen.
+ */
+export function withDisplayItems(repository: AsyncRepository<ItemRepository>): DisplayItemRepository {
+ const reads: Pick<DisplayItemRepository, ItemReads> = {
+ getAll: async () => toDisplayItems(await repository.getAll()),
+ getById: async (itemId, manifestId) => {
+ const item = await repository.getById(itemId, manifestId);
+ return item ? toDisplayItems([item])[0] : null;
+ },
+ getArchived: async () => toDisplayItems(await repository.getArchived()),
+ getRecentlyDeleted: async () => toDisplayItems(await repository.getRecentlyDeleted()),
+ };
+
+ return new Proxy(repository, {
+ /**
+ * Resolve a member, substituting the item reads.
+ */
+ get: (target, property): unknown => Object.prototype.hasOwnProperty.call(reads, property) ? reads[property as ItemReads] : Reflect.get(target, property),
+ }) as unknown as DisplayItemRepository;
+}
+
+/**
+ * Replace each item's logo bytes with a data URI.
+ */
+export function toDisplayItems<T extends Item>(items: T[]): DisplayItem<T>[] {
+ // Keyed by logo row, so items that share a logo share one string.
+ const dataUris = new Map<string, string | undefined>();
+
+ /**
+ * The data URI of an item's logo, encoded once per logo row.
+ */
+ const dataUriOf = (item: T): string | undefined => {
+ if (!item.Logo || item.Logo.length === 0) {
+ return undefined;
+ }
+ if (!item.LogoInfo) {
+ return toDataUri(item.Logo);
+ }
+ const key = `${item.ManifestId}/${item.LogoInfo.Id}`;
+ if (!dataUris.has(key)) {
+ dataUris.set(key, toDataUri(item.Logo));
+ }
+ return dataUris.get(key);
+ };
+
+ return items.map((item) => {
+ const { Logo: _logo, ...rest } = item;
+ const logoDataUri = dataUriOf(item);
+ return logoDataUri ? { ...rest, LogoDataUri: logoDataUri } : rest;
+ });
+}
+
+/**
+ * Encode logo bytes as a data URI, or undefined when they cannot be encoded.
+ */
+function toDataUri(logo: Uint8Array | number[]): string | undefined {
+ try {
+ const bytes = logo instanceof Uint8Array ? logo : Uint8Array.from(logo);
+ return `data:${detectMimeType(bytes)};base64,${Buffer.from(bytes).toString('base64')}`;
+ } catch (error) {
+ // A broken logo shows the placeholder; it must not fail the whole item read.
+ console.error('Error converting logo:', error);
+ return undefined;
+ }
+}
+
+/**
+ * Detect an image's MIME type from its file signature, defaulting to an icon.
+ */
+function detectMimeType(bytes: Uint8Array): string {
+ const header = String.fromCharCode(...bytes.subarray(0, 5)).toLowerCase();
+ if (header.includes('<?xml') || header.includes('<svg')) {
+ return 'image/svg+xml';
+ }
+ if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
+ return 'image/png';
+ }
+ return 'image/x-icon';
+}
diff --git a/apps/mobile-app/utils/SqliteClient.ts b/apps/mobile-app/utils/SqliteClient.ts
index e58ef9869..46ea873de 100644
--- a/apps/mobile-app/utils/SqliteClient.ts
+++ b/apps/mobile-app/utils/SqliteClient.ts
@@ -12,6 +12,7 @@ import { VaultVersionIncompatibleError } from '@aliasvault/client/api/errors/Vau
import NativeVaultManager from '@/specs/NativeVaultManager';
import { NativeDatabaseClient } from '@/platform/NativeDatabaseClient';
+import { withDisplayItems } from '@/utils/DisplayItem';
/**
* The vault as the app reads and writes it: the client core's repositories over the native vault store, plus the
@@ -29,9 +30,9 @@ class SqliteClient {
private readonly logoRepository = new LogoRepository(this.database);
/**
- * Repository for Item CRUD operations.
+ * Repository for Item CRUD operations. Item reads return display items, which carry no logo bytes.
*/
- public readonly items = asyncRepository(new ItemRepository(this.database, this.logoRepository), this.database);
+ public readonly items = withDisplayItems(asyncRepository(new ItemRepository(this.database, this.logoRepository), this.database));
/**
* Repository for Folder operations.