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:
irrlicht
2026-10-13 12:52:10 +02:00
co-authored by Claude Opus 5.5
parent ed227f0d81
commit f75407ea5b
33 changed files with 983 additions and 33 deletions
+1 -1
View File
@@ -8,7 +8,7 @@ type Target = { title: string; icon?: ReactNode; to: string; end?: boolean };
// Bereiche, die es noch nicht gibt: Route und Platzhalter-Seite bestehen,
// in der Navigation sind sie bis dahin ausgeblendet.
const unfinished = new Set(["/search", "/notifications", "/chats"]);
const unfinished = new Set(["/search", "/notifications"]);
export const isReady = (to: string) => !unfinished.has(to);
+20
View File
@@ -773,3 +773,23 @@ form input[type="file"] {
display: block;
}
}
/* --- Chats --- */
#chat-list {
list-style: none;
padding: 0;
}
#chat-list li {
padding: 0.3rem 0;
}
/* Nachrichten wie Beiträge (Meta-Zeile, Text), aber nicht klickbar. */
.message {
padding: 0.4rem 0;
font-size: 1.2rem;
border-bottom: 1px solid var(--ink);
}
.message .content {
padding: 0.3rem 0;
line-height: 1.5;
overflow-wrap: break-word;
}
+1
View File
@@ -24,6 +24,7 @@
<ul>
<li>Unter <em>Einstellungen → Schlüssel</em> richtest du deinen Schlüssel für Ende-zu-Ende-verschlüsselte Direktnachrichten ein. Er liegt bei uns, verschlüsselt mit sechs zufälligen Wörtern, die nur du kennst – so brauchst du keine Datei zu sichern und hast ihn auf jedem Gerät.</li>
<li>Passphrase ändern, Schlüsseldatei herunterladen und den Schlüssel als verloren markieren, wenn die Passphrase weg ist.</li>
<li>Chats: Auf dem Profil sprichst du andere mit <em>Ansprechen</em> an, wenn ihr beide einen Schlüssel habt. Nachrichten sind Ende-zu-Ende verschlüsselt – wir können sie nicht lesen – und verschwinden nach 15 Tagen.</li>
</ul>
<h3>12.10.2026</h3>
<ul>
+57
View File
@@ -0,0 +1,57 @@
import { useSyncExternalStore } from "react";
import { fetchSecrets, ImportError, unlockKey } from "./keystore";
// Der Schlüsselbund: die eigenen privaten Schlüssel, entsperrt, solange der
// Tab offen ist (notes/chats.md). Entsperrt wird einmal mit der Passphrase;
// nach dem Neuladen ist er wieder zu. Mehr Schutz auf dem Client ist nicht
// das Ziel -- die Schlüssel schützen die Chats vor dem Server.
type PrivateKey = import("openpgp").PrivateKey;
// Keyring gehört zu einem Konto (username); current ist der aktuelle
// Schlüssel zum Signieren, all alle entsperrbaren zum Entschlüsseln.
export type Keyring = { username: string; fingerprint: string; current: PrivateKey; all: PrivateKey[] };
let ring: Keyring | null = null;
const listeners = new Set<() => void>();
function set(r: Keyring | null) {
ring = r;
listeners.forEach((l) => l());
}
// unlockKeyring entsperrt die eigenen Schlüssel mit der Passphrase. Der
// aktuelle muss passen; frühere mit einer anderen Passphrase (etwa nach
// „als verloren markieren“) bleiben zu, Nachrichten an sie unlesbar.
export async function unlockKeyring(username: string, passphrase: string) {
const secrets = await fetchSecrets();
const current = secrets.find((s) => s.current);
if (!current) throw new ImportError("Du hast noch keinen Schlüssel hinterlegt.");
const key = await unlockKey(current.secret, passphrase);
const all = [key];
for (const s of secrets) {
if (s.current) continue;
try {
all.push(await unlockKey(s.secret, passphrase));
} catch {
// Andere Passphrase: bleibt zu.
}
}
set({ username, fingerprint: current.fingerprint, current: key, all });
}
// lockKeyring vergisst die entsperrten Schlüssel, etwa nach einem neuen
// Schlüssel oder „als verloren markieren“.
export const lockKeyring = () => set(null);
const subscribe = (l: () => void) => {
listeners.add(l);
return () => listeners.delete(l);
};
// useKeyring liefert den Schlüsselbund des Kontos username, sonst null
// (zu oder einem anderen Konto entsperrt).
export function useKeyring(username: string | undefined): Keyring | null {
const r = useSyncExternalStore(subscribe, () => ring);
return r && r.username === username ? r : null;
}
+52
View File
@@ -207,3 +207,55 @@ export async function armorSecret(secret: string): Promise<string> {
const openpgp = await loadOpenPGP();
return (await openpgp.readPrivateKey({ binaryKey: fromBase64(secret) })).armor();
}
// encryptMessage verschlüsselt eine Direktnachricht an den Empfänger und an
// sich selbst (theirKey, ownKey: öffentliche Schlüssel, Base64 wie von der
// API) und signiert sie mit dem eigenen entsperrten Schlüssel. Ergebnis:
// die binäre OpenPGP-Nachricht für /chats/{username}.
export async function encryptMessage(
text: string,
theirKey: string,
ownKey: string,
signingKey: PrivateKey,
): Promise<Uint8Array> {
const openpgp = await loadOpenPGP();
const encryptionKeys = await Promise.all(
[theirKey, ownKey].map((k) => openpgp.readKey({ binaryKey: fromBase64(k) })),
);
return openpgp.encrypt({
message: await openpgp.createMessage({ text }),
encryptionKeys,
signingKeys: signingKey,
format: "binary",
});
}
// Decrypted ist eine entschlüsselte Nachricht; verified sagt, ob die
// Signatur zu einem der erwarteten Schlüssel passt.
export type Decrypted = { text: string; verified: boolean };
// decryptMessage entschlüsselt body (Base64) mit einem der eigenen
// entsperrten Schlüssel und prüft die Signatur gegen verifyWith (öffentliche
// Schlüssel, Base64). Passt kein eigener Schlüssel: ImportError.
export async function decryptMessage(body: string, keys: PrivateKey[], verifyWith: string[]): Promise<Decrypted> {
const openpgp = await loadOpenPGP();
const verificationKeys = await Promise.all(verifyWith.map((k) => openpgp.readKey({ binaryKey: fromBase64(k) })));
let result;
try {
result = await openpgp.decrypt({
message: await openpgp.readMessage({ binaryMessage: fromBase64(body) }),
decryptionKeys: keys,
verificationKeys,
});
} catch {
throw new ImportError("Nicht lesbar.");
}
let verified = false;
try {
await result.signatures[0]?.verified;
verified = result.signatures.length > 0;
} catch {
verified = false;
}
return { text: String(result.data), verified };
}
+3 -1
View File
@@ -13,6 +13,7 @@ import { MePage, Placeholder } from "./pages/Placeholder";
import { DocPage } from "./pages/DocPage";
import { SettingsPage } from "./pages/SettingsPage";
import { KeysPage } from "./pages/KeysPage";
import { ChatPage, ChatsPage } from "./pages/ChatsPage";
import { applyTheme, loadTheme } from "./theme";
import "./app.css";
@@ -45,7 +46,8 @@ const router = createBrowserRouter([
{ path: "/me", element: <MePage /> },
{ path: "/search", element: <Placeholder title="Suche" /> },
{ path: "/notifications", element: <Placeholder title="Benachrichtigungen" /> },
{ path: "/chats", element: <Placeholder title="Chats" /> },
{ path: "/chats", element: <ChatsPage /> },
{ path: "/chats/:username", element: <ChatPage /> },
{ path: "/settings", element: <SettingsPage /> },
{ path: "/settings/keys", element: <KeysPage /> },
{ path: "/info", element: <DocPage name="info" /> },
+271
View File
@@ -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>
);
}
+15 -22
View File
@@ -1,10 +1,12 @@
import { useEffect, useState, type FormEvent } from "react";
import { Link } from "react-router";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { ApiError, api, errMsg } from "../api";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { api, errMsg } from "../api";
import { useMe } from "../auth";
import { AuthBox } from "../components/AuthBox";
import { formatTime } from "../format";
import { lockKeyring } from "../keyring";
import { useUserKey } from "../useKey";
import {
armorSecret,
download,
@@ -96,25 +98,8 @@ function BrowserCheck({ support }: { support: Support | null }) {
);
}
// useServerKey liefert den aktuellen Schlüssel vom Server; key ist null, wenn
// keiner hinterlegt oder er als verloren markiert ist (lost).
function useServerKey(username: string) {
return useQuery({
queryKey: ["key", username],
queryFn: async (): Promise<{ key: KeyInfo | null; lost: boolean }> => {
try {
return { key: await api.get<KeyInfo>(`/u/${encodeURIComponent(username)}/key`), lost: false };
} catch (err) {
if (err instanceof ApiError && err.status === 404) return { key: null, lost: err.code === "key.lost" };
throw err;
}
},
});
}
function MyKey({ username }: { username: string }) {
const server = useServerKey(username);
const server = useUserKey(username);
if (!server.data) return null;
const { key, lost } = server.data;
return key ? (
@@ -245,7 +230,11 @@ function MarkLost({ username }: { username: string }) {
const qc = useQueryClient();
const lost = useMutation({
mutationFn: () => api.post("/user/key/lost", new FormData()),
onSuccess: () => qc.invalidateQueries({ queryKey: ["key", username] }),
onSuccess: () => {
// Der entsperrte Schlüsselbund gehört zum bisherigen Schlüssel.
lockKeyring();
return qc.invalidateQueries({ queryKey: ["key", username] });
},
});
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
@@ -306,7 +295,11 @@ function SaveKey({ username, created, onCancel }: { username: string; created: C
fd.set("secret", toBase64(key.privateBinary));
await api.post<KeyInfo>("/user/key", fd);
},
onSuccess: () => qc.invalidateQueries({ queryKey: ["key", username] }),
onSuccess: () => {
// Der entsperrte Schlüsselbund gehört zum bisherigen Schlüssel.
lockKeyring();
return qc.invalidateQueries({ queryKey: ["key", username] });
},
});
return (
<ConfirmPassphrase
+1 -1
View File
@@ -3,7 +3,7 @@ import { useMe } from "../auth";
import { AuthBox } from "../components/AuthBox";
// Placeholder steht für Bereiche, die noch eigene Projekte sind (Suche,
// Benachrichtigungen, Chats).
// Benachrichtigungen).
export function Placeholder({ title }: { title: string }) {
return (
<section>
+16 -1
View File
@@ -1,9 +1,10 @@
import { useState } from "react";
import { useParams } from "react-router";
import { Link, useParams } from "react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { api, errMsg } from "../api";
import { useAuthChanged, useMe } from "../auth";
import { avatarUrl, linkify } from "../format";
import { useUserKey } from "../useKey";
import { useFormAction } from "../useFormAction";
import { Feed } from "../components/Feed";
import type { Profile } from "../types";
@@ -49,6 +50,7 @@ function ProfileView({ username }: { username: string }) {
{editing ? "Fertig" : "Profil bearbeiten"}
</button>
)}
{me && info && !isOwner && <Contact me={me.username} other={info.username} />}
</div>
<h2 id="profile-name">{name}</h2>
{info?.bio && <p className="bio">{linkify(info.bio)}</p>}
@@ -71,6 +73,19 @@ function ProfileView({ username }: { username: string }) {
);
}
// Contact führt zum Chat mit dem Profil -- nur, wenn beide einen Schlüssel
// haben; wer selbst keinen hat, sieht den Knopf gar nicht.
function Contact({ me, other }: { me: string; other: string }) {
const own = useUserKey(me);
const theirs = useUserKey(other);
if (!own.data?.key || !theirs.data?.key) return null;
return (
<Link className="button" to={`/chats/${encodeURIComponent(other)}`}>
Ansprechen
</Link>
);
}
// ProfileEdit: Header-Bild, Profilbild und Beschreibung, nur für den
// Eigentümer.
function ProfileEdit({ info }: { info: Profile }) {
+21
View File
@@ -0,0 +1,21 @@
import { useQuery } from "@tanstack/react-query";
import { ApiError, api } from "./api";
import type { KeyInfo } from "./keystore";
// useUserKey liefert den aktuellen öffentlichen Schlüssel eines Nutzers;
// key ist null, wenn keiner hinterlegt oder er als verloren markiert ist
// (lost).
export function useUserKey(username: string | undefined) {
return useQuery({
queryKey: ["key", username],
enabled: !!username,
queryFn: async (): Promise<{ key: KeyInfo | null; lost: boolean }> => {
try {
return { key: await api.get<KeyInfo>(`/u/${encodeURIComponent(username!)}/key`), lost: false };
} catch (err) {
if (err instanceof ApiError && err.status === 404) return { key: null, lost: err.code === "key.lost" };
throw err;
}
},
});
}