Skip to content

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

Enforce single alias claims and add explicit transfer between manifests (#2469)

Leendert de Borst8490abf54167
diff --git a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
index 87f77d9be..7d1de1911 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/EmailPreview.tsx
@@ -1,11 +1,15 @@
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';
+import { type AliasOwnerNotice, aliasOwnerErrorText, aliasOwnerNotice, moveAliasHere } from '@aliasvault/client/email/AliasOwner';
import { SpamOkClient } from '@aliasvault/client/email/SpamOkClient';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
+import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
import { mailboxPollDelayMs } from '@aliasvault/client/utilities/PollBackoff';
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation } from 'react-router-dom';
+import Modal from '@/entrypoints/popup/components/Dialogs/Modal';
import { AttachmentIcon } from '@/entrypoints/popup/components/Icons/AttachmentIcon';
import Icon from '@/entrypoints/popup/components/Icons/Icon';
import { useDb } from '@/entrypoints/popup/context/DbContext';
@@ -14,7 +18,7 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { StorageKeys } from '@/utils/constants/storageKeys';
import { logExpected } from '@/utils/Diagnostics';
-import type { ApiErrorResponse, MailboxEmail } from '@aliasvault/models/webapi';
+import type { ApiErrorResponse, Mailbox, MailboxEmail } from '@aliasvault/models/webapi';
import { storage } from '#imports';
@@ -23,12 +27,13 @@ const spamOk = new SpamOkClient('av-chrome', AppInfo.VERSION);
type EmailPreviewProps = {
email: string;
+ manifestId: string;
}
/**
* This component shows a preview of the latest emails in the inbox.
*/
-export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
+export const EmailPreview: React.FC<EmailPreviewProps> = ({ email, manifestId }) => {
const { t } = useTranslation();
const [emails, setEmails] = useState<MailboxEmail[]>([]);
const [displayedEmails, setDisplayedEmails] = useState<MailboxEmail[]>([]);
@@ -38,6 +43,8 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
const [error, setError] = useState<string | null>(null);
const [isSupportedDomain, setIsSupportedDomain] = useState(false);
const [displayedCount, setDisplayedCount] = useState(2);
+ const [ownerNotice, setOwnerNotice] = useState<AliasOwnerNotice | null>(null);
+ const [showMoveConfirm, setShowMoveConfirm] = useState(false);
const webApi = useWebApi();
const dbContext = useDb();
const location = useLocation();
@@ -155,7 +162,8 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
*/
const response = await webApi.authFetch(`EmailBox/${email}`, { method: 'GET' }, true, false);
try {
- const data = response as { mails: MailboxEmail[], publicKeys: string[] };
+ const data = response as Mailbox;
+ setOwnerNotice(aliasOwnerNotice(email, data, manifestId, dbContext.sqliteClient!.getPersonalManifestId(), dbContext.sqliteClient!.folders.getAll()));
// Store all emails, sorted by date
const allMails = data.mails
@@ -201,7 +209,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
}
markPollFailed(`The server rejected the mailbox request: ${apiErrorResponse?.code ?? 'unknown'}`);
- setError(t('apiErrors.' + apiErrorResponse?.code, { defaultValue: t('common.errors.unknownErrorTryAgain') }));
+ setError(aliasOwnerErrorText(apiErrorResponse?.code) ?? t('apiErrors.' + apiErrorResponse?.code, { defaultValue: t('common.errors.unknownErrorTryAgain') }));
return;
}
} catch (err) {
@@ -241,7 +249,45 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
clearTimeout(timer);
}
};
- }, [email, loading, webApi, dbContext, t, displayedCount]);
+ }, [email, manifestId, loading, webApi, dbContext, t, displayedCount]);
+
+ /**
+ * Move the alias to this item's vault, then reload so the notice goes away.
+ */
+ const moveHere = async (): Promise<void> => {
+ setShowMoveConfirm(false);
+ try {
+ await moveAliasHere(webApi, email, manifestId);
+ setOwnerNotice(null);
+ setLoading(true);
+ } catch (err) {
+ setError(aliasOwnerErrorText(apiErrorCodeOf(err)) ?? t('common.errors.unknownErrorTryAgain'));
+ }
+ };
+
+ const ownerNoticeBlock = ownerNotice && (
+ <div className="mb-2 p-3 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 rounded">
+ <p className="text-sm text-amber-800 dark:text-amber-200">{ownerNotice.notice}</p>
+ {ownerNotice.canMove && (
+ <button
+ id="move-alias-here"
+ onClick={() => setShowMoveConfirm(true)}
+ className="mt-2 py-1 px-3 bg-primary-600 hover:bg-primary-700 text-white rounded-md text-sm"
+ >
+ {familySharingText.aliasOwner.moveHere}
+ </button>
+ )}
+ <Modal
+ isOpen={showMoveConfirm}
+ onClose={() => setShowMoveConfirm(false)}
+ onConfirm={() => void moveHere()}
+ title={familySharingText.aliasOwner.moveHere}
+ message={ownerNotice.moveConfirm}
+ confirmText={t('common.confirm')}
+ cancelText={t('common.cancel')}
+ />
+ </div>
+ );
// Don't render anything if the domain is not supported
if (!isSupportedDomain) {
@@ -291,6 +337,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('common.recentEmails')}</h2>
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
</div>
+ {ownerNoticeBlock}
{t('emails.noEmails')}
</div>
);
@@ -302,6 +349,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) => {
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('common.recentEmails')}</h2>
<div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
</div>
+ {ownerNoticeBlock}
{displayedEmails.map((mail) => (
isSpamOk ? (
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
index a312be8b8..a9ebc63c8 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailsList.tsx
@@ -52,7 +52,7 @@ const EmailsList: React.FC = () => {
/**
* The addresses whose mailbox this vault may ask for: aliases on a server-hosted domain that are still switched on.
- * A deleted or switched-off alias has no enabled claim link on the server, so its mail stays hidden, and addresses
+ * A deleted or switched-off alias has no enabled claim on the server, so its mail stays hidden, and addresses
* on domains the server does not host are never sent to it in the first place.
*/
const getMailboxAddresses = useCallback(async () : Promise<string[]> => {
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
index a5a22215e..09877e684 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
@@ -200,7 +200,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
const emailField = item.Fields.find(f => f.FieldKey === 'login.email');
const emailValue = emailField?.Value;
const email = Array.isArray(emailValue) ? emailValue[0] : emailValue;
- return email ? <EmailPreview email={email} /> : null;
+ return email ? <EmailPreview email={email} manifestId={item.ManifestId} /> : null;
})()}
{/* TOTP codes - only for Login and Alias types, shown at top */}
diff --git a/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsx b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsx
index c92282b27..47cec7be3 100644
--- a/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsx
+++ b/apps/mobile-app/app/(tabs)/items/[manifestId]/[id]/index.tsx
@@ -304,7 +304,7 @@ export default function ItemDetailsScreen() : React.ReactNode {
{renderUrls()}
</View>
</ThemedView>
- <EmailPreview email={email} />
+ <EmailPreview email={email} manifestId={item.ManifestId} />
<TotpSection item={item} />
<LoginFields item={item} />
<CardDetails item={item} />
diff --git a/apps/mobile-app/components/items/details/EmailPreview.tsx b/apps/mobile-app/components/items/details/EmailPreview.tsx
index 66a123b8c..e4b7290e5 100644
--- a/apps/mobile-app/components/items/details/EmailPreview.tsx
+++ b/apps/mobile-app/components/items/details/EmailPreview.tsx
@@ -4,11 +4,14 @@ import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { View, StyleSheet, TouchableOpacity, Linking, AppState } from 'react-native';
+import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
+import { type AliasOwnerNotice, aliasOwnerErrorText, aliasOwnerNotice, moveAliasHere } from '@aliasvault/client/email/AliasOwner';
import { SpamOkClient } from '@aliasvault/client/email/SpamOkClient';
+import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { logExpected } from '@aliasvault/client/utilities/Diagnostics';
import { mailboxPollDelayMs } from '@aliasvault/client/utilities/PollBackoff';
-import type { ApiErrorResponse, MailboxEmail } from '@aliasvault/models/webapi';
+import type { ApiErrorResponse, Mailbox, MailboxEmail } from '@aliasvault/models/webapi';
import EncryptionUtility from '@/utils/EncryptionUtility';
import { useColors } from '@/hooks/useColorScheme';
@@ -17,6 +20,7 @@ import { PulseDot } from '@/components/PulseDot';
import { ThemedText } from '@/components/themed/ThemedText';
import { ThemedView } from '@/components/themed/ThemedView';
import { useDb } from '@/context/DbContext';
+import { useDialog } from '@/context/DialogContext';
import { useWebApi } from '@/context/WebApiContext';
/** Client for the SpamOK mailboxes of the public email domains. */
@@ -24,12 +28,13 @@ const spamOk = new SpamOkClient('av-mobile', AppInfo.VERSION);
type EmailPreviewProps = {
email: string | undefined;
+ manifestId: string;
};
/**
* Email preview component.
*/
-export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.ReactNode => {
+export const EmailPreview: React.FC<EmailPreviewProps> = ({ email, manifestId }) : React.ReactNode => {
const [emails, setEmails] = useState<MailboxEmail[]>([]);
const [displayedEmails, setDisplayedEmails] = useState<MailboxEmail[]>([]);
const [loading, setLoading] = useState(true);
@@ -39,6 +44,8 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
const [error, setError] = useState<string | null>(null);
const [isSupportedDomain, setIsSupportedDomain] = useState(false);
const [displayedCount, setDisplayedCount] = useState(2);
+ const [ownerNotice, setOwnerNotice] = useState<AliasOwnerNotice | null>(null);
+ const { showConfirm } = useDialog();
const webApi = useWebApi();
const dbContext = useDb();
const colors = useColors();
@@ -188,7 +195,8 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
// Use single emailbox operator instead of bulk
const response = await webApi.authFetch(`EmailBox/${email}`, { method: 'GET' }, true, false);
try {
- const data = response as { mails: MailboxEmail[]; publicKeys: string[] };
+ const data = response as Mailbox;
+ setOwnerNotice(aliasOwnerNotice(email, data, manifestId, await dbContext.sqliteClient.getPersonalManifestId(), await dbContext.sqliteClient.folders.getAll()));
// Store all emails, sorted by date
const allMails = data.mails
@@ -225,7 +233,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
}
markPollFailed(`The server rejected the mailbox request: ${apiErrorResponse?.code ?? 'unknown'}`);
- setError(t(`apiErrors.${apiErrorResponse?.code}`, { defaultValue: t('common.errors.unknownErrorTryAgain') }));
+ setError(aliasOwnerErrorText(apiErrorResponse?.code) ?? t(`apiErrors.${apiErrorResponse?.code}`, { defaultValue: t('common.errors.unknownErrorTryAgain') }));
return;
}
} catch (err) {
@@ -265,7 +273,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
clearTimeout(timer);
}
};
- }, [email, loading, webApi, dbContext, isPublicDomain, isPrivateDomain, isComponentVisible, t, displayedCount, updateDisplayedEmails]);
+ }, [email, manifestId, loading, webApi, dbContext, isPublicDomain, isPrivateDomain, isComponentVisible, t, displayedCount, updateDisplayedEmails]);
const styles = StyleSheet.create({
date: {
@@ -305,6 +313,31 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
paddingHorizontal: 16,
paddingVertical: 10,
},
+ moveButton: {
+ alignSelf: 'flex-start',
+ backgroundColor: colors.primary,
+ borderRadius: 8,
+ marginTop: 8,
+ paddingHorizontal: 12,
+ paddingVertical: 8,
+ },
+ moveButtonText: {
+ color: colors.primarySurfaceText,
+ fontSize: 14,
+ fontWeight: '600',
+ },
+ ownerNotice: {
+ backgroundColor: colors.accentBackground,
+ borderColor: colors.accentBorder,
+ borderRadius: 8,
+ borderWidth: 1,
+ marginTop: 8,
+ padding: 12,
+ },
+ ownerNoticeText: {
+ color: colors.text,
+ fontSize: 14,
+ },
loadMoreText: {
color: colors.textMuted,
fontSize: 14,
@@ -348,6 +381,32 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
return null;
}
+ /**
+ * Move the alias to this item's vault after confirmation, then reload.
+ */
+ const confirmMoveHere = (moveConfirm: string): void => {
+ showConfirm(familySharingText.aliasOwner.moveHere, moveConfirm, t('common.confirm'), async () => {
+ try {
+ await moveAliasHere(webApi, email, manifestId);
+ setOwnerNotice(null);
+ setLoading(true);
+ } catch (err) {
+ setError(aliasOwnerErrorText(apiErrorCodeOf(err)) ?? t('common.errors.unknownErrorTryAgain'));
+ }
+ });
+ };
+
+ const ownerNoticeBlock = ownerNotice && (
+ <View style={styles.ownerNotice}>
+ <ThemedText style={styles.ownerNoticeText}>{ownerNotice.notice}</ThemedText>
+ {ownerNotice.canMove && (
+ <TouchableOpacity style={styles.moveButton} onPress={() => confirmMoveHere(ownerNotice.moveConfirm)} testID="move-alias-here">
+ <ThemedText style={styles.moveButtonText}>{familySharingText.aliasOwner.moveHere}</ThemedText>
+ </TouchableOpacity>
+ )}
+ </View>
+ );
+
// Don't render anything if the domain is not supported
if (!isSupportedDomain) {
return null;
@@ -397,6 +456,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
<ThemedText type="title" style={styles.title}>{t('common.recentEmails')}</ThemedText>
<PulseDot />
</View>
+ {ownerNoticeBlock}
<ThemedText style={styles.placeholderText}>{t('items.noEmailsYet')}</ThemedText>
</ThemedView>
);
@@ -408,6 +468,7 @@ export const EmailPreview: React.FC<EmailPreviewProps> = ({ email }) : React.Rea
<ThemedText type="title" style={styles.title}>{t('common.recentEmails')}</ThemedText>
<PulseDot />
</View>
+ {ownerNoticeBlock}
{displayedEmails.map((mail) => (
<TouchableOpacity
key={mail.id}
diff --git a/apps/server/AliasVault.Admin/Main/Models/EmailClaimWithCount.cs b/apps/server/AliasVault.Admin/Main/Models/EmailClaimWithCount.cs
index 066aecd55..2dbcff3ea 100644
--- a/apps/server/AliasVault.Admin/Main/Models/EmailClaimWithCount.cs
+++ b/apps/server/AliasVault.Admin/Main/Models/EmailClaimWithCount.cs
@@ -10,7 +10,7 @@ namespace AliasVault.Admin.Main.Models;
using AliasServerDb;
/// <summary>
-/// An email claim as seen from one manifest, with the number of emails stored for its address.
+/// An email claim with the number of emails stored for its address.
/// </summary>
public class EmailClaimWithCount
{
@@ -25,9 +25,9 @@ public class EmailClaimWithCount
public string Address { get; set; } = string.Empty;
/// <summary>
- /// Gets or sets what the manifest's link to this claim says about the alias right now.
+ /// Gets or sets the state of the alias in its owning manifest.
/// </summary>
- public EmailClaimLinkState State { get; set; }
+ public EmailClaimState State { get; set; }
/// <summary>
/// Gets or sets the created at timestamp.
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Dashboard/Components/RecentActiveUsersCard.razor b/apps/server/AliasVault.Admin/Main/Pages/Dashboard/Components/RecentActiveUsersCard.razor
index 6a52f71e8..eeeaab15b 100644
--- a/apps/server/AliasVault.Admin/Main/Pages/Dashboard/Components/RecentActiveUsersCard.razor
+++ b/apps/server/AliasVault.Admin/Main/Pages/Dashboard/Components/RecentActiveUsersCard.razor
@@ -70,7 +70,7 @@
u.TwoFactorEnabled,
LastActivityDate = u.LastActivityDate!.Value,
CredentialCount = dbContext.VaultManifests.Where(m => m.OwnerGroupId == u.PersonalGroupId).Sum(m => m.CredentialsCount),
- EmailClaimCount = dbContext.EmailClaimLinks.Count(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == u.PersonalGroupId),
+ EmailClaimCount = dbContext.EmailClaims.Count(c => c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == u.PersonalGroupId),
})
.ToListAsync();
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor
index b59465d37..36899aa9e 100644
--- a/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor
+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/Users.razor
@@ -192,7 +192,7 @@ else
x.User.LastActivityDate,
x.VaultStorageKb,
CredentialCount = dbContext.VaultManifests.Where(m => m.OwnerGroupId == x.User.PersonalGroupId).Sum(m => m.CredentialsCount),
- EmailClaimCount = dbContext.EmailClaimLinks.Count(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == x.User.PersonalGroupId),
+ EmailClaimCount = dbContext.EmailClaims.Count(c => c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == x.User.PersonalGroupId),
})
.ToListAsync(cancellationToken);
@@ -317,8 +317,8 @@ else
? query.OrderBy(x => dbContext.VaultManifests.Where(m => m.OwnerGroupId == x.User.PersonalGroupId).Sum(m => m.CredentialsCount))
: query.OrderByDescending(x => dbContext.VaultManifests.Where(m => m.OwnerGroupId == x.User.PersonalGroupId).Sum(m => m.CredentialsCount)),
"EmailClaimCount" => ascending
- ? query.OrderBy(x => dbContext.EmailClaimLinks.Count(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == x.User.PersonalGroupId))
- : query.OrderByDescending(x => dbContext.EmailClaimLinks.Count(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == x.User.PersonalGroupId)),
+ ? query.OrderBy(x => dbContext.EmailClaims.Count(c => c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == x.User.PersonalGroupId))
+ : query.OrderByDescending(x => dbContext.EmailClaims.Count(c => c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == x.User.PersonalGroupId)),
"VaultStorageInKb" => ascending ? query.OrderBy(x => x.VaultStorageKb) : query.OrderByDescending(x => x.VaultStorageKb),
_ => ascending ? query.OrderBy(x => x.User.Id) : query.OrderByDescending(x => x.User.Id),
};
diff --git a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/EmailClaimTable.razor b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/EmailClaimTable.razor
index 65edd96d2..1a8f03f25 100644
--- a/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/EmailClaimTable.razor
+++ b/apps/server/AliasVault.Admin/Main/Pages/Users/View/Components/EmailClaimTable.razor
@@ -5,7 +5,7 @@
<Button Color="secondary" OnClick="ToggleShowRemoved">
@(ShowRemoved ? "Hide removed aliases" : "Show removed aliases")
</Button>
- @if (EmailClaimList.Any(e => e.State != EmailClaimLinkState.Removed))
+ @if (EmailClaimList.Any(e => e.State != EmailClaimState.Removed))
{
<Button Color="danger" OnClick="RemoveAllEmailClaims">Disable All</Button>
}
@@ -21,7 +21,7 @@ else
<SortableTable Columns="@_emailClaimTableColumns" SortColumn="@SortColumn" SortDirection="@SortDirection" OnSortChanged="HandleSortChanged">
@foreach (var entry in SortedEmailClaimList)
{
- <SortableTableRow Class="@(entry.State == EmailClaimLinkState.Removed ? "bg-secondary" : "")">
+ <SortableTableRow Class="@(entry.State == EmailClaimState.Removed ? "bg-secondary" : "")">
<SortableTableColumn IsPrimary="true">@entry.Id</SortableTableColumn>
<SortableTableColumn>@entry.CreatedAt.ToString("yyyy-MM-dd HH:mm")</SortableTableColumn>
<SortableTableColumn><a href="[email protected]">@entry.Address</a></SortableTableColumn>
@@ -29,10 +29,10 @@ else
<SortableTableColumn>
@switch (entry.State)
{
- case EmailClaimLinkState.Active:
+ case EmailClaimState.Active:
<StatusPill Enabled="true" TextTrue="Active" />
break;
- case EmailClaimLinkState.Paused:
+ case EmailClaimState.Paused:
<span class="bg-yellow-100 text-yellow-800 text-xs font-medium px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300" title="The user switched this alias off. Stored mail stays readable, new mail is rejected.">Paused</span>
break;
default:
@@ -41,13 +41,13 @@ else
}
</SortableTableColumn>
<SortableTableColumn>
- @if (entry.State == EmailClaimLinkState.Removed)
+ @if (entry.State == EmailClaimState.Removed)
{
- <Button Color="success" OnClick="() => SetLinkStateAsync(entry, EmailClaimLinkState.Active)">Enable</Button>
+ <Button Color="success" OnClick="() => SetClaimStateAsync(entry, EmailClaimState.Active)">Enable</Button>
}
else
{
- <Button Color="danger" OnClick="() => SetLinkStateAsync(entry, EmailClaimLinkState.Removed)">Disable</Button>
+ <Button Color="danger" OnClick="() => SetClaimStateAsync(entry, EmailClaimState.Removed)">Disable</Button>
}
</SortableTableColumn>
</SortableTableRow>
@@ -89,7 +89,7 @@ else
];
private IEnumerable<EmailClaimWithCount> SortedEmailClaimList =>
- SortList(ShowRemoved ? EmailClaimList : EmailClaimList.Where(e => e.State != EmailClaimLinkState.Removed).ToList(), SortColumn, SortDirection);
+ SortList(ShowRemoved ? EmailClaimList : EmailClaimList.Where(e => e.State != EmailClaimState.Removed).ToList(), SortColumn, SortDirection);
/// <inheritdoc />
protected override async Task OnInitializedAsync()
@@ -104,7 +104,7 @@ else
}
/// <summary>
- /// Loads the claims linked to the user's personal manifest, in any state, with the number of stored emails per address.
+ /// Loads the claims owned by the user's personal manifest, in any state, with the number of stored emails per address.
/// </summary>
private async Task RefreshData()
{
@@ -116,20 +116,20 @@ else
return;
}
- var links = await dbContext.EmailClaimLinks
- .Where(l => l.VaultManifest.OwnerGroupId == User.PersonalGroupId)
- .Select(l => new { l.EmailClaim.Id, l.EmailClaim.Address, l.EmailClaim.CreatedAt, l.EmailClaim.UpdatedAt, l.State })
+ var claims = await dbContext.EmailClaims
+ .Where(c => c.VaultManifest!.OwnerGroupId == User.PersonalGroupId)
+ .Select(c => new { c.Id, c.Address, c.CreatedAt, c.UpdatedAt, c.State })
.OrderBy(x => x.CreatedAt)
.ToListAsync();
- var addresses = links.Select(x => x.Address).ToList();
+ var addresses = claims.Select(x => x.Address).ToList();
var emailCounts = await dbContext.Emails
.Where(e => addresses.Contains(e.To))
.GroupBy(e => e.To)
.Select(g => new { Address = g.Key, Count = g.Count() })
.ToDictionaryAsync(x => x.Address, x => x.Count);
- EmailClaimList = links.Select(x => new EmailClaimWithCount
+ EmailClaimList = claims.Select(x => new EmailClaimWithCount
{
Id = x.Id,
Address = x.Address,
@@ -157,13 +157,13 @@ else
}
/// <summary>
- /// Sets the state of the personal manifest's link to a claim. Disabling marks the link Removed, after which the
+ /// Sets the state of a claim owned by the personal manifest. Disabling marks it Removed, after which the
/// server rejects mail for the address; enabling puts it back to Active. The user's next vault sync recomputes
/// the state from their vault contents, so either change is undone as soon as the vault says otherwise.
/// </summary>
- private async Task SetLinkStateAsync(EmailClaimWithCount entry, EmailClaimLinkState state)
+ private async Task SetClaimStateAsync(EmailClaimWithCount entry, EmailClaimState state)
{
- if (state == EmailClaimLinkState.Removed && !await ConfirmModalService.ShowConfirmation(
+ if (state == EmailClaimState.Removed && !await ConfirmModalService.ShowConfirmation(
title: "Confirm Email Alias Disable",
message: @"Are you sure you want to disable this email alias?
@@ -177,10 +177,9 @@ Do you want to proceed with disabling this alias?"))
}
await using var dbContext = await DbContextFactory.CreateDbContextAsync();
- await dbContext.EmailClaimLinks
- .Where(l => l.EmailClaimId == entry.Id && l.VaultManifest.OwnerGroupId == User.PersonalGroupId)
- .ExecuteUpdateAsync(s => s.SetProperty(l => l.State, state));
- await dbContext.EmailClaims.Where(c => c.Id == entry.Id).ExecuteUpdateAsync(s => s.SetProperty(c => c.UpdatedAt, DateTime.UtcNow));
+ await dbContext.EmailClaims
+ .Where(c => c.Id == entry.Id && c.VaultManifest!.OwnerGroupId == User.PersonalGroupId)
+ .ExecuteUpdateAsync(s => s.SetProperty(c => c.State, state).SetProperty(c => c.UpdatedAt, DateTime.UtcNow));
await RefreshData();
}
@@ -198,9 +197,9 @@ Important notes:
Do you want to proceed with disabling all email aliases?"))
{
await using var dbContext = await DbContextFactory.CreateDbContextAsync();
- await dbContext.EmailClaimLinks
- .Where(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == User.PersonalGroupId)
- .ExecuteUpdateAsync(s => s.SetProperty(l => l.State, EmailClaimLinkState.Removed));
+ await dbContext.EmailClaims
+ .Where(c => c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == User.PersonalGroupId)
+ .ExecuteUpdateAsync(s => s.SetProperty(c => c.State, EmailClaimState.Removed));
await RefreshData();
}
diff --git a/apps/server/AliasVault.Admin/Services/StatisticsService.cs b/apps/server/AliasVault.Admin/Services/StatisticsService.cs
index 7257f401c..a6f9cad19 100644
--- a/apps/server/AliasVault.Admin/Services/StatisticsService.cs
+++ b/apps/server/AliasVault.Admin/Services/StatisticsService.cs
@@ -74,7 +74,7 @@ public class StatisticsService(IAliasServerDbContextFactory contextFactory)
return new ServerStatistics
{
TotalUsers = await context.AliasVaultUsers.CountAsync(),
- TotalAliases = await context.EmailClaims.CountAsync(c => c.Links.Any(l => l.State != EmailClaimLinkState.Removed)),
+ TotalAliases = await context.EmailClaims.CountAsync(c => c.State != EmailClaimState.Removed && c.VaultManifestId != null),
TotalEmails = await context.Emails.CountAsync(),
TotalVaultStorageKb = await context.AliasVaultUsers.WithVaultStorage(context).SumAsync(x => x.VaultStorageKb),
};
@@ -120,10 +120,10 @@ public class StatisticsService(IAliasServerDbContextFactory contextFactory)
{
await using var context = await contextFactory.CreateDbContextAsync();
- // A claim link is the ownership record of an alias; only links that are not Removed still carry it.
- var liveLinksPerUser = context.EmailClaimLinks
- .Where(l => l.State != EmailClaimLinkState.Removed)
- .Join(context.AliasVaultUsers, l => l.VaultManifest.OwnerGroupId, u => u.PersonalGroupId, (l, u) => new { u.Id, u.UserName, u.Blocked })
+ // Only claims that are not Removed are still carried by their owning manifest.
+ var liveLinksPerUser = context.EmailClaims
+ .Where(c => c.State != EmailClaimState.Removed)
+ .Join(context.AliasVaultUsers, c => c.VaultManifest!.OwnerGroupId, u => u.PersonalGroupId, (c, u) => new { u.Id, u.UserName, u.Blocked })
.GroupBy(x => new { x.Id, x.UserName, x.Blocked })
.Select(g => new { UserId = g.Key.Id, Username = g.Key.UserName, g.Key.Blocked, AliasCount = g.Count() });
@@ -226,7 +226,7 @@ public class StatisticsService(IAliasServerDbContextFactory contextFactory)
return new UserUsageStatistics
{
TotalCredentials = await context.VaultManifests.Where(m => m.OwnerGroupId == personalGroupId).SumAsync(m => m.CredentialsCount),
- ActiveEmailClaims = await context.EmailClaimLinks.CountAsync(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == personalGroupId),
+ ActiveEmailClaims = await context.EmailClaims.CountAsync(c => c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == personalGroupId),
TotalReceivedEmails = await context.Emails.CountAsync(e => e.DecryptionKeys.Any(d => d.VaultManifestDeliveryKey.VaultManifest.OwnerGroupId == personalGroupId)),
};
}
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
index a57d096d4..3ee52d231 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailBoxController.cs
@@ -50,9 +50,8 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var sanitizedEmail = to.Trim().ToLower();
// Unclaimed and claimed by someone else return the same error on purpose.
- var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail && x.Links.Any(l => l.State != EmailClaimLinkState.Removed));
- var hasPersonalLink = emailClaim is not null && await context.EmailClaimLinks.AnyAsync(l => l.EmailClaimId == emailClaim.Id && l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId);
- if (!hasPersonalLink)
+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail && x.State != EmailClaimState.Removed && x.VaultManifest!.OwnerGroupId == user.PersonalGroupId);
+ if (emailClaim is null)
{
return BadRequest(new ApiErrorResponse
{
@@ -131,10 +130,9 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
model.PageSize = Math.Clamp(model.PageSize, 1, 50);
// Load all email addresses that the user has a claim to where the address is in the list.
- var validAddresses = await context.EmailClaimLinks
- .Where(l => model.Addresses.Contains(l.EmailClaim.Address) && l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId)
- .Select(l => l.EmailClaim.Address)
- .Distinct()
+ var validAddresses = await context.EmailClaims
+ .Where(c => model.Addresses.Contains(c.Address) && c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == user.PersonalGroupId)
+ .Select(c => c.Address)
.ToListAsync();
// The caller's personal keys: v1 clients only hold the private halves of these, so serve the matching decryption keys.
diff --git a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
index 20814bf9e..4d7dfbb41 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/Email/EmailController.cs
@@ -178,7 +178,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
{
await context.Emails
.Where(e => model.Ids.Contains(e.Id))
- .Where(e => context.EmailClaims.Any(c => c.Address == e.To.Trim().ToLower() && c.Links.Any(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId)))
+ .Where(e => context.EmailClaims.Any(c => c.Address == e.To.Trim().ToLower() && c.State != EmailClaimState.Removed && c.VaultManifest!.OwnerGroupId == user.PersonalGroupId))
.ExecuteDeleteAsync();
}
catch (Exception ex)
@@ -245,7 +245,7 @@ public class EmailController(ILogger<EmailController> logger, IAliasServerDbCont
var normalizedEmailAddress = email.To.Trim().ToLower();
var emailClaim = await context.EmailClaims
.Where(x => x.Address == normalizedEmailAddress)
- .FirstOrDefaultAsync(x => x.Links.Any(l => l.State != EmailClaimLinkState.Removed && l.VaultManifest.OwnerGroupId == user.PersonalGroupId));
+ .FirstOrDefaultAsync(x => x.State != EmailClaimState.Removed && x.VaultManifest!.OwnerGroupId == user.PersonalGroupId);
if (emailClaim is null)
{
diff --git a/apps/server/AliasVault.Api/Controllers/V1/IdentityController.cs b/apps/server/AliasVault.Api/Controllers/V1/IdentityController.cs
index 3338f7161..5dbaf203c 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/IdentityController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/IdentityController.cs
@@ -10,6 +10,7 @@ namespace AliasVault.Api.Controllers.V1;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
using AliasVault.Api.Helpers;
+using AliasVault.Api.Services;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@@ -20,8 +21,9 @@ using Microsoft.EntityFrameworkCore;
/// </summary>
/// <param name="userManager">UserManager instance.</param>
/// <param name="dbContextFactory">DbContextFactory instance.</param>
+/// <param name="takenAliasLookupRateLimit">Limits how many taken addresses a caller may learn about.</param>
[ApiVersion("1")]
-public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasServerDbContextFactory dbContextFactory) : AuthenticatedRequestController(userManager)
+public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasServerDbContextFactory dbContextFactory, TakenAliasLookupRateLimitService takenAliasLookupRateLimit) : AuthenticatedRequestController(userManager)
{
/// <summary>
/// Verify that provided email address is not already taken by another user.
@@ -37,7 +39,8 @@ public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasS
return Unauthorized();
}
- bool isTaken = await EmailClaimExistsAsync(email);
+ // Over the lookup limit a taken address reads as free; a later claim of it is still refused, this only slows down enumeration.
+ bool isTaken = await EmailClaimExistsAsync(email) && takenAliasLookupRateLimit.TryRecord(user.Id, RegistrationCheckRateLimit.GetClientKey(HttpContext), EmailHelper.SanitizeEmail(email));
return Ok(new { isTaken });
}
diff --git a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
index 16d0fe34e..e0a935f92 100644
--- a/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V1/VaultController.cs
@@ -410,12 +410,8 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
// multiple credentials share the same private email address.
newEmailAddresses = newEmailAddresses.Select(EmailHelper.SanitizeEmail).Distinct().ToList();
- // Get list of email claims owned by the user.
- var userOwnedEmailClaims = await context.EmailClaims
- .Include(x => x.Links)
- .Where(x => x.Links.Any(l => l.VaultManifestId == personalManifestId && l.State != EmailClaimLinkState.Removed)
- || (x.Links.All(l => l.State == EmailClaimLinkState.Removed) && x.Links.Any(l => l.VaultManifestId == personalManifestId)))
- .ToListAsync();
+ // Get list of email claims owned by the user's personal manifest, removed ones included.
+ var userOwnedEmailClaims = await context.EmailClaims.Where(x => x.VaultManifestId == personalManifestId).ToListAsync();
// Keep track of processed and sanitized email addresses to know which ones still exist.
var processedEmailAddresses = new List<string>();
@@ -436,13 +432,13 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
if (limit.WindowSeconds == 0)
{
// Global absolute cap: every claim ever billed to the caller's group.
- baseCount = await context.EmailClaimLinks.Where(l => l.VaultManifest.OwnerGroupId == user.PersonalGroupId).Select(l => l.EmailClaimId).Distinct().CountAsync();
+ baseCount = await context.EmailClaims.CountAsync(c => c.VaultManifest!.OwnerGroupId == user.PersonalGroupId);
}
else
{
// Time-based cap: aliases created within the rolling window (create-then-delete still counts).
var windowStart = timeProvider.GetUtcNow().UtcDateTime.AddSeconds(-limit.WindowSeconds);
- baseCount = await context.EmailClaimLinks.Where(l => l.EmailClaim.CreatedAt >= windowStart && l.VaultManifest.OwnerGroupId == user.PersonalGroupId).Select(l => l.EmailClaimId).Distinct().CountAsync();
+ baseCount = await context.EmailClaims.CountAsync(c => c.CreatedAt >= windowStart && c.VaultManifest!.OwnerGroupId == user.PersonalGroupId);
}
limitUsages.Add((limit.MaxCount, baseCount));
@@ -479,17 +475,14 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
var existingUserClaim = userOwnedEmailClaims.FirstOrDefault(x => x.Address == sanitizedEmail);
if (existingUserClaim != null)
{
- // The personal manifest carries the address again, so revive its link. A paused link keeps its pause:
+ // The personal manifest carries the address again, so revive the claim. A paused claim keeps its pause:
// v1 has no per-alias switch, and a v1 sync must never undo one set from a v2 client.
- var personalLink = existingUserClaim.Links.FirstOrDefault(l => l.VaultManifestId == personalManifestId);
- if (personalLink is { State: EmailClaimLinkState.Removed })
+ if (existingUserClaim.State == EmailClaimState.Removed)
{
- personalLink.State = EmailClaimLinkState.Active;
+ existingUserClaim.State = EmailClaimState.Active;
existingUserClaim.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
}
- // Reviving the link is all there is to re-enabling the alias: a claim counts as live for as long as
- // any of its links is not removed, so there is no separate flag to put back.
continue;
}
@@ -519,7 +512,7 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
{
context.EmailClaims.Add(new EmailClaim
{
- Links = [new EmailClaimLink { VaultManifestId = personalManifestId }],
+ VaultManifestId = personalManifestId,
Address = sanitizedEmail,
AddressLocal = sanitizedEmail.Split('@')[0],
AddressDomain = sanitizedEmail.Split('@')[1],
@@ -535,26 +528,10 @@ public class VaultController(ILogger<VaultController> logger, IAliasServerDbCont
}
}
- // Disable email claim links that are no longer in the new provided email claim list.
- foreach (var existingClaim in userOwnedEmailClaims)
+ // The addresses gone from the personal vault: mark their claims removed.
+ foreach (var existingClaim in userOwnedEmailClaims.Where(c => c.State != EmailClaimState.Removed && !processedEmailAddresses.Contains(c.Address)))
{
- if (processedEmailAddresses.Contains(existingClaim.Address))
- {
- continue;
- }
-
- // The address is gone from the personal vault: disable its link.
- var personalLinks = existingClaim.Links.Where(l => l.VaultManifestId == personalManifestId && l.State != EmailClaimLinkState.Removed).ToList();
- if (personalLinks.Count == 0)
- {
- continue;
- }
-
- foreach (var link in personalLinks)
- {
- link.State = EmailClaimLinkState.Removed;
- }
-
+ existingClaim.State = EmailClaimState.Removed;
existingClaim.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
index 6aa6a0c1d..084737a8e 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/Email/EmailBoxController.cs
@@ -10,7 +10,9 @@ namespace AliasVault.Api.Controllers.V2.Email;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
using AliasVault.Api.Helpers;
+using AliasVault.Api.Services;
using AliasVault.Auth.IpAddress;
+using AliasVault.Shared.Models.Enums;
using AliasVault.Shared.Models.WebApi;
using AliasVault.Shared.Models.WebApi.V2.Email;
using Asp.Versioning;
@@ -26,8 +28,9 @@ using NpgsqlTypes;
/// <param name="dbContextFactory">DbContext instance.</param>
/// <param name="userManager">UserManager instance.</param>
/// <param name="ipBlockListService">IpBlockListService used to shadow-block email retrieval from blocked IPs.</param>
+/// <param name="takenAliasLookupRateLimit">Limits how many taken addresses a caller may learn about.</param>
[ApiVersion("2")]
-public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IpBlockListService ipBlockListService) : AuthenticatedRequestController(userManager)
+public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, UserManager<AliasVaultUser> userManager, IpBlockListService ipBlockListService, TakenAliasLookupRateLimitService takenAliasLookupRateLimit) : AuthenticatedRequestController(userManager)
{
/// <summary>
/// Returns a list of emails for the provided email address.
@@ -49,11 +52,32 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var shadowCutoff = await ipBlockListService.GetShadowBlockCutoffAsync(user, IpAddressUtility.GetRawIpAddressFromContext(HttpContext));
var sanitizedEmail = to.Trim().ToLower();
-
- // Unclaimed and claimed by someone else return the same error, so this endpoint does not reveal which addresses are taken.
- var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail && x.Links.Any(l => l.State != EmailClaimLinkState.Removed));
- if (emailClaim is null || !await EmailAccessHelper.CanReadClaimAsync(context, emailClaim, user.Id))
+ var emailClaim = await context.EmailClaims.FirstOrDefaultAsync(x => x.Address == sanitizedEmail);
+ if (emailClaim is null || !await EmailAccessHelper.CanAccessOwnerAsync(context, emailClaim, user.Id))
{
+ if (emailClaim is not null && await EmailAccessHelper.IsOwnedWithinSharedGroupAsync(context, emailClaim, user.Id))
+ {
+ return BadRequest(new ApiErrorResponse
+ {
+ Message = "This email alias is owned by another vault.",
+ Code = nameof(ApiErrorCode.CLAIM_OWNED_BY_OTHER_VAULT),
+ StatusCode = StatusCodes.Status400BadRequest,
+ Timestamp = DateTime.UtcNow,
+ });
+ }
+
+ // Over the lookup limit a taken address falls back to the generic error, which slows down enumeration.
+ if (emailClaim is not null && takenAliasLookupRateLimit.TryRecord(user.Id, RegistrationCheckRateLimit.GetClientKey(HttpContext), sanitizedEmail))
+ {
+ return BadRequest(new ApiErrorResponse
+ {
+ Message = "This email address is already in use by another account.",
+ Code = nameof(ApiErrorCode.CLAIM_TAKEN),
+ StatusCode = StatusCodes.Status400BadRequest,
+ Timestamp = DateTime.UtcNow,
+ });
+ }
+
return BadRequest(new ApiErrorResponse
{
Message = "No claim exists for this email address.",
@@ -68,6 +92,13 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
var decryptableKeyIds = await EmailAccessHelper.ResolveDecryptableKeyIdsAsync(context, user.Id);
var keyTable = await EmailKeyTable.BuildAsync(context, decryptableKeyIds);
var emailQuery = context.Emails.AsNoTracking().Where(x => x.To == sanitizedEmail && x.DecryptionKeys.Any(d => decryptableKeyIds.Contains(d.VaultManifestDeliveryKeyId)));
+
+ // A removed alias still answers with its owner (so the client can offer to move it), but without its mail.
+ if (emailClaim.State == EmailClaimState.Removed)
+ {
+ emailQuery = emailQuery.Where(x => false);
+ }
+
if (shadowCutoff is not null)
{
emailQuery = emailQuery.Where(x => x.DateSystem <= shadowCutoff.Value);
@@ -109,6 +140,10 @@ public class EmailBoxController(IAliasServerDbContextFactory dbContextFactory, U
Subscribed = false,
PublicKeys = keyTable.PublicKeys,
Mails = emails,
+ OwnerManifestId = emailClaim.VaultManifestId,
+
+ // For now anyone who can open the owning manifest may move the alias, matching VaultController.TransferEmailClaim.
+ CanTransfer = true,
};
return Ok(returnValue);
diff --git a/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs b/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
index 829528f13..ccbaa8042 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/IdentityController.cs
@@ -10,6 +10,7 @@ namespace AliasVault.Api.Controllers.V2;
using AliasServerDb;
using AliasVault.Api.Controllers.Abstracts;
using AliasVault.Api.Helpers;
+using AliasVault.Api.Services;
using Asp.Versioning;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
@@ -20,8 +21,9 @@ using Microsoft.EntityFrameworkCore;
/// </summary>
/// <param name="userManager">UserManager instance.</param>
/// <param name="dbContextFactory">DbContextFactory instance.</param>
+/// <param name="takenAliasLookupRateLimit">Limits how many taken addresses a caller may learn about.</param>
[ApiVersion("2")]
-public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasServerDbContextFactory dbContextFactory) : AuthenticatedRequestController(userManager)
+public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasServerDbContextFactory dbContextFactory, TakenAliasLookupRateLimitService takenAliasLookupRateLimit) : AuthenticatedRequestController(userManager)
{
/// <summary>
/// Verify that provided email address is not already taken by another user.
@@ -37,7 +39,8 @@ public class IdentityController(UserManager<AliasVaultUser> userManager, IAliasS
return Unauthorized();
}
- bool isTaken = await EmailClaimExistsAsync(email);
+ // Over the lookup limit a taken address reads as free; a later claim of it is still refused, this only slows down enumeration.
+ bool isTaken = await EmailClaimExistsAsync(email) && takenAliasLookupRateLimit.TryRecord(user.Id, RegistrationCheckRateLimit.GetClientKey(HttpContext), EmailHelper.SanitizeEmail(email));
return Ok(new { isTaken });
}
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
index fc0a67d27..dd194fd8c 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -744,6 +744,63 @@ public class VaultController(
return Ok(rows);
}
+ /// <summary>
+ /// Moves an email alias to another manifest, which becomes its only owner. The caller must be able to open both the
+ /// current owning manifest and the target.
+ /// </summary>
+ /// <param name="model">The alias and the target manifest.</param>
+ /// <returns>Ok when the alias is owned by the target manifest.</returns>
+ [HttpPost("email-claims/transfer")]
+ public async Task<IActionResult> TransferEmailClaim([FromBody] EmailClaimTransferRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var user = await GetCurrentUserAsync();
+ if (user == null)
+ {
+ return Unauthorized();
+ }
+
+ var accessScope = await ManifestAccessHelper.ResolveScopeAsync(context, user.Id, user.PersonalGroupId);
+ var accessible = (await AccessibleManifests(context, accessScope).Select(m => m.ManifestId).ToListAsync()).ToHashSet();
+
+ var address = EmailHelper.SanitizeEmail(model.Address);
+ var claim = await context.EmailClaims.FirstOrDefaultAsync(c => c.Address == address);
+ if (claim?.VaultManifestId is not Guid sourceManifestId || !accessible.Contains(sourceManifestId))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.EMAIL_CLAIM_NOT_FOUND, 404));
+ }
+
+ if (!accessible.Contains(model.TargetManifestId))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ }
+
+ if (sourceManifestId == model.TargetManifestId)
+ {
+ return Ok();
+ }
+
+ // The alias is charged to the target's group from now on, so it has to fit that group's alias limit.
+ var targetGroupId = (await GroupHelper.GetOwnerGroupsAsync(context, [model.TargetManifestId]))[model.TargetManifestId];
+ var remaining = await GetRemainingAliasAllowancesAsync(context, user, [targetGroupId]);
+ if (remaining.TryGetValue(targetGroupId, out var left) && left <= 0)
+ {
+ return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.ALIAS_LIMIT_REACHED, 400));
+ }
+
+ claim.VaultManifestId = model.TargetManifestId;
+ if (claim.State == EmailClaimState.Removed)
+ {
+ claim.State = EmailClaimState.Active;
+ }
+
+ claim.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
+ await context.SaveChangesAsync();
+
+ logger.LogInformation("{User} transferred alias {Email} from manifest {Source} to manifest {Target}.", user.UserName, address, sourceManifestId, model.TargetManifestId);
+ return Ok();
+ }
+
/// <summary>
/// Gets the manifest ids that a user has admin access to.
/// </summary>
@@ -967,8 +1024,7 @@ public class VaultController(
private async Task<EmailRouting> BuildEmailRoutingAsync(AliasServerDbContext context, AliasVaultUser user)
{
var claims = await context.EmailClaims
- .Where(c => c.Links.Any(l => l.State != EmailClaimLinkState.Removed
- && context.GroupMembers.Any(gm => gm.GroupId == l.VaultManifest.OwnerGroupId && gm.UserId == user.Id && gm.Role == GroupRole.Owner)))
+ .Where(c => c.State != EmailClaimState.Removed && context.GroupMembers.Any(gm => gm.GroupId == c.VaultManifest!.OwnerGroupId && gm.UserId == user.Id && gm.Role == GroupRole.Owner))
.Select(c => c.Address)
.ToListAsync();
@@ -1033,7 +1089,9 @@ public class VaultController(
}
/// <summary>
- /// Updates the email claims based on the routing data pushed by the client.
+ /// Updates the email claims based on the routing data pushed by the client. Every claim has one owning manifest: a push
+ /// creates claims for new addresses and updates the claims owned by the manifests it speaks for. A pair that names any
+ /// other manifest for an existing address is ignored; moving an alias is an explicit transfer (see <see cref="TransferEmailClaim"/>).
/// </summary>
/// <param name="context">Database context.</param>
/// <param name="user">The calling user.</param>
@@ -1044,7 +1102,7 @@ public class VaultController(
// Get all unique emails with calculated state (active wins from paused in case there are multiple).
var pushedPairs = routing.EmailAddressList
.GroupBy(x => new { Address = EmailHelper.SanitizeEmail(x.Address), x.ManifestId })
- .Select(g => new { g.Key.Address, g.Key.ManifestId, State = g.All(x => x.Paused) ? EmailClaimLinkState.Paused : EmailClaimLinkState.Active })
+ .Select(g => new { g.Key.Address, g.Key.ManifestId, State = g.All(x => x.Paused) ? EmailClaimState.Paused : EmailClaimState.Active })
.ToList();
var accessibleManifests = (await ManifestAccessHelper.AccessibleManifests(context, scope).Select(m => m.ManifestId).ToListAsync()).ToHashSet();
@@ -1061,7 +1119,7 @@ public class VaultController(
return;
}
- var assertedPairs = new List<(string Address, Guid ManifestId, EmailClaimLinkState State)>();
+ var assertedPairs = new List<(string Address, Guid ManifestId, EmailClaimState State)>();
foreach (var pair in pushedPairs)
{
if (!accessibleManifests.Contains(pair.ManifestId))
@@ -1087,30 +1145,28 @@ public class VaultController(
.Where(k => assertedManifestIds.Contains(k.VaultManifestId) && k.IsPrimary)
.Select(k => k.VaultManifestId)
.ToListAsync()).ToHashSet();
- foreach (var (address, manifestId, _) in assertedPairs.Where(p => p.State == EmailClaimLinkState.Active && p.ManifestId != personalManifestId.Value && !manifestsWithDeliveryKey.Contains(p.ManifestId)))
+ foreach (var (address, manifestId, _) in assertedPairs.Where(p => p.State == EmailClaimState.Active && p.ManifestId != personalManifestId.Value && !manifestsWithDeliveryKey.Contains(p.ManifestId)))
{
logger.LogWarning("{User} claimed shared alias {Email} for manifest {Manifest} with no published delivery key; that manifest gets no wrap for its mail until a delivery key is published.", user.UserName, address, manifestId);
}
- // Per address: the manifests that carry it, each with the state the push puts that link in.
+ // Per address: the manifests that carry it, each with the state the push puts it in there.
var desiredByAddress = assertedPairs.GroupBy(p => p.Address).ToDictionary(g => g.Key, g => g.ToDictionary(p => p.ManifestId, p => p.State));
- // Get the claims this push may update.
- var scopedEmailClaims = await context.EmailClaims
- .Include(c => c.Links)
- .Where(c => c.Links.Any(l => updateScope.Contains(l.VaultManifestId)))
- .ToListAsync();
- var userOwnedEmailClaims = scopedEmailClaims
- .Where(c => c.Links.Any(l => updateScope.Contains(l.VaultManifestId) && l.State != EmailClaimLinkState.Removed) || c.Links.All(l => l.State == EmailClaimLinkState.Removed))
- .ToList();
- var processed = new HashSet<string>();
+ // The claims this push may touch: the ones owned by a manifest it speaks for, plus any existing claim on a pushed address.
+ var pushedAddresses = desiredByAddress.Keys.ToList();
+ var updateScopeIds = updateScope.Select(id => (Guid?)id).ToList();
+ var claims = await context.EmailClaims.Where(c => updateScopeIds.Contains(c.VaultManifestId) || pushedAddresses.Contains(c.Address)).ToListAsync();
+ var claimedAddresses = claims.Select(c => c.Address).ToHashSet();
+
var supportedDomains = config.PrivateEmailDomains;
+ var now = timeProvider.GetUtcNow().UtcDateTime;
- // Max-alias check: how many new aliases each quota subject (the group owning the linked manifest) may still create.
+ // Max-alias check: how many new aliases each quota subject (the group owning the manifest) may still create.
var remainingAliases = await GetRemainingAliasAllowancesAsync(context, user, ownerGroupByManifest.Values);
var limitLoggedFor = new HashSet<Guid>();
- // Check if the caller has enough quota to create a new link for the given manifest.
+ // Check if the caller has enough quota to create a new claim for the given manifest.
bool TryChargeQuota(Guid manifestId)
{
var quotaGroupId = ownerGroupByManifest.TryGetValue(manifestId, out var ownerGroupId) ? ownerGroupId : user.PersonalGroupId;
@@ -1133,129 +1189,50 @@ public class VaultController(
return true;
}
- foreach (var sanitized in pushedPairs.Select(p => p.Address).Distinct())
+ // New addresses: the first manifest to claim one owns it, preferring the caller's personal manifest when the push files it there.
+ foreach (var (address, desiredManifests) in desiredByAddress.Where(d => !claimedAddresses.Contains(d.Key)))
{
- processed.Add(sanitized);
-
- if (!new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(sanitized))
+ if (!new System.ComponentModel.DataAnnotations.EmailAddressAttribute().IsValid(address))
{
- logger.LogWarning("{User} tried to claim invalid email: {Email}", user.UserName, sanitized);
+ logger.LogWarning("{User} tried to claim invalid email: {Email}", user.UserName, address);
continue;
}
- var domain = sanitized.Split('@')[1];
+ var domain = address.Split('@')[1];
if (!supportedDomains.Contains(domain))
{
- logger.LogWarning("{User} tried to claim unsupported domain: {Email}", user.UserName, sanitized);
- continue;
- }
-
- // 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 desiredManifests) || desiredManifests.Count == 0)
- {
- continue;
- }
-
- var existing = userOwnedEmailClaims.FirstOrDefault(x => x.Address == sanitized);
- if (existing != null)
- {
- var changed = false;
- foreach (var (manifestId, state) in desiredManifests)
- {
- var link = existing.Links.FirstOrDefault(l => l.VaultManifestId == manifestId);
- if (link is null)
- {
- if (TryChargeQuota(manifestId))
- {
- existing.Links.Add(new EmailClaimLink { EmailClaimId = existing.Id, VaultManifestId = manifestId, State = state });
- changed = true;
- }
-
- continue;
- }
-
- if (link.State != state)
- {
- link.State = state;
- changed = true;
- }
- }
-
- // Links in the caller's update scope that this push no longer carries: those manifests dropped the alias.
- var inScopeLinks = existing.Links.Where(l => l.State != EmailClaimLinkState.Removed && updateScope.Contains(l.VaultManifestId));
- var droppedLinks = inScopeLinks.Where(l => !desiredManifests.ContainsKey(l.VaultManifestId)).ToList();
- if (droppedLinks.Count > 0 && existing.Links.All(l => l.State == EmailClaimLinkState.Removed || droppedLinks.Contains(l)))
- {
- // The push carries this address, yet every link would end up removed: the links it named were all
- // blocked (e.g. by quota). Keep the previous ones rather than disable an alias the vault still has.
- logger.LogWarning("{User} pushed {Email} but none of its links could be created; keeping its previous links.", user.UserName, sanitized);
- droppedLinks.Clear();
- }
-
- foreach (var dropped in droppedLinks)
- {
- dropped.State = EmailClaimLinkState.Removed;
- changed = true;
- }
-
- if (changed)
- {
- existing.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
- }
-
- continue;
- }
-
- // 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))
- {
- logger.LogWarning("{User} tried to claim email already owned by another user: {Email}", user.UserName, sanitized);
+ logger.LogWarning("{User} tried to claim unsupported domain: {Email}", user.UserName, address);
continue;
}
- var newLinks = new List<EmailClaimLink>();
- foreach (var (manifestId, state) in desiredManifests)
- {
- if (TryChargeQuota(manifestId))
- {
- newLinks.Add(new EmailClaimLink { VaultManifestId = manifestId, State = state });
- }
- }
-
- if (newLinks.Count == 0)
+ var ownerManifestId = desiredManifests.ContainsKey(personalManifestId.Value) ? personalManifestId.Value : desiredManifests.Keys.First();
+ if (!TryChargeQuota(ownerManifestId))
{
continue;
}
context.EmailClaims.Add(new EmailClaim
{
- Links = newLinks,
- Address = sanitized,
- AddressLocal = sanitized.Split('@')[0],
- AddressDomain = sanitized.Split('@')[1],
- CreatedAt = timeProvider.GetUtcNow().UtcDateTime,
- UpdatedAt = timeProvider.GetUtcNow().UtcDateTime,
+ VaultManifestId = ownerManifestId,
+ State = desiredManifests[ownerManifestId],
+ Address = address,
+ AddressLocal = address.Split('@')[0],
+ AddressDomain = domain,
+ CreatedAt = now,
+ UpdatedAt = now,
});
}
- // An address that is no longer pushed is dropped by every manifest in the caller's update scope: their links go to
- // removed, and once that leaves no manifest carrying the address the claim reads as dead. The rows stay behind
- // as the ownership record, which is what lets the same manifests claim the address back later.
- foreach (var claim in userOwnedEmailClaims.Where(x => !processed.Contains(x.Address)))
+ // Claims owned by a manifest this push speaks for take the state the push gives them there, or Removed when that
+ // manifest no longer carries the address. A Removed claim stays owned, so only this manifest can claim it back.
+ foreach (var claim in claims.Where(c => c.VaultManifestId is Guid owner && updateScope.Contains(owner)))
{
- var droppedLinks = claim.Links.Where(l => l.State != EmailClaimLinkState.Removed && updateScope.Contains(l.VaultManifestId)).ToList();
- if (droppedLinks.Count == 0)
+ var state = desiredByAddress.TryGetValue(claim.Address, out var desired) && desired.TryGetValue(claim.VaultManifestId!.Value, out var pushed) ? pushed : EmailClaimState.Removed;
+ if (claim.State != state)
{
- continue;
+ claim.State = state;
+ claim.UpdatedAt = now;
}
-
- foreach (var link in droppedLinks)
- {
- link.State = EmailClaimLinkState.Removed;
- }
-
- claim.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
}
}
@@ -1286,14 +1263,14 @@ public class VaultController(
int currentCount;
if (limit.WindowSeconds == 0)
{
- // Global absolute cap: every claim ever charged to this group. A claim is charged to every group it is linked into.
- currentCount = await context.EmailClaimLinks.Where(l => l.VaultManifest.OwnerGroupId == groupId).Select(l => l.EmailClaimId).Distinct().CountAsync();
+ // Global absolute cap: every claim owned by one of this group's manifests, removed ones included.
+ currentCount = await context.EmailClaims.CountAsync(c => c.VaultManifest!.OwnerGroupId == groupId);
}
else
{
// Time-based cap: aliases created within the rolling window (create-then-delete still counts).
var windowStart = timeProvider.GetUtcNow().UtcDateTime.AddSeconds(-limit.WindowSeconds);
- currentCount = await context.EmailClaimLinks.Where(l => l.EmailClaim.CreatedAt >= windowStart && l.VaultManifest.OwnerGroupId == groupId).Select(l => l.EmailClaimId).Distinct().CountAsync();
+ currentCount = await context.EmailClaims.CountAsync(c => c.CreatedAt >= windowStart && c.VaultManifest!.OwnerGroupId == groupId);
}
var allowed = limit.MaxCount - currentCount;
diff --git a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs
index 70f6af807..d639fe77b 100644
--- a/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/EmailAccessHelper.cs
@@ -21,11 +21,49 @@ public static class EmailAccessHelper
/// <param name="context">Database context.</param>
/// <param name="claim">The email claim to check access for.</param>
/// <param name="userId">The user requesting access.</param>
- /// <returns>True when the alias is linked to a manifest the user can access.</returns>
+ /// <returns>True when the alias is owned by a manifest the user can access.</returns>
public static async Task<bool> CanReadClaimAsync(AliasServerDbContext context, EmailClaim claim, string userId)
{
var accessible = await AccessibleManifestsAsync(context, userId);
- return await context.EmailClaimLinks.AnyAsync(l => l.EmailClaimId == claim.Id && l.State != EmailClaimLinkState.Removed && accessible.Any(m => m.ManifestId == l.VaultManifestId));
+ return claim.State != EmailClaimState.Removed && claim.VaultManifestId is Guid owner && await accessible.AnyAsync(m => m.ManifestId == owner);
+ }
+
+ /// <summary>
+ /// Check if the user can open the manifest that owns the email claim, whatever the claim's state.
+ /// </summary>
+ /// <param name="context">Database context.</param>
+ /// <param name="claim">The email claim to check.</param>
+ /// <param name="userId">The user requesting access.</param>
+ /// <returns>True when the owning manifest is accessible to the user.</returns>
+ public static async Task<bool> CanAccessOwnerAsync(AliasServerDbContext context, EmailClaim claim, string userId)
+ {
+ var accessible = await AccessibleManifestsAsync(context, userId);
+ return claim.VaultManifestId is Guid owner && await accessible.AnyAsync(m => m.ManifestId == owner);
+ }
+
+ /// <summary>
+ /// Check if the email claim is owned by a vault of someone the user shares a group with: a shared vault of that group, or
+ /// the personal vault of one of its members. Only then may the user learn that the address is owned elsewhere.
+ /// </summary>
+ /// <param name="context">Database context.</param>
+ /// <param name="claim">The email claim to check.</param>
+ /// <param name="userId">The user asking.</param>
+ /// <returns>True when the claim's owner is within one of the user's shared groups.</returns>
+ public static async Task<bool> IsOwnedWithinSharedGroupAsync(AliasServerDbContext context, EmailClaim claim, string userId)
+ {
+ if (claim.VaultManifestId is not Guid owner)
+ {
+ return false;
+ }
+
+ var ownerGroupId = await context.VaultManifests.Where(m => m.ManifestId == owner).Select(m => (Guid?)m.OwnerGroupId).FirstOrDefaultAsync();
+ if (ownerGroupId is null)
+ {
+ return false;
+ }
+
+ var sharedGroupIds = context.GroupMembers.Where(gm => gm.UserId == userId && gm.Group.Type == GroupType.Shared).Select(gm => gm.GroupId);
+ return await context.GroupMembers.AnyAsync(gm => sharedGroupIds.Contains(gm.GroupId) && (gm.GroupId == ownerGroupId || gm.User.PersonalGroupId == ownerGroupId));
}
/// <summary>
@@ -43,10 +81,9 @@ public static class EmailAccessHelper
}
var accessible = await AccessibleManifestsAsync(context, userId);
- return await context.EmailClaimLinks
- .Where(l => addresses.Contains(l.EmailClaim.Address) && l.State != EmailClaimLinkState.Removed && accessible.Any(m => m.ManifestId == l.VaultManifestId))
- .Select(l => l.EmailClaim.Address)
- .Distinct()
+ return await context.EmailClaims
+ .Where(c => addresses.Contains(c.Address) && c.State != EmailClaimState.Removed && accessible.Any(m => m.ManifestId == c.VaultManifestId))
+ .Select(c => c.Address)
.ToListAsync();
}
diff --git a/apps/server/AliasVault.Api/Helpers/GrantHelper.cs b/apps/server/AliasVault.Api/Helpers/GrantHelper.cs
index 41b645ca9..dc725afc5 100644
--- a/apps/server/AliasVault.Api/Helpers/GrantHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/GrantHelper.cs
@@ -99,15 +99,6 @@ public static class GrantHelper
}
context.VaultManifestAccessKeys.RemoveRange(grants);
-
- var personalGroupId = await GroupHelper.GetPersonalGroupIdAsync(context, userId);
- if (personalGroupId is not null)
- {
- await context.EmailClaimLinks
- .Where(l => l.VaultManifest.OwnerGroupId == personalGroupId.Value && context.EmailClaimLinks.Any(s => s.EmailClaimId == l.EmailClaimId && s.VaultManifestId == manifestId))
- .ExecuteUpdateAsync(s => s.SetProperty(l => l.State, EmailClaimLinkState.Removed));
- }
-
return true;
}
diff --git a/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs b/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
index 96b81cb57..80a846696 100644
--- a/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
+++ b/apps/server/AliasVault.Api/Helpers/RegistrationCheckRateLimit.cs
@@ -66,7 +66,9 @@ public static class RegistrationCheckRateLimit
/// <summary>
/// The client IP as partition key, IPv6 reduced to its /64 since a single client usually controls a whole /64.
/// </summary>
- private static string GetClientKey(HttpContext httpContext)
+ /// <param name="httpContext">The current request.</param>
+ /// <returns>The partition key of the client.</returns>
+ public static string GetClientKey(HttpContext httpContext)
{
var ip = IpAddressUtility.GetRawIpAddressFromContext(httpContext);
if (ip is null)
diff --git a/apps/server/AliasVault.Api/Program.cs b/apps/server/AliasVault.Api/Program.cs
index 149f3c3ff..f6d5a6363 100644
--- a/apps/server/AliasVault.Api/Program.cs
+++ b/apps/server/AliasVault.Api/Program.cs
@@ -94,6 +94,7 @@ builder.Services.AddScoped<RegistrationInviteService>();
builder.Services.AddScoped<IpBlockListService>();
builder.Services.AddScoped<MobileLoginRateLimitService>();
builder.Services.AddSingleton<FaviconRateLimitService>();
+builder.Services.AddSingleton<TakenAliasLookupRateLimitService>();
builder.Services.AddScoped<RateLimitService>();
builder.Services.AddScoped<CapabilityService>();
builder.Services.AddHttpContextAccessor();
diff --git a/apps/server/AliasVault.Api/Services/TakenAliasLookupRateLimitService.cs b/apps/server/AliasVault.Api/Services/TakenAliasLookupRateLimitService.cs
new file mode 100644
index 000000000..ca01dc9dd
--- /dev/null
+++ b/apps/server/AliasVault.Api/Services/TakenAliasLookupRateLimitService.cs
@@ -0,0 +1,121 @@
+//-----------------------------------------------------------------------
+// <copyright file="TakenAliasLookupRateLimitService.cs" company="aliasvault">
+// Copyright (c) aliasvault. All rights reserved.
+// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
+// </copyright>
+//-----------------------------------------------------------------------
+
+namespace AliasVault.Api.Services;
+
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using Microsoft.Extensions.Logging;
+
+/// <summary>
+/// In-memory limit on how many distinct taken addresses an account and a source IP may learn about per 24 hours.
+/// Asking again about an address already counted is free, so polling a mailbox never runs into it. State is held in
+/// process (not shared across instances).
+/// </summary>
+/// <param name="logger">Logger, warned once per account or IP per window when it hits the limit.</param>
+public sealed class TakenAliasLookupRateLimitService(ILogger<TakenAliasLookupRateLimitService> logger)
+{
+ /// <summary>
+ /// Maximum distinct taken addresses one account may learn about per window.
+ /// </summary>
+ public const int MaxPerUser = 50;
+
+ /// <summary>
+ /// Maximum distinct taken addresses one source IP may learn about per window, across accounts.
+ /// </summary>
+ public const int MaxPerIp = 200;
+
+ private static readonly TimeSpan WindowDuration = TimeSpan.FromHours(24);
+
+ private readonly ConcurrentDictionary<string, SeenAddresses> _byUser = new();
+ private readonly ConcurrentDictionary<string, SeenAddresses> _byIp = new();
+
+ /// <summary>
+ /// Records that the caller learns <paramref name="address"/> is taken, when both the account and the IP still have room.
+ /// </summary>
+ /// <param name="userId">The authenticated user id.</param>
+ /// <param name="ipKey">The source IP key.</param>
+ /// <param name="address">The taken address.</param>
+ /// <returns>True when the caller may be told the address is taken; false when a limit has been reached.</returns>
+ public bool TryRecord(string userId, string ipKey, string address)
+ {
+ var user = _byUser.GetOrAdd(userId, _ => new SeenAddresses());
+ var ip = _byIp.GetOrAdd(ipKey, _ => new SeenAddresses());
+ var now = DateTime.UtcNow;
+
+ // Fixed lock order (user, then IP) so two requests can never deadlock on each other.
+ lock (user)
+ {
+ lock (ip)
+ {
+ var userHasRoom = user.HasRoom(address, MaxPerUser, now);
+ var ipHasRoom = ip.HasRoom(address, MaxPerIp, now);
+ if (!userHasRoom || !ipHasRoom)
+ {
+ if (!userHasRoom && user.ShouldWarn(now))
+ {
+ logger.LogWarning("User {UserId} looked up more than {Max} distinct taken email addresses within 24 hours; possible alias enumeration.", userId, MaxPerUser);
+ }
+
+ if (!ipHasRoom && ip.ShouldWarn(now))
+ {
+ logger.LogWarning("IP {IpKey} looked up more than {Max} distinct taken email addresses within 24 hours; possible alias enumeration.", ipKey, MaxPerIp);
+ }
+
+ return false;
+ }
+
+ user.Add(address, now);
+ ip.Add(address, now);
+ return true;
+ }
+ }
+ }
+
+ /// <summary>
+ /// The distinct addresses one key has learned about, with the time each was first counted.
+ /// </summary>
+ private sealed class SeenAddresses
+ {
+ private readonly Dictionary<string, DateTime> _firstSeen = new(StringComparer.Ordinal);
+ private DateTime? _warnedAt;
+
+ /// <summary>
+ /// Whether the address is already counted or still fits under <paramref name="max"/>.
+ /// </summary>
+ public bool HasRoom(string address, int max, DateTime now)
+ {
+ var cutoff = now - WindowDuration;
+ foreach (var expired in _firstSeen.Where(e => e.Value < cutoff).Select(e => e.Key).ToList())
+ {
+ _firstSeen.Remove(expired);
+ }
+
+ return _firstSeen.ContainsKey(address) || _firstSeen.Count < max;
+ }
+
+ /// <summary>
+ /// Count the address, keeping its first-seen time when already counted.
+ /// </summary>
+ public void Add(string address, DateTime now) => _firstSeen.TryAdd(address, now);
+
+ /// <summary>
+ /// Whether hitting the limit should be logged now: once per window, so a polling client does not flood the log.
+ /// </summary>
+ public bool ShouldWarn(DateTime now)
+ {
+ if (_warnedAt is DateTime warnedAt && now - warnedAt < WindowDuration)
+ {
+ return false;
+ }
+
+ _warnedAt = now;
+ return true;
+ }
+ }
+}
diff --git a/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs b/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
index 24858701b..70f9391f1 100644
--- a/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
+++ b/apps/server/AliasVault.SmtpService/Handlers/DatabaseMessageStore.cs
@@ -390,20 +390,16 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
return false;
}
- // An alias may be claimed by several manifests at once (personal + shared). The mail is stored once, with
- // the symmetric key wrapped per linked manifest's primary delivery key.
- var links = await dbContext.EmailClaimLinks.Where(l => l.EmailClaimId == emailClaim.Id).Select(l => new { l.VaultManifestId, l.State }).ToListAsync(CancellationToken.None);
- if (links.Count == 0)
+ if (emailClaim.VaultManifestId is not Guid ownerManifestId)
{
- // The claim is orphaned: every manifest it was linked to no longer exists (owner deleted account).
+ // The claim is orphaned: the manifest that owned it no longer exists (owner deleted account or vault).
logger.LogInformation(
"Rejected email: email for {ToAddress} is claimed but its owning vault no longer exists. The owner has most likely deleted their account.",
toAddress.User + "@" + toAddress.Host);
return false;
}
- // Check whether any vault still carries the alias at all.
- if (links.All(l => l.State == EmailClaimLinkState.Removed))
+ if (emailClaim.State == EmailClaimState.Removed)
{
// Email claim is disabled, so we cannot process this email.
logger.LogInformation(
@@ -412,35 +408,28 @@ public class DatabaseMessageStore(ILogger<DatabaseMessageStore> logger, Config c
return false;
}
- // Check if there is at least one manifest that still carries the alias and wants its mail.
- var linkedManifestIds = links.Where(l => l.State == EmailClaimLinkState.Active).Select(l => l.VaultManifestId).ToList();
- if (linkedManifestIds.Count == 0)
+ if (emailClaim.State == EmailClaimState.Paused)
{
logger.LogInformation(
- "Rejected email: email for {ToAddress} is claimed but every vault that still carries it has the alias switched off.",
+ "Rejected email: email for {ToAddress} is claimed but the vault that carries it has the alias switched off.",
toAddress.User + "@" + toAddress.Host);
return false;
}
- // Resolve every linked manifest's primary delivery key.
- var deliveryKeys = await dbContext.VaultManifestDeliveryKeys.Where(x => linkedManifestIds.Contains(x.VaultManifestId) && x.IsPrimary).ToListAsync(CancellationToken.None);
- foreach (var keylessManifestId in linkedManifestIds.Except(deliveryKeys.Select(k => k.VaultManifestId)))
- {
- logger.LogWarning("Manifest {ManifestId} claims alias {ToAddress} but has no primary delivery key published; it gets no wrap for this email.", keylessManifestId, toAddress.User + "@" + toAddress.Host);
- }
-
+ // Resolve the owning manifest's primary delivery key.
+ var deliveryKeys = await dbContext.VaultManifestDeliveryKeys.Where(x => x.VaultManifestId == ownerManifestId && x.IsPrimary).ToListAsync(CancellationToken.None);
if (deliveryKeys.Count == 0)
{
- // No linked manifest has a published primary delivery key, so we cannot process this email.
+ // The owning manifest has no published primary delivery key, so we cannot process this email.
logger.LogCritical(
- "Rejected email: email for {ToAddress} cannot be processed. No primary delivery encryption key found for any of its manifests.",
- toAddress.User + "@" + toAddress.Host);
+ "Rejected email: email for {ToAddress} cannot be processed. No primary delivery encryption key found for manifest {ManifestId}.",
+ toAddress.User + "@" + toAddress.Host,
+ ownerManifestId);
return false;
}
- // Resolve the groups that own the wrapped-for manifests, only used to increment their EmailsReceived counters.
- var wrappedManifestIds = deliveryKeys.Select(k => k.VaultManifestId).ToList();
- var recipientGroupIds = await dbContext.VaultManifests.Where(m => wrappedManifestIds.Contains(m.ManifestId)).Select(m => m.OwnerGroupId).Distinct().ToListAsync(CancellationToken.None);
+ // Resolve the group that owns the manifest, only used to increment its EmailsReceived counter.
+ var recipientGroupIds = await dbContext.VaultManifests.Where(m => m.ManifestId == ownerManifestId).Select(m => m.OwnerGroupId).ToListAsync(CancellationToken.None);
var insertedId = await InsertEmailIntoDatabase(message, detachedParts, new MailAddress(toAddress.AsAddress()), deliveryKeys, recipientGroupIds, emailClaim.Id, emailClaim.AnonymizedSenderCounted);
logger.LogDebug("Email for {ToAddress} successfully saved into database with ID {InsertedId}.", toAddress.User + "@" + toAddress.Host, insertedId);
diff --git a/apps/server/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs b/apps/server/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs
index e5a49f0f9..850d18420 100644
--- a/apps/server/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs
+++ b/apps/server/AliasVault.TaskRunner/Tasks/DisabledEmailCleanupTask.cs
@@ -52,9 +52,9 @@ public class DisabledEmailCleanupTask : IMaintenanceTask
await using var dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
var cutoffDate = DateTime.UtcNow.AddDays(-settings.DisabledEmailRetentionDays);
- // An alias is dead once no manifest carries it anymore, which is what the absence of a live link says.
+ // An alias is dead once its owning manifest no longer carries it, or that manifest is gone.
var deletedCount = await dbContext.Emails
- .Where(e => e.DateSystem <= cutoffDate && dbContext.EmailClaims.Any(c => c.Address == e.To && !c.Links.Any(l => l.State != EmailClaimLinkState.Removed)))
+ .Where(e => e.DateSystem <= cutoffDate && dbContext.EmailClaims.Any(c => c.Address == e.To && (c.State == EmailClaimState.Removed || c.VaultManifestId == null)))
.ExecuteDeleteAsync(cancellationToken);
_logger.LogInformation("Deleted {Count} emails for aliases that no vault carries anymore.", deletedCount);
diff --git a/apps/server/AliasVault.TaskRunner/Tasks/EmailCleanupTask.cs b/apps/server/AliasVault.TaskRunner/Tasks/EmailCleanupTask.cs
index 86b3e2d15..e428b931f 100644
--- a/apps/server/AliasVault.TaskRunner/Tasks/EmailCleanupTask.cs
+++ b/apps/server/AliasVault.TaskRunner/Tasks/EmailCleanupTask.cs
@@ -79,8 +79,7 @@ public class EmailCleanupTask : IMaintenanceTask
// Get all email addresses this user's vault still carries.
var userAddresses = await dbContext.EmailClaims
- .Where(c => c.Links.Any(l => l.State != EmailClaimLinkState.Removed
- && dbContext.AliasVaultUsers.Any(u => u.Id == user.Id && u.PersonalGroupId == l.VaultManifest.OwnerGroupId)))
+ .Where(c => c.State != EmailClaimState.Removed && dbContext.AliasVaultUsers.Any(u => u.Id == user.Id && u.PersonalGroupId == c.VaultManifest!.OwnerGroupId))
.Select(c => c.Address)
.ToListAsync(cancellationToken);
diff --git a/apps/server/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs b/apps/server/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs
index 25094f5b0..98a532ee0 100644
--- a/apps/server/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs
+++ b/apps/server/AliasVault.TaskRunner/Tasks/EmailQuotaCleanupTask.cs
@@ -49,8 +49,8 @@ public class EmailQuotaCleanupTask : IMaintenanceTask
var usersWithClaims = await (from u in dbContext.AliasVaultUsers
join g in dbContext.Groups on u.PersonalGroupId equals g.Id
join m in dbContext.VaultManifests on g.Id equals m.OwnerGroupId
- join l in dbContext.EmailClaimLinks.Where(link => link.State != EmailClaimLinkState.Removed) on m.ManifestId equals l.VaultManifestId
- select new { u.Id, u.UserName, g.MaxEmails, u.LastActivityDate, u.CreatedAt, l.EmailClaim.Address })
+ join c in dbContext.EmailClaims.Where(claim => claim.State != EmailClaimState.Removed) on m.ManifestId equals c.VaultManifestId
+ select new { u.Id, u.UserName, g.MaxEmails, u.LastActivityDate, u.CreatedAt, c.Address })
.ToListAsync(cancellationToken);
// Get minimum activity date which is used to determine if user is active.
diff --git a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
index 763346fe7..32b54a3bd 100644
--- a/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
+++ b/apps/server/Databases/AliasServerDb/AliasServerDbContext.cs
@@ -96,11 +96,6 @@ 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 EmailDecryptionKeys DbSet.
/// </summary>
@@ -517,28 +512,22 @@ public class AliasServerDbContext : WorkerStatusDbContext, IDataProtectionKeyCon
});
/*
- * Configure EmailClaimLink - the claim's ownership references.
+ * Configure EmailClaim - one owning manifest per address.
*/
- modelBuilder.Entity<EmailClaimLink>(builder =>
+ modelBuilder.Entity<EmailClaim>(builder =>
{
- builder.HasKey(l => new { l.EmailClaimId, l.VaultManifestId });
-
- // Stored as its name rather than an ordinal: every query here reads "is this link still Removed", which
+ // Stored as its name rather than an ordinal: every query here reads "is this claim still Removed", which
// is worth being able to answer from a raw SQL prompt without a lookup table in your head.
- builder.Property(l => l.State).HasConversion<string>().HasMaxLength(20);
+ builder.Property(c => c.State).HasConversion<string>().HasMaxLength(20);
- builder.HasOne(l => l.EmailClaim)
- .WithMany(c => c.Links)
- .HasForeignKey(l => l.EmailClaimId)
- .OnDelete(DeleteBehavior.Cascade);
-
- builder.HasOne(l => l.VaultManifest)
+ // Deleting the owning manifest leaves the claim behind as a tombstone, so the address is never handed out again.
+ builder.HasOne(c => c.VaultManifest)
.WithMany()
- .HasForeignKey(l => l.VaultManifestId)
- .OnDelete(DeleteBehavior.Cascade);
+ .HasForeignKey(c => c.VaultManifestId)
+ .OnDelete(DeleteBehavior.SetNull);
- builder.HasIndex(l => new { l.VaultManifestId, l.EmailClaimId });
- builder.HasIndex(l => l.EmailClaimId).HasFilter("\"State\" <> 'Removed'").HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live");
+ builder.HasIndex(c => new { c.VaultManifestId, c.State });
+ builder.HasIndex(c => new { c.VaultManifestId, c.CreatedAt });
});
/*
diff --git a/apps/server/Databases/AliasServerDb/EmailClaim.cs b/apps/server/Databases/AliasServerDb/EmailClaim.cs
index dc8b65ca3..21bbbbf9c 100644
--- a/apps/server/Databases/AliasServerDb/EmailClaim.cs
+++ b/apps/server/Databases/AliasServerDb/EmailClaim.cs
@@ -8,12 +8,13 @@
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 linked to every manifest that
-/// has ever held the alias (see <see cref="Links"/>), each link saying whether that manifest still carries it; a
-/// claim whose links are all gone is a tombstone that blocks re-use of the address by design.
+/// EmailClaim object. This object is used to reserve an email address for exactly one owning manifest. Only that manifest
+/// can update or reclaim it; moving it to another manifest is an explicit transfer. A claim whose manifest is gone is a
+/// tombstone that blocks re-use of the address by design.
/// </summary>
[Index(nameof(Address), IsUnique = true)]
public class EmailClaim
@@ -25,9 +26,20 @@ public class EmailClaim
public Guid Id { get; set; }
/// <summary>
- /// Gets or sets the manifests this alias lives in (and from which the owner groups can be derived).
+ /// Gets or sets the manifest that owns the alias. Null once that manifest has been deleted (tombstone).
/// </summary>
- public virtual List<EmailClaimLink> Links { get; set; } = [];
+ public Guid? VaultManifestId { get; set; }
+
+ /// <summary>
+ /// Gets or sets the navigation property to the manifest that owns the alias.
+ /// </summary>
+ [ForeignKey("VaultManifestId")]
+ public virtual VaultManifest? VaultManifest { get; set; }
+
+ /// <summary>
+ /// Gets or sets the state of the alias in its owning manifest.
+ /// </summary>
+ public EmailClaimState State { get; set; } = EmailClaimState.Active;
/// <summary>
/// Gets or sets the full email address.
diff --git a/apps/server/Databases/AliasServerDb/EmailClaimLink.cs b/apps/server/Databases/AliasServerDb/EmailClaimLink.cs
deleted file mode 100644
index 6cf153af9..000000000
--- a/apps/server/Databases/AliasServerDb/EmailClaimLink.cs
+++ /dev/null
@@ -1,44 +0,0 @@
-//-----------------------------------------------------------------------
-// <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!;
-
- /// <summary>
- /// Gets or sets the state of the link. A link record is permanent and never deleted, except when the owner account/group is permanently deleted.
- /// </summary>
- public EmailClaimLinkState State { get; set; } = EmailClaimLinkState.Active;
-}
diff --git a/apps/server/Databases/AliasServerDb/EmailClaimLinkState.cs b/apps/server/Databases/AliasServerDb/EmailClaimState.cs
similarity index 50%
rename from apps/server/Databases/AliasServerDb/EmailClaimLinkState.cs
rename to apps/server/Databases/AliasServerDb/EmailClaimState.cs
index ff342698d..c4b5801d3 100644
--- a/apps/server/Databases/AliasServerDb/EmailClaimLinkState.cs
+++ b/apps/server/Databases/AliasServerDb/EmailClaimState.cs
@@ -1,5 +1,5 @@
//-----------------------------------------------------------------------
-// <copyright file="EmailClaimLinkState.cs" company="aliasvault">
+// <copyright file="EmailClaimState.cs" company="aliasvault">
// Copyright (c) aliasvault. All rights reserved.
// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
// </copyright>
@@ -8,13 +8,9 @@
namespace AliasServerDb;
/// <summary>
-/// What a manifest's link to an email claim says about the alias right now.
-/// <para>
-/// The claim link row itself is permanent: it is the record of which manifests have ever held the address, which is what
-/// lets a manifest reclaim an alias it dropped and what stops another account from taking the address over.
-/// </para>
+/// What the owning manifest of an email claim says about the alias right now.
/// </summary>
-public enum EmailClaimLinkState
+public enum EmailClaimState
{
/// <summary>
/// The manifest carries the alias and wants its mail: incoming mail is wrapped for this manifest's delivery key.
@@ -23,13 +19,13 @@ public enum EmailClaimLinkState
/// <summary>
/// The manifest carries the alias but the user switched it off. Mail already received stays readable.
- /// New mail is not wrapped for this manifest. Re-enabling is possible by setting the state to 'Active'.
+ /// New mail is not accepted. Re-enabling is possible by setting the state to 'Active'.
/// </summary>
Paused = 1,
/// <summary>
- /// The manifest no longer carries the alias: the item holding it is gone from that vault, or a revoke severed the
- /// tie. No mail is wrapped for it, so the row survives purely as the ownership record.
+ /// The manifest no longer carries the alias. No mail is accepted; the row survives as the ownership record, so only
+ /// the owning manifest can claim the address back.
/// </summary>
Removed = 2,
}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20261004181927_SingleOwnerEmailClaims.Designer.cs b/apps/server/Databases/AliasServerDb/Migrations/20261004181927_SingleOwnerEmailClaims.Designer.cs
new file mode 100644
index 000000000..110f440eb
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20261004181927_SingleOwnerEmailClaims.Designer.cs
@@ -0,0 +1,2112 @@
+// <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("20261004181927_SingleOwnerEmailClaims")]
+ partial class SingleOwnerEmailClaims
+ {
+ /// <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.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.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(255)
+ .HasColumnType("character varying(255)");
+
+ 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.CapabilityRule", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<string>("CapabilityKey")
+ .IsRequired()
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<string>("ClientName")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ 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<string>("Kind")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property<string>("Notes")
+ .HasMaxLength(1000)
+ .HasColumnType("character varying(1000)");
+
+ b.Property<string>("Tier")
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("UserId")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("Value")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.HasKey("Id");
+
+ b.HasIndex("GroupId");
+
+ b.HasIndex("Tier");
+
+ b.HasIndex("UserId");
+
+ b.HasIndex("CapabilityKey", "Enabled");
+
+ b.ToTable("CapabilityRules");
+ });
+
+ modelBuilder.Entity("AliasServerDb.ClientAction", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<Guid?>("ManifestId")
+ .HasColumnType("uuid");
+
+ b.Property<string>("Payload")
+ .HasColumnType("jsonb");
+
+ b.Property<Guid?>("TargetGroupId")
+ .HasColumnType("uuid");
+
+ b.Property<string>("TargetUserId")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("Type")
+ .IsRequired()
+ .HasMaxLength(50)
+ .HasColumnType("character varying(50)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.HasIndex("TargetGroupId");
+
+ b.HasIndex("TargetUserId");
+
+ b.ToTable("ClientActions");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<int>("AttachmentCount")
+ .HasColumnType("integer");
+
+ 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")
+ .HasColumnType("text");
+
+ b.Property<byte[]>("MessageSourceBytes")
+ .HasColumnType("bytea");
+
+ 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<bool>("AnonymizedSenderCounted")
+ .HasColumnType("boolean");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("State")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.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.HasIndex("VaultManifestId", "State");
+
+ b.ToTable("EmailClaims");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
+ {
+ b.Property<int>("EmailId")
+ .HasColumnType("integer");
+
+ b.Property<Guid>("VaultManifestDeliveryKeyId")
+ .HasColumnType("uuid");
+
+ b.Property<string>("EncryptedSymmetricKey")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.HasKey("EmailId", "VaultManifestDeliveryKeyId");
+
+ b.HasIndex("VaultManifestDeliveryKeyId", "EmailId");
+
+ b.ToTable("EmailDecryptionKeys");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailPart", b =>
+ {
+ b.Property<int>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer");
+
+ NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id"));
+
+ b.Property<byte[]>("Bytes")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ b.Property<int>("EmailId")
+ .HasColumnType("integer");
+
+ b.Property<int>("PartIndex")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.HasIndex("EmailId", "PartIndex")
+ .IsUnique();
+
+ b.ToTable("EmailParts");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Group", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.PrimitiveCollection<int[]>("AnonymizedEmailAliasSenderCounts")
+ .IsRequired()
+ .ValueGeneratedOnAdd()
+ .HasColumnType("integer[]")
+ .HasDefaultValueSql("array_fill(0, ARRAY[64])");
+
+ 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<string>("Type")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("Id");
+
+ b.ToTable("Groups");
+ });
+
+ modelBuilder.Entity("AliasServerDb.GroupInvitation", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<string>("Algorithm")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("EncryptedName")
+ .HasColumnType("text");
+
+ b.Property<string>("EncryptedVek")
+ .HasColumnType("text");
+
+ b.Property<Guid>("GroupId")
+ .HasColumnType("uuid");
+
+ b.Property<string>("InviteeUserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<string>("InviterUserId")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<DateTime?>("RespondedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("Role")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property<string>("State")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<Guid?>("UserGrantKeyId")
+ .HasColumnType("uuid");
+
+ b.Property<int>("VaultKeyVersion")
+ .HasColumnType("integer");
+
+ b.Property<Guid?>("VaultManifestId")
+ .HasColumnType("uuid");
+
+ b.HasKey("Id");
+
+ b.HasIndex("GroupId");
+
+ b.HasIndex("InviterUserId");
+
+ b.HasIndex("UserGrantKeyId");
+
+ b.HasIndex("InviteeUserId", "State");
+
+ b.HasIndex("VaultManifestId", "InviteeUserId")
+ .IsUnique()
+ .HasDatabaseName("UX_GroupInvitations_Manifest_Invitee_Pending")
+ .HasFilter("\"State\" = 'Pending'");
+
+ b.ToTable("GroupInvitations");
+ });
+
+ 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<string>("Role")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ 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<string>("Algorithm")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property<DateTime?>("ClearedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("ClientBrowser")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<string>("ClientIpAddress")
+ .HasColumnType("text");
+
+ b.Property<string>("ClientName")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<string>("ClientOperatingSystem")
+ .HasMaxLength(100)
+ .HasColumnType("character varying(100)");
+
+ b.Property<string>("ClientPublicKey")
+ .IsRequired()
+ .HasColumnType("text");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<DateTime?>("DeclinedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("EncryptedUnlockKey")
+ .HasColumnType("text");
+
+ b.Property<DateTime?>("FulfilledAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("MobileIpAddress")
+ .HasColumnType("text");
+
+ b.Property<string>("PollSecretHash")
+ .IsRequired()
+ .HasMaxLength(44)
+ .HasColumnType("character varying(44)");
+
+ 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.RegistrationInvite", b =>
+ {
+ b.Property<Guid>("Id")
+ .ValueGeneratedOnAdd()
+ .HasColumnType("uuid");
+
+ b.Property<string>("Code")
+ .IsRequired()
+ .HasMaxLength(32)
+ .HasColumnType("character varying(32)");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("CreatedBy")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<DateTime?>("ExpiresAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<DateTime?>("LastUsedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<int>("MaxUses")
+ .HasColumnType("integer");
+
+ b.Property<string>("Note")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<int>("UseCount")
+ .HasColumnType("integer");
+
+ b.HasKey("Id");
+
+ b.HasIndex(new[] { "Code" }, "IX_RegistrationInvite_Code")
+ .IsUnique();
+
+ b.ToTable("RegistrationInvites");
+ });
+
+ 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<string>("Algorithm")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ 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.UserUnlockKeysHistory", 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>("ArchivedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("ArchivedByClient")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ 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<string>("Metadata")
+ .HasColumnType("jsonb");
+
+ b.Property<string>("Type")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ b.Property<Guid>("UnlockKeyId")
+ .HasColumnType("uuid");
+
+ 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("ArchivedAt")
+ .HasDatabaseName("IX_UserUnlockKeysHistory_ArchivedAt");
+
+ b.HasIndex("UserId", "Type", "ArchivedAt")
+ .HasDatabaseName("IX_UserUnlockKeysHistory_UserId_Type_ArchivedAt");
+
+ b.ToTable("UserUnlockKeysHistory", (string)null);
+ });
+
+ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>
+ {
+ b.Property<Guid>("ManifestId")
+ .HasColumnType("uuid");
+
+ b.Property<string>("Hash")
+ .HasMaxLength(64)
+ .HasColumnType("character varying(64)");
+
+ b.Property<string>("Category")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("EncryptedBlobKey")
+ .IsRequired()
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ b.Property<byte[]>("EncryptedData")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ b.Property<int>("KeyVersion")
+ .HasColumnType("integer");
+
+ b.Property<int>("SizeBytes")
+ .HasColumnType("integer");
+
+ b.HasKey("ManifestId", "Hash");
+
+ 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<byte[]>("EncryptedData")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ 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<byte[]>("EncryptedData")
+ .IsRequired()
+ .HasColumnType("bytea");
+
+ 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<byte[]>("ManifestBlob")
+ .HasColumnType("bytea");
+
+ b.Property<string>("ManifestCiphertextHash")
+ .HasMaxLength(64)
+ .HasColumnType("character varying(64)");
+
+ 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>("UpdatedByUserId")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ 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.HasIndex("UpdatedByUserId");
+
+ 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<string>("Algorithm")
+ .IsRequired()
+ .HasMaxLength(30)
+ .HasColumnType("character varying(30)");
+
+ 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.VaultManifestShareDetails", b =>
+ {
+ b.Property<Guid>("ManifestId")
+ .HasColumnType("uuid");
+
+ b.Property<DateTime>("CreatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.Property<string>("EncryptedName")
+ .HasMaxLength(2000)
+ .HasColumnType("character varying(2000)");
+
+ b.Property<DateTime>("UpdatedAt")
+ .HasColumnType("timestamp with time zone");
+
+ b.HasKey("ManifestId");
+
+ b.ToTable("VaultManifestShareDetails");
+ });
+
+ 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<byte[]>("ManifestBlob")
+ .HasColumnType("bytea");
+
+ 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>("UpdatedByUserId")
+ .HasMaxLength(255)
+ .HasColumnType("character varying(255)");
+
+ 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.HasIndex("UpdatedByUserId");
+
+ 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<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.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.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.CapabilityRule", b =>
+ {
+ b.HasOne("AliasServerDb.Group", "Group")
+ .WithMany()
+ .HasForeignKey("GroupId")
+ .OnDelete(DeleteBehavior.Cascade);
+
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade);
+
+ b.Navigation("Group");
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.ClientAction", b =>
+ {
+ b.HasOne("AliasServerDb.Group", "TargetGroup")
+ .WithMany()
+ .HasForeignKey("TargetGroupId")
+ .OnDelete(DeleteBehavior.Cascade);
+
+ b.HasOne("AliasServerDb.AliasVaultUser", "TargetUser")
+ .WithMany()
+ .HasForeignKey("TargetUserId")
+ .OnDelete(DeleteBehavior.Cascade);
+
+ b.Navigation("TargetGroup");
+
+ b.Navigation("TargetUser");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailAttachment", b =>
+ {
+ b.HasOne("AliasServerDb.Email", "Email")
+ .WithMany("Attachments")
+ .HasForeignKey("EmailId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Email");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
+ {
+ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")
+ .WithMany()
+ .HasForeignKey("VaultManifestId")
+ .OnDelete(DeleteBehavior.SetNull);
+
+ b.Navigation("VaultManifest");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
+ {
+ b.HasOne("AliasServerDb.Email", "Email")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("EmailId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("AliasServerDb.VaultManifestDeliveryKey", "VaultManifestDeliveryKey")
+ .WithMany("DecryptionKeys")
+ .HasForeignKey("VaultManifestDeliveryKeyId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired()
+ .HasConstraintName("FK_EmailDecryptionKeys_VaultManifestDeliveryKeys_DeliveryKeyId");
+
+ b.Navigation("Email");
+
+ b.Navigation("VaultManifestDeliveryKey");
+ });
+
+ modelBuilder.Entity("AliasServerDb.EmailPart", b =>
+ {
+ b.HasOne("AliasServerDb.Email", "Email")
+ .WithMany("Parts")
+ .HasForeignKey("EmailId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Email");
+ });
+
+ modelBuilder.Entity("AliasServerDb.GroupInvitation", b =>
+ {
+ b.HasOne("AliasServerDb.Group", "Group")
+ .WithMany()
+ .HasForeignKey("GroupId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("AliasServerDb.AliasVaultUser", "Invitee")
+ .WithMany()
+ .HasForeignKey("InviteeUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("AliasServerDb.AliasVaultUser", "Inviter")
+ .WithMany()
+ .HasForeignKey("InviterUserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.HasOne("AliasServerDb.UserGrantKey", "UserGrantKey")
+ .WithMany()
+ .HasForeignKey("UserGrantKeyId")
+ .OnDelete(DeleteBehavior.SetNull);
+
+ b.Navigation("Group");
+
+ b.Navigation("Invitee");
+
+ b.Navigation("Inviter");
+
+ b.Navigation("UserGrantKey");
+ });
+
+ 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.UserUnlockKeysHistory", b =>
+ {
+ b.HasOne("AliasServerDb.AliasVaultUser", "User")
+ .WithMany()
+ .HasForeignKey("UserId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("User");
+ });
+
+ modelBuilder.Entity("AliasServerDb.VaultBlobObject", b =>
+ {
+ b.HasOne("AliasServerDb.VaultManifest", "Manifest")
+ .WithMany()
+ .HasForeignKey("ManifestId")
+ .OnDelete(DeleteBehavior.Cascade)
+ .IsRequired();
+
+ b.Navigation("Manifest");
+ });
+
+ 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.HasOne("AliasServerDb.AliasVaultUser", "UpdatedByUser")
+ .WithMany()
+ .HasForeignKey("UpdatedByUserId")
+ .OnDelete(DeleteBehavior.SetNull);
+
+ b.Navigation("OwnerGroup");
+
+ b.Navigation("UpdatedByUser");
+ });
+
+ 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.VaultManifestShareDetails", b =>
+ {
+ b.HasOne("AliasServerDb.VaultManifest", "VaultManifest")
+ .WithOne()
+ .HasForeignKey("AliasServerDb.VaultManifestShareDetails", "ManifestId")
+ .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.HasOne("AliasServerDb.AliasVaultUser", "UpdatedByUser")
+ .WithMany()
+ .HasForeignKey("UpdatedByUserId")
+ .OnDelete(DeleteBehavior.SetNull);
+
+ b.Navigation("Manifest");
+
+ b.Navigation("UpdatedByUser");
+ });
+
+ modelBuilder.Entity("AliasServerDb.AliasVaultUser", b =>
+ {
+ b.Navigation("VaultManifestAccessKeys");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Email", b =>
+ {
+ b.Navigation("Attachments");
+
+ b.Navigation("DecryptionKeys");
+
+ b.Navigation("Parts");
+ });
+
+ modelBuilder.Entity("AliasServerDb.Group", b =>
+ {
+ b.Navigation("Members");
+ });
+
+ modelBuilder.Entity("AliasServerDb.VaultManifestDeliveryKey", b =>
+ {
+ b.Navigation("DecryptionKeys");
+ });
+#pragma warning restore 612, 618
+ }
+ }
+}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/20261004181927_SingleOwnerEmailClaims.cs b/apps/server/Databases/AliasServerDb/Migrations/20261004181927_SingleOwnerEmailClaims.cs
new file mode 100644
index 000000000..e0d4fe02f
--- /dev/null
+++ b/apps/server/Databases/AliasServerDb/Migrations/20261004181927_SingleOwnerEmailClaims.cs
@@ -0,0 +1,71 @@
+using System;
+using Microsoft.EntityFrameworkCore.Migrations;
+
+#nullable disable
+
+namespace AliasServerDb.Migrations
+{
+ /// <inheritdoc />
+ public partial class SingleOwnerEmailClaims : Migration
+ {
+ /// <inheritdoc />
+ protected override void Up(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.AddColumn<string>(name: "State", table: "EmailClaims", type: "character varying(20)", maxLength: 20, nullable: false, defaultValue: "Active");
+ migrationBuilder.AddColumn<Guid>(name: "VaultManifestId", table: "EmailClaims", type: "uuid", nullable: true);
+
+ // Every claim keeps one owner: its live link when it has one, else any link. Claims without links stay tombstones.
+ migrationBuilder.Sql("""
+ UPDATE "EmailClaims" c
+ SET "VaultManifestId" = l."VaultManifestId", "State" = l."State"
+ FROM (
+ SELECT DISTINCT ON ("EmailClaimId") "EmailClaimId", "VaultManifestId", "State"
+ FROM "EmailClaimLinks"
+ ORDER BY "EmailClaimId", ("State" = 'Removed'), "VaultManifestId"
+ ) l
+ WHERE l."EmailClaimId" = c."Id";
+ """);
+ migrationBuilder.Sql("""UPDATE "EmailClaims" SET "State" = 'Removed' WHERE "VaultManifestId" IS NULL;""");
+
+ migrationBuilder.DropTable(name: "EmailClaimLinks");
+
+ migrationBuilder.CreateIndex(name: "IX_EmailClaims_VaultManifestId_CreatedAt", table: "EmailClaims", columns: new[] { "VaultManifestId", "CreatedAt" });
+ migrationBuilder.CreateIndex(name: "IX_EmailClaims_VaultManifestId_State", table: "EmailClaims", columns: new[] { "VaultManifestId", "State" });
+ migrationBuilder.AddForeignKey(name: "FK_EmailClaims_VaultManifests_VaultManifestId", table: "EmailClaims", column: "VaultManifestId", principalTable: "VaultManifests", principalColumn: "ManifestId", onDelete: ReferentialAction.SetNull);
+ }
+
+ /// <inheritdoc />
+ protected override void Down(MigrationBuilder migrationBuilder)
+ {
+ migrationBuilder.DropForeignKey(name: "FK_EmailClaims_VaultManifests_VaultManifestId", table: "EmailClaims");
+ migrationBuilder.DropIndex(name: "IX_EmailClaims_VaultManifestId_CreatedAt", table: "EmailClaims");
+ migrationBuilder.DropIndex(name: "IX_EmailClaims_VaultManifestId_State", table: "EmailClaims");
+
+ migrationBuilder.CreateTable(
+ name: "EmailClaimLinks",
+ columns: table => new
+ {
+ EmailClaimId = table.Column<Guid>(type: "uuid", nullable: false),
+ VaultManifestId = table.Column<Guid>(type: "uuid", nullable: false),
+ State = table.Column<string>(type: "character varying(20)", maxLength: 20, 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.Sql("""
+ INSERT INTO "EmailClaimLinks" ("EmailClaimId", "VaultManifestId", "State")
+ SELECT "Id", "VaultManifestId", "State" FROM "EmailClaims" WHERE "VaultManifestId" IS NOT NULL;
+ """);
+
+ migrationBuilder.CreateIndex(name: "IX_EmailClaimLinks_EmailClaimId_Live", table: "EmailClaimLinks", column: "EmailClaimId", filter: "\"State\" <> 'Removed'");
+ migrationBuilder.CreateIndex(name: "IX_EmailClaimLinks_VaultManifestId_EmailClaimId", table: "EmailClaimLinks", columns: new[] { "VaultManifestId", "EmailClaimId" });
+
+ migrationBuilder.DropColumn(name: "State", table: "EmailClaims");
+ migrationBuilder.DropColumn(name: "VaultManifestId", table: "EmailClaims");
+ }
+ }
+}
diff --git a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
index 453efcb9a..263df868b 100644
--- a/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
+++ b/apps/server/Databases/AliasServerDb/Migrations/AliasServerDbContextModelSnapshot.cs
@@ -584,39 +584,27 @@ namespace AliasServerDb.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
+ b.Property<string>("State")
+ .IsRequired()
+ .HasMaxLength(20)
+ .HasColumnType("character varying(20)");
+
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
+ b.Property<Guid?>("VaultManifestId")
+ .HasColumnType("uuid");
+
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.Property<string>("State")
- .IsRequired()
- .HasMaxLength(20)
- .HasColumnType("character varying(20)");
-
- b.HasKey("EmailClaimId", "VaultManifestId");
-
- b.HasIndex("EmailClaimId")
- .HasDatabaseName("IX_EmailClaimLinks_EmailClaimId_Live")
- .HasFilter("\"State\" <> 'Removed'");
+ b.HasIndex("VaultManifestId", "CreatedAt");
- b.HasIndex("VaultManifestId", "EmailClaimId");
+ b.HasIndex("VaultManifestId", "State");
- b.ToTable("EmailClaimLinks");
+ b.ToTable("EmailClaims");
});
modelBuilder.Entity("AliasServerDb.EmailDecryptionKey", b =>
@@ -1825,21 +1813,12 @@ namespace AliasServerDb.Migrations
b.Navigation("Email");
});
- modelBuilder.Entity("AliasServerDb.EmailClaimLink", b =>
+ modelBuilder.Entity("AliasServerDb.EmailClaim", 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");
+ .OnDelete(DeleteBehavior.SetNull);
b.Navigation("VaultManifest");
});
@@ -2115,11 +2094,6 @@ namespace AliasServerDb.Migrations
b.Navigation("Parts");
});
- modelBuilder.Entity("AliasServerDb.EmailClaim", b =>
- {
- b.Navigation("Links");
- });
-
modelBuilder.Entity("AliasServerDb.Group", b =>
{
b.Navigation("Members");
diff --git a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
index 7e54fe987..3e7906adf 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/Enums/ApiErrorCode.cs
@@ -272,4 +272,24 @@ public enum ApiErrorCode
/// The registration invite code is unknown, expired or used up.
/// </summary>
INVITE_CODE_INVALID,
+
+ /// <summary>
+ /// The email claim does not exist, or its owning manifest is not accessible to the caller.
+ /// </summary>
+ EMAIL_CLAIM_NOT_FOUND,
+
+ /// <summary>
+ /// The target manifest's group already holds as many aliases as it is allowed to.
+ /// </summary>
+ ALIAS_LIMIT_REACHED,
+
+ /// <summary>
+ /// The email alias is owned by a vault the caller cannot open, of someone the caller shares a group with.
+ /// </summary>
+ CLAIM_OWNED_BY_OTHER_VAULT,
+
+ /// <summary>
+ /// The email address is already in use by another account.
+ /// </summary>
+ CLAIM_TAKEN,
}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs
index 13f70ecde..1e3fa3d76 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Email/MailboxApiModel.cs
@@ -28,6 +28,17 @@ public class MailboxApiModel
/// </summary>
public List<string> PublicKeys { get; set; } = [];
+ /// <summary>
+ /// Gets or sets the manifest that owns the alias. A client shows the alias as owned elsewhere when this differs from the
+ /// manifest of the item it is looking at.
+ /// </summary>
+ public Guid? OwnerManifestId { get; set; }
+
+ /// <summary>
+ /// Gets or sets a value indicating whether the caller may move the alias to another manifest it can access.
+ /// </summary>
+ public bool CanTransfer { get; set; }
+
/// <summary>
/// Gets or sets the list of mailbox email API models.
/// </summary>
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ClaimedEmailAddress.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ClaimedEmailAddress.cs
index 9fe20ae1a..9e072a86f 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ClaimedEmailAddress.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ClaimedEmailAddress.cs
@@ -8,9 +8,7 @@
namespace AliasVault.Shared.Models.WebApi.V2.Vault;
/// <summary>
-/// An email alias the client claims, together with the manifest holding the item it belongs to. The manifest
-/// decides how the alias's mail is encrypted: a shared manifest's published keypair (readable by every member)
-/// or, for the caller's personal manifest, their own primary personal key.
+/// An email alias the client claims, together with the manifest holding the item it belongs to.
/// </summary>
public class ClaimedEmailAddress
{
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/EmailClaimTransferRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/EmailClaimTransferRequest.cs
new file mode 100644
index 000000000..8e7291005
--- /dev/null
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/EmailClaimTransferRequest.cs
@@ -0,0 +1,20 @@
+//-----------------------------------------------------------------------
+// <copyright file="EmailClaimTransferRequest.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.Vault;
+
+/// <summary>
+/// Moves an email alias from its current owning manifest to another manifest.
+/// </summary>
+public class EmailClaimTransferRequest
+{
+ /// <summary>Gets or sets the full email address of the alias.</summary>
+ public required string Address { get; set; }
+
+ /// <summary>Gets or sets the manifest that becomes the new owner of the alias.</summary>
+ public required Guid TargetManifestId { get; set; }
+}
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
index 64ca2c67d..f6b947857 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/TaskRunner/TaskRunnerTests.cs
@@ -815,7 +815,7 @@ public class TaskRunnerTests
foreach (var alias in aliases)
{
// Add 50 random emails for enabled aliases
- if (alias.Links.Any(l => l.State != EmailClaimLinkState.Removed))
+ if (alias.State != EmailClaimState.Removed)
{
for (int i = 0; i < 50; i++)
{
diff --git a/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs b/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs
index 7aaeb1743..b90041dd2 100644
--- a/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs
+++ b/apps/server/Tests/AliasVault.IntegrationTests/TestUserSeeder.cs
@@ -79,7 +79,8 @@ public static class TestUserSeeder
AddressDomain = addressParts[1],
CreatedAt = timestamp,
UpdatedAt = timestamp,
- Links = [new EmailClaimLink { VaultManifestId = vaultManifestId, State = disabled ? EmailClaimLinkState.Removed : EmailClaimLinkState.Active }],
+ VaultManifestId = vaultManifestId,
+ State = disabled ? EmailClaimState.Removed : EmailClaimState.Active,
};
}
}
diff --git a/apps/server/Tests/AliasVault.UnitTests/Services/TakenAliasLookupRateLimitServiceTests.cs b/apps/server/Tests/AliasVault.UnitTests/Services/TakenAliasLookupRateLimitServiceTests.cs
new file mode 100644
index 000000000..a8d2cb3fc
--- /dev/null
+++ b/apps/server/Tests/AliasVault.UnitTests/Services/TakenAliasLookupRateLimitServiceTests.cs
@@ -0,0 +1,63 @@
+//-----------------------------------------------------------------------
+// <copyright file="TakenAliasLookupRateLimitServiceTests.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.UnitTests.Services;
+
+using AliasVault.Api.Services;
+using Microsoft.Extensions.Logging.Abstractions;
+
+/// <summary>
+/// Tests for <see cref="TakenAliasLookupRateLimitService"/>.
+/// </summary>
+public class TakenAliasLookupRateLimitServiceTests
+{
+ /// <summary>
+ /// An account learns at most the per-user number of distinct taken addresses.
+ /// </summary>
+ [Test]
+ public void LimitsDistinctAddressesPerUserTest()
+ {
+ var limiter = new TakenAliasLookupRateLimitService(NullLogger<TakenAliasLookupRateLimitService>.Instance);
+ for (var i = 0; i < TakenAliasLookupRateLimitService.MaxPerUser; i++)
+ {
+ Assert.That(limiter.TryRecord("user", "1.2.3.4", $"a{i}@example.com"), Is.True);
+ }
+
+ Assert.That(limiter.TryRecord("user", "1.2.3.4", "[email protected]"), Is.False);
+ }
+
+ /// <summary>
+ /// Asking again about an address already counted is always allowed, so mailbox polling never hits the limit.
+ /// </summary>
+ [Test]
+ public void RepeatedAddressIsFreeTest()
+ {
+ var limiter = new TakenAliasLookupRateLimitService(NullLogger<TakenAliasLookupRateLimitService>.Instance);
+ for (var i = 0; i < TakenAliasLookupRateLimitService.MaxPerUser; i++)
+ {
+ limiter.TryRecord("user", "1.2.3.4", $"a{i}@example.com");
+ }
+
+ Assert.That(limiter.TryRecord("user", "1.2.3.4", "[email protected]"), Is.True);
+ }
+
+ /// <summary>
+ /// Many accounts from one source IP share the per-IP limit.
+ /// </summary>
+ [Test]
+ public void LimitsDistinctAddressesPerIpAcrossUsersTest()
+ {
+ var limiter = new TakenAliasLookupRateLimitService(NullLogger<TakenAliasLookupRateLimitService>.Instance);
+ for (var i = 0; i < TakenAliasLookupRateLimitService.MaxPerIp; i++)
+ {
+ Assert.That(limiter.TryRecord($"user{i}", "1.2.3.4", $"a{i}@example.com"), Is.True);
+ }
+
+ Assert.That(limiter.TryRecord("another-user", "1.2.3.4", "[email protected]"), Is.False);
+ Assert.That(limiter.TryRecord("another-user", "5.6.7.8", "[email protected]"), Is.True);
+ }
+}
diff --git a/apps/web/src/components/email/RecentEmails.tsx b/apps/web/src/components/email/RecentEmails.tsx
index c6b55a30a..ef3956140 100644
--- a/apps/web/src/components/email/RecentEmails.tsx
+++ b/apps/web/src/components/email/RecentEmails.tsx
@@ -1,5 +1,7 @@
import { apiErrorCodeOf } from '@aliasvault/client/api/errors/ApiRequestError';
import EncryptionUtility from '@aliasvault/client/crypto/EncryptionUtility';
+import { type AliasOwnerNotice, aliasOwnerErrorText, aliasOwnerNotice, moveAliasHere } from '@aliasvault/client/email/AliasOwner';
+import { familySharingText } from '@aliasvault/client/sharing/FamilySharingView';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -9,16 +11,18 @@ import SkeletonBase from '@/components/loading/SkeletonBase';
import Card from '@/components/shared/Card';
import Icon from '@/components/shared/Icon';
import SectionTitle from '@/components/shared/SectionTitle';
+import { useConfirmModal } from '@/context/ConfirmModalContext';
import { useDb } from '@/context/DbContext';
import { useWebApi } from '@/context/WebApiContext';
import { useEmailDomains } from '@/hooks/useEmailDomains';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import { type EmailViewModel, loadAliasVaultEmail, loadSpamOkEmail, spamOk } from '@/utils/EmailViewModel';
-import type { MailboxBulkResponse, MailboxEmail } from '@aliasvault/models/webapi';
+import type { Mailbox, MailboxEmail } from '@aliasvault/models/webapi';
type RecentEmailsProps = {
emailAddress: string;
+ manifestId: string;
};
const INITIAL_DISPLAY_COUNT = 2;
@@ -36,7 +40,7 @@ const formatDate = (value: string): string => {
/**
* The recent emails received on an item's email address, with an in-place email modal.
*/
-const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress }) => {
+const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress, manifestId }) => {
const { t } = useTranslation();
const dbContext = useDb();
const webApi = useWebApi();
@@ -45,6 +49,8 @@ const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress }) => {
const [mailboxEmails, setMailboxEmails] = useState<MailboxEmail[]>([]);
const [displayedCount, setDisplayedCount] = useState(INITIAL_DISPLAY_COUNT);
const [error, setError] = useState('');
+ const [ownerNotice, setOwnerNotice] = useState<AliasOwnerNotice | null>(null);
+ const { showConfirmation } = useConfirmModal();
const [emailModalVisible, setEmailModalVisible] = useState(false);
const [email, setEmail] = useState<EmailViewModel | null>(null);
const isPageVisible = useRef(true);
@@ -68,7 +74,8 @@ const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress }) => {
setMailboxEmails(mails);
}
} else if (isAliasVault && dbContext.sqliteClient) {
- const mailbox = await webApi.get<MailboxBulkResponse>(`EmailBox/${emailAddress}`);
+ const mailbox = await webApi.get<Mailbox>(`EmailBox/${emailAddress}`);
+ setOwnerNotice(aliasOwnerNotice(emailAddress, mailbox, manifestId, dbContext.sqliteClient.getPersonalManifestId(), dbContext.sqliteClient.folders.getAll()));
const decrypted = await EncryptionUtility.decryptEmailList(mailbox.mails, mailbox.publicKeys, dbContext.sqliteClient.encryptionKeys.getAll());
setMailboxEmails(decrypted);
setError('');
@@ -84,11 +91,13 @@ const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress }) => {
return;
}
setError(t('apiErrors.CLAIM_DOES_NOT_EXIST'));
+ } else if (apiErrorCodeOf(err)) {
+ setError(aliasOwnerErrorText(apiErrorCodeOf(err)) ?? t('apiErrors.' + apiErrorCodeOf(err), { defaultValue: t('common.errors.unknownErrorTryAgain') }));
} else {
setError(err instanceof Error ? err.message : String(err));
}
}
- }, [dbContext.isSyncing, dbContext.isUploading, dbContext.sqliteClient, emailAddress, emailPrefix, isAliasVault, isSpamOk, showComponent, t, webApi]);
+ }, [dbContext.isSyncing, dbContext.isUploading, dbContext.sqliteClient, emailAddress, emailPrefix, isAliasVault, isSpamOk, manifestId, showComponent, t, webApi]);
/**
* Reload from scratch, with the loading skeleton.
@@ -181,6 +190,21 @@ const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress }) => {
}
};
+ /**
+ * Move the alias to this item's vault after confirmation, then reload.
+ */
+ const moveHere = async (): Promise<void> => {
+ if (!ownerNotice || !await showConfirmation(familySharingText.aliasOwner.moveHere, ownerNotice.moveConfirm, t('common.confirm'), t('common.cancel'))) {
+ return;
+ }
+ try {
+ await moveAliasHere(webApi, emailAddress, manifestId);
+ await manualRefresh();
+ } catch (err) {
+ setError(aliasOwnerErrorText(apiErrorCodeOf(err)) ?? t('common.errors.unknownErrorTryAgain'));
+ }
+ };
+
if (!showComponent) {
return null;
}
@@ -213,6 +237,17 @@ const RecentEmails: React.FC<RecentEmailsProps> = ({ emailAddress }) => {
</div>
</div>
+ {!isLoading && error.length === 0 && ownerNotice && (
+ <div className="mt-4 p-3 bg-amber-50 dark:bg-amber-900/30 border border-amber-200 dark:border-amber-800 rounded-lg">
+ <p className="text-sm text-amber-800 dark:text-amber-200">{ownerNotice.notice}</p>
+ {ownerNotice.canMove && (
+ <button id="move-alias-here" type="button" onClick={() => void moveHere()} className="mt-2 py-1.5 px-3 bg-primary-600 hover:bg-primary-700 text-white rounded-lg text-sm font-medium">
+ {familySharingText.aliasOwner.moveHere}
+ </button>
+ )}
+ </div>
+ )}
+
{isLoading ? (
<div className="flex flex-col mt-6">
<div className="overflow-x-auto rounded-lg">
diff --git a/apps/web/src/pages/items/View.tsx b/apps/web/src/pages/items/View.tsx
index 2778b79dc..2670af830 100644
--- a/apps/web/src/pages/items/View.tsx
+++ b/apps/web/src/pages/items/View.tsx
@@ -211,7 +211,7 @@ const ItemView: React.FC = () => {
</div>
</Section>
- {isLoginLike && emailAddress.length > 0 && <RecentEmails emailAddress={emailAddress} />}
+ {isLoginLike && emailAddress.length > 0 && <RecentEmails emailAddress={emailAddress} manifestId={item.ManifestId} />}
{totpCodes.length > 0 && <TotpViewer totpCodes={totpCodes} item={item} />}
diff --git a/core/client/src/database/queries/ItemQueries.ts b/core/client/src/database/queries/ItemQueries.ts
index c8cb1d166..e6ab1024d 100644
--- a/core/client/src/database/queries/ItemQueries.ts
+++ b/core/client/src/database/queries/ItemQueries.ts
@@ -284,7 +284,7 @@ export class ItemQueries {
/**
* Get all unique email addresses the vault still routes mail to. Addresses the user switched off are excluded:
- * their claim link is disabled server-side, so no new mail arrives for them and their inbox stays hidden.
+ * their claim is disabled server-side, so no new mail arrives for them and their inbox stays hidden.
*/
public static readonly GET_ROUTABLE_EMAIL_ADDRESSES = `
SELECT DISTINCT fv.Value as Email
diff --git a/core/client/src/database/repositories/ItemRepository.ts b/core/client/src/database/repositories/ItemRepository.ts
index 2dbccd2ad..74203cc02 100644
--- a/core/client/src/database/repositories/ItemRepository.ts
+++ b/core/client/src/database/repositories/ItemRepository.ts
@@ -233,7 +233,7 @@ export class ItemRepository extends BaseRepository {
/**
* Fetch the unique email addresses the vault still routes mail to, i.e. every live login email field the user
- * has not switched off. A switched-off alias keeps its claim link and its stored mail server-side, but the
+ * has not switched off. A switched-off alias keeps its claim and its stored mail server-side, but the
* client stops asking for its mailbox until it is switched back on.
* @returns Array of email addresses
*/
diff --git a/core/client/src/email/AliasOwner.ts b/core/client/src/email/AliasOwner.ts
new file mode 100644
index 000000000..910d8ef72
--- /dev/null
+++ b/core/client/src/email/AliasOwner.ts
@@ -0,0 +1,87 @@
+import { familySharingText } from '../sharing/FamilySharingView';
+
+import type { Folder } from '../database/repositories/FolderRepository';
+import type { EmailClaimTransferRequest, Mailbox } from '@aliasvault/models/webapi';
+
+/**
+ * What an item shows when its email alias receives its emails somewhere else than the item's own vault or shared folder.
+ */
+export type AliasOwnerNotice = {
+ /** Where the alias receives its emails now. */
+ notice: string;
+ /** Whether the user may move the alias to the item's vault or shared folder. */
+ canMove: boolean;
+ /** The confirmation shown before moving the alias. */
+ moveConfirm: string;
+};
+
+/**
+ * The API surface needed to move an alias, offered by the WebApiService of every host.
+ */
+type PostApi = {
+ post<TRequest, TResponse>(endpoint: string, data: TRequest, parseJson?: boolean): Promise<TResponse>;
+};
+
+/**
+ * The name of the shared folder a shared manifest is shown as (its root folder carries the manifest id as its id).
+ * @param folders - all rendered folders
+ * @param manifestId - the shared manifest
+ */
+function sharedFolderName(folders: Pick<Folder, 'Id' | 'ManifestId' | 'Name'>[], manifestId: string): string {
+ const id = manifestId.toLowerCase();
+ return folders.find(f => f.Id.toLowerCase() === id && f.ManifestId.toLowerCase() === id)?.Name ?? familySharingText.sharedVault;
+}
+
+/**
+ * The notice for an item in `itemManifestId` whose alias is owned elsewhere, or null when it is owned by the item's own manifest.
+ * @param email - the alias address
+ * @param mailbox - the mailbox response of the alias
+ * @param itemManifestId - the manifest of the item showing the alias
+ * @param personalManifestId - the user's personal manifest
+ * @param folders - all rendered folders, to name shared folders
+ */
+export function aliasOwnerNotice(
+ email: string,
+ mailbox: Pick<Mailbox, 'ownerManifestId' | 'canTransfer'>,
+ itemManifestId: string,
+ personalManifestId: string | null,
+ folders: Pick<Folder, 'Id' | 'ManifestId' | 'Name'>[]
+): AliasOwnerNotice | null {
+ const owner = mailbox.ownerManifestId?.toLowerCase();
+ if (!owner || owner === itemManifestId.toLowerCase()) {
+ return null;
+ }
+
+ const text = familySharingText.aliasOwner;
+ /**
+ * Whether the manifest is the user's personal one.
+ */
+ const isPersonal = (manifestId: string): boolean => manifestId.toLowerCase() === personalManifestId?.toLowerCase();
+ return {
+ notice: isPersonal(owner) ? text.inPersonalVault : text.inSharedFolder(sharedFolderName(folders, owner)),
+ canMove: mailbox.canTransfer,
+ moveConfirm: isPersonal(itemManifestId) ? text.moveToPersonalVaultConfirm(email) : text.moveToSharedFolderConfirm(email, sharedFolderName(folders, itemManifestId)),
+ };
+}
+
+/**
+ * The text for an API error about the ownership of an alias, or null when the code is not one of those.
+ * @param code - the API error code
+ */
+export function aliasOwnerErrorText(code: string | null | undefined): string | null {
+ switch (code) {
+ case 'CLAIM_OWNED_BY_OTHER_VAULT': return familySharingText.errors.aliasOwnedByOtherFolder;
+ case 'ALIAS_LIMIT_REACHED': return familySharingText.errors.aliasLimitReached;
+ default: return null;
+ }
+}
+
+/**
+ * Make the item's manifest the owner of the alias, so new mail for it is delivered there.
+ * @param webApi - the host's API client
+ * @param address - the alias address
+ * @param itemManifestId - the manifest of the item showing the alias
+ */
+export async function moveAliasHere(webApi: PostApi, address: string, itemManifestId: string): Promise<void> {
+ await webApi.post<EmailClaimTransferRequest, Response>('Vault/email-claims/transfer', { address, targetManifestId: itemManifestId }, false);
+}
diff --git a/core/client/src/sharing/FamilySharingView.ts b/core/client/src/sharing/FamilySharingView.ts
index c12a806b7..514542b43 100644
--- a/core/client/src/sharing/FamilySharingView.ts
+++ b/core/client/src/sharing/FamilySharingView.ts
@@ -54,6 +54,17 @@ export const familySharingText = {
/** Password prompt for deleting a shared vault. */
deleteVaultPasswordPrompt: (vault: string): string => `Enter your master password to confirm deleting “${vault}” for the whole family.`,
vaultDeleted: 'The shared vault has been deleted.',
+ /** An item's email alias that receives its emails in another place than the item's own vault or shared folder. */
+ aliasOwner: {
+ inPersonalVault: 'This email alias receives its emails in your personal vault.',
+ /** The alias receives its emails in a shared folder. */
+ inSharedFolder: (folder: string): string => `This email alias receives its emails in the shared folder “${folder}”.`,
+ moveHere: 'Move alias here',
+ /** Confirmation for moving the alias into a shared folder. */
+ moveToSharedFolderConfirm: (email: string, folder: string): string => `From now on, new emails for ${email} go to the shared folder “${folder}”, where everyone with access to it can read them. Emails received before stay where they are.`,
+ /** Confirmation for moving the alias into the personal vault. */
+ moveToPersonalVaultConfirm: (email: string): string => `From now on, new emails for ${email} go to your personal vault, where only you can read them. Emails received before stay where they are.`,
+ },
errors: {
loadFailed: 'Family sharing could not be loaded.',
createVaultFailed: 'The shared vault could not be created. Please try again.',
@@ -69,6 +80,8 @@ export const familySharingText = {
lastMemberWithAccess: 'Somebody has to be able to open the shared vault. Give another member access to it first.',
vaultLimitReached: 'Max amount of shared vaults reached.',
deleteVaultFailed: 'The shared vault could not be deleted. Please try again.',
+ aliasOwnedByOtherFolder: 'This email alias receives its emails in a shared folder you cannot open, or in the personal vault of another family member. Ask them to move it here.',
+ aliasLimitReached: 'The maximum number of email aliases has been reached.',
},
};
diff --git a/core/i18n/locales/en.json b/core/i18n/locales/en.json
index c06091fca..8d75c05b7 100644
--- a/core/i18n/locales/en.json
+++ b/core/i18n/locales/en.json
@@ -4,6 +4,7 @@
"ACCOUNT_LOCKED": "Account temporarily locked due to too many failed attempts. Please try again later.",
"ACCOUNT_SUCCESSFULLY_DELETED": "Account successfully deleted.",
"CLAIM_DOES_NOT_EXIST": "An error occurred while trying to load the emails. Please try to edit and save the credential entry to synchronize the database, then try again.",
+ "CLAIM_TAKEN": "This email address is already used by another account. Edit this item and choose a different email address.",
"INTERNAL_SERVER_ERROR": "Internal server error.",
"INVALID_AUTHENTICATOR_CODE": "Invalid authenticator code. Please try again.",
"INVALID_RECOVERY_CODE": "Invalid recovery code. Please try again.",
diff --git a/core/models/src/webapi/Mailbox.ts b/core/models/src/webapi/Mailbox.ts
new file mode 100644
index 000000000..a9c488ad6
--- /dev/null
+++ b/core/models/src/webapi/Mailbox.ts
@@ -0,0 +1,25 @@
+import type { MailboxEmail } from "./MailboxEmail";
+
+/**
+ * Mailbox response type for a single address.
+ */
+export type Mailbox = {
+ address: string;
+ subscribed: boolean;
+ publicKeys: string[];
+ mails: MailboxEmail[];
+
+ /** The manifest that owns the alias. */
+ ownerManifestId: string | null;
+
+ /** Whether the caller may move the alias to another manifest it can access. */
+ canTransfer: boolean;
+}
+
+/**
+ * Request to move an email alias to another manifest.
+ */
+export type EmailClaimTransferRequest = {
+ address: string;
+ targetManifestId: string;
+}
diff --git a/core/models/src/webapi/index.ts b/core/models/src/webapi/index.ts
index cb1c7a289..ca7c54a2b 100644
--- a/core/models/src/webapi/index.ts
+++ b/core/models/src/webapi/index.ts
@@ -9,6 +9,7 @@ export * from './StatusResponse';
export * from './StatusResponseV2';
export * from './Login';
export * from './ValidateLogin';
+export * from './Mailbox';
export * from './MailboxBulk';
export * from './MailboxEmail';
export * from './Email';