Skip to content

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

Update shared manifest render logic (#2159)

Leendert de Borst29decaab6b02
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
index c3834ebeb..00ee986f8 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
@@ -178,7 +178,7 @@ const ItemsList: React.FC = () => {
return dbContext.sqliteClient.folders.getById(currentFolderRef);
}, [currentFolderRef, dbContext?.sqliteClient, folderRefreshKey]);
- // A virtual folder (today: a shared manifest) is drawn by this client, so it is not editable or deletable here
+ // A virtual folder (e.g. shared manifest) is not editable or deletable here.
const currentFolderIsVirtual = currentFolder !== null && multiManifestRendering.isVirtualFolder(currentFolder);
// Get current folder's full path (for relative path computation in search results)
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
index d5707e255..6ae7ffd09 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSync.kt
@@ -25,7 +25,7 @@ class VaultSync(
private const val TAG = "VaultSync"
/** The engine operations the sharing screen may ask for. */
- private val SHARING_OPERATIONS = setOf("createSharedManifest", "inviteToSharedManifest")
+ private val SHARING_OPERATIONS = setOf("createSharedManifest", "inviteToSharedManifest", "updateSharedManifest")
}
/**
@@ -135,7 +135,7 @@ class VaultSync(
}
/**
- * Run a sharing operation of the engine: `createSharedManifest` or `inviteToSharedManifest`.
+ * Run a sharing operation of the engine: `createSharedManifest`, `inviteToSharedManifest` or `updateSharedManifest`.
*/
suspend fun runSharingOperation(operation: String, params: JSONObject, webApiService: WebApiService): VaultSharingResult {
if (operation !in SHARING_OPERATIONS) {
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
index 687396013..fecc540c7 100644
--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/VaultSyncEngine.kt
@@ -96,7 +96,6 @@ class VaultSyncEngine(
put("forcePull", forcePull)
put("minServerVersion", AppInfo.MIN_SERVER_VERSION)
put("isOfflineMode", vaultStore.getOfflineMode())
- put("unnamedSharedVaultName", storageProvider.getAppContext()?.getString(R.string.unnamed_shared_vault) ?: "Shared vault")
}
(encryptionKey ?: vaultStore.getEncryptionKeyBase64())?.let { request.put("encryptionKey", it) }
(state("accountPublicKey") as? String)?.let { request.put("accountPublicKey", it) }
diff --git a/apps/mobile-app/android/app/src/main/res/values/strings.xml b/apps/mobile-app/android/app/src/main/res/values/strings.xml
index 32a59e5d6..ea172c57c 100644
--- a/apps/mobile-app/android/app/src/main/res/values/strings.xml
+++ b/apps/mobile-app/android/app/src/main/res/values/strings.xml
@@ -88,5 +88,4 @@
<string name="password_unlock_error">Failed to verify password</string>
<string name="password_unlock_attempts_warning">Incorrect password. You will be logged out if you enter the wrong password %d more times.</string>
<string name="password_unlock_max_attempts_reached">Too many failed unlock attempts. You have been logged out for security reasons.</string>
- <string name="unnamed_shared_vault">Shared vault</string>
</resources>
\ No newline at end of file
diff --git a/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx
index a136da19f..a08df652b 100644
--- a/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx
+++ b/apps/mobile-app/app/(tabs)/items/folder/[manifestId]/[id].tsx
@@ -1,6 +1,7 @@
import { scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { canHaveSubfolders, getRecursiveItemCount, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { applyTypeFilter, isItemTypeFilter, parseItemFilterType, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
+import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
import { getFieldValue, FieldKey, ItemTypes } from '@aliasvault/models/vault';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import { useNavigation, useRouter, useLocalSearchParams } from 'expo-router';
@@ -320,6 +321,9 @@ export default function FolderViewScreen(): React.ReactNode {
loadItems();
}, [isAuthenticated, isDatabaseAvailable, loadItems, setIsLoadingItems]);
+ // A virtual folder (e.g. shared manifest) is not editable or deletable here.
+ const isVirtualFolder = multiManifestRendering.isVirtualFolder(folderRef);
+
/**
* Set up header with folder name and edit/delete buttons.
*/
@@ -329,7 +333,7 @@ export default function FolderViewScreen(): React.ReactNode {
/**
* Header right buttons for edit and delete.
*/
- headerRight: (): React.ReactNode => (
+ headerRight: (): React.ReactNode => (isVirtualFolder ? null : (
<View style={{ flexDirection: 'row', gap: 4 }}>
<RobustPressable
onPress={() => setShowEditFolderModal(true)}
@@ -352,9 +356,9 @@ export default function FolderViewScreen(): React.ReactNode {
/>
</RobustPressable>
</View>
- ),
+ )),
});
- }, [navigation, folder?.Name, colors.primary, colors.destructive, t]);
+ }, [navigation, folder?.Name, isVirtualFolder, colors.primary, colors.destructive, t]);
/**
* Delete an item (move to trash).
diff --git a/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx b/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx
index 0c17ef5a5..968363afd 100644
--- a/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx
+++ b/apps/mobile-app/app/(tabs)/settings/family-sharing.tsx
@@ -16,6 +16,7 @@ import { useColors } from '@/hooks/useColorScheme';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import { useVaultSync } from '@/hooks/useVaultSync';
+import { FolderModal } from '@/components/folders/FolderModal';
import { ThemedContainer } from '@/components/themed/ThemedContainer';
import { ThemedScrollView } from '@/components/themed/ThemedScrollView';
import { ThemedText } from '@/components/themed/ThemedText';
@@ -56,6 +57,7 @@ export default function FamilySharingScreen(): React.ReactNode {
const [isRefreshing, setIsRefreshing] = useMinDurationLoading(false, 200);
const [expandedRosters, setExpandedRosters] = useState<Record<string, boolean>>({});
const [newVaultNames, setNewVaultNames] = useState<Record<string, string>>({});
+ const [pendingVaultRename, setPendingVaultRename] = useState<{ group: GroupInfo; manifest: SharedManifestInfo } | null>(null);
/**
* Load the families, their shared folders and the open invitations, plus the names this vault has for them.
@@ -66,9 +68,9 @@ export default function FamilySharingScreen(): React.ReactNode {
setOverview(loaded);
if (sqliteClient) {
- // A shared folder is named after the top-level folder it is rendered as.
+ // A shared vault is shown as a top-level folder.
const folders = await sqliteClient.folders.getAll();
- setVaultNames(Object.fromEntries(folders.filter(folder => multiManifestRendering.isManifestRoot(folder)).map(folder => [folder.Id.toLowerCase(), folder.Name])));
+ setVaultNames(Object.fromEntries(folders.filter(folder => multiManifestRendering.isVirtualFolder(folder)).map(folder => [folder.Id.toLowerCase(), folder.Name])));
setInvitationNames(await SharingService.openInvitationNamesWith(async publicKey => (await sqliteClient.encryptionKeys.getAccountKeypair(publicKey))?.PrivateKey ?? null, loaded.receivedInvitations));
}
@@ -136,7 +138,7 @@ export default function FamilySharingScreen(): React.ReactNode {
* @param params - what it acts on.
* @param fallback - the message for a failure without a more specific reason.
*/
- const runSharingOperation = async (operation: 'createSharedManifest' | 'inviteToSharedManifest', params: Record<string, string>, fallback: string): Promise<void> => {
+ const runSharingOperation = async (operation: 'createSharedManifest' | 'inviteToSharedManifest' | 'updateSharedManifest', params: Record<string, string>, fallback: string): Promise<void> => {
const result = await NativeVaultManager.runSharingOperation(operation, JSON.stringify(params));
if (result.success) {
return;
@@ -168,6 +170,22 @@ export default function FamilySharingScreen(): React.ReactNode {
}, t('sharing.family.errors.createVaultFailed'));
};
+ /**
+ * Rename a shared folder, which only an administrator of the family may do. Every member fetches the name on their next sync.
+ * @param name - the new name.
+ */
+ const renameSharedVault = async (name: string): Promise<void> => {
+ const target = pendingVaultRename;
+ if (!target) {
+ return;
+ }
+
+ await run(async () => {
+ await runSharingOperation('updateSharedManifest', { groupId: target.group.groupId, manifestId: target.manifest.manifestId, name }, t('common.errors.unknownErrorTryAgain'));
+ await syncVault();
+ }, t('common.errors.unknownErrorTryAgain'));
+ };
+
/**
* Invite one member to one shared folder.
* @param group - the family the shared folder belongs to.
@@ -495,6 +513,8 @@ export default function FamilySharingScreen(): React.ReactNode {
<View key={manifest.manifestId} style={styles.card}>
<View style={styles.cardHeader}>
<ThemedText style={styles.cardTitle} numberOfLines={1}>{vaultLabel(manifest)}</ThemedText>
+ {/* Renaming encrypts the name with the folder's key, so it takes a member who holds it. */}
+ {canAdminister && holdsManifestKey(manifest, myUserId) && renderAction(t('items.folders.editFolder'), () => setPendingVaultRename({ group, manifest }))}
{canAdminister && renderAction(t('sharing.family.deleteVault'), () => confirmVaultDelete(group, manifest), true)}
</View>
@@ -543,6 +563,14 @@ export default function FamilySharingScreen(): React.ReactNode {
</>
)}
</ThemedScrollView>
+
+ <FolderModal
+ isOpen={pendingVaultRename !== null}
+ onClose={() => setPendingVaultRename(null)}
+ onSave={renameSharedVault}
+ initialName={pendingVaultRename ? vaultLabel(pendingVaultRename.manifest) : ''}
+ mode="edit"
+ />
</ThemedContainer>
);
}
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
index 44ae3f2e5..c7908175d 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSync.swift
@@ -215,7 +215,7 @@ internal final class VaultSync {
}
/// The engine operations the sharing screen may ask for.
- private static let sharingOperations: Set<String> = ["createSharedManifest", "inviteToSharedManifest"]
+ private static let sharingOperations: Set<String> = ["createSharedManifest", "inviteToSharedManifest", "updateSharedManifest"]
/// The forced logouts by the engine's reason.
private static let logoutErrors: [String: AppError] = [
diff --git a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
index ef43f4a8a..5f28accb5 100644
--- a/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
+++ b/apps/mobile-app/ios/VaultStoreKit/Services/VaultSyncEngine.swift
@@ -84,8 +84,7 @@ public final class VaultSyncEngine {
"privateEmailDomains": metadata?.privateEmailDomains ?? [],
"forcePull": forcePull,
"minServerVersion": AppInfo.minServerVersion,
- "isOfflineMode": vaultStore.getOfflineMode(),
- "unnamedSharedVaultName": NSLocalizedString("unnamed_shared_vault", bundle: .vaultStoreKit, value: "Shared vault", comment: "Name of a shared vault without a name")
+ "isOfflineMode": vaultStore.getOfflineMode()
]
if let key = encryptionKey ?? (try? vaultStore.getEncryptionKeyBase64()) {
request["encryptionKey"] = key
diff --git a/apps/mobile-app/ios/VaultStoreKit/en.lproj/Localizable.strings b/apps/mobile-app/ios/VaultStoreKit/en.lproj/Localizable.strings
index 0afe3f38b..d20f8298a 100644
--- a/apps/mobile-app/ios/VaultStoreKit/en.lproj/Localizable.strings
+++ b/apps/mobile-app/ios/VaultStoreKit/en.lproj/Localizable.strings
@@ -1,2 +1 @@
/* English localization strings for VaultStoreKit */
-"unnamed_shared_vault" = "Shared vault";
diff --git a/apps/mobile-app/platform/MobilePlatform.ts b/apps/mobile-app/platform/MobilePlatform.ts
index aacb9778c..a89ffe6eb 100644
--- a/apps/mobile-app/platform/MobilePlatform.ts
+++ b/apps/mobile-app/platform/MobilePlatform.ts
@@ -11,7 +11,6 @@ import { MobileAppIdentity } from '@/utils/AppInfo';
* Which translation key backs each of the client core's own messages.
*/
const TRANSLATION_KEYS: Record<TranslatableMessage, string> = {
- [TranslatableMessage.UnnamedSharedVault]: 'sharing.family.unnamedVault',
[TranslatableMessage.ClientOutdated]: 'vault.errors.appOutdated',
[TranslatableMessage.SharedFolderDeleteRefused]: 'items.folders.deleteSharedFolderHint',
[TranslatableMessage.VaultUpgradeRequired]: 'vault.errors.vaultOutdated',
diff --git a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
index defea9255..898c62a7a 100644
--- a/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
+++ b/apps/server/AliasVault.Api/Controllers/V2/GroupsController.cs
@@ -192,6 +192,7 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
UpdatedAt = timeProvider.UtcNow,
};
context.VaultManifests.Add(manifest);
+ context.VaultManifestShareDetails.Add(new VaultManifestShareDetails { ManifestId = manifest.ManifestId, EncryptedName = model.EncryptedName, CreatedAt = timeProvider.UtcNow, UpdatedAt = timeProvider.UtcNow });
context.VaultManifestAccessKeys.Add(GrantHelper.BuildGrant(manifest.ManifestId, me.Id, selfPublicKeyId.Value, model.SelfEncryptedVek, algorithm, manifest.KeyVersion, timeProvider.UtcNow));
try
@@ -383,6 +384,55 @@ public class GroupsController(IAliasServerDbContextFactory dbContextFactory, Use
return Ok();
}
+ /// <summary>
+ /// Change the details of one of the group's shared manifests. Metadata that can contain sensitive information is encrypted
+ /// like the name of the manifest / shared vault.
+ /// </summary>
+ /// <param name="groupId">The group ID.</param>
+ /// <param name="manifestId">The shared manifest to change.</param>
+ /// <param name="model">The details to change.</param>
+ /// <returns>Ok on success.</returns>
+ [HttpPost("{groupId:guid}/manifests/{manifestId:guid}")]
+ [RequireCapability(CapabilityKeys.VaultSharing)]
+ public async Task<IActionResult> UpdateManifest(Guid groupId, Guid manifestId, [FromBody] UpdateSharedManifestRequest model)
+ {
+ await using var context = await dbContextFactory.CreateDbContextAsync();
+ var me = await GetCurrentUserAsync();
+ if (me == null)
+ {
+ return Unauthorized();
+ }
+
+ if (!await GroupHelper.IsSharedGroupAdminAsync(context, groupId, me.Id))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.GROUP_NOT_FOUND, 404));
+ }
+
+ if (!await context.VaultManifests.AnyAsync(m => m.ManifestId == manifestId && m.OwnerGroupId == groupId))
+ {
+ return NotFound(ApiErrorCodeHelper.CreateValidationErrorResponse(ApiErrorCode.SHARED_MANIFEST_NOT_FOUND, 404));
+ }
+
+ // A shared manifest created before the details existed gets its row on the first change.
+ var details = await context.VaultManifestShareDetails.FirstOrDefaultAsync(d => d.ManifestId == manifestId);
+ if (details is null)
+ {
+ details = new VaultManifestShareDetails { ManifestId = manifestId, CreatedAt = timeProvider.UtcNow };
+ context.VaultManifestShareDetails.Add(details);
+ }
+
+ if (model.EncryptedName is not null)
+ {
+ details.EncryptedName = model.EncryptedName;
+ }
+
+ details.UpdatedAt = timeProvider.UtcNow;
+
+ await context.SaveChangesAsync();
+
+ return Ok();
+ }
+
/// <summary>
/// Begin deleting one of the group's shared manifests.
/// </summary>
diff --git a/apps/server/AliasVault.Api/Helpers/VaultStatusHelper.cs b/apps/server/AliasVault.Api/Helpers/VaultStatusHelper.cs
index a9ac6eb8c..675aa8eee 100644
--- a/apps/server/AliasVault.Api/Helpers/VaultStatusHelper.cs
+++ b/apps/server/AliasVault.Api/Helpers/VaultStatusHelper.cs
@@ -26,7 +26,12 @@ public static class VaultStatusHelper
public static async Task<List<ManifestRevision>> GetManifestRevisionsAsync(AliasServerDbContext context, ManifestAccessScope scope)
{
return await ManifestAccessHelper.AccessibleManifests(context, scope)
- .Select(x => new ManifestRevision { ManifestId = x.ManifestId, Revision = x.RevisionNumber })
+ .Select(x => new ManifestRevision
+ {
+ ManifestId = x.ManifestId,
+ Revision = x.RevisionNumber,
+ EncryptedName = context.VaultManifestShareDetails.Where(d => d.ManifestId == x.ManifestId).Select(d => d.EncryptedName).FirstOrDefault(),
+ })
.ToListAsync();
}
}
diff --git a/apps/server/AliasVault.Client/Services/Database/VaultTableReader.cs b/apps/server/AliasVault.Client/Services/Database/VaultTableReader.cs
index 4e4e4babb..8693058f9 100644
--- a/apps/server/AliasVault.Client/Services/Database/VaultTableReader.cs
+++ b/apps/server/AliasVault.Client/Services/Database/VaultTableReader.cs
@@ -111,31 +111,6 @@ public static class VaultTableReader
return ids;
}
- /// <summary>
- /// The display name of every shared manifest rendered as a folder (a folder whose id is the manifest id), keyed by
- /// lowercase manifest id. This is the authority for the name the push writes into a shared manifest.
- /// </summary>
- /// <param name="connection">The open connection.</param>
- /// <returns>Manifest id to name.</returns>
- public static async Task<Dictionary<string, string>> ReadDisplayNamesAsync(SqliteConnection connection)
- {
- var names = new Dictionary<string, string>(StringComparer.Ordinal);
- if (!await HasColumnAsync(connection, "Folders", ManifestIdColumn))
- {
- return names;
- }
-
- await using var command = connection.CreateCommand();
- command.CommandText = "SELECT ManifestId, Name FROM Folders WHERE IsDeleted = 0 AND ManifestId IS NOT NULL AND UPPER(Id) = UPPER(ManifestId)";
- await using var reader = await command.ExecuteReaderAsync();
- while (await reader.ReadAsync())
- {
- names[reader.GetString(0).ToLowerInvariant()] = reader.IsDBNull(1) ? string.Empty : reader.GetString(1);
- }
-
- return names;
- }
-
/// <summary>
/// The public half of a manifest's active email delivery keypair, or null when the manifest holds none.
/// </summary>
diff --git a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs
index af54dd2ce..4b0db7996 100644
--- a/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs
+++ b/apps/server/AliasVault.Client/Services/VaultSync/VaultSyncService.cs
@@ -1384,8 +1384,7 @@ public sealed class VaultSyncService(HttpClient httpClient, AuthService authServ
personalManifestSalt = state.PersonalManifestSalt,
stampedManifestIds = (await VaultTableReader.ManifestIdsInVaultAsync(connection)).ToList(),
openedManifestIds = opened.Select(record => record.ManifestId.ToString()).ToList(),
- heldRecords = state.SharedManifests.Values.Select(record => new { manifestId = record.ManifestId.ToString(), salt = record.Salt, name = record.Name, canAdminister = record.CanAdminister }).ToList(),
- displayNames = await VaultTableReader.ReadDisplayNamesAsync(connection),
+ heldRecords = state.SharedManifests.Values.Select(record => new { manifestId = record.ManifestId.ToString(), salt = record.Salt, canAdminister = record.CanAdminister }).ToList(),
};
var writeSetJson = await rustCoreService.VaultSharingResolveManifestWriteSetAsync(JsonSerializer.Serialize(request));
diff --git a/core/client/src/database/BaseRepository.ts b/core/client/src/database/BaseRepository.ts
index 27eb3b4f7..0414fec2b 100644
--- a/core/client/src/database/BaseRepository.ts
+++ b/core/client/src/database/BaseRepository.ts
@@ -1,10 +1,14 @@
+import { multiManifestRendering } from '../sharing/MultiManifestRendering';
import { DEFAULT_VAULT_MUTATION_SCOPE } from '../sync/VaultMutationScope';
import * as dateFormatter from '../utilities/DateFormatter';
import { runAsync } from './DbOp';
+import { FolderQueries } from './queries/FolderQueries';
import type { DbOp, ManifestScope } from './DbOp';
+import type { Folder } from './repositories/FolderRepository';
import type { ISqliteDatabase } from '../platform/SqliteEngine';
+import type { SharedManifest } from '../sharing/MultiManifestRendering';
import type { VaultMutationScope } from '../sync/VaultMutationScope';
export type SqliteBindValue = string | number | null | Uint8Array;
@@ -112,6 +116,41 @@ export abstract class BaseRepository {
return manifestId;
}
+ /**
+ * The folders as the client presents them (see {@link multiManifestRendering}): the stored rows plus potentially shared manifests
+ * as virtual folders.
+ * @returns The rendered folders (empty array if the vault predates the Folders table or the manifest stamp)
+ */
+ protected *renderedFolders(): DbOp<Folder[]> {
+ try {
+ const stored = yield* this.query<Folder>(FolderQueries.GET_ALL);
+ const personal = yield* this.personalManifestId();
+ const shared = personal ? yield* this.query<SharedManifest>(FolderQueries.GET_SHARED_MANIFESTS, [personal]) : [];
+ return multiManifestRendering.folders(stored, shared);
+ } catch (error) {
+ if (error instanceof Error && (error.message.includes('no such table') || error.message.includes('no such column'))) {
+ return [];
+ }
+ throw error;
+ }
+ }
+
+ /**
+ * Point rows at the folder they are presented in.
+ * @param rows - Rows carrying a stored `FolderId`
+ * @returns The same rows, re-pointed in place
+ */
+ protected *renderFolderIds<T extends { FolderId: string | null; ManifestId: string }>(rows: T[]): DbOp<T[]> {
+ if (rows.length === 0) {
+ return rows;
+ }
+ const personal = yield* this.personalManifestId();
+ for (const row of rows) {
+ row.FolderId = multiManifestRendering.renderedFolderId(row.FolderId, row.ManifestId, personal);
+ }
+ return rows;
+ }
+
/**
* Hard delete manifest-scoped records by a foreign key, within one manifest.
* @param table - The table name
diff --git a/core/client/src/database/__tests__/SharedManifestRendering.test.ts b/core/client/src/database/__tests__/SharedManifestRendering.test.ts
new file mode 100644
index 000000000..2eb049431
--- /dev/null
+++ b/core/client/src/database/__tests__/SharedManifestRendering.test.ts
@@ -0,0 +1,91 @@
+import { ItemTypes } from '@aliasvault/models/vault';
+import { VaultSqlGenerator } from '@aliasvault/vault';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { StorageKeys } from '../../constants/StorageKeys';
+import { getPlatform } from '../../platform/ClientPlatform';
+import { SqliteClient } from '../SqliteClient';
+
+import type { Item } from '@aliasvault/models/vault';
+
+const PERSONAL = '11111111-1111-4111-8111-111111111111';
+const SHARED = '22222222-2222-4222-8222-222222222222';
+const SHARED_ROOT = { Id: SHARED, ManifestId: SHARED };
+
+/**
+ * A client over a vault that holds a shared manifest named "Family", the way a pull leaves it.
+ * @returns The opened client
+ */
+async function openClient(): Promise<SqliteClient> {
+ const db = await getPlatform().sqlite.open();
+ db.exec(new VaultSqlGenerator().getCompleteSchemaSql());
+ db.exec(`INSERT INTO Manifests (Id, Name) VALUES ('${PERSONAL}', NULL), ('${SHARED}', 'Family')`);
+ const bytes = db.export();
+
+ await getPlatform().storage.set(StorageKeys.VAULT_PERSONAL_MANIFEST_ID, PERSONAL);
+ const client = new SqliteClient();
+ await client.initializeFromBytes(bytes);
+ return client;
+}
+
+/**
+ * A minimal item as the form hands it over.
+ * @param name - The item's name
+ * @param manifestId - The manifest it is written into
+ * @param folderId - The folder it is presented in
+ * @returns The draft
+ */
+function draftItem(name: string, manifestId: string, folderId: string | null): Item {
+ return { Name: name, ManifestId: manifestId, FolderId: folderId, ItemType: ItemTypes.Note, Fields: [], CreatedAt: '', UpdatedAt: '' } as unknown as Item;
+}
+
+describe('a shared manifest rendered as a folder', () => {
+ let client: SqliteClient;
+
+ beforeEach(async () => {
+ client = await openClient();
+ });
+
+ it('shows up as a folder although the vault stores none', () => {
+ expect(client.folders.getAll()).toEqual([{ Id: SHARED, Name: 'Family', ParentFolderId: null, Weight: 0, ManifestId: SHARED }]);
+ expect(client.executeQuery('SELECT Id FROM Folders')).toEqual([]);
+ });
+
+ it('stores an item put into it at the top level of the manifest, and presents it inside the folder', async () => {
+ const ref = await client.items.create(draftItem('Netflix', SHARED, SHARED));
+
+ expect(client.executeQuery('SELECT FolderId, ManifestId FROM Items')).toEqual([{ FolderId: null, ManifestId: SHARED }]);
+ expect(client.items.getById(ref)?.FolderId).toBe(SHARED);
+ expect(client.items.getByFolder(SHARED_ROOT).map(item => item.Name)).toEqual(['Netflix']);
+ expect(client.items.getAll()[0].FolderPath).toEqual(['Family']);
+ });
+
+ it('leaves a personal item outside every folder where it is', async () => {
+ const ref = await client.items.create(draftItem('Mine', PERSONAL, null));
+ expect(client.items.getById(ref)?.FolderId).toBeNull();
+ });
+
+ it('stores a folder created inside it at the top level of the manifest', async () => {
+ const id = await client.folders.create('Bills', SHARED_ROOT);
+
+ expect(client.executeQuery('SELECT ParentFolderId, ManifestId FROM Folders')).toEqual([{ ParentFolderId: null, ManifestId: SHARED }]);
+ expect(client.folders.getById({ Id: id, ManifestId: SHARED })?.ParentFolderId).toBe(SHARED);
+ });
+
+ it('refuses to rename the folder, the shared vault is renamed from the sharing settings', async () => {
+ await expect(client.folders.update(SHARED_ROOT, 'Household')).rejects.toThrow();
+ expect(client.executeQuery('SELECT Name FROM Manifests WHERE Id = ?', [SHARED])).toEqual([{ Name: 'Family' }]);
+ });
+
+ it('keeps the items of a deleted top-level folder inside the manifest', async () => {
+ const folderId = await client.folders.create('Bills', SHARED_ROOT);
+ await client.items.create(draftItem('Power', SHARED, folderId));
+ await client.folders.delete({ Id: folderId, ManifestId: SHARED });
+
+ expect(client.executeQuery('SELECT FolderId, ManifestId FROM Items')).toEqual([{ FolderId: null, ManifestId: SHARED }]);
+ });
+
+ it('refuses to delete the folder', async () => {
+ await expect(client.folders.delete(SHARED_ROOT)).rejects.toThrow();
+ });
+});
diff --git a/core/client/src/database/queries/FolderQueries.ts b/core/client/src/database/queries/FolderQueries.ts
index ed21e16fe..19766fd07 100644
--- a/core/client/src/database/queries/FolderQueries.ts
+++ b/core/client/src/database/queries/FolderQueries.ts
@@ -58,13 +58,11 @@ export class FolderQueries {
WHERE Id = ? AND ManifestId = ?`;
/**
- * Clear folder reference from items (set to NULL). The manifest bound to the SET is the one an item
- * outside every folder joins; the one in the WHERE is the folder's own.
+ * Clear folder reference from items (set to NULL).
*/
public static readonly CLEAR_ITEMS_FOLDER = `
UPDATE Items
SET FolderId = NULL,
- ManifestId = ?,
UpdatedAt = ?
WHERE FolderId = ? AND ManifestId = ?`;
@@ -103,4 +101,14 @@ export class FolderQueries {
SET ParentFolderId = ?,
UpdatedAt = ?
WHERE ParentFolderId = ? AND ManifestId = ?`;
+
+ /**
+ * The shared manifests this vault holds, with their names. This is locally created bookkeeping and is not synced to the server.
+ * Params: the personal manifest id.
+ */
+ public static readonly GET_SHARED_MANIFESTS = `
+ SELECT Id AS ManifestId, Name
+ FROM Manifests
+ WHERE Id <> ? COLLATE NOCASE
+ ORDER BY Name`;
}
diff --git a/core/client/src/database/queries/ItemQueries.ts b/core/client/src/database/queries/ItemQueries.ts
index ffa0371b5..51f5b2dcb 100644
--- a/core/client/src/database/queries/ItemQueries.ts
+++ b/core/client/src/database/queries/ItemQueries.ts
@@ -49,6 +49,14 @@ export class ItemQueries {
WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL AND i.FolderId = ? AND i.ManifestId = ?
ORDER BY i.CreatedAt DESC`;
+ /**
+ * Get the active items a manifest stores outside every folder.
+ */
+ public static readonly GET_AT_MANIFEST_TOP_LEVEL = `
+ ${ItemQueries.BASE_SELECT}
+ WHERE i.IsDeleted = 0 AND i.DeletedAt IS NULL AND i.ArchivedAt IS NULL AND i.FolderId IS NULL AND i.ManifestId = ?
+ ORDER BY i.CreatedAt DESC`;
+
/**
* Get every active item that the folder counts need.
*/
diff --git a/core/client/src/database/repositories/FolderRepository.ts b/core/client/src/database/repositories/FolderRepository.ts
index 61b67111c..4bc61dc1b 100644
--- a/core/client/src/database/repositories/FolderRepository.ts
+++ b/core/client/src/database/repositories/FolderRepository.ts
@@ -47,7 +47,8 @@ export class FolderRepository extends BaseRepository {
}
const manifestId = parent?.ManifestId ?? await this.run(this.writeManifestId());
- await this.run(this.execute(FolderQueries.INSERT, [folderId, name, parent?.Id ?? null, manifestId, currentDateTime, currentDateTime]));
+ const parentId = parent ? multiManifestRendering.storedFolderId(parent.Id, parent.ManifestId) : null;
+ await this.run(this.execute(FolderQueries.INSERT, [folderId, name, parentId, manifestId, currentDateTime, currentDateTime]));
return folderId;
});
@@ -63,16 +64,13 @@ export class FolderRepository extends BaseRepository {
throw new Error(`FolderRepository: folder ${ref.Id} does not exist in manifest ${ref.ManifestId}; refusing the write.`);
}
}
+
+ /**
+ * Get all folders as the client presents them.
+ * @returns The rendered folders
+ */
public *getAll(): DbOp<Folder[]> {
- try {
- return yield* this.query<Folder>(FolderQueries.GET_ALL);
- } catch (error) {
- // Table may not exist in older vault versions - return empty array
- if (error instanceof Error && error.message.includes('no such table')) {
- return [];
- }
- throw error;
- }
+ return yield* this.renderedFolders();
}
/**
@@ -81,8 +79,8 @@ export class FolderRepository extends BaseRepository {
* @returns Folder object or null if not found
*/
public *getById(ref: FolderRef): DbOp<Omit<Folder, 'Weight'> | null> {
- const results = yield* this.query<Omit<Folder, 'Weight'>>(FolderQueries.GET_BY_ID, [ref.Id, ref.ManifestId]);
- return results.length > 0 ? results[0] : null;
+ const folders = yield* this.renderedFolders();
+ return folders.find(folder => folder.Id.toLowerCase() === ref.Id.toLowerCase() && folder.ManifestId.toLowerCase() === ref.ManifestId.toLowerCase()) ?? null;
}
/**
@@ -92,6 +90,7 @@ export class FolderRepository extends BaseRepository {
* @returns The number of rows updated
*/
public async update(ref: FolderRef, name: string): Promise<number> {
+ await this.assertNotVirtual(ref);
return this.withTransaction(() => this.run(this.execute(FolderQueries.UPDATE_NAME, [name, this.now(), ref.Id, ref.ManifestId])));
}
@@ -126,7 +125,7 @@ export class FolderRepository extends BaseRepository {
* @returns The number of rows updated
*/
public async delete(ref: FolderRef): Promise<number> {
- await this.assertDeletable(ref);
+ await this.assertNotVirtual(ref);
return this.withTransaction(() => this.run(this.deleteKeepingContents(ref)));
}
@@ -140,16 +139,15 @@ export class FolderRepository extends BaseRepository {
// Get the parent folder of the folder being deleted
const folder = yield* this.getById(ref);
- const targetParentId = folder?.ParentFolderId || null;
- const manifestId = yield* this.writeManifestId();
+ const targetParentId = multiManifestRendering.storedFolderId(folder?.ParentFolderId, ref.ManifestId);
// Move only items in this folder to the parent folder (or root if no parent)
if (targetParentId) {
// Has parent: move items to the parent folder, which a folder tree keeps in the same manifest
yield* this.execute(FolderQueries.MOVE_ITEMS_TO_FOLDER, [targetParentId, currentDateTime, ref.Id, ref.ManifestId]);
} else {
- // No parent: move items to root (NULL); out of every folder means into the default manifest.
- yield* this.execute(FolderQueries.CLEAR_ITEMS_FOLDER, [manifestId, currentDateTime, ref.Id, ref.ManifestId]);
+ // No parent: move items to the top level (NULL) of the manifest the folder lives in.
+ yield* this.execute(FolderQueries.CLEAR_ITEMS_FOLDER, [currentDateTime, ref.Id, ref.ManifestId]);
}
// Move direct child folders to the parent of the deleted folder
@@ -168,7 +166,7 @@ export class FolderRepository extends BaseRepository {
* @returns The number of items trashed
*/
public async deleteWithContents(ref: FolderRef): Promise<number> {
- await this.assertDeletable(ref);
+ await this.assertNotVirtual(ref);
return this.withTransaction(() => this.run(this.deleteFolderTree(ref)));
}
@@ -197,12 +195,12 @@ export class FolderRepository extends BaseRepository {
}
/**
- * Refuse to delete a folder that a shared manifest is rendered as (see {@link multiManifestRendering}).
- * @param ref - The folder about to be deleted
+ * Refuse to change or delete a virtual folder (see {@link multiManifestRendering}): the vault stores no row for
+ * one, setting are managed elsewhere (e.g. shared manifest settings).
+ * @param ref - The folder about to be changed
*/
- private async assertDeletable(ref: FolderRef): Promise<void> {
- const folder = await this.run(this.getById(ref));
- if (folder && multiManifestRendering.isManifestRoot(folder)) {
+ private async assertNotVirtual(ref: FolderRef): Promise<void> {
+ if (multiManifestRendering.isVirtualFolder(ref)) {
throw new Error(await getPlatform().translate(TranslatableMessage.SharedFolderDeleteRefused));
}
}
diff --git a/core/client/src/database/repositories/ItemRepository.ts b/core/client/src/database/repositories/ItemRepository.ts
index e0936c14c..d0b1c3bc4 100644
--- a/core/client/src/database/repositories/ItemRepository.ts
+++ b/core/client/src/database/repositories/ItemRepository.ts
@@ -2,6 +2,7 @@ import { FieldKey, LogoKinds, MAX_FIELD_HISTORY_RECORDS, getSystemField, normali
import { getFolderPath } from '../../items/FolderUtils';
import { selectFaviconTarget, toUrlList } from '../../rust/RustCore';
+import { multiManifestRendering } from '../../sharing/MultiManifestRendering';
import { BaseRepository, type IDatabaseClient, type SqliteBindValue } from '../BaseRepository';
import { itemKeyBindings, scopedKey, type ItemRef } from '../ItemRef';
import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';
@@ -62,23 +63,16 @@ export class ItemRepository extends BaseRepository {
private *buildFolderPaths(): DbOp<Map<string, string[]>> {
const folderPathMap = new Map<string, string[]>();
- let folders: (Folder & { ManifestId: string })[];
- try {
- folders = yield* this.query<Folder & { ManifestId: string }>('SELECT Id, ManifestId, Name, ParentFolderId, Weight FROM Folders WHERE IsDeleted = 0');
- } catch (error) {
- // Folders table may not exist in older vault versions
- if (error instanceof Error && error.message.includes('no such table')) {
- return folderPathMap;
- }
- throw error;
- }
+ // The rendered folders, so a path starts at whatever a shared manifest is presented as.
+ const folders = yield* this.renderedFolders();
// Use shared utility to build paths, one manifest's tree at a time
- const foldersByManifest = new Map<string, (Folder & { ManifestId: string })[]>();
+ const foldersByManifest = new Map<string, Folder[]>();
for (const folder of folders) {
- const siblings = foldersByManifest.get(folder.ManifestId) ?? [];
+ const key = folder.ManifestId.toLowerCase();
+ const siblings = foldersByManifest.get(key) ?? [];
siblings.push(folder);
- foldersByManifest.set(folder.ManifestId, siblings);
+ foldersByManifest.set(key, siblings);
}
for (const [manifestId, manifestFolders] of foldersByManifest) {
@@ -109,7 +103,10 @@ export class ItemRepository extends BaseRepository {
* @returns Array of Item objects (empty array if the folder does not exist)
*/
public *getByFolder(folder: FolderRef): DbOp<Item[]> {
- const itemRows = yield* this.selectItemRows(ItemQueries.GET_BY_FOLDER, [folder.Id, folder.ManifestId]);
+ const storedFolderId = multiManifestRendering.storedFolderId(folder.Id, folder.ManifestId);
+ const itemRows = storedFolderId
+ ? yield* this.selectItemRows(ItemQueries.GET_BY_FOLDER, [storedFolderId, folder.ManifestId])
+ : yield* this.selectItemRows(ItemQueries.GET_AT_MANIFEST_TOP_LEVEL, [folder.ManifestId]);
return yield* this.hydrateItems(itemRows);
}
@@ -120,7 +117,7 @@ export class ItemRepository extends BaseRepository {
public *getAllSummaries(): DbOp<ItemSummary[]> {
try {
const rows = yield* this.query<ItemSummaryRow>(ItemQueries.GET_ALL_SUMMARIES);
- return ItemMapper.mapSummaryRows(rows);
+ return ItemMapper.mapSummaryRows(yield* this.renderFolderIds(rows));
} catch (error) {
// Items table may not exist in older vault versions - return empty array
if (error instanceof Error && error.message.includes('no such table')) {
@@ -164,7 +161,7 @@ export class ItemRepository extends BaseRepository {
*/
private *selectItemRows(query: string, params: SqliteBindValue[] = []): DbOp<ItemRow[]> {
try {
- return yield* this.query<ItemRow>(query, params);
+ return yield* this.renderFolderIds(yield* this.query<ItemRow>(query, params));
} catch (error) {
// Items table may not exist in older vault versions - return empty array
if (error instanceof Error && error.message.includes('no such table')) {
@@ -211,7 +208,7 @@ export class ItemRepository extends BaseRepository {
*/
public *getById(ref: ItemRef): DbOp<Item | null> {
- const results = yield* this.query<ItemRow>(ItemQueries.GET_BY_ID, [ref.Id, ref.ManifestId]);
+ const results = yield* this.renderFolderIds(yield* this.query<ItemRow>(ItemQueries.GET_BY_ID, [ref.Id, ref.ManifestId]));
if (results.length === 0) {
return null;
}
@@ -286,13 +283,14 @@ export class ItemRepository extends BaseRepository {
// 1. The item names its manifest; a folder it points at has to live in that same manifest.
const manifestId = item.ManifestId;
- await this.run(this.assertFolderInManifest(item));
+ const folderId = multiManifestRendering.storedFolderId(item.FolderId, manifestId);
+ await this.run(this.assertFolderInManifest(folderId, manifestId));
// 2. Handle the logo
const logoId = await this.resolveLogoId(item, manifestId, currentDateTime, null, logoSelection);
// 3. Insert Item
- await this.run(this.execute(ItemQueries.INSERT_ITEM, [itemId, item.Name ?? null, item.ItemType, logoId, item.FolderId ?? null, manifestId, currentDateTime, currentDateTime, 0]));
+ await this.run(this.execute(ItemQueries.INSERT_ITEM, [itemId, item.Name ?? null, item.ItemType, logoId, folderId, manifestId, currentDateTime, currentDateTime, 0]));
/*
* 4-6. Insert the child rows into the manifest the item was just written into.
@@ -473,17 +471,18 @@ export class ItemRepository extends BaseRepository {
// 2. The manifest the item ends up in, then the logo inside it.
const manifestId = item.ManifestId;
- await this.run(this.assertFolderInManifest(item));
+ const folderId = multiManifestRendering.storedFolderId(item.FolderId, manifestId);
+ await this.run(this.assertFolderInManifest(folderId, manifestId));
const logoId = await this.resolveLogoId(item, manifestId, currentDateTime, existing.LogoId, logoSelection, ref.ManifestId);
const nameChanged = (item.Name ?? null) !== existing.Name;
const itemTypeChanged = String(item.ItemType) !== String(existing.ItemType);
- const folderChanged = (item.FolderId ?? null) !== existing.FolderId || manifestId !== ref.ManifestId;
+ const folderChanged = folderId !== existing.FolderId || manifestId !== ref.ManifestId;
const logoIdChanged = logoId !== existing.LogoId;
if (nameChanged || itemTypeChanged || folderChanged || logoIdChanged) {
// A move across manifests re-stamps the item; the schema trigger takes its child rows along.
- await this.run(this.execute(ItemQueries.UPDATE_ITEM_WITH_LOGO, [item.Name ?? null, item.ItemType, item.FolderId ?? null, manifestId, logoId, currentDateTime, ref.Id, ref.ManifestId]));
+ await this.run(this.execute(ItemQueries.UPDATE_ITEM_WITH_LOGO, [item.Name ?? null, item.ItemType, folderId, manifestId, logoId, currentDateTime, ref.Id, ref.ManifestId]));
}
// 3. Track history for fields that have EnableHistory=true before updating
@@ -596,7 +595,7 @@ export class ItemRepository extends BaseRepository {
WHERE i.IsDeleted = 0 AND i.DeletedAt IS NOT NULL
ORDER BY i.DeletedAt DESC`;
- itemRows = yield* this.query<ItemRow & { DeletedAt: string }>(query);
+ itemRows = yield* this.renderFolderIds(yield* this.query<ItemRow & { DeletedAt: string }>(query));
} catch (error) {
if (error instanceof Error && error.message.includes('no such table')) {
return [];
@@ -699,17 +698,18 @@ export class ItemRepository extends BaseRepository {
/**
* Refuse a folder that is not in the item's manifest. A folder id can exist in several manifests, so the item's
- * own `ManifestId` is what determines explicitly which folder is targeted.
- * @param item The item being created or updated
+ * own manifest is what determines explicitly which folder is targeted.
+ * @param folderId The folder the item is stored in, null for the top level of its manifest
+ * @param manifestId The manifest the item is written into
*/
- private *assertFolderInManifest(item: Item): DbOp<void> {
- if (!item.FolderId) {
+ private *assertFolderInManifest(folderId: string | null, manifestId: string): DbOp<void> {
+ if (!folderId) {
return;
}
- const rows = yield* this.query<{ Found: number }>(FolderQueries.EXISTS, [item.FolderId, item.ManifestId]);
+ const rows = yield* this.query<{ Found: number }>(FolderQueries.EXISTS, [folderId, manifestId]);
if (rows.length === 0) {
- throw new Error(`ItemRepository: folder ${item.FolderId} does not exist in manifest ${item.ManifestId}; refusing the write.`);
+ throw new Error(`ItemRepository: folder ${folderId} does not exist in manifest ${manifestId}; refusing the write.`);
}
}
diff --git a/core/client/src/platform/TranslatableMessage.ts b/core/client/src/platform/TranslatableMessage.ts
index bc28c9584..2c1991280 100644
--- a/core/client/src/platform/TranslatableMessage.ts
+++ b/core/client/src/platform/TranslatableMessage.ts
@@ -4,13 +4,10 @@
* TODO: refactor this to use centralized translation system instead (on to-do list) once that is implemented.
*/
export enum TranslatableMessage {
- /** Display name for a shared vault whose name is not known locally. */
- UnnamedSharedVault = 'unnamed-shared-vault',
-
/** The local vault is newer than what this client understands; the app must be updated. */
ClientOutdated = 'client-outdated',
- /** A shared vault's anchor folder cannot be deleted from the folder list. */
+ /** The folder a shared vault is shown as cannot be deleted from the folder list. */
SharedFolderDeleteRefused = 'shared-folder-delete-refused',
/** The vault still has to walk the sqlite-blob upgrade chain before the manifest migration can run. */
diff --git a/core/client/src/sharing/MultiManifestRendering.ts b/core/client/src/sharing/MultiManifestRendering.ts
index db72da7f8..e92278c2b 100644
--- a/core/client/src/sharing/MultiManifestRendering.ts
+++ b/core/client/src/sharing/MultiManifestRendering.ts
@@ -6,14 +6,25 @@ import type { SqliteClient } from '../database/SqliteClient';
* holds the personal manifest plus every shared manifest this account holds a key for. How the different
* manifests are presented to the user is purely a client-side choice. Currently two modes are in scope:
* - `subfolder`: every shared manifest shows up as a top-level folder in the one vault view, so items from all
- * manifests are browsed, searched and moved together. This is the mode that is built.
+ * manifests are browsed, searched and moved together.
* - `switcher`: the UI scopes itself to one manifest at a time and the user switches vaults, so a shared manifest
* never appears in the personal folder tree. TODO: add this mode (not offered to users (yet)).
*/
export type MultiManifestRenderingMode = 'subfolder' | 'switcher';
/**
- * The presentation policy for a multi-manifest vault, as one swappable unit.
+ * A shared manifest this vault holds, with its name. The server keeps the name encrypted with the manifest's own
+ * key; every sync fetches it into the local `Manifests` table, which is read-only to the client.
+ */
+export type SharedManifest = {
+ ManifestId: string;
+ Name: string | null;
+};
+
+/**
+ * The presentation policy for a multi-manifest vault, as one swappable unit. The repositories pass every folder and
+ * every item folder reference through it, in both directions, so the rest of the client only ever sees the rendered
+ * shape and the vault only ever holds the stored one.
*/
export type MultiManifestRenderer = {
/**
@@ -22,49 +33,121 @@ export type MultiManifestRenderer = {
readonly mode: MultiManifestRenderingMode;
/**
- * Whether a folder is one that a shared manifest is rendered as, and so is not the user's to delete or rehome.
+ * Whether a folder is virtual: drawn by this client rather than stored in the vault, and so not the user's to
+ * rename, move or delete. In `subfolder` mode the folder a shared manifest is rendered as is the virtual one.
* @param folder - The folder to classify
*/
- isManifestRoot(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean;
+ isVirtualFolder(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean;
/**
- * 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.
+ * The folders as this mode presents them.
+ * @param stored - The folder rows of the vault
+ * @param sharedManifests - The shared manifests the vault holds
+ */
+ folders(stored: Folder[], sharedManifests: SharedManifest[]): Folder[];
+
+ /**
+ * The folder a row is presented in, given the folder the vault stores for it.
+ * @param storedFolderId - The stored `FolderId` or `ParentFolderId`
+ * @param manifestId - The manifest the row lives in
+ * @param personalManifestId - The personal manifest
+ */
+ renderedFolderId(storedFolderId: string | null, manifestId: string, personalManifestId: string | null): string | null;
+
+ /**
+ * The folder the vault stores for a row, given the folder it is presented in.
+ * @param renderedFolderId - The presented `FolderId` or `ParentFolderId`
+ * @param manifestId - The manifest the row lives in
+ */
+ storedFolderId(renderedFolderId: string | null | undefined, manifestId: string): string | null;
+
+ /**
+ * What each shared manifest is called, keyed by lower-cased manifest id.
* @param sqliteClient - The open local vault
*/
displayNames(sqliteClient: SqliteClient): Record<string, string>;
};
/**
- * 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.
+ * Whether two ids name the same thing.
+ * @param a - One id
+ * @param b - The other id
+ */
+function sameId(a: string | null | undefined, b: string | null | undefined): boolean {
+ return Boolean(a) && Boolean(b) && String(a).toLowerCase() === String(b).toLowerCase();
+}
+
+/**
+ * Renders every shared manifest as a top-level folder that exists only in this client: its id is the manifest id,
+ * its name is the manifest's name, and everything the manifest stores at its top level is presented inside it.
*/
const subfolderRendering: MultiManifestRenderer = {
mode: 'subfolder',
/**
- * A folder carrying its own manifest's id is the one that manifest is rendered as.
+ * A folder carrying its own manifest's id is the one that manifest is rendered as, which this mode never stores.
* @param folder - The folder to classify
*/
- isManifestRoot(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean {
- return Boolean(folder.ManifestId) && folder.Id.toLowerCase() === String(folder.ManifestId).toLowerCase();
+ isVirtualFolder(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean {
+ return sameId(folder.Id, folder.ManifestId);
+ },
+
+ /**
+ * One folder per shared manifest, with the manifest's top-level folders moved inside it.
+ * @param stored - The folder rows of the vault
+ * @param sharedManifests - The shared manifests the vault holds
+ */
+ folders(stored: Folder[], sharedManifests: SharedManifest[]): Folder[] {
+ const shared = new Set(sharedManifests.map(manifest => manifest.ManifestId.toLowerCase()));
+
+ // A vault written by an earlier build can still store the folder; it then stands in for the rendered one.
+ const storedRoots = new Set(stored.filter(folder => subfolderRendering.isVirtualFolder(folder)).map(folder => folder.ManifestId.toLowerCase()));
+
+ const roots = sharedManifests
+ .filter(manifest => !storedRoots.has(manifest.ManifestId.toLowerCase()))
+ .map(manifest => ({ Id: manifest.ManifestId.toLowerCase(), Name: manifest.Name ?? '', ParentFolderId: null, Weight: 0, ManifestId: manifest.ManifestId }));
+
+ const nested = stored.map(folder => (folder.ParentFolderId === null && shared.has(String(folder.ManifestId).toLowerCase()) && !subfolderRendering.isVirtualFolder(folder)
+ ? { ...folder, ParentFolderId: String(folder.ManifestId).toLowerCase() }
+ : folder));
+
+ return [...roots, ...nested];
+ },
+
+ /**
+ * A shared manifest's top level is presented as the inside of its folder.
+ * @param storedFolderId - The stored `FolderId` or `ParentFolderId`
+ * @param manifestId - The manifest the row lives in
+ * @param personalManifestId - The personal manifest
+ */
+ renderedFolderId(storedFolderId: string | null, manifestId: string, personalManifestId: string | null): string | null {
+ if (storedFolderId || !manifestId || !personalManifestId || sameId(manifestId, personalManifestId)) {
+ return storedFolderId;
+ }
+ return manifestId.toLowerCase();
+ },
+
+ /**
+ * The folder a shared manifest is rendered as is not stored, so a row inside it is stored at the top level.
+ * @param renderedFolderId - The presented `FolderId` or `ParentFolderId`
+ * @param manifestId - The manifest the row lives in
+ */
+ storedFolderId(renderedFolderId: string | null | undefined, manifestId: string): string | null {
+ return !renderedFolderId || sameId(renderedFolderId, manifestId) ? null : renderedFolderId;
},
/**
- * The name of a shared manifest is the name of the folder it is rendered as.
+ * The name of a manifest as the last sync fetched it.
* @param sqliteClient - The open local vault
*/
displayNames(sqliteClient: SqliteClient): Record<string, string> {
- /*
- * A vault whose schema predates the manifest stamp holds nothing but the personal manifest, so it names none.
- * This runs while migrating such a vault onto the current schema, where the column is not there yet.
- */
- if (!sqliteClient.hasColumn('Folders', 'ManifestId')) {
+ // A vault whose schema predates the table holds nothing but the personal manifest, so it names none.
+ if (!sqliteClient.hasColumn('Manifests', 'Name')) {
return {};
}
- const roots = sqliteClient.executeQuery<{ ManifestId: string; Name: string }>('SELECT ManifestId, Name FROM Folders WHERE IsDeleted = 0 AND ManifestId IS NOT NULL AND UPPER(Id) = UPPER(ManifestId)');
- return Object.fromEntries(roots.map(root => [root.ManifestId.toLowerCase(), root.Name]));
+ const rows = sqliteClient.executeQuery<{ Id: string; Name: string }>('SELECT Id, Name FROM Manifests WHERE Name IS NOT NULL');
+ return Object.fromEntries(rows.map(row => [row.Id.toLowerCase(), row.Name]));
},
};
diff --git a/core/client/src/sharing/SharingService.ts b/core/client/src/sharing/SharingService.ts
index d797b7415..5e7ebb173 100644
--- a/core/client/src/sharing/SharingService.ts
+++ b/core/client/src/sharing/SharingService.ts
@@ -45,7 +45,7 @@ export type ManifestVekGrant = {
export type SharedManifestRecord = ManifestVekGrant & {
manifestId: string;
salt: string;
- name?: string | null;
+ encryptedName?: string | null;
canAdminister?: boolean;
};
diff --git a/core/client/src/sync/VaultSync.ts b/core/client/src/sync/VaultSync.ts
index 853e19213..adb55c0f1 100644
--- a/core/client/src/sync/VaultSync.ts
+++ b/core/client/src/sync/VaultSync.ts
@@ -53,6 +53,14 @@ export type VaultManifestMigrationResult = SyncErrorDetail & {
pushed: boolean;
};
+/**
+ * The details of a shared manifest an administrator of its group can change. One that is left out stays as it is.
+ */
+export type SharedManifestDetails = {
+ /** What to call the shared manifest. */
+ name?: string;
+};
+
/**
* Result of a sharing operation as the UI reads it.
*/
@@ -166,7 +174,7 @@ export class VaultSync {
* 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
+ * @param name - name of the shared manifest / shared vault
*/
public async createSharedManifest(groupId: string, name: string): Promise<SharingOperationResult> {
return this.runSharingOperation('createSharedManifest', { groupId, name });
@@ -183,6 +191,16 @@ export class VaultSync {
return this.runSharingOperation('inviteToSharedManifest', { groupId, manifestId, userId });
}
+ /**
+ * Change the details of a shared manifest (only allowed for administrators of the group).
+ * @param groupId - the group the shared manifest belongs to
+ * @param manifestId - the shared manifest to change
+ * @param details - the details to change; null values are ignored during update
+ */
+ public async updateSharedManifest(groupId: string, manifestId: string, details: SharedManifestDetails): Promise<SharingOperationResult> {
+ return this.runSharingOperation('updateSharedManifest', { groupId, manifestId, ...details });
+ }
+
/**
* Run one sharing operation.
* @param operation - the operation
diff --git a/core/client/src/sync/VaultSyncEngine.ts b/core/client/src/sync/VaultSyncEngine.ts
index ce3668e9c..816983a87 100644
--- a/core/client/src/sync/VaultSyncEngine.ts
+++ b/core/client/src/sync/VaultSyncEngine.ts
@@ -13,7 +13,6 @@ import { StorageKeys } from '../constants/StorageKeys';
import { AppInfo } from '../platform/AppInfo';
import { getPlatform } from '../platform/ClientPlatform';
import { devLog, devWarn } from '../platform/Logger';
-import { TranslatableMessage } from '../platform/TranslatableMessage';
import { rustCore } from '../rust/RustCore';
import { base64ToBytes, bytesToBase64 } from '../utilities/Base64';
@@ -23,7 +22,7 @@ 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' | 'createSharedManifest' | 'inviteToSharedManifest';
+export type VaultSyncOperation = 'fullSync' | 'migrationStatus' | 'migrateManifest' | 'statusCheck' | 'resolveVaultKey' | 'createSharedManifest' | 'inviteToSharedManifest' | 'updateSharedManifest';
/** What a sharing operation acts on (the Rust `SharingParams`). */
export type VaultSyncSharingParams = {
@@ -47,7 +46,6 @@ export type VaultSyncEngineRequest = {
forcePull: boolean;
minServerVersion: string;
isOfflineMode: boolean;
- unnamedSharedVaultName: string;
sharing?: VaultSyncSharingParams;
};
@@ -573,6 +571,5 @@ export async function buildVaultSyncRequest(operation: VaultSyncOperation, optio
forcePull: options.forcePull === true,
minServerVersion: AppInfo.MIN_SERVER_VERSION,
isOfflineMode: isOfflineMode ?? false,
- unnamedSharedVaultName: await getPlatform().translate(TranslatableMessage.UnnamedSharedVault),
};
}
diff --git a/core/models/src/webapi/Groups.ts b/core/models/src/webapi/Groups.ts
index 7c43e4123..e4d805fba 100644
--- a/core/models/src/webapi/Groups.ts
+++ b/core/models/src/webapi/Groups.ts
@@ -78,6 +78,16 @@ export type CreateSharedManifestRequest = {
selfEncryptedVek: string;
selfPublicKey: string;
algorithm: VaultKeyAlgorithmValue;
+ /** The name of the manifest, encrypted with the manifest's own key (base64). */
+ encryptedName?: string | null;
+}
+
+/**
+ * Change the details of one of a group's shared manifests (POST /v2/Groups/{groupId}/manifests/{manifestId}).
+ */
+export type UpdateSharedManifestRequest = {
+ /** The new name of the manifest, encrypted with the manifest's own key (base64). */
+ encryptedName?: string | null;
}
/**
diff --git a/core/models/src/webapi/StatusResponseV2.ts b/core/models/src/webapi/StatusResponseV2.ts
index 729d0000b..f0d867730 100644
--- a/core/models/src/webapi/StatusResponseV2.ts
+++ b/core/models/src/webapi/StatusResponseV2.ts
@@ -4,6 +4,8 @@
export type ManifestRevision = {
manifestId: string;
revision: number;
+ /** The name of a shared manifest, encrypted with the manifest's own key (base64). */
+ encryptedName?: string | null;
}
/**
diff --git a/core/rust/src/vault_sharing/mod.rs b/core/rust/src/vault_sharing/mod.rs
index a83df51a8..d8ee5dcf7 100644
--- a/core/rust/src/vault_sharing/mod.rs
+++ b/core/rust/src/vault_sharing/mod.rs
@@ -4,8 +4,6 @@ pub mod types;
#[cfg(test)]
mod tests;
-use std::collections::HashMap;
-
pub use types::{
ManifestAccessPartition, ManifestAccessRequest, ManifestWriteRecord, ManifestWriteSet,
ManifestWriteSetRequest, SharedManifestRecord, SkippedManifest, WriteSkipReason,
@@ -24,7 +22,6 @@ pub fn resolve_manifest_write_set(request: ManifestWriteSetRequest) -> ManifestW
manifest_id: request.personal_manifest_id,
is_personal: true,
salt: request.personal_manifest_salt,
- name: None,
can_administer: false,
}];
let mut skipped = Vec::new();
@@ -46,8 +43,6 @@ pub fn resolve_manifest_write_set(request: ManifestWriteSetRequest) -> ManifestW
manifest_id: record.manifest_id.clone(),
is_personal: false,
salt: record.salt.clone(),
- // Re-read on every push, so the name inside the manifest follows a rename.
- name: resolve_name(&request.display_names, &record.manifest_id, record.name.as_deref()),
can_administer: record.can_administer,
});
}
@@ -75,13 +70,3 @@ pub fn partition_manifest_access(request: ManifestAccessRequest) -> ManifestAcce
ManifestAccessPartition { unwritable, lost }
}
-/// The name to write into a manifest: the rendered one, else the stored one, else none.
-fn resolve_name(display_names: &HashMap<String, String>, manifest_id: &str, record_name: Option<&str>) -> Option<String> {
- let wanted = id_key(manifest_id);
- display_names
- .iter()
- .find(|(key, _)| id_key(key) == wanted)
- .map(|(_, name)| name.clone())
- .or_else(|| record_name.map(|name| name.to_string()))
- .filter(|name| !name.is_empty())
-}
diff --git a/core/rust/src/vault_sharing/tests.rs b/core/rust/src/vault_sharing/tests.rs
index 2e710f356..97f20d6c0 100644
--- a/core/rust/src/vault_sharing/tests.rs
+++ b/core/rust/src/vault_sharing/tests.rs
@@ -1,15 +1,13 @@
//! Tests for the sharing policy.
-use std::collections::HashMap;
use super::*;
/// A held key record for a manifest.
-fn record(manifest_id: &str, name: Option<&str>) -> SharedManifestRecord {
+fn record(manifest_id: &str) -> SharedManifestRecord {
SharedManifestRecord {
manifest_id: manifest_id.to_string(),
salt: "salt-1".to_string(),
- name: name.map(|n| n.to_string()),
can_administer: true,
}
}
@@ -22,7 +20,6 @@ fn write_set_request(stamped: &[&str], opened: &[&str], held: Vec<SharedManifest
stamped_manifest_ids: stamped.iter().map(|id| id.to_string()).collect(),
opened_manifest_ids: opened.iter().map(|id| id.to_string()).collect(),
held_records: held,
- display_names: HashMap::new(),
}
}
@@ -32,27 +29,25 @@ fn write_set_request(stamped: &[&str], opened: &[&str], held: Vec<SharedManifest
#[test]
fn the_write_set_leads_with_the_personal_manifest() {
- let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1"], &["MAN-1"], vec![record("MAN-1", Some("Family"))]));
+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1"], &["MAN-1"], vec![record("MAN-1")]));
assert_eq!(set.records.len(), 2);
assert!(set.records[0].is_personal);
assert_eq!(set.records[0].manifest_id, "PERSONAL");
assert_eq!(set.records[0].salt, "personal-salt");
- // A personal manifest is never named and is not administered through a group.
- assert_eq!(set.records[0].name, None);
+ // A personal manifest is not administered through a group.
assert!(!set.records[0].can_administer);
assert!(!set.records[1].is_personal);
assert_eq!(set.records[1].manifest_id, "MAN-1");
assert_eq!(set.records[1].salt, "salt-1");
- assert_eq!(set.records[1].name.as_deref(), Some("Family"));
assert!(set.records[1].can_administer);
assert!(set.skipped.is_empty());
}
#[test]
fn a_manifest_with_no_local_rows_is_left_alone_rather_than_emptied() {
- let set = resolve_manifest_write_set(write_set_request(&["PERSONAL"], &["MAN-1"], vec![record("MAN-1", None)]));
+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL"], &["MAN-1"], vec![record("MAN-1")]));
assert_eq!(set.records.len(), 1);
assert_eq!(set.skipped.len(), 1);
@@ -62,7 +57,7 @@ fn a_manifest_with_no_local_rows_is_left_alone_rather_than_emptied() {
#[test]
fn a_manifest_whose_key_did_not_open_is_not_written() {
- let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1"], &[], vec![record("MAN-1", None)]));
+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1"], &[], vec![record("MAN-1")]));
assert_eq!(set.records.len(), 1);
assert_eq!(set.skipped[0].reason, WriteSkipReason::KeyDidNotOpen);
@@ -70,7 +65,7 @@ fn a_manifest_whose_key_did_not_open_is_not_written() {
#[test]
fn the_write_set_matches_ids_regardless_of_casing() {
- let set = resolve_manifest_write_set(write_set_request(&["man-1"], &["MAN-1"], vec![record("Man-1", None)]));
+ let set = resolve_manifest_write_set(write_set_request(&["man-1"], &["MAN-1"], vec![record("Man-1")]));
assert_eq!(set.records.len(), 2);
// The record's own spelling comes back, since that is what addresses the write.
@@ -78,28 +73,9 @@ fn the_write_set_matches_ids_regardless_of_casing() {
assert!(set.skipped.is_empty());
}
-#[test]
-fn the_rendered_name_overrides_the_stored_one_on_every_push() {
- let mut request = write_set_request(&["PERSONAL", "MAN-1"], &["MAN-1"], vec![record("MAN-1", Some("Name at creation"))]);
- request.display_names.insert("MAN-1".to_string(), "Renamed since".to_string());
-
- let set = resolve_manifest_write_set(request);
- assert_eq!(set.records[1].name.as_deref(), Some("Renamed since"));
-}
-
-#[test]
-fn a_manifest_with_no_name_anywhere_is_written_without_one() {
- let mut request = write_set_request(&["PERSONAL", "MAN-1"], &["MAN-1"], vec![record("MAN-1", None)]);
- // An empty rendered name must not shadow the absent one.
- request.display_names.insert("MAN-1".to_string(), String::new());
-
- let set = resolve_manifest_write_set(request);
- assert_eq!(set.records[1].name, None);
-}
-
#[test]
fn several_manifests_keep_the_order_they_were_held_in() {
- let held = vec![record("MAN-1", None), record("MAN-2", None), record("MAN-3", None)];
+ let held = vec![record("MAN-1"), record("MAN-2"), record("MAN-3")];
let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1", "MAN-3"], &["MAN-1", "MAN-2", "MAN-3"], held));
let written: Vec<&str> = set.records.iter().map(|r| r.manifest_id.as_str()).collect();
@@ -173,20 +149,18 @@ fn the_json_boundary_round_trips() {
"personalManifestSalt": "personal-salt",
"stampedManifestIds": ["PERSONAL", "MAN-1"],
"openedManifestIds": ["MAN-1"],
- "heldRecords": [{ "manifestId": "MAN-1", "salt": "salt-1", "encryptedVek": "ignored", "canAdminister": true }],
- "displayNames": { "man-1": "Family" }
+ "heldRecords": [{ "manifestId": "MAN-1", "salt": "salt-1", "encryptedVek": "ignored", "canAdminister": true }]
}"#;
let output: serde_json::Value = serde_json::from_str(&crate::error::json_call(input, |request| Ok(resolve_manifest_write_set(request))).unwrap()).unwrap();
assert_eq!(output["records"][1]["manifestId"], "MAN-1");
- assert_eq!(output["records"][1]["name"], "Family");
assert_eq!(output["records"][1]["isPersonal"], false);
assert_eq!(output["skipped"].as_array().unwrap().len(), 0);
}
#[test]
fn a_skip_reason_is_a_stable_token() {
- let set = resolve_manifest_write_set(write_set_request(&["PERSONAL"], &[], vec![record("MAN-1", None)]));
+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL"], &[], vec![record("MAN-1")]));
let json = serde_json::to_value(&set).unwrap();
assert_eq!(json["skipped"][0]["reason"], "NO_ROWS_IN_VAULT");
}
diff --git a/core/rust/src/vault_sharing/types.rs b/core/rust/src/vault_sharing/types.rs
index 45a8d845c..887ae526e 100644
--- a/core/rust/src/vault_sharing/types.rs
+++ b/core/rust/src/vault_sharing/types.rs
@@ -1,5 +1,4 @@
//! Input and output types for the sharing write logic.
-use std::collections::HashMap;
use serde::{Deserialize, Serialize};
@@ -11,9 +10,6 @@ pub struct SharedManifestRecord {
pub manifest_id: String,
/// Salt this manifest's blob hashes are derived with.
pub salt: String,
- /// Name as recorded on the last pull.
- #[serde(default)]
- pub name: Option<String>,
/// Whether this account may publish the manifest's email delivery key.
#[serde(default)]
pub can_administer: bool,
@@ -36,9 +32,6 @@ pub struct ManifestWriteSetRequest {
/// The shared-manifest key records this client holds.
#[serde(default)]
pub held_records: Vec<SharedManifestRecord>,
- /// What this client renders each manifest as, keyed by manifest id.
- #[serde(default)]
- pub display_names: HashMap<String, String>,
}
/// Why a manifest is left out of the write.
@@ -71,8 +64,6 @@ pub struct ManifestWriteRecord {
pub is_personal: bool,
/// Salt this manifest's blob hashes are derived with.
pub salt: String,
- /// Name to write into the manifest, or none.
- pub name: Option<String>,
/// Whether this account may publish the manifest's email delivery key.
pub can_administer: bool,
}
diff --git a/core/rust/src/vault_sync/db.rs b/core/rust/src/vault_sync/db.rs
index feebaf808..9a5a3ece6 100644
--- a/core/rust/src/vault_sync/db.rs
+++ b/core/rust/src/vault_sync/db.rs
@@ -33,10 +33,6 @@ pub(crate) async fn exec(host: &Host, db: Db, statements: Vec<SqlStatement>) ->
Ok(())
}
-pub(crate) async fn exec_one(host: &Host, db: Db, sql: &str, params: Vec<Value>) -> SyncResult<()> {
- exec(host, db, vec![SqlStatement { sql: sql.to_string(), params }]).await
-}
-
/// Open the staging database: fresh with the current schema, or from SQLite bytes.
pub(crate) async fn open_staging(host: &Host, bytes: Option<&[u8]>) -> SyncResult<()> {
host.call::<Ack>(Command::DbOpen { db: Db::Staging, bytes: bytes.map(base64_encode) }).await?;
@@ -230,16 +226,9 @@ const GET_ACTIVE_KEY_FOR_MANIFEST: &str = "SELECT x.Id, x.PublicKey, x.PrivateKe
const GET_ACCOUNT_KEY_BY_PUBLIC_KEY: &str = "SELECT x.PublicKey, x.PrivateKey, x.IsPrimary FROM EncryptionKeys x WHERE x.ManifestId = ? AND x.PublicKey = ? AND x.IsDeleted = 0 LIMIT 1";
const DEMOTE_KEYS_FOR_MANIFEST: &str = "UPDATE EncryptionKeys SET IsPrimary = 0, UpdatedAt = ? WHERE ManifestId = ? AND IsPrimary = 1";
const INSERT_KEY_FOR_MANIFEST: &str = "INSERT INTO EncryptionKeys (Id, ManifestId, PublicKey, PrivateKey, IsPrimary, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, 1, ?, ?, 0)";
-const INSERT_FOLDER: &str = "INSERT INTO Folders (Id, Name, ParentFolderId, ManifestId, Weight, IsDeleted, CreatedAt, UpdatedAt) VALUES (?, ?, ?, ?, 0, 0, ?, ?)";
-const RESTAMP_SUBTREE_ITEMS: &str = "UPDATE Items SET ManifestId = ?, UpdatedAt = ? WHERE ManifestId = ? AND FolderId IN (WITH RECURSIVE subtree(Id) AS (SELECT Id FROM Folders WHERE Id = ? AND ManifestId = ? UNION ALL SELECT f.Id FROM Folders f INNER JOIN subtree s ON f.ParentFolderId = s.Id WHERE f.ManifestId = ?) SELECT Id FROM subtree)";
-const RESTAMP_SUBTREE_FOLDERS: &str = "UPDATE Folders SET ManifestId = ? WHERE ManifestId = ? AND Id IN (WITH RECURSIVE subtree(Id) AS (SELECT Id FROM Folders WHERE Id = ? AND ManifestId = ? UNION ALL SELECT f.Id FROM Folders f INNER JOIN subtree s ON f.ParentFolderId = s.Id WHERE f.ManifestId = ?) SELECT Id FROM subtree)";
-const FIND_ITEMS_WITH_FOREIGN_LOGO: &str = "SELECT i.Id, i.ManifestId, origin.Kind, origin.Source FROM Items i INNER JOIN Logos origin ON origin.Id = i.LogoId LEFT JOIN Logos own ON own.Id = i.LogoId AND own.ManifestId = i.ManifestId WHERE i.LogoId IS NOT NULL AND own.Id IS NULL AND i.IsDeleted = 0";
-const GET_LOGO_ID_FOR_KEY: &str = "SELECT Id FROM Logos WHERE ManifestId = ? AND Kind = ? AND Source = ? AND IsDeleted = 0 LIMIT 1";
-const GET_BEST_LOGO_FOR_KEY: &str = "SELECT FileData, MimeType, Name FROM Logos WHERE Kind = ? AND Source = ? AND IsDeleted = 0 ORDER BY (FileData IS NOT NULL AND LENGTH(FileData) > 0) DESC, UpdatedAt DESC LIMIT 1";
-const UPSERT_LOGO: &str = "INSERT INTO Logos (Id, Kind, Source, ManifestId, FileData, MimeType, Name, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0) ON CONFLICT(ManifestId, Id) DO UPDATE SET FileData = excluded.FileData, MimeType = excluded.MimeType, Name = COALESCE(excluded.Name, Logos.Name), UpdatedAt = excluded.UpdatedAt, IsDeleted = 0";
-const REPOINT_ITEM_LOGO: &str = "UPDATE Items SET LogoId = ? WHERE Id = ? AND ManifestId = ?";
-const RENDERED_MANIFEST_FOLDER: &str = "SELECT Id FROM Folders WHERE ManifestId = ? AND IsDeleted = 0 AND ParentFolderId IS NULL";
-const MANIFEST_ROOT_FOLDER_NAMES: &str = "SELECT ManifestId, Name FROM Folders WHERE IsDeleted = 0 AND ManifestId IS NOT NULL AND UPPER(Id) = UPPER(ManifestId)";
+const MANIFEST_NAMES: &str = "SELECT Id, Name FROM Manifests WHERE Name IS NOT NULL";
+const UPDATE_MANIFEST_NAME: &str = "UPDATE Manifests SET Name = ? WHERE Id = ?";
+const UPSERT_MANIFEST_NAME: &str = "INSERT INTO Manifests (Id, Name) VALUES (?, ?) ON CONFLICT(Id) DO UPDATE SET Name = excluded.Name";
/// The active mail delivery keypair of a manifest, when it has one.
pub(crate) async fn active_key_for_manifest(host: &Host, manifest_id: &str) -> SyncResult<Option<Row>> {
@@ -266,68 +255,35 @@ pub(crate) async fn set_active_key_for_manifest(host: &Host, manifest_id: &str,
.await
}
-/// What each shared manifest is called: the name of the top-level folder it is rendered as, keyed by lower-cased id.
+/*
+ * What each manifest is called, keyed by lower-cased id.
+ */
pub(crate) async fn manifest_display_names(host: &Host) -> SyncResult<HashMap<String, String>> {
- // A vault whose schema predates the manifest stamp names none.
- if !has_column(host, Db::Local, "Folders", "ManifestId").await? {
+ // A vault whose schema predates the table names none.
+ if !has_column(host, Db::Local, "Manifests", "Name").await? {
return Ok(HashMap::new());
}
- let rows = query(host, Db::Local, MANIFEST_ROOT_FOLDER_NAMES, vec![]).await?;
+ let rows = query(host, Db::Local, MANIFEST_NAMES, vec![]).await?;
Ok(rows
.iter()
- .filter_map(|row| Some((id_key(row.get("ManifestId")?.as_str()?), row.get("Name")?.as_str()?.to_string())))
+ .filter_map(|row| Some((id_key(row.get("Id")?.as_str()?), row.get("Name")?.as_str()?.to_string())))
.collect())
}
-/// Whether a shared manifest already has the top-level folder it is rendered as.
-pub(crate) async fn has_rendered_manifest_folder(host: &Host, manifest_id: &str) -> SyncResult<bool> {
- Ok(!query(host, Db::Local, RENDERED_MANIFEST_FOLDER, vec![json!(manifest_id)]).await?.is_empty())
-}
-
-/// The statements that create the folder a shared manifest is rendered as and pull everything under it into the manifest.
-pub(crate) fn render_manifest_folder_statements(manifest_id: &str, name: &str, active_manifest_id: &str, now: &str) -> Vec<SqlStatement> {
- let folder_id = id_key(manifest_id);
- vec![
- SqlStatement { sql: INSERT_FOLDER.to_string(), params: vec![json!(folder_id), json!(name), Value::Null, json!(active_manifest_id), json!(now), json!(now)] },
- // Items first: their walk reads the folder stamps the last statement changes.
- SqlStatement { sql: RESTAMP_SUBTREE_ITEMS.to_string(), params: vec![json!(manifest_id), json!(now), json!(active_manifest_id), json!(folder_id), json!(active_manifest_id), json!(active_manifest_id)] },
- SqlStatement { sql: RESTAMP_SUBTREE_FOLDERS.to_string(), params: vec![json!(manifest_id), json!(active_manifest_id), json!(folder_id), json!(active_manifest_id), json!(active_manifest_id)] },
- ]
+/// Name a manifest in the local vault.
+pub(crate) async fn set_manifest_name(host: &Host, manifest_id: &str, name: &str) -> SyncResult<()> {
+ exec(host, Db::Local, vec![set_manifest_name_statement(manifest_id, name)]).await
}
-/// Create the folder a shared manifest is rendered as and pull everything under it into the manifest.
-pub(crate) async fn render_manifest_folder(host: &Host, manifest_id: &str, name: &str, active_manifest_id: &str) -> SyncResult<()> {
- let now = now_vault_datetime();
- exec(host, Db::Local, render_manifest_folder_statements(manifest_id, name, active_manifest_id, &now)).await?;
- reconcile_item_logo_scopes(host, &now).await
+/// Name the manifests a database already holds; a manifest it does not hold stays out of it.
+pub(crate) async fn apply_manifest_names(host: &Host, db: Db, names: &HashMap<String, String>) -> SyncResult<()> {
+ let statements: Vec<SqlStatement> = names.iter().map(|(manifest_id, name)| SqlStatement { sql: UPDATE_MANIFEST_NAME.to_string(), params: vec![json!(name), json!(manifest_id)] }).collect();
+ exec(host, db, statements).await
}
-/// Point every item at a copy of its logo inside its own manifest, copying the image in when needed.
-pub(crate) async fn reconcile_item_logo_scopes(host: &Host, now: &str) -> SyncResult<()> {
- let foreign = query(host, Db::Local, FIND_ITEMS_WITH_FOREIGN_LOGO, vec![]).await?;
- for item in foreign {
- let manifest_id = cell_string(&item, "ManifestId");
- let kind = cell_string(&item, "Kind");
- let source = cell_string(&item, "Source");
- let item_id = cell_string(&item, "Id");
-
- let in_scope = query(host, Db::Local, GET_LOGO_ID_FOR_KEY, vec![json!(manifest_id), json!(kind), json!(source)]).await?;
- let logo_id = match in_scope.first().and_then(|row| row.get("Id")).and_then(Value::as_str) {
- Some(id) => id.to_string(),
- None => {
- let origin = query(host, Db::Local, GET_BEST_LOGO_FOR_KEY, vec![json!(kind), json!(source)]).await?;
- let Some(origin) = origin.into_iter().next() else { continue };
- let logo_id = crate::vault_codec::logo_id_for(&manifest_id, &kind, &source);
- let file_data = origin.get("FileData").cloned().unwrap_or(Value::Null);
- let mime = origin.get("MimeType").cloned().unwrap_or(Value::Null);
- let name = origin.get("Name").cloned().unwrap_or(Value::Null);
- exec_one(host, Db::Local, UPSERT_LOGO, vec![json!(logo_id), json!(kind), json!(source), json!(manifest_id), file_data, mime, name, json!(now), json!(now)]).await?;
- logo_id
- }
- };
- exec_one(host, Db::Local, REPOINT_ITEM_LOGO, vec![json!(logo_id), json!(item_id), json!(manifest_id)]).await?;
- }
- Ok(())
+/// The statement that names a manifest.
+pub(crate) fn set_manifest_name_statement(manifest_id: &str, name: &str) -> SqlStatement {
+ SqlStatement { sql: UPSERT_MANIFEST_NAME.to_string(), params: vec![json!(id_key(manifest_id)), json!(name)] }
}
/// Prune expired trash items in place. Returns the number of statements executed.
diff --git a/core/rust/src/vault_sync/engine.rs b/core/rust/src/vault_sync/engine.rs
index 1b3cf8fc3..c73b9566d 100644
--- a/core/rust/src/vault_sync/engine.rs
+++ b/core/rust/src/vault_sync/engine.rs
@@ -14,7 +14,7 @@ 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, sharing};
use crate::crypto;
-use crate::vault_model::ids_equal;
+use crate::vault_model::{id_key, ids_equal};
/// How many times a chain of syncs may re-sync after an outdated push before giving up.
/// This is a auto-healing mechanism in case two clients are pushing at the same time, which could
@@ -57,6 +57,10 @@ pub(crate) async fn run(host: Host, request: SyncRequest) -> Value {
let result = sharing::invite_to_shared_manifest_operation(&mut ctx).await;
finish(&ctx, result)
}
+ SyncOperation::UpdateSharedManifest => {
+ let result = sharing::update_shared_manifest_operation(&mut ctx).await;
+ finish(&ctx, result)
+ }
}
}
@@ -143,7 +147,8 @@ async fn full_sync_once(ctx: &mut Ctx) -> SyncResult<Flow> {
};
announce_phase(ctx, needs_pull, ctx.is_dirty).await;
- let grant_sync_changed_vault = apply_server_directed_changes(ctx, &status).await?;
+ let names_changed_vault = refresh_manifest_names(ctx, &status, needs_pull).await?;
+ let grant_sync_changed_vault = apply_server_directed_changes(ctx, &status).await? || names_changed_vault;
// The rows just reconciled can turn a clean vault dirty after the preflight decided; a dirty vault was checked there.
if !needs_pull && grant_sync_changed_vault && push::vault_holds_unwritable_manifests(ctx).await {
needs_pull = true;
@@ -336,6 +341,40 @@ pub(crate) async fn vault_requires_manifest_migration(ctx: &mut Ctx) -> SyncResu
Ok(schema_state(ctx).await? == SchemaState::Stale || !keys::has_local_vault_key(&ctx.host).await?)
}
+/*
+ * Fetch the shared manifest names the status served and store them in the local vault.
+ */
+async fn refresh_manifest_names(ctx: &mut Ctx, status: &StatusResponse, needs_pull: bool) -> SyncResult<bool> {
+ ctx.served_manifest_names = status.manifest_revisions.iter().filter_map(|m| Some((id_key(&m.manifest_id), m.encrypted_name.clone()?))).collect();
+ if needs_pull || ctx.served_manifest_names.is_empty() || !ctx.has_local_vault().await? || vault_requires_manifest_migration(ctx).await? {
+ return Ok(false);
+ }
+
+ let mut records = keys::shared_manifest_records(ctx).await?;
+ let mut opened: HashMap<String, String> = HashMap::new();
+ for record in records.values_mut() {
+ let Some(served) = ctx.served_manifest_names.get(&id_key(&record.manifest_id)).filter(|served| record.encrypted_name.as_ref() != Some(*served)).cloned() else { continue };
+ let Some(vek) = keys::open_shared_manifest_vek(ctx, record).await? else { continue };
+ match pull::open_manifest_name(&served, &vek) {
+ Some(name) => drop(opened.insert(id_key(&record.manifest_id), name)),
+ None => ctx.warn(format!("[Sharing] The name of shared manifest {} did not open with its key.", record.manifest_id)).await,
+ }
+ record.encrypted_name = Some(served);
+ }
+ if opened.is_empty() {
+ return Ok(false);
+ }
+
+ let key = ctx.encryption_key()?;
+ db::apply_manifest_names(&ctx.host, Db::Local, &opened).await?;
+ let bytes = db::export(&ctx.host, Db::Local).await?;
+ ctx.store_vault(&state::encrypt_vault_blob(&bytes, &key)?, false, None, None).await?;
+ keys::set_shared_manifest_records(&ctx.host, &records, &key).await?;
+ ctx.vault_changed = true;
+ ctx.log(format!("[Sharing] Refreshed the name of {} shared manifest(s).", opened.len())).await;
+ Ok(true)
+}
+
/// Carry out the work the server has addressed to the current client (e.g. shared groups revocation/rotation actions).
async fn apply_server_directed_changes(ctx: &mut Ctx, status: &StatusResponse) -> SyncResult<bool> {
let shared = keys::shared_manifest_records(ctx).await?;
@@ -343,19 +382,6 @@ async fn apply_server_directed_changes(ctx: &mut Ctx, status: &StatusResponse) -
let mut vault_changed = false;
if can_reconcile {
- let personal = state::get::<String>(&ctx.host, state::VAULT_PERSONAL_MANIFEST_ID).await?;
- for record in shared.values().filter(|r| r.can_administer) {
- // A member waiting for the administrator's first push has nothing to render yet.
- if db::has_rendered_manifest_folder(&ctx.host, &record.manifest_id).await? {
- continue;
- }
- let Some(active) = personal.as_deref() else { break };
- let name = record.name.clone().filter(|n| !n.is_empty()).or_else(|| ctx.request.unnamed_shared_vault_name.clone()).unwrap_or_else(|| "Shared vault".to_string());
- db::render_manifest_folder(&ctx.host, &record.manifest_id, &name, active).await?;
- ctx.warn(format!("[Sharing] Shared manifest {} had no folder; recreated it.", record.manifest_id)).await;
- vault_changed = true;
- }
-
let mut completed = 0usize;
for action in &status.pending_actions {
let outcome: SyncResult<(bool, bool)> = async {
@@ -590,7 +616,7 @@ pub(crate) async fn rebuild_local_schema(ctx: &mut Ctx, adopt_unstamped_into: Op
}
}
let manifests: Vec<_> = set.canonicalized.manifests.iter().map(|m| m.manifest.clone()).collect();
- let bytes = pull::materialize_to_sqlite(ctx, &manifests, &set.canonicalized.data_buckets, &blob_map).await?;
+ let bytes = pull::materialize_to_sqlite(ctx, &manifests, &set.canonicalized.data_buckets, &blob_map, &HashMap::new()).await?;
ctx.log(format!("[ManifestMigration] Migration complete: {} blobs re-embedded, {} bytes.", blob_map.len(), bytes.len())).await;
let stored = ctx.store_vault(&state::encrypt_vault_blob(&bytes, &ctx.encryption_key()?)?, true, None, None).await?;
diff --git a/core/rust/src/vault_sync/merge.rs b/core/rust/src/vault_sync/merge.rs
index 08f6553e0..77c295a52 100644
--- a/core/rust/src/vault_sync/merge.rs
+++ b/core/rust/src/vault_sync/merge.rs
@@ -59,7 +59,7 @@ pub(crate) async fn pull_and_merge(ctx: &mut Ctx) -> SyncResult<PullAndMergeOutc
Err(merge_error) => {
// The merge-failure fallback, from the same snapshot: the server vault stands, local changes are dropped.
ctx.warn(format!("[V2Merge] Canonical merge failed, falling back to the server vault: {}", merge_error)).await;
- let sqlite_bytes = pull::materialize_to_sqlite(ctx, &opened.manifests(), &opened.data_buckets, &opened.blob_map).await?;
+ let sqlite_bytes = pull::materialize_to_sqlite(ctx, &opened.manifests(), &opened.data_buckets, &opened.blob_map, &opened.manifest_names).await?;
Ok(PullAndMergeOutcome::ServerOnly(opened.pulled_vault(state::encrypt_vault_blob(&sqlite_bytes, &vek)?, email_routing)))
}
}
@@ -144,7 +144,7 @@ async fn merge_onto_opened_manifests(ctx: &mut Ctx, opened: &OpenedManifestSet,
let personal_id = opened.resolved.first().map(|m| m.manifest_id.clone()).unwrap_or_default();
let merged_blobs = resolve_merged_blob_refs(ctx, &manifests, &blob_map, &personal_id, &local_blobs).await?;
- let sqlite_bytes = pull::materialize_to_sqlite(ctx, &manifests, &data_buckets, &blob_map).await?;
+ let sqlite_bytes = pull::materialize_to_sqlite(ctx, &manifests, &data_buckets, &blob_map, &opened.manifest_names).await?;
let encrypted_vault = state::encrypt_vault_blob(&sqlite_bytes, vek)?;
ctx.log(format!("[V2Merge] Canonical merge complete: {} conflict(s), {} offline row(s) kept, {} validation fallback(s), {} dropped local manifest(s).", stats.conflicts, stats.records_inserted, fallback_manifest_ids.len(), merge_output.dropped_local_manifest_ids.len())).await;
diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rs
index d25bad904..802c565d7 100644
--- a/core/rust/src/vault_sync/pull.rs
+++ b/core/rust/src/vault_sync/pull.rs
@@ -3,7 +3,7 @@
use std::collections::HashMap;
-use crate::vault_model::ids_equal;
+use crate::vault_model::{id_key, ids_equal};
use super::errors::{SyncError, SyncResult};
use super::state::{self, Ctx};
use super::types::{self, BlobDto, BlobHashesRequest, Db, EmailRoutingDto, GetResponse, ManifestDto, SharedManifestDto, StoredBlobRef};
@@ -29,6 +29,7 @@ pub(crate) struct OpenedManifestSet {
pub resolved: Vec<ResolvedManifest>,
pub data_buckets: Vec<DataBucket>,
pub blob_map: HashMap<String, Vec<u8>>,
+ pub manifest_names: HashMap<String, String>,
pub contentless_manifest_ids: Vec<String>,
pub personal_revision: i64,
pub manifest_revisions: HashMap<String, i64>,
@@ -105,7 +106,7 @@ pub(crate) async fn pull(ctx: &mut Ctx) -> SyncResult<PulledVault> {
ctx.log("[V2Pull] Step 2/4: manifest format: decrypting and reassembling local SQLite...").await;
let opened = open_manifests_and_record_sync_state(ctx, &snapshot, &vek).await?;
- let sqlite_bytes = materialize_to_sqlite(ctx, &opened.manifests(), &opened.data_buckets, &opened.blob_map).await?;
+ let sqlite_bytes = materialize_to_sqlite(ctx, &opened.manifests(), &opened.data_buckets, &opened.blob_map, &opened.manifest_names).await?;
ctx.log(format!("[V2Pull] Step 3/4: materialized SQLite ({} bytes); re-encrypting for local storage...", sqlite_bytes.len())).await;
Ok(opened.pulled_vault(state::encrypt_vault_blob(&sqlite_bytes, &vek)?, email_routing_of(&snapshot)))
}
@@ -122,6 +123,8 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
let mut resolved: Vec<ResolvedManifest> = Vec::new();
let mut shared_records: HashMap<String, SharedManifestDto> = HashMap::new();
let mut contentless_revisions: HashMap<String, i64> = HashMap::new();
+ let mut manifest_names: HashMap<String, String> = HashMap::new();
+ let previous_records = keys::shared_manifest_records(ctx).await?;
let ordered: Vec<&ManifestDto> = std::iter::once(personal_dto).chain(snapshot.manifests.iter().filter(|m| m.manifest_id != personal_dto.manifest_id)).collect();
for dto in ordered {
@@ -130,7 +133,8 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
if dto.blob.as_deref().unwrap_or("").is_empty() {
// A shared manifest served without content yet (created but never written); its grant and revision are still tracked.
let (encrypted_vek, encryption_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} was served without content and without a grant, refusing to assemble", dto.manifest_id)))?;
- shared_records.insert(dto.manifest_id.clone(), SharedManifestDto { manifest_id: dto.manifest_id.clone(), encrypted_vek, encryption_public_key, algorithm, salt: vault_codec::generate_manifest_salt(), name: None, can_administer: dto.can_administer });
+ let encrypted_name = served_encrypted_name(ctx, &previous_records, &dto.manifest_id);
+ shared_records.insert(dto.manifest_id.clone(), SharedManifestDto { manifest_id: dto.manifest_id.clone(), encrypted_vek, encryption_public_key, algorithm, salt: vault_codec::generate_manifest_salt(), encrypted_name, can_administer: dto.can_administer });
contentless_revisions.insert(dto.manifest_id.clone(), dto.revision);
continue;
}
@@ -148,7 +152,14 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
}
let (encrypted_vek, encryption_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant this account can re-open, refusing to assemble", entry.manifest_id)))?;
- shared_records.insert(entry.manifest_id.clone(), SharedManifestDto { manifest_id: entry.manifest_id.clone(), encrypted_vek, encryption_public_key, algorithm, salt: entry.manifest.manifest_salt.clone(), name: entry.manifest.name.clone(), can_administer: dto.can_administer });
+ let encrypted_name = served_encrypted_name(ctx, &previous_records, &entry.manifest_id);
+ if let Some(ciphertext) = &encrypted_name {
+ match open_manifest_name(ciphertext, &manifest_key) {
+ Some(name) => drop(manifest_names.insert(id_key(&entry.manifest_id), name)),
+ None => ctx.warn(format!("[V2Pull] The name of shared manifest {} did not open with its key; leaving it unnamed.", entry.manifest_id)).await,
+ }
+ }
+ shared_records.insert(entry.manifest_id.clone(), SharedManifestDto { manifest_id: entry.manifest_id.clone(), encrypted_vek, encryption_public_key, algorithm, salt: entry.manifest.manifest_salt.clone(), encrypted_name, can_administer: dto.can_administer });
resolved.push(entry);
}
keys::set_shared_manifest_records(&ctx.host, &shared_records, vek).await?;
@@ -173,6 +184,7 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
resolved,
data_buckets,
blob_map,
+ manifest_names,
contentless_manifest_ids: contentless_revisions.keys().cloned().collect(),
personal_revision,
manifest_revisions,
@@ -180,6 +192,19 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshot
})
}
+/// The encrypted name of a manifest.
+fn served_encrypted_name(ctx: &Ctx, previous: &HashMap<String, SharedManifestDto>, manifest_id: &str) -> Option<String> {
+ ctx.served_manifest_names
+ .get(&id_key(manifest_id))
+ .cloned()
+ .or_else(|| previous.values().find(|record| ids_equal(&record.manifest_id, manifest_id)).and_then(|record| record.encrypted_name.clone()))
+}
+
+/// Decrypt a manifest's name with the manifest's own key.
+pub(crate) fn open_manifest_name(ciphertext: &str, manifest_key: &str) -> Option<String> {
+ crypto::symmetric_decrypt(ciphertext, manifest_key).ok().filter(|name| !name.is_empty())
+}
+
/// Commit a snapshot's revision maps as the local believed-current revisions, manifests and buckets together.
pub(crate) async fn commit_revisions(ctx: &Ctx, manifest_revisions: &HashMap<String, i64>, bucket_revisions: &HashMap<String, i64>) -> SyncResult<()> {
state::set(&ctx.host, state::SERVER_MANIFEST_REVISIONS, manifest_revisions).await?;
@@ -269,7 +294,7 @@ async fn download_referenced_blobs(ctx: &Ctx, resolved: &[ResolvedManifest], fal
}
/// Materialize manifests and buckets into a fresh database and return its bytes.
-pub(crate) async fn materialize_to_sqlite(ctx: &mut Ctx, manifests: &[Manifest], data_buckets: &[DataBucket], blob_map: &HashMap<String, Vec<u8>>) -> SyncResult<Vec<u8>> {
+pub(crate) async fn materialize_to_sqlite(ctx: &mut Ctx, manifests: &[Manifest], data_buckets: &[DataBucket], blob_map: &HashMap<String, Vec<u8>>, opened_names: &HashMap<String, String>) -> SyncResult<Vec<u8>> {
ctx.log(format!("[V2Pull] {} blobs decrypted; running codec reassembly into a fresh SQLite ({} manifest(s) combined)...", blob_map.len(), manifests.len())).await;
let schema = ctx.schema().await?;
let materialized = vault_codec::materialize_as_sqlite(MaterializeInput { manifests: manifests.to_vec(), data_buckets: data_buckets.to_vec(), schema_columns: schema.columns })?;
@@ -282,6 +307,11 @@ pub(crate) async fn materialize_to_sqlite(ctx: &mut Ctx, manifests: &[Manifest],
// Use a fresh staging database for every materialize.
db::open_staging(&ctx.host, None).await?;
db::insert_materialized(&ctx.host, &materialized, blob_map).await?;
+
+ // Names are not part of a manifest: the ones the vault already shows are kept, the ones this run opened win.
+ let mut names = if ctx.has_local_vault().await? { db::manifest_display_names(&ctx.host).await? } else { HashMap::new() };
+ names.extend(opened_names.clone());
+ db::apply_manifest_names(&ctx.host, Db::Staging, &names).await?;
let bytes = db::export(&ctx.host, Db::Staging).await?;
ctx.log(format!("[V2Pull] Codec reassembly complete: {} bytes.", bytes.len())).await;
Ok(bytes)
diff --git a/core/rust/src/vault_sync/push.rs b/core/rust/src/vault_sync/push.rs
index 4c48a5cd7..56febfd14 100644
--- a/core/rust/src/vault_sync/push.rs
+++ b/core/rust/src/vault_sync/push.rs
@@ -68,7 +68,7 @@ pub(crate) struct UploadOutcome {
pub(crate) async fn canonicalize_vault(ctx: &Ctx, adopt_unstamped_into: Option<String>) -> SyncResult<CanonicalizedSet> {
let tables = db::read_tables(&ctx.host, Db::Local).await?;
let manifest_records = resolve_manifest_records(ctx).await?;
- let manifests: Vec<ManifestSpec> = manifest_records.iter().map(|r| ManifestSpec { manifest_id: r.manifest_id.clone(), manifest_salt: r.salt.clone(), name: r.name.clone() }).collect();
+ let manifests: Vec<ManifestSpec> = manifest_records.iter().map(|r| ManifestSpec { manifest_id: r.manifest_id.clone(), manifest_salt: r.salt.clone(), name: None }).collect();
let canonicalized = vault_codec::canonicalize_from_sqlite(CanonicalizeInput { tables, canonicalized_at: crate::timestamp::now_iso_utc(), manifests, adopt_unstamped_into })?;
Ok(CanonicalizedSet { canonicalized, manifest_records })
}
@@ -90,8 +90,7 @@ async fn resolve_manifest_records(ctx: &Ctx) -> SyncResult<Vec<ManifestRecord>>
personal_manifest_salt: manifest_salt,
stamped_manifest_ids: db::manifest_ids_in_vault(&ctx.host, Db::Local).await?,
opened_manifest_ids: shared_veks.keys().cloned().collect(),
- held_records: held.values().map(|r| SharedManifestRecord { manifest_id: r.manifest_id.clone(), salt: r.salt.clone(), name: r.name.clone(), can_administer: r.can_administer }).collect(),
- display_names: db::manifest_display_names(&ctx.host).await?,
+ held_records: held.values().map(|r| SharedManifestRecord { manifest_id: r.manifest_id.clone(), salt: r.salt.clone(), can_administer: r.can_administer }).collect(),
});
for skipped in &write_set.skipped {
let why = match skipped.reason {
@@ -324,7 +323,7 @@ impl Candidate<'_> {
if self.record.is_personal {
"Personal manifest".to_string()
} else {
- format!("Shared manifest \"{}\"", self.manifest.name.clone().unwrap_or_else(|| self.record.manifest_id.clone()))
+ format!("Shared manifest {}", self.record.manifest_id)
}
}
}
diff --git a/core/rust/src/vault_sync/sharing.rs b/core/rust/src/vault_sync/sharing.rs
index 827ac88a3..f480ada9c 100644
--- a/core/rust/src/vault_sync/sharing.rs
+++ b/core/rust/src/vault_sync/sharing.rs
@@ -1,5 +1,7 @@
//! The sharing operations that take vault keys: creating a group's shared manifest and inviting a member to one.
+use std::collections::HashMap;
+
use serde::{Deserialize, Serialize};
use super::errors::{SyncError, SyncResult};
@@ -57,6 +59,14 @@ struct CreateSharedManifestRequest<'a> {
self_encrypted_vek: &'a str,
self_public_key: &'a str,
algorithm: &'a str,
+ encrypted_name: &'a str,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct UpdateSharedManifestRequest<'a> {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ encrypted_name: Option<&'a str>,
}
#[derive(Debug, Deserialize)]
@@ -106,6 +116,12 @@ pub(crate) async fn invite_to_shared_manifest_operation(ctx: &mut Ctx) -> Sharin
finish(ctx, "invite to shared manifest", outcome).await
}
+/// Change the details of a shared manifest this account administers.
+pub(crate) async fn update_shared_manifest_operation(ctx: &mut Ctx) -> SharingOperationResult {
+ let outcome = update_shared_manifest(ctx).await;
+ finish(ctx, "update 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 {
@@ -167,18 +183,22 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
// 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 state::get::<String>(&ctx.host, state::VAULT_PERSONAL_MANIFEST_ID).await?.is_none() {
+ 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)?;
+ // The server keeps the name for every member to fetch, encrypted with the manifest's own key.
+ let encrypted_name = crypto::symmetric_encrypt(&name, &manifest_vek)?;
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 },
+ &CreateSharedManifestRequest { manifest_id: &requested_id, self_encrypted_vek: &self_encrypted_vek, self_public_key: &self_public_key, algorithm: ALGORITHM_RSA_OAEP_SHA256, encrypted_name: &encrypted_name },
false,
)
.await?;
@@ -193,23 +213,23 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
encryption_public_key: self_public_key,
algorithm: ALGORITHM_RSA_OAEP_SHA256.to_string(),
salt: vault_codec::generate_manifest_salt(),
- name: Some(name.clone()),
+ encrypted_name: Some(encrypted_name),
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();
+ let mut revisions: 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?;
+ db::set_manifest_name(&ctx.host, &manifest_id, &name).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.
+ // The name 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;
@@ -220,6 +240,38 @@ async fn create_shared_manifest(ctx: &mut Ctx) -> Outcome {
Ok(Ok(manifest_id))
}
+/// The details an update can change (e.g. the name of a manifest / shared vault).
+async fn update_shared_manifest(ctx: &mut Ctx) -> Outcome {
+ let key = ctx.encryption_key()?;
+ let target = params(ctx)?;
+ let manifest_id = target.manifest_id.clone().ok_or_else(|| SyncError::Other("The update names no shared manifest".to_string()))?;
+ let name = target.name.as_deref().map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| SyncError::Other("The update changes nothing".to_string()))?.to_string();
+
+ let mut records = keys::shared_manifest_records(ctx).await?;
+ let record = records.values().find(|record| ids_equal(&record.manifest_id, &manifest_id)).cloned().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 server decides who may change a shared manifest; it only ever sees the name encrypted.
+ let encrypted_name = crypto::symmetric_encrypt(&name, &manifest_vek)?;
+ http::post_no_content(&ctx.host, &format!("Groups/{}/manifests/{}", target.group_id, record.manifest_id), &UpdateSharedManifestRequest { encrypted_name: Some(&encrypted_name) }).await?;
+
+ if let Some(held) = records.values_mut().find(|held| ids_equal(&held.manifest_id, &manifest_id)) {
+ held.encrypted_name = Some(encrypted_name);
+ }
+ keys::set_shared_manifest_records(&ctx.host, &records, &key).await?;
+
+ // Show the new name right away; every other member fetches it on their next sync.
+ if ctx.has_local_vault().await? {
+ db::apply_manifest_names(&ctx.host, Db::Local, &HashMap::from([(id_key(&record.manifest_id), name)])).await?;
+ let bytes = db::export(&ctx.host, Db::Local).await?;
+ ctx.store_vault(&state::encrypt_vault_blob(&bytes, &key)?, false, None, None).await?;
+ ctx.vault_changed = true;
+ }
+
+ ctx.log(format!("[Sharing] Updated shared manifest {}.", record.manifest_id)).await;
+ Ok(Ok(record.manifest_id))
+}
+
async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {
ctx.encryption_key()?;
let target = params(ctx)?;
@@ -245,7 +297,7 @@ async fn invite_to_shared_manifest(ctx: &mut Ctx) -> Outcome {
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 name = db::manifest_display_names(&ctx.host).await?.get(&id_key(&manifest.manifest_id)).cloned().filter(|name| !name.is_empty());
let grant = ManifestGrant {
recipient_user_id: member.user_id.clone(),
recipient_public_key_id,
diff --git a/core/rust/src/vault_sync/state.rs b/core/rust/src/vault_sync/state.rs
index 353d77cf2..7ee5153fb 100644
--- a/core/rust/src/vault_sync/state.rs
+++ b/core/rust/src/vault_sync/state.rs
@@ -25,6 +25,7 @@ pub(crate) struct Ctx {
pub vault_changed: bool,
pub schema: Option<SchemaInfo>,
pub vault_key_probed: bool,
+ pub served_manifest_names: HashMap<String, String>,
has_local_vault: bool,
}
@@ -47,6 +48,7 @@ impl Ctx {
vault_changed: false,
schema: None,
vault_key_probed: false,
+ served_manifest_names: HashMap::new(),
has_local_vault: false,
host,
request,
diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rs
index fcb880276..e2d8599f8 100644
--- a/core/rust/src/vault_sync/tests/mod.rs
+++ b/core/rust/src/vault_sync/tests/mod.rs
@@ -1,7 +1,7 @@
//! Engine tests: the whole sync driven through the command loop against a real SQLite host.
mod item_move;
-mod render_manifest_folder;
+mod manifest_name;
mod test_host;
use std::collections::HashMap;
diff --git a/core/rust/src/vault_sync/types.rs b/core/rust/src/vault_sync/types.rs
index 356d1dbca..44e790849 100644
--- a/core/rust/src/vault_sync/types.rs
+++ b/core/rust/src/vault_sync/types.rs
@@ -27,6 +27,8 @@ pub enum SyncOperation {
CreateSharedManifest,
/// Invite a group member to a shared manifest, handing them its key encrypted for their account keypair.
InviteToSharedManifest,
+ /// Change the details of a shared manifest (its name); the server refuses anyone but an administrator of its group.
+ UpdateSharedManifest,
}
/// What a sharing operation acts on.
@@ -34,14 +36,10 @@ pub enum SyncOperation {
#[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>,
}
@@ -72,8 +70,6 @@ pub struct SyncRequest {
pub min_server_version: Option<String>,
#[serde(default)]
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>,
@@ -532,6 +528,9 @@ pub struct StatusResponse {
pub struct ManifestRevision {
pub manifest_id: String,
pub revision: i64,
+ /// The name of a shared manifest, encrypted with the manifest's own key.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub encrypted_name: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -776,8 +775,9 @@ pub struct SharedManifestDto {
pub encryption_public_key: String,
pub algorithm: String,
pub salt: String,
+ /// The manifest's name as the server last served it, encrypted with the manifest's own key.
#[serde(default)]
- pub name: Option<String>,
+ pub encrypted_name: Option<String>,
#[serde(default)]
pub can_administer: bool,
}