Skip to content

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

Add EmailRouting.ts helper (#2159)

Leendert de Borstafb223b0df52
diff --git a/apps/browser-extension/src/utils/EmailRouting.ts b/apps/browser-extension/src/utils/EmailRouting.ts
new file mode 100644
index 000000000..0baffe853
--- /dev/null
+++ b/apps/browser-extension/src/utils/EmailRouting.ts
@@ -0,0 +1,75 @@
+import { FieldKey } from '@/utils/dist/core/models/vault';
+import type { CodecManifest } from '@/utils/RustCore';
+import type { EmailRoutingPush } from '@/utils/types/EmailRoutingPush';
+
+/**
+ * Build the email routing set a push sends to the server from the canonicalized manifests.
+ *
+ * Which manifest an alias belongs to decides how its mail is encrypted. Every row has already been
+ * routed into the manifest that owns it by the codec, so an address found in a shared manifest is a
+ * shared alias and everything left in the root manifest is personal.
+ *
+ * @param rootManifest - the canonicalized root manifest
+ * @param sharedManifests - the shared manifests produced by the same canonicalize run
+ * @param privateEmailDomains - domains the server hosts mail for; addresses outside them are not claimed
+ * @returns The addresses to claim, split into personal and shared-manifest ones
+ */
+export function buildEmailRouting(rootManifest: CodecManifest, sharedManifests: CodecManifest[], privateEmailDomains: string[]): EmailRoutingPush {
+ const manifestIdByAddress = new Map<string, string | null>();
+
+ /**
+ * Record every claimable address one manifest carries against that manifest.
+ * @param manifest - the manifest to read the items and their login-email fields from
+ * @param manifestId - the manifest's id, or null for the root manifest (its addresses stay personal)
+ */
+ const collect = (manifest: CodecManifest, manifestId: string | null): void => {
+ const liveItemIds = new Set(
+ rowsOf(manifest, 'Items').filter(row => !row.IsDeleted && row.DeletedAt == null).map(row => String(row.Id))
+ );
+
+ for (const fieldValue of rowsOf(manifest, 'FieldValues')) {
+ if (fieldValue.FieldKey !== FieldKey.LoginEmail || fieldValue.IsDeleted) {
+ continue;
+ }
+ if (!liveItemIds.has(String(fieldValue.ItemId))) {
+ continue;
+ }
+
+ const address = typeof fieldValue.Value === 'string' ? fieldValue.Value : '';
+ const domain = address.split('@')[1];
+ if (!domain || !privateEmailDomains.includes(domain)) {
+ continue;
+ }
+
+ if (manifestId !== null || !manifestIdByAddress.has(address)) {
+ manifestIdByAddress.set(address, manifestId);
+ }
+ }
+ };
+
+ collect(rootManifest, null);
+ for (const manifest of sharedManifests) {
+ collect(manifest, manifest.manifestId);
+ }
+
+ const routing: EmailRoutingPush = { emailAddressList: [], sharedEmailAddressList: [] };
+ for (const [address, manifestId] of manifestIdByAddress) {
+ if (manifestId) {
+ routing.sharedEmailAddressList.push({ address, manifestId });
+ } else {
+ routing.emailAddressList.push(address);
+ }
+ }
+
+ return routing;
+}
+
+/**
+ * The rows of one manifest table, or an empty list when the manifest does not carry that table.
+ * @param manifest - the manifest to read from
+ * @param table - the table name
+ * @returns The table's rows
+ */
+function rowsOf(manifest: CodecManifest, table: string): Array<Record<string, unknown>> {
+ return manifest.tables[table] ?? [];
+}
diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.ts
index 607fced51..517384928 100644
--- a/apps/browser-extension/src/utils/VaultSyncService.ts
+++ b/apps/browser-extension/src/utils/VaultSyncService.ts
@@ -10,11 +10,12 @@ import { bucketRevisionStorageKey, StorageKeys } from '@/utils/constants/storage
import { devError, devLog, devWarn } from '@/utils/devLogger/DevLogger';
import type { VaultResponse } from '@/utils/dist/core/models/webapi';
import { VaultSqlGenerator } from '@/utils/dist/core/vault';
+import { buildEmailRouting } from '@/utils/EmailRouting';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
import {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateUserSalt, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecCanonicalized, type CodecManifest, type CodecSharedManifestSpec} from '@/utils/RustCore';
import { SharingService, type SessionSharedManifest } from '@/utils/SharingService';
import { SqliteClient } from '@/utils/SqliteClient';
-import type { EmailRoutingPush } from '@/utils/types/EmailRoutingPush';
+import { getItemWithFallback } from '@/utils/StorageUtility';
import { ServerUpdateRequiredError } from '@/utils/types/errors/ServerUpdateRequiredError';
import { VaultProcessingError } from '@/utils/types/errors/VaultProcessingError';
import { type VaultManifest, type VaultDataBucket, VaultCodec } from '@/utils/VaultCodec';
@@ -664,8 +665,6 @@ export class VaultSyncService {
* @param vek - the symmetric encryption key (on a KEK/VEK migration push this is the password-derived key,
* which becomes the KEK; on a normal push it is the VEK itself)
* @param username - the user's username (sent in the upload payload for cross-check)
- * @param emailRouting - claimed email aliases, split into personal and shared-manifest ones (the server needs
- * these in plaintext for routing, and the split decides which key each alias's mail is encrypted with)
* @param options - set createVaultKey to perform the KEK/VEK migration as part of this push (decided once, in
* handleUploadVault); set forceFullWrite to bypass the content-fingerprint gating and
* rewrite every manifest and bucket (server rollback recovery)
@@ -675,10 +674,9 @@ export class VaultSyncService {
sqliteClient: SqliteClient,
vek: string,
username: string,
- emailRouting: EmailRoutingPush,
options?: { createVaultKey?: boolean; forceFullWrite?: boolean }
): Promise<PushResult> {
- return this.withOutdatedServerGuard(() => this.pushInternal(sqliteClient, vek, username, emailRouting, options));
+ return this.withOutdatedServerGuard(() => this.pushInternal(sqliteClient, vek, username, options));
}
/**
@@ -686,14 +684,12 @@ export class VaultSyncService {
* @param sqliteClient - the in-memory SQLite the user has been editing
* @param vek - the symmetric encryption key
* @param username - the user's username
- * @param emailRouting - claimed email aliases, split into personal and shared-manifest ones
* @param options - see {@link push}
*/
private async pushInternal(
sqliteClient: SqliteClient,
vek: string,
username: string,
- emailRouting: EmailRoutingPush,
options?: { createVaultKey?: boolean; forceFullWrite?: boolean }
): Promise<PushResult> {
/*
@@ -727,6 +723,8 @@ export class VaultSyncService {
devLog('[V2Push] Reusing the canonicalize result from the pre-push no-op check.');
}
const { canonicalized, sharedManifestRecords } = cachedSet ?? await this.canonicalizeVault(sqliteClient);
+ const privateEmailDomains = (await getItemWithFallback<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS)) ?? [];
+ const emailRouting = buildEmailRouting(canonicalized.manifest, (canonicalized.sharedVaults ?? []).map(v => v.manifest), privateEmailDomains);
// Plaintext blob bytes held platform-side for encryption/upload, each staged with the key that encrypts it.
const rootBlobEntries = new Map<string, UploadBlobEntry>(
diff --git a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts b/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
index fb8abff48..f08b1b4aa 100644
--- a/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
+++ b/apps/browser-extension/src/utils/db/queries/ItemQueries.ts
@@ -1,3 +1,5 @@
+import { BaseQueries } from './BaseQueries';
+
/**
* SQL query constants for Item operations.
* Centralizes all item-related queries to avoid duplication.
@@ -170,11 +172,12 @@ export class ItemQueries {
ORDER BY t.DisplayOrder, t.Name`;
/**
- * Insert a new item.
+ * Insert a new item, stamped best-effort with the root manifest id (the codec restamps membership
+ * authoritatively from the folder chain at every sync boundary).
*/
public static readonly INSERT_ITEM = `
- INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
+ INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, ManifestId, CreatedAt, UpdatedAt, IsDeleted)
+ VALUES (?, ?, ?, ?, ?, ${BaseQueries.ROOT_MANIFEST_ID}, ?, ?, ?)`;
/**
* Update an existing item (preserves LogoId if null is passed).