import { useEffect, useRef, useState, type FormEvent } from "react"; import { Link, useParams } from "react-router"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { api, errMsg } from "../api"; import { useMe } from "../auth"; import { AuthBox } from "../components/AuthBox"; import { avatarUrl, formatTime, linkify, userName } from "../format"; import { submitOnShiftEnter } from "../keys"; import { hasRememberedPassphrase, rememberDays, unlockKeyring, unlockRemembered, useKeyring, type Keyring, } from "../keyring"; import { decryptMessage, encryptMessage, formatFingerprint, ImportError, toBase64, type KeyInfo } from "../keystore"; import { useUserKey } from "../useKey"; import { useChats } from "../chats"; import type { Profile } from "../types"; // Direktnachrichten (notes/chats.md): Ende-zu-Ende verschlüsselt mit den // Schlüsseln aus /settings/keys. Der Server sieht nur, wer wann wem wie // viel schreibt. // Muss zu chat.Retention passen (internal/chat/purge.go). const retentionDays = 15; // Länge einer Nachricht im Textfeld; der Server begrenzt die verschlüsselte // Form (pgpkey.MaxMessage). const maxMessage = 4000; const pollChat = 5_000; type Message = { id: number; mine: boolean; body: string; created_at: number }; type Shown = { id: number; mine: boolean; created_at: number; text: string; verified: boolean; unreadable: boolean }; const chatPath = (handle: string) => `/chats/${encodeURIComponent(handle)}`; // ChatsPage: die Gespräche, das mit der jüngsten Nachricht zuerst. export function ChatsPage() { const me = useMe(); return ( <>

Chats

{me.data && }
{me.isSuccess && !me.data && } ); } function ChatList({ handle }: { handle: string }) { const own = useUserKey(handle); const chats = useChats(); return ( <>

Experimentell. Nachrichten sind Ende-zu-Ende verschlüsselt und verschwinden nach {retentionDays} Tagen.

{own.data && !own.data.key && } {chats.isError &&

{errMsg(chats.error, "Chats konnten nicht geladen werden.")}

} {chats.data?.length === 0 &&

Noch keine Gespräche. Sprich jemanden auf dem Profil an.

} ); } function NeedKey() { return (

Um zu chatten, richte unter Einstellungen → Schlüssel deinen Schlüssel ein.

); } // ChatPage: ein Gespräch. Lesen braucht den entsperrten eigenen Schlüssel, // Schreiben zusätzlich den des Gegenübers. export function ChatPage() { const { handle = "" } = useParams(); const me = useMe(); return ( <>

← Chats

Chat mit @{handle}

{me.data && }
{me.isSuccess && !me.data && } ); } function Conversation({ me, other }: { me: string; other: string }) { const ring = useKeyring(me); const own = useUserKey(me); const theirs = useUserKey(other); if (!own.data || !theirs.data) return null; if (!own.data.key) return ; if (!ring) return ; return ; } // Unlock entsperrt den Schlüsselbund: mit der gemerkten Passphrase von // selbst, sonst fragt es nach ihr. function Unlock({ me }: { me: string }) { const [auto, setAuto] = useState(() => hasRememberedPassphrase(me)); useEffect(() => { if (auto) unlockRemembered(me).finally(() => setAuto(false)); }, [auto, me]); const unlock = useMutation({ mutationFn: (passphrase: string) => unlockKeyring(me, passphrase) }); if (auto) return

Entsperre …

; const onSubmit = (e: FormEvent) => { e.preventDefault(); unlock.mutate(String(new FormData(e.currentTarget).get("passphrase") ?? "")); }; return (

Gib deine Passphrase ein, um die Nachrichten zu lesen. Dieser Browser merkt sie sich {rememberDays} Tage.

{unlock.isError ? unlock.error instanceof ImportError ? unlock.error.message : errMsg(unlock.error, "Entsperren fehlgeschlagen.") : ""}

); } // useMessages lädt die Nachrichten, entschlüsselt sie und fragt alle paar // Sekunden nach neuen (nur die nach der letzten bekannten). reload holt // sofort nach, etwa nach dem Senden. function useMessages(other: string, ring: Keyring, verifyWith: string[]) { const qc = useQueryClient(); const [shown, setShown] = useState([]); const [error, setError] = useState(""); const last = useRef(0); const busy = useRef(false); const verify = verifyWith.join(","); const load = useRef<() => Promise>(async () => {}); load.current = async () => { if (busy.current) return; busy.current = true; try { const { messages } = await api.get<{ messages: Message[] }>(`${chatPath(other)}?after=${last.current}`); if (messages.length === 0) return; last.current = messages[messages.length - 1].id; const decrypted = await Promise.all(messages.map((m) => show(m, ring, verifyWith))); setShown((s) => [...s, ...decrypted]); setError(""); // Abgerufen heißt gelesen: die Zähler der Übersicht stimmen nicht mehr. if (messages.some((m) => !m.mine)) qc.invalidateQueries({ queryKey: ["chats"] }); } catch (err) { setError(errMsg(err, "Nachrichten konnten nicht geladen werden.")); } finally { busy.current = false; } }; useEffect(() => { last.current = 0; setShown([]); load.current(); const t = setInterval(() => load.current(), pollChat); return () => clearInterval(t); }, [other, ring, verify]); return { shown, error, reload: () => load.current() }; } async function show(m: Message, ring: Keyring, verifyWith: string[]): Promise { const base = { id: m.id, mine: m.mine, created_at: m.created_at }; try { const d = await decryptMessage(m.body, ring.all, verifyWith); return { ...base, text: d.text, verified: d.verified, unreadable: false }; } catch { return { ...base, text: "", verified: false, unreadable: true }; } } function Messages(props: { me: string; other: string; ring: Keyring; ownKey: KeyInfo; theirKey: KeyInfo | null }) { const { me, other, ring, ownKey, theirKey } = props; // Signaturen gelten, wenn sie vom aktuellen Schlüssel des Absenders stammen. const verifyWith = theirKey ? [theirKey.key, ownKey.key] : [ownKey.key]; const { shown, error, reload } = useMessages(other, ring, verifyWith); const profile = useQuery({ queryKey: ["profile", other], queryFn: () => api.get(`/u/${encodeURIComponent(other)}/info`), }); const myAvatar = useMe().data?.avatar ?? ""; const end = useRef(null); // In Klammern: Neuere Browser geben bei scrollIntoView ein Promise zurück, // und was ein Effekt zurückgibt, ruft React später als Aufräumfunktion auf. useEffect(() => { end.current?.scrollIntoView({ block: "nearest" }); }, [shown.length]); return ( <> {theirKey && (

Schlüssel von {other}: {formatFingerprint(theirKey.fingerprint)}

)}
{shown.length === 0 &&

Noch keine Nachrichten.

} {shown.map((m) => (
{m.mine ? me : other} · {formatTime(m.created_at)} {!m.unreadable && !m.verified && " · Signatur nicht prüfbar"}
{m.unreadable ? [nicht lesbar] : linkify(m.text)}
))}

{error}

{theirKey ? ( ) : (

{other} hat keinen Schlüssel hinterlegt; schreiben geht gerade nicht.

)}
); } function SendForm(props: { other: string; ring: Keyring; ownKey: KeyInfo; theirKey: KeyInfo; onSent: () => void }) { const { other, ring, ownKey, theirKey, onSent } = props; const send = useMutation({ mutationFn: async (text: string) => { const body = await encryptMessage(text, theirKey.key, ownKey.key, ring.current); const fd = new FormData(); fd.set("body", toBase64(body)); await api.post(chatPath(other), fd); }, }); const onSubmit = (e: FormEvent) => { e.preventDefault(); const form = e.currentTarget; const text = String(new FormData(form).get("text") ?? "").trim(); if (!text) return; send.mutate(text, { onSuccess: () => { form.reset(); onSent(); }, }); }; return (