Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add email attachment download (#541)
Leendert de Borstcba4a6d3ecb5
diff --git a/browser-extensions/chrome/src/app/pages/EmailDetails.tsx b/browser-extensions/chrome/src/app/pages/EmailDetails.tsxindex cf394e1b6..11aeed8c7 100644--- a/browser-extensions/chrome/src/app/pages/EmailDetails.tsx+++ b/browser-extensions/chrome/src/app/pages/EmailDetails.tsx@@ -6,7 +6,7 @@ import { useWebApi } from '../context/WebApiContext';import LoadingSpinner from '../components/LoadingSpinner';import { useMinDurationLoading } from '../hooks/useMinDurationLoading';import EncryptionUtility from '../../shared/EncryptionUtility';-+import { Attachment } from '../../shared/types/webapi/Attachment';/*** Email details page.*/@@ -94,6 +94,50 @@ const EmailDetails: React.FC = () => {window.close();};+ /**+ * Handle downloading an attachment.+ */+ const handleDownloadAttachment = async (attachment: Attachment): Promise<void> => {+ try {+ // Get the encrypted attachment bytes from the API+ const base64EncryptedAttachment = await webApi.downloadBlobAndConvertToBase64(`Email/${id}/attachments/${attachment.id}`);++ if (!dbContext?.sqliteClient) {+ setError('Database context not available');+ return;+ }++ // Get encryption keys for decryption+ const encryptionKeys = dbContext.sqliteClient.getAllEncryptionKeys();++ // Decrypt the attachment using ArrayBuffer+ const decryptedBytes = await EncryptionUtility.decryptAttachment(base64EncryptedAttachment, 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.contentType || 'application/octet-stream' });++ // Create download link and trigger download+ const url = window.URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = attachment.filename;+ document.body.appendChild(a);+ a.click();++ // Cleanup+ window.URL.revokeObjectURL(url);+ document.body.removeChild(a);+ } catch (err) {+ console.error('handleDownloadAttachment error', err);+ setError(err instanceof Error ? err.message : 'Failed to download attachment');+ }+ };+if (isLoading) {return (<div className="flex justify-center items-center p-8">@@ -192,7 +236,8 @@ const EmailDetails: React.FC = () => {{email.attachments.map((attachment) => (<divkey={attachment.id}- className="flex items-center space-x-2 text-sm text-gray-600 dark:text-gray-400"+ onClick={() => handleDownloadAttachment(attachment)}+ className="flex items-center space-x-2 text-sm text-gray-600 dark:text-gray-400 cursor-pointer hover:text-primary-600 dark:hover:text-primary-400"><svgclassName="w-4 h-4"diff --git a/browser-extensions/chrome/src/shared/EncryptionUtility.tsx b/browser-extensions/chrome/src/shared/EncryptionUtility.tsxindex 30fb9054a..3c137ada7 100644--- a/browser-extensions/chrome/src/shared/EncryptionUtility.tsx+++ b/browser-extensions/chrome/src/shared/EncryptionUtility.tsx@@ -282,6 +282,31 @@ class EncryptionUtility {}}));}++ /**+ * Decrypts an attachment based on the provided public/private key pairs and returns the decrypted bytes as a base64 string.+ */+ public static async decryptAttachment(base64EncryptedAttachment: string, email: Email, encryptionKeys: EncryptionKey[]): Promise<string> {+ 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 symmetricKey = await EncryptionUtility.decryptWithPrivateKey(+ email.encryptedSymmetricKey,+ encryptionKey.PrivateKey+ );+ const symmetricKeyBase64 = Buffer.from(symmetricKey).toString('base64');++ const encryptedBytesString = await EncryptionUtility.symmetricDecrypt(base64EncryptedAttachment, symmetricKeyBase64);+ return encryptedBytesString;+ } catch (err) {+ throw new Error(err instanceof Error ? err.message : 'Failed to decrypt attachment');+ }+ }}export default EncryptionUtility;diff --git a/browser-extensions/chrome/src/shared/WebApiService.ts b/browser-extensions/chrome/src/shared/WebApiService.tsindex c3d6e03ab..e071e36b5 100644--- a/browser-extensions/chrome/src/shared/WebApiService.ts+++ b/browser-extensions/chrome/src/shared/WebApiService.ts@@ -77,7 +77,7 @@ export class WebApiService {throw new Error('Request failed after token refresh');}- return parseJson ? retryResponse.json() : retryResponse.text() as T;+ return parseJson ? retryResponse.json() : retryResponse as unknown as T;} else {this.handleLogout();throw new Error('Session expired');@@ -88,7 +88,7 @@ export class WebApiService {throw new Error(`HTTP error! status: ${response.status}`);}- return parseJson ? response.json() : response.text() as T;+ return parseJson ? response.json() : response as unknown as T;} catch (error) {console.error('API request failed:', error);throw error;@@ -138,6 +138,27 @@ export class WebApiService {return this.fetch<T>(endpoint, { method: 'GET' });}+ /**+ * Issue GET request to the API expecting a file download and return it as a Base64 string.+ */+ public async downloadBlobAndConvertToBase64(endpoint: string): Promise<string> {+ try {+ const response = await this.fetch<Response>(endpoint, {+ method: 'GET',+ headers: {+ 'Accept': 'application/octet-stream'+ }+ }, false);++ // Ensure we get the response as a blob+ const blob = await response.blob();+ return await this.blobToBase64(blob);+ } catch (error) {+ console.error('Error fetching and converting to Base64:', error);+ throw error;+ }+ }+/*** Issue POST request to the API.*/@@ -245,4 +266,31 @@ export class WebApiService {refreshToken});}++ /**+ * Convert a Blob to a Base64 string.+ */+ private async blobToBase64(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();++ /**+ * When the reader has finished loading, convert the result to a Base64 string.+ */+ reader.onloadend = () : void => {+ const result = reader.result;+ if (typeof result === 'string') {+ resolve(result.split(',')[1]); // Remove the data URL prefix+ } else {+ reject(new Error('Failed to convert Blob to Base64.'));+ }+ };++ /**+ * If the reader encounters an error, reject the promise.+ */+ reader.onerror = (error) : void => reject(error);+ reader.readAsDataURL(blob);+ });+ }}