Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add multi email encryption (#2159)
Leendert de Borst91574f0d3dc6
diff --git a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.tsindex 6f177f0dc..6b67cae0d 100644--- a/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts+++ b/apps/browser-extension/src/utils/__tests__/EncryptionUtility.crypto.test.ts@@ -32,8 +32,7 @@ async function createMailboxEmail(date: '2026-05-26T00:00:00Z',dateSystem: '2026-05-26T00:00:00Z',secondsAgo: id,- encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey),- encryptionKey: encryptionKey.PublicKey,+ wraps: [{ publicKey: encryptionKey.PublicKey, encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],};}@@ -58,8 +57,7 @@ async function createEmail(date: '2026-05-26T00:00:00Z',dateSystem: '2026-05-26T00:00:00Z',secondsAgo: 1,- encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey),- encryptionKey: encryptionKey.PublicKey,+ wraps: [{ publicKey: encryptionKey.PublicKey, encryptedSymmetricKey: await EncryptionUtility.encryptWithPublicKey(rawSymmetricKey, encryptionKey.PublicKey) }],attachments: [],};}diff --git a/apps/browser-extension/src/utils/dist/core/models/vault/index.d.ts b/apps/browser-extension/src/utils/dist/core/models/vault/index.d.tsindex da0241ab8..546c008ba 100644--- a/apps/browser-extension/src/utils/dist/core/models/vault/index.d.ts+++ b/apps/browser-extension/src/utils/dist/core/models/vault/index.d.ts@@ -120,7 +120,10 @@ declare const TOTP_SUPPORTED_ALGORITHMS: readonly ["SHA1", "SHA256", "SHA512"];*/declare function normalizeTotpAlgorithm(value: string | null | undefined): string;/**- * Normalizes a raw `digits` value to a supported code length (6-10), falling back to {@link TOTP_DEFAULT_DIGITS}.+ * Normalizes a raw `digits` value to a supported code length, falling back to {@link TOTP_DEFAULT_DIGITS}.+ *+ * The 6-8 range is what the authenticator ecosystem actually issues, and it keeps the modulo below 2^32+ * so the native generators can compute it in a 32-bit integer without overflowing.** @param value - Raw digits value, e.g. "8" or undefined* @returns A usable digit countdiff --git a/apps/browser-extension/src/utils/dist/core/models/vault/index.js b/apps/browser-extension/src/utils/dist/core/models/vault/index.jsindex ac22860f2..90782efcc 100644--- a/apps/browser-extension/src/utils/dist/core/models/vault/index.js+++ b/apps/browser-extension/src/utils/dist/core/models/vault/index.js@@ -13,7 +13,7 @@ function normalizeTotpAlgorithm(value) {}function normalizeTotpDigits(value) {const parsed = typeof value === "number" ? value : parseInt(String(value ?? ""), 10);- return Number.isInteger(parsed) && parsed >= 6 && parsed <= 10 ? parsed : TOTP_DEFAULT_DIGITS;+ return Number.isInteger(parsed) && parsed >= 6 && parsed <= 8 ? parsed : TOTP_DEFAULT_DIGITS;}function normalizeTotpPeriod(value) {const parsed = typeof value === "number" ? value : parseInt(String(value ?? ""), 10);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.tsindex b8ffc588e..baebb60e1 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,6 +139,13 @@ type ValidateLoginResponse = {serverSessionProof: string;};+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;+};+type MailboxEmail = {/** The preview of the email message */messagePreview: string;@@ -164,13 +171,8 @@ type MailboxEmail = {dateSystem: string;/** The number of seconds ago the email was received */secondsAgo: number;- /**- * The encrypted symmetric key which was used to encrypt the email message.- * This key is encrypted with the public key of the user.- */- encryptedSymmetricKey: string;- /** The public key of the user used to encrypt the symmetric key */- encryptionKey: string;+ /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */+ wraps: EmailKeyWrap[];};/**@@ -235,13 +237,8 @@ type Email = {dateSystem: string;/** The number of seconds ago the email was received */secondsAgo: number;- /**- * The encrypted symmetric key which was used to encrypt the email message.- * This key is encrypted with the public key of the user.- */- encryptedSymmetricKey: string;- /** The public key of the user used to encrypt the symmetric key */- encryptionKey: string;+ /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */+ wraps: EmailKeyWrap[];/** The attachments of the email */attachments: EmailAttachment[];};@@ -531,4 +528,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 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 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 };diff --git a/apps/mobile-app/utils/dist/core/models/vault/index.d.ts b/apps/mobile-app/utils/dist/core/models/vault/index.d.tsindex da0241ab8..546c008ba 100644--- a/apps/mobile-app/utils/dist/core/models/vault/index.d.ts+++ b/apps/mobile-app/utils/dist/core/models/vault/index.d.ts@@ -120,7 +120,10 @@ declare const TOTP_SUPPORTED_ALGORITHMS: readonly ["SHA1", "SHA256", "SHA512"];*/declare function normalizeTotpAlgorithm(value: string | null | undefined): string;/**- * Normalizes a raw `digits` value to a supported code length (6-10), falling back to {@link TOTP_DEFAULT_DIGITS}.+ * Normalizes a raw `digits` value to a supported code length, falling back to {@link TOTP_DEFAULT_DIGITS}.+ *+ * The 6-8 range is what the authenticator ecosystem actually issues, and it keeps the modulo below 2^32+ * so the native generators can compute it in a 32-bit integer without overflowing.** @param value - Raw digits value, e.g. "8" or undefined* @returns A usable digit countdiff --git a/apps/mobile-app/utils/dist/core/models/vault/index.js b/apps/mobile-app/utils/dist/core/models/vault/index.jsindex ac22860f2..90782efcc 100644--- a/apps/mobile-app/utils/dist/core/models/vault/index.js+++ b/apps/mobile-app/utils/dist/core/models/vault/index.js@@ -13,7 +13,7 @@ function normalizeTotpAlgorithm(value) {}function normalizeTotpDigits(value) {const parsed = typeof value === "number" ? value : parseInt(String(value ?? ""), 10);- return Number.isInteger(parsed) && parsed >= 6 && parsed <= 10 ? parsed : TOTP_DEFAULT_DIGITS;+ return Number.isInteger(parsed) && parsed >= 6 && parsed <= 8 ? parsed : TOTP_DEFAULT_DIGITS;}function normalizeTotpPeriod(value) {const parsed = typeof value === "number" ? value : parseInt(String(value ?? ""), 10);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.tsindex b8ffc588e..baebb60e1 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,6 +139,13 @@ type ValidateLoginResponse = {serverSessionProof: string;};+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;+};+type MailboxEmail = {/** The preview of the email message */messagePreview: string;@@ -164,13 +171,8 @@ type MailboxEmail = {dateSystem: string;/** The number of seconds ago the email was received */secondsAgo: number;- /**- * The encrypted symmetric key which was used to encrypt the email message.- * This key is encrypted with the public key of the user.- */- encryptedSymmetricKey: string;- /** The public key of the user used to encrypt the symmetric key */- encryptionKey: string;+ /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */+ wraps: EmailKeyWrap[];};/**@@ -235,13 +237,8 @@ type Email = {dateSystem: string;/** The number of seconds ago the email was received */secondsAgo: number;- /**- * The encrypted symmetric key which was used to encrypt the email message.- * This key is encrypted with the public key of the user.- */- encryptedSymmetricKey: string;- /** The public key of the user used to encrypt the symmetric key */- encryptionKey: string;+ /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */+ wraps: EmailKeyWrap[];/** The attachments of the email */attachments: EmailAttachment[];};@@ -531,4 +528,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 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 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 };diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.csindex 1132102d5..6d519b6ce 100644--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs@@ -52,7 +52,6 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U// See if this user has a valid claim to the email address.var emailClaim = await context.EmailClaims- .Include(x => x.VaultManifest).FirstOrDefaultAsync(x => x.Address == sanitizedEmail);if (emailClaim is null || emailClaim.Disabled)@@ -67,8 +66,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U});}- // An orphaned claim (no manifest) has no owner, so it matches nobody.- if (emailClaim.VaultManifest?.OwnerGroupId != user.PersonalGroupId)+ var hasPersonalLink = await context.EmailClaimLinks.AnyAsync(l => l.EmailClaimId == emailClaim.Id && l.VaultManifest.OwnerGroupId == user.PersonalGroupId);+ if (!hasPersonalLink){return BadRequest(new ApiErrorResponse{@@ -80,8 +79,13 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U});}+ var personalKeyIds = await context.VaultManifestDeliveryKeys+ .Where(k => context.VaultManifests.Any(m => m.ManifestId == k.VaultManifestId && m.OwnerGroupId == user.PersonalGroupId))+ .Select(k => k.Id)+ .ToListAsync();+// Retrieve emails from database (excluding any received after a shadow-block took effect).- var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail);+ var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.Wraps.Any(w => personalKeyIds.Contains(w.EncryptionKeyId)));if (shadowCutoff is not null){emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);@@ -101,8 +105,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UDateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,MessagePreview = x.MessagePreview ?? string.Empty,- EncryptedSymmetricKey = x.EncryptedSymmetricKey,- EncryptionKey = x.EncryptionKey.PublicKey,+ 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(),}).OrderByDescending(x => x.DateSystem).Take(50)@@ -142,9 +146,16 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, Umodel.PageSize = Math.Min(model.PageSize, 50);// Load all email addresses that the user has a claim to where the address is in the list.- var validAddresses = await context.EmailClaims- .Where(claim => model.Addresses.Contains(claim.Address) && !claim.Disabled && claim.VaultManifest!.OwnerGroupId == user.PersonalGroupId)- .Select(claim => claim.Address)+ var validAddresses = await context.EmailClaimLinks+ .Where(l => model.Addresses.Contains(l.EmailClaim.Address) && !l.EmailClaim.Disabled && 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.+ 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 page = Math.Max(model.Page, 1);@@ -157,7 +168,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UFROM unnest(@addresses) AS addr(email)CROSS JOIN LATERAL (SELECT * FROM ""Emails"" AS e2- WHERE e2.""To"" = addr.email{cutoffClause}+ WHERE e2.""To"" = addr.email AND EXISTS (SELECT 1 FROM ""EmailKeyWraps"" AS w WHERE w.""EmailId"" = e2.""Id"" AND w.""EncryptionKeyId"" = ANY(@keyids)){cutoffClause}ORDER BY e2.""DateSystem"" DESCLIMIT @limit) AS e";@@ -165,6 +176,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UList<NpgsqlParameter> parameters =[new("addresses", validAddresses.ToArray()),+ new("keyids", personalKeyIds.ToArray()),new("limit", page * model.PageSize),];@@ -193,14 +205,14 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UDateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,MessagePreview = x.MessagePreview ?? string.Empty,- EncryptedSymmetricKey = x.EncryptedSymmetricKey,- EncryptionKey = x.EncryptionKey.PublicKey,+ 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(),HasAttachments = x.Attachments.Any(),}).ToListAsync();// Total count for pagination- var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To));+ var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && email.Wraps.Any(w => personalKeyIds.Contains(w.EncryptionKeyId)));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.csindex 0d44e1223..0b8b65600 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, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);+ var (email, personalWrap, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);if (errorResult != null){return errorResult;@@ -57,8 +57,8 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbContMessageHtml = email.MessageHtml,MessagePlain = email.MessagePlain,MessageSource = email.MessageSource,- EncryptedSymmetricKey = email.EncryptedSymmetricKey,- EncryptionKey = email.EncryptionKey.PublicKey,+ EncryptedSymmetricKey = personalWrap!.EncryptedSymmetricKey,+ EncryptionKey = personalWrap.EncryptionKey.PublicKey,};// Add attachment metadata (without the filebytes)@@ -86,7 +86,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont{await using var context = await dbContextFactory.CreateDbContextAsync();- var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);+ var (email, _, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);if (errorResult != null){return errorResult;@@ -119,7 +119,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont{await using var context = await dbContextFactory.CreateDbContextAsync();- var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);+ var (email, _, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);if (errorResult != null){return errorResult;@@ -144,13 +144,13 @@ 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 authenticated user, the email, and an IActionResult if there's an error.</returns>- private async Task<(Email? Email, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)+ /// <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){var user = await GetCurrentUserAsync();if (user is null){- return (null, Unauthorized("Not authenticated."));+ return (null, null, Unauthorized("Not authenticated."));}// Shadow-block: when active, emails received after the block took effect behave as if they do not exist.@@ -159,28 +159,41 @@ 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).FirstOrDefaultAsync(x => x.Id == id);if (email is null){- return (null, NotFound("Email not found."));+ return (null, null, NotFound("Email not found."));}// Hide emails received after a shadow-block took effect.if (shadowCutoff is not null && email.DateSystem > shadowCutoff.Value){- return (null, NotFound());+ return (null, null, NotFound());}// 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.VaultManifest!.OwnerGroupId == user.PersonalGroupId);+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == normalizedEmailAddress && !x.Disabled && x.Links.Any(l => l.VaultManifest.OwnerGroupId == user.PersonalGroupId));if (emailClaim is null){- return (null, Unauthorized("User does not have a claim to this email address."));+ return (null, null, Unauthorized("User does not have a claim to this email address."));}- return (email, null);+ // Serve the wrap 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)+ {+ return (null, null, NotFound("Email not found."));+ }++ return (email, personalWrap, null);}}diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.csindex 6f9ef5afa..900a5570d 100644--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs@@ -398,7 +398,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont// Get list of email claims owned by the user (v1 only supports personal claims in the personal manifest).var userOwnedEmailClaims = await context.EmailClaims- .Where(x => x.VaultManifestId == personalManifestId)+ .Include(x => x.Links)+ .Where(x => x.Links.Any(l => l.VaultManifestId == personalManifestId)).ToListAsync();// Keep track of processed and sanitized email addresses to know which ones still exist.@@ -420,13 +421,13 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbContif (limit.WindowSeconds == 0){// Global absolute cap: every claim ever billed to the caller's group (including disabled ones).- baseCount = await context.EmailClaims.CountAsync(x => x.VaultManifest!.OwnerGroupId == user.PersonalGroupId);+ baseCount = await context.EmailClaimLinks.Where(l => l.VaultManifest.OwnerGroupId == user.PersonalGroupId).Select(l => l.EmailClaimId).Distinct().CountAsync();}else{// Time-based cap: aliases created within the rolling window (create-then-delete still counts).var windowStart = timeProvider.UtcNow.AddSeconds(-limit.WindowSeconds);- baseCount = await context.EmailClaims.CountAsync(x => x.CreatedAt >= windowStart && x.VaultManifest!.OwnerGroupId == user.PersonalGroupId);+ baseCount = await context.EmailClaimLinks.Where(l => l.EmailClaim.CreatedAt >= windowStart && l.VaultManifest.OwnerGroupId == user.PersonalGroupId).Select(l => l.EmailClaimId).Distinct().CountAsync();}limitUsages.Add((limit.MaxCount, baseCount));@@ -500,7 +501,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont{context.EmailClaims.Add(new EmailClaim{- VaultManifestId = personalManifestId,+ Links = [new EmailClaimLink { VaultManifestId = personalManifestId }],Address = sanitizedEmail,AddressLocal = sanitizedEmail.Split('@')[0],AddressDomain = sanitizedEmail.Split('@')[1],@@ -524,8 +525,21 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont{if (!processedEmailAddresses.Contains(existingClaim.Address)){- // Email address is no longer in the new list and has not been disabled yet, so disable it.- existingClaim.Disabled = true;+ // 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;+ }++ foreach (var link in personalLinks)+ {+ existingClaim.Links.Remove(link);+ context.EmailClaimLinks.Remove(link);+ }+existingClaim.UpdatedAt = timeProvider.UtcNow;}}diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.csindex 9b5dc6696..e9ea034ed 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs@@ -11,9 +11,8 @@ using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;using AliasVault.Api.Helpers;using AliasVault.Auth.IpAddress;-using AliasVault.Shared.Models.Spamok;using AliasVault.Shared.Models.WebApi;-using AliasVault.Shared.Models.WebApi.V1.Email;+using AliasVault.Shared.Models.WebApi.V2.Email;using Asp.Versioning;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;@@ -80,9 +79,9 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U});}- // Retrieve emails from database.+ // Retrieve emails from database, restricted to emails carrying a wrap the caller can open.var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);- var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && decryptableKeyIds.Contains(x.EncryptionKeyId));+ var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.Wraps.Any(w => decryptableKeyIds.Contains(w.EncryptionKeyId)));if (shadowCutoff is not null){emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);@@ -102,8 +101,7 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UDateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,MessagePreview = x.MessagePreview ?? string.Empty,- EncryptedSymmetricKey = x.EncryptedSymmetricKey,- EncryptionKey = x.EncryptionKey.PublicKey,+ 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(),}).OrderByDescending(x => x.DateSystem).Take(50)@@ -150,14 +148,14 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U// Restrict to emails this user holds a key for.var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);- // Fetch the newest emails for each address individually.+ // Fetch the newest emails for each address individually, restricted to emails carrying a wrap 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 e2.""EncryptionKeyId"" = ANY(@keyids){cutoffClause}+ WHERE e2.""To"" = addr.email AND EXISTS (SELECT 1 FROM ""EmailKeyWraps"" AS w WHERE w.""EmailId"" = e2.""Id"" AND w.""EncryptionKeyId"" = ANY(@keyids)){cutoffClause}ORDER BY e2.""DateSystem"" DESCLIMIT @limit) AS e";@@ -194,14 +192,13 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UDateSystem = DateTime.SpecifyKind(x.DateSystem, DateTimeKind.Utc),SecondsAgo = (int)DateTime.UtcNow.Subtract(x.DateSystem).TotalSeconds,MessagePreview = x.MessagePreview ?? string.Empty,- EncryptedSymmetricKey = x.EncryptedSymmetricKey,- EncryptionKey = x.EncryptionKey.PublicKey,+ 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.Attachments.Any(),}).ToListAsync();// Count the total number of emails.- var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && decryptableKeyIds.Contains(email.EncryptionKeyId));+ var countQuery = context.Emails.Where(email => validAddresses.Contains(email.To) && email.Wraps.Any(w => decryptableKeyIds.Contains(w.EncryptionKeyId)));if (shadowCutoff is not null){countQuery = countQuery.Where(email => email.DateSystem <= shadowCutoff.Value);diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.csindex df704a1ca..d9cd8d22f 100644--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailController.cs@@ -11,11 +11,12 @@ using AliasServerDb;using AliasVault.Api.Controllers.Abstracts;using AliasVault.Api.Helpers;using AliasVault.Auth.IpAddress;-using AliasVault.Shared.Models.Spamok;+using AliasVault.Shared.Models.WebApi.V2.Email;using Asp.Versioning;using Microsoft.AspNetCore.Identity;using Microsoft.AspNetCore.Mvc;using Microsoft.EntityFrameworkCore;+using AttachmentApiModel = AliasVault.Shared.Models.Spamok.AttachmentApiModel;/// <summary>/// Email controller for retrieving emails from the database.@@ -37,7 +38,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont{await using var context = await dbContextFactory.CreateDbContextAsync();- var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);+ var (email, callerWraps, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);if (errorResult != null){return errorResult;@@ -58,12 +59,11 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbContMessageHtml = email.MessageHtml,MessagePlain = email.MessagePlain,MessageSource = email.MessageSource,- EncryptedSymmetricKey = email.EncryptedSymmetricKey,- EncryptionKey = email.EncryptionKey.PublicKey,+ Wraps = callerWraps.Select(w => new EmailKeyWrapApiModel { PublicKey = w.EncryptionKey.PublicKey, EncryptedSymmetricKey = w.EncryptedSymmetricKey }).ToList(),};// Add attachment metadata (without the filebytes)- var attachments = await context.EmailAttachments.Where(x => x.EmailId == email.Id).Select(x => new AttachmentApiModel()+ var attachments = await context.EmailAttachments.Where(x => x.EmailId == email!.Id).Select(x => new AttachmentApiModel(){Id = x.Id,Email_Id = x.EmailId,@@ -87,7 +87,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont{await using var context = await dbContextFactory.CreateDbContextAsync();- var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);+ var (email, _, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);if (errorResult != null){return errorResult;@@ -120,7 +120,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont{await using var context = await dbContextFactory.CreateDbContextAsync();- var (email, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);+ var (email, _, errorResult) = await AuthenticateAndRetrieveEmailAsync(id, context);if (errorResult != null){return errorResult;@@ -145,13 +145,13 @@ 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 authenticated user, the email, and an IActionResult if there's an error.</returns>- private async Task<(Email? Email, IActionResult? ErrorResult)> AuthenticateAndRetrieveEmailAsync(int id, AliasServerDbContext context)+ /// <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){var user = await GetCurrentUserAsync();if (user is null){- return (null, Unauthorized("Not authenticated."));+ return (null, [], Unauthorized("Not authenticated."));}// Shadow-block: when active, emails received after the block took effect behave as if they do not exist.@@ -160,17 +160,19 @@ 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).FirstOrDefaultAsync(x => x.Id == id);if (email is null){- return (null, NotFound("Email not found."));+ return (null, [], NotFound("Email not found."));}// Hide emails received after a shadow-block took effect.if (shadowCutoff is not null && email.DateSystem > shadowCutoff.Value){- return (null, NotFound());+ return (null, [], NotFound());}// Check if the user has access to the email address.@@ -179,16 +181,17 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbContif (emailClaim is null || !await EmailAccessHelper.CanReadClaimAsync(context, emailClaim, user.Id)){- return (null, Unauthorized("User does not have a claim to this email address."));+ return (null, [], Unauthorized("User does not have a claim to this email address."));}- // Check if the user has access to the email.+ // The email is accessible only through a wrap the caller holds a private key for.var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);- if (!decryptableKeyIds.Contains(email.EncryptionKeyId))+ var callerWraps = email.Wraps.Where(w => decryptableKeyIds.Contains(w.EncryptionKeyId)).OrderBy(w => w.EncryptionKeyId).ToList();+ if (callerWraps.Count == 0){- return (null, NotFound("Email not found."));+ return (null, [], NotFound("Email not found."));}- return (email, null);+ return (email, callerWraps, null);}}diff --git a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs b/apps/server/AliasVault.Api/Controllers/V2/SharingController.csindex d710067f9..52fe15a65 100644--- a/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/SharingController.cs@@ -247,6 +247,14 @@ 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.+ 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();+await context.SaveChangesAsync();return Ok();diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.csindex 9c5c9bd2c..1fa88ba1b 100644--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs@@ -419,10 +419,11 @@ public class VaultController(row.Client = clientHeader;row.UpdatedAt = timeProvider.UtcNow;- // Every manifest counts the aliases the push filed against it, shared manifests included.+ // Every manifest counts the aliases the push filed against it, shared manifests included. One+ // address may be pushed for several manifests at once, so count distinct addresses per manifest.if (model.EmailRouting != null){- row.EmailClaimsCount = model.EmailRouting.EmailAddressList.Count(x => x.ManifestId == row.ManifestId);+ row.EmailClaimsCount = model.EmailRouting.EmailAddressList.Where(x => x.ManifestId == row.ManifestId).Select(x => EmailHelper.SanitizeEmail(x.Address)).Distinct().Count();}if (row.OwnerGroupId == user.PersonalGroupId)@@ -914,7 +915,7 @@ public class VaultController(private async Task<EmailRouting> BuildEmailRoutingAsync(AliasServerDbContext context, AliasVaultUser user){var claims = await context.EmailClaims- .Where(c => !c.Disabled && context.GroupMembers.Any(gm => gm.GroupId == c.VaultManifest!.OwnerGroupId && gm.UserId == user.Id && gm.Role == GroupRole.Owner))+ .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))).Select(c => c.Address).ToListAsync();@@ -979,16 +980,17 @@ public class VaultController(/// </summary>/// <param name="context">Database context.</param>/// <param name="user">The calling user.</param>- /// <param name="routing">The pushed routing data: every claimed address with the manifest it is filed under.</param>+ /// <param name="routing">The pushed routing data: one entry per (address, manifest) pair.</param>private async Task UpdateEmailClaimsAsync(AliasServerDbContext context, AliasVaultUser user, EmailRoutingPush routing){- var claimedManifestIds = routing.EmailAddressList.Select(x => x.ManifestId).Distinct().ToList();- var accessibleManifests = (await ManifestAccessHelper.AccessibleManifests(context, user.Id)- .Where(m => claimedManifestIds.Contains(m.ManifestId))+ var pushedPairs = routing.EmailAddressList.Select(x => new { Address = EmailHelper.SanitizeEmail(x.Address), x.ManifestId }).Distinct().ToList();++ var accessibleManifests = (await ManifestAccessHelper.AccessibleManifests(context, user.Id).Select(m => m.ManifestId).ToListAsync()).ToHashSet();+ var ownedManifests = (await context.VaultManifests+ .Where(m => context.GroupMembers.Any(gm => gm.GroupId == m.OwnerGroupId && gm.UserId == user.Id && gm.Role == GroupRole.Owner)).Select(m => m.ManifestId).ToListAsync()).ToHashSet();-- var ownerGroupByManifest = await GroupHelper.GetOwnerGroupsAsync(context, accessibleManifests);+ var speaksFor = accessibleManifests.Union(ownedManifests).ToHashSet();// Resolved server-side and never read off the push: this is what stops a client filing an alias under a manifest it merely named.var personalManifestId = await GroupHelper.GetPersonalManifestIdAsync(context, user.PersonalGroupId);@@ -998,49 +1000,70 @@ public class VaultController(return;}- // Get the manifests with a delivery key.- var manifestsWithDeliveryKey = (await context.VaultManifestDeliveryKeys- .Where(k => accessibleManifests.Contains(k.VaultManifestId) && k.IsPrimary)- .Select(k => k.VaultManifestId)- .ToListAsync()).ToHashSet();-- var manifestByAddress = new Dictionary<string, Guid>();- foreach (var claimed in routing.EmailAddressList)+ var assertedPairs = new List<(string Address, Guid ManifestId)>();+ foreach (var pair in pushedPairs){- var sanitizedClaimed = EmailHelper.SanitizeEmail(claimed.Address);- if (!accessibleManifests.Contains(claimed.ManifestId))+ if (!accessibleManifests.Contains(pair.ManifestId)){- logger.LogWarning("{User} claimed alias {Email} for manifest {Manifest} they cannot access; filing it under their own personal manifest instead.", user.UserName, sanitizedClaimed, claimed.ManifestId);+ logger.LogWarning("{User} claimed alias {Email} for manifest {Manifest} they cannot access; dropping the pair.", user.UserName, pair.Address, pair.ManifestId);continue;}- manifestByAddress[sanitizedClaimed] = claimed.ManifestId;- if (claimed.ManifestId != personalManifestId.Value && !manifestsWithDeliveryKey.Contains(claimed.ManifestId))- {- logger.LogWarning("{User} claimed shared alias {Email} for manifest {Manifest} with no published delivery key; its mail stays readable by the routing owner alone until a delivery key is published.", user.UserName, sanitizedClaimed, claimed.ManifestId);- }+ assertedPairs.Add((pair.Address, pair.ManifestId));}- var newEmailAddresses = routing.EmailAddressList- .Select(x => EmailHelper.SanitizeEmail(x.Address))- .Distinct()- .ToList();+ var assertedManifestIds = assertedPairs.Select(p => p.ManifestId).Distinct().ToList();+ var ownerGroupByManifest = await GroupHelper.GetOwnerGroupsAsync(context, assertedManifestIds);++ // Warn when a shared manifest claims aliases without a published delivery key: it gets no wrap for its mail until one is published.+ var manifestsWithDeliveryKey = (await context.VaultManifestDeliveryKeys+ .Where(k => assertedManifestIds.Contains(k.VaultManifestId) && k.IsPrimary)+ .Select(k => k.VaultManifestId)+ .ToListAsync()).ToHashSet();+ foreach (var (address, manifestId) in assertedPairs.Where(p => 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);+ }++ var desiredByAddress = assertedPairs.GroupBy(p => p.Address).ToDictionary(g => g.Key, g => g.Select(p => p.ManifestId).ToHashSet());- // Get the claims this push may update: every claim whose manifest is owned by a group the caller owns, plus every claim belonging to a shared manifest they can currently access.+ // Get the claims this push may update: every claim linked to a manifest the caller speaks for.var userOwnedEmailClaims = await context.EmailClaims- .Where(x => context.GroupMembers.Any(gm => gm.GroupId == x.VaultManifest!.OwnerGroupId && gm.UserId == user.Id && gm.Role == GroupRole.Owner)- || (x.VaultManifestId != null && accessibleManifests.Contains(x.VaultManifestId.Value)))+ .Include(c => c.Links)+ .Where(c => c.Links.Any(l => speaksFor.Contains(l.VaultManifestId))).ToListAsync();- var processed = new List<string>();+ var processed = new HashSet<string>();var supportedDomains = config.PrivateEmailDomains;- // Max-alias check: how many new aliases each quota subject (the group owning the manifest) may still create.+ // Max-alias check: how many new aliases each quota subject (the group owning the linked manifest) may still create.var remainingAliases = await GetRemainingAliasAllowancesAsync(context, user, ownerGroupByManifest.Values);var limitLoggedFor = new HashSet<Guid>();- foreach (var email in newEmailAddresses)+ // Check if the caller has enough quota to create a new link for the given manifest.+ bool TryChargeQuota(Guid manifestId)+ {+ var quotaGroupId = ownerGroupByManifest.TryGetValue(manifestId, out var ownerGroupId) ? ownerGroupId : user.PersonalGroupId;+ if (!remainingAliases.TryGetValue(quotaGroupId, out var remaining))+ {+ return true;+ }++ if (remaining <= 0)+ {+ if (limitLoggedFor.Add(quotaGroupId))+ {+ logger.LogWarning("Alias creation limit reached for group {QuotaGroup} (pushed by {User}). Skipping creation of additional aliases charged to it.", quotaGroupId, user.UserName);+ }++ return false;+ }++ remainingAliases[quotaGroupId] = remaining - 1;+ return true;+ }++ foreach (var sanitized in pushedPairs.Select(p => p.Address).Distinct()){- var sanitized = EmailHelper.SanitizeEmail(email);processed.Add(sanitized);if (!new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(sanitized))@@ -1056,59 +1079,81 @@ public class VaultController(continue;}- // Which manifest the alias is filed against: the one the push named when the caller may claim for it, their own personal manifest otherwise.- var resolvedManifestId = manifestByAddress.TryGetValue(sanitized, out var claimedManifestId) ? claimedManifestId : personalManifestId.Value;-- // The quota subject is the group owning that manifest: the shared manifest's group, or the caller's personal group.- var quotaGroupId = ownerGroupByManifest.TryGetValue(resolvedManifestId, out var ownerGroupId) ? ownerGroupId : user.PersonalGroupId;+ // Every pair for this address named a manifest the caller cannot access: nothing is asserted. The+ // address still counts as pushed, so the absence handling below leaves its claim alone.+ if (!desiredByAddress.TryGetValue(sanitized, out var desiredManifestIds) || desiredManifestIds.Count == 0)+ {+ continue;+ }var existing = userOwnedEmailClaims.FirstOrDefault(x => x.Address == sanitized);if (existing != null){+ var changed = false;+ foreach (var manifestId in desiredManifestIds.Where(m => existing.Links.All(l => l.VaultManifestId != m)))+ {+ if (!TryChargeQuota(manifestId))+ {+ continue;+ }++ existing.Links.Add(new EmailClaimLink { EmailClaimId = existing.Id, VaultManifestId = manifestId });+ changed = true;+ }++ var staleLinks = existing.Links.Where(l => speaksFor.Contains(l.VaultManifestId) && !desiredManifestIds.Contains(l.VaultManifestId)).ToList();+ if (staleLinks.Count == existing.Links.Count)+ {+ // 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.+ logger.LogWarning("{User} pushed {Email} but none of its links could be created; keeping its previous links.", user.UserName, sanitized);+ staleLinks.Clear();+ }++ foreach (var stale in staleLinks)+ {+ existing.Links.Remove(stale);+ context.EmailClaimLinks.Remove(stale);+ changed = true;+ }+if (existing.Disabled){existing.Disabled = false;- existing.UpdatedAt = timeProvider.UtcNow;+ changed = true;}- // Re-point the claim when the alias moved into or out of a shared manifest.- if (existing.VaultManifestId != resolvedManifestId)+ if (changed){- existing.VaultManifestId = resolvedManifestId;existing.UpdatedAt = timeProvider.UtcNow;}continue;}- var foreignClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitized);- if (foreignClaim != null)+ // Adding a link to an existing address requires access to one of its current links' manifests.+ if (await context.EmailClaims.AnyAsync(x => x.Address == sanitized)){- // The address already exists: either a genuine attempt on someone else's address, or a shared alias of a manifest this caller cannot access. Neither may touch the claim.logger.LogWarning("{User} tried to claim email already owned by another user: {Email}", user.UserName, sanitized);continue;}- // Once the quota group's max is reached, silently skip creating further aliases charged to it- // (logged once per group for audits), while aliases charged to other groups in the same push carry on.- if (remainingAliases.TryGetValue(quotaGroupId, out var remaining))+ var newLinks = new List<EmailClaimLink>();+ foreach (var manifestId in desiredManifestIds){- if (remaining <= 0)+ if (TryChargeQuota(manifestId)){- if (limitLoggedFor.Add(quotaGroupId))- {- logger.LogWarning("Alias creation limit reached for group {QuotaGroup} (pushed by {User}). Skipping creation of additional aliases charged to it.", quotaGroupId, user.UserName);- }-- continue;+ newLinks.Add(new EmailClaimLink { VaultManifestId = manifestId });}+ }- remainingAliases[quotaGroupId] = remaining - 1;+ if (newLinks.Count == 0)+ {+ continue;}context.EmailClaims.Add(new EmailClaim{- VaultManifestId = resolvedManifestId,+ Links = newLinks,Address = sanitized,AddressLocal = sanitized.Split('@')[0],AddressDomain = sanitized.Split('@')[1],@@ -1117,15 +1162,29 @@ public class VaultController(});}- // Disable claims that were not processed in this push and the user had access to (all active claims should be pushed on every change.)- var disabledClaims = userOwnedEmailClaims.Where(x => !x.Disabled && !processed.Contains(x.Address)).ToList();- foreach (var claim in disabledClaims)+ // An address that is no longer pushed loses the links the caller speaks for. 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))){- claim.Disabled = true;- claim.UpdatedAt = timeProvider.UtcNow;- }+ var removable = claim.Links.Where(l => speaksFor.Contains(l.VaultManifestId)).ToList();+ if (removable.Count == claim.Links.Count)+ {+ claim.Disabled = true;+ claim.UpdatedAt = timeProvider.UtcNow;+ continue;+ }++ foreach (var link in removable)+ {+ claim.Links.Remove(link);+ context.EmailClaimLinks.Remove(link);+ }- context.EmailClaims.UpdateRange(disabledClaims);+ if (removable.Count > 0)+ {+ claim.UpdatedAt = timeProvider.UtcNow;+ }+ }}/// <summary>@@ -1155,14 +1214,14 @@ public class VaultController(int currentCount;if (limit.WindowSeconds == 0){- // Global absolute cap: every claim ever charged to this group (including disabled ones).- currentCount = await context.EmailClaims.CountAsync(x => x.VaultManifest!.OwnerGroupId == groupId);+ // Global absolute cap: every claim ever charged to this group (including disabled ones). 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{// Time-based cap: aliases created within the rolling window (create-then-delete still counts).var windowStart = timeProvider.UtcNow.AddSeconds(-limit.WindowSeconds);- currentCount = await context.EmailClaims.CountAsync(x => x.CreatedAt >= windowStart && x.VaultManifest!.OwnerGroupId == groupId);+ currentCount = await context.EmailClaimLinks.Where(l => l.EmailClaim.CreatedAt >= windowStart && l.VaultManifest.OwnerGroupId == groupId).Select(l => l.EmailClaimId).Distinct().CountAsync();}var allowed = limit.MaxCount - currentCount;diff --git a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.csindex 6a8d9c515..b813ad800 100644--- a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs+++ b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs@@ -25,23 +25,24 @@ 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 manifest and therefore no owner: it is a tombstone holding an address, and nobody may read mail for it.- if (claim.VaultManifestId is null)+ // 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();+ if (linkedManifestIds.Count == 0){return false;}- // Holding any access key on the manifest is proof of access: AccountKey on a personal manifest, GrantKey on a shared manifest (owner self-grant and recipient alike).- var hasAccessKey = await context.VaultManifestAccessKeys.AnyAsync(k => k.UserId == userId && k.VaultManifestId == claim.VaultManifestId);+ // 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).+ var hasAccessKey = await context.VaultManifestAccessKeys.AnyAsync(k => k.UserId == userId && linkedManifestIds.Contains(k.VaultManifestId));if (hasAccessKey){return true;}- // TODO: legacy fallback: pre-KEK/VEK accounts have no AccountKey row on their personal manifest yet, so the manifest being filed- // under their personal group is their only proof of access. Personal groups only: a shared manifest is grants-only, so a group owner+ // TODO: legacy fallback: pre-KEK/VEK accounts have no AccountKey row on their personal manifest yet, so the manifest being linked+ // to their personal group is their only proof of access. Personal groups only: a shared manifest is grants-only, so a group owner// whose grant was revoked must not read its mail. Delete once all clients have migrated.- return await context.VaultManifests.AnyAsync(m => m.ManifestId == claim.VaultManifestId && context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == m.OwnerGroupId));+ return await context.VaultManifests.AnyAsync(m => linkedManifestIds.Contains(m.ManifestId) && context.AliasVaultUsers.Any(u => u.Id == userId && u.PersonalGroupId == m.OwnerGroupId));}/// <summary>@@ -58,10 +59,10 @@ public static class EmailAccessHelperreturn [];}- // Get the claims that the user may read.- var claims = await context.EmailClaims- .Where(claim => addresses.Contains(claim.Address) && !claim.Disabled && claim.VaultManifestId != null)- .Select(claim => new { claim.Address, ManifestId = claim.VaultManifestId!.Value, claim.VaultManifest!.OwnerGroupId })+ // 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();if (claims.Count == 0){@@ -81,7 +82,7 @@ public static class EmailAccessHelper// grant was revoked must not read its mail. TODO: delete once all clients have migrated.var personalGroupId = await GroupHelper.GetPersonalGroupIdAsync(context, userId);- return claims.Where(c => keyedManifestIds.Contains(c.ManifestId) || c.OwnerGroupId == personalGroupId).Select(c => c.Address).ToList();+ return claims.Where(c => keyedManifestIds.Contains(c.ManifestId) || c.OwnerGroupId == personalGroupId).Select(c => c.Address).Distinct().ToList();}/// <summary>diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.csindex fedd4c4d8..bfb703152 100644--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs@@ -120,6 +120,16 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon/// </summary>public DbSet<EmailClaim> EmailClaims { get; set; }+ /// <summary>+ /// Gets or sets the EmailClaimLinks DbSet.+ /// </summary>+ public DbSet<EmailClaimLink> EmailClaimLinks { get; set; }++ /// <summary>+ /// Gets or sets the EmailKeyWraps DbSet.+ /// </summary>+ public DbSet<EmailKeyWrap> EmailKeyWraps { get; set; }+/// <summary>/// Gets or sets the Groups DbSet./// </summary>@@ -411,20 +421,46 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon});/*- * Configure EmailClaim - VaultManifest relationship, the claim's ownership reference.+ * Configure EmailClaimLink - the claim's ownership references.*/- modelBuilder.Entity<EmailClaim>()- .HasOne(e => e.VaultManifest)- .WithMany()- .HasForeignKey(e => e.VaultManifestId)- .OnDelete(DeleteBehavior.SetNull);-- // Configure Email - VaultManifestDeliveryKey relationship- modelBuilder.Entity<Email>()- .HasOne(l => l.EncryptionKey)- .WithMany(c => c.Emails)- .HasForeignKey(l => l.EncryptionKeyId)- .OnDelete(DeleteBehavior.Cascade);+ modelBuilder.Entity<EmailClaimLink>(builder =>+ {+ builder.HasKey(l => new { l.EmailClaimId, l.VaultManifestId });++ builder.HasOne(l => l.EmailClaim)+ .WithMany(c => c.Links)+ .HasForeignKey(l => l.EmailClaimId)+ .OnDelete(DeleteBehavior.Cascade);++ builder.HasOne(l => l.VaultManifest)+ .WithMany()+ .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 });+ });++ /*+ * Configure EmailKeyWrap - one wrapped symmetric key per (email, delivery key).+ */+ modelBuilder.Entity<EmailKeyWrap>(builder =>+ {+ builder.HasKey(w => new { w.EmailId, w.EncryptionKeyId });++ builder.HasOne(w => w.Email)+ .WithMany(e => e.Wraps)+ .HasForeignKey(w => w.EmailId)+ .OnDelete(DeleteBehavior.Cascade);++ builder.HasOne(w => w.EncryptionKey)+ .WithMany(k => k.Wraps)+ .HasForeignKey(w => w.EncryptionKeyId)+ .OnDelete(DeleteBehavior.Cascade);++ // The mailbox queries filter emails by the set of keys the caller holds.+ builder.HasIndex(w => new { w.EncryptionKeyId, w.EmailId });+ });modelBuilder.Entity<VaultManifestDeliveryKey>(builder =>{diff --git a/apps/server/Databases/AliasServerDb/Email.cs b/apps/server/Databases/AliasServerDb/Email.csindex 793722481..2039aaf5e 100644--- a/apps/server/Databases/AliasServerDb/Email.cs+++ b/apps/server/Databases/AliasServerDb/Email.cs@@ -7,8 +7,6 @@namespace AliasServerDb;-using System.ComponentModel.DataAnnotations;-using System.ComponentModel.DataAnnotations.Schema;using Microsoft.EntityFrameworkCore;/// <summary>@@ -27,23 +25,10 @@ public class Emailpublic int Id { get; set; }/// <summary>- /// Gets or sets encryption key foreign key.+ /// Gets or sets the wrapped copies of the symmetric key the email contents are encrypted with, one per+ /// manifest that had claimed the alias at delivery time./// </summary>- [StringLength(255)]- public Guid EncryptionKeyId { get; set; }-- /// <summary>- /// Gets or sets foreign key to the VaultManifestDeliveryKey object which contains the public key used for encrypting- /// the symmetric encryption key.- /// </summary>- [ForeignKey("EncryptionKeyId")]- public virtual VaultManifestDeliveryKey EncryptionKey { get; set; } = null!;-- /// <summary>- /// Gets or sets the encrypted symmetric key which was used to encrypt the email message.- /// This key is encrypted with the public key of the user.- /// </summary>- public string EncryptedSymmetricKey { get; set; } = null!;+ public virtual List<EmailKeyWrap> Wraps { 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.csindex 11753fca3..a0b42edf1 100644--- a/apps/server/Databases/AliasServerDb/EmailClaim.cs+++ b/apps/server/Databases/AliasServerDb/EmailClaim.cs@@ -8,16 +8,14 @@namespace AliasServerDb;using System.ComponentModel.DataAnnotations;-using System.ComponentModel.DataAnnotations.Schema;using Microsoft.EntityFrameworkCore;/// <summary>-/// EmailClaim object. This object is used to reserve an email address. The claim is filed against the manifest-/// the alias lives in (see <see cref="VaultManifestId"/>).+/// 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./// </summary>[Index(nameof(Address), IsUnique = true)]-[Index(nameof(VaultManifestId), nameof(Disabled))]-[Index(nameof(VaultManifestId), nameof(CreatedAt))]public class EmailClaim{/// <summary>@@ -27,15 +25,9 @@ public class EmailClaimpublic Guid Id { get; set; }/// <summary>- /// Gets or sets the manifest this alias lives in (and from which owner group can be derived from).+ /// Gets or sets the manifests this alias lives in (and from which the owner groups can be derived)./// </summary>- public Guid? VaultManifestId { get; set; }-- /// <summary>- /// Gets or sets the navigation property to the manifest this alias lives in.- /// </summary>- [ForeignKey("VaultManifestId")]- public virtual VaultManifest? VaultManifest { get; set; }+ public virtual List<EmailClaimLink> Links { get; set; } = [];/// <summary>/// Gets or sets the full email address.diff --git a/apps/server/Databases/AliasServerDb/EmailClaimLink.cs b/apps/server/Databases/AliasServerDb/EmailClaimLink.csnew file mode 100644index 000000000..cd9a952ea--- /dev/null+++ b/apps/server/Databases/AliasServerDb/EmailClaimLink.cs@@ -0,0 +1,39 @@+//-----------------------------------------------------------------------+// <copyright file="EmailClaimLink.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 AliasServerDb;++using System.ComponentModel.DataAnnotations.Schema;++/// <summary>+/// Links an email claim to one manifest that carries the alias. An address may be claimed by several manifests+/// at once (e.g. a personal and a shared manifest).+/// </summary>+public class EmailClaimLink+{+ /// <summary>+ /// Gets or sets the email claim this link belongs to.+ /// </summary>+ public Guid EmailClaimId { get; set; }++ /// <summary>+ /// Gets or sets the navigation property to the email claim this link belongs to.+ /// </summary>+ [ForeignKey("EmailClaimId")]+ public virtual EmailClaim EmailClaim { get; set; } = null!;++ /// <summary>+ /// Gets or sets the manifest that claims the alias.+ /// </summary>+ public Guid VaultManifestId { get; set; }++ /// <summary>+ /// Gets or sets the navigation property to the manifest that claims the alias.+ /// </summary>+ [ForeignKey("VaultManifestId")]+ public virtual VaultManifest VaultManifest { get; set; } = null!;+}diff --git a/apps/server/Databases/AliasServerDb/EmailKeyWrap.cs b/apps/server/Databases/AliasServerDb/EmailKeyWrap.csnew file mode 100644index 000000000..b8f858721--- /dev/null+++ b/apps/server/Databases/AliasServerDb/EmailKeyWrap.cs@@ -0,0 +1,43 @@+//-----------------------------------------------------------------------+// <copyright file="EmailKeyWrap.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 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.+/// </summary>+public class EmailKeyWrap+{+ /// <summary>+ /// Gets or sets the email this wrap belongs to.+ /// </summary>+ public int EmailId { get; set; }++ /// <summary>+ /// Gets or sets the navigation property to the email this wrap 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.+ /// </summary>+ public Guid EncryptionKeyId { get; set; }++ /// <summary>+ /// Gets or sets the navigation property to the delivery key whose public half encrypted this wrap.+ /// </summary>+ [ForeignKey("EncryptionKeyId")]+ public virtual VaultManifestDeliveryKey EncryptionKey { get; set; } = null!;++ /// <summary>+ /// Gets or sets the email's symmetric key, encrypted with the delivery key's public half.+ /// </summary>+ public string EncryptedSymmetricKey { get; set; } = null!;+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.Designer.csnew file mode 100644index 000000000..caf9021f2--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.Designer.cs@@ -0,0 +1,1713 @@+// <auto-generated />+using System;+using AliasServerDb;+using Microsoft.EntityFrameworkCore;+using Microsoft.EntityFrameworkCore.Infrastructure;+using Microsoft.EntityFrameworkCore.Migrations;+using Microsoft.EntityFrameworkCore.Storage.ValueConversion;+using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;++#nullable disable++namespace AliasServerDb.Migrations+{+ [DbContext(typeof(AliasServerDbContext))]+ [Migration("20260810154523_AddEmailMultiWrap")]+ partial class AddEmailMultiWrap+ {+ /// <inheritdoc />+ protected override void BuildTargetModel(ModelBuilder modelBuilder)+ {+#pragma warning disable 612, 618+ modelBuilder+ .HasAnnotation("ProductVersion", "10.0.10")+ .HasAnnotation("Proxies:ChangeTracking", false)+ .HasAnnotation("Proxies:CheckEquality", false)+ .HasAnnotation("Proxies:LazyLoading", true)+ .HasAnnotation("Relational:MaxIdentifierLength", 63);++ NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder);++ modelBuilder.Entity("AliasServerDb.AdminRole", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("NormalizedName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AdminRoles");+ });++ modelBuilder.Entity("AliasServerDb.AdminUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastPasswordChanged")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AdminUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultRole", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("NormalizedName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("AliasVaultRoles");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<int>("AccessFailedCount")+ .HasColumnType("integer");++ b.Property<bool>("Blocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("BlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ConcurrencyStamp")+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Email")+ .HasColumnType("text");++ b.Property<bool>("EmailConfirmed")+ .HasColumnType("boolean");++ b.Property<DateTime?>("LastActivityDate")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("LockoutEnabled")+ .HasColumnType("boolean");++ b.Property<DateTimeOffset?>("LockoutEnd")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("NormalizedEmail")+ .HasColumnType("text");++ b.Property<string>("NormalizedUserName")+ .HasColumnType("text");++ b.Property<DateTime>("PasswordChangedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("PasswordHash")+ .HasColumnType("text");++ b.Property<Guid>("PersonalGroupId")+ .HasColumnType("uuid");++ b.Property<string>("PhoneNumber")+ .HasColumnType("text");++ b.Property<bool>("PhoneNumberConfirmed")+ .HasColumnType("boolean");++ b.Property<string>("SecurityStamp")+ .HasColumnType("text");++ b.Property<string>("SrpIdentity")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("TwoFactorEnabled")+ .HasColumnType("boolean");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserName")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("PersonalGroupId")+ .IsUnique()+ .HasDatabaseName("UX_AliasVaultUsers_PersonalGroupId");++ b.ToTable("AliasVaultUsers");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("DeviceIdentifier")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("ExpireDate")+ .HasMaxLength(255)+ .HasColumnType("timestamp with time zone");++ b.Property<string>("IpAddress")+ .HasMaxLength(45)+ .HasColumnType("character varying(45)");++ b.Property<string>("PreviousTokenValue")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Value")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.ToTable("AliasVaultUserRefreshTokens");+ });++ modelBuilder.Entity("AliasServerDb.AuthLog", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("AdditionalInfo")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Browser")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Client")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("Country")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("DeviceType")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<int>("EventType")+ .HasColumnType("integer");++ b.Property<int?>("FailureReason")+ .HasColumnType("integer");++ b.Property<string>("IpAddress")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<bool>("IsSuccess")+ .HasColumnType("boolean");++ b.Property<bool>("IsSuspiciousActivity")+ .HasColumnType("boolean");++ b.Property<string>("OperatingSystem")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("RequestPath")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime>("Timestamp")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Username")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex(new[] { "EventType" }, "IX_EventType");++ b.HasIndex(new[] { "IpAddress" }, "IX_IpAddress");++ b.HasIndex(new[] { "Timestamp" }, "IX_Timestamp");++ b.HasIndex(new[] { "Username", "IsSuccess", "Timestamp" }, "IX_Username_IsSuccess_Timestamp")+ .IsDescending(false, false, true);++ b.HasIndex(new[] { "Username", "Timestamp" }, "IX_Username_Timestamp")+ .IsDescending(false, true);++ b.ToTable("AuthLogs");+ });++ modelBuilder.Entity("AliasServerDb.BlockedIpRange", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<bool>("BlockLogin")+ .HasColumnType("boolean");++ b.Property<bool>("BlockRegistration")+ .HasColumnType("boolean");++ b.Property<bool>("BlockShadow")+ .HasColumnType("boolean");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<string>("IpRange")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Reason")+ .HasMaxLength(500)+ .HasColumnType("character varying(500)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex(new[] { "Enabled" }, "IX_BlockedIpRange_Enabled");++ b.HasIndex(new[] { "IpRange" }, "IX_BlockedIpRange_IpRange")+ .IsUnique();++ b.ToTable("BlockedIpRanges");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("DateSystem")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("From")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("FromLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageHtml")+ .HasColumnType("text");++ b.Property<string>("MessagePlain")+ .HasColumnType("text");++ b.Property<string>("MessagePreview")+ .HasColumnType("text");++ b.Property<string>("MessageSource")+ .IsRequired()+ .HasColumnType("text");++ b.Property<bool>("PushNotificationSent")+ .HasColumnType("boolean");++ b.Property<string>("Subject")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("To")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToDomain")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("ToLocal")+ .IsRequired()+ .HasColumnType("text");++ b.Property<bool>("Visible")+ .HasColumnType("boolean");++ b.HasKey("Id");++ b.HasIndex("Date");++ b.HasIndex("DateSystem");++ b.HasIndex("PushNotificationSent");++ b.HasIndex("Visible");++ b.HasIndex("To", "DateSystem");++ b.ToTable("Emails");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<byte[]>("Bytes")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<DateTime>("Date")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<string>("Filename")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("Filesize")+ .HasColumnType("integer");++ b.Property<string>("MimeType")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex("EmailId");++ b.ToTable("EmailAttachments");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Address")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressDomain")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("AddressLocal")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Disabled")+ .HasColumnType("boolean");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Address")+ .IsUnique();++ b.ToTable("EmailClaims");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.Property<Guid>("EmailClaimId")+ .HasColumnType("uuid");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("EmailClaimId", "VaultManifestId");++ b.HasIndex("VaultManifestId", "EmailClaimId");++ b.ToTable("EmailClaimLinks");+ });++ modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>+ {+ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<Guid>("EncryptionKeyId")+ .HasColumnType("uuid");++ b.Property<string>("EncryptedSymmetricKey")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("EmailId", "EncryptionKeyId");++ b.HasIndex("EncryptionKeyId", "EmailId");++ b.ToTable("EmailKeyWraps");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("EmailsReceived")+ .HasColumnType("integer");++ b.Property<int>("MaxEmailAgeDays")+ .HasColumnType("integer");++ b.Property<int>("MaxEmails")+ .HasColumnType("integer");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<bool>("ShadowBlocked")+ .HasColumnType("boolean");++ b.Property<DateTime?>("ShadowBlockedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("Type")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.ToTable("Groups");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("Role")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId");++ b.HasIndex("GroupId", "UserId")+ .IsUnique();++ b.ToTable("GroupMembers");+ });++ modelBuilder.Entity("AliasServerDb.Log", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("Application")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("Exception")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Level")+ .IsRequired()+ .HasMaxLength(128)+ .HasColumnType("character varying(128)");++ b.Property<string>("LogEvent")+ .IsRequired()+ .HasColumnType("text")+ .HasColumnName("LogEvent");++ b.Property<string>("Message")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("MessageTemplate")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Properties")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("SourceContext")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("TimeStamp")+ .HasColumnType("timestamp with time zone");++ b.HasKey("Id");++ b.HasIndex("Application");++ b.HasIndex("TimeStamp");++ b.ToTable("Logs", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.Property<string>("Id")+ .HasColumnType("text");++ b.Property<DateTime?>("ClearedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ClientIpAddress")+ .HasColumnType("text");++ b.Property<string>("ClientPublicKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedDecryptionKey")+ .HasColumnType("text");++ b.Property<DateTime?>("FulfilledAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("MobileIpAddress")+ .HasColumnType("text");++ b.Property<DateTime?>("RetrievedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.HasIndex(new[] { "ClientIpAddress" }, "IX_ClientIpAddress");++ b.HasIndex(new[] { "CreatedAt" }, "IX_CreatedAt");++ b.HasIndex(new[] { "MobileIpAddress" }, "IX_MobileIpAddress");++ b.HasIndex(new[] { "RetrievedAt", "ClearedAt", "FulfilledAt" }, "IX_RetrievedAt_ClearedAt_FulfilledAt");++ b.HasIndex(new[] { "UserId" }, "IX_UserId");++ b.ToTable("MobileLoginRequests");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AppliesToAccountAgeMaxDays")+ .HasColumnType("integer");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("CreatedBy")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime?>("EffectiveFrom")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime?>("EffectiveUntil")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("Enabled")+ .HasColumnType("boolean");++ b.Property<Guid?>("GroupId")+ .HasColumnType("uuid");++ b.Property<int>("LimitType")+ .HasColumnType("integer");++ b.Property<int>("MaxCount")+ .HasColumnType("integer");++ b.Property<string>("Notes")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<int?>("Tier")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("WindowSeconds")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.HasIndex("GroupId");++ b.HasIndex("Tier");++ b.HasIndex("LimitType", "Enabled");++ b.ToTable("RateLimits");+ });++ modelBuilder.Entity("AliasServerDb.ServerSetting", b =>+ {+ b.Property<string>("Key")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("Key");++ b.ToTable("ServerSettings");+ });++ modelBuilder.Entity("AliasServerDb.TaskRunnerJob", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<TimeOnly?>("EndTime")+ .HasColumnType("time without time zone");++ b.Property<string>("ErrorMessage")+ .HasColumnType("text");++ b.Property<bool>("IsOnDemand")+ .HasColumnType("boolean");++ b.Property<string>("Name")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("RunDate")+ .HasColumnType("timestamp with time zone");++ b.Property<TimeOnly>("StartTime")+ .HasColumnType("time without time zone");++ b.Property<int>("Status")+ .HasColumnType("integer");++ b.HasKey("Id");++ b.ToTable("TaskRunnerJobs");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedPrivateKey")+ .IsRequired()+ .HasMaxLength(4000)+ .HasColumnType("character varying(4000)");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId")+ .IsUnique()+ .HasDatabaseName("UX_UserGrantKeys_User_Primary")+ .HasFilter("\"IsPrimary\"");++ b.ToTable("UserGrantKeys");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedAccountKey")+ .IsRequired()+ .HasColumnType("text");++ b.Property<string>("Label")+ .IsRequired()+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.HasIndex("UserId", "Type", "Label")+ .IsUnique()+ .HasDatabaseName("UX_UserUnlockKeys_UserId_Type_Label");++ b.ToTable("UserUnlockKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.Property<string>("Hash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("OwnerUserId")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<string>("Category")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<byte[]>("EncryptedData")+ .IsRequired()+ .HasColumnType("bytea");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("LastReferencedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("SizeBytes")+ .HasColumnType("integer");++ b.HasKey("Hash", "OwnerUserId");++ b.HasIndex("OwnerUserId", "Category");++ b.ToTable("VaultBlobObjects");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("BlobHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.HasKey("ManifestId", "RevisionNumber", "BlobHash");++ b.ToTable("VaultBlobReferences");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedData")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category");++ b.ToTable("VaultDataBuckets");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<string>("Category")+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("CiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedData")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.HasKey("ManifestId", "Category", "RevisionNumber");++ b.ToTable("VaultDataBucketsHistory");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.Property<Guid>("ManifestId")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<string>("ManifestBlob")+ .HasColumnType("text");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Name")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<Guid>("OwnerGroupId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId");++ b.HasIndex("OwnerGroupId");++ b.ToTable("VaultManifests");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<int?>("AccountKeyVersion")+ .HasColumnType("integer");++ b.Property<string>("Algorithm")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("EncryptedVek")+ .IsRequired()+ .HasColumnType("text");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<DateTime?>("LastUsedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("Metadata")+ .HasColumnType("jsonb");++ b.Property<string>("Type")+ .IsRequired()+ .HasMaxLength(30)+ .HasColumnType("character varying(30)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid?>("UserGrantKeyId")+ .HasColumnType("uuid");++ b.Property<string>("UserId")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("UserGrantKeyId");++ b.HasIndex("VaultManifestId")+ .HasDatabaseName("IX_VaultManifestAccessKeys_VaultManifestId");++ b.HasIndex("UserId", "Type", "VaultManifestId", "KeyVersion")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestAccessKeys_UserId_Type_Manifest_Version");++ b.ToTable("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Property<Guid>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("uuid");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<bool>("IsPrimary")+ .HasColumnType("boolean");++ b.Property<string>("PublicKey")+ .IsRequired()+ .HasMaxLength(2000)+ .HasColumnType("character varying(2000)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("Id");++ b.HasIndex("VaultManifestId")+ .IsUnique()+ .HasDatabaseName("UX_VaultManifestDeliveryKeys_Manifest_Primary")+ .HasFilter("\"IsPrimary\"");++ b.HasIndex("VaultManifestId", "IsPrimary");++ b.ToTable("VaultManifestDeliveryKeys");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.Property<Guid>("ManifestId")+ .HasColumnType("uuid");++ b.Property<long>("RevisionNumber")+ .HasColumnType("bigint");++ b.Property<string>("Client")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.Property<DateTime>("CreatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<int>("CredentialsCount")+ .HasColumnType("integer");++ b.Property<int>("EmailClaimsCount")+ .HasColumnType("integer");++ b.Property<string>("EncryptionSettings")+ .HasColumnType("text");++ b.Property<string>("EncryptionType")+ .HasColumnType("text");++ b.Property<int>("FileSize")+ .HasColumnType("integer");++ b.Property<int>("KeyVersion")+ .HasColumnType("integer");++ b.Property<string>("ManifestBlob")+ .HasColumnType("text");++ b.Property<string>("ManifestCiphertextHash")+ .HasMaxLength(64)+ .HasColumnType("character varying(64)");++ b.Property<string>("Salt")+ .HasMaxLength(100)+ .HasColumnType("character varying(100)");++ b.Property<string>("StorageFormat")+ .IsRequired()+ .HasMaxLength(20)+ .HasColumnType("character varying(20)");++ b.Property<DateTime>("UpdatedAt")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("VaultBlob")+ .HasColumnType("text");++ b.Property<string>("Verifier")+ .HasMaxLength(1000)+ .HasColumnType("character varying(1000)");++ b.Property<string>("Version")+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("ManifestId", "RevisionNumber");++ b.ToTable("VaultManifestsHistory", (string)null);+ });++ modelBuilder.Entity("AliasVault.WorkerStatus.Database.WorkerServiceStatus", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("CurrentStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<string>("DesiredStatus")+ .IsRequired()+ .HasMaxLength(50)+ .HasColumnType("character varying(50)");++ b.Property<DateTime>("Heartbeat")+ .HasColumnType("timestamp with time zone");++ b.Property<string>("ServiceName")+ .IsRequired()+ .HasMaxLength(255)+ .HasColumnType("character varying(255)");++ b.HasKey("Id");++ b.ToTable("WorkerServiceStatuses");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("FriendlyName")+ .HasColumnType("text");++ b.Property<string>("Xml")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("DataProtectionKeys");+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("ClaimType")+ .HasColumnType("text");++ b.Property<string>("ClaimValue")+ .HasColumnType("text");++ b.Property<string>("RoleId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("RoleClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>+ {+ b.Property<int>("Id")+ .ValueGeneratedOnAdd()+ .HasColumnType("integer");++ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));++ b.Property<string>("ClaimType")+ .HasColumnType("text");++ b.Property<string>("ClaimValue")+ .HasColumnType("text");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("Id");++ b.ToTable("UserClaims", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>+ {+ b.Property<string>("LoginProvider")+ .HasColumnType("text");++ b.Property<string>("ProviderKey")+ .HasColumnType("text");++ b.Property<string>("ProviderDisplayName")+ .HasColumnType("text");++ b.Property<string>("UserId")+ .HasColumnType("text");++ b.HasKey("LoginProvider", "ProviderKey");++ b.ToTable("UserLogins", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("text");++ b.Property<string>("RoleId")+ .HasColumnType("text");++ b.HasKey("UserId", "RoleId");++ b.ToTable("UserRoles", (string)null);+ });++ modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>+ {+ b.Property<string>("UserId")+ .HasColumnType("text");++ b.Property<string>("LoginProvider")+ .HasColumnType("text");++ b.Property<string>("Name")+ .HasColumnType("text");++ b.Property<string>("Value")+ .HasColumnType("text");++ b.HasKey("UserId", "LoginProvider", "Name");++ b.ToTable("UserTokens", (string)null);+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.HasOne("AliasServerDb.Group", "PersonalGroup")+ .WithOne()+ .HasForeignKey("AliasServerDb.AliasVaultUser", "PersonalGroupId")+ .OnDelete(DeleteBehavior.Restrict)+ .IsRequired();++ b.Navigation("PersonalGroup");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUserRefreshToken", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Attachments")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.HasOne("AliasServerDb.EmailClaim", "EmailClaim")+ .WithMany("Links")+ .HasForeignKey("EmailClaimId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("EmailClaim");++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Wraps")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")+ .WithMany("Wraps")+ .HasForeignKey("EncryptionKeyId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");++ b.Navigation("EncryptionKey");+ });++ modelBuilder.Entity("AliasServerDb.GroupMember", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany("Members")+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Group");++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.MobileLoginRequest", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.RateLimit", b =>+ {+ b.HasOne("AliasServerDb.Group", "Group")+ .WithMany()+ .HasForeignKey("GroupId")+ .OnDelete(DeleteBehavior.Cascade);++ b.Navigation("Group");+ });++ modelBuilder.Entity("AliasServerDb.UserGrantKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.UserUnlockKey", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>+ {+ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany()+ .HasForeignKey("OwnerUserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");+ });++ modelBuilder.Entity("AliasServerDb.VaultBlobReference", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucket", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultDataBucketsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultDataBucket", "Bucket")+ .WithMany()+ .HasForeignKey("ManifestId", "Category")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Bucket");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifest", b =>+ {+ b.HasOne("AliasServerDb.Group", "OwnerGroup")+ .WithMany()+ .HasForeignKey("OwnerGroupId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("OwnerGroup");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestAccessKey", b =>+ {+ b.HasOne("AliasServerDb.UserGrantKey", "UserGrantKey")+ .WithMany()+ .HasForeignKey("UserGrantKeyId")+ .OnDelete(DeleteBehavior.SetNull);++ b.HasOne("AliasServerDb.AliasVaultUser", "User")+ .WithMany("VaultManifestAccessKeys")+ .HasForeignKey("UserId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("User");++ b.Navigation("UserGrantKey");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")+ .WithMany()+ .HasForeignKey("VaultManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("VaultManifest");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestsHistory", b =>+ {+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")+ .WithMany()+ .HasForeignKey("ManifestId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Manifest");+ });++ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>+ {+ b.Navigation("VaultManifestAccessKeys");+ });++ modelBuilder.Entity("AliasServerDb.Email", b =>+ {+ b.Navigation("Attachments");++ b.Navigation("Wraps");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Navigation("Links");+ });++ modelBuilder.Entity("AliasServerDb.Group", b =>+ {+ b.Navigation("Members");+ });++ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>+ {+ b.Navigation("Wraps");+ });+#pragma warning restore 612, 618+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.cs b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.csnew file mode 100644index 000000000..2abe2d55a--- /dev/null+++ b/apps/server/Databases/AliasServerDb/Migrations/20260810154523_AddEmailMultiWrap.cs@@ -0,0 +1,189 @@+using System;+using Microsoft.EntityFrameworkCore.Migrations;++#nullable disable++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+ {+ /// <inheritdoc />+ protected override void Up(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.CreateTable(+ name: "EmailClaimLinks",+ columns: table => new+ {+ EmailClaimId = table.Column<Guid>(type: "uuid", nullable: false),+ VaultManifestId = table.Column<Guid>(type: "uuid", nullable: false)+ },+ constraints: table =>+ {+ table.PrimaryKey("PK_EmailClaimLinks", x => new { x.EmailClaimId, x.VaultManifestId });+ table.ForeignKey(+ name: "FK_EmailClaimLinks_EmailClaims_EmailClaimId",+ column: x => x.EmailClaimId,+ principalTable: "EmailClaims",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ table.ForeignKey(+ name: "FK_EmailClaimLinks_VaultManifests_VaultManifestId",+ column: x => x.VaultManifestId,+ principalTable: "VaultManifests",+ principalColumn: "ManifestId",+ onDelete: ReferentialAction.Cascade);+ });++ migrationBuilder.CreateTable(+ name: "EmailKeyWraps",+ columns: table => new+ {+ EmailId = table.Column<int>(type: "integer", nullable: false),+ EncryptionKeyId = 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.ForeignKey(+ name: "FK_EmailKeyWraps_Emails_EmailId",+ column: x => x.EmailId,+ principalTable: "Emails",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ table.ForeignKey(+ name: "FK_EmailKeyWraps_VaultManifestDeliveryKeys_EncryptionKeyId",+ column: x => x.EncryptionKeyId,+ principalTable: "VaultManifestDeliveryKeys",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ });++ migrationBuilder.CreateIndex(+ name: "IX_EmailClaimLinks_VaultManifestId_EmailClaimId",+ table: "EmailClaimLinks",+ columns: new[] { "VaultManifestId", "EmailClaimId" });++ migrationBuilder.CreateIndex(+ name: "IX_EmailKeyWraps_EncryptionKeyId_EmailId",+ table: "EmailKeyWraps",+ columns: new[] { "EncryptionKeyId", "EmailId" });++ // Every existing email gets exactly one wrap (its current key), every claim one link (its current+ // manifest). A tombstoned claim (VaultManifestId already null) simply gets zero links.+ migrationBuilder.Sql("""+ INSERT INTO "EmailKeyWraps" ("EmailId", "EncryptionKeyId", "EncryptedSymmetricKey")+ SELECT "Id", "EncryptionKeyId", "EncryptedSymmetricKey" FROM "Emails";++ INSERT INTO "EmailClaimLinks" ("EmailClaimId", "VaultManifestId")+ SELECT "Id", "VaultManifestId" FROM "EmailClaims" WHERE "VaultManifestId" IS NOT NULL;+ """);++ migrationBuilder.DropForeignKey(name: "FK_EmailClaims_VaultManifests_VaultManifestId", table: "EmailClaims");+ migrationBuilder.DropForeignKey(name: "FK_Emails_VaultManifestDeliveryKeys_EncryptionKeyId", table: "Emails");+ migrationBuilder.DropIndex(name: "IX_Emails_EncryptionKeyId", table: "Emails");+ migrationBuilder.DropIndex(name: "IX_EmailClaims_VaultManifestId_CreatedAt", table: "EmailClaims");+ migrationBuilder.DropIndex(name: "IX_EmailClaims_VaultManifestId_Disabled", table: "EmailClaims");+ migrationBuilder.DropColumn(name: "EncryptedSymmetricKey", table: "Emails");+ migrationBuilder.DropColumn(name: "EncryptionKeyId", table: "Emails");+ migrationBuilder.DropColumn(name: "VaultManifestId", table: "EmailClaims");+ }++ /// <inheritdoc />+ protected override void Down(MigrationBuilder migrationBuilder)+ {+ migrationBuilder.AddColumn<string>(+ name: "EncryptedSymmetricKey",+ table: "Emails",+ type: "text",+ nullable: true);++ migrationBuilder.AddColumn<Guid>(+ name: "EncryptionKeyId",+ table: "Emails",+ type: "uuid",+ maxLength: 255,+ nullable: true);++ migrationBuilder.AddColumn<Guid>(+ name: "VaultManifestId",+ table: "EmailClaims",+ 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.+ 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";++ DELETE FROM "Emails" WHERE "EncryptionKeyId" IS NULL;++ UPDATE "EmailClaims" c+ SET "VaultManifestId" = l."VaultManifestId"+ FROM (SELECT DISTINCT ON ("EmailClaimId") "EmailClaimId", "VaultManifestId" FROM "EmailClaimLinks" ORDER BY "EmailClaimId", "VaultManifestId") l+ WHERE l."EmailClaimId" = c."Id";+ """);++ migrationBuilder.AlterColumn<string>(+ name: "EncryptedSymmetricKey",+ table: "Emails",+ type: "text",+ nullable: false,+ oldClrType: typeof(string),+ oldType: "text",+ oldNullable: true);++ migrationBuilder.AlterColumn<Guid>(+ name: "EncryptionKeyId",+ table: "Emails",+ type: "uuid",+ maxLength: 255,+ nullable: false,+ oldClrType: typeof(Guid),+ oldType: "uuid",+ oldMaxLength: 255,+ oldNullable: true);++ migrationBuilder.DropTable(name: "EmailClaimLinks");+ migrationBuilder.DropTable(name: "EmailKeyWraps");++ migrationBuilder.CreateIndex(+ name: "IX_Emails_EncryptionKeyId",+ table: "Emails",+ column: "EncryptionKeyId");++ migrationBuilder.CreateIndex(+ name: "IX_EmailClaims_VaultManifestId_CreatedAt",+ table: "EmailClaims",+ columns: new[] { "VaultManifestId", "CreatedAt" });++ migrationBuilder.CreateIndex(+ name: "IX_EmailClaims_VaultManifestId_Disabled",+ table: "EmailClaims",+ columns: new[] { "VaultManifestId", "Disabled" });++ migrationBuilder.AddForeignKey(+ name: "FK_EmailClaims_VaultManifests_VaultManifestId",+ table: "EmailClaims",+ column: "VaultManifestId",+ principalTable: "VaultManifests",+ principalColumn: "ManifestId",+ onDelete: ReferentialAction.SetNull);++ migrationBuilder.AddForeignKey(+ name: "FK_Emails_VaultManifestDeliveryKeys_EncryptionKeyId",+ table: "Emails",+ column: "EncryptionKeyId",+ principalTable: "VaultManifestDeliveryKeys",+ principalColumn: "Id",+ onDelete: ReferentialAction.Cascade);+ }+ }+}diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.csindex a78cd65c8..c8fc5aec9 100644--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs@@ -381,14 +381,6 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("DateSystem").HasColumnType("timestamp with time zone");- b.Property<string>("EncryptedSymmetricKey")- .IsRequired()- .HasColumnType("text");-- b.Property<Guid>("EncryptionKeyId")- .HasMaxLength(255)- .HasColumnType("uuid");-b.Property<string>("From").IsRequired().HasColumnType("text");@@ -442,8 +434,6 @@ namespace AliasServerDb.Migrationsb.HasIndex("DateSystem");- b.HasIndex("EncryptionKeyId");-b.HasIndex("PushNotificationSent");b.HasIndex("Visible");@@ -519,19 +509,46 @@ namespace AliasServerDb.Migrationsb.Property<DateTime>("UpdatedAt").HasColumnType("timestamp with time zone");- b.Property<Guid?>("VaultManifestId")- .HasColumnType("uuid");-b.HasKey("Id");b.HasIndex("Address").IsUnique();- b.HasIndex("VaultManifestId", "CreatedAt");+ b.ToTable("EmailClaims");+ });- b.HasIndex("VaultManifestId", "Disabled");+ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>+ {+ b.Property<Guid>("EmailClaimId")+ .HasColumnType("uuid");- b.ToTable("EmailClaims");+ b.Property<Guid>("VaultManifestId")+ .HasColumnType("uuid");++ b.HasKey("EmailClaimId", "VaultManifestId");++ b.HasIndex("VaultManifestId", "EmailClaimId");++ b.ToTable("EmailClaimLinks");+ });++ modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>+ {+ b.Property<int>("EmailId")+ .HasColumnType("integer");++ b.Property<Guid>("EncryptionKeyId")+ .HasColumnType("uuid");++ b.Property<string>("EncryptedSymmetricKey")+ .IsRequired()+ .HasColumnType("text");++ b.HasKey("EmailId", "EncryptionKeyId");++ b.HasIndex("EncryptionKeyId", "EmailId");++ b.ToTable("EmailKeyWraps");});modelBuilder.Entity("AliasServerDb.Group", b =>@@ -1456,17 +1473,6 @@ namespace AliasServerDb.Migrationsb.Navigation("User");});- modelBuilder.Entity("AliasServerDb.Email", b =>- {- b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")- .WithMany("Emails")- .HasForeignKey("EncryptionKeyId")- .OnDelete(DeleteBehavior.Cascade)- .IsRequired();-- b.Navigation("EncryptionKey");- });-modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>{b.HasOne("AliasServerDb.Email", "Email")@@ -1478,16 +1484,44 @@ namespace AliasServerDb.Migrationsb.Navigation("Email");});- modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>{+ b.HasOne("AliasServerDb.EmailClaim", "EmailClaim")+ .WithMany("Links")+ .HasForeignKey("EmailClaimId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();+b.HasOne("AliasServerDb.VaultManifest", "VaultManifest").WithMany().HasForeignKey("VaultManifestId")- .OnDelete(DeleteBehavior.SetNull);+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("EmailClaim");b.Navigation("VaultManifest");});+ modelBuilder.Entity("AliasServerDb.EmailKeyWrap", b =>+ {+ b.HasOne("AliasServerDb.Email", "Email")+ .WithMany("Wraps")+ .HasForeignKey("EmailId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "EncryptionKey")+ .WithMany("Wraps")+ .HasForeignKey("EncryptionKeyId")+ .OnDelete(DeleteBehavior.Cascade)+ .IsRequired();++ b.Navigation("Email");++ b.Navigation("EncryptionKey");+ });+modelBuilder.Entity("AliasServerDb.GroupMember", b =>{b.HasOne("AliasServerDb.Group", "Group")@@ -1652,6 +1686,13 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.Email", b =>{b.Navigation("Attachments");++ b.Navigation("Wraps");+ });++ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>+ {+ b.Navigation("Links");});modelBuilder.Entity("AliasServerDb.Group", b =>@@ -1661,7 +1702,7 @@ namespace AliasServerDb.MigrationsmodelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>{- b.Navigation("Emails");+ b.Navigation("Wraps");});#pragma warning restore 612, 618}diff --git a/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.cs b/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.csindex f885097d7..69c21bea0 100644--- a/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.cs+++ b/apps/server/Databases/AliasServerDb/VaultManifestDeliveryKey.cs@@ -54,7 +54,7 @@ public class VaultManifestDeliveryKeypublic DateTime UpdatedAt { get; set; }/// <summary>- /// Gets or sets the collection of Emails that are using this encryption key.+ /// Gets or sets the collection of email key wraps that were encrypted with this key./// </summary>- public virtual ICollection<Email> Emails { get; set; } = [];+ public virtual ICollection<EmailKeyWrap> Wraps { get; set; } = [];}diff --git a/apps/server/Services/AliasVault.TaskRunner/Program.cs b/apps/server/Services/AliasVault.TaskRunner/Program.csindex 365da824a..ba9015db9 100644--- a/apps/server/Services/AliasVault.TaskRunner/Program.cs+++ b/apps/server/Services/AliasVault.TaskRunner/Program.cs@@ -34,6 +34,7 @@ builder.Services.AddTransient<IMaintenanceTask, RefreshTokenCleanupTask>();builder.Services.AddTransient<IMaintenanceTask, EmailCleanupTask>();builder.Services.AddTransient<IMaintenanceTask, EmailQuotaCleanupTask>();builder.Services.AddTransient<IMaintenanceTask, DisabledEmailCleanupTask>();+builder.Services.AddTransient<IMaintenanceTask, OrphanedEmailCleanupTask>();builder.Services.AddStatusHostedService<TaskRunnerWorker, AliasServerDbContext>(Assembly.GetExecutingAssembly().GetName().Name!);diff --git a/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailCleanupTask.cs b/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailCleanupTask.csindex 042cd8e85..4925f7803 100644--- a/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailCleanupTask.cs+++ b/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailCleanupTask.cs@@ -79,7 +79,7 @@ public class EmailCleanupTask : IMaintenanceTask// Get all email addresses for this uservar userAddresses = await dbContext.EmailClaims- .Where(c => dbContext.AliasVaultUsers.Any(u => u.Id == user.Id && u.PersonalGroupId == c.VaultManifest!.OwnerGroupId))+ .Where(c => c.Links.Any(l => dbContext.AliasVaultUsers.Any(u => u.Id == user.Id && u.PersonalGroupId == l.VaultManifest.OwnerGroupId))).Select(c => c.Address).ToListAsync(cancellationToken);diff --git a/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs b/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.csindex 0bc812166..51c6ed20e 100644--- a/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs+++ b/apps/server/Services/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs@@ -49,8 +49,8 @@ public class EmailQuotaCleanupTask : IMaintenanceTaskvar usersWithClaims = await (from u in dbContext.AliasVaultUsersjoin g in dbContext.Groups on u.PersonalGroupId equals g.Idjoin m in dbContext.VaultManifests on g.Id equals m.OwnerGroupId- join c in dbContext.EmailClaims on (Guid?)m.ManifestId equals c.VaultManifestId- select new { u.Id, u.UserName, g.MaxEmails, u.LastActivityDate, u.CreatedAt, c.Address })+ join l in dbContext.EmailClaimLinks on m.ManifestId equals l.VaultManifestId+ select new { u.Id, u.UserName, g.MaxEmails, u.LastActivityDate, u.CreatedAt, l.EmailClaim.Address }).ToListAsync(cancellationToken);// Get minimum activity date which is used to determine if user is active.diff --git a/apps/server/Services/AliasVault.TaskRunner/Tasks/OrphanedEmailCleanupTask.cs b/apps/server/Services/AliasVault.TaskRunner/Tasks/OrphanedEmailCleanupTask.csnew file mode 100644index 000000000..272cbd1a0--- /dev/null+++ b/apps/server/Services/AliasVault.TaskRunner/Tasks/OrphanedEmailCleanupTask.cs@@ -0,0 +1,54 @@+//-----------------------------------------------------------------------+// <copyright file="OrphanedEmailCleanupTask.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.TaskRunner.Tasks;++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+/// undecryptable: nobody holds a key that can open it, so it can be safely deleted.+/// </summary>+public class OrphanedEmailCleanupTask : IMaintenanceTask+{+ private readonly ILogger<OrphanedEmailCleanupTask> _logger;+ private readonly IAliasServerDbContextFactory _dbContextFactory;++ /// <summary>+ /// Initializes a new instance of the <see cref="OrphanedEmailCleanupTask"/> class.+ /// </summary>+ /// <param name="logger">The logger.</param>+ /// <param name="dbContextFactory">The database context factory.</param>+ public OrphanedEmailCleanupTask(+ ILogger<OrphanedEmailCleanupTask> logger,+ IAliasServerDbContextFactory dbContextFactory)+ {+ _logger = logger;+ _dbContextFactory = dbContextFactory;+ }++ /// <inheritdoc />+ public string Name => "Orphaned Email Cleanup";++ /// <inheritdoc />+ public async Task ExecuteAsync(CancellationToken cancellationToken)+ {+ await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);++ // Delete all emails without a single remaining key wrap - attachments cascade with them.+ var deletedCount = await dbContext.Emails+ .Where(x => !x.Wraps.Any())+ .ExecuteDeleteAsync(cancellationToken);++ if (deletedCount > 0)+ {+ _logger.LogInformation("Deleted {Count} emails that no remaining key can decrypt.", deletedCount);+ }+ }+}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.csnew file mode 100644index 000000000..b0dcc1070--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModel.cs@@ -0,0 +1,36 @@+//-----------------------------------------------------------------------+// <copyright file="EmailApiModel.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.Shared.Models.WebApi.V2.Email;++using AliasVault.Shared.Models.Spamok;++/// <summary>+/// Represents the email API model.+/// </summary>+public class EmailApiModel : EmailApiModelBase+{+ /// <summary>+ /// Gets or sets the HTML content of the email message.+ /// </summary>+ public string? MessageHtml { get; set; }++ /// <summary>+ /// Gets or sets the plain text content of the email message.+ /// </summary>+ public string? MessagePlain { get; set; }++ /// <summary>+ /// Gets or sets the source content of the email message.+ /// </summary>+ public string? MessageSource { get; set; }++ /// <summary>+ /// Gets or sets the list of attachments in the email.+ /// </summary>+ public List<AttachmentApiModel> Attachments { 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.csnew file mode 100644index 000000000..f913b1c63--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailApiModelBase.cs@@ -0,0 +1,71 @@+//-----------------------------------------------------------------------+// <copyright file="EmailApiModelBase.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.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.+/// </summary>+public abstract class EmailApiModelBase+{+ /// <summary>+ /// Gets or sets the ID of the email.+ /// </summary>+ public int Id { get; set; }++ /// <summary>+ /// Gets or sets the subject of the email.+ /// </summary>+ public string Subject { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the display name of the sender.+ /// </summary>+ public string FromDisplay { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the domain of the sender's email address.+ /// </summary>+ public string FromDomain { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the local part of the sender's email address.+ /// </summary>+ public string FromLocal { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the domain of the recipient's email address.+ /// </summary>+ public string ToDomain { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the local part of the recipient's email address.+ /// </summary>+ public string ToLocal { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the date of the email.+ /// </summary>+ public DateTime Date { get; set; }++ /// <summary>+ /// Gets or sets the system date of the email.+ /// </summary>+ public DateTime DateSystem { get; set; }++ /// <summary>+ /// Gets or sets the number of seconds ago the email was received.+ /// </summary>+ 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+ /// the caller holds (their personal key, plus the delivery key of every shared manifest they can access).+ /// </summary>+ public List<EmailKeyWrapApiModel> Wraps { 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/EmailKeyWrapApiModel.csnew file mode 100644index 000000000..7ad327cbe--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/EmailKeyWrapApiModel.cs@@ -0,0 +1,25 @@+//-----------------------------------------------------------------------+// <copyright file="EmailKeyWrapApiModel.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.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.+/// </summary>+public class EmailKeyWrapApiModel+{+ /// <summary>+ /// Gets or sets the public key whose private half unwraps this wrap.+ /// </summary>+ public string PublicKey { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets the email's symmetric key, encrypted with the public key.+ /// </summary>+ public string EncryptedSymmetricKey { get; set; } = string.Empty;+}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.csnew file mode 100644index 000000000..c71c294b4--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs@@ -0,0 +1,29 @@+//-----------------------------------------------------------------------+// <copyright file="MailboxApiModel.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.Shared.Models.WebApi.V2.Email;++/// <summary>+/// Represents the mailbox API model.+/// </summary>+public class MailboxApiModel+{+ /// <summary>+ /// Gets or sets the address of the mailbox.+ /// </summary>+ public string Address { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets a value indicating whether the mailbox is subscribed.+ /// </summary>+ public bool Subscribed { get; set; }++ /// <summary>+ /// Gets or sets the list of mailbox email API models.+ /// </summary>+ public List<MailboxEmailApiModel> Mails { get; set; } = [];+}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkRequest.csnew file mode 100644index 000000000..3296c846f--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkRequest.cs@@ -0,0 +1,29 @@+//-----------------------------------------------------------------------+// <copyright file="MailboxBulkRequest.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.Shared.Models.WebApi.V2.Email;++/// <summary>+/// Represents the bulk mailbox request.+/// </summary>+public class MailboxBulkRequest+{+ /// <summary>+ /// Gets or sets the mailbox addresses that client wants to retrieve emails for.+ /// </summary>+ public List<string> Addresses { get; set; } = [];++ /// <summary>+ /// Gets or sets requested page number.+ /// </summary>+ public int Page { get; set; }++ /// <summary>+ /// Gets or sets requested page size.+ /// </summary>+ public int PageSize { 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.csnew file mode 100644index 000000000..3e74fc71d--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxBulkResponse.cs@@ -0,0 +1,39 @@+//-----------------------------------------------------------------------+// <copyright file="MailboxBulkResponse.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.Shared.Models.WebApi.V2.Email;++/// <summary>+/// Represents the bulk mailbox response.+/// </summary>+public class MailboxBulkResponse+{+ /// <summary>+ /// Gets or sets the mailbox addresses that client wants to retrieve emails for.+ /// </summary>+ public List<string> Addresses { get; set; } = [];++ /// <summary>+ /// Gets or sets requested page number.+ /// </summary>+ public int CurrentPage { get; set; }++ /// <summary>+ /// Gets or sets requested page size.+ /// </summary>+ public int PageSize { get; set; }++ /// <summary>+ /// Gets or sets total number of emails.+ /// </summary>+ public int TotalRecords { get; set; }++ /// <summary>+ /// Gets or sets the list of mailbox email API models.+ /// </summary>+ public List<MailboxEmailApiModel> Mails { get; set; } = [];+}diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxEmailApiModel.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxEmailApiModel.csnew file mode 100644index 000000000..853d49c5b--- /dev/null+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxEmailApiModel.cs@@ -0,0 +1,24 @@+//-----------------------------------------------------------------------+// <copyright file="MailboxEmailApiModel.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.Shared.Models.WebApi.V2.Email;++/// <summary>+/// Represents the mailbox email API model.+/// </summary>+public class MailboxEmailApiModel : EmailApiModelBase+{+ /// <summary>+ /// Gets or sets the preview of the email message.+ /// </summary>+ public string MessagePreview { get; set; } = string.Empty;++ /// <summary>+ /// Gets or sets a value indicating whether the email has attachments.+ /// </summary>+ public bool HasAttachments { get; set; }+}diff --git a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.csindex 993d898f2..7caeffdb0 100644--- a/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs+++ b/apps/server/Utilities/Cryptography/AliasVault.Cryptography.Server/EmailEncryption.cs@@ -15,12 +15,12 @@ using AliasServerDb;public static class EmailEncryption{/// <summary>- /// Encrypt the email contents with the user's public key.+ /// Encrypt the email contents with a fresh symmetric key, wrapped once per recipient manifest's delivery key./// </summary>/// <param name="email">The plain text email object to encrypt.</param>- /// <param name="encryptionKey">The user public encryption key to use for the encryption.</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>/// <returns>Email object with all sensitive fields encrypted.</returns>- public static Email EncryptEmail(Email email, VaultManifestDeliveryKey encryptionKey)+ public static Email EncryptEmail(Email email, IReadOnlyCollection<VaultManifestDeliveryKey> deliveryKeys){// Generate symmetric key for email encryption.var symmetricKey = Encryption.GenerateRandomSymmetricKey();@@ -53,9 +53,11 @@ public static class EmailEncryptionattachment.Bytes = Encryption.SymmetricEncrypt(attachment.Bytes, symmetricKey);}- // Encrypt the symmetric key with the user's public key.- email.EncryptedSymmetricKey = Encryption.EncryptSymmetricKeyWithRsa(symmetricKey, encryptionKey.PublicKey);- email.EncryptionKeyId = encryptionKey.Id;+ // Wrap 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) });+ }return email;}@@ -68,8 +70,26 @@ public static class EmailEncryption/// <returns>Email object with all sensitive fields decrypted.</returns>public static Email DecryptEmail(Email email, string userPrivateKey){- // Decrypt symmetric key using private key.- var symmetricKey = Encryption.DecryptSymmetricKeyWithRsa(email.EncryptedSymmetricKey, userPrivateKey);+ // Decrypt the symmetric key from the wrap belonging to this private key; with multiple wraps the+ // matching one is found by simply trying each.+ byte[]? symmetricKey = null;+ foreach (var wrap in email.Wraps)+ {+ try+ {+ symmetricKey = Encryption.DecryptSymmetricKeyWithRsa(wrap.EncryptedSymmetricKey, userPrivateKey);+ break;+ }+ catch (System.Security.Cryptography.CryptographicException)+ {+ // Wrap belongs to another manifest's key; try the next one.+ }+ }++ if (symmetricKey is null)+ {+ throw new InvalidOperationException("The email carries no wrap that the provided private key can open.");+ }// Encrypt all email contents with the symmetric key.if (email.MessageHtml is not null)diff --git a/core/models/src/webapi/Email.ts b/core/models/src/webapi/Email.tsindex 0b0109df3..87501a3e1 100644--- a/core/models/src/webapi/Email.ts+++ b/core/models/src/webapi/Email.ts@@ -1,4 +1,5 @@import { EmailAttachment } from "./EmailAttachment";+import { EmailKeyWrap } from "./EmailKeyWrap";export type Email = {/** The body of the email message */@@ -40,14 +41,8 @@ export type Email = {/** The number of seconds ago the email was received */secondsAgo: number;- /**- * The encrypted symmetric key which was used to encrypt the email message.- * This key is encrypted with the public key of the user.- */- encryptedSymmetricKey: string;-- /** The public key of the user used to encrypt the symmetric key */- encryptionKey: string;+ /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */+ wraps: EmailKeyWrap[];/** The attachments of the email */attachments: EmailAttachment[];diff --git a/core/models/src/webapi/EmailKeyWrap.ts b/core/models/src/webapi/EmailKeyWrap.tsnew file mode 100644index 000000000..a8e8b985d--- /dev/null+++ b/core/models/src/webapi/EmailKeyWrap.ts@@ -0,0 +1,7 @@+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/MailboxEmail.ts b/core/models/src/webapi/MailboxEmail.tsindex dd15b9ae4..140377569 100644--- a/core/models/src/webapi/MailboxEmail.ts+++ b/core/models/src/webapi/MailboxEmail.ts@@ -1,3 +1,5 @@+import { EmailKeyWrap } from "./EmailKeyWrap";+export type MailboxEmail = {/** The preview of the email message */messagePreview: string;@@ -35,12 +37,6 @@ export type MailboxEmail = {/** The number of seconds ago the email was received */secondsAgo: number;- /**- * The encrypted symmetric key which was used to encrypt the email message.- * This key is encrypted with the public key of the user.- */- encryptedSymmetricKey: string;-- /** The public key of the user used to encrypt the symmetric key */- encryptionKey: string;+ /** The wrapped copies of the email's symmetric key the caller can open, one per manifest keypair the caller holds */+ wraps: EmailKeyWrap[];}\ No newline at end of filediff --git a/core/models/src/webapi/index.ts b/core/models/src/webapi/index.tsindex 5d3555b94..80c056d3c 100644--- a/core/models/src/webapi/index.ts+++ b/core/models/src/webapi/index.ts@@ -13,6 +13,7 @@ export * from './MailboxBulk';export * from './MailboxEmail';export * from './Email';export * from './EmailAttachment';+export * from './EmailKeyWrap';export * from './AuthLog';export * from './RefreshToken';export * from './FaviconExtractModel';