Mit "Anzeigename @handle" in einer Zeile wurde die Meta-Zeile lang und unruhig. Jetzt steht neben dem Avatar oben der Anzeigename, darunter @handle mit der Zeit; die Namen sind nicht mehr unterstrichen. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
289 lines
10 KiB
TypeScript
289 lines
10 KiB
TypeScript
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 { AuthorName, avatarUrl, formatTime, linkify } from "../format";
|
|
import { submitOnCtrlEnter } 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 (
|
|
<>
|
|
<section id="chats">
|
|
<h2>Chats</h2>
|
|
{me.data && <ChatList handle={me.data.handle} />}
|
|
</section>
|
|
{me.isSuccess && !me.data && <AuthBox />}
|
|
</>
|
|
);
|
|
}
|
|
|
|
function ChatList({ handle }: { handle: string }) {
|
|
const own = useUserKey(handle);
|
|
const chats = useChats();
|
|
return (
|
|
<>
|
|
<p className="muted">
|
|
Experimentell. 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.handle} className="byline">
|
|
<img className="avatar avatar-sm" src={avatarUrl(c.avatar)} alt="" loading="lazy" />
|
|
<AuthorName
|
|
u={c}
|
|
to={chatPath(c.handle)}
|
|
meta={<> · {formatTime(c.last_at)}{c.unread > 0 && <strong> · {c.unread} neu</strong>}</>}
|
|
/>
|
|
</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 { handle = "" } = useParams();
|
|
const me = useMe();
|
|
return (
|
|
<>
|
|
<section id="chat">
|
|
<p>
|
|
<Link to="/chats">← Chats</Link>
|
|
</p>
|
|
<h2>
|
|
Chat mit <Link to={`/u/${encodeURIComponent(handle)}`}>@{handle}</Link>
|
|
</h2>
|
|
{me.data && <Conversation key={handle} me={me.data.handle} other={handle} />}
|
|
</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 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 <p className="muted">Entsperre …</p>;
|
|
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. Dieser Browser merkt sie sich {rememberDays} Tage.
|
|
</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);
|
|
// 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 && (
|
|
<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={submitOnCtrlEnter} />
|
|
<button type="submit" title="Strg+Enter" disabled={send.isPending}>
|
|
Senden
|
|
</button>
|
|
<p className="msg">{send.isError ? errMsg(send.error, "Senden fehlgeschlagen.") : ""}</p>
|
|
</form>
|
|
);
|
|
}
|