Skip to content

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

Update email claim link structure (#2159)

Leendert de Borstbf2dd1764435
diff --git a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
index 7324f54af..fd2dc4b55 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
@@ -141,7 +141,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
*/
const response = await webApi.authFetch(`EmailBox/${email}`, { method: 'GET' }, true, false);
try {
- const data = response as { mails: MailboxEmail[] };
+ const data = response as { mails: MailboxEmail[], publicKeys: string[] };
// Store all emails, sorted by date
const allMails = data.mails
@@ -151,6 +151,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
// Loop through all emails and decrypt them locally
const decryptedEmails: MailboxEmail[] = await EncryptionUtility.decryptEmailList(
allMails,
+ data.publicKeys,
dbContext.sqliteClient!.encryptionKeys.getAll()
);
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 350b863e7..43082e7ec 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
@@ -89,7 +89,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, encryptionKeys);
+ const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
if (reset) {
setEmails(decryptedEmails);
@@ -131,7 +131,7 @@ const EmailsList: React.FC = () => {
// Decrypt emails locally
const encryptionKeys = dbContext.sqliteClient.encryptionKeys.getAll();
- const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, encryptionKeys);
+ const decryptedEmails = await EncryptionUtility.decryptEmailList(data.mails, data.publicKeys, encryptionKeys);
// Append to existing emails
setEmails((prevEmails) => [...prevEmails, ...decryptedEmails]);
diff --git a/apps/browser-extension/src/utils/EmailRouting.ts b/apps/browser-extension/src/utils/EmailRouting.ts
index 90a9ad483..178b284ac 100644
Binary files a/apps/browser-extension/src/utils/EmailRouting.ts and b/apps/browser-extension/src/utils/EmailRouting.ts differ
diff --git a/apps/browser-extension/src/utils/EncryptionUtility.ts b/apps/browser-extension/src/utils/EncryptionUtility.ts
index 1bb69d64b..c9758ceb1 100644
--- a/apps/browser-extension/src/utils/EncryptionUtility.ts
+++ b/apps/browser-extension/src/utils/EncryptionUtility.ts
@@ -4,7 +4,7 @@ import argon2 from 'argon2-browser/dist/argon2-bundled.min.js';
import { devWarn } from '@/utils/devLogger/DevLogger';
import type { EncryptionKey } from '@/utils/dist/core/models/vault';
-import type { Email, EmailKeyWrap, MailboxEmail } from '@/utils/dist/core/models/webapi';
+import type { Email, EmailDecryptionKey, MailboxEmail } from '@/utils/dist/core/models/webapi';
import { parseEmailSource, type ParsedEmailAttachment } from '@/utils/RustCore';
/**
@@ -379,14 +379,20 @@ export class EncryptionUtility {
}
/**
- * Finds the wrap of an email's symmetric key that one of the locally held keypairs can open. An email carries
- * one wrap per manifest keypair the caller holds.
+ * 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 resolveEmailWrap(email: { wraps: EmailKeyWrap[] },encryptionKeys: EncryptionKey[]): { encryptionKey: EncryptionKey, encryptedSymmetricKey: string } {
- for (const wrap of email.wraps) {
- const key = encryptionKeys.find(k => k.PublicKey === wrap.publicKey);
+ 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: wrap.encryptedSymmetricKey };
+ return { encryptionKey: key, encryptedSymmetricKey: decryptionKey.encryptedSymmetricKey };
}
}
@@ -394,12 +400,12 @@ export class EncryptionUtility {
}
/**
- * Unwraps the symmetric key an email's contents are encrypted with, as base64.
+ * Decrypts the symmetric key an email's contents are encrypted with, as base64.
*/
- private static async resolveEmailSymmetricKey(email: { wraps: EmailKeyWrap[] }, encryptionKeys: EncryptionKey[]): Promise<string> {
- const wrap = EncryptionUtility.resolveEmailWrap(email, encryptionKeys);
- const privateKey = await EncryptionUtility.getPrivateKeyObject(wrap.encryptionKey);
- const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(wrap.encryptedSymmetricKey, privateKey);
+ private static async resolveEmailSymmetricKey(decryptionKeys: EmailDecryptionKey[], publicKeys: string[], encryptionKeys: EncryptionKey[]): Promise<string> {
+ const match = EncryptionUtility.resolveEmailDecryptionKey(decryptionKeys, publicKeys, encryptionKeys);
+ const privateKey = await EncryptionUtility.getPrivateKeyObject(match.encryptionKey);
+ const symmetricKey = await EncryptionUtility.decryptWithPrivateKeyObject(match.encryptedSymmetricKey, privateKey);
return Buffer.from(symmetricKey).toString('base64');
}
@@ -409,7 +415,7 @@ export class EncryptionUtility {
*/
public static async decryptEmail(email: Email, encryptionKeys: EncryptionKey[]): Promise<DecryptedEmail> {
try {
- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email, encryptionKeys);
+ const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);
const decryptedEmail = { ...email };
decryptedEmail.subject = await EncryptionUtility.symmetricDecrypt(email.subject, symmetricKeyBase64);
@@ -443,7 +449,8 @@ export class EncryptionUtility {
}
/**
- * Decrypts a list of emails based on the provided public/private key pairs.
+ * 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
@@ -451,11 +458,12 @@ export class EncryptionUtility {
*/
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, encryptionKeys);
+ const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, publicKeys, encryptionKeys);
// Create a new object to avoid mutating the original
const decryptedEmail = { ...email };
@@ -489,7 +497,7 @@ export class EncryptionUtility {
encryptionKeys: EncryptionKey[]
): Promise<Uint8Array> {
try {
- const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email, encryptionKeys);
+ const symmetricKeyBase64 = await EncryptionUtility.resolveEmailSymmetricKey(email.decryptionKeys, email.publicKeys, encryptionKeys);
// Decrypt the attachment using raw bytes
return await EncryptionUtility.symmetricDecryptBytes(encryptedBytes, symmetricKeyBase64);
diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.ts
index 0e735dc6c..e22905f19 100644
--- a/apps/browser-extension/src/utils/VaultSyncService.ts
+++ b/apps/browser-extension/src/utils/VaultSyncService.ts
@@ -865,6 +865,9 @@ export class VaultSyncService {
* run earlier (the pre-push no-op check caches its result) and a write in between advances them.
*/
const storedRevisions = await getManifestRevisions();
+ /**
+ * Get the revision of a manifest from the stored revisions, or use the revision from the manifest record if not found.
+ */
const revisionOf = (record: ManifestRecord): number => storedRevisions[record.manifestId] ?? record.revision;
const recordByManifestId = new Map(manifestRecords.map(r => [r.manifestId, r]));
diff --git a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
index 6b67cae0d..525184740 100644
--- a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts
@@ -9,13 +9,15 @@ beforeEach(() => {
});
/**
- * Creates a mailbox email with fields encrypted by the supplied RSA key pair.
+ * 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
+ subject: string,
+ keyIndex: number
): Promise<MailboxEmail> {
const symmetricKeyBase64 = Buffer.from(rawSymmetricKey).toString('base64');
@@ -32,21 +34,21 @@ async function createMailboxEmail(
date: '2026-05-26T00:00:00Z',
dateSystem: '2026-05-26T00:00:00Z',
secondsAgo: id,
- wraps: [{ publicKey: encryptionKey.PublicKey, encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],
+ decryptionKeys: [{ keyIndex, encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],
};
}
/**
- * Creates an email with the supplied symmetric key encrypted by the RSA key pair.
+ * 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 {
- messageHtml: '',
- messagePlain: '',
messageSource: '',
+ attachmentCount: 0,
id: 1,
subject: '',
fromDisplay: '',
@@ -57,7 +59,8 @@ async function createEmail(
date: '2026-05-26T00:00:00Z',
dateSystem: '2026-05-26T00:00:00Z',
secondsAgo: 1,
- wraps: [{ publicKey: encryptionKey.PublicKey, encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],
+ decryptionKeys: [{ keyIndex: 0, encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],
+ publicKeys: [encryptionKey.PublicKey],
attachments: [],
};
}
@@ -170,34 +173,84 @@ describe('email RSA private key cache', () => {
PrivateKey: keyPairB.privateKey,
IsPrimary: false,
};
+ const publicKeys = [encryptionKeyA.PublicKey, encryptionKeyB.PublicKey];
const emails = [
- await createMailboxEmail(1, encryptionKeyA, '0123456789abcdef0123456789abcdef', 'Subject A1'),
- await createMailboxEmail(2, encryptionKeyA, 'abcdef0123456789abcdef0123456789', 'Subject A2'),
- await createMailboxEmail(3, encryptionKeyB, 'fedcba9876543210fedcba9876543210', 'Subject B1'),
+ 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, [encryptionKeyA, encryptionKeyB]);
+ 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]], [encryptionKeyA, encryptionKeyB]);
+ await EncryptionUtility.decryptEmailList([emails[0]], publicKeys, [encryptionKeyA, encryptionKeyB]);
expect(countPrivateKeyImports(importKeySpy.mock.calls as unknown[][])).toBe(2);
EncryptionUtility.clearRsaPrivateKeyCache();
- await EncryptionUtility.decryptEmailList([emails[0]], [encryptionKeyA, encryptionKeyB]);
+ 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. Mail delivered to an alias before
- // it moved into a shared manifest is encrypted with the owner's personal key. The server filters those out,
- // but if one slips through it must cost that single row, not blank the entire mailbox.
+ /*
+ * 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 = {
@@ -212,14 +265,15 @@ describe('email RSA private key cache', () => {
PrivateKey: strangerKeyPair.privateKey,
IsPrimary: false,
};
+ const publicKeys = [encryptionKey.PublicKey, strangerKey.PublicKey];
const emails = [
- await createMailboxEmail(1, encryptionKey, '0123456789abcdef0123456789abcdef', 'Readable'),
- await createMailboxEmail(2, strangerKey, 'abcdef0123456789abcdef0123456789', 'Unreadable'),
- await createMailboxEmail(3, encryptionKey, 'fedcba9876543210fedcba9876543210', 'Also readable'),
+ 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, [encryptionKey]);
+ const decryptedEmails = await EncryptionUtility.decryptEmailList(emails, publicKeys, [encryptionKey]);
expect(decryptedEmails.map(email => email.subject)).toEqual(['Readable', 'Also readable']);
});
diff --git a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts b/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
index a2b9a99e8..173efec71 100644
--- a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
+++ b/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
@@ -190,6 +190,9 @@ export class ItemQueries {
ORDER BY t.DisplayOrder, t.Name`;
}
+ /**
+ * Generate placeholders for item key pairs.
+ */
private static itemKeyPlaceholders(itemCount: number): string {
return Array(itemCount).fill('(?, ?)').join(', ');
}
diff --git a/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts b/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts
index c6c7f1f2a..8cf670e99 100644
--- a/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts
+++ b/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts
@@ -139,9 +139,9 @@ type ValidateLoginResponse = {
serverSessionProof: string;
};
-type EmailKeyWrap = {
- /** The public key whose private half unwraps this wrap */
- publicKey: string;
+type EmailDecryptionKey = {
+ /** Position of the public key in the response-level publicKeys table */
+ keyIndex: number;
/** The email's symmetric key, encrypted with the public key */
encryptedSymmetricKey: string;
};
@@ -171,8 +171,8 @@ type MailboxEmail = {
dateSystem: string;
/** The number of seconds ago the email was received */
secondsAgo: number;
- /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */
- wraps: EmailKeyWrap[];
+ /** The encrypted copies of the email's symmetric key the caller can decrypt, one per manifest keypair the caller holds. */
+ decryptionKeys: EmailDecryptionKey[];
};
/**
@@ -191,6 +191,7 @@ type MailboxBulkResponse = {
currentPage: number;
pageSize: number;
totalRecords: number;
+ publicKeys: string[];
mails: MailboxEmail[];
};
@@ -235,8 +236,10 @@ type Email = {
dateSystem: string;
/** The number of seconds ago the email was received */
secondsAgo: number;
- /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */
- wraps: EmailKeyWrap[];
+ /** The encrypted copies of the email's symmetric key the caller can decrypt, one per manifest keypair the caller holds */
+ decryptionKeys: EmailDecryptionKey[];
+ /** The public keys referenced by this email's decryption keys, indexed by EmailDecryptionKey.keyIndex */
+ publicKeys: string[];
/** The attachments of the email */
attachments: EmailAttachment[];
};
@@ -526,4 +529,4 @@ declare const VaultKeyAlgorithm: {
*/
type VaultKeyAlgorithmValue = typeof VaultKeyAlgorithm[keyof typeof VaultKeyAlgorithm];
-export { type ApiErrorResponse, AuthEventType, type AuthLogModel, type BadRequestResponse, type DeleteAccountInitiateRequest, type DeleteAccountInitiateResponse, type DeleteAccountRequest, type Email, type EmailAttachment, type EmailKeyWrap, type FaviconExtractModel, type LoginRequest, type LoginResponse, type MailboxBulkRequest, type MailboxBulkResponse, type MailboxEmail, ManifestKeyType, type ManifestKeyTypeValue, type ManifestRevision, type MobileLoginInitiateRequest, type MobileLoginInitiateResponse, type MobileLoginPollResponse, type MobileLoginSubmitRequest, type PasswordChangeInitiateResponse, type RefreshToken, type StatusResponse, type StatusResponseV2, type TokenModel, UnlockMethodType, type UnlockMethodTypeValue, type ValidateLoginRequest, type ValidateLoginRequest2Fa, type ValidateLoginResponse, type Vault, VaultKeyAlgorithm, type VaultKeyAlgorithmValue, type VaultKeyGetResponse, type VaultKeyResponse, type VaultPasswordChangeRequest, type VaultPostResponse, type VaultResponse };
+export { type ApiErrorResponse, AuthEventType, type AuthLogModel, type BadRequestResponse, type DeleteAccountInitiateRequest, type DeleteAccountInitiateResponse, type DeleteAccountRequest, type Email, type EmailAttachment, type EmailDecryptionKey, type FaviconExtractModel, type LoginRequest, type LoginResponse, type MailboxBulkRequest, type MailboxBulkResponse, type MailboxEmail, ManifestKeyType, type ManifestKeyTypeValue, type ManifestRevision, type MobileLoginInitiateRequest, type MobileLoginInitiateResponse, type MobileLoginPollResponse, type MobileLoginSubmitRequest, type PasswordChangeInitiateResponse, type RefreshToken, type StatusResponse, type StatusResponseV2, type TokenModel, UnlockMethodType, type UnlockMethodTypeValue, type ValidateLoginRequest, type ValidateLoginRequest2Fa, type ValidateLoginResponse, type Vault, VaultKeyAlgorithm, type VaultKeyAlgorithmValue, type VaultKeyGetResponse, type VaultKeyResponse, type VaultPasswordChangeRequest, type VaultPostResponse, type VaultResponse };
diff --git a/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts b/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts
index c6c7f1f2a..8cf670e99 100644
--- a/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts
+++ b/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts
@@ -139,9 +139,9 @@ type ValidateLoginResponse = {
serverSessionProof: string;
};
-type EmailKeyWrap = {
- /** The public key whose private half unwraps this wrap */
- publicKey: string;
+type EmailDecryptionKey = {
+ /** Position of the public key in the response-level publicKeys table */
+ keyIndex: number;
/** The email's symmetric key, encrypted with the public key */
encryptedSymmetricKey: string;
};
@@ -171,8 +171,8 @@ type MailboxEmail = {
dateSystem: string;
/** The number of seconds ago the email was received */
secondsAgo: number;
- /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */
- wraps: EmailKeyWrap[];
+ /** The encrypted copies of the email's symmetric key the caller can decrypt, one per manifest keypair the caller holds. */
+ decryptionKeys: EmailDecryptionKey[];
};
/**
@@ -191,6 +191,7 @@ type MailboxBulkResponse = {
currentPage: number;
pageSize: number;
totalRecords: number;
+ publicKeys: string[];
mails: MailboxEmail[];
};
@@ -235,8 +236,10 @@ type Email = {
dateSystem: string;
/** The number of seconds ago the email was received */
secondsAgo: number;
- /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */
- wraps: EmailKeyWrap[];
+ /** The encrypted copies of the email's symmetric key the caller can decrypt, one per manifest keypair the caller holds */
+ decryptionKeys: EmailDecryptionKey[];
+ /** The public keys referenced by this email's decryption keys, indexed by EmailDecryptionKey.keyIndex */
+ publicKeys: string[];
/** The attachments of the email */
attachments: EmailAttachment[];
};
@@ -526,4 +529,4 @@ declare const VaultKeyAlgorithm: {
*/
type VaultKeyAlgorithmValue = typeof VaultKeyAlgorithm[keyof typeof VaultKeyAlgorithm];
-export { type ApiErrorResponse, AuthEventType, type AuthLogModel, type BadRequestResponse, type DeleteAccountInitiateRequest, type DeleteAccountInitiateResponse, type DeleteAccountRequest, type Email, type EmailAttachment, type EmailKeyWrap, type FaviconExtractModel, type LoginRequest, type LoginResponse, type MailboxBulkRequest, type MailboxBulkResponse, type MailboxEmail, ManifestKeyType, type ManifestKeyTypeValue, type ManifestRevision, type MobileLoginInitiateRequest, type MobileLoginInitiateResponse, type MobileLoginPollResponse, type MobileLoginSubmitRequest, type PasswordChangeInitiateResponse, type RefreshToken, type StatusResponse, type StatusResponseV2, type TokenModel, UnlockMethodType, type UnlockMethodTypeValue, type ValidateLoginRequest, type ValidateLoginRequest2Fa, type ValidateLoginResponse, type Vault, VaultKeyAlgorithm, type VaultKeyAlgorithmValue, type VaultKeyGetResponse, type VaultKeyResponse, type VaultPasswordChangeRequest, type VaultPostResponse, type VaultResponse };
+export { type ApiErrorResponse, AuthEventType, type AuthLogModel, type BadRequestResponse, type DeleteAccountInitiateRequest, type DeleteAccountInitiateResponse, type DeleteAccountRequest, type Email, type EmailAttachment, type EmailDecryptionKey, type FaviconExtractModel, type LoginRequest, type LoginResponse, type MailboxBulkRequest, type MailboxBulkResponse, type MailboxEmail, ManifestKeyType, type ManifestKeyTypeValue, type ManifestRevision, type MobileLoginInitiateRequest, type MobileLoginInitiateResponse, type MobileLoginPollResponse, type MobileLoginSubmitRequest, type PasswordChangeInitiateResponse, type RefreshToken, type StatusResponse, type StatusResponseV2, type TokenModel, UnlockMethodType, type UnlockMethodTypeValue, type ValidateLoginRequest, type ValidateLoginRequest2Fa, type ValidateLoginResponse, type Vault, VaultKeyAlgorithm, type VaultKeyAlgorithmValue, type VaultKeyGetResponse, type VaultKeyResponse, type VaultPasswordChangeRequest, type VaultPostResponse, type VaultResponse };
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
index 15369a035..5b6222dec 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
@@ -50,10 +50,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var sanitizedEmail = to.Trim().ToLower();
// See if this user has a valid claim to the email address.
- var emailClaim = await context.EmailClaims
- .FirstOrDefaultAsync(x => x.Address == sanitizedEmail);
-
- if (emailClaim is null || emailClaim.Disabled)
+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail && x.Links.Any(l => l.State != EmailClaimLinkState.Removed));
+ if (emailClaim is null)
{
return BadRequest(new ApiErrorResponse
{
@@ -65,7 +63,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
});
}
- var hasPersonalLink = await context.EmailClaimLinks.AnyAsync(l => l.EmailClaimId == emailClaim.Id && l.VaultManifest.OwnerGroupId == user.PersonalGroupId);
+ var hasPersonalLink = await context.EmailClaimLinks.AnyAsync(l => l.EmailClaimId == emailClaim.Id && l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId);
if (!hasPersonalLink)
{
return BadRequest(new ApiErrorResponse
@@ -84,7 +82,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
.ToListAsync();
// Retrieve emails from database (excluding any received after a shadow-block took effect).
- var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.Wraps.Any(w => personalKeyIds.Contains(w.EncryptionKeyId)));
+ var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.DecryptionKeys.Any(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)));
if (shadowCutoff is not null)
{
emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);
@@ -104,8 +102,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
MessagePreview = x.MessagePreview ?? string.Empty,
- EncryptedSymmetricKey = x.Wraps.Where(w => personalKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => w.EncryptedSymmetricKey).First(),
- EncryptionKey = x.Wraps.Where(w => personalKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => w.EncryptionKey.PublicKey).First(),
+ EncryptedSymmetricKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.EncryptedSymmetricKey).First(),
+ EncryptionKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.VaultManifestDeliveryKey.PublicKey).First(),
})
.OrderByDescending(x => x.DateSystem)
.Take(50)
@@ -146,12 +144,12 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
// Load all email addresses that the user has a claim to where the address is in the list.
var validAddresses = await context.EmailClaimLinks
- .Where(l => model.Addresses.Contains(l.EmailClaim.Address) && !l.EmailClaim.Disabled && l.VaultManifest.OwnerGroupId == user.PersonalGroupId)
+ .Where(l => model.Addresses.Contains(l.EmailClaim.Address) && l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId)
.Select(l => l.EmailClaim.Address)
.Distinct()
.ToListAsync();
- // The caller's personal keys: v1 clients only hold the private halves of these, so serve the matching wraps.
+ // The caller's personal keys: v1 clients only hold the private halves of these, so serve the matching decryption keys.
var personalKeyIds = await context.VaultManifestDeliveryKeys
.Where(k => context.VaultManifests.Any(m => m.ManifestId == k.VaultManifestId && m.OwnerGroupId == user.PersonalGroupId))
.Select(k => k.Id)
@@ -167,7 +165,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
FROM unnest(@addresses) AS addr(email)
CROSS JOIN LATERAL (
SELECT * FROM ""Emails"" AS e2
- WHERE e2.""To"" = addr.email AND EXISTS (SELECT 1 FROM ""EmailKeyWraps"" AS w WHERE w.""EmailId"" = e2.""Id"" AND w.""EncryptionKeyId"" = ANY(@keyids)){cutoffClause}
+ WHERE e2.""To"" = addr.email AND EXISTS (SELECT 1 FROM ""EmailDecryptionKeys"" AS d WHERE d.""EmailId"" = e2.""Id"" AND d.""VaultManifestDeliveryKeyId"" = ANY(@keyids)){cutoffClause}
ORDER BY e2.""DateSystem"" DESC
LIMIT @limit
) AS e";
@@ -204,14 +202,14 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
MessagePreview = x.MessagePreview ?? string.Empty,
- EncryptedSymmetricKey = x.Wraps.Where(w => personalKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => w.EncryptedSymmetricKey).First(),
- EncryptionKey = x.Wraps.Where(w => personalKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => w.EncryptionKey.PublicKey).First(),
+ EncryptedSymmetricKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.EncryptedSymmetricKey).First(),
+ EncryptionKey = x.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).Select(d => d.VaultManifestDeliveryKey.PublicKey).First(),
HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),
})
.ToListAsync();
// Total count for pagination
- var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && email.Wraps.Any(w => personalKeyIds.Contains(w.EncryptionKeyId)));
+ var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && email.DecryptionKeys.Any(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)));
if (shadowCutoff is not null)
{
countQuery = countQuery.Where(email => email.DateSystem <= shadowCutoff.Value);
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
index e872fe665..26bea4de8 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
@@ -36,7 +36,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- var (email, personalWrap, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
+ var (email, personalDecryptionKey, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
if (errorResult != null)
{
return errorResult;
@@ -57,8 +57,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
MessageHtml = email.MessageHtml,
MessagePlain = email.MessagePlain,
MessageSource = email.MessageSourceBytes is not null ? Convert.ToBase64String(email.MessageSourceBytes) : email.MessageSource,
- EncryptedSymmetricKey = personalWrap!.EncryptedSymmetricKey,
- EncryptionKey = personalWrap.EncryptionKey.PublicKey,
+ EncryptedSymmetricKey = personalDecryptionKey!.EncryptedSymmetricKey,
+ EncryptionKey = personalDecryptionKey.VaultManifestDeliveryKey.PublicKey,
};
// Add attachment metadata (without the filebytes)
@@ -144,8 +144,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
/// </summary>
/// <param name="id">The email ID to retrieve.</param>
/// <param name="context">The database context.</param>
- /// <returns>A tuple containing the email, the wrap belonging to the caller's personal keys, and an IActionResult if there's an error.</returns>
- private async Task<(Email? Email, EmailKeyWrap? PersonalWrap, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)
+ /// <returns>A tuple containing the email, the decryption key belonging to the caller's personal keys, and an IActionResult if there's an error.</returns>
+ private async Task<(Email? Email, EmailDecryptionKey? PersonalDecryptionKey, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)
{
var user = await GetCurrentUserAsync();
if (user is null)
@@ -159,8 +159,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
// Retrieve email from database.
var email = await context.Emails
.Include(x => x.Attachments)
- .Include(x => x.Wraps)
- .ThenInclude(w => w.EncryptionKey)
+ .Include(x => x.DecryptionKeys)
+ .ThenInclude(d => d.VaultManifestDeliveryKey)
.FirstOrDefaultAsync(x => x.Id == id);
if (email is null)
@@ -176,24 +176,26 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
// See if this user has a valid claim to the email address.
var normalizedEmailAddress = email.To.Trim().ToLower();
- var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == normalizedEmailAddress && !x.Disabled && x.Links.Any(l => l.VaultManifest.OwnerGroupId == user.PersonalGroupId));
+ var emailClaim = await context.EmailClaims
+ .Where(x => x.Address == normalizedEmailAddress)
+ .FirstOrDefaultAsync(x => x.Links.Any(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId));
if (emailClaim is null)
{
return (null, null, Unauthorized("User does not have a claim to this email address."));
}
- // Serve the wrap belonging to the caller's personal keys.
+ // Serve the decryption key belonging to the caller's personal keys.
var personalKeyIds = await context.VaultManifestDeliveryKeys
.Where(k => context.VaultManifests.Any(m => m.ManifestId == k.VaultManifestId && m.OwnerGroupId == user.PersonalGroupId))
.Select(k => k.Id)
.ToListAsync();
- var personalWrap = email.Wraps.Where(w => personalKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).FirstOrDefault();
- if (personalWrap is null)
+ var personalDecryptionKey = email.DecryptionKeys.Where(d => personalKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).FirstOrDefault();
+ if (personalDecryptionKey is null)
{
return (null, null, NotFound("Email not found."));
}
- return (email, personalWrap, null);
+ return (email, personalDecryptionKey, null);
}
}
diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
index e8f63bd4c..a46af3ce8 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
@@ -320,7 +320,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
}
/// <summary>
- /// HTTP 426 Upgrade Required — returned to legacy v1 clients hitting a migrated user. This is a backstop only:
+ /// HTTP 426 Upgrade Required: returned to legacy v1 clients hitting a migrated user. This is a backstop only:
/// the status endpoint already reports such clients as unsupported, so a well-behaved client logs out with a
/// proper "update your client" message before it ever calls a vault endpoint.
/// </summary>
@@ -396,10 +396,11 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
// multiple credentials share the same private email address.
newEmailAddresses = newEmailAddresses.Select(EmailHelper.SanitizeEmail).Distinct().ToList();
- // Get list of email claims owned by the user (v1 only supports personal claims in the personal manifest).
+ // Get list of email claims owned by the user.
var userOwnedEmailClaims = await context.EmailClaims
.Include(x => x.Links)
- .Where(x => x.Links.Any(l => l.VaultManifestId == personalManifestId))
+ .Where(x => x.Links.Any(l => l.VaultManifestId == personalManifestId && l.State != EmailClaimLinkState.Removed)
+ || (x.Links.All(l => l.State == EmailClaimLinkState.Removed) && x.Links.Any(l => l.VaultManifestId == personalManifestId)))
.ToListAsync();
// Keep track of processed and sanitized email addresses to know which ones still exist.
@@ -420,7 +421,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
int baseCount;
if (limit.WindowSeconds == 0)
{
- // Global absolute cap: every claim ever billed to the caller's group (including disabled ones).
+ // Global absolute cap: every claim ever billed to the caller's group.
baseCount = await context.EmailClaimLinks.Where(l => l.VaultManifest.OwnerGroupId == user.PersonalGroupId).Select(l => l.EmailClaimId).Distinct().CountAsync();
}
else
@@ -464,14 +465,17 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
var existingUserClaim = userOwnedEmailClaims.FirstOrDefault(x => x.Address == sanitizedEmail);
if (existingUserClaim != null)
{
- // Claim already exists but is disabled, so we can re-enable it.
- if (existingUserClaim.Disabled)
+ // The personal manifest carries the address again, so revive its link. A paused link keeps its pause:
+ // v1 has no per-alias switch, and a v1 sync must never undo one set from a v2 client.
+ var personalLink = existingUserClaim.Links.FirstOrDefault(l => l.VaultManifestId == personalManifestId);
+ if (personalLink is { State: EmailClaimLinkState.Removed })
{
- existingUserClaim.Disabled = false;
+ personalLink.State = EmailClaimLinkState.Active;
existingUserClaim.UpdatedAt = timeProvider.UtcNow;
}
- // If the claim already exists and is not disabled, everything is good, we don't need to do anything.
+ // Reviving the link is all there is to re-enabling the alias: a claim counts as live for as long as
+ // any of its links is not removed, so there is no separate flag to put back.
continue;
}
@@ -517,31 +521,27 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
}
}
- // Disable email claims that are no longer in the new list and have not been disabled yet.
- // Important: we do not delete email claims ever, as they may be re-used by the user in the future.
- // We also don't want to allow other users to re-use emails used by other users.
- // Email claims are considered permanent.
- foreach (var existingClaim in userOwnedEmailClaims.Where(x => !x.Disabled).ToList())
+ // Disable email claim links that are no longer in the new provided email claim list.
+ foreach (var existingClaim in userOwnedEmailClaims)
{
- if (!processedEmailAddresses.Contains(existingClaim.Address))
+ if (processedEmailAddresses.Contains(existingClaim.Address))
{
- // The address is gone from the personal vault. Disable the claim when the personal manifest is its only link (keeping the link so a later re-claim re-enables it).
- var personalLinks = existingClaim.Links.Where(l => l.VaultManifestId == personalManifestId).ToList();
- if (personalLinks.Count == existingClaim.Links.Count)
- {
- existingClaim.Disabled = true;
- existingClaim.UpdatedAt = timeProvider.UtcNow;
- continue;
- }
+ continue;
+ }
- foreach (var link in personalLinks)
- {
- existingClaim.Links.Remove(link);
- context.EmailClaimLinks.Remove(link);
- }
+ // The address is gone from the personal vault: disable its link.
+ var personalLinks = existingClaim.Links.Where(l => l.VaultManifestId == personalManifestId && l.State != EmailClaimLinkState.Removed).ToList();
+ if (personalLinks.Count == 0)
+ {
+ continue;
+ }
- existingClaim.UpdatedAt = timeProvider.UtcNow;
+ foreach (var link in personalLinks)
+ {
+ link.State = EmailClaimLinkState.Removed;
}
+
+ existingClaim.UpdatedAt = timeProvider.UtcNow;
}
await context.SaveChangesAsync();
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
index 2a8a985de..d66f33bfb 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
@@ -51,10 +51,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var sanitizedEmail = to.Trim().ToLower();
// See if this user has a valid claim to the email address.
- var emailClaim = await context.EmailClaims
- .FirstOrDefaultAsync(x => x.Address == sanitizedEmail);
-
- if (emailClaim is null || emailClaim.Disabled)
+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail && x.Links.Any(l => l.State != EmailClaimLinkState.Removed));
+ if (emailClaim is null)
{
return BadRequest(new ApiErrorResponse
{
@@ -79,39 +77,50 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
});
}
- // Retrieve emails from database, restricted to emails carrying a wrap the caller can open.
+ // Retrieve emails from database, restricted to emails carrying a decryption key the caller can open.
var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);
- var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.Wraps.Any(w => decryptableKeyIds.Contains(w.EncryptionKeyId)));
+ var keyTable = await EmailKeyTable.BuildAsync(context, decryptableKeyIds);
+ var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.DecryptionKeys.Any(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)));
if (shadowCutoff is not null)
{
emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);
}
- List<MailboxEmailApiModel> emails = await emailQuery
- .Select(x => new MailboxEmailApiModel()
+ var rows = await emailQuery
+ .Select(x => new
{
- Id = x.Id,
- Subject = x.Subject,
- FromDisplay = x.From,
- FromDomain = x.FromDomain,
- FromLocal = x.FromLocal,
- ToDomain = x.ToDomain,
- ToLocal = x.ToLocal,
- Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
- DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
- SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
- MessagePreview = x.MessagePreview ?? string.Empty,
- Wraps = x.Wraps.Where(w => decryptableKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => new EmailKeyWrapApiModel { PublicKey = w.EncryptionKey.PublicKey, EncryptedSymmetricKey = w.EncryptedSymmetricKey }).ToList(),
- HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),
+ Mail = new MailboxEmailApiModel()
+ {
+ Id = x.Id,
+ Subject = x.Subject,
+ FromDisplay = x.From,
+ FromDomain = x.FromDomain,
+ FromLocal = x.FromLocal,
+ ToDomain = x.ToDomain,
+ ToLocal = x.ToLocal,
+ Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
+ DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
+ MessagePreview = x.MessagePreview ?? string.Empty,
+ HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),
+ },
+ DecryptionKeys = x.DecryptionKeys.Where(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)).Select(d => new { d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey }).ToList(),
})
- .OrderByDescending(x => x.DateSystem)
+ .OrderByDescending(x => x.Mail.DateSystem)
.Take(50)
.ToListAsync();
+ var emails = rows.ConvertAll(r =>
+ {
+ r.Mail.DecryptionKeys = keyTable.ToApiModels(r.DecryptionKeys.Select(d => (d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey)));
+ return r.Mail;
+ });
+
var returnValue = new MailboxApiModel
{
Address = to,
Subscribed = false,
+ PublicKeys = keyTable.PublicKeys,
Mails = emails,
};
@@ -148,15 +157,16 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
// Restrict to emails this user holds a key for.
var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);
+ var keyTable = await EmailKeyTable.BuildAsync(context, decryptableKeyIds);
- // Fetch the newest emails for each address individually, restricted to emails carrying a wrap the caller can open.
+ // Fetch the newest emails for each address individually, restricted to emails carrying a decryption key the caller can open.
var cutoffClause = shadowCutoff is null ? string.Empty : @" AND e2.""DateSystem"" <= @cutoff";
var pageSql = $@"
SELECT e.*
FROM unnest(@addresses) AS addr(email)
CROSS JOIN LATERAL (
SELECT * FROM ""Emails"" AS e2
- WHERE e2.""To"" = addr.email AND EXISTS (SELECT 1 FROM ""EmailKeyWraps"" AS w WHERE w.""EmailId"" = e2.""Id"" AND w.""EncryptionKeyId"" = ANY(@keyids)){cutoffClause}
+ WHERE e2.""To"" = addr.email AND EXISTS (SELECT 1 FROM ""EmailDecryptionKeys"" AS d WHERE d.""EmailId"" = e2.""Id"" AND d.""VaultManifestDeliveryKeyId"" = ANY(@keyids)){cutoffClause}
ORDER BY e2.""DateSystem"" DESC
LIMIT @limit
) AS e";
@@ -174,32 +184,41 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
}
// Merge the per-address results, order them globally and take the requested page.
- var mails = await context.Emails
+ var rows = await context.Emails
.FromSqlRaw(pageSql, parameters.ToArray())
.AsNoTracking()
.OrderByDescending(x => x.DateSystem)
.Skip((page - 1) * model.PageSize)
.Take(model.PageSize)
- .Select(x => new MailboxEmailApiModel
+ .Select(x => new
{
- Id = x.Id,
- Subject = x.Subject,
- FromDisplay = x.From,
- FromDomain = x.FromDomain,
- FromLocal = x.FromLocal,
- ToDomain = x.ToDomain,
- ToLocal = x.ToLocal,
- Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
- DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
- SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
- MessagePreview = x.MessagePreview ?? string.Empty,
- Wraps = x.Wraps.Where(w => decryptableKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).Select(w => new EmailKeyWrapApiModel { PublicKey = w.EncryptionKey.PublicKey, EncryptedSymmetricKey = w.EncryptedSymmetricKey }).ToList(),
- HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),
+ Mail = new MailboxEmailApiModel
+ {
+ Id = x.Id,
+ Subject = x.Subject,
+ FromDisplay = x.From,
+ FromDomain = x.FromDomain,
+ FromLocal = x.FromLocal,
+ ToDomain = x.ToDomain,
+ ToLocal = x.ToLocal,
+ Date = DateTime.SpecifyKind(x.Date, DateTimeKind.Utc),
+ DateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),
+ SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,
+ MessagePreview = x.MessagePreview ?? string.Empty,
+ HasAttachments = x.AttachmentCount > 0 || x.Attachments.Any(),
+ },
+ DecryptionKeys = x.DecryptionKeys.Where(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)).Select(d => new { d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey }).ToList(),
})
.ToListAsync();
+ var mails = rows.ConvertAll(r =>
+ {
+ r.Mail.DecryptionKeys = keyTable.ToApiModels(r.DecryptionKeys.Select(d => (d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey)));
+ return r.Mail;
+ });
+
// Count the total number of emails.
- var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && email.Wraps.Any(w => decryptableKeyIds.Contains(w.EncryptionKeyId)));
+ var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && email.DecryptionKeys.Any(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)));
if (shadowCutoff is not null)
{
countQuery = countQuery.Where(email => email.DateSystem <= shadowCutoff.Value);
@@ -210,6 +229,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
MailboxBulkResponse returnValue = new()
{
Addresses = validAddresses,
+ PublicKeys = keyTable.PublicKeys,
Mails = mails,
PageSize = model.PageSize,
CurrentPage = page,
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
index 259d3a155..e67d769d9 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs
@@ -37,12 +37,13 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
{
await using var context = await dbContextFactory.CreateDbContextAsync();
- var (email, callerWraps, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
+ var (email, callerDecryptionKeys, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);
if (errorResult != null)
{
return errorResult;
}
+ var keyTable = EmailKeyTable.Create(callerDecryptionKeys.Select(d => (d.VaultManifestDeliveryKeyId, d.VaultManifestDeliveryKey.PublicKey)));
var returnEmail = new EmailApiModel
{
Id = email!.Id,
@@ -57,7 +58,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
SecondsAgo = (int)DateTime.UtcNow.Subtract(email.DateSystem).TotalSeconds,
MessageSource = email.MessageSourceBytes is not null ? Convert.ToBase64String(email.MessageSourceBytes) : email.MessageSource,
AttachmentCount = email.AttachmentCount,
- Wraps = callerWraps.Select(w => new EmailKeyWrapApiModel { PublicKey = w.EncryptionKey.PublicKey, EncryptedSymmetricKey = w.EncryptedSymmetricKey }).ToList(),
+ PublicKeys = keyTable.PublicKeys,
+ DecryptionKeys = keyTable.ToApiModels(callerDecryptionKeys.Select(d => (d.VaultManifestDeliveryKeyId, d.EncryptedSymmetricKey))),
};
// Add attachment metadata (without the filebytes)
@@ -170,8 +172,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
/// </summary>
/// <param name="id">The email ID to retrieve.</param>
/// <param name="context">The database context.</param>
- /// <returns>A tuple containing the email, the wraps of it the caller can open, and an IActionResult if there's an error.</returns>
- private async Task<(Email? Email, List<EmailKeyWrap> CallerWraps, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)
+ /// <returns>A tuple containing the email, the decryption keys of it the caller can open, and an IActionResult if there's an error.</returns>
+ private async Task<(Email? Email, List<EmailDecryptionKey> CallerDecryptionKeys, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)
{
var user = await GetCurrentUserAsync();
if (user is null)
@@ -185,8 +187,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
// Retrieve email from database.
var email = await context.Emails
.Include(x => x.Attachments)
- .Include(x => x.Wraps)
- .ThenInclude(w => w.EncryptionKey)
+ .Include(x => x.DecryptionKeys)
+ .ThenInclude(d => d.VaultManifestDeliveryKey)
.FirstOrDefaultAsync(x => x.Id == id);
if (email is null)
@@ -202,21 +204,20 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
// Check if the user has access to the email address.
var normalizedEmailAddress = email.To.Trim().ToLower();
- var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == normalizedEmailAddress && !x.Disabled);
-
+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == normalizedEmailAddress);
if (emailClaim is null || !await EmailAccessHelper.CanReadClaimAsync(context, emailClaim, user.Id))
{
return (null, [], Unauthorized("User does not have a claim to this email address."));
}
- // The email is accessible only through a wrap the caller holds a private key for.
+ // The email is accessible only through a decryption key the caller holds the private half for.
var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);
- var callerWraps = email.Wraps.Where(w => decryptableKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).ToList();
- if (callerWraps.Count == 0)
+ var callerDecryptionKeys = email.DecryptionKeys.Where(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)).OrderBy(d => d.VaultManifestDeliveryKeyId).ToList();
+ if (callerDecryptionKeys.Count == 0)
{
return (null, [], NotFound("Email not found."));
}
- return (email, callerWraps, null);
+ return (email, callerDecryptionKeys, null);
}
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs b/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs
index 96f07301c..736baa2c6 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs
@@ -254,12 +254,12 @@ public class SharingController(IAliasServerDbContextFactory dbContextFactory, Us
context.VaultManifestAccessKeys.Remove(grant);
- // Strip the recipient's personal manifest links from every address also linked to the revoked manifest,
- // so future mail is no longer wrapped for their personal key.
+ // Remove any recipient's personal claim that also exists on the shared manifest.
+ // TODO: verify design that this is correct in terms of sharing and revocation logic.
var recipientPersonalGroupId = await context.AliasVaultUsers.Where(u => u.Id == model.RecipientUserId).Select(u => u.PersonalGroupId).FirstOrDefaultAsync();
await context.EmailClaimLinks
.Where(l => l.VaultManifest.OwnerGroupId == recipientPersonalGroupId && context.EmailClaimLinks.Any(s => s.EmailClaimId == l.EmailClaimId && s.VaultManifestId == model.ManifestId))
- .ExecuteDeleteAsync();
+ .ExecuteUpdateAsync(s => s.SetProperty(l => l.State, EmailClaimLinkState.Removed));
await context.SaveChangesAsync();
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
index 806b528a3..c06284844 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -928,7 +928,8 @@ public class VaultController(
private async Task<EmailRouting> BuildEmailRoutingAsync(AliasServerDbContext context, AliasVaultUser user)
{
var claims = await context.EmailClaims
- .Where(c => !c.Disabled && c.Links.Any(l => context.GroupMembers.Any(gm => gm.GroupId == l.VaultManifest.OwnerGroupId && gm.UserId == user.Id && gm.Role == GroupRole.Owner)))
+ .Where(c => c.Links.Any(l => l.State != EmailClaimLinkState.Removed
+ && context.GroupMembers.Any(gm => gm.GroupId == l.VaultManifest.OwnerGroupId && gm.UserId == user.Id && gm.Role == GroupRole.Owner)))
.Select(c => c.Address)
.ToListAsync();
@@ -996,9 +997,10 @@ public class VaultController(
/// <param name="routing">The pushed routing data: one entry per (address, manifest) pair.</param>
private async Task UpdateEmailClaimsAsync(AliasServerDbContext context, AliasVaultUser user, EmailRoutingPush routing)
{
+ // Get all unique emails with calculated state (active wins from paused in case there are multiple).
var pushedPairs = routing.EmailAddressList
.GroupBy(x => new { Address = EmailHelper.SanitizeEmail(x.Address), x.ManifestId })
- .Select(g => new { g.Key.Address, g.Key.ManifestId, Paused = g.All(x => x.Paused) })
+ .Select(g => new { g.Key.Address, g.Key.ManifestId, State = g.All(x => x.Paused) ? EmailClaimLinkState.Paused : EmailClaimLinkState.Active })
.ToList();
var accessibleManifests = (await ManifestAccessHelper.AccessibleManifests(context, user.Id).Select(m => m.ManifestId).ToListAsync()).ToHashSet();
@@ -1016,7 +1018,7 @@ public class VaultController(
return;
}
- var assertedPairs = new List<(string Address, Guid ManifestId, bool Paused)>();
+ var assertedPairs = new List<(string Address, Guid ManifestId, EmailClaimLinkState State)>();
foreach (var pair in pushedPairs)
{
if (!accessibleManifests.Contains(pair.ManifestId))
@@ -1025,7 +1027,7 @@ public class VaultController(
continue;
}
- assertedPairs.Add((pair.Address, pair.ManifestId, pair.Paused));
+ assertedPairs.Add((pair.Address, pair.ManifestId, pair.State));
}
var assertedManifestIds = assertedPairs.Select(p => p.ManifestId).Distinct().ToList();
@@ -1036,18 +1038,19 @@ public class VaultController(
.Where(k => assertedManifestIds.Contains(k.VaultManifestId) && k.IsPrimary)
.Select(k => k.VaultManifestId)
.ToListAsync()).ToHashSet();
- foreach (var (address, manifestId, _) in assertedPairs.Where(p => !p.Paused && p.ManifestId != personalManifestId.Value && !manifestsWithDeliveryKey.Contains(p.ManifestId)))
+ foreach (var (address, manifestId, _) in assertedPairs.Where(p => p.State == EmailClaimLinkState.Active && p.ManifestId != personalManifestId.Value && !manifestsWithDeliveryKey.Contains(p.ManifestId)))
{
logger.LogWarning("{User} claimed shared alias {Email} for manifest {Manifest} with no published delivery key; that manifest gets no wrap for its mail until a delivery key is published.", user.UserName, address, manifestId);
}
- // Per address: the manifests that claim it, each with whether the user switched the alias off there.
- var desiredByAddress = assertedPairs.GroupBy(p => p.Address).ToDictionary(g => g.Key, g => g.ToDictionary(p => p.ManifestId, p => p.Paused));
+ // Per address: the manifests that carry it, each with the state the push puts that link in.
+ var desiredByAddress = assertedPairs.GroupBy(p => p.Address).ToDictionary(g => g.Key, g => g.ToDictionary(p => p.ManifestId, p => p.State));
// Get the claims this push may update: every claim linked to a manifest inside the caller's update scope.
var userOwnedEmailClaims = await context.EmailClaims
.Include(c => c.Links)
- .Where(c => c.Links.Any(l => updateScope.Contains(l.VaultManifestId)))
+ .Where(c => c.Links.Any(l => updateScope.Contains(l.VaultManifestId) && l.State != EmailClaimLinkState.Removed)
+ || (c.Links.All(l => l.State == EmailClaimLinkState.Removed) && c.Links.Any(l => updateScope.Contains(l.VaultManifestId))))
.ToListAsync();
var processed = new HashSet<string>();
var supportedDomains = config.PrivateEmailDomains;
@@ -1107,45 +1110,41 @@ public class VaultController(
if (existing != null)
{
var changed = false;
- foreach (var (manifestId, paused) in desiredManifests.Where(d => existing.Links.All(l => l.VaultManifestId != d.Key)))
+ foreach (var (manifestId, state) in desiredManifests)
{
- if (!TryChargeQuota(manifestId))
+ var link = existing.Links.FirstOrDefault(l => l.VaultManifestId == manifestId);
+ if (link is null)
{
+ if (TryChargeQuota(manifestId))
+ {
+ existing.Links.Add(new EmailClaimLink { EmailClaimId = existing.Id, VaultManifestId = manifestId, State = state });
+ changed = true;
+ }
+
continue;
}
- existing.Links.Add(new EmailClaimLink { EmailClaimId = existing.Id, VaultManifestId = manifestId, Paused = paused });
- changed = true;
- }
-
- // Switching a single alias on or off only affects this flag: the link itself survives, so mail already received for it stays readable.
- foreach (var link in existing.Links)
- {
- if (desiredManifests.TryGetValue(link.VaultManifestId, out var paused) && link.Paused != paused)
+ if (link.State != state)
{
- link.Paused = paused;
+ link.State = state;
changed = true;
}
}
- var staleLinks = existing.Links.Where(l => updateScope.Contains(l.VaultManifestId) && !desiredManifests.ContainsKey(l.VaultManifestId)).ToList();
- if (staleLinks.Count == existing.Links.Count)
+ // Links in the caller's update scope that this push no longer carries: those manifests dropped the alias.
+ var inScopeLinks = existing.Links.Where(l => l.State != EmailClaimLinkState.Removed && updateScope.Contains(l.VaultManifestId));
+ var droppedLinks = inScopeLinks.Where(l => !desiredManifests.ContainsKey(l.VaultManifestId)).ToList();
+ if (droppedLinks.Count > 0 && existing.Links.All(l => l.State == EmailClaimLinkState.Removed || droppedLinks.Contains(l)))
{
- // Removing these would orphan the claim (the pushed links were all blocked, e.g. by quota); keep the previous links rather than leave a tombstone.
+ // The push carries this address, yet every link would end up removed: the links it named were all
+ // blocked (e.g. by quota). Keep the previous ones rather than disable an alias the vault still has.
logger.LogWarning("{User} pushed {Email} but none of its links could be created; keeping its previous links.", user.UserName, sanitized);
- staleLinks.Clear();
+ droppedLinks.Clear();
}
- foreach (var stale in staleLinks)
+ foreach (var dropped in droppedLinks)
{
- existing.Links.Remove(stale);
- context.EmailClaimLinks.Remove(stale);
- changed = true;
- }
-
- if (existing.Disabled)
- {
- existing.Disabled = false;
+ dropped.State = EmailClaimLinkState.Removed;
changed = true;
}
@@ -1165,11 +1164,11 @@ public class VaultController(
}
var newLinks = new List<EmailClaimLink>();
- foreach (var (manifestId, paused) in desiredManifests)
+ foreach (var (manifestId, state) in desiredManifests)
{
if (TryChargeQuota(manifestId))
{
- newLinks.Add(new EmailClaimLink { VaultManifestId = manifestId, Paused = paused });
+ newLinks.Add(new EmailClaimLink { VaultManifestId = manifestId, State = state });
}
}
@@ -1189,28 +1188,23 @@ public class VaultController(
});
}
- // An address that is no longer pushed loses the links inside the caller's update scope. When that would remove
- // every link, the claim is disabled instead and keeps its links.
- foreach (var claim in userOwnedEmailClaims.Where(x => !x.Disabled && !processed.Contains(x.Address)))
+ // An address that is no longer pushed is dropped by every manifest in the caller's update scope: their links go to
+ // removed, and once that leaves no manifest carrying the address the claim reads as dead. The rows stay behind
+ // as the ownership record, which is what lets the same manifests claim the address back later.
+ foreach (var claim in userOwnedEmailClaims.Where(x => !processed.Contains(x.Address)))
{
- var removable = claim.Links.Where(l => updateScope.Contains(l.VaultManifestId)).ToList();
- if (removable.Count == claim.Links.Count)
+ var droppedLinks = claim.Links.Where(l => l.State != EmailClaimLinkState.Removed && updateScope.Contains(l.VaultManifestId)).ToList();
+ if (droppedLinks.Count == 0)
{
- claim.Disabled = true;
- claim.UpdatedAt = timeProvider.UtcNow;
continue;
}
- foreach (var link in removable)
+ foreach (var link in droppedLinks)
{
- claim.Links.Remove(link);
- context.EmailClaimLinks.Remove(link);
+ link.State = EmailClaimLinkState.Removed;
}
- if (removable.Count > 0)
- {
- claim.UpdatedAt = timeProvider.UtcNow;
- }
+ claim.UpdatedAt = timeProvider.UtcNow;
}
}
@@ -1241,7 +1235,7 @@ public class VaultController(
int currentCount;
if (limit.WindowSeconds == 0)
{
- // Global absolute cap: every claim ever charged to this group (including disabled ones). A claim is charged to every group it is linked into.
+ // Global absolute cap: every claim ever charged to this group. A claim is charged to every group it is linked into.
currentCount = await context.EmailClaimLinks.Where(l => l.VaultManifest.OwnerGroupId == groupId).Select(l => l.EmailClaimId).Distinct().CountAsync();
}
else
diff --git a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs
index b813ad800..d2484a5ad 100644
--- a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs
@@ -25,14 +25,14 @@ public static class EmailAccessHelper
/// <returns>True when the user holds an access key on the alias's manifest.</returns>
public static async Task<bool> CanReadClaimAsync(AliasServerDbContext context, EmailClaim claim, string userId)
{
- // An orphaned claim has no links and therefore no owner: it is a tombstone holding an address, and nobody may read mail for it.
- var linkedManifestIds = await context.EmailClaimLinks.Where(l => l.EmailClaimId == claim.Id).Select(l => l.VaultManifestId).ToListAsync();
+ // Only manifests that carry the alias grant access.
+ var linkedManifestIds = await context.EmailClaimLinks.Where(l => l.EmailClaimId == claim.Id && l.State != EmailClaimLinkState.Removed).Select(l => l.VaultManifestId).ToListAsync();
if (linkedManifestIds.Count == 0)
{
return false;
}
- // Holding any access key on a linked manifest is proof of access: AccountKey on a personal manifest, GrantKey on a shared manifest (owner self-grant and recipient alike).
+ // Holding any access key on a linked manifest is proof of access.
var hasAccessKey = await context.VaultManifestAccessKeys.AnyAsync(k => k.UserId == userId && linkedManifestIds.Contains(k.VaultManifestId));
if (hasAccessKey)
{
@@ -59,11 +59,8 @@ public static class EmailAccessHelper
return [];
}
- // Get the claim links that the user may read through; a dual-claimed address is readable through any one of its links.
- var claims = await context.EmailClaimLinks
- .Where(l => addresses.Contains(l.EmailClaim.Address) && !l.EmailClaim.Disabled)
- .Select(l => new { l.EmailClaim.Address, ManifestId = l.VaultManifestId, l.VaultManifest.OwnerGroupId })
- .ToListAsync();
+ // Get the claim links that the user may read through.
+ var claims = await context.EmailClaimLinks.Where(l => addresses.Contains(l.EmailClaim.Address) && l.State != EmailClaimLinkState.Removed).Select(l => new { l.EmailClaim.Address, ManifestId = l.VaultManifestId, l.VaultManifest.OwnerGroupId }).ToListAsync();
if (claims.Count == 0)
{
return [];
diff --git a/apps/server/AliasVault.Api/Helpers/EmailKeyTable.cs b/apps/server/AliasVault.Api/Helpers/EmailKeyTable.cs
new file mode 100644
index 000000000..0ecfa59a8
--- /dev/null
+++ b/apps/server/AliasVault.Api/Helpers/EmailKeyTable.cs
@@ -0,0 +1,80 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailKeyTable.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Helpers;
+
+using AliasServerDb;
+using AliasVault.Shared.Models.WebApi.V2.Email;
+using Microsoft.EntityFrameworkCore;
+
+/// <summary>
+/// The public keys a caller can decrypt mail with, in specific order so other items in the response can refer to public keys by stable index.
+/// </summary>
+public sealed class EmailKeyTable
+{
+ private readonly Dictionary<Guid, int> indexByKeyId;
+
+ private EmailKeyTable(Dictionary<Guid, int> indexByKeyId, List<string> publicKeys)
+ {
+ this.indexByKeyId = indexByKeyId;
+ PublicKeys = publicKeys;
+ }
+
+ /// <summary>
+ /// Gets the public keys in index order, to be sent as the response-level key table.
+ /// </summary>
+ public List<string> PublicKeys { get; }
+
+ /// <summary>
+ /// Build the key table for the encryption keys the caller holds the private half of.
+ /// </summary>
+ /// <param name="context">Database context.</param>
+ /// <param name="decryptableKeyIds">The encryption key ids resolved by <see cref="EmailAccessHelper.ResolveDecryptableKeyIdsAsync"/>.</param>
+ /// <returns>The key table.</returns>
+ public static async Task<EmailKeyTable> BuildAsync(AliasServerDbContext context, List<Guid> decryptableKeyIds)
+ {
+ var keys = await context.VaultManifestDeliveryKeys
+ .Where(k => decryptableKeyIds.Contains(k.Id))
+ .Select(k => new { k.Id, k.PublicKey })
+ .ToListAsync();
+
+ return Create(keys.Select(k => (k.Id, k.PublicKey)));
+ }
+
+ /// <summary>
+ /// Build the key table from keys that are already loaded.
+ /// </summary>
+ /// <param name="keys">The encryption keys, duplicates allowed.</param>
+ /// <returns>The key table.</returns>
+ public static EmailKeyTable Create(IEnumerable<(Guid Id, string PublicKey)> keys)
+ {
+ // Order by id so the table is deterministic.
+ var ordered = keys.DistinctBy(k => k.Id).OrderBy(k => k.Id).ToList();
+
+ var indexByKeyId = new Dictionary<Guid, int>(ordered.Count);
+ for (var i = 0; i < ordered.Count; i++)
+ {
+ indexByKeyId[ordered[i].Id] = i;
+ }
+
+ return new EmailKeyTable(indexByKeyId, ordered.ConvertAll(k => k.PublicKey));
+ }
+
+ /// <summary>
+ /// Convert the raw decryption keys of a single email into API models that reference this table by index.
+ /// </summary>
+ /// <param name="decryptionKeys">The decryption keys of one email, already filtered to the keys the caller holds.</param>
+ /// <returns>The decryption key API models, ordered by key index.</returns>
+ public List<EmailDecryptionKeyApiModel> ToApiModels(IEnumerable<(Guid VaultManifestDeliveryKeyId, string EncryptedSymmetricKey)> decryptionKeys)
+ {
+ return decryptionKeys
+ .Where(d => indexByKeyId.ContainsKey(d.VaultManifestDeliveryKeyId))
+ .Select(d => new EmailDecryptionKeyApiModel { KeyIndex = indexByKeyId[d.VaultManifestDeliveryKeyId], EncryptedSymmetricKey = d.EncryptedSymmetricKey })
+ .OrderBy(d => d.KeyIndex)
+ .ToList();
+ }
+}
diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
index 97f9f6f66..1282e19f1 100644
--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
@@ -102,9 +102,9 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon
public DbSet<EmailClaimLink> EmailClaimLinks { get; set; }
/// <summary>
- /// Gets or sets the EmailKeyWraps DbSet.
+ /// Gets or sets the EmailDecryptionKeys DbSet.
/// </summary>
- public DbSet<EmailKeyWrap> EmailKeyWraps { get; set; }
+ public DbSet<EmailDecryptionKey> EmailDecryptionKeys { get; set; }
/// <summary>
/// Gets or sets the EmailParts DbSet.
@@ -415,29 +415,30 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon
.HasForeignKey(l => l.VaultManifestId)
.OnDelete(DeleteBehavior.Cascade);
- // The reconcilers and quota checks walk from a manifest to its claimed addresses.
builder.HasIndex(l => new { l.VaultManifestId, l.EmailClaimId });
+ builder.HasIndex(l => l.EmailClaimId).HasFilter("\"State\" <> 'Removed'").HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live");
});
/*
- * Configure EmailKeyWrap - one wrapped symmetric key per (email, delivery key).
+ * Configure EmailDecryptionKey - one encrypted symmetric key per (email, delivery key).
*/
- modelBuilder.Entity<EmailKeyWrap>(builder =>
+ modelBuilder.Entity<EmailDecryptionKey>(builder =>
{
- builder.HasKey(w => new { w.EmailId, w.EncryptionKeyId });
+ builder.HasKey(d => new { d.EmailId, d.VaultManifestDeliveryKeyId });
- builder.HasOne(w => w.Email)
- .WithMany(e => e.Wraps)
- .HasForeignKey(w => w.EmailId)
+ builder.HasOne(d => d.Email)
+ .WithMany(e => e.DecryptionKeys)
+ .HasForeignKey(d => d.EmailId)
.OnDelete(DeleteBehavior.Cascade);
- builder.HasOne(w => w.EncryptionKey)
- .WithMany(k => k.Wraps)
- .HasForeignKey(w => w.EncryptionKeyId)
+ builder.HasOne(d => d.VaultManifestDeliveryKey)
+ .WithMany(k => k.DecryptionKeys)
+ .HasForeignKey(d => d.VaultManifestDeliveryKeyId)
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade);
// The mailbox queries filter emails by the set of keys the caller holds.
- builder.HasIndex(w => new { w.EncryptionKeyId, w.EmailId });
+ builder.HasIndex(d => new { d.VaultManifestDeliveryKeyId, d.EmailId });
});
modelBuilder.Entity<VaultManifestDeliveryKey>(builder =>
diff --git a/apps/server/Databases/AliasServerDb/Email.cs b/apps/server/Databases/AliasServerDb/Email.cs
index 4cbb41b1f..37df31829 100644
--- a/apps/server/Databases/AliasServerDb/Email.cs
+++ b/apps/server/Databases/AliasServerDb/Email.cs
@@ -25,10 +25,10 @@ public class Email
public int Id { get; set; }
/// <summary>
- /// Gets or sets the wrapped copies of the symmetric key the email contents are encrypted with, one per
+ /// Gets or sets the encrypted copies of the symmetric key the email contents are encrypted with, one per
/// manifest that had claimed the alias at delivery time.
/// </summary>
- public virtual List<EmailKeyWrap> Wraps { get; set; } = [];
+ public virtual List<EmailDecryptionKey> DecryptionKeys { get; set; } = [];
/// <summary>
/// Gets or sets the subject of the email.
diff --git a/apps/server/Databases/AliasServerDb/EmailClaim.cs b/apps/server/Databases/AliasServerDb/EmailClaim.cs
index 22d6b9c95..59ee27317 100644
--- a/apps/server/Databases/AliasServerDb/EmailClaim.cs
+++ b/apps/server/Databases/AliasServerDb/EmailClaim.cs
@@ -11,9 +11,9 @@ using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
/// <summary>
-/// EmailClaim object. This object is used to reserve an email address. The claim is linked to every manifest
-/// the alias lives in (see <see cref="Links"/>); a claim whose links are all gone is a tombstone that blocks
-/// re-use of the address on purpose any by design.
+/// EmailClaim object. This object is used to reserve an email address. The claim is linked to every manifest that
+/// has ever held the alias (see <see cref="Links"/>), each link saying whether that manifest still carries it; a
+/// claim whose links are all gone is a tombstone that blocks re-use of the address on purpose and by design.
/// </summary>
[Index(nameof(Address), IsUnique = true)]
public class EmailClaim
@@ -47,14 +47,6 @@ public class EmailClaim
[StringLength(255)]
public string AddressDomain { get; set; } = null!;
- /// <summary>
- /// Gets or sets a value indicating whether the email claim has been disabled. Disabled means that
- /// the email claim was claimed by a user previously, but that user has deleted this alias since.
- /// Incoming emails addressed to dusabled aliases are rejected by the server. However if the user
- /// later claims this alias again it will be automatically re-enabled.
- /// </summary>
- public bool Disabled { get; set; }
-
/// <summary>
/// Gets or sets a value indicating whether this alias has been counted in the anonymized sender bucket
/// of the owner group.
diff --git a/apps/server/Databases/AliasServerDb/EmailKeyWrap.cs b/apps/server/Databases/AliasServerDb/EmailDecryptionKey.cs
similarity index 56%
rename from apps/server/Databases/AliasServerDb/EmailKeyWrap.cs
rename to apps/server/Databases/AliasServerDb/EmailDecryptionKey.cs
index b8f858721..f93859b5f 100644
--- a/apps/server/Databases/AliasServerDb/EmailKeyWrap.cs
+++ b/apps/server/Databases/AliasServerDb/EmailDecryptionKey.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="EmailKeyWrap.cs" company="aliasvault">
+// <copyright file="EmailDecryptionKey.cs" company="aliasvault">
// Copyright (c) aliasvault. All rights reserved.
// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
// </copyright>
@@ -10,31 +10,31 @@ namespace AliasServerDb;
using System.ComponentModel.DataAnnotations.Schema;
/// <summary>
-/// An email is stored once, but the symmetric encryption key is individually wrapped for each manifest that claims this email's alias.
+/// An email is stored once, but the symmetric encryption key is individually encrypted for each manifest that claims this email's alias.
/// </summary>
-public class EmailKeyWrap
+public class EmailDecryptionKey
{
/// <summary>
- /// Gets or sets the email this wrap belongs to.
+ /// Gets or sets the email this decryption key belongs to.
/// </summary>
public int EmailId { get; set; }
/// <summary>
- /// Gets or sets the navigation property to the email this wrap belongs to.
+ /// Gets or sets the navigation property to the email this decryption key belongs to.
/// </summary>
[ForeignKey("EmailId")]
public virtual Email Email { get; set; } = null!;
/// <summary>
- /// Gets or sets the delivery key whose public half encrypted this wrap.
+ /// Gets or sets the manifest delivery key whose public half encrypted this decryption key.
/// </summary>
- public Guid EncryptionKeyId { get; set; }
+ public Guid VaultManifestDeliveryKeyId { get; set; }
/// <summary>
- /// Gets or sets the navigation property to the delivery key whose public half encrypted this wrap.
+ /// Gets or sets the navigation property to the manifest delivery key whose public half encrypted this decryption key.
/// </summary>
- [ForeignKey("EncryptionKeyId")]
- public virtual VaultManifestDeliveryKey EncryptionKey { get; set; } = null!;
+ [ForeignKey("VaultManifestDeliveryKeyId")]
+ public virtual VaultManifestDeliveryKey VaultManifestDeliveryKey { get; set; } = null!;
/// <summary>
/// Gets or sets the email's symmetric key, encrypted with the delivery key's public half.
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiManifest.Designer.cs
similarity index 98%
rename from apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.Designer.cs
rename to apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiManifest.Designer.cs
index d1aa054e4..c615a09dd 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.Designer.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiManifest.Designer.cs
@@ -12,8 +12,8 @@ using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace AliasServerDb.Migrations
{
[DbContext(typeof(AliasServerDbContext))]
- [Migration("20260810154523_AddEmailMultiWrap")]
- partial class AddEmailMultiWrap
+ [Migration("20260810154523_AddEmailMultiManifest")]
+ partial class AddEmailMultiManifest
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
@@ -506,9 +506,6 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
- b.Property<bool>("Disabled")
- .HasColumnType("boolean");
-
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -537,26 +534,30 @@ namespace AliasServerDb.Migrations
b.HasIndex("VaultManifestId", "EmailClaimId");
+ b.HasIndex("EmailClaimId")
+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
+ .HasFilter("\"State\" <> 'Removed'");
+
b.ToTable("EmailClaimLinks");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
- b.Property<Guid>("EncryptionKeyId")
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
.HasColumnType("uuid");
b.Property<string>("EncryptedSymmetricKey")
.IsRequired()
.HasColumnType("text");
- b.HasKey("EmailId", "EncryptionKeyId");
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
- b.HasIndex("EncryptionKeyId", "EmailId");
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
- b.ToTable("EmailKeyWraps");
+ b.ToTable("EmailDecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.Group", b =>
@@ -1511,23 +1512,24 @@ namespace AliasServerDb.Migrations
b.Navigation("VaultManifest");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.HasOne("AliasServerDb.Email", "Email")
- .WithMany("Wraps")
+ .WithMany("DecryptionKeys")
.HasForeignKey("EmailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")
- .WithMany("Wraps")
- .HasForeignKey("EncryptionKeyId")
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Email");
- b.Navigation("EncryptionKey");
+ b.Navigation("VaultManifestDeliveryKey");
});
modelBuilder.Entity("AliasServerDb.GroupMember", b =>
@@ -1695,7 +1697,7 @@ namespace AliasServerDb.Migrations
{
b.Navigation("Attachments");
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -1710,7 +1712,7 @@ namespace AliasServerDb.Migrations
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
{
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
#pragma warning restore 612, 618
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiManifest.cs
similarity index 74%
rename from apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.cs
rename to apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiManifest.cs
index 99118da19..f0cfe2f4b 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiManifest.cs
@@ -8,7 +8,7 @@ namespace AliasServerDb.Migrations
/// <summary>
/// Adds a many-to-many relationship between emails and manifests, allowing an email to be claimed by multiple manifests.
/// </summary>
- public partial class AddEmailMultiWrap : Migration
+ public partial class AddEmailMultiManifest : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
@@ -39,25 +39,25 @@ namespace AliasServerDb.Migrations
});
migrationBuilder.CreateTable(
- name: "EmailKeyWraps",
+ name: "EmailDecryptionKeys",
columns: table => new
{
EmailId = table.Column<int>(type: "integer", nullable: false),
- EncryptionKeyId = table.Column<Guid>(type: "uuid", nullable: false),
+ VaultManifestDeliveryKeyId = table.Column<Guid>(type: "uuid", nullable: false),
EncryptedSymmetricKey = table.Column<string>(type: "text", nullable: false)
},
constraints: table =>
{
- table.PrimaryKey("PK_EmailKeyWraps", x => new { x.EmailId, x.EncryptionKeyId });
+ table.PrimaryKey("PK_EmailDecryptionKeys", x => new { x.EmailId, x.VaultManifestDeliveryKeyId });
table.ForeignKey(
- name: "FK_EmailKeyWraps_Emails_EmailId",
+ name: "FK_EmailDecryptionKeys_Emails_EmailId",
column: x => x.EmailId,
principalTable: "Emails",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
- name: "FK_EmailKeyWraps_VaultManifestDeliveryKeys_EncryptionKeyId",
- column: x => x.EncryptionKeyId,
+ name: "FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId",
+ column: x => x.VaultManifestDeliveryKeyId,
principalTable: "VaultManifestDeliveryKeys",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
@@ -69,15 +69,15 @@ namespace AliasServerDb.Migrations
columns: new[] { "VaultManifestId", "EmailClaimId" });
migrationBuilder.CreateIndex(
- name: "IX_EmailKeyWraps_EncryptionKeyId_EmailId",
- table: "EmailKeyWraps",
- columns: new[] { "EncryptionKeyId", "EmailId" });
+ name: "IX_EmailDecryptionKeys_VaultManifestDeliveryKeyId_EmailId",
+ table: "EmailDecryptionKeys",
+ columns: new[] { "VaultManifestDeliveryKeyId", "EmailId" });
- // Every existing email gets exactly one wrap (its current key), every claim one link (its current
+ // Every existing email gets exactly one decryption key (its current key), every claim one link (its current
// manifest). A tombstoned claim (VaultManifestId already null) simply gets zero links. A disabled claim
// kept its manifest reference purely as an ownership record, which is what 'Removed' now indicates.
migrationBuilder.Sql("""
- INSERT INTO "EmailKeyWraps" ("EmailId", "EncryptionKeyId", "EncryptedSymmetricKey")
+ INSERT INTO "EmailDecryptionKeys" ("EmailId", "VaultManifestDeliveryKeyId", "EncryptedSymmetricKey")
SELECT "Id", "EncryptionKeyId", "EncryptedSymmetricKey" FROM "Emails";
INSERT INTO "EmailClaimLinks" ("EmailClaimId", "VaultManifestId", "State")
@@ -92,11 +92,28 @@ namespace AliasServerDb.Migrations
migrationBuilder.DropColumn(name: "EncryptedSymmetricKey", table: "Emails");
migrationBuilder.DropColumn(name: "EncryptionKeyId", table: "Emails");
migrationBuilder.DropColumn(name: "VaultManifestId", table: "EmailClaims");
+ migrationBuilder.DropColumn(name: "Disabled", table: "EmailClaims");
+ migrationBuilder.Sql("""CREATE INDEX "IX_EmailClaimLinks_EmailClaimId_Live" ON "EmailClaimLinks" ("EmailClaimId") WHERE "State" <> 'Removed';""");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
+ migrationBuilder.Sql("""DROP INDEX IF EXISTS "IX_EmailClaimLinks_EmailClaimId_Live";""");
+
+ migrationBuilder.AddColumn<bool>(
+ name: "Disabled",
+ table: "EmailClaims",
+ type: "boolean",
+ nullable: false,
+ defaultValue: false);
+
+ // Rebuild the roll-up from the links before they are dropped with the table below.
+ migrationBuilder.Sql("""
+ UPDATE "EmailClaims" c
+ SET "Disabled" = NOT EXISTS (SELECT 1 FROM "EmailClaimLinks" l WHERE l."EmailClaimId" = c."Id" AND l."State" <> 'Removed');
+ """);
+
migrationBuilder.AddColumn<string>(
name: "EncryptedSymmetricKey",
table: "Emails",
@@ -116,14 +133,14 @@ namespace AliasServerDb.Migrations
type: "uuid",
nullable: true);
- // Collapse back to one wrap/link per row (the lowest key/manifest id when there are several - the
- // extra wraps are unrepresentable in the singular model and are dropped with the table). An email
- // whose wraps are all gone is undecryptable and cannot be represented either; it is deleted.
+ // Collapse back to one decryption key/link per row (the lowest key/manifest id when there are several - the
+ // extra decryption keys are unrepresentable in the singular model and are dropped with the table). An email
+ // whose decryption keys are all gone is undecryptable and cannot be represented either; it is deleted.
migrationBuilder.Sql("""
UPDATE "Emails" e
- SET "EncryptionKeyId" = w."EncryptionKeyId", "EncryptedSymmetricKey" = w."EncryptedSymmetricKey"
- FROM (SELECT DISTINCT ON ("EmailId") "EmailId", "EncryptionKeyId", "EncryptedSymmetricKey" FROM "EmailKeyWraps" ORDER BY "EmailId", "EncryptionKeyId") w
- WHERE w."EmailId" = e."Id";
+ SET "EncryptionKeyId" = d."VaultManifestDeliveryKeyId", "EncryptedSymmetricKey" = d."EncryptedSymmetricKey"
+ FROM (SELECT DISTINCT ON ("EmailId") "EmailId", "VaultManifestDeliveryKeyId", "EncryptedSymmetricKey" FROM "EmailDecryptionKeys" ORDER BY "EmailId", "VaultManifestDeliveryKeyId") d
+ WHERE d."EmailId" = e."Id";
DELETE FROM "Emails" WHERE "EncryptionKeyId" IS NULL;
@@ -154,7 +171,7 @@ namespace AliasServerDb.Migrations
oldNullable: true);
migrationBuilder.DropTable(name: "EmailClaimLinks");
- migrationBuilder.DropTable(name: "EmailKeyWraps");
+ migrationBuilder.DropTable(name: "EmailDecryptionKeys");
migrationBuilder.CreateIndex(
name: "IX_Emails_EncryptionKeyId",
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.Designer.cs
index aea638238..4ff379c94 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.Designer.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810200139_EmailStorageFormatV2.Designer.cs
@@ -511,9 +511,6 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
- b.Property<bool>("Disabled")
- .HasColumnType("boolean");
-
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -542,26 +539,30 @@ namespace AliasServerDb.Migrations
b.HasIndex("VaultManifestId", "EmailClaimId");
+ b.HasIndex("EmailClaimId")
+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
+ .HasFilter("\"State\" <> 'Removed'");
+
b.ToTable("EmailClaimLinks");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
- b.Property<Guid>("EncryptionKeyId")
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
.HasColumnType("uuid");
b.Property<string>("EncryptedSymmetricKey")
.IsRequired()
.HasColumnType("text");
- b.HasKey("EmailId", "EncryptionKeyId");
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
- b.HasIndex("EncryptionKeyId", "EmailId");
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
- b.ToTable("EmailKeyWraps");
+ b.ToTable("EmailDecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.Group", b =>
@@ -1516,23 +1517,24 @@ namespace AliasServerDb.Migrations
b.Navigation("VaultManifest");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.HasOne("AliasServerDb.Email", "Email")
- .WithMany("Wraps")
+ .WithMany("DecryptionKeys")
.HasForeignKey("EmailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")
- .WithMany("Wraps")
- .HasForeignKey("EncryptionKeyId")
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Email");
- b.Navigation("EncryptionKey");
+ b.Navigation("VaultManifestDeliveryKey");
});
modelBuilder.Entity("AliasServerDb.GroupMember", b =>
@@ -1700,7 +1702,7 @@ namespace AliasServerDb.Migrations
{
b.Navigation("Attachments");
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -1715,7 +1717,7 @@ namespace AliasServerDb.Migrations
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
{
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
#pragma warning restore 612, 618
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260811192745_DropUnusedIdentityTables.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260811192745_DropUnusedIdentityTables.Designer.cs
index 18de1826e..4de37968c 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260811192745_DropUnusedIdentityTables.Designer.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260811192745_DropUnusedIdentityTables.Designer.cs
@@ -473,9 +473,6 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
- b.Property<bool>("Disabled")
- .HasColumnType("boolean");
-
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -504,26 +501,30 @@ namespace AliasServerDb.Migrations
b.HasIndex("VaultManifestId", "EmailClaimId");
+ b.HasIndex("EmailClaimId")
+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
+ .HasFilter("\"State\" <> 'Removed'");
+
b.ToTable("EmailClaimLinks");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
- b.Property<Guid>("EncryptionKeyId")
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
.HasColumnType("uuid");
b.Property<string>("EncryptedSymmetricKey")
.IsRequired()
.HasColumnType("text");
- b.HasKey("EmailId", "EncryptionKeyId");
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
- b.HasIndex("EncryptionKeyId", "EmailId");
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
- b.ToTable("EmailKeyWraps");
+ b.ToTable("EmailDecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.Group", b =>
@@ -1424,23 +1425,24 @@ namespace AliasServerDb.Migrations
b.Navigation("VaultManifest");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.HasOne("AliasServerDb.Email", "Email")
- .WithMany("Wraps")
+ .WithMany("DecryptionKeys")
.HasForeignKey("EmailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")
- .WithMany("Wraps")
- .HasForeignKey("EncryptionKeyId")
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Email");
- b.Navigation("EncryptionKey");
+ b.Navigation("VaultManifestDeliveryKey");
});
modelBuilder.Entity("AliasServerDb.GroupMember", b =>
@@ -1608,7 +1610,7 @@ namespace AliasServerDb.Migrations
{
b.Navigation("Attachments");
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -1623,7 +1625,7 @@ namespace AliasServerDb.Migrations
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
{
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
#pragma warning restore 612, 618
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.Designer.cs
index f0502dcea..310060c74 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.Designer.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.Designer.cs
@@ -473,9 +473,6 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
- b.Property<bool>("Disabled")
- .HasColumnType("boolean");
-
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -504,26 +501,30 @@ namespace AliasServerDb.Migrations
b.HasIndex("VaultManifestId", "EmailClaimId");
+ b.HasIndex("EmailClaimId")
+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
+ .HasFilter("\"State\" <> 'Removed'");
+
b.ToTable("EmailClaimLinks");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
- b.Property<Guid>("EncryptionKeyId")
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
.HasColumnType("uuid");
b.Property<string>("EncryptedSymmetricKey")
.IsRequired()
.HasColumnType("text");
- b.HasKey("EmailId", "EncryptionKeyId");
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
- b.HasIndex("EncryptionKeyId", "EmailId");
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
- b.ToTable("EmailKeyWraps");
+ b.ToTable("EmailDecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.Group", b =>
@@ -1424,23 +1425,24 @@ namespace AliasServerDb.Migrations
b.Navigation("VaultManifest");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.HasOne("AliasServerDb.Email", "Email")
- .WithMany("Wraps")
+ .WithMany("DecryptionKeys")
.HasForeignKey("EmailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")
- .WithMany("Wraps")
- .HasForeignKey("EncryptionKeyId")
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Email");
- b.Navigation("EncryptionKey");
+ b.Navigation("VaultManifestDeliveryKey");
});
modelBuilder.Entity("AliasServerDb.GroupMember", b =>
@@ -1608,7 +1610,7 @@ namespace AliasServerDb.Migrations
{
b.Navigation("Attachments");
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -1623,7 +1625,7 @@ namespace AliasServerDb.Migrations
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
{
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
#pragma warning restore 612, 618
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.cs b/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.cs
index 918a369f5..27576e33c 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260811194817_ReorderTableColumns.cs
@@ -53,8 +53,8 @@ namespace AliasServerDb.Migrations
ALTER TABLE "AliasVaultUsers" DROP CONSTRAINT "FK_AliasVaultUsers_Groups_PersonalGroupId";
ALTER TABLE "EmailAttachments" DROP CONSTRAINT "FK_EmailAttachments_Emails_EmailId";
ALTER TABLE "EmailClaimLinks" DROP CONSTRAINT "FK_EmailClaimLinks_VaultManifests_VaultManifestId";
- ALTER TABLE "EmailKeyWraps" DROP CONSTRAINT "FK_EmailKeyWraps_Emails_EmailId";
- ALTER TABLE "EmailKeyWraps" DROP CONSTRAINT "FK_EmailKeyWraps_VaultManifestDeliveryKeys_EncryptionKeyId";
+ ALTER TABLE "EmailDecryptionKeys" DROP CONSTRAINT "FK_EmailDecryptionKeys_Emails_EmailId";
+ ALTER TABLE "EmailDecryptionKeys" DROP CONSTRAINT "FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId";
ALTER TABLE "GroupMembers" DROP CONSTRAINT "FK_GroupMembers_AliasVaultUsers_UserId";
ALTER TABLE "MobileLoginRequests" DROP CONSTRAINT "FK_MobileLoginRequests_AliasVaultUsers_UserId";
ALTER TABLE "RateLimits" DROP CONSTRAINT "FK_RateLimits_Groups_GroupId";
@@ -534,8 +534,8 @@ namespace AliasServerDb.Migrations
ALTER TABLE "AliasVaultUsers" ADD CONSTRAINT "FK_AliasVaultUsers_Groups_PersonalGroupId" FOREIGN KEY ("PersonalGroupId") REFERENCES "Groups"("Id") ON DELETE RESTRICT;
ALTER TABLE "EmailAttachments" ADD CONSTRAINT "FK_EmailAttachments_Emails_EmailId" FOREIGN KEY ("EmailId") REFERENCES "Emails"("Id") ON DELETE CASCADE;
ALTER TABLE "EmailClaimLinks" ADD CONSTRAINT "FK_EmailClaimLinks_VaultManifests_VaultManifestId" FOREIGN KEY ("VaultManifestId") REFERENCES "VaultManifests"("ManifestId") ON DELETE CASCADE;
- ALTER TABLE "EmailKeyWraps" ADD CONSTRAINT "FK_EmailKeyWraps_Emails_EmailId" FOREIGN KEY ("EmailId") REFERENCES "Emails"("Id") ON DELETE CASCADE;
- ALTER TABLE "EmailKeyWraps" ADD CONSTRAINT "FK_EmailKeyWraps_VaultManifestDeliveryKeys_EncryptionKeyId" FOREIGN KEY ("EncryptionKeyId") REFERENCES "VaultManifestDeliveryKeys"("Id") ON DELETE CASCADE;
+ ALTER TABLE "EmailDecryptionKeys" ADD CONSTRAINT "FK_EmailDecryptionKeys_Emails_EmailId" FOREIGN KEY ("EmailId") REFERENCES "Emails"("Id") ON DELETE CASCADE;
+ ALTER TABLE "EmailDecryptionKeys" ADD CONSTRAINT "FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId" FOREIGN KEY ("VaultManifestDeliveryKeyId") REFERENCES "VaultManifestDeliveryKeys"("Id") ON DELETE CASCADE;
ALTER TABLE "GroupMembers" ADD CONSTRAINT "FK_GroupMembers_AliasVaultUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AliasVaultUsers"("Id") ON DELETE CASCADE;
ALTER TABLE "MobileLoginRequests" ADD CONSTRAINT "FK_MobileLoginRequests_AliasVaultUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AliasVaultUsers"("Id") ON DELETE CASCADE;
ALTER TABLE "RateLimits" ADD CONSTRAINT "FK_RateLimits_Groups_GroupId" FOREIGN KEY ("GroupId") REFERENCES "Groups"("Id") ON DELETE CASCADE;
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260811195539_EmailDetachedParts.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260811195539_EmailDetachedParts.Designer.cs
index c1dee91e5..a9aaece6f 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260811195539_EmailDetachedParts.Designer.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260811195539_EmailDetachedParts.Designer.cs
@@ -473,9 +473,6 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
- b.Property<bool>("Disabled")
- .HasColumnType("boolean");
-
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -504,26 +501,30 @@ namespace AliasServerDb.Migrations
b.HasIndex("VaultManifestId", "EmailClaimId");
+ b.HasIndex("EmailClaimId")
+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
+ .HasFilter("\"State\" <> 'Removed'");
+
b.ToTable("EmailClaimLinks");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
- b.Property<Guid>("EncryptionKeyId")
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
.HasColumnType("uuid");
b.Property<string>("EncryptedSymmetricKey")
.IsRequired()
.HasColumnType("text");
- b.HasKey("EmailId", "EncryptionKeyId");
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
- b.HasIndex("EncryptionKeyId", "EmailId");
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
- b.ToTable("EmailKeyWraps");
+ b.ToTable("EmailDecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailPart", b =>
@@ -1450,23 +1451,24 @@ namespace AliasServerDb.Migrations
b.Navigation("VaultManifest");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.HasOne("AliasServerDb.Email", "Email")
- .WithMany("Wraps")
+ .WithMany("DecryptionKeys")
.HasForeignKey("EmailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")
- .WithMany("Wraps")
- .HasForeignKey("EncryptionKeyId")
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Email");
- b.Navigation("EncryptionKey");
+ b.Navigation("VaultManifestDeliveryKey");
});
modelBuilder.Entity("AliasServerDb.EmailPart", b =>
@@ -1647,7 +1649,7 @@ namespace AliasServerDb.Migrations
b.Navigation("Parts");
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -1662,7 +1664,7 @@ namespace AliasServerDb.Migrations
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
{
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
#pragma warning restore 612, 618
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.Designer.cs
index 8525aa0b3..c01b87bc4 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.Designer.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/20260812141816_AddAnonymizedSenderCounts.Designer.cs
@@ -476,9 +476,6 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
- b.Property<bool>("Disabled")
- .HasColumnType("boolean");
-
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -507,26 +504,30 @@ namespace AliasServerDb.Migrations
b.HasIndex("VaultManifestId", "EmailClaimId");
+ b.HasIndex("EmailClaimId")
+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
+ .HasFilter("\"State\" <> 'Removed'");
+
b.ToTable("EmailClaimLinks");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
- b.Property<Guid>("EncryptionKeyId")
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
.HasColumnType("uuid");
b.Property<string>("EncryptedSymmetricKey")
.IsRequired()
.HasColumnType("text");
- b.HasKey("EmailId", "EncryptionKeyId");
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
- b.HasIndex("EncryptionKeyId", "EmailId");
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
- b.ToTable("EmailKeyWraps");
+ b.ToTable("EmailDecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailPart", b =>
@@ -1459,23 +1460,24 @@ namespace AliasServerDb.Migrations
b.Navigation("VaultManifest");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.HasOne("AliasServerDb.Email", "Email")
- .WithMany("Wraps")
+ .WithMany("DecryptionKeys")
.HasForeignKey("EmailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")
- .WithMany("Wraps")
- .HasForeignKey("EncryptionKeyId")
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Email");
- b.Navigation("EncryptionKey");
+ b.Navigation("VaultManifestDeliveryKey");
});
modelBuilder.Entity("AliasServerDb.EmailPart", b =>
@@ -1656,7 +1658,7 @@ namespace AliasServerDb.Migrations
b.Navigation("Parts");
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -1671,7 +1673,7 @@ namespace AliasServerDb.Migrations
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
{
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
#pragma warning restore 612, 618
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
index 8f0c46682..7a2a3c6fa 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
@@ -77,7 +77,7 @@ namespace AliasServerDb.Migrations
b.HasKey("Id");
- b.ToTable("AdminUsers");
+ b.ToTable("AdminUsers", (string)null);
});
modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>
@@ -158,7 +158,7 @@ namespace AliasServerDb.Migrations
.IsUnique()
.HasDatabaseName("UX_AliasVaultUsers_PersonalGroupId");
- b.ToTable("AliasVaultUsers");
+ b.ToTable("AliasVaultUsers", (string)null);
});
modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>
@@ -200,7 +200,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("UserId");
- b.ToTable("AliasVaultUserRefreshTokens");
+ b.ToTable("AliasVaultUserRefreshTokens", (string)null);
});
modelBuilder.Entity("AliasServerDb.AuthLog", b =>
@@ -277,7 +277,7 @@ namespace AliasServerDb.Migrations
b.HasIndex(new[] { "Username", "Timestamp" }, "IX_Username_Timestamp")
.IsDescending(false, true);
- b.ToTable("AuthLogs");
+ b.ToTable("AuthLogs", (string)null);
});
modelBuilder.Entity("AliasServerDb.BlockedIpRange", b =>
@@ -326,7 +326,7 @@ namespace AliasServerDb.Migrations
b.HasIndex(new[] { "IpRange" }, "IX_BlockedIpRange_IpRange")
.IsUnique();
- b.ToTable("BlockedIpRanges");
+ b.ToTable("BlockedIpRanges", (string)null);
});
modelBuilder.Entity("AliasServerDb.Email", b =>
@@ -407,7 +407,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("To", "DateSystem");
- b.ToTable("Emails");
+ b.ToTable("Emails", (string)null);
});
modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
@@ -443,7 +443,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("EmailId");
- b.ToTable("EmailAttachments");
+ b.ToTable("EmailAttachments", (string)null);
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -473,9 +473,6 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
- b.Property<bool>("Disabled")
- .HasColumnType("boolean");
-
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
@@ -484,7 +481,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("Address")
.IsUnique();
- b.ToTable("EmailClaims");
+ b.ToTable("EmailClaims", (string)null);
});
modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>
@@ -502,28 +499,32 @@ namespace AliasServerDb.Migrations
b.HasKey("EmailClaimId", "VaultManifestId");
+ b.HasIndex("EmailClaimId")
+ .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
+ .HasFilter("\"State\" <> 'Removed'");
+
b.HasIndex("VaultManifestId", "EmailClaimId");
- b.ToTable("EmailClaimLinks");
+ b.ToTable("EmailClaimLinks", (string)null);
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
- b.Property<Guid>("EncryptionKeyId")
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
.HasColumnType("uuid");
b.Property<string>("EncryptedSymmetricKey")
.IsRequired()
.HasColumnType("text");
- b.HasKey("EmailId", "EncryptionKeyId");
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
- b.HasIndex("EncryptionKeyId", "EmailId");
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
- b.ToTable("EmailKeyWraps");
+ b.ToTable("EmailDecryptionKeys", (string)null);
});
modelBuilder.Entity("AliasServerDb.EmailPart", b =>
@@ -549,7 +550,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("EmailId", "PartIndex")
.IsUnique();
- b.ToTable("EmailParts");
+ b.ToTable("EmailParts", (string)null);
});
modelBuilder.Entity("AliasServerDb.Group", b =>
@@ -595,7 +596,7 @@ namespace AliasServerDb.Migrations
b.HasKey("Id");
- b.ToTable("Groups");
+ b.ToTable("Groups", (string)null);
});
modelBuilder.Entity("AliasServerDb.GroupMember", b =>
@@ -628,7 +629,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("GroupId", "UserId")
.IsUnique();
- b.ToTable("GroupMembers");
+ b.ToTable("GroupMembers", (string)null);
});
modelBuilder.Entity("AliasServerDb.Log", b =>
@@ -732,7 +733,7 @@ namespace AliasServerDb.Migrations
b.HasIndex(new[] { "UserId" }, "IX_UserId");
- b.ToTable("MobileLoginRequests");
+ b.ToTable("MobileLoginRequests", (string)null);
});
modelBuilder.Entity("AliasServerDb.RateLimit", b =>
@@ -790,7 +791,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("LimitType", "Enabled");
- b.ToTable("RateLimits");
+ b.ToTable("RateLimits", (string)null);
});
modelBuilder.Entity("AliasServerDb.ServerSetting", b =>
@@ -810,7 +811,7 @@ namespace AliasServerDb.Migrations
b.HasKey("Key");
- b.ToTable("ServerSettings");
+ b.ToTable("ServerSettings", (string)null);
});
modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>
@@ -846,7 +847,7 @@ namespace AliasServerDb.Migrations
b.HasKey("Id");
- b.ToTable("TaskRunnerJobs");
+ b.ToTable("TaskRunnerJobs", (string)null);
});
modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>
@@ -889,7 +890,7 @@ namespace AliasServerDb.Migrations
.HasDatabaseName("UX_UserGrantKeys_User_Primary")
.HasFilter("\"IsPrimary\"");
- b.ToTable("UserGrantKeys");
+ b.ToTable("UserGrantKeys", (string)null);
});
modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>
@@ -943,7 +944,7 @@ namespace AliasServerDb.Migrations
.IsUnique()
.HasDatabaseName("UX_UserUnlockKeys_UserId_Type_Label");
- b.ToTable("UserUnlockKeys");
+ b.ToTable("UserUnlockKeys", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>
@@ -981,7 +982,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("OwnerUserId", "Category");
- b.ToTable("VaultBlobObjects");
+ b.ToTable("VaultBlobObjects", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>
@@ -998,7 +999,7 @@ namespace AliasServerDb.Migrations
b.HasKey("ManifestId", "RevisionNumber", "BlobHash");
- b.ToTable("VaultBlobReferences");
+ b.ToTable("VaultBlobReferences", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>
@@ -1032,7 +1033,7 @@ namespace AliasServerDb.Migrations
b.HasKey("ManifestId", "Category");
- b.ToTable("VaultDataBuckets");
+ b.ToTable("VaultDataBuckets", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>
@@ -1066,7 +1067,7 @@ namespace AliasServerDb.Migrations
b.HasKey("ManifestId", "Category", "RevisionNumber");
- b.ToTable("VaultDataBucketsHistory");
+ b.ToTable("VaultDataBucketsHistory", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultManifest", b =>
@@ -1144,7 +1145,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("OwnerGroupId");
- b.ToTable("VaultManifests");
+ b.ToTable("VaultManifests", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>
@@ -1207,7 +1208,7 @@ namespace AliasServerDb.Migrations
.IsUnique()
.HasDatabaseName("UX_VaultManifestAccessKeys_UserId_Type_Manifest_Version");
- b.ToTable("VaultManifestAccessKeys");
+ b.ToTable("VaultManifestAccessKeys", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
@@ -1242,7 +1243,7 @@ namespace AliasServerDb.Migrations
b.HasIndex("VaultManifestId", "IsPrimary");
- b.ToTable("VaultManifestDeliveryKeys");
+ b.ToTable("VaultManifestDeliveryKeys", (string)null);
});
modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>
@@ -1341,7 +1342,7 @@ namespace AliasServerDb.Migrations
b.HasKey("Id");
- b.ToTable("WorkerServiceStatuses");
+ b.ToTable("WorkerServiceStatuses", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>
@@ -1360,7 +1361,7 @@ namespace AliasServerDb.Migrations
b.HasKey("Id");
- b.ToTable("DataProtectionKeys");
+ b.ToTable("DataProtectionKeys", (string)null);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
@@ -1456,23 +1457,24 @@ namespace AliasServerDb.Migrations
b.Navigation("VaultManifest");
});
- modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
{
b.HasOne("AliasServerDb.Email", "Email")
- .WithMany("Wraps")
+ .WithMany("DecryptionKeys")
.HasForeignKey("EmailId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")
- .WithMany("Wraps")
- .HasForeignKey("EncryptionKeyId")
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Email");
- b.Navigation("EncryptionKey");
+ b.Navigation("VaultManifestDeliveryKey");
});
modelBuilder.Entity("AliasServerDb.EmailPart", b =>
@@ -1653,7 +1655,7 @@ namespace AliasServerDb.Migrations
b.Navigation("Parts");
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
@@ -1668,7 +1670,7 @@ namespace AliasServerDb.Migrations
modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
{
- b.Navigation("Wraps");
+ b.Navigation("DecryptionKeys");
});
#pragma warning restore 612, 618
}
diff --git a/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.cs b/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.cs
index 69c21bea0..7e2fdbb07 100644
--- a/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.cs
+++ b/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.cs
@@ -54,7 +54,7 @@ public class VaultManifestDeliveryKey
public DateTime UpdatedAt { get; set; }
/// <summary>
- /// Gets or sets the collection of email key wraps that were encrypted with this key.
+ /// Gets or sets the collection of email decryption keys that were encrypted with this key.
/// </summary>
- public virtual ICollection<EmailKeyWrap> Wraps { get; set; } = [];
+ public virtual ICollection<EmailDecryptionKey> DecryptionKeys { get; set; } = [];
}
diff --git a/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index 2c27ad4bc..82026a46c 100644
--- a/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/apps/server/Services/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -400,8 +400,8 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
return false;
}
- // Check if the email claim is disabled.
- if (emailClaim.Disabled)
+ // Check whether any vault still carries the alias at all.
+ if (links.All(l => l.State == EmailClaimLinkState.Removed))
{
// Email claim is disabled, so we cannot process this email.
logger.LogInformation(
diff --git a/apps/server/Services/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs b/apps/server/Services/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs
index 3120ec1f5..18c0cf207 100644
--- a/apps/server/Services/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs
+++ b/apps/server/Services/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs
@@ -52,26 +52,14 @@ public class DisabledEmailCleanupTask : IMaintenanceTask
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
var cutoffDate = DateTime.UtcNow.AddDays(-settings.DisabledEmailRetentionDays);
- // Find all aliases that are currently disabled and last modified before the cutoff date.
- var disabledAliasAddresses = await dbContext.EmailClaims
- .Where(x => x.Disabled)
- .Select(x => x.Address)
- .ToListAsync(cancellationToken);
-
- if (disabledAliasAddresses.Count == 0)
- {
- _logger.LogDebug("No disabled aliases found that need cleanup");
- return;
- }
-
- // Delete all emails for these disabled aliases
+ // An alias is dead once no manifest carries it anymore, which is what the absence of a live link says.
var deletedCount = await dbContext.Emails
- .Where(x => disabledAliasAddresses.Contains(x.To) && x.DateSystem <= cutoffDate)
+ .Where(e => e.DateSystem <= cutoffDate && dbContext.EmailClaims.Any(c => c.Address == e.To && !c.Links.Any(l => l.State != EmailClaimLinkState.Removed)))
.ExecuteDeleteAsync(cancellationToken);
if (deletedCount > 0)
{
- _logger.LogInformation("Deleted {Count} emails for {AliasCount} disabled aliases.", deletedCount, disabledAliasAddresses.Count);
+ _logger.LogInformation("Deleted {Count} emails for aliases that no vault carries anymore.", deletedCount);
}
}
}
diff --git a/apps/server/Services/AliasVault.TaskRunner/Tasks/OrphanedEmailCleanupTask.cs b/apps/server/Services/AliasVault.TaskRunner/Tasks/OrphanedEmailCleanupTask.cs
index 272cbd1a0..4c7c21dea 100644
--- a/apps/server/Services/AliasVault.TaskRunner/Tasks/OrphanedEmailCleanupTask.cs
+++ b/apps/server/Services/AliasVault.TaskRunner/Tasks/OrphanedEmailCleanupTask.cs
@@ -11,8 +11,8 @@ using AliasServerDb;
using Microsoft.EntityFrameworkCore;
/// <summary>
-/// A maintenance task that deletes emails whose key wraps are all gone. Wraps cascade away with their manifest's
-/// delivery keys (account deletion, shared folder deletion), and an email without any wrap is permanently
+/// A maintenance task that deletes emails whose decryption keys are all gone. They cascade away with their manifest's
+/// delivery keys (account deletion, shared folder deletion), and an email without any decryption key is permanently
/// undecryptable: nobody holds a key that can open it, so it can be safely deleted.
/// </summary>
public class OrphanedEmailCleanupTask : IMaintenanceTask
@@ -41,9 +41,9 @@ public class OrphanedEmailCleanupTask : IMaintenanceTask
{
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
- // Delete all emails without a single remaining key wrap - attachments cascade with them.
+ // Delete all emails without a single remaining decryption key - attachments cascade with them.
var deletedCount = await dbContext.Emails
- .Where(x => !x.Wraps.Any())
+ .Where(x => !x.DecryptionKeys.Any())
.ExecuteDeleteAsync(cancellationToken);
if (deletedCount > 0)
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs
index 1260cdece..96023a669 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs
@@ -13,8 +13,8 @@ namespace AliasVault.Shared.Models.WebApi.V2.Email;
public class EmailApiModel : EmailApiModelBase
{
/// <summary>
- /// Gets or sets the public keys referenced by this email's wraps. A wrap's
- /// <see cref="EmailKeyWrapApiModel.KeyIndex"/> is its position in this list.
+ /// Gets or sets the public keys referenced by this email's decryption keys. A decryption key's
+ /// <see cref="EmailDecryptionKeyApiModel.KeyIndex"/> is its position in this list.
/// </summary>
public List<string> PublicKeys { get; set; } = [];
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModelBase.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModelBase.cs
index f15afa4d9..264f65a50 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModelBase.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModelBase.cs
@@ -9,7 +9,7 @@ namespace AliasVault.Shared.Models.WebApi.V2.Email;
/// <summary>
/// Represents the base email API model. Decryptability is expressed exclusively through
-/// <see cref="Wraps"/>: one wrapped symmetric key per manifest keypair the caller holds.
+/// <see cref="DecryptionKeys"/>: one encrypted symmetric key per manifest keypair the caller holds.
/// </summary>
public abstract class EmailApiModelBase
{
@@ -64,9 +64,9 @@ public abstract class EmailApiModelBase
public double SecondsAgo { get; set; }
/// <summary>
- /// Gets or sets the wrapped copies of the email's symmetric key the caller can open, one per manifest keypair
+ /// Gets or sets the encrypted copies of the email's symmetric key the caller can decrypt, one per manifest keypair
/// the caller holds (their personal key, plus the delivery key of every shared manifest they can access).
- /// Each wrap names its public key by index into the public key table of the response model.
+ /// Each entry names its public key by index into the public key table of the response model.
/// </summary>
- public List<EmailKeyWrapApiModel> Wraps { get; set; } = [];
+ public List<EmailDecryptionKeyApiModel> DecryptionKeys { get; set; } = [];
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailKeyWrapApiModel.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailDecryptionKeyApiModel.cs
similarity index 76%
rename from apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailKeyWrapApiModel.cs
rename to apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailDecryptionKeyApiModel.cs
index 88bb88ec9..851f1d366 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailKeyWrapApiModel.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailDecryptionKeyApiModel.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="EmailKeyWrapApiModel.cs" company="aliasvault">
+// <copyright file="EmailDecryptionKeyApiModel.cs" company="aliasvault">
// Copyright (c) aliasvault. All rights reserved.
// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
// </copyright>
@@ -8,10 +8,10 @@
namespace AliasVault.Shared.Models.WebApi.V2.Email;
/// <summary>
-/// One wrapped copy of an email's symmetric key. The client picks the wrap whose public key matches a keypair
-/// it holds locally (a personal key or a shared manifest's delivery key) and unwraps with the private half.
+/// One encrypted copy of an email's symmetric key. The client picks the copy whose public key matches a keypair
+/// it holds locally (a personal key or a shared manifest's delivery key) and decrypts it with the private half.
/// </summary>
-public class EmailKeyWrapApiModel
+public class EmailDecryptionKeyApiModel
{
/// <summary>
/// Gets or sets the position of the public key in the response-level public key table. The key itself is sent
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs
index 987692deb..13f70ecde 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs
@@ -23,8 +23,8 @@ public class MailboxApiModel
public bool Subscribed { get; set; }
/// <summary>
- /// Gets or sets the public keys referenced by the wraps of the returned emails, sent once for the whole
- /// response. A wrap's <see cref="EmailKeyWrapApiModel.KeyIndex"/> is its position in this list.
+ /// Gets or sets the public keys referenced by the decryption keys of the returned emails, sent once for the whole
+ /// response. A decryption key's <see cref="EmailDecryptionKeyApiModel.KeyIndex"/> is its position in this list.
/// </summary>
public List<string> PublicKeys { get; set; } = [];
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkResponse.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkResponse.cs
index d561424a0..c814cf5d5 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkResponse.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkResponse.cs
@@ -33,8 +33,8 @@ public class MailboxBulkResponse
public int TotalRecords { get; set; }
/// <summary>
- /// Gets or sets the public keys referenced by the wraps of the returned emails, sent once for the whole
- /// response. A wrap's <see cref="EmailKeyWrapApiModel.KeyIndex"/> is its position in this list.
+ /// Gets or sets the public keys referenced by the decryption keys of the returned emails, sent once for the whole
+ /// response. A decryption key's <see cref="EmailDecryptionKeyApiModel.KeyIndex"/> is its position in this list.
/// </summary>
public List<string> PublicKeys { get; set; } = [];
diff --git a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.cs b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.cs
index bc7a3ca37..646e9e16c 100644
--- a/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.cs
+++ b/apps/server/Tests/AliasVault.E2ETests/Tests/Client/Shard1/EmailDecryptionTests.cs
@@ -8,6 +8,7 @@
namespace AliasVault.E2ETests.Tests.Client.Shard1;
using System.Text;
+using AliasServerDb;
using AliasVault.IntegrationTests.SmtpServer.Helpers;
using MailKit.Net.Smtp;
using MailKit.Security;
@@ -65,7 +66,7 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that the claim was created on the server.
- var claim = await ApiDbContext.UserEmailClaims.Where(x => x.Address == email).FirstOrDefaultAsync();
+ var claim = await ApiDbContext.EmailClaims.Where(x => x.Address == email).FirstOrDefaultAsync();
Assert.That(claim, Is.Not.Null, "Claim for email address not found in database. Check if item creation and claim creation are working correctly.");
// Assert that the users public key was created on the server.
@@ -162,7 +163,7 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that the claim was created on the server.
- var claim = await ApiDbContext.UserEmailClaims.Where(x => x.Address == email).FirstOrDefaultAsync();
+ var claim = await ApiDbContext.EmailClaims.Where(x => x.Address == email).FirstOrDefaultAsync();
Assert.That(claim, Is.Not.Null, "Claim for email address not found in database. Check if item creation and claim creation are working correctly.");
// Assert that the users public key was created on the server.
@@ -304,7 +305,7 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that the claim was created on the server.
- var claim = await ApiDbContext.UserEmailClaims.FirstOrDefaultAsync(x => x.Address == email);
+ var claim = await ApiDbContext.EmailClaims.FirstOrDefaultAsync(x => x.Address == email);
Assert.That(claim, Is.Null, "Claim for unknown email address domain found in database. Check if claim creation domain check is working correctly.");
}
@@ -327,7 +328,7 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that the claim was created on the server.
- var claim = await ApiDbContext.UserEmailClaims.FirstOrDefaultAsync(x => x.Address == email);
+ var claim = await ApiDbContext.EmailClaims.FirstOrDefaultAsync(x => x.Address == email);
Assert.That(claim, Is.Not.Null, "Claim for email address not found in database. Check if item creation and claim creation are working correctly.");
// Login as new user.
@@ -341,7 +342,7 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that still only one claim exists for the email address.
- var claimCount = await ApiDbContext.UserEmailClaims.CountAsync(x => x.Address == email);
+ var claimCount = await ApiDbContext.EmailClaims.CountAsync(x => x.Address == email);
Assert.That(
claimCount,
Is.LessThanOrEqualTo(1),
@@ -374,19 +375,19 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that the claim was created on the server.
- var claim = await ApiDbContext.UserEmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email1);
+ var claim = await ApiDbContext.EmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email1);
Assert.That(claim, Is.Not.Null, "Initial claim for email address not found in database.");
// Step 2: Delete the email claim from the database directly.
// This simulates the scenario where both credentials were created while the API was down
// (offline mode) so no claim exists on the server yet. When the vault syncs, it will send
// both email addresses at once, and the server needs to handle the case-insensitive duplicates.
- var claimToRemove = await ApiDbContext.UserEmailClaims.FirstAsync(x => x.Address == email1);
- ApiDbContext.UserEmailClaims.Remove(claimToRemove);
+ var claimToRemove = await ApiDbContext.EmailClaims.FirstAsync(x => x.Address == email1);
+ ApiDbContext.EmailClaims.Remove(claimToRemove);
await ApiDbContext.SaveChangesAsync();
// Verify claim is gone.
- var claimAfterDelete = await ApiDbContext.UserEmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email1);
+ var claimAfterDelete = await ApiDbContext.EmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email1);
Assert.That(claimAfterDelete, Is.Null, "Claim should have been removed from database.");
// Step 3: Create credential B with the same email but different casing (capital C).
@@ -409,15 +410,15 @@ public class EmailDecryptionTests : ClientPlaywrightTest
// so if we reach here without exception, the vault sync succeeded.
// Step 5: Assert that exactly one email claim exists on the server (normalized to lowercase).
- var claims = await ApiDbContext.UserEmailClaims.AsNoTracking()
+ var claims = await ApiDbContext.EmailClaims.AsNoTracking()
.Where(x => x.Address == email1)
.ToListAsync();
Assert.That(claims, Has.Count.EqualTo(1), "Exactly one email claim should exist for the case-insensitive duplicate email address.");
Assert.That(claims[0].Address, Is.EqualTo(email1), "Email claim should be stored in lowercase.");
- Assert.That(claims[0].Disabled, Is.False, "Email claim should not be disabled.");
+ Assert.That(await IsClaimLiveAsync(claims[0].Id), Is.True, "Email claim should not be disabled.");
// Step 6: Verify no duplicate claims exist with different casing.
- var allClaims = await ApiDbContext.UserEmailClaims.AsNoTracking()
+ var allClaims = await ApiDbContext.EmailClaims.AsNoTracking()
.Where(x => x.AddressLocal == "casedupe" && x.AddressDomain == "example.tld")
.ToListAsync();
Assert.That(allClaims, Has.Count.EqualTo(1), "No duplicate claims with different casing should exist.");
@@ -450,8 +451,8 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that both claims were created on the server.
- var claim1 = await ApiDbContext.UserEmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email1);
- var claim2 = await ApiDbContext.UserEmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email2);
+ var claim1 = await ApiDbContext.EmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email1);
+ var claim2 = await ApiDbContext.EmailClaims.AsNoTracking().FirstOrDefaultAsync(x => x.Address == email2);
Assert.Multiple(() =>
{
Assert.That(claim1, Is.Not.Null, "Claim for email address not found in database. Check if item creation and claim creation are working correctly.");
@@ -459,10 +460,12 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that both claims are not disabled.
+ var claim1Live = await IsClaimLiveAsync(claim1!.Id);
+ var claim2Live = await IsClaimLiveAsync(claim2!.Id);
Assert.Multiple(() =>
{
- Assert.That(claim1.Disabled, Is.False, "Claim for new email address is marked disabled after creation.");
- Assert.That(claim2.Disabled, Is.False, "Claim for new email address is marked disabled after creation.");
+ Assert.That(claim1Live, Is.True, "Claim for new email address is marked disabled after creation.");
+ Assert.That(claim2Live, Is.True, "Claim for new email address is marked disabled after creation.");
});
// Delete the first credential.
@@ -472,12 +475,14 @@ public class EmailDecryptionTests : ClientPlaywrightTest
await Task.Delay(1000);
// Assert that the first claim is now disabled, and second still enabled.
- claim1 = await ApiDbContext.UserEmailClaims.AsNoTracking().FirstAsync(x => x.Address == email1);
- claim2 = await ApiDbContext.UserEmailClaims.AsNoTracking().FirstAsync(x => x.Address == email2);
+ claim1 = await ApiDbContext.EmailClaims.AsNoTracking().FirstAsync(x => x.Address == email1);
+ claim2 = await ApiDbContext.EmailClaims.AsNoTracking().FirstAsync(x => x.Address == email2);
+ claim1Live = await IsClaimLiveAsync(claim1.Id);
+ claim2Live = await IsClaimLiveAsync(claim2.Id);
Assert.Multiple(() =>
{
- Assert.That(claim1.Disabled, Is.True, "Claim for deleted alias is not marked as disabled after deletion.");
- Assert.That(claim2.Disabled, Is.False, "Claim for existing email address is marked disabled after deleting another claim.");
+ Assert.That(claim1Live, Is.False, "Claim for deleted alias is not marked as disabled after deletion.");
+ Assert.That(claim2Live, Is.True, "Claim for existing email address is marked disabled after deleting another claim.");
});
// Create a new credential with the same email as the one that was disabled.
@@ -488,8 +493,8 @@ public class EmailDecryptionTests : ClientPlaywrightTest
});
// Assert that the first email claim is enabled again.
- claim1 = await ApiDbContext.UserEmailClaims.AsNoTracking().FirstAsync(x => x.Address == email1);
- Assert.That(claim1.Disabled, Is.False, "Claim is not marked as (re)enabled when user re-claims it after having previously deleted it.");
+ claim1 = await ApiDbContext.EmailClaims.AsNoTracking().FirstAsync(x => x.Address == email1);
+ Assert.That(await IsClaimLiveAsync(claim1.Id), Is.True, "Claim is not marked as (re)enabled when user re-claims it after having previously deleted it.");
}
/// <summary>
@@ -504,6 +509,17 @@ public class EmailDecryptionTests : ClientPlaywrightTest
await _testHostBuilder.DisposeAsync();
}
+ /// <summary>
+ /// Checks whether an alias is still carried by any vault. There is no disabled flag on the claim: a link that is
+ /// not removed is what says the alias is live, and paused counts as live because the user still has the alias.
+ /// </summary>
+ /// <param name="emailClaimId">The email claim to check.</param>
+ /// <returns>True while at least one manifest still carries the alias.</returns>
+ private async Task<bool> IsClaimLiveAsync(Guid emailClaimId)
+ {
+ return await ApiDbContext.EmailClaimLinks.AsNoTracking().AnyAsync(l => l.EmailClaimId == emailClaimId && l.State != EmailClaimLinkState.Removed);
+ }
+
/// <summary>
/// Sends a message to the SMTP server.
/// </summary>
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
index 9a9186d6f..cce3de3c2 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/SmtpServer/SmtpServerTests.cs
@@ -184,7 +184,7 @@ public class SmtpServerTests
await SendMessageToSmtpServer(message);
// Check if the email is in the database.
- var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Wraps).FirstAsync();
+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.DecryptionKeys).FirstAsync();
// Test non-encrypted fields.
Assert.Multiple(() =>
@@ -376,7 +376,7 @@ public class SmtpServerTests
await SendMessageToSmtpServer(message);
// Check if the email is in the database.
- var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Wraps).FirstAsync();
+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.DecryptionKeys).FirstAsync();
// Test non-encrypted field.
Assert.That(processedEmail.To, Is.EqualTo("[email protected]"));
@@ -416,7 +416,7 @@ public class SmtpServerTests
await SendMessageToSmtpServer(message);
// Check if the email is in the database.
- var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Wraps).FirstAsync();
+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.DecryptionKeys).FirstAsync();
// Test non-encrypted field.
Assert.That(processedEmail.To, Is.EqualTo("[email protected]"));
@@ -465,7 +465,7 @@ public class SmtpServerTests
await SendMessageToSmtpServer(message);
// Retrieve the stored email and verify the unencrypted metadata written at ingest.
- var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Wraps).FirstAsync();
+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.DecryptionKeys).FirstAsync();
var encryptedSourceBytes = processedEmail.MessageSourceBytes;
Assert.Multiple(() =>
{
@@ -533,7 +533,7 @@ public class SmtpServerTests
await SendMessageToSmtpServer(message);
// Check if the email is in the database.
- var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Wraps).FirstAsync();
+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.DecryptionKeys).FirstAsync();
// Decrypt the email and verify the accented characters survived into the preview.
processedEmail = EmailEncryption.DecryptEmail(processedEmail, PrivateKey);
@@ -679,7 +679,7 @@ public class SmtpServerTests
await SendMessageToSmtpServer(message);
- var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Parts).Include(x => x.Wraps).FirstAsync();
+ var processedEmail = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Parts).Include(x => x.DecryptionKeys).FirstAsync();
var storedPart = processedEmail.Parts.Single();
Assert.Multiple(() =>
{
@@ -747,7 +747,7 @@ public class SmtpServerTests
await SendMessageToSmtpServer(message);
- var emails = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Parts).Include(x => x.Wraps).ToListAsync();
+ var emails = await _testHostBuilder.GetDbContext().Emails.Include(x => x.Parts).Include(x => x.DecryptionKeys).ToListAsync();
Assert.That(emails, Has.Count.EqualTo(2));
foreach (var email in emails)
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs
index 61cbbb873..9ef13b7aa 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/Helpers/SeedData.cs
@@ -52,7 +52,7 @@ public static class SeedData
/// Seeds the database with test emails.
/// </summary>
/// <param name="dbContext">The database context.</param>
- /// <param name="encryptionKeyId">The delivery key ID the emails' key wraps reference.</param>
+ /// <param name="encryptionKeyId">The delivery key ID the emails' decryption keys reference.</param>
/// <returns>Task.</returns>
private static async Task SeedEmails(AliasServerDbContext dbContext, Guid encryptionKeyId)
{
@@ -133,7 +133,7 @@ public static class SeedData
/// </summary>
/// <param name="index">The index.</param>
/// <param name="daysOffset">The days offset.</param>
- /// <param name="encryptionKeyId">The delivery key ID the email's key wrap references.</param>
+ /// <param name="encryptionKeyId">The delivery key ID the email's decryption key references.</param>
/// <param name="prefix">The prefix.</param>
/// <returns>Email.</returns>
private static Email CreateTestEmail(int index, int daysOffset, Guid encryptionKeyId, string prefix)
@@ -152,7 +152,7 @@ public static class SeedData
MessagePreview = "Test message",
MessageSourceBytes = Gzip("Test source"),
AttachmentCount = 0,
- Wraps = [new EmailKeyWrap { EncryptionKeyId = encryptionKeyId, EncryptedSymmetricKey = "dummy-key" }],
+ DecryptionKeys = [new EmailDecryptionKey { VaultManifestDeliveryKeyId = encryptionKeyId, EncryptedSymmetricKey = "dummy-key" }],
};
}
@@ -162,7 +162,7 @@ public static class SeedData
/// </summary>
/// <param name="index">The index.</param>
/// <param name="daysOffset">The days offset.</param>
- /// <param name="encryptionKeyId">The delivery key ID the email's key wrap references.</param>
+ /// <param name="encryptionKeyId">The delivery key ID the email's decryption key references.</param>
/// <param name="prefix">The prefix.</param>
/// <returns>Email.</returns>
private static Email CreateLegacyTestEmail(int index, int daysOffset, Guid encryptionKeyId, string prefix)
@@ -182,7 +182,7 @@ public static class SeedData
MessagePreview = "Test message",
MessageSource = "Test source",
Attachments = [new EmailAttachment { Bytes = [1, 2, 3], Filename = "legacy.txt", MimeType = "text/plain", Filesize = 3, Date = DateTime.UtcNow.AddDays(daysOffset) }],
- Wraps = [new EmailKeyWrap { EncryptionKeyId = encryptionKeyId, EncryptedSymmetricKey = "dummy-key" }],
+ DecryptionKeys = [new EmailDecryptionKey { VaultManifestDeliveryKeyId = encryptionKeyId, EncryptedSymmetricKey = "dummy-key" }],
};
}
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
index 5f0b75066..42da56740 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
@@ -640,7 +640,7 @@ public class TaskRunnerTests
/// Creates a base email with static required fields.
/// </summary>
/// <param name="to">The recipient email address.</param>
- /// <param name="deliveryKey">The delivery key the email's key wrap references.</param>
+ /// <param name="deliveryKey">The delivery key the email's decryption key references.</param>
/// <param name="subject">The email subject.</param>
/// <param name="date">The email date.</param>
/// <returns>A new Email object with static fields pre-filled.</returns>
@@ -648,7 +648,7 @@ public class TaskRunnerTests
{
return new Email
{
- Wraps = [new EmailKeyWrap { EncryptionKeyId = deliveryKey.Id, EncryptedSymmetricKey = "n/a" }],
+ DecryptionKeys = [new EmailDecryptionKey { VaultManifestDeliveryKeyId = deliveryKey.Id, EncryptedSymmetricKey = "n/a" }],
From = "n/a",
FromLocal = "n/a",
FromDomain = "n/a",
@@ -738,7 +738,7 @@ public class TaskRunnerTests
foreach (var alias in aliases)
{
// Add 50 random emails for enabled aliases
- if (!alias.Disabled)
+ if (alias.Links.Any(l => l.State != EmailClaimLinkState.Removed))
{
for (int i = 0; i < 50; i++)
{
@@ -806,7 +806,7 @@ public class TaskRunnerTests
// Create user3 with no limit (0 = unlimited)
var user3 = await TestUserSeeder.CreateTestUserAsync(dbContext, "user3", "[email protected]", configureGroup: g => g.MaxEmails = 0);
- // The emails' key wraps all reference user1's delivery key, mirroring the single encryption key used before.
+ // The emails' decryption keys all reference user1's delivery key, mirroring the single encryption key used before.
var deliveryKey = user1.DeliveryKey;
// Create email claims for each user, linked to their personal manifest
@@ -844,7 +844,7 @@ public class TaskRunnerTests
// Create user3 with no age limit (0 = unlimited)
var user3 = await TestUserSeeder.CreateTestUserAsync(dbContext, "user3", "[email protected]", configureGroup: g => g.MaxEmailAgeDays = 0);
- // The emails' key wraps all reference user1's delivery key, mirroring the single encryption key used before.
+ // The emails' decryption keys all reference user1's delivery key, mirroring the single encryption key used before.
var deliveryKey = user1.DeliveryKey;
// Create email claims for each user, linked to their personal manifest
@@ -889,7 +889,7 @@ public class TaskRunnerTests
// Create user without specific limit (0 = use global limit)
var userWithoutLimit = await TestUserSeeder.CreateTestUserAsync(dbContext, "userwithoutLimit", "[email protected]", configureGroup: g => g.MaxEmails = 0);
- // The emails' key wraps all reference the first user's delivery key, mirroring the single encryption key used before.
+ // The emails' decryption keys all reference the first user's delivery key, mirroring the single encryption key used before.
var deliveryKey = userWithLimit.DeliveryKey;
// Create email claims, linked to each user's personal manifest
@@ -929,7 +929,7 @@ public class TaskRunnerTests
u.CreatedAt = DateTime.UtcNow.AddDays(-100);
});
- // The emails' key wraps all reference the active user's delivery key, mirroring the single encryption key used before.
+ // The emails' decryption keys all reference the active user's delivery key, mirroring the single encryption key used before.
var deliveryKey = activeUser.DeliveryKey;
// Create email claims for each user, linked to their personal manifest
@@ -969,7 +969,7 @@ public class TaskRunnerTests
// Create inactive user (no recent activity for 45 days)
var inactiveUser = await TestUserSeeder.CreateTestUserAsync(dbContext, "inactiveuser", "[email protected]", configureUser: u => u.LastActivityDate = DateTime.UtcNow.AddDays(-45));
- // The emails' key wraps all reference the active user's delivery key, mirroring the single encryption key used before.
+ // The emails' decryption keys all reference the active user's delivery key, mirroring the single encryption key used before.
var deliveryKey = activeUser.DeliveryKey;
// Create email claims for each user, linked to their personal manifest
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs b/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs
index 9f65254c6..ef49bd94f 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs
@@ -64,7 +64,7 @@ public static class TestUserSeeder
/// </summary>
/// <param name="vaultManifestId">The manifest that claims the alias.</param>
/// <param name="address">The full email address; the local and domain parts are derived from it.</param>
- /// <param name="disabled">Whether the claim is disabled.</param>
+ /// <param name="disabled">Whether the claim is disabled, i.e. the manifest no longer carries the alias.</param>
/// <param name="createdAt">Optional created/updated timestamp; defaults to now.</param>
/// <returns>The new email claim carrying a single link to the manifest.</returns>
public static EmailClaim CreateEmailClaim(Guid vaultManifestId, string address, bool disabled = false, DateTime? createdAt = null)
@@ -76,10 +76,9 @@ public static class TestUserSeeder
Address = address,
AddressLocal = addressParts[0],
AddressDomain = addressParts[1],
- Disabled = disabled,
CreatedAt = timestamp,
UpdatedAt = timestamp,
- Links = [new EmailClaimLink { VaultManifestId = vaultManifestId }],
+ Links = [new EmailClaimLink { VaultManifestId = vaultManifestId, State = disabled ? EmailClaimLinkState.Removed : EmailClaimLinkState.Active }],
};
}
}
diff --git a/apps/server/Tests/AliasVault.UnitTests/Utilities/EmailEncryptionTests.cs b/apps/server/Tests/AliasVault.UnitTests/Utilities/EmailEncryptionTests.cs
index ad286eab2..cb64390f1 100644
--- a/apps/server/Tests/AliasVault.UnitTests/Utilities/EmailEncryptionTests.cs
+++ b/apps/server/Tests/AliasVault.UnitTests/Utilities/EmailEncryptionTests.cs
@@ -37,8 +37,8 @@ public class EmailEncryptionTests
{
Assert.That(encrypted.MessageSourceBytes, Is.Not.EqualTo(gzippedSource), "MessageSourceBytes should be encrypted at rest.");
Assert.That(encrypted.MessageSource, Is.Null, "The legacy text source column should remain unset for source-only emails.");
- Assert.That(encrypted.Wraps, Has.Count.EqualTo(1));
- Assert.That(encrypted.Wraps[0].EncryptionKeyId, Is.EqualTo(deliveryKey.Id));
+ Assert.That(encrypted.DecryptionKeys, Has.Count.EqualTo(1));
+ Assert.That(encrypted.DecryptionKeys[0].VaultManifestDeliveryKeyId, Is.EqualTo(deliveryKey.Id));
});
var decrypted = EmailEncryption.DecryptEmail(encrypted, RsaEncryptionTests.PrivateKey);
diff --git a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs
index 24a3779e1..88c886758 100644
--- a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs
+++ b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs
@@ -15,10 +15,10 @@ using AliasServerDb;
public static class EmailEncryption
{
/// <summary>
- /// Encrypt the email contents with a fresh symmetric key, wrapped once per recipient manifest's delivery key.
+ /// Encrypt the email contents with a fresh symmetric key, encrypted once per recipient manifest's delivery key.
/// </summary>
/// <param name="email">The plain text email object to encrypt.</param>
- /// <param name="deliveryKeys">The delivery keys of every manifest that claims the alias; each gets its own wrap of the same symmetric key.</param>
+ /// <param name="deliveryKeys">The delivery keys of every manifest that claims the alias; each gets its own encrypted copy of the same symmetric key.</param>
/// <returns>Email object with all sensitive fields encrypted.</returns>
public static Email EncryptEmail(Email email, IReadOnlyCollection<VaultManifestDeliveryKey> deliveryKeys)
{
@@ -68,10 +68,10 @@ public static class EmailEncryption
part.Bytes = Encryption.SymmetricEncrypt(part.Bytes, symmetricKey);
}
- // Wrap the same symmetric key once per recipient manifest's delivery key.
+ // Encrypt the same symmetric key once per recipient manifest's delivery key.
foreach (var deliveryKey in deliveryKeys)
{
- email.Wraps.Add(new EmailKeyWrap { EncryptionKeyId = deliveryKey.Id, EncryptedSymmetricKey = Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, deliveryKey.PublicKey) });
+ email.DecryptionKeys.Add(new EmailDecryptionKey { VaultManifestDeliveryKeyId = deliveryKey.Id, EncryptedSymmetricKey = Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, deliveryKey.PublicKey) });
}
return email;
@@ -85,25 +85,25 @@ public static class EmailEncryption
/// <returns>Email object with all sensitive fields decrypted.</returns>
public static Email DecryptEmail(Email email, string userPrivateKey)
{
- // Decrypt the symmetric key from the wrap belonging to this private key; with multiple wraps the
+ // Decrypt the symmetric key belonging to this private key; with multiple decryption keys the
// matching one is found by simply trying each.
byte[]? symmetricKey = null;
- foreach (var wrap in email.Wraps)
+ foreach (var decryptionKey in email.DecryptionKeys)
{
try
{
- symmetricKey = Encryption.DecryptSymmetricKeyWithRsa(wrap.EncryptedSymmetricKey, userPrivateKey);
+ symmetricKey = Encryption.DecryptSymmetricKeyWithRsa(decryptionKey.EncryptedSymmetricKey, userPrivateKey);
break;
}
catch (System.Security.Cryptography.CryptographicException)
{
- // Wrap belongs to another manifest's key; try the next one.
+ // The key belongs to another manifest; try the next one.
}
}
if (symmetricKey is null)
{
- throw new InvalidOperationException("The email carries no wrap that the provided private key can open.");
+ throw new InvalidOperationException("The email carries no decryption key that the provided private key can open.");
}
// Encrypt all email contents with the symmetric key.
diff --git a/core/models/src/webapi/Email.ts b/core/models/src/webapi/Email.ts
index 69848754c..efb473856 100644
--- a/core/models/src/webapi/Email.ts
+++ b/core/models/src/webapi/Email.ts
@@ -1,5 +1,5 @@
import { EmailAttachment } from "./EmailAttachment";
-import { EmailKeyWrap } from "./EmailKeyWrap";
+import { EmailDecryptionKey } from "./EmailDecryptionKey";
export type Email = {
/** The raw RFC 822 source of the email message (ciphertext, base64) */
@@ -38,8 +38,11 @@ export type Email = {
/** The number of seconds ago the email was received */
secondsAgo: number;
- /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */
- wraps: EmailKeyWrap[];
+ /** The encrypted copies of the email's symmetric key the caller can decrypt, one per manifest keypair the caller holds */
+ decryptionKeys: EmailDecryptionKey[];
+
+ /** The public keys referenced by this email's decryption keys, indexed by EmailDecryptionKey.keyIndex */
+ publicKeys: string[];
/** The attachments of the email */
attachments: EmailAttachment[];
diff --git a/core/models/src/webapi/EmailDecryptionKey.ts b/core/models/src/webapi/EmailDecryptionKey.ts
new file mode 100644
index 000000000..3e276f6af
--- /dev/null
+++ b/core/models/src/webapi/EmailDecryptionKey.ts
@@ -0,0 +1,7 @@
+export type EmailDecryptionKey = {
+ /** Position of the public key in the response-level publicKeys table */
+ keyIndex: number;
+
+ /** The email's symmetric key, encrypted with the public key */
+ encryptedSymmetricKey: string;
+}
diff --git a/core/models/src/webapi/EmailKeyWrap.ts b/core/models/src/webapi/EmailKeyWrap.ts
deleted file mode 100644
index a8e8b985d..000000000
--- a/core/models/src/webapi/EmailKeyWrap.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export type EmailKeyWrap = {
- /** The public key whose private half unwraps this wrap */
- publicKey: string;
-
- /** The email's symmetric key, encrypted with the public key */
- encryptedSymmetricKey: string;
-}
diff --git a/core/models/src/webapi/MailboxBulk.ts b/core/models/src/webapi/MailboxBulk.ts
index 775b8c56d..5e390852a 100644
--- a/core/models/src/webapi/MailboxBulk.ts
+++ b/core/models/src/webapi/MailboxBulk.ts
@@ -17,5 +17,6 @@ export type MailboxBulkResponse = {
currentPage: number;
pageSize: number;
totalRecords: number;
+ publicKeys: string[];
mails: MailboxEmail[];
}
\ No newline at end of file
diff --git a/core/models/src/webapi/MailboxEmail.ts b/core/models/src/webapi/MailboxEmail.ts
index 140377569..4e36cdaff 100644
--- a/core/models/src/webapi/MailboxEmail.ts
+++ b/core/models/src/webapi/MailboxEmail.ts
@@ -1,4 +1,4 @@
-import { EmailKeyWrap } from "./EmailKeyWrap";
+import { EmailDecryptionKey } from "./EmailDecryptionKey";
export type MailboxEmail = {
/** The preview of the email message */
@@ -37,6 +37,6 @@ export type MailboxEmail = {
/** The number of seconds ago the email was received */
secondsAgo: number;
- /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */
- wraps: EmailKeyWrap[];
+ /** The encrypted copies of the email's symmetric key the caller can decrypt, one per manifest keypair the caller holds. */
+ decryptionKeys: EmailDecryptionKey[];
}
\ No newline at end of file
diff --git a/core/models/src/webapi/index.ts b/core/models/src/webapi/index.ts
index 80c056d3c..024dc4a9b 100644
--- a/core/models/src/webapi/index.ts
+++ b/core/models/src/webapi/index.ts
@@ -13,7 +13,7 @@ export * from './MailboxBulk';
export * from './MailboxEmail';
export * from './Email';
export * from './EmailAttachment';
-export * from './EmailKeyWrap';
+export * from './EmailDecryptionKey';
export * from './AuthLog';
export * from './RefreshToken';
export * from './FaviconExtractModel';