Files
cinny/src/client/initMatrix.ts
T
litruv 33ae13e514
Checks / checks (push) Successful in 2m0s
Trigger cinny-mobile / dispatch (push) Successful in 1s
Drop the key conflict handler and the crypto store prefix. [skip build]
2026-11-03 02:10:33 +11:00

250 lines
7.7 KiB
TypeScript

import { createClient, MatrixClient, IndexedDBStore, IndexedDBCryptoStore } from 'matrix-js-sdk';
import { cryptoCallbacks } from './secretStorageKeys';
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';
const MAX_BODY = 8192;
const jsonField = (text: string | undefined, key: string) => {
if (!text) return undefined;
try {
const parsed = JSON.parse(text);
return typeof parsed?.[key] === 'string' ? parsed[key] : undefined;
} catch {
return undefined;
}
};
// Bodies are only read from a clone, so the SDK still gets the response it asked for
const readBody = async (res: Response) => {
const type = res.headers.get('content-type') ?? '';
if (!type.includes('json') && !type.includes('text')) return undefined;
try {
return (await res.clone().text()).slice(0, MAX_BODY);
} catch {
return undefined;
}
};
const debugFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
if (!getSettings().debugPackets) return globalThis.fetch(input, init);
// The SDK passes `URL | string`, and a URL instance has href, not url
const url = input instanceof URL ? input : new URL(typeof input === 'string' ? input : input.url);
const method = init?.method ?? (input instanceof Request ? input.method : 'GET');
const req = typeof init?.body === 'string' ? init.body.slice(0, MAX_BODY) : undefined;
const txnId = jsonField(req, 'transaction_id');
const start = Date.now();
recordPacket({
ts: start,
phase: 'start',
method,
url: url.toString(),
path: url.pathname,
txnId,
req,
});
let res: Response;
try {
res = await globalThis.fetch(input, init);
} catch (error) {
recordPacket({
ts: Date.now(),
phase: 'end',
method,
url: url.toString(),
path: url.pathname,
ms: Date.now() - start,
txnId,
req,
error: String(error),
});
throw error;
}
const body = await readBody(res);
recordPacket({
ts: Date.now(),
phase: 'end',
method,
url: url.toString(),
path: url.pathname,
status: res.status,
ms: Date.now() - start,
txnId,
eventId: jsonField(body, 'event_id'),
req,
res: body,
});
return res;
};
export const initClient = async (session: Session): Promise<MatrixClient> => {
const storeName = getSessionStoreName(session);
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: globalThis.indexedDB,
localStorage: globalThis.localStorage,
dbName: storeName.sync,
});
const legacyCryptoStore = new IndexedDBCryptoStore(globalThis.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'],
fetchFn: debugFetch,
});
await indexedDBStore.startup();
await mx.initRustCrypto();
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;
};
// Register this as the global MatrixClient so auth utils can access the latest token
const { setGlobalMatrixClient } = await import('../app/utils/auth');
setGlobalMatrixClient(mx);
console.log('[initMatrix] Registered global MatrixClient for auth utils');
return mx;
} catch (error) {
// Handle crypto store account mismatch error
if (error instanceof Error && 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)`,
{ cause: error },
);
}
// Re-throw other errors
throw error;
}
};
export const startClient = async (mx: MatrixClient) => {
await mx.startClient({
lazyLoadMembers: true,
});
};
export const clearCacheAndReload = async (mx: MatrixClient) => {
mx.stopClient();
clearNavToActivePathStore(mx.getSafeUserId());
await mx.store.deleteAllData();
window.location.reload();
};
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();
const { getLocalStorageItem, setLocalStorageItem } =
await import('../app/state/utils/atomWithLocalStorage');
const userId = mx.getSafeUserId();
const allSessions = getLocalStorageItem<Sessions>('matrixSessions', []);
const currentUserId = getLocalStorageItem('currentSessionUserId', undefined);
// Remove the current session
const remainingSessions = allSessions.filter((s: Session) => 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();
dbs.forEach((idbInfo) => {
if (idbInfo.name) {
window.indexedDB.deleteDatabase(idbInfo.name);
}
});
window.location.reload();
};
export const clearLoginData = async () => {
const dbs = await window.indexedDB.databases();
dbs.forEach((idbInfo) => {
const { name } = idbInfo;
if (name) {
window.indexedDB.deleteDatabase(name);
}
});
window.localStorage.clear();
window.location.reload();
};