Chats: Ende-zu-Ende-verschlüsselte Direktnachrichten
Erste Version der Chats auf Basis der Schlüsselverwaltung: Gespräche zu
zweit, nur Text. Ziel ist, dass der Betreiber den Inhalt nicht kennt;
der Server speichert und verteilt nur OpenPGP-Chiffrate.
- Profil: „Ansprechen“, wenn beide einen Schlüssel haben (für Nutzer
ohne Schlüssel unsichtbar).
- Entsperren einmal pro Tab mit der Passphrase; der Schlüsselbund bleibt
im Speicher (keyring.ts) und umfasst auch frühere eigene Schlüssel.
- Nachrichten an Empfänger und Absender verschlüsselt und signiert; das
offene Gespräch fragt alle 5 s nach, die Übersicht alle 30 s.
- Server: Tabelle message, /api/chats, /api/chats/{username};
pgpkey.CheckMessage weist Klartext ab; internal/chat löscht stündlich,
was älter als 15 Tage ist. Konto löschen nimmt die Nachrichten mit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TiXsPUqw7oeomZ8wZrQW5q
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
ed227f0d81
commit
f75407ea5b
@@ -0,0 +1,271 @@
|
||||
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 } from "../format";
|
||||
import { submitOnShiftEnter } from "../keys";
|
||||
import { unlockKeyring, useKeyring, type Keyring } from "../keyring";
|
||||
import { decryptMessage, encryptMessage, formatFingerprint, ImportError, toBase64, type KeyInfo } from "../keystore";
|
||||
import { useUserKey } from "../useKey";
|
||||
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;
|
||||
const pollList = 30_000;
|
||||
|
||||
type ChatSummary = { username: string; avatar: string; last_at: number; unread: number };
|
||||
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 = (username: string) => `/chats/${encodeURIComponent(username)}`;
|
||||
|
||||
// ChatsPage: die Gespräche, das mit der jüngsten Nachricht zuerst.
|
||||
export function ChatsPage() {
|
||||
const me = useMe();
|
||||
return (
|
||||
<>
|
||||
<section id="chats">
|
||||
<h2>Chats</h2>
|
||||
{me.data && <ChatList username={me.data.username} />}
|
||||
</section>
|
||||
{me.isSuccess && !me.data && <AuthBox />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatList({ username }: { username: string }) {
|
||||
const own = useUserKey(username);
|
||||
const chats = useQuery({
|
||||
queryKey: ["chats"],
|
||||
queryFn: async () => (await api.get<{ chats: ChatSummary[] }>("/chats")).chats,
|
||||
refetchInterval: pollList,
|
||||
});
|
||||
return (
|
||||
<>
|
||||
<p className="muted">Nachrichten sind Ende-zu-Ende verschlüsselt und verschwinden nach {retentionDays} Tagen.</p>
|
||||
{own.data && !own.data.key && <NeedKey />}
|
||||
{chats.isError && <p className="msg">{errMsg(chats.error, "Chats konnten nicht geladen werden.")}</p>}
|
||||
{chats.data?.length === 0 && <p className="muted">Noch keine Gespräche. Sprich jemanden auf dem Profil an.</p>}
|
||||
<ul id="chat-list">
|
||||
{chats.data?.map((c) => (
|
||||
<li key={c.username} className="byline">
|
||||
<img className="avatar avatar-sm" src={avatarUrl(c.avatar)} alt="" loading="lazy" />
|
||||
<span>
|
||||
<Link to={chatPath(c.username)}>{c.username}</Link> · {formatTime(c.last_at)}
|
||||
{c.unread > 0 && <strong> · {c.unread} neu</strong>}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NeedKey() {
|
||||
return (
|
||||
<p className="msg">
|
||||
Um zu chatten, richte unter <Link to="/settings/keys">Einstellungen → Schlüssel</Link> deinen Schlüssel ein.
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
// ChatPage: ein Gespräch. Lesen braucht den entsperrten eigenen Schlüssel,
|
||||
// Schreiben zusätzlich den des Gegenübers.
|
||||
export function ChatPage() {
|
||||
const { username = "" } = useParams();
|
||||
const me = useMe();
|
||||
return (
|
||||
<>
|
||||
<section id="chat">
|
||||
<p>
|
||||
<Link to="/chats">← Chats</Link>
|
||||
</p>
|
||||
<h2>
|
||||
Chat mit <Link to={`/u/${encodeURIComponent(username)}`}>{username}</Link>
|
||||
</h2>
|
||||
{me.data && <Conversation key={username} me={me.data.username} other={username} />}
|
||||
</section>
|
||||
{me.isSuccess && !me.data && <AuthBox />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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 <NeedKey />;
|
||||
if (!ring) return <Unlock me={me} />;
|
||||
return <Messages me={me} other={other} ring={ring} ownKey={own.data.key} theirKey={theirs.data.key} />;
|
||||
}
|
||||
|
||||
// Unlock entsperrt den Schlüsselbund mit der Passphrase, einmal pro Tab.
|
||||
function Unlock({ me }: { me: string }) {
|
||||
const unlock = useMutation({ mutationFn: (passphrase: string) => unlockKeyring(me, passphrase) });
|
||||
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
unlock.mutate(String(new FormData(e.currentTarget).get("passphrase") ?? ""));
|
||||
};
|
||||
return (
|
||||
<form id="chat-unlock" onSubmit={onSubmit}>
|
||||
<p className="muted">Gib deine Passphrase ein, um die Nachrichten zu lesen.</p>
|
||||
<input name="passphrase" type="text" placeholder="Passphrase" autoComplete="off" spellCheck={false} autoFocus />
|
||||
<button type="submit" disabled={unlock.isPending}>
|
||||
{unlock.isPending ? "Entsperre …" : "Entsperren"}
|
||||
</button>
|
||||
<p className="msg">
|
||||
{unlock.isError
|
||||
? unlock.error instanceof ImportError
|
||||
? unlock.error.message
|
||||
: errMsg(unlock.error, "Entsperren fehlgeschlagen.")
|
||||
: ""}
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// 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<Shown[]>([]);
|
||||
const [error, setError] = useState("");
|
||||
const last = useRef(0);
|
||||
const busy = useRef(false);
|
||||
const verify = verifyWith.join(",");
|
||||
|
||||
const load = useRef<() => Promise<void>>(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<Shown> {
|
||||
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<Profile>(`/u/${encodeURIComponent(other)}/info`),
|
||||
});
|
||||
const myAvatar = useMe().data?.avatar ?? "";
|
||||
const end = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => end.current?.scrollIntoView({ block: "nearest" }), [shown.length]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{theirKey && (
|
||||
<p className="muted">
|
||||
Schlüssel von {other}: <code>{formatFingerprint(theirKey.fingerprint)}</code>
|
||||
</p>
|
||||
)}
|
||||
<div id="chat-messages">
|
||||
{shown.length === 0 && <p className="muted">Noch keine Nachrichten.</p>}
|
||||
{shown.map((m) => (
|
||||
<div key={m.id} className="message">
|
||||
<div className="muted byline">
|
||||
<img
|
||||
className="avatar avatar-sm"
|
||||
src={avatarUrl(m.mine ? myAvatar : (profile.data?.avatar ?? ""))}
|
||||
alt=""
|
||||
/>
|
||||
<span>
|
||||
{m.mine ? me : other} · {formatTime(m.created_at)}
|
||||
{!m.unreadable && !m.verified && " · Signatur nicht prüfbar"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="content">{m.unreadable ? <em>[nicht lesbar]</em> : linkify(m.text)}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<p className="msg">{error}</p>
|
||||
{theirKey ? (
|
||||
<SendForm other={other} ring={ring} ownKey={ownKey} theirKey={theirKey} onSent={reload} />
|
||||
) : (
|
||||
<p className="msg">{other} hat keinen Schlüssel hinterlegt; schreiben geht gerade nicht.</p>
|
||||
)}
|
||||
<div ref={end} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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<HTMLFormElement>) => {
|
||||
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 (
|
||||
<form id="chat-send" onSubmit={onSubmit}>
|
||||
<textarea name="text" rows={3} maxLength={maxMessage} placeholder="Nachricht" onKeyDown={submitOnShiftEnter} />
|
||||
<button type="submit" title="Shift+Enter" disabled={send.isPending}>
|
||||
Senden
|
||||
</button>
|
||||
<p className="msg">{send.isError ? errMsg(send.error, "Senden fehlgeschlagen.") : ""}</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user