Apply the auto-fixable lint rules and the formatter, and drop the Vite build artifacts.
This commit is contained in:
+91
-79
@@ -7,8 +7,8 @@ import { Session, getSessionStoreName } from '../app/state/sessions';
|
||||
// Track if we're currently handling a key conflict to prevent loops
|
||||
let handlingKeyConflict = false;
|
||||
|
||||
const deleteIndexedDB = (dbName: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const deleteIndexedDB = (dbName: string): Promise<void> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const request = global.indexedDB.deleteDatabase(dbName);
|
||||
request.onsuccess = () => {
|
||||
console.log(`[initMatrix] Deleted IndexedDB database: ${dbName}`);
|
||||
@@ -24,7 +24,6 @@ const deleteIndexedDB = (dbName: string): Promise<void> => {
|
||||
resolve();
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const getAllIndexedDBNames = async (): Promise<string[]> => {
|
||||
try {
|
||||
@@ -36,11 +35,11 @@ const getAllIndexedDBNames = async (): Promise<string[]> => {
|
||||
resolve([]);
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
const databasesPromise = (global.indexedDB as any).databases().then((dbs: any[]) => {
|
||||
return dbs.map((db: any) => db.name).filter(Boolean);
|
||||
});
|
||||
|
||||
|
||||
const databasesPromise = (global.indexedDB as any)
|
||||
.databases()
|
||||
.then((dbs: any[]) => dbs.map((db: any) => db.name).filter(Boolean));
|
||||
|
||||
return await Promise.race([databasesPromise, timeoutPromise]);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -52,21 +51,22 @@ const getAllIndexedDBNames = async (): Promise<string[]> => {
|
||||
|
||||
const deleteAllMatrixDatabases = async (): Promise<void> => {
|
||||
console.log('[initMatrix] Clearing all Matrix-related IndexedDB databases...');
|
||||
|
||||
|
||||
const dbNames = await getAllIndexedDBNames();
|
||||
console.log('[initMatrix] Found databases:', dbNames);
|
||||
|
||||
|
||||
// Delete all Matrix-related databases (with matrix-js-sdk: prefix)
|
||||
const matrixDbNames = dbNames.filter(name =>
|
||||
name.startsWith('matrix-js-sdk:') ||
|
||||
name.startsWith('crypto@') ||
|
||||
name.startsWith('sync@') ||
|
||||
name === 'crypto-store' ||
|
||||
name === 'web-sync-store'
|
||||
const matrixDbNames = dbNames.filter(
|
||||
(name) =>
|
||||
name.startsWith('matrix-js-sdk:') ||
|
||||
name.startsWith('crypto@') ||
|
||||
name.startsWith('sync@') ||
|
||||
name === 'crypto-store' ||
|
||||
name === 'web-sync-store',
|
||||
);
|
||||
|
||||
|
||||
console.log('[initMatrix] Deleting Matrix databases:', matrixDbNames);
|
||||
|
||||
|
||||
for (const dbName of matrixDbNames) {
|
||||
try {
|
||||
await deleteIndexedDB(dbName);
|
||||
@@ -82,23 +82,22 @@ const deleteAllMatrixDatabases = async (): Promise<void> => {
|
||||
*/
|
||||
const deleteRustCryptoDatabase = async (session: Session): Promise<boolean> => {
|
||||
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)
|
||||
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 (const dbName of cryptoDbNames) {
|
||||
try {
|
||||
await deleteIndexedDB(dbName);
|
||||
@@ -107,7 +106,7 @@ const deleteRustCryptoDatabase = async (session: Session): Promise<boolean> => {
|
||||
console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
@@ -118,47 +117,56 @@ 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 originalConsoleLog = console.log;
|
||||
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: any[]): boolean => {
|
||||
const message = args.map(a => String(a)).join(' ');
|
||||
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: any[]) => {
|
||||
if (checkKeyConflict(args)) {
|
||||
keyConflictCount++;
|
||||
console.log(`[initMatrix] ⚠️ Detected key conflict (${keyConflictCount}/${KEY_CONFLICT_THRESHOLD})`);
|
||||
|
||||
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()
|
||||
}));
|
||||
|
||||
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(() => {
|
||||
if (confirm('Detected encryption key conflict. The app needs to reset your encryption session. You may need to re-verify your devices after this. Continue?')) {
|
||||
if (
|
||||
confirm(
|
||||
'Detected encryption key conflict. The app needs to reset your encryption session. You may need to re-verify your devices after this. Continue?',
|
||||
)
|
||||
) {
|
||||
deleteRustCryptoDatabase(session).then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
@@ -170,7 +178,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => {
|
||||
}
|
||||
originalError.apply(console, args);
|
||||
};
|
||||
|
||||
|
||||
console.error = errorHandler;
|
||||
console.warn = (...args: any[]) => {
|
||||
if (checkKeyConflict(args)) {
|
||||
@@ -182,7 +190,7 @@ const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => {
|
||||
|
||||
export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
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) {
|
||||
@@ -198,7 +206,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
localStorage.removeItem('cinny_fix_key_conflict');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
console.log('[initMatrix] ========================================');
|
||||
console.log('[initMatrix] Initializing Matrix client for session:');
|
||||
console.log('[initMatrix] User ID:', session.userId);
|
||||
@@ -207,9 +215,9 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
console.log('[initMatrix] Sync store name:', storeName.sync);
|
||||
console.log('[initMatrix] Crypto store name:', storeName.crypto);
|
||||
console.log('[initMatrix] ========================================');
|
||||
|
||||
|
||||
console.log('[initMatrix] Creating Matrix client...');
|
||||
|
||||
|
||||
try {
|
||||
const indexedDBStore = new IndexedDBStore({
|
||||
indexedDB: global.indexedDB,
|
||||
@@ -232,10 +240,13 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
});
|
||||
|
||||
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}`);
|
||||
console.log(
|
||||
'[initMatrix] Initializing Rust crypto with prefix:',
|
||||
`${session.userId}@${session.deviceId}`,
|
||||
);
|
||||
await mx.initRustCrypto({
|
||||
storagePrefix: `${session.userId}@${session.deviceId}`,
|
||||
});
|
||||
@@ -243,7 +254,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
console.log('[initMatrix] ✅ Client initialized successfully!');
|
||||
|
||||
mx.setMaxListeners(50);
|
||||
|
||||
|
||||
// Increase max listeners for User objects to prevent warnings when many components
|
||||
// subscribe to presence events (e.g., in member lists)
|
||||
const originalGetUser = mx.getUser.bind(mx);
|
||||
@@ -270,16 +281,16 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
console.error('[initMatrix] ❌ Crypto store account mismatch detected!');
|
||||
console.error('[initMatrix] Error details:', error.message);
|
||||
console.error('[initMatrix] Expected account:', session.userId, session.deviceId);
|
||||
|
||||
|
||||
// This shouldn't happen anymore since we delete the shared db before init
|
||||
// If it does happen, it means there's a different issue
|
||||
throw new Error(
|
||||
`❌ Crypto store conflict detected.\n\n` +
|
||||
`This account's crypto store contains data from a different account.\n` +
|
||||
`Please clear site data in DevTools (F12 → Application → Storage → Clear site data)`
|
||||
`This account's crypto store contains data from a different account.\n` +
|
||||
`Please clear site data in DevTools (F12 → Application → Storage → Clear site data)`,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// Re-throw other errors
|
||||
throw error;
|
||||
}
|
||||
@@ -306,29 +317,28 @@ export const clearCacheAndReload = async (mx: MatrixClient) => {
|
||||
export const fixKeyConflict = async (mx: MatrixClient): Promise<void> => {
|
||||
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')
|
||||
|
||||
const cryptoDbNames = dbNames.filter(
|
||||
(name) =>
|
||||
name.includes('matrix-sdk-crypto') || name.includes(storagePrefix) || name.includes('crypto'),
|
||||
);
|
||||
|
||||
|
||||
console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames);
|
||||
|
||||
|
||||
for (const dbName of cryptoDbNames) {
|
||||
try {
|
||||
await deleteIndexedDB(dbName);
|
||||
@@ -337,7 +347,7 @@ export const fixKeyConflict = async (mx: MatrixClient): Promise<void> => {
|
||||
console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Reload the page
|
||||
console.log('[initMatrix] 🔄 Reloading...');
|
||||
window.location.reload();
|
||||
@@ -345,30 +355,32 @@ export const fixKeyConflict = async (mx: MatrixClient): Promise<void> => {
|
||||
|
||||
export const logoutClient = async (mx: MatrixClient) => {
|
||||
mx.stopClient();
|
||||
|
||||
|
||||
// Clear the global MatrixClient reference
|
||||
const { setGlobalMatrixClient } = await import('../app/utils/auth');
|
||||
setGlobalMatrixClient(null);
|
||||
|
||||
|
||||
try {
|
||||
await mx.logout();
|
||||
} catch {
|
||||
// ignore if failed to logout
|
||||
}
|
||||
await mx.clearStores();
|
||||
|
||||
// Import sessions management
|
||||
const { sessionsAtom, currentSessionAtom, getSessionByUserId, getCurrentSession } = await import('../app/state/sessions');
|
||||
const { getLocalStorageItem, setLocalStorageItem } = await import('../app/state/utils/atomWithLocalStorage');
|
||||
|
||||
|
||||
// Import sessions management
|
||||
const { sessionsAtom, currentSessionAtom, getSessionByUserId, getCurrentSession } =
|
||||
await import('../app/state/sessions');
|
||||
const { getLocalStorageItem, setLocalStorageItem } =
|
||||
await import('../app/state/utils/atomWithLocalStorage');
|
||||
|
||||
const userId = mx.getSafeUserId();
|
||||
const allSessions = getLocalStorageItem('matrixSessions', []);
|
||||
const currentUserId = getLocalStorageItem('currentSessionUserId', undefined);
|
||||
|
||||
|
||||
// Remove the current session
|
||||
const remainingSessions = allSessions.filter((s: any) => s.userId !== userId);
|
||||
setLocalStorageItem('matrixSessions', remainingSessions);
|
||||
|
||||
|
||||
// If we're logging out the current session and there are other sessions, switch to the first one
|
||||
if (remainingSessions.length > 0 && currentUserId === userId) {
|
||||
setLocalStorageItem('currentSessionUserId', remainingSessions[0].userId);
|
||||
@@ -385,7 +397,7 @@ export const logoutClient = async (mx: MatrixClient) => {
|
||||
|
||||
export const logoutAllSessions = async () => {
|
||||
window.localStorage.clear();
|
||||
|
||||
|
||||
// Clear all IndexedDB databases
|
||||
const dbs = await window.indexedDB.databases();
|
||||
for (const idbInfo of dbs) {
|
||||
@@ -393,7 +405,7 @@ export const logoutAllSessions = async () => {
|
||||
window.indexedDB.deleteDatabase(idbInfo.name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user