Skip to content

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

Add attachment filename sanitize on mobile (#2159)

Leendert de Borstb5c0d954837d
diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsx
index 7152aabbe..34b88a603 100644
--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx
@@ -2,7 +2,7 @@ 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 { Paths } from 'expo-file-system';
import { useLocalSearchParams, useRouter, useNavigation, Stack } from 'expo-router';
import React, { useEffect, useMemo, useRef, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,6 +14,7 @@ import ConversionUtility from '@/utils/ConversionUtility';
import type { DisplayItem } from '@/utils/DisplayItem';
import EncryptionUtility, { type DecryptedEmail } from '@/utils/EncryptionUtility';
import emitter from '@/utils/EventEmitter';
+import { getFileForFilename } from '@/utils/FileUtility';
import { useAttachmentViewer } from '@/hooks/useAttachmentViewer';
import { useColors } from '@/hooks/useColorScheme';
@@ -192,7 +193,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
const decryptedBytes = await extractEmailAttachment(sourceBytes, index, detachedBody);
- const tempFile = new File(Paths.cache, attachment.filename);
+ const tempFile = getFileForFilename(Paths.cache, attachment.filename);
if (tempFile.exists) {
tempFile.delete();
}
diff --git a/apps/mobile-app/components/items/details/AttachmentSection.tsx b/apps/mobile-app/components/items/details/AttachmentSection.tsx
index 47c09e13a..7667d80a8 100644
--- a/apps/mobile-app/components/items/details/AttachmentSection.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentSection.tsx
@@ -1,11 +1,12 @@
import { MaterialIcons } from '@expo/vector-icons';
-import { Directory, File, Paths } from 'expo-file-system';
+import { Directory, Paths } from 'expo-file-system';
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity } from 'react-native';
import type { Item, Attachment } from '@aliasvault/models/vault';
import emitter from '@/utils/EventEmitter';
+import { getFileForFilename } from '@/utils/FileUtility';
import { useAttachmentViewer } from '@/hooks/useAttachmentViewer';
import { useColors } from '@/hooks/useColorScheme';
@@ -36,14 +37,12 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
*/
const handleAttachment = async (attachment: Omit<Attachment, 'Blob'>): Promise<void> => {
try {
- // Sanitize filename
- const sanitizedFilename = attachment.Filename.replace(/[/\\]/g, '_');
const downloadsDir = new Directory(Paths.document, 'Downloads');
if (!downloadsDir.exists) {
downloadsDir.create({ intermediates: true });
}
- const file = new File(downloadsDir, sanitizedFilename);
+ const file = getFileForFilename(downloadsDir, attachment.Filename);
if (file.exists) {
file.delete();
}
@@ -56,7 +55,7 @@ export const AttachmentSection: React.FC<AttachmentSectionProps> = ({ item }): R
file.write((blob ?? new Uint8Array(0)) as unknown as Uint8Array);
}
- await openAttachment({ filePath: file.uri, fileName: sanitizedFilename });
+ await openAttachment({ filePath: file.uri, fileName: attachment.Filename });
} catch (error) {
console.error('Error handling attachment:', error);
showAlert('Error', 'Failed to process attachment');
diff --git a/apps/mobile-app/components/items/details/AttachmentUploader.tsx b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
index bc2574b56..c4947329a 100644
--- a/apps/mobile-app/components/items/details/AttachmentUploader.tsx
+++ b/apps/mobile-app/components/items/details/AttachmentUploader.tsx
@@ -8,6 +8,7 @@ import { View, StyleSheet, TouchableOpacity } from 'react-native';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { useColors } from '@/hooks/useColorScheme';
+import { getFileForFilename } from '@/utils/FileUtility';
import type { Attachment } from '@aliasvault/models/vault';
type AttachmentUploaderProps = {
@@ -59,7 +60,7 @@ export const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
* try to copy it to a readable location
*/
if (file.uri.startsWith('content://')) {
- tempFile = new File(Paths.cache, file.name);
+ tempFile = getFileForFilename(Paths.cache, file.name);
if (tempFile.exists) {
tempFile.delete();
}
diff --git a/apps/mobile-app/utils/FileUtility.ts b/apps/mobile-app/utils/FileUtility.ts
new file mode 100644
index 000000000..014f18c07
--- /dev/null
+++ b/apps/mobile-app/utils/FileUtility.ts
@@ -0,0 +1,36 @@
+import { Directory, File } from 'expo-file-system';
+
+/*
+ * Sanitize filenames for attachments so they are accepted by mobile OS filesystems.
+ * E.g. Android turns the URI into a java.net.URI, which rejects characters that are legal
+ * on disk but not in a URI path (square brackets, braces, pipes, quotes).
+ */
+
+const FALLBACK_FILENAME = 'attachment';
+
+/**
+ * Checks whether a character can stay in a single path segment.
+ */
+const isSafeFilenameChar = (char: string): boolean => {
+ const code = char.charCodeAt(0);
+ return code > 31 && code !== 127 && char !== '/' && char !== '\\';
+};
+
+/**
+ * Reduces an untrusted filename to a single path segment.
+ */
+const sanitizeFilename = (filename: string): string => {
+ const sanitized = Array.from(filename).map((char: string): string => isSafeFilenameChar(char) ? char : '_').join('').trim();
+ return sanitized.length > 0 && !/^\.+$/.test(sanitized) ? sanitized : FALLBACK_FILENAME;
+};
+
+/**
+ * Creates a file reference for an untrusted filename inside a directory, without creating it on disk.
+ * @param directory The directory to place the file in.
+ * @param filename The filename as provided by the attachment or the file picker.
+ * @returns The file reference.
+ */
+export const getFileForFilename = (directory: Directory, filename: string): File => {
+ const directoryUri = directory.uri.endsWith('/') ? directory.uri : `${directory.uri}/`;
+ return new File(`${directoryUri}${encodeURIComponent(sanitizeFilename(filename))}`);
+};