Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add MultiManifestRendering abstraction in favor of static folder implementation (#2159)
Leendert de Borst6e0f9203624c
diff --git a/apps/browser-extension/src/utils/FolderUtils.ts b/apps/browser-extension/src/utils/FolderUtils.tsindex 0c6804837..377c4ac81 100644--- a/apps/browser-extension/src/utils/FolderUtils.ts+++ b/apps/browser-extension/src/utils/FolderUtils.ts@@ -26,15 +26,6 @@ export function isSharedFolder(folder: Pick<Folder, 'ManifestId'>, personalManifreturn Boolean(personalManifestId && folder.ManifestId && folder.ManifestId !== personalManifestId);}-/**- * Whether a folder is the one this client renders a shared manifest as.- * @param folder - The folder to classify- * @returns True when the folder anchors a shared manifest- */-export function isAnchorFolder(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean {- return Boolean(folder.ManifestId) && folder.Id.toUpperCase() === String(folder.ManifestId).toUpperCase();-}-/*** Build a hierarchical tree from a flat array of folders.* @param folders - Flat array of folders@@ -224,62 +215,6 @@ export function truncateFolderPath(pathSegments: string[], maxSegments: number =];}-/**- * Format folder path for display with separator.- * @param pathSegments - Array of folder names- * @param separator - Separator string (default: " > ")- * @param truncate - Whether to truncate long paths (default: false)- * @returns Formatted folder path string- */-export function formatFolderPath(- pathSegments: string[],- separator: string = ' > ',- truncate: boolean = false-): string {- const segments = truncate ? truncateFolderPath(pathSegments) : pathSegments;- return segments.join(separator);-}--/**- * Flatten a folder tree into a sorted array suitable for dropdowns.- * Includes visual indentation in the name.- * @param tree - Root-level folder tree nodes- * @param excludeId - Optional folder ID to exclude (useful when moving folders)- * @returns Flat array of folders with indented names- */-export function flattenFolderTree(- tree: FolderTreeNode[],- excludeId?: string-): Array<Folder & { indentedName: string; depth: number }> {- const result: Array<Folder & { indentedName: string; depth: number }> = [];-- /**- * Traverse a folder tree and flatten it into a sorted array.- */- const traverse = (nodes: FolderTreeNode[]): void => {- nodes.forEach(node => {- if (node.Id === excludeId) {- return; // Skip excluded folder and its children- }-- const indent = ' '.repeat(node.depth); // Two spaces per level- result.push({- Id: node.Id,- Name: node.Name,- ParentFolderId: node.ParentFolderId,- Weight: node.Weight,- indentedName: `${indent}${node.Name}`,- depth: node.depth- });-- traverse(node.children);- });- };-- traverse(tree);- return result;-}-/*** Check if a folder can have subfolders (not at max depth).* @param folderId - The folder ID to checkdiff --git a/apps/browser-extension/src/utils/MultiManifestRendering.ts b/apps/browser-extension/src/utils/MultiManifestRendering.tsnew file mode 100644index 000000000..916056a08--- /dev/null+++ b/apps/browser-extension/src/utils/MultiManifestRendering.ts@@ -0,0 +1,143 @@+import type { Folder } from '@/utils/db/repositories/FolderRepository';+import { devWarn } from '@/utils/devLogger/DevLogger';+import type { SqliteClient } from '@/utils/SqliteClient';++import { t } from '@/i18n/StandaloneI18n';++/**+ * How this client presents a vault that is made of several manifests. The local SQLite vault working copy+ * 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.+ * - `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';++/**+ * Rendering policy for a shared manifest.+ */+export type RenderableManifest = {+ manifestId: string;+ name?: string | null;+ canAdminister?: boolean;+};++/**+ * The presentation policy for a multi-manifest vault, as one swappable unit.+ */+export type MultiManifestRenderer = {+ /**+ * The mode this renderer implements.+ */+ 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.+ * @param folder - The folder to classify+ */+ isManifestRoot(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean;++ /**+ * Give a shared manifest whatever local presence this mode renders it as.+ * @param sqliteClient - The open local vault (caller must run this inside a vault mutation so it is saved)+ * @param manifestId - The shared manifest to render+ * @param name - The manifest's own name+ */+ render(sqliteClient: SqliteClient, manifestId: string, name: string): Promise<void>;++ /**+ * Restore that presence for every administered manifest that is missing it.+ * @param sqliteClient - The open local vault+ * @param manifests - The shared manifests this session holds a key for+ * @returns Whether the vault was mutated+ */+ reconcile(sqliteClient: SqliteClient, manifests: RenderableManifest[]): Promise<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.+ * @param sqliteClient - The open local vault+ */+ displayNames(sqliteClient: SqliteClient): Record<string, string>;+};++/**+ * What a shared manifest is called when this client has no name for it yet.+ */+async function defaultSharedVaultName(): Promise<string> {+ return t('sharing.family.unnamedVault');+}++/**+ * Renders every shared manifest as a top-level folder whose id is the manifest id, which is what makes the folder+ * findable from a manifest id alone and what lets its subtree be re-stamped in one statement.+ */+const subfolderRendering: MultiManifestRenderer = {+ mode: 'subfolder',++ /**+ * A folder carrying its own manifest's id is the one that manifest is rendered as.+ * @param folder - The folder to classify+ */+ isManifestRoot(folder: Pick<Folder, 'Id' | 'ManifestId'>): boolean {+ return Boolean(folder.ManifestId) && folder.Id.toUpperCase() === String(folder.ManifestId).toUpperCase();+ },++ /**+ * Create the manifest's folder and pull everything under it into the manifest.+ * @param sqliteClient - The open local vault+ * @param manifestId - The shared manifest to render+ * @param name - The folder name, which is the vault's name+ */+ async render(sqliteClient: SqliteClient, manifestId: string, name: string): Promise<void> {+ const folderId = manifestId.toUpperCase();+ await sqliteClient.folders.create(name, null, folderId);+ await sqliteClient.folders.restampSubtree(folderId, manifestId);+ },++ /**+ * Re-create the folder of any administered manifest that has none.+ * @param sqliteClient - The open local vault+ * @param manifests - The shared manifests this session holds a key for+ * @returns Whether the vault was mutated+ */+ async reconcile(sqliteClient: SqliteClient, manifests: RenderableManifest[]): Promise<boolean> {+ let mutated = false;++ for (const manifest of manifests) {+ if (!manifest.canAdminister) {+ // A member waiting for the administrator's first push has nothing to render yet.+ continue;+ }++ const rendered = sqliteClient.executeQuery<{ Id: string }>('SELECT Id FROM Folders WHERE ManifestId = ? AND IsDeleted = 0 AND ParentFolderId IS NULL', [manifest.manifestId]);+ if (rendered.length > 0) {+ continue;+ }++ await this.render(sqliteClient, manifest.manifestId, manifest.name ?? await defaultSharedVaultName());+ devWarn(`[Sharing] Shared vault ${manifest.manifestId} had no folder; recreated it.`);+ mutated = true;+ }++ return mutated;+ },++ /**+ * The name of a shared vault is the name of the folder it is rendered as.+ * @param sqliteClient - The open local vault+ */+ displayNames(sqliteClient: SqliteClient): Record<string, string> {+ 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]));+ },+};++/**+ * The rendering mode this build ships. Every caller goes through this, so the mode is decided here and nowhere else.+ */+export const multiManifestRendering: MultiManifestRenderer = subfolderRendering;++export default multiManifestRendering;diff --git a/apps/browser-extension/src/utils/constants/storageKeys.ts b/apps/browser-extension/src/utils/constants/storageKeys.tsindex aae8de326..b09aa9724 100644--- a/apps/browser-extension/src/utils/constants/storageKeys.ts+++ b/apps/browser-extension/src/utils/constants/storageKeys.ts@@ -83,6 +83,8 @@ export const StorageKeys = {VAULT_BLOB_CIPHER_CACHE: 'local:vaultBlobCipherCache',/** Blob hashes the server has stored (refreshed on every pull/push). */VAULT_SERVER_BLOB_HASHES: 'local:vaultServerBlobHashes',+ /** Shared-vault key records (wrapped VEK grants). */+ SHARED_MANIFESTS: 'local:sharedManifests',/** -- Session state (cleared when the vault locks) --@@ -102,8 +104,6 @@ export const StorageKeys = {NAVIGATION_HISTORY: 'session:navigationHistory',/** URL of the tab the popup was opened from. */LAST_TAB_URL: 'session:lastTabUrl',- /** Shared manifest records from the last pull, needed to push shared manifests back. */- SHARED_MANIFESTS: 'session:sharedManifests',/** The item that was most recently autofilled, used to prioritize it in the list. */RECENTLY_SELECTED_ITEM: 'session:aliasvault_recently_selected_item',@@ -263,6 +263,7 @@ export const vaultDataStorageKeys = (): StorageKey[] => [StorageKeys.VAULT_BUCKET_REVISIONS,StorageKeys.VAULT_MANIFEST_SALT,StorageKeys.VAULT_PERSONAL_MANIFEST_ID,+ StorageKeys.SHARED_MANIFESTS,StorageKeys.VAULT_CONTENT_FINGERPRINTS,StorageKeys.VAULT_BLOB_CIPHER_CACHE,StorageKeys.VAULT_SERVER_BLOB_HASHES,diff --git a/apps/browser-extension/src/utils/db/repositories/FolderRepository.ts b/apps/browser-extension/src/utils/db/repositories/FolderRepository.tsindex 6fb09b0bb..ed38568dc 100644--- a/apps/browser-extension/src/utils/db/repositories/FolderRepository.ts+++ b/apps/browser-extension/src/utils/db/repositories/FolderRepository.ts@@ -1,4 +1,4 @@-import { isAnchorFolder } from '@/utils/FolderUtils';+import { multiManifestRendering } from '@/utils/MultiManifestRendering';import { t } from '@/i18n/StandaloneI18n';@@ -37,8 +37,8 @@ export class FolderRepository extends BaseRepository {* Create a new folder.* @param name - The name of the folder* @param parentFolderId - Optional parent folder ID for nested folders- * @param id - Optional explicit folder ID (used when the id must be known before creation, e.g. an anchor folder- * whose id is embedded in its server-side shared manifest); a new GUID is generated when omitted.+ * @param id - Optional explicit folder ID (used when the id must be known before creation, e.g. the folder a+ * shared manifest is rendered as); a new GUID is generated when omitted.* @returns The ID of the created folder*/public async create(name: string, parentFolderId?: string | null, id?: string): Promise<string> {@@ -239,12 +239,12 @@ export class FolderRepository extends BaseRepository {}/**- * Refuse to delete the folder a shared vault is rendered as (see {@link isAnchorFolder}).+ * Refuse to delete a folder that a shared vault is rendered as (see {@link multiManifestRendering}).* @param folderId - The folder about to be deleted*/private async assertDeletable(folderId: string): Promise<void> {const folder = this.getById(folderId);- if (folder && isAnchorFolder(folder)) {+ if (folder && multiManifestRendering.isManifestRoot(folder)) {throw new Error(await t('items.deleteSharedFolderHint'));}}@@ -265,16 +265,6 @@ export class FolderRepository extends BaseRepository {});}- /**- * Re-stamp a folder's whole subtree back into the vault's own (personal) manifest.- * @param folderId - The root of the subtree to re-stamp- * @returns The number of rows re-stamped, or 0 when the personal manifest is not registered yet- */- public async restampSubtreeToPersonal(folderId: string): Promise<number> {- const personalId = this.personalManifestId();- return personalId ? this.restampSubtree(folderId, personalId) : 0;- }-/*** Move an item to a folder.* @param itemId - The ID of the item to move