Skip to content

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

Add browser extension groups/sharing init logic (#2159)

Leendert de Borst1ca04a787ade
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 3eba92c52..4d0d1dfc7 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -14,7 +14,7 @@ import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { readLegacySessionEncryptionKey } from '@/utils/legacy/LegacyStorageKeyFallbacks';
import { requiresLegacyAccountKeyMigration } from '@/utils/legacy/LegacyStorageModelMigration';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
-import { getManifestRevisions, manifestsRequiringPull, toManifestRevisionMap } from '@/utils/ManifestRevisions';
+import { getManifestRevisions, manifestsRequiringPull, recordManifestRevisions, toManifestRevisionMap } from '@/utils/ManifestRevisions';
import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessaging';
import { PendingActionProcessor } from '@/utils/PendingActionProcessor';
import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';
@@ -2504,7 +2504,7 @@ export async function handleGetRecentlySelected(
* Create the shared vault of a group the user administers.
* @param message - the group to create the vault for.
*/
-export async function handleGroupCreateVault(message: { groupId: string }): Promise<{ success: boolean; error?: string }> {
+export async function handleGroupCreateVault(message: { groupId: string }): Promise<{ success: boolean; error?: string; apiErrorCode?: string }> {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
return { success: false, error: formatErrorWithCode(await t('common.errors.vaultIsLocked'), AppErrorCode.VAULT_LOCKED) };
@@ -2516,6 +2516,7 @@ export async function handleGroupCreateVault(message: { groupId: string }): Prom
const group = overview.groups.find(candidate => candidate.groupId.toLowerCase() === message.groupId.toLowerCase());
if (!group || group.role === 'Member') {
+ console.error(`Failed to create shared vault: group ${message.groupId} is not one this account administers.`);
return { success: false, error: await t('sharing.family.errors.createVaultFailed') };
}
@@ -2536,31 +2537,28 @@ export async function handleGroupCreateVault(message: { groupId: string }): Prom
return { success: false, error: await t('sharing.family.errors.vaultUpgradeRequired') };
}
- // The vault's id doubles as its anchor folder id.
- const anchorId = crypto.randomUUID().toUpperCase();
const mapping = await SharingService.createSharedManifest(webApi, {
groupId: group.groupId,
name: group.name,
selfPublicKey,
- }, anchorId, anchorId);
+ }, crypto.randomUUID().toUpperCase());
await SharingService.addSessionSharedManifest({
- folderId: anchorId,
manifestId: mapping.manifestId,
vek: mapping.vek,
salt: mapping.salt,
- revision: mapping.revision,
name: group.name,
canAdminister: true,
});
+ await recordManifestRevisions({ [mapping.manifestId]: mapping.revision });
await createAnchorFolder(sqliteClient, mapping.manifestId, group.name);
// Mail to an alias in this vault is encrypted with the vault's own keypair, which is what makes it readable by every member.
await SharingService.rotateManifestEncryptionKey(sqliteClient, mapping.manifestId);
await persistLocalVaultMutation(sqliteClient, encryptionKey);
- devLog(`[Sharing] Created shared vault ${mapping.manifestId} for group ${group.groupId}, anchored at folder ${anchorId}.`);
+ devLog(`[Sharing] Created shared vault ${mapping.manifestId} for group ${group.groupId}.`);
return { success: true };
} catch (error) {
if (error instanceof ApiRequestError && error.apiErrorCode === 'GROUP_MANIFEST_EXISTS') {
@@ -2569,7 +2567,17 @@ export async function handleGroupCreateVault(message: { groupId: string }): Prom
}
console.error('Failed to create shared vault:', error);
- return { success: false, error: await t('sharing.family.errors.createVaultFailed') };
+ if (error instanceof ApiRequestError && error.apiErrorCode) {
+ return { success: false, apiErrorCode: error.apiErrorCode };
+ }
+
+ /*
+ * Everything this can fail on (a vault that will not open, a key that will not import, a server that refuses
+ * without a code) collapses into the same sentence otherwise, which leaves nothing to act on. The cause is
+ * appended the way the upload path does it.
+ */
+ const detail = error instanceof Error && error.message.length > 0 ? ` [${error.message}]` : '';
+ return { success: false, error: `${await t('sharing.family.errors.createVaultFailed')}${detail}` };
}
}
@@ -2599,10 +2607,10 @@ export async function handleGroupInviteMember(message: { groupId: string; userna
}
const recipient = await SharingService.resolveInvitationRecipient(webApi, group.groupId, message.username);
- const grant = await SharingService.sealVekFor(record.vek, recipient);
+ const grant = await SharingService.encryptVekFor(record.vek, recipient);
await SharingService.invite(webApi, group.groupId, recipient.userId, grant, VaultKeyAlgorithm.RsaOaepSha256);
- devLog(`[Sharing] Invited ${recipient.userId} to group ${group.groupId} with the key to vault ${record.manifestId} sealed in.`);
+ devLog(`[Sharing] Invited ${recipient.userId} to group ${group.groupId} with the key to vault ${record.manifestId} encrypted for them.`);
return { success: true };
} catch (error) {
if (error instanceof ApiRequestError && error.apiErrorCode) {
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 e2f8aa42e..b01b6de1e 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/ServerSyncIndicator.tsx
@@ -8,9 +8,11 @@ import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
/**
* Minimum time (ms) to show the syncing indicator.
- * Ensures user sees confirmation that a new vault was downloaded.
+ * 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.
*/
-const MIN_SYNC_DISPLAY_TIME = 1000;
+const MIN_SYNC_DISPLAY_TIME = 400;
/**
* Grace period (ms) before the pending indicator appears. A save flips the vault to dirty for a few hundred ms
diff --git a/apps/browser-extension/src/utils/SharingService.ts b/apps/browser-extension/src/utils/SharingService.ts
new file mode 100644
index 000000000..b8908737c
--- /dev/null
+++ b/apps/browser-extension/src/utils/SharingService.ts
@@ -0,0 +1,246 @@
+import { storage } from 'wxt/utils/storage';
+
+import { StorageKeys } from '@/utils/constants/storageKeys';
+import { devWarn } from '@/utils/devLogger/DevLogger';
+import { VaultKeyAlgorithm, type CreateGroupInvitationRequest, type CreateGroupInvitationResponse, type CreateSharedManifestRequest, type CreateSharedManifestResponse, type GrantRecipient, type GroupInvitationRecipientRequest, type GroupInvitationRecipientResponse, type GroupOverviewResponse, type ManifestGrant, type VaultKeyAlgorithmValue } from '@/utils/dist/core/models/webapi';
+import { EncryptionUtility } from '@/utils/EncryptionUtility';
+import { vaultCodecGenerateManifestSalt } from '@/utils/RustCore';
+import type { SqliteClient } from '@/utils/SqliteClient';
+import type { WebApiService } from '@/utils/WebApiService';
+
+/**
+ * Vault sharing logic. A shared manifest is a non-personal VaultManifest server-side, owned by a group and encrypted with its own VEK.
+ * All manifests (both personal and shared) get combined into a single local sqlite vault database that this client consumes.
+ */
+
+/**
+ * The group a new shared vault is being created for, with the creator's own public key: the VEK is encrypted for it and
+ * for nothing else, because a vault is created before its group has a second member and everyone who joins afterwards
+ * gets the key encrypted for them inside their invitation.
+ */
+export type ShareTarget = {
+ groupId: string;
+ name: string;
+ selfPublicKey: string;
+};
+
+/**
+ * The client-side mapping of a shared manifest: the manifest id plus its VEK, blob-hashing salt and current revision.
+ */
+export type SharedManifestMapping = { manifestId: string; vek: string; salt: string; revision: number };
+
+/**
+ * Session record of a shared manifest resolved during the last pull. Kept in session storage (cleared on lock)
+ * because the VEK is plaintext; rebuilt from the server grant on the next pull.
+ *
+ * This is the sync layer's key cache and nothing more: it says which manifests this session can open and write,
+ * never how any of them is presented. Where a manifest is rendered is the client's own choice, made from the vault
+ * itself (see {@link createAnchorFolder}), and its revision is owned by `ManifestRevisions`.
+ *
+ * The presence of a record is what makes a manifest writable. `canAdminister` is the permission: whether this user
+ * may grant/revoke access and publish the manifest's email delivery key, which is also true for an admin of a group
+ * they do not own.
+ */
+export type SessionSharedManifest = {
+ manifestId: string;
+ vek: string;
+ salt: string;
+ name?: string | null;
+ canAdminister?: boolean;
+};
+
+/**
+ * Service with static helpers implementing the vault sharing flows.
+ */
+export class SharingService {
+ /**
+ * The groups this user is in and the invitations awaiting their answer.
+ * @param webApi - API client to reuse.
+ */
+ public static async getOverview(webApi: WebApiService): Promise<GroupOverviewResponse> {
+ return webApi.get<GroupOverviewResponse>('Groups');
+ }
+
+ /**
+ * Create a shared group's vault.
+ * @param webApi - API client to reuse.
+ * @param group - the group to create the vault for, with this client's own public key to encrypt its VEK for.
+ * @param manifestId - the client-minted id of the new vault.
+ */
+ public static async createSharedManifest(webApi: WebApiService, group: ShareTarget, manifestId: string): Promise<SharedManifestMapping> {
+ const manifestVek = EncryptionUtility.generateVaultEncryptionKey();
+
+ const response = await webApi.post<CreateSharedManifestRequest, CreateSharedManifestResponse>(`Groups/${group.groupId}/manifest`, {
+ manifestId,
+ name: group.name,
+ selfEncryptedVek: await EncryptionUtility.encryptWithPublicKey(manifestVek, group.selfPublicKey),
+ selfPublicKey: group.selfPublicKey,
+ algorithm: VaultKeyAlgorithm.RsaOaepSha256,
+ });
+
+ // The salt the first push writes into the vault: it lives inside the manifest, which does not exist yet.
+ return { manifestId: response.manifestId, vek: manifestVek, salt: await vaultCodecGenerateManifestSalt(), revision: response.revisionNumber };
+ }
+
+ /**
+ * Resolve the account behind a username together with the public key an invitation to it has to be encrypted for.
+ * @param webApi - API client to reuse.
+ * @param groupId - the group to invite into.
+ * @param username - the account to look up.
+ */
+ public static async resolveInvitationRecipient(webApi: WebApiService, groupId: string, username: string): Promise<GrantRecipient> {
+ const response = await webApi.post<GroupInvitationRecipientRequest, GroupInvitationRecipientResponse>(`Groups/${groupId}/invitations/recipient`, { username });
+ return response.recipient;
+ }
+
+ /**
+ * Encrypt a shared manifest's VEK for one recipient, with that recipient's own public key, ready to travel inside
+ * the invitation that offers them the vault.
+ * @param manifestVek - the shared manifest's VEK.
+ * @param recipient - who to encrypt it for.
+ */
+ public static async encryptVekFor(manifestVek: string, recipient: GrantRecipient): Promise<ManifestGrant> {
+ return {
+ recipientUserId: recipient.userId,
+ recipientPublicKeyId: recipient.publicKeyId,
+ encryptedVek: await EncryptionUtility.encryptWithPublicKey(manifestVek, recipient.publicKey),
+ };
+ }
+
+ /**
+ * Invite an account to a group.
+ * @param webApi - API client to reuse.
+ * @param groupId - the group to invite into.
+ * @param userId - the account being invited, as resolved by {@link resolveInvitationRecipient}.
+ * @param grant - the group's vault key, encrypted for that account's public key, as produced by {@link encryptVekFor}.
+ * @param algorithm - the algorithm the grant was encrypted with.
+ */
+ public static async invite(webApi: WebApiService, groupId: string, userId: string, grant: ManifestGrant, algorithm: VaultKeyAlgorithmValue): Promise<void> {
+ await webApi.post<CreateGroupInvitationRequest, CreateGroupInvitationResponse>(`Groups/${groupId}/invitations`, { userId, grant, algorithm });
+ }
+
+ /**
+ * Withdraw an invitation this group sent that has not been answered yet.
+ * @param webApi - API client to reuse.
+ * @param invitationId - the invitation to withdraw.
+ */
+ public static async withdrawInvitation(webApi: WebApiService, invitationId: string): Promise<void> {
+ await webApi.delete<void>(`Groups/invitations/${invitationId}`);
+ }
+
+ /**
+ * Accept an invitation addressed to this user, joining the group.
+ * @param webApi - API client to reuse.
+ * @param invitationId - the invitation to accept.
+ */
+ public static async acceptInvitation(webApi: WebApiService, invitationId: string): Promise<void> {
+ await webApi.post<object, void>(`Groups/invitations/${invitationId}/accept`, {}, false);
+ }
+
+ /**
+ * Decline an invitation addressed to this user.
+ * @param webApi - API client to reuse.
+ * @param invitationId - the invitation to decline.
+ */
+ public static async declineInvitation(webApi: WebApiService, invitationId: string): Promise<void> {
+ await webApi.post<object, void>(`Groups/invitations/${invitationId}/decline`, {}, false);
+ }
+
+ /**
+ * Remove a member from a group, or leave one by naming oneself.
+ * @param webApi - API client to reuse.
+ * @param groupId - the group.
+ * @param userId - the member to remove.
+ */
+ public static async removeMember(webApi: WebApiService, groupId: string, userId: string): Promise<void> {
+ await webApi.delete<void>(`Groups/${groupId}/members/${userId}`);
+ }
+
+ /**
+ * Make sure every shared vault this session administers is anchored at a local folder.
+ * @param sqliteClient - the open local vault.
+ * @returns Whether the vault was mutated.
+ */
+ public static async ensureAnchorFolders(sqliteClient: SqliteClient): Promise<boolean> {
+ let mutated = false;
+
+ for (const record of Object.values(await this.getSessionSharedManifests())) {
+ if (!record.canAdminister) {
+ // A member waiting for the administrator's first push has nothing to anchor yet.
+ continue;
+ }
+
+ const anchored = sqliteClient.executeQuery<{ Id: string }>('SELECT Id FROM Folders WHERE ManifestId = ? AND IsDeleted = 0 AND ParentFolderId IS NULL', [record.manifestId]);
+ if (anchored.length > 0) {
+ continue;
+ }
+
+ await createAnchorFolder(sqliteClient, record.manifestId, record.name ?? 'Shared');
+ devWarn(`[Sharing] Shared vault ${record.manifestId} had no anchor folder; recreated it.`);
+ mutated = true;
+ }
+
+ return mutated;
+ }
+
+ /**
+ * Mint a fresh active keypair for a shared manifest.
+ * @param sqliteClient - the open local vault DB (caller must run this inside a vault mutation so it is saved)
+ * @param manifestId - the shared manifest's id (the stamp its key rows carry)
+ */
+ public static async rotateManifestEncryptionKey(sqliteClient: SqliteClient, manifestId: string): Promise<void> {
+ const keyPair = await EncryptionUtility.generateRsaKeyPair();
+ sqliteClient.encryptionKeys.setActiveForManifest(manifestId, keyPair.publicKey, keyPair.privateKey);
+ }
+
+ /**
+ * The shared manifests resolved during the last pull (see {@link SessionSharedManifest}), keyed by manifest id.
+ * Both manifests the user administers and manifests shared with them arrive embedded in GET /v2/Vault; the pull
+ * flow decrypts their VEKs with the private key and records them here for the push path.
+ */
+ public static async getSessionSharedManifests(): Promise<Record<string, SessionSharedManifest>> {
+ return ((await storage.getItem(StorageKeys.SHARED_MANIFESTS)) as Record<string, SessionSharedManifest> | null) ?? {};
+ }
+
+ /**
+ * Persist the session shared-manifest records (written by the pull flow and share create, read by push and the UI).
+ */
+ public static async setSessionSharedManifests(manifests: Record<string, SessionSharedManifest>): Promise<void> {
+ await storage.setItem(StorageKeys.SHARED_MANIFESTS, manifests);
+ }
+
+ /**
+ * Add (or replace) a session shared-manifest record, used after creating a share so the very next push already
+ * carries the rows stamped for it, before any pull has run.
+ */
+ public static async addSessionSharedManifest(record: SessionSharedManifest): Promise<void> {
+ const manifests = await this.getSessionSharedManifests();
+ manifests[record.manifestId] = record;
+ await this.setSessionSharedManifests(manifests);
+ }
+
+ /**
+ * Decrypt an RSA-OAEP encrypted manifest VEK with the given private key (JWK string), returning the VEK as base64.
+ */
+ public static async decryptManifestVek(encryptedVek: string, privateKey: string): Promise<string> {
+ const plaintextBytes = await EncryptionUtility.decryptWithPrivateKey(encryptedVek, privateKey);
+ return new TextDecoder().decode(plaintextBytes);
+ }
+
+}
+
+/**
+ * Renders a shared manifest as a local folder. This is purely a client-side UI choice: manifests are not tied
+ * to anything, all items in the vault are associated with a manifestId, but how its rendered, either as a
+ * local folder or as hard vault-switching, is the client's own choice. It does not affect the storage and sync layers.
+ * @param sqliteClient - the open local vault.
+ * @param manifestId - the shared vault to give a folder to.
+ * @param name - the group name, used as the folder name.
+ */
+export async function createAnchorFolder(sqliteClient: SqliteClient, manifestId: string, name: string): Promise<void> {
+ const folderId = manifestId.toUpperCase();
+ await sqliteClient.folders.create(name, null, folderId);
+ await sqliteClient.folders.restampSubtree(folderId, manifestId);
+}
+
+export default SharingService;
diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.ts
index 62ddf6a54..92701f616 100644
--- a/apps/browser-extension/src/utils/VaultSyncService.ts
+++ b/apps/browser-extension/src/utils/VaultSyncService.ts
@@ -14,13 +14,13 @@ import { VaultSqlGenerator } from '@/utils/dist/core/vault';
import { buildEmailRouting } from '@/utils/EmailRouting';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { completeLegacyAccountKeyMigration, isLegacySqliteBlobSnapshot, legacyUnstampedRowAdoption, openLegacySqliteBlobSnapshot, prepareLegacyAccountKeyMigration, withOutdatedServerGuard, type LegacyAccountKeyMigration, type LegacySqliteBlobSnapshot } from '@/utils/legacy/LegacyStorageModelMigration';
-import { getManifestRevisions, getPersonalManifestId, recordManifestRevisions, replaceManifestRevisions } from '@/utils/ManifestRevisions';
+import { getManifestRevisions, getPersonalManifestId, recordManifestRevisions, replaceManifestRevisions, toManifestRevisionMap } from '@/utils/ManifestRevisions';
import {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateManifestSalt, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecBlobEntry, type CodecCanonicalized, type CodecManifest, type CodecManifestSpec} from '@/utils/RustCore';
import { SharingService, type SessionSharedManifest } from '@/utils/SharingService';
import { SqliteClient } from '@/utils/SqliteClient';
import { getStorageItem } from '@/utils/StorageUtility';
import { VaultProcessingError } from '@/utils/types/errors/VaultProcessingError';
-import { type VaultManifest, type VaultDataBucket, VaultCodec } from '@/utils/VaultCodec';
+import { type VaultManifest, type VaultDataBucket, type TableData, VaultCodec } from '@/utils/VaultCodec';
import { VaultKeyService } from '@/utils/VaultKeyService';
import { WebApiService } from '@/utils/WebApiService';
@@ -87,13 +87,23 @@ async function verifyDecryptUnpack(base64Ciphertext: string, vek: string, expect
}
/**
- * The folder a client renders a manifest at: the single top-level folder inside it (the one whose
- * parent lives in a namespace this manifest cannot see, so canonicalize nulled it).
- * @param manifest - the decrypted manifest
+ * Every manifest id the vault holds a row for. Read off the whole table set the codec is about to be handed rather
+ * than off a chosen few tables: any stamped row of any table is a row that has to travel with its manifest, so a
+ * narrower check would silently drop the ones it did not look at. Ids are compared exactly, the way the codec
+ * routes them, so "present here" means the same thing as "rows will land there".
+ * @param tables - the vault's tables as read for this canonicalize
*/
-function topLevelFolderId(manifest: VaultManifest): string | null {
- const roots = (manifest.tables.Folders ?? []).filter(row => row.ParentFolderId == null && !row.IsDeleted).map(row => String(row.Id));
- return roots.length === 1 ? roots[0] : null;
+function manifestIdsPresentIn(tables: TableData[]): Set<string> {
+ const present = new Set<string>();
+ for (const table of tables) {
+ for (const record of table.records) {
+ const manifestId = record.ManifestId;
+ if (typeof manifestId === 'string' && manifestId.length > 0) {
+ present.add(manifestId);
+ }
+ }
+ }
+ return present;
}
/**
@@ -268,12 +278,8 @@ type ManifestRecord = {
isPersonal: boolean;
/** Salt this manifest's blob hashes are derived with. */
salt: string;
- /** The folder this manifest is anchored at; null for the personal manifest, which anchors nowhere. */
- folderId: string | null;
/** The key this manifest encrypts with; null for the personal manifest, whose content key the push supplies (it can be freshly minted). */
vek: string | null;
- /** Last-known server revision as of this resolve; the push overlays anything newer it has recorded since. */
- revision: number;
/** Plaintext display name; null for the personal manifest. */
name: string | null;
/** Whether the caller may publish this manifest's email delivery key. */
@@ -422,19 +428,24 @@ export class VaultSyncService {
const accountKeyVeks = new Map<string, string>([[personalDto.manifestId, vek]]);
const resolved: ResolvedManifest[] = [];
const sessionSharedManifests: Record<string, SessionSharedManifest> = {};
- /*
- * Folder id of each manifest as of the last pull, so a manifest that is currently empty (created
- * but not yet split into) still resolves to the folder the client renders it at.
- */
- const priorFolderIds = new Map(Object.values(await SharingService.getSessionSharedManifests()).map(r => [r.manifestId, r.folderId]));
+ const contentlessRevisions: Record<string, number> = {};
for (const dto of [personalDto, ...(snapshot.manifests ?? []).filter(m => m.manifestId !== personalDto.manifestId)]) {
const isPersonal = dto.manifestId === personalDto.manifestId;
const manifestKey = await this.resolveManifestVek(dto, accountKeyVeks, isPersonal, resolved[0]?.manifest ?? null);
if (!manifestKey || !dto.blob) {
- // Same policy as a manifest that fails to open: a shared one only costs us that folder, the home one is the vault.
if (dto.manifestId === personalDto.manifestId) {
throw new Error(`VaultSyncService: no key resolved for the home manifest ${dto.manifestId} (key type "${dto.keyType ?? 'unspecified'}"), refusing to assemble.`);
}
+ if (manifestKey) {
+ sessionSharedManifests[dto.manifestId] = {
+ manifestId: dto.manifestId,
+ vek: manifestKey,
+ salt: await vaultCodecGenerateManifestSalt(),
+ name: dto.name ?? null,
+ canAdminister: dto.canAdminister ?? false,
+ };
+ contentlessRevisions[dto.manifestId] = dto.revision;
+ }
continue;
}
@@ -451,8 +462,7 @@ export class VaultSyncService {
}
resolved.push(entry);
- const folderId = isPersonal ? null : (topLevelFolderId(entry.manifest) ?? priorFolderIds.get(dto.manifestId) ?? null);
- devLog(`[V2Pull] Manifest ${entry.manifestId} opened (content hash verified, ${isPersonal ? 'personal' : `folder ${folderId ?? 'unassigned'}`}): tables: ${Object.entries(entry.manifest.tables).map(([t, rows]) => `${t}=${rows.length}`).join(', ')}`);
+ devLog(`[V2Pull] Manifest ${entry.manifestId} opened (content hash verified, ${isPersonal ? 'personal' : `shared "${entry.manifest.name ?? dto.name ?? 'unnamed'}"`}): tables: ${Object.entries(entry.manifest.tables).map(([t, rows]) => `${t}=${rows.length}`).join(', ')}`);
if (isPersonal) {
/*
@@ -465,21 +475,13 @@ export class VaultSyncService {
continue;
}
- if (folderId) {
- // A manifest the user administers must win over one they only have read access to for the same folder id.
- const existing = sessionSharedManifests[folderId];
- if (!(existing?.canAdminister && !dto.canAdminister)) {
- sessionSharedManifests[folderId] = {
- folderId,
- manifestId: dto.manifestId,
- vek: manifestKey,
- salt: entry.manifest.manifestSalt,
- revision: entry.revision,
- name: entry.manifest.name ?? dto.name ?? null,
- canAdminister: dto.canAdminister ?? false,
- };
- }
- }
+ sessionSharedManifests[entry.manifestId] = {
+ manifestId: entry.manifestId,
+ vek: manifestKey,
+ salt: entry.manifest.manifestSalt,
+ name: entry.manifest.name ?? dto.name ?? null,
+ canAdminister: dto.canAdminister ?? false,
+ };
}
await SharingService.setSessionSharedManifests(sessionSharedManifests);
@@ -538,7 +540,7 @@ export class VaultSyncService {
pulledFingerprints[fingerprintManifestKey(entry.manifestId)] = entry.contentFingerprint;
}
- const manifestRevisions = Object.fromEntries(resolved.map(m => [m.manifestId, m.revision]));
+ const manifestRevisions = { ...Object.fromEntries(resolved.map(m => [m.manifestId, m.revision])), ...contentlessRevisions };
await replaceManifestRevisions(manifestRevisions);
devLog(`[V2Pull] Stored local manifest revisions from snapshot: ${Object.entries(manifestRevisions).map(([id, rev]) => `${id}=${rev}`).join(', ')}. Next status check compares against these.`);
@@ -861,16 +863,7 @@ export class VaultSyncService {
const forceFullWrite = options?.forceFullWrite === true;
const fingerprints = await this.loadContentFingerprints();
- /*
- * The revision each manifest rebases on, re-read here rather than taken off the records: canonicalize may have
- * run earlier (the pre-push no-op check caches its result) and a write in between advances them.
- */
const storedRevisions = await getManifestRevisions();
- /**
- * Get the revision of a manifest from the stored revisions, or use the revision from the manifest record if not found.
- */
- const revisionOf = (record: ManifestRecord): number => storedRevisions[record.manifestId] ?? record.revision;
-
const recordByManifestId = new Map(manifestRecords.map(r => [r.manifestId, r]));
const candidates: PushManifest[] = canonicalized.manifests.flatMap(({ manifest, blobs }): PushManifest[] => {
const record = recordByManifestId.get(manifest.manifestId);
@@ -881,10 +874,9 @@ export class VaultSyncService {
manifestId: record.manifestId,
isPersonal: record.isPersonal,
manifest,
- // Only the personal manifest leaves its key open, for the content key resolved above.
vek: record.vek ?? contentKey,
blobs,
- currentRevision: revisionOf(record),
+ currentRevision: storedRevisions[record.manifestId] ?? 0,
}];
});
@@ -1068,7 +1060,7 @@ export class VaultSyncService {
* 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 anchored at folder ${record.folderId} is missing its email keypair; its aliases stay personal until sharing is re-enabled.`);
+ devWarn(`[V2Push] Shared manifest ${record.manifestId} is missing its email keypair; its aliases stay personal until sharing is re-enabled.`);
}
}
@@ -1125,16 +1117,7 @@ export class VaultSyncService {
}
// Advance the baseline of the manifests this write included.
- const sessionShared = await SharingService.getSessionSharedManifests();
- const writtenRevisions = new Map((resp.manifestRevisions ?? []).map(r => [r.manifestId, r.revision]));
- await recordManifestRevisions(Object.fromEntries(writtenRevisions));
- for (const record of Object.values(sessionShared)) {
- const revision = writtenRevisions.get(record.manifestId);
- if (revision !== undefined) {
- record.revision = revision;
- }
- }
- await SharingService.setSessionSharedManifests(sessionShared);
+ await recordManifestRevisions(toManifestRevisionMap(resp.manifestRevisions));
/*
* Record the new content baselines for every target this write actually carried, so the next push can skip
@@ -1188,7 +1171,7 @@ export class VaultSyncService {
// Read tables from the SQLite database and apply the manifest-v1 format rules.
const tables = VaultCodec.readTables(sqliteClient);
- const manifestRecords = await this.resolveManifestRecords(sqliteClient);
+ const manifestRecords = await this.resolveManifestRecords(tables);
/*
* Membership is the ManifestId stamp on each row (written by the repositories at insert, move and share time),
* so a spec only has to name the manifest and supply its blob salt. The personal manifest goes first: the codec reads the
@@ -1335,40 +1318,35 @@ export class VaultSyncService {
/**
* Resolve every manifest this vault can write, personal manifest first, as one uniform list.
- * @param sqliteClient - the open local vault DB
+ * @param tables - the vault's tables as read for this canonicalize
*/
- private async resolveManifestRecords(sqliteClient: SqliteClient): Promise<ManifestRecord[]> {
+ private async resolveManifestRecords(tables: TableData[]): Promise<ManifestRecord[]> {
let manifestSalt = (await storage.getItem(StorageKeys.VAULT_MANIFEST_SALT)) as string | null;
if (!manifestSalt) {
manifestSalt = await vaultCodecGenerateManifestSalt();
await storage.setItem(StorageKeys.VAULT_MANIFEST_SALT, manifestSalt);
}
- const personalManifestId = await this.resolvePersonalManifestId();
const records: ManifestRecord[] = [{
- manifestId: personalManifestId,
+ manifestId: await this.resolvePersonalManifestId(),
isPersonal: true,
salt: manifestSalt,
- folderId: null,
vek: null,
- revision: (await getManifestRevisions())[personalManifestId] ?? 0,
name: null,
- // The personal manifest's own delivery key is published as the account-level key, not per manifest.
canAdminister: false,
}];
- const folderIdsInDb = new Set(sqliteClient.executeQuery<{ Id: string }>('SELECT Id FROM Folders').map(r => r.Id));
+ const stampedManifestIds = manifestIdsPresentIn(tables);
for (const record of Object.values(await SharingService.getSessionSharedManifests())) {
- if (!folderIdsInDb.has(record.folderId)) {
+ if (!stampedManifestIds.has(record.manifestId)) {
+ devLog(`[V2Push] Shared manifest ${record.manifestId} has no rows in this vault; leaving it out of the write rather than emptying it server-side.`);
continue;
}
records.push({
manifestId: record.manifestId,
isPersonal: false,
salt: record.salt,
- folderId: record.folderId,
vek: record.vek,
- revision: record.revision ?? 0,
name: record.name ?? null,
canAdminister: record.canAdminister === true,
});
diff --git a/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts b/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts
index ef0426816..38a72444b 100644
--- a/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts
+++ b/apps/browser-extension/src/utils/dist/core/models/webapi/index.d.ts
@@ -525,16 +525,10 @@ declare const VaultKeyAlgorithm: {
type VaultKeyAlgorithmValue = typeof VaultKeyAlgorithm[keyof typeof VaultKeyAlgorithm];
/**
- * The messages of the /v2/Groups API: the membership half of vault sharing — who is in a shared group, who has been
- * asked to join one, and the grants that hand a group's vault key to a member.
- *
- * The names mirror the server DTOs in `AliasVault.Shared.Models.WebApi.V2.Groups` one for one, so a change on either
- * side is visible as a change to its counterpart. Server `Guid` and `DateTime` are strings here, as they are on the
- * wire.
+ * The messages of the /v2/Groups API: the membership half of vault sharing.
*/
/**
- * A member's role in a group. The wire form is the name of the server-side `GroupRole` enum member; the privilege
- * ordering it encodes belongs to the server and is never re-derived by a client.
+ * A member's role in a group.
*/
type GroupRole = 'Owner' | 'Admin' | 'Member';
/**
@@ -554,7 +548,7 @@ type SentGroupInvitation = {
createdAt: string;
};
/**
- * An open invitation addressed to this user: an offer to join somebody else's group.
+ * An open invitation addressed to this user.
*/
type ReceivedGroupInvitation = {
id: string;
@@ -570,10 +564,8 @@ type GroupInfo = {
groupId: string;
name: string;
role: GroupRole;
- /** The group's shared vault, or null while no admin has created one yet. Nobody can be invited before it exists. */
manifestId: string | null;
members: GroupMemberInfo[];
- /** Open invitations sent from this group. Only served to admins, so empty for a plain member. */
pendingInvitations: SentGroupInvitation[];
};
/**
@@ -584,28 +576,24 @@ type GroupOverviewResponse = {
receivedInvitations: ReceivedGroupInvitation[];
};
/**
- * Create a shared group's vault: the manifest blob encrypted with a freshly minted VEK, plus the creator's own copy
- * of that VEK. The server is told which public key was used and looks its own row up from that, so it cannot name a
- * key it holds the private half of and be handed a readable copy of the VEK.
+ * Create a shared group's vault.
*/
type CreateSharedManifestRequest = {
manifestId: string;
name: string;
- manifestBlob: string;
- manifestCiphertextHash?: string;
selfEncryptedVek: string;
selfPublicKey: string;
algorithm: VaultKeyAlgorithmValue;
};
/**
- * The created vault, as served by POST /v2/Groups/{groupId}/manifest.
+ * The created manifest, as served by POST /v2/Groups/{groupId}/manifest.
*/
type CreateSharedManifestResponse = {
manifestId: string;
revisionNumber: number;
};
/**
- * Ask which account a username belongs to, and which public key an invitation to it must be sealed for.
+ * Ask which account a username belongs to, and which public key an invitation to it must be encrypted for.
*/
type GroupInvitationRecipientRequest = {
username: string;
@@ -633,8 +621,7 @@ type ManifestGrant = {
encryptedVek: string;
};
/**
- * Invite an account to a group, handing over the group's vault key sealed for them in the same call: accepting is
- * then the single step that makes someone a member and gives them the key.
+ * Invite an account to a group.
*/
type CreateGroupInvitationRequest = {
userId: string;
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index aa7481793..0a2609289 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -89,7 +89,7 @@ export interface IExtensionMessageProtocol {
GET_VAULT(): VaultResponse;
GET_VAULT_MIGRATION_STATUS(): VaultMigrationStatus;
GET_WEBAUTHN_SETTINGS(data: any): WebAuthnSettingsResponse;
- GROUP_CREATE_VAULT(data: { groupId: string }): { success: boolean; error?: string };
+ GROUP_CREATE_VAULT(data: { groupId: string }): { success: boolean; error?: string; apiErrorCode?: string };
GROUP_INVITE_MEMBER(data: { groupId: string; username: string }): { success: boolean; error?: string; apiErrorCode?: string };
GROUP_REMOVE_MEMBER(data: { groupId: string; userId: string }): { success: boolean; error?: string };
IS_URL_LINKED_TO_CREDENTIAL(data: { itemId: string; url: string }): { linked: boolean };
diff --git a/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts b/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts
index ef0426816..38a72444b 100644
--- a/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts
+++ b/apps/mobile-app/utils/dist/core/models/webapi/index.d.ts
@@ -525,16 +525,10 @@ declare const VaultKeyAlgorithm: {
type VaultKeyAlgorithmValue = typeof VaultKeyAlgorithm[keyof typeof VaultKeyAlgorithm];
/**
- * The messages of the /v2/Groups API: the membership half of vault sharing — who is in a shared group, who has been
- * asked to join one, and the grants that hand a group's vault key to a member.
- *
- * The names mirror the server DTOs in `AliasVault.Shared.Models.WebApi.V2.Groups` one for one, so a change on either
- * side is visible as a change to its counterpart. Server `Guid` and `DateTime` are strings here, as they are on the
- * wire.
+ * The messages of the /v2/Groups API: the membership half of vault sharing.
*/
/**
- * A member's role in a group. The wire form is the name of the server-side `GroupRole` enum member; the privilege
- * ordering it encodes belongs to the server and is never re-derived by a client.
+ * A member's role in a group.
*/
type GroupRole = 'Owner' | 'Admin' | 'Member';
/**
@@ -554,7 +548,7 @@ type SentGroupInvitation = {
createdAt: string;
};
/**
- * An open invitation addressed to this user: an offer to join somebody else's group.
+ * An open invitation addressed to this user.
*/
type ReceivedGroupInvitation = {
id: string;
@@ -570,10 +564,8 @@ type GroupInfo = {
groupId: string;
name: string;
role: GroupRole;
- /** The group's shared vault, or null while no admin has created one yet. Nobody can be invited before it exists. */
manifestId: string | null;
members: GroupMemberInfo[];
- /** Open invitations sent from this group. Only served to admins, so empty for a plain member. */
pendingInvitations: SentGroupInvitation[];
};
/**
@@ -584,28 +576,24 @@ type GroupOverviewResponse = {
receivedInvitations: ReceivedGroupInvitation[];
};
/**
- * Create a shared group's vault: the manifest blob encrypted with a freshly minted VEK, plus the creator's own copy
- * of that VEK. The server is told which public key was used and looks its own row up from that, so it cannot name a
- * key it holds the private half of and be handed a readable copy of the VEK.
+ * Create a shared group's vault.
*/
type CreateSharedManifestRequest = {
manifestId: string;
name: string;
- manifestBlob: string;
- manifestCiphertextHash?: string;
selfEncryptedVek: string;
selfPublicKey: string;
algorithm: VaultKeyAlgorithmValue;
};
/**
- * The created vault, as served by POST /v2/Groups/{groupId}/manifest.
+ * The created manifest, as served by POST /v2/Groups/{groupId}/manifest.
*/
type CreateSharedManifestResponse = {
manifestId: string;
revisionNumber: number;
};
/**
- * Ask which account a username belongs to, and which public key an invitation to it must be sealed for.
+ * Ask which account a username belongs to, and which public key an invitation to it must be encrypted for.
*/
type GroupInvitationRecipientRequest = {
username: string;
@@ -633,8 +621,7 @@ type ManifestGrant = {
encryptedVek: string;
};
/**
- * Invite an account to a group, handing over the group's vault key sealed for them in the same call: accepting is
- * then the single step that makes someone a member and gives them the key.
+ * Invite an account to a group.
*/
type CreateGroupInvitationRequest = {
userId: string;
diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
index df4d1de63..1e8ad5af0 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
@@ -137,12 +137,6 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.MANIFEST_ID_INVALID, 400));
}
- // The manifest ciphertext is base64-encoded but stored as raw bytes.
- if (!CiphertextHelper.TryDecode(model.ManifestBlob, out var manifestBlob))
- {
- return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.VAULT_ERROR, 400));
- }
-
if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
{
return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
@@ -165,16 +159,15 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
return BadRequest(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_MANIFEST_EXISTS, 400));
}
+ // Create the empty manifest.
var manifest = new VaultManifest
{
ManifestId = model.ManifestId,
OwnerGroupId = groupId,
Name = model.Name,
StorageFormat = ManifestFormat,
- ManifestBlob = manifestBlob,
- ManifestCiphertextHash = model.ManifestCiphertextHash,
- RevisionNumber = 1,
- FileSize = FileHelper.BytesToKilobytes(manifestBlob.Length),
+ RevisionNumber = 0,
+ FileSize = 0,
Client = clientHeader,
CreatedAt = timeProvider.UtcNow,
UpdatedAt = timeProvider.UtcNow,
diff --git a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
index b40a166c3..ca6af9a84 100644
--- a/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
+++ b/apps/server/Shared/AliasVault.Shared/Models/WebApi/V2/Groups/CreateSharedManifestRequest.cs
@@ -18,12 +18,6 @@ public class CreateSharedManifestRequest
/// <summary>Gets or sets the plaintext display name of the manifest.</summary>
public required string Name { get; set; }
- /// <summary>Gets or sets the encrypted manifest blob (AES-GCM ciphertext under the manifest VEK, base64).</summary>
- public required string ManifestBlob { get; set; }
-
- /// <summary>Gets or sets the SHA-256 (hex) of the manifest ciphertext, for storage-layer integrity verification.</summary>
- public string? ManifestCiphertextHash { get; set; }
-
/// <summary>Gets or sets the manifest VEK encrypted with the user's own public key (base64), decryptable only by the user.</summary>
public required string SelfEncryptedVek { get; set; }
diff --git a/core/models/src/webapi/Email.ts b/core/models/src/webapi/Email.ts
index bcf93d4cf..79f12add2 100644
--- a/core/models/src/webapi/Email.ts
+++ b/core/models/src/webapi/Email.ts
@@ -1,4 +1,3 @@
-import { EmailAttachment } from "./EmailAttachment";
import { EmailDecryptionKey } from "./EmailDecryptionKey";
export type Email = {
diff --git a/core/models/src/webapi/Groups.ts b/core/models/src/webapi/Groups.ts
index e6a08fac8..2c2d8f5ad 100644
--- a/core/models/src/webapi/Groups.ts
+++ b/core/models/src/webapi/Groups.ts
@@ -64,8 +64,6 @@ export type GroupOverviewResponse = {
export type CreateSharedManifestRequest = {
manifestId: string;
name: string;
- manifestBlob: string;
- manifestCiphertextHash?: string;
selfEncryptedVek: string;
selfPublicKey: string;
algorithm: VaultKeyAlgorithmValue;
@@ -80,7 +78,7 @@ export type CreateSharedManifestResponse = {
}
/**
- * Ask which account a username belongs to, and which public key an invitation to it must be sealed for.
+ * Ask which account a username belongs to, and which public key an invitation to it must be encrypted for.
*/
export type GroupInvitationRecipientRequest = {
username: string;