Compare commits

...
4 Commits
Author SHA1 Message Date
jaredandClaude Opus 4.8 8a15405189 perf(presence): shared presence store instead of per-avatar listeners (PERF-1)
CI / Trigger Desktop Build (push) Successful in 7s
CI / Build & Quality Checks (push) Successful in 10m50s
useUserPresence registered 3 client listeners (Presence / CurrentlyActive /
LastPresenceTs) PER hook instance. On a large room that meant 100-250 global
listeners, every presence event fanning out across all of them, with add/remove
churn on every fast scroll.

Replace with a module-level PresenceStore singleton that registers exactly 3
listeners total (lazily, on first subscriber) and fans out to per-user
subscribers itself. The hook keeps the same public API (useState + a subscribe
effect); consumers are unchanged. Cache + subscriber sets stay bounded to
currently-mounted users; the mx-swap branch re-homes listeners on re-login.

Reviewed by two passes (SDK mutate-before-emit ordering and handler signatures
independently verified). Includes their recommended hardening: the unsubscribe
is made idempotent via a set-identity check so a double-invoke / re-subscribe
can't evict a newer subscriber.

Note: a User object that appears silently with no presence event no longer
re-seeds (deps are [mx, userId] not [mx, user]); the common presence-EDU case
is handled (and better than before). Reviewers rated this narrow case Low.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-18 17:09:21 -04:00
jaredandClaude Opus 4.8 fd3b8b421e fix(spaces): unlink one space-child edge instead of over-deleting (COR-1)
When a single m.space.child was removed (unlinking child C from space P), the
roomToParents reducer fired the whole-room DELETE action, which wiped C's
entire parent set, stripped C as a parent from every other room, and orphaned
C's own descendants until a full resync. So removing C from space A also
dropped C's other parent B, and C's children lost C.

Add a targeted UNLINK {parent, child} action that removes only that one
parent->child edge and prunes the child entry only when its parent set
empties (matching the map's build-time invariant that zero-parent rooms have
no entry). Point the invalid-child branch of handleStateChange at it; DELETE
is unchanged for genuine room leave/delete. Unit-tested (keeps other parents,
prunes on last parent, does NOT orphan descendants, unknown pair no-op).

Verified correct + consumer-safe by two review passes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-18 17:04:14 -04:00
jaredandClaude Opus 4.8 1f80d1d129 fix(correctness): call-join reset on embed swap + per-path notify dedupe
COR-2 (useCallEmbed): useCallJoined only reset `joined` when the embed became
undefined. Answering a 2nd call swaps the embed A->B directly (embed stays
truthy), so `joined` stayed true and call B rendered as already-joined,
skipping the loading/watchdog UI. Re-seed from `embed?.joined ?? false` on
every embed identity change.

COR-4 (ClientNonUIFeatures): the notify-dedupe used one Map<roomId,eventId>
slot shared by the main-timeline and per-thread paths, so a thread reply
overwrote the room's slot and a re-fired main message (decrypt/edit re-emit,
common in E2EE) then mismatched and double-notified. Key the slot by
`${roomId}|${threadId ?? 'main'}` so each path dedupes independently.

Both verified correct by two review passes (no missed-notification or
missed-join regressions).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-18 17:00:52 -04:00
jaredandClaude Opus 4.8 726cefb5ab fix(privacy): wipe plaintext/PII localStorage caches on logout (SEC-1/2)
Several localStorage caches held decrypted message content or user PII and
survived a normal logout, leaving residue on a shared device (the search
index was already wiped; these were not):

- cinny_scheduled_messages_v1 - decrypted IContent.body of pending sends
- cinny_recent_searches_v1     - search query text
- cinny_recent_forward_targets_v1 - recent forward contact/room graph
- cinny_recent_gifs_v1 / cinny_recent_stickers_v1 - media the user sent
- navToActivePath<userId>       - per-space last-visited room paths
- (plus the translation cache added earlier)

Add a clear function per module and a single auditable clearPlaintextCaches()
aggregator, called from both logout paths (logoutClient + the server-forced
SessionLoggedOut handler) alongside the existing session/search-index wipes.
Unit-tested.

Deliberately NOT cleared (documented in the aggregator): unsent composer
drafts and the presence status message (preserved by product decision N98);
SDK sync/crypto store + io.lotus.* account data (reminders/bookmarks/notes),
already wiped by mx.clearStores(); low-sensitivity UI/metadata residue.

The forward-targets/gifs/stickers/nav-path additions and the accurate
"not covered" documentation address findings from two review passes.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
2026-07-18 16:56:08 -04:00
14 changed files with 368 additions and 45 deletions

No files matched your search

+5 -3
View File
@@ -149,9 +149,11 @@ export const useCallJoined = (embed?: CallEmbed): boolean => {
);
useEffect(() => {
if (!embed) {
setJoined(false);
}
// Re-seed from the (new) embed whenever it changes identity, not only when
// it becomes undefined. Answering a 2nd call swaps embed A→B directly (embed
// stays truthy), so a plain `if (!embed)` reset left `joined` stuck true and
// B rendered as already-joined, skipping the loading/watchdog UI.
setJoined(embed?.joined ?? false);
}, [embed]);
return joined;
+90 -26
View File
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from 'react';
import { User, UserEvent, UserEventHandlerMap } from 'matrix-js-sdk';
import { MatrixClient, User, UserEvent, UserEventHandlerMap } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient';
export enum Presence {
@@ -22,35 +22,99 @@ const getUserPresence = (user: User): UserPresence => ({
lastActiveTs: user.getLastActiveTs(),
});
export const useUserPresence = (userId: string): UserPresence | undefined => {
const mx = useMatrixClient();
const user = mx.getUser(userId);
type PresenceListener = () => void;
const [presence, setPresence] = useState(() => (user ? getUserPresence(user) : undefined));
/**
* Shared presence store. Previously every avatar's `useUserPresence` registered
* its own 3 client listeners (Presence / CurrentlyActive / LastPresenceTs) — on
* a big room that meant hundreds of global listeners, each presence event
* fanning out across all of them, with churn on every fast scroll (PERF-1).
*
* This registers exactly 3 listeners total (once, on the first subscriber) and
* fans out to per-user subscribers itself. Subscribing on the client rather
* than per-`User` object also avoids the SDK's 10-listener-per-User cap.
*/
class PresenceStore {
private mx: MatrixClient | undefined;
useEffect(() => {
// Re-seed when the User object appears/changes after first render — the
// useState initializer only ran if `user` already existed at mount, so a
// late-arriving user would otherwise show no presence until the next event.
if (user) setPresence(getUserPresence(user));
// Subscribe on mx (MatrixClient) rather than on individual User objects.
// User objects have a default 10-listener limit; the same user can appear
// in many components simultaneously (avatars, member list, etc.) and
// per-user subscription causes MaxListenersExceededWarning at 11+.
const updatePresence: UserEventHandlerMap[UserEvent.Presence] = (event, u) => {
if (u.userId === user?.userId) {
setPresence(getUserPresence(u));
private started = false;
// userId -> set of component callbacks to notify on change.
private subscribers = new Map<string, Set<PresenceListener>>();
// userId -> last computed presence (stable reference until it changes), only
// retained while at least one subscriber for that user is mounted.
private cache = new Map<string, UserPresence | undefined>();
private handleEvent: UserEventHandlerMap[UserEvent.Presence] = (_event, user) => {
const subs = this.subscribers.get(user.userId);
if (!subs || subs.size === 0) return; // ignore users nothing is watching
this.cache.set(user.userId, getUserPresence(user));
subs.forEach((cb) => cb());
};
private start(mx: MatrixClient): void {
if (this.started && this.mx === mx) return;
// A different client (re-login without reload) — drop the old listeners.
if (this.started && this.mx) {
this.mx.removeListener(UserEvent.Presence, this.handleEvent);
this.mx.removeListener(UserEvent.CurrentlyActive, this.handleEvent);
this.mx.removeListener(UserEvent.LastPresenceTs, this.handleEvent);
this.cache.clear();
}
this.mx = mx;
mx.on(UserEvent.Presence, this.handleEvent);
mx.on(UserEvent.CurrentlyActive, this.handleEvent);
mx.on(UserEvent.LastPresenceTs, this.handleEvent);
this.started = true;
}
subscribe(mx: MatrixClient, userId: string, cb: PresenceListener): () => void {
this.start(mx);
let subs = this.subscribers.get(userId);
if (!subs) {
subs = new Set();
this.subscribers.set(userId, subs);
}
subs.add(cb);
return () => {
subs.delete(cb);
// Only tear down the registry entry if this is still the live set for the
// user — keeps unsubscribe idempotent so a double-invoke (or a later
// re-subscribe that replaced the set) can't evict a newer subscriber.
if (subs.size === 0 && this.subscribers.get(userId) === subs) {
this.subscribers.delete(userId);
this.cache.delete(userId);
}
};
mx.on(UserEvent.Presence, updatePresence);
mx.on(UserEvent.CurrentlyActive, updatePresence);
mx.on(UserEvent.LastPresenceTs, updatePresence);
return () => {
mx.removeListener(UserEvent.Presence, updatePresence);
mx.removeListener(UserEvent.CurrentlyActive, updatePresence);
mx.removeListener(UserEvent.LastPresenceTs, updatePresence);
};
}, [mx, user]);
}
get(mx: MatrixClient, userId: string): UserPresence | undefined {
if (this.cache.has(userId)) return this.cache.get(userId);
const user = mx.getUser(userId);
const presence = user ? getUserPresence(user) : undefined;
// Only retain in the cache while something is actually subscribed, so a
// render that never commits (and thus never subscribes) can't leave a
// dangling entry. handleEvent keeps it fresh thereafter.
if (this.subscribers.get(userId)?.size) this.cache.set(userId, presence);
return presence;
}
}
const presenceStore = new PresenceStore();
export const useUserPresence = (userId: string): UserPresence | undefined => {
const mx = useMatrixClient();
const [presence, setPresence] = useState(() => presenceStore.get(mx, userId));
useEffect(() => {
// Re-seed synchronously (userId/mx may have changed, or a late-arriving User
// object now exists), then track changes via the shared store.
setPresence(presenceStore.get(mx, userId));
return presenceStore.subscribe(mx, userId, () => {
setPresence(presenceStore.get(mx, userId));
});
}, [mx, userId]);
return presence;
};
+14 -8
View File
@@ -373,8 +373,10 @@ function StatusExpiryMonitor() {
function MessageNotifications() {
const audioRef = useRef<HTMLAudioElement>(null);
// Notify dedupe, keyed `${roomId}|${threadId ?? 'main'}` -> last notified
// eventId, so the main timeline and each thread dedupe independently.
const lastNotifiedEventRef = useRef<Map<string, string>>(new Map());
// Per-thread dedupe: threadId -> last notified eventId.
// Per-thread dedupe (thread-detection gate): threadId -> last notified eventId.
const lastNotifiedThreadRef = useRef<Map<string, string>>(new Map());
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -513,12 +515,16 @@ function MessageNotifications() {
const eventId = mEvent.getId();
if (!sender || !eventId) return;
// Dedupe on the event id (per room): the same event can re-fire (decryption,
// edit, thread repopulation). This replaces the old unread-COUNT dedupe,
// which suppressed a genuinely-new message whenever its post-read count
// matched the previously-notified count — i.e. "read a DM, next message
// never notifies/sounds" (the common one-at-a-time cadence).
if (lastNotifiedEventRef.current.get(room.roomId) === eventId) return;
// Dedupe on the event id (per room AND per path): the same event can
// re-fire (decryption, edit, thread repopulation). The main timeline and
// each thread get their own slot — a shared per-room slot let a thread
// reply overwrite the main slot, so a re-fired main message then mismatched
// and double-notified. This replaces the old unread-COUNT dedupe, which
// suppressed a genuinely-new message whenever its post-read count matched
// the previously-notified count (the "read a DM, next message never
// notifies/sounds" one-at-a-time cadence).
const dedupeKey = `${room.roomId}|${threadId ?? 'main'}`;
if (lastNotifiedEventRef.current.get(dedupeKey) === eventId) return;
// Main-timeline path respects push rules: don't notify when the room has no
// notification count (e.g. a non-mention in a Mentions-only room). The
@@ -527,7 +533,7 @@ function MessageNotifications() {
// override in a Mentions-only room is silently dropped.
if (!threadId && getUnreadInfo(room).total === 0) return;
lastNotifiedEventRef.current.set(room.roomId, eventId);
lastNotifiedEventRef.current.set(dedupeKey, eventId);
const quietActive =
focusAssistActive ||
+5 -4
View File
@@ -32,7 +32,7 @@ import {
startClient,
} from '../../../client/initMatrix';
import { deleteSearchCacheDatabase } from '../../utils/searchCache';
import { clearTranslationCache } from '../../state/translation';
import { clearPlaintextCaches } from '../../state/plaintextCaches';
import { SplashScreen } from '../../components/splash-screen';
import { ServerConfigsLoader } from '../../components/ServerConfigsLoader';
import { CapabilitiesProvider } from '../../hooks/useCapabilities';
@@ -163,9 +163,10 @@ const useLogoutListener = (mx?: MatrixClient) => {
// change) — the manual logout path already does, but this path didn't, so
// the plaintext survived on disk (and persist() makes it non-evictable).
await deleteSearchCacheDatabase();
// The message-translation cache also holds decrypted plaintext — wipe it
// on server-forced logout too.
clearTranslationCache();
// Other localStorage caches also hold decrypted plaintext / PII
// (translation, scheduled messages, recent searches/forwards/gifs/
// stickers, nav paths) — wipe them on server-forced logout too.
clearPlaintextCaches(mx?.getUserId() ?? undefined);
// Remove only the session credential keys — NOT settings, drafts, and
// other preferences (N98). The SDK's IndexedDB stores are cleared above;
// window.localStorage.clear() is reserved for the explicit reset path.
+70
View File
@@ -0,0 +1,70 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
// These modules touch localStorage at import/runtime. Provide a minimal mock
// that records removed keys, then import dynamically (a static import would
// hoist above the mock).
const removed: string[] = [];
const store = new Map<string, string>();
(globalThis as { localStorage?: unknown }).localStorage = {
getItem: (k: string) => store.get(k) ?? null,
setItem: (k: string, v: string) => {
store.set(k, v);
},
removeItem: (k: string) => {
removed.push(k);
store.delete(k);
},
};
const { clearPlaintextCaches } = await import('./plaintextCaches');
test('clearPlaintextCaches removes every plaintext/PII localStorage key', () => {
store.clear();
store.set('cinny_translation_cache_v1', '[]');
store.set('cinny_scheduled_messages_v1', '{}');
store.set('cinny_recent_searches_v1', '[]');
store.set('cinny_recent_forward_targets_v1', '[]');
store.set('cinny_recent_gifs_v1', '[]');
store.set('cinny_recent_stickers_v1', '[]');
removed.length = 0;
clearPlaintextCaches();
for (const key of [
'cinny_translation_cache_v1',
'cinny_scheduled_messages_v1',
'cinny_recent_searches_v1',
'cinny_recent_forward_targets_v1',
'cinny_recent_gifs_v1',
'cinny_recent_stickers_v1',
]) {
assert.ok(removed.includes(key), `${key} cleared`);
}
assert.equal(store.size, 0, 'all keys gone from store');
});
test('clearPlaintextCaches clears the per-user nav-path store only when given a userId', () => {
store.clear();
store.set('navToActivePath@me:server', '{}');
removed.length = 0;
clearPlaintextCaches(); // no userId -> nav path untouched
assert.ok(!removed.includes('navToActivePath@me:server'), 'nav path kept without userId');
clearPlaintextCaches('@me:server');
assert.ok(removed.includes('navToActivePath@me:server'), 'nav path cleared with userId');
});
test('clearPlaintextCaches does NOT touch drafts or session keys', () => {
store.clear();
store.set('draft-msg-!room:server', '{"body":"unsent"}');
store.set('cinny_session', '{"accessToken":"x"}');
removed.length = 0;
clearPlaintextCaches('@me:server');
assert.ok(!removed.includes('draft-msg-!room:server'), 'draft preserved (N98)');
assert.ok(!removed.includes('cinny_session'), 'session key not this module’s concern');
assert.ok(store.has('draft-msg-!room:server'));
});
+43
View File
@@ -0,0 +1,43 @@
import { clearTranslationCache } from './translation';
import { clearScheduledMessages } from './scheduledMessages';
import { clearRecentSearches } from './recentSearches';
import { clearRecentForwardTargets } from './recentForwardTargets';
import { clearRecentGifs } from './recentGifs';
import { clearRecentStickers } from './recentStickers';
import { clearNavToActivePathStore } from './navToActivePath';
/**
* Single auditable place that wipes the `localStorage` caches holding decrypted
* message content, sent media, or a user's messaging/nav activity. Called on
* logout so this residue can't survive on a shared device.
*
* Swept here:
* - `cinny_translation_cache_v1` — decrypted translated message text
* - `cinny_scheduled_messages_v1` — decrypted `IContent.body` of pending sends
* - `cinny_recent_searches_v1` — search query text (PII)
* - `cinny_recent_forward_targets_v1` — recent forward contact/room graph (PII)
* - `cinny_recent_gifs_v1` / `cinny_recent_stickers_v1` — media the user sent
* - `navToActivePath<userId>` — per-space last-visited room paths (needs userId)
*
* NOT swept here (by design):
* - session credential keys → `removeFallbackSession()`
* - the SDK sync/crypto store + all `io.lotus.*` account data (reminders,
* bookmarks, user notes, status presets — themselves plaintext) → wiped by
* `mx.clearStores()` on both logout paths
* - the opt-in encrypted-search index (IndexedDB) → `deleteSearchCacheDatabase()`
* - unsent composer drafts (`draft-msg-*`) and the presence status message
* (`lotus-status-msg-*`) are deliberately preserved across a normal logout
* (N98); clearing them is a separate product decision
* - low-sensitivity UI/metadata residue (`io.lotus.mute_timers`, collapsed
* nav/space categories, `cinny_oidc_dynamic_clients`) is treated as
* preferences, not swept here
*/
export const clearPlaintextCaches = (userId?: string): void => {
clearTranslationCache();
clearScheduledMessages();
clearRecentSearches();
clearRecentForwardTargets();
clearRecentGifs();
clearRecentStickers();
if (userId) clearNavToActivePathStore(userId);
};
+13
View File
@@ -39,3 +39,16 @@ export const addRecentForwardTarget = (prev: string[], roomId: string): string[]
const withoutDupe = prev.filter((id) => id !== roomId);
return [roomId, ...withoutDupe].slice(0, MAX_RECENT_FORWARD_TARGETS);
};
/**
* Wipe persisted recent forward targets. Called on logout — the list is the
* user's recent messaging contact/room graph (PII) and must not survive a
* session on a shared device.
*/
export const clearRecentForwardTargets = (): void => {
try {
localStorage.removeItem(STORAGE_KEY);
} catch {
/* localStorage unavailable — nothing to clear */
}
};
+13
View File
@@ -48,3 +48,16 @@ export const addRecentGif = (
const withoutDupe = prev.filter((g) => g.url !== gif.url);
return [gif, ...withoutDupe].slice(0, max);
};
/**
* Wipe persisted recent GIFs. Called on logout — these are media the user sent
* (can be personally sensitive) and must not surface under "Recent" to the next
* person on a shared device.
*/
export const clearRecentGifs = (): void => {
try {
localStorage.removeItem(STORAGE_KEY);
} catch {
/* localStorage unavailable — nothing to clear */
}
};
+12
View File
@@ -36,3 +36,15 @@ export const addRecentSearch = (prev: string[], term: string): string[] => {
const withoutDupe = prev.filter((t) => t !== trimmed);
return [trimmed, ...withoutDupe].slice(0, MAX_RECENT_SEARCHES);
};
/**
* Wipe persisted recent search terms. Called on logout — search queries are
* user PII and must not survive a session on a shared device.
*/
export const clearRecentSearches = (): void => {
try {
localStorage.removeItem(STORAGE_KEY);
} catch {
/* localStorage unavailable — nothing to clear */
}
};
+13
View File
@@ -48,3 +48,16 @@ export const addRecentSticker = (
const withoutDupe = prev.filter((s) => s.url !== sticker.url);
return [sticker, ...withoutDupe].slice(0, max);
};
/**
* Wipe persisted recent stickers. Called on logout — these are stickers the
* user sent (mxc + label text) and must not surface under "Recent" to the next
* person on a shared device.
*/
export const clearRecentStickers = (): void => {
try {
localStorage.removeItem(STORAGE_KEY);
} catch {
/* localStorage unavailable — nothing to clear */
}
};
+46
View File
@@ -116,3 +116,49 @@ test('DELETE of an unknown room only prunes nothing', () => {
assert.deepEqual(parentsOf(store, '!c:s'), ['!p:s']);
assert.equal(get(store).size, 1);
});
test('UNLINK removes ONE parent but keeps the child’s other parents', () => {
const store = createStore();
// !c is a child of both !a and !b.
store.set(roomToParentsAtom, { type: 'PUT', parent: '!a:s', children: ['!c:s'] });
store.set(roomToParentsAtom, { type: 'PUT', parent: '!b:s', children: ['!c:s'] });
store.set(roomToParentsAtom, { type: 'UNLINK', parent: '!a:s', child: '!c:s' });
// Only !a is dropped; !b remains. (DELETE would have wiped both.)
assert.deepEqual(parentsOf(store, '!c:s'), ['!b:s']);
});
test('UNLINK prunes the child only when it was the last parent', () => {
const store = createStore();
store.set(roomToParentsAtom, { type: 'PUT', parent: '!a:s', children: ['!c:s'] });
store.set(roomToParentsAtom, { type: 'UNLINK', parent: '!a:s', child: '!c:s' });
// !c had only !a; with that gone its entry is pruned.
assert.equal(get(store).has('!c:s'), false);
assert.equal(get(store).size, 0);
});
test('UNLINK does NOT orphan the child’s own descendants', () => {
const store = createStore();
// !mid is a child of !top and a parent of !leaf.
store.set(roomToParentsAtom, { type: 'PUT', parent: '!top:s', children: ['!mid:s'] });
store.set(roomToParentsAtom, { type: 'PUT', parent: '!mid:s', children: ['!leaf:s'] });
// Unlink !mid from !top only (one m.space.child removed).
store.set(roomToParentsAtom, { type: 'UNLINK', parent: '!top:s', child: '!mid:s' });
// !mid lost its only parent -> its own entry is pruned...
assert.equal(get(store).has('!mid:s'), false);
// ...but !leaf MUST still have !mid as a parent (DELETE wrongly stripped this).
assert.deepEqual(parentsOf(store, '!leaf:s'), ['!mid:s']);
});
test('UNLINK of an unknown parent/child is a no-op', () => {
const store = createStore();
store.set(roomToParentsAtom, { type: 'PUT', parent: '!a:s', children: ['!c:s'] });
store.set(roomToParentsAtom, { type: 'UNLINK', parent: '!nope:s', child: '!c:s' });
assert.deepEqual(parentsOf(store, '!c:s'), ['!a:s']);
store.set(roomToParentsAtom, { type: 'UNLINK', parent: '!a:s', child: '!missing:s' });
assert.deepEqual(parentsOf(store, '!c:s'), ['!a:s']);
assert.equal(get(store).size, 1);
});
+26 -1
View File
@@ -31,6 +31,11 @@ export type RoomToParentsAction =
| {
type: 'DELETE';
roomId: string;
}
| {
type: 'UNLINK';
parent: string;
child: string;
};
const baseRoomToParents = atom<RoomToParents>(new Map());
@@ -63,6 +68,23 @@ export const roomToParentsAtom = atom<RoomToParents, [RoomToParentsAction], unde
noParentRooms.forEach((room) => draftRoomToParents.delete(room));
}),
);
return;
}
if (action.type === 'UNLINK') {
// Remove ONE parent from ONE child (a single `m.space.child` was removed).
// Unlike DELETE (used when a room is left/deleted), this must NOT touch the
// child's other parents, nor strip the child as a parent elsewhere, nor
// orphan the child's own descendants. Only prune the child's entry if this
// was its last parent.
set(
baseRoomToParents,
produce(get(baseRoomToParents), (draftRoomToParents) => {
const parents = draftRoomToParents.get(action.child);
if (!parents) return;
parents.delete(action.parent);
if (parents.size === 0) draftRoomToParents.delete(action.child);
}),
);
}
},
);
@@ -100,7 +122,10 @@ export const useBindRoomToParentsAtom = (
if (isValidChild(mEvent)) {
setRoomToParents({ type: 'PUT', parent: roomId, children: [childId] });
} else {
setRoomToParents({ type: 'DELETE', roomId: childId });
// A single m.space.child was removed: unlink only THIS parent→child
// edge. DELETE here wiped the child's other parents and orphaned its
// descendants until a full resync (COR-1).
setRoomToParents({ type: 'UNLINK', parent: roomId, child: childId });
}
}
}
+13
View File
@@ -40,3 +40,16 @@ export const scheduledMessagesAtom = atom(
});
},
);
/**
* Wipe persisted scheduled messages. Called on logout — the stored content is
* decrypted message plaintext (the E2EE `body`), so it must not survive a
* session on a shared device.
*/
export const clearScheduledMessages = (): void => {
try {
localStorage.removeItem(STORAGE_KEY);
} catch {
/* localStorage unavailable — nothing to clear */
}
};
+5 -3
View File
@@ -7,7 +7,7 @@ import { LotusOidcTokenRefresher } from './oidcTokenRefresher';
import { revokeOidcTokens } from './oidcLogout';
import { pushSessionToSW } from '../sw-session';
import { deleteSearchCacheDatabase } from '../app/utils/searchCache';
import { clearTranslationCache } from '../app/state/translation';
import { clearPlaintextCaches } from '../app/state/plaintextCaches';
// Thrown when the local IndexedDB has a higher schema version than this SDK expects.
// This happens after a downgrade (e.g. matrix-js-sdk was briefly upgraded and then reverted).
@@ -124,8 +124,10 @@ export const logoutClient = async (mx: MatrixClient) => {
// The opt-in local search index stores decrypted plaintext — always wipe it
// on logout. (clearLoginData below nukes all IDB databases, covering it too.)
await deleteSearchCacheDatabase();
// The message-translation cache also holds decrypted plaintext — wipe it too.
clearTranslationCache();
// Other localStorage caches also hold decrypted plaintext / PII (translation,
// scheduled messages, recent searches/forwards/gifs/stickers, nav paths) —
// wipe them too.
clearPlaintextCaches(mx.getUserId() ?? undefined);
// Remove only the session credential keys, preserving user preferences and
// unsent drafts (N98). The factory-reset path is clearLoginData() below.
removeFallbackSession();