Skip to content

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

Update API RSA public key Vault push payload structure (#2159)

Leendert de Borstcf2fb7bbb79c
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
index 330cb4413..ccd93ce62 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
@@ -7,10 +7,10 @@ import { useDb } from '@/entrypoints/popup/context/DbContext';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
/**
- * Minimum time (ms) to show the syncing indicator.
- * Ensures user sees confirmation that a new vault was downloaded. Kept just long enough to register as a state
- * rather than a flicker: a pull of an ordinary vault finishes in a few hundred ms, so a longer floor is the
- * indicator waiting on itself rather than on the sync.
+ * Minimum time (ms) an in-flight indicator stays visible once it has appeared.
+ * A sync that resolves in tens of milliseconds would otherwise flicker the badge, so we hold it just long enough
+ * to register as a state rather than a flicker. This also bridges the short idle gap between two chained syncs,
+ * which would otherwise flicker the badge off and straight back on.
*/
const MIN_SYNC_DISPLAY_TIME = 400;
@@ -21,6 +21,47 @@ const MIN_SYNC_DISPLAY_TIME = 400;
*/
const PENDING_DISPLAY_DELAY = 1000;
+/**
+ * Keep the syncing indicator visible for a minimum amount of time, measured from the moment it first turned on to prevent flickering.
+ * @param active - the underlying state the indicator reflects
+ * @param minVisibleMs - how long the indicator has to stay visible at minimum
+ * @returns Whether the indicator should be rendered.
+ */
+const useMinimumVisible = (active: boolean, minVisibleMs: number): boolean => {
+ const [visible, setVisible] = useState(active);
+ const shownAtRef = useRef<number | null>(null);
+
+ useEffect(() => {
+ if (active) {
+ if (shownAtRef.current === null) {
+ shownAtRef.current = Date.now();
+ }
+ setVisible(true);
+ return;
+ }
+
+ // Never shown, so there is nothing to hold on to.
+ if (shownAtRef.current === null) {
+ return;
+ }
+
+ const remaining = minVisibleMs - (Date.now() - shownAtRef.current);
+ if (remaining <= 0) {
+ shownAtRef.current = null;
+ setVisible(false);
+ return;
+ }
+
+ const timer = setTimeout((): void => {
+ shownAtRef.current = null;
+ setVisible(false);
+ }, remaining);
+ return (): void => clearTimeout(timer);
+ }, [active, minVisibleMs]);
+
+ return visible;
+};
+
/**
* Sync status indicator component.
* Displays clickable status badges for offline mode, syncing, and pending sync.
@@ -28,7 +69,7 @@ const PENDING_DISPLAY_DELAY = 1000;
* Priority order (highest to lowest):
* 1. Offline (amber) - network unavailable, clickable to retry
* 2. Syncing (green spinner) - downloading new vault (minimum display time)
- * 3. Uploading (blue spinner) - uploading local changes to server
+ * 3. Uploading (blue spinner) - uploading local changes to server (minimum display time)
* 4. Pending (blue pulsing) - local changes waiting to be uploaded, clickable to retry
* 5. Hidden - when synced
*
@@ -41,9 +82,9 @@ const ServerSyncIndicator: React.FC = () => {
const dbContext = useDb();
const [isRetrying, setIsRetrying] = useState(false);
- // Track syncing state with minimum display time
- const [showSyncing, setShowSyncing] = useState(false);
- const syncStartTimeRef = useRef<number | null>(null);
+ // Hold both in-flight indicators up long enough that a fast sync never flashes them
+ const showSyncing = useMinimumVisible(dbContext.isSyncing, MIN_SYNC_DISPLAY_TIME);
+ const showUploading = useMinimumVisible(dbContext.isUploading, MIN_SYNC_DISPLAY_TIME);
// Track pending state with a grace delay so transient dirty windows never flash the badge
const [showPending, setShowPending] = useState(false);
@@ -60,36 +101,6 @@ const ServerSyncIndicator: React.FC = () => {
return (): void => clearTimeout(timer);
}, [dbContext.hasUnsyncedUserChanges]);
- /**
- * Handle syncing state changes with minimum display time.
- * When syncing starts, show indicator immediately.
- * When syncing ends, wait until minimum time has passed.
- */
- useEffect(() => {
- if (dbContext.isSyncing) {
- // Sync started - show immediately and record start time
- setShowSyncing(true);
- syncStartTimeRef.current = Date.now();
- } else if (syncStartTimeRef.current !== null) {
- // Sync ended - wait for minimum display time
- const elapsed = Date.now() - syncStartTimeRef.current;
- const remaining = MIN_SYNC_DISPLAY_TIME - elapsed;
-
- if (remaining > 0) {
- const timer = setTimeout((): void => {
- setShowSyncing(false);
- syncStartTimeRef.current = null;
- }, remaining);
- return (): void => {
- clearTimeout(timer);
- };
- } else {
- setShowSyncing(false);
- syncStartTimeRef.current = null;
- }
- }
- }, [dbContext.isSyncing]);
-
/**
* Handle tap to force sync retry.
*/
@@ -204,7 +215,7 @@ const ServerSyncIndicator: React.FC = () => {
}
// Priority 3: Uploading indicator (not clickable, shows progress)
- if (dbContext.isUploading) {
+ if (showUploading) {
return (
<div
className="flex items-center gap-1.5 mx-2 px-2 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 rounded-md text-xs font-medium"
diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.ts
index 12e13cc68..f958ccc1c 100644
--- a/apps/browser-extension/src/utils/VaultSyncService.ts
+++ b/apps/browser-extension/src/utils/VaultSyncService.ts
@@ -307,8 +307,8 @@ type ManifestWriteDto = {
currentRevision: number;
credentialsCount: number;
blobReferences: BlobRefDto[];
- /** The new VEK (set by legacy migration). */
encryptedVek?: string;
+ encryptionPublicKey?: string;
};
/** Per-manifest result of a write: the new revision (Ok) or the current server revision (Outdated). */
@@ -1231,7 +1231,7 @@ export class VaultSyncService {
}
const { canonicalized, manifestRecords } = cachedSet ?? await this.canonicalizeVault(sqliteClient);
// Personal manifest first by construction (see `resolveManifestRecords`), which is also the order canonicalize requires.
- const [personalRecord, ...sharedRecords] = manifestRecords;
+ const [personalRecord] = manifestRecords;
const privateEmailDomains = (await getStorageItem<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS)) ?? [];
const emailRouting = buildEmailRouting(canonicalized.manifests.map(m => m.manifest), privateEmailDomains);
@@ -1363,6 +1363,21 @@ export class VaultSyncService {
const ciphertextHash = await vaultCodecComputeCiphertextHash(ciphertext);
devLog(`[V2Push] ${label}: raw ${formatKb(plaintext.length)} → compressed ${formatKb(compressedBytes)} → encrypted ${formatKb(ciphertext.length)}.`);
+ /*
+ * Publish the public half of this manifest's RSA key pair, which is used to e.g. encrypt incoming emails.
+ * Only admins are allowed to publish a new shared manifest's key.
+ */
+ const mayPublish = candidate.isPersonal || recordByManifestId.get(candidate.manifestId)?.canAdminister === true;
+ const manifestKey = mayPublish ? sqliteClient.encryptionKeys.getActiveForManifest(candidate.manifestId) : null;
+ if (mayPublish && !manifestKey && !candidate.isPersonal) {
+ /*
+ * Sharing a folder mints its keypair in the same vault mutation, so an owned shared manifest without one
+ * means that mutation was interrupted after the manifest was created server-side. Aliases in its subtree
+ * stay personal (readable by the owner only) until sharing is toggled again.
+ */
+ devWarn(`[V2Push] ${label} is missing its email keypair; its aliases stay personal until sharing is re-enabled.`);
+ }
+
manifestWrites.push({
manifestId: candidate.manifestId,
manifestBlob: ciphertext,
@@ -1375,6 +1390,7 @@ export class VaultSyncService {
* A migration always forces a personal-manifest write (see the gate above), so the key can never be stranded without one.
*/
...(candidate.isPersonal && migration ? { encryptedVek: migration.encryptedVek } : {}),
+ ...(manifestKey ? { encryptionPublicKey: manifestKey.PublicKey } : {}),
});
writtenManifestFingerprints[candidate.manifestId] = fingerprint;
}
@@ -1428,43 +1444,12 @@ export class VaultSyncService {
uploadedCiphertexts.set(hash, ciphertext);
}
- /*
- * Publish the public half of the vault's active personal keypair, which is e.g. used by SMTP services to encrypt mail for personal aliases.
- */
- const primaryKey = sqliteClient.encryptionKeys.getPrimary();
-
- /*
- * Publish the public half of each shared manifest's email keypair that this user administers, which is e.g. used by SMTP services to encrypt
- * mail for the manifest's aliases. Only an admin of the owning group publishes: the server records the delivery key per manifest, so a plain
- * member publishing too would leave it ambiguous which row is the manifest's active key. Members still *claim* shared aliases (below). They
- * just resolve the key the admin published.
- */
- const sharedManifestEncryptionPublicKeys: Array<{ manifestId: string; publicKey: string }> = [];
- for (const record of sharedRecords) {
- if (!record.canAdminister) {
- continue;
- }
- const manifestKey = sqliteClient.encryptionKeys.getActiveForManifest(record.manifestId);
- if (manifestKey) {
- sharedManifestEncryptionPublicKeys.push({ manifestId: record.manifestId, publicKey: manifestKey.PublicKey });
- } else {
- /*
- * Sharing a folder mints its keypair in the same vault mutation, so an owned shared manifest without one
- * means that mutation was interrupted after the manifest was created server-side. Aliases in its subtree
- * stay personal (readable by the owner only) until sharing is toggled again.
- */
- devWarn(`[V2Push] Shared manifest ${record.manifestId} is missing its email keypair; its aliases stay personal until sharing is re-enabled.`);
- }
- }
-
const payload = {
username,
manifests: manifestWrites,
buckets: bucketDtos,
newBlobs: [] as BlobDto[],
emailRouting,
- userEncryptionPublicKey: primaryKey?.PublicKey ?? '',
- sharedManifestEncryptionPublicKeys,
// LEGACY: only the one-time KEK/VEK migration push carries a key hierarchy for the server to store.
accountKeys: migration?.accountKeys ?? null,
};
@@ -1661,7 +1646,7 @@ export class VaultSyncService {
const webApi = new WebApiService();
/** POST the single-bucket write with the given believed-current revision (called again on the rebase retry). */
const postBucket = (currentRevision: number): Promise<VaultWriteResponseDto> => webApi.post<Record<string, unknown>, VaultWriteResponseDto>(VAULT_ENDPOINT, {
- username, manifests: [], buckets: [{ manifestId, category, blob: ciphertext, ciphertextHash, currentRevision }], newBlobs: [], emailRouting: null, userEncryptionPublicKey: '',
+ username, manifests: [], buckets: [{ manifestId, category, blob: ciphertext, ciphertextHash, currentRevision }], newBlobs: [], emailRouting: null,
});
/** This bucket's revision as the server reported it, matched on both halves of its address. */
diff --git a/apps/browser-extension/src/utils/db/repositories/EncryptionKeyRepository.ts b/apps/browser-extension/src/utils/db/repositories/EncryptionKeyRepository.ts
index c10c5e0c9..a68ef0434 100644
--- a/apps/browser-extension/src/utils/db/repositories/EncryptionKeyRepository.ts
+++ b/apps/browser-extension/src/utils/db/repositories/EncryptionKeyRepository.ts
@@ -19,15 +19,6 @@ export class EncryptionKeyRepository extends BaseRepository {
return this.client.executeQuery<EncryptionKey>(EncryptionKeyQueries.GET_ALL);
}
- /**
- * Get the user's active personal keypair.
- * @returns The active personal keypair, or null when absent
- */
- public getPrimary(): EncryptionKey | null {
- const personalManifestId = this.personalManifestId();
- return personalManifestId ? this.getActiveForManifest(personalManifestId) : null;
- }
-
/**
* Get a manifest's active keypair, whose public half is published to the server as that manifest's delivery
* key. Returns null for a manifest that has no keypair in this vault.
diff --git a/apps/browser-extension/tests/helpers/manifest-v2-api.ts b/apps/browser-extension/tests/helpers/manifest-v2-api.ts
index 58be3bb6f..2ecfb1610 100644
--- a/apps/browser-extension/tests/helpers/manifest-v2-api.ts
+++ b/apps/browser-extension/tests/helpers/manifest-v2-api.ts
@@ -148,7 +148,6 @@ export async function pushManifest(
buckets: [],
newBlobs: [],
emailRouting: null,
- userEncryptionPublicKey: '',
};
const response = await fetch(`${apiBaseUrl.replace(/\/$/, '')}/v2/Vault`, {
diff --git a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
index 6682fc432..a1867ba8a 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/VaultController.cs
@@ -538,24 +538,19 @@ public class VaultController(
newBucketRevisions.Add(new BucketRevision { ManifestId = bucket.ManifestId, Category = bucket.Category, Revision = rev });
}
- // 6) Personal-scoped email routing + public keys. The personal key is published scoped to the caller's
- // personal manifest, the exact same flow as a shared manifest's delivery key below.
- if (!string.IsNullOrEmpty(model.UserEncryptionPublicKey))
+ /*
+ * 6) Delivery keys. A manifest's keypair lives inside the manifest content, so its public half should only
+ * change in a write that changes that content.
+ */
+ var publishing = resolved.Where(r => !string.IsNullOrEmpty(r.Write.EncryptionPublicKey)).ToList();
+ if (publishing.Count > 0)
{
- var personalManifestId = await GroupHelper.GetPersonalManifestIdAsync(context, user.PersonalGroupId);
- if (personalManifestId is not null)
+ // Only admins are allowed to publish a new shared manifest's key.
+ var sharedIds = publishing.Where(r => r.Row.OwnerGroupId != user.PersonalGroupId).Select(r => r.Row.ManifestId);
+ var publishable = await GetAdminAccessSharedManifestIdsAsync(context, user.Id, sharedIds);
+ foreach (var (mw, row) in publishing.Where(r => r.Row.OwnerGroupId == user.PersonalGroupId || publishable.Contains(r.Row.ManifestId)))
{
- await PublishManifestPublicKeyAsync(context, personalManifestId.Value, model.UserEncryptionPublicKey);
- }
- }
-
- // Publish shared manifest delivery keys.
- if (model.SharedManifestEncryptionPublicKeys.Count > 0)
- {
- var publishable = await GetAdminAccessSharedManifestIdsAsync(context, user.Id, model.SharedManifestEncryptionPublicKeys.Select(k => k.ManifestId));
- foreach (var manifestKey in model.SharedManifestEncryptionPublicKeys.Where(k => publishable.Contains(k.ManifestId)))
- {
- await PublishManifestPublicKeyAsync(context, manifestKey.ManifestId, manifestKey.PublicKey);
+ await PublishManifestPublicKeyAsync(context, row.ManifestId, mw.EncryptionPublicKey!);
}
// Claim resolution below reads these rows back, so they must be visible to the query.
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs
index 97593dd1f..cbed9b748 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/ManifestWrite.cs
@@ -31,6 +31,11 @@ public class ManifestWrite
/// each exists (in the caller's store for their personal manifest; in any member's store for a shared manifest) before committing.</summary>
public List<BlobReference> BlobReferences { get; set; } = [];
+ /// <summary>
+ /// Gets or sets the public half of this manifest's active RSA key pair (used to e.g. encrypt incoming emails).
+ /// </summary>
+ public string? EncryptionPublicKey { get; set; }
+
/// <summary>
/// Gets or sets the encrypted VEK of the vault encryption key encrypted with the password-derived KEK using AES-256-GCM.
/// Set on the legacy user's first manifest-v1 write, where the client re-encrypts the whole vault under a fresh VEK;
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/SharedManifestEncryptionPublicKey.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/SharedManifestEncryptionPublicKey.cs
deleted file mode 100644
index a662c65f2..000000000
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/SharedManifestEncryptionPublicKey.cs
+++ /dev/null
@@ -1,21 +0,0 @@
-//-----------------------------------------------------------------------
-// <copyright file="SharedManifestEncryptionPublicKey.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>
-/// The public half of a shared manifest's email keypair, published so the SMTP service can encrypt mail
-/// for the manifest's aliases. The private half never leaves the manifest.
-/// </summary>
-public class SharedManifestEncryptionPublicKey
-{
- /// <summary>Gets or sets the shared manifest this key belongs to.</summary>
- public required Guid ManifestId { get; set; }
-
- /// <summary>Gets or sets the public key to publish as the manifest's active delivery key.</summary>
- public required string PublicKey { get; set; }
-}
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.cs
index a24c4772e..ce19f183c 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Vault/VaultWriteRequest.cs
@@ -27,16 +27,6 @@ public class VaultWriteRequest
/// <summary>Gets or sets the email routing data to update server-side.</summary>
public EmailRoutingPush? EmailRouting { get; set; }
- /// <summary>
- /// Gets or sets the user's public encryption key.
- /// </summary>
- public string? UserEncryptionPublicKey { get; set; }
-
- /// <summary>
- /// Gets or sets the shared manifests' public encryption keys.
- /// </summary>
- public List<SharedManifestEncryptionPublicKey> SharedManifestEncryptionPublicKeys { get; set; } = [];
-
/// <summary>
/// Gets or sets the encrypted Account Key and KEK derivation parameters for the given unlock method.
/// </summary>