Files
siftlode/frontend/src/lib/messaging.ts
T
peter 34297b696f refactor(fe): migrate plex/messaging/admin/downloads/notifications to qk (R7 S2b)
Extend lib/queryKeys.ts to the remaining ~34 key roots and migrate every
remaining literal (queryKey: [...] AND the positional useLiveQuery keys) in
36 files. All ~200 React Query keys across the app now route through the
factory; zero raw key literals remain outside queryKeys.ts.

The heterogeneous composite plex keys (plex-library/facets/collections/
playlists carry a filters object, a ratingKeys array, or a union/group
discriminator) take a variadic pass-through — the factory centralizes the
ROOT string; single-id keys stay precisely typed. Nullable keys (thread,
playlist, ytSearch) accept null so a null segment is preserved.

Pure substitution — byte-identical key arrays, so TanStack prefix matching
is unchanged. Gate green: typecheck (app+node+e2e), eslint (0 err),
prettier, 68 vitest. Runtime-verified on a fresh dev server: Feed + Plex
modules load, feed/facets/tags/my-status/plex-library/plex-facets/
plex-collections/plex-playlists all 200, full UI renders.
2026-07-27 22:10:03 +02:00

67 lines
3.7 KiB
TypeScript

// Shared messaging helpers used by both the Messages page and the floating chat dock.
import { useSyncExternalStore } from "react";
import { qk } from "./queryKeys";
import { useQuery } from "@tanstack/react-query";
import { api } from "./api";
import { forgetConv, isUnlocked, subscribeUnlock } from "./e2ee";
export const SYSTEM_ID = 0; // synthetic "Siftlode" system conversation partner id
// Safety-net poll interval for message queries; live updates arrive over the WebSocket.
export const POLL_MS = 20000;
// Cache of partner public keys (the server is the directory). Keys are stable in normal use, but a
// partner can rotate theirs via a passphrase reset — refreshPartnerPub() evicts a stale entry (and
// its derived conversation key) so the next fetch picks up the new key.
const pubCache = new Map<number, string>();
export async function partnerPub(partnerId: number): Promise<string> {
const cached = pubCache.get(partnerId);
if (cached) return cached;
const r = await api.messagePublicKey(partnerId);
pubCache.set(partnerId, r.public_key);
return r.public_key;
}
// Drop a partner's cached public key + derived conversation key and refetch. Called after a decrypt
// fails, which can mean the partner reset their passphrase and published a NEW keypair; refetching
// lets this device both read their new messages and encrypt future ones under the current key.
//
// KNOWN LIMITATION: this refresh is wired only to the DECRYPT path. If you send a partner a message
// AFTER they rotated their key but BEFORE any of their messages arrived to trigger a refresh, that
// one send is encrypted under the stale cached key and is undecryptable for them (subsequent sends
// self-heal once an incoming message refreshes the cache). Accepted for now — same cross-user
// staleness envelope as the multi-device note in useKeyState; a fuller fix needs a key TTL / a
// send-time freshness check, which is out of the current no-forward-secrecy scope.
export async function refreshPartnerPub(partnerId: number): Promise<string> {
pubCache.delete(partnerId);
forgetConv(partnerId);
return partnerPub(partnerId);
}
// Live "is secure messaging unlocked on this device" — shared so the page and the dock agree.
function useUnlocked(): boolean {
return useSyncExternalStore(subscribeUnlock, isUnlocked, isUnlocked);
}
// The SERVER is the source of truth for whether messaging is set up. Combining it with the
// local unlock state gives the real gate: "setup" if the server has no key (even if a stale
// private key lingers in this browser — setup overwrites it), "unlock" if the server has a key
// but this device hasn't unlocked it, else "ready".
//
// KNOWN LIMITATION (multi-device, passphrase reset): this doesn't compare the locally-unlocked
// key's public half against the server's current public_key, so if the user resets their passphrase
// on ANOTHER device (new keypair), this already-unlocked device stays "ready" with the now-dead old
// key and silently fails to decrypt new messages until it's manually re-unlocked. Accepted for now:
// it fits the E2EE scope (static pairwise key, no forward secrecy) and self-heals once the device is
// re-unlocked with the new passphrase. Incoming-message decrypt failures on the CURRENT device DO
// self-heal via refreshPartnerPub() (a partner's rotation), which covers the common single-device case.
export type KeyState = "loading" | "setup" | "unlock" | "ready";
export function useKeyState(): KeyState {
const unlocked = useUnlocked();
const q = useQuery({ queryKey: qk.messageKey(), queryFn: api.messageMyKey, staleTime: 60_000 });
if (q.isLoading && !q.data) return "loading";
if (!(q.data?.configured ?? false)) return "setup";
if (!unlocked) return "unlock";
return "ready";
}