Skip to content

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

Add devlog (#2268)

Leendert de Borst1fa550e31e4e
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
index 91822659f..3f14e10aa 100644
--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts
@@ -3,6 +3,7 @@ import * as OTPAuth from 'otpauth';
import { storage } from 'wxt/utils/storage';
import { TRASH_RETENTION_DAYS } from '@/utils/constants/vault';
+import { devLog } from '@/utils/DevLogger';
import type { EncryptionKeyDerivationParams } from '@/utils/dist/core/models/metadata';
import { FieldKey, ItemTypes, createSystemField, type Item, type PasswordSettings } from '@/utils/dist/core/models/vault';
import type { Vault, VaultResponse, VaultPostResponse } from '@/utils/dist/core/models/webapi';
@@ -664,13 +665,14 @@ export async function handleUploadVault(
const sqliteClient = await createVaultSqliteClient();
// Upload the vault to the server.
- const response = await uploadNewVaultToServer(sqliteClient);
+ const { response, vaultPruned } = await uploadNewVaultToServer(sqliteClient);
return {
success: true,
status: response.status,
newRevisionNumber: response.newRevisionNumber,
- mutationSeqAtStart
+ mutationSeqAtStart,
+ vaultPruned
};
} catch (error) {
console.error('Failed to upload vault:', error);
@@ -768,8 +770,10 @@ export async function handleClearPersistedFormValues(): Promise<void> {
* Upload a new version of the vault to the server using the provided sqlite client.
* Prunes expired trash items before uploading.
*/
-async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<VaultPostResponse> {
+async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<{ response: VaultPostResponse; vaultPruned: boolean }> {
+ devLog('[VaultSync] Upload started');
let updatedVaultData = sqliteClient.exportToBase64();
+ let vaultPruned = false;
const encryptionKey = await handleGetEncryptionKey();
if (!encryptionKey) {
@@ -785,8 +789,9 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
try {
const pruneResult = await vaultMergeService.prune(updatedVaultData, TRASH_RETENTION_DAYS);
if (pruneResult.success && pruneResult.statementCount > 0) {
- console.info(`[VaultSync] Pruned expired items from trash (${pruneResult.statementCount} statements)`);
+ devLog(`[VaultSync] Pruned expired items from trash (${pruneResult.statementCount} statements)`);
updatedVaultData = pruneResult.prunedVaultBase64;
+ vaultPruned = true;
/**
* Reload the sqlite client with the pruned vault so the UI reflects the change.
@@ -805,6 +810,8 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
encryptionKey
);
+ devLog('[VaultSync] Vault exported, pruned and encrypted, sending to server');
+
// Store in local: storage for persistence
await storage.setItem('local:encryptedVault', encryptedVault);
@@ -841,6 +848,8 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
// Check if response is successful (.status === 0)
if (response.status === 0) {
+ devLog(`[VaultSync] Upload completed (new revision ${response.newRevisionNumber})`);
+
// Upload succeeded - update server revision
await storage.setItem('local:serverRevision', response.newRevisionNumber);
} else if (response.status === 2) {
@@ -851,7 +860,7 @@ async function uploadNewVaultToServer(sqliteClient: SqliteClient) : Promise<Vaul
throw new Error(formatErrorWithCode(`${await t('common.errors.unknownError')} [server status: ${response.status}]`, AppErrorCode.UPLOAD_FAILED));
}
- return response;
+ return { response, vaultPruned };
}
/**
@@ -1199,7 +1208,7 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
if (isSyncInProgress) {
// Mark that we need to sync again after current sync completes
hasPendingSync = true;
- console.info('[VaultSync] Sync already in progress, queued for retry after completion');
+ devLog('[VaultSync] Sync already in progress, queued for retry after completion');
return { success: true, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: false };
}
@@ -1207,6 +1216,8 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
isSyncInProgress = true;
hasPendingSync = false;
+ devLog('[VaultSync] Sync started');
+
const webApi = new WebApiService();
try {
@@ -1227,6 +1238,8 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
// Get current sync state
const syncState = await handleGetSyncState();
+ devLog(`[VaultSync] Status received (server rev ${statusResponse.vaultRevision}, local rev ${syncState.serverRevision}, isDirty ${syncState.isDirty})`);
+
// Check if server is actually available (0.0.0 indicates connection error)
if (statusResponse.serverVersion === '0.0.0') {
// Server is unavailable - enter offline mode if we have a local vault
@@ -1286,7 +1299,7 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
const mergeResult = await vaultMergeService.merge(localDecrypted, serverDecrypted);
if (mergeResult.success) {
- console.info('Vault merge during sync completed:', mergeResult.stats);
+ devLog('[VaultSync] Vault merge during sync completed:', mergeResult.stats);
const mergedEncryptedVault = await EncryptionUtility.symmetricEncrypt(
mergeResult.mergedVaultBase64,
@@ -1304,7 +1317,7 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
});
if (!storeResult.success) {
- console.info('Mutation detected during merge, re-syncing...');
+ devLog('[VaultSync] Mutation detected during merge, re-syncing...');
return handleFullVaultSync();
}
@@ -1354,7 +1367,7 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
});
if (!storeResult.success) {
- console.info('Mutation detected during sync, re-syncing...');
+ devLog('[VaultSync] Mutation detected during sync, re-syncing...');
return handleFullVaultSync();
}
@@ -1391,6 +1404,13 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
mutationSeqAtStart: uploadResponse.mutationSeqAtStart!,
newServerRevision: uploadResponse.newRevisionNumber!
});
+
+ /*
+ * If expired trash items were pruned during upload, report the vault as new
+ * so the popup reloads the pruned vault instead of resurrecting the items
+ * from its stale in-memory copy on the next mutation.
+ */
+ return { success: true, hasNewVault: uploadResponse.vaultPruned === true, wasOffline: false, upgradeRequired: false, requiresLogout: false };
} else if (uploadResponse.status === 2) {
/**
* Server returned Outdated - another device uploaded first.
@@ -1426,10 +1446,10 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
`Server recovery complete: rev ${statusResponse.vaultRevision} → ${uploadResponse.newRevisionNumber}`
);
- return { success: true, hasNewVault: false, wasOffline: false, upgradeRequired: false, requiresLogout: false };
+ return { success: true, hasNewVault: uploadResponse.vaultPruned === true, wasOffline: false, upgradeRequired: false, requiresLogout: false };
} else if (uploadResponse.status === 2) {
// Another client recovered first
- console.info('Another client recovered server first, re-syncing...');
+ devLog('[VaultSync] Another client recovered server first, re-syncing...');
return handleFullVaultSync();
} else {
console.error('Server recovery failed:', uploadResponse.error);
@@ -1489,13 +1509,15 @@ async function handleFullVaultSyncInternal(): Promise<FullVaultSyncResult> {
// Reset sync in progress flag
isSyncInProgress = false;
+ devLog('[VaultSync] Sync finished');
+
/*
* Check if another sync is needed (mutations happened during this sync).
* Trigger follow-up sync asynchronously (don't await to avoid blocking).
* Popup will poll isDirty flag to detect when background sync completes.
*/
if (hasPendingSync) {
- console.info('[VaultSync] Pending mutations detected, triggering follow-up sync');
+ devLog('[VaultSync] Pending mutations detected, triggering follow-up sync');
hasPendingSync = false;
handleFullVaultSync().catch(err => {
diff --git a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
index ec0421f25..c6b164297 100644
--- a/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
+++ b/apps/browser-extension/src/entrypoints/popup/hooks/useVaultMutate.ts
@@ -2,6 +2,7 @@ import { useCallback, useRef } from 'react';
import { useDb } from '@/entrypoints/popup/context/DbContext';
+import { devLog } from '@/utils/DevLogger';
import { EncryptionUtility } from '@/utils/EncryptionUtility';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';
@@ -55,7 +56,7 @@ export function useVaultMutate(): {
/**
* Start polling to detect when background sync completes.
- * Polls isDirty flag AND background sync state every 500ms.
+ * Polls isDirty flag AND background sync state every 200ms.
* Only clears indicator when vault is clean AND background has no sync in progress.
*/
const startPollingForCompletion = useCallback((): void => {
@@ -64,7 +65,7 @@ export function useVaultMutate(): {
clearInterval(pollIntervalRef.current);
}
- console.info('[VaultMutate] Starting to poll for sync completion');
+ devLog('[VaultMutate] Starting to poll for sync completion');
pollIntervalRef.current = setInterval(async () => {
try {
@@ -82,7 +83,7 @@ export function useVaultMutate(): {
* This prevents clearing the indicator between queued syncs.
*/
if (!syncState.isDirty && !syncState.isSyncInProgress) {
- console.info('[VaultMutate] Sync completed (isDirty=false, isSyncInProgress=false), clearing uploading indicator');
+ devLog('[VaultMutate] Sync completed (isDirty=false, isSyncInProgress=false), clearing uploading indicator');
dbContext.setIsUploading(false);
dbContext.setIsSyncing(false);
@@ -98,7 +99,7 @@ export function useVaultMutate(): {
} catch (error) {
console.error('[VaultMutate] Error polling sync state:', error);
}
- }, 500); /* Poll every 500ms */
+ }, 200); /* Poll every 200ms */
}, [dbContext]);
/**
diff --git a/apps/browser-extension/src/utils/DevLogger.ts b/apps/browser-extension/src/utils/DevLogger.ts
new file mode 100644
index 000000000..311716e69
--- /dev/null
+++ b/apps/browser-extension/src/utils/DevLogger.ts
@@ -0,0 +1,10 @@
+/**
+ * Log a timestamped trace message for debugging. Only logs in dev builds.
+ */
+export function devLog(message: string, ...args: unknown[]): void {
+ if (!import.meta.env.DEV) {
+ return;
+ }
+ const time = new Date().toISOString().slice(11, 23);
+ console.info(`[${time}] ${message}`, ...args);
+}
diff --git a/apps/browser-extension/src/utils/VaultMergeService.ts b/apps/browser-extension/src/utils/VaultMergeService.ts
index c429e06d9..ff5ecb53b 100644
--- a/apps/browser-extension/src/utils/VaultMergeService.ts
+++ b/apps/browser-extension/src/utils/VaultMergeService.ts
@@ -2,6 +2,7 @@ import initSqlJs, { Database, SqlJsStatic, SqlValue } from 'sql.js';
import { browser } from 'wxt/browser';
import { TRASH_RETENTION_DAYS } from '@/utils/constants/vault';
+import { devLog } from '@/utils/DevLogger';
import init, { getSyncableTableNames, mergeVaults, pruneVault } from './dist/core/rust/aliasvault_core.js';
@@ -134,6 +135,21 @@ export class VaultMergeService {
this.rustInitialized = true;
}
+ /**
+ * Get the SQL.js instance, initializing and caching it on first use.
+ */
+ private async getSqlJs(): Promise<SqlJsStatic> {
+ this.sqlJsInstance ??= await initSqlJs({
+ /**
+ * Locate the SQL.js WASM file.
+ * @param file - The file name to locate
+ * @returns The path to the file
+ */
+ locateFile: (file: string) => `src/${file}`
+ });
+ return this.sqlJsInstance;
+ }
+
/**
* Merge local vault changes with server vault using LWW strategy.
*
@@ -153,15 +169,7 @@ export class VaultMergeService {
// Initialize Rust WASM
await this.initRust();
- // Use injected SQL.js instance or initialize a new one
- const SQL = this.sqlJsInstance ?? await initSqlJs({
- /**
- * Locate the SQL.js WASM file.
- * @param file - The file name to locate
- * @returns The path to the file
- */
- locateFile: (file: string) => `src/${file}`
- });
+ const SQL = await this.getSqlJs();
// Load both databases
const localDb = this.loadDatabase(SQL, localVaultBase64);
@@ -191,7 +199,7 @@ export class VaultMergeService {
server_tables: serverTables,
})) as MergeInput;
- console.debug('[VaultMerge] Merge input:', {
+ devLog('[VaultMerge] Merge input:', {
localTableCount: localTables.length,
serverTableCount: serverTables.length,
localTables: localTables.map(t => ({ name: t.name, recordCount: t.records.length })),
@@ -254,15 +262,7 @@ export class VaultMergeService {
// Initialize Rust WASM
await this.initRust();
- // Use injected SQL.js instance or initialize a new one
- const SQL = this.sqlJsInstance ?? await initSqlJs({
- /**
- * Locate the SQL.js WASM file.
- * @param file - The file name to locate
- * @returns The path to the file
- */
- locateFile: (file: string) => `src/${file}`
- });
+ const SQL = await this.getSqlJs();
// Load the database
const db = this.loadDatabase(SQL, vaultBase64);
@@ -285,6 +285,16 @@ export class VaultMergeService {
})) as PruneInput;
const pruneOutput = pruneVault(pruneInput) as PruneOutput;
+ const statementCount = pruneOutput.statements.length;
+
+ // Nothing to prune - return original vault, skipping the export roundtrip
+ if (statementCount === 0) {
+ return {
+ success: pruneOutput.success,
+ prunedVaultBase64: vaultBase64,
+ statementCount,
+ };
+ }
// Execute SQL statements from Rust on database
for (const stmt of pruneOutput.statements) {
@@ -294,10 +304,9 @@ export class VaultMergeService {
// Export the pruned database
const prunedVaultBase64 = this.exportDatabase(db);
- const statementCount = pruneOutput.statements.length;
if (statementCount > 0) {
- console.info(`[VaultMerge] Pruned expired items from trash (${statementCount} SQL statements executed)`);
+ devLog(`[VaultMerge] Pruned expired items from trash (${statementCount} SQL statements executed)`);
}
return {
@@ -338,11 +347,13 @@ export class VaultMergeService {
private exportDatabase(db: Database): string {
db.run('VACUUM');
const binaryArray = db.export();
- let binaryString = '';
- for (let i = 0; i < binaryArray.length; i++) {
- binaryString += String.fromCharCode(binaryArray[i]);
+ // Convert to string in chunks to avoid O(n²) byte-by-byte concatenation
+ const chunkSize = 0x8000;
+ const parts: string[] = [];
+ for (let i = 0; i < binaryArray.length; i += chunkSize) {
+ parts.push(String.fromCharCode(...binaryArray.subarray(i, i + chunkSize)));
}
- return btoa(binaryString);
+ return btoa(parts.join(''));
}
/**
diff --git a/apps/browser-extension/src/utils/types/messaging/VaultUploadResponse.ts b/apps/browser-extension/src/utils/types/messaging/VaultUploadResponse.ts
index 96f761eaf..831d36426 100644
--- a/apps/browser-extension/src/utils/types/messaging/VaultUploadResponse.ts
+++ b/apps/browser-extension/src/utils/types/messaging/VaultUploadResponse.ts
@@ -4,5 +4,7 @@ export type VaultUploadResponse = {
status?: number,
newRevisionNumber?: number,
/** Mutation sequence at the start of upload, for race detection */
- mutationSeqAtStart?: number
+ mutationSeqAtStart?: number,
+ /** Whether expired trash items were pruned from the vault during upload */
+ vaultPruned?: boolean
};