Skip to content

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

Fix attachment download in browser extension and mobile app (#902)

Leendert de Borstd9942844e28c
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/EmailDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/EmailDetails.tsx
index 1f27fbbd3..1f57b4a27 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/EmailDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/EmailDetails.tsx
@@ -125,7 +125,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
const handleDownloadAttachment = async (attachment: EmailAttachment): Promise<void> => {
try {
// Get the encrypted attachment bytes from the API
- const base64EncryptedAttachment = await webApi.downloadBlobAndConvertToBase64(`Email/${id}/attachments/${attachment.id}`);
+ const encryptedBytes = await webApi.downloadBlob(`Email/${id}/attachments/${attachment.id}`);
if (!dbContext?.sqliteClient || !email) {
setError('Database context or email not available');
@@ -135,16 +135,18 @@ const EmailDetails: React.FC = (): React.ReactElement => {
// Get encryption keys for decryption
const encryptionKeys = dbContext.sqliteClient.getAllEncryptionKeys();
- // Decrypt the attachment using ArrayBuffer
- const decryptedBytes = await EncryptionUtility.decryptAttachment(base64EncryptedAttachment, email, encryptionKeys);
+ // Decrypt the attachment using raw bytes
+ const decryptedBytes = await EncryptionUtility.decryptAttachment(encryptedBytes, email, encryptionKeys);
if (!decryptedBytes) {
setError('Failed to decrypt attachment');
return;
}
- // Create blob from decrypted bytes with proper MIME type
- const blob = new Blob([decryptedBytes], { type: attachment.mimeType ?? 'application/octet-stream' });
+ // Create Blob directly from Uint8Array
+ const blob = new Blob([new Uint8Array(decryptedBytes)], {
+ type: attachment.mimeType ?? 'application/octet-stream'
+ });
// Create download link and trigger download
const url = window.URL.createObjectURL(blob);
diff --git a/apps/browser-extension/src/utils/EncryptionUtility.ts b/apps/browser-extension/src/utils/EncryptionUtility.ts
index 7ad9136c0..30f6dea44 100644
--- a/apps/browser-extension/src/utils/EncryptionUtility.ts
+++ b/apps/browser-extension/src/utils/EncryptionUtility.ts
@@ -119,6 +119,37 @@ export class EncryptionUtility {
return decoder.decode(decrypted);
}
+ /**
+ * Decrypts data using AES-GCM symmetric encryption with raw bytes input/output
+ */
+ public static async symmetricDecryptBytes(encryptedBytes: Uint8Array, base64Key: string): Promise<Uint8Array> {
+ if (!encryptedBytes || encryptedBytes.length === 0) {
+ return encryptedBytes;
+ }
+
+ const key = await crypto.subtle.importKey(
+ "raw",
+ Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),
+ {
+ name: "AES-GCM",
+ length: 256,
+ },
+ false,
+ ["decrypt"]
+ );
+
+ const iv = encryptedBytes.slice(0, 12);
+ const ciphertext = encryptedBytes.slice(12);
+
+ const decrypted = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv },
+ key,
+ ciphertext
+ );
+
+ return new Uint8Array(decrypted);
+ }
+
/**
* Generates a new RSA key pair for asymmetric encryption
*/
@@ -293,9 +324,13 @@ export class EncryptionUtility {
}
/**
- * Decrypts an attachment based on the provided public/private key pairs and returns the decrypted bytes as a base64 string.
+ * Decrypts an attachment and returns the decrypted content as Uint8Array (raw bytes).
*/
- public static async decryptAttachment(base64EncryptedAttachment: string, email: Email, encryptionKeys: EncryptionKey[]): Promise<string> {
+ public static async decryptAttachment(
+ encryptedBytes: Uint8Array,
+ email: Email,
+ encryptionKeys: EncryptionKey[]
+ ): Promise<Uint8Array> {
try {
const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);
@@ -303,15 +338,17 @@ export class EncryptionUtility {
throw new Error('Encryption key not found');
}
- // Decrypt symmetric key with asymmetric private key
+ // Decrypt the symmetric key using private key (returns raw bytes)
const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
email.encryptedSymmetricKey,
encryptionKey.PrivateKey
);
+
+ // Convert symmetric key to base64 string if symmetricDecrypt expects it
const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
- const encryptedBytesString = await EncryptionUtility.symmetricDecrypt(base64EncryptedAttachment, symmetricKeyBase64);
- return encryptedBytesString;
+ // Decrypt the attachment using raw bytes
+ return await EncryptionUtility.symmetricDecryptBytes(encryptedBytes, symmetricKeyBase64);
} catch (err) {
throw new Error(err instanceof Error ? err.message : 'Failed to decrypt attachment');
}
diff --git a/apps/browser-extension/src/utils/WebApiService.ts b/apps/browser-extension/src/utils/WebApiService.ts
index 95b191336..4099a917c 100644
--- a/apps/browser-extension/src/utils/WebApiService.ts
+++ b/apps/browser-extension/src/utils/WebApiService.ts
@@ -164,9 +164,9 @@ export class WebApiService {
}
/**
- * Issue GET request to the API expecting a file download and return it as a Base64 string.
+ * Issue GET request to the API expecting a file download and return it as raw bytes.
*/
- public async downloadBlobAndConvertToBase64(endpoint: string): Promise<string> {
+ public async downloadBlob(endpoint: string): Promise<Uint8Array> {
try {
const response = await this.authFetch<Response>(endpoint, {
method: 'GET',
@@ -175,11 +175,11 @@ export class WebApiService {
}
}, false);
- // Ensure we get the response as a blob
- const blob = await response.blob();
- return await this.blobToBase64(blob);
+ // Get the response as an ArrayBuffer
+ const arrayBuffer = await response.arrayBuffer();
+ return new Uint8Array(arrayBuffer);
} catch (error) {
- console.error('Error fetching and converting to Base64:', error);
+ console.error('Error downloading blob:', error);
throw error;
}
}
diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsx
index 851b1eeab..cd8aba63f 100644
--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx
@@ -5,10 +5,10 @@ import React, { useEffect, useState, useCallback } from 'react';
import { StyleSheet, View, TouchableOpacity, ActivityIndicator, Alert, Share, useColorScheme, TextInput, Linking } from 'react-native';
import { WebView } from 'react-native-webview';
+import type { Credential } from '@/utils/dist/shared/models/vault';
import type { Email } from '@/utils/dist/shared/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
import emitter from '@/utils/EventEmitter';
-import type { Credential } from '@/utils/types/Credential';
import { useColors } from '@/hooks/useColorScheme';
@@ -122,7 +122,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
*/
const handleDownloadAttachment = async (attachment: Email['attachments'][0]) : Promise<void> => {
try {
- const base64EncryptedAttachment = await webApi.downloadBlobAndConvertToBase64(
+ const encryptedBytes = await webApi.downloadBlob(
`Email/${id}/attachments/${attachment.id}`
);
@@ -133,7 +133,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
const encryptionKeys = await dbContext.sqliteClient.getAllEncryptionKeys();
const decryptedBytes = await EncryptionUtility.decryptAttachment(
- base64EncryptedAttachment,
+ encryptedBytes,
email,
encryptionKeys
);
@@ -143,8 +143,10 @@ export default function EmailDetailsScreen() : React.ReactNode {
return;
}
+ // Convert decrypted bytes to base64 for FileSystem.writeAsStringAsync
+ const base64Data = Buffer.from(decryptedBytes).toString('base64');
const tempFile = `${FileSystem.cacheDirectory}${attachment.filename}`;
- await FileSystem.writeAsStringAsync(tempFile, decryptedBytes, {
+ await FileSystem.writeAsStringAsync(tempFile, base64Data, {
encoding: FileSystem.EncodingType.Base64,
});
@@ -187,6 +189,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
borderTopColor: colors.accentBorder,
borderTopWidth: 1,
padding: 16,
+ paddingBottom: 100,
},
attachmentsTitle: {
color: colors.text,
diff --git a/apps/mobile-app/utils/EncryptionUtility.tsx b/apps/mobile-app/utils/EncryptionUtility.tsx
index d1cd84b16..ae53dd8ee 100644
--- a/apps/mobile-app/utils/EncryptionUtility.tsx
+++ b/apps/mobile-app/utils/EncryptionUtility.tsx
@@ -107,6 +107,37 @@ class EncryptionUtility {
}
}
+ /**
+ * Decrypts data using AES-GCM symmetric encryption with raw bytes input/output
+ */
+ public static async symmetricDecryptBytes(encryptedBytes: Uint8Array, base64Key: string): Promise<Uint8Array> {
+ if (!encryptedBytes || encryptedBytes.length === 0) {
+ return encryptedBytes;
+ }
+
+ const key = await crypto.subtle.importKey(
+ "raw",
+ Uint8Array.from(atob(base64Key), c => c.charCodeAt(0)),
+ {
+ name: "AES-GCM",
+ length: 256,
+ },
+ false,
+ ["decrypt"]
+ );
+
+ const iv = encryptedBytes.slice(0, 12);
+ const ciphertext = encryptedBytes.slice(12);
+
+ const decrypted = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv },
+ key,
+ ciphertext
+ );
+
+ return new Uint8Array(decrypted);
+ }
+
/**
* Generates a new RSA key pair for asymmetric encryption
*/
@@ -281,9 +312,13 @@ class EncryptionUtility {
}
/**
- * Decrypts an attachment based on the provided public/private key pairs and returns the decrypted bytes as a base64 string.
+ * Decrypts an attachment and returns the decrypted content as Uint8Array (raw bytes).
*/
- public static async decryptAttachment(base64EncryptedAttachment: string, email: Email, encryptionKeys: EncryptionKey[]): Promise<string> {
+ public static async decryptAttachment(
+ encryptedBytes: Uint8Array,
+ email: Email,
+ encryptionKeys: EncryptionKey[]
+ ): Promise<Uint8Array> {
try {
const encryptionKey = encryptionKeys.find(key => key.PublicKey === email.encryptionKey);
@@ -291,15 +326,17 @@ class EncryptionUtility {
throw new Error('Encryption key not found');
}
- // Decrypt symmetric key with asymmetric private key
+ // Decrypt the symmetric key using private key (returns raw bytes)
const symmetricKey = await EncryptionUtility.decryptWithPrivateKey(
email.encryptedSymmetricKey,
encryptionKey.PrivateKey
);
+
+ // Convert symmetric key to base64 string if symmetricDecrypt expects it
const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');
- const encryptedBytesString = await EncryptionUtility.symmetricDecrypt(base64EncryptedAttachment, symmetricKeyBase64);
- return encryptedBytesString;
+ // Decrypt the attachment using raw bytes
+ return await EncryptionUtility.symmetricDecryptBytes(encryptedBytes, symmetricKeyBase64);
} catch (err) {
throw new Error(err instanceof Error ? err.message : 'Failed to decrypt attachment');
}
diff --git a/apps/mobile-app/utils/WebApiService.ts b/apps/mobile-app/utils/WebApiService.ts
index 25ef6b8c6..e260a7de7 100644
--- a/apps/mobile-app/utils/WebApiService.ts
+++ b/apps/mobile-app/utils/WebApiService.ts
@@ -163,9 +163,9 @@ export class WebApiService {
}
/**
- * Issue GET request to the API expecting a file download and return it as a Base64 string.
+ * Issue GET request to the API expecting a file download and return it as raw bytes.
*/
- public async downloadBlobAndConvertToBase64(endpoint: string): Promise<string> {
+ public async downloadBlob(endpoint: string): Promise<Uint8Array> {
try {
const response = await this.authFetch<Response>(endpoint, {
method: 'GET',
@@ -174,11 +174,11 @@ export class WebApiService {
}
}, false);
- // Ensure we get the response as a blob
- const blob = await response.blob();
- return await this.blobToBase64(blob);
+ // Get the response as an ArrayBuffer
+ const arrayBuffer = await response.arrayBuffer();
+ return new Uint8Array(arrayBuffer);
} catch (error) {
- console.error('Error fetching and converting to Base64:', error);
+ console.error('Error downloading blob:', error);
throw error;
}
}