Skip to content

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

Refactor all navigation and queries to include explicit manifestId instead of attempting to resolve it (#2159)

Leendert de Borsteee67bd84a6f
diff --git a/apps/browser-extension/src/entrypoints/background.ts b/apps/browser-extension/src/entrypoints/background.ts
index 48a38e504..266df0cf6 100644
--- a/apps/browser-extension/src/entrypoints/background.ts
+++ b/apps/browser-extension/src/entrypoints/background.ts
@@ -173,12 +173,12 @@ function handleValidatedGetMatchingPasskeys(
* The trusted origin is embedded in the signed client data.
*/
function handleValidatedWebAuthnGetAssertion(
- data: { passkeyId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload },
+ data: { passkeyId: string; manifestId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload },
sender: WebAuthnMessageSender
): Promise<WebAuthnAssertionResponse> | WebAuthnAssertionResponse {
return withTrustedWebAuthnSender(
sender,
- (ctx) => typeof data?.passkeyId === 'string' && validateWebAuthnRequest('get', data, ctx.origin, ctx.host),
+ (ctx) => typeof data?.passkeyId === 'string' && typeof data?.manifestId === 'string' && validateWebAuthnRequest('get', data, ctx.origin, ctx.host),
(ctx) => handleWebAuthnGetAssertion({ ...data, origin: ctx.origin }),
{ success: false, error: 'Invalid request' }
);
diff --git a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
index 8430e5b7b..94ae05064 100644
--- a/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PasskeyHandler.ts
@@ -225,10 +225,11 @@ export async function handleGetMatchingPasskeys(
}
const options: ConditionalPasskeyOption[] = passkeys.map((pk) => {
- const item = sqliteClient.items.getById(pk.ItemId);
+ const item = sqliteClient.items.getById({ Id: pk.ItemId, ManifestId: pk.ManifestId });
return {
id: pk.Id,
itemId: pk.ItemId,
+ manifestId: pk.ManifestId,
serviceName: pk.ServiceName ?? pk.DisplayName,
username: pk.Username ?? '',
logo: item?.Logo ? Array.from(item.Logo) : null
@@ -246,18 +247,18 @@ export async function handleGetMatchingPasskeys(
* Build a WebAuthn assertion for a passkey the user picked in the inline dropdown.
*/
export async function handleWebAuthnGetAssertion(
- data: { passkeyId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload }
+ data: { passkeyId: string; manifestId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload }
): Promise<WebAuthnAssertionResponse> {
- const { passkeyId, origin, publicKey } = data;
+ const { passkeyId, manifestId, origin, publicKey } = data;
try {
const sqliteClient = await createVaultSqliteClient();
- const credential = await buildPasskeyAssertion(sqliteClient, { origin, publicKey }, passkeyId);
+ const credential = await buildPasskeyAssertion(sqliteClient, { origin, publicKey }, passkeyId, manifestId);
// Signing an assertion is a use of the item the passkey hangs off.
- const itemId = sqliteClient.passkeys.getById(passkeyId)?.ItemId;
+ const itemId = sqliteClient.passkeys.getById(passkeyId, manifestId)?.ItemId;
if (itemId) {
- void handleRecordItemUsage({ itemId, action: 'passkey' });
+ void handleRecordItemUsage({ itemId, manifestId, action: 'passkey' });
}
return { success: true, credential };
diff --git a/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts
index ffe33cae6..62ffc4afe 100644
--- a/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/PopupMessageHandler.ts
@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { setupContextMenus } from '@/entrypoints/background/ContextMenu';
+import { itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { ServiceDetectionUtility } from '@/utils/serviceDetection/ServiceDetectionUtility';
import type { BoolResponse } from '@/utils/types/messaging/BoolResponse';
@@ -26,10 +27,10 @@ export function handleOpenPopup() : Promise<BoolResponse> {
/**
* Handle opening the popup with an item.
*/
-export function handlePopupWithItem(message: any) : Promise<BoolResponse> {
+export function handlePopupWithItem(message: { itemId: string; manifestId: string }) : Promise<BoolResponse> {
return (async () : Promise<BoolResponse> => {
browser.windows.create({
- url: browser.runtime.getURL(`/popup.html?expanded=true#/items/${message.itemId}`),
+ url: browser.runtime.getURL(`/popup.html?expanded=true#${itemRoute({ Id: message.itemId, ManifestId: message.manifestId })}`),
type: 'popup',
width: 400,
height: 600,
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 48cb0c49b..a11f65b5e 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -8,6 +8,7 @@ import { MasterPasswordService } from '@aliasvault/client/auth/MasterPasswordSer
import { VaultKeyService } from '@aliasvault/client/auth/VaultKeyService';
import { EncryptionUtility } from '@aliasvault/client/crypto/EncryptionUtility';
import { decryptVaultBlob, encryptVaultBlob } from '@aliasvault/client/crypto/VaultBlob';
+import { manifestForItemIn, scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { SqliteClient } from '@aliasvault/client/database/SqliteClient';
import { generateTotpCode } from '@aliasvault/client/items/TotpUtility';
import { filterItems, AutofillMatchingMode, extractRootDomain, isUrlAlreadyLinked, generatePassword } from '@aliasvault/client/rust/RustCore';
@@ -27,6 +28,7 @@ import { handleClearTwoFactorState } from '@/entrypoints/background/TwoFactorSta
import { AUTH_STORAGE_KEYS, dirtyScopeStorageKey, SESSION_STORAGE_KEYS, StorageKeys, vaultDataStorageKeys, VAULT_LOCK_STORAGE_KEYS } from '@/utils/constants/storageKeys';
import { devLog } from '@/utils/devLogger/DevLogger';
+import { isSameItem } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessaging';
import { RecentlySelectedItemService } from '@/utils/RecentlySelectedItemService';
@@ -47,7 +49,6 @@ import type { VaultSyncState } from '@/utils/types/messaging/VaultSyncState';
import { t } from '@/i18n/StandaloneI18n';
import type { ItemUsageAction } from '@aliasvault/client/database';
-import type { DraftItem } from '@aliasvault/client/database/ItemRef';
import type { ISqliteDatabase, SqliteValue } from '@aliasvault/client/platform';
import type { UnlockKeyDerivationParams } from '@aliasvault/models/metadata';
@@ -345,21 +346,21 @@ function filterItemsByUrl(items: Item[], currentUrl: string, pageTitle: string,
* @param items - The filtered items array
* @param rootDomain - The current root domain for recently selected item validation
* @param allItems - All items from the vault (to fetch recently selected if not in filtered)
- * @returns The items (with recently selected prioritized) and the matched id, if any
+ * @returns The items (with recently selected prioritized) and the matched item, if any
*/
async function prioritizeRecentlySelectedItem(
items: Item[],
rootDomain: string,
allItems: Item[]
-): Promise<{ items: Item[], recentlySelectedId: string | null }> {
- const recentlySelectedId = await RecentlySelectedItemService.getRecentlySelected(rootDomain);
+): Promise<{ items: Item[], recentlySelected: ItemRef | null }> {
+ const recentlySelected = await RecentlySelectedItemService.getRecentlySelected(rootDomain);
- if (!recentlySelectedId) {
- return { items, recentlySelectedId: null };
+ if (!recentlySelected) {
+ return { items, recentlySelected: null };
}
// Find the recently selected item in the filtered results
- const recentlySelectedIndex = items.findIndex(item => item.Id === recentlySelectedId);
+ const recentlySelectedIndex = items.findIndex(item => isSameItem(item, recentlySelected));
if (recentlySelectedIndex !== -1) {
// Item is already in filtered results - move it to the front
@@ -369,19 +370,19 @@ async function prioritizeRecentlySelectedItem(
...items.slice(0, recentlySelectedIndex),
...items.slice(recentlySelectedIndex + 1)
];
- return { items: reorderedItems, recentlySelectedId };
+ return { items: reorderedItems, recentlySelected };
}
// Item is not in filtered results - fetch it from all items and prepend it
- const recentlySelectedItem = allItems.find(item => item.Id === recentlySelectedId);
+ const recentlySelectedItem = allItems.find(item => isSameItem(item, recentlySelected));
if (!recentlySelectedItem) {
// Item not found in vault (might have been deleted)
- return { items, recentlySelectedId: null };
+ return { items, recentlySelected: null };
}
// Prepend the recently selected item to the filtered results
- return { items: [recentlySelectedItem, ...items], recentlySelectedId };
+ return { items: [recentlySelectedItem, ...items], recentlySelected };
}
/**
@@ -474,7 +475,7 @@ export async function handleGetFilteredItems(
if (message.includeRecentlySelected) {
const rootDomain = await extractRootDomainFromUrl(message.currentUrl);
const prioritized = await prioritizeRecentlySelectedItem(filteredItems, rootDomain, allItems);
- return { success: true, items: prioritized.items, recentlySelectedId: prioritized.recentlySelectedId };
+ return { success: true, items: prioritized.items, recentlySelected: prioritized.recentlySelected };
}
return { success: true, items: filteredItems };
@@ -1015,12 +1016,7 @@ export async function handleCheckLoginDuplicate(
const itemEmail = (typeof emailValue === 'string' ? emailValue : '').toLowerCase();
if (itemUsername === normalizedUsername || itemEmail === normalizedUsername) {
- return {
- success: true,
- isDuplicate: true,
- matchingItemId: item.Id,
- matchingItemName: item.Name ?? undefined
- };
+ return { success: true, isDuplicate: true };
}
}
@@ -1100,8 +1096,9 @@ export async function handleSaveLoginCredential(
}
// Create the new item
- const newItem: DraftItem = {
+ const newItem: Item = {
Id: '', // Will be generated by SQLite
+ ManifestId: manifestForItemIn(null, sqliteClient.getPersonalManifestId()),
Name: message.serviceName || message.domain,
ItemType: ItemTypes.Login,
Logo: logo,
@@ -1111,12 +1108,12 @@ export async function handleSaveLoginCredential(
};
// Add the item to the vault
- await sqliteClient.items.create(newItem, [], []);
+ const created = await sqliteClient.items.create(newItem, [], []);
// Persist locally and sync in the background (doesn't block when server is offline).
await persistLocalVaultMutation(sqliteClient, encryptionKey);
- return { success: true, itemId: newItem.Id };
+ return { success: true, itemId: created.Id, manifestId: created.ManifestId };
} catch (error) {
console.error('Failed to save login credential:', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_CREATE_FAILED) };
@@ -1131,7 +1128,7 @@ export async function handleSaveLoginCredential(
* @param message - The item ID and URL to add.
* @returns Success status.
*/
-export async function handleAddUrlToCredential(message: { itemId: string; url: string }): Promise<{ success: boolean; error?: string }> {
+export async function handleAddUrlToCredential(message: { itemId: string; manifestId: string; url: string }): Promise<{ success: boolean; error?: string }> {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
@@ -1143,7 +1140,7 @@ export async function handleAddUrlToCredential(message: { itemId: string; url: s
const url = ServiceDetectionUtility.sanitizeUrl(message.url) || message.url;
// Get the existing item
- const item = sqliteClient.items.getById(message.itemId);
+ const item = sqliteClient.items.getById({ Id: message.itemId, ManifestId: message.manifestId });
if (!item) {
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
}
@@ -1179,7 +1176,7 @@ export async function handleAddUrlToCredential(message: { itemId: string; url: s
item.UpdatedAt = new Date().toISOString();
// Update the item in the vault
- await sqliteClient.items.update(item, [], [], [], []);
+ await sqliteClient.items.update({ Id: item.Id, ManifestId: item.ManifestId }, item, [], [], [], []);
// Persist locally and sync in the background (doesn't block when server is offline).
await persistLocalVaultMutation(sqliteClient, encryptionKey);
@@ -1194,14 +1191,14 @@ export async function handleAddUrlToCredential(message: { itemId: string; url: s
/**
* Check whether a URL is already linked (host-equivalent) to a credential.
*/
-export async function handleIsUrlLinkedToCredential(message: { itemId: string; url: string }): Promise<{ linked: boolean }> {
+export async function handleIsUrlLinkedToCredential(message: { itemId: string; manifestId: string; url: string }): Promise<{ linked: boolean }> {
try {
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
return { linked: false };
}
const sqliteClient = await createVaultSqliteClient();
- const item = sqliteClient.items.getById(message.itemId);
+ const item = sqliteClient.items.getById({ Id: message.itemId, ManifestId: message.manifestId });
if (!item) {
return { linked: false };
}
@@ -1328,7 +1325,7 @@ export async function handleGetItemsWithTotp(
const rootDomain = await extractRootDomainFromUrl(message.currentUrl);
const prioritized = await prioritizeRecentlySelectedItem(filteredItems, rootDomain, itemsWithTotp);
- return { success: true, items: prioritized.items, recentlySelectedId: prioritized.recentlySelectedId };
+ return { success: true, items: prioritized.items, recentlySelected: prioritized.recentlySelected };
} catch (error) {
console.error('Error getting items with TOTP:', error);
return { success: false, error: formatErrorWithCode(await t('common.errors.unknownError'), AppErrorCode.ITEM_READ_FAILED) };
@@ -1371,10 +1368,10 @@ export async function handleSearchItemsWithTotp(
* Get TOTP secret keys for items.
* Used by content script to generate codes locally for live preview.
*
- * @param message - Array of item IDs to get TOTP secrets for
+ * @param message - The items to get TOTP secrets for; the result is keyed by `scopedKey(ManifestId, Id)`
*/
export async function handleGetTotpSecrets(
- message: { itemIds: string[] }
+ message: { items: ItemRef[] }
): Promise<{ success: boolean; secrets?: Record<string, TotpSecret>; error?: string }> {
const encryptionKey = await handleGetEncryptionKey();
@@ -1386,11 +1383,11 @@ export async function handleGetTotpSecrets(
const sqliteClient = await createVaultSqliteClient();
const secrets: Record<string, TotpSecret> = {};
- for (const itemId of message.itemIds) {
- const totpCodes = sqliteClient.items.getTotpCodesForItem(itemId);
+ for (const item of message.items) {
+ const totpCodes = sqliteClient.items.getTotpCodesForItem(item);
if (totpCodes.length > 0) {
const totpCode = totpCodes[0];
- secrets[itemId] = {
+ secrets[scopedKey(item.ManifestId, item.Id)] = {
SecretKey: totpCode.SecretKey,
Algorithm: totpCode.Algorithm,
Digits: totpCode.Digits,
@@ -1413,7 +1410,7 @@ export async function handleGetTotpSecrets(
* @param message - The item ID to generate TOTP code for
*/
export async function handleGenerateTotpCode(
- message: { itemId: string }
+ message: { itemId: string; manifestId: string }
): Promise<{ success: boolean; code?: string; error?: string }> {
const encryptionKey = await handleGetEncryptionKey();
@@ -1423,7 +1420,7 @@ export async function handleGenerateTotpCode(
try {
const sqliteClient = await createVaultSqliteClient();
- const totpCodes = sqliteClient.items.getTotpCodesForItem(message.itemId);
+ const totpCodes = sqliteClient.items.getTotpCodesForItem({ Id: message.itemId, ManifestId: message.manifestId });
if (totpCodes.length === 0) {
return { success: false, error: 'No TOTP codes found for this item' };
@@ -1446,7 +1443,7 @@ export async function handleGenerateTotpCode(
* @param message - The item that was used and what was done with it.
*/
export async function handleRecordItemUsage(
- message: { itemId: string; action: ItemUsageAction }
+ message: { itemId: string; manifestId: string; action: ItemUsageAction }
): Promise<{ success: boolean }> {
try {
const encryptionKey = await handleGetEncryptionKey();
@@ -1455,7 +1452,7 @@ export async function handleRecordItemUsage(
}
const sqliteClient = await createVaultSqliteClient();
- if (!sqliteClient.itemStats.recordUsage(message.itemId, message.action)) {
+ if (!sqliteClient.itemStats.recordUsage({ Id: message.itemId, ManifestId: message.manifestId }, message.action)) {
// No such item (deleted between use and record); nothing to attribute the use to.
return { success: false };
}
@@ -1472,11 +1469,11 @@ export async function handleRecordItemUsage(
* Set recently selected item for smart autofill.
*/
export async function handleSetRecentlySelected(
- message: { itemId: string; domain: string }
+ message: { itemId: string; manifestId: string; domain: string }
): Promise<{ success: boolean }> {
try {
const rootDomain = await extractRootDomain(message.domain);
- await RecentlySelectedItemService.setRecentlySelected(message.itemId, rootDomain);
+ await RecentlySelectedItemService.setRecentlySelected({ Id: message.itemId, ManifestId: message.manifestId }, rootDomain);
return { success: true };
} catch (error) {
console.error('Error setting recently selected item:', error);
@@ -1489,11 +1486,11 @@ export async function handleSetRecentlySelected(
*/
export async function handleGetRecentlySelected(
message: { domain: string }
-): Promise<{ success: boolean; itemId?: string | null }> {
+): Promise<{ success: boolean; itemId?: string | null; manifestId?: string | null }> {
try {
const rootDomain = await extractRootDomain(message.domain);
- const itemId = await RecentlySelectedItemService.getRecentlySelected(rootDomain);
- return { success: true, itemId };
+ const item = await RecentlySelectedItemService.getRecentlySelected(rootDomain);
+ return { success: true, itemId: item?.Id ?? null, manifestId: item?.ManifestId ?? null };
} catch (error) {
console.error('Error getting recently selected item:', error);
return { success: false, itemId: null };
diff --git a/apps/browser-extension/src/entrypoints/content.ts b/apps/browser-extension/src/entrypoints/content.ts
index e1338cf6b..36285a311 100644
--- a/apps/browser-extension/src/entrypoints/content.ts
+++ b/apps/browser-extension/src/entrypoints/content.ts
@@ -25,6 +25,7 @@ import { getDeepActiveElement, getDeepElementById, getDeepEventTarget } from '@/
import { t } from '@/i18n/StandaloneI18n';
import { extensionPlatform } from '@/platform/ExtensionPlatform';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
import type { Item } from '@aliasvault/models/vault';
import { defineContentScript, createShadowRootUi, storage } from '#imports';
@@ -116,13 +117,14 @@ async function handleSavePromptDismiss(): Promise<void> {
/**
* Handle adding URL to an existing credential.
- * @param itemId - The ID of the credential to add the URL to.
+ * @param item - The credential to add the URL to, named by its manifest and id.
* @param url - The URL to add.
*/
-async function handleAddUrlToCredential(itemId: string, url: string): Promise<void> {
+async function handleAddUrlToCredential(item: ItemRef, url: string): Promise<void> {
try {
const response = await sendMessage('ADD_URL_TO_CREDENTIAL', {
- itemId,
+ itemId: item.Id,
+ manifestId: item.ManifestId,
url,
});
@@ -423,6 +425,7 @@ function initializeLoginDetector(container: HTMLElement): void {
*/
const linkCheck = await sendMessage('IS_URL_LINKED_TO_CREDENTIAL', {
itemId: lastAutofilledResponse.credential.itemId,
+ manifestId: lastAutofilledResponse.credential.manifestId,
url: login.url,
});
diff --git a/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts b/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts
index 74b09c11b..6a8543f9f 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/ConditionalPasskey.ts
@@ -138,9 +138,10 @@ export function clearConditionalPasskeyRequestIfMatches(requestId: string): bool
* Signs in the background, resolves the page's pending `get()` promise, and clears state.
*
* @param passkeyId - The vault ID of the selected passkey.
+ * @param manifestId - The manifest that passkey belongs to.
* @returns true when an assertion was produced and returned to the page.
*/
-export async function completeConditionalWithPasskey(passkeyId: string): Promise<boolean> {
+export async function completeConditionalWithPasskey(passkeyId: string, manifestId: string): Promise<boolean> {
const request = pendingRequest;
if (!request) {
return false;
@@ -152,6 +153,7 @@ export async function completeConditionalWithPasskey(passkeyId: string): Promise
try {
const result = await sendMessage('WEBAUTHN_GET_ASSERTION', {
passkeyId,
+ manifestId,
origin: request.origin,
publicKey: request.publicKey as unknown as WebAuthnPublicKeyGetPayload
});
@@ -160,9 +162,9 @@ export async function completeConditionalWithPasskey(passkeyId: string): Promise
/*
* Copy the linked TOTP code to the clipboard (if any).
*/
- const selected = request.passkeys.find((passkey) => passkey.id === passkeyId);
+ const selected = request.passkeys.find((passkey) => passkey.id === passkeyId && passkey.manifestId === manifestId);
if (selected) {
- await copyTotpToClipboardIfEnabled(selected.itemId);
+ await copyTotpToClipboardIfEnabled({ Id: selected.itemId, ManifestId: selected.manifestId });
}
request.respond({ requestId: request.requestId, credential: result.credential });
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Form.ts b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
index 85118d9d2..18793ab41 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/Form.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/Form.ts
@@ -12,6 +12,7 @@ import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { ClickValidator } from '@/utils/security/ClickValidator';
import { copyTotpToClipboardIfEnabled } from '@/utils/TotpClipboard';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
import type { Item } from '@aliasvault/models/vault';
/**
@@ -131,6 +132,7 @@ export async function fillItem(item: Item, input: HTMLInputElement): Promise<voi
const lastAutofilled: LastAutofilledCredential = {
itemId: item.Id,
+ manifestId: item.ManifestId,
itemName: item.Name || '',
username,
domain: window.location.hostname,
@@ -143,17 +145,17 @@ export async function fillItem(item: Item, input: HTMLInputElement): Promise<voi
});
// Store recently selected item for smart autofill prioritization
- sendMessage('SET_RECENTLY_SELECTED', { itemId: item.Id, domain: window.location.hostname }).catch(() => {
+ sendMessage('SET_RECENTLY_SELECTED', { itemId: item.Id, manifestId: item.ManifestId, domain: window.location.hostname }).catch(() => {
// Ignore errors
});
// Record the use in the vault's Stats bucket (last used + counts).
- sendMessage('RECORD_ITEM_USAGE', { itemId: item.Id, action: 'autofill' }).catch(() => {
+ sendMessage('RECORD_ITEM_USAGE', { itemId: item.Id, manifestId: item.ManifestId, action: 'autofill' }).catch(() => {
// Ignore errors
});
// Auto-copy TOTP to clipboard if enabled and item has TOTP after autofill.
- await copyTotpToClipboardIfEnabled(item.Id);
+ await copyTotpToClipboardIfEnabled(item);
}
/**
@@ -412,10 +414,10 @@ export function injectIcon(input: HTMLInputElement, container: HTMLElement, fiel
* Fill TOTP code into the input field.
* Generates the code via background script and fills it.
*
- * @param itemId - The item ID to generate TOTP code for.
+ * @param item - The item to generate the TOTP code for, named by its manifest and id.
* @param input - The input element to fill the TOTP code into.
*/
-export async function fillTotpCode(itemId: string, input: HTMLInputElement): Promise<void> {
+export async function fillTotpCode(item: ItemRef, input: HTMLInputElement): Promise<void> {
// Set debounce time to 300ms to prevent the popup from being shown again within 300ms because of autofill events.
hidePopupFor(300);
@@ -425,7 +427,7 @@ export async function fillTotpCode(itemId: string, input: HTMLInputElement): Pro
});
// Generate TOTP code via background
- const response = await sendMessage('GENERATE_TOTP_CODE', { itemId });
+ const response = await sendMessage('GENERATE_TOTP_CODE', { itemId: item.Id, manifestId: item.ManifestId });
if (!response.success || !response.code) {
console.error('Failed to generate TOTP code:', response.error);
@@ -439,12 +441,12 @@ export async function fillTotpCode(itemId: string, input: HTMLInputElement): Pro
triggerInputEvents(input);
// Store recently selected item for smart autofill prioritization
- sendMessage('SET_RECENTLY_SELECTED', { itemId, domain: window.location.hostname }).catch(() => {
+ sendMessage('SET_RECENTLY_SELECTED', { itemId: item.Id, manifestId: item.ManifestId, domain: window.location.hostname }).catch(() => {
// Ignore errors as background script might not be ready
});
// Record the use in the vault's Stats bucket (last used + counts).
- sendMessage('RECORD_ITEM_USAGE', { itemId, action: 'autofill' }).catch(() => {
+ sendMessage('RECORD_ITEM_USAGE', { itemId: item.Id, manifestId: item.ManifestId, action: 'autofill' }).catch(() => {
// Ignore errors as background script might not be ready
});
}
diff --git a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
index 59f659c56..bba485ea3 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/Popup.ts
@@ -1,3 +1,4 @@
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
import { SqliteClient } from '@aliasvault/client/database/SqliteClient';
import { generateTotpCode, getTotpRemainingSeconds } from '@aliasvault/client/items/TotpUtility';
import { ItemTypeIconSvgs } from '@aliasvault/models/icons';
@@ -5,6 +6,7 @@ import { FieldKey, getFieldValue, normalizeTotpPeriod } from '@aliasvault/models
import { fillItem, fillTotpCode } from '@/entrypoints/contentScript/Form';
+import { isSameItem } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage, type TotpSecret } from '@/utils/messaging/ExtensionMessaging';
import { ClickValidator } from '@/utils/security/ClickValidator';
@@ -15,6 +17,7 @@ import { t } from '@/i18n/StandaloneI18n';
import { getCurrentAutofillFrameUrl } from './AutofillFrameUrl';
import { completeConditionalWithPasskey, getConditionalPasskeyOptions, hasPendingConditionalRequest } from './ConditionalPasskey';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
import type { Item } from '@aliasvault/models/vault';
/**
@@ -160,7 +163,7 @@ export function openAutofillPopup(input: HTMLInputElement, container: HTMLElemen
});
if (response.success) {
- await createAutofillPopup(input, response.items, container, response.recentlySelectedId);
+ await createAutofillPopup(input, response.items, container, response.recentlySelected);
} else {
// Check if the user has dismissed the vault locked popup (only for auto-show, not manual clicks)
if (!forceShow) {
@@ -216,7 +219,7 @@ export function openTotpPopup(input: HTMLInputElement, container: HTMLElement, f
});
if (response.success) {
- await createTotpPopup(input, response.items, container, response.recentlySelectedId);
+ await createTotpPopup(input, response.items, container, response.recentlySelected);
} else {
// Check if the user has dismissed the vault locked popup (only for auto-show, not manual clicks)
if (!forceShow) {
@@ -237,7 +240,7 @@ export function openTotpPopup(input: HTMLInputElement, container: HTMLElement, f
* Create TOTP autofill popup showing items with 2FA codes.
* Matches the styling of the regular autofill popup.
*/
-async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefined, rootContainer: HTMLElement, recentlySelectedId?: string | null) : Promise<void> {
+async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefined, rootContainer: HTMLElement, recentlySelected?: ItemRef | null) : Promise<void> {
const searchPlaceholder = await t('content.searchVault');
const hideFor1HourText = await t('content.hideFor1Hour');
const hidePermanentlyText = await t('content.hidePermanently');
@@ -256,7 +259,7 @@ async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefine
items = [];
}
- updateTotpPopupContent(items, credentialList, input, rootContainer, noTotpItemsText, recentlySelectedId);
+ updateTotpPopupContent(items, credentialList, input, rootContainer, noTotpItemsText, recentlySelected);
// Add divider
const divider = document.createElement('div');
@@ -286,7 +289,7 @@ async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefine
if (searchTerm === '') {
// If search is empty, show the initially URL-filtered items
- updateTotpPopupContent(items, credentialList, input, rootContainer, noTotpItemsText, recentlySelectedId);
+ updateTotpPopupContent(items, credentialList, input, rootContainer, noTotpItemsText, recentlySelected);
} else {
// Search in TOTP items only
const response = await sendMessage('SEARCH_ITEMS_WITH_TOTP', {
@@ -298,7 +301,7 @@ async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefine
updateTotpPopupContent(response.items, credentialList, input, rootContainer, noTotpItemsText);
} else {
// On error, fallback to showing initial filtered items
- updateTotpPopupContent(items, credentialList, input, rootContainer, noTotpItemsText, recentlySelectedId);
+ updateTotpPopupContent(items, credentialList, input, rootContainer, noTotpItemsText, recentlySelected);
}
}
});
@@ -420,7 +423,7 @@ async function createTotpPopup(input: HTMLInputElement, items: Item[] | undefine
* @param rootContainer - The root container element.
* @param noMatchesText - Text to show when no items match.
*/
-function updateTotpPopupContent(items: Item[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelectedId?: string | null) : void {
+function updateTotpPopupContent(items: Item[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : void {
if (!itemList) {
itemList = document.getElementById('aliasvault-credential-list') as HTMLElement;
}
@@ -445,8 +448,7 @@ function updateTotpPopupContent(items: Item[], itemList: HTMLElement | null, inp
// Fetch TOTP secrets and create items with live codes
(async (): Promise<void> => {
- const itemIds = items.map(item => item.Id);
- const secretsResponse = await sendMessage('GET_TOTP_SECRETS', { itemIds });
+ const secretsResponse = await sendMessage('GET_TOTP_SECRETS', { items: items.map(item => ({ Id: item.Id, ManifestId: item.ManifestId })) });
const secrets = secretsResponse.success && secretsResponse.secrets ? secretsResponse.secrets : {};
const hasSecrets = Object.keys(secrets).length > 0;
@@ -455,8 +457,8 @@ function updateTotpPopupContent(items: Item[], itemList: HTMLElement | null, inp
const codeElements: Map<string, { codeSpan: HTMLSpanElement; pieChart: SVGPathElement }> = new Map();
items.forEach(item => {
- const secret = secrets[item.Id];
- const isRecentlySelected = recentlySelectedId != null && item.Id === recentlySelectedId;
+ const secret = secrets[scopedKey(item.ManifestId, item.Id)];
+ const isRecentlySelected = recentlySelected != null && isSameItem(item, recentlySelected);
const itemElement = createTotpItem(item, secret, input, rootContainer, hasSecrets ? codeElements : undefined, isRecentlySelected);
itemList!.appendChild(itemElement);
});
@@ -509,8 +511,8 @@ function updateTotpCodes(
codeElements: Map<string, { codeSpan: HTMLSpanElement; pieChart: SVGPathElement }>,
secrets: Record<string, TotpSecret>
): void {
- codeElements.forEach((elements, itemId) => {
- const secret = secrets[itemId];
+ codeElements.forEach((elements, itemKey) => {
+ const secret = secrets[itemKey];
if (secret) {
elements.codeSpan.textContent = formatTotpCodeForSecret(secret);
}
@@ -601,15 +603,15 @@ function createTotpItem(
// Store references for live updates (only if secret exists and codeElements provided)
if (secret && codeElements) {
- codeElements.set(item.Id, { codeSpan, pieChart });
+ codeElements.set(scopedKey(item.ManifestId, item.Id), { codeSpan, pieChart });
}
itemElement.appendChild(itemInfo);
- itemElement.appendChild(createPopoutIcon(item.Id, rootContainer));
+ itemElement.appendChild(createPopoutIcon(item, rootContainer));
// Handle click to fill TOTP code
addReliableClickHandler(itemInfo, async () => {
- await fillTotpCode(item.Id, input);
+ await fillTotpCode(item, input);
removeExistingPopup(rootContainer);
});
@@ -729,7 +731,7 @@ export function createLoadingPopup(input: HTMLInputElement, message: string, roo
* @param itemList - The item list element.
* @param input - The input element that triggered the popup. Required when filling items to know which form to fill.
*/
-export async function updatePopupContent(items: Item[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelectedId?: string | null) : Promise<void> {
+export async function updatePopupContent(items: Item[], itemList: HTMLElement | null, input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : Promise<void> {
if (!itemList) {
itemList = document.getElementById('aliasvault-credential-list') as HTMLElement;
}
@@ -742,7 +744,7 @@ export async function updatePopupContent(items: Item[], itemList: HTMLElement |
itemList.innerHTML = '';
// Add items using the shared function
- const itemElements = createItemList(items, input, rootContainer, noMatchesText, recentlySelectedId);
+ const itemElements = createItemList(items, input, rootContainer, noMatchesText, recentlySelected);
itemElements.forEach(element => itemList.appendChild(element));
}
@@ -814,7 +816,7 @@ function hasFillableLoginField(item: Item): boolean {
/**
* Create auto-fill popup
*/
-export async function createAutofillPopup(input: HTMLInputElement, items: Item[] | undefined, rootContainer: HTMLElement, recentlySelectedId?: string | null) : Promise<void> {
+export async function createAutofillPopup(input: HTMLInputElement, items: Item[] | undefined, rootContainer: HTMLElement, recentlySelected?: ItemRef | null) : Promise<void> {
// Remember the input so a credential created in the full popup window can be filled back here.
lastAutofillInput = input;
@@ -848,7 +850,7 @@ export async function createAutofillPopup(input: HTMLInputElement, items: Item[]
// Drop entries that have nothing to fill (no username/email/password) - they're not useful matches.
items = items.filter(hasFillableLoginField);
- await updatePopupContent(items, credentialList, input, rootContainer, noMatchesText, recentlySelectedId);
+ await updatePopupContent(items, credentialList, input, rootContainer, noMatchesText, recentlySelected);
// Add divider
const divider = document.createElement('div');
@@ -918,7 +920,7 @@ export async function createAutofillPopup(input: HTMLInputElement, items: Item[]
// Handle search input.
let searchTimeout: NodeJS.Timeout | null = null;
searchInput.addEventListener('input', async () => {
- await handleSearchInput(searchInput, items, rootContainer, searchTimeout, credentialList, input, noMatchesText, recentlySelectedId);
+ await handleSearchInput(searchInput, items, rootContainer, searchTimeout, credentialList, input, noMatchesText, recentlySelected);
});
// Close button
@@ -1195,7 +1197,7 @@ export async function createVaultLockedPopup(input: HTMLInputElement, rootContai
* @param input - The input field that triggered the popup
* @param noMatchesText - Text to show when no matches found
*/
-async function handleSearchInput(searchInput: HTMLInputElement, initialItems: Item[], rootContainer: HTMLElement, searchTimeout: NodeJS.Timeout | null, itemList: HTMLElement | null, input: HTMLInputElement, noMatchesText?: string, recentlySelectedId?: string | null) : Promise<void> {
+async function handleSearchInput(searchInput: HTMLInputElement, initialItems: Item[], rootContainer: HTMLElement, searchTimeout: NodeJS.Timeout | null, itemList: HTMLElement | null, input: HTMLInputElement, noMatchesText?: string, recentlySelected?: ItemRef | null) : Promise<void> {
if (searchTimeout) {
clearTimeout(searchTimeout);
}
@@ -1204,7 +1206,7 @@ async function handleSearchInput(searchInput: HTMLInputElement, initialItems: It
if (searchTerm === '') {
// If search is empty, show the initially URL-filtered items with the recently-used star restored
- await updatePopupContent(initialItems, itemList, input, rootContainer, noMatchesText, recentlySelectedId);
+ await updatePopupContent(initialItems, itemList, input, rootContainer, noMatchesText, recentlySelected);
} else {
// Search in full vault with search term
const response = await sendMessage('GET_SEARCH_ITEMS', {
@@ -1217,7 +1219,7 @@ async function handleSearchInput(searchInput: HTMLInputElement, initialItems: It
await updatePopupContent(fillableItems, itemList, input, rootContainer, noMatchesText);
} else {
// On error, fallback to showing initial filtered items
- await updatePopupContent(initialItems, itemList, input, rootContainer, noMatchesText, recentlySelectedId);
+ await updatePopupContent(initialItems, itemList, input, rootContainer, noMatchesText, recentlySelected);
}
}
}
@@ -1268,7 +1270,7 @@ function createLogoContainer(logo: Uint8Array | number[] | undefined): HTMLEleme
/**
* Build popout icon shown at the trailing edge of a row, which opens the underlying item in the full extension popup.
*/
-function createPopoutIcon(itemId: string, rootContainer: HTMLElement): HTMLElement {
+function createPopoutIcon(item: ItemRef, rootContainer: HTMLElement): HTMLElement {
const popoutIcon = document.createElement('div');
popoutIcon.className = 'av-popout-icon';
popoutIcon.innerHTML = `
@@ -1281,7 +1283,7 @@ function createPopoutIcon(itemId: string, rootContainer: HTMLElement): HTMLEleme
addReliableClickHandler(popoutIcon, (e) => {
e.stopPropagation(); // Don't trigger the row's primary action.
- sendMessage('OPEN_POPUP_WITH_ITEM', { itemId });
+ sendMessage('OPEN_POPUP_WITH_ITEM', { itemId: item.Id, manifestId: item.ManifestId });
removeExistingPopup(rootContainer);
});
@@ -1356,14 +1358,14 @@ async function createPasskeySection(rootContainer: HTMLElement): Promise<{ list:
itemElement.appendChild(itemInfo);
// Popout icon opens the underlying credential in the full extension popup.
- itemElement.appendChild(createPopoutIcon(option.itemId, rootContainer));
+ itemElement.appendChild(createPopoutIcon({ Id: option.itemId, ManifestId: option.manifestId }, rootContainer));
addReliableClickHandler(itemInfo, () => {
// Explicit user action - keep the vault from auto-locking mid-assertion.
sendMessage('RESET_AUTO_LOCK_TIMER').catch(() => {
// Ignore: background may be asleep.
});
- void completeConditionalWithPasskey(option.id);
+ void completeConditionalWithPasskey(option.id, option.manifestId);
removeExistingPopup(rootContainer);
});
@@ -1394,7 +1396,7 @@ function createViewSwitchPill(label: string): HTMLButtonElement {
* @param items - The items to display.
* @param input - The input element that triggered the popup. Required when filling items to know which form to fill.
*/
-function createItemList(items: Item[], input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelectedId?: string | null): HTMLElement[] {
+function createItemList(items: Item[], input: HTMLInputElement, rootContainer: HTMLElement, noMatchesText?: string, recentlySelected?: ItemRef | null): HTMLElement[] {
const elements: HTMLElement[] = [];
if (items.length > 0) {
@@ -1425,7 +1427,7 @@ function createItemList(items: Item[], input: HTMLInputElement, rootContainer: H
serviceNameContainer.appendChild(serviceNameText);
// Add "recently used" indicator if this item was the last autofill on this site
- if (recentlySelectedId != null && item.Id === recentlySelectedId) {
+ if (recentlySelected != null && isSameItem(item, recentlySelected)) {
serviceNameContainer.appendChild(createRecentlySelectedIcon());
}
@@ -1463,7 +1465,7 @@ function createItemList(items: Item[], input: HTMLInputElement, rootContainer: H
itemInfo.appendChild(itemTextContainer);
itemElement.appendChild(itemInfo);
- itemElement.appendChild(createPopoutIcon(item.Id, rootContainer));
+ itemElement.appendChild(createPopoutIcon(item, rootContainer));
// Update click handler to only trigger on itemInfo with security validation
addReliableClickHandler(itemInfo, () => {
diff --git a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
index 57d88b5f3..092878a79 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/SavePrompt.ts
@@ -9,6 +9,8 @@ import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { t } from '@/i18n/StandaloneI18n';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+
/** Reference to the current save prompt element */
let currentPrompt: HTMLElement | null = null;
@@ -400,7 +402,7 @@ export async function restoreSavePromptFromState(
export async function restoreAddUrlPromptFromState(
container: HTMLElement,
state: SavePromptPersistedState,
- onAddUrl: (itemId: string, url: string) => void,
+ onAddUrl: (item: ItemRef, url: string) => void,
onDismiss: () => void
): Promise<void> {
// Clear the persisted state now that we're restoring
@@ -932,8 +934,8 @@ async function createAddUrlPromptHTML(login: CapturedLogin, existingCredential:
function setupAddUrlEventListeners(
prompt: HTMLElement,
login: CapturedLogin,
- existingCredential: { itemId: string; itemName: string },
- onAddUrl: (itemId: string, url: string) => void,
+ existingCredential: { itemId: string; manifestId: string; itemName: string },
+ onAddUrl: (item: ItemRef, url: string) => void,
onDismiss: () => void
): void {
const addUrlBtn = prompt.querySelector('.av-save-prompt__btn--add-url');
@@ -942,7 +944,7 @@ function setupAddUrlEventListeners(
addUrlBtn?.addEventListener('click', () => {
const loginToUse = currentLogin || login;
removeSavePrompt();
- onAddUrl(existingCredential.itemId, loginToUse.url);
+ onAddUrl({ Id: existingCredential.itemId, ManifestId: existingCredential.manifestId }, loginToUse.url);
});
dismissBtn?.addEventListener('click', () => {
diff --git a/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts b/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts
index ec7468114..f07f31003 100644
--- a/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts
+++ b/apps/browser-extension/src/entrypoints/contentScript/__tests__/ConditionalPasskey.test.ts
@@ -19,7 +19,7 @@ import {
} from '../ConditionalPasskey';
const OPTIONS: ConditionalPasskeyOption[] = [
- { id: 'pk-1', itemId: 'item-1', serviceName: 'Example', username: '[email protected]', logo: null }
+ { id: 'pk-1', itemId: 'item-1', manifestId: 'manifest-1', serviceName: 'Example', username: '[email protected]', logo: null }
];
/**
@@ -142,11 +142,12 @@ describe('ConditionalPasskey bridge', () => {
const { request, respond } = buildRequest();
registerConditionalPasskeyRequest(request);
- const result = await completeConditionalWithPasskey('pk-1');
+ const result = await completeConditionalWithPasskey('pk-1', 'manifest-1');
expect(result).toBe(true);
expect(sendMessageMock).toHaveBeenCalledWith('WEBAUTHN_GET_ASSERTION', {
passkeyId: 'pk-1',
+ manifestId: 'manifest-1',
origin: 'https://example.com',
publicKey: { challenge: 'Y2hhbGxlbmdl' }
});
@@ -161,7 +162,7 @@ describe('ConditionalPasskey bridge', () => {
const { request, respond } = buildRequest();
registerConditionalPasskeyRequest(request);
- const result = await completeConditionalWithPasskey('pk-1');
+ const result = await completeConditionalWithPasskey('pk-1', 'manifest-1');
expect(result).toBe(false);
expect(respond).toHaveBeenCalledWith({ requestId: 'req-1', error: 'boom' });
@@ -169,7 +170,7 @@ describe('ConditionalPasskey bridge', () => {
});
it('does nothing when there is no pending request', async () => {
- const result = await completeConditionalWithPasskey('pk-1');
+ const result = await completeConditionalWithPasskey('pk-1', 'manifest-1');
expect(result).toBe(false);
expect(sendMessageMock).not.toHaveBeenCalled();
diff --git a/apps/browser-extension/src/entrypoints/popup/App.tsx b/apps/browser-extension/src/entrypoints/popup/App.tsx
index 5a0326cc4..7693ef4c3 100644
--- a/apps/browser-extension/src/entrypoints/popup/App.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/App.tsx
@@ -196,12 +196,12 @@ const App: React.FC = () => {
{ path: '/upgrade', element: <Upgrade />, showBackButton: false },
{ path: '/auth-settings', element: <AuthSettings />, showBackButton: true, title: t('common.settings') },
{ path: '/items', element: <ItemsList />, showBackButton: false },
- { path: '/items/folder/:folderId', element: <ItemsList />, showBackButton: true },
+ { path: '/items/folder/:manifestId/:folderId', element: <ItemsList />, showBackButton: true },
{ path: '/items/select-type', element: <ItemTypeSelector />, showBackButton: true, title: t('itemTypes.selectType') },
{ path: '/items/add', element: <ItemAddEdit />, showBackButton: true },
{ path: '/items/deleted', element: <RecentlyDeleted />, showBackButton: true, title: t('recentlyDeleted.title') },
- { path: '/items/:id/edit', element: <ItemAddEdit />, showBackButton: true },
- { path: '/items/:id', element: <ItemDetails />, showBackButton: true },
+ { path: '/items/:manifestId/:id/edit', element: <ItemAddEdit />, showBackButton: true },
+ { path: '/items/:manifestId/:id', element: <ItemDetails />, showBackButton: true },
{ path: '/passkeys/create', element: <PasskeyCreate />, layout: LayoutType.PASSKEY },
{ path: '/passkeys/authenticate', element: <PasskeyAuthenticate />, layout: LayoutType.PASSKEY },
{ path: '/emails', element: <EmailsList />, showBackButton: false },
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderBreadcrumb.tsx b/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderBreadcrumb.tsx
index 55ba3ce47..9fc8a62b5 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderBreadcrumb.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Folders/FolderBreadcrumb.tsx
@@ -6,6 +6,8 @@ import { useNavigate, useLocation } from 'react-router-dom';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useNavigationHistory } from '@/entrypoints/popup/hooks/useNavigationHistory';
+import type { FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
+
type Breadcrumb = {
name: string;
id: string;
@@ -13,10 +15,10 @@ type Breadcrumb = {
type FolderBreadcrumbProps = {
/**
- * The ID of the current folder to show breadcrumbs for.
+ * The current folder to show breadcrumbs for.
* If null/undefined, no breadcrumbs are shown.
*/
- folderId: string | null | undefined;
+ folder: FolderRef | null | undefined;
/**
* Optional root path to navigate to when clicking the root breadcrumb.
* Defaults to '/items'.
@@ -35,7 +37,7 @@ type FolderBreadcrumbProps = {
* Example: If viewing "Client A" folder, shows "Items > Work > Projects" (not including "Client A")
*/
const FolderBreadcrumb: React.FC<FolderBreadcrumbProps> = ({
- folderId,
+ folder,
rootPath = '/items',
rootLabel,
}) => {
@@ -44,18 +46,21 @@ const FolderBreadcrumb: React.FC<FolderBreadcrumbProps> = ({
const location = useLocation();
const dbContext = useDb();
const { findStepsBack } = useNavigationHistory();
+ const folderId = folder?.Id ?? null;
+ const manifestId = folder?.ManifestId ?? null;
/**
* Compute breadcrumb trail based on current folder.
* Excludes the current folder if we're viewing it (to avoid duplication with page title).
*/
const breadcrumbs = useMemo((): Breadcrumb[] => {
- if (!folderId || !dbContext?.sqliteClient) {
+ if (!folderId || !manifestId || !dbContext?.sqliteClient) {
return [];
}
+ const ref = { Id: folderId, ManifestId: manifestId };
const allFolders = dbContext.sqliteClient.folders.getAll();
- const folderNames = getFolderPath(folderId, allFolders);
- const folderIds = getFolderIdPath(folderId, allFolders);
+ const folderNames = getFolderPath(ref, allFolders);
+ const folderIds = getFolderIdPath(ref, allFolders);
const fullPath = folderNames.map((name, index) => ({
name,
id: folderIds[index]
@@ -65,13 +70,13 @@ const FolderBreadcrumb: React.FC<FolderBreadcrumbProps> = ({
* If we're on the folder view page for this folder, exclude it from breadcrumbs
* (it's already shown as the page title)
*/
- const currentFolderPath = `/items/folder/${folderId}`;
+ const currentFolderPath = `/items/folder/${manifestId}/${folderId}`;
if (location.pathname === currentFolderPath && fullPath.length > 0) {
return fullPath.slice(0, -1); // Remove last item (current folder)
}
return fullPath;
- }, [folderId, dbContext?.sqliteClient, location.pathname]);
+ }, [folderId, manifestId, dbContext?.sqliteClient, location.pathname]);
/**
* Handle breadcrumb navigation with history management.
@@ -127,7 +132,7 @@ const FolderBreadcrumb: React.FC<FolderBreadcrumbProps> = ({
</button>
)}
{breadcrumbs.map((crumb) => {
- const crumbPath = `/items/folder/${crumb.id}`;
+ const crumbPath = `/items/folder/${manifestId}/${crumb.id}`;
return (
<React.Fragment key={crumb.id}>
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx b/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx
index 466f51011..1e34948d4 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Forms/FormInputCopyToClipboard.tsx
@@ -16,6 +16,7 @@ type FormInputCopyToClipboardProps = {
labelSuffix?: React.ReactNode;
/** The item this field belongs to. Copying it counts as a use; omit where the value has no item. */
itemId?: string;
+ manifestId?: string;
}
const clipboardService = new ClipboardCopyService();
@@ -66,7 +67,8 @@ export const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> =
value,
type = 'text',
labelSuffix,
- itemId
+ itemId,
+ manifestId
}) => {
const { t } = useTranslation();
const [showPassword, setShowPassword] = useState(false);
@@ -93,8 +95,8 @@ export const FormInputCopyToClipboard: React.FC<FormInputCopyToClipboardProps> =
await sendMessage('CLIPBOARD_COPIED');
// Record the use against the item this field belongs to, where one is known.
- if (itemId) {
- sendMessage('RECORD_ITEM_USAGE', { itemId, action: 'copy' }).catch(() => {
+ if (itemId && manifestId) {
+ sendMessage('RECORD_ITEM_USAGE', { itemId, manifestId, action: 'copy' }).catch(() => {
// Ignore errors
});
}
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/CurrentSiteSuggestion.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/CurrentSiteSuggestion.tsx
index adf364e81..85051c99a 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/CurrentSiteSuggestion.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/CurrentSiteSuggestion.tsx
@@ -5,6 +5,8 @@ import { useNavigate } from 'react-router-dom';
import useCurrentTabInfo from '@/entrypoints/popup/hooks/useCurrentTabInfo';
+import { itemRoute } from '@/utils/ItemRoute';
+
import ItemIcon from './ItemIcon';
import type { Item } from '@aliasvault/models/vault';
@@ -54,7 +56,7 @@ const CurrentSiteSuggestion: React.FC<CurrentSiteSuggestionProps> = ({ items, on
const item: Item = matches[0];
return (
<button
- onClick={() => navigate(`/items/${item.Id}`)}
+ onClick={() => navigate(itemRoute(item))}
className="w-full mb-4 p-2 flex items-center gap-2 rounded-lg border border-orange-300 dark:border-orange-500/40 bg-orange-50 dark:bg-orange-900/20 hover:bg-orange-100 dark:hover:bg-orange-900/30 transition-colors focus:outline-none focus:ring-2 focus:ring-orange-500 text-left"
>
<div className="w-8 h-8 flex-shrink-0">
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
index dba1b672a..5456d758c 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentBlock.tsx
@@ -7,12 +7,13 @@ import type { Attachment } from '@aliasvault/models/vault';
type AttachmentBlockProps = {
itemId: string;
+ manifestId: string;
}
/**
* This component shows attachments for an item.
*/
-const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId }) => {
+const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId, manifestId }) => {
const { t } = useTranslation();
const [attachments, setAttachments] = useState<Attachment[]>([]);
const [loading, setLoading] = useState(true);
@@ -55,7 +56,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId }) => {
}
try {
- const attachmentList = dbContext.sqliteClient.items.getAttachmentsForItem(itemId);
+ const attachmentList = dbContext.sqliteClient.items.getAttachmentsForItem({ Id: itemId, ManifestId: manifestId });
setAttachments(attachmentList);
} catch (error) {
console.error('Error loading attachments:', error);
@@ -65,7 +66,7 @@ const AttachmentBlock: React.FC<AttachmentBlockProps> = ({ itemId }) => {
};
loadAttachments();
- }, [itemId, dbContext?.sqliteClient]);
+ }, [itemId, manifestId, dbContext?.sqliteClient]);
if (loading) {
return (
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx
index 1e30915b9..f46670e21 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/AttachmentUploader.tsx
@@ -3,6 +3,8 @@ import { useTranslation } from 'react-i18next';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { itemRoute } from '@/utils/ItemRoute';
+
import type { Attachment } from '@aliasvault/models/vault';
type AttachmentUploaderProps = {
@@ -10,6 +12,7 @@ type AttachmentUploaderProps = {
onAttachmentsChange: (attachments: Attachment[]) => void;
/** Item ID for edit mode - used to determine return path when opening expanded window */
itemId?: string;
+ manifestId?: string;
}
/**
@@ -18,7 +21,8 @@ type AttachmentUploaderProps = {
const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
attachments,
onAttachmentsChange,
- itemId
+ itemId,
+ manifestId
}) => {
const { t } = useTranslation();
const [statusMessage, setStatusMessage] = useState<string>('');
@@ -112,7 +116,7 @@ const AttachmentUploader: React.FC<AttachmentUploaderProps> = ({
<button
type="button"
onClick={() => {
- const returnTo = itemId ? `/items/${itemId}` : '/items';
+ const returnTo = itemId && manifestId ? itemRoute({ Id: itemId, ManifestId: manifestId }) : '/items';
PopoutUtility.openInNewPopup(undefined, returnTo);
}}
className="inline-flex items-center px-3 py-1.5 text-sm font-medium text-white bg-primary-600 hover:bg-primary-700 rounded-md transition-colors"
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx
index 9094dc986..e5ecfd228 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldBlock.tsx
@@ -12,6 +12,7 @@ import type { ItemField } from '@aliasvault/models/vault';
type FieldBlockProps = {
field: ItemField;
itemId?: string;
+ manifestId?: string;
/** Whether to hide the label (useful when label is already shown as section header) */
hideLabel?: boolean;
}
@@ -84,7 +85,7 @@ const TextWithLinks: React.FC<{ text: string }> = ({ text }) => {
* Dynamic field block component that renders based on field type.
* Uses the same FormInputCopyToClipboard component as existing credential blocks.
*/
-const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = false }) => {
+const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, manifestId, hideLabel = false }) => {
const { t } = useTranslation();
const dbContext = useDb();
const [showHistoryModal, setShowHistoryModal] = useState(false);
@@ -105,9 +106,9 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = fals
* 2. There is exactly 1 history record but its value differs from current value
*/
useEffect(() => {
- if (hasHistoryEnabled && itemId && dbContext?.sqliteClient) {
+ if (hasHistoryEnabled && itemId && manifestId && dbContext?.sqliteClient) {
try {
- const history = dbContext.sqliteClient.items.getFieldHistory(itemId, field.FieldKey);
+ const history = dbContext.sqliteClient.items.getFieldHistory({ Id: itemId, ManifestId: manifestId }, field.FieldKey);
if (history.length > 1) {
// Multiple history records - always show icon
@@ -131,7 +132,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = fals
console.error('[FieldBlock] Error checking history:', error);
}
}
- }, [hasHistoryEnabled, itemId, field.FieldKey, field.Value, dbContext?.sqliteClient]);
+ }, [hasHistoryEnabled, itemId, manifestId, field.FieldKey, field.Value, dbContext?.sqliteClient]);
// Skip rendering if no value
if (!field.Value || (typeof field.Value === 'string' && field.Value.trim() === '')) {
@@ -152,6 +153,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = fals
value={value}
type={field.FieldType === FieldTypes.Password ? 'password' : 'text'}
itemId={itemId}
+ manifestId={manifestId}
/>
))}
</div>
@@ -175,11 +177,12 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = fals
) : null;
// History modal component
- const HistoryModal = showHistoryModal && itemId ? (
+ const HistoryModal = showHistoryModal && itemId && manifestId ? (
<FieldHistoryModal
isOpen={showHistoryModal}
onClose={() => setShowHistoryModal(false)}
itemId={itemId}
+ manifestId={manifestId}
fieldKey={field.FieldKey}
fieldLabel={label}
fieldType={field.FieldType}
@@ -200,6 +203,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = fals
type="password"
labelSuffix={HistoryButton}
itemId={itemId}
+ manifestId={manifestId}
/>
{HistoryModal}
</>
@@ -238,6 +242,7 @@ const FieldBlock: React.FC<FieldBlockProps> = ({ field, itemId, hideLabel = fals
type="text"
labelSuffix={HistoryButton}
itemId={itemId}
+ manifestId={manifestId}
/>
{HistoryModal}
</>
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx
index 829679610..44500f2fa 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/FieldHistoryModal.tsx
@@ -13,6 +13,7 @@ type FieldHistoryModalProps = {
isOpen: boolean;
onClose: () => void;
itemId: string;
+ manifestId: string;
fieldKey: string;
fieldLabel: string;
fieldType: FieldType;
@@ -29,6 +30,7 @@ const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({
isOpen,
onClose,
itemId,
+ manifestId,
fieldKey,
fieldLabel,
fieldType,
@@ -54,14 +56,14 @@ const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({
try {
setLoading(true);
- const historyRecords = dbContext.sqliteClient.items.getFieldHistory(itemId, fieldKey);
+ const historyRecords = dbContext.sqliteClient.items.getFieldHistory({ Id: itemId, ManifestId: manifestId }, fieldKey);
setHistory(historyRecords);
} catch (error) {
console.error('Error loading field history:', error);
} finally {
setLoading(false);
}
- }, [dbContext?.sqliteClient, itemId, fieldKey]);
+ }, [dbContext?.sqliteClient, itemId, manifestId, fieldKey]);
useEffect(() => {
if (!isOpen) {
@@ -110,7 +112,7 @@ const FieldHistoryModal: React.FC<FieldHistoryModalProps> = ({
try {
// Use vault mutation to delete and sync in background
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.items.deleteFieldHistory(historyId);
+ await dbContext.sqliteClient!.items.deleteFieldHistory(historyId, manifestId);
});
// Reload history after deletion
loadHistory();
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx
index e3f93b10d..0f0b20009 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyBlock.tsx
@@ -8,6 +8,7 @@ import type { Passkey } from '@aliasvault/models/vault';
type PasskeyBlockProps = {
itemId: string;
+ manifestId: string;
}
/**
@@ -30,7 +31,7 @@ const PasskeyIcon: React.FC<{ className?: string }> = ({ className = "w-5 h-5" }
/**
* Display passkey information for an item in view mode.
*/
-const PasskeyBlock: React.FC<PasskeyBlockProps> = ({ itemId }) => {
+const PasskeyBlock: React.FC<PasskeyBlockProps> = ({ itemId, manifestId }) => {
const { t } = useTranslation();
const dbContext = useDb();
const [passkeys, setPasskeys] = useState<Passkey[]>([]);
@@ -43,14 +44,14 @@ const PasskeyBlock: React.FC<PasskeyBlockProps> = ({ itemId }) => {
}
try {
- const itemPasskeys = dbContext.sqliteClient.passkeys.getByItemId(itemId);
+ const itemPasskeys = dbContext.sqliteClient.passkeys.getByItemId({ Id: itemId, ManifestId: manifestId });
setPasskeys(itemPasskeys);
} catch (err) {
console.error('Error loading passkeys:', err);
} finally {
setLoading(false);
}
- }, [dbContext?.sqliteClient, itemId]);
+ }, [dbContext?.sqliteClient, itemId, manifestId]);
if (loading) {
return (
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx
index fabb16702..0d097fe01 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/PasskeyEditor.tsx
@@ -10,6 +10,7 @@ import type { Passkey } from '@aliasvault/models/vault';
type PasskeyEditorProps = {
itemId: string;
+ manifestId: string;
passkeyIdsMarkedForDeletion: string[];
onPasskeyMarkedForDeletion: (passkeyIds: string[]) => void;
}
@@ -20,6 +21,7 @@ type PasskeyEditorProps = {
*/
const PasskeyEditor: React.FC<PasskeyEditorProps> = ({
itemId,
+ manifestId,
passkeyIdsMarkedForDeletion,
onPasskeyMarkedForDeletion
}) => {
@@ -35,14 +37,14 @@ const PasskeyEditor: React.FC<PasskeyEditorProps> = ({
}
try {
- const itemPasskeys = dbContext.sqliteClient.passkeys.getByItemId(itemId);
+ const itemPasskeys = dbContext.sqliteClient.passkeys.getByItemId({ Id: itemId, ManifestId: manifestId });
setPasskeys(itemPasskeys);
} catch (err) {
console.error('Error loading passkeys:', err);
} finally {
setLoading(false);
}
- }, [dbContext?.sqliteClient, itemId]);
+ }, [dbContext?.sqliteClient, itemId, manifestId]);
/**
* Mark a passkey for deletion.
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx
index 9c509f7bb..54b011780 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/Details/TotpBlock.tsx
@@ -24,12 +24,13 @@ const formatTotpCode = (code: string | undefined): string => {
type TotpBlockProps = {
itemId: string;
+ manifestId: string;
}
/**
* This component shows TOTP codes for an item.
*/
-const TotpBlock: React.FC<TotpBlockProps> = ({ itemId }) => {
+const TotpBlock: React.FC<TotpBlockProps> = ({ itemId, manifestId }) => {
const { t } = useTranslation();
const [totpCodes, setTotpCodes] = useState<TotpCode[]>([]);
const [loading, setLoading] = useState(true);
@@ -52,7 +53,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId }) => {
* Record the use against the item. The auto-copy that follows an autofill deliberately does not go
* through here: that interaction is already counted as an autofill, and would otherwise count twice.
*/
- sendMessage('RECORD_ITEM_USAGE', { itemId, action: 'copy' }).catch(() => {
+ sendMessage('RECORD_ITEM_USAGE', { itemId, manifestId, action: 'copy' }).catch(() => {
// Ignore errors
});
@@ -75,7 +76,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId }) => {
}
try {
- const codes = dbContext.sqliteClient.items.getTotpCodesForItem(itemId);
+ const codes = dbContext.sqliteClient.items.getTotpCodesForItem({ Id: itemId, ManifestId: manifestId });
setTotpCodes(codes);
} catch (error) {
console.error('Error loading TOTP codes:', error);
@@ -85,7 +86,7 @@ const TotpBlock: React.FC<TotpBlockProps> = ({ itemId }) => {
};
loadTotpCodes();
- }, [itemId, dbContext?.sqliteClient]);
+ }, [itemId, manifestId, dbContext?.sqliteClient]);
useEffect(() => {
/**
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemCard.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemCard.tsx
index 9af95cd92..da694c665 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemCard.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemCard.tsx
@@ -1,9 +1,12 @@
+import { scopedKey, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { truncateFolderPath } from '@aliasvault/client/items/FolderUtils';
import { FieldKey } from '@aliasvault/models/vault';
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
+import { itemRoute } from '@/utils/ItemRoute';
+
import ItemContextMenu from './ItemContextMenu';
import ItemIcon from './ItemIcon';
@@ -17,8 +20,8 @@ type ItemCardProps = {
isActive?: boolean;
optionId?: string;
isHighlighted?: boolean;
- onDuplicate?: (itemId: string) => void;
- onDelete?: (itemId: string) => void;
+ onDuplicate?: (item: ItemRef) => void;
+ onDelete?: (item: ItemRef) => void;
};
/**
@@ -129,11 +132,11 @@ const ItemCard: React.FC<ItemCardProps> = ({ item, showFolderPath = false, searc
};
return (
- <li id={optionId} data-item-id={item.Id} role="option" aria-selected={isActive} className="relative group" onContextMenu={handleContextMenu}>
+ <li id={optionId} data-item-key={scopedKey(item.ManifestId, item.Id)} role="option" aria-selected={isActive} className="relative group" onContextMenu={handleContextMenu}>
<button
onClick={() => {
// Build URL with search query parameter if present
- const url = searchTerm ? `/items/${item.Id}?returnSearch=${encodeURIComponent(searchTerm)}` : `/items/${item.Id}`;
+ const url = searchTerm ? `${itemRoute(item)}?returnSearch=${encodeURIComponent(searchTerm)}` : itemRoute(item);
navigate(url);
}}
className={`w-full p-2 border rounded flex items-center bg-white dark:bg-gray-800 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-primary-500 ${
@@ -228,9 +231,9 @@ const ItemCard: React.FC<ItemCardProps> = ({ item, showFolderPath = false, searc
<ItemContextMenu
position={menuPosition}
onClose={() => setMenuPosition(null)}
- onEdit={() => navigate(`/items/${item.Id}/edit`)}
- onDuplicate={() => onDuplicate?.(item.Id)}
- onDelete={() => onDelete?.(item.Id)}
+ onEdit={() => navigate(itemRoute(item, true))}
+ onDuplicate={() => onDuplicate?.({ Id: item.Id, ManifestId: item.ManifestId })}
+ onDelete={() => onDelete?.({ Id: item.Id, ManifestId: item.ManifestId })}
/>
)}
</li>
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemIcon.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemIcon.tsx
index 0e6cdd3a0..e51d305d4 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemIcon.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemIcon.tsx
@@ -4,14 +4,14 @@ import {
FieldKey,
LogoKinds,
ItemTypes,
+ type Item,
} from '@aliasvault/models/vault';
import React from 'react';
-import type { DraftItem } from '@aliasvault/client/database/ItemRef';
import type { ItemTypeIconKey } from '@aliasvault/models/icons';
type ItemIconProps = {
- item: DraftItem;
+ item: Item;
className?: string;
};
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
index 480fe50fd..6dd824e59 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemLogoPicker.tsx
@@ -6,11 +6,10 @@ import LogoPickerModal from '@/entrypoints/popup/components/Items/LogoPickerModa
import ItemIconComponent from './ItemIcon';
-import type { DraftItem } from '@aliasvault/client/database/ItemRef';
-import type { LogoSelection, ItemLogo } from '@aliasvault/models/vault';
+import type { Item, LogoSelection, ItemLogo } from '@aliasvault/models/vault';
type ItemLogoPickerProps = {
- item: DraftItem;
+ item: Item;
pendingSelection?: LogoSelection;
faviconSource?: string | null;
isFetching?: boolean;
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemNameInput.tsx b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemNameInput.tsx
index 82af5f217..87787a66c 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Items/ItemNameInput.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Items/ItemNameInput.tsx
@@ -1,3 +1,4 @@
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
import { buildFolderTree, getFolderIdPath, isSharedFolder, type FolderTreeNode } from '@aliasvault/client/items/FolderUtils';
import React, { useState, useCallback, useMemo, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
@@ -5,21 +6,15 @@ import { useTranslation } from 'react-i18next';
import FolderIcon from '@/entrypoints/popup/components/Folders/FolderIcon';
import { useDb } from '@/entrypoints/popup/context/DbContext';
-type Folder = {
- Id: string;
- Name: string;
- ParentFolderId: string | null;
- Weight: number;
- ManifestId?: string | null;
-};
+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
type ItemNameInputProps = {
inputRef?: React.RefObject<HTMLInputElement | null>;
value: string;
onChange: (value: string) => void;
folders: Folder[];
- selectedFolderId: string | null | undefined;
- onFolderChange: (folderId: string | null) => void;
+ selectedFolder: FolderRef | null | undefined;
+ onFolderChange: (folder: FolderRef | null) => void;
// Optional control rendered directly left of the input (the item logo).
logoSlot?: React.ReactNode;
suggestions?: string[];
@@ -34,7 +29,7 @@ const ItemNameInput: React.FC<ItemNameInputProps> = ({
value,
onChange,
folders,
- selectedFolderId,
+ selectedFolder: selectedFolderRef,
onFolderChange,
logoSlot,
suggestions = []
@@ -44,7 +39,9 @@ const ItemNameInput: React.FC<ItemNameInputProps> = ({
const [showFolderModal, setShowFolderModal] = useState(false);
const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set());
- const selectedFolder = folders.find(f => f.Id === selectedFolderId);
+ const selectedFolderId = selectedFolderRef?.Id ?? null;
+ const selectedManifestId = selectedFolderRef?.ManifestId ?? null;
+ const selectedFolder = folders.find(f => f.Id === selectedFolderId && f.ManifestId === selectedManifestId);
const personalManifestId = dbContext?.sqliteClient?.getPersonalManifestId() ?? null;
// Build folder tree
@@ -55,27 +52,27 @@ const ItemNameInput: React.FC<ItemNameInputProps> = ({
* This ensures the selected folder is visible in the tree when the modal opens.
*/
useEffect(() => {
- if (selectedFolderId && folders.length > 0) {
- const fullPath = getFolderIdPath(selectedFolderId, folders);
+ if (selectedFolderId && selectedManifestId && folders.length > 0) {
+ const fullPath = getFolderIdPath({ Id: selectedFolderId, ManifestId: selectedManifestId }, folders);
if (fullPath.length > 0) {
// Expand all folders in the path including the selected folder if it has children.
- setExpandedFolders(new Set(fullPath));
+ setExpandedFolders(new Set(fullPath.map(id => scopedKey(selectedManifestId, id))));
}
} else {
setExpandedFolders(new Set());
}
- }, [selectedFolderId, folders]);
+ }, [selectedFolderId, selectedManifestId, folders]);
/**
* Toggle folder expansion in tree view.
*/
- const toggleFolder = useCallback((folderId: string): void => {
+ const toggleFolder = useCallback((folderKey: string): void => {
setExpandedFolders(prev => {
const next = new Set(prev);
- if (next.has(folderId)) {
- next.delete(folderId);
+ if (next.has(folderKey)) {
+ next.delete(folderKey);
} else {
- next.add(folderId);
+ next.add(folderKey);
}
return next;
});
@@ -84,8 +81,8 @@ const ItemNameInput: React.FC<ItemNameInputProps> = ({
/**
* Handle folder selection and close the modal.
*/
- const handleSelectFolder = useCallback((folderId: string | null): void => {
- onFolderChange(folderId);
+ const handleSelectFolder = useCallback((folder: FolderRef | null): void => {
+ onFolderChange(folder);
setShowFolderModal(false);
}, [onFolderChange]);
@@ -114,15 +111,16 @@ const ItemNameInput: React.FC<ItemNameInputProps> = ({
* Render a folder tree node recursively.
*/
const renderFolderNode = useCallback((node: FolderTreeNode, depth: number = 0): React.ReactNode => {
- const isExpanded = expandedFolders.has(node.Id);
+ const nodeKey = scopedKey(node.ManifestId, node.Id);
+ const isExpanded = expandedFolders.has(nodeKey);
const hasChildren = node.children.length > 0;
- const isSelected = selectedFolderId === node.Id;
+ const isSelected = selectedFolderId === node.Id && selectedManifestId === node.ManifestId;
return (
- <div key={node.Id}>
+ <div key={nodeKey}>
<button
type="button"
- onClick={() => handleSelectFolder(node.Id)}
+ onClick={() => handleSelectFolder({ Id: node.Id, ManifestId: node.ManifestId })}
className={`w-full px-3 py-2 text-left rounded-md flex items-center gap-2 transition-colors ${
isSelected
? 'bg-primary-50 dark:bg-primary-900/20 text-primary-700 dark:text-primary-300'
@@ -136,7 +134,7 @@ const ItemNameInput: React.FC<ItemNameInputProps> = ({
type="button"
onClick={(e) => {
e.stopPropagation();
- toggleFolder(node.Id);
+ toggleFolder(nodeKey);
}}
className="p-0.5 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
>
@@ -177,7 +175,7 @@ const ItemNameInput: React.FC<ItemNameInputProps> = ({
)}
</div>
);
- }, [expandedFolders, selectedFolderId, handleSelectFolder, toggleFolder, personalManifestId]);
+ }, [expandedFolders, selectedFolderId, selectedManifestId, handleSelectFolder, toggleFolder, personalManifestId]);
return (
<>
diff --git a/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx b/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx
index 9342178d2..d373375df 100644
--- a/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/components/Layout/Header.tsx
@@ -73,7 +73,7 @@ const Header: React.FC<HeaderProps> = ({
// Check if we're on an item details page with a returnSearch param
const returnSearch = searchParams.get('returnSearch');
- const isItemDetailsPage = /^\/items\/[^/]+$/.test(location.pathname);
+ const isItemDetailsPage = /^\/items\/[^/]+\/[^/]+$/.test(location.pathname);
if (isItemDetailsPage && returnSearch) {
// Navigate back to items list with search query
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
index 7090e47cb..52e843179 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/emails/EmailDetails.tsx
@@ -14,11 +14,14 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import ConversionUtility from '@/entrypoints/popup/utils/ConversionUtility';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { itemRoute } from '@/utils/ItemRoute';
+
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
import HeaderButton from '../../components/HeaderButton';
import { HeaderIconType } from '../../components/Icons/HeaderIcons';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
import type { Email } from '@aliasvault/models/webapi';
/**
@@ -40,7 +43,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showMetadata, setShowMetadata] = useState(false);
const [viewMode, setViewMode] = useState<'html' | 'plain' | 'source'>('html');
- const [credential, setCredential] = useState<{ id: string; name: string } | null>(null);
+ const [credential, setCredential] = useState<{ item: ItemRef; name: string } | null>(null);
const attachmentsRef = useRef<HTMLDivElement>(null);
const { setIsInitialLoading } = useLoading();
const { setHeaderButtons } = useHeaderButtons();
@@ -117,7 +120,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
const address = `${email.toLocal}@${email.toDomain}`;
const match = dbContext.sqliteClient.items.findIdByEmail(address);
- setCredential(match ? { id: match.Id, name: match.Name ?? address } : null);
+ setCredential(match ? { item: { Id: match.Id, ManifestId: match.ManifestId }, name: match.Name ?? address } : null);
}, [email, dbContext?.sqliteClient]);
// Available view modes for the cycle button.
@@ -365,7 +368,7 @@ const EmailDetails: React.FC = (): React.ReactElement => {
<p>
<span className="font-bold">{t('emails.item')}</span>{' '}
<Link
- to={`/items/${credential.id}`}
+ to={itemRoute(credential.item)}
className="text-primary-600 hover:underline dark:text-primary-400"
>
{credential.name}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
index cf0639b62..fba9f08df 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemAddEdit.tsx
@@ -1,3 +1,5 @@
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
+import { manifestForItemIn } from '@aliasvault/client/database/ItemRef';
import * as RustCore from '@aliasvault/client/rust/RustCore';
import { FieldCategories, FieldTypes, LogoKinds, ItemTypes, getSystemFieldsForItemType, getOptionalFieldsForItemType, isFieldShownByDefault, getSystemField, fieldAppliesToType } from '@aliasvault/models/vault';
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
@@ -34,13 +36,13 @@ import useServiceDetection from '@/entrypoints/popup/hooks/useServiceDetection';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { FaviconService } from '@/utils/FaviconService';
+import { itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { NavigationStateService } from '@/utils/NavigationStateService';
-import type { DraftItem } from '@aliasvault/client/database/ItemRef';
import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
-import type { ItemField, ItemType, FieldType, Attachment, TotpCode, PasswordSettings } from '@aliasvault/models/vault';
+import type { Item, ItemField, ItemType, FieldType, Attachment, TotpCode, PasswordSettings } from '@aliasvault/models/vault';
import { browser } from '#imports';
@@ -55,7 +57,7 @@ const DEFAULT_ITEM_TYPE: ItemType = ItemTypes.Login;
* This is the data portion stored via useFormPersistence hook.
*/
type PersistedFormData = {
- item: DraftItem | null;
+ item: Item | null;
fieldValues: Record<string, string | string[]>;
customFields: CustomFieldDefinition[];
totpEditorState?: {
@@ -84,17 +86,18 @@ const isMaskedFieldType = (fieldType: FieldType): boolean =>
*/
const ItemAddEdit: React.FC = () => {
const { t } = useTranslation();
- const { id } = useParams();
+ const { id, manifestId } = useParams();
const [searchParams] = useSearchParams();
const location = useLocation();
const navigate = useNavigate();
const dbContext = useDb();
- const isEditMode = id !== undefined && id.length > 0;
+ const isEditMode = id !== undefined && id.length > 0 && manifestId !== undefined && manifestId.length > 0;
// Get item type, title, and folder from URL parameters (for create mode)
const itemTypeParam = searchParams.get('type') as ItemType | null;
const itemTitleParam = searchParams.get('itemTitle');
- const folderIdParam = searchParams.get('folderId');
+ const folderManifestIdParam = searchParams.get('folderManifestId');
+ const folderIdParam = folderManifestIdParam ? searchParams.get('folderId') : null;
const sourceTabIdParam = searchParams.get('sourceTabId');
const fillBackElementIdentifier = searchParams.get('elementIdentifier');
@@ -111,7 +114,7 @@ const ItemAddEdit: React.FC = () => {
const [isSaving, setIsSaving] = useState(false);
const [showDeleteModal, setShowDeleteModal] = useState(false);
// A draft until the vault writes it: a new item's manifest follows from the folder it lands in.
- const [item, setItem] = useState<DraftItem | null>(null);
+ const [item, setItem] = useState<Item | null>(null);
// Form state for dynamic fields
const [fieldValues, setFieldValues] = useState<Record<string, string | string[]>>({});
@@ -211,7 +214,7 @@ const ItemAddEdit: React.FC = () => {
* The hook auto-persists on state changes and clears on unmount.
*/
const { loadPersistedValues, clearPersistedValues } = useFormPersistence<PersistedFormData>({
- formId: id || null,
+ formId: id && manifestId ? scopedKey(manifestId, id) : null,
isLoading: localLoading,
formData: {
item,
@@ -345,7 +348,7 @@ const ItemAddEdit: React.FC = () => {
* Load item data if in edit mode, or initialize for create mode with service detection.
*/
useEffect(() => {
- if (!dbContext?.sqliteClient || !id || !isEditMode) {
+ if (!dbContext?.sqliteClient || !id || !manifestId || !isEditMode) {
// Create mode - initialize with defaults
const effectiveType: ItemType = (itemTypeParam && VALID_ITEM_TYPES.includes(itemTypeParam))
? itemTypeParam
@@ -359,12 +362,16 @@ const ItemAddEdit: React.FC = () => {
const { serviceName, serviceUrl, suggestedNames: detectedSuggestedNames } = await detectService(itemTitleParam);
setSuggestedNames(detectedSuggestedNames);
+ // A new item belongs in the manifest of the folder it starts in, or the personal one outside any folder.
+ const startManifestId = manifestForItemIn(folderIdParam ? { ManifestId: folderManifestIdParam! } : null, dbContext?.sqliteClient?.getPersonalManifestId());
+
// Create the new item with detected values
- const newItem: DraftItem = {
+ const newItem: Item = {
Id: crypto.randomUUID(),
Name: serviceName,
ItemType: effectiveType,
FolderId: folderIdParam || null,
+ ManifestId: startManifestId,
Fields: [],
CreatedAt: new Date().toISOString(),
UpdatedAt: new Date().toISOString()
@@ -404,7 +411,8 @@ const ItemAddEdit: React.FC = () => {
// Also override the FolderId with the current URL param (if any).
setItem(prev => prev ? {
...prev,
- FolderId: folderIdParam || null
+ FolderId: folderIdParam || null,
+ ManifestId: startManifestId
} : prev);
}
@@ -427,7 +435,7 @@ const ItemAddEdit: React.FC = () => {
}
try {
- const result = sqliteClient.items.getById(id);
+ const result = sqliteClient.items.getById({ Id: id, ManifestId: manifestId });
if (!result) {
console.error('Item not found');
navigate('/items');
@@ -469,7 +477,7 @@ const ItemAddEdit: React.FC = () => {
setInitiallyVisibleFields(fieldsWithValues);
// Load TOTP codes for this item
- const itemTotpCodes = sqliteClient.items.getTotpCodesForItem(id, result.ManifestId);
+ const itemTotpCodes = sqliteClient.items.getTotpCodesForItem(result);
setTotpCodes(itemTotpCodes);
setOriginalTotpCodeIds(itemTotpCodes.map((tc) => tc.Id));
if (itemTotpCodes.length > 0) {
@@ -477,7 +485,7 @@ const ItemAddEdit: React.FC = () => {
}
// Load attachments for this item
- const itemAttachments = sqliteClient.items.getAttachmentsForItem(id, result.ManifestId);
+ const itemAttachments = sqliteClient.items.getAttachmentsForItem(result);
setAttachments(itemAttachments);
setOriginalAttachmentIds(itemAttachments.map((a) => a.Id));
if (itemAttachments.length > 0) {
@@ -503,7 +511,7 @@ const ItemAddEdit: React.FC = () => {
};
void initializeEditMode();
- }, [dbContext?.sqliteClient, id, isEditMode, itemTypeParam, itemTitleParam, folderIdParam, navigate, setIsInitialLoading, detectService, loadPersistedValues]);
+ }, [dbContext?.sqliteClient, id, manifestId, isEditMode, itemTypeParam, itemTitleParam, folderIdParam, folderManifestIdParam, navigate, setIsInitialLoading, detectService, loadPersistedValues]);
/**
* Handle generating alias and populating fields.
@@ -695,7 +703,7 @@ const ItemAddEdit: React.FC = () => {
* created item back into the originating tab and close this popup window. Returns true when the
* fill-back path handled the post-save behaviour (so the caller should skip normal navigation).
*/
- const fillBackAndCloseWindow = useCallback(async (savedItem: DraftItem): Promise<boolean> => {
+ const fillBackAndCloseWindow = useCallback(async (savedItem: Item): Promise<boolean> => {
if (isEditMode || !sourceTabIdParam) {
return false;
}
@@ -802,7 +810,7 @@ const ItemAddEdit: React.FC = () => {
});
});
- let updatedItem: DraftItem = {
+ let updatedItem: Item = {
...item,
/*
* For create mode, always generate a fresh ID to prevent UNIQUE constraint
@@ -842,25 +850,21 @@ const ItemAddEdit: React.FC = () => {
* Use async mutation - saves locally and navigates immediately.
* Sync happens in background, status shown via header indicator.
*/
+ let savedItem: Item = updatedItem;
await executeVaultMutationAsync(async () => {
- if (isEditMode) {
- await dbContext.sqliteClient!.items.update(
- updatedItem,
- originalAttachmentIds,
- attachments,
- originalTotpCodeIds,
- totpCodes,
- logoSelection
- );
+ if (isEditMode && manifestId) {
+ const saved = await dbContext.sqliteClient!.items.update({ Id: item.Id, ManifestId: manifestId }, updatedItem, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, logoSelection);
+ if (saved) {
+ savedItem = { ...updatedItem, ManifestId: saved.ManifestId };
+ }
- // Delete passkeys marked for deletion
- if (passkeyIdsMarkedForDeletion.length > 0) {
- for (const passkeyId of passkeyIdsMarkedForDeletion) {
- await dbContext.sqliteClient!.passkeys.deleteById(passkeyId, item.ManifestId);
- }
+ // Delete passkeys marked for deletion, in the manifest the item is in after the save
+ for (const passkeyId of passkeyIdsMarkedForDeletion) {
+ await dbContext.sqliteClient!.passkeys.deleteById(passkeyId, saved?.ManifestId ?? manifestId);
}
} else {
- await dbContext.sqliteClient!.items.create(updatedItem, attachments, totpCodes, logoSelection);
+ const created = await dbContext.sqliteClient!.items.create(updatedItem, attachments, totpCodes, logoSelection);
+ savedItem = { ...updatedItem, Id: created.Id, ManifestId: created.ManifestId };
}
});
@@ -871,38 +875,38 @@ const ItemAddEdit: React.FC = () => {
* If this create was launched from a page's "create new item" flow, autofill the new
* credential back into the originating tab and close this window instead of navigating.
*/
- if (await fillBackAndCloseWindow(updatedItem)) {
+ if (await fillBackAndCloseWindow(savedItem)) {
return;
}
/*
* Navigate after save:
* - Edit mode and came from details: navigate(-1) so back from details goes to list (no duplicate details).
- * - Edit mode and did not come from details: go to details with replace so we still land on details.
+ * - Edit mode and did not come from details, or the save moved the item to another manifest: go to details with replace.
* - Create mode: go to new item details with replace.
*/
- if (isEditMode && (location.state as { fromDetails?: boolean } | null)?.fromDetails) {
+ if (isEditMode && savedItem.ManifestId === manifestId && (location.state as { fromDetails?: boolean } | null)?.fromDetails) {
navigate(-1);
} else {
- navigate(`/items/${updatedItem.Id}`, { replace: true });
+ navigate(itemRoute(savedItem), { replace: true });
}
} catch (err) {
console.error('Error saving item:', err);
setIsSaving(false);
}
- }, [item, isSaving, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, location.state, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, logoSelection, resolvedFaviconSource, webApi, clearPersistedValues, fillBackAndCloseWindow]);
+ }, [item, manifestId, isSaving, fieldValues, applicableSystemFields, customFields, dbContext, isEditMode, executeVaultMutationAsync, navigate, location.state, originalAttachmentIds, attachments, originalTotpCodeIds, totpCodes, passkeyIdsMarkedForDeletion, logoSelection, resolvedFaviconSource, webApi, clearPersistedValues, fillBackAndCloseWindow]);
/**
* Handle delete action.
*/
const handleDelete = useCallback(async () => {
- if (!item || !isEditMode || !dbContext?.sqliteClient) {
+ if (!item || !isEditMode || !manifestId || !dbContext?.sqliteClient) {
return;
}
try {
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.items.trash(item.Id);
+ await dbContext.sqliteClient!.items.trash({ Id: item.Id, ManifestId: manifestId });
});
navigate('/items');
@@ -911,7 +915,7 @@ const ItemAddEdit: React.FC = () => {
} finally {
setShowDeleteModal(false);
}
- }, [item, isEditMode, dbContext, executeVaultMutationAsync, navigate]);
+ }, [item, manifestId, isEditMode, dbContext, executeVaultMutationAsync, navigate]);
/**
* Add custom field handler.
@@ -1156,7 +1160,7 @@ const ItemAddEdit: React.FC = () => {
} else if (folderIdParam && dbContext?.sqliteClient) {
// Create mode with folder: back button goes to folder
const allFolders = dbContext.sqliteClient.folders.getAll();
- const folder = allFolders.find(f => f.Id === folderIdParam);
+ const folder = allFolders.find(f => f.Id === folderIdParam && f.ManifestId === folderManifestIdParam);
if (folder) {
setBackButtonTitle(folder.Name);
} else {
@@ -1168,7 +1172,7 @@ const ItemAddEdit: React.FC = () => {
}
return (): void => setBackButtonTitle(null);
- }, [setBackButtonTitle, isEditMode, folderIdParam, dbContext?.sqliteClient, t]);
+ }, [setBackButtonTitle, isEditMode, folderIdParam, folderManifestIdParam, dbContext?.sqliteClient, t]);
/**
* Render a field input based on field type.
@@ -1418,8 +1422,8 @@ const ItemAddEdit: React.FC = () => {
value={item.Name || ''}
onChange={(name) => setItem({ ...item, Name: name })}
folders={folders}
- selectedFolderId={item.FolderId}
- onFolderChange={(folderId) => setItem({ ...item, FolderId: folderId })}
+ selectedFolder={item.FolderId ? { Id: item.FolderId, ManifestId: item.ManifestId } : null}
+ onFolderChange={(folder) => setItem({ ...item, FolderId: folder?.Id ?? null, ManifestId: manifestForItemIn(folder, dbContext?.sqliteClient?.getPersonalManifestId()) })}
logoSlot={
<ItemLogoPicker
item={item}
@@ -1450,6 +1454,7 @@ const ItemAddEdit: React.FC = () => {
{isEditMode && item.HasPasskey && (
<PasskeyEditor
itemId={item.Id}
+ manifestId={manifestId!}
passkeyIdsMarkedForDeletion={passkeyIdsMarkedForDeletion}
onPasskeyMarkedForDeletion={setPasskeyIdsMarkedForDeletion}
/>
@@ -1592,6 +1597,7 @@ const ItemAddEdit: React.FC = () => {
attachments={attachments}
onAttachmentsChange={setAttachments}
itemId={isEditMode ? id : undefined}
+ manifestId={isEditMode ? manifestId : undefined}
/>
)}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
index b5c6f516e..29da26cc4 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemDetails.tsx
@@ -19,6 +19,8 @@ import { useHeaderButtons } from '@/entrypoints/popup/context/HeaderButtonsConte
import { useLoading } from '@/entrypoints/popup/context/LoadingContext';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { itemRoute } from '@/utils/ItemRoute';
+
import { EmailPreview } from '../../components/EmailPreview';
import type { Item } from '@aliasvault/models/vault';
@@ -28,7 +30,7 @@ import type { Item } from '@aliasvault/models/vault';
*/
const ItemDetails: React.FC = (): React.ReactElement => {
const { t } = useTranslation();
- const { id } = useParams();
+ const { id, manifestId } = useParams();
const navigate = useNavigate();
const dbContext = useDb();
const [item, setItem] = useState<Item | null>(null);
@@ -39,29 +41,33 @@ const ItemDetails: React.FC = (): React.ReactElement => {
* Open the item details in a new expanded popup.
*/
const openInNewPopup = useCallback((): void => {
- PopoutUtility.openInNewPopup(`/items/${id}`);
- }, [id]);
+ if (id && manifestId) {
+ PopoutUtility.openInNewPopup(itemRoute({ Id: id, ManifestId: manifestId }));
+ }
+ }, [id, manifestId]);
/**
* Navigate to the edit page for this item.
* Pass fromDetails so save can use navigate(-1) and avoid duplicate details in history.
*/
const handleEdit = useCallback((): void => {
- navigate(`/items/${id}/edit`, { state: { fromDetails: true } });
- }, [id, navigate]);
+ if (id && manifestId) {
+ navigate(itemRoute({ Id: id, ManifestId: manifestId }, true), { state: { fromDetails: true } });
+ }
+ }, [id, manifestId, navigate]);
useEffect(() => {
- if (PopoutUtility.isPopup()) {
+ if (PopoutUtility.isPopup() && id && manifestId) {
window.history.replaceState({}, '', `popup.html#/items`);
- window.history.pushState({}, '', `popup.html#/items/${id}`);
+ window.history.pushState({}, '', `popup.html#${itemRoute({ Id: id, ManifestId: manifestId })}`);
}
- if (!dbContext?.sqliteClient || !id) {
+ if (!dbContext?.sqliteClient || !id || !manifestId) {
return;
}
try {
- const result = dbContext.sqliteClient.items.getById(id);
+ const result = dbContext.sqliteClient.items.getById({ Id: id, ManifestId: manifestId });
if (result) {
setItem(result);
setIsInitialLoading(false);
@@ -72,7 +78,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
} catch (err) {
console.error('Error loading item:', err);
}
- }, [dbContext.sqliteClient, id, navigate, setIsInitialLoading]);
+ }, [dbContext.sqliteClient, id, manifestId, navigate, setIsInitialLoading]);
// Set header buttons on mount and clear on unmount
useEffect((): (() => void) => {
@@ -108,7 +114,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
if (item.FolderId) {
// Item is in a folder - show folder name
const allFolders = dbContext.sqliteClient.folders.getAll();
- const folder = allFolders.find(f => f.Id === item.FolderId);
+ const folder = allFolders.find(f => f.Id === item.FolderId && f.ManifestId === item.ManifestId);
if (folder) {
setBackButtonTitle(folder.Name);
} else {
@@ -142,7 +148,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
return (
<div className="space-y-4">
{/* Folder breadcrumb navigation */}
- <FolderBreadcrumb folderId={item.FolderId} />
+ <FolderBreadcrumb folder={item.FolderId ? { Id: item.FolderId, ManifestId: item.ManifestId } : null} />
{/* Header with name, logo, and URLs */}
<div className="flex justify-between items-start">
@@ -198,12 +204,12 @@ const ItemDetails: React.FC = (): React.ReactElement => {
{/* TOTP codes - only for Login and Alias types, shown at top */}
{(item.ItemType === ItemTypes.Login || item.ItemType === ItemTypes.Alias) && (
- <TotpBlock itemId={item.Id} />
+ <TotpBlock itemId={item.Id} manifestId={item.ManifestId} />
)}
{/* Passkeys - only for Login and Alias types */}
{(item.ItemType === ItemTypes.Login || item.ItemType === ItemTypes.Alias) && item.HasPasskey && (
- <PasskeyBlock itemId={item.Id} />
+ <PasskeyBlock itemId={item.Id} manifestId={item.ManifestId} />
)}
{/* Notes - shown at top for Note type (primary content) */}
@@ -213,7 +219,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">
{t(`fieldLabels.${field.FieldKey}`, { defaultValue: field.Label || field.FieldKey })}
</h2>
- <FieldBlock field={field} itemId={item.Id} hideLabel />
+ <FieldBlock field={field} itemId={item.Id} manifestId={item.ManifestId} hideLabel />
</div>
))
)}
@@ -227,7 +233,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
{t('common.credentials')}
</h2>
{groupedFields[FieldCategories.Login].map((field) => (
- <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} />
+ <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} manifestId={item.ManifestId} />
))}
</div>
)}
@@ -238,7 +244,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
{t('common.alias')}
</h2>
{groupedFields[FieldCategories.Alias].map((field) => (
- <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} />
+ <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} manifestId={item.ManifestId} />
))}
</div>
)}
@@ -249,7 +255,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
{t('items.cardInformation')}
</h2>
{groupedFields[FieldCategories.Card].map((field) => (
- <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} />
+ <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} manifestId={item.ManifestId} />
))}
</div>
)}
@@ -261,7 +267,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
<h2 className="text-xl font-semibold text-gray-900 dark:text-white">
{t(`fieldLabels.${field.FieldKey}`, { defaultValue: field.Label || field.FieldKey })}
</h2>
- <FieldBlock field={field} itemId={item.Id} hideLabel />
+ <FieldBlock field={field} itemId={item.Id} manifestId={item.ManifestId} hideLabel />
</div>
))
)}
@@ -270,7 +276,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
{groupedFields[FieldCategories.Custom] && groupedFields[FieldCategories.Custom].length > 0 && (
<div className="space-y-2">
{groupedFields[FieldCategories.Custom].map((field) => (
- <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} />
+ <FieldBlock key={field.FieldKey} field={field} itemId={item.Id} manifestId={item.ManifestId} />
))}
</div>
)}
@@ -278,7 +284,7 @@ const ItemDetails: React.FC = (): React.ReactElement => {
)}
{/* Attachments - shown at bottom */}
- <AttachmentBlock itemId={item.Id} />
+ <AttachmentBlock itemId={item.Id} manifestId={item.ManifestId} />
{/* Tags */}
{item.Tags && item.Tags.length > 0 && (
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 7c18cbd42..4f2e57401 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/ItemsList.tsx
@@ -1,4 +1,5 @@
-import { canHaveSubfolders, getDescendantFolderIds, getFolderPath, getRecursiveItemCount, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
+import { canHaveSubfolders, getDescendantFolderIds, getFolderPath, getRecursiveItemCount, isItemInFolder, isSharedFolder } from '@aliasvault/client/items/FolderUtils';
import { applySearchFilter, applyTypeFilter, isItemTypeFilter, parseItemFilterType, type ItemFilterType } from '@aliasvault/client/items/ItemFilters';
import { multiManifestRendering } from '@aliasvault/client/sharing/MultiManifestRendering';
import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
@@ -28,11 +29,13 @@ import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { useVaultSync } from '@/entrypoints/popup/hooks/useVaultSync';
import { PopoutUtility } from '@/entrypoints/popup/utils/PopoutUtility';
+import { isSameItem, itemRoute } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
-import type { Folder } from '@aliasvault/client/database/repositories/FolderRepository';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+import type { Folder, FolderRef } from '@aliasvault/client/database/repositories/FolderRepository';
import type { CredentialSortOrder } from '@aliasvault/client/database/repositories/SettingsRepository';
import type { Item, ItemType } from '@aliasvault/models/vault';
@@ -99,6 +102,7 @@ const storeFilter = (filter: ItemFilterType): void => {
*/
type FolderWithCount = {
id: string;
+ manifestId: string;
name: string;
itemCount: number;
isShared: boolean;
@@ -109,7 +113,7 @@ type FolderWithCount = {
*/
const ItemsList: React.FC = () => {
const { t } = useTranslation();
- const { folderId: folderIdParam } = useParams<{ folderId?: string }>();
+ const { folderId: folderIdParam, manifestId: manifestIdParam } = useParams<{ folderId?: string; manifestId?: string }>();
const location = useLocation();
const [searchParams] = useSearchParams();
const dbContext = useDb();
@@ -131,8 +135,8 @@ const ItemsList: React.FC = () => {
const [showFolderModal, setShowFolderModal] = useState(false);
const [showDeleteFolderModal, setShowDeleteFolderModal] = useState(false);
const [showEditFolderModal, setShowEditFolderModal] = useState(false);
- const [deleteItemId, setDeleteItemId] = useState<string | null>(null);
- const [highlightedItemId, setHighlightedItemId] = useState<string | null>(null);
+ const [deleteItem, setDeleteItem] = useState<ItemRef | null>(null);
+ const [highlightedItem, setHighlightedItem] = useState<ItemRef | null>(null);
const [recentlyDeletedCount, setRecentlyDeletedCount] = useState(0);
const [folderRefreshKey, setFolderRefreshKey] = useState(0);
const [sortOrder, setSortOrder] = useState<CredentialSortOrder>('NewestFirst');
@@ -146,44 +150,46 @@ const ItemsList: React.FC = () => {
LocalPreferencesService.getShowFolders().then(setShowFolders);
}, []);
- // Derive current folder from URL params
- const currentFolderId = folderIdParam ?? null;
+ // Derive current folder from URL params: a folder is only named by its manifest and its id together
+ const currentFolderId = folderIdParam && manifestIdParam ? folderIdParam : null;
+ const currentManifestId = currentFolderId ? manifestIdParam ?? null : null;
+ const currentFolderRef = useMemo((): FolderRef | null => (currentFolderId && currentManifestId ? { Id: currentFolderId, ManifestId: currentManifestId } : null), [currentFolderId, currentManifestId]);
// Get current folder name from database
const currentFolderName = useMemo(() => {
// folderRefreshKey is included in deps to force re-computation when folder is renamed
void folderRefreshKey;
- if (!currentFolderId || !dbContext?.sqliteClient) {
+ if (!currentFolderRef || !dbContext?.sqliteClient) {
return null;
}
const folders = dbContext.sqliteClient.folders.getAll();
- const folder = folders.find((f: { Id: string; Name: string }) => f.Id === currentFolderId);
+ const folder = folders.find((f: Folder) => f.Id === currentFolderRef.Id && f.ManifestId === currentFolderRef.ManifestId);
return folder?.Name ?? null;
- }, [currentFolderId, dbContext?.sqliteClient, folderRefreshKey]);
+ }, [currentFolderRef, dbContext?.sqliteClient, folderRefreshKey]);
// The folder being viewed, re-read when it changes
const currentFolder = useMemo(() => {
// folderRefreshKey is included in deps to force re-computation when the folder changes
void folderRefreshKey;
- if (!currentFolderId || !dbContext?.sqliteClient) {
+ if (!currentFolderRef || !dbContext?.sqliteClient) {
return null;
}
- return dbContext.sqliteClient.folders.getById(currentFolderId);
- }, [currentFolderId, dbContext?.sqliteClient, folderRefreshKey]);
+ return dbContext.sqliteClient.folders.getById(currentFolderRef);
+ }, [currentFolderRef, dbContext?.sqliteClient, folderRefreshKey]);
// Whether it is the folder a shared manifest is rendered as: left or revoked in Family Sharing, never deleted here
const currentFolderIsSharedVaultRoot = currentFolder !== null && multiManifestRendering.isManifestRoot(currentFolder);
// Get current folder's full path (for relative path computation in search results)
const currentFolderPath = useMemo(() => {
- if (!currentFolderId || !dbContext?.sqliteClient) {
+ if (!currentFolderRef || !dbContext?.sqliteClient) {
return null;
}
const folders = dbContext.sqliteClient.folders.getAll();
- const path = getFolderPath(currentFolderId, folders);
+ const path = getFolderPath(currentFolderRef, folders);
return path.length > 0 ? path : null;
- }, [currentFolderId, dbContext?.sqliteClient]);
+ }, [currentFolderRef, dbContext?.sqliteClient]);
/**
* Loading state with minimum duration for more fluid UX.
@@ -237,12 +243,13 @@ const ItemsList: React.FC = () => {
params.set('type', type);
// Pre-select the current folder if we're inside a folder
- if (currentFolderId) {
- params.set('folderId', currentFolderId);
+ if (currentFolderRef) {
+ params.set('folderId', currentFolderRef.Id);
+ params.set('folderManifestId', currentFolderRef.ManifestId);
}
navigate(`/items/add?${params.toString()}`);
- }, [navigate, currentFolderId]);
+ }, [navigate, currentFolderRef]);
/**
* Handle add new folder.
@@ -262,26 +269,26 @@ const ItemsList: React.FC = () => {
}
await executeVaultMutationAsync(async () => {
- // Create folder in current location (currentFolderId = null means root)
- await dbContext.sqliteClient!.folders.create(folderName, currentFolderId);
+ // Create folder in current location (no current folder means root)
+ await dbContext.sqliteClient!.folders.create(folderName, currentFolderRef);
});
// Refresh items to show the new folder
const results = dbContext.sqliteClient!.items.getAll();
setItems(results);
- }, [dbContext, currentFolderId, executeVaultMutationAsync]);
+ }, [dbContext, currentFolderRef, executeVaultMutationAsync]);
/**
* Duplicate an item via the item context menu.
*/
- const handleDuplicateItem = useCallback(async (itemId: string) : Promise<void> => {
+ const handleDuplicateItem = useCallback(async (source: ItemRef) : Promise<void> => {
if (!dbContext?.sqliteClient) {
return;
}
- let newItemId: string | null = null;
+ let newItem: ItemRef | null = null;
await executeVaultMutationAsync(async () => {
- newItemId = await dbContext.sqliteClient!.items.duplicate(itemId);
+ newItem = await dbContext.sqliteClient!.items.duplicate(source);
});
// Refresh items to show the new duplicate
@@ -289,7 +296,7 @@ const ItemsList: React.FC = () => {
setItems(results);
// Scroll to and briefly highlight the new duplicate so it's clear where it landed
- setHighlightedItemId(newItemId);
+ setHighlightedItem(newItem);
}, [dbContext, executeVaultMutationAsync]);
/**
@@ -297,32 +304,32 @@ const ItemsList: React.FC = () => {
* rendered, then clear the highlight after a short moment.
*/
useEffect(() => {
- if (!highlightedItemId) {
+ if (!highlightedItem) {
return;
}
// Wait a frame so the re-rendered list contains the new item before scrolling.
requestAnimationFrame(() => {
- document.querySelector(`[data-item-id="${highlightedItemId}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ document.querySelector(`[data-item-key="${scopedKey(highlightedItem.ManifestId, highlightedItem.Id)}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' });
});
- const timer = setTimeout(() => setHighlightedItemId(null), 2000);
+ const timer = setTimeout(() => setHighlightedItem(null), 2000);
return (): void => clearTimeout(timer);
- }, [highlightedItemId]);
+ }, [highlightedItem]);
/**
* Move an item to the trash after confirmation via the item context menu.
*/
const handleConfirmDeleteItem = useCallback(async () : Promise<void> => {
- if (!dbContext?.sqliteClient || !deleteItemId) {
+ if (!dbContext?.sqliteClient || !deleteItem) {
return;
}
- const itemId = deleteItemId;
- setDeleteItemId(null);
+ const target = deleteItem;
+ setDeleteItem(null);
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.items.trash(itemId);
+ await dbContext.sqliteClient!.items.trash(target);
});
// Refresh items to reflect the deletion
@@ -330,23 +337,21 @@ const ItemsList: React.FC = () => {
setItems(results);
const deletedCount = dbContext.sqliteClient!.items.getRecentlyDeletedCount();
setRecentlyDeletedCount(deletedCount);
- }, [dbContext, deleteItemId, executeVaultMutationAsync]);
+ }, [dbContext, deleteItem, executeVaultMutationAsync]);
/**
* Handle delete folder (keep items, move them to root).
*/
const handleDeleteFolderOnly = useCallback(async () : Promise<void> => {
- if (!dbContext?.sqliteClient || !currentFolderId) {
+ if (!dbContext?.sqliteClient || !currentFolderRef) {
return;
}
// Get the current folder to determine parent before deletion
- const allFolders = dbContext.sqliteClient.folders.getAll();
- const currentFolder = allFolders.find(f => f.Id === currentFolderId);
- const parentFolderId = currentFolder?.ParentFolderId ?? null;
+ const parentFolderId = dbContext.sqliteClient.folders.getById(currentFolderRef)?.ParentFolderId ?? null;
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.folders.delete(currentFolderId);
+ await dbContext.sqliteClient!.folders.delete(currentFolderRef);
});
// Refresh items list to reflect changes
@@ -357,27 +362,25 @@ const ItemsList: React.FC = () => {
// Navigate to parent folder if it exists, otherwise root
if (parentFolderId) {
- navigate(`/items/folder/${parentFolderId}`);
+ navigate(`/items/folder/${currentFolderRef.ManifestId}/${parentFolderId}`);
} else {
navigate('/items');
}
- }, [dbContext, currentFolderId, executeVaultMutationAsync, navigate]);
+ }, [dbContext, currentFolderRef, executeVaultMutationAsync, navigate]);
/**
* Handle delete folder and all its contents.
*/
const handleDeleteFolderAndContents = useCallback(async () : Promise<void> => {
- if (!dbContext?.sqliteClient || !currentFolderId) {
+ if (!dbContext?.sqliteClient || !currentFolderRef) {
return;
}
// Get the current folder to determine parent before deletion
- const allFolders = dbContext.sqliteClient.folders.getAll();
- const currentFolder = allFolders.find(f => f.Id === currentFolderId);
- const parentFolderId = currentFolder?.ParentFolderId ?? null;
+ const parentFolderId = dbContext.sqliteClient.folders.getById(currentFolderRef)?.ParentFolderId ?? null;
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.folders.deleteWithContents(currentFolderId);
+ await dbContext.sqliteClient!.folders.deleteWithContents(currentFolderRef);
});
// Refresh items list to reflect changes
@@ -388,22 +391,22 @@ const ItemsList: React.FC = () => {
// Navigate to parent folder if it exists, otherwise root
if (parentFolderId) {
- navigate(`/items/folder/${parentFolderId}`);
+ navigate(`/items/folder/${currentFolderRef.ManifestId}/${parentFolderId}`);
} else {
navigate('/items');
}
- }, [dbContext, currentFolderId, executeVaultMutationAsync, navigate]);
+ }, [dbContext, currentFolderRef, executeVaultMutationAsync, navigate]);
/**
* Handle edit/rename folder.
*/
const handleEditFolder = useCallback(async (newName: string) : Promise<void> => {
- if (!dbContext?.sqliteClient || !currentFolderId) {
+ if (!dbContext?.sqliteClient || !currentFolderRef) {
return;
}
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.folders.update(currentFolderId, newName);
+ await dbContext.sqliteClient!.folders.update(currentFolderRef, newName);
});
// Trigger re-computation of currentFolderName
@@ -411,7 +414,7 @@ const ItemsList: React.FC = () => {
// Close modal
setShowEditFolderModal(false);
- }, [dbContext, currentFolderId, executeVaultMutationAsync]);
+ }, [dbContext, currentFolderRef, executeVaultMutationAsync]);
/**
* Retrieve latest vault and refresh the items list.
@@ -479,13 +482,12 @@ const ItemsList: React.FC = () => {
// Set back button title for folder view
useEffect(() => {
- if (folderIdParam && dbContext?.sqliteClient) {
- const allFolders = dbContext.sqliteClient.folders.getAll();
- const currentFolder = allFolders.find(f => f.Id === folderIdParam);
+ if (currentFolderRef && dbContext?.sqliteClient) {
+ const currentFolder = dbContext.sqliteClient.folders.getById(currentFolderRef);
if (currentFolder && currentFolder.ParentFolderId) {
- // Has parent folder - show parent folder name
- const parentFolder = allFolders.find(f => f.Id === currentFolder.ParentFolderId);
+ // Has parent folder - show parent folder name, looked up inside the same manifest
+ const parentFolder = dbContext.sqliteClient.folders.getById({ Id: currentFolder.ParentFolderId, ManifestId: currentFolderRef.ManifestId });
if (parentFolder) {
setBackButtonTitle(parentFolder.Name);
} else {
@@ -501,7 +503,7 @@ const ItemsList: React.FC = () => {
}
return (): void => setBackButtonTitle(null);
- }, [folderIdParam, dbContext?.sqliteClient, setBackButtonTitle, t]);
+ }, [currentFolderRef, dbContext?.sqliteClient, setBackButtonTitle, t]);
/**
* Load items list on mount and on sqlite client change.
@@ -566,9 +568,9 @@ const ItemsList: React.FC = () => {
* Navigate into a folder via URL, preserving the active filter so the folder view
* shows the same subset reflected in the folder pill's badge count.
*/
- const handleFolderClick = useCallback((folderId: string, _folderName: string) => {
+ const handleFolderClick = useCallback((folder: FolderRef) => {
setSearchTerm(''); // Clear search when entering folder
- navigate(`/items/folder/${folderId}?filter=${encodeURIComponent(filterType)}`);
+ navigate(`/items/folder/${folder.ManifestId}/${folder.Id}?filter=${encodeURIComponent(filterType)}`);
}, [navigate, filterType]);
/**
@@ -592,9 +594,9 @@ const ItemsList: React.FC = () => {
// Filter folders based on current location
const relevantFolders = allFolders.filter((folder: Folder) => {
- if (currentFolderId) {
- // Inside a folder: show only direct children
- return folder.ParentFolderId === currentFolderId;
+ if (currentFolderRef) {
+ // Inside a folder: show only direct children, which live in the folder's own manifest
+ return folder.ParentFolderId === currentFolderRef.Id && folder.ManifestId === currentFolderRef.ManifestId;
} else {
/*
* At root: show only root-level folders
@@ -609,23 +611,24 @@ const ItemsList: React.FC = () => {
const directFolderCounts = new Map<string, number>();
filteredForCounts.forEach((item: Item) => {
if (item.FolderId) {
- directFolderCounts.set(item.FolderId, (directFolderCounts.get(item.FolderId) || 0) + 1);
+ const key = scopedKey(item.ManifestId, item.FolderId);
+ directFolderCounts.set(key, (directFolderCounts.get(key) || 0) + 1);
}
});
/**
* Recursively count items in a folder and all its subfolders.
- * @param folderId - The folder ID to count items for
+ * @param folder - The folder to count items for
* @returns Total count of items in this folder and all descendant folders
*/
- const getRecursiveItemCountLocal = (folderId: string): number => {
+ const getRecursiveItemCountLocal = (folder: FolderRef): number => {
// Start with direct items in this folder
- let count = directFolderCounts.get(folderId) || 0;
+ let count = directFolderCounts.get(scopedKey(folder.ManifestId, folder.Id)) || 0;
// Add counts from all child folders recursively
- const childFolderIds = getDescendantFolderIds(folderId, allFolders);
+ const childFolderIds = getDescendantFolderIds(folder, allFolders);
for (const childId of childFolderIds) {
- count += directFolderCounts.get(childId) || 0;
+ count += directFolderCounts.get(scopedKey(folder.ManifestId, childId)) || 0;
}
return count;
@@ -635,8 +638,9 @@ const ItemsList: React.FC = () => {
const personalManifestId = dbContext.sqliteClient.getPersonalManifestId();
const result = relevantFolders.map((folder: Folder) => ({
id: folder.Id,
+ manifestId: folder.ManifestId,
name: folder.Name,
- itemCount: getRecursiveItemCountLocal(folder.Id),
+ itemCount: getRecursiveItemCountLocal(folder),
isShared: isSharedFolder(folder, personalManifestId)
})).sort((a: { name: string }, b: { name: string }) => a.name.localeCompare(b.name));
@@ -649,18 +653,18 @@ const ItemsList: React.FC = () => {
const filteredItems = ((): Item[] => {
// Filter by current folder (if in folder view)
let folderScoped: Item[];
- if (currentFolderId !== null) {
+ if (currentFolderRef !== null) {
if (searchTerm) {
// When searching inside a folder, include items in subfolders too
const allFolders = dbContext?.sqliteClient?.folders.getAll() || [];
- const childFolderIds = getDescendantFolderIds(currentFolderId, allFolders);
- const allFolderIds = [currentFolderId, ...childFolderIds];
+ const childFolderIds = getDescendantFolderIds(currentFolderRef, allFolders);
+ const allFolderIds = [currentFolderRef.Id, ...childFolderIds];
folderScoped = items.filter((item: Item) =>
- item.FolderId !== null && item.FolderId !== undefined && allFolderIds.includes(item.FolderId)
+ item.ManifestId === currentFolderRef.ManifestId && item.FolderId !== null && item.FolderId !== undefined && allFolderIds.includes(item.FolderId)
);
} else {
// When not searching, only show direct items (not items in subfolders)
- folderScoped = items.filter((item: Item) => item.FolderId === currentFolderId);
+ folderScoped = items.filter((item: Item) => isItemInFolder(item, currentFolderRef));
}
} else if (!searchTerm && showFolders) {
/*
@@ -706,28 +710,28 @@ const ItemsList: React.FC = () => {
* Used for the delete folder modal to show accurate count.
*/
const totalItemCountInFolderTree = useMemo(() => {
- if (!currentFolderId || !dbContext?.sqliteClient) {
+ if (!currentFolderRef || !dbContext?.sqliteClient) {
return filteredItems.length;
}
const allFolders = dbContext.sqliteClient.folders.getAll();
- return getRecursiveItemCount(currentFolderId, items, allFolders);
- }, [currentFolderId, items, dbContext?.sqliteClient, filteredItems.length]);
+ return getRecursiveItemCount(currentFolderRef, items, allFolders);
+ }, [currentFolderRef, items, dbContext?.sqliteClient, filteredItems.length]);
/**
* Check if the current folder can have subfolders (not at max depth).
* At root level (currentFolderId = null), we can always create folders.
*/
const canCreateSubfolder = useMemo(() => {
- if (!currentFolderId) {
+ if (!currentFolderRef) {
return true; // Root level, always allowed
}
if (!dbContext?.sqliteClient) {
return false;
}
const allFolders = dbContext.sqliteClient.folders.getAll();
- return canHaveSubfolders(currentFolderId, allFolders);
- }, [currentFolderId, dbContext?.sqliteClient]);
+ return canHaveSubfolders(currentFolderRef, allFolders);
+ }, [currentFolderRef, dbContext?.sqliteClient]);
/**
* Check if all items are in folders (no items at root level but items exist in folders).
@@ -743,7 +747,7 @@ const ItemsList: React.FC = () => {
if (!item) {
return;
}
- const url = searchTerm ? `/items/${item.Id}?returnSearch=${encodeURIComponent(searchTerm)}` : `/items/${item.Id}`;
+ const url = searchTerm ? `${itemRoute(item)}?returnSearch=${encodeURIComponent(searchTerm)}` : itemRoute(item);
navigate(url);
}, [sortedItems, searchTerm, navigate]);
@@ -755,7 +759,7 @@ const ItemsList: React.FC = () => {
if (!folder) {
return;
}
- handleFolderClick(folder.id, folder.name);
+ handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId });
}, [folders, handleFolderClick]);
/**
@@ -769,24 +773,22 @@ const ItemsList: React.FC = () => {
* Go up one folder (ArrowLeft).
*/
const handleGoBack = useCallback((): void => {
- if (!currentFolderId || !dbContext?.sqliteClient) {
+ if (!currentFolderRef || !dbContext?.sqliteClient) {
return;
}
- const allFolders = dbContext.sqliteClient.folders.getAll();
- const current = allFolders.find((f: Folder) => f.Id === currentFolderId);
- const parentFolderId = current?.ParentFolderId ?? null;
+ const parentFolderId = dbContext.sqliteClient.folders.getById(currentFolderRef)?.ParentFolderId ?? null;
if (parentFolderId) {
- navigate(`/items/folder/${parentFolderId}`);
+ navigate(`/items/folder/${currentFolderRef.ManifestId}/${parentFolderId}`);
} else {
navigate('/items');
}
- }, [currentFolderId, dbContext, navigate]);
+ }, [currentFolderRef, dbContext, navigate]);
const { activeKind, activeIndex, itemIdFor, folderIdFor, activeDescendantId } = useListKeyboardNav({
folderCount: folders.length,
itemCount: sortedItems.length,
searchInputRef,
- resetKey: currentFolderId,
+ resetKey: currentFolderRef ? scopedKey(currentFolderRef.ManifestId, currentFolderRef.Id) : null,
onActivateFolder: handleActivateFolder,
onActivateItem: handleActivateItem,
onGoBack: handleGoBack,
@@ -804,7 +806,7 @@ const ItemsList: React.FC = () => {
return (
<div>
{/* Breadcrumb navigation - only show when inside a folder */}
- <FolderBreadcrumb folderId={currentFolderId} />
+ <FolderBreadcrumb folder={currentFolderRef} />
<div className="flex justify-between items-center gap-2 mb-4">
<div className="min-w-0 flex-1 flex items-center gap-2">
@@ -1005,9 +1007,9 @@ const ItemsList: React.FC = () => {
<div className="flex flex-wrap items-center gap-2 mb-4" role="listbox" aria-label={t('items.title')}>
{folders.map((folder, index) => (
<FolderPill
- key={folder.id}
+ key={scopedKey(folder.manifestId, folder.id)}
folder={folder}
- onClick={() => handleFolderClick(folder.id, folder.name)}
+ onClick={() => handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId })}
isActive={activeKind === 'folder' && activeIndex === index}
optionId={folderIdFor(index)}
isShared={folder.isShared}
@@ -1043,9 +1045,9 @@ const ItemsList: React.FC = () => {
<div className="flex flex-wrap items-center gap-2 mb-4" role="listbox" aria-label={t('items.title')}>
{folders.map((folder, index) => (
<FolderPill
- key={folder.id}
+ key={scopedKey(folder.manifestId, folder.id)}
folder={folder}
- onClick={() => handleFolderClick(folder.id, folder.name)}
+ onClick={() => handleFolderClick({ Id: folder.id, ManifestId: folder.manifestId })}
isActive={activeKind === 'folder' && activeIndex === index}
optionId={folderIdFor(index)}
isShared={folder.isShared}
@@ -1084,16 +1086,16 @@ const ItemsList: React.FC = () => {
<ul id="items-list" role="listbox" className="space-y-2">
{sortedItems.map((item, index) => (
<ItemCard
- key={item.Id}
+ key={scopedKey(item.ManifestId, item.Id)}
item={item}
showFolderPath={!!searchTerm && !!item.FolderPath}
searchTerm={searchTerm}
currentFolderPath={currentFolderPath}
isActive={activeKind === 'item' && activeIndex === index}
optionId={itemIdFor(index)}
- isHighlighted={item.Id === highlightedItemId}
+ isHighlighted={highlightedItem !== null && isSameItem(item, highlightedItem)}
onDuplicate={handleDuplicateItem}
- onDelete={setDeleteItemId}
+ onDelete={setDeleteItem}
/>
))}
</ul>
@@ -1143,8 +1145,8 @@ const ItemsList: React.FC = () => {
{/* Delete Item Confirmation Modal */}
<ConfirmDeleteModal
- isOpen={deleteItemId !== null}
- onClose={() => setDeleteItemId(null)}
+ isOpen={deleteItem !== null}
+ onClose={() => setDeleteItem(null)}
onConfirm={handleConfirmDeleteItem}
title={t('items.deleteItemTitle')}
message={t('items.deleteItemConfirm')}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/items/RecentlyDeleted.tsx b/apps/browser-extension/src/entrypoints/popup/pages/items/RecentlyDeleted.tsx
index 81c1eba76..7c13c3ab1 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/items/RecentlyDeleted.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/items/RecentlyDeleted.tsx
@@ -1,4 +1,5 @@
import { TRASH_RETENTION_DAYS } from '@aliasvault/client/constants/Vault';
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
import React, { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -13,6 +14,7 @@ import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
import { useMinDurationLoading } from '@/hooks/useMinDurationLoading';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
import type { ItemFilterType } from '@aliasvault/client/items/ItemFilters';
import type { Item } from '@aliasvault/models/vault';
@@ -40,7 +42,7 @@ const RecentlyDeleted: React.FC = () => {
const { executeVaultMutationAsync } = useVaultMutate();
const { setHeaderButtons } = useHeaderButtons();
const [items, setItems] = useState<Item[]>([]);
- const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
+ const [selectedItem, setSelectedItem] = useState<ItemRef | null>(null);
const [showConfirmDelete, setShowConfirmDelete] = useState(false);
const [showConfirmEmptyAll, setShowConfirmEmptyAll] = useState(false);
@@ -62,13 +64,13 @@ const RecentlyDeleted: React.FC = () => {
/**
* Restore an item from Recently Deleted.
*/
- const handleRestore = useCallback(async (itemId: string) => {
+ const handleRestore = useCallback(async (item: ItemRef) => {
if (!dbContext?.sqliteClient) {
return;
}
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.items.restore(itemId);
+ await dbContext.sqliteClient!.items.restore(item);
});
loadItems();
@@ -78,18 +80,18 @@ const RecentlyDeleted: React.FC = () => {
* Permanently delete an item.
*/
const handlePermanentDelete = useCallback(async () => {
- if (!dbContext?.sqliteClient || !selectedItemId) {
+ if (!dbContext?.sqliteClient || !selectedItem) {
return;
}
await executeVaultMutationAsync(async () => {
- await dbContext.sqliteClient!.items.permanentlyDelete(selectedItemId);
+ await dbContext.sqliteClient!.items.permanentlyDelete(selectedItem);
});
loadItems();
setShowConfirmDelete(false);
- setSelectedItemId(null);
- }, [dbContext?.sqliteClient, executeVaultMutationAsync, loadItems, selectedItemId]);
+ setSelectedItem(null);
+ }, [dbContext?.sqliteClient, executeVaultMutationAsync, loadItems, selectedItem]);
/**
* Empty all items from Recently Deleted (permanent delete all).
@@ -101,7 +103,7 @@ const RecentlyDeleted: React.FC = () => {
await executeVaultMutationAsync(async () => {
for (const item of items) {
- await dbContext.sqliteClient!.items.permanentlyDelete(item.Id, item.ManifestId);
+ await dbContext.sqliteClient!.items.permanentlyDelete(item);
}
});
@@ -136,7 +138,7 @@ const RecentlyDeleted: React.FC = () => {
*/
const handleCloseDeleteModal = useCallback(() => {
setShowConfirmDelete(false);
- setSelectedItemId(null);
+ setSelectedItem(null);
}, []);
if (isLoading) {
@@ -188,7 +190,7 @@ const RecentlyDeleted: React.FC = () => {
const daysRemaining = deletedAt ? getDaysRemaining(deletedAt) : TRASH_RETENTION_DAYS;
return (
- <li key={item.Id} className="relative">
+ <li key={scopedKey(item.ManifestId, item.Id)} className="relative">
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-3">
<div className="flex items-start gap-3">
{/* Item card content (simplified) */}
@@ -211,14 +213,14 @@ const RecentlyDeleted: React.FC = () => {
{/* Action buttons */}
<div className="flex items-center gap-2">
<button
- onClick={() => handleRestore(item.Id)}
+ onClick={() => handleRestore(item)}
className="px-3 py-1 text-sm bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded hover:bg-green-200 dark:hover:bg-green-900/50"
>
{t('recentlyDeleted.restore')}
</button>
<button
onClick={() => {
- setSelectedItemId(item.Id);
+ setSelectedItem({ Id: item.Id, ManifestId: item.ManifestId });
setShowConfirmDelete(true);
}}
className="px-3 py-1 text-sm bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400 rounded hover:bg-red-200 dark:hover:bg-red-900/50"
@@ -237,7 +239,7 @@ const RecentlyDeleted: React.FC = () => {
{/* Confirm Delete Modal */}
<ConfirmDeleteModal
- isOpen={showConfirmDelete && !!selectedItemId}
+ isOpen={showConfirmDelete && !!selectedItem}
onClose={handleCloseDeleteModal}
onConfirm={handlePermanentDelete}
title={t('recentlyDeleted.confirmDeleteTitle')}
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
index 76ce38049..5d3e78d8d 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyAuthenticate.tsx
@@ -1,3 +1,4 @@
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
import { extractDomain } from '@aliasvault/client/rust/RustCore';
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -28,7 +29,7 @@ const PasskeyAuthenticate: React.FC = () => {
const [request, setRequest] = useState<PendingPasskeyGetRequest | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
- const [availablePasskeys, setAvailablePasskeys] = useState<Array<{ id: string; itemId: string; displayName: string; rpId: string; serviceName?: string | null }>>([]);
+ const [availablePasskeys, setAvailablePasskeys] = useState<Array<{ id: string; itemId: string; manifestId: string; displayName: string; rpId: string; serviceName?: string | null }>>([]);
const [showBypassDialog, setShowBypassDialog] = useState(false);
const { isLocked } = useVaultLockRedirect();
const firstPasskeyRef = useRef<HTMLDivElement>(null);
@@ -82,9 +83,10 @@ const PasskeyAuthenticate: React.FC = () => {
}
// Map to display format
- setAvailablePasskeys(filteredPasskeys.map((pk: { Id: string; ItemId: string; DisplayName: string; ServiceName?: string | null; RpId: string; Username?: string | null }) => ({
+ setAvailablePasskeys(filteredPasskeys.map((pk: { Id: string; ItemId: string; ManifestId: string; DisplayName: string; ServiceName?: string | null; RpId: string; Username?: string | null }) => ({
id: pk.Id,
itemId: pk.ItemId,
+ manifestId: pk.ManifestId,
displayName: pk.DisplayName,
serviceName: pk.ServiceName,
rpId: pk.RpId,
@@ -118,7 +120,7 @@ const PasskeyAuthenticate: React.FC = () => {
*/
const handleKeyDown = (e: KeyboardEvent) : void => {
if (e.key === 'Enter' && !loading && availablePasskeys.length > 0) {
- handleUsePasskey(availablePasskeys[0].id);
+ handleUsePasskey(availablePasskeys[0]);
}
};
@@ -137,7 +139,7 @@ const PasskeyAuthenticate: React.FC = () => {
/**
* Handle passkey authentication
*/
- const handleUsePasskey = async (passkeyId: string) : Promise<void> => {
+ const handleUsePasskey = async (selected: { id: string; itemId: string; manifestId: string }) : Promise<void> => {
if (!request || !dbContext.sqliteClient) {
return;
}
@@ -147,20 +149,15 @@ const PasskeyAuthenticate: React.FC = () => {
try {
// Build the assertion from the selected passkey using the shared service.
- const credential = await buildPasskeyAssertion(dbContext.sqliteClient, request, passkeyId);
+ const credential = await buildPasskeyAssertion(dbContext.sqliteClient, request, selected.id, selected.manifestId);
- /*
- * Copy the linked TOTP code to the clipboard (if any).
- */
- const selected = availablePasskeys.find((pk) => pk.id === passkeyId);
- if (selected) {
- // Signing an assertion is a use of the item the passkey hangs off.
- sendMessage('RECORD_ITEM_USAGE', { itemId: selected.itemId, action: 'passkey' }).catch(() => {
- // Ignore errors
- });
-
- await copyTotpToClipboardIfEnabled(selected.itemId);
- }
+ // Signing an assertion is a use of the item the passkey hangs off.
+ sendMessage('RECORD_ITEM_USAGE', { itemId: selected.itemId, manifestId: selected.manifestId, action: 'passkey' }).catch(() => {
+ // Ignore errors
+ });
+
+ // Copy the linked TOTP code to the clipboard (if any).
+ await copyTotpToClipboardIfEnabled({ Id: selected.itemId, ManifestId: selected.manifestId });
/*
* Send response back
@@ -274,14 +271,14 @@ const PasskeyAuthenticate: React.FC = () => {
<div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2 bg-gray-50 dark:bg-gray-800">
{availablePasskeys.map((pk, index) => (
<div
- key={pk.id}
+ key={scopedKey(pk.manifestId, pk.id)}
ref={index === 0 ? firstPasskeyRef : null}
tabIndex={0}
className="p-3 rounded-lg border cursor-pointer transition-colors bg-white border-gray-200 hover:bg-gray-100 hover:border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:hover:bg-gray-600 dark:hover:border-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
- onClick={() => !loading && handleUsePasskey(pk.id)}
+ onClick={() => !loading && handleUsePasskey(pk)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !loading) {
- handleUsePasskey(pk.id);
+ handleUsePasskey(pk);
}
}}
>
diff --git a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
index 521eb877c..39953df41 100644
--- a/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
+++ b/apps/browser-extension/src/entrypoints/popup/pages/passkeys/PasskeyCreate.tsx
@@ -1,3 +1,5 @@
+import { scopedKey } from '@aliasvault/client/database/ItemRef';
+import { manifestForItemIn, type ItemRef } from '@aliasvault/client/database/ItemRef';
import { extractDomain, filterItems, AutofillMatchingMode } from '@aliasvault/client/rust/RustCore';
import { FieldKey, ItemTypes, getFieldValue, createSystemField } from '@aliasvault/models/vault';
import React, { useEffect, useRef, useState } from 'react';
@@ -15,13 +17,13 @@ import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';
import { useVaultLockRedirect } from '@/entrypoints/popup/hooks/useVaultLockRedirect';
import { useVaultMutate } from '@/entrypoints/popup/hooks/useVaultMutate';
+import { isSameItem } from '@/utils/ItemRoute';
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
import { PasskeyAuthenticator } from '@/utils/passkey/PasskeyAuthenticator';
import { PasskeyHelper } from '@/utils/passkey/PasskeyHelper';
import type { CreateRequest, PasskeyCreateCredentialResponse, PendingPasskeyCreateRequest } from '@/utils/passkey/types';
-import type { DraftItem } from '@aliasvault/client/database/ItemRef';
import type { Item, Passkey } from '@aliasvault/models/vault';
/**
@@ -40,8 +42,8 @@ const PasskeyCreate: React.FC = () => {
const { isLocked } = useVaultLockRedirect();
const [existingPasskeys, setExistingPasskeys] = useState<Array<Passkey & { Username?: string | null; Email?: string | null; ServiceName?: string | null }>>([]);
const [matchingItems, setMatchingItems] = useState<Item[]>([]);
- const [selectedPasskeyToReplace, setSelectedPasskeyToReplace] = useState<string | null>(null);
- const [selectedItemToAttach, setSelectedItemToAttach] = useState<string | null>(null);
+ const [selectedPasskeyToReplace, setSelectedPasskeyToReplace] = useState<ItemRef | null>(null);
+ const [selectedItemToAttach, setSelectedItemToAttach] = useState<ItemRef | null>(null);
const [showCreateForm, setShowCreateForm] = useState(false);
const [localLoading, setLocalLoading] = useState(false);
const [showBypassDialog, setShowBypassDialog] = useState(false);
@@ -228,8 +230,8 @@ const PasskeyCreate: React.FC = () => {
/**
* Handle when user selects an existing passkey to replace
*/
- const handleSelectReplace = (passkeyId: string) : void => {
- setSelectedPasskeyToReplace(passkeyId);
+ const handleSelectReplace = (passkey: ItemRef) : void => {
+ setSelectedPasskeyToReplace({ Id: passkey.Id, ManifestId: passkey.ManifestId });
setSelectedItemToAttach(null);
setShowCreateForm(true);
};
@@ -237,8 +239,8 @@ const PasskeyCreate: React.FC = () => {
/**
* Handle when user selects an existing item to attach the passkey to
*/
- const handleSelectItem = (itemId: string) : void => {
- setSelectedItemToAttach(itemId);
+ const handleSelectItem = (item: ItemRef) : void => {
+ setSelectedItemToAttach({ Id: item.Id, ManifestId: item.ManifestId });
setSelectedPasskeyToReplace(null);
setShowCreateForm(true);
};
@@ -321,13 +323,14 @@ const PasskeyCreate: React.FC = () => {
await executeVaultMutationAsync(async () => {
if (selectedPasskeyToReplace) {
// Replace existing passkey: update the item and passkey
- const existingPasskey = dbContext.sqliteClient!.passkeys.getById(selectedPasskeyToReplace);
+ const existingPasskey = dbContext.sqliteClient!.passkeys.getById(selectedPasskeyToReplace.Id, selectedPasskeyToReplace.ManifestId);
if (existingPasskey) {
// Get existing item to preserve its data
- const existingItem = dbContext.sqliteClient!.items.getById(existingPasskey.ItemId);
+ const existingItem = dbContext.sqliteClient!.items.getById({ Id: existingPasskey.ItemId, ManifestId: existingPasskey.ManifestId });
if (existingItem) {
// Update the parent item with new favicon and user-provided display name
await dbContext.sqliteClient!.items.update(
+ existingItem,
{
...existingItem,
Name: displayName,
@@ -344,7 +347,7 @@ const PasskeyCreate: React.FC = () => {
}
// Delete the old passkey
- await dbContext.sqliteClient!.passkeys.deleteById(selectedPasskeyToReplace, existingPasskey?.ManifestId);
+ await dbContext.sqliteClient!.passkeys.deleteById(selectedPasskeyToReplace.Id, selectedPasskeyToReplace.ManifestId);
/**
* Create new passkey with same item
@@ -363,6 +366,7 @@ const PasskeyCreate: React.FC = () => {
await dbContext.sqliteClient!.passkeys.create({
Id: newPasskeyGuid,
ItemId: existingPasskey.ItemId,
+ ManifestId: existingPasskey.ManifestId,
RpId: stored.rpId,
UserHandle: userHandleBytes,
PublicKey: JSON.stringify(stored.publicKey),
@@ -390,7 +394,8 @@ const PasskeyCreate: React.FC = () => {
await dbContext.sqliteClient!.passkeys.create({
Id: newPasskeyGuid,
- ItemId: selectedItemToAttach,
+ ItemId: selectedItemToAttach.Id,
+ ManifestId: selectedItemToAttach.ManifestId,
RpId: stored.rpId,
UserHandle: userHandleBytes,
PublicKey: JSON.stringify(stored.publicKey),
@@ -401,8 +406,9 @@ const PasskeyCreate: React.FC = () => {
});
} else {
// Create new item and passkey
- const newItem: DraftItem = {
+ const newItem: Item = {
Id: '',
+ ManifestId: manifestForItemIn(null, dbContext.sqliteClient!.getPersonalManifestId()),
Name: displayName,
ItemType: ItemTypes.Login,
Logo: faviconLogo,
@@ -414,7 +420,7 @@ const PasskeyCreate: React.FC = () => {
UpdatedAt: new Date().toISOString()
};
- const itemId = await dbContext.sqliteClient!.items.create(newItem, []);
+ const createdItem = await dbContext.sqliteClient!.items.create(newItem, []);
/**
* Create the Passkey linked to the item
@@ -433,7 +439,8 @@ const PasskeyCreate: React.FC = () => {
await dbContext.sqliteClient!.passkeys.create({
Id: newPasskeyGuid,
- ItemId: itemId,
+ ItemId: createdItem.Id,
+ ManifestId: createdItem.ManifestId,
RpId: stored.rpId,
UserHandle: userHandleBytes,
PublicKey: JSON.stringify(stored.publicKey),
@@ -629,8 +636,8 @@ const PasskeyCreate: React.FC = () => {
<div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2 bg-gray-50 dark:bg-gray-800">
{existingPasskeys.map((passkey) => (
<button
- key={passkey.Id}
- onClick={() => handleSelectReplace(passkey.Id)}
+ key={scopedKey(passkey.ManifestId, passkey.Id)}
+ onClick={() => handleSelectReplace(passkey)}
className="w-full p-3 text-left rounded-lg border cursor-pointer transition-colors bg-white border-gray-200 hover:bg-gray-100 hover:border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:hover:bg-gray-600 dark:hover:border-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
>
<div className="flex items-center justify-between">
@@ -699,8 +706,8 @@ const PasskeyCreate: React.FC = () => {
<div className="space-y-2 max-h-48 overflow-y-auto border rounded-lg p-2 bg-gray-50 dark:bg-gray-800">
{matchingItems.map((item) => (
<button
- key={item.Id}
- onClick={() => handleSelectItem(item.Id)}
+ key={scopedKey(item.ManifestId, item.Id)}
+ onClick={() => handleSelectItem(item)}
className="w-full p-3 text-left rounded-lg border cursor-pointer transition-colors bg-white border-gray-200 hover:bg-gray-100 hover:border-gray-300 dark:bg-gray-700 dark:border-gray-600 dark:hover:bg-gray-600 dark:hover:border-gray-500 focus:outline-none focus:ring-1 focus:ring-primary-500 focus:border-primary-500"
>
<div className="flex items-center justify-between">
@@ -740,7 +747,7 @@ const PasskeyCreate: React.FC = () => {
{selectedPasskeyToReplace && (
<Alert variant="warning">
{t('passkeys.create.replacingPasskey', {
- displayName: existingPasskeys.find(p => p.Id === selectedPasskeyToReplace)?.DisplayName || ''
+ displayName: existingPasskeys.find(p => isSameItem(p, selectedPasskeyToReplace))?.DisplayName || ''
})}
</Alert>
)}
@@ -748,7 +755,7 @@ const PasskeyCreate: React.FC = () => {
{selectedItemToAttach && (
<Alert variant="info">
{t('passkeys.create.attachingToCredential', {
- serviceName: matchingItems.find(i => i.Id === selectedItemToAttach)?.Name || ''
+ serviceName: matchingItems.find(i => isSameItem(i, selectedItemToAttach))?.Name || ''
})}
</Alert>
)}
diff --git a/apps/browser-extension/src/utils/FaviconService.ts b/apps/browser-extension/src/utils/FaviconService.ts
index 406fa5ed3..7a13bee63 100644
--- a/apps/browser-extension/src/utils/FaviconService.ts
+++ b/apps/browser-extension/src/utils/FaviconService.ts
@@ -3,9 +3,9 @@ import { Buffer } from 'buffer';
import { selectFaviconTarget, toUrlList } from '@aliasvault/client/rust/RustCore';
import type { WebApiService } from '@aliasvault/client/api/WebApiService';
-import type { DraftItem } from '@aliasvault/client/database/ItemRef';
import type { SqliteClient } from '@aliasvault/client/database/SqliteClient';
import type { FaviconTarget } from '@aliasvault/client/rust/RustCore';
+import type { Item } from '@aliasvault/models/vault';
/**
* Result of a favicon fetch operation.
@@ -116,11 +116,11 @@ export class FaviconService {
* @returns The updated item with Logo attached (if favicon was fetched), or cleared when nothing was fetched
*/
public static async fetchAndAttachFavicon(
- item: DraftItem,
+ item: Item,
urlFieldValue: string | string[] | undefined | null,
sqliteClient: SqliteClient,
webApi: WebApiService
- ): Promise<DraftItem> {
+ ): Promise<Item> {
const target = await FaviconService.resolveTarget(urlFieldValue);
// No valid URL found: clear any existing logo.
diff --git a/apps/browser-extension/src/utils/ItemRoute.ts b/apps/browser-extension/src/utils/ItemRoute.ts
new file mode 100644
index 000000000..6778feedd
--- /dev/null
+++ b/apps/browser-extension/src/utils/ItemRoute.ts
@@ -0,0 +1,21 @@
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+
+/**
+ * The popup route of an item.
+ * @param item - The item, named by its manifest and id
+ * @param edit - True for the edit page instead of the details page
+ * @returns The route path
+ */
+export function itemRoute(item: ItemRef, edit: boolean = false): string {
+ return `/items/${encodeURIComponent(item.ManifestId)}/${encodeURIComponent(item.Id)}${edit ? '/edit' : ''}`;
+}
+
+/**
+ * Whether two references name the same item: same id inside the same manifest.
+ * @param a - One item
+ * @param b - The other item
+ * @returns True when both halves match
+ */
+export function isSameItem(a: ItemRef, b: ItemRef): boolean {
+ return a.Id === b.Id && a.ManifestId === b.ManifestId;
+}
diff --git a/apps/browser-extension/src/utils/RecentlySelectedItemService.ts b/apps/browser-extension/src/utils/RecentlySelectedItemService.ts
index 6e2aa7f20..86768f838 100644
--- a/apps/browser-extension/src/utils/RecentlySelectedItemService.ts
+++ b/apps/browser-extension/src/utils/RecentlySelectedItemService.ts
@@ -1,5 +1,7 @@
import { StorageKeys } from '@/utils/constants/storageKeys';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+
import { storage } from '#imports';
/**
@@ -12,6 +14,7 @@ const TTL_MS = 60 * 1000;
*/
export interface IRecentlySelectedItem {
itemId: string;
+ manifestId: string;
timestamp: number;
domain: string;
}
@@ -27,12 +30,13 @@ export interface IRecentlySelectedItem {
export const RecentlySelectedItemService = {
/**
* Store a recently selected item with the current timestamp.
- * @param itemId - The ID of the item that was selected
+ * @param item - The item that was selected, named by its manifest and id
* @param domain - The domain where the item was used (for scoping)
*/
- async setRecentlySelected(itemId: string, domain: string): Promise<void> {
+ async setRecentlySelected(item: ItemRef, domain: string): Promise<void> {
const data: IRecentlySelectedItem = {
- itemId,
+ itemId: item.Id,
+ manifestId: item.ManifestId,
timestamp: Date.now(),
domain,
};
@@ -42,9 +46,9 @@ export const RecentlySelectedItemService = {
/**
* Get the recently selected item if it exists and is not expired.
* @param domain - The current domain to check against
- * @returns The item ID if valid, or null if expired or not matching domain
+ * @returns The item if valid, or null if expired or not matching domain
*/
- async getRecentlySelected(domain: string): Promise<string | null> {
+ async getRecentlySelected(domain: string): Promise<ItemRef | null> {
const data = await storage.getItem(StorageKeys.RECENTLY_SELECTED_ITEM) as IRecentlySelectedItem | null;
if (!data) {
@@ -63,7 +67,7 @@ export const RecentlySelectedItemService = {
return null;
}
- return data.itemId;
+ return { Id: data.itemId, ManifestId: data.manifestId };
},
/**
@@ -72,8 +76,7 @@ export const RecentlySelectedItemService = {
* @returns True if a valid recently selected item exists
*/
async hasRecentlySelected(domain: string): Promise<boolean> {
- const itemId = await this.getRecentlySelected(domain);
- return itemId !== null;
+ return (await this.getRecentlySelected(domain)) !== null;
},
/**
diff --git a/apps/browser-extension/src/utils/TotpClipboard.ts b/apps/browser-extension/src/utils/TotpClipboard.ts
index acc88094e..87fac555f 100644
--- a/apps/browser-extension/src/utils/TotpClipboard.ts
+++ b/apps/browser-extension/src/utils/TotpClipboard.ts
@@ -1,20 +1,22 @@
import { LocalPreferencesService } from '@/utils/LocalPreferencesService';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
+
/**
* Copy an item's current TOTP code to the clipboard (only when the user has the copy-on-fill
* setting enabled, which is the default).
*
- * @param itemId - The ID of the item being filled.
+ * @param item - The item being filled, named by its manifest and id.
*/
-export async function copyTotpToClipboardIfEnabled(itemId: string): Promise<void> {
+export async function copyTotpToClipboardIfEnabled(item: ItemRef): Promise<void> {
try {
if (!await LocalPreferencesService.getAutoCopyTotpOnAutofill()) {
return;
}
// Generate TOTP code via background
- const response = await sendMessage('GENERATE_TOTP_CODE', { itemId });
+ const response = await sendMessage('GENERATE_TOTP_CODE', { itemId: item.Id, manifestId: item.ManifestId });
if (!response.success || !response.code) {
return;
diff --git a/apps/browser-extension/src/utils/loginDetector/types.ts b/apps/browser-extension/src/utils/loginDetector/types.ts
index 87eeb22d9..dcbcd25b4 100644
--- a/apps/browser-extension/src/utils/loginDetector/types.ts
+++ b/apps/browser-extension/src/utils/loginDetector/types.ts
@@ -1,6 +1,7 @@
/**
* Types for login detection and credential saving functionality.
*/
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
/**
* Represents login credentials captured from a form submission.
@@ -47,8 +48,6 @@ export type SavePromptConfig = {
login: CapturedLogin;
/** Whether this appears to be a duplicate */
isDuplicate: boolean;
- /** If duplicate, the ID of the matching item */
- matchingItemId?: string;
};
/**
@@ -76,7 +75,7 @@ export type AddUrlPromptOptions = {
/** The existing credential that was autofilled */
existingCredential: LastAutofilledCredential;
/** Callback when user clicks "Add URL" */
- onAddUrl: (itemId: string, url: string) => void;
+ onAddUrl: (item: ItemRef, url: string) => void;
/** Callback when prompt is dismissed */
onDismiss: () => void;
/** Auto-dismiss timeout in milliseconds (default: 15000) */
@@ -139,6 +138,8 @@ export type SavePromptPersistedState = {
export type LastAutofilledCredential = {
/** The ID of the item that was autofilled */
itemId: string;
+ /** The manifest of the item that was autofilled */
+ manifestId: string;
/** The name of the item (for display in the prompt) */
itemName: string;
/** The username that was filled */
diff --git a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
index 588bfae24..ea4a2ec2a 100644
--- a/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
+++ b/apps/browser-extension/src/utils/messaging/ExtensionMessaging.ts
@@ -34,6 +34,7 @@ import type { VaultSyncPhase } from '@/utils/types/messaging/VaultSyncPhase';
import type { VaultSyncState } from '@/utils/types/messaging/VaultSyncState';
import type { ItemUsageAction } from '@aliasvault/client/database';
+import type { ItemRef } from '@aliasvault/client/database/ItemRef';
import type { VaultMigrationKind } from '@aliasvault/client/sync/VaultManifestMigration';
import type { VaultMutationScope } from '@aliasvault/client/sync/VaultMutationScope';
import type { FullVaultSyncResult, VaultManifestMigrationResult } from '@aliasvault/client/sync/VaultSync';
@@ -49,7 +50,7 @@ import type { LoginResponse } from '@aliasvault/models/webapi';
* the response shape (promises are unwrapped automatically by the library).
*/
export interface IExtensionMessageProtocol {
- ADD_URL_TO_CREDENTIAL(data: { itemId: string; url: string }): { success: boolean; error?: string };
+ ADD_URL_TO_CREDENTIAL(data: { itemId: string; manifestId: string; url: string }): { success: boolean; error?: string };
AUTOFILL_CREATED_ITEM(data: { item: any; elementIdentifier?: string }): BoolResponse;
CANCEL_CLIPBOARD_CLEAR(): void;
CHECK_AUTH_STATUS(): { isLoggedIn: boolean; isVaultLocked: boolean; requiresLegacySqliteBlobMigration: boolean; requiresManifestMigration: boolean; error?: string };
@@ -67,7 +68,7 @@ export interface IExtensionMessageProtocol {
CLIPBOARD_COUNTDOWN_CANCELLED(data: Record<string, never>): void;
FULL_VAULT_SYNC(data: FullVaultSyncRequest): FullVaultSyncResult;
GENERATE_PASSWORD(data: { settings: PasswordSettings }): { success: boolean; password?: string; error?: string };
- GENERATE_TOTP_CODE(data: { itemId: string }): { success: boolean; code?: string; error?: string };
+ GENERATE_TOTP_CODE(data: { itemId: string; manifestId: string }): { success: boolean; code?: string; error?: string };
GET_CLIPBOARD_CLEAR_TIMEOUT(): number;
GET_CLIPBOARD_COUNTDOWN_STATE(): { remaining: number; total: number; id: number } | null;
GET_DEFAULT_EMAIL_DOMAIN(): StringResponse;
@@ -82,12 +83,12 @@ export interface IExtensionMessageProtocol {
GET_MATCHING_PASSKEYS(data: { rpId: string; allowCredentialIds?: string[] }): MatchingPasskeysResponse;
GET_PASSWORD_SETTINGS(): PasswordSettingsResponse;
GET_PERSISTED_FORM_VALUES(): any | null;
- GET_RECENTLY_SELECTED(data: { domain: string }): { success: boolean; itemId?: string | null };
+ GET_RECENTLY_SELECTED(data: { domain: string }): { success: boolean; itemId?: string | null; manifestId?: string | null };
GET_REQUEST_DATA(data: any): PendingPasskeyRequest | null;
GET_SAVE_PROMPT_STATE(): { success: boolean; state: SavePromptPersistedState | null };
GET_SEARCH_ITEMS(data: { searchTerm: string }): ItemsResponse;
GET_SYNC_STATE(): VaultSyncState;
- GET_TOTP_SECRETS(data: { itemIds: string[] }): { success: boolean; secrets?: Record<string, TotpSecret>; error?: string };
+ GET_TOTP_SECRETS(data: { items: ItemRef[] }): { success: boolean; secrets?: Record<string, TotpSecret>; error?: string };
GET_TWO_FACTOR_STATE(): TwoFactorState | null;
GET_VAULT(): VaultResponse;
GET_VAULT_MIGRATION_STATUS(): VaultMigrationKind;
@@ -95,26 +96,26 @@ export interface IExtensionMessageProtocol {
GROUP_CREATE_VAULT(data: { groupId: string; name: string }): { success: boolean; error?: string; apiErrorCode?: string };
GROUP_INVITE_MEMBER(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
GROUP_REVOKE_ACCESS(data: { groupId: string; manifestId: string; userId: string }): { success: boolean; error?: string; apiErrorCode?: string };
- IS_URL_LINKED_TO_CREDENTIAL(data: { itemId: string; url: string }): { linked: boolean };
+ IS_URL_LINKED_TO_CREDENTIAL(data: { itemId: string; manifestId: string; url: string }): { linked: boolean };
LOCK_VAULT(): BoolResponse;
MARK_VAULT_CLEAN(data: { mutationSeqAtStart: number }): { cleared: boolean; currentMutationSeq: number };
MIGRATE_VAULT_MANIFEST(): VaultManifestMigrationResult;
OPEN_AUTOFILL_POPUP(data: { elementIdentifier: string; popupType?: string }): BoolResponse;
OPEN_POPUP(): BoolResponse;
OPEN_POPUP_CREATE_CREDENTIAL(data: { itemTitle?: string; currentUrl?: string; elementIdentifier?: string; left?: number; top?: number }): BoolResponse;
- OPEN_POPUP_WITH_ITEM(data: any): BoolResponse;
+ OPEN_POPUP_WITH_ITEM(data: { itemId: string; manifestId: string }): BoolResponse;
PASSKEY_POPUP_RESPONSE(data: any): { success: boolean };
PERSIST_FORM_VALUES(data: any): void;
PING(): boolean;
POPUP_HEARTBEAT(): void;
- RECORD_ITEM_USAGE(data: { itemId: string; action: ItemUsageAction }): { success: boolean };
+ RECORD_ITEM_USAGE(data: { itemId: string; manifestId: string; action: ItemUsageAction }): { success: boolean };
RESET_AUTO_LOCK_TIMER(): void;
SAVE_LOGIN_CREDENTIAL(data: { serviceName: string; username: string; password: string; url: string; domain: string; logoBase64?: string; faviconUrl?: string }): SaveLoginResponse;
SEARCH_ITEMS_WITH_TOTP(data: { searchTerm: string }): ItemsResponse;
SET_AUTO_LOCK_TIMEOUT(data: number): boolean;
SET_CLIPBOARD_CLEAR_TIMEOUT(data: number): boolean;
SET_LOGIN_SAVE_ENABLED(data: boolean): BoolResponse;
- SET_RECENTLY_SELECTED(data: { itemId: string; domain: string }): { success: boolean };
+ SET_RECENTLY_SELECTED(data: { itemId: string; manifestId: string; domain: string }): { success: boolean };
STORE_ENCRYPTED_VAULT(data: { vaultBlob: string; markDirty?: boolean; expectedMutationSeq?: number; scopes?: VaultMutationScope[] }): { success: boolean; mutationSequence: number };
STORE_UNLOCK_KEY(data: string): BoolResponse;
STORE_UNLOCK_KEY_DERIVATION_PARAMS(data: UnlockKeyDerivationParams): BoolResponse;
@@ -126,7 +127,7 @@ export interface IExtensionMessageProtocol {
VAULT_UNLOCKED(): void;
WEBAUTHN_CREATE(data: any): any;
WEBAUTHN_GET(data: any): any;
- WEBAUTHN_GET_ASSERTION(data: { passkeyId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload }): WebAuthnAssertionResponse;
+ WEBAUTHN_GET_ASSERTION(data: { passkeyId: string; manifestId: string; origin: string; publicKey: WebAuthnPublicKeyGetPayload }): WebAuthnAssertionResponse;
}
/* eslint-enable @typescript-eslint/no-explicit-any */
diff --git a/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts
index 77e5e9f83..388b56a31 100644
--- a/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts
+++ b/apps/browser-extension/src/utils/passkey/PasskeyAssertionService.ts
@@ -79,15 +79,17 @@ function extractPrfInputs(
* @param sqliteClient - An initialized client for the unlocked vault.
* @param request - The pending `get` request (origin + publicKey challenge).
* @param passkeyId - The vault ID (GUID) of the passkey the user selected.
+ * @param manifestId - The manifest that passkey belongs to.
* @returns The assertion response ready to hand back to the relying party.
* @throws If the passkey does not exist in the vault.
*/
export async function buildPasskeyAssertion(
sqliteClient: SqliteClient,
request: PasskeyAssertionRequest,
- passkeyId: string
+ passkeyId: string,
+ manifestId: string
): Promise<PasskeyGetCredentialResponse> {
- const storedPasskey = sqliteClient.passkeys.getById(passkeyId);
+ const storedPasskey = sqliteClient.passkeys.getById(passkeyId, manifestId);
if (!storedPasskey) {
throw new Error(`Passkey not found for id ${passkeyId}`);
}
diff --git a/apps/browser-extension/src/utils/passkey/types.ts b/apps/browser-extension/src/utils/passkey/types.ts
index 37a9abb81..a6ec2ba8c 100644
--- a/apps/browser-extension/src/utils/passkey/types.ts
+++ b/apps/browser-extension/src/utils/passkey/types.ts
@@ -87,6 +87,7 @@ export type WebAuthnSettingsResponse = {
export type ConditionalPasskeyOption = {
id: string;
itemId: string;
+ manifestId: string;
serviceName: string;
username: string;
logo: number[] | null;
diff --git a/apps/browser-extension/src/utils/types/messaging/DuplicateCheckResponse.ts b/apps/browser-extension/src/utils/types/messaging/DuplicateCheckResponse.ts
index 6d105456e..8abe570e0 100644
--- a/apps/browser-extension/src/utils/types/messaging/DuplicateCheckResponse.ts
+++ b/apps/browser-extension/src/utils/types/messaging/DuplicateCheckResponse.ts
@@ -4,7 +4,5 @@
export type DuplicateCheckResponse = {
success: boolean;
isDuplicate: boolean;
- matchingItemId?: string;
- matchingItemName?: string;
error?: string;
};
diff --git a/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts b/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts
index bb080a388..d8894f65c 100644
--- a/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts
+++ b/apps/browser-extension/src/utils/types/messaging/ItemsResponse.ts
@@ -1,8 +1,9 @@
+import type { ItemRef } from "@aliasvault/client/database/ItemRef";
import type { Item } from "@aliasvault/models/vault";
export type ItemsResponse = {
success: boolean,
error?: string,
items?: Item[],
- recentlySelectedId?: string | null
+ recentlySelected?: ItemRef | null
};
diff --git a/apps/browser-extension/src/utils/types/messaging/SaveLoginResponse.ts b/apps/browser-extension/src/utils/types/messaging/SaveLoginResponse.ts
index d074e53c9..ada7c0490 100644
--- a/apps/browser-extension/src/utils/types/messaging/SaveLoginResponse.ts
+++ b/apps/browser-extension/src/utils/types/messaging/SaveLoginResponse.ts
@@ -4,5 +4,6 @@
export type SaveLoginResponse = {
success: boolean;
itemId?: string;
+ manifestId?: string;
error?: string;
};
diff --git a/core/client/src/database/BaseRepository.ts b/core/client/src/database/BaseRepository.ts
index 209fde8c4..27eb3b4f7 100644
--- a/core/client/src/database/BaseRepository.ts
+++ b/core/client/src/database/BaseRepository.ts
@@ -2,7 +2,6 @@ import { DEFAULT_VAULT_MUTATION_SCOPE } from '../sync/VaultMutationScope';
import * as dateFormatter from '../utilities/DateFormatter';
import { runAsync } from './DbOp';
-import { BaseQueries } from './queries/BaseQueries';
import type { DbOp, ManifestScope } from './DbOp';
import type { ISqliteDatabase } from '../platform/SqliteEngine';
@@ -113,40 +112,6 @@ export abstract class BaseRepository {
return manifestId;
}
- /**
- * The manifest a manifest-scoped row belongs to, looked up from the row itself.
- * @param table - The manifest-scoped table to look in
- * @param id - The row id
- * @param column - The column `id` names, when it is not the primary key
- * @returns The manifest id, or null when no such row exists
- */
- protected *resolveRowManifestId(table: string, id: string, column: string = 'Id'): DbOp<string | null> {
- const rows = yield* this.query<{ ManifestId: string }>(`SELECT ManifestId FROM ${table} WHERE ${column} = ? ORDER BY ManifestId`, [id]);
- if (rows.length === 0) {
- return null;
- }
-
- const { active, personal } = yield* this.manifestScope();
- const preferredId = active ?? personal;
- return (rows.find(row => row.ManifestId === preferredId) ?? rows[0]).ManifestId;
- }
-
- /**
- * The manifest a row placed in the given folder belongs to: that folder's, or the write manifest when the row
- * sits outside any folder. The same value the write path stamps (see {@link BaseQueries.MANIFEST_OF_FOLDER}).
- * @param folderId - The folder the row is placed in, or null for none
- * @returns The manifest id to stamp the row with
- */
- protected *manifestOfFolder(folderId: string | null): DbOp<string> {
- const fallbackManifestId = yield* this.writeManifestId();
- const rows = yield* this.query<{ ManifestId: string | null }>(BaseQueries.GET_MANIFEST_OF_FOLDER, [folderId, fallbackManifestId]);
- const manifestId = rows[0]?.ManifestId;
- if (!manifestId) {
- throw new Error('BaseRepository: could not resolve the manifest for this write; refusing to write a row that names no manifest.');
- }
- return manifestId;
- }
-
/**
* Hard delete manifest-scoped records by a foreign key, within one manifest.
* @param table - The table name
diff --git a/core/client/src/database/ItemRef.ts b/core/client/src/database/ItemRef.ts
index 357c1f27e..74d67af66 100644
--- a/core/client/src/database/ItemRef.ts
+++ b/core/client/src/database/ItemRef.ts
@@ -1,5 +1,3 @@
-import type { Item } from '@aliasvault/models/vault';
-
/**
* A manifest-qualified reference to an item: the only thing that names one item in the vault.
*
@@ -13,17 +11,13 @@ export type ItemRef = {
};
/**
- * The grouping key for a manifest-scoped row: its manifest and its id, in that order.
- *
- * Used wherever rows fetched by one query are joined to rows fetched by another (items to their
- * fields, items to their tags, items to their folder paths). Keying those maps by id alone would let
- * one manifest's rows land on another manifest's item.
+ * The grouping key for a manifest-scoped row: its manifest and its id, separated by a pipe symbol.
* @param manifestId - The owning manifest's id
* @param id - The row's id within that manifest
* @returns A key unique across manifests
*/
export function scopedKey(manifestId: string, id: string): string {
- return `${manifestId}${id}`;
+ return `${manifestId}|${id}`;
}
/**
@@ -37,10 +31,15 @@ export function itemKeyBindings(refs: ItemRef[]): string[] {
}
/**
- * An item as the UI holds it, whose manifest may not be decided yet.
- *
- * A new item has no manifest until the vault writes it: which manifest it lands in follows from the
- * folder it is created in. Everything read back out of the vault is a full {@link Item} and carries
- * one, so this is only ever wider than an Item, never narrower.
+ * The manifest a new item belongs in: the one its folder is in, or the personal manifest outside any folder.
+ * @param folder - The folder the item is created in, or null for none
+ * @param personalManifestId - The user's personal manifest id
+ * @returns The manifest id to set on the item
*/
-export type DraftItem = Omit<Item, 'ManifestId'> & { ManifestId?: string };
+export function manifestForItemIn(folder: { ManifestId: string } | null | undefined, personalManifestId: string | null | undefined): string {
+ const manifestId = folder?.ManifestId ?? personalManifestId;
+ if (!manifestId) {
+ throw new Error('This client has no personal manifest recorded yet; sync once before writing.');
+ }
+ return manifestId;
+}
diff --git a/core/client/src/database/__tests__/FieldValueRows.test.ts b/core/client/src/database/__tests__/FieldValueRows.test.ts
index eec22a094..c4b21a2ed 100644
--- a/core/client/src/database/__tests__/FieldValueRows.test.ts
+++ b/core/client/src/database/__tests__/FieldValueRows.test.ts
@@ -8,8 +8,7 @@ import { LogoRepository } from '../repositories/LogoRepository';
import type { ISqliteDatabase, SqliteValue } from '../../platform/SqliteEngine';
import type { ISyncDatabaseClient, SqliteBindValue } from '../BaseRepository';
-import type { DraftItem } from '../ItemRef';
-import type { ItemField } from '@aliasvault/models/vault';
+import type { Item, ItemField } from '@aliasvault/models/vault';
const PERSONAL = '11111111-1111-4111-8111-111111111111';
const ITEM = '33333333-3333-4333-8333-333333333333';
@@ -126,7 +125,7 @@ async function vaultWithItem(fields: ItemField[]): Promise<{ db: ISqliteDatabase
/**
* The item as the form hands it over, holding the given fields.
*/
- const draft = (itemFields: ItemField[]): DraftItem => ({ Id: ITEM, Name: 'Note', ItemType: ItemTypes.Note, Fields: itemFields, CreatedAt: '', UpdatedAt: '' } as DraftItem);
+ const draft = (itemFields: ItemField[]): Item => ({ Id: ITEM, ManifestId: PERSONAL, Name: 'Note', ItemType: ItemTypes.Note, Fields: itemFields, CreatedAt: '', UpdatedAt: '' } as Item);
await repository.create(draft(fields));
return {
@@ -135,7 +134,7 @@ async function vaultWithItem(fields: ItemField[]): Promise<{ db: ISqliteDatabase
* Save the item again with the given fields.
*/
save: async (next: ItemField[]): Promise<void> => {
- expect(await repository.update(draft(next))).toBe(1);
+ expect(await repository.update({ Id: ITEM, ManifestId: PERSONAL }, draft(next))).toEqual({ Id: ITEM, ManifestId: PERSONAL });
},
};
}
diff --git a/core/client/src/database/__tests__/LogoScoping.test.ts b/core/client/src/database/__tests__/LogoScoping.test.ts
index b4dd875e3..9f5d91b12 100644
--- a/core/client/src/database/__tests__/LogoScoping.test.ts
+++ b/core/client/src/database/__tests__/LogoScoping.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, it } from 'vitest';
import { getPlatform } from '../../platform/ClientPlatform';
-import { BaseQueries } from '../queries/BaseQueries';
import { LogoQueries } from '../queries/LogoQueries';
import type { ISqliteDatabase, SqliteValue } from '../../platform/SqliteEngine';
@@ -40,14 +39,6 @@ function rows(db: ISqliteDatabase, sql: string, params: SqliteValue[] = []): Rec
}
describe('logo manifest scoping', () => {
- it('GET_MANIFEST_OF_FOLDER agrees with what an insert would stamp', async () => {
- const db = await makeDb();
- expect(rows(db, BaseQueries.GET_MANIFEST_OF_FOLDER, ['FOLDER-SHARED', PERSONAL])[0].ManifestId).toBe(SHARED);
- expect(rows(db, BaseQueries.GET_MANIFEST_OF_FOLDER, ['FOLDER-MINE', PERSONAL])[0].ManifestId).toBe(PERSONAL);
- expect(rows(db, BaseQueries.GET_MANIFEST_OF_FOLDER, [null, PERSONAL])[0].ManifestId).toBe(PERSONAL);
- expect(rows(db, BaseQueries.GET_MANIFEST_OF_FOLDER, [null, SHARED])[0].ManifestId).toBe(SHARED);
- });
-
it('GET_BEST_FOR_KEY prefers the copy that actually carries bytes', async () => {
const db = await makeDb();
db.run(`INSERT INTO Logos VALUES ('${SHARED}','L-SHARED','favicon','github.com',NULL,NULL,'empty','t','2026-01-02',0)`);
@@ -62,10 +53,10 @@ describe('logo manifest scoping', () => {
db.run(`INSERT INTO Items VALUES ('${SHARED}','ITEM-MOVED','L-PERSONAL','FOLDER-SHARED',0)`);
/*
- * The write path reads the item's current logo by id alone, so the built-in logo the user picked is
- * still found and kept instead of being replaced by the domain's favicon.
+ * The write path prefers the item's own manifest but still finds the logo row the item came with, so the
+ * built-in logo the user picked is kept instead of being replaced by the domain's favicon.
*/
- expect(rows(db, LogoQueries.GET_BY_ID, ['L-PERSONAL'])[0]).toMatchObject({ Kind: 'builtin', Source: 'shopping' });
+ expect(rows(db, LogoQueries.GET_BY_ID, ['L-PERSONAL', SHARED])[0]).toMatchObject({ Kind: 'builtin', Source: 'shopping' });
});
it('GET_ID_FOR_KEY will not hand one manifest another manifest row', async () => {
diff --git a/core/client/src/database/__tests__/MutationScopes.test.ts b/core/client/src/database/__tests__/MutationScopes.test.ts
index a16b3ab34..b1e7cff34 100644
--- a/core/client/src/database/__tests__/MutationScopes.test.ts
+++ b/core/client/src/database/__tests__/MutationScopes.test.ts
@@ -6,7 +6,7 @@ import { StorageKeys } from '../../constants/StorageKeys';
import { getPlatform } from '../../platform/ClientPlatform';
import { SqliteClient } from '../SqliteClient';
-import type { DraftItem } from '../ItemRef';
+import type { Item } from '@aliasvault/models/vault';
const PERSONAL = '11111111-1111-4111-8111-111111111111';
@@ -30,8 +30,8 @@ async function openClient(): Promise<SqliteClient> {
* @param name - The item's name
* @returns The draft
*/
-function draftItem(name: string): DraftItem {
- return { Name: name, ItemType: ItemTypes.Note, Fields: [], CreatedAt: '', UpdatedAt: '' } as unknown as DraftItem;
+function draftItem(name: string): Item {
+ return { Name: name, ManifestId: PERSONAL, ItemType: ItemTypes.Note, Fields: [], CreatedAt: '', UpdatedAt: '' } as unknown as Item;
}
describe('mutation scopes', () => {
diff --git a/core/client/src/database/index.ts b/core/client/src/database/index.ts
index 3aa3327d5..5a1d9fe59 100644
--- a/core/client/src/database/index.ts
+++ b/core/client/src/database/index.ts
@@ -18,7 +18,7 @@ export {
// Repositories
export { ItemRepository } from './repositories/ItemRepository';
export { PasskeyRepository } from './repositories/PasskeyRepository';
-export { FolderRepository, type Folder } from './repositories/FolderRepository';
+export { FolderRepository, type Folder, type FolderRef } from './repositories/FolderRepository';
export { SettingsRepository } from './repositories/SettingsRepository';
export { EncryptionKeyRepository } from './repositories/EncryptionKeyRepository';
export { LogoRepository } from './repositories/LogoRepository';
diff --git a/core/client/src/database/queries/BaseQueries.ts b/core/client/src/database/queries/BaseQueries.ts
deleted file mode 100644
index 95835459d..000000000
--- a/core/client/src/database/queries/BaseQueries.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-/**
- * SQL query constants for generic base operations.
- */
-export class BaseQueries {
- /**
- * SQL fragment resolving the manifest a row placed in the folder bound to its first `?` (possibly
- * NULL) belongs to: that folder's manifest, or the manifest bound to its second `?` when the row sits
- * outside any folder.
- */
- public static readonly MANIFEST_OF_FOLDER = 'COALESCE((SELECT ManifestId FROM Folders WHERE Id = ?), ?)';
-
- /**
- * {@link MANIFEST_OF_FOLDER} as a standalone query, for a caller that has to know the manifest a row is
- * about to be stamped with *before* writing it.
- */
- public static readonly GET_MANIFEST_OF_FOLDER = `SELECT ${BaseQueries.MANIFEST_OF_FOLDER} AS ManifestId`;
-
- /**
- * SQL fragment resolving the manifest of the item whose id is bound to its first `?`. Every row hanging
- * off an item (field values, TOTP codes, attachments, tags, history) is keyed by (ManifestId, Id) and
- * points at its item by the composite (ManifestId, ItemId), so it has to be stamped with the item's
- * own manifest.
- */
- public static readonly MANIFEST_OF_ITEM = 'COALESCE((SELECT ManifestId FROM Items WHERE Id = ?), ?)';
-}
diff --git a/core/client/src/database/queries/FolderQueries.ts b/core/client/src/database/queries/FolderQueries.ts
index 33db98989..ed21e16fe 100644
--- a/core/client/src/database/queries/FolderQueries.ts
+++ b/core/client/src/database/queries/FolderQueries.ts
@@ -1,5 +1,3 @@
-import { BaseQueries } from './BaseQueries';
-
/**
* SQL query constants for Folder operations.
* Centralizes all folder-related queries to avoid duplication.
@@ -27,11 +25,19 @@ export class FolderQueries {
WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0`;
/**
- * Insert a new folder, stamped with its parent folder's manifest.
+ * Whether a live folder exists under this manifest-qualified key.
+ */
+ public static readonly EXISTS = `
+ SELECT 1 AS Found
+ FROM Folders
+ WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0`;
+
+ /**
+ * Insert a new folder into the manifest the caller names, which is its parent folder's own.
*/
public static readonly INSERT = `
INSERT INTO Folders (Id, Name, ParentFolderId, ManifestId, Weight, IsDeleted, CreatedAt, UpdatedAt)
- VALUES (?, ?, ?, ${BaseQueries.MANIFEST_OF_FOLDER}, 0, 0, ?, ?)`;
+ VALUES (?, ?, ?, ?, 0, 0, ?, ?)`;
/**
* Update folder name.
@@ -63,12 +69,11 @@ export class FolderQueries {
WHERE FolderId = ? AND ManifestId = ?`;
/**
- * Move items to a different folder.
+ * Move items to a different folder of the same manifest.
*/
public static readonly MOVE_ITEMS_TO_FOLDER = `
UPDATE Items
SET FolderId = ?,
- ManifestId = ${BaseQueries.MANIFEST_OF_FOLDER},
UpdatedAt = ?
WHERE FolderId = ? AND ManifestId = ?`;
diff --git a/core/client/src/database/queries/ItemQueries.ts b/core/client/src/database/queries/ItemQueries.ts
index 08bef8932..ffa0371b5 100644
--- a/core/client/src/database/queries/ItemQueries.ts
+++ b/core/client/src/database/queries/ItemQueries.ts
@@ -1,5 +1,3 @@
-import { BaseQueries } from './BaseQueries';
-
/**
* SQL query constants for Item operations.
* Centralizes all item-related queries to avoid duplication.
@@ -208,11 +206,11 @@ export class ItemQueries {
ORDER BY t.DisplayOrder, t.Name`;
/**
- * Insert a new item, stamped with the manifest of the folder it is placed in.
+ * Insert a new item into the manifest the caller names, which is its folder's own.
*/
public static readonly INSERT_ITEM = `
INSERT INTO Items (Id, Name, ItemType, LogoId, FolderId, ManifestId, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ${BaseQueries.MANIFEST_OF_FOLDER}, ?, ?, ?)`;
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;
/**
* Update an existing item with explicit LogoId setting (can clear LogoId to null).
@@ -222,7 +220,7 @@ export class ItemQueries {
SET Name = ?,
ItemType = ?,
FolderId = ?,
- ManifestId = ${BaseQueries.MANIFEST_OF_FOLDER},
+ ManifestId = ?,
LogoId = ?,
UpdatedAt = ?
WHERE Id = ? AND ManifestId = ?`;
@@ -308,10 +306,10 @@ export class ItemQueries {
AND i.DeletedAt IS NULL`;
/**
- * Look up an item (id + name) by an email address stored in any of its login email fields.
+ * Look up an item (reference + name) by an email address stored in any of its login email fields.
*/
public static readonly GET_ITEM_BY_EMAIL = `
- SELECT i.Id as Id, i.Name as Name
+ SELECT i.Id as Id, i.ManifestId as ManifestId, i.Name as Name
FROM FieldValues fv
INNER JOIN Items i ON fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId
WHERE fv.FieldKey = ?
@@ -327,7 +325,7 @@ export class ItemQueries {
public static readonly GET_ITEM_FIELDS = `
SELECT Name, ItemType, FolderId, LogoId
FROM Items
- WHERE Id = ? AND ManifestId = ?`;
+ WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0`;
}
/**
@@ -345,11 +343,11 @@ export class FieldValueQueries {
ORDER BY ValueIndex`;
/**
- * Insert a new field value, stamped with the manifest of the item it hangs off.
+ * Insert a new field value, into the manifest of the item it hangs off.
*/
public static readonly INSERT = `
INSERT INTO FieldValues (Id, ItemId, ManifestId, FieldDefinitionId, FieldKey, Value, Weight, ValueIndex, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?, ?, ?, ?, ?, ?)`;
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
/**
* Update an existing field value, bringing it back when it was removed before.
@@ -387,23 +385,23 @@ export class FieldValueQueries {
*/
export class FieldDefinitionQueries {
/**
- * Check if a field definition exists in the item's manifest. Binds [definitionId, itemId].
+ * Check if a field definition exists in the item's manifest. Binds [definitionId, manifestId].
*/
public static readonly EXISTS = `
- SELECT Id FROM FieldDefinitions WHERE Id = ? AND ManifestId = ${BaseQueries.MANIFEST_OF_ITEM}`;
+ SELECT Id FROM FieldDefinitions WHERE Id = ? AND ManifestId = ?`;
/**
- * Check if a field definition exists in the item's manifest and is not deleted. Binds [definitionId, itemId].
+ * Check if a field definition exists in the item's manifest and is not deleted. Binds [definitionId, manifestId].
*/
public static readonly EXISTS_ACTIVE = `
- SELECT Id FROM FieldDefinitions WHERE Id = ? AND ManifestId = ${BaseQueries.MANIFEST_OF_ITEM} AND IsDeleted = 0`;
+ SELECT Id FROM FieldDefinitions WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0`;
/**
- * Insert a new field definition into the item's manifest. Binds [definitionId, itemId, ...].
+ * Insert a new field definition into the item's manifest. Binds [definitionId, manifestId, ...].
*/
public static readonly INSERT = `
INSERT INTO FieldDefinitions (Id, ManifestId, FieldType, Label, IsMultiValue, IsHidden, EnableHistory, Weight, ApplicableToTypes, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
/**
* Update an existing field definition.
@@ -415,7 +413,7 @@ export class FieldDefinitionQueries {
IsHidden = ?,
Weight = ?,
UpdatedAt = ?
- WHERE Id = ? AND ManifestId = ${BaseQueries.MANIFEST_OF_ITEM}`;
+ WHERE Id = ? AND ManifestId = ?`;
}
/**
@@ -423,11 +421,11 @@ export class FieldDefinitionQueries {
*/
export class FieldHistoryQueries {
/**
- * Insert a history record, stamped with the manifest of the item it hangs off.
+ * Insert a history record, into the manifest of the item it hangs off.
*/
public static readonly INSERT = `
INSERT INTO FieldHistories (Id, ItemId, ManifestId, FieldDefinitionId, FieldKey, ValueSnapshot, ChangedAt, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?, ?, ?, ?, ?)`;
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
/**
* Get history records for a field.
@@ -491,11 +489,11 @@ export class TotpCodeQueries {
WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`;
/**
- * Insert a new TOTP code, stamped with the manifest of the item it hangs off.
+ * Insert a new TOTP code, into the manifest of the item it hangs off.
*/
public static readonly INSERT = `
INSERT INTO TotpCodes (Id, Name, SecretKey, Algorithm, Digits, Period, ItemId, ManifestId, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ?, ?, ?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?)`;
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
/**
* Update an existing TOTP code.
@@ -541,11 +539,11 @@ export class AttachmentQueries {
WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`;
/**
- * Insert a new attachment, stamped with the manifest of the item it hangs off.
+ * Insert a new attachment, into the manifest of the item it hangs off.
*/
public static readonly INSERT = `
INSERT INTO Attachments (Id, Filename, Blob, ItemId, ManifestId, CreatedAt, UpdatedAt, IsDeleted)
- VALUES (?, ?, ?, ?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?)`;
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;
/**
* Soft delete an attachment. Also drops the Blob bytes so storage is reclaimed
diff --git a/core/client/src/database/queries/ItemStatsQueries.ts b/core/client/src/database/queries/ItemStatsQueries.ts
index 2135faf84..51184a6c6 100644
--- a/core/client/src/database/queries/ItemStatsQueries.ts
+++ b/core/client/src/database/queries/ItemStatsQueries.ts
@@ -6,13 +6,12 @@
*/
export class ItemStatsQueries {
/**
- * The manifest an item belongs to.
+ * Whether the item exists.
*/
- public static readonly GET_ITEM_MANIFEST = `
- SELECT ManifestId
+ public static readonly ITEM_EXISTS = `
+ SELECT 1 AS Found
FROM Items
- WHERE Id = ?
- LIMIT 1`;
+ WHERE Id = ? AND ManifestId = ?`;
/**
* Create the stats row for an item on its first recorded use.
diff --git a/core/client/src/database/queries/LogoQueries.ts b/core/client/src/database/queries/LogoQueries.ts
index 1a56e1549..fe41f6633 100644
--- a/core/client/src/database/queries/LogoQueries.ts
+++ b/core/client/src/database/queries/LogoQueries.ts
@@ -29,11 +29,13 @@ export class LogoQueries {
LIMIT 1`;
/**
- * The kind and key of an existing logo, in whichever manifest holds it.
+ * The kind and key of an item's logo. Binds [logoId, item manifest]: the item's own manifest wins, and another
+ * manifest only answers for an item that was moved and still points at the logo row it came with.
*/
public static readonly GET_BY_ID = `
SELECT Id, Kind, Source, Name FROM Logos
WHERE Id = ? AND IsDeleted = 0
+ ORDER BY (ManifestId = ?) DESC, ManifestId
LIMIT 1`;
/**
diff --git a/core/client/src/database/queries/PasskeyQueries.ts b/core/client/src/database/queries/PasskeyQueries.ts
index 2cfb89122..bcd4e6ca9 100644
--- a/core/client/src/database/queries/PasskeyQueries.ts
+++ b/core/client/src/database/queries/PasskeyQueries.ts
@@ -1,7 +1,5 @@
import { FieldKey } from '@aliasvault/models/vault';
-import { BaseQueries } from './BaseQueries';
-
/**
* SQL query constants for Passkey operations.
* Centralizes all passkey-related queries to avoid duplication.
@@ -57,7 +55,7 @@ export class PasskeyQueries {
(SELECT fv.Value FROM FieldValues fv WHERE fv.ItemId = i.Id AND fv.ManifestId = i.ManifestId AND fv.FieldKey = '${FieldKey.LoginEmail}' AND fv.IsDeleted = 0 LIMIT 1) as Email
FROM Passkeys p
INNER JOIN Items i ON p.ItemId = i.Id AND i.ManifestId = p.ManifestId
- WHERE p.Id = ? AND p.IsDeleted = 0
+ WHERE p.Id = ? AND p.ManifestId = ? AND p.IsDeleted = 0
AND i.IsDeleted = 0 AND i.DeletedAt IS NULL`;
/**
@@ -83,15 +81,14 @@ export class PasskeyQueries {
ORDER BY p.CreatedAt DESC`;
/**
- * Insert a new passkey, stamped with the manifest of the item it hangs off. Binds the item id
- * twice — once for the column, once for {@link BaseQueries.MANIFEST_OF_ITEM}.
+ * Insert a new passkey into the manifest of the item it hangs off.
*/
public static readonly INSERT = `
INSERT INTO Passkeys (
Id, ItemId, ManifestId, RpId, UserHandle, PublicKey, PrivateKey,
PrfKey, DisplayName, AdditionalData, CreatedAt, UpdatedAt, IsDeleted
)
- VALUES (?, ?, ${BaseQueries.MANIFEST_OF_ITEM}, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
/**
* Soft delete passkey by ID.
diff --git a/core/client/src/database/repositories/FolderRepository.ts b/core/client/src/database/repositories/FolderRepository.ts
index 0e3a95727..61b67111c 100644
--- a/core/client/src/database/repositories/FolderRepository.ts
+++ b/core/client/src/database/repositories/FolderRepository.ts
@@ -14,14 +14,14 @@ export type Folder = {
Name: string;
ParentFolderId: string | null;
Weight: number;
- ManifestId?: string | null;
+ ManifestId: string;
}
/**
* A manifest-qualified reference to a folder: folders are keyed by `(ManifestId, Id)`, so an id on its
* own does not name one folder.
*/
-type FolderRef = {
+export type FolderRef = {
Id: string;
ManifestId: string;
}
@@ -31,38 +31,38 @@ type FolderRef = {
*/
export class FolderRepository extends BaseRepository {
/**
- * Create a new folder.
+ * Create a new folder inside its parent's manifest, or the personal manifest (default) when there is no parent.
* @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. the folder a
- * shared manifest is rendered as); a new GUID is generated when omitted.
+ * @param parent - The parent folder for a nested folder, or null for a top-level one
+ * @param id - Optional explicit folder ID; 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> {
+ public async create(name: string, parent: FolderRef | null = null, id?: string): Promise<string> {
return this.withTransaction(async () => {
const folderId = id ?? crypto.randomUUID();
const currentDateTime = this.now();
- const manifestId = await this.run(this.writeManifestId());
- await this.run(this.execute(FolderQueries.INSERT, [
- folderId,
- name,
- parentFolderId || null,
- // Second bind of the parent id, then the manifest a top-level folder joins (see INSERT).
- parentFolderId || null,
- manifestId,
- currentDateTime,
- currentDateTime
- ]));
+ if (parent) {
+ await this.run(this.assertExists(parent));
+ }
+ const manifestId = parent?.ManifestId ?? await this.run(this.writeManifestId());
+
+ await this.run(this.execute(FolderQueries.INSERT, [folderId, name, parent?.Id ?? null, manifestId, currentDateTime, currentDateTime]));
return folderId;
});
}
/**
- * Get all folders.
- * @returns Array of folder objects (empty array if Folders table doesn't exist yet)
+ * Reject a folder reference that does not exist.
+ * @param ref - The folder to check
*/
+ public *assertExists(ref: FolderRef): DbOp<void> {
+ const folder = yield* this.getById(ref);
+ if (!folder) {
+ throw new Error(`FolderRepository: folder ${ref.Id} does not exist in manifest ${ref.ManifestId}; refusing the write.`);
+ }
+ }
public *getAll(): DbOp<Folder[]> {
try {
return yield* this.query<Folder>(FolderQueries.GET_ALL);
@@ -76,51 +76,23 @@ export class FolderRepository extends BaseRepository {
}
/**
- * Get a folder by ID.
- * @param folderId - The ID of the folder
- * @param manifestId - The manifest the folder belongs to, when known
+ * Get a folder by its manifest-qualified reference.
+ * @param ref - The folder to read
* @returns Folder object or null if not found
*/
- public *getById(folderId: string, manifestId?: string): DbOp<Omit<Folder, 'Weight'> | null> {
- const ref = yield* this.resolveFolderRef(folderId, manifestId);
- if (!ref) {
- return null;
- }
-
+ 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;
}
- /**
- * Resolve the manifest-qualified reference a folder id names.
- * @param folderId - The folder id
- * @param manifestId - The manifest the folder belongs to, when the caller already knows it
- * @returns The reference, or null when no folder carries this id
- */
- private *resolveFolderRef(folderId: string, manifestId?: string): DbOp<FolderRef | null> {
- if (manifestId) {
- return { Id: folderId, ManifestId: manifestId };
- }
-
- const resolved = yield* this.resolveRowManifestId('Folders', folderId);
- return resolved ? { Id: folderId, ManifestId: resolved } : null;
- }
-
/**
* Update a folder's name.
- * @param folderId - The ID of the folder to update
+ * @param ref - The folder to update
* @param name - The new name for the folder
- * @param manifestId - The manifest the folder belongs to, when known
* @returns The number of rows updated
*/
- public async update(folderId: string, name: string, manifestId?: string): Promise<number> {
- return this.withTransaction(async () => {
- const ref = await this.run(this.resolveFolderRef(folderId, manifestId));
- if (!ref) {
- return 0;
- }
- return this.run(this.execute(FolderQueries.UPDATE_NAME, [name, this.now(), ref.Id, ref.ManifestId]));
- });
+ public async update(ref: FolderRef, name: string): Promise<number> {
+ return this.withTransaction(() => this.run(this.execute(FolderQueries.UPDATE_NAME, [name, this.now(), ref.Id, ref.ManifestId])));
}
/**
@@ -150,16 +122,10 @@ export class FolderRepository extends BaseRepository {
* - Items in this folder only are moved to the parent folder (or root if no parent)
* - Items in child folders stay in their respective folders (since child folders are moved to parent)
* - All direct child folders are moved to the parent of the deleted folder
- * @param folderId - The ID of the folder to delete
- * @param manifestId - The manifest the folder belongs to, when known
+ * @param ref - The folder to delete
* @returns The number of rows updated
*/
- public async delete(folderId: string, manifestId?: string): Promise<number> {
- const ref = await this.run(this.resolveFolderRef(folderId, manifestId));
- if (!ref) {
- return 0;
- }
-
+ public async delete(ref: FolderRef): Promise<number> {
await this.assertDeletable(ref);
return this.withTransaction(() => this.run(this.deleteKeepingContents(ref)));
}
@@ -173,22 +139,14 @@ export class FolderRepository extends BaseRepository {
const currentDateTime = this.now();
// Get the parent folder of the folder being deleted
- const folder = yield* this.getById(ref.Id, ref.ManifestId);
+ const folder = yield* this.getById(ref);
const targetParentId = folder?.ParentFolderId || null;
const manifestId = yield* this.writeManifestId();
// Move only items in this folder to the parent folder (or root if no parent)
if (targetParentId) {
- // Has parent: move items to parent folder
- yield* this.execute(FolderQueries.MOVE_ITEMS_TO_FOLDER, [
- targetParentId,
- // Second bind of the destination: the items adopt that folder's manifest.
- targetParentId,
- manifestId,
- currentDateTime,
- ref.Id,
- ref.ManifestId
- ]);
+ // 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]);
@@ -206,16 +164,10 @@ export class FolderRepository extends BaseRepository {
* Recursively handles child folders:
* - All items in this folder and child folders are moved to "Recently Deleted" (trash)
* - All child folders are also deleted
- * @param folderId - The ID of the folder to delete
- * @param manifestId - The manifest the folder belongs to, when known
+ * @param ref - The folder to delete
* @returns The number of items trashed
*/
- public async deleteWithContents(folderId: string, manifestId?: string): Promise<number> {
- const ref = await this.run(this.resolveFolderRef(folderId, manifestId));
- if (!ref) {
- return 0;
- }
-
+ public async deleteWithContents(ref: FolderRef): Promise<number> {
await this.assertDeletable(ref);
return this.withTransaction(() => this.run(this.deleteFolderTree(ref)));
}
@@ -249,7 +201,7 @@ export class FolderRepository extends BaseRepository {
* @param ref - The folder about to be deleted
*/
private async assertDeletable(ref: FolderRef): Promise<void> {
- const folder = await this.run(this.getById(ref.Id, ref.ManifestId));
+ const folder = await this.run(this.getById(ref));
if (folder && multiManifestRendering.isManifestRoot(folder)) {
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 6e65237af..e0936c14c 100644
--- a/core/client/src/database/repositories/ItemRepository.ts
+++ b/core/client/src/database/repositories/ItemRepository.ts
@@ -3,9 +3,10 @@ import { FieldKey, LogoKinds, MAX_FIELD_HISTORY_RECORDS, getSystemField, normali
import { getFolderPath } from '../../items/FolderUtils';
import { selectFaviconTarget, toUrlList } from '../../rust/RustCore';
import { BaseRepository, type IDatabaseClient, type SqliteBindValue } from '../BaseRepository';
-import { itemKeyBindings, scopedKey, type DraftItem, type ItemRef } from '../ItemRef';
+import { itemKeyBindings, scopedKey, type ItemRef } from '../ItemRef';
import { FieldMapper, type FieldRow } from '../mappers/FieldMapper';
import { ItemMapper, type ItemRow, type ItemSummary, type ItemSummaryRow, type TagRow, type ItemWithArchivedAt, type ItemWithDeletedAt } from '../mappers/ItemMapper';
+import { FolderQueries } from '../queries/FolderQueries';
import {
ItemQueries,
FieldValueQueries,
@@ -16,7 +17,7 @@ import {
} from '../queries/ItemQueries';
import type { DbOp } from '../DbOp';
-import type { Folder } from './FolderRepository';
+import type { Folder, FolderRef } from './FolderRepository';
import type { LogoRepository } from './LogoRepository';
import type { Item, ItemField, Attachment, TotpCode, FieldHistory, LogoSelection } from '@aliasvault/models/vault';
@@ -82,7 +83,7 @@ export class ItemRepository extends BaseRepository {
for (const [manifestId, manifestFolders] of foldersByManifest) {
for (const folder of manifestFolders) {
- const path = getFolderPath(folder.Id, manifestFolders);
+ const path = getFolderPath(folder, manifestFolders);
if (path.length > 0) {
folderPathMap.set(scopedKey(manifestId, folder.Id), path);
}
@@ -104,17 +105,11 @@ export class ItemRepository extends BaseRepository {
/**
* Fetch the active items of one folder with their dynamic fields and tags.
- * @param folderId - The ID of the folder to read
- * @param manifestId - The manifest the folder belongs to, when known
+ * @param folder - The folder to read
* @returns Array of Item objects (empty array if the folder does not exist)
*/
- public *getByFolder(folderId: string, manifestId?: string): DbOp<Item[]> {
- const scope = manifestId ?? (yield* this.resolveRowManifestId('Folders', folderId));
- if (!scope) {
- return [];
- }
-
- const itemRows = yield* this.selectItemRows(ItemQueries.GET_BY_FOLDER, [folderId, scope]);
+ public *getByFolder(folder: FolderRef): DbOp<Item[]> {
+ const itemRows = yield* this.selectItemRows(ItemQueries.GET_BY_FOLDER, [folder.Id, folder.ManifestId]);
return yield* this.hydrateItems(itemRows);
}
@@ -211,15 +206,10 @@ export class ItemRepository extends BaseRepository {
/**
* Fetch a single item with its dynamic fields and tags.
- * @param itemId - The ID of the item to fetch
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns Item object or null if not found
*/
- public *getById(itemId: string, manifestId?: string): DbOp<Item | null> {
- const ref = yield* this.resolveItemRef(itemId, manifestId);
- if (!ref) {
- return null;
- }
+ public *getById(ref: ItemRef): DbOp<Item | null> {
const results = yield* this.query<ItemRow>(ItemQueries.GET_BY_ID, [ref.Id, ref.ManifestId]);
if (results.length === 0) {
@@ -244,21 +234,6 @@ export class ItemRepository extends BaseRepository {
return ItemMapper.mapRow(results[0], fields, tags, folderPath);
}
- /**
- * Resolve the manifest-qualified reference an item id names.
- * @param itemId - The item id
- * @param manifestId - The manifest the item belongs to, when known
- * @returns The item reference, or null when no such item exists
- */
- private *resolveItemRef(itemId: string, manifestId?: string): DbOp<ItemRef | null> {
- if (manifestId) {
- return { Id: itemId, ManifestId: manifestId };
- }
-
- const resolved = yield* this.resolveRowManifestId('Items', itemId);
- return resolved ? { Id: itemId, ManifestId: resolved } : null;
- }
-
/**
* Fetch the unique email addresses the vault still routes mail to, i.e. every live login email field the user
* has not switched off. A switched-off alias keeps its claim link and its stored mail server-side, but the
@@ -282,12 +257,12 @@ export class ItemRepository extends BaseRepository {
}
/**
- * Find the item (id + name) associated with a given email address, if any.
+ * Find the item (reference + name) associated with a given email address, if any.
* @param email - The full email address (local@domain) to look up
- * @returns Object with Id and Name, or null when no active item uses this address
+ * @returns The item reference and name, or null when no active item uses this address
*/
- public *findIdByEmail(email: string): DbOp<{ Id: string; Name: string | null } | null> {
- const results = yield* this.query<{ Id: string; Name: string | null }>(ItemQueries.GET_ITEM_BY_EMAIL, [FieldKey.LoginEmail, email]);
+ public *findIdByEmail(email: string): DbOp<(ItemRef & { Name: string | null }) | null> {
+ const results = yield* this.query<ItemRef & { Name: string | null }>(ItemQueries.GET_ITEM_BY_EMAIL, [FieldKey.LoginEmail, email]);
return results.length > 0 ? results[0] : null;
}
@@ -297,40 +272,30 @@ export class ItemRepository extends BaseRepository {
* @param attachments Optional attachments to associate with the item
* @param totpCodes Optional TOTP codes to associate with the item
* @param logoSelection A logo the user picked or uploaded; omit to resolve the favicon from the URL
- * @returns The ID of the created item
+ * @returns The created item, named by its manifest and id
*/
public async create(
- item: DraftItem,
+ item: Item,
attachments: Attachment[] = [],
totpCodes: TotpCode[] = [],
logoSelection?: LogoSelection
- ): Promise<string> {
+ ): Promise<ItemRef> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
const itemId = item.Id || this.generateId();
- // 1. Handle the logo
- const logoId = await this.resolveLogoId(item, currentDateTime, null, logoSelection);
+ // 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));
- // 2. Insert Item
- const manifestId = await this.run(this.writeManifestId());
- await this.run(this.execute(ItemQueries.INSERT_ITEM, [
- itemId,
- item.Name ?? null,
- item.ItemType,
- logoId,
- item.FolderId ?? null,
- // Second bind of the folder id, then the manifest an item outside any folder joins (see INSERT_ITEM).
- item.FolderId ?? null,
- manifestId,
- currentDateTime,
- currentDateTime,
- 0
- ]));
+ // 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]));
/*
- * 3-5. Insert the child rows. Each stamps itself with the manifest of the item it hangs off
- * (see BaseQueries.MANIFEST_OF_ITEM), which the INSERT above has just decided from the folder.
+ * 4-6. Insert the child rows into the manifest the item was just written into.
*/
if (item.Fields && item.Fields.length > 0) {
await this.run(this.insertFieldValues(itemId, item.Fields, item.ItemType, manifestId, currentDateTime));
@@ -339,37 +304,31 @@ export class ItemRepository extends BaseRepository {
await this.run(this.insertTotpCodes(itemId, totpCodes, manifestId, currentDateTime));
await this.run(this.insertAttachments(itemId, attachments, manifestId, currentDateTime));
- return itemId;
+ return { Id: itemId, ManifestId: manifestId };
});
}
/**
* Duplicate an item including all fields. Data that is not duplicated is passkeys and field history.
- * @param itemId - The ID of the item to duplicate
- * @param manifestId - The manifest the item belongs to, when known
- * @returns The ID of the newly created item
+ * @param ref - The item, named by its manifest and id
+ * @returns The newly created item, which lives in the same manifest
*/
- public async duplicate(itemId: string, manifestId?: string): Promise<string> {
- return this.withTransaction(() => this.run(this.copyItem(itemId, manifestId)));
+ public async duplicate(ref: ItemRef): Promise<ItemRef> {
+ return this.withTransaction(() => this.run(this.copyItem(ref)));
}
/**
* Copy an item and its child rows under fresh ids.
- * @param itemId - The ID of the item to duplicate
- * @param manifestId - The manifest the item belongs to, when known
- * @returns The ID of the newly created item
+ * @param ref - The item, named by its manifest and id
+ * @returns The newly created item
*/
- private *copyItem(itemId: string, manifestId?: string): DbOp<string> {
+ private *copyItem(ref: ItemRef): DbOp<ItemRef> {
const currentDateTime = this.now();
const newItemId = this.generateId();
- const ref = yield* this.resolveItemRef(itemId, manifestId);
- if (!ref) {
- throw new Error(`Item not found: ${itemId}`);
- }
const sourceRows = yield* this.query<{ Name: string | null }>('SELECT Name FROM Items WHERE Id = ? AND ManifestId = ? AND IsDeleted = 0', [ref.Id, ref.ManifestId]);
if (sourceRows.length === 0) {
- throw new Error(`Item not found: ${itemId}`);
+ throw new Error(`Item not found: ${ref.Id}`);
}
const existingNames = yield* this.query<{ Name: string | null }>('SELECT Name FROM Items WHERE IsDeleted = 0 AND DeletedAt IS NULL');
@@ -452,7 +411,7 @@ export class ItemRepository extends BaseRepository {
SELECT ManifestId, ?, TagId, ?, ?, 0 FROM ItemTags WHERE ItemId = ? AND ManifestId = ? AND IsDeleted = 0`,
[newItemId, currentDateTime, currentDateTime, ref.Id, ref.ManifestId]);
- return newItemId;
+ return { Id: newItemId, ManifestId: ref.ManifestId };
}
/**
@@ -477,29 +436,28 @@ export class ItemRepository extends BaseRepository {
/**
* Update an existing item with field-based structure.
+ * @param ref Where the item is now; `item.ManifestId` names where it belongs, which differs when it changed folder
* @param item The item object to update
* @param originalAttachmentIds Original attachment IDs for tracking changes
* @param attachments Current attachments list
* @param originalTotpCodeIds Original TOTP code IDs for tracking changes
* @param totpCodes Current TOTP codes list
* @param logoSelection A logo the user picked or uploaded; omit to leave the current logo logic alone
- * @returns The number of rows modified
+ * @returns Where the item is after the write (a folder change may move it to another manifest), or null when it does not exist
*/
public async update(
- item: DraftItem,
+ ref: ItemRef,
+ item: Item,
originalAttachmentIds: string[] = [],
attachments: Attachment[] = [],
originalTotpCodeIds: string[] = [],
totpCodes: TotpCode[] = [],
logoSelection?: LogoSelection
- ): Promise<number> {
+ ): Promise<ItemRef | null> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
-
- // Every row this write touches stays inside the item's own manifest.
- const ref = await this.run(this.resolveItemRef(item.Id, item.ManifestId));
- if (!ref) {
- return 0;
+ if (item.Id !== ref.Id) {
+ throw new Error('ItemRepository: the item to update does not carry the id of the row it replaces.');
}
// 1. Read the stored item first: resolving the logo needs to know which one it already has.
@@ -509,81 +467,61 @@ export class ItemRepository extends BaseRepository {
FolderId: string | null;
LogoId: string | null;
}>(ItemQueries.GET_ITEM_FIELDS, [ref.Id, ref.ManifestId])))[0];
+ if (!existing) {
+ return null;
+ }
- // 2. Handle the logo
- const logoId = await this.resolveLogoId(item, currentDateTime, existing?.LogoId ?? null, logoSelection);
- const manifestId = await this.run(this.writeManifestId());
-
- if (existing) {
- const nameChanged = (item.Name ?? null) !== existing.Name;
- const itemTypeChanged = String(item.ItemType) !== String(existing.ItemType);
- const folderIdChanged = (item.FolderId ?? null) !== existing.FolderId;
- const logoIdChanged = logoId !== existing.LogoId;
-
- if (nameChanged || itemTypeChanged || folderIdChanged || logoIdChanged) {
- // Use UPDATE_ITEM_WITH_LOGO to allow explicit clearing of LogoId
- await this.run(this.execute(ItemQueries.UPDATE_ITEM_WITH_LOGO, [
- item.Name ?? null,
- item.ItemType,
- item.FolderId ?? null,
- // Moving an item across a folder boundary moves it across a manifest boundary: re-stamp it.
- item.FolderId ?? null,
- manifestId,
- logoId,
- currentDateTime,
- ref.Id,
- // The row is addressed by the manifest it is in *now*; the SET above may move it.
- ref.ManifestId
- ]));
- }
+ // 2. The manifest the item ends up in, then the logo inside it.
+ const manifestId = item.ManifestId;
+ await this.run(this.assertFolderInManifest(item));
+ 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 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]));
}
// 3. Track history for fields that have EnableHistory=true before updating
- await this.run(this.trackFieldHistory(ref.Id, ref.ManifestId, item.Fields, manifestId, currentDateTime));
+ await this.run(this.trackFieldHistory(ref.Id, manifestId, item.Fields, currentDateTime));
// 4. Update field values
- await this.run(this.updateFieldValues(item, ref.ManifestId, manifestId, currentDateTime));
+ await this.run(this.updateFieldValues(item, manifestId, currentDateTime));
// 5. Handle TOTP codes
- await this.run(this.handleTotpCodes(ref.Id, ref.ManifestId, totpCodes, originalTotpCodeIds, manifestId, currentDateTime));
+ await this.run(this.handleTotpCodes(ref.Id, manifestId, totpCodes, originalTotpCodeIds, currentDateTime));
// 6. Handle attachments
- await this.run(this.handleAttachments(ref.Id, ref.ManifestId, attachments, originalAttachmentIds, manifestId, currentDateTime));
+ await this.run(this.handleAttachments(ref.Id, manifestId, attachments, originalAttachmentIds, currentDateTime));
- return 1;
+ return { Id: ref.Id, ManifestId: manifestId };
});
}
/**
* Move an item to "Recently Deleted" (trash).
- * @param itemId - The ID of the item to trash
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns The number of rows updated
*/
- public async trash(itemId: string, manifestId?: string): Promise<number> {
+ public async trash(ref: ItemRef): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = await this.run(this.resolveItemRef(itemId, manifestId));
- if (!ref) {
- return 0;
- }
return this.run(this.execute(ItemQueries.TRASH_ITEM, [currentDateTime, currentDateTime, ref.Id, ref.ManifestId]));
});
}
/**
* Restore an item from "Recently Deleted".
- * @param itemId - The ID of the item to restore
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns The number of rows updated
*/
- public async restore(itemId: string, manifestId?: string): Promise<number> {
+ public async restore(ref: ItemRef): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = await this.run(this.resolveItemRef(itemId, manifestId));
- if (!ref) {
- return 0;
- }
return this.run(this.execute(ItemQueries.RESTORE_ITEM, [currentDateTime, ref.Id, ref.ManifestId]));
});
}
@@ -591,51 +529,36 @@ export class ItemRepository extends BaseRepository {
/**
* Archive an item: it disappears from the main list and from autofill, but keeps all of its data
* and its email aliases, and is never auto-pruned.
- * @param itemId - The ID of the item to archive
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns The number of rows updated
*/
- public async archive(itemId: string, manifestId?: string): Promise<number> {
+ public async archive(ref: ItemRef): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = await this.run(this.resolveItemRef(itemId, manifestId));
- if (!ref) {
- return 0;
- }
return this.run(this.execute(ItemQueries.ARCHIVE_ITEM, [currentDateTime, currentDateTime, ref.Id, ref.ManifestId]));
});
}
/**
* Unarchive an item, returning it to the main list and to autofill.
- * @param itemId - The ID of the item to unarchive
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns The number of rows updated
*/
- public async unarchive(itemId: string, manifestId?: string): Promise<number> {
+ public async unarchive(ref: ItemRef): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = await this.run(this.resolveItemRef(itemId, manifestId));
- if (!ref) {
- return 0;
- }
return this.run(this.execute(ItemQueries.UNARCHIVE_ITEM, [currentDateTime, ref.Id, ref.ManifestId]));
});
}
/**
* Permanently delete an item - converts to tombstone for sync.
- * @param itemId - The ID of the item to permanently delete
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns The number of rows updated
*/
- public async permanentlyDelete(itemId: string, manifestId?: string): Promise<number> {
+ public async permanentlyDelete(ref: ItemRef): Promise<number> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
- const ref = await this.run(this.resolveItemRef(itemId, manifestId));
- if (!ref) {
- return 0;
- }
// Hard delete all related entities within this item's manifest.
for (const table of ['FieldValues', 'FieldHistories', 'Passkeys', 'TotpCodes', 'Attachments', 'ItemTags']) {
@@ -719,44 +642,29 @@ export class ItemRepository extends BaseRepository {
/**
* Get an item's TOTP codes.
- * @param itemId - The ID of the item to get TOTP codes for
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns Array of TotpCode objects
*/
- public *getTotpCodesForItem(itemId: string, manifestId?: string): DbOp<TotpCode[]> {
- const ref = yield* this.resolveItemRef(itemId, manifestId);
- if (!ref) {
- return [];
- }
+ public *getTotpCodesForItem(ref: ItemRef): DbOp<TotpCode[]> {
return yield* this.query<TotpCode>(TotpCodeQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);
}
/**
* Get an item's attachments.
- * @param itemId - The ID of the item
- * @param manifestId - The manifest the item belongs to, when known
+ * @param ref - The item, named by its manifest and id
* @returns Array of attachments for the item
*/
- public *getAttachmentsForItem(itemId: string, manifestId?: string): DbOp<Attachment[]> {
- const ref = yield* this.resolveItemRef(itemId, manifestId);
- if (!ref) {
- return [];
- }
+ public *getAttachmentsForItem(ref: ItemRef): DbOp<Attachment[]> {
return yield* this.query<Attachment>(AttachmentQueries.GET_BY_ITEM_ID, [ref.Id, ref.ManifestId]);
}
/**
* Get field history for a specific field.
- * @param itemId - The ID of the item
+ * @param ref - The item, named by its manifest and id
* @param fieldKey - The field key to get history for
- * @param manifestId - The manifest the item belongs to, when known
* @returns Array of field history records
*/
- public *getFieldHistory(itemId: string, fieldKey: string, manifestId?: string): DbOp<FieldHistory[]> {
- const ref = yield* this.resolveItemRef(itemId, manifestId);
- if (!ref) {
- return [];
- }
+ public *getFieldHistory(ref: ItemRef, fieldKey: string): DbOp<FieldHistory[]> {
const results = yield* this.query<{
Id: string;
@@ -782,17 +690,27 @@ export class ItemRepository extends BaseRepository {
/**
* Delete a specific field history record.
* @param historyId - The ID of the history record to delete
- * @param manifestId - The manifest the record belongs to, when known
+ * @param manifestId - The manifest the record belongs to, which is its item's
* @returns Number of rows affected
*/
- public async deleteFieldHistory(historyId: string, manifestId?: string): Promise<number> {
- return this.withTransaction(async () => {
- const scope = manifestId ?? await this.run(this.resolveRowManifestId('FieldHistories', historyId));
- if (!scope) {
- return 0;
- }
- return this.run(this.execute(FieldHistoryQueries.SOFT_DELETE, [this.now(), historyId, scope]));
- });
+ public async deleteFieldHistory(historyId: string, manifestId: string): Promise<number> {
+ return this.withTransaction(() => this.run(this.execute(FieldHistoryQueries.SOFT_DELETE, [this.now(), historyId, manifestId])));
+ }
+
+ /**
+ * 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
+ */
+ private *assertFolderInManifest(item: Item): DbOp<void> {
+ if (!item.FolderId) {
+ return;
+ }
+
+ const rows = yield* this.query<{ Found: number }>(FolderQueries.EXISTS, [item.FolderId, item.ManifestId]);
+ if (rows.length === 0) {
+ throw new Error(`ItemRepository: folder ${item.FolderId} does not exist in manifest ${item.ManifestId}; refusing the write.`);
+ }
}
/**
@@ -807,24 +725,26 @@ export class ItemRepository extends BaseRepository {
* image the domain's row holds;
*
* @param item The item being created or updated
+ * @param scope The manifest the item is written into, which the logo row has to live in too
* @param currentDateTime The current date/time string for timestamps
* @param existingLogoId The favicon the item currently has, when updating
* @param selection A favicon the user explicitly picked or uploaded
+ * @param storedManifestId The manifest the stored item is in, where its current logo row lives
* @returns The favicon ID to store on the item, or null when it should have none
*/
private async resolveLogoId(
- item: DraftItem,
+ item: Item,
+ scope: string,
currentDateTime: string,
existingLogoId: string | null = null,
- selection?: LogoSelection
+ selection?: LogoSelection,
+ storedManifestId: string = scope
): Promise<string | null> {
- const scope = await this.run(this.manifestOfFolder(item.FolderId ?? null));
-
if (selection && selection.Kind !== LogoKinds.Favicon) {
return this.resolveSelectedLogo(selection, scope, currentDateTime);
}
- const existing = existingLogoId ? await this.run(this.logoRepository.getById(existingLogoId)) : null;
+ const existing = existingLogoId ? await this.run(this.logoRepository.getById(existingLogoId, storedManifestId)) : null;
if (!selection && existing && existing.Kind !== LogoKinds.Favicon) {
return this.logoRepository.adoptIntoScope(scope, existing.Kind, existing.Source, currentDateTime);
}
@@ -907,7 +827,7 @@ export class ItemRepository extends BaseRepository {
itemId: string,
fields: ItemField[],
itemType: string,
- writeManifestId: string,
+ manifestId: string,
currentDateTime: string
): DbOp<void> {
for (const field of fields) {
@@ -921,7 +841,7 @@ export class ItemRepository extends BaseRepository {
// For custom fields, create or get FieldDefinition
if (field.IsCustomField) {
- fieldDefinitionId = yield* this.ensureFieldDefinition(field, itemId, itemType, writeManifestId, currentDateTime);
+ fieldDefinitionId = yield* this.ensureFieldDefinition(field, itemId, itemType, manifestId, currentDateTime);
}
// Handle multi-value fields
@@ -937,8 +857,7 @@ export class ItemRepository extends BaseRepository {
yield* this.execute(FieldValueQueries.INSERT, [
this.generateId(),
itemId,
- itemId,
- writeManifestId,
+ manifestId,
fieldDefinitionId,
field.IsCustomField ? null : field.FieldKey,
value,
@@ -955,8 +874,7 @@ export class ItemRepository extends BaseRepository {
yield* this.execute(FieldHistoryQueries.INSERT, [
this.generateId(),
itemId,
- itemId,
- writeManifestId,
+ manifestId,
null,
field.FieldKey,
JSON.stringify(filteredValues),
@@ -976,16 +894,15 @@ export class ItemRepository extends BaseRepository {
field: ItemField,
itemId: string,
itemType: string,
- writeManifestId: string,
+ manifestId: string,
currentDateTime: string
): DbOp<string> {
- const existingDef = yield* this.query<{ Id: string }>(FieldDefinitionQueries.EXISTS, [field.FieldKey, itemId, writeManifestId]);
+ const existingDef = yield* this.query<{ Id: string }>(FieldDefinitionQueries.EXISTS, [field.FieldKey, manifestId]);
if (existingDef.length === 0) {
yield* this.execute(FieldDefinitionQueries.INSERT, [
field.FieldKey,
- itemId,
- writeManifestId,
+ manifestId,
field.FieldType,
field.Label,
0, // IsMultiValue
@@ -1005,7 +922,7 @@ export class ItemRepository extends BaseRepository {
/**
* Update field values for an existing item.
*/
- private *updateFieldValues(item: DraftItem, manifestId: string, writeManifestId: string, currentDateTime: string): DbOp<void> {
+ private *updateFieldValues(item: Item, manifestId: string, currentDateTime: string): DbOp<void> {
const storedRows = yield* this.query<StoredFieldValue>(FieldValueQueries.GET_ALL_FOR_ITEM, [item.Id, manifestId]);
const rowsByField = new Map<string, StoredFieldValue[]>();
@@ -1026,7 +943,7 @@ export class ItemRepository extends BaseRepository {
let fieldDefinitionId = null;
if (field.IsCustomField) {
- fieldDefinitionId = yield* this.ensureOrUpdateFieldDefinition(field, item.Id, item.ItemType, writeManifestId, currentDateTime);
+ fieldDefinitionId = yield* this.ensureOrUpdateFieldDefinition(field, item.Id, item.ItemType, manifestId, currentDateTime);
}
const values = Array.isArray(field.Value) ? field.Value : [field.Value];
@@ -1047,8 +964,7 @@ export class ItemRepository extends BaseRepository {
yield* this.execute(FieldValueQueries.INSERT, [
this.generateId(),
item.Id,
- item.Id,
- writeManifestId,
+ manifestId,
fieldDefinitionId,
field.IsCustomField ? null : field.FieldKey,
value,
@@ -1117,16 +1033,15 @@ export class ItemRepository extends BaseRepository {
field: ItemField,
itemId: string,
itemType: string,
- writeManifestId: string,
+ manifestId: string,
currentDateTime: string
): DbOp<string> {
- const existingDef = yield* this.query<{ Id: string }>(FieldDefinitionQueries.EXISTS_ACTIVE, [field.FieldKey, itemId, writeManifestId]);
+ const existingDef = yield* this.query<{ Id: string }>(FieldDefinitionQueries.EXISTS_ACTIVE, [field.FieldKey, manifestId]);
if (existingDef.length === 0) {
yield* this.execute(FieldDefinitionQueries.INSERT, [
field.FieldKey,
- itemId,
- writeManifestId,
+ manifestId,
field.FieldType,
field.Label,
0,
@@ -1146,8 +1061,7 @@ export class ItemRepository extends BaseRepository {
field.DisplayOrder ?? 0,
currentDateTime,
field.FieldKey,
- itemId,
- writeManifestId
+ manifestId
]);
}
@@ -1166,7 +1080,6 @@ export class ItemRepository extends BaseRepository {
itemId: string,
manifestId: string,
newFields: ItemField[],
- writeManifestId: string,
currentDateTime: string
): DbOp<void> {
const existingFields = yield* this.query<{ FieldKey: string; Value: string }>(FieldValueQueries.GET_FOR_HISTORY, [itemId, manifestId]);
@@ -1204,8 +1117,7 @@ export class ItemRepository extends BaseRepository {
yield* this.execute(FieldHistoryQueries.INSERT, [
this.generateId(),
itemId,
- itemId,
- writeManifestId,
+ manifestId,
null,
newField.FieldKey,
JSON.stringify(filteredNewValues),
@@ -1243,7 +1155,7 @@ export class ItemRepository extends BaseRepository {
/**
* Insert TOTP codes for a new item.
*/
- private *insertTotpCodes(itemId: string, totpCodes: TotpCode[], writeManifestId: string, currentDateTime: string): DbOp<void> {
+ private *insertTotpCodes(itemId: string, totpCodes: TotpCode[], manifestId: string, currentDateTime: string): DbOp<void> {
for (const totpCode of totpCodes) {
yield* this.execute(TotpCodeQueries.INSERT, [
totpCode.Id || this.generateId(),
@@ -1253,8 +1165,7 @@ export class ItemRepository extends BaseRepository {
normalizeTotpDigits(totpCode.Digits),
normalizeTotpPeriod(totpCode.Period),
itemId,
- itemId,
- writeManifestId,
+ manifestId,
currentDateTime,
currentDateTime,
0
@@ -1270,7 +1181,6 @@ export class ItemRepository extends BaseRepository {
manifestId: string,
totpCodes: TotpCode[],
originalIds: string[],
- writeManifestId: string,
currentDateTime: string
): DbOp<void> {
// Fetch existing TOTP codes to compare values
@@ -1306,8 +1216,7 @@ export class ItemRepository extends BaseRepository {
normalizeTotpDigits(totpCode.Digits),
normalizeTotpPeriod(totpCode.Period),
itemId,
- itemId,
- writeManifestId,
+ manifestId,
currentDateTime,
currentDateTime,
0
@@ -1319,7 +1228,7 @@ export class ItemRepository extends BaseRepository {
/**
* Insert attachments for a new item.
*/
- private *insertAttachments(itemId: string, attachments: Attachment[], writeManifestId: string, currentDateTime: string): DbOp<void> {
+ private *insertAttachments(itemId: string, attachments: Attachment[], manifestId: string, currentDateTime: string): DbOp<void> {
for (const attachment of attachments) {
const blobData = attachment.Blob instanceof Uint8Array ? attachment.Blob : new Uint8Array(attachment.Blob ?? []);
@@ -1328,8 +1237,7 @@ export class ItemRepository extends BaseRepository {
attachment.Filename,
blobData,
itemId,
- itemId,
- writeManifestId,
+ manifestId,
currentDateTime,
currentDateTime,
0
@@ -1345,7 +1253,6 @@ export class ItemRepository extends BaseRepository {
manifestId: string,
attachments: Attachment[],
originalIds: string[],
- writeManifestId: string,
currentDateTime: string
): DbOp<void> {
// Track which original attachments are still present
@@ -1374,8 +1281,7 @@ export class ItemRepository extends BaseRepository {
attachment.Filename,
blobData,
itemId,
- itemId,
- writeManifestId,
+ manifestId,
currentDateTime,
currentDateTime,
0
diff --git a/core/client/src/database/repositories/ItemStatsRepository.ts b/core/client/src/database/repositories/ItemStatsRepository.ts
index ac6317f7e..f12c995a1 100644
--- a/core/client/src/database/repositories/ItemStatsRepository.ts
+++ b/core/client/src/database/repositories/ItemStatsRepository.ts
@@ -2,6 +2,7 @@ import { BaseRepository } from '../BaseRepository';
import { ItemStatsQueries } from '../queries/ItemStatsQueries';
import type { DbOp } from '../DbOp';
+import type { ItemRef } from '../ItemRef';
/**
* The actions whose use of an item is recorded. Each maps to its own timestamp + counter pair alongside
@@ -37,30 +38,20 @@ export type ItemStats = {
export class ItemStatsRepository extends BaseRepository {
/**
* Record one use of an item.
- * @param itemId - The item that was used
+ * @param item - The item that was used, named by its manifest and id
* @param action - What the user did with it
* @returns True when a use was recorded, false when no such item exists
*/
- public *recordUsage(itemId: string, action: ItemUsageAction): DbOp<boolean> {
- const manifestId = yield* this.itemManifestId(itemId);
- if (!manifestId) {
+ public *recordUsage(item: ItemRef, action: ItemUsageAction): DbOp<boolean> {
+ if ((yield* this.query<{ Found: number }>(ItemStatsQueries.ITEM_EXISTS, [item.Id, item.ManifestId])).length === 0) {
return false;
}
const now = this.now();
const columns = ACTION_COLUMNS[action];
- yield* this.execute(ItemStatsQueries.INSERT_ROW, [manifestId, itemId, now, now]);
- yield* this.execute(ItemStatsQueries.forAction(columns.last, columns.count), [now, now, now, manifestId, itemId]);
+ yield* this.execute(ItemStatsQueries.INSERT_ROW, [item.ManifestId, item.Id, now, now]);
+ yield* this.execute(ItemStatsQueries.forAction(columns.last, columns.count), [now, now, now, item.ManifestId, item.Id]);
return true;
}
-
- /**
- * The manifest the given item belongs to.
- * @param itemId - The item id
- * @returns The manifest id, or null when no such item exists
- */
- private *itemManifestId(itemId: string): DbOp<string | null> {
- return (yield* this.query<{ ManifestId: string }>(ItemStatsQueries.GET_ITEM_MANIFEST, [itemId]))[0]?.ManifestId ?? null;
- }
}
diff --git a/core/client/src/database/repositories/LogoRepository.ts b/core/client/src/database/repositories/LogoRepository.ts
index 273f71ca0..34d8f4e7a 100644
--- a/core/client/src/database/repositories/LogoRepository.ts
+++ b/core/client/src/database/repositories/LogoRepository.ts
@@ -78,10 +78,11 @@ export class LogoRepository extends BaseRepository {
/**
* Get a logo's identity (kind, key, label) by id, or null when it no longer exists.
* @param logoId The logo id to look up
+ * @param manifestId The manifest of the item pointing at it
* @returns The logo, or null
*/
- public *getById(logoId: string): DbOp<ItemLogo | null> {
- const rows = yield* this.query<{ Id: string; Kind: LogoKind; Source: string; Name: string | null }>(LogoQueries.GET_BY_ID, [logoId]);
+ public *getById(logoId: string, manifestId: string): DbOp<ItemLogo | null> {
+ const rows = yield* this.query<{ Id: string; Kind: LogoKind; Source: string; Name: string | null }>(LogoQueries.GET_BY_ID, [logoId, manifestId]);
return rows.length > 0 ? rows[0] : null;
}
diff --git a/core/client/src/database/repositories/PasskeyRepository.ts b/core/client/src/database/repositories/PasskeyRepository.ts
index e7f2ab0aa..9d926bb8e 100644
--- a/core/client/src/database/repositories/PasskeyRepository.ts
+++ b/core/client/src/database/repositories/PasskeyRepository.ts
@@ -3,6 +3,7 @@ import { PasskeyMapper, type PasskeyRow, type PasskeyWithItemRow, type PasskeyWi
import { PasskeyQueries } from '../queries/PasskeyQueries';
import type { DbOp } from '../DbOp';
+import type { ItemRef } from '../ItemRef';
import type { Passkey } from '@aliasvault/models/vault';
/**
@@ -22,10 +23,11 @@ export class PasskeyRepository extends BaseRepository {
/**
* Get a passkey by its ID.
* @param passkeyId - The passkey ID
+ * @param manifestId - The manifest the passkey belongs to, which is its item's
* @returns The passkey object or null if not found
*/
- public *getById(passkeyId: string): DbOp<PasskeyWithItem | null> {
- const results = yield* this.query<PasskeyWithItemRow>(PasskeyQueries.GET_BY_ID_WITH_ITEM, [passkeyId]);
+ public *getById(passkeyId: string, manifestId: string): DbOp<PasskeyWithItem | null> {
+ const results = yield* this.query<PasskeyWithItemRow>(PasskeyQueries.GET_BY_ID_WITH_ITEM, [passkeyId, manifestId]);
if (results.length === 0) {
return null;
@@ -36,28 +38,21 @@ export class PasskeyRepository extends BaseRepository {
/**
* Get all passkeys for a specific item.
- * @param itemId - The item ID
- * @param manifestId - The manifest the item belongs to, when known
+ * @param item - The item, named by its manifest and id
* @returns Array of passkey objects
*/
- public *getByItemId(itemId: string, manifestId?: string): DbOp<Passkey[]> {
- const scope = manifestId ?? (yield* this.resolveRowManifestId('Items', itemId));
- if (!scope) {
- return [];
- }
-
- const results = yield* this.query<PasskeyRow>(PasskeyQueries.GET_BY_ITEM_ID, [itemId, scope]);
+ public *getByItemId(item: ItemRef): DbOp<Passkey[]> {
+ const results = yield* this.query<PasskeyRow>(PasskeyQueries.GET_BY_ITEM_ID, [item.Id, item.ManifestId]);
return PasskeyMapper.mapRows(results);
}
/**
* Create a new passkey linked to an item.
*
- * The manifest is not passed in: a passkey belongs to whichever manifest its item is in, and the
- * INSERT reads it from there (see {@link BaseQueries.MANIFEST_OF_ITEM}).
+ * A passkey belongs to whichever manifest its item is in, so `ManifestId` names the item's manifest.
* @param passkey - The passkey object to create
*/
- public async create(passkey: Omit<Passkey, 'CreatedAt' | 'UpdatedAt' | 'IsDeleted' | 'ManifestId'>): Promise<void> {
+ public async create(passkey: Omit<Passkey, 'CreatedAt' | 'UpdatedAt' | 'IsDeleted'>): Promise<void> {
return this.withTransaction(async () => {
const currentDateTime = this.now();
@@ -77,12 +72,10 @@ export class PasskeyRepository extends BaseRepository {
: new Uint8Array(passkey.UserHandle);
}
- const manifestId = await this.run(this.writeManifestId());
await this.run(this.execute(PasskeyQueries.INSERT, [
passkey.Id,
passkey.ItemId,
- passkey.ItemId,
- manifestId,
+ passkey.ManifestId,
passkey.RpId,
userHandleData,
passkey.PublicKey,
@@ -100,16 +93,10 @@ export class PasskeyRepository extends BaseRepository {
/**
* Delete a passkey by its ID (soft delete).
* @param passkeyId - The ID of the passkey to delete
- * @param manifestId - The manifest the passkey belongs to, when known
+ * @param manifestId - The manifest the passkey belongs to, which is its item's
* @returns The number of rows updated
*/
- public async deleteById(passkeyId: string, manifestId?: string): Promise<number> {
- return this.withTransaction(async () => {
- const scope = manifestId ?? await this.run(this.resolveRowManifestId('Passkeys', passkeyId));
- if (!scope) {
- return 0;
- }
- return this.run(this.execute(PasskeyQueries.SOFT_DELETE, [this.now(), passkeyId, scope]));
- });
+ public async deleteById(passkeyId: string, manifestId: string): Promise<number> {
+ return this.withTransaction(() => this.run(this.execute(PasskeyQueries.SOFT_DELETE, [this.now(), passkeyId, manifestId])));
}
}
diff --git a/core/client/src/items/FolderUtils.ts b/core/client/src/items/FolderUtils.ts
index 229293258..35f63574a 100644
--- a/core/client/src/items/FolderUtils.ts
+++ b/core/client/src/items/FolderUtils.ts
@@ -1,4 +1,6 @@
-import type { Folder } from '../database/repositories/FolderRepository';
+import { scopedKey } from '../database/ItemRef';
+
+import type { Folder, FolderRef } from '../database/repositories/FolderRepository';
/**
* Maximum allowed folder nesting depth.
@@ -16,6 +18,27 @@ export type FolderTreeNode = Folder & {
path: string[]; // Array of folder IDs from root to this folder
};
+/**
+ * The folders of one manifest. A folder is keyed by (ManifestId, Id) and a folder tree never crosses a
+ * manifest, so every walk below stays inside the manifest of the folder it starts from.
+ * @param manifestId - The manifest to keep
+ * @param folders - Flat array of all folders
+ * @returns The folders stamped for that manifest
+ */
+function foldersOfManifest(manifestId: string, folders: Folder[]): Folder[] {
+ return folders.filter(f => f.ManifestId === manifestId);
+}
+
+/**
+ * Whether an item sits directly in the given folder.
+ * @param item - The item to test
+ * @param folder - The folder
+ * @returns True when the item names this folder inside the folder's own manifest
+ */
+export function isItemInFolder(item: { FolderId?: string | null; ManifestId?: string | null }, folder: FolderRef): boolean {
+ return item.FolderId === folder.Id && item.ManifestId === folder.ManifestId;
+}
+
/**
* Whether a folder is shared with other people rather than the user's own.
* @param folder - The folder to classify
@@ -37,7 +60,7 @@ export function buildFolderTree(folders: Folder[]): FolderTreeNode[] {
// Initialize all folders as tree nodes
folders.forEach(folder => {
- folderMap.set(folder.Id, {
+ folderMap.set(scopedKey(folder.ManifestId, folder.Id), {
...folder,
children: [],
depth: 0,
@@ -49,7 +72,7 @@ export function buildFolderTree(folders: Folder[]): FolderTreeNode[] {
const rootFolders: FolderTreeNode[] = [];
folders.forEach(folder => {
- const node = folderMap.get(folder.Id)!;
+ const node = folderMap.get(scopedKey(folder.ManifestId, folder.Id))!;
if (!folder.ParentFolderId) {
// Root folder
@@ -58,7 +81,7 @@ export function buildFolderTree(folders: Folder[]): FolderTreeNode[] {
rootFolders.push(node);
} else {
// Child folder
- const parent = folderMap.get(folder.ParentFolderId);
+ const parent = folderMap.get(scopedKey(folder.ManifestId, folder.ParentFolderId));
if (parent) {
node.depth = parent.depth + 1;
node.path = [...parent.path, folder.Id];
@@ -93,18 +116,19 @@ export function buildFolderTree(folders: Folder[]): FolderTreeNode[] {
/**
* Get folder depth in the hierarchy.
- * @param folderId - The folder ID to check
- * @param folders - Flat array of all folders
+ * @param ref - The folder to check
+ * @param allFolders - Flat array of all folders
* @returns Depth (0 = root, 1 = one level deep, etc.) or null if folder not found
*/
-export function getFolderDepth(folderId: string, folders: Folder[]): number | null {
- const folder = folders.find(f => f.Id === folderId);
+export function getFolderDepth(ref: FolderRef, allFolders: Folder[]): number | null {
+ const folders = foldersOfManifest(ref.ManifestId, allFolders);
+ const folder = folders.find(f => f.Id === ref.Id);
if (!folder) {
return null;
}
let depth = 0;
- let currentId: string | null = folderId;
+ let currentId: string | null = ref.Id;
// Traverse up to root, counting levels
while (currentId) {
@@ -126,17 +150,19 @@ export function getFolderDepth(folderId: string, folders: Folder[]): number | nu
/**
* Get the full path of folder names from root to the specified folder.
- * @param folderId - The folder ID
- * @param folders - Flat array of all folders
+ * @param ref - The folder, or null for none
+ * @param allFolders - Flat array of all folders
* @returns Array of folder names from root to current folder, or empty array if not found
*/
-export function getFolderPath(folderId: string | null, folders: Folder[]): string[] {
- if (!folderId) {
+export function getFolderPath(ref: FolderRef | null, allFolders: Folder[]): string[] {
+ if (!ref) {
return [];
}
+ const folders = foldersOfManifest(ref.ManifestId, allFolders);
+
const path: string[] = [];
- let currentId: string | null = folderId;
+ let currentId: string | null = ref.Id;
let iterations = 0;
// Build path by traversing up to root
@@ -155,17 +181,19 @@ export function getFolderPath(folderId: string | null, folders: Folder[]): strin
/**
* Get the full path of folder IDs from root to the specified folder.
- * @param folderId - The folder ID
- * @param folders - Flat array of all folders
+ * @param ref - The folder, or null for none
+ * @param allFolders - Flat array of all folders
* @returns Array of folder IDs from root to current folder, or empty array if not found
*/
-export function getFolderIdPath(folderId: string | null, folders: Folder[]): string[] {
- if (!folderId) {
+export function getFolderIdPath(ref: FolderRef | null, allFolders: Folder[]): string[] {
+ if (!ref) {
return [];
}
+ const folders = foldersOfManifest(ref.ManifestId, allFolders);
+
const path: string[] = [];
- let currentId: string | null = folderId;
+ let currentId: string | null = ref.Id;
let iterations = 0;
// Build path by traversing up to root
@@ -217,22 +245,23 @@ export function truncateFolderPath(pathSegments: string[], maxSegments: number =
/**
* Check if a folder can have subfolders (not at max depth).
- * @param folderId - The folder ID to check
+ * @param ref - The folder to check
* @param folders - Flat array of all folders
* @returns True if folder can have children, false otherwise
*/
-export function canHaveSubfolders(folderId: string, folders: Folder[]): boolean {
- const depth = getFolderDepth(folderId, folders);
+export function canHaveSubfolders(ref: FolderRef, folders: Folder[]): boolean {
+ const depth = getFolderDepth(ref, folders);
return depth !== null && depth < MAX_FOLDER_DEPTH;
}
/**
* Get all descendant folder IDs (children, grandchildren, etc.).
- * @param folderId - The parent folder ID
- * @param folders - Flat array of all folders
- * @returns Array of descendant folder IDs
+ * @param ref - The parent folder
+ * @param allFolders - Flat array of all folders
+ * @returns Array of descendant folder IDs, all inside the parent's own manifest
*/
-export function getDescendantFolderIds(folderId: string, folders: Folder[]): string[] {
+export function getDescendantFolderIds(ref: FolderRef, allFolders: Folder[]): string[] {
+ const folders = foldersOfManifest(ref.ManifestId, allFolders);
const descendants: string[] = [];
/**
@@ -247,26 +276,26 @@ export function getDescendantFolderIds(folderId: string, folders: Folder[]): str
});
};
- traverse(folderId);
+ traverse(ref.Id);
return descendants;
}
/**
* Get total count of items in a folder and all its subfolders.
- * @param folderId - The folder ID to count items for
+ * @param ref - The folder to count items for
* @param allItems - All items in the vault
* @param allFolders - All folders in the vault
* @returns Total item count including subfolders
*/
export function getRecursiveItemCount(
- folderId: string,
- allItems: Array<{ FolderId?: string | null }>,
+ ref: FolderRef,
+ allItems: Array<{ FolderId?: string | null; ManifestId?: string | null }>,
allFolders: Folder[]
): number {
// Get all descendant folder IDs
- const descendantIds = getDescendantFolderIds(folderId, allFolders);
- const allFolderIds = [folderId, ...descendantIds];
+ const descendantIds = getDescendantFolderIds(ref, allFolders);
+ const allFolderIds = [ref.Id, ...descendantIds];
- // Count items in current folder and all descendants
- return allItems.filter(item => item.FolderId && allFolderIds.includes(item.FolderId)).length;
+ // Count items in current folder and all descendants, which share the folder's manifest
+ return allItems.filter(item => item.ManifestId === ref.ManifestId && item.FolderId && allFolderIds.includes(item.FolderId)).length;
}
diff --git a/core/rust/src/vault_codec/sharing_tests.rs b/core/rust/src/vault_codec/sharing_tests.rs
index 919e41839..e4fe6aacc 100644
--- a/core/rust/src/vault_codec/sharing_tests.rs
+++ b/core/rust/src/vault_codec/sharing_tests.rs
@@ -138,8 +138,8 @@ fn stamp_subtree(mut tables: Vec<CodecTableData>, folder_id: &str, manifest_id:
}
/*
- * Every item takes the stamp of the folder it sits in, which is what the client's INSERT/UPDATE/
- * MOVE statements resolve via `BaseQueries.MANIFEST_OF_FOLDER`. Deriving it here rather than
+ * Every item takes the stamp of the folder it sits in, which is what the client's INSERT/UPDATE
+ * statements write from the folder reference the caller names. Deriving it here rather than
* carrying it forward is what makes an item moved OUT of a shared folder leave that manifest.
*/
let folder_scope: HashMap<String, String> = tables
diff --git a/core/rust/src/vault_sync/db.rs b/core/rust/src/vault_sync/db.rs
index 551f1140c..0b65f01ec 100644
--- a/core/rust/src/vault_sync/db.rs
+++ b/core/rust/src/vault_sync/db.rs
@@ -230,7 +230,7 @@ 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 (?, ?, ?, COALESCE((SELECT ManifestId FROM Folders WHERE Id = ?), ?), 0, 0, ?, ?)";
+const INSERT_FOLDER: &str = "INSERT INTO Folders (Id, Name, ParentFolderId, ManifestId, Weight, IsDeleted, CreatedAt, UpdatedAt) VALUES (?, ?, ?, ?, 0, 0, ?, ?)";
const RESTAMP_SUBTREE_FOLDERS: &str = "UPDATE Folders SET ManifestId = ? WHERE Id IN (WITH RECURSIVE subtree(Id) AS (SELECT Id FROM Folders WHERE Id = ? UNION ALL SELECT f.Id FROM Folders f INNER JOIN subtree s ON f.ParentFolderId = s.Id) SELECT Id FROM subtree)";
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 = ? UNION ALL SELECT f.Id FROM Folders f INNER JOIN subtree s ON f.ParentFolderId = s.Id) 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";
@@ -292,7 +292,7 @@ pub(crate) async fn render_manifest_folder(host: &Host, manifest_id: &str, name:
host,
Db::Local,
vec![
- SqlStatement { sql: INSERT_FOLDER.to_string(), params: vec![json!(folder_id), json!(name), Value::Null, Value::Null, json!(active_manifest_id), json!(now), json!(now)] },
+ SqlStatement { sql: INSERT_FOLDER.to_string(), params: vec![json!(folder_id), json!(name), Value::Null, json!(active_manifest_id), json!(now), json!(now)] },
SqlStatement { sql: RESTAMP_SUBTREE_FOLDERS.to_string(), params: vec![json!(manifest_id), json!(folder_id)] },
SqlStatement { sql: RESTAMP_SUBTREE_ITEMS.to_string(), params: vec![json!(manifest_id), json!(now), json!(manifest_id), json!(folder_id)] },
],