Skip to content

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

Refactor email decryption logic

Leendert de Borst653d57015482
diff --git a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
index f44c7d8f5..e9ec848d9 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
@@ -1,6 +1,6 @@
import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';
import { type AliasOwnerNotice, aliasOwnerErrorText, aliasOwnerNotice, moveAliasHere } from '@aliasvault/client/email/AliasOwner';
+import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import { SpamOkClient } from '@aliasvault/client/email/SpamOkClient';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
@@ -171,7 +171,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email, manifestId })
if (allMails) {
// Loop through all emails and decrypt them locally
- const decryptedEmails: MailboxEmail[] = await EncryptionUtility.decryptEmailList(
+ const decryptedEmails: MailboxEmail[] = await decryptEmailList(
allMails,
data.publicKeys,
dbContext.sqliteClient!.encryptionKeys.getAll()
diff --git a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
index 2ab4ee090..7499ab762 100644
--- a/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/context/DbContext.tsx
@@ -1,7 +1,7 @@
import { AppErrorCode, formatErrorWithCode } from '@aliasvault/client/api/errors/AppErrorCodes';
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
import { decryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';
import SqliteClient from '@aliasvault/client/database/SqliteClient';
+import { clearEmailKeyCache } from '@aliasvault/client/email/EmailDecryption';
import { syncErrorMessage, toSyncErrorDetail } from '@aliasvault/client/sync/SyncErrorMessage';
import { hasUnsyncedUserChanges as hasUnsyncedUserChangesInStorage } from '@aliasvault/client/sync/VaultDirtyState';
import { vaultRequiresManifestMigration } from '@aliasvault/client/sync/VaultManifestMigration';
@@ -245,7 +245,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
// Reflect locks from other windows.
useEffect(() => {
return vaultStateEvents.onVaultLocked(() => {
- EncryptionUtility.clearRsaPrivateKeyCache();
+ clearEmailKeyCache();
setSqliteClient(null);
setDbAvailable(false);
});
@@ -395,7 +395,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Clear database and remove from background worker, called when logging out.
*/
const clearDatabase = useCallback(() : void => {
- EncryptionUtility.clearRsaPrivateKeyCache();
+ clearEmailKeyCache();
setSqliteClient(null);
setDbInitialized(false);
setDbAvailable(false);
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
index 30f173bde..1ca9492bc 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
@@ -1,5 +1,5 @@
-import EncryptionUtility, { type DecryptedEmail } from '@aliasvault/client/crypto/EncryptionUtility';
import { getEmailAttachmentBytes } from '@aliasvault/client/email/EmailAttachments';
+import { decryptEmail, type DecryptedEmail } from '@aliasvault/client/email/EmailDecryption';
import { sanitizeEmailHtml } from '@aliasvault/client/email/EmailHtmlSanitizer';
import { decodeEmailSource, type ParsedEmailAttachment } from '@aliasvault/client/rust/RustCore';
import { downloadBytes } from '@aliasvault/client/utilities/FileDownload';
@@ -89,7 +89,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
const response = await webApi.get<Email>(`Email/${id}`);
const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();
- const decryptedEmail = await EncryptionUtility.decryptEmail(response, encryptionKeys);
+ const decryptedEmail = await decryptEmail(response, encryptionKeys);
setDecrypted(decryptedEmail);
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
index db3ae6aec..c9413750c 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
@@ -1,4 +1,4 @@
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
+import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
@@ -74,7 +74,7 @@ const EmailsList: React.FC = () => {
const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();
// Decrypt emails locally using public/private key pairs.
- const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
+ const decryptedEmails = await decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
if (reset) {
setEmails(decryptedEmails);
@@ -111,7 +111,7 @@ const EmailsList: React.FC = () => {
// Decrypt emails locally
const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();
- const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
+ const decryptedEmails = await decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
// Append to existing emails
setEmails((prevEmails) => [...prevEmails, ...decryptedEmails]);
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
index 08a10fa52..31f9c6b58 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/nativevaultmanager/RustCoreDispatcher.kt
@@ -37,7 +37,6 @@ import uniffi.aliasvault_core.srpGenerateSalt
import uniffi.aliasvault_core.srpVerifySession
import uniffi.aliasvault_core.symmetricDecrypt
import uniffi.aliasvault_core.symmetricDecryptBytes
-import uniffi.aliasvault_core.symmetricEncryptBytes
import uniffi.aliasvault_core.vaultCodecCanonicalizeFromSqlite
import uniffi.aliasvault_core.vaultCodecGenerateManifestSalt
import uniffi.aliasvault_core.vaultCodecLogoContentHash
@@ -86,7 +85,6 @@ object RustCoreDispatcher {
"decodeEmailSource" -> json(decodeEmailSource(args.bytes(0)))
"extractEmailAttachment" -> json(extractEmailAttachment(args.bytes(0), args.uint(1), args.optionalBytes(2)))
"rsaDecrypt" -> json(rsaDecrypt(args.string(0), args.string(1)))
- "symmetricEncryptBytes" -> json(symmetricEncryptBytes(args.bytes(0), args.string(1)))
"symmetricDecrypt" -> json(symmetricDecrypt(args.string(0), args.string(1)))
"symmetricDecryptBytes" -> json(symmetricDecryptBytes(args.bytes(0), args.string(1)))
diff --git a/apps/mobile-app/app/(tabs)/emails/[id].tsx b/apps/mobile-app/app/(tabs)/emails/[id].tsx
index 0a6af75b3..c696735da 100644
--- a/apps/mobile-app/app/(tabs)/emails/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/emails/[id].tsx
@@ -1,6 +1,6 @@
import { Buffer } from 'buffer';
-import EncryptionUtility, { type DecryptedEmail } from '@aliasvault/client/crypto/EncryptionUtility';
+import { decryptEmail, decryptEmailAttachment, type DecryptedEmail } from '@aliasvault/client/email/EmailDecryption';
import { decodeEmailSource, extractEmailAttachment, type ParsedEmailAttachment } from '@aliasvault/client/rust/RustCore';
import { Ionicons } from '@expo/vector-icons';
import { Paths } from 'expo-file-system';
@@ -84,7 +84,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
// Decrypt email locally using public/private key pairs
const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
- const decryptedEmail = await EncryptionUtility.decryptEmail(response, encryptionKeys);
+ const decryptedEmail = await decryptEmail(response, encryptionKeys);
const { sourceBytes, ...parsedEmail } = decryptedEmail;
sourceBytesRef.current = sourceBytes;
setDecrypted({ ...parsedEmail, hasSource: sourceBytes !== null });
@@ -187,7 +187,7 @@ export default function EmailDetailsScreen() : React.ReactNode {
const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
const encryptedPart = attachment.detached ? await webApi.downloadBlob(`Email/${email.id}/parts/${attachment.partIndex}`) : null;
- const detachedBody = encryptedPart ? await EncryptionUtility.decryptAttachment(encryptedPart, email, encryptionKeys) : undefined;
+ const detachedBody = encryptedPart ? await decryptEmailAttachment(encryptedPart, email, encryptionKeys) : undefined;
const decryptedBytes = await extractEmailAttachment(sourceBytes, index, detachedBody);
const tempFile = getFileForFilename(Paths.cache, attachment.filename);
diff --git a/apps/mobile-app/app/(tabs)/emails/index.tsx b/apps/mobile-app/app/(tabs)/emails/index.tsx
index 019414ef9..88587404c 100644
--- a/apps/mobile-app/app/(tabs)/emails/index.tsx
+++ b/apps/mobile-app/app/(tabs)/emails/index.tsx
@@ -1,4 +1,4 @@
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
+import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import { useNavigation } from 'expo-router';
import React, { useEffect, useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
@@ -71,7 +71,7 @@ export default function EmailsScreen() : React.ReactNode {
const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
// Decrypt emails locally using public/private key pairs
- const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
+ const decryptedEmails = await decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
if (reset) {
setEmails(decryptedEmails);
@@ -122,7 +122,7 @@ export default function EmailsScreen() : React.ReactNode {
// Decrypt emails locally
const encryptionKeys = await dbContext.sqliteClient.encryptionKeys.getAll();
- const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
+ const decryptedEmails = await decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
// Append to existing emails
setEmails((prevEmails) => [...prevEmails, ...decryptedEmails]);
diff --git a/apps/mobile-app/components/items/details/EmailPreview.tsx b/apps/mobile-app/components/items/details/EmailPreview.tsx
index 791d9853b..818012bb2 100644
--- a/apps/mobile-app/components/items/details/EmailPreview.tsx
+++ b/apps/mobile-app/components/items/details/EmailPreview.tsx
@@ -12,7 +12,7 @@ import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { logExpected } from '@aliasvault/client/utilities/Diagnostics';
import { mailboxPollDelayMs } from '@aliasvault/client/utilities/PollBackoff';
import type { ApiErrorResponse, Mailbox, MailboxEmail } from '@aliasvault/models/webapi';
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
+import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import { useColors } from '@/hooks/useColorScheme';
@@ -204,7 +204,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email, manifestId })
if (allMails) {
// Loop through all emails and decrypt them locally
- const decryptedEmails = await EncryptionUtility.decryptEmailList(
+ const decryptedEmails = await decryptEmailList(
allMails,
data.publicKeys,
encryptionKeys
diff --git a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
index ec70ea2ae..42ce6de8a 100644
--- a/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
+++ b/apps/mobile-app/ios/NativeVaultManager/NativeVaultManager.swift
@@ -1547,7 +1547,6 @@ private enum RustCoreDispatcher {
case "extractEmailAttachment":
return try json(bytes: try RustCoreFramework.extractEmailAttachment(source: try args.data(0), index: try args.uint32(1), detachedBody: try args.optionalData(2)))
case "rsaDecrypt": return try json(bytes: try RustCoreFramework.rsaDecrypt(base64Ciphertext: try args.string(0), privateKeyJwk: try args.string(1)))
- case "symmetricEncryptBytes": return try json(bytes: try RustCoreFramework.symmetricEncryptBytes(plaintext: try args.data(0), keyBase64: try args.string(1)))
case "symmetricDecrypt": return try json(try RustCoreFramework.symmetricDecrypt(base64Ciphertext: try args.string(0), keyBase64: try args.string(1)))
case "symmetricDecryptBytes": return try json(bytes: try RustCoreFramework.symmetricDecryptBytes(encrypted: try args.data(0), keyBase64: try args.string(1)))
diff --git a/apps/mobile-app/platform/NativeRustCore.ts b/apps/mobile-app/platform/NativeRustCore.ts
index ad0fe98b5..007929303 100644
--- a/apps/mobile-app/platform/NativeRustCore.ts
+++ b/apps/mobile-app/platform/NativeRustCore.ts
@@ -67,9 +67,8 @@ export const nativeRustCore: IRustCore = {
decodeEmailSource: (source) => callForBytes('decodeEmailSource', base64(source)),
extractEmailAttachment: (source, index, detachedBody) => callForBytes('extractEmailAttachment', base64(source), index, detachedBody ? base64(detachedBody) : null),
- symmetricEncryptBytes: (plaintext, keyBase64) => callForBytes('symmetricEncryptBytes', base64(plaintext), keyBase64),
- symmetricDecryptBytes: (encrypted, keyBase64) => callForBytes('symmetricDecryptBytes', base64(encrypted), keyBase64),
symmetricDecrypt: (base64Ciphertext, keyBase64) => call('symmetricDecrypt', base64Ciphertext, keyBase64),
+ symmetricDecryptBytes: (encrypted, keyBase64) => callForBytes('symmetricDecryptBytes', base64(encrypted), keyBase64),
rsaDecrypt: (base64Ciphertext, privateKeyJwk) => callForBytes('rsaDecrypt', base64Ciphertext, privateKeyJwk),
pinGenerateSalt: () => notImplementedOnMobile('pinGenerateSalt', PIN_IS_NATIVE),
diff --git a/apps/web/src/components/email/RecentEmails.tsx b/apps/web/src/components/email/RecentEmails.tsx
index 774f78dc0..ef8873cc9 100644
--- a/apps/web/src/components/email/RecentEmails.tsx
+++ b/apps/web/src/components/email/RecentEmails.tsx
@@ -1,6 +1,6 @@
import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
import { type AliasOwnerNotice, aliasOwnerErrorText, aliasOwnerNotice, moveAliasHere } from '@aliasvault/client/email/AliasOwner';
+import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -78,7 +78,7 @@ const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress, manifestId })
} else if (isAliasVault && dbContext.sqliteClient) {
const mailbox = await webApi.get<Mailbox>(`EmailBox/${emailAddress}`);
setOwnerNotice(aliasOwnerNotice(emailAddress, mailbox, manifestId, dbContext.sqliteClient.getPersonalManifestId(), dbContext.sqliteClient.folders.getAll()));
- const decrypted = await EncryptionUtility.decryptEmailList(mailbox.mails, mailbox.publicKeys, dbContext.sqliteClient.encryptionKeys.getAll());
+ const decrypted = await decryptEmailList(mailbox.mails, mailbox.publicKeys, dbContext.sqliteClient.encryptionKeys.getAll());
setMailboxEmails(decrypted);
setError('');
}
diff --git a/apps/web/src/context/DbContext.tsx b/apps/web/src/context/DbContext.tsx
index 7d7b295eb..49abd0c8b 100644
--- a/apps/web/src/context/DbContext.tsx
+++ b/apps/web/src/context/DbContext.tsx
@@ -1,6 +1,6 @@
import { AppErrorCode } from '@aliasvault/client/api/errors/AppErrorCodes';
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
import SqliteClient from '@aliasvault/client/database/SqliteClient';
+import { clearEmailKeyCache } from '@aliasvault/client/email/EmailDecryption';
import { getPlatform } from '@aliasvault/client/platform';
import { syncErrorMessage, toSyncErrorDetail } from '@aliasvault/client/sync/SyncErrorMessage';
import React, { createContext, useContext, useState, useEffect, useCallback, useMemo, useRef } from 'react';
@@ -146,7 +146,7 @@ export const DbProvider: React.FC<{ children: React.ReactNode }> = ({ children }
* Drop the in-memory database, called when logging out or locking.
*/
const clearDatabase = useCallback((): void => {
- EncryptionUtility.clearRsaPrivateKeyCache();
+ clearEmailKeyCache();
setSqliteClient(null);
setDbInitialized(false);
setDbAvailable(false);
diff --git a/apps/web/src/pages/emails/Home.tsx b/apps/web/src/pages/emails/Home.tsx
index 62c3585d5..c86581822 100644
--- a/apps/web/src/pages/emails/Home.tsx
+++ b/apps/web/src/pages/emails/Home.tsx
@@ -1,5 +1,5 @@
import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
+import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import { getPlatform } from '@aliasvault/client/platform';
import { hasUnsyncedUserChanges } from '@aliasvault/client/sync/VaultDirtyState';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
@@ -128,7 +128,7 @@ const EmailsHome: React.FC = () => {
try {
const data = await webApi.get<InboxResponse>(`EmailBox?page=${page}&pageSize=${pageSize}`);
const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();
- const decrypted: MailboxEmail[] = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
+ const decrypted: MailboxEmail[] = await decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
const lookup = getItemLookup();
const emails = decrypted.map((email): MailListEntry => {
diff --git a/apps/web/src/utils/EmailViewModel.ts b/apps/web/src/utils/EmailViewModel.ts
index a1c96aaea..3fff86258 100644
--- a/apps/web/src/utils/EmailViewModel.ts
+++ b/apps/web/src/utils/EmailViewModel.ts
@@ -1,5 +1,5 @@
-import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
import { getEmailAttachmentBytes } from '@aliasvault/client/email/EmailAttachments';
+import { decryptEmail } from '@aliasvault/client/email/EmailDecryption';
import { SpamOkClient } from '@aliasvault/client/email/SpamOkClient';
import { decodeEmailSource } from '@aliasvault/client/rust/RustCore';
@@ -82,7 +82,7 @@ export async function loadSpamOkEmail(emailPrefix: string, emailId: number): Pro
*/
export async function loadAliasVaultEmail(webApi: WebApiService, sqliteClient: SqliteClient, emailId: number): Promise<EmailViewModel> {
const email = await webApi.get<Email>(`Email/${emailId}`);
- const decrypted = await EncryptionUtility.decryptEmail(email, sqliteClient.encryptionKeys.getAll());
+ const decrypted = await decryptEmail(email, sqliteClient.encryptionKeys.getAll());
return {
id: decrypted.email.id,
subject: decrypted.email.subject,
diff --git a/core/client/src/crypto/EncryptionUtility.crypto.test.ts b/core/client/src/crypto/EncryptionUtility.crypto.test.ts
deleted file mode 100644
index 8b49193d0..000000000
--- a/core/client/src/crypto/EncryptionUtility.crypto.test.ts
+++ /dev/null
@@ -1,371 +0,0 @@
-import { beforeEach, describe, it, expect, vi } from 'vitest';
-
-import EncryptionUtility from './EncryptionUtility';
-
-import type { EncryptionKey } from '@aliasvault/models/vault';
-import type { Email, MailboxEmail } from '@aliasvault/models/webapi';
-
-beforeEach(() => {
- EncryptionUtility.clearRsaPrivateKeyCache();
-});
-
-/**
- * RSA-OAEP encrypts a string with a JWK public key, the way the server encrypts email keys.
- */
-async function encryptWithPublicKey(plaintext: string, publicKey: string): Promise<string> {
- const key = await crypto.subtle.importKey('jwk', JSON.parse(publicKey), { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['encrypt']);
- const cipherBuffer = await crypto.subtle.encrypt({ name: 'RSA-OAEP' }, key, new TextEncoder().encode(plaintext));
- return Buffer.from(cipherBuffer).toString('base64');
-}
-
-/**
- * Creates a mailbox email with fields encrypted by the supplied RSA key pair. The decryption key references the key
- * by its position in the response-level public key table, mirroring what the API sends.
- */
-async function createMailboxEmail(
- id: number,
- encryptionKey: EncryptionKey,
- rawSymmetricKey: string,
- subject: string,
- keyIndex: number
-): Promise<MailboxEmail> {
- const symmetricKeyBase64 = Buffer.from(rawSymmetricKey).toString('base64');
-
- return {
- messagePreview: await EncryptionUtility.symmetricEncrypt(`Preview ${id}`, symmetricKeyBase64),
- hasAttachments: false,
- id,
- subject: await EncryptionUtility.symmetricEncrypt(subject, symmetricKeyBase64),
- fromDisplay: await EncryptionUtility.symmetricEncrypt(`Sender ${id}`, symmetricKeyBase64),
- fromDomain: await EncryptionUtility.symmetricEncrypt('example.com', symmetricKeyBase64),
- fromLocal: await EncryptionUtility.symmetricEncrypt(`sender${id}`, symmetricKeyBase64),
- toDomain: 'aliasvault.net',
- toLocal: `alias${id}`,
- date: '2026-05-26T00:00:00Z',
- dateSystem: '2026-05-26T00:00:00Z',
- secondsAgo: id,
- decryptionKeys: [{ keyIndex, encryptedSymmetricKey: await encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],
- };
-}
-
-/**
- * Creates an email with the supplied symmetric key encrypted by the RSA key pair. A single email carries its own
- * public key table, so the decryption key always references index 0.
- */
-async function createEmail(
- encryptionKey: EncryptionKey,
- rawSymmetricKey: string
-): Promise<Email> {
- return {
- messageSource: '',
- id: 1,
- subject: '',
- fromDisplay: '',
- fromDomain: '',
- fromLocal: '',
- toDomain: 'aliasvault.net',
- toLocal: 'alias',
- date: '2026-05-26T00:00:00Z',
- dateSystem: '2026-05-26T00:00:00Z',
- secondsAgo: 1,
- decryptionKeys: [{ keyIndex: 0, encryptedSymmetricKey: await encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],
- publicKeys: [encryptionKey.PublicKey],
- };
-}
-
-/**
- * Encrypts bytes in the same IV+ciphertext format used by attachment decryption.
- */
-async function encryptAttachmentBytes(plaintext: Uint8Array, rawSymmetricKey: string): Promise<Uint8Array> {
- const key = await crypto.subtle.importKey(
- 'raw',
- Uint8Array.from(rawSymmetricKey, c => c.charCodeAt(0)),
- {
- name: 'AES-GCM',
- length: 256,
- },
- false,
- ['encrypt']
- );
- const iv = crypto.getRandomValues(new Uint8Array(12));
- const ciphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, new Uint8Array(plaintext));
- const encryptedBytes = new Uint8Array(iv.length + ciphertext.byteLength);
- encryptedBytes.set(iv, 0);
- encryptedBytes.set(new Uint8Array(ciphertext), iv.length);
- return encryptedBytes;
-}
-
-/**
- * Gzip compresses a string.
- */
-async function gzip(plaintext: string): Promise<Uint8Array> {
- const stream = new Blob([new TextEncoder().encode(plaintext) as BlobPart]).stream()
- .pipeThrough(new CompressionStream('gzip'));
- return new Uint8Array(await new Response(stream).arrayBuffer());
-}
-
-/**
- * Counts non-extractable RSA private-key imports.
- */
-function countPrivateKeyImports(importKeyCalls: unknown[][]): number {
- return importKeyCalls.filter(call =>
- call[0] === 'jwk' &&
- call[3] === false &&
- Array.isArray(call[4]) &&
- call[4].includes('decrypt')
- ).length;
-}
-
-describe('generateRsaKeyPairNonExtractable', () => {
- it('returns a non-extractable CryptoKey for the private half', async () => {
- const { privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
-
- expect(privateKey).toBeInstanceOf(CryptoKey);
- expect(privateKey.type).toBe('private');
- expect(privateKey.extractable).toBe(false);
- });
-
- it('rejects every attempt to export the private key', async () => {
- const { privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
-
- await expect(crypto.subtle.exportKey('jwk', privateKey)).rejects.toBeDefined();
- await expect(crypto.subtle.exportKey('pkcs8', privateKey)).rejects.toBeDefined();
- });
-
- it('returns the public key as a JWK string without private fields', async () => {
- const { publicKeyJwk } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
-
- const jwk = JSON.parse(publicKeyJwk);
- expect(jwk.kty).toBe('RSA');
- expect(jwk.n).toBeDefined();
- expect(jwk.e).toBeDefined();
- expect(jwk.d).toBeUndefined();
- expect(jwk.p).toBeUndefined();
- expect(jwk.q).toBeUndefined();
- });
-
- it('round-trips: encrypt with JWK public key, decrypt with CryptoKey', async () => {
- const { publicKeyJwk, privateKey } = await EncryptionUtility.generateRsaKeyPairNonExtractable();
-
- const ciphertext = await encryptWithPublicKey('hello mobile login', publicKeyJwk);
- const plaintextBytes = await EncryptionUtility.decryptWithPrivateKeyObject(ciphertext, privateKey);
-
- expect(new TextDecoder().decode(plaintextBytes)).toBe('hello mobile login');
- });
-});
-
-describe('generateRsaKeyPair (legacy JWK path, used by vault email decrypt)', () => {
- it('still round-trips through the JWK-string decrypt path', async () => {
- const { publicKey, privateKey } = await EncryptionUtility.generateRsaKeyPair();
-
- const ciphertext = await encryptWithPublicKey('email body', publicKey);
- const plaintextBytes = await EncryptionUtility.decryptWithPrivateKey(ciphertext, privateKey);
-
- expect(new TextDecoder().decode(plaintextBytes)).toBe('email body');
- });
-});
-
-describe('email RSA private key cache', () => {
- it('caches multiple non-extractable private keys by matching public key', async () => {
- const keyPairA = await EncryptionUtility.generateRsaKeyPair();
- const keyPairB = await EncryptionUtility.generateRsaKeyPair();
- const encryptionKeyA: EncryptionKey = {
- Id: 'key-a',
- PublicKey: keyPairA.publicKey,
- PrivateKey: keyPairA.privateKey,
- IsPrimary: true,
- };
- const encryptionKeyB: EncryptionKey = {
- Id: 'key-b',
- PublicKey: keyPairB.publicKey,
- PrivateKey: keyPairB.privateKey,
- IsPrimary: false,
- };
- const publicKeys = [encryptionKeyA.PublicKey, encryptionKeyB.PublicKey];
- const emails = [
- await createMailboxEmail(1, encryptionKeyA, '0123456789abcdef0123456789abcdef', 'Subject A1', 0),
- await createMailboxEmail(2, encryptionKeyA, 'abcdef0123456789abcdef0123456789', 'Subject A2', 0),
- await createMailboxEmail(3, encryptionKeyB, 'fedcba9876543210fedcba9876543210', 'Subject B1', 1),
- ];
- const importKeySpy = vi.spyOn(crypto.subtle, 'importKey');
-
- try {
- const decryptedEmails = await EncryptionUtility.decryptEmailList(emails, publicKeys, [encryptionKeyA, encryptionKeyB]);
-
- expect(decryptedEmails.map(email => email.subject)).toEqual(['Subject A1', 'Subject A2', 'Subject B1']);
- expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(2);
-
- await EncryptionUtility.decryptEmailList([emails[0]], publicKeys, [encryptionKeyA, encryptionKeyB]);
- expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(2);
-
- EncryptionUtility.clearRsaPrivateKeyCache();
- await EncryptionUtility.decryptEmailList([emails[0]], publicKeys, [encryptionKeyA, encryptionKeyB]);
- expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(3);
- } finally {
- importKeySpy.mockRestore();
- }
- });
-
- it('resolves the decryption key by key index rather than by list order', async () => {
- /*
- * The key table is shared by the whole response, so an email's own decryption key list is not aligned with it. Picking
- * the wrong entry would decrypt with a key that does not match and blank the row.
- */
- const keyPairA = await EncryptionUtility.generateRsaKeyPair();
- const keyPairB = await EncryptionUtility.generateRsaKeyPair();
- const encryptionKeyA: EncryptionKey = {
- Id: 'key-a',
- PublicKey: keyPairA.publicKey,
- PrivateKey: keyPairA.privateKey,
- IsPrimary: true,
- };
- const encryptionKeyB: EncryptionKey = {
- Id: 'key-b',
- PublicKey: keyPairB.publicKey,
- PrivateKey: keyPairB.privateKey,
- IsPrimary: false,
- };
-
- // Only the second key of the table is held locally, and it is the only decryption key on the email.
- const publicKeys = [encryptionKeyA.PublicKey, encryptionKeyB.PublicKey];
- const email = await createMailboxEmail(1, encryptionKeyB, '0123456789abcdef0123456789abcdef', 'Indexed', 1);
-
- const decryptedEmails = await EncryptionUtility.decryptEmailList([email], publicKeys, [encryptionKeyB]);
-
- expect(decryptedEmails.map(mail => mail.subject)).toEqual(['Indexed']);
- });
-
- it('skips an email whose decryption key points outside the key table', async () => {
- // A decryption key referencing an index the response never sent is a malformed response; it must cost that row only.
- const keyPair = await EncryptionUtility.generateRsaKeyPair();
- const encryptionKey: EncryptionKey = {
- Id: 'key-a',
- PublicKey: keyPair.publicKey,
- PrivateKey: keyPair.privateKey,
- IsPrimary: true,
- };
- const emails = [
- await createMailboxEmail(1, encryptionKey, '0123456789abcdef0123456789abcdef', 'Readable', 0),
- await createMailboxEmail(2, encryptionKey, 'abcdef0123456789abcdef0123456789', 'Dangling', 7),
- ];
-
- const decryptedEmails = await EncryptionUtility.decryptEmailList(emails, [encryptionKey.PublicKey], [encryptionKey]);
-
- expect(decryptedEmails.map(mail => mail.subject)).toEqual(['Readable']);
- });
-
- it('skips undecryptable emails instead of failing the whole batch', async () => {
- /*
- * A mailbox can legitimately contain a message this user has no key for, e.g. when an alias is moved from a personal manifest to a shared manifest
- * but previously emails have not been encrypted yet for the new manifest, so older emails are hidden.
- */
- const keyPair = await EncryptionUtility.generateRsaKeyPair();
- const strangerKeyPair = await EncryptionUtility.generateRsaKeyPair();
- const encryptionKey: EncryptionKey = {
- Id: 'key-a',
- PublicKey: keyPair.publicKey,
- PrivateKey: keyPair.privateKey,
- IsPrimary: true,
- };
- const strangerKey: EncryptionKey = {
- Id: 'key-stranger',
- PublicKey: strangerKeyPair.publicKey,
- PrivateKey: strangerKeyPair.privateKey,
- IsPrimary: false,
- };
- const publicKeys = [encryptionKey.PublicKey, strangerKey.PublicKey];
- const emails = [
- await createMailboxEmail(1, encryptionKey, '0123456789abcdef0123456789abcdef', 'Readable', 0),
- await createMailboxEmail(2, strangerKey, 'abcdef0123456789abcdef0123456789', 'Unreadable', 1),
- await createMailboxEmail(3, encryptionKey, 'fedcba9876543210fedcba9876543210', 'Also readable', 0),
- ];
-
- // Only the own key is held, so email 2 cannot be decrypted.
- const decryptedEmails = await EncryptionUtility.decryptEmailList(emails, publicKeys, [encryptionKey]);
-
- expect(decryptedEmails.map(email => email.subject)).toEqual(['Readable', 'Also readable']);
- });
-
- it('reuses cached private keys when decrypting attachments', async () => {
- const keyPair = await EncryptionUtility.generateRsaKeyPair();
- const encryptionKey: EncryptionKey = {
- Id: 'key-a',
- PublicKey: keyPair.publicKey,
- PrivateKey: keyPair.privateKey,
- IsPrimary: true,
- };
- const rawSymmetricKey = '0123456789abcdef0123456789abcdef';
- const email = await createEmail(encryptionKey, rawSymmetricKey);
- const encryptedBytes = await encryptAttachmentBytes(
- new TextEncoder().encode('attachment body'),
- rawSymmetricKey
- );
- const importKeySpy = vi.spyOn(crypto.subtle, 'importKey');
-
- try {
- const decryptedBytes = await EncryptionUtility.decryptAttachment(encryptedBytes, email, [encryptionKey]);
- expect(new TextDecoder().decode(decryptedBytes)).toBe('attachment body');
- expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(1);
-
- await EncryptionUtility.decryptAttachment(encryptedBytes, email, [encryptionKey]);
- expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(1);
- } finally {
- importKeySpy.mockRestore();
- }
- });
-});
-
-describe('decryptEmail message source', () => {
- const rawSource = 'Subject: Hello\r\nContent-Type: text/plain\r\n\r\nRaw RFC 822 body.';
-
- /**
- * Builds an email whose message source holds the supplied already-encoded bytes.
- */
- async function createEmailWithSource(
- sourceBytes: Uint8Array,
- encryptionKey: EncryptionKey,
- rawSymmetricKey: string
- ): Promise<Email> {
- const email = await createEmail(encryptionKey, rawSymmetricKey);
- const encryptedBytes = await encryptAttachmentBytes(sourceBytes, rawSymmetricKey);
- email.messageSource = Buffer.from(encryptedBytes).toString('base64');
- return email;
- }
-
- /**
- * Creates an RSA encryption key pair for the test.
- */
- async function createEncryptionKey(): Promise<EncryptionKey> {
- const keyPair = await EncryptionUtility.generateRsaKeyPair();
- return {
- Id: 'key-a',
- PublicKey: keyPair.publicKey,
- PrivateKey: keyPair.privateKey,
- IsPrimary: true,
- };
- }
-
- it('decrypts an uncompressed message source', async () => {
- const encryptionKey = await createEncryptionKey();
- const rawSymmetricKey = '0123456789abcdef0123456789abcdef';
- const sourceBytes = new TextEncoder().encode(rawSource);
- const email = await createEmailWithSource(sourceBytes, encryptionKey, rawSymmetricKey);
-
- const decrypted = await EncryptionUtility.decryptEmail(email, [encryptionKey]);
-
- expect(decrypted.sourceBytes).toEqual(sourceBytes);
- expect(decrypted.email.messageSource).toBe('');
- });
-
- it('hands a compressed message source to the parser untouched', async () => {
- const encryptionKey = await createEncryptionKey();
- const rawSymmetricKey = '0123456789abcdef0123456789abcdef';
- const compressed = await gzip(rawSource);
- const email = await createEmailWithSource(compressed, encryptionKey, rawSymmetricKey);
-
- const decrypted = await EncryptionUtility.decryptEmail(email, [encryptionKey]);
-
- // Gunzipping is the parser's job (see core/rust/src/email_parser); decryption only unwraps the ciphertext.
- expect(decrypted.sourceBytes).toEqual(compressed);
- });
-});
diff --git a/core/client/src/crypto/EncryptionUtility.ts b/core/client/src/crypto/EncryptionUtility.ts
index 3aa7453e0..9db03ea40 100644
--- a/core/client/src/crypto/EncryptionUtility.ts
+++ b/core/client/src/crypto/EncryptionUtility.ts
@@ -1,36 +1,7 @@
-import { devWarn } from '../platform/Logger';
-import { argon2DeriveKey, parseEmailSource, rustCore, type ParsedEmailAttachment } from '../rust/RustCore';
+import { argon2DeriveKey } from '../rust/RustCore';
import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';
import { logDefect } from '../utilities/Diagnostics';
-import type { EncryptionKey } from '@aliasvault/models/vault';
-import type { Email, EmailDecryptionKey, MailboxEmail } from '@aliasvault/models/webapi';
-
-/**
- * A decrypted email. Its metadata (subject, sender) is decrypted from the individually encrypted fields, while
- * the bodies and attachments are 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;
-};
-
-/**
- * Whether the host has WebCrypto. Hosts without it (the mobile app) run AES-GCM and the email key unwrap in the Rust
- * core, which writes the same `IV | ciphertext | tag` format; the web hosts keep WebCrypto for its speed on large blobs.
- */
-function hasWebCrypto(): boolean {
- return typeof crypto !== 'undefined' && crypto.subtle !== undefined;
-}
-
/**
* Utility class for encryption operations including:
* - Argon2Id key derivation
@@ -38,8 +9,6 @@ function hasWebCrypto(): boolean {
* - RSA-OAEP asymmetric encryption/decryption
*/
export class EncryptionUtility {
- private static rsaPrivateKeyCache = new Map<string, Promise<CryptoKey>>();
-
/**
* Derives a key from a password using Argon2Id
*/
@@ -64,10 +33,6 @@ export class EncryptionUtility {
return plaintext;
}
- if (!hasWebCrypto()) {
- return bytesToBase64(await rustCore().symmetricEncryptBytes(new TextEncoder().encode(plaintext), base64Key));
- }
-
const key = await crypto.subtle.importKey(
"raw",
base64ToBytes(base64Key),
@@ -100,10 +65,6 @@ export class EncryptionUtility {
* Encrypts raw bytes using AES-GCM symmetric encryption.
*/
public static async symmetricEncryptBytes(plaintextBytes: Uint8Array, base64Key: string): Promise<string> {
- if (!hasWebCrypto()) {
- return bytesToBase64(await rustCore().symmetricEncryptBytes(plaintextBytes, base64Key));
- }
-
const key = await crypto.subtle.importKey(
"raw",
base64ToBytes(base64Key),
@@ -139,10 +100,6 @@ export class EncryptionUtility {
return base64Ciphertext;
}
- if (!hasWebCrypto()) {
- return rustCore().symmetricDecrypt(base64Ciphertext, base64Key);
- }
-
const key = await crypto.subtle.importKey(
"raw",
base64ToBytes(base64Key),
@@ -176,10 +133,6 @@ export class EncryptionUtility {
return encryptedBytes;
}
- if (!hasWebCrypto()) {
- return rustCore().symmetricDecryptBytes(encryptedBytes, base64Key);
- }
-
const key = await crypto.subtle.importKey(
"raw",
base64ToBytes(base64Key),
@@ -279,13 +232,6 @@ export class EncryptionUtility {
return new Uint8Array(plaintextBuffer);
}
- /**
- * Clears cached RSA private keys when the in-memory vault is locked or reset.
- */
- public static clearRsaPrivateKeyCache(): void {
- EncryptionUtility.rsaPrivateKeyCache.clear();
- }
-
/**
* Imports an RSA-OAEP private key as non-extractable.
*/
@@ -301,157 +247,6 @@ export class EncryptionUtility {
["decrypt"]
);
}
-
- /**
- * Returns the cached non-extractable private key matching an email encryption public key.
- */
- private static async getPrivateKeyObject(encryptionKey: EncryptionKey): Promise<CryptoKey> {
- const cachedPrivateKey = EncryptionUtility.rsaPrivateKeyCache.get(encryptionKey.PublicKey);
-
- if (cachedPrivateKey) {
- return await cachedPrivateKey;
- }
-
- const privateKey = EncryptionUtility.importPrivateKey(encryptionKey.PrivateKey).catch(error => {
- EncryptionUtility.rsaPrivateKeyCache.delete(encryptionKey.PublicKey);
- throw error;
- });
-
- EncryptionUtility.rsaPrivateKeyCache.set(encryptionKey.PublicKey, privateKey);
- return await privateKey;
- }
-
- /**
- * 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 that 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];
- if (!publicKey) {
- continue;
- }
-
- const key = encryptionKeys.find(k => k.PublicKey === publicKey);
- 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);
- if (!hasWebCrypto()) {
- return bytesToBase64(await rustCore().rsaDecrypt(match.encryptedSymmetricKey, match.encryptionKey.PrivateKey));
- }
-
- const privateKey = await EncryptionUtility.getPrivateKeyObject(match.encryptionKey);
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(match.encryptedSymmetricKey, privateKey);
-
- return bytesToBase64(symmetricKey);
- }
-
- /**
- * Decrypts an individual email based on the provided public/private key pairs.
- */
- public static async decryptEmail(email: Email, encryptionKeys: EncryptionKey[]): Promise<DecryptedEmail> {
- try {
- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);
-
- const decryptedEmail = { ...email };
- decryptedEmail.subject = await EncryptionUtility.symmetricDecrypt(email.subject, symmetricKeyBase64);
- decryptedEmail.fromDisplay = await EncryptionUtility.symmetricDecrypt(email.fromDisplay, symmetricKeyBase64);
- decryptedEmail.fromDomain = await EncryptionUtility.symmetricDecrypt(email.fromDomain, symmetricKeyBase64);
- decryptedEmail.fromLocal = await EncryptionUtility.symmetricDecrypt(email.fromLocal, symmetricKeyBase64);
-
- const sourceBytes = email.messageSource ? await EncryptionUtility.symmetricDecryptBytes(base64ToBytes(email.messageSource), 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.
- devWarn(`[Email] Could not parse the source of email ${email.id}:`, err);
- }
- }
-
- 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. The publicKeys table is the one the
- * API sent alongside the emails; each email's decryption keys reference it by index.
- *
- * Emails that cannot be decrypted are skipped rather than failing the batch. The server only serves mail the
- * caller holds a key for, so this should not happen but we handle it gracefully to prevent one unreadable record
- * from breaking the whole list view.
- */
- public static async decryptEmailList(
- emails: MailboxEmail[],
- publicKeys: string[],
- encryptionKeys: EncryptionKey[]
- ): Promise<MailboxEmail[]> {
- const results = await Promise.all(emails.map(async email => {
- try {
- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, publicKeys, encryptionKeys);
-
- // Create a new object to avoid mutating the original
- const decryptedEmail = { ...email };
-
- // Decrypt all email fields
- decryptedEmail.subject = await EncryptionUtility.symmetricDecrypt(email.subject, symmetricKeyBase64);
- decryptedEmail.fromDisplay = await EncryptionUtility.symmetricDecrypt(email.fromDisplay, symmetricKeyBase64);
- decryptedEmail.fromDomain = await EncryptionUtility.symmetricDecrypt(email.fromDomain, symmetricKeyBase64);
- decryptedEmail.fromLocal = await EncryptionUtility.symmetricDecrypt(email.fromLocal, symmetricKeyBase64);
-
- if (email.messagePreview) {
- decryptedEmail.messagePreview = await EncryptionUtility.symmetricDecrypt(email.messagePreview, symmetricKeyBase64);
- }
-
- return decryptedEmail;
- } catch (err) {
- devWarn(`[Email] Skipping email ${email.id}, it could not be decrypted:`, err);
- return null;
- }
- }));
-
- return results.filter((email): email is MailboxEmail => email !== null);
- }
-
- /**
- * Decrypts an attachment and returns the decrypted content as Uint8Array (raw bytes).
- */
- public static async decryptAttachment(
- encryptedBytes: Uint8Array,
- email: Email,
- encryptionKeys: EncryptionKey[]
- ): Promise<Uint8Array> {
- try {
- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);
-
- // 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');
- }
- }
}
export default EncryptionUtility;
diff --git a/core/client/src/email/EmailAttachments.ts b/core/client/src/email/EmailAttachments.ts
index bb5c60c25..4a3707e06 100644
--- a/core/client/src/email/EmailAttachments.ts
+++ b/core/client/src/email/EmailAttachments.ts
@@ -1,6 +1,7 @@
-import EncryptionUtility from '../crypto/EncryptionUtility';
import { extractEmailAttachment } from '../rust/RustCore';
+import { decryptEmailAttachment } from './EmailDecryption';
+
import type { WebApiService } from '../api/WebApiService';
import type { EncryptionKey } from '@aliasvault/models/vault';
import type { Email } from '@aliasvault/models/webapi';
@@ -19,7 +20,7 @@ export async function getEmailAttachmentBytes(webApi: Pick<WebApiService, 'downl
let detachedBody: Uint8Array | undefined;
if (partIndex !== null) {
const encryptedPart = await webApi.downloadBlob(`Email/${email.id}/parts/${partIndex}`);
- detachedBody = await EncryptionUtility.decryptAttachment(encryptedPart, email, encryptionKeys);
+ detachedBody = await decryptEmailAttachment(encryptedPart, email, encryptionKeys);
}
return extractEmailAttachment(sourceBytes, index, detachedBody);
}
diff --git a/core/client/src/email/EmailDecryption.ts b/core/client/src/email/EmailDecryption.ts
new file mode 100644
index 000000000..c4cb43cb4
--- /dev/null
+++ b/core/client/src/email/EmailDecryption.ts
@@ -0,0 +1,197 @@
+/**
+ * Email decryption logic.
+ *
+ * 1. Pick the email's decryption key whose public key the caller holds ({@link resolveSymmetricKey}).
+ * 2. Unwrap the email's symmetric key with that keypair's RSA-OAEP-256 private key.
+ * 3. Decrypt the header fields, the message source and attachments with AES-256-GCM (`IV | ciphertext | tag`).
+ * 4. Hand the decrypted source to the Rust email parser for the bodies and attachment list.
+ *
+ * The crypto primitives run on WebCrypto in the browser extension and web app, which is about 10x faster than the Rust
+ * core compiled to WebAssembly for RSA and for large sources. The mobile app has no WebCrypto and uses the native Rust
+ * core (core/rust/src/crypto) instead. Both produce and read the same formats.
+ */
+import { devWarn } from '../platform/Logger';
+import { parseEmailSource, rustCore, type ParsedEmailAttachment } from '../rust/RustCore';
+import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';
+
+import type { EncryptionKey } from '@aliasvault/models/vault';
+import type { Email, EmailDecryptionKey, MailboxEmail } from '@aliasvault/models/webapi';
+
+/**
+ * A decrypted email. Its metadata (subject, sender) is decrypted from the individually encrypted fields, while
+ * the bodies and attachments are 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;
+};
+
+/**
+ * Decrypts a full email and parses its source.
+ */
+export async function decryptEmail(email: Email, encryptionKeys: EncryptionKey[]): Promise<DecryptedEmail> {
+ try {
+ const symmetricKey = await resolveSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);
+
+ const decryptedEmail: Email = {
+ ...email,
+ subject: await decryptText(email.subject, symmetricKey),
+ fromDisplay: await decryptText(email.fromDisplay, symmetricKey),
+ fromDomain: await decryptText(email.fromDomain, symmetricKey),
+ fromLocal: await decryptText(email.fromLocal, symmetricKey),
+ messageSource: '',
+ };
+
+ const sourceBytes = email.messageSource ? await decryptBytes(base64ToBytes(email.messageSource), symmetricKey) : null;
+
+ let htmlBody: string | null = null;
+ let textBody: string | null = null;
+ let attachments: ParsedEmailAttachment[] = [];
+ if (sourceBytes) {
+ try {
+ ({ htmlBody, textBody, attachments } = await parseEmailSource(sourceBytes));
+ } catch (err) {
+ // A parse failure costs the bodies, not the email: the raw source view renders without the parser.
+ devWarn(`[Email] Could not parse the source of email ${email.id}:`, err);
+ }
+ }
+
+ return { email: decryptedEmail, htmlBody, textBody, attachments, sourceBytes };
+ } catch (err) {
+ throw new Error(err instanceof Error ? err.message : 'Failed to decrypt email');
+ }
+}
+
+/**
+ * Decrypts the header fields of a page of mailbox emails. The publicKeys table is the one the API sent alongside the
+ * emails; each email's decryption keys reference it by index.
+ *
+ * Emails that cannot be decrypted are skipped rather than failing the batch. The server only serves mail the caller
+ * holds a key for, so this should not happen, but one unreadable record must not break the whole list view.
+ */
+export async function decryptEmailList(emails: MailboxEmail[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<MailboxEmail[]> {
+ const results = await Promise.all(emails.map(async (email): Promise<MailboxEmail | null> => {
+ try {
+ const symmetricKey = await resolveSymmetricKey(email.decryptionKeys, publicKeys, encryptionKeys);
+ return {
+ ...email,
+ subject: await decryptText(email.subject, symmetricKey),
+ fromDisplay: await decryptText(email.fromDisplay, symmetricKey),
+ fromDomain: await decryptText(email.fromDomain, symmetricKey),
+ fromLocal: await decryptText(email.fromLocal, symmetricKey),
+ messagePreview: await decryptText(email.messagePreview, symmetricKey),
+ };
+ } catch (err) {
+ devWarn(`[Email] Skipping email ${email.id}, it could not be decrypted:`, err);
+ return null;
+ }
+ }));
+
+ return results.filter((email): email is MailboxEmail => email !== null);
+}
+
+/**
+ * Decrypts a separately fetched attachment body with the email's symmetric key.
+ */
+export async function decryptEmailAttachment(encryptedBytes: Uint8Array, email: Email, encryptionKeys: EncryptionKey[]): Promise<Uint8Array> {
+ try {
+ return await decryptBytes(encryptedBytes, await resolveSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys));
+ } catch (err) {
+ throw new Error(err instanceof Error ? err.message : 'Failed to decrypt attachment');
+ }
+}
+
+/**
+ * Forget the imported RSA private keys, called when the vault is locked or reset.
+ */
+export function clearEmailKeyCache(): void {
+ privateKeyCache.clear();
+}
+
+/**
+ * The email's symmetric key (base64), unwrapped from the first decryption key whose public key the caller holds. A
+ * decryption key names its public key by index into the response's publicKeys table, so the email's own list of
+ * decryption keys is not aligned with the caller's keys.
+ */
+async function resolveSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<string> {
+ for (const decryptionKey of decryptionKeys) {
+ const publicKey = publicKeys[decryptionKey.keyIndex];
+ const encryptionKey = publicKey ? encryptionKeys.find(key => key.PublicKey === publicKey) : undefined;
+ if (encryptionKey) {
+ return unwrapSymmetricKey(decryptionKey.encryptedSymmetricKey, encryptionKey);
+ }
+ }
+
+ throw new Error('Encryption key not found');
+}
+
+/*
+ * Crypto primitives: WebCrypto where the host has it, the native Rust core otherwise (mobile).
+ */
+
+/** Imported non-extractable RSA private keys, by public key, so a page of emails imports each keypair once. */
+const privateKeyCache = new Map<string, Promise<CryptoKey>>();
+
+/**
+ * Whether the host has WebCrypto; the mobile app does not.
+ */
+function hasWebCrypto(): boolean {
+ return typeof crypto !== 'undefined' && crypto.subtle !== undefined;
+}
+
+/**
+ * RSA-OAEP-256 decrypt an email's symmetric key with the keypair's private key. Returns the key as base64.
+ */
+async function unwrapSymmetricKey(encryptedSymmetricKey: string, encryptionKey: EncryptionKey): Promise<string> {
+ if (!hasWebCrypto()) {
+ return bytesToBase64(await rustCore().rsaDecrypt(encryptedSymmetricKey, encryptionKey.PrivateKey));
+ }
+
+ let privateKey = privateKeyCache.get(encryptionKey.PublicKey);
+ if (!privateKey) {
+ privateKey = crypto.subtle.importKey('jwk', JSON.parse(encryptionKey.PrivateKey), { name: 'RSA-OAEP', hash: 'SHA-256' }, false, ['decrypt']);
+ privateKey.catch(() => privateKeyCache.delete(encryptionKey.PublicKey));
+ privateKeyCache.set(encryptionKey.PublicKey, privateKey);
+ }
+
+ return bytesToBase64(new Uint8Array(await crypto.subtle.decrypt({ name: 'RSA-OAEP' }, await privateKey, base64ToBytes(encryptedSymmetricKey))));
+}
+
+/**
+ * AES-256-GCM decrypt a base64 `IV | ciphertext | tag` field into UTF-8. An empty field stays empty.
+ */
+async function decryptText(base64Ciphertext: string, symmetricKey: string): Promise<string> {
+ if (!base64Ciphertext) {
+ return base64Ciphertext;
+ }
+
+ if (!hasWebCrypto()) {
+ return rustCore().symmetricDecrypt(base64Ciphertext, symmetricKey);
+ }
+
+ return new TextDecoder().decode(await decryptBytes(base64ToBytes(base64Ciphertext), symmetricKey));
+}
+
+/**
+ * AES-256-GCM decrypt `IV | ciphertext | tag` bytes.
+ */
+async function decryptBytes(encrypted: Uint8Array, symmetricKey: string): Promise<Uint8Array> {
+ if (encrypted.length === 0) {
+ return encrypted;
+ }
+
+ if (!hasWebCrypto()) {
+ return rustCore().symmetricDecryptBytes(encrypted, symmetricKey);
+ }
+
+ const key = await crypto.subtle.importKey('raw', base64ToBytes(symmetricKey), { name: 'AES-GCM', length: 256 }, false, ['decrypt']);
+ return new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: encrypted.slice(0, 12) }, key, encrypted.slice(12)));
+}
diff --git a/core/client/src/rust/RustCoreBinding.ts b/core/client/src/rust/RustCoreBinding.ts
index 8d77ca18d..469932680 100644
--- a/core/client/src/rust/RustCoreBinding.ts
+++ b/core/client/src/rust/RustCoreBinding.ts
@@ -45,9 +45,8 @@ export interface IRustCore {
decodeEmailSource(source: Uint8Array): Promise<Uint8Array>;
extractEmailAttachment(source: Uint8Array, index: number, detachedBody?: Uint8Array): Promise<Uint8Array>;
- symmetricEncryptBytes(plaintext: Uint8Array, keyBase64: string): Promise<Uint8Array>;
- symmetricDecryptBytes(encrypted: Uint8Array, keyBase64: string): Promise<Uint8Array>;
symmetricDecrypt(base64Ciphertext: string, keyBase64: string): Promise<string>;
+ symmetricDecryptBytes(encrypted: Uint8Array, keyBase64: string): Promise<Uint8Array>;
rsaDecrypt(base64Ciphertext: string, privateKeyJwk: string): Promise<Uint8Array>;
pinGenerateSalt(): Promise<Uint8Array>;
diff --git a/core/client/src/rust/WasmRustCore.ts b/core/client/src/rust/WasmRustCore.ts
index a8abdb51a..a18d7a8a7 100644
--- a/core/client/src/rust/WasmRustCore.ts
+++ b/core/client/src/rust/WasmRustCore.ts
@@ -69,9 +69,8 @@ export function createWasmRustCore(loadWasm: WasmLoader): IRustCore {
decodeEmailSource: (source): Promise<Uint8Array> => ready(() => core.decodeEmailSource(source)),
extractEmailAttachment: (source, index, detachedBody): Promise<Uint8Array> => ready(() => core.extractEmailAttachment(source, index, detachedBody)),
- symmetricEncryptBytes: (plaintext, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricEncryptBytes(plaintext, keyBase64)),
- symmetricDecryptBytes: (encrypted, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricDecryptBytes(encrypted, keyBase64)),
symmetricDecrypt: (base64Ciphertext, keyBase64): Promise<string> => ready(() => core.symmetricDecrypt(base64Ciphertext, keyBase64)),
+ symmetricDecryptBytes: (encrypted, keyBase64): Promise<Uint8Array> => ready(() => core.symmetricDecryptBytes(encrypted, keyBase64)),
rsaDecrypt: (base64Ciphertext, privateKeyJwk): Promise<Uint8Array> => ready(() => core.rsaDecrypt(base64Ciphertext, privateKeyJwk)),
/*
diff --git a/core/rust/src/bindings/uniffi_api.rs b/core/rust/src/bindings/uniffi_api.rs
index 1c8818c65..83f112470 100644
--- a/core/rust/src/bindings/uniffi_api.rs
+++ b/core/rust/src/bindings/uniffi_api.rs
@@ -186,10 +186,10 @@ pub fn argon2_derive_key(password: String, salt: String, encryption_settings: St
crate::crypto::argon2::argon2_derive_key_from_settings(&password, &salt, &encryption_settings)
}
-/// AES-256-GCM encrypt bytes with a base64 key. Returns `IV | ciphertext | tag`.
+/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.
#[uniffi::export]
-pub fn symmetric_encrypt_bytes(plaintext: Vec<u8>, key_base64: String) -> Result<Vec<u8>, VaultError> {
- crate::crypto::symmetric_encrypt_raw_with_aad(&plaintext, &key_base64, &[])
+pub fn symmetric_decrypt(base64_ciphertext: String, key_base64: String) -> Result<String, VaultError> {
+ crate::crypto::symmetric_decrypt(&base64_ciphertext, &key_base64)
}
/// AES-256-GCM decrypt `IV | ciphertext | tag` bytes with a base64 key.
@@ -198,12 +198,6 @@ pub fn symmetric_decrypt_bytes(encrypted: Vec<u8>, key_base64: String) -> Result
crate::crypto::symmetric_decrypt_bytes(&encrypted, &key_base64)
}
-/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.
-#[uniffi::export]
-pub fn symmetric_decrypt(base64_ciphertext: String, key_base64: String) -> Result<String, VaultError> {
- crate::crypto::symmetric_decrypt(&base64_ciphertext, &key_base64)
-}
-
/// A fresh random salt for a new PIN wrap.
#[uniffi::export]
pub fn pin_generate_salt() -> Vec<u8> {
diff --git a/core/rust/src/bindings/wasm.rs b/core/rust/src/bindings/wasm.rs
index cf67e7392..eadf4c024 100644
--- a/core/rust/src/bindings/wasm.rs
+++ b/core/rust/src/bindings/wasm.rs
@@ -198,10 +198,10 @@ pub fn argon2_derive_key_js(password: &str, salt: &str, encryption_settings: &st
crate::crypto::argon2::argon2_derive_key_from_settings(password, salt, encryption_settings).map_err(js_err)
}
-/// AES-256-GCM encrypt bytes with a base64 key. Returns `IV | ciphertext | tag`.
-#[wasm_bindgen(js_name = symmetricEncryptBytes)]
-pub fn symmetric_encrypt_bytes_js(plaintext: &[u8], key_base64: &str) -> Result<Vec<u8>, JsValue> {
- crate::crypto::symmetric_encrypt_raw_with_aad(plaintext, key_base64, &[]).map_err(js_err)
+/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.
+#[wasm_bindgen(js_name = symmetricDecrypt)]
+pub fn symmetric_decrypt_js(base64_ciphertext: &str, key_base64: &str) -> Result<String, JsValue> {
+ crate::crypto::symmetric_decrypt(base64_ciphertext, key_base64).map_err(js_err)
}
/// AES-256-GCM decrypt `IV | ciphertext | tag` bytes with a base64 key.
@@ -210,12 +210,6 @@ pub fn symmetric_decrypt_bytes_js(encrypted: &[u8], key_base64: &str) -> Result<
crate::crypto::symmetric_decrypt_bytes(encrypted, key_base64).map_err(js_err)
}
-/// AES-256-GCM decrypt a base64 `IV | ciphertext | tag` string into UTF-8 with a base64 key; empty stays empty.
-#[wasm_bindgen(js_name = symmetricDecrypt)]
-pub fn symmetric_decrypt_js(base64_ciphertext: &str, key_base64: &str) -> Result<String, JsValue> {
- crate::crypto::symmetric_decrypt(base64_ciphertext, key_base64).map_err(js_err)
-}
-
/// RSA-OAEP-256 decrypt base64 ciphertext with a JWK private key.
#[wasm_bindgen(js_name = rsaDecrypt)]
pub fn rsa_decrypt_js(base64_ciphertext: &str, private_key_jwk: &str) -> Result<Vec<u8>, JsValue> {