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
@@ -20,6 +20,7 @@ import (
|
|||||||
"github.com/oschwald/maxminddb-golang"
|
"github.com/oschwald/maxminddb-golang"
|
||||||
|
|
||||||
"kver/internal/charts"
|
"kver/internal/charts"
|
||||||
|
"kver/internal/chat"
|
||||||
"kver/internal/database"
|
"kver/internal/database"
|
||||||
"kver/internal/httpapi"
|
"kver/internal/httpapi"
|
||||||
"kver/internal/impression"
|
"kver/internal/impression"
|
||||||
@@ -123,6 +124,7 @@ func serve(ctx context.Context, cfg config, db *sql.DB, log *slog.Logger) error
|
|||||||
Previews: linkpreview.New(linkpreview.Config{DB: db, Log: log, Now: time.Now}),
|
Previews: linkpreview.New(linkpreview.Config{DB: db, Log: log, Now: time.Now}),
|
||||||
Charts: charts.New(db, log, time.Now),
|
Charts: charts.New(db, log, time.Now),
|
||||||
Impressions: impression.NewTracker(db, geo, log, time.Now),
|
Impressions: impression.NewTracker(db, geo, log, time.Now),
|
||||||
|
Chats: chat.NewPurger(db, log, time.Now),
|
||||||
}
|
}
|
||||||
// Die Worker überdauern das Signal: sie stoppen erst, wenn der Server
|
// Die Worker überdauern das Signal: sie stoppen erst, wenn der Server
|
||||||
// keine Requests mehr bedient.
|
// keine Requests mehr bedient.
|
||||||
@@ -165,6 +167,7 @@ func startWorkers(ctx context.Context, d httpapi.Deps) (stop func()) {
|
|||||||
wg.Go(func() { d.Previews.Run(ctx) })
|
wg.Go(func() { d.Previews.Run(ctx) })
|
||||||
wg.Go(func() { d.Charts.Run(ctx) })
|
wg.Go(func() { d.Charts.Run(ctx) })
|
||||||
wg.Go(func() { d.Impressions.Run(ctx) })
|
wg.Go(func() { d.Impressions.Run(ctx) })
|
||||||
|
wg.Go(func() { d.Chats.Run(ctx) })
|
||||||
return func() {
|
return func() {
|
||||||
cancel()
|
cancel()
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
|||||||
@@ -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,
|
// Bereiche, die es noch nicht gibt: Route und Platzhalter-Seite bestehen,
|
||||||
// in der Navigation sind sie bis dahin ausgeblendet.
|
// 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);
|
export const isReady = (to: string) => !unfinished.has(to);
|
||||||
|
|
||||||
|
|||||||
@@ -773,3 +773,23 @@ form input[type="file"] {
|
|||||||
display: block;
|
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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@
|
|||||||
<ul>
|
<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>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>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>
|
</ul>
|
||||||
<h3>12.10.2026</h3>
|
<h3>12.10.2026</h3>
|
||||||
<ul>
|
<ul>
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -207,3 +207,55 @@ export async function armorSecret(secret: string): Promise<string> {
|
|||||||
const openpgp = await loadOpenPGP();
|
const openpgp = await loadOpenPGP();
|
||||||
return (await openpgp.readPrivateKey({ binaryKey: fromBase64(secret) })).armor();
|
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 };
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { MePage, Placeholder } from "./pages/Placeholder";
|
|||||||
import { DocPage } from "./pages/DocPage";
|
import { DocPage } from "./pages/DocPage";
|
||||||
import { SettingsPage } from "./pages/SettingsPage";
|
import { SettingsPage } from "./pages/SettingsPage";
|
||||||
import { KeysPage } from "./pages/KeysPage";
|
import { KeysPage } from "./pages/KeysPage";
|
||||||
|
import { ChatPage, ChatsPage } from "./pages/ChatsPage";
|
||||||
import { applyTheme, loadTheme } from "./theme";
|
import { applyTheme, loadTheme } from "./theme";
|
||||||
import "./app.css";
|
import "./app.css";
|
||||||
|
|
||||||
@@ -45,7 +46,8 @@ const router = createBrowserRouter([
|
|||||||
{ path: "/me", element: <MePage /> },
|
{ path: "/me", element: <MePage /> },
|
||||||
{ path: "/search", element: <Placeholder title="Suche" /> },
|
{ path: "/search", element: <Placeholder title="Suche" /> },
|
||||||
{ path: "/notifications", element: <Placeholder title="Benachrichtigungen" /> },
|
{ 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", element: <SettingsPage /> },
|
||||||
{ path: "/settings/keys", element: <KeysPage /> },
|
{ path: "/settings/keys", element: <KeysPage /> },
|
||||||
{ path: "/info", element: <DocPage name="info" /> },
|
{ path: "/info", element: <DocPage name="info" /> },
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
import { useEffect, useState, type FormEvent } from "react";
|
import { useEffect, useState, type FormEvent } from "react";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { ApiError, api, errMsg } from "../api";
|
import { api, errMsg } from "../api";
|
||||||
import { useMe } from "../auth";
|
import { useMe } from "../auth";
|
||||||
import { AuthBox } from "../components/AuthBox";
|
import { AuthBox } from "../components/AuthBox";
|
||||||
import { formatTime } from "../format";
|
import { formatTime } from "../format";
|
||||||
|
import { lockKeyring } from "../keyring";
|
||||||
|
import { useUserKey } from "../useKey";
|
||||||
import {
|
import {
|
||||||
armorSecret,
|
armorSecret,
|
||||||
download,
|
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 }) {
|
function MyKey({ username }: { username: string }) {
|
||||||
const server = useServerKey(username);
|
const server = useUserKey(username);
|
||||||
if (!server.data) return null;
|
if (!server.data) return null;
|
||||||
const { key, lost } = server.data;
|
const { key, lost } = server.data;
|
||||||
return key ? (
|
return key ? (
|
||||||
@@ -245,7 +230,11 @@ function MarkLost({ username }: { username: string }) {
|
|||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
const lost = useMutation({
|
const lost = useMutation({
|
||||||
mutationFn: () => api.post("/user/key/lost", new FormData()),
|
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>) => {
|
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -306,7 +295,11 @@ function SaveKey({ username, created, onCancel }: { username: string; created: C
|
|||||||
fd.set("secret", toBase64(key.privateBinary));
|
fd.set("secret", toBase64(key.privateBinary));
|
||||||
await api.post<KeyInfo>("/user/key", fd);
|
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 (
|
return (
|
||||||
<ConfirmPassphrase
|
<ConfirmPassphrase
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useMe } from "../auth";
|
|||||||
import { AuthBox } from "../components/AuthBox";
|
import { AuthBox } from "../components/AuthBox";
|
||||||
|
|
||||||
// Placeholder steht für Bereiche, die noch eigene Projekte sind (Suche,
|
// Placeholder steht für Bereiche, die noch eigene Projekte sind (Suche,
|
||||||
// Benachrichtigungen, Chats).
|
// Benachrichtigungen).
|
||||||
export function Placeholder({ title }: { title: string }) {
|
export function Placeholder({ title }: { title: string }) {
|
||||||
return (
|
return (
|
||||||
<section>
|
<section>
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useParams } from "react-router";
|
import { Link, useParams } from "react-router";
|
||||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
import { api, errMsg } from "../api";
|
import { api, errMsg } from "../api";
|
||||||
import { useAuthChanged, useMe } from "../auth";
|
import { useAuthChanged, useMe } from "../auth";
|
||||||
import { avatarUrl, linkify } from "../format";
|
import { avatarUrl, linkify } from "../format";
|
||||||
|
import { useUserKey } from "../useKey";
|
||||||
import { useFormAction } from "../useFormAction";
|
import { useFormAction } from "../useFormAction";
|
||||||
import { Feed } from "../components/Feed";
|
import { Feed } from "../components/Feed";
|
||||||
import type { Profile } from "../types";
|
import type { Profile } from "../types";
|
||||||
@@ -49,6 +50,7 @@ function ProfileView({ username }: { username: string }) {
|
|||||||
{editing ? "Fertig" : "Profil bearbeiten"}
|
{editing ? "Fertig" : "Profil bearbeiten"}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{me && info && !isOwner && <Contact me={me.username} other={info.username} />}
|
||||||
</div>
|
</div>
|
||||||
<h2 id="profile-name">{name}</h2>
|
<h2 id="profile-name">{name}</h2>
|
||||||
{info?.bio && <p className="bio">{linkify(info.bio)}</p>}
|
{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
|
// ProfileEdit: Header-Bild, Profilbild und Beschreibung, nur für den
|
||||||
// Eigentümer.
|
// Eigentümer.
|
||||||
function ProfileEdit({ info }: { info: Profile }) {
|
function ProfileEdit({ info }: { info: Profile }) {
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
// Package chat räumt Direktnachrichten ab (notes/chats.md). Die Nachrichten
|
||||||
|
// selbst sind Ende-zu-Ende verschlüsselt; der Server speichert und verteilt
|
||||||
|
// sie nur (internal/httpapi/chats.go) und löscht sie nach Retention.
|
||||||
|
package chat
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"log/slog"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Retention: so lange bleiben Nachrichten auf dem Server.
|
||||||
|
const Retention = 15 * 24 * time.Hour
|
||||||
|
|
||||||
|
const purgeEvery = time.Hour
|
||||||
|
|
||||||
|
// Purger löscht abgelaufene Nachrichten.
|
||||||
|
type Purger struct {
|
||||||
|
db *sql.DB
|
||||||
|
log *slog.Logger
|
||||||
|
now func() time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPurger(db *sql.DB, log *slog.Logger, now func() time.Time) *Purger {
|
||||||
|
return &Purger{db: db, log: log, now: now}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run löscht sofort und danach stündlich, bis ctx endet.
|
||||||
|
func (p *Purger) Run(ctx context.Context) {
|
||||||
|
tick := time.NewTicker(purgeEvery)
|
||||||
|
defer tick.Stop()
|
||||||
|
for {
|
||||||
|
if _, err := p.Purge(ctx); err != nil && ctx.Err() == nil {
|
||||||
|
p.log.Error("nachrichten löschen", "err", err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-tick.C:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Purge löscht alle Nachrichten, die älter als Retention sind, und liefert
|
||||||
|
// ihre Anzahl.
|
||||||
|
func (p *Purger) Purge(ctx context.Context) (int64, error) {
|
||||||
|
res, err := p.db.ExecContext(ctx, `DELETE FROM message WHERE created_at < $1`,
|
||||||
|
p.now().Add(-Retention).Unix())
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return res.RowsAffected()
|
||||||
|
}
|
||||||
@@ -126,6 +126,24 @@ CREATE TABLE IF NOT EXISTS account_key (
|
|||||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_account_key_current ON account_key(uid) WHERE replaced_at = 0;
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_account_key_current ON account_key(uid) WHERE replaced_at = 0;
|
||||||
CREATE INDEX IF NOT EXISTS idx_account_key_uid ON account_key(uid);
|
CREATE INDEX IF NOT EXISTS idx_account_key_uid ON account_key(uid);
|
||||||
|
|
||||||
|
-- Direktnachrichten, Ende-zu-Ende verschlüsselt (notes/chats.md). body ist
|
||||||
|
-- die binäre OpenPGP-Nachricht, verschlüsselt an Empfänger und Absender und
|
||||||
|
-- vom Absender signiert; lesen kann sie nur, wer die Passphrase kennt.
|
||||||
|
-- Sichtbar bleiben Absender, Empfänger, Zeitpunkt und Länge. read_at > 0:
|
||||||
|
-- vom Empfänger abgerufen. Der Server löscht Nachrichten nach 15 Tagen
|
||||||
|
-- (internal/chat).
|
||||||
|
CREATE TABLE IF NOT EXISTS message (
|
||||||
|
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||||
|
sender BIGINT NOT NULL,
|
||||||
|
recipient BIGINT NOT NULL,
|
||||||
|
body BYTEA NOT NULL,
|
||||||
|
created_at BIGINT NOT NULL,
|
||||||
|
read_at BIGINT NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_message_pair ON message(sender, recipient, id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_message_recipient ON message(recipient, id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_message_created ON message(created_at);
|
||||||
|
|
||||||
-- Indizes für die häufigen Zugriffspfade; ohne sie werden Feed (ORDER BY
|
-- Indizes für die häufigen Zugriffspfade; ohne sie werden Feed (ORDER BY
|
||||||
-- last_activity), Thread (WHERE reply_to) und Vote-Zähler (WHERE pid) mit
|
-- last_activity), Thread (WHERE reply_to) und Vote-Zähler (WHERE pid) mit
|
||||||
-- wachsender Tabelle zu Full-Table-Scans. username/session.value/vote(uid,pid)
|
-- wachsender Tabelle zu Full-Table-Scans. username/session.value/vote(uid,pid)
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
|
||||||
|
"kver/internal/apperr"
|
||||||
|
"kver/internal/chat"
|
||||||
|
"kver/internal/pgpkey"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Direktnachrichten (notes/chats.md). Der Server sieht nur verschlüsselte
|
||||||
|
// OpenPGP-Nachrichten: Ver- und Entschlüsseln macht der Browser mit den
|
||||||
|
// Schlüsseln aus keys.go. Gespräche sind Paare von Konten; schreiben dürfen
|
||||||
|
// sich zwei Konten, die beide einen aktuellen Schlüssel haben.
|
||||||
|
|
||||||
|
var (
|
||||||
|
errChatSelf = apperr.Invalid("chat.self", "Mit dir selbst kannst du nicht chatten.")
|
||||||
|
errChatNoKey = apperr.Conflict("chat.no_key", "Ihr braucht beide einen Schlüssel, um euch zu schreiben.")
|
||||||
|
errChatBody = apperr.Invalid("chat.body", "Keine verschlüsselte Nachricht.").At("body")
|
||||||
|
errChatTooLong = apperr.TooLarge("chat.too_large", "Die Nachricht ist zu lang.").At("body")
|
||||||
|
)
|
||||||
|
|
||||||
|
// chatJSON ist ein Gespräch in der Übersicht.
|
||||||
|
type chatJSON struct {
|
||||||
|
Username string `json:"username"`
|
||||||
|
Avatar string `json:"avatar"`
|
||||||
|
LastAt int64 `json:"last_at"`
|
||||||
|
Unread int `json:"unread"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleChats liefert die Gespräche des eingeloggten Nutzers, das mit der
|
||||||
|
// jüngsten Nachricht zuerst.
|
||||||
|
func (s *Server) handleChats(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
uid := currentUID(r)
|
||||||
|
rows, err := s.DB.QueryContext(r.Context(),
|
||||||
|
`SELECT a.username, a.avatar, m.last_at, m.unread
|
||||||
|
FROM (SELECT CASE WHEN sender = $1 THEN recipient ELSE sender END AS other,
|
||||||
|
MAX(created_at) AS last_at,
|
||||||
|
COUNT(*) FILTER (WHERE recipient = $1 AND read_at = 0) AS unread
|
||||||
|
FROM message WHERE (sender = $1 OR recipient = $1) AND created_at >= $2
|
||||||
|
GROUP BY 1) m
|
||||||
|
JOIN account a ON a.uid = m.other
|
||||||
|
ORDER BY m.last_at DESC, a.username`, uid, s.expiredBefore())
|
||||||
|
if err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
chats := []chatJSON{}
|
||||||
|
for rows.Next() {
|
||||||
|
var c chatJSON
|
||||||
|
if err := rows.Scan(&c.Username, &c.Avatar, &c.LastAt, &c.Unread); err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
chats = append(chats, c)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"chats": chats})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// messageJSON ist eine Nachricht im Drahtformat; body ist die binäre
|
||||||
|
// OpenPGP-Nachricht (base64), mine kennzeichnet die eigenen.
|
||||||
|
type messageJSON struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Mine bool `json:"mine"`
|
||||||
|
Body []byte `json:"body"`
|
||||||
|
CreatedAt int64 `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// partner liefert die uid des Gesprächspartners aus der URL.
|
||||||
|
func (s *Server) partner(r *http.Request) (int64, error) {
|
||||||
|
other, err := s.uidOf(r.Context(), chi.URLParam(r, "username"))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if other == currentUID(r) {
|
||||||
|
return 0, errChatSelf
|
||||||
|
}
|
||||||
|
return other, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleChat liefert die Nachrichten eines Gesprächs, älteste zuerst; mit
|
||||||
|
// ?after=id nur die neueren (für das Nachfragen im offenen Gespräch). Die
|
||||||
|
// abgerufenen Nachrichten an den Nutzer gelten danach als gelesen.
|
||||||
|
func (s *Server) handleChat(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
ctx, uid := r.Context(), currentUID(r)
|
||||||
|
other, err := s.partner(r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
after, _ := strconv.ParseInt(r.URL.Query().Get("after"), 10, 64)
|
||||||
|
rows, err := s.DB.QueryContext(ctx,
|
||||||
|
`SELECT id, sender = $1, body, created_at FROM message
|
||||||
|
WHERE ((sender = $1 AND recipient = $2) OR (sender = $2 AND recipient = $1))
|
||||||
|
AND id > $3 AND created_at >= $4
|
||||||
|
ORDER BY id`, uid, other, after, s.expiredBefore())
|
||||||
|
if err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
msgs := []messageJSON{}
|
||||||
|
var lastIn int64
|
||||||
|
for rows.Next() {
|
||||||
|
var m messageJSON
|
||||||
|
if err := rows.Scan(&m.ID, &m.Mine, &m.Body, &m.CreatedAt); err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
if !m.Mine {
|
||||||
|
lastIn = m.ID
|
||||||
|
}
|
||||||
|
msgs = append(msgs, m)
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
if lastIn > 0 {
|
||||||
|
if _, err := s.DB.ExecContext(ctx,
|
||||||
|
`UPDATE message SET read_at = $1 WHERE recipient = $2 AND sender = $3 AND read_at = 0 AND id <= $4`,
|
||||||
|
s.Now().Unix(), uid, other, lastIn); err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, map[string]any{"messages": msgs})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// hasKey meldet, ob uid einen aktuellen, nicht verlorenen Schlüssel hat.
|
||||||
|
func (s *Server) hasKey(ctx context.Context, uid int64) (bool, error) {
|
||||||
|
var ok bool
|
||||||
|
err := s.DB.QueryRowContext(ctx,
|
||||||
|
`SELECT EXISTS (SELECT 1 FROM account_key WHERE uid = $1 AND replaced_at = 0 AND lost_at = 0)`, uid).Scan(&ok)
|
||||||
|
return ok, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleSendMessage nimmt eine verschlüsselte Nachricht (body, base64) an
|
||||||
|
// den Nutzer aus der URL an. Beide brauchen einen aktuellen Schlüssel: der
|
||||||
|
// Empfänger zum Lesen, der Absender, damit er seine eigenen Nachrichten
|
||||||
|
// wieder entschlüsseln kann.
|
||||||
|
func (s *Server) handleSendMessage(w http.ResponseWriter, r *http.Request) error {
|
||||||
|
ctx, uid := r.Context(), currentUID(r)
|
||||||
|
other, err := s.partner(r)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
body, err := base64.StdEncoding.DecodeString(r.FormValue("body"))
|
||||||
|
if err != nil || len(body) == 0 {
|
||||||
|
return errChatBody
|
||||||
|
}
|
||||||
|
switch err := pgpkey.CheckMessage(body); {
|
||||||
|
case errors.Is(err, pgpkey.ErrTooLarge):
|
||||||
|
return errChatTooLong
|
||||||
|
case err != nil:
|
||||||
|
return errChatBody
|
||||||
|
}
|
||||||
|
for _, id := range []int64{uid, other} {
|
||||||
|
ok, err := s.hasKey(ctx, id)
|
||||||
|
if err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return errChatNoKey
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m := messageJSON{Mine: true, Body: body, CreatedAt: s.Now().Unix()}
|
||||||
|
if err := s.DB.QueryRowContext(ctx,
|
||||||
|
`INSERT INTO message (sender, recipient, body, created_at) VALUES ($1, $2, $3, $4) RETURNING id`,
|
||||||
|
uid, other, body, m.CreatedAt).Scan(&m.ID); err != nil {
|
||||||
|
return apperr.Internal(err)
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, m)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// expiredBefore: Nachrichten davor sind abgelaufen. Der Purger löscht sie
|
||||||
|
// stündlich; bis dahin werden sie schon nicht mehr ausgeliefert.
|
||||||
|
func (s *Server) expiredBefore() int64 { return s.Now().Add(-chat.Retention).Unix() }
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
package httpapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"kver/internal/chat"
|
||||||
|
)
|
||||||
|
|
||||||
|
type chatsJSON struct {
|
||||||
|
Chats []chatJSON
|
||||||
|
}
|
||||||
|
|
||||||
|
type messagesJSON struct {
|
||||||
|
Messages []messageJSON
|
||||||
|
}
|
||||||
|
|
||||||
|
func msgForm(body []byte) url.Values {
|
||||||
|
return url.Values{"body": {base64.StdEncoding.EncodeToString(body)}}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestChats(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
srv := newTestServer(t)
|
||||||
|
alice := registerAndLogin(t, srv, "alice")
|
||||||
|
bob := registerAndLogin(t, srv, "bob")
|
||||||
|
carol := registerAndLogin(t, srv, "carol")
|
||||||
|
msg := fixture(t, "v6-msg.pgp")
|
||||||
|
for c, kf := range map[*http.Client][2]string{alice: {"v6.pgp", "v6-locked.pgp"}, bob: {"v6-2.pgp", "v6-2-locked.pgp"}} {
|
||||||
|
if st, code := postCode(t, c, srv.URL+"/api/user/key", keyForm(fixture(t, kf[0]), fixture(t, kf[1]))); st != http.StatusCreated {
|
||||||
|
t.Fatalf("schlüssel %s: %d %s", kf[0], st, code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
toBob, toAlice := srv.URL+"/api/chats/bob", srv.URL+"/api/chats/alice"
|
||||||
|
|
||||||
|
// Ablehnungen.
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
c *http.Client
|
||||||
|
url string
|
||||||
|
form url.Values
|
||||||
|
status int
|
||||||
|
code string
|
||||||
|
}{
|
||||||
|
{"ohne login", newClient(t), toBob, msgForm(msg), 401, "auth.required"},
|
||||||
|
{"an sich selbst", alice, toAlice, msgForm(msg), 400, "chat.self"},
|
||||||
|
{"unbekannt", alice, srv.URL + "/api/chats/niemand", msgForm(msg), 404, "not_found"},
|
||||||
|
{"empfänger ohne schlüssel", alice, srv.URL + "/api/chats/carol", msgForm(msg), 409, "chat.no_key"},
|
||||||
|
{"absender ohne schlüssel", carol, toBob, msgForm(msg), 409, "chat.no_key"},
|
||||||
|
{"klartext", alice, toBob, msgForm([]byte("hallo")), 400, "chat.body"},
|
||||||
|
{"kein base64", alice, toBob, url.Values{"body": {"%%%"}}, 400, "chat.body"},
|
||||||
|
{"öffentlicher schlüssel", alice, toBob, msgForm(fixture(t, "v6.pgp")), 400, "chat.body"},
|
||||||
|
} {
|
||||||
|
if st, code := postCode(t, tc.c, tc.url, tc.form); st != tc.status || (tc.code != "not_found" && code != tc.code) {
|
||||||
|
t.Errorf("%s: %d %s, erwartet %d %s", tc.name, st, code, tc.status, tc.code)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if st, code := postCode(t, alice, toBob, msgForm(msg)); st != http.StatusCreated {
|
||||||
|
t.Fatalf("senden: %d %s", st, code)
|
||||||
|
}
|
||||||
|
var list chatsJSON
|
||||||
|
if getAs(t, bob, srv.URL+"/api/chats", &list); len(list.Chats) != 1 || list.Chats[0].Username != "alice" || list.Chats[0].Unread != 1 {
|
||||||
|
t.Fatalf("bobs chats: %+v", list)
|
||||||
|
}
|
||||||
|
var got messagesJSON
|
||||||
|
if getAs(t, bob, toAlice, &got); len(got.Messages) != 1 || got.Messages[0].Mine || !bytes.Equal(got.Messages[0].Body, msg) {
|
||||||
|
t.Fatalf("bob liest: %+v", got)
|
||||||
|
}
|
||||||
|
// Abgerufen heißt gelesen.
|
||||||
|
if getAs(t, bob, srv.URL+"/api/chats", &list); list.Chats[0].Unread != 0 {
|
||||||
|
t.Fatalf("nach dem lesen: %+v", list)
|
||||||
|
}
|
||||||
|
id := got.Messages[0].ID
|
||||||
|
if getAs(t, alice, toBob, &got); len(got.Messages) != 1 || !got.Messages[0].Mine {
|
||||||
|
t.Fatalf("alice liest: %+v", got)
|
||||||
|
}
|
||||||
|
if getAs(t, alice, toBob+"?after="+strconv.FormatInt(id, 10), &got); len(got.Messages) != 0 {
|
||||||
|
t.Fatalf("after: %+v", got)
|
||||||
|
}
|
||||||
|
// Dritte sehen nichts.
|
||||||
|
if getAs(t, carol, srv.URL+"/api/chats", &list); len(list.Chats) != 0 {
|
||||||
|
t.Fatalf("carols chats: %+v", list)
|
||||||
|
}
|
||||||
|
if getAs(t, carol, toAlice, &got); len(got.Messages) != 0 {
|
||||||
|
t.Fatalf("carol liest alice: %+v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Abgelaufene Nachrichten: nicht mehr ausgeliefert, dann gelöscht.
|
||||||
|
if _, err := srv.db.Exec(`UPDATE message SET created_at = created_at - $1`, int64(chat.Retention/time.Second)+1); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if getAs(t, bob, toAlice, &got); len(got.Messages) != 0 {
|
||||||
|
t.Fatalf("abgelaufen ausgeliefert: %+v", got)
|
||||||
|
}
|
||||||
|
if n, err := chat.NewPurger(srv.db, slog.Default(), time.Now).Purge(t.Context()); err != nil || n != 1 {
|
||||||
|
t.Fatalf("purge: %d %v", n, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Konto löschen nimmt die Nachrichten mit.
|
||||||
|
if st, code := postCode(t, alice, toBob, msgForm(msg)); st != http.StatusCreated {
|
||||||
|
t.Fatalf("senden: %d %s", st, code)
|
||||||
|
}
|
||||||
|
if st := postStatus(t, bob, srv.URL+"/api/user/delete", url.Values{"pass1": {"supersecret1"}}); st != http.StatusOK {
|
||||||
|
t.Fatalf("konto löschen: %d", st)
|
||||||
|
}
|
||||||
|
var n int
|
||||||
|
if err := srv.db.QueryRow(`SELECT COUNT(*) FROM message`).Scan(&n); err != nil || n != 0 {
|
||||||
|
t.Fatalf("nachrichten nach konto-löschung: %d %v", n, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -15,6 +15,7 @@ import (
|
|||||||
"kver/internal/account"
|
"kver/internal/account"
|
||||||
"kver/internal/apperr"
|
"kver/internal/apperr"
|
||||||
"kver/internal/charts"
|
"kver/internal/charts"
|
||||||
|
"kver/internal/chat"
|
||||||
"kver/internal/impression"
|
"kver/internal/impression"
|
||||||
"kver/internal/linkpreview"
|
"kver/internal/linkpreview"
|
||||||
"kver/internal/media"
|
"kver/internal/media"
|
||||||
@@ -29,6 +30,7 @@ type Deps struct {
|
|||||||
Previews *linkpreview.Service
|
Previews *linkpreview.Service
|
||||||
Charts *charts.Service
|
Charts *charts.Service
|
||||||
Impressions *impression.Tracker // optional
|
Impressions *impression.Tracker // optional
|
||||||
|
Chats *chat.Purger // optional
|
||||||
// TORNet ist das interne Netz, über das TOR-Anfragen ankommen (siehe
|
// TORNet ist das interne Netz, über das TOR-Anfragen ankommen (siehe
|
||||||
// blockTOR); ein ungültiges Prefix schaltet die Sperre ab.
|
// blockTOR); ein ungültiges Prefix schaltet die Sperre ab.
|
||||||
TORNet netip.Prefix
|
TORNet netip.Prefix
|
||||||
@@ -123,6 +125,10 @@ func (s *Server) apiRoutes(r chi.Router) {
|
|||||||
r.Post("/user/delete", s.api(s.handleUserDelete))
|
r.Post("/user/delete", s.api(s.handleUserDelete))
|
||||||
// Schlüssel (notes/schluessel.md); die Änderungen gedrosselt.
|
// Schlüssel (notes/schluessel.md); die Änderungen gedrosselt.
|
||||||
r.Get("/user/keys/secret", s.api(s.handleKeySecrets))
|
r.Get("/user/keys/secret", s.api(s.handleKeySecrets))
|
||||||
|
// Direktnachrichten (notes/chats.md); Senden gedrosselt gegen Spam.
|
||||||
|
r.Get("/chats", s.api(s.handleChats))
|
||||||
|
r.Get("/chats/{username}", s.api(s.handleChat))
|
||||||
|
r.With(s.limitByIP(60, time.Minute)).Post("/chats/{username}", s.api(s.handleSendMessage))
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
r.Use(s.limitByIP(20, time.Minute))
|
r.Use(s.limitByIP(20, time.Minute))
|
||||||
r.Post("/user/key", s.api(s.handleSetKey))
|
r.Post("/user/key", s.api(s.handleSetKey))
|
||||||
@@ -140,6 +146,7 @@ func (s *Server) pageRoutes(r chi.Router) {
|
|||||||
r.With(s.trackImpression).Get("/", serveApp)
|
r.With(s.trackImpression).Get("/", serveApp)
|
||||||
r.With(s.trackImpression).Get("/e/{pid}", serveApp)
|
r.With(s.trackImpression).Get("/e/{pid}", serveApp)
|
||||||
r.With(s.trackImpression).Get("/u/{username}", serveApp)
|
r.With(s.trackImpression).Get("/u/{username}", serveApp)
|
||||||
|
r.Get("/chats/{username}", serveApp)
|
||||||
r.Get("/stats", serveApp)
|
r.Get("/stats", serveApp)
|
||||||
// Das Reset-Token steht im Fragment (#...) und erreicht den Server über
|
// Das Reset-Token steht im Fragment (#...) und erreicht den Server über
|
||||||
// diese Route nie, siehe account/reset.go.
|
// diese Route nie, siehe account/reset.go.
|
||||||
|
|||||||
@@ -274,6 +274,7 @@ func deleteAccount(ctx context.Context, tx *sql.Tx, uid int64) error {
|
|||||||
`DELETE FROM password_reset WHERE uid = $1`,
|
`DELETE FROM password_reset WHERE uid = $1`,
|
||||||
`DELETE FROM vote WHERE uid = $1`,
|
`DELETE FROM vote WHERE uid = $1`,
|
||||||
`DELETE FROM account_key WHERE uid = $1`,
|
`DELETE FROM account_key WHERE uid = $1`,
|
||||||
|
`DELETE FROM message WHERE sender = $1 OR recipient = $1`,
|
||||||
`UPDATE entry SET deleted = 1, content = '', filepath = '', link_url = '', uid = 0 WHERE uid = $1`,
|
`UPDATE entry SET deleted = 1, content = '', filepath = '', link_url = '', uid = 0 WHERE uid = $1`,
|
||||||
`DELETE FROM account WHERE uid = $1`,
|
`DELETE FROM account WHERE uid = $1`,
|
||||||
} {
|
} {
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ import (
|
|||||||
const MaxSize = 16 << 10
|
const MaxSize = 16 << 10
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
tagPKESK = 1
|
||||||
tagSecretKey = 5
|
tagSecretKey = 5
|
||||||
tagPublicKey = 6
|
tagPublicKey = 6
|
||||||
tagSecretSubkey = 7
|
tagSecretSubkey = 7
|
||||||
@@ -40,8 +41,14 @@ var (
|
|||||||
ErrNotSecret = errors.New("kein privater schlüssel am anfang")
|
ErrNotSecret = errors.New("kein privater schlüssel am anfang")
|
||||||
ErrUnprotected = errors.New("privater schlüssel nicht mit argon2 und aead geschützt")
|
ErrUnprotected = errors.New("privater schlüssel nicht mit argon2 und aead geschützt")
|
||||||
ErrMismatch = errors.New("privater schlüssel passt nicht zum zertifikat")
|
ErrMismatch = errors.New("privater schlüssel passt nicht zum zertifikat")
|
||||||
|
|
||||||
|
ErrNotEncrypted = errors.New("keine verschlüsselte nachricht")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// MaxMessage begrenzt eine verschlüsselte Direktnachricht (Text bis einige
|
||||||
|
// tausend Zeichen, dazu Signatur und Schlüsselpakete).
|
||||||
|
const MaxMessage = 64 << 10
|
||||||
|
|
||||||
// Fingerprint prüft das Zertifikat cert und liefert den v6-Fingerprint
|
// Fingerprint prüft das Zertifikat cert und liefert den v6-Fingerprint
|
||||||
// (SHA-256 über das erste Paket, RFC 9580 Abschnitt 5.5.4.3).
|
// (SHA-256 über das erste Paket, RFC 9580 Abschnitt 5.5.4.3).
|
||||||
func Fingerprint(cert []byte) ([32]byte, error) {
|
func Fingerprint(cert []byte) ([32]byte, error) {
|
||||||
@@ -150,6 +157,25 @@ func splitSecret(body []byte) ([]byte, error) {
|
|||||||
return body[:n], nil
|
return body[:n], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CheckMessage prüft oberflächlich, dass msg eine verschlüsselte
|
||||||
|
// OpenPGP-Nachricht ist: höchstens MaxMessage, erstes Paket ein
|
||||||
|
// Public-Key Encrypted Session Key Packet. Der Rest (Datenpaket, oft mit
|
||||||
|
// Teil-Längen) bleibt ungeprüft -- es geht nur darum, dass kein Klartext
|
||||||
|
// versehentlich beim Server landet.
|
||||||
|
func CheckMessage(msg []byte) error {
|
||||||
|
if len(msg) > MaxMessage {
|
||||||
|
return ErrTooLarge
|
||||||
|
}
|
||||||
|
tag, _, _, err := nextPacket(msg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if tag != tagPKESK {
|
||||||
|
return ErrNotEncrypted
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// nextPacket zerlegt das erste Paket aus b in Tag und Inhalt. Neues und altes
|
// nextPacket zerlegt das erste Paket aus b in Tag und Inhalt. Neues und altes
|
||||||
// Header-Format; Teil-Längen und unbestimmte Längen kommen in Zertifikaten
|
// Header-Format; Teil-Längen und unbestimmte Längen kommen in Zertifikaten
|
||||||
// nicht vor und gelten als ungültig.
|
// nicht vor und gelten als ungültig.
|
||||||
|
|||||||
@@ -11,8 +11,9 @@ import (
|
|||||||
// Die Fixtures in testdata sind Wegwerf-Schlüssel, erzeugt mit OpenPGP.js
|
// Die Fixtures in testdata sind Wegwerf-Schlüssel, erzeugt mit OpenPGP.js
|
||||||
// (testdata/gen.mjs; v6 ohne User-ID, v4 mit, curve25519). *-locked sind die
|
// (testdata/gen.mjs; v6 ohne User-ID, v4 mit, curve25519). *-locked sind die
|
||||||
// privaten Schlüssel dazu mit Argon2 und AEAD, v6-secret ist ungeschützt,
|
// privaten Schlüssel dazu mit Argon2 und AEAD, v6-secret ist ungeschützt,
|
||||||
// v6-iter mit dem älteren S2K-Verfahren; die .fpr-Dateien enthalten den
|
// v6-iter mit dem älteren S2K-Verfahren, v6-msg eine signierte Nachricht
|
||||||
// Fingerprint, wie OpenPGP.js ihn berechnet.
|
// von v6 an v6-2; die .fpr-Dateien enthalten den Fingerprint, wie
|
||||||
|
// OpenPGP.js ihn berechnet.
|
||||||
func read(t *testing.T, name string) []byte {
|
func read(t *testing.T, name string) []byte {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
b, err := os.ReadFile("testdata/" + name)
|
b, err := os.ReadFile("testdata/" + name)
|
||||||
@@ -87,3 +88,24 @@ func TestCheckSecret(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestCheckMessage(t *testing.T) {
|
||||||
|
msg := read(t, "v6-msg.pgp")
|
||||||
|
if err := CheckMessage(msg); err != nil {
|
||||||
|
t.Fatalf("v6-msg: %v", err)
|
||||||
|
}
|
||||||
|
for _, tc := range []struct {
|
||||||
|
name string
|
||||||
|
msg []byte
|
||||||
|
want error
|
||||||
|
}{
|
||||||
|
{"öffentlicher schlüssel", read(t, "v6.pgp"), ErrNotEncrypted},
|
||||||
|
{"klartext", []byte("hallo"), ErrMalformed},
|
||||||
|
{"leer", nil, ErrMalformed},
|
||||||
|
{"zu groß", make([]byte, MaxMessage+1), ErrTooLarge},
|
||||||
|
} {
|
||||||
|
if err := CheckMessage(tc.msg); !errors.Is(err, tc.want) {
|
||||||
|
t.Errorf("%s: erwartet %v, bekam %v", tc.name, tc.want, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Vendored
+6
@@ -19,3 +19,9 @@ const open = await openpgp.decryptKey({ privateKey: a.privateKey, passphrase: "p
|
|||||||
writeFileSync(`${out}/v6-secret.pgp`, open.write());
|
writeFileSync(`${out}/v6-secret.pgp`, open.write());
|
||||||
const iter = await openpgp.encryptKey({ privateKey: open, passphrase: "probe probe", config: { s2kType: openpgp.enums.s2k.iterated, aeadProtect: false } });
|
const iter = await openpgp.encryptKey({ privateKey: open, passphrase: "probe probe", config: { s2kType: openpgp.enums.s2k.iterated, aeadProtect: false } });
|
||||||
writeFileSync(`${out}/v6-iter.pgp`, iter.write());
|
writeFileSync(`${out}/v6-iter.pgp`, iter.write());
|
||||||
|
// Direktnachricht von v6 an v6-2 (und an sich selbst), signiert.
|
||||||
|
const b = await openpgp.readKey({ binaryKey: (await import("fs")).readFileSync(`${out}/v6-2.pgp`) });
|
||||||
|
const msg = await openpgp.encrypt({
|
||||||
|
message: await openpgp.createMessage({ text: "hallo" }),
|
||||||
|
encryptionKeys: [b, a.publicKey], signingKeys: open, format: "binary" });
|
||||||
|
writeFileSync(`${out}/v6-msg.pgp`, msg);
|
||||||
|
|||||||
BIN
Binary file not shown.
Vendored
+1
-1
@@ -1 +1 @@
|
|||||||
09273bc7a75ed04b7388fe1b7c62f8468d73a514d6e4a0e21f81af65fbdc943e
|
9890454127e961250eb59f3dd3533b3bbf9802f1284ad412ac58545fa983af29
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
+1
-1
@@ -1 +1 @@
|
|||||||
d1282dcf82f128d67217ea8c6f858eda4ee5674e7f8ea1a28706e03662b7221d
|
5a1b886df7ffc708d21c27f335df62e0d2ca1afde74c951c88512420a4e43ca7
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
@@ -173,6 +173,22 @@ Ein Kontopasswort verlangt keiner der Endpunkte (siehe
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Chats
|
||||||
|
|
||||||
|
Direktnachrichten, Ende-zu-Ende verschlüsselt (`notes/chats.md`). `body` ist
|
||||||
|
die binäre OpenPGP-Nachricht in Base64; der Server sieht den Inhalt nicht.
|
||||||
|
|
||||||
|
| Methode | Pfad | Auth | Request | Erfolg |
|
||||||
|
|---------|------|------|---------|--------|
|
||||||
|
| GET | `/api/chats` | ✓ | – | `200 {"chats":[{"username","avatar","last_at","unread"}]}`, jüngstes Gespräch zuerst |
|
||||||
|
| GET | `/api/chats/{username}` | ✓ | `?after=id` (optional) | `200 {"messages":[{"id","mine","body","created_at"}]}`, älteste zuerst; die abgerufenen Nachrichten an einen gelten als gelesen |
|
||||||
|
| POST | `/api/chats/{username}` | ✓ | `body` (Base64) | `201` Nachricht. Mit sich selbst: `400 chat.self`; kein OpenPGP-Chiffrat: `400 chat.body`; zu groß (> 64 KiB): `413 chat.too_large`; einer ohne aktuellen Schlüssel: `409 chat.no_key`; unbekannt: `404` |
|
||||||
|
|
||||||
|
Nachrichten älter als 15 Tage liefert der Server nicht mehr aus und löscht
|
||||||
|
sie stündlich. Senden ist gedrosselt (60/min pro IP).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Statistik
|
## Statistik
|
||||||
|
|
||||||
| Methode | Pfad | Erfolg |
|
| Methode | Pfad | Erfolg |
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
# Direktnachrichten (Chats)
|
||||||
|
|
||||||
|
Stand 2026-10-13: erste Version umgesetzt. Gespräche zu zweit, nur Text,
|
||||||
|
Ende-zu-Ende verschlüsselt mit den Schlüsseln aus `notes/schluessel.md`.
|
||||||
|
|
||||||
|
Ziel: Der Betreiber soll nicht wissen können, was in den Chats steht. Der
|
||||||
|
Client muss dafür nicht streng geschützt werden -- gegen eine übernommene
|
||||||
|
Session oder einen gehackten Server (der das JavaScript ausliefert) hilft
|
||||||
|
die Web-Version ohnehin nicht.
|
||||||
|
|
||||||
|
## Ablauf
|
||||||
|
|
||||||
|
- **Ansprechen:** Auf dem Profil steht „Ansprechen“, wenn beide einen
|
||||||
|
aktuellen Schlüssel haben. Wer selbst keinen hat, sieht den Knopf nicht.
|
||||||
|
Er führt zu `/chats/{username}`.
|
||||||
|
- **Entsperren:** Beim ersten Öffnen eines Gesprächs im Tab fragt die Seite
|
||||||
|
die Passphrase ab. Der Schlüsselbund (`frontend/src/keyring.ts`) holt alle
|
||||||
|
eigenen privaten Schlüssel (`/user/keys/secret`) und entsperrt die, die zur
|
||||||
|
Passphrase passen; er bleibt im Speicher, bis der Tab neu geladen wird.
|
||||||
|
Neuer Schlüssel oder „als verloren markieren“ sperren ihn wieder.
|
||||||
|
- **Senden:** OpenPGP-Nachricht an den Schlüssel des Empfängers und an den
|
||||||
|
eigenen (damit man die eigenen Nachrichten wieder lesen kann), signiert
|
||||||
|
mit dem eigenen aktuellen Schlüssel (`encryptMessage` in `keystore.ts`).
|
||||||
|
- **Lesen:** Entschlüsseln mit allen entsperrten eigenen Schlüsseln, die
|
||||||
|
Signatur prüfen gegen die aktuellen Schlüssel von Absender und Empfänger.
|
||||||
|
Passt sie nicht (etwa weil der Absender inzwischen einen neuen Schlüssel
|
||||||
|
hat), steht „Signatur nicht prüfbar“ daneben; passt kein eigener
|
||||||
|
Schlüssel, „[nicht lesbar]“.
|
||||||
|
- **Neue Nachrichten:** Das offene Gespräch fragt alle 5 Sekunden nach
|
||||||
|
Nachrichten nach der letzten bekannten, die Übersicht alle 30 Sekunden.
|
||||||
|
Abgerufene Nachrichten an einen gelten als gelesen.
|
||||||
|
- **Ablauf:** Der Server liefert Nachrichten nach 15 Tagen nicht mehr aus
|
||||||
|
und löscht sie stündlich (`internal/chat`, `chat.Retention`). Konto
|
||||||
|
löschen nimmt alle Nachrichten von und an das Konto mit.
|
||||||
|
|
||||||
|
Signiert wird, damit der Server keine Nachrichten im Namen anderer
|
||||||
|
einschleusen kann. Der Preis -- ein Empfänger könnte belegen, dass eine
|
||||||
|
Nachricht vom Schlüssel des Absenders stammt -- ist klein, weil der
|
||||||
|
Schlüssel keine Identität trägt und nur über unseren Server einem Konto
|
||||||
|
zugeordnet ist. Wirklich schützt das erst, wenn Fingerprints verglichen
|
||||||
|
werden; der Chat zeigt den des Gegenübers dafür an.
|
||||||
|
|
||||||
|
## Server
|
||||||
|
|
||||||
|
Tabelle `message` (`schema.sql`): `sender`, `recipient`, `body` (binäre
|
||||||
|
OpenPGP-Nachricht), `created_at`, `read_at`. Der Server sieht, wer wann wem
|
||||||
|
wie viel schreibt, nicht den Inhalt. Er prüft nur, dass `body` mit einem
|
||||||
|
verschlüsselten Sitzungsschlüssel beginnt (`pgpkey.CheckMessage`,
|
||||||
|
höchstens 64 KiB) und dass beide einen aktuellen Schlüssel haben.
|
||||||
|
|
||||||
|
API in `notes/api.md` (Abschnitt „Chats“). Senden ist gedrosselt (60/min
|
||||||
|
pro IP).
|
||||||
|
|
||||||
|
## Später
|
||||||
|
|
||||||
|
- Blockieren, „Gespräch für mich löschen“
|
||||||
|
- Zähler ungelesener Nachrichten in der Navigation, Benachrichtigungen
|
||||||
|
- Fingerprint des Gegenübers als „verifiziert“ merken und bei einem
|
||||||
|
Wechsel deutlich warnen
|
||||||
|
- Signaturen älterer Nachrichten nach einem Schlüsselwechsel prüfbar halten
|
||||||
|
(dafür bräuchte der Client die früheren öffentlichen Schlüssel)
|
||||||
|
- Entsperrt bleiben über das Neuladen hinaus (`sessionStorage`)
|
||||||
|
- Bilder und Anhänge, Gruppen
|
||||||
+4
-3
@@ -49,13 +49,14 @@ githooks` läuft das nach jedem Commit automatisch im Hintergrund (Log:
|
|||||||
| `src/Layout.tsx` | Seitenrahmen: Kopf (mobil mit Menü und Einstellungen), Schublade |
|
| `src/Layout.tsx` | Seitenrahmen: Kopf (mobil mit Menü und Einstellungen), Schublade |
|
||||||
| `src/Nav.tsx` | Seitenleiste (alle Ziele) und mobile TabBar (fünf wichtigste); Icons von lucide-react, die Rechtstexte ohne Icon |
|
| `src/Nav.tsx` | Seitenleiste (alle Ziele) und mobile TabBar (fünf wichtigste); Icons von lucide-react, die Rechtstexte ohne Icon |
|
||||||
| `src/docs/*.html` | Rechtstexte (Impressum, Datenschutz, Beitragsordnung) |
|
| `src/docs/*.html` | Rechtstexte (Impressum, Datenschutz, Beitragsordnung) |
|
||||||
| `src/pages/*` | Startseite, Thread, Profil (Header, Beschreibung, Bearbeiten für den Eigentümer), Einstellungen (Name, Passwort, Konto löschen), Statistik, Rechtstexte (`DocPage.tsx`); `Placeholder.tsx` für Suche, Benachrichtigungen, Chats und die Profil-Weiche `/me` |
|
| `src/pages/*` | Startseite, Thread, Profil (Header, Beschreibung, Bearbeiten für den Eigentümer), Einstellungen (Name, Passwort, Konto löschen), Statistik, Rechtstexte (`DocPage.tsx`); `ChatsPage.tsx` (Chats, `notes/chats.md`); `Placeholder.tsx` für Suche, Benachrichtigungen und die Profil-Weiche `/me` |
|
||||||
| `src/theme.ts` | Darstellung hell/dunkel (experimentell) |
|
| `src/theme.ts` | Darstellung hell/dunkel (experimentell) |
|
||||||
| `src/useFormAction.ts` | Formular-POST mit Fehlermeldung (Profil, Einstellungen) |
|
| `src/useFormAction.ts` | Formular-POST mit Fehlermeldung (Profil, Einstellungen) |
|
||||||
| `src/components/*` | Feed, Beitragskarte, Votes, Repost, Login, Beitrag verfassen |
|
| `src/components/*` | Feed, Beitragskarte, Votes, Repost, Login, Beitrag verfassen |
|
||||||
|
|
||||||
Seitenrouten des Clients (`/`, `/e/:pid`, `/u/:username`, `/stats`, `/reset`,
|
Seitenrouten des Clients (`/`, `/e/:pid`, `/u/:username`, `/stats`, `/reset`,
|
||||||
`/me`, `/search`, `/notifications`, `/chats`, `/settings`, `/info`, `/impressum`,
|
`/me`, `/search`, `/notifications`, `/chats`, `/chats/:username`, `/settings`,
|
||||||
|
`/settings/keys`, `/info`, `/impressum`,
|
||||||
`/datenschutz`, `/beitragsordnung`) müssen
|
`/datenschutz`, `/beitragsordnung`) müssen
|
||||||
auch in `pageRoutes()` (`internal/httpapi/server.go`) stehen, sonst liefert ein direkter Aufruf 404.
|
auch in `pageRoutes()` (`internal/httpapi/server.go`) stehen, sonst liefert ein direkter Aufruf 404.
|
||||||
|
|
||||||
@@ -76,7 +77,7 @@ Ab 900 px Fensterbreite steht links die Seitenleiste mit allen Zielen (Icon +
|
|||||||
Titel); der Menüknopf oben links klappt sie ein und aus, der Zustand liegt im
|
Titel); der Menüknopf oben links klappt sie ein und aus, der Zustand liegt im
|
||||||
`localStorage` (`kver.navCollapsed`). Darunter: Kopfleiste mit Menü, Titel und Einstellungsrad, unten die
|
`localStorage` (`kver.navCollapsed`). Darunter: Kopfleiste mit Menü, Titel und Einstellungsrad, unten die
|
||||||
TabBar mit Feed, Suche, Benachrichtigungen, Chats und Profil; das Menü blendet
|
TabBar mit Feed, Suche, Benachrichtigungen, Chats und Profil; das Menü blendet
|
||||||
die Seitenleiste als Schublade ein. Suche, Benachrichtigungen und Chats sind
|
die Seitenleiste als Schublade ein. Suche und Benachrichtigungen sind
|
||||||
noch Platzhalter und deshalb ausgeblendet (`unfinished` in
|
noch Platzhalter und deshalb ausgeblendet (`unfinished` in
|
||||||
`src/Nav.tsx`); ihre Routen bestehen weiter. Umgeschaltet wird per CSS
|
`src/Nav.tsx`); ihre Routen bestehen weiter. Umgeschaltet wird per CSS
|
||||||
(`app.css`, Abschnitt Navigation); nur der Menüknopf fragt die Breite ab.
|
(`app.css`, Abschnitt Navigation); nur der Menüknopf fragt die Breite ab.
|
||||||
|
|||||||
Reference in New Issue
Block a user