Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add vault sharing manifest create and invite user logic to Rust layer (#2159)
Leendert de Borst6e7b06bca1b3
diff --git a/core/client/src/sharing/FamilySharingView.ts b/core/client/src/sharing/FamilySharingView.tsnew file mode 100644index 000000000..752a2dc2c--- /dev/null+++ b/core/client/src/sharing/FamilySharingView.ts@@ -0,0 +1,105 @@+import type { GroupInfo, GroupMemberInfo, SentManifestInvitation, SharedManifestInfo } from '@aliasvault/models/webapi';++/**+ * What the family sharing screen shows and offers, generic and used by multiple clients.+ */++/**+ * One member's access status and current user's available actions on it.+ */+export type MemberAccess = {+ isSelf: boolean;+ hasAccess: boolean;+ invitation: SentManifestInvitation | null;+ statusKey: string;+ canLeave: boolean;+ canRevoke: boolean;+ canWithdraw: boolean;+ canInvite: boolean;+ isReadyForInvite: boolean;+};++/**+ * Whether this account administers the group, which is what creating, inviting, revoking and deleting take.+ * @param group - the group as served by the API.+ */+export function canAdministerGroup(group: Pick<GroupInfo, 'role'>): boolean {+ return group.role === 'Owner' || group.role === 'Admin';+}++/**+ * The viewer's own user id in a group, found through the roster because the API does not name the caller.+ * @param group - the group as served by the API.+ * @param username - the viewer's username.+ * @returns The user id, or an empty string when the roster does not list the viewer.+ */+export function ownUserIdIn(group: Pick<GroupInfo, 'members'>, username: string | null | undefined): string {+ return group.members.find(member => member.username === username)?.userId ?? '';+}++/**+ * Whether the viewer holds a grant on the manifest. Inviting encrypts the manifest's key for somebody else, which+ * an administrator without a grant of their own cannot do.+ * @param manifest - the shared manifest.+ * @param ownUserId - the viewer's user id.+ */+export function holdsManifestKey(manifest: Pick<SharedManifestInfo, 'memberUserIds'>, ownUserId: string): boolean {+ return manifest.memberUserIds.includes(ownUserId);+}++/**+ * One member's access status and current user's available actions on it.+ * @param group - the group the manifest belongs to.+ * @param manifest - the shared manifest.+ * @param member - the member being described.+ * @param ownUserId - the viewer's user id.+ */+export function describeMemberAccess(group: GroupInfo, manifest: SharedManifestInfo, member: GroupMemberInfo, ownUserId: string): MemberAccess {+ const isSelf = member.userId === ownUserId;+ const isAdmin = canAdministerGroup(group);+ const hasAccess = manifest.memberUserIds.includes(member.userId);+ const invitation = manifest.pendingInvitations.find(candidate => candidate.inviteeUserId === member.userId) ?? null;++ return {+ isSelf,+ hasAccess,+ invitation,+ statusKey: hasAccess ? 'sharing.family.hasAccess' : invitation ? 'sharing.family.invited' : 'sharing.family.noAccess',+ canLeave: hasAccess && isSelf && !isAdmin,+ canRevoke: hasAccess && !isSelf && isAdmin,+ canWithdraw: invitation !== null && !isSelf && isAdmin,+ canInvite: !hasAccess && invitation === null && !isSelf && isAdmin && holdsManifestKey(manifest, ownUserId),+ isReadyForInvite: Boolean(member.publicKey),+ };+}++/**+ * The translation key of a member's role.+ * @param member - the member.+ */+export function roleTranslationKey(member: Pick<GroupMemberInfo, 'role'>): string {+ switch (member.role) {+ case 'Owner': return 'sharing.owner';+ case 'Admin': return 'sharing.family.admin';+ default: return 'sharing.family.member';+ }+}++/**+ * The translation key that explains a sharing API error code.+ * @param apiErrorCode - the code the server answered with.+ * @returns The key, or null for a code this screen has no words for.+ */+export function sharingErrorTranslationKey(apiErrorCode: string | null | undefined): string | null {+ switch (apiErrorCode) {+ case 'INVITE_RECIPIENT_NOT_READY': return 'sharing.family.errors.userNotReady';+ case 'NOT_GROUP_MEMBER': return 'sharing.family.errors.notFamilyMember';+ case 'ACCESS_ALREADY_GRANTED': return 'sharing.family.errors.alreadyHasAccess';+ case 'INVITATION_ALREADY_EXISTS': return 'sharing.family.errors.alreadyInvited';+ case 'INVITATION_NOT_FOUND': return 'sharing.family.errors.invitationGone';+ case 'INVITATION_KEY_OUTDATED': return 'sharing.family.errors.invitationKeyOutdated';+ case 'LAST_MANIFEST_GRANT_HOLDER': return 'sharing.family.errors.lastMemberWithAccess';+ case 'GROUP_MANIFEST_LIMIT_REACHED': return 'sharing.family.errors.vaultLimitReached';+ default: return null;+ }+}diff --git a/core/client/src/sharing/MultiManifestRendering.ts b/core/client/src/sharing/MultiManifestRendering.tsindex 68f9f037c..db72da7f8 100644--- a/core/client/src/sharing/MultiManifestRendering.ts+++ b/core/client/src/sharing/MultiManifestRendering.ts@@ -27,14 +27,6 @@ export type MultiManifestRenderer = {*/isManifestRoot(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean;- /**- * Give a shared manifest whatever local presence this mode renders it as.- * @param sqliteClient - The open local vault (caller must run this inside a vault mutation so it is saved)- * @param manifestId - The shared manifest to render- * @param name - The manifest's own name- */- render(sqliteClient: SqliteClient, manifestId: string, name: string): Promise<void>;-/*** What each shared manifest is called, keyed by lower-cased manifest id. This is the authority for the name that* gets pushed into the manifest, so a rename in the UI follows the vault.@@ -45,7 +37,7 @@ export type MultiManifestRenderer = {/*** Renders every shared manifest as a top-level folder whose id is the manifest id, which is what makes the folder- * findable from a manifest id alone and what lets its subtree be re-stamped in one statement.+ * findable from a manifest id alone.*/const subfolderRendering: MultiManifestRenderer = {mode: 'subfolder',@@ -58,18 +50,6 @@ const subfolderRendering: MultiManifestRenderer = {return Boolean(folder.ManifestId) && folder.Id.toLowerCase() === String(folder.ManifestId).toLowerCase();},- /**- * Create the manifest's folder and pull everything under it into the manifest.- * @param sqliteClient - The open local vault- * @param manifestId - The shared manifest to render- * @param name - The folder name, which is the vault's name- */- async render(sqliteClient: SqliteClient, manifestId: string, name: string): Promise<void> {- const folderId = manifestId.toLowerCase();- await sqliteClient.folders.create(name, null, folderId);- await sqliteClient.folders.restampSubtree(folderId, manifestId);- },-/*** The name of a shared manifest is the name of the folder it is rendered as.* @param sqliteClient - The open local vaultdiff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.tsindex 7d81c20d4..d797b7415 100644--- a/core/client/src/sharing/SharingService.ts+++ b/core/client/src/sharing/SharingService.ts@@ -1,12 +1,10 @@-import { VaultKeyAlgorithm, type CreateSharedManifestRequest, type CreateSharedManifestResponse, type DeleteSharedManifestInitiateResponse, type DeleteSharedManifestRequest, type GrantManifestAccessRequest, type GrantManifestAccessResponse, type GroupMemberInfo, type GroupOverviewResponse, type ManifestGrant, type ReceivedManifestInvitation, type VaultKeyAlgorithmValue } from '@aliasvault/models/webapi';+import { type DeleteSharedManifestInitiateResponse, type DeleteSharedManifestRequest, type GroupOverviewResponse, type ReceivedManifestInvitation } from '@aliasvault/models/webapi';-import { MasterPasswordService } from '../auth/MasterPasswordService';import { VaultKeyService } from '../auth/VaultKeyService';import { StorageKeys } from '../constants/StorageKeys';import { EncryptionUtility } from '../crypto/EncryptionUtility';import { getPlatform } from '../platform/ClientPlatform';import { devWarn } from '../platform/Logger';-import { vaultCodecGenerateManifestSalt } from '../rust/RustCore';import type { WebApiService } from '../api/WebApiService';import type { SqliteClient } from '../database/SqliteClient';@@ -17,14 +15,19 @@ import type { SqliteClient } from '../database/SqliteClient';*//**- * A shared manifest about to be created, with the creator's own public key: the VEK is encrypted for it and for nothing- * else, because a new manifest starts out with one member and everybody who is let in afterwards gets the key encrypted- * for them inside the invitation that lets them in.+ * The API calls the sharing flows make.*/-export type ShareTarget = {- groupId: string;- selfPublicKey: string;-};+export type SharingApi = Pick<WebApiService, 'get' | 'post' | 'delete'>;++/**+ * Proves the caller's master password to the server by answering its SRP challenge.+ */+export type SrpChallengeResponder = (challenge: DeleteSharedManifestInitiateResponse) => Promise<DeleteSharedManifestRequest>;++/**+ * Finds the private key that opens something encrypted for the given public key, or null when this client holds none.+ */+export type PrivateKeyResolver = (publicKey: string) => Promise<string | null>;/*** A manifest's VEK as this account holds it.@@ -35,11 +38,6 @@ export type ManifestVekGrant = {algorithm: string;};-/**- * The client-side mapping of a newly created shared manifest.- */-export type SharedManifestMapping = ManifestVekGrant & { manifestId: string; salt: string; revision: number };-/*** Key record of a shared manifest, resolved during the last pull (or a share create) and rebuilt from the server* grant on every pull.@@ -59,63 +57,27 @@ export class SharingService {* The families this user belongs to, their shared manifests, and the invitations awaiting an answer.* @param webApi - API client to reuse.*/- public static async getOverview(webApi: WebApiService): Promise<GroupOverviewResponse> {+ public static async getOverview(webApi: SharingApi): Promise<GroupOverviewResponse> {return webApi.get<GroupOverviewResponse>('Groups');}/**- * Create a shared group's manifest.- * @param webApi - API client to reuse.- * @param group - the group to create the manifest for, with this client's own public key to encrypt its VEK for.- * @param manifestId - the client-generated id of the new manifest.- */- public static async createSharedManifest(webApi: WebApiService, group: ShareTarget, manifestId: string): Promise<SharedManifestMapping> {- const manifestVek = EncryptionUtility.generateVaultEncryptionKey();- const selfEncryptedVek = await EncryptionUtility.encryptWithPublicKey(manifestVek, group.selfPublicKey);-- const response = await webApi.post<CreateSharedManifestRequest, CreateSharedManifestResponse>(`Groups/${group.groupId}/manifests`, {- manifestId,- selfEncryptedVek,- selfPublicKey: group.selfPublicKey,- algorithm: VaultKeyAlgorithm.RsaOaepSha256,- });-- return {- manifestId: response.manifestId,- encryptedVek: selfEncryptedVek,- encryptionPublicKey: group.selfPublicKey,- algorithm: VaultKeyAlgorithm.RsaOaepSha256,- salt: await vaultCodecGenerateManifestSalt(),- revision: response.revisionNumber,- };- }-- /**- * Encrypt a shared manifest's VEK for one member of the group.- * @param manifestVek - the shared manifest's VEK.- * @param member - the member to encrypt it for.- * @param vaultName - what the vault is called, or null when this client has no name for it.+ * Decrypt the vault names encrypted into the invitations addressed to this account.+ * @param sqliteClient - the open local vault, which holds this account's superseded private keys.+ * @param invitations - the invitations as served by the API.+ * @returns The name of each invitation's vault, keyed by invitation id; invitations whose name will not open are left out.*/- public static async encryptVekFor(manifestVek: string, member: GroupMemberInfo, vaultName: string | null): Promise<ManifestGrant | null> {- if (!member.publicKey || !member.publicKeyId) {- return null;- }-- return {- recipientUserId: member.userId,- recipientPublicKeyId: member.publicKeyId,- encryptedVek: await EncryptionUtility.encryptWithPublicKey(manifestVek, member.publicKey),- encryptedName: vaultName ? await EncryptionUtility.encryptWithPublicKey(vaultName, member.publicKey) : null,- };+ public static async openInvitationNames(sqliteClient: SqliteClient, invitations: ReceivedManifestInvitation[]): Promise<Record<string, string>> {+ return this.openInvitationNamesWith(publicKey => this.resolveGrantPrivateKey(sqliteClient, publicKey), invitations);}/**- * Decrypt the vault names encrypted into the invitations addressed to this account.- * @param sqliteClient - the open local vault, which holds this account's superseded private keys.+ * Decrypt the vault names encrypted into the invitations addressed to this account, for a host that keeps its keys elsewhere.+ * @param resolvePrivateKey - finds the private key for the public key an invitation was encrypted for.* @param invitations - the invitations as served by the API.* @returns The name of each invitation's vault, keyed by invitation id; invitations whose name will not open are left out.*/- public static async openInvitationNames(sqliteClient: SqliteClient, invitations: ReceivedManifestInvitation[]): Promise<Record<string, string>> {+ public static async openInvitationNamesWith(resolvePrivateKey: PrivateKeyResolver, invitations: ReceivedManifestInvitation[]): Promise<Record<string, string>> {const names: Record<string, string> = {};for (const invitation of invitations) {@@ -123,7 +85,7 @@ export class SharingService {continue;}- const privateKey = await this.resolveGrantPrivateKey(sqliteClient, invitation.recipientPublicKey);+ const privateKey = await resolvePrivateKey(invitation.recipientPublicKey);if (!privateKey) {devWarn(`[Sharing] No account key in this vault decrypts the name encrypted into invitation ${invitation.id}.`);continue;@@ -139,19 +101,6 @@ export class SharingService {return names;}- /**- * Invite a member of the group to one of its shared manifests.- * @param webApi - API client to reuse.- * @param groupId - the group the manifest belongs to.- * @param manifestId - the shared manifest to invite them to.- * @param userId - the member being invited.- * @param grant - the manifest's key, encrypted for that member, as produced by {@link encryptVekFor}.- * @param algorithm - the algorithm the grant was encrypted with.- */- public static async inviteMember(webApi: WebApiService, groupId: string, manifestId: string, userId: string, grant: ManifestGrant, algorithm: VaultKeyAlgorithmValue): Promise<void> {- await webApi.post<GrantManifestAccessRequest, GrantManifestAccessResponse>(`Groups/${groupId}/manifests/${manifestId}/access`, { userId, grant, algorithm });- }-/*** Take a member's access to one shared manifest away, or hand back one's own. The server refuses the latter for group admins.* @param webApi - API client to reuse.@@ -159,7 +108,7 @@ export class SharingService {* @param manifestId - the shared manifest.* @param userId - the member losing access.*/- public static async revokeAccess(webApi: WebApiService, groupId: string, manifestId: string, userId: string): Promise<void> {+ public static async revokeAccess(webApi: SharingApi, groupId: string, manifestId: string, userId: string): Promise<void> {await webApi.delete<void>(`Groups/${groupId}/manifests/${manifestId}/access/${userId}`);}@@ -169,12 +118,11 @@ export class SharingService {* @param webApi - API client to reuse.* @param groupId - the group the manifest belongs to.* @param manifestId - the shared manifest to delete.- * @param password - the caller's master password, proven to the server and forgotten.+ * @param answerChallenge - proves the master password, which each host derives its own way.*/- public static async deleteSharedManifest(webApi: WebApiService, groupId: string, manifestId: string, password: string): Promise<void> {+ public static async deleteSharedManifest(webApi: SharingApi, groupId: string, manifestId: string, answerChallenge: SrpChallengeResponder): Promise<void> {const challenge = await webApi.post<object, DeleteSharedManifestInitiateResponse>(`Groups/${groupId}/manifests/${manifestId}/delete/initiate`, {});- const { proof } = await MasterPasswordService.answerSrpChallenge(challenge, password);- await webApi.post<DeleteSharedManifestRequest, void>(`Groups/${groupId}/manifests/${manifestId}/delete/confirm`, proof, false);+ await webApi.post<DeleteSharedManifestRequest, void>(`Groups/${groupId}/manifests/${manifestId}/delete/confirm`, await answerChallenge(challenge), false);}/**@@ -182,7 +130,7 @@ export class SharingService {* @param webApi - API client to reuse.* @param invitationId - the invitation to withdraw.*/- public static async withdrawInvitation(webApi: WebApiService, invitationId: string): Promise<void> {+ public static async withdrawInvitation(webApi: SharingApi, invitationId: string): Promise<void> {await webApi.delete<void>(`Groups/invitations/${invitationId}`);}@@ -191,7 +139,7 @@ export class SharingService {* @param webApi - API client to reuse.* @param invitationId - the invitation to accept.*/- public static async acceptInvitation(webApi: WebApiService, invitationId: string): Promise<void> {+ public static async acceptInvitation(webApi: SharingApi, invitationId: string): Promise<void> {await webApi.post<object, void>(`Groups/invitations/${invitationId}/accept`, {}, false);}@@ -200,20 +148,10 @@ export class SharingService {* @param webApi - API client to reuse.* @param invitationId - the invitation to decline.*/- public static async declineInvitation(webApi: WebApiService, invitationId: string): Promise<void> {+ public static async declineInvitation(webApi: SharingApi, invitationId: string): Promise<void> {await webApi.post<object, void>(`Groups/invitations/${invitationId}/decline`, {}, false);}- /**- * Generate 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-manifest key records (see {@link SharedManifestRecord}), keyed by manifest id.*/@@ -232,34 +170,6 @@ export class SharingService {}}- /**- * The key record of one shared manifest.- * @param manifestId - the manifest to look up.- */- public static async getSharedManifestRecord(manifestId: string): Promise<SharedManifestRecord | null> {- return Object.values(await this.getSharedManifestRecords()).find(record => record.manifestId.toLowerCase() === manifestId.toLowerCase()) ?? null;- }-- /**- * Persist the shared-manifest key records.- * @param manifests - the full record map; replaces whatever is stored.- * @param encryptionKey - the vault encryption key the map is encrypted with, passed explicitly because both writers already hold it.- */- public static async setSharedManifestRecords(manifests: Record<string, SharedManifestRecord>, encryptionKey: string): Promise<void> {- await getPlatform().storage.set(StorageKeys.SHARED_MANIFESTS, await EncryptionUtility.symmetricEncrypt(JSON.stringify(manifests), encryptionKey));- }-- /**- * Add (or replace) one shared-manifest key record.- * @param record - the record to add.- * @param encryptionKey - the vault encryption key the map is encrypted with.- */- public static async addSharedManifestRecord(record: SharedManifestRecord, encryptionKey: string): Promise<void> {- const manifests = await this.getSharedManifestRecords();- manifests[record.manifestId] = record;- await this.setSharedManifestRecords(manifests, encryptionKey);- }-/*** The session vault encryption key, or null while the vault is locked.*/@@ -267,39 +177,6 @@ export class SharingService {return VaultKeyService.getSessionVaultEncryptionKey();}- /**- * 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);- }-- /**- * Unwrap one shared manifest's VEK from the grant this account holds on it.- * @param sqliteClient - the open local vault, the durable home of the account's superseded private keys.- * @param record - the manifest to open.- */- public static async openSharedManifestVek(sqliteClient: SqliteClient, record: SharedManifestRecord): Promise<string | null> {- if (record.algorithm !== VaultKeyAlgorithm.RsaOaepSha256) {- devWarn(`[Sharing] Manifest ${record.manifestId} grants its key under an unsupported algorithm "${record.algorithm}" (newer server?); leaving it closed.`);- return null;- }-- const privateKey = await this.resolveGrantPrivateKey(sqliteClient, record.encryptionPublicKey);- if (!privateKey) {- devWarn(`[Sharing] No account key in this vault opens the grant on manifest ${record.manifestId}; leaving it closed.`);- return null;- }-- try {- return await this.decryptManifestVek(record.encryptedVek, privateKey);- } catch (error) {- devWarn(`[Sharing] Failed to unwrap the key of manifest ${record.manifestId}; leaving it closed.`, error);- return null;- }- }-/*** The private key that opens a grant made out to `publicKey`.* @param sqliteClient - the open local vault.diff --git a/core/client/src/sync/ManifestRevisions.ts b/core/client/src/sync/ManifestRevisions.tsdeleted file mode 100644index 0ae400a88..000000000--- a/core/client/src/sync/ManifestRevisions.ts+++ /dev/null@@ -1,23 +0,0 @@-/**- * ManifestRevisions.- *- * The client's last-known server revision per manifest.- */--import { StorageKeys } from '../constants/StorageKeys';-import { getPlatform } from '../platform/ClientPlatform';--/**- * Every manifest's last-known server revision, keyed by manifest id; empty when nothing has been pulled yet.- */-async function getManifestRevisions(): Promise<Record<string, number>> {- return ((await getPlatform().storage.get(StorageKeys.SERVER_MANIFEST_REVISIONS)) as Record<string, number> | null) ?? {};-}--/**- * Merge new revisions into the stored map, used after a write where only the manifests actually written advanced.- * @param revisions - the manifest revisions to record- */-export async function recordManifestRevisions(revisions: Record<string, number>): Promise<void> {- await getPlatform().storage.set(StorageKeys.SERVER_MANIFEST_REVISIONS, { ...await getManifestRevisions(), ...revisions });-}diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.tsindex 0aed0f729..853e19213 100644--- a/core/client/src/sync/VaultSync.ts+++ b/core/client/src/sync/VaultSync.ts@@ -21,7 +21,7 @@ import { TranslatableMessage } from '../platform/TranslatableMessage';import { VaultMigrationKind } from './VaultManifestMigration';import { buildVaultSyncRequest, runVaultSyncEngine } from './VaultSyncEngine';-import type { IVaultSyncEngineHost, VaultSyncEmailRouting, VaultSyncEngineResult, VaultSyncEngineResultBase, VaultSyncMigrateManifestResult, VaultSyncMigrationStatusResult, VaultSyncOperation, VaultSyncOptions, VaultSyncResolveVaultKeyResult, VaultSyncStatusCheckResult } from './VaultSyncEngine';+import type { IVaultSyncEngineHost, VaultSyncEmailRouting, VaultSyncEngineRequest, VaultSyncEngineResult, VaultSyncEngineResultBase, VaultSyncMigrateManifestResult, VaultSyncMigrationStatusResult, VaultSyncOperation, VaultSyncOptions, VaultSyncResolveVaultKeyResult, VaultSyncSharingParams, VaultSyncSharingResult, VaultSyncStatusCheckResult } from './VaultSyncEngine';import type { SqliteClient } from '../database/SqliteClient';/**@@ -53,6 +53,17 @@ export type VaultManifestMigrationResult = SyncErrorDetail & {pushed: boolean;};+/**+ * Result of a sharing operation as the UI reads it.+ */+export type SharingOperationResult = SyncErrorDetail & {+ success: boolean;+ /** The API error code the server refused with, which the sharing screen has words for. */+ apiErrorCode?: string;+ /** The vault (or the account's key hierarchy) has to finish upgrading before it can be shared. */+ vaultUpgradeRequired: boolean;+};+/** What every engine result may report for the host to persist. */type AdoptableSyncResult = VaultSyncEngineResultBase & {serverVersion?: string;@@ -148,7 +159,44 @@ export class VaultSync {* @param unlockKeyBase64 - the password-derived key (KEK)*/public async resolveVaultKey(unlockKeyBase64: string): Promise<VaultSyncResolveVaultKeyResult> {- return this.run<VaultSyncResolveVaultKeyResult>('resolveVaultKey', {}, unlockKeyBase64);+ return this.run<VaultSyncResolveVaultKeyResult>('resolveVaultKey', {}, { encryptionKey: unlockKeyBase64 });+ }++ /**+ * Create a group's shared manifest with this account as its first member. The vault is left dirty, so the caller's+ * next sync pushes the new manifest. Never throws.+ * @param groupId - the group to create the shared manifest for+ * @param name - what to call it; the name stays on the clients+ */+ public async createSharedManifest(groupId: string, name: string): Promise<SharingOperationResult> {+ return this.runSharingOperation('createSharedManifest', { groupId, name });+ }++ /**+ * Invite a member of a group to one of its shared manifests, handing them the manifest's key encrypted for their+ * account keypair. Never throws.+ * @param groupId - the group the shared manifest belongs to+ * @param manifestId - the shared manifest to invite them to+ * @param userId - the member being invited+ */+ public async inviteToSharedManifest(groupId: string, manifestId: string, userId: string): Promise<SharingOperationResult> {+ return this.runSharingOperation('inviteToSharedManifest', { groupId, manifestId, userId });+ }++ /**+ * Run one sharing operation.+ * @param operation - the operation+ * @param sharing - what it acts on+ */+ private async runSharingOperation(operation: VaultSyncOperation, sharing: VaultSyncSharingParams): Promise<SharingOperationResult> {+ try {+ const result = await this.run<VaultSyncSharingResult>(operation, {}, { sharing });+ return { success: result.success, apiErrorCode: result.apiErrorCode, vaultUpgradeRequired: result.vaultUpgradeRequired, ...VaultSync.syncError(result) };+ } catch (error) {+ const detail = VaultSync.driverError(error);+ devError(`[Sharing] ${operation} failed (${detail.errorCode ?? 'no code'}): ${detail.error ?? 'no detail'}`);+ return { success: false, vaultUpgradeRequired: false, ...detail };+ }}/**@@ -194,13 +242,10 @@ export class VaultSync {* Run one engine operation and adopt what it reported.* @param operation - the operation* @param options - what the caller asks beyond what the engine decides- * @param encryptionKey - the request key of the one operation that runs on the unlock key itself (resolveVaultKey)+ * @param overrides - what one operation sets on the request itself: the unlock key resolveVaultKey runs on, or the target of a sharing operation*/- private async run<T extends VaultSyncEngineResultBase>(operation: VaultSyncOperation, options: VaultSyncOptions = {}, encryptionKey?: string): Promise<T> {- const request = await buildVaultSyncRequest(operation, options);- if (encryptionKey) {- request.encryptionKey = encryptionKey;- }+ private async run<T extends VaultSyncEngineResultBase>(operation: VaultSyncOperation, options: VaultSyncOptions = {}, overrides: Partial<Pick<VaultSyncEngineRequest, 'encryptionKey' | 'sharing'>> = {}): Promise<T> {+ const request = { ...await buildVaultSyncRequest(operation, options), ...overrides };const result = await runVaultSyncEngine<T>(this.host, request, this.webApi);await this.adoptSyncResult(result);return result;diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.tsindex 9cee5eba7..ce3668e9c 100644--- a/core/client/src/sync/VaultSyncEngine.ts+++ b/core/client/src/sync/VaultSyncEngine.ts@@ -23,7 +23,15 @@ import type { StorageKey } from '../platform/KeyValueStore';import type { ISqliteDatabase, SqliteValue } from '../platform/SqliteEngine';/** The operations the engine runs. */-export type VaultSyncOperation = 'fullSync' | 'migrationStatus' | 'migrateManifest' | 'statusCheck' | 'resolveVaultKey';+export type VaultSyncOperation = 'fullSync' | 'migrationStatus' | 'migrateManifest' | 'statusCheck' | 'resolveVaultKey' | 'createSharedManifest' | 'inviteToSharedManifest';++/** What a sharing operation acts on (the Rust `SharingParams`). */+export type VaultSyncSharingParams = {+ groupId: string;+ manifestId?: string;+ userId?: string;+ name?: string;+};/** What the host hands the engine at session start (the Rust `SyncRequest`). */export type VaultSyncEngineRequest = {@@ -40,6 +48,7 @@ export type VaultSyncEngineRequest = {minServerVersion: string;isOfflineMode: boolean;unnamedSharedVaultName: string;+ sharing?: VaultSyncSharingParams;};/** Session values the engine changed and the host has to adopt. */@@ -109,6 +118,18 @@ export type VaultSyncResolveVaultKeyResult = VaultSyncEngineResultBase & {requiresLogout: boolean;};+/** Outcome of a sharing operation (the Rust `SharingOperationResult`). */+export type VaultSyncSharingResult = VaultSyncEngineResultBase & {+ success: boolean;+ manifestId?: string;+ apiErrorCode?: string;+ vaultUpgradeRequired: boolean;+ error?: string;+ errorCode?: string;+ errorKey?: string;+ requiresLogout: boolean;+};+/** Outcome of the lightweight status check. */export type VaultSyncStatusCheckResult = VaultSyncEngineResultBase & {success: boolean;diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rsindex d6c56802f..1b3cf8fc3 100644--- a/core/rust/src/vault_sync/engine.rs+++ b/core/rust/src/vault_sync/engine.rs@@ -12,7 +12,7 @@ use super::push::{self, CanonicalizedSet, PushStatus};use super::session::Host;use super::state::{self, Ctx};use super::types::{Db, FailureFields, FullSyncResult, LogLevel, MigrateManifestResult, MigrationKind, MigrationStatusResult, OperationResult, ResolveVaultKeyResult, SessionOutcome, StatusCheckResult, StatusResponse, SyncOperation, SyncRequest};-use super::{db, http, keys, legacy};+use super::{db, http, keys, legacy, sharing};use crate::crypto;use crate::vault_model::ids_equal;@@ -49,6 +49,14 @@ pub(crate) async fn run(host: Host, request: SyncRequest) -> Value {let result = resolve_vault_key(&mut ctx).await;finish(&ctx, result)}+ SyncOperation::CreateSharedManifest => {+ let result = sharing::create_shared_manifest_operation(&mut ctx).await;+ finish(&ctx, result)+ }+ SyncOperation::InviteToSharedManifest => {+ let result = sharing::invite_to_shared_manifest_operation(&mut ctx).await;+ finish(&ctx, result)+ }}}@@ -108,7 +116,7 @@ async fn full_sync_operation(ctx: &mut Ctx) -> FullSyncResult {}/// Full vault sync, re-running itself when a mutation raced a store or the server refused a push as outdated.-async fn full_sync(ctx: &mut Ctx) -> SyncResult<FullSyncResult> {+pub(crate) async fn full_sync(ctx: &mut Ctx) -> SyncResult<FullSyncResult> {let mut outdated_resyncs = 0u32;loop {match full_sync_once(ctx).await? {@@ -324,7 +332,7 @@ async fn vault_predates_current_schema(ctx: &mut Ctx) -> SyncResult<bool> {}/// Whether the vault still has to run the manifest migration: a stale schema, or a missing account key hierarchy.-async fn vault_requires_manifest_migration(ctx: &mut Ctx) -> SyncResult<bool> {+pub(crate) async fn vault_requires_manifest_migration(ctx: &mut Ctx) -> SyncResult<bool> {Ok(schema_state(ctx).await? == SchemaState::Stale || !keys::has_local_vault_key(&ctx.host).await?)}diff --git a/core/rust/src/vault_sync/mod.rs b/core/rust/src/vault_sync/mod.rsindex 3c530da11..2c4ca5718 100644--- a/core/rust/src/vault_sync/mod.rs+++ b/core/rust/src/vault_sync/mod.rs@@ -11,6 +11,7 @@ mod merge;mod pull;mod push;mod session;+mod sharing;pub(crate) mod state;pub(crate) mod types;diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rsnew file mode 100644index 000000000..827ac88a3--- /dev/null+++ b/core/rust/src/vault_sync/sharing.rs@@ -0,0 +1,270 @@+//! The sharing operations that take vault keys: creating a group's shared manifest and inviting a member to one.++use serde::{Deserialize, Serialize};++use super::errors::{SyncError, SyncResult};+use super::state::{self, Ctx};+use super::types::{Db, FailureFields, SharedManifestDto, SharingOperationResult, SharingParams, ALGORITHM_RSA_OAEP_SHA256};+use super::{db, engine, http, keys};+use crate::crypto;+use crate::vault_codec;+use crate::vault_model::{id_key, ids_equal};++/// The role of a group member who may not administer it.+const ROLE_MEMBER: &str = "Member";++/// The API error code for a recipient whose account has no keypair yet (legacy non-migrated user account).+const INVITE_RECIPIENT_NOT_READY: &str = "INVITE_RECIPIENT_NOT_READY";++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+struct GroupOverview {+ #[serde(default)]+ groups: Vec<GroupInfo>,+}++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+struct GroupInfo {+ group_id: String,+ role: String,+ #[serde(default)]+ manifests: Vec<GroupManifestInfo>,+ #[serde(default)]+ members: Vec<GroupMemberInfo>,+}++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+struct GroupManifestInfo {+ manifest_id: String,+}++#[derive(Debug, Clone, Default, Deserialize)]+#[serde(rename_all = "camelCase")]+struct GroupMemberInfo {+ user_id: String,+ #[serde(default)]+ public_key_id: Option<String>,+ #[serde(default)]+ public_key: Option<String>,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct CreateSharedManifestRequest<'a> {+ manifest_id: &'a str,+ self_encrypted_vek: &'a str,+ self_public_key: &'a str,+ algorithm: &'a str,+}++#[derive(Debug, Deserialize)]+#[serde(rename_all = "camelCase")]+struct CreateSharedManifestResponse {+ manifest_id: String,+ revision_number: i64,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct ManifestGrant {+ recipient_user_id: String,+ recipient_public_key_id: String,+ encrypted_vek: String,+ encrypted_name: Option<String>,+}++#[derive(Debug, Serialize)]+#[serde(rename_all = "camelCase")]+struct GrantManifestAccessRequest<'a> {+ user_id: &'a str,+ grant: ManifestGrant,+ algorithm: &'a str,+}++/// How a sharing operation ends when it does not succeed.+enum Refusal {+ /// The server (or the engine, seeing the same thing first) refused with an API error code.+ Api(String),+ /// The vault or the account's key hierarchy has to finish upgrading first.+ VaultUpgradeRequired,+}++/// What a sharing operation came to before its result is built.+type Outcome = SyncResult<Result<String, Refusal>>;++/// Create a group's shared manifest.+pub(crate) async fn create_shared_manifest_operation(ctx: &mut Ctx) -> SharingOperationResult {+ let outcome = create_shared_manifest(ctx).await;+ finish(ctx, "create shared manifest", outcome).await+}++/// Invite a group member to a shared manifest.+pub(crate) async fn invite_to_shared_manifest_operation(ctx: &mut Ctx) -> SharingOperationResult {+ let outcome = invite_to_shared_manifest(ctx).await;+ finish(ctx, "invite to shared manifest", outcome).await+}++/// Turn an operation's outcome into the result the host acts on.+async fn finish(ctx: &Ctx, what: &str, outcome: Outcome) -> SharingOperationResult {+ match outcome {+ Ok(Ok(manifest_id)) => SharingOperationResult { success: true, manifest_id: Some(manifest_id), ..Default::default() },+ Ok(Err(Refusal::Api(code))) => SharingOperationResult { api_error_code: Some(code), ..Default::default() },+ Ok(Err(Refusal::VaultUpgradeRequired)) => SharingOperationResult { vault_upgrade_required: true, ..Default::default() },+ Err(error) => {+ ctx.warn(format!("[Sharing] Could not {}: {}", what, error)).await;+ match api_error_code_of(&error) {+ Some(code) => SharingOperationResult { api_error_code: Some(code), ..Default::default() },+ None => SharingOperationResult { failure: FailureFields::from(&error), ..Default::default() },+ }+ }+ }+}++/// The structured API error code (e.g. `GROUP_MANIFEST_LIMIT_REACHED`) of a refused request, when its body names one.+fn api_error_code_of(error: &SyncError) -> Option<String> {+ let SyncError::Http { body, .. } = error else { return None };+ let parsed: serde_json::Value = serde_json::from_str(body).ok()?;+ ["code", "title"].iter().filter_map(|field| parsed.get(field)?.as_str()).find(|value| is_api_error_code(value)).map(str::to_string)+}++/// Server error codes are uppercase enum names.+fn is_api_error_code(value: &str) -> bool {+ (2..=64).contains(&value.len()) && value.chars().all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')+}++/// The sharing target the host sent along.+fn params(ctx: &Ctx) -> SyncResult<SharingParams> {+ ctx.request.sharing.clone().ok_or_else(|| SyncError::Other("The sharing operation carries no target".to_string()))+}++/// The group with the given id, when this account administers it.+async fn administered_group(ctx: &Ctx, group_id: &str) -> SyncResult<GroupInfo> {+ let overview: GroupOverview = http::get(&ctx.host, "Groups", false).await?;+ overview+ .groups+ .into_iter()+ .find(|group| ids_equal(&group.group_id, group_id))+ .filter(|group| group.role != ROLE_MEMBER)+ .ok_or_else(|| SyncError::Other(format!("Group {} is not one this account administers", group_id)))+}++/// This account's public key, which a new shared manifest's key is encrypted for.+async fn own_public_key(ctx: &Ctx) -> SyncResult<Option<String>> {+ match &ctx.account_public_key {+ Some(key) => Ok(Some(key.clone())),+ None => state::get::<String>(&ctx.host, state::ACCOUNT_PUBLIC_KEY).await,+ }+}++async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {+ let key = ctx.encryption_key()?;+ let target = params(ctx)?;+ let name = target.name.as_deref().map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| SyncError::Other("A shared manifest needs a name".to_string()))?.to_string();++ let group = administered_group(ctx, &target.group_id).await?;++ // The new manifest's VEK is encrypted only for this account's own public key upon creation, other users are invited separately.+ let Some(self_public_key) = own_public_key(ctx).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };+ let Some(personal_manifest_id) = state::get::<String>(&ctx.host, state::VAULT_PERSONAL_MANIFEST_ID).await? else { return Ok(Err(Refusal::VaultUpgradeRequired)) };+ if !ctx.has_local_vault().await? || engine::vault_requires_manifest_migration(ctx).await? {+ return Ok(Err(Refusal::VaultUpgradeRequired));+ }++ let manifest_vek = crypto::generate_key_base64();+ let self_encrypted_vek = crypto::encrypt_with_public_key(manifest_vek.as_bytes(), &self_public_key)?;+ let requested_id = db::new_id();+ let response: CreateSharedManifestResponse = http::post(+ &ctx.host,+ &format!("Groups/{}/manifests", group.group_id),+ &CreateSharedManifestRequest { manifest_id: &requested_id, self_encrypted_vek: &self_encrypted_vek, self_public_key: &self_public_key, algorithm: ALGORITHM_RSA_OAEP_SHA256 },+ false,+ )+ .await?;+ let manifest_id = response.manifest_id;++ let mut records = keys::shared_manifest_records(ctx).await?;+ records.insert(+ manifest_id.clone(),+ SharedManifestDto {+ manifest_id: manifest_id.clone(),+ encrypted_vek: self_encrypted_vek,+ encryption_public_key: self_public_key,+ algorithm: ALGORITHM_RSA_OAEP_SHA256.to_string(),+ salt: vault_codec::generate_manifest_salt(),+ name: Some(name.clone()),+ can_administer: true,+ },+ );+ keys::set_shared_manifest_records(&ctx.host, &records, &key).await?;++ let mut revisions: std::collections::HashMap<String, i64> = state::get(&ctx.host, state::SERVER_MANIFEST_REVISIONS).await?.unwrap_or_default();+ revisions.insert(manifest_id.clone(), response.revision_number);+ state::set(&ctx.host, state::SERVER_MANIFEST_REVISIONS, &revisions).await?;++ db::render_manifest_folder(&ctx.host, &manifest_id, &name, &personal_manifest_id).await?;++ // Mail to an alias in this manifest is encrypted with the manifest's own keypair.+ let delivery_keys = crypto::generate_rsa_key_pair()?;+ db::set_active_key_for_manifest(&ctx.host, &manifest_id, &delivery_keys.public_key, &delivery_keys.private_key).await?;++ // The new folder and keypair ride out on the host's next sync, which the dirty flag asks for.+ let bytes = db::export(&ctx.host, Db::Local).await?;+ let stored = ctx.store_vault(&state::encrypt_vault_blob(&bytes, &key)?, true, None, None).await?;+ ctx.is_dirty = true;+ ctx.mutation_sequence = stored.mutation_sequence;+ ctx.vault_changed = true;++ ctx.log(format!("[Sharing] Created shared manifest {} for group {}.", manifest_id, group.group_id)).await;+ Ok(Ok(manifest_id))+}++async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {+ ctx.encryption_key()?;+ let target = params(ctx)?;+ let manifest_id = target.manifest_id.clone().ok_or_else(|| SyncError::Other("The invitation names no shared manifest".to_string()))?;+ let user_id = target.user_id.clone().ok_or_else(|| SyncError::Other("The invitation names no recipient".to_string()))?;++ let group = administered_group(ctx, &target.group_id).await?;+ let manifest = group.manifests.iter().find(|candidate| ids_equal(&candidate.manifest_id, &manifest_id)).ok_or_else(|| SyncError::Other("The shared manifest does not belong to the group".to_string()))?;+ let member = group.members.iter().find(|candidate| candidate.user_id == user_id).ok_or_else(|| SyncError::Other("The recipient is not a member of the group".to_string()))?;+ let (Some(recipient_public_key), Some(recipient_public_key_id)) = (member.public_key.clone(), member.public_key_id.clone()) else {+ return Ok(Err(Refusal::Api(INVITE_RECIPIENT_NOT_READY.to_string())));+ };++ // Find this account's own grant on the manifest.+ let mut record = held_record(ctx, &manifest.manifest_id).await?;+ if record.is_none() {+ ctx.warn(format!("[Sharing] No key record stored for shared manifest {}; pulling to re-record it before inviting.", manifest.manifest_id)).await;+ ctx.request.force_pull = true;+ engine::full_sync(ctx).await?;+ record = held_record(ctx, &manifest.manifest_id).await?;+ }+ let record = record.ok_or_else(|| SyncError::Other("This account holds no key for the shared manifest".to_string()))?;+ let manifest_vek = keys::open_shared_manifest_vek(ctx, &record).await?.ok_or_else(|| SyncError::Other("The key of the shared manifest did not open".to_string()))?;++ // The name travels encrypted in the invitation, so the recipient sees what they are invited to.+ let name = db::manifest_display_names(&ctx.host).await?.get(&id_key(&manifest.manifest_id)).cloned().or(record.name.clone()).filter(|name| !name.is_empty());+ let grant = ManifestGrant {+ recipient_user_id: member.user_id.clone(),+ recipient_public_key_id,+ encrypted_vek: crypto::encrypt_with_public_key(manifest_vek.as_bytes(), &recipient_public_key)?,+ encrypted_name: name.map(|name| crypto::encrypt_with_public_key(name.as_bytes(), &recipient_public_key)).transpose()?,+ };++ http::post_no_content(+ &ctx.host,+ &format!("Groups/{}/manifests/{}/access", group.group_id, manifest.manifest_id),+ &GrantManifestAccessRequest { user_id: &member.user_id, grant, algorithm: ALGORITHM_RSA_OAEP_SHA256 },+ )+ .await?;++ ctx.log(format!("[Sharing] Invited {} to shared manifest {} with its key encrypted for them.", member.user_id, manifest.manifest_id)).await;+ Ok(Ok(manifest.manifest_id.clone()))+}++/// The key record this account holds on a shared manifest.+async fn held_record(ctx: &Ctx, manifest_id: &str) -> SyncResult<Option<SharedManifestDto>> {+ Ok(keys::shared_manifest_records(ctx).await?.into_values().find(|record| ids_equal(&record.manifest_id, manifest_id)))+}diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rsindex 095fa2861..100e7ed10 100644--- a/core/rust/src/vault_sync/tests/mod.rs+++ b/core/rust/src/vault_sync/tests/mod.rs@@ -1,5 +1,6 @@//! Engine tests: the whole sync driven through the command loop against a real SQLite host.+mod sharing;mod test_host;use std::collections::HashMap;diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rsindex dc1a9a205..1bd2a5d18 100644--- a/core/rust/src/vault_sync/types.rs+++ b/core/rust/src/vault_sync/types.rs@@ -23,6 +23,27 @@ pub enum SyncOperation {StatusCheck,/// Open the account's key chain with the password-derived key right after login; see `ResolveVaultKeyResult`.ResolveVaultKey,+ /// Create a group's shared manifest with this account as its first member; see `SharingParams`.+ CreateSharedManifest,+ /// Invite a group member to a shared manifest, handing them its key encrypted for their account keypair.+ InviteToSharedManifest,+}++/// What a sharing operation acts on.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SharingParams {+ pub group_id: String,+ /// The shared manifest to invite to (`inviteToSharedManifest`).+ #[serde(default)]+ pub manifest_id: Option<String>,+ /// The group member being invited (`inviteToSharedManifest`).+ #[serde(default)]+ pub user_id: Option<String>,+ /// What to call the new shared manifest (`createSharedManifest`). It stays on the clients: it rides into the+ /// vault and the invitations, never into the create request.+ #[serde(default)]+ pub name: Option<String>,}/// Sync request.@@ -53,6 +74,9 @@ pub struct SyncRequest {pub is_offline_mode: bool,#[serde(default)]pub unnamed_shared_vault_name: Option<String>,+ /// The target of a sharing operation; absent for every other operation.+ #[serde(default)]+ pub sharing: Option<SharingParams>,}/// Session values the engine changed and the host has to adopt.@@ -209,6 +233,32 @@ impl OperationResult for ResolveVaultKeyResult {}}+/// Outcome of a sharing operation.+#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SharingOperationResult {+ pub success: bool,+ /// The manifest the operation created or invited to.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub manifest_id: Option<String>,+ /// The API error code the server refused with (e.g. `GROUP_MANIFEST_LIMIT_REACHED`), which the sharing screen has+ /// words for. `INVITE_RECIPIENT_NOT_READY` is also reported when the engine sees the recipient has no key yet.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub api_error_code: Option<String>,+ /// The vault (or the account's key hierarchy) has to finish upgrading before it can be shared.+ pub vault_upgrade_required: bool,+ #[serde(flatten)]+ pub failure: FailureFields,+ #[serde(flatten)]+ pub session: SessionOutcome,+}++impl OperationResult for SharingOperationResult {+ fn session_mut(&mut self) -> &mut SessionOutcome {+ &mut self.session+ }+}+/// Outcome of the lightweight status check.#[derive(Debug, Clone, Default, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]