multiuser
This commit is contained in:
+202
-40
@@ -2,52 +2,177 @@ import { createClient, MatrixClient, IndexedDBStore, IndexedDBCryptoStore } from
|
||||
|
||||
import { cryptoCallbacks } from './secretStorageKeys';
|
||||
import { clearNavToActivePathStore } from '../app/state/navToActivePath';
|
||||
import { Session, getSessionStoreName } from '../app/state/sessions';
|
||||
|
||||
type Session = {
|
||||
baseUrl: string;
|
||||
accessToken: string;
|
||||
userId: string;
|
||||
deviceId: string;
|
||||
const deleteIndexedDB = (dbName: string): Promise<void> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const request = global.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<string[]> => {
|
||||
try {
|
||||
if ('databases' in global.indexedDB) {
|
||||
// Add timeout to prevent hanging
|
||||
const timeoutPromise = new Promise<string[]>((resolve) => {
|
||||
setTimeout(() => {
|
||||
console.warn('[initMatrix] indexedDB.databases() timed out after 2s');
|
||||
resolve([]);
|
||||
}, 2000);
|
||||
});
|
||||
|
||||
const databasesPromise = (global.indexedDB as any).databases().then((dbs: any[]) => {
|
||||
return dbs.map((db: any) => db.name).filter(Boolean);
|
||||
});
|
||||
|
||||
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 [];
|
||||
};
|
||||
|
||||
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'
|
||||
);
|
||||
|
||||
console.log('[initMatrix] Deleting Matrix databases:', matrixDbNames);
|
||||
|
||||
for (const dbName of matrixDbNames) {
|
||||
try {
|
||||
await deleteIndexedDB(dbName);
|
||||
} catch (error) {
|
||||
console.error(`[initMatrix] Failed to delete ${dbName}:`, error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const initClient = async (session: Session): Promise<MatrixClient> => {
|
||||
const indexedDBStore = new IndexedDBStore({
|
||||
indexedDB: global.indexedDB,
|
||||
localStorage: global.localStorage,
|
||||
dbName: 'web-sync-store',
|
||||
});
|
||||
|
||||
const legacyCryptoStore = new IndexedDBCryptoStore(global.indexedDB, 'crypto-store');
|
||||
|
||||
const mx = createClient({
|
||||
baseUrl: session.baseUrl,
|
||||
accessToken: session.accessToken,
|
||||
userId: session.userId,
|
||||
store: indexedDBStore,
|
||||
cryptoStore: legacyCryptoStore,
|
||||
deviceId: session.deviceId,
|
||||
timelineSupport: true,
|
||||
cryptoCallbacks: cryptoCallbacks as any,
|
||||
verificationMethods: ['m.sas.v1'],
|
||||
});
|
||||
|
||||
await indexedDBStore.startup();
|
||||
await mx.initRustCrypto();
|
||||
|
||||
mx.setMaxListeners(50);
|
||||
const storeName = getSessionStoreName(session);
|
||||
|
||||
// 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);
|
||||
mx.getUser = (userId: string) => {
|
||||
const user = originalGetUser(userId);
|
||||
if (user) {
|
||||
user.setMaxListeners(50);
|
||||
}
|
||||
return user;
|
||||
};
|
||||
console.log('[initMatrix] ========================================');
|
||||
console.log('[initMatrix] Initializing Matrix client for session:');
|
||||
console.log('[initMatrix] User ID:', session.userId);
|
||||
console.log('[initMatrix] Device ID:', session.deviceId);
|
||||
console.log('[initMatrix] Using fallback stores:', session.fallbackSdkStores || false);
|
||||
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,
|
||||
localStorage: global.localStorage,
|
||||
dbName: storeName.sync,
|
||||
});
|
||||
|
||||
return mx;
|
||||
const legacyCryptoStore = new IndexedDBCryptoStore(global.indexedDB, storeName.crypto);
|
||||
|
||||
const mx = createClient({
|
||||
baseUrl: session.baseUrl,
|
||||
accessToken: session.accessToken,
|
||||
userId: session.userId,
|
||||
store: indexedDBStore,
|
||||
cryptoStore: legacyCryptoStore,
|
||||
deviceId: session.deviceId,
|
||||
timelineSupport: true,
|
||||
cryptoCallbacks: cryptoCallbacks as any,
|
||||
verificationMethods: ['m.sas.v1'],
|
||||
});
|
||||
|
||||
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({
|
||||
storagePrefix: `${session.userId}@${session.deviceId}`,
|
||||
});
|
||||
|
||||
// List databases after init to verify isolation
|
||||
try {
|
||||
const dbsAfterInit = await getAllIndexedDBNames();
|
||||
console.log('[initMatrix] 📦 Databases after initialization:', dbsAfterInit);
|
||||
|
||||
// Check if a shared crypto database was created despite storagePrefix
|
||||
const hasSharedCrypto = dbsAfterInit.includes('matrix-js-sdk::matrix-sdk-crypto');
|
||||
if (hasSharedCrypto) {
|
||||
console.warn('[initMatrix] ⚠️ WARNING: Shared crypto database still exists after init!');
|
||||
console.warn('[initMatrix] The storagePrefix option may not be working correctly.');
|
||||
}
|
||||
|
||||
// List account-specific databases
|
||||
const accountDbs = dbsAfterInit.filter(db =>
|
||||
db.includes(session.userId) || db.includes(session.deviceId)
|
||||
);
|
||||
console.log('[initMatrix] 📁 Account-specific databases:', accountDbs);
|
||||
} catch (e) {
|
||||
console.log('[initMatrix] Could not list databases after init:', e);
|
||||
}
|
||||
|
||||
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);
|
||||
mx.getUser = (userId: string) => {
|
||||
const user = originalGetUser(userId);
|
||||
if (user) {
|
||||
user.setMaxListeners(50);
|
||||
}
|
||||
return user;
|
||||
};
|
||||
|
||||
return mx;
|
||||
} catch (error: any) {
|
||||
// Handle crypto store account mismatch error
|
||||
if (error && error.message && error.message.includes("account in the store doesn't match")) {
|
||||
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)`
|
||||
);
|
||||
}
|
||||
|
||||
// Re-throw other errors
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const startClient = async (mx: MatrixClient) => {
|
||||
@@ -71,7 +196,44 @@ export const logoutClient = async (mx: MatrixClient) => {
|
||||
// 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');
|
||||
|
||||
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);
|
||||
window.location.reload();
|
||||
} else if (remainingSessions.length === 0) {
|
||||
// No more sessions, clear everything
|
||||
window.localStorage.clear();
|
||||
window.location.reload();
|
||||
} else {
|
||||
// We logged out a non-current session, just reload
|
||||
window.location.reload();
|
||||
}
|
||||
};
|
||||
|
||||
export const logoutAllSessions = async () => {
|
||||
window.localStorage.clear();
|
||||
|
||||
// Clear all IndexedDB databases
|
||||
const dbs = await window.indexedDB.databases();
|
||||
for (const idbInfo of dbs) {
|
||||
if (idbInfo.name) {
|
||||
window.indexedDB.deleteDatabase(idbInfo.name);
|
||||
}
|
||||
}
|
||||
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user