diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index 82c9087b..9d100132 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -5,7 +5,6 @@ import { clearNavToActivePathStore } from '../app/state/navToActivePath'; import { Session, Sessions, getSessionStoreName } from '../app/state/sessions'; import { getSettings } from '../app/state/settings'; import { recordPacket } from '../app/state/debugPackets'; -import { promptDialog } from '../app/state/dialog'; const MAX_BODY = 8192; @@ -86,183 +85,9 @@ const debugFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise return res; }; -// Track if we're currently handling a key conflict to prevent loops -let handlingKeyConflict = false; - -const deleteIndexedDB = (dbName: string): Promise => - new Promise((resolve, reject) => { - const request = globalThis.indexedDB.deleteDatabase(dbName); - request.onsuccess = () => { - console.log(`[initMatrix] Deleted IndexedDB database: ${dbName}`); - resolve(); - }; - request.onerror = () => { - console.error(`[initMatrix] Failed to delete IndexedDB database: ${dbName}`, request.error); - reject(request.error); - }; - request.onblocked = () => { - console.warn(`[initMatrix] Delete blocked for IndexedDB database: ${dbName}`); - // Resolve anyway as the delete might succeed later - resolve(); - }; - }); - -const getAllIndexedDBNames = async (): Promise => { - try { - if ('databases' in globalThis.indexedDB) { - // Add timeout to prevent hanging - const timeoutPromise = new Promise((resolve) => { - setTimeout(() => { - console.warn('[initMatrix] indexedDB.databases() timed out after 2s'); - resolve([]); - }, 2000); - }); - - const databasesPromise = globalThis.indexedDB - .databases() - .then((dbs) => dbs.map((db) => db.name).filter((name) => typeof name === 'string')); - - return await Promise.race([databasesPromise, timeoutPromise]); - } - } catch (error) { - console.warn('[initMatrix] Error getting IndexedDB names:', error); - } - // Fallback for browsers that don't support indexedDB.databases() - return []; -}; - -/** - * Delete the Rust crypto database to fix one-time key conflicts. - * This happens when the local crypto state has keys that conflict with server state. - */ -const deleteRustCryptoDatabase = async (session: Session): Promise => { - console.log('[initMatrix] 🔑 Attempting to delete Rust crypto database to fix key conflicts...'); - - const dbNames = await getAllIndexedDBNames(); - const storagePrefix = `${session.userId}@${session.deviceId}`; - - // Find crypto databases for this session - const cryptoDbNames = dbNames.filter( - (name) => name.includes('matrix-sdk-crypto') || name.includes(storagePrefix), - ); - - if (cryptoDbNames.length === 0) { - console.log('[initMatrix] No crypto databases found to delete'); - return false; - } - - console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames); - - for (let i = 0; i < cryptoDbNames.length; i += 1) { - const dbName = cryptoDbNames[i]; - try { - await deleteIndexedDB(dbName); - console.log(`[initMatrix] ✅ Deleted: ${dbName}`); - } catch (error) { - console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error); - } - } - - return true; -}; - -/** - * Setup error listener to detect one-time key conflicts and auto-fix them. - */ -const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => { - // Listen for HTTP errors from the client - let keyConflictCount = 0; - const KEY_CONFLICT_THRESHOLD = 3; - - // Patch console.log/error to detect the key conflict errors - const keyConflictPattern = /One time key.*already exists/; - - // We need to use a different approach - listen to the crypto module - // Since we can't directly intercept, we'll use a MutationObserver-style approach - // by checking for repeated key upload failures - - const checkKeyConflict = (args: unknown[]): boolean => { - const message = args.map((a) => String(a)).join(' '); - return keyConflictPattern.test(message); - }; - - // Override console methods temporarily to detect the errors - const originalError = console.error; - const originalWarn = console.warn; - - const errorHandler = (...args: unknown[]) => { - if (checkKeyConflict(args)) { - keyConflictCount += 1; - console.log( - `[initMatrix] ⚠️ Detected key conflict (${keyConflictCount}/${KEY_CONFLICT_THRESHOLD})`, - ); - - if (keyConflictCount >= KEY_CONFLICT_THRESHOLD && !handlingKeyConflict) { - handlingKeyConflict = true; - console.log('[initMatrix] 🔄 Too many key conflicts detected, attempting auto-fix...'); - - // Schedule the fix for next page load to avoid issues during active session - localStorage.setItem( - 'cinny_fix_key_conflict', - JSON.stringify({ - userId: session.userId, - deviceId: session.deviceId, - timestamp: Date.now(), - }), - ); - - // Restore console methods - console.error = originalError; - console.warn = originalWarn; - - // Notify user and reload - setTimeout(() => { - promptDialog( - 'Detected encryption key conflict. The app needs to reset your encryption session. You may need to re-verify your devices after this. Continue?', - true, - ).then((continueFix) => { - if (continueFix) { - deleteRustCryptoDatabase(session).then(() => { - window.location.reload(); - }); - } else { - handlingKeyConflict = false; - } - }); - }, 100); - } - } - originalError.apply(console, args); - }; - - console.error = errorHandler; - console.warn = (...args: unknown[]) => { - if (checkKeyConflict(args)) { - keyConflictCount += 1; - } - originalWarn.apply(console, args); - }; -}; - export const initClient = async (session: Session): Promise => { const storeName = getSessionStoreName(session); - // Check if we need to fix a key conflict from a previous session - const pendingFix = localStorage.getItem('cinny_fix_key_conflict'); - if (pendingFix) { - try { - const fixData = JSON.parse(pendingFix); - if (fixData.userId === session.userId && fixData.deviceId === session.deviceId) { - console.log('[initMatrix] 🔧 Found pending key conflict fix, clearing crypto database...'); - await deleteRustCryptoDatabase(session); - localStorage.removeItem('cinny_fix_key_conflict'); - console.log('[initMatrix] ✅ Crypto database cleared'); - } - } catch { - localStorage.removeItem('cinny_fix_key_conflict'); - } - } - console.log('[initMatrix] ========================================'); console.log('[initMatrix] Initializing Matrix client for session:'); console.log('[initMatrix] User ID:', session.userId); @@ -298,15 +123,7 @@ export const initClient = async (session: Session): Promise => { await indexedDBStore.startup(); - // Initialize Rust crypto with a unique store prefix for this account - // This ensures each account has its own isolated crypto database - console.log( - '[initMatrix] Initializing Rust crypto with prefix:', - `${session.userId}@${session.deviceId}`, - ); - await mx.initRustCrypto({ - cryptoDatabasePrefix: `${session.userId}@${session.deviceId}`, - }); + await mx.initRustCrypto(); console.log('[initMatrix] ✅ Client initialized successfully!'); @@ -323,9 +140,6 @@ export const initClient = async (session: Session): Promise => { return user; }; - // Setup handler to detect and auto-fix one-time key conflicts - setupKeyConflictHandler(mx, session); - // Register this as the global MatrixClient so auth utils can access the latest token const { setGlobalMatrixClient } = await import('../app/utils/auth'); setGlobalMatrixClient(mx); @@ -367,51 +181,6 @@ export const clearCacheAndReload = async (mx: MatrixClient) => { window.location.reload(); }; -/** - * Fix one-time key conflicts by clearing the Rust crypto database. - * Call this when you see repeated "One time key already exists" errors. - * The user will need to re-verify their devices after this. - */ -export const fixKeyConflict = async (mx: MatrixClient): Promise => { - const userId = mx.getSafeUserId(); - const deviceId = mx.getDeviceId(); - - if (!userId || !deviceId) { - console.error('[initMatrix] Cannot fix key conflict: missing userId or deviceId'); - return; - } - - console.log('[initMatrix] 🔧 Fixing key conflict for', userId, deviceId); - - // Stop the client first - mx.stopClient(); - - // Delete the crypto databases - const dbNames = await getAllIndexedDBNames(); - const storagePrefix = `${userId}@${deviceId}`; - - const cryptoDbNames = dbNames.filter( - (name) => - name.includes('matrix-sdk-crypto') || name.includes(storagePrefix) || name.includes('crypto'), - ); - - console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames); - - for (let i = 0; i < cryptoDbNames.length; i += 1) { - const dbName = cryptoDbNames[i]; - try { - await deleteIndexedDB(dbName); - console.log(`[initMatrix] ✅ Deleted: ${dbName}`); - } catch (error) { - console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error); - } - } - - // Reload the page - console.log('[initMatrix] 🔄 Reloading...'); - window.location.reload(); -}; - export const logoutClient = async (mx: MatrixClient) => { mx.stopClient();