Compare commits
64
Commits
4a9f59bf3f
...
master
@@ -7,7 +7,10 @@ Forum: Go-Backend (`cmd/kver`, `internal/`, Postgres), React-Frontend in
|
||||
## Arbeitsablauf nach jeder Änderung
|
||||
|
||||
1. **Prüfen**: `go build ./... && go test ./...` bzw. `npm run build` in
|
||||
`frontend/`; sichtbare Änderungen im Browser ansehen.
|
||||
`frontend/`; sichtbare Änderungen im Browser ansehen. Die DB-Tests
|
||||
brauchen `KVER_TEST_DSN` aus `dev.env` (`set -a; . ./dev.env; set +a`),
|
||||
sonst werden sie still übersprungen. Nach Änderungen an `go.mod` oder
|
||||
`package.json`: `govulncheck ./...` (`~/go/bin`) und `npm audit`.
|
||||
2. **Changelog**: Ist die Änderung für Nutzende sichtbar, im selben Commit
|
||||
einen kurzen Stichpunkt eintragen:
|
||||
`./changelog.sh 'Stichpunkt'` (HTML erlaubt, z. B. `<kbd>Esc</kbd>`). Das
|
||||
@@ -17,10 +20,8 @@ Forum: Go-Backend (`cmd/kver`, `internal/`, Postgres), React-Frontend in
|
||||
3. **Committen**: ohne Rückfrage, sobald eine Änderung abgeschlossen und
|
||||
geprüft ist. Nachricht auf Deutsch, Muster `Bereich: was sich ändert`,
|
||||
Rumpf mit dem Warum. Zusammengehöriges in einen Commit.
|
||||
4. **DEV**: aktualisiert sich selbst -- `githooks/post-commit` startet
|
||||
`./dev-up.sh` im Hintergrund (Log `.git/dev-up.log`, fertig bei
|
||||
`== läuft: http://127.0.0.1:8081`). Danach kurz prüfen, dass DEV läuft
|
||||
und die Änderung ausliefert.
|
||||
4. **DEV**: aktualisiert sich nicht automatisch. `./dev-up.sh` baut den
|
||||
Container `kver-dev` von Hand neu (http://127.0.0.1:8081).
|
||||
5. **Nicht pushen**, außer auf ausdrückliche Anweisung.
|
||||
|
||||
Die Git-Hooks liegen in `githooks/` (`git config core.hooksPath githooks`).
|
||||
|
||||
+191
-9
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -20,6 +21,7 @@ type cmdEnv struct {
|
||||
db *sql.DB
|
||||
log *slog.Logger
|
||||
baseURL string
|
||||
media media.Store
|
||||
}
|
||||
|
||||
// runCommand führt einen Admin-Unterbefehl aus (kver <befehl> ...). Im
|
||||
@@ -28,43 +30,79 @@ func runCommand(ctx context.Context, env cmdEnv, args []string) error {
|
||||
switch args[0] {
|
||||
case "reset-link":
|
||||
if len(args) != 2 {
|
||||
return errors.New("Verwendung: kver reset-link <nutzername>")
|
||||
return errors.New("Verwendung: kver reset-link <handle>")
|
||||
}
|
||||
return cmdResetLink(ctx, env, args[1])
|
||||
case "handles":
|
||||
if len(args) != 1 {
|
||||
return errors.New("Verwendung: kver handles")
|
||||
}
|
||||
return cmdHandles(ctx, env)
|
||||
case "link-previews":
|
||||
if len(args) != 1 {
|
||||
return errors.New("Verwendung: kver link-previews")
|
||||
}
|
||||
return cmdLinkPreviews(ctx, env)
|
||||
case "reports":
|
||||
if len(args) != 1 {
|
||||
return errors.New("Verwendung: kver reports")
|
||||
}
|
||||
return cmdReports(ctx, env)
|
||||
case "cover-image":
|
||||
if len(args) != 3 || strings.TrimSpace(args[2]) == "" {
|
||||
return errors.New("Verwendung: kver cover-image <pid> <hinweis>")
|
||||
}
|
||||
return cmdCoverImage(ctx, env, args[1], strings.TrimSpace(args[2]))
|
||||
case "uncover-image":
|
||||
if len(args) != 2 {
|
||||
return errors.New("Verwendung: kver uncover-image <pid>")
|
||||
}
|
||||
return cmdUncoverImage(ctx, env, args[1])
|
||||
default:
|
||||
return fmt.Errorf("unbekannter Befehl %q (bekannt: reset-link, link-previews)", args[0])
|
||||
return fmt.Errorf("unbekannter Befehl %q (bekannt: reset-link, handles, link-previews, reports, cover-image, uncover-image)", args[0])
|
||||
}
|
||||
}
|
||||
|
||||
// cmdResetLink erzeugt einen Passwort-Reset-Link und gibt ihn aus.
|
||||
// KVER_BASE_URL (z. B. https://example.org) macht daraus einen fertigen Link;
|
||||
// ohne steht nur der Pfad da.
|
||||
func cmdResetLink(ctx context.Context, env cmdEnv, username string) error {
|
||||
username = account.SanitizeUsername(username)
|
||||
token, expires, err := account.NewStore(env.db, time.Now).CreateResetToken(ctx, username)
|
||||
func cmdResetLink(ctx context.Context, env cmdEnv, handle string) error {
|
||||
handle = account.NormalizeHandle(handle)
|
||||
token, expires, err := account.NewStore(env.db, time.Now).CreateResetToken(ctx, handle)
|
||||
if errors.Is(err, account.ErrUserNotFound) {
|
||||
return fmt.Errorf("Nutzer %q nicht gefunden", username)
|
||||
return fmt.Errorf("Nutzer @%s nicht gefunden", handle)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
base := strings.TrimSuffix(env.baseURL, "/")
|
||||
fmt.Printf("Reset-Link für %s (gültig bis %s, einmalig):\n\n %s/reset#%s\n\n",
|
||||
username, expires.Format("02.01.2006 15:04 MST"), base, token)
|
||||
fmt.Printf("Reset-Link für @%s (gültig bis %s, einmalig):\n\n %s/reset#%s\n\n",
|
||||
handle, expires.Format("02.01.2006 15:04 MST"), base, token)
|
||||
fmt.Println("Ältere Reset-Links dieses Nutzers sind damit ungültig.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// cmdHandles listet die Konten, deren Handle seit der Trennung von Handle und
|
||||
// Anzeigename anders lautet als ihr alter Nutzername: Sie melden sich damit
|
||||
// an und sollten Bescheid bekommen. Groß-/Kleinschreibung zählt nicht, die
|
||||
// ignoriert der Login.
|
||||
func cmdHandles(ctx context.Context, env cmdEnv) error {
|
||||
changes, err := account.NewStore(env.db, time.Now).HandleChanges(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range changes {
|
||||
fmt.Printf("%s -> @%s\n", c.LegacyName, c.Handle)
|
||||
}
|
||||
fmt.Printf("%d Konten mit neuem Handle.\n", len(changes))
|
||||
return nil
|
||||
}
|
||||
|
||||
// cmdLinkPreviews trägt bei bestehenden Beiträgen den ersten Link nach und
|
||||
// holt alle offenen Vorschauen nacheinander. Läuft der Server parallel, holt
|
||||
// er höchstens dieselben Links noch einmal -- harmlos.
|
||||
func cmdLinkPreviews(ctx context.Context, env cmdEnv) error {
|
||||
previews := linkpreview.New(linkpreview.Config{DB: env.db, Log: env.log, Now: time.Now, Media: media.Store{}})
|
||||
previews := linkpreview.New(linkpreview.Config{DB: env.db, Log: env.log, Now: time.Now, Media: env.media})
|
||||
n, err := previews.Backfill(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -86,3 +124,147 @@ func cmdLinkPreviews(ctx context.Context, env cmdEnv) error {
|
||||
fmt.Printf("Vorschauen: %d fertig, %d ohne Vorschau.\n", ok, none)
|
||||
return nil
|
||||
}
|
||||
|
||||
// cmdReports listet die offenen Meldungen, gruppiert nach Beitrag: zuerst der
|
||||
// Beitrag mit Autor und Inhalt, darunter jede Meldung mit Melder und Grund.
|
||||
// Beiträge erscheinen in der Reihenfolge ihrer ersten Meldung. Nur per CLI,
|
||||
// damit es keine Admin-Rolle und keine weitere Web-Route braucht.
|
||||
func cmdReports(ctx context.Context, env cmdEnv) error {
|
||||
rows, err := env.db.QueryContext(ctx,
|
||||
`SELECT r.pid, r.created_at, COALESCE(m.handle, ''), r.reason,
|
||||
e.pid IS NOT NULL, COALESCE(a.handle, ''), COALESCE(e.content, ''),
|
||||
COALESCE(e.filepath, ''), COALESCE(e.deleted, 0)
|
||||
FROM report r
|
||||
LEFT JOIN entry e ON e.pid = r.pid
|
||||
LEFT JOIN account a ON a.uid = e.uid
|
||||
LEFT JOIN account m ON m.uid = r.uid AND r.uid <> 0
|
||||
WHERE r.handled = 0
|
||||
ORDER BY MIN(r.created_at) OVER (PARTITION BY r.pid), r.pid, r.created_at`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
base := strings.TrimSuffix(env.baseURL, "/")
|
||||
const day = "02.01.2006 15:04"
|
||||
var (
|
||||
lastPID int64 = -1
|
||||
posts, count int
|
||||
)
|
||||
for rows.Next() {
|
||||
var (
|
||||
pid, at, deleted int64
|
||||
reporter, reason, author, content string
|
||||
filepath string
|
||||
found bool
|
||||
)
|
||||
if err := rows.Scan(&pid, &at, &reporter, &reason, &found, &author, &content, &filepath, &deleted); err != nil {
|
||||
return err
|
||||
}
|
||||
if pid != lastPID {
|
||||
lastPID = pid
|
||||
posts++
|
||||
fmt.Printf("\n== %s/e/%d", base, pid)
|
||||
switch {
|
||||
case !found:
|
||||
fmt.Print(" (Beitrag existiert nicht)")
|
||||
case deleted != 0:
|
||||
fmt.Print(" (gelöscht)")
|
||||
}
|
||||
fmt.Println()
|
||||
if found {
|
||||
fmt.Printf("von @%s\n", author)
|
||||
if filepath != "" {
|
||||
fmt.Printf("Datei: %s/%s\n", base, filepath)
|
||||
}
|
||||
fmt.Printf("%s\n", indent(content))
|
||||
}
|
||||
}
|
||||
count++
|
||||
if reporter == "" {
|
||||
reporter = "anonym"
|
||||
} else {
|
||||
reporter = "@" + reporter
|
||||
}
|
||||
if reason == "" {
|
||||
reason = "(ohne Grund)"
|
||||
}
|
||||
fmt.Printf(" Meldung %s von %s: %s\n", time.Unix(at, 0).Format(day), reporter, reason)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("\n%d offene Meldungen zu %d Beiträgen.\n", count, posts)
|
||||
return nil
|
||||
}
|
||||
|
||||
// indent rückt jede Zeile ein, damit mehrzeilige Beiträge als Block lesbar
|
||||
// bleiben.
|
||||
func indent(s string) string {
|
||||
return " | " + strings.ReplaceAll(s, "\n", "\n | ")
|
||||
}
|
||||
|
||||
// cmdCoverImage legt einen Hinweis vor das Bild eines Beitrags: Angezeigt wird
|
||||
// dann eine verpixelte Variante mit dem Hinweis, das Bild erst auf Klick.
|
||||
// Steht schon ein Hinweis davor, ändert sich nur der Text.
|
||||
func cmdCoverImage(ctx context.Context, env cmdEnv, arg, warning string) error {
|
||||
pid, err := strconv.ParseInt(arg, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ungültige pid %q", arg)
|
||||
}
|
||||
var file, cover string
|
||||
var deleted int64
|
||||
err = env.db.QueryRowContext(ctx,
|
||||
`SELECT filepath, image_cover, deleted FROM entry WHERE pid = $1`, pid).Scan(&file, &cover, &deleted)
|
||||
switch {
|
||||
case errors.Is(err, sql.ErrNoRows) || err == nil && deleted != 0:
|
||||
return fmt.Errorf("Beitrag %d nicht gefunden", pid)
|
||||
case err != nil:
|
||||
return err
|
||||
case file == "":
|
||||
return fmt.Errorf("Beitrag %d hat kein Bild", pid)
|
||||
}
|
||||
created := ""
|
||||
if cover == "" {
|
||||
if cover, err = env.media.SaveCover(file); err != nil {
|
||||
return err
|
||||
}
|
||||
created = cover
|
||||
}
|
||||
if _, err := env.db.ExecContext(ctx,
|
||||
`UPDATE entry SET image_warning = $1, image_cover = $2 WHERE pid = $3`, warning, cover, pid); err != nil {
|
||||
_ = env.media.Remove(created)
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Hinweis vor dem Bild von Beitrag %d: %s\n", pid, warning)
|
||||
return nil
|
||||
}
|
||||
|
||||
// cmdUncoverImage nimmt den Hinweis wieder weg und löscht die verpixelte
|
||||
// Variante.
|
||||
func cmdUncoverImage(ctx context.Context, env cmdEnv, arg string) error {
|
||||
pid, err := strconv.ParseInt(arg, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("ungültige pid %q", arg)
|
||||
}
|
||||
var cover string
|
||||
err = env.db.QueryRowContext(ctx,
|
||||
`UPDATE entry e SET image_warning = '', image_cover = ''
|
||||
FROM entry old WHERE e.pid = $1 AND old.pid = e.pid
|
||||
RETURNING old.image_cover`, pid).Scan(&cover)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("Beitrag %d nicht gefunden", pid)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cover == "" {
|
||||
fmt.Printf("Vor dem Bild von Beitrag %d stand kein Hinweis.\n", pid)
|
||||
return nil
|
||||
}
|
||||
if err := env.media.Remove(cover); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Hinweis vor dem Bild von Beitrag %d entfernt.\n", pid)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"kver/internal/media"
|
||||
"kver/internal/testdb"
|
||||
)
|
||||
|
||||
func TestCmdReports(t *testing.T) {
|
||||
db := testdb.New(t)
|
||||
for _, q := range []string{
|
||||
`INSERT INTO account (uid, handle, password, created_at) VALUES (1, 'autor', '', 0), (2, 'melder', '', 0)`,
|
||||
`INSERT INTO entry (pid, uid, created_at, content) VALUES (10, 1, 0, 'Zeile eins
|
||||
Zeile zwei')`,
|
||||
`INSERT INTO entry (pid, uid, created_at, content, deleted) VALUES (20, 1, 0, 'weg', 1)`,
|
||||
`INSERT INTO report (pid, uid, reason, created_at) VALUES
|
||||
(20, 2, 'spät', 300), (10, 2, 'Spam', 100), (10, 0, '', 200), (99, 0, 'x', 400)`,
|
||||
`INSERT INTO report (pid, uid, reason, created_at, handled) VALUES (10, 2, 'erledigt', 50, 1)`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
stdout := os.Stdout
|
||||
os.Stdout = w
|
||||
err = cmdReports(context.Background(), cmdEnv{db: db, log: slog.Default(), baseURL: "https://x.test/"})
|
||||
os.Stdout = stdout
|
||||
w.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, _ := io.ReadAll(r)
|
||||
got := string(out)
|
||||
|
||||
for _, want := range []string{
|
||||
"== https://x.test/e/10\nvon @autor\n | Zeile eins\n | Zeile zwei\n",
|
||||
"von @melder: Spam\n",
|
||||
"von anonym: (ohne Grund)\n",
|
||||
"== https://x.test/e/20 (gelöscht)\n",
|
||||
"== https://x.test/e/99 (Beitrag existiert nicht)\n",
|
||||
"4 offene Meldungen zu 3 Beiträgen.",
|
||||
} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("Ausgabe enthält nicht %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
if strings.Contains(got, "erledigt") {
|
||||
t.Errorf("erledigte Meldung gelistet:\n%s", got)
|
||||
}
|
||||
if i, j := strings.Index(got, "/e/10"), strings.Index(got, "/e/20"); i > j {
|
||||
t.Errorf("Beiträge nicht nach erster Meldung sortiert:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCmdCoverImage(t *testing.T) {
|
||||
db := testdb.New(t)
|
||||
root := t.TempDir()
|
||||
store := media.Store{Root: root}
|
||||
if err := os.MkdirAll(filepath.Join(root, media.Dir), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 64, 32))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := media.Dir + "/bild.png"
|
||||
if err := os.WriteFile(filepath.Join(root, src), buf.Bytes(), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Exec(`INSERT INTO entry (pid, uid, created_at, filepath) VALUES (10, 1, 0, $1), (20, 1, 0, '')`, src); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
env := cmdEnv{db: db, log: slog.Default(), media: store}
|
||||
ctx := context.Background()
|
||||
state := func() (warning, cover string) {
|
||||
t.Helper()
|
||||
if err := db.QueryRow(`SELECT image_warning, image_cover FROM entry WHERE pid = 10`).Scan(&warning, &cover); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return warning, cover
|
||||
}
|
||||
|
||||
if err := cmdCoverImage(ctx, env, "10", "Hinweis"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
warning, cover := state()
|
||||
if warning != "Hinweis" || cover == "" {
|
||||
t.Fatalf("nach cover-image: %q, %q", warning, cover)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, cover)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Erneut: nur der Text ändert sich, die Variante bleibt.
|
||||
if err := cmdCoverImage(ctx, env, "10", "Anderer Hinweis"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, c := state(); w != "Anderer Hinweis" || c != cover {
|
||||
t.Errorf("nach zweitem cover-image: %q, %q", w, c)
|
||||
}
|
||||
|
||||
if err := cmdCoverImage(ctx, env, "20", "x"); err == nil {
|
||||
t.Error("Beitrag ohne Bild angenommen")
|
||||
}
|
||||
if err := cmdCoverImage(ctx, env, "99", "x"); err == nil {
|
||||
t.Error("fehlender Beitrag angenommen")
|
||||
}
|
||||
|
||||
if err := cmdUncoverImage(ctx, env, "10"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w, c := state(); w != "" || c != "" {
|
||||
t.Errorf("nach uncover-image: %q, %q", w, c)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, cover)); !os.IsNotExist(err) {
|
||||
t.Errorf("verpixelte Variante noch da: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/oschwald/maxminddb-golang"
|
||||
|
||||
"kver/internal/charts"
|
||||
"kver/internal/chat"
|
||||
"kver/internal/database"
|
||||
"kver/internal/httpapi"
|
||||
"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}),
|
||||
Charts: charts.New(db, 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
|
||||
// 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.Charts.Run(ctx) })
|
||||
wg.Go(func() { d.Impressions.Run(ctx) })
|
||||
wg.Go(func() { d.Chats.Run(ctx) })
|
||||
return func() {
|
||||
cancel()
|
||||
wg.Wait()
|
||||
|
||||
@@ -1,69 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# dev-up.sh — baut das Image aus dem aktuellen Arbeitsverzeichnis neu und
|
||||
# startet den lokalen DEV-Container (kver-dev) damit neu.
|
||||
# dev-up.sh — baut das Image aus dem Arbeitsverzeichnis und startet den
|
||||
# DEV-Container kver-dev auf http://127.0.0.1:8081 neu.
|
||||
#
|
||||
# Verwendung:
|
||||
# ./dev-up.sh
|
||||
# Postgres läuft auf dem Host: localhost im DSN wird zu host.containers.internal,
|
||||
# und pasta leitet diese Adresse (169.254.1.2) auf das Host-Loopback.
|
||||
#
|
||||
# Läuft auch automatisch nach jedem Commit (githooks/post-commit, im
|
||||
# Hintergrund, Log in .git/dev-up.log). Einrichten einmalig per:
|
||||
# git config core.hooksPath githooks
|
||||
#
|
||||
# Voraussetzungen:
|
||||
# - dev.env mit KVER_DSN (Host "localhost" wird für den Container auf
|
||||
# host.containers.internal umgeschrieben)
|
||||
# - Daten/Medien aus dem PROD-Dump unter $KVER_DEV_DATA (read-only gemountet)
|
||||
#
|
||||
set -euo pipefail
|
||||
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
NAME=kver-dev
|
||||
IMAGE=localhost/kver:dev
|
||||
PORT="${KVER_DEV_PORT:-8081}"
|
||||
DATA="${KVER_DEV_DATA:-./prod_backup/2026-09-26}"
|
||||
podman build -t localhost/kver:dev .
|
||||
|
||||
# Nur ein Lauf gleichzeitig (schnell aufeinanderfolgende Commits). podman
|
||||
# bekommt fd 9 jeweils nicht mit (9>&-): conmon lebt so lange wie der
|
||||
# Container und würde den Lock sonst für immer halten.
|
||||
exec 9>.git/dev-up.lock
|
||||
flock 9
|
||||
podman rm -f kver-dev
|
||||
|
||||
DSN="$(grep '^KVER_DSN=' dev.env | cut -d= -f2- | sed 's/@localhost:/@host.containers.internal:/')"
|
||||
if [[ -z "$DSN" ]]; then
|
||||
echo "FEHLER: KVER_DSN fehlt in dev.env." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "== $(date '+%F %T') Baue $IMAGE ($(git rev-parse --short HEAD))"
|
||||
podman build -q -t "$IMAGE" . 9>&-
|
||||
|
||||
mounts=()
|
||||
[[ -d "$DATA/data" ]] && mounts+=(-v "$DATA/data:/app/data:ro" -e KVER_GEOIP_ASN=/app/data/GeoLite2-ASN.mmdb)
|
||||
if [[ -d "$DATA/media" ]]; then
|
||||
mounts+=(-v "$DATA/media:/app/static/media:ro")
|
||||
# Linkvorschau-Bilder schreibt der Server selbst: beschreibbares Volume über
|
||||
# dem read-only Media-Mount. Der Mountpunkt muss im Quellverzeichnis
|
||||
# existieren, weil der Container ihn im read-only Mount nicht anlegen kann.
|
||||
mkdir -p "$DATA/media/preview"
|
||||
mounts+=(-v kver-dev-preview:/app/static/media/preview:U)
|
||||
fi
|
||||
|
||||
podman rm -f "$NAME" >/dev/null 2>&1 9>&- || true
|
||||
podman run -d --name "$NAME" -p "127.0.0.1:$PORT:8080" \
|
||||
-e KVER_DSN="$DSN" \
|
||||
"${mounts[@]}" \
|
||||
--security-opt label=disable "$IMAGE" >/dev/null 9>&-
|
||||
|
||||
# Warten, bis die API antwortet.
|
||||
for _ in $(seq 30); do
|
||||
if curl -fs -o /dev/null "http://127.0.0.1:$PORT/api/stats"; then
|
||||
echo "== läuft: http://127.0.0.1:$PORT"
|
||||
exit 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
echo "FEHLER: $NAME antwortet nicht. Log:" >&2
|
||||
podman logs --tail 20 "$NAME" >&2
|
||||
exit 1
|
||||
podman run -d --name kver-dev -p 127.0.0.1:8081:8080 \
|
||||
--network pasta:--map-host-loopback,169.254.1.2 \
|
||||
-e KVER_DSN="$(grep '^KVER_DSN=' dev.env | cut -d= -f2- | sed 's/@localhost:/@host.containers.internal:/')" \
|
||||
-v ./prod_backup/2026-10-30/media:/app/static/media:ro \
|
||||
-v kver-dev-preview:/app/static/media/preview:U \
|
||||
--security-opt label=disable \
|
||||
localhost/kver:dev
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Kontrollverlust</title>
|
||||
<link rel="icon" type="image/png" href="/static/assets/k_black_bg.png">
|
||||
<link rel="apple-touch-icon" href="/static/assets/k_black_bg.png">
|
||||
</head>
|
||||
<body>
|
||||
<noscript>
|
||||
|
||||
Generated
+256
-119
@@ -8,6 +8,7 @@
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.104.0",
|
||||
"lucide-react": "1.48.0",
|
||||
"openpgp": "^6.3.2",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router": "^8.4.0"
|
||||
@@ -21,10 +22,66 @@
|
||||
"vite": "^8.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "2.0.0-beta.2",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-2.0.0-beta.2.tgz",
|
||||
"integrity": "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/wasi-threads": "2.2.0",
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/runtime": {
|
||||
"version": "2.0.0-beta.2",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-2.0.0-beta.2.tgz",
|
||||
"integrity": "sha512-JcrSPzPvZuNZvJqPTF9Fw25LbOJ8avzFVlaf2grmH4Cku0oGP47tRgqPZadcfj3YoZMHkFVnCYFbQM8I+i5QEw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/wasi-threads": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-2.2.0.tgz",
|
||||
"integrity": "sha512-JP7OYH38Q7+pyTAe14raZHLQIK7BDKbdwji+Xi3pcd/6QkJYQH3SX4wu6EplGrGJWRepoNzedfm0G3B9Z4e9Rw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@napi-rs/wasm-runtime": {
|
||||
"version": "1.2.6",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz",
|
||||
"integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@tybys/wasm-util": "^0.10.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/Brooooooklyn"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@emnapi/core": "^1.7.1 || 2.0.0-beta.2",
|
||||
"@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2"
|
||||
}
|
||||
},
|
||||
"node_modules/@oxc-project/types": {
|
||||
"version": "0.151.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.151.0.tgz",
|
||||
"integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==",
|
||||
"version": "0.156.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.156.0.tgz",
|
||||
"integrity": "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
@@ -38,9 +95,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm-eabi": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.11.tgz",
|
||||
"integrity": "sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.19.tgz",
|
||||
"integrity": "sha512-e+Ebe0WT+9tbXmNKPIiC8YrWAHYwug3m6i4p3rZGGulfZri1jtI4HslT+OZnFf/OIHowWF71DTlHwXBP2SiA7A==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -55,9 +112,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-android-arm64": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.11.tgz",
|
||||
"integrity": "sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.19.tgz",
|
||||
"integrity": "sha512-hOombrTJ+szt2ciEzS7oCA78lMPBgF5UMQWCJIyNfnrI7GLl8HYoFqCnpL2gcPOaXMqryGCU5ExdQKyDDcC+yA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -72,9 +129,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-arm64": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.11.tgz",
|
||||
"integrity": "sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.19.tgz",
|
||||
"integrity": "sha512-XoMA2pwCKGTQzUjPgtRwkedH4WmXhdIPKT6l6oOxd1PUbNodGI6DcBekgN7EC//+x3pfBYX/qL1gNmZAqivw5g==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -89,9 +146,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-darwin-x64": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.11.tgz",
|
||||
"integrity": "sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.19.tgz",
|
||||
"integrity": "sha512-zo8EsSSwMZCY/e+fRnGaX02YGgvJD0yvhNi/9hpGPA2MJ9ZF8dPCw75UGfpI6OpQ/myR/dIYmogRvqiZD0TrXg==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -106,9 +163,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-freebsd-x64": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.11.tgz",
|
||||
"integrity": "sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.19.tgz",
|
||||
"integrity": "sha512-O8ISAOfI1nj7AuBPd30FSF47z7f7lzlk5poQVGgiikvQuGEBFYvW8ki+UEnT+YJPnNGjQzn304klt4O9FUE7mA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -123,9 +180,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm-gnueabihf": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.11.tgz",
|
||||
"integrity": "sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.19.tgz",
|
||||
"integrity": "sha512-/lYCba5NO0yq4S0jGMH8QTBtkvQxoXjoQWzF5BcWp9MjB9jxVRD1GQDNofkVjcOj30DWyhLIN/4Oe60JKzaONw==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -140,9 +197,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-gnu": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.11.tgz",
|
||||
"integrity": "sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.19.tgz",
|
||||
"integrity": "sha512-pm/apFMBnSbFb3O6nG5pHO1iqHhZrjGDFEjSm+ot9J17XXPvH9L90y5h+jgfHCE+Qdlsvy8qKEcU4VKxgjD+vA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -160,9 +217,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-arm64-musl": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.11.tgz",
|
||||
"integrity": "sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.19.tgz",
|
||||
"integrity": "sha512-K1SmQp3FFichn8oqrNIwvFoZ5wcvjC7goBzpaMNvLf9FZc+QB/QvLmnpJZgAAGHiD980tP8FZZnXk2K94rvlxg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -180,9 +237,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-ppc64-gnu": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.11.tgz",
|
||||
"integrity": "sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.19.tgz",
|
||||
"integrity": "sha512-I0xwD57jP/3A7+5UPZin2w8Y7XHEmEM5zqpYZOcQ45MlNW6tUJUziymV3yRr7rL4vwyfEcRsRksC4a7Kc08p5Q==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@@ -200,9 +257,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-s390x-gnu": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.11.tgz",
|
||||
"integrity": "sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.19.tgz",
|
||||
"integrity": "sha512-BrtEHT24SNXj9HiXqy+s/kXiSiQGt6EKCPUlRirAoIioVxKGnbXBUEkbZASAei7iZJB0/Ynm+0JP00Ipx7AnSw==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
@@ -220,9 +277,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-gnu": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.11.tgz",
|
||||
"integrity": "sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.19.tgz",
|
||||
"integrity": "sha512-rm75/9DkHKeU2WnA8w4X94WGYgLlDCFCfkQC+4bguVJmC/jvDRv2B+2wLOYhyE0fVuv7//Ckk39OoOufyCu76Q==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -240,9 +297,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-linux-x64-musl": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.11.tgz",
|
||||
"integrity": "sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.19.tgz",
|
||||
"integrity": "sha512-irh/4+iYFM4GAzpluDErgjz89bj6NDtqqMAG/6O1LG38Ed3NpyebzCpcVNkFW8uhy+/3/BocUvnXDR33CXWe9A==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -260,9 +317,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-openharmony-arm64": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.11.tgz",
|
||||
"integrity": "sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.19.tgz",
|
||||
"integrity": "sha512-+KWTWNoPt+CfSq94CiceWu3yPE+QzkaG+phPyz9G60tmZLwfQkcA4AeksafzvJAw4pvg1mcd5a1TkUqVv0s4JA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -276,10 +333,29 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-wasm32-wasi": {
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.2.19.tgz",
|
||||
"integrity": "sha512-7EH+skOsl5qpWnK0vzamgJFhOv1cwxQpsxm8tI883K9fur5c27p8q87fzEO6BbBPabA2/+s/zR63/pLc137iOg==",
|
||||
"cpu": [
|
||||
"wasm32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@emnapi/core": "2.0.0-beta.2",
|
||||
"@emnapi/runtime": "2.0.0-beta.2",
|
||||
"@napi-rs/wasm-runtime": "1.2.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^20.19.0 || ^22.13.0 || >=23.5.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-arm64-msvc": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.11.tgz",
|
||||
"integrity": "sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.19.tgz",
|
||||
"integrity": "sha512-3Q1Yg1Q7tEvBWoZf5rFvG/GKZQPgwfru+p4wBajDfJFBs0SHCpL++dfTjW9gyAKd1T7ZpIYvdaUax7Pa/IhFVQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -294,9 +370,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/binding-win32-x64-msvc": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.11.tgz",
|
||||
"integrity": "sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.19.tgz",
|
||||
"integrity": "sha512-y/sqRRc6d7hECzOFc5n3LSeqctmIp9mMjY1Kq4s14uLPd/LZ4z7i1zrW6fMtp2mPeuQIC4e6ULMcwQzMomqQag==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -311,16 +387,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@rolldown/pluginutils": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
|
||||
"integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.1.1.tgz",
|
||||
"integrity": "sha512-glFIJDvLNDtJhT9qrMFWLPbvS+skxgt4L0K8Ei2YtnhPysAJnsI7nyxSJxKj4ADeKX0OLjC4ntRkwpLOoS3rwA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@tanstack/query-core": {
|
||||
"version": "5.104.0",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.104.0.tgz",
|
||||
"integrity": "sha512-JrC2r/JQlXt7khBSdUpsgxNvybzOg+aITa+ARRMlP2AFo93Y8vIqz077rp+e61mJetSZ0T6AJbwW1JHer1vrPQ==",
|
||||
"version": "5.108.2",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.108.2.tgz",
|
||||
"integrity": "sha512-0l+0xDKqn71hfJBKaAvFP/X7WYM0TbscEk6nK1pHaWQUWUEA+WJD0VlT8wF+HIJANMV9B/DouPWwDnX3w/l9BA==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
@@ -328,25 +404,42 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@tanstack/react-query": {
|
||||
"version": "5.104.0",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.104.0.tgz",
|
||||
"integrity": "sha512-e1TZmDCQnWIfiDVryIHeA6Idj+Lfx1hORLOhXS/l5wcgvtVD4yYqbTDl378sGQKIi2cSgb0TEMC9cKK8GGoJEw==",
|
||||
"version": "5.108.2",
|
||||
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.108.2.tgz",
|
||||
"integrity": "sha512-wV6hEjVGTfh9rvu3uREYW0hgBfS9klDejGelhPY575jD5jg6qbAb1nzT7hR1Q+wemR66ZjtE5p9pAGUwqK8zbg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@tanstack/query-core": "5.104.0"
|
||||
"@tanstack/query-core": "5.108.2"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/tannerlinsley"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": "^18 || ^19",
|
||||
"react": "^18 || ^19"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@tybys/wasm-util": {
|
||||
"version": "0.10.5",
|
||||
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.5.tgz",
|
||||
"integrity": "sha512-dOGOPxlaNV+G046mZzN+9C0dAcQZeSKcXiVaM0TYy/LM4ttTmgSBDxYfovcYI8Em3+eAbiAYpvWLOv8+ZVRJKA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"tslib": "^2.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "26.6.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.3.tgz",
|
||||
"integrity": "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg==",
|
||||
"version": "26.6.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
|
||||
"integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -357,7 +450,7 @@
|
||||
"version": "19.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
|
||||
"integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"csstype": "^3.2.2"
|
||||
@@ -367,7 +460,7 @@
|
||||
"version": "19.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
|
||||
"integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@types/react": "^19.3.0"
|
||||
@@ -714,9 +807,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitejs/plugin-react": {
|
||||
"version": "6.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.1.tgz",
|
||||
"integrity": "sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw==",
|
||||
"version": "6.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.3.0.tgz",
|
||||
"integrity": "sha512-H9E955aVvD2F4zNHCw4eIZbIfF6xKldlh7MNu+hSU7xwQzh65lI/N+CJWqmfhi0PEjDXIt/H7T7J/4wU63KJiw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -726,9 +819,9 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
|
||||
"@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"oxc-transform-react": "^0.145.0",
|
||||
"oxc-transform-react": ">=0.152.0 <0.157.0",
|
||||
"vite": "^8.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
@@ -750,10 +843,10 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/csstype": {
|
||||
"version": "3.2.3",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
|
||||
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
|
||||
"dev": true,
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.4.tgz",
|
||||
"integrity": "sha512-PoKaoPzQapnEoqUSnHx1u6W6ku8CVEgKsnpmmzU3m1nwkidpPBQ8V/Zq2+bWNrsOKoKLwTGdbx6xF7BXP1zLVQ==",
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/detect-libc": {
|
||||
@@ -766,6 +859,12 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/eckey-utils": {
|
||||
"version": "0.7.14",
|
||||
"resolved": "https://registry.npmjs.org/eckey-utils/-/eckey-utils-0.7.14.tgz",
|
||||
"integrity": "sha512-s/mENS+mMnJjDSydy0muBQQHMTWJ1nPe8EiphANZrf+lv/1u35aP9WvWHTWqCBJ21blNIurGF7UoLjtaOpoCFw==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
@@ -1082,9 +1181,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.19",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",
|
||||
"integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",
|
||||
"version": "3.3.20",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
|
||||
"integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -1100,6 +1199,27 @@
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
}
|
||||
},
|
||||
"node_modules/openpgp": {
|
||||
"version": "6.3.3",
|
||||
"resolved": "https://registry.npmjs.org/openpgp/-/openpgp-6.3.3.tgz",
|
||||
"integrity": "sha512-W0foQI+Zb7/TCy7Z50gqZejYe3oJkiZJ9OSV4ImuRT8MmoKOJhtAMvRm6w9STlyYluLiuezG7+0Qdqbcmmx7ig==",
|
||||
"license": "LGPL-3.0+",
|
||||
"dependencies": {
|
||||
"eckey-utils": "^0.7.14"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18.0.0",
|
||||
"typescript": ">= 5.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@openpgp/web-stream-tools": "~0.3.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@openpgp/web-stream-tools": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/picocolors": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
|
||||
@@ -1121,9 +1241,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.28",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
|
||||
"integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
|
||||
"version": "8.5.33",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.33.tgz",
|
||||
"integrity": "sha512-RVHEU9/Pp1Fnjr/MpAJsZoADukCKhfIi15OunEYiGktIkYLkPVvC1sioWolGDS7XByMTx9m/IGbro0Js13zhnQ==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -1141,39 +1261,39 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.18",
|
||||
"nanoid": "^3.3.20",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
"source-map-js": "^1.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^10 || ^12 || >=14"
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "19.3.0",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",
|
||||
"integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",
|
||||
"version": "19.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz",
|
||||
"integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "19.3.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
|
||||
"integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",
|
||||
"version": "19.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.1.tgz",
|
||||
"integrity": "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"scheduler": "^0.28.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.3.0"
|
||||
"react": "^19.3.1"
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "8.4.0",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-8.4.0.tgz",
|
||||
"integrity": "sha512-JtydAkBvU9UTEe5qNC+POhu+ZBNM7rlKY2IegwXc7Idj7xfRG16x5RZrw3mju+XlqBxfvb2ky9P3jUp9WyWC1g==",
|
||||
"version": "8.5.2",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-8.5.2.tgz",
|
||||
"integrity": "sha512-luPXqNUAIZAmCHbeBysc2KO7VJjckIMZk4ByEetS7Jotit8R6lLSVVeC76UE//AYK6QD6tAnVAPGkvmqMd+b1w==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/route-pattern": "^0.22.1",
|
||||
@@ -1183,23 +1303,31 @@
|
||||
"node": ">=22.22.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/react": ">=19.2.0",
|
||||
"@types/react-dom": ">=19.2.0",
|
||||
"react": ">=19.2.7",
|
||||
"react-dom": ">=19.2.7"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@types/react": {
|
||||
"optional": true
|
||||
},
|
||||
"@types/react-dom": {
|
||||
"optional": true
|
||||
},
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/rolldown": {
|
||||
"version": "1.2.11",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.11.tgz",
|
||||
"integrity": "sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==",
|
||||
"version": "1.2.19",
|
||||
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.19.tgz",
|
||||
"integrity": "sha512-QIiV1J9d0pzN4jeeTH4sjPy0AZ6cAy2cG0ExeoE1+U8Rvj+hR3gYkokx0YbeUNGlZqiQJJ2utcETe0oKXwzsuA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@oxc-project/types": "=0.151.0",
|
||||
"@oxc-project/types": "=0.156.0",
|
||||
"@rolldown/pluginutils": "^1.0.0"
|
||||
},
|
||||
"bin": {
|
||||
@@ -1209,21 +1337,22 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@rolldown/binding-android-arm-eabi": "1.2.11",
|
||||
"@rolldown/binding-android-arm64": "1.2.11",
|
||||
"@rolldown/binding-darwin-arm64": "1.2.11",
|
||||
"@rolldown/binding-darwin-x64": "1.2.11",
|
||||
"@rolldown/binding-freebsd-x64": "1.2.11",
|
||||
"@rolldown/binding-linux-arm-gnueabihf": "1.2.11",
|
||||
"@rolldown/binding-linux-arm64-gnu": "1.2.11",
|
||||
"@rolldown/binding-linux-arm64-musl": "1.2.11",
|
||||
"@rolldown/binding-linux-ppc64-gnu": "1.2.11",
|
||||
"@rolldown/binding-linux-s390x-gnu": "1.2.11",
|
||||
"@rolldown/binding-linux-x64-gnu": "1.2.11",
|
||||
"@rolldown/binding-linux-x64-musl": "1.2.11",
|
||||
"@rolldown/binding-openharmony-arm64": "1.2.11",
|
||||
"@rolldown/binding-win32-arm64-msvc": "1.2.11",
|
||||
"@rolldown/binding-win32-x64-msvc": "1.2.11"
|
||||
"@rolldown/binding-android-arm-eabi": "1.2.19",
|
||||
"@rolldown/binding-android-arm64": "1.2.19",
|
||||
"@rolldown/binding-darwin-arm64": "1.2.19",
|
||||
"@rolldown/binding-darwin-x64": "1.2.19",
|
||||
"@rolldown/binding-freebsd-x64": "1.2.19",
|
||||
"@rolldown/binding-linux-arm-gnueabihf": "1.2.19",
|
||||
"@rolldown/binding-linux-arm64-gnu": "1.2.19",
|
||||
"@rolldown/binding-linux-arm64-musl": "1.2.19",
|
||||
"@rolldown/binding-linux-ppc64-gnu": "1.2.19",
|
||||
"@rolldown/binding-linux-s390x-gnu": "1.2.19",
|
||||
"@rolldown/binding-linux-x64-gnu": "1.2.19",
|
||||
"@rolldown/binding-linux-x64-musl": "1.2.19",
|
||||
"@rolldown/binding-openharmony-arm64": "1.2.19",
|
||||
"@rolldown/binding-wasm32-wasi": "1.2.19",
|
||||
"@rolldown/binding-win32-arm64-msvc": "1.2.19",
|
||||
"@rolldown/binding-win32-x64-msvc": "1.2.19"
|
||||
}
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
@@ -1233,13 +1362,13 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/source-map-js": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
|
||||
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz",
|
||||
"integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
@@ -1259,6 +1388,14 @@
|
||||
"url": "https://github.com/sponsors/SuperchupuDev"
|
||||
}
|
||||
},
|
||||
"node_modules/tslib": {
|
||||
"version": "2.9.1",
|
||||
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
|
||||
"integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
|
||||
"dev": true,
|
||||
"license": "0BSD",
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
|
||||
@@ -1302,16 +1439,16 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/vite": {
|
||||
"version": "8.3.1",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz",
|
||||
"integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==",
|
||||
"version": "8.3.8",
|
||||
"resolved": "https://registry.npmjs.org/vite/-/vite-8.3.8.tgz",
|
||||
"integrity": "sha512-LzOn3h9rG/0vhLdXrV4yJ4QFA9eEoqCl+Yx+kGJd7aB9w6nfNgVHKSYwLPZUHrz4ZGa+t+kXjV9itvcHDLQouA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"lightningcss": "^1.33.0",
|
||||
"picomatch": "^4.0.7",
|
||||
"postcss": "^8.5.28",
|
||||
"rolldown": "~1.2.9",
|
||||
"postcss": "^8.5.32",
|
||||
"rolldown": "~1.2.18",
|
||||
"tinyglobby": "^0.2.17"
|
||||
},
|
||||
"bin": {
|
||||
@@ -1328,7 +1465,7 @@
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/node": "^20.19.0 || >=22.12.0",
|
||||
"@vitejs/devtools": "^0.7.1",
|
||||
"@vitejs/devtools": "^0.7.1 || ^0.8.0",
|
||||
"esbuild": "^0.27.0 || ^0.28.0",
|
||||
"jiti": ">=1.21.0",
|
||||
"less": "^4.0.0",
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
"dependencies": {
|
||||
"@tanstack/react-query": "^5.104.0",
|
||||
"lucide-react": "1.48.0",
|
||||
"openpgp": "^6.3.2",
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router": "^8.4.0"
|
||||
|
||||
+22
-8
@@ -3,12 +3,15 @@ import { NavLink } from "react-router";
|
||||
import { Bell, ChartColumn, House, Info, LogOut, MessageSquare, Search, Settings, User } from "lucide-react";
|
||||
import { api } from "./api";
|
||||
import { useAuthChanged, useMe } from "./auth";
|
||||
import { useUnread } from "./chats";
|
||||
import { useUnreadNotifications } from "./notifications";
|
||||
import { lockKeyring } from "./keyring";
|
||||
|
||||
type Target = { title: string; icon?: ReactNode; to: string; end?: boolean };
|
||||
type Target = { title: string; icon?: ReactNode; to: string; end?: boolean; badge?: number };
|
||||
|
||||
// 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<string>();
|
||||
|
||||
export const isReady = (to: string) => !unfinished.has(to);
|
||||
|
||||
@@ -17,12 +20,14 @@ export const isReady = (to: string) => !unfinished.has(to);
|
||||
// /me mit dem Login.
|
||||
function useMainTargets(): Target[] {
|
||||
const me = useMe().data;
|
||||
const profile = me ? `/u/${encodeURIComponent(me.username)}` : "/me";
|
||||
const profile = me ? `/u/${encodeURIComponent(me.handle)}` : "/me";
|
||||
const unread = useUnread();
|
||||
const unseen = useUnreadNotifications();
|
||||
const targets: Target[] = [
|
||||
{ title: "Feed", icon: <House className="icon" />, to: "/", end: true },
|
||||
{ title: "Suche", icon: <Search className="icon" />, to: "/search" },
|
||||
{ title: "Benachrichtigungen", icon: <Bell className="icon" />, to: "/notifications" },
|
||||
{ title: "Chats", icon: <MessageSquare className="icon" />, to: "/chats" },
|
||||
{ title: "Benachrichtigungen", icon: <Bell className="icon" />, to: "/notifications", badge: unseen },
|
||||
{ title: "Chats", icon: <MessageSquare className="icon" />, to: "/chats", badge: unread },
|
||||
{ title: "Profil", icon: <User className="icon" />, to: profile },
|
||||
];
|
||||
return targets.filter((t) => isReady(t.to));
|
||||
@@ -60,7 +65,7 @@ function TargetList({ targets, onNavigate }: { targets: Target[]; onNavigate: ()
|
||||
{targets.map((t) => (
|
||||
<li key={t.title}>
|
||||
<NavLink to={t.to} end={t.end} onClick={onNavigate}>
|
||||
{t.icon}<span>{t.title}</span>
|
||||
{t.icon}<span>{t.title}</span><Badge n={t.badge} />
|
||||
</NavLink>
|
||||
</li>
|
||||
))}
|
||||
@@ -76,6 +81,7 @@ function Logout({ onDone }: { onDone: () => void }) {
|
||||
if (!me) return null;
|
||||
const logout = async () => {
|
||||
await api.post("/auth/logout").catch(() => undefined);
|
||||
lockKeyring();
|
||||
await authChanged();
|
||||
onDone();
|
||||
};
|
||||
@@ -88,13 +94,21 @@ function Logout({ onDone }: { onDone: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
// Badge: schlichter Zähler hinter dem Symbol, etwa ungelesene Nachrichten.
|
||||
function Badge({ n }: { n?: number }) {
|
||||
if (!n) return null;
|
||||
return <span className="badge" aria-hidden="true">{n > 99 ? "99+" : n}</span>;
|
||||
}
|
||||
|
||||
const label = (t: Target) => (t.badge ? `${t.title} (${t.badge} ungelesen)` : t.title);
|
||||
|
||||
// TabBar: mobil unten die (bis zu) fünf wichtigsten Ziele, nur Icons.
|
||||
export function TabBar() {
|
||||
return (
|
||||
<nav id="tabbar" aria-label="Hauptnavigation">
|
||||
{useMainTargets().map((t) => (
|
||||
<NavLink key={t.title} to={t.to} end={t.end} aria-label={t.title} title={t.title}>
|
||||
{t.icon}
|
||||
<NavLink key={t.title} to={t.to} end={t.end} aria-label={label(t)} title={label(t)}>
|
||||
{t.icon}<Badge n={t.badge} />
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
+127
-6
@@ -1,6 +1,6 @@
|
||||
/* Designsprache aus der alten Python-Version (verwaiste Linie bb6b966):
|
||||
EB Garamond als Fließtext, Cheltenham Classic für die Überschrift,
|
||||
Concrete-Textur als Hintergrund, weiße zentrierte Inhaltsspalte. */
|
||||
Concrete-Textur als Hintergrund, helle zentrierte Inhaltsspalte. */
|
||||
|
||||
/* font-display: swap -> Text wird sofort mit System-Serife gezeichnet und
|
||||
wechselt zur Webschrift, sobald geladen (kein FOIT). Der Browser lädt nur
|
||||
@@ -42,10 +42,10 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--ink: black; /* Text, Linien, Rahmen */
|
||||
--paper: white; /* Flächen */
|
||||
--paper: #f4f1ea; /* Flächen: warmes Off-White, blendet weniger als Weiß */
|
||||
--muted: gray; /* Nebentext, Thread-Strich */
|
||||
--faint: #ccc; /* gesperrte Rahmen */
|
||||
--hover: #f7f7f5; /* Karte unter dem Zeiger */
|
||||
--faint: #ccc8bf; /* gesperrte Rahmen */
|
||||
--hover: #ebe7de; /* Karte unter dem Zeiger: etwas dunkler als paper */
|
||||
--avatar-bg: #eee; /* Avatar, solange das Bild lädt */
|
||||
--shade: rgba(0, 0, 0, 0.4); /* hinter der Schublade */
|
||||
--texture: url("/static/assets/concrete/Concrete012_1024p_Color.jpg");
|
||||
@@ -58,7 +58,7 @@
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--ink: #e8e6e1;
|
||||
--ink: #d8d4cc; /* gedämpftes Off-White: auf OLED-Schwarz blendet Weiß */
|
||||
--paper: black;
|
||||
--muted: #999;
|
||||
--faint: #444;
|
||||
@@ -239,6 +239,28 @@ h2 {
|
||||
padding: 0.6rem 0;
|
||||
}
|
||||
|
||||
/* Zähler am Symbol (ungelesene Chats): kleines invertiertes Kästchen,
|
||||
oben rechts angesetzt; im aktiven (invertierten) Ziel wieder umgekehrt. */
|
||||
.badge {
|
||||
align-self: flex-start;
|
||||
margin-left: -0.3rem;
|
||||
padding: 0 0.25rem;
|
||||
font-size: 0.8rem;
|
||||
line-height: 1.3;
|
||||
/* Versalziffern: die Mediävalziffern der Schrift wären hier zu klein. */
|
||||
font-variant-numeric: lining-nums;
|
||||
background-color: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
#sidebar .badge {
|
||||
align-self: center;
|
||||
margin-left: 0;
|
||||
}
|
||||
a.active .badge {
|
||||
background-color: var(--paper);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
@@ -456,6 +478,41 @@ a.button:hover, button:hover {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
/* Bild mit Hinweis: verpixelte Variante, darüber mittig Hinweis und Knopf. */
|
||||
.card .cover {
|
||||
position: relative;
|
||||
max-width: 300px;
|
||||
margin: 0.5rem auto;
|
||||
}
|
||||
#focus .card .cover { max-width: 100%; }
|
||||
/* Mindesthöhe: Hinweis und Knopf brauchen Platz, auch solange das Bild noch
|
||||
lädt oder bei sehr flachen Bildern. */
|
||||
.card .cover img {
|
||||
width: 100%;
|
||||
min-height: 9rem;
|
||||
max-width: none;
|
||||
margin: 0;
|
||||
object-fit: cover;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
.cover-note {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
}
|
||||
.cover-note p {
|
||||
margin: 0;
|
||||
padding: 0.25rem 0.5rem;
|
||||
background-color: var(--paper);
|
||||
border: 1px solid var(--ink);
|
||||
}
|
||||
|
||||
/* Linkvorschau: abgesetzte Karte unter dem Text, kleines Vorschaubild links,
|
||||
Titel und Seiten- bzw. Kanalname daneben. Rahmen wie bei den Buttons,
|
||||
weiß auch beim Card-Hover. */
|
||||
@@ -535,8 +592,15 @@ img.avatar-sm { width: var(--avatar-sm); height: var(--avatar-sm); }
|
||||
auf 1rem liegt). Hier explizit angleichen -> ganze Meta-Zeile gleich groß. */
|
||||
.byline span { font-size: 1rem; }
|
||||
|
||||
/* Melden steht rechts in der Byline. */
|
||||
/* Name neben dem Avatar: Anzeigename oben, @handle (+ Zeit) darunter, ohne
|
||||
Unterstreichung. */
|
||||
.byline .author { display: flex; flex-direction: column; line-height: 1.25; }
|
||||
.byline .author a { text-decoration: none; }
|
||||
|
||||
/* Datum rechts in der Byline, Melden (falls da) direkt daneben ganz außen. */
|
||||
.byline .byline-time { margin-left: auto; }
|
||||
.byline .report { margin-left: auto; }
|
||||
.byline .byline-time + .report { margin-left: 0; }
|
||||
|
||||
/* --- Profil ---
|
||||
Header-Bild im Format 3:1 über die ganze Spalte; ohne Bild ein schwarzer
|
||||
@@ -716,6 +780,9 @@ form input[type="file"] {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* Generierte Passphrase: ein Klick markiert sie ganz, zum Kopieren. */
|
||||
.passphrase { user-select: all; }
|
||||
|
||||
/* --- Statistik-Seite --- */
|
||||
.statgrid {
|
||||
display: flex;
|
||||
@@ -770,3 +837,57 @@ form input[type="file"] {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
|
||||
/* --- Chats --- */
|
||||
#chat-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
#chat-list li {
|
||||
padding: 0.3rem 0;
|
||||
}
|
||||
/* Vorschläge für @handle und #tag unter dem Textfeld (SuggestTextarea); der
|
||||
gewählte invertiert wie das aktuelle Ziel in der Seitenleiste. */
|
||||
.suggest {
|
||||
list-style: none;
|
||||
margin: -4px 0 4px; /* schließt an den Rand des Textfelds an */
|
||||
padding: 0;
|
||||
border: 1px solid var(--ink);
|
||||
background-color: var(--paper);
|
||||
}
|
||||
.suggest li {
|
||||
padding: 0.3rem 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.suggest li[aria-selected="true"] {
|
||||
background-color: var(--ink);
|
||||
color: var(--paper);
|
||||
}
|
||||
.suggest li[aria-selected="true"] .muted { color: var(--paper); }
|
||||
.suggest img.avatar { width: 1.6rem; height: 1.6rem; }
|
||||
|
||||
/* Benachrichtigungen: ganzer Eintrag ist der Link, ohne Unterstreichung;
|
||||
Typ fett, darunter Auszug und Datum. */
|
||||
#notification-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
}
|
||||
#notification-list li {
|
||||
padding: 0.8rem 0;
|
||||
}
|
||||
#notification-list a {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
text-decoration: none;
|
||||
}
|
||||
/* 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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { api } from "./api";
|
||||
import { useMe } from "./auth";
|
||||
|
||||
// Die Gesprächsübersicht (notes/chats.md), geteilt von der Chats-Seite und
|
||||
// dem Zähler in der Navigation. Angemeldet alle 30 Sekunden neu; nach dem
|
||||
// Lesen eines Gesprächs invalidiert (ChatsPage.tsx).
|
||||
|
||||
export type ChatSummary = { handle: string; display_name: string; avatar: string; last_at: number; unread: number };
|
||||
|
||||
const pollList = 30_000;
|
||||
|
||||
export function useChats() {
|
||||
const me = useMe().data;
|
||||
return useQuery({
|
||||
queryKey: ["chats"],
|
||||
queryFn: async () => (await api.get<{ chats: ChatSummary[] }>("/chats")).chats,
|
||||
enabled: !!me,
|
||||
refetchInterval: pollList,
|
||||
});
|
||||
}
|
||||
|
||||
// useUnread zählt die ungelesenen Nachrichten aller Gespräche.
|
||||
export function useUnread() {
|
||||
return useChats().data?.reduce((n, c) => n + c.unread, 0) ?? 0;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ export function AuthBox() {
|
||||
const register = submit(async (fd) => {
|
||||
await api.post("/auth/newuser", fd);
|
||||
const creds = new FormData();
|
||||
creds.append("user", String(fd.get("user")));
|
||||
creds.append("user", String(fd.get("handle")));
|
||||
creds.append("pass", String(fd.get("pass1")));
|
||||
creds.append("timeout", "86400");
|
||||
await api.post("/auth/login", creds);
|
||||
@@ -50,7 +50,7 @@ export function AuthBox() {
|
||||
<section id="auth-box">
|
||||
<form id="login-form" hidden={mode !== "login"} onSubmit={login}>
|
||||
<h2>Login</h2>{" "}
|
||||
<input name="user" placeholder="Nutzername" autoComplete="username" />{" "}
|
||||
<input name="user" placeholder="Handle" autoComplete="username" />{" "}
|
||||
<input name="pass" type="password" placeholder="Passwort" autoComplete="current-password" />{" "}
|
||||
<label>
|
||||
Angemeldet bleiben für{" "}
|
||||
@@ -68,7 +68,8 @@ export function AuthBox() {
|
||||
|
||||
<form id="register-form" hidden={mode !== "register"} onSubmit={register}>
|
||||
<h2>Registrieren</h2>{" "}
|
||||
<input name="user" placeholder="Nutzername" autoComplete="username" />{" "}
|
||||
<input name="handle" placeholder="Handle (a–z, 0–9, _)" autoComplete="username" />{" "}
|
||||
<input name="display_name" placeholder="Anzeigename (optional)" autoComplete="nickname" />{" "}
|
||||
<input name="pass1" type="password" placeholder="Passwort" autoComplete="new-password" />{" "}
|
||||
<input name="pass2" type="password" placeholder="Passwort wiederholen" autoComplete="new-password" />{" "}
|
||||
<button type="submit" disabled={busy}>Konto erstellen</button>{" "}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { avatarUrl, formatTime } from "../format";
|
||||
|
||||
// Wer schreibt: Handle (@name, eindeutig), frei gewählter Anzeigename ('' =
|
||||
// keiner) und Profilbild.
|
||||
export type Author = { handle: string; display_name: string; avatar: string };
|
||||
|
||||
// Byline ist der Kopf von Beiträgen, Chat-Nachrichten und Einträgen der
|
||||
// Chat-Liste -- ein Element, damit alle gleich aussehen:
|
||||
//
|
||||
// [Avatar] Anzeigename Datum · after end
|
||||
// @handle · meta
|
||||
//
|
||||
// Ohne Anzeigenamen steht oben der Handle. Avatar und Namen verlinken auf to.
|
||||
// meta steht unter dem Namen (etwa "2 neu"), after hinter dem Datum (etwa der
|
||||
// Repost-Countdown), end ganz außen rechts (etwa Melden).
|
||||
export function Byline({ u, to, time, meta, after, end }: {
|
||||
u: Author;
|
||||
to: string;
|
||||
time: number;
|
||||
meta?: ReactNode;
|
||||
after?: ReactNode;
|
||||
end?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="muted byline">
|
||||
<Link to={to}>
|
||||
<img className="avatar avatar-sm" src={avatarUrl(u.avatar)} alt="" loading="lazy" />
|
||||
</Link>
|
||||
<span className="author">
|
||||
<Link to={to}>{u.display_name || u.handle}</Link>
|
||||
<span>
|
||||
<Link to={to}>@{u.handle}</Link>
|
||||
{meta}
|
||||
</span>
|
||||
</span>
|
||||
<span className="byline-time">
|
||||
{formatTime(time)}
|
||||
{after}
|
||||
</span>
|
||||
{end}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { MouseEvent } from "react";
|
||||
import { useState, type MouseEvent } from "react";
|
||||
import { Link, useNavigate } from "react-router";
|
||||
import type { Entry, LinkPreview } from "../types";
|
||||
import { avatarUrl, formatTime, linkify } from "../format";
|
||||
import { formatTime, linkify } from "../format";
|
||||
import { Byline } from "./Byline";
|
||||
import { Votes } from "./Votes";
|
||||
import { useBump } from "./Bump";
|
||||
import { useReport } from "./Report";
|
||||
@@ -36,6 +37,23 @@ function DeletedCard({ entry: e }: { entry: Entry }) {
|
||||
);
|
||||
}
|
||||
|
||||
// EntryImage zeigt das Bild eines Beitrags. Steht ein Hinweis davor, erst nur
|
||||
// die verpixelte Variante mit dem Hinweis; das Bild selbst lädt der Browser
|
||||
// erst nach dem Klick auf "Inhalt anzeigen".
|
||||
function EntryImage({ entry: e }: { entry: Entry }) {
|
||||
const [shown, setShown] = useState(false);
|
||||
if (!e.image_cover || shown) return <img src={`/${e.filepath}`} alt="" loading="lazy" />;
|
||||
return (
|
||||
<div className="cover">
|
||||
<img src={`/${e.image_cover}`} alt="" loading="lazy" />
|
||||
<div className="cover-note">
|
||||
<p>{e.image_warning}</p>
|
||||
<button type="button" onClick={() => setShown(true)}>Inhalt anzeigen</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// LinkPreviewCard zeigt die Vorschau des ersten Links als abgesetzte Karte:
|
||||
// kleines Bild links, Titel und Seite daneben.
|
||||
// Alles darin kommt von unserem Server; erst der Klick führt zur fremden Seite.
|
||||
@@ -56,27 +74,24 @@ function LiveCard({ entry: e }: { entry: Entry }) {
|
||||
const bump = useBump(e);
|
||||
const report = useReport(e.pid);
|
||||
const own = useMe().data?.uid === e.uid;
|
||||
const profile = `/u/${encodeURIComponent(e.username)}`;
|
||||
const profile = `/u/${encodeURIComponent(e.handle)}`;
|
||||
|
||||
return (
|
||||
<article className="card" data-pid={e.pid} onClick={open}>
|
||||
<div className="muted byline">
|
||||
<Link to={profile}>
|
||||
<img className="avatar avatar-sm" src={avatarUrl(e.avatar)} alt="" loading="lazy" />
|
||||
</Link>
|
||||
<span>
|
||||
<Link to={profile}>{e.username}</Link> · {formatTime(e.created_at)}
|
||||
<span className="cooldown">{bump.cooldown}</span>
|
||||
</span>
|
||||
{!own && report.button}
|
||||
</div>
|
||||
<Byline
|
||||
u={e}
|
||||
to={profile}
|
||||
time={e.created_at}
|
||||
after={<span className="cooldown">{bump.cooldown}</span>}
|
||||
end={!own && report.button}
|
||||
/>
|
||||
<div className="threadline-wrapper">
|
||||
<div className="threadline"></div>
|
||||
<div className="body">
|
||||
{report.form}
|
||||
<div className="content">{linkify(e.content)}</div>
|
||||
<div className="content">{linkify(e.content, e.mentions)}</div>
|
||||
{e.preview && <LinkPreviewCard preview={e.preview} />}
|
||||
{e.filepath && <img src={`/${e.filepath}`} alt="" loading="lazy" />}
|
||||
{e.filepath && <EntryImage entry={e} />}
|
||||
<div className="interactions">
|
||||
<Link className="button reply" to={`/e/${e.pid}`}>Antworten ({e.reply_count})</Link>
|
||||
<Votes pid={e.pid} />
|
||||
|
||||
@@ -24,12 +24,14 @@ function scrollBelowHeader(el: Element) {
|
||||
window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - offset });
|
||||
}
|
||||
|
||||
export function Feed({ queryKey, urlFor, as: Container = "section", focus, onFocused }: {
|
||||
// empty ersetzt bei einem ganz leeren Ergebnis die Endmarke (Suche).
|
||||
export function Feed({ queryKey, urlFor, as: Container = "section", focus, onFocused, empty }: {
|
||||
queryKey: unknown[];
|
||||
urlFor: (page: number) => string;
|
||||
as?: "section" | "div";
|
||||
focus?: number;
|
||||
onFocused?: () => void;
|
||||
empty?: string;
|
||||
}) {
|
||||
const feed = useInfiniteQuery({
|
||||
queryKey,
|
||||
@@ -85,7 +87,9 @@ export function Feed({ queryKey, urlFor, as: Container = "section", focus, onFoc
|
||||
<Container id="feed">
|
||||
{entries.map((e) => <Discussion key={e.pid} entry={e} />)}
|
||||
{feed.isError && <p className="msg">{errMsg(feed.error, "Feed konnte nicht geladen werden.")}</p>}
|
||||
{feed.isSuccess && !hasNextPage && <p className="muted">YOU REACHED THE END!</p>}
|
||||
{feed.isSuccess && !hasNextPage && (
|
||||
<p className="muted">{empty && !entries.length ? empty : "YOU REACHED THE END!"}</p>
|
||||
)}
|
||||
</Container>
|
||||
<div id="sentinel" ref={sentinel}></div>
|
||||
</>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { api, errMsg } from "../api";
|
||||
import { submitOnShiftEnter } from "../keys";
|
||||
import { submitOnCtrlEnter } from "../keys";
|
||||
import { SuggestTextarea } from "./SuggestTextarea";
|
||||
import { pasteImage } from "../paste";
|
||||
|
||||
// PostForm verfasst einen Beitrag, mit replyTo eine Antwort darauf.
|
||||
// Abgeschickt wird per Knopf oder mit Shift+Enter aus dem Textfeld heraus
|
||||
// (siehe submitOnShiftEnter).
|
||||
// Abgeschickt wird per Knopf oder mit Strg+Enter aus dem Textfeld heraus
|
||||
// (siehe submitOnCtrlEnter).
|
||||
export function PostForm({ replyTo, rows, placeholder, submitLabel, fallback, onDone }: {
|
||||
replyTo?: string;
|
||||
rows: number;
|
||||
@@ -42,16 +43,16 @@ export function PostForm({ replyTo, rows, placeholder, submitLabel, fallback, on
|
||||
if (pasteImage(e)) setPasteMsg("Bild aus Zwischenablage übernommen.");
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
<SuggestTextarea
|
||||
name="content"
|
||||
rows={rows}
|
||||
maxLength={1000}
|
||||
placeholder={placeholder}
|
||||
onKeyDown={submitOnShiftEnter}
|
||||
></textarea>{" "}
|
||||
onKeyDown={submitOnCtrlEnter}
|
||||
/>{" "}
|
||||
<p className="muted">{pasteMsg}</p>{" "}
|
||||
<input name="file" type="file" accept="image/*" />{" "}
|
||||
<button type="submit" title="Shift+Enter" disabled={create.isPending}>{submitLabel}</button>
|
||||
<button type="submit" title="Strg+Enter" disabled={create.isPending}>{submitLabel}</button>
|
||||
</form>
|
||||
<p className="msg">{create.isError ? errMsg(create.error, fallback) : ""}</p>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode, type TextareaHTMLAttributes } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { api } from "../api";
|
||||
import { avatarUrl } from "../format";
|
||||
|
||||
type User = { handle: string; display_name: string; avatar: string };
|
||||
type Tag = { tag: string; count: number };
|
||||
|
||||
// Ein Vorschlag: key für React, insert ersetzt das angefangene Wort.
|
||||
type Suggestion = { key: string; insert: string; label: ReactNode };
|
||||
|
||||
// Angefangenes @… oder #… direkt vor dem Cursor; davor kein Buchstabe, keine
|
||||
// Ziffer, kein _ wie bei Erwähnungen und Hashtags (format.tsx). Beim @
|
||||
// Buchstaben statt nur a–z, damit "@jö" auch über den Anzeigenamen findet.
|
||||
const tokenPattern = /(^|[^\p{L}\p{N}_])([@#])([\p{L}\p{N}_]{0,50})$/u;
|
||||
|
||||
type Token = { start: number; end: number; trigger: "@" | "#"; query: string };
|
||||
|
||||
function tokenAt(ta: HTMLTextAreaElement): Token | null {
|
||||
const end = ta.selectionStart;
|
||||
if (end !== ta.selectionEnd) return null;
|
||||
const m = ta.value.slice(0, end).match(tokenPattern);
|
||||
if (!m) return null;
|
||||
const trigger = m[2] as Token["trigger"];
|
||||
// Ein nacktes "#" zeigt schon die häufigsten Tags, ein nacktes "@" nicht
|
||||
// gleich alle Nutzer.
|
||||
if (trigger === "@" && (m[3].length === 0 || m[3].length > 20)) return null;
|
||||
return { start: end - m[3].length - 1, end, trigger, query: m[3] };
|
||||
}
|
||||
|
||||
// fetchSuggestions fragt den passenden Endpunkt und bringt beide Arten in
|
||||
// dieselbe Form.
|
||||
async function fetchSuggestions(trigger: Token["trigger"], q: string): Promise<Suggestion[]> {
|
||||
const query = encodeURIComponent(q);
|
||||
if (trigger === "#") {
|
||||
const { tags } = await api.get<{ tags: Tag[] }>(`/tags/suggest?q=${query}`);
|
||||
return tags.map((t) => ({
|
||||
key: t.tag,
|
||||
insert: `#${t.tag}`,
|
||||
label: (
|
||||
<span>
|
||||
#{t.tag} <span className="muted">· {t.count} {t.count === 1 ? "Beitrag" : "Beiträge"}</span>
|
||||
</span>
|
||||
),
|
||||
}));
|
||||
}
|
||||
const { users } = await api.get<{ users: User[] }>(`/users/suggest?q=${query}`);
|
||||
return users.map((u) => ({
|
||||
key: u.handle,
|
||||
insert: `@${u.handle}`,
|
||||
label: (
|
||||
<>
|
||||
<img className="avatar" src={avatarUrl(u.avatar)} alt="" />
|
||||
<span>
|
||||
{u.display_name || u.handle} <span className="muted">@{u.handle}</span>
|
||||
</span>
|
||||
</>
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
// useDebounced liefert value erst, wenn es ms lang unverändert war: nicht
|
||||
// jeder Tastendruck soll den Server fragen.
|
||||
function useDebounced<T>(value: T, ms: number): T {
|
||||
const [v, setV] = useState(value);
|
||||
useEffect(() => {
|
||||
const t = setTimeout(() => setV(value), ms);
|
||||
return () => clearTimeout(t);
|
||||
}, [value, ms]);
|
||||
return v;
|
||||
}
|
||||
|
||||
// SuggestTextarea ist ein Textfeld mit Autovervollständigung: Steht vor dem
|
||||
// Cursor ein angefangenes @…, schlägt die Liste darunter passende Nutzer vor,
|
||||
// bei #… die häufigsten passenden Hashtags. ↑/↓ wählen, Enter oder Tab
|
||||
// übernehmen, Esc schließt; Antippen übernimmt ebenso. Übernehmen ersetzt das
|
||||
// angefangene Wort durch "@handle " bzw. "#tag ". Alle übrigen Eigenschaften
|
||||
// gehen ans Textfeld, ein eigenes onKeyDown (etwa Strg+Enter) läuft, wenn die
|
||||
// Liste die Taste nicht braucht.
|
||||
export function SuggestTextarea({ onKeyDown, ...props }: TextareaHTMLAttributes<HTMLTextAreaElement>) {
|
||||
const ref = useRef<HTMLTextAreaElement>(null);
|
||||
const listId = useId();
|
||||
const [token, setToken] = useState<Token | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
// Als ein String entprellt, damit Wechsel zwischen @ und # mitzählen.
|
||||
const typed = token ? token.trigger + token.query : "";
|
||||
const debounced = useDebounced(typed, 150);
|
||||
|
||||
const suggest = useQuery({
|
||||
queryKey: ["suggest", debounced],
|
||||
queryFn: () => fetchSuggestions(debounced[0] as Token["trigger"], debounced.slice(1)),
|
||||
enabled: debounced !== "",
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const items = token && debounced === typed ? (suggest.data ?? []) : [];
|
||||
const open = items.length > 0;
|
||||
const current = Math.min(active, items.length - 1);
|
||||
|
||||
const update = () => {
|
||||
const ta = ref.current;
|
||||
const t = ta ? tokenAt(ta) : null;
|
||||
if (t?.trigger !== token?.trigger || t?.query !== token?.query) setActive(0);
|
||||
setToken(t);
|
||||
};
|
||||
|
||||
const pick = (item: Suggestion) => {
|
||||
const ta = ref.current;
|
||||
if (!ta || !token) return;
|
||||
const after = ta.value.slice(token.end);
|
||||
const insert = item.insert + (after.startsWith(" ") ? "" : " ");
|
||||
ta.value = ta.value.slice(0, token.start) + insert + after;
|
||||
const caret = token.start + insert.length;
|
||||
ta.setSelectionRange(caret, caret);
|
||||
ta.focus();
|
||||
setToken(null);
|
||||
};
|
||||
|
||||
const keyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (open && !e.ctrlKey && !e.metaKey && !e.altKey) {
|
||||
const step = { ArrowDown: 1, ArrowUp: -1 }[e.key];
|
||||
if (step) {
|
||||
e.preventDefault();
|
||||
setActive((current + step + items.length) % items.length);
|
||||
return;
|
||||
}
|
||||
if (e.key === "Enter" || e.key === "Tab") {
|
||||
e.preventDefault();
|
||||
pick(items[current]);
|
||||
return;
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
// Die Seitenleiste soll nicht mit umschalten (useEscToggle).
|
||||
e.preventDefault();
|
||||
setToken(null);
|
||||
return;
|
||||
}
|
||||
}
|
||||
onKeyDown?.(e);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<textarea
|
||||
{...props}
|
||||
ref={ref}
|
||||
onKeyDown={keyDown}
|
||||
onInput={update}
|
||||
onClick={update}
|
||||
onKeyUp={(e) => {
|
||||
if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "Home" || e.key === "End") update();
|
||||
}}
|
||||
onBlur={() => setToken(null)}
|
||||
aria-autocomplete="list"
|
||||
aria-controls={open ? listId : undefined}
|
||||
aria-expanded={open}
|
||||
aria-activedescendant={open ? `${listId}-${current}` : undefined}
|
||||
/>
|
||||
{open && (
|
||||
<ul
|
||||
id={listId}
|
||||
className="suggest"
|
||||
role="listbox"
|
||||
aria-label={token?.trigger === "#" ? "Hashtag einfügen" : "Nutzer erwähnen"}
|
||||
>
|
||||
{items.map((item, i) => (
|
||||
<li
|
||||
key={item.key}
|
||||
id={`${listId}-${i}`}
|
||||
role="option"
|
||||
aria-selected={i === current}
|
||||
className="byline"
|
||||
// mousedown statt click: sonst verliert das Textfeld vorher den
|
||||
// Fokus, und onBlur schließt die Liste.
|
||||
onMouseDown={(e) => {
|
||||
e.preventDefault();
|
||||
pick(item);
|
||||
}}
|
||||
>
|
||||
{item.label}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -122,7 +122,7 @@ Inhalte, die gegen deutsches Recht verstoßen, sind verboten. Dazu gehören insb
|
||||
<li>Temporäre Sperre</li>
|
||||
<li>Permanente Sperre</li>
|
||||
</ol>
|
||||
<em>Einspruch:</em> Per E-Mail an <a>stress@bnd.wtf</a>
|
||||
<em>Einspruch:</em> Per E-Mail an <a>kontakt@irldata.de</a>
|
||||
</p>
|
||||
|
||||
<p><strong>§10 Änderungen</strong><br><br>
|
||||
|
||||
@@ -6,7 +6,7 @@ Merseburger Str. 108<br>
|
||||
06110 Halle (Saale)<br>
|
||||
<br>
|
||||
Telefon: +49-15782760787<br>
|
||||
E-Mail: <a>stress@bnd.wtf</a>
|
||||
E-Mail: <a>kontakt@irldata.de</a>
|
||||
</p>
|
||||
|
||||
<p><strong>Übersicht der erfassten Daten</strong></p>
|
||||
|
||||
@@ -10,7 +10,7 @@ David Bernet<br>
|
||||
</p>
|
||||
<p><strong>Kontakt:</strong> <br>
|
||||
Telefon: +49-15782760787<br>
|
||||
E-Mail: <a>stress@bnd.wtf</a></p>
|
||||
E-Mail: <a>kontakt@irldata.de</a></p>
|
||||
<p><strong>Verbraucherstreitbeilegung / Universalschlichtungsstelle</strong>
|
||||
<br>Wir nehmen nicht an Streitbeilegungsverfahren vor einer Verbraucherschlichtungsstelle teil und sind dazu auch nicht verpflichtet.
|
||||
</p>
|
||||
|
||||
@@ -1,15 +1,10 @@
|
||||
<div id="sigils" aria-hidden="true">
|
||||
<img src="/static/assets/sigils/anarchy_a.svg" alt="">
|
||||
<img src="/static/assets/sigils/chaos_star.svg" alt="">
|
||||
<img src="/static/assets/sigils/sab_cat.svg" alt="">
|
||||
</div>
|
||||
<h1>Info</h1>
|
||||
|
||||
<p>Der Kontrollverlust ist ein freies Forum für anarchistische Menschen in Mitteldeutschland.</p>
|
||||
<p>Der Kontrollverlust ist ein freies Forum für Menschen in Mitteldeutschland.</p>
|
||||
|
||||
<h2>Tastenkürzel</h2>
|
||||
<dl>
|
||||
<dt><kbd>Shift</kbd> + <kbd>Enter</kbd></dt>
|
||||
<dt><kbd>Strg</kbd> + <kbd>Enter</kbd> (Mac: <kbd>Cmd</kbd> + <kbd>Enter</kbd>)</dt>
|
||||
<dd>Beitrag, Antwort oder Bearbeitung abschicken. <kbd>Enter</kbd> allein macht einen Zeilenumbruch.</dd>
|
||||
<dt><kbd>←</kbd> / <kbd>→</kbd></dt>
|
||||
<dd>Auf der Beitragsseite: zum vorherigen bzw. nächsten Beitrag unter demselben Elternbeitrag. Bei einem Rootpost sind das die Nachbarn im Feed.</dd>
|
||||
@@ -20,6 +15,51 @@
|
||||
<h2>Changelog</h2>
|
||||
<!-- Neuester Tag oben, darunter kurze Stichpunkte. Einträge per
|
||||
./changelog.sh 'Stichpunkt' (legt den Abschnitt für heute bei Bedarf an). -->
|
||||
<h3>22.11.2026</h3>
|
||||
<ul>
|
||||
<li>Sicherheit: Sitzungen werden serverseitig nur noch als Hash gespeichert. Dafür wurden alle bestehenden Anmeldungen einmalig beendet, bitte neu anmelden.</li>
|
||||
</ul>
|
||||
<h3>21.11.2026</h3>
|
||||
<ul>
|
||||
<li>Bilder können hinter einem Hinweis liegen: dann erscheint erst eine verpixelte Fassung, das Bild selbst nach Klick auf „Inhalt anzeigen“.</li>
|
||||
</ul>
|
||||
<h3>13.11.2026</h3>
|
||||
<ul>
|
||||
<li>Abschicken jetzt mit <kbd>Strg</kbd> + <kbd>Enter</kbd> (Mac: <kbd>Cmd</kbd> + <kbd>Enter</kbd>) statt <kbd>Shift</kbd> + <kbd>Enter</kbd></li>
|
||||
<li>Helles Design: Hintergrund in warmem Off-White statt reinem Weiß, angenehmer zu lesen</li>
|
||||
<li>Beiträge und Chats: Anzeigename und @handle stehen zweizeilig neben dem Profilbild</li>
|
||||
<li>Beiträge und Chats: Das Datum steht jetzt rechts in der Kopfzeile</li>
|
||||
<li>Neu: Benachrichtigungen. Antwortet jemand auf deinen Beitrag, zählt die Glocke in der Navigation mit; ein Klick auf die Meldung führt zur Antwort</li>
|
||||
<li>Benachrichtigungen nennen jetzt den Handle der Antwortenden und melden auch, wenn jemand deinen Beitrag repostet</li>
|
||||
<li>Benachrichtigungen übersichtlicher: was passiert ist fett, darunter Auszug und Datum, mehr Abstand, keine Unterstreichung</li>
|
||||
<li>Erwähnungen: Mit <code>@handle</code> im Beitrag erwähnst du jemanden. Der Name wird zum Profil-Link, die Person bekommt eine Benachrichtigung</li>
|
||||
<li>Beim Schreiben schlägt eine Liste unter dem Textfeld passende Nutzer vor, sobald du <code>@</code> tippst: <kbd>↑</kbd>/<kbd>↓</kbd> wählen, <kbd>Enter</kbd> oder <kbd>Tab</kbd> übernehmen, <kbd>Esc</kbd> schließt</li>
|
||||
<li>Chats: Nachrichten und Gesprächsliste haben jetzt denselben Kopf wie Beiträge (Anzeigename und @handle zweizeilig, Datum rechts)</li>
|
||||
<li>Auch für Hashtags gibt es jetzt Vorschläge beim Tippen: nach <code>#</code> erscheinen die häufigsten passenden Tags</li>
|
||||
</ul>
|
||||
<h3>07.11.2026</h3>
|
||||
<ul>
|
||||
<li>Handle und Anzeigename getrennt: Angemeldet wird mit dem Handle (@name, nur a–z, 0–9 und _), der Anzeigename ist frei wählbar, auch mit Umlauten und Emoji. Beides lässt sich in den Einstellungen ändern</li>
|
||||
<li>Bestehende Konten: Der bisherige Name ist jetzt der Anzeigename, der Handle wurde daraus abgeleitet (z. B. ä → ae)</li>
|
||||
</ul>
|
||||
<h3>31.10.2026</h3>
|
||||
<ul>
|
||||
<li>Dunkles Design: Schrift in wärmerem, gedämpftem Off-White, angenehmer zu lesen</li>
|
||||
<li>Neues Seitensymbol im Browser-Tab: das K-Logo</li>
|
||||
</ul>
|
||||
<h3>30.10.2026</h3>
|
||||
<ul>
|
||||
<li>Suche: Beiträge nach Text, Nutzer und Hashtags filtern, wahlweise ohne Antworten</li>
|
||||
<li>Hashtags in Beiträgen, Profilbeschreibungen und Chats führen zur Suche nach genau diesem Tag</li>
|
||||
</ul>
|
||||
<h3>13.10.2026</h3>
|
||||
<ul>
|
||||
<li><strong>Experimentell:</strong> Chats. Auf einem Profil sprichst du die Person 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. Ein Zähler am Chat-Symbol zeigt ungelesene Nachrichten.</li>
|
||||
<li><strong>Experimentell:</strong> Unter <em>Einstellungen → Schlüssel</em> richtest du deinen Schlüssel für die Chats ein. Er liegt bei uns, verschlüsselt mit sechs zufälligen Wörtern, die nur du kennst. Schreib sie dir auf: Ohne sie können wir dir nicht helfen, und deine Nachrichten sind weg.</li>
|
||||
<li>Dort kannst du auch die Passphrase ändern, die Schlüsseldatei herunterladen und den Schlüssel als verloren markieren, wenn die Passphrase weg ist.</li>
|
||||
<li>Chats stürzen in neueren Browsern nicht mehr mit „Unexpected Application Error“ ab.</li>
|
||||
<li>Chats: Die Passphrase merkt sich der Browser 7 Tage lang, bis zum Logout; danach fragt er wieder.</li>
|
||||
</ul>
|
||||
<h3>12.10.2026</h3>
|
||||
<ul>
|
||||
<li>Info-Seite mit Tastenkürzeln und Changelog</li>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+40
-5
@@ -1,4 +1,5 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Link } from "react-router";
|
||||
|
||||
// avatarUrl liefert den Bildpfad oder das Platzhalterbild bei leerem Avatar.
|
||||
export function avatarUrl(path: string): string {
|
||||
@@ -11,16 +12,50 @@ export function formatTime(unix: number): string {
|
||||
|
||||
const urlPattern = /https?:\/\/[^\s<]+/g;
|
||||
|
||||
// linkify macht aus URLs im Text Links und aus Zeilenumbrüchen <br>. Den Text
|
||||
// escaped React selbst.
|
||||
export function linkify(text: string): ReactNode[] {
|
||||
// Hashtag wie in der Suche (internal/httpapi/search.go): Buchstaben, Ziffern,
|
||||
// _; Erwähnung wie im Backend (internal/httpapi/mentions.go): @ und Handle.
|
||||
// Davor jeweils keines dieser Zeichen -- "a#b" ist kein Tag, "mail@bob.org"
|
||||
// keine Erwähnung.
|
||||
const tagPattern = /(^|[^\p{L}\p{N}_])(?:#([\p{L}\p{N}_]+)|@([A-Za-z0-9_]+))/gu;
|
||||
|
||||
// Mentions: Handle, wie er im Text steht (klein) -> heutiger Handle derselben
|
||||
// Person (Entry.mentions).
|
||||
export type Mentions = Record<string, string>;
|
||||
|
||||
// tagify verlinkt die Hashtags eines Textstücks auf die Suche nach genau
|
||||
// diesem Tag und die Erwähnungen aus mentions aufs Profil; unbekannte @…
|
||||
// bleiben Text.
|
||||
function tagify(text: string, key: string, mentions: Mentions): ReactNode[] {
|
||||
const out: ReactNode[] = [];
|
||||
let last = 0;
|
||||
for (const m of text.matchAll(tagPattern)) {
|
||||
const start = m.index + m[1].length;
|
||||
const [tag, handle] = [m[2], m[3]];
|
||||
const to = tag ? `/search?tag=${encodeURIComponent(tag)}` : mentions[handle.toLowerCase()];
|
||||
if (!to) continue;
|
||||
if (start > last) out.push(text.slice(last, start));
|
||||
out.push(
|
||||
<Link key={`${key}-t${start}`} to={tag ? to : `/u/${encodeURIComponent(to)}`}>
|
||||
{tag ? `#${tag}` : `@${handle}`}
|
||||
</Link>,
|
||||
);
|
||||
last = m.index + m[0].length;
|
||||
}
|
||||
if (last < text.length) out.push(text.slice(last));
|
||||
return out;
|
||||
}
|
||||
|
||||
// linkify macht aus URLs im Text Links, aus Hashtags Links auf die Suche, aus
|
||||
// bekannten Erwähnungen Links aufs Profil und aus Zeilenumbrüchen <br>. Den
|
||||
// Text escaped React selbst.
|
||||
export function linkify(text: string, mentions: Mentions = {}): ReactNode[] {
|
||||
const out: ReactNode[] = [];
|
||||
text.split("\n").forEach((line, i) => {
|
||||
if (i > 0) out.push(<br key={`br${i}`} />);
|
||||
let last = 0;
|
||||
for (const m of line.matchAll(urlPattern)) {
|
||||
const start = m.index;
|
||||
if (start > last) out.push(line.slice(last, start));
|
||||
if (start > last) out.push(...tagify(line.slice(last, start), `${i}-${last}`, mentions));
|
||||
out.push(
|
||||
<a key={`a${i}-${start}`} href={m[0]} target="_blank" rel="noopener">
|
||||
{m[0]}
|
||||
@@ -28,7 +63,7 @@ export function linkify(text: string): ReactNode[] {
|
||||
);
|
||||
last = start + m[0].length;
|
||||
}
|
||||
if (last < line.length) out.push(line.slice(last));
|
||||
if (last < line.length) out.push(...tagify(line.slice(last), `${i}-${last}`, mentions));
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { fetchSecrets, ImportError, unlockKey } from "./keystore";
|
||||
|
||||
// Der Schlüsselbund: die eigenen privaten Schlüssel, entsperrt im Speicher
|
||||
// des Tabs (notes/chats.md). Entsperrt wird mit der Passphrase; die merkt
|
||||
// sich der Browser rememberDays lang im localStorage (nur für diese Origin
|
||||
// lesbar), damit sie nicht bei jedem Neuladen fällig ist. 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 (handle); current ist der aktuelle
|
||||
// Schlüssel zum Signieren, all alle entsperrbaren zum Entschlüsseln.
|
||||
export type Keyring = { handle: 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 und merkt
|
||||
// sie sich. 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(handle: string, passphrase: string) {
|
||||
await unlock(handle, passphrase);
|
||||
remember(handle, passphrase);
|
||||
}
|
||||
|
||||
async function unlock(handle: 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({ handle, fingerprint: current.fingerprint, current: key, all });
|
||||
}
|
||||
|
||||
// lockKeyring vergisst die entsperrten Schlüssel und die gemerkte
|
||||
// Passphrase, etwa nach einem neuen Schlüssel, „als verloren markieren“ oder
|
||||
// dem Logout.
|
||||
export function lockKeyring() {
|
||||
forgetPassphrase();
|
||||
set(null);
|
||||
}
|
||||
|
||||
// Gemerkte Passphrase: ab der Eingabe rememberDays gültig, danach wird sie
|
||||
// wieder abgefragt. Ohne Storage (privates Fenster o. ä.) eben jedes Mal.
|
||||
export const rememberDays = 7;
|
||||
const storeKey = "kver.passphrase";
|
||||
type Remembered = { handle: string; passphrase: string; until: number };
|
||||
|
||||
function remember(handle: string, passphrase: string) {
|
||||
const r: Remembered = { handle, passphrase, until: Date.now() + rememberDays * 86_400_000 };
|
||||
try {
|
||||
localStorage.setItem(storeKey, JSON.stringify(r));
|
||||
} catch {
|
||||
// egal, siehe oben
|
||||
}
|
||||
}
|
||||
|
||||
function remembered(handle: string): string | null {
|
||||
try {
|
||||
const r = JSON.parse(localStorage.getItem(storeKey) ?? "null") as Remembered | null;
|
||||
if (r && r.handle === handle && r.until > Date.now()) return r.passphrase;
|
||||
} catch {
|
||||
// unlesbar: wie nicht gemerkt
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// forgetPassphrase löscht die gemerkte Passphrase, etwa wenn sie nicht mehr
|
||||
// passt (Passphrase geändert).
|
||||
export function forgetPassphrase() {
|
||||
try {
|
||||
localStorage.removeItem(storeKey);
|
||||
} catch {
|
||||
// egal
|
||||
}
|
||||
}
|
||||
|
||||
export const hasRememberedPassphrase = (handle: string) => remembered(handle) !== null;
|
||||
|
||||
// unlockRemembered entsperrt mit der gemerkten Passphrase, ohne ihre Frist zu
|
||||
// verlängern. Passt sie nicht mehr, wird sie vergessen. Läuft schon ein
|
||||
// Versuch, wartet es auf diesen.
|
||||
let pending: Promise<void> | null = null;
|
||||
export function unlockRemembered(handle: string): Promise<void> {
|
||||
const passphrase = remembered(handle);
|
||||
if (!passphrase) return Promise.resolve();
|
||||
pending ??= unlock(handle, passphrase)
|
||||
.catch((err) => {
|
||||
if (err instanceof ImportError) forgetPassphrase();
|
||||
})
|
||||
.finally(() => (pending = null));
|
||||
return pending;
|
||||
}
|
||||
|
||||
const subscribe = (l: () => void) => {
|
||||
listeners.add(l);
|
||||
return () => listeners.delete(l);
|
||||
};
|
||||
|
||||
// useKeyring liefert den Schlüsselbund des Kontos handle, sonst null
|
||||
// (zu oder einem anderen Konto entsperrt).
|
||||
export function useKeyring(handle: string | undefined): Keyring | null {
|
||||
const r = useSyncExternalStore(subscribe, () => ring);
|
||||
return r && r.handle === handle ? r : null;
|
||||
}
|
||||
@@ -39,13 +39,13 @@ export function useSiblingKeys(prev: number, next: number) {
|
||||
}, [prev, next, navigate]);
|
||||
}
|
||||
|
||||
// submitOnShiftEnter schickt das Formular eines Textfelds mit Shift+Enter ab.
|
||||
// Enter allein bleibt der Zeilenumbruch: ein Beitrag ist oft mehrzeilig, und
|
||||
// ein versehentlich abgeschickter halber Satz lässt sich nicht zurückholen.
|
||||
// requestSubmit statt submit(), weil submit() den onSubmit-Handler des
|
||||
// Formulars umgehen und die Seite neu laden würde.
|
||||
export function submitOnShiftEnter(e: ReactKeyboardEvent<HTMLTextAreaElement>) {
|
||||
if (e.key !== "Enter" || !e.shiftKey) return;
|
||||
// submitOnCtrlEnter schickt das Formular eines Textfelds mit Strg+Enter ab
|
||||
// (auf dem Mac auch Cmd+Enter). Enter allein bleibt der Zeilenumbruch: ein
|
||||
// Beitrag ist oft mehrzeilig, und ein versehentlich abgeschickter halber Satz
|
||||
// lässt sich nicht zurückholen. requestSubmit statt submit(), weil submit()
|
||||
// den onSubmit-Handler des Formulars umgehen und die Seite neu laden würde.
|
||||
export function submitOnCtrlEnter(e: ReactKeyboardEvent<HTMLTextAreaElement>) {
|
||||
if (e.key !== "Enter" || !(e.ctrlKey || e.metaKey)) return;
|
||||
e.preventDefault();
|
||||
e.currentTarget.form?.requestSubmit();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
// Schlüsselverwaltung im Browser (Plan: notes/schluessel.md): Prüfung der
|
||||
// Browser-Fähigkeiten, Erzeugen und Entsperren. Alles Kryptographische macht
|
||||
// OpenPGP.js. Der Server bekommt den öffentlichen Schlüssel und den privaten
|
||||
// nur mit der Passphrase verschlüsselt; die Passphrase verlässt den Browser
|
||||
// nie.
|
||||
|
||||
import { api } from "./api";
|
||||
|
||||
export type Support = { generate: boolean; sign: boolean; encrypt: boolean; protect: boolean };
|
||||
|
||||
export const supported = (s: Support) => s.generate && s.sign && s.encrypt && s.protect;
|
||||
|
||||
// Schutz des privaten Schlüssels: Argon2 (verlangt AEAD-Schutz des
|
||||
// Schlüsselpakets). Der Server nimmt nichts Schwächeres an (pgpkey.CheckSecret).
|
||||
const protectConfig = async (): Promise<Partial<import("openpgp").Config>> => {
|
||||
const openpgp = await loadOpenPGP();
|
||||
return { s2kType: openpgp.enums.s2k.argon2, aeadProtect: true };
|
||||
};
|
||||
|
||||
// openpgp ist groß und wird nur hier gebraucht -> eigener Chunk, nachgeladen
|
||||
// erst auf der Schlüsselseite.
|
||||
const loadOpenPGP = () => import("openpgp");
|
||||
|
||||
// probeSupport testet die Fähigkeiten selbst, statt Browser-Versionen zu
|
||||
// raten: einen OpenPGP-v6-Schlüssel erzeugen (Ed25519 + X25519, wie später
|
||||
// der echte, nur ohne Passphrase), damit signieren und verschlüsseln und ihn
|
||||
// mit einer Passphrase per Argon2 schützen (WebAssembly, braucht
|
||||
// 'wasm-unsafe-eval' in der CSP). OpenPGP.js rechnet fehlende Verfahren
|
||||
// notfalls selbst.
|
||||
export async function probeSupport(): Promise<Support> {
|
||||
const none: Support = { generate: false, sign: false, encrypt: false, protect: false };
|
||||
let openpgp: Awaited<ReturnType<typeof loadOpenPGP>>;
|
||||
let key: import("openpgp").PrivateKey;
|
||||
try {
|
||||
openpgp = await loadOpenPGP();
|
||||
({ privateKey: key } = await openpgp.generateKey({
|
||||
type: "curve25519",
|
||||
userIDs: [],
|
||||
format: "object",
|
||||
config: { v6Keys: true },
|
||||
}));
|
||||
} catch {
|
||||
return none;
|
||||
}
|
||||
|
||||
const sign = await attempt(async () => {
|
||||
const message = await openpgp.createMessage({ text: "probe" });
|
||||
const armoredSignature = await openpgp.sign({ message, signingKeys: key, detached: true });
|
||||
const signature = await openpgp.readSignature({ armoredSignature });
|
||||
const { signatures } = await openpgp.verify({ message, signature, verificationKeys: key.toPublic() });
|
||||
await signatures[0].verified;
|
||||
});
|
||||
const encrypt = await attempt(async () => {
|
||||
const encrypted = await openpgp.encrypt({
|
||||
message: await openpgp.createMessage({ text: "probe" }),
|
||||
encryptionKeys: key.toPublic(),
|
||||
});
|
||||
const { data } = await openpgp.decrypt({
|
||||
message: await openpgp.readMessage({ armoredMessage: encrypted }),
|
||||
decryptionKeys: key,
|
||||
});
|
||||
if (data !== "probe") throw new Error("decrypt");
|
||||
});
|
||||
const protect = await attempt(async () => {
|
||||
const locked = await openpgp.encryptKey({
|
||||
privateKey: key,
|
||||
passphrase: "probe",
|
||||
config: await protectConfig(),
|
||||
});
|
||||
await openpgp.decryptKey({ privateKey: locked, passphrase: "probe" });
|
||||
});
|
||||
return { generate: true, sign, encrypt, protect };
|
||||
}
|
||||
|
||||
async function attempt(fn: () => Promise<unknown>): Promise<boolean> {
|
||||
try {
|
||||
await fn();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// KeyInfo ist ein öffentlicher Schlüssel, wie die API ihn liefert (key ist
|
||||
// das binäre Zertifikat als Base64).
|
||||
export type KeyInfo = {
|
||||
fingerprint: string;
|
||||
key: string;
|
||||
status: "current" | "replaced" | "lost";
|
||||
created_at: number;
|
||||
};
|
||||
|
||||
// NewKey ist ein frisch erzeugter Schlüssel: privat (mit Passphrase
|
||||
// verschlüsselt) und öffentlich, beide binär.
|
||||
export type NewKey = {
|
||||
fingerprint: string;
|
||||
privateBinary: Uint8Array;
|
||||
publicBinary: Uint8Array;
|
||||
};
|
||||
|
||||
// Passphrase: sechs zufällige Wörter aus der EFF-Liste (7776 Wörter, je
|
||||
// 12,9 Bit -> rund 77 Bit). Mit Argon2 offline praktisch nicht zu knacken.
|
||||
// Eine eigene Passphrase gibt es bewusst nicht.
|
||||
// Wortliste: EFF Large Wordlist, Electronic Frontier Foundation, CC BY 3.0 US
|
||||
// (https://www.eff.org/dice).
|
||||
export const passphraseWords = 6;
|
||||
|
||||
export async function generatePassphrase(): Promise<string[]> {
|
||||
const words = (await import("./eff_large_wordlist.txt?raw")).default.trim().split("\n");
|
||||
// Gleichverteilt: Zufallszahlen oberhalb des größten Vielfachen der
|
||||
// Listenlänge verwerfen, statt per Modulo zu verzerren.
|
||||
const limit = Math.floor(2 ** 32 / words.length) * words.length;
|
||||
const out: string[] = [];
|
||||
const buf = new Uint32Array(1);
|
||||
while (out.length < passphraseWords) {
|
||||
crypto.getRandomValues(buf);
|
||||
if (buf[0] < limit) out.push(words[buf[0] % words.length]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// normalizePassphrase macht aus einer Eingabe die Form, mit der der Schlüssel
|
||||
// verschlüsselt wurde: Kleinbuchstaben, Wörter durch genau ein Leerzeichen
|
||||
// getrennt. So schaden beim Abtippen weder Großschreibung noch Zeilenumbrüche.
|
||||
export const normalizePassphrase = (input: string) => input.trim().toLowerCase().split(/\s+/).join(" ");
|
||||
|
||||
// generateKey erzeugt den Schlüssel eines Accounts: OpenPGP v6, Ed25519 mit
|
||||
// X25519-Unterschlüssel, Passphrase per Argon2. Ohne User-ID und ohne
|
||||
// Ablaufdatum: Er dient nur den Direktnachrichten und wird allein über
|
||||
// unseren Server verteilt, der ihn dem Konto zuordnet.
|
||||
export async function generateKey(passphrase: string): Promise<NewKey> {
|
||||
const openpgp = await loadOpenPGP();
|
||||
const { privateKey, publicKey } = await openpgp.generateKey({
|
||||
type: "curve25519",
|
||||
userIDs: [],
|
||||
passphrase,
|
||||
format: "object",
|
||||
config: { v6Keys: true, ...(await protectConfig()) },
|
||||
});
|
||||
return {
|
||||
fingerprint: publicKey.getFingerprint(),
|
||||
privateBinary: privateKey.write(),
|
||||
publicBinary: publicKey.write(),
|
||||
};
|
||||
}
|
||||
|
||||
// formatFingerprint gliedert den Hex-Fingerprint in Vierergruppen.
|
||||
export const formatFingerprint = (hex: string) => hex.toUpperCase().replace(/(.{4})(?!$)/g, "$1 ");
|
||||
|
||||
export function toBase64(bytes: Uint8Array): string {
|
||||
let s = "";
|
||||
for (const b of bytes) s += String.fromCharCode(b);
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
export function fromBase64(b64: string): Uint8Array {
|
||||
return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
|
||||
}
|
||||
|
||||
// download bietet text als Datei zum Speichern an.
|
||||
export function download(filename: string, text: string) {
|
||||
const url = URL.createObjectURL(new Blob([text], { type: "application/pgp-keys" }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = filename;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||
}
|
||||
|
||||
// ImportError trägt eine Meldung für die Anzeige.
|
||||
export class ImportError extends Error {}
|
||||
|
||||
type PrivateKey = import("openpgp").PrivateKey;
|
||||
|
||||
// OwnSecret ist ein eigener privater Schlüssel, wie /user/keys/secret ihn
|
||||
// liefert (secret verschlüsselt, Base64); current ist der aktuelle.
|
||||
export type OwnSecret = { fingerprint: string; secret: string; current: boolean };
|
||||
|
||||
// fetchSecrets holt alle eigenen privaten Schlüssel, neueste zuerst.
|
||||
export async function fetchSecrets(): Promise<OwnSecret[]> {
|
||||
return (await api.get<{ keys: OwnSecret[] }>("/user/keys/secret")).keys;
|
||||
}
|
||||
|
||||
// unlockKey entschlüsselt den privaten Schlüssel (Base64 wie von
|
||||
// /user/key/secret) mit der Passphrase. Das Ergebnis bleibt im Speicher.
|
||||
export async function unlockKey(secret: string, passphrase: string): Promise<PrivateKey> {
|
||||
const openpgp = await loadOpenPGP();
|
||||
const privateKey = await openpgp.readPrivateKey({ binaryKey: fromBase64(secret) });
|
||||
try {
|
||||
return await openpgp.decryptKey({ privateKey, passphrase: normalizePassphrase(passphrase) });
|
||||
} catch {
|
||||
throw new ImportError("Die Passphrase stimmt nicht.");
|
||||
}
|
||||
}
|
||||
|
||||
// lockKey verschlüsselt einen entsperrten Schlüssel mit einer neuen
|
||||
// Passphrase, zum Hochladen.
|
||||
export async function lockKey(key: PrivateKey, passphrase: string): Promise<Uint8Array> {
|
||||
const openpgp = await loadOpenPGP();
|
||||
const locked = await openpgp.encryptKey({ privateKey: key, passphrase, config: await protectConfig() });
|
||||
return locked.write();
|
||||
}
|
||||
|
||||
// armorSecret macht aus dem privaten Schlüssel (Base64) eine Schlüsseldatei
|
||||
// -- weiterhin verschlüsselt.
|
||||
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/{handle}.
|
||||
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 };
|
||||
}
|
||||
+11
-5
@@ -9,9 +9,13 @@ import { EntryPage } from "./pages/EntryPage";
|
||||
import { UserPage } from "./pages/UserPage";
|
||||
import { StatsPage } from "./pages/StatsPage";
|
||||
import { ResetPage } from "./pages/ResetPage";
|
||||
import { MePage, Placeholder } from "./pages/Placeholder";
|
||||
import { MePage } from "./pages/Placeholder";
|
||||
import { NotificationsPage } from "./pages/NotificationsPage";
|
||||
import { DocPage } from "./pages/DocPage";
|
||||
import { SettingsPage } from "./pages/SettingsPage";
|
||||
import { KeysPage } from "./pages/KeysPage";
|
||||
import { ChatPage, ChatsPage } from "./pages/ChatsPage";
|
||||
import { SearchPage } from "./pages/SearchPage";
|
||||
import { applyTheme, loadTheme } from "./theme";
|
||||
import "./app.css";
|
||||
|
||||
@@ -38,14 +42,16 @@ const router = createBrowserRouter([
|
||||
children: [
|
||||
{ path: "/", element: <FeedPage /> },
|
||||
{ path: "/e/:pid", element: <EntryPage /> },
|
||||
{ path: "/u/:username", element: <UserPage /> },
|
||||
{ path: "/u/:handle", element: <UserPage /> },
|
||||
{ path: "/stats", element: <StatsPage /> },
|
||||
{ path: "/reset", element: <ResetPage /> },
|
||||
{ path: "/me", element: <MePage /> },
|
||||
{ path: "/search", element: <Placeholder title="Suche" /> },
|
||||
{ path: "/notifications", element: <Placeholder title="Benachrichtigungen" /> },
|
||||
{ path: "/chats", element: <Placeholder title="Chats" /> },
|
||||
{ path: "/search", element: <SearchPage /> },
|
||||
{ path: "/notifications", element: <NotificationsPage /> },
|
||||
{ path: "/chats", element: <ChatsPage /> },
|
||||
{ path: "/chats/:handle", element: <ChatPage /> },
|
||||
{ path: "/settings", element: <SettingsPage /> },
|
||||
{ path: "/settings/keys", element: <KeysPage /> },
|
||||
{ path: "/info", element: <DocPage name="info" /> },
|
||||
{ path: "/impressum", element: <DocPage name="impressum" /> },
|
||||
{ path: "/datenschutz", element: <DocPage name="datenschutz" /> },
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { api } from "./api";
|
||||
import { useMe } from "./auth";
|
||||
|
||||
// Benachrichtigungen (notes/api.md): der Zähler am Glocken-Icon fragt
|
||||
// angemeldet alle 30 Sekunden nach; die Liste markiert beim Abruf alles als
|
||||
// gesehen, danach steht der Zähler sofort auf 0.
|
||||
|
||||
export type Notification = {
|
||||
id: number;
|
||||
kind: "reply" | "mention" | "bump";
|
||||
// Was passiert ist, etwa "@bob hat auf deinen Beitrag geantwortet."
|
||||
message: string;
|
||||
// Anfang des zitierten Beitrags, '' = keiner.
|
||||
excerpt: string;
|
||||
// Interner Pfad, etwa /e/123.
|
||||
link: string;
|
||||
created_at: number;
|
||||
// Stand vor dem Abruf: false = neu.
|
||||
seen: boolean;
|
||||
};
|
||||
|
||||
const pollUnread = 30_000;
|
||||
|
||||
export function useUnreadNotifications() {
|
||||
const me = useMe().data;
|
||||
return (
|
||||
useQuery({
|
||||
queryKey: ["notifications", "unread"],
|
||||
queryFn: async () => (await api.get<{ unread: number }>("/notifications/unread")).unread,
|
||||
enabled: !!me,
|
||||
refetchInterval: pollUnread,
|
||||
}).data ?? 0
|
||||
);
|
||||
}
|
||||
|
||||
export function useNotifications() {
|
||||
const me = useMe().data;
|
||||
const qc = useQueryClient();
|
||||
return useQuery({
|
||||
queryKey: ["notifications", "list"],
|
||||
queryFn: async () => {
|
||||
const list = (await api.get<{ notifications: Notification[] }>("/notifications")).notifications;
|
||||
qc.setQueryData(["notifications", "unread"], 0);
|
||||
return list;
|
||||
},
|
||||
enabled: !!me,
|
||||
// Jeder Besuch der Seite gilt als Ansehen.
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
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 { linkify } from "../format";
|
||||
import { Byline } from "../components/Byline";
|
||||
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}>
|
||||
<Byline
|
||||
u={c}
|
||||
to={chatPath(c.handle)}
|
||||
time={c.last_at}
|
||||
meta={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 myself = useMe().data;
|
||||
// Bis die Daten geladen sind, steht der Handle allein da.
|
||||
const bare = (handle: string) => ({ handle, display_name: "", avatar: "" });
|
||||
const them = profile.data ?? bare(other);
|
||||
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">
|
||||
<Byline
|
||||
u={m.mine ? (myself ?? bare(me)) : them}
|
||||
to={`/u/${encodeURIComponent(m.mine ? me : other)}`}
|
||||
time={m.created_at}
|
||||
after={!m.unreadable && !m.verified && " · Signatur nicht prüfbar"}
|
||||
/>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,8 @@ import { useParams } from "react-router";
|
||||
import { queryOptions, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { api, errMsg } from "../api";
|
||||
import { useMe } from "../auth";
|
||||
import { submitOnShiftEnter, useSiblingKeys } from "../keys";
|
||||
import { submitOnCtrlEnter, useSiblingKeys } from "../keys";
|
||||
import { SuggestTextarea } from "../components/SuggestTextarea";
|
||||
import { Discussion, EntryCard } from "../components/EntryCard";
|
||||
import { PostForm } from "../components/PostForm";
|
||||
import { previewPoll } from "../previewPoll";
|
||||
@@ -89,7 +90,7 @@ function ThreadView({ pid }: { pid: string }) {
|
||||
}
|
||||
|
||||
// OwnerActions: Bearbeiten und Löschen für den eigenen, nicht gelöschten
|
||||
// Beitrag. Gespeichert wird wie beim Verfassen auch mit Shift+Enter.
|
||||
// Beitrag. Gespeichert wird wie beim Verfassen auch mit Strg+Enter.
|
||||
function OwnerActions({ entry, onChange }: { entry: Entry; onChange: () => void }) {
|
||||
const [editing, setEditing] = useState(false);
|
||||
|
||||
@@ -127,14 +128,14 @@ function OwnerActions({ entry, onChange }: { entry: Entry; onChange: () => void
|
||||
</button>
|
||||
{editing && (
|
||||
<form onSubmit={onSubmit}>
|
||||
<textarea
|
||||
<SuggestTextarea
|
||||
name="content"
|
||||
rows={4}
|
||||
maxLength={1000}
|
||||
defaultValue={entry.content}
|
||||
onKeyDown={submitOnShiftEnter}
|
||||
></textarea>{" "}
|
||||
<button type="submit" title="Shift+Enter">Speichern</button>{" "}
|
||||
onKeyDown={submitOnCtrlEnter}
|
||||
/>{" "}
|
||||
<button type="submit" title="Strg+Enter">Speichern</button>{" "}
|
||||
<button type="button" className="cancel" onClick={cancel}>Abbrechen</button>{" "}
|
||||
<p className="msg">{edit.isError ? errMsg(edit.error, "Bearbeiten fehlgeschlagen.") : ""}</p>
|
||||
</form>
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { Link } from "react-router";
|
||||
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 { forgetPassphrase, lockKeyring } from "../keyring";
|
||||
import { useUserKey } from "../useKey";
|
||||
import {
|
||||
armorSecret,
|
||||
download,
|
||||
formatFingerprint,
|
||||
generateKey,
|
||||
generatePassphrase,
|
||||
fetchSecrets,
|
||||
ImportError,
|
||||
lockKey,
|
||||
normalizePassphrase,
|
||||
probeSupport,
|
||||
supported,
|
||||
toBase64,
|
||||
unlockKey,
|
||||
type KeyInfo,
|
||||
type NewKey,
|
||||
type Support,
|
||||
} from "../keystore";
|
||||
|
||||
// KeysPage: Schlüssel für Ende-zu-Ende-verschlüsselte Direktnachrichten
|
||||
// (notes/schluessel.md): Browser-Prüfung, Anzeige, Einrichten,
|
||||
// Schlüsseldatei herunterladen, Passphrase ändern und als verloren markieren.
|
||||
export function KeysPage() {
|
||||
const me = useMe();
|
||||
const support = useSupport();
|
||||
return (
|
||||
<>
|
||||
<section id="settings">
|
||||
<h2>Schlüssel</h2>
|
||||
<p>
|
||||
<Link to="/settings">← Einstellungen</Link>
|
||||
</p>
|
||||
{me.data && <KeysContent handle={me.data.handle} support={support} />}
|
||||
</section>
|
||||
{me.isSuccess && !me.data && <AuthBox />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function KeysContent({ handle, support }: { handle: string; support: Support | null }) {
|
||||
return (
|
||||
<>
|
||||
<p className="muted">
|
||||
Experimentell. Mit deinem Schlüssel sind Direktnachrichten Ende-zu-Ende verschlüsselt. Er liegt bei uns,
|
||||
verschlüsselt mit deiner Passphrase. Die kennst nur du – verlierst du sie, sind auch deine Nachrichten weg.
|
||||
</p>
|
||||
<BrowserCheck support={support} />
|
||||
{support && supported(support) && <MyKey handle={handle} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function useSupport() {
|
||||
const [support, setSupport] = useState<Support | null>(null);
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
probeSupport().then((s) => live && setSupport(s));
|
||||
return () => {
|
||||
live = false;
|
||||
};
|
||||
}, []);
|
||||
return support;
|
||||
}
|
||||
|
||||
const checks: { key: keyof Support; label: string }[] = [
|
||||
{ key: "generate", label: "Schlüssel erzeugen (OpenPGP)" },
|
||||
{ key: "sign", label: "Signieren und prüfen" },
|
||||
{ key: "encrypt", label: "Ver- und entschlüsseln" },
|
||||
{ key: "protect", label: "Mit Passphrase schützen (Argon2)" },
|
||||
];
|
||||
|
||||
// BrowserCheck zeigt die Einzelergebnisse nur, wenn der Browser etwas nicht
|
||||
// kann; sonst bleibt die Prüfung unsichtbar.
|
||||
function BrowserCheck({ support }: { support: Support | null }) {
|
||||
if (!support) return <p className="muted">Prüfe Browser …</p>;
|
||||
if (supported(support)) return null;
|
||||
return (
|
||||
<>
|
||||
<h3>Browser</h3>
|
||||
<ul id="key-check">
|
||||
{checks.map((c) => (
|
||||
<li key={c.key}>
|
||||
{support[c.key] ? "✓" : "✗"} {c.label}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p className="msg">Dein Browser kann das noch nicht. Verschlüsselte Chats bleiben hier gesperrt.</p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function MyKey({ handle }: { handle: string }) {
|
||||
const server = useUserKey(handle);
|
||||
if (!server.data) return null;
|
||||
const { key, lost } = server.data;
|
||||
return key ? (
|
||||
<>
|
||||
<h3>Schlüssel hinterlegt</h3>
|
||||
<KeyDetails handle={handle} info={key} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h3>Kein Schlüssel hinterlegt</h3>
|
||||
{lost && <p className="muted">Dein bisheriger Schlüssel ist als verloren markiert. Richte einen neuen ein.</p>}
|
||||
<Setup handle={handle} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function KeyDetails({ handle, info }: { handle: string; info: KeyInfo }) {
|
||||
return (
|
||||
<>
|
||||
<ul id="key-details">
|
||||
<li>Eingerichtet: {formatTime(info.created_at)}</li>
|
||||
<li>
|
||||
Fingerprint: <code>{formatFingerprint(info.fingerprint)}</code>
|
||||
</li>
|
||||
</ul>
|
||||
<DownloadKey info={info} />
|
||||
<ChangePassphrase />
|
||||
<MarkLost handle={handle} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// fetchSecret holt den verschlüsselten privaten Schlüssel des aktuellen
|
||||
// Schlüssels vom Server; entsperrt wird er erst im Browser.
|
||||
async function fetchSecret() {
|
||||
const current = (await fetchSecrets()).find((k) => k.current);
|
||||
if (!current) throw new ImportError("Kein Schlüssel hinterlegt.");
|
||||
return current.secret;
|
||||
}
|
||||
|
||||
// failMsg zeigt Meldungen aus dem Browser (ImportError) direkt, sonst die
|
||||
// des Servers.
|
||||
const failMsg = (err: Error, fallback: string) => (err instanceof ImportError ? err.message : errMsg(err, fallback));
|
||||
|
||||
// DownloadKey bietet den privaten Schlüssel als Datei an, verschlüsselt wie
|
||||
// hinterlegt.
|
||||
function DownloadKey({ info }: { info: KeyInfo }) {
|
||||
const save = useMutation({
|
||||
mutationFn: async () => {
|
||||
download(`kontrollverlust-${info.fingerprint.slice(0, 8)}.asc`, await armorSecret(await fetchSecret()));
|
||||
},
|
||||
});
|
||||
return (
|
||||
<form id="key-download" onSubmit={(e) => (e.preventDefault(), save.mutate())}>
|
||||
<button type="submit" disabled={save.isPending}>
|
||||
Schlüsseldatei herunterladen
|
||||
</button>
|
||||
<p className="msg">{save.isError ? errMsg(save.error, "Herunterladen fehlgeschlagen.") : ""}</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
// ChangePassphrase entsperrt den Schlüssel mit der bisherigen Passphrase,
|
||||
// erzeugt eine neue und lädt ihn damit verschlüsselt wieder hoch.
|
||||
function ChangePassphrase() {
|
||||
const [next, setNext] = useState<{ key: Awaited<ReturnType<typeof unlockKey>>; passphrase: string } | null>(null);
|
||||
const [done, setDone] = useState(false);
|
||||
const unlock = useMutation({
|
||||
mutationFn: async (old: string) => {
|
||||
const key = await unlockKey(await fetchSecret(), old);
|
||||
return { key, passphrase: (await generatePassphrase()).join(" ") };
|
||||
},
|
||||
onSuccess: (n) => (setNext(n), setDone(false)),
|
||||
});
|
||||
const store = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!next) return;
|
||||
const fd = new FormData();
|
||||
fd.set("secret", toBase64(await lockKey(next.key, next.passphrase)));
|
||||
await api.post("/user/key/passphrase", fd);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Die gemerkte Passphrase ist die alte.
|
||||
forgetPassphrase();
|
||||
setNext(null);
|
||||
setDone(true);
|
||||
},
|
||||
});
|
||||
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
unlock.mutate(String(new FormData(e.currentTarget).get("passphrase") ?? ""));
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<h3>Passphrase ändern</h3>
|
||||
{next ? (
|
||||
<ConfirmPassphrase
|
||||
id="key-newpass"
|
||||
passphrase={next.passphrase}
|
||||
submit="Neue Passphrase speichern"
|
||||
pending={store.isPending}
|
||||
error={store.isError ? errMsg(store.error, "Speichern fehlgeschlagen.") : ""}
|
||||
onConfirm={() => store.mutate()}
|
||||
onCancel={() => setNext(null)}
|
||||
/>
|
||||
) : (
|
||||
<form id="key-pass" onSubmit={onSubmit}>
|
||||
<PassphraseInput placeholder="Bisherige Passphrase" />
|
||||
<button type="submit" disabled={unlock.isPending}>
|
||||
{unlock.isPending ? "Prüfe …" : "Neue Passphrase erzeugen"}
|
||||
</button>
|
||||
<p className="msg">
|
||||
{unlock.isError
|
||||
? failMsg(unlock.error, "Prüfen fehlgeschlagen.")
|
||||
: done
|
||||
? "Neue Passphrase gespeichert."
|
||||
: ""}
|
||||
</p>
|
||||
</form>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function PassphraseInput({ placeholder }: { placeholder: string }) {
|
||||
return <input name="passphrase" type="text" placeholder={placeholder} autoComplete="off" spellCheck={false} />;
|
||||
}
|
||||
|
||||
// MarkLost markiert den Schlüssel als verloren, wenn die Passphrase weg ist:
|
||||
// Der Server liefert ihn nicht mehr aus, danach lässt sich ein neuer
|
||||
// einrichten. Nachrichten an den alten bleiben unlesbar.
|
||||
function MarkLost({ handle }: { handle: string }) {
|
||||
const qc = useQueryClient();
|
||||
const lost = useMutation({
|
||||
mutationFn: () => api.post("/user/key/lost", new FormData()),
|
||||
onSuccess: () => {
|
||||
// Der entsperrte Schlüsselbund gehört zum bisherigen Schlüssel.
|
||||
lockKeyring();
|
||||
return qc.invalidateQueries({ queryKey: ["key", handle] });
|
||||
},
|
||||
});
|
||||
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
if (confirm("Schlüssel wirklich als verloren markieren?")) lost.mutate();
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<h3>Als verloren markieren</h3>
|
||||
<form id="key-lost" onSubmit={onSubmit}>
|
||||
<button type="submit" disabled={lost.isPending}>
|
||||
Als verloren markieren
|
||||
</button>
|
||||
<p className="msg">{lost.isError ? errMsg(lost.error, "Markieren fehlgeschlagen.") : ""}</p>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Setup führt durch das Einrichten: Schlüssel samt Passphrase erzeugen,
|
||||
// Passphrase einmal wiederholen lassen, dann öffentlichen und verschlüsselten
|
||||
// privaten Schlüssel hinterlegen.
|
||||
type Created = { key: NewKey; passphrase: string };
|
||||
|
||||
function Setup({ handle }: { handle: string }) {
|
||||
const [created, setCreated] = useState<Created | null>(null);
|
||||
return created ? (
|
||||
<SaveKey handle={handle} created={created} onCancel={() => setCreated(null)} />
|
||||
) : (
|
||||
<CreateKey onCreated={setCreated} />
|
||||
);
|
||||
}
|
||||
|
||||
function CreateKey({ onCreated }: { onCreated: (c: Created) => void }) {
|
||||
const create = useMutation({
|
||||
mutationFn: async () => {
|
||||
const passphrase = (await generatePassphrase()).join(" ");
|
||||
return { key: await generateKey(passphrase), passphrase };
|
||||
},
|
||||
onSuccess: onCreated,
|
||||
});
|
||||
return (
|
||||
<form id="key-create" onSubmit={(e) => (e.preventDefault(), create.mutate())}>
|
||||
<button type="submit" disabled={create.isPending}>
|
||||
{create.isPending ? "Erzeuge …" : "Schlüssel erzeugen"}
|
||||
</button>
|
||||
<p className="msg">{create.isError ? errMsg(create.error, "Erzeugen fehlgeschlagen.") : ""}</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function SaveKey({ handle, created, onCancel }: { handle: string; created: Created; onCancel: () => void }) {
|
||||
const qc = useQueryClient();
|
||||
const { key, passphrase } = created;
|
||||
const upload = useMutation({
|
||||
mutationFn: async () => {
|
||||
const fd = new FormData();
|
||||
fd.set("key", toBase64(key.publicBinary));
|
||||
fd.set("secret", toBase64(key.privateBinary));
|
||||
await api.post<KeyInfo>("/user/key", fd);
|
||||
},
|
||||
onSuccess: () => {
|
||||
// Der entsperrte Schlüsselbund gehört zum bisherigen Schlüssel.
|
||||
lockKeyring();
|
||||
return qc.invalidateQueries({ queryKey: ["key", handle] });
|
||||
},
|
||||
});
|
||||
return (
|
||||
<ConfirmPassphrase
|
||||
id="key-save"
|
||||
passphrase={passphrase}
|
||||
submit="Schlüssel hinterlegen"
|
||||
pending={upload.isPending}
|
||||
error={upload.isError ? errMsg(upload.error, "Hinterlegen fehlgeschlagen.") : ""}
|
||||
onConfirm={() => upload.mutate()}
|
||||
onCancel={onCancel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// ConfirmPassphrase zeigt eine neue Passphrase und lässt sie einmal
|
||||
// wiederholen, bevor onConfirm sie verwendet.
|
||||
function ConfirmPassphrase(props: {
|
||||
id: string;
|
||||
passphrase: string;
|
||||
submit: string;
|
||||
pending: boolean;
|
||||
error: string;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
}) {
|
||||
const [msg, setMsg] = useState("");
|
||||
const onSubmit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const typed = normalizePassphrase(String(new FormData(e.currentTarget).get("passphrase") ?? ""));
|
||||
if (typed !== props.passphrase) return setMsg("Die Passphrase stimmt nicht.");
|
||||
setMsg("");
|
||||
props.onConfirm();
|
||||
};
|
||||
return (
|
||||
<form id={props.id} onSubmit={onSubmit}>
|
||||
<p>Deine Passphrase:</p>
|
||||
<p>
|
||||
<code className="passphrase">{props.passphrase}</code>
|
||||
</p>
|
||||
<PassphraseInput placeholder="Passphrase wiederholen" />
|
||||
<div className="row">
|
||||
<button type="submit" disabled={props.pending}>
|
||||
{props.submit}
|
||||
</button>
|
||||
<button type="button" onClick={props.onCancel} disabled={props.pending}>
|
||||
Verwerfen
|
||||
</button>
|
||||
</div>
|
||||
<p className="msg">{msg || props.error}</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { Link } from "react-router";
|
||||
import { errMsg } from "../api";
|
||||
import { useMe } from "../auth";
|
||||
import { AuthBox } from "../components/AuthBox";
|
||||
import { formatTime } from "../format";
|
||||
import { useNotifications } from "../notifications";
|
||||
|
||||
// NotificationsPage listet die jüngsten Benachrichtigungen; ein Klick führt
|
||||
// zum Beitrag. Fett steht, was passiert ist, darunter Auszug und Datum; was
|
||||
// beim Öffnen noch ungesehen war, trägt "neu".
|
||||
export function NotificationsPage() {
|
||||
const me = useMe();
|
||||
return (
|
||||
<>
|
||||
<section id="notifications">
|
||||
<h2>Benachrichtigungen</h2>
|
||||
{me.data && <NotificationList />}
|
||||
</section>
|
||||
{me.isSuccess && !me.data && <AuthBox />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NotificationList() {
|
||||
const list = useNotifications();
|
||||
if (list.isError) return <p className="msg">{errMsg(list.error, "Benachrichtigungen konnten nicht geladen werden.")}</p>;
|
||||
if (list.data?.length === 0) return <p className="muted">Noch keine Benachrichtigungen.</p>;
|
||||
return (
|
||||
<ul id="notification-list">
|
||||
{list.data?.map((n) => (
|
||||
<li key={n.id}>
|
||||
<Link to={n.link}>
|
||||
<strong>{n.message}</strong>
|
||||
{n.excerpt && <span className="excerpt">{n.excerpt}</span>}
|
||||
<span className="muted">
|
||||
{formatTime(n.created_at)}
|
||||
{!n.seen && " · neu"}
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,8 @@ import { Navigate } from "react-router";
|
||||
import { useMe } from "../auth";
|
||||
import { AuthBox } from "../components/AuthBox";
|
||||
|
||||
// Placeholder steht für Bereiche, die noch eigene Projekte sind (Suche,
|
||||
// Benachrichtigungen, Chats).
|
||||
// Placeholder steht für Bereiche, die noch eigene Projekte sind (siehe
|
||||
// unfinished in Nav.tsx).
|
||||
export function Placeholder({ title }: { title: string }) {
|
||||
return (
|
||||
<section>
|
||||
@@ -18,6 +18,6 @@ export function Placeholder({ title }: { title: string }) {
|
||||
export function MePage() {
|
||||
const me = useMe();
|
||||
if (!me.isSuccess) return null;
|
||||
if (me.data) return <Navigate to={`/u/${encodeURIComponent(me.data.username)}`} replace />;
|
||||
if (me.data) return <Navigate to={`/u/${encodeURIComponent(me.data.handle)}`} replace />;
|
||||
return <AuthBox />;
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ export function ResetPage() {
|
||||
queryFn: () => {
|
||||
const fd = new FormData();
|
||||
fd.append("token", token);
|
||||
return api.post<{ username: string }>("/auth/reset/check", fd);
|
||||
return api.post<{ handle: string }>("/auth/reset/check", fd);
|
||||
},
|
||||
enabled: token !== "",
|
||||
staleTime: Infinity,
|
||||
@@ -52,8 +52,8 @@ export function ResetPage() {
|
||||
{error && <p className="msg">{error}</p>}
|
||||
{check.data && (
|
||||
<form id="reset-form" onSubmit={submit}>
|
||||
<p>für <strong>{check.data.username}</strong></p>
|
||||
<input name="username" type="hidden" value={check.data.username} autoComplete="username" />
|
||||
<p>für <strong>@{check.data.handle}</strong></p>
|
||||
<input name="username" type="hidden" value={check.data.handle} autoComplete="username" />
|
||||
<input name="pass1" type="password" placeholder="Neues Passwort" autoComplete="new-password" />{" "}
|
||||
<input name="pass2" type="password" placeholder="Passwort wiederholen" autoComplete="new-password" />{" "}
|
||||
<button type="submit" disabled={busy}>Passwort setzen</button>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { FormEvent } from "react";
|
||||
import { useSearchParams } from "react-router";
|
||||
import { Feed } from "../components/Feed";
|
||||
|
||||
// Die Filter stehen in der Adresse (/search?q=…&user=…&tag=…&roots=1): so
|
||||
// lässt sich eine Suche verlinken, und Zurück führt zur vorigen. Sie
|
||||
// entsprechen den Parametern von /api/entry/search (notes/api.md).
|
||||
const fields = ["q", "user", "tag"] as const;
|
||||
|
||||
export function SearchPage() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const roots = params.get("roots") === "1";
|
||||
const active = fields.some((f) => params.get(f));
|
||||
|
||||
// apply übernimmt das Formular in die Adresse. Leere Felder fallen weg,
|
||||
// damit gleiche Suchen gleich aussehen. Auch der Antworten-Umschalter geht
|
||||
// hierüber, sonst wäre noch nicht abgeschickter Text danach verloren.
|
||||
const apply = (el: HTMLFormElement | null, withoutReplies: boolean) => {
|
||||
const form = new FormData(el ?? undefined);
|
||||
const next = new URLSearchParams();
|
||||
for (const f of fields) {
|
||||
const v = String(form.get(f) ?? "").trim();
|
||||
if (v) next.set(f, v);
|
||||
}
|
||||
if (withoutReplies) next.set("roots", "1");
|
||||
setParams(next);
|
||||
};
|
||||
|
||||
const submit = (e: FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
apply(e.currentTarget, roots);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<section id="search">
|
||||
<h2>Suche</h2>
|
||||
{/* key: Bei Zurück/Vor zeigen die Felder die Suche aus der Adresse. */}
|
||||
<form key={params.toString()} onSubmit={submit} role="search">
|
||||
<input name="q" type="search" placeholder="Text" defaultValue={params.get("q") ?? ""} autoFocus />
|
||||
<input name="user" type="text" placeholder="Von @handle" defaultValue={params.get("user") ?? ""} />
|
||||
<input name="tag" type="text" placeholder="#Hashtags" defaultValue={params.get("tag") ?? ""} />
|
||||
<div className="row" role="group" aria-label="Antworten">
|
||||
<button type="button" aria-pressed={!roots} onClick={(e) => apply(e.currentTarget.form, false)}>
|
||||
Mit Antworten
|
||||
</button>
|
||||
<button type="button" aria-pressed={roots} onClick={(e) => apply(e.currentTarget.form, true)}>
|
||||
Ohne Antworten
|
||||
</button>
|
||||
</div>
|
||||
<button type="submit">Suchen</button>
|
||||
</form>
|
||||
{!active && <p className="muted">Mindestens Text, Nutzer oder Hashtag angeben.</p>}
|
||||
</section>
|
||||
{active && (
|
||||
<Feed
|
||||
queryKey={["feed", "search", params.toString()]}
|
||||
urlFor={(page) => `/entry/search/${page}?${params}`}
|
||||
empty="Keine Treffer."
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router";
|
||||
import { Link, useNavigate } from "react-router";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { useAuthChanged, useMe } from "../auth";
|
||||
import { useFormAction } from "../useFormAction";
|
||||
import { AuthBox } from "../components/AuthBox";
|
||||
import { loadTheme, saveTheme, type Theme } from "../theme";
|
||||
import type { Me } from "../types";
|
||||
|
||||
// SettingsPage: Darstellung (auch ohne Konto) und Kontoeinstellungen (Name,
|
||||
// Passwort, Löschen). Profilbild, Header und Beschreibung bearbeitet man auf
|
||||
// SettingsPage: Darstellung (auch ohne Konto) und Kontoeinstellungen
|
||||
// (Anzeigename, Handle, Passwort, Löschen). Profilbild, Header und Beschreibung bearbeitet man auf
|
||||
// dem eigenen Profil.
|
||||
export function SettingsPage() {
|
||||
const me = useMe();
|
||||
@@ -16,7 +17,7 @@ export function SettingsPage() {
|
||||
<section id="settings">
|
||||
<h2>Einstellungen</h2>
|
||||
<Appearance />
|
||||
{me.data && <AccountSettings />}
|
||||
{me.data && <AccountSettings me={me.data} />}
|
||||
</section>
|
||||
{me.isSuccess && !me.data && <AuthBox />}
|
||||
</>
|
||||
@@ -48,12 +49,12 @@ function Appearance() {
|
||||
);
|
||||
}
|
||||
|
||||
function AccountSettings() {
|
||||
function AccountSettings({ me }: { me: Me }) {
|
||||
const qc = useQueryClient();
|
||||
const navigate = useNavigate();
|
||||
const authChanged = useAuthChanged();
|
||||
|
||||
// Der neue Name taucht auch in den Beitragskarten auf -> Feeds, Profile und
|
||||
// Name und Handle tauchen auch in den Beitragskarten auf -> Feeds, Profile und
|
||||
// das eigene Konto neu laden.
|
||||
const refresh = () => {
|
||||
qc.invalidateQueries({ queryKey: ["feed"] });
|
||||
@@ -62,7 +63,8 @@ function AccountSettings() {
|
||||
return authChanged();
|
||||
};
|
||||
|
||||
const rename = useFormAction<{ username: string }>("/user/rename", "Umbenennen fehlgeschlagen.", async (form) => {
|
||||
const displayName = useFormAction("/user/display_name", "Ändern fehlgeschlagen.", refresh);
|
||||
const handle = useFormAction("/user/handle", "Ändern fehlgeschlagen.", async (form) => {
|
||||
form.reset();
|
||||
await refresh();
|
||||
});
|
||||
@@ -74,13 +76,23 @@ function AccountSettings() {
|
||||
|
||||
return (
|
||||
<>
|
||||
<h3>Name ändern</h3>
|
||||
<form id="rename-form" onSubmit={rename.onSubmit}>
|
||||
<input name="user" type="text" placeholder="Neuer Nutzername" autoComplete="username" />{" "}
|
||||
<button type="submit" disabled={rename.busy}>Namen ändern</button>
|
||||
<h3>Anzeigename</h3>
|
||||
<form id="display-name-form" onSubmit={displayName.onSubmit}>
|
||||
<input name="display_name" type="text" defaultValue={me.display_name} placeholder="Anzeigename" autoComplete="nickname" />{" "}
|
||||
<button type="submit" disabled={displayName.busy}>Speichern</button>
|
||||
</form>
|
||||
<p className="msg" id="rename-msg">{rename.msg}</p>
|
||||
{rename.ok && <p className="muted">Name geändert.</p>}
|
||||
<p className="muted">Frei wählbar, auch mit Emoji. Leer: dein Handle wird angezeigt.</p>
|
||||
<p className="msg">{displayName.msg}</p>
|
||||
{displayName.ok && <p className="muted">Anzeigename gespeichert.</p>}
|
||||
|
||||
<h3>Handle ändern</h3>
|
||||
<p className="muted">Jetzt: @{me.handle}. Damit meldest du dich an, unter ihm ist dein Profil erreichbar.</p>
|
||||
<form id="handle-form" onSubmit={handle.onSubmit}>
|
||||
<input name="handle" type="text" placeholder="Neuer Handle (a–z, 0–9, _)" autoComplete="username" />{" "}
|
||||
<button type="submit" disabled={handle.busy}>Handle ändern</button>
|
||||
</form>
|
||||
<p className="msg">{handle.msg}</p>
|
||||
{handle.ok && <p className="muted">Handle geändert.</p>}
|
||||
|
||||
<h3>Passwort ändern</h3>
|
||||
<form id="password-form" onSubmit={password.onSubmit}>
|
||||
@@ -92,6 +104,11 @@ function AccountSettings() {
|
||||
<p className="msg" id="password-msg">{password.msg}</p>
|
||||
{password.ok && <p className="muted">Passwort geändert. Andere Geräte sind abgemeldet.</p>}
|
||||
|
||||
<h3>Schlüssel</h3>
|
||||
<p>
|
||||
<Link className="button" to="/settings/keys">Schlüssel verwalten</Link>
|
||||
</p>
|
||||
|
||||
<h3>Konto löschen</h3>
|
||||
<form
|
||||
id="delete-form"
|
||||
|
||||
@@ -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";
|
||||
@@ -13,18 +14,18 @@ const maxBio = 300;
|
||||
|
||||
// Beim Wechsel zu einem anderen Profil frisch anfangen (Meldungen, Formulare).
|
||||
export function UserPage() {
|
||||
const { username = "" } = useParams();
|
||||
return <ProfileView key={username} username={username} />;
|
||||
const { handle = "" } = useParams();
|
||||
return <ProfileView key={handle} handle={handle} />;
|
||||
}
|
||||
|
||||
// ProfileView: Header-Bild (ohne Bild ein schwarzer Balken), darauf
|
||||
// überlappend der Avatar, darunter Name, Beschreibung, Meta-Zeile und die
|
||||
// Beiträge. Der Eigentümer bearbeitet Bilder und Beschreibung direkt hier;
|
||||
// Name und Konto stehen unter /settings.
|
||||
function ProfileView({ username }: { username: string }) {
|
||||
function ProfileView({ handle }: { handle: string }) {
|
||||
const profile = useQuery({
|
||||
queryKey: ["profile", username],
|
||||
queryFn: () => api.get<Profile>(`/u/${encodeURIComponent(username)}/info`),
|
||||
queryKey: ["profile", handle],
|
||||
queryFn: () => api.get<Profile>(`/u/${encodeURIComponent(handle)}/info`),
|
||||
});
|
||||
const me = useMe().data;
|
||||
const [editing, setEditing] = useState(false);
|
||||
@@ -32,9 +33,9 @@ function ProfileView({ username }: { username: string }) {
|
||||
const info = profile.data;
|
||||
let name = "";
|
||||
if (profile.isError) name = errMsg(profile.error, "Profil konnte nicht geladen werden.");
|
||||
else if (info) name = info.username;
|
||||
else if (info) name = info.display_name || `@${info.handle}`;
|
||||
|
||||
const isOwner = !!me && !!info && me.username === info.username;
|
||||
const isOwner = !!me && !!info && me.handle === info.handle;
|
||||
|
||||
return (
|
||||
<section id="profile">
|
||||
@@ -49,8 +50,10 @@ function ProfileView({ username }: { username: string }) {
|
||||
{editing ? "Fertig" : "Profil bearbeiten"}
|
||||
</button>
|
||||
)}
|
||||
{me && info && !isOwner && <Contact me={me.handle} other={info.handle} />}
|
||||
</div>
|
||||
<h2 id="profile-name">{name}</h2>
|
||||
{info?.display_name && <p className="muted">@{info.handle}</p>}
|
||||
{info?.bio && <p className="bio">{linkify(info.bio)}</p>}
|
||||
<p id="profile-info" className="muted">
|
||||
{info &&
|
||||
@@ -63,14 +66,27 @@ function ProfileView({ username }: { username: string }) {
|
||||
{info && (
|
||||
<Feed
|
||||
as="div"
|
||||
queryKey={["feed", "user", username]}
|
||||
urlFor={(page) => `/u/${encodeURIComponent(username)}/feed/${page}`}
|
||||
queryKey={["feed", "user", handle]}
|
||||
urlFor={(page) => `/u/${encodeURIComponent(handle)}/feed/${page}`}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
// 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 }) {
|
||||
|
||||
+12
-4
@@ -7,14 +7,20 @@ export interface Entry {
|
||||
created_at: number;
|
||||
content: string;
|
||||
filepath: string;
|
||||
// Hinweis vor dem Bild; dann ist image_cover seine verpixelte Variante.
|
||||
image_warning?: string;
|
||||
image_cover?: string;
|
||||
reply_to: number;
|
||||
reply_count: number;
|
||||
last_activity: number;
|
||||
deleted: number;
|
||||
bump_count: number;
|
||||
last_bump: number;
|
||||
username: string;
|
||||
handle: string;
|
||||
display_name: string;
|
||||
avatar: string;
|
||||
// Erwähnte Handles, wie im Text (klein) -> heutiger Handle.
|
||||
mentions?: Record<string, string>;
|
||||
// Vorschau des ersten Links, sobald der Server sie geholt hat.
|
||||
preview?: LinkPreview;
|
||||
// Der Server holt die Vorschau noch (siehe previewPoll).
|
||||
@@ -62,16 +68,18 @@ export interface BumpResult {
|
||||
// GET /api/user/info -- das eigene Konto.
|
||||
export interface Me {
|
||||
uid: number;
|
||||
username: string;
|
||||
handle: string;
|
||||
display_name: string;
|
||||
created_at: number;
|
||||
last_login: number;
|
||||
avatar: string;
|
||||
}
|
||||
|
||||
// GET /api/u/{username}/info -- öffentliches Profil.
|
||||
// GET /api/u/{handle}/info -- öffentliches Profil.
|
||||
export interface Profile {
|
||||
uid: number;
|
||||
username: string;
|
||||
handle: string;
|
||||
display_name: string;
|
||||
created_at: number;
|
||||
avatar: string;
|
||||
// Header-Bild, '' = schwarzer Balken.
|
||||
|
||||
@@ -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(handle: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ["key", handle],
|
||||
enabled: !!handle,
|
||||
queryFn: async (): Promise<{ key: KeyInfo | null; lost: boolean }> => {
|
||||
try {
|
||||
return { key: await api.get<KeyInfo>(`/u/${encodeURIComponent(handle!)}/key`), lost: false };
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 404) return { key: null, lost: err.code === "key.lost" };
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
# Nach jedem Commit den DEV-Container im Hintergrund neu bauen und starten,
|
||||
# damit der Commit nicht auf den Build wartet. Ausgabe: .git/dev-up.log
|
||||
# Aussetzen für einen Commit: KVER_NO_DEV_UP=1 git commit ...
|
||||
[[ -n "${KVER_NO_DEV_UP:-}" ]] && exit 0
|
||||
root="$(git rev-parse --show-toplevel)"
|
||||
nohup "$root/dev-up.sh" >"$root/.git/dev-up.log" 2>&1 </dev/null &
|
||||
echo "dev-up: DEV-Container wird neu gebaut (Log: .git/dev-up.log)"
|
||||
@@ -3,22 +3,22 @@ module kver
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.3.0
|
||||
github.com/go-chi/httprate v0.15.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/go-chi/chi/v5 v5.5.0
|
||||
github.com/go-chi/httprate v0.16.1
|
||||
github.com/jackc/pgx/v5 v5.13.0
|
||||
github.com/oschwald/maxminddb-golang v1.13.1
|
||||
golang.org/x/crypto v0.57.0
|
||||
golang.org/x/image v0.41.0
|
||||
golang.org/x/net v0.59.0
|
||||
golang.org/x/crypto v0.59.0
|
||||
golang.org/x/image v0.48.0
|
||||
golang.org/x/net v0.63.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 // indirect
|
||||
github.com/zeebo/xxh3 v1.0.2 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.4 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.4.2 // indirect
|
||||
github.com/zeebo/xxh3 v1.1.0 // indirect
|
||||
golang.org/x/sync v0.25.0 // indirect
|
||||
golang.org/x/sys v0.50.0 // indirect
|
||||
golang.org/x/text v0.44.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,20 +1,20 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM=
|
||||
github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||
github.com/go-chi/httprate v0.15.0 h1:j54xcWV9KGmPf/X4H32/aTH+wBlrvxL7P+SdnRqxh5g=
|
||||
github.com/go-chi/httprate v0.15.0/go.mod h1:rzGHhVrsBn3IMLYDOZQsSU4fJNWcjui4fWKJcCId1R4=
|
||||
github.com/go-chi/chi/v5 v5.5.0 h1:xdKQ1dJmVJsmgahrXSKhUx8NyVPzpwdlyrrQFpMPJgg=
|
||||
github.com/go-chi/chi/v5 v5.5.0/go.mod h1:d1IG7GtKPSjPyBP365PH8sAGVHk3qfB/IhjFNRH1wWM=
|
||||
github.com/go-chi/httprate v0.16.1 h1:q2M8FmDsI4oEr1oRX43N+VeA0Ujd1tb/EasrSzXy87o=
|
||||
github.com/go-chi/httprate v0.16.1/go.mod h1:A8lo+qRhk+s9LiuP5saS7XCGDXRXMcrueq0NfIuCa/I=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/jackc/pgx/v5 v5.13.0 h1:Hl08k64maU0nrRyVUEbwCnK6/gT0EhMrtAqBHz9/gA4=
|
||||
github.com/jackc/pgx/v5 v5.13.0/go.mod h1:u2Fi6no03HCSBYE+ZVdLxbwdu3xyi2vU+K/YNJioSds=
|
||||
github.com/jackc/puddle/v2 v2.2.4 h1:N6Mz6EGB9DL0bz3OEfxJ7eoOpjRHnnjpOh+G8kbLoG8=
|
||||
github.com/jackc/puddle/v2 v2.2.4/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/cpuid/v2 v2.4.2 h1:xRw7IZEsAgVCp6trS/DgWbTAqpixhmywgVgBjYGg1bQ=
|
||||
github.com/klauspost/cpuid/v2 v2.4.2/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/oschwald/maxminddb-golang v1.13.1 h1:G3wwjdN9JmIK2o/ermkHM+98oX5fS+k5MbwsmL4MRQE=
|
||||
github.com/oschwald/maxminddb-golang v1.13.1/go.mod h1:K4pgV9N/GcK694KSTmVSDTODk4IsCNThNdTmnaBZ/F8=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
@@ -26,20 +26,20 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ=
|
||||
github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=
|
||||
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
|
||||
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
|
||||
golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=
|
||||
golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
|
||||
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
|
||||
golang.org/x/image v0.48.0 h1:1AvuPcuoOTJpA7s4VZ5umrb90T3So0rkB/bSGmxkxik=
|
||||
golang.org/x/image v0.48.0/go.mod h1:mmtg64iqJKGqEgy+r13dfybl85tmxUd2lMnmaiSdWYY=
|
||||
golang.org/x/net v0.63.0 h1:HCoTmNh9EpD1PpK8gBNFY4gcTY4N+KQEO8ylfIKqFJ0=
|
||||
golang.org/x/net v0.63.0/go.mod h1:15JLg3IX1bLjHK264EZQEbIpTiR/KVLuo9CTRWd0pig=
|
||||
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
|
||||
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
|
||||
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
|
||||
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
+38
-50
@@ -1,5 +1,5 @@
|
||||
// Package account verwaltet Konten und Passwörter: Anlegen, Namensregeln und
|
||||
// den Passwort-Reset per Einmal-Link.
|
||||
// Package account verwaltet Konten und Passwörter: Anlegen, Handle und
|
||||
// Anzeigename (handle.go) und den Passwort-Reset per Einmal-Link.
|
||||
package account
|
||||
|
||||
import (
|
||||
@@ -11,20 +11,15 @@ import (
|
||||
"fmt"
|
||||
mrand "math/rand/v2"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/database"
|
||||
"kver/internal/runes"
|
||||
)
|
||||
|
||||
const (
|
||||
// MinNameLen ist die Mindestlänge eines Nutzernamens in Bytes.
|
||||
MinNameLen = 3
|
||||
maxNameRunes = 32
|
||||
minPasswordLen = 10
|
||||
// bcrypt verarbeitet maximal 72 Bytes; GenerateFromPassword gäbe darüber
|
||||
// einen Fehler.
|
||||
@@ -33,27 +28,11 @@ const (
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrUsernameTaken: der Name ist vergeben (auch wenn erst der
|
||||
// UNIQUE-Constraint beim Schreiben das Rennen entschied).
|
||||
ErrUsernameTaken = apperr.Conflict("user.name_taken", "Der Nutzername wird bereits verwendet.")
|
||||
// ErrUserNotFound: zum Namen bzw. zur uid gibt es keinen Account.
|
||||
// ErrUserNotFound: zum Handle bzw. zur uid gibt es keinen Account.
|
||||
ErrUserNotFound = apperr.NotFound("user.not_found", "Nutzer nicht gefunden")
|
||||
)
|
||||
|
||||
var (
|
||||
// \p{L}\p{N} statt \w: Go-RE2-\w ist ASCII-only und würde Unicode-Namen
|
||||
// (z. B. "佳紫达尔") komplett entfernen -> Login/Rename unmöglich.
|
||||
nonNameChars = regexp.MustCompile(`[^._\p{L}\p{N}\s-]`)
|
||||
whitespace = regexp.MustCompile(`\s+`)
|
||||
)
|
||||
|
||||
// SanitizeUsername kürzt einen Namen auf 32 Runen, entfernt unerlaubte
|
||||
// Zeichen und ersetzt Leerraum durch "_".
|
||||
func SanitizeUsername(u string) string {
|
||||
u = runes.Truncate(strings.TrimSpace(u), maxNameRunes)
|
||||
u = nonNameChars.ReplaceAllString(u, "")
|
||||
return whitespace.ReplaceAllString(u, "_")
|
||||
}
|
||||
var whitespace = regexp.MustCompile(`\s+`)
|
||||
|
||||
// CheckNewPassword trägt Fehler zu einem neuen Passwort (pass1) und seiner
|
||||
// Wiederholung (pass2) in fields ein.
|
||||
@@ -88,8 +67,9 @@ func NewStore(db *sql.DB, now func() time.Time) *Store {
|
||||
return &Store{db: db, now: now}
|
||||
}
|
||||
|
||||
// Create legt den Account an und liefert dessen uid.
|
||||
func (s *Store) Create(ctx context.Context, username, password string) (int64, error) {
|
||||
// Create legt den Account an und liefert dessen uid. handle muss gültig sein
|
||||
// (ValidHandle), displayName bereinigt (CleanDisplayName).
|
||||
func (s *Store) Create(ctx context.Context, handle, displayName, password string) (int64, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("passwort hashen: %w", err)
|
||||
@@ -99,13 +79,13 @@ func (s *Store) Create(ctx context.Context, username, password string) (int64, e
|
||||
for range uidAttempts {
|
||||
uid := int64(mrand.IntN(99999999)) + 1
|
||||
_, err = s.db.ExecContext(ctx,
|
||||
`INSERT INTO account (uid, created_at, username, password) VALUES ($1, $2, $3, $4)`,
|
||||
uid, s.now().Unix(), username, hash)
|
||||
`INSERT INTO account (uid, created_at, handle, display_name, password) VALUES ($1, $2, $3, $4, $5)`,
|
||||
uid, s.now().Unix(), handle, displayName, hash)
|
||||
switch {
|
||||
case err == nil:
|
||||
return uid, nil
|
||||
case database.IsUniqueViolation(err, "account_username_key"):
|
||||
return 0, ErrUsernameTaken.WithCause(err)
|
||||
case database.IsUniqueViolation(err, "account_handle_key"):
|
||||
return 0, ErrHandleTaken.WithCause(err)
|
||||
case !database.IsUniqueViolation(err, "account_uid_key"):
|
||||
return 0, fmt.Errorf("account anlegen: %w", err)
|
||||
}
|
||||
@@ -113,21 +93,23 @@ func (s *Store) Create(ctx context.Context, username, password string) (int64, e
|
||||
return 0, fmt.Errorf("account anlegen: %w", err)
|
||||
}
|
||||
|
||||
// NameTaken meldet, ob ein Nutzername vergeben ist.
|
||||
func (s *Store) NameTaken(ctx context.Context, username string) (bool, error) {
|
||||
// HandleTaken meldet, ob ein Handle vergeben ist.
|
||||
func (s *Store) HandleTaken(ctx context.Context, handle string) (bool, error) {
|
||||
var taken bool
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT EXISTS (SELECT 1 FROM account WHERE username = $1)`, username).Scan(&taken)
|
||||
`SELECT EXISTS (SELECT 1 FROM account WHERE handle = $1)`, handle).Scan(&taken)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("nutzername prüfen: %w", err)
|
||||
return false, fmt.Errorf("handle prüfen: %w", err)
|
||||
}
|
||||
return taken, nil
|
||||
}
|
||||
|
||||
// UID liefert die uid zu einem Nutzernamen oder ErrUserNotFound.
|
||||
func (s *Store) UID(ctx context.Context, username string) (int64, error) {
|
||||
// UID liefert die uid zu einem Handle (Eingabe wie vom Nutzer, etwa "@Anna")
|
||||
// oder ErrUserNotFound.
|
||||
func (s *Store) UID(ctx context.Context, handle string) (int64, error) {
|
||||
var uid int64
|
||||
err := s.db.QueryRowContext(ctx, `SELECT uid FROM account WHERE username = $1`, username).Scan(&uid)
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT uid FROM account WHERE handle = $1`, NormalizeHandle(handle)).Scan(&uid)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrUserNotFound
|
||||
}
|
||||
@@ -137,22 +119,28 @@ func (s *Store) UID(ctx context.Context, username string) (int64, error) {
|
||||
return uid, nil
|
||||
}
|
||||
|
||||
// ErrWrongPassword: das bisherige Passwort beim Ändern stimmt nicht.
|
||||
var ErrWrongPassword = apperr.Forbidden("auth.bad_password", "Das bisherige Passwort ist falsch.").At("pass")
|
||||
// ErrWrongPassword: das eingegebene Passwort stimmt nicht. Der Aufrufer hängt
|
||||
// das Formularfeld an (At), in dem es stand.
|
||||
var ErrWrongPassword = apperr.Forbidden("auth.bad_password", "Das Passwort ist falsch.")
|
||||
|
||||
// VerifyPassword bestätigt eine heikle Aktion mit dem Passwort des Kontos.
|
||||
func (s *Store) VerifyPassword(ctx context.Context, uid int64, password string) error {
|
||||
var hash []byte
|
||||
err := s.db.QueryRowContext(ctx, `SELECT password FROM account WHERE uid = $1`, uid).Scan(&hash)
|
||||
if err != nil {
|
||||
return notFoundOr(err, "passwort")
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword(hash, []byte(password)) != nil {
|
||||
return ErrWrongPassword
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ChangePassword setzt ein neues Passwort, wenn current das bisherige ist.
|
||||
// Alle anderen Sessions des Nutzers enden; keepSession (die eigene) bleibt.
|
||||
func (s *Store) ChangePassword(ctx context.Context, uid int64, current, password, keepSession string) error {
|
||||
var old []byte
|
||||
err := s.db.QueryRowContext(ctx, `SELECT password FROM account WHERE uid = $1`, uid).Scan(&old)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("passwort lesen: %w", err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword(old, []byte(current)) != nil {
|
||||
return ErrWrongPassword
|
||||
if err := s.VerifyPassword(ctx, uid, current); err != nil {
|
||||
return err
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
|
||||
@@ -10,23 +10,6 @@ import (
|
||||
"kver/internal/testdb"
|
||||
)
|
||||
|
||||
func TestSanitizeUsername(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct{ in, want string }{
|
||||
{" alice ", "alice"},
|
||||
{"Max Mustermann", "Max_Mustermann"},
|
||||
{"a<b>c;d", "abcd"},
|
||||
{"佳紫达尔", "佳紫达尔"},
|
||||
{"x.y-z_1", "x.y-z_1"},
|
||||
{strings.Repeat("ä", 40), strings.Repeat("ä", 32)},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := SanitizeUsername(tt.in); got != tt.want {
|
||||
t.Errorf("SanitizeUsername(%q) = %q, erwartet %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckNewPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
@@ -56,15 +39,18 @@ func TestCreateAndReset(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := context.Background()
|
||||
s := NewStore(testdb.New(t), time.Now)
|
||||
uid, err := s.Create(ctx, "alice", "supersecret1")
|
||||
uid, err := s.Create(ctx, "alice", "Alice ✨", "supersecret1")
|
||||
if err != nil || uid == 0 {
|
||||
t.Fatalf("Create: %d, %v", uid, err)
|
||||
}
|
||||
if _, err := s.Create(ctx, "alice", "supersecret1"); !errors.Is(err, ErrUsernameTaken) {
|
||||
t.Errorf("doppelter Name: %v", err)
|
||||
if _, err := s.Create(ctx, "alice", "", "supersecret1"); !errors.Is(err, ErrHandleTaken) {
|
||||
t.Errorf("doppelter Handle: %v", err)
|
||||
}
|
||||
if taken, err := s.NameTaken(ctx, "alice"); err != nil || !taken {
|
||||
t.Errorf("NameTaken: %v, %v", taken, err)
|
||||
if taken, err := s.HandleTaken(ctx, "alice"); err != nil || !taken {
|
||||
t.Errorf("HandleTaken: %v, %v", taken, err)
|
||||
}
|
||||
if got, err := s.UID(ctx, " @Alice"); err != nil || got != uid {
|
||||
t.Errorf("UID(@Alice) = %d, %v", got, err)
|
||||
}
|
||||
|
||||
token, _, err := s.CreateResetToken(ctx, "alice")
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/runes"
|
||||
)
|
||||
|
||||
// Der Handle (@name) identifiziert ein Konto: Login, Profil-URL, Erwähnungen.
|
||||
// Er ist klein geschrieben und besteht nur aus a-z, 0-9 und "_". Der
|
||||
// Anzeigename ist frei gestaltbarer Unicode-Text und muss nicht eindeutig sein.
|
||||
const (
|
||||
MinHandleLen = 3
|
||||
MaxHandleLen = 20
|
||||
maxDisplayRunes = 32
|
||||
)
|
||||
|
||||
var (
|
||||
handleRE = regexp.MustCompile(`^[a-z0-9_]{3,20}$`)
|
||||
// Steuer- und unsichtbare Formatzeichen haben im Anzeigenamen nichts
|
||||
// verloren; Leerraum wird zu einem einfachen Leerzeichen.
|
||||
nonDisplayChars = regexp.MustCompile(`[\p{Cc}\p{Cf}]`)
|
||||
)
|
||||
|
||||
var (
|
||||
ErrHandleTaken = apperr.Conflict("user.handle_taken", "Der Handle wird bereits verwendet.").At("handle")
|
||||
ErrHandleInvalid = apperr.Invalid("user.handle_invalid",
|
||||
"Der Handle braucht 3 bis 20 Zeichen aus a–z, 0–9 und _.").At("handle")
|
||||
)
|
||||
|
||||
// NormalizeHandle bereitet eine Eingabe zum Vergleich auf: ohne Leerraum am
|
||||
// Rand, ohne führendes "@", klein geschrieben. Ob das Ergebnis gültig ist,
|
||||
// sagt ValidHandle.
|
||||
func NormalizeHandle(h string) string {
|
||||
return strings.ToLower(strings.TrimPrefix(strings.TrimSpace(h), "@"))
|
||||
}
|
||||
|
||||
// ValidHandle meldet, ob h (bereits normalisiert) ein gültiger Handle ist.
|
||||
func ValidHandle(h string) bool { return handleRE.MatchString(h) }
|
||||
|
||||
// CleanDisplayName kürzt einen Anzeigenamen auf 32 Runen, entfernt Steuer-
|
||||
// und Formatzeichen und fasst Leerraum zusammen. Leer heißt: keiner, das
|
||||
// Frontend zeigt dann den Handle.
|
||||
func CleanDisplayName(n string) string {
|
||||
n = nonDisplayChars.ReplaceAllString(n, "")
|
||||
n = whitespace.ReplaceAllString(strings.TrimSpace(n), " ")
|
||||
return runes.Truncate(n, maxDisplayRunes)
|
||||
}
|
||||
|
||||
// HandleChange ist ein Konto, dessen Handle vom alten Nutzernamen
|
||||
// (legacy_name, bis 11/2026) abweicht -- mehr als nur in der
|
||||
// Groß-/Kleinschreibung, die der Login ignoriert. Die Umschrift der alten
|
||||
// Namen ist längst gelaufen; die Liste bleibt, bis alle Betroffenen ihren
|
||||
// neuen Handle kennen.
|
||||
type HandleChange struct {
|
||||
LegacyName, Handle string
|
||||
}
|
||||
|
||||
// HandleChanges listet die Konten, die sich mit einem anderen Namen anmelden
|
||||
// müssen als früher.
|
||||
func (s *Store) HandleChanges(ctx context.Context) ([]HandleChange, error) {
|
||||
rows, err := s.db.QueryContext(ctx,
|
||||
`SELECT legacy_name, handle FROM account
|
||||
WHERE legacy_name IS NOT NULL AND handle <> lower(legacy_name) ORDER BY id`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("handles lesen: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []HandleChange
|
||||
for rows.Next() {
|
||||
var c HandleChange
|
||||
if err := rows.Scan(&c.LegacyName, &c.Handle); err != nil {
|
||||
return nil, fmt.Errorf("handles lesen: %w", err)
|
||||
}
|
||||
out = append(out, c)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidHandle(t *testing.T) {
|
||||
t.Parallel()
|
||||
for in, want := range map[string]bool{
|
||||
"alice": true, "a_1": true, strings.Repeat("a", 20): true,
|
||||
"ab": false, strings.Repeat("a", 21): false, "Alice": false, "a.b": false, "jörg": false,
|
||||
} {
|
||||
if got := ValidHandle(in); got != want {
|
||||
t.Errorf("ValidHandle(%q) = %v", in, got)
|
||||
}
|
||||
}
|
||||
if got := NormalizeHandle(" @Alice "); got != "alice" {
|
||||
t.Errorf("NormalizeHandle = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanDisplayName(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct{ in, want string }{
|
||||
{" Max Mustermann ", "Max Mustermann"},
|
||||
{"Jörg 🌻", "Jörg 🌻"},
|
||||
{"ab\x07c", "abc"},
|
||||
{strings.Repeat("ä", 40), strings.Repeat("ä", 32)},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := CleanDisplayName(tt.in); got != tt.want {
|
||||
t.Errorf("CleanDisplayName(%q) = %q, erwartet %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/database"
|
||||
"kver/internal/runes"
|
||||
)
|
||||
|
||||
// MaxBioRunes begrenzt die Profilbeschreibung.
|
||||
const MaxBioRunes = 300
|
||||
|
||||
// Profile ist das öffentliche Profil eines Kontos (GET /u/{handle}/info).
|
||||
type Profile struct {
|
||||
UID int64 `json:"uid"`
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Avatar string `json:"avatar"`
|
||||
// Header ist das Header-Bild, '' = keins.
|
||||
Header string `json:"header"`
|
||||
Bio string `json:"bio"`
|
||||
// Entries zählt die nicht gelöschten Beiträge.
|
||||
Entries int64 `json:"entries"`
|
||||
}
|
||||
|
||||
// Info ist das eigene Konto (GET /user/info).
|
||||
type Info struct {
|
||||
UID int64 `json:"uid"`
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
LastLogin int64 `json:"last_login"`
|
||||
Avatar string `json:"avatar"`
|
||||
}
|
||||
|
||||
// notFoundOr bildet sql.ErrNoRows auf ErrUserNotFound ab, alles andere auf
|
||||
// einen Lesefehler.
|
||||
func notFoundOr(err error, what string) error {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ErrUserNotFound
|
||||
}
|
||||
return fmt.Errorf("%s lesen: %w", what, err)
|
||||
}
|
||||
|
||||
// Profile liefert das öffentliche Profil zum Handle (Eingabe wie vom Nutzer).
|
||||
func (s *Store) Profile(ctx context.Context, handle string) (Profile, error) {
|
||||
var p Profile
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT uid, handle, display_name, created_at, avatar, header, bio,
|
||||
(SELECT COUNT(*) FROM entry e WHERE e.uid = a.uid AND e.deleted = 0)
|
||||
FROM account a WHERE handle = $1`, NormalizeHandle(handle),
|
||||
).Scan(&p.UID, &p.Handle, &p.DisplayName, &p.CreatedAt, &p.Avatar, &p.Header, &p.Bio, &p.Entries)
|
||||
if err != nil {
|
||||
return Profile{}, notFoundOr(err, "profil")
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// Info liefert das Konto zu uid.
|
||||
func (s *Store) Info(ctx context.Context, uid int64) (Info, error) {
|
||||
i := Info{UID: uid}
|
||||
var lastLogin sql.NullInt64
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT created_at, last_login, handle, display_name, avatar FROM account WHERE uid = $1`, uid,
|
||||
).Scan(&i.CreatedAt, &lastLogin, &i.Handle, &i.DisplayName, &i.Avatar)
|
||||
if err != nil {
|
||||
return Info{}, notFoundOr(err, "konto")
|
||||
}
|
||||
i.LastLogin = lastLogin.Int64
|
||||
return i, nil
|
||||
}
|
||||
|
||||
// ErrHandleUnchanged: der neue Handle ist der bisherige.
|
||||
var ErrHandleUnchanged = apperr.Invalid("user.handle_unchanged", "Das ist bereits dein Handle.").At("handle")
|
||||
|
||||
// SetHandle ändert den Handle des Kontos (Eingabe wie vom Nutzer) und liefert
|
||||
// ihn normalisiert zurück. Alles hängt an der uid, daher genügt ein UPDATE;
|
||||
// Links auf das alte /u/<handle> laufen danach ins Leere.
|
||||
func (s *Store) SetHandle(ctx context.Context, uid int64, handle string) (string, error) {
|
||||
handle = NormalizeHandle(handle)
|
||||
if !ValidHandle(handle) {
|
||||
return "", ErrHandleInvalid
|
||||
}
|
||||
res, err := s.db.ExecContext(ctx,
|
||||
`UPDATE account SET handle = $1 WHERE uid = $2 AND handle <> $1`, handle, uid)
|
||||
if err != nil {
|
||||
// Vergeben, auch im Rennen zweier gleichzeitiger Änderungen.
|
||||
if database.IsUniqueViolation(err, "account_handle_key") {
|
||||
return "", ErrHandleTaken.WithCause(err)
|
||||
}
|
||||
return "", fmt.Errorf("handle setzen: %w", err)
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return "", ErrHandleUnchanged
|
||||
}
|
||||
return handle, nil
|
||||
}
|
||||
|
||||
// SetDisplayName setzt den bereinigten Anzeigenamen (CleanDisplayName) und
|
||||
// liefert ihn; leer heißt: Handle anzeigen.
|
||||
func (s *Store) SetDisplayName(ctx context.Context, uid int64, name string) (string, error) {
|
||||
name = CleanDisplayName(name)
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`UPDATE account SET display_name = $1 WHERE uid = $2`, name, uid); err != nil {
|
||||
return "", fmt.Errorf("anzeigename setzen: %w", err)
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
// SetBio setzt die Profilbeschreibung: Klartext, getrimmt, auf MaxBioRunes
|
||||
// gekürzt; leer löscht sie. Liefert den gespeicherten Text.
|
||||
func (s *Store) SetBio(ctx context.Context, uid int64, bio string) (string, error) {
|
||||
bio = strings.ReplaceAll(bio, "\r\n", "\n")
|
||||
bio = runes.Truncate(strings.TrimSpace(bio), MaxBioRunes)
|
||||
if _, err := s.db.ExecContext(ctx,
|
||||
`UPDATE account SET bio = $1 WHERE uid = $2`, bio, uid); err != nil {
|
||||
return "", fmt.Errorf("beschreibung setzen: %w", err)
|
||||
}
|
||||
return bio, nil
|
||||
}
|
||||
|
||||
// Image ist eines der Profilbilder: Spalte in account und zugleich Name des
|
||||
// Formularfelds.
|
||||
type Image string
|
||||
|
||||
const (
|
||||
Avatar Image = "avatar"
|
||||
Header Image = "header"
|
||||
)
|
||||
|
||||
// Die Abfragen stehen fest im Code, damit kein Spaltenname in SQL
|
||||
// zusammengesetzt wird. Der Self-Join liefert das bisherige Bild (prev sieht
|
||||
// die Zeile vor dem UPDATE), ohne eigene Abfrage davor.
|
||||
var setImageQuery = map[Image]string{
|
||||
Avatar: `UPDATE account a SET avatar = $1 FROM account prev
|
||||
WHERE a.uid = $2 AND prev.uid = a.uid RETURNING prev.avatar`,
|
||||
Header: `UPDATE account a SET header = $1 FROM account prev
|
||||
WHERE a.uid = $2 AND prev.uid = a.uid RETURNING prev.header`,
|
||||
}
|
||||
|
||||
// SetImage setzt das Profilbild img auf path (leer entfernt es) und liefert den
|
||||
// bisherigen Pfad, damit der Aufrufer die alte Datei löschen kann.
|
||||
func (s *Store) SetImage(ctx context.Context, uid int64, img Image, path string) (string, error) {
|
||||
var old string
|
||||
if err := s.db.QueryRowContext(ctx, setImageQuery[img], path, uid).Scan(&old); err != nil {
|
||||
return "", notFoundOr(err, "profilbild")
|
||||
}
|
||||
return old, nil
|
||||
}
|
||||
|
||||
// Delete löscht das Konto und alles, was nur ihm gehört: Sessions,
|
||||
// Reset-Links, Schlüssel und Direktnachrichten. Was von ihm im Forum steht
|
||||
// (Beiträge, Votes, Erwähnungen, Benachrichtigungen), räumt der Aufrufer in
|
||||
// derselben Transaktion ab -- die Beiträge bleiben als Platzhalter erhalten,
|
||||
// damit fremde Antworten nicht verwaisen.
|
||||
func (s *Store) Delete(ctx context.Context, tx *sql.Tx, uid int64) error {
|
||||
for _, q := range []string{
|
||||
`DELETE FROM session WHERE uid = $1`,
|
||||
`DELETE FROM password_reset WHERE uid = $1`,
|
||||
`DELETE FROM account_key WHERE uid = $1`,
|
||||
`DELETE FROM message WHERE sender = $1 OR recipient = $1`,
|
||||
`DELETE FROM account WHERE uid = $1`,
|
||||
} {
|
||||
if _, err := tx.ExecContext(ctx, q, uid); err != nil {
|
||||
return fmt.Errorf("konto löschen: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+26
-24
@@ -29,18 +29,20 @@ const resetTTL = 72 * time.Hour
|
||||
// Nutzer ist das dasselbe: einen neuen Link holen.
|
||||
var ErrResetInvalid = apperr.NotFound("reset.invalid", "Der Link ist ungültig oder abgelaufen.")
|
||||
|
||||
// hashResetToken: in der DB steht nur der Hash. SHA-256 statt bcrypt genügt,
|
||||
// das Token ist 256 Bit Zufall und nicht zu erraten.
|
||||
func hashResetToken(token string) string {
|
||||
// HashToken: in der DB steht von Reset-Links und Sessions nur der Hash; wer
|
||||
// die DB (oder ein Backup) liest, kann damit weder ein Passwort setzen noch
|
||||
// eine Sitzung übernehmen. SHA-256 statt bcrypt genügt, das Token ist 256 Bit
|
||||
// Zufall (NewToken) und nicht zu erraten.
|
||||
func HashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// CreateResetToken legt für username einen neuen Reset-Link an und liefert
|
||||
// CreateResetToken legt für handle einen neuen Reset-Link an und liefert
|
||||
// das Token im Klartext (nur hier sichtbar) und seinen Ablauf. Ältere Links
|
||||
// desselben Nutzers werden ungültig, abgelaufene aller Nutzer weggeräumt.
|
||||
func (s *Store) CreateResetToken(ctx context.Context, username string) (string, time.Time, error) {
|
||||
uid, err := s.UID(ctx, username)
|
||||
func (s *Store) CreateResetToken(ctx context.Context, handle string) (string, time.Time, error) {
|
||||
uid, err := s.UID(ctx, handle)
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
@@ -57,7 +59,7 @@ func (s *Store) CreateResetToken(ctx context.Context, username string) (string,
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO password_reset (uid, token_hash, created_at, expires) VALUES ($1, $2, $3, $4)`,
|
||||
uid, hashResetToken(token), now.Unix(), expires.Unix()); err != nil {
|
||||
uid, HashToken(token), now.Unix(), expires.Unix()); err != nil {
|
||||
return fmt.Errorf("reset-link anlegen: %w", err)
|
||||
}
|
||||
return nil
|
||||
@@ -68,31 +70,31 @@ func (s *Store) CreateResetToken(ctx context.Context, username string) (string,
|
||||
return token, expires, nil
|
||||
}
|
||||
|
||||
// ResetUsername liefert den Nutzer zu einem gültigen Link, ohne ihn zu
|
||||
// ResetHandle liefert den Nutzer zu einem gültigen Link, ohne ihn zu
|
||||
// verbrauchen.
|
||||
func (s *Store) ResetUsername(ctx context.Context, token string) (string, error) {
|
||||
var username string
|
||||
func (s *Store) ResetHandle(ctx context.Context, token string) (string, error) {
|
||||
var handle string
|
||||
err := s.db.QueryRowContext(ctx,
|
||||
`SELECT a.username FROM password_reset p JOIN account a ON a.uid = p.uid
|
||||
`SELECT a.handle FROM password_reset p JOIN account a ON a.uid = p.uid
|
||||
WHERE p.token_hash = $1 AND p.expires >= $2`,
|
||||
hashResetToken(token), s.now().Unix(),
|
||||
).Scan(&username)
|
||||
HashToken(token), s.now().Unix(),
|
||||
).Scan(&handle)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrResetInvalid
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("reset-link prüfen: %w", err)
|
||||
}
|
||||
return username, nil
|
||||
return handle, nil
|
||||
}
|
||||
|
||||
// ResetPassword setzt über einen gültigen Link ein neues Passwort, verbraucht
|
||||
// den Link und meldet alle bestehenden Sessions des Nutzers ab. Liefert uid
|
||||
// und Namen des Nutzers.
|
||||
// und Handle des Nutzers.
|
||||
func (s *Store) ResetPassword(ctx context.Context, token, password string) (int64, string, error) {
|
||||
// Vorab ohne Verbrauch prüfen: bcrypt kostet spürbar CPU und soll nicht
|
||||
// für jedes beliebige Token anlaufen. Verbindlich ist erst consumeReset.
|
||||
if _, err := s.ResetUsername(ctx, token); err != nil {
|
||||
if _, err := s.ResetHandle(ctx, token); err != nil {
|
||||
return 0, "", err
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
@@ -100,13 +102,13 @@ func (s *Store) ResetPassword(ctx context.Context, token, password string) (int6
|
||||
return 0, "", fmt.Errorf("passwort hashen: %w", err)
|
||||
}
|
||||
var uid int64
|
||||
var username string
|
||||
var handle string
|
||||
err = database.InTx(ctx, s.db, func(tx *sql.Tx) error {
|
||||
var txErr error
|
||||
if uid, txErr = s.consumeReset(ctx, tx, token); txErr != nil {
|
||||
return txErr
|
||||
}
|
||||
if username, txErr = setPassword(ctx, tx, uid, hash); txErr != nil {
|
||||
if handle, txErr = setPassword(ctx, tx, uid, hash); txErr != nil {
|
||||
return txErr
|
||||
}
|
||||
// Wer das alte Passwort kannte, soll mit dessen Sessions nicht drin bleiben.
|
||||
@@ -115,21 +117,21 @@ func (s *Store) ResetPassword(ctx context.Context, token, password string) (int6
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return uid, username, err
|
||||
return uid, handle, err
|
||||
}
|
||||
|
||||
// setPassword speichert den neuen Hash und liefert den Nutzernamen.
|
||||
// setPassword speichert den neuen Hash und liefert den Handle.
|
||||
func setPassword(ctx context.Context, tx *sql.Tx, uid int64, hash []byte) (string, error) {
|
||||
var username string
|
||||
var handle string
|
||||
err := tx.QueryRowContext(ctx,
|
||||
`UPDATE account SET password = $1 WHERE uid = $2 RETURNING username`, hash, uid).Scan(&username)
|
||||
`UPDATE account SET password = $1 WHERE uid = $2 RETURNING handle`, hash, uid).Scan(&handle)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return "", ErrResetInvalid // Konto inzwischen gelöscht: der Link führt ins Leere.
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("passwort setzen: %w", err)
|
||||
}
|
||||
return username, nil
|
||||
return handle, nil
|
||||
}
|
||||
|
||||
// consumeReset verbraucht den Link atomar per DELETE ... RETURNING: zwei
|
||||
@@ -138,7 +140,7 @@ func (s *Store) consumeReset(ctx context.Context, tx *sql.Tx, token string) (int
|
||||
var uid int64
|
||||
err := tx.QueryRowContext(ctx,
|
||||
`DELETE FROM password_reset WHERE token_hash = $1 AND expires >= $2 RETURNING uid`,
|
||||
hashResetToken(token), s.now().Unix(),
|
||||
HashToken(token), s.now().Unix(),
|
||||
).Scan(&uid)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrResetInvalid
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
// und der HTTP-Status ergibt sich allein aus Kind (siehe httpapi).
|
||||
package apperr
|
||||
|
||||
import "errors"
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Kind ist die Schwere eines Fehlers. Bewusst kein HTTP-Status: die Zuordnung
|
||||
// passiert erst im Adapter, damit ein CLI- oder App-Client dieselben Fehler
|
||||
@@ -33,7 +36,13 @@ type Error struct {
|
||||
Msg string // deutsche Nutzermeldung
|
||||
Field string // optional: betroffenes Formularfeld
|
||||
Fields map[string]string // optional: mehrere Feldfehler auf einmal
|
||||
cause error // nur fürs Log, nie für den Nutzer
|
||||
// Extra sind Nutzdaten, die der Client neben dem Fehler braucht (etwa
|
||||
// retry_after beim Repost-Cooldown); der Adapter legt sie neben "error".
|
||||
Extra map[string]any
|
||||
// RetryAfter sagt bei KindRateLimited, wann es sich lohnt, es erneut zu
|
||||
// versuchen (HTTP: Header Retry-After). 0 = keine Angabe.
|
||||
RetryAfter time.Duration
|
||||
cause error // nur fürs Log, nie für den Nutzer
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Code + ": " + e.Msg }
|
||||
@@ -86,6 +95,20 @@ func (e *Error) WithFields(fields map[string]string) *Error {
|
||||
return &c
|
||||
}
|
||||
|
||||
// WithExtra hängt Nutzdaten an, die neben dem Fehler ausgeliefert werden.
|
||||
func (e *Error) WithExtra(extra map[string]any) *Error {
|
||||
c := *e
|
||||
c.Extra = extra
|
||||
return &c
|
||||
}
|
||||
|
||||
// WithRetryAfter vermerkt, wann ein erneuter Versuch Aussicht hat.
|
||||
func (e *Error) WithRetryAfter(d time.Duration) *Error {
|
||||
c := *e
|
||||
c.RetryAfter = d
|
||||
return &c
|
||||
}
|
||||
|
||||
// WithCause hängt eine technische Ursache an einen fachlichen Fehler, etwa
|
||||
// wenn ein DB-Fehler fachlich eindeutig ist, die Ursache aber ins Log soll.
|
||||
func (e *Error) WithCause(cause error) *Error {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestModifiersCopy(t *testing.T) {
|
||||
@@ -17,9 +18,12 @@ func TestModifiersCopy(t *testing.T) {
|
||||
{"At", sentinel.At("feld")},
|
||||
{"WithFields", sentinel.WithFields(map[string]string{"a": "b"})},
|
||||
{"WithCause", sentinel.WithCause(cause)},
|
||||
{"WithExtra", sentinel.WithExtra(map[string]any{"n": 1})},
|
||||
{"WithRetryAfter", sentinel.WithRetryAfter(time.Minute)},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if sentinel.Field != "" || sentinel.Fields != nil || sentinel.Unwrap() != nil {
|
||||
if sentinel.Field != "" || sentinel.Fields != nil || sentinel.Unwrap() != nil ||
|
||||
sentinel.Extra != nil || sentinel.RetryAfter != 0 {
|
||||
t.Fatalf("%s hat das Sentinel verändert: %+v", tt.name, sentinel)
|
||||
}
|
||||
if !errors.Is(fmt.Errorf("verpackt: %w", tt.err), sentinel) {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -51,7 +51,7 @@ func InTx(ctx context.Context, db *sql.DB, fn func(*sql.Tx) error) error {
|
||||
}
|
||||
|
||||
// IsUniqueViolation meldet, ob err am UNIQUE-Constraint constraint scheiterte
|
||||
// (Postgres-Namen nach Schema <tabelle>_<spalte>_key, z. B. account_username_key).
|
||||
// (Postgres-Namen nach Schema <tabelle>_<spalte>_key, z. B. account_handle_key).
|
||||
func IsUniqueViolation(err error, constraint string) bool {
|
||||
pgErr, ok := errors.AsType[*pgconn.PgError](err)
|
||||
return ok && pgErr.Code == "23505" && pgErr.ConstraintName == constraint
|
||||
|
||||
+121
-20
@@ -1,21 +1,33 @@
|
||||
-- Schema der App, beim Start idempotent angewendet (siehe database.Open).
|
||||
-- Zeitstempel sind Unix-Sekunden (BIGINT) statt timestamptz: das JSON-Format
|
||||
-- der API liefert sie so aus, und die Bump-Rechnung arbeitet direkt damit.
|
||||
-- "user" ist in Postgres ein reserviertes Wort, daher heißt die Tabelle account.
|
||||
-- Es beschreibt den Ist-Stand: Es gibt genau eine Datenbank (Rolling
|
||||
-- Release), Umbauten werden direkt dort ausgeführt und hier eingetragen; alte
|
||||
-- Migrationsschritte verbleiben nicht. Zeitstempel sind Unix-Sekunden (BIGINT)
|
||||
-- statt timestamptz: das JSON-Format der API liefert sie so aus, und die
|
||||
-- Bump-Rechnung arbeitet direkt damit. "user" ist in Postgres ein
|
||||
-- reserviertes Wort, daher heißt die Tabelle account.
|
||||
|
||||
-- handle: @name, eindeutig, nur a-z0-9_ (account.ValidHandle); display_name:
|
||||
-- freier Anzeigename, '' = Handle anzeigen. legacy_name ist der Unicode-
|
||||
-- Nutzername aus der Zeit vor der Trennung (bis 11/2026), NULL bei jüngeren
|
||||
-- Konten; er bleibt, bis alle Betroffenen ihren neuen Handle kennen
|
||||
-- (kver handles).
|
||||
CREATE TABLE IF NOT EXISTS account (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
uid BIGINT NOT NULL UNIQUE,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
password BYTEA NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
last_login BIGINT,
|
||||
avatar TEXT NOT NULL DEFAULT ''
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
uid BIGINT NOT NULL UNIQUE,
|
||||
handle TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL DEFAULT '',
|
||||
legacy_name TEXT UNIQUE,
|
||||
password BYTEA NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
last_login BIGINT,
|
||||
avatar TEXT NOT NULL DEFAULT '',
|
||||
-- Profil: Header-Bild ('' = keins) und Beschreibung (Klartext).
|
||||
header TEXT NOT NULL DEFAULT '',
|
||||
bio TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
-- Profil: Beschreibung (Klartext) und Header-Bild, '' = keins.
|
||||
ALTER TABLE account ADD COLUMN IF NOT EXISTS bio TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE account ADD COLUMN IF NOT EXISTS header TEXT NOT NULL DEFAULT '';
|
||||
|
||||
-- value ist der SHA-256 des Cookie-Werts (account.HashToken), nie der Wert
|
||||
-- selbst.
|
||||
CREATE TABLE IF NOT EXISTS session (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
uid BIGINT NOT NULL,
|
||||
@@ -25,6 +37,11 @@ CREATE TABLE IF NOT EXISTS session (
|
||||
description TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
-- link_url: kanonische URL des ersten Links im Inhalt (linkpreview.Key), ''
|
||||
-- ohne Link. image_warning/image_cover: Hinweis vor dem Bild (kver
|
||||
-- cover-image). Steht ein Text da, zeigt das Frontend statt des Bilds die
|
||||
-- verpixelte Variante image_cover, bis jemand "Inhalt anzeigen" klickt. Für
|
||||
-- Bilder, die erlaubt sind, aber nicht jedem ungefragt begegnen müssen.
|
||||
CREATE TABLE IF NOT EXISTS entry (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
pid BIGINT NOT NULL UNIQUE,
|
||||
@@ -37,10 +54,11 @@ CREATE TABLE IF NOT EXISTS entry (
|
||||
last_activity BIGINT NOT NULL DEFAULT 0,
|
||||
deleted BIGINT NOT NULL DEFAULT 0,
|
||||
bump_count BIGINT NOT NULL DEFAULT 0,
|
||||
last_bump BIGINT NOT NULL DEFAULT 0
|
||||
last_bump BIGINT NOT NULL DEFAULT 0,
|
||||
link_url TEXT NOT NULL DEFAULT '',
|
||||
image_warning TEXT NOT NULL DEFAULT '',
|
||||
image_cover TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
-- Kanonische URL des ersten Links im Inhalt (previewKey), '' ohne Link.
|
||||
ALTER TABLE entry ADD COLUMN IF NOT EXISTS link_url TEXT NOT NULL DEFAULT '';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS vote (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
@@ -99,14 +117,97 @@ CREATE TABLE IF NOT EXISTS link_preview (
|
||||
site TEXT NOT NULL DEFAULT '',
|
||||
thumb TEXT NOT NULL DEFAULT '',
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
fetched_at BIGINT NOT NULL DEFAULT 0
|
||||
fetched_at BIGINT NOT NULL DEFAULT 0,
|
||||
attempts INT NOT NULL DEFAULT 0,
|
||||
retry_at BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
ALTER TABLE link_preview ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE link_preview ADD COLUMN IF NOT EXISTS retry_at BIGINT NOT NULL DEFAULT 0;
|
||||
|
||||
-- OpenPGP-Schlüssel (v6) der Accounts für Ende-zu-Ende-verschlüsselte
|
||||
-- Direktnachrichten, siehe notes/schluessel.md. public_key ist das binäre
|
||||
-- Zertifikat, secret_key der private Schlüssel, im Browser mit der
|
||||
-- Passphrase verschlüsselt (Argon2 + AEAD, pgpkey.CheckSecret); entschlüsseln
|
||||
-- kann ihn nur, wer die Passphrase kennt -- der Server nicht. Ersetzte
|
||||
-- Schlüssel bleiben, damit ihr Besitzer alte Nachrichten noch lesen kann.
|
||||
-- replaced_at = 0: aktueller Schlüssel; lost_at > 0: als verloren markiert,
|
||||
-- wird nicht mehr ausgeliefert.
|
||||
CREATE TABLE IF NOT EXISTS account_key (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
uid BIGINT NOT NULL,
|
||||
fingerprint BYTEA NOT NULL UNIQUE,
|
||||
public_key BYTEA NOT NULL,
|
||||
secret_key BYTEA NOT NULL,
|
||||
created_at BIGINT NOT NULL,
|
||||
replaced_at BIGINT NOT NULL DEFAULT 0,
|
||||
lost_at BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
-- Höchstens ein aktueller Schlüssel pro Account.
|
||||
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);
|
||||
|
||||
-- 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);
|
||||
|
||||
-- Benachrichtigungen an uid. kind: reply (Antwort auf einen eigenen Beitrag),
|
||||
-- mention (in einem Beitrag erwähnt) oder bump (eigener Beitrag repostet).
|
||||
-- actor: wer geantwortet bzw. erwähnt hat, 0 =
|
||||
-- unbekannt (Reposts werden niemandem zugeordnet). excerpt: Anfang des
|
||||
-- zitierten Beitrags; den Text setzt erst der Abruf zusammen, damit er den
|
||||
-- aktuellen Handle zeigt. link ist ein interner Pfad (/e/<pid>), pid der
|
||||
-- zitierte Beitrag: wird er bearbeitet oder gelöscht, zieht die
|
||||
-- Benachrichtigung mit (internal/httpapi/notifications.go). seen_at = 0:
|
||||
-- ungesehen.
|
||||
CREATE TABLE IF NOT EXISTS notification (
|
||||
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
uid BIGINT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
actor BIGINT NOT NULL DEFAULT 0,
|
||||
excerpt TEXT NOT NULL DEFAULT '',
|
||||
link TEXT NOT NULL,
|
||||
pid BIGINT NOT NULL DEFAULT 0,
|
||||
created_at BIGINT NOT NULL,
|
||||
seen_at BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notification_uid ON notification(uid, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_notification_pid ON notification(pid);
|
||||
|
||||
-- Erwähnungen (@handle) in Beiträgen. handle steht so im Text (klein), uid ist
|
||||
-- wer ihn beim Schreiben trug: nach einer Umbenennung führt der alte Link so
|
||||
-- weiter zur richtigen Person, nicht zu dem, der den Handle neu bekommt.
|
||||
CREATE TABLE IF NOT EXISTS mention (
|
||||
pid BIGINT NOT NULL,
|
||||
handle TEXT NOT NULL,
|
||||
uid BIGINT NOT NULL,
|
||||
PRIMARY KEY (pid, handle)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_mention_uid ON mention(uid);
|
||||
|
||||
-- Hashtags je Beitrag, klein geschrieben, für die Vorschläge beim Tippen
|
||||
-- (häufigste zuerst). Gepflegt beim Anlegen/Bearbeiten/Löschen (syncTags).
|
||||
CREATE TABLE IF NOT EXISTS entry_tag (
|
||||
pid BIGINT NOT NULL,
|
||||
tag TEXT NOT NULL,
|
||||
PRIMARY KEY (pid, tag)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_entry_tag_tag ON entry_tag(tag text_pattern_ops);
|
||||
|
||||
-- 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
|
||||
-- wachsender Tabelle zu Full-Table-Scans. username/session.value/vote(uid,pid)
|
||||
-- wachsender Tabelle zu Full-Table-Scans. handle/session.value/vote(uid,pid)
|
||||
-- sind über UNIQUE bereits indiziert.
|
||||
CREATE INDEX IF NOT EXISTS idx_entry_last_activity ON entry(last_activity);
|
||||
CREATE INDEX IF NOT EXISTS idx_entry_reply_to ON entry(reply_to);
|
||||
|
||||
+141
-49
@@ -9,6 +9,7 @@ import (
|
||||
"net/http/cookiejar"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -61,7 +62,7 @@ func registerAndLogin(t *testing.T, srv *testServer, username string) *http.Clie
|
||||
c := newClient(t)
|
||||
|
||||
resp := postForm(t, c, srv.URL+"/api/auth/newuser", url.Values{
|
||||
"user": {username}, "pass1": {"supersecret1"}, "pass2": {"supersecret1"},
|
||||
"handle": {username}, "pass1": {"supersecret1"}, "pass2": {"supersecret1"},
|
||||
})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
@@ -111,12 +112,35 @@ func TestRegisterLoginSession(t *testing.T) {
|
||||
if got := getStatus(t, c, srv.URL+"/api/auth/sessioninfo"); got != http.StatusOK {
|
||||
t.Fatalf("sessioninfo nach Login: erwartet 200, bekam %d", got)
|
||||
}
|
||||
// In der DB steht nur der Hash des Cookie-Werts.
|
||||
cookie := sessionCookieValue(t, c, srv.URL)
|
||||
var plain, hashed int
|
||||
if err := srv.db.QueryRow(`SELECT COUNT(*) FILTER (WHERE value = $1), COUNT(*) FILTER (WHERE value = $2) FROM session`,
|
||||
cookie, account.HashToken(cookie)).Scan(&plain, &hashed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if plain != 0 || hashed != 1 {
|
||||
t.Fatalf("session in der DB: %d im Klartext, %d gehasht", plain, hashed)
|
||||
}
|
||||
// Anonymer Client hat keine Session.
|
||||
if got := getStatus(t, newClient(t), srv.URL+"/api/auth/sessioninfo"); got != http.StatusUnauthorized {
|
||||
t.Fatalf("sessioninfo anonym: erwartet 401, bekam %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// sessionCookieValue liest den Session-Cookie aus dem Jar des Clients.
|
||||
func sessionCookieValue(t *testing.T, c *http.Client, srvURL string) string {
|
||||
t.Helper()
|
||||
u, _ := url.Parse(srvURL)
|
||||
for _, ck := range c.Jar.Cookies(u) {
|
||||
if ck.Name == sessionCookie {
|
||||
return ck.Value
|
||||
}
|
||||
}
|
||||
t.Fatal("kein Session-Cookie")
|
||||
return ""
|
||||
}
|
||||
|
||||
// getStatus macht einen GET und liefert nur den Statuscode.
|
||||
func getStatus(t *testing.T, c *http.Client, urlStr string) int {
|
||||
t.Helper()
|
||||
@@ -151,12 +175,12 @@ func TestFeedEmptyThenPopulated(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var posts []struct {
|
||||
Content string `json:"content"`
|
||||
Username string `json:"username"`
|
||||
Content string `json:"content"`
|
||||
Handle string `json:"handle"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&posts)
|
||||
resp.Body.Close()
|
||||
if len(posts) != 1 || posts[0].Content != "hallo welt" || posts[0].Username != "alice" {
|
||||
if len(posts) != 1 || posts[0].Content != "hallo welt" || posts[0].Handle != "alice" {
|
||||
t.Fatalf("unerwarteter Feed: %+v", posts)
|
||||
}
|
||||
}
|
||||
@@ -224,6 +248,15 @@ func TestVoteRequiresAuthAndValidMode(t *testing.T) {
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("ungültiger Modus: erwartet 400, bekam %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Gelöschte Beiträge nehmen keine Stimmen mehr an.
|
||||
resp = postForm(t, alice, fmt.Sprintf("%s/api/entry/%d/delete", srv.URL, pid), url.Values{})
|
||||
resp.Body.Close()
|
||||
resp = postForm(t, alice, voteURL, url.Values{"mode": {"yes"}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("vote auf gelöschten Beitrag: erwartet 404, bekam %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBump(t *testing.T) {
|
||||
@@ -257,12 +290,25 @@ func TestBump(t *testing.T) {
|
||||
}
|
||||
|
||||
// Cooldown gilt pro Beitrag (global): auch ein anderer Nutzer wird sofort
|
||||
// abgewiesen.
|
||||
// abgewiesen -- mit Restzeit im Header und neben dem Fehler im Body.
|
||||
resp = postForm(t, bob, bumpURL, url.Values{})
|
||||
resp.Body.Close()
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusTooManyRequests {
|
||||
t.Fatalf("bump im cooldown: erwartet 429, bekam %d", resp.StatusCode)
|
||||
}
|
||||
var cool struct {
|
||||
Error errorBody `json:"error"`
|
||||
RetryAfter int64 `json:"retry_after"`
|
||||
BumpCount int64 `json:"bump_count"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&cool)
|
||||
if cool.Error.Code != "entry.bump_cooldown" || cool.BumpCount != 1 ||
|
||||
cool.RetryAfter <= 0 || cool.RetryAfter > 86400 {
|
||||
t.Fatalf("cooldown-antwort: %+v", cool)
|
||||
}
|
||||
if ra, _ := strconv.ParseInt(resp.Header.Get("Retry-After"), 10, 64); ra != cool.RetryAfter {
|
||||
t.Fatalf("Retry-After %q, body %d", resp.Header.Get("Retry-After"), cool.RetryAfter)
|
||||
}
|
||||
|
||||
// Gelöschter Beitrag lässt sich nicht bumpen.
|
||||
del := createEntry(t, alice, srv, post("weg gleich"))
|
||||
@@ -280,7 +326,7 @@ type threadEntry struct {
|
||||
ReplyCount int64 `json:"reply_count"`
|
||||
Deleted int64 `json:"deleted"`
|
||||
Content string `json:"content"`
|
||||
Username string `json:"username"`
|
||||
Handle string `json:"handle"`
|
||||
Latest *struct {
|
||||
Entry threadEntry `json:"entry"`
|
||||
Skipped int64 `json:"skipped"`
|
||||
@@ -593,7 +639,7 @@ func TestSoftDelete(t *testing.T) {
|
||||
|
||||
// Root bleibt als [deleted]-Platzhalter; die Antwort verwaist nicht.
|
||||
tv := getThread(t, srv, root)
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Username != "" {
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Handle != "" {
|
||||
t.Fatalf("deleted entry nicht anonymisiert: %+v", tv.Entry)
|
||||
}
|
||||
if len(tv.Replies) != 1 || tv.Replies[0].PID != answer {
|
||||
@@ -666,41 +712,43 @@ func TestReport(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameUser(t *testing.T) {
|
||||
func TestSetHandle(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
registerAndLogin(t, srv, "bob")
|
||||
|
||||
// Zu kurz -> 400.
|
||||
resp := postForm(t, alice, srv.URL+"/api/user/rename", url.Values{"user": {"ab"}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("zu kurz: erwartet 400, bekam %d", resp.StatusCode)
|
||||
for _, tt := range []struct {
|
||||
handle string
|
||||
want int
|
||||
}{
|
||||
{"ab", http.StatusBadRequest},
|
||||
{"jörg", http.StatusBadRequest},
|
||||
{"alice", http.StatusBadRequest}, // unverändert
|
||||
{"@BOB", http.StatusConflict},
|
||||
} {
|
||||
resp := postForm(t, alice, srv.URL+"/api/user/handle", url.Values{"handle": {tt.handle}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != tt.want {
|
||||
t.Errorf("%q: erwartet %d, bekam %d", tt.handle, tt.want, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// Bereits vergeben -> 409.
|
||||
resp = postForm(t, alice, srv.URL+"/api/user/rename", url.Values{"user": {"bob"}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("vergeben: erwartet 409, bekam %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// Gültig -> 200 + neuer Name.
|
||||
resp = postForm(t, alice, srv.URL+"/api/user/rename", url.Values{"user": {"alice2"}})
|
||||
// Gültig -> 200 + neuer Handle, klein geschrieben.
|
||||
resp := postForm(t, alice, srv.URL+"/api/user/handle", url.Values{"handle": {"Alice2"}})
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("rename: erwartet 200, bekam %d", resp.StatusCode)
|
||||
t.Fatalf("handle: erwartet 200, bekam %d", resp.StatusCode)
|
||||
}
|
||||
var out struct {
|
||||
Username string `json:"username"`
|
||||
Handle string `json:"handle"`
|
||||
}
|
||||
json.NewDecoder(resp.Body).Decode(&out)
|
||||
if out.Username != "alice2" {
|
||||
t.Fatalf("erwarteter Name alice2, bekam %q", out.Username)
|
||||
if out.Handle != "alice2" {
|
||||
t.Fatalf("erwarteter Handle alice2, bekam %q", out.Handle)
|
||||
}
|
||||
|
||||
// Profil unter dem neuen Namen erreichbar, alter Name weg.
|
||||
// Profil unter dem neuen Handle erreichbar, alter weg.
|
||||
r2, _ := http.Get(srv.URL + "/api/u/alice2/info")
|
||||
r2.Body.Close()
|
||||
if r2.StatusCode != http.StatusOK {
|
||||
@@ -749,7 +797,7 @@ func TestDeleteUser(t *testing.T) {
|
||||
|
||||
// alices Beitrag bleibt als [deleted]-Platzhalter; bobs Antwort verwaist nicht.
|
||||
tv := getThread(t, srv, root)
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Username != "" {
|
||||
if tv.Entry.Deleted != 1 || tv.Entry.Content != "" || tv.Entry.Handle != "" {
|
||||
t.Fatalf("beitrag nach konto-löschung nicht soft-deleted: %+v", tv.Entry)
|
||||
}
|
||||
if len(tv.Replies) != 1 || tv.Replies[0].PID != answer {
|
||||
@@ -817,19 +865,13 @@ func TestPasswordResetReplacesSession(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
var bobSession string
|
||||
u, _ := url.Parse(srv.URL)
|
||||
for _, ck := range bob.Jar.Cookies(u) {
|
||||
if ck.Name == sessionCookie {
|
||||
bobSession = ck.Value
|
||||
}
|
||||
}
|
||||
bobSession := sessionCookieValue(t, bob, srv.URL)
|
||||
form := resetForm(srv.resetToken(t, "alice"), "drittesgeheim")
|
||||
if got := postStatus(t, bob, srv.URL+"/api/auth/reset", form); got != http.StatusOK {
|
||||
t.Fatalf("reset mit fremder Session: erwartet 200, bekam %d", got)
|
||||
}
|
||||
var n int
|
||||
if err := srv.db.QueryRow(`SELECT COUNT(*) FROM session WHERE value = $1`, bobSession).Scan(&n); err != nil {
|
||||
if err := srv.db.QueryRow(`SELECT COUNT(*) FROM session WHERE value = $1`, account.HashToken(bobSession)).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 0 {
|
||||
@@ -948,7 +990,7 @@ func TestCrossOriginPostRejected(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
c := registerAndLogin(t, srv, "alice")
|
||||
|
||||
post := func(origin string) int {
|
||||
post := func(origin, fetchSite string) int {
|
||||
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/entry/create",
|
||||
strings.NewReader(url.Values{"content": {"x"}}.Encode()))
|
||||
if err != nil {
|
||||
@@ -959,6 +1001,9 @@ func TestCrossOriginPostRejected(t *testing.T) {
|
||||
if origin != "" {
|
||||
req.Header.Set("Origin", origin)
|
||||
}
|
||||
if fetchSite != "" {
|
||||
req.Header.Set("Sec-Fetch-Site", fetchSite)
|
||||
}
|
||||
resp, err := c.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -967,17 +1012,24 @@ func TestCrossOriginPostRejected(t *testing.T) {
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
if got := post("https://boese-seite.example"); got != http.StatusForbidden {
|
||||
t.Fatalf("cross-origin POST: erwartet 403, bekam %d", got)
|
||||
}
|
||||
if got := post("null"); got != http.StatusForbidden {
|
||||
t.Fatalf("Origin null: erwartet 403, bekam %d", got)
|
||||
}
|
||||
if got := post(srv.URL); got != http.StatusCreated {
|
||||
t.Fatalf("same-origin POST: erwartet 201, bekam %d", got)
|
||||
}
|
||||
if got := post(""); got != http.StatusCreated {
|
||||
t.Fatalf("POST ohne Origin: erwartet 201, bekam %d", got)
|
||||
for _, tc := range []struct {
|
||||
name, origin, fetchSite string
|
||||
want int
|
||||
}{
|
||||
{"cross-origin", "https://boese-seite.example", "", http.StatusForbidden},
|
||||
{"Origin null", "null", "", http.StatusForbidden},
|
||||
{"Sec-Fetch-Site cross-site", "", "cross-site", http.StatusForbidden},
|
||||
// Andere Subdomain: Origin stimmt nicht, auch wenn Browser "same-site" sagen.
|
||||
{"Sec-Fetch-Site same-site", "", "same-site", http.StatusForbidden},
|
||||
{"passender Origin, aber cross-site", srv.URL, "cross-site", http.StatusForbidden},
|
||||
{"same-origin", srv.URL, "same-origin", http.StatusCreated},
|
||||
{"nur Origin", srv.URL, "", http.StatusCreated},
|
||||
{"Nutzer selbst (none)", "", "none", http.StatusCreated},
|
||||
{"ohne beides (curl)", "", "", http.StatusCreated},
|
||||
} {
|
||||
if got := post(tc.origin, tc.fetchSite); got != tc.want {
|
||||
t.Errorf("%s: erwartet %d, bekam %d", tc.name, tc.want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1026,3 +1078,43 @@ func TestBlockTOREntry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisplayName(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
c := newClient(t)
|
||||
resp := postForm(t, c, srv.URL+"/api/auth/newuser", url.Values{
|
||||
"handle": {"@Joerg"}, "display_name": {" Jörg 🌻 "},
|
||||
"pass1": {"supersecret1"}, "pass2": {"supersecret1"},
|
||||
})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("register: status %d", resp.StatusCode)
|
||||
}
|
||||
// Login ignoriert Groß-/Kleinschreibung und "@" im Handle.
|
||||
resp = postForm(t, c, srv.URL+"/api/auth/login", url.Values{
|
||||
"user": {"@JOERG"}, "pass": {"supersecret1"}, "timeout": {"86400"},
|
||||
})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("login: status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
type user struct {
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
var u user
|
||||
if getAs(t, c, srv.URL+"/api/user/info", &u); u != (user{"joerg", "Jörg 🌻"}) {
|
||||
t.Errorf("/user/info: %+v", u)
|
||||
}
|
||||
|
||||
resp = postForm(t, c, srv.URL+"/api/user/display_name", url.Values{"display_name": {""}})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("display_name: status %d", resp.StatusCode)
|
||||
}
|
||||
if getAs(t, c, srv.URL+"/api/u/JOERG/info", &u); u != (user{"joerg", ""}) {
|
||||
t.Errorf("/u/JOERG/info: %+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
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 {
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
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.handle, a.display_name, 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.handle`, 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.Handle, &c.DisplayName, &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.accounts.UID(r.Context(), chi.URLParam(r, "handle"))
|
||||
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].Handle != "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)
|
||||
}
|
||||
}
|
||||
+32
-16
@@ -3,6 +3,7 @@ package httpapi
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -15,19 +16,27 @@ import (
|
||||
)
|
||||
|
||||
type Entry struct {
|
||||
PID int64 `json:"pid"`
|
||||
UID int64 `json:"uid"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Content string `json:"content"`
|
||||
Filepath string `json:"filepath"`
|
||||
PID int64 `json:"pid"`
|
||||
UID int64 `json:"uid"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Content string `json:"content"`
|
||||
Filepath string `json:"filepath"`
|
||||
// ImageWarning steht vor dem Bild; ImageCover ist dann seine verpixelte
|
||||
// Variante, die das Frontend zuerst zeigt.
|
||||
ImageWarning string `json:"image_warning,omitempty"`
|
||||
ImageCover string `json:"image_cover,omitempty"`
|
||||
ReplyTo int64 `json:"reply_to"`
|
||||
ReplyCount int64 `json:"reply_count"`
|
||||
LastActivity int64 `json:"last_activity"`
|
||||
Deleted int64 `json:"deleted"`
|
||||
BumpCount int64 `json:"bump_count"`
|
||||
LastBump int64 `json:"last_bump"`
|
||||
Username string `json:"username"`
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Avatar string `json:"avatar"`
|
||||
// Mentions ordnet jedem erwähnten Handle, wie er im Text steht (klein),
|
||||
// den heutigen Handle derselben Person zu, siehe mentions.go.
|
||||
Mentions map[string]string `json:"mentions,omitempty"`
|
||||
// Preview ist die fertige Vorschau des ersten Links.
|
||||
Preview *linkpreview.Preview `json:"preview,omitempty"`
|
||||
// PreviewPending: Der Worker holt die Vorschau gerade noch; das Frontend
|
||||
@@ -61,16 +70,19 @@ var (
|
||||
errEntryNotOwned = apperr.Forbidden("entry.not_owner", "Das ist nicht dein Beitrag.")
|
||||
)
|
||||
|
||||
// entrySelect liest Beiträge samt Autor und Linkvorschau. LEFT JOIN +
|
||||
// COALESCE, damit soft-gelöschte Beiträge (uid auf 0 gesetzt) als
|
||||
// entrySelect liest Beiträge samt Autor, Linkvorschau und Erwähnungen (als
|
||||
// JSON-Objekt, über den Primärschlüssel von mention). LEFT JOIN + COALESCE,
|
||||
// damit soft-gelöschte Beiträge (uid auf 0 gesetzt) als
|
||||
// [deleted]-Platzhalter erhalten bleiben und Threads nicht verwaisen.
|
||||
const entrySelect = `
|
||||
SELECT e.pid, e.uid, e.created_at, e.content, e.filepath,
|
||||
e.reply_to, e.reply_count, e.last_activity, e.deleted,
|
||||
e.image_warning, e.image_cover, e.reply_to, e.reply_count, e.last_activity, e.deleted,
|
||||
e.bump_count, e.last_bump,
|
||||
COALESCE(u.username, ''), COALESCE(u.avatar, ''),
|
||||
COALESCE(u.handle, ''), COALESCE(u.display_name, ''), COALESCE(u.avatar, ''),
|
||||
COALESCE(lp.url, ''), COALESCE(lp.kind, ''), COALESCE(lp.title, ''),
|
||||
COALESCE(lp.site, ''), COALESCE(lp.thumb, ''), COALESCE(lp.status, '')
|
||||
COALESCE(lp.site, ''), COALESCE(lp.thumb, ''), COALESCE(lp.status, ''),
|
||||
(SELECT jsonb_object_agg(m.handle, a.handle) FROM mention m
|
||||
JOIN account a ON a.uid = m.uid WHERE m.pid = e.pid)
|
||||
FROM entry e LEFT JOIN account u ON u.uid = e.uid
|
||||
LEFT JOIN link_preview lp ON lp.url = e.link_url`
|
||||
|
||||
@@ -82,10 +94,14 @@ func scanEntry(row interface{ Scan(...any) error }) (Entry, error) {
|
||||
var e Entry
|
||||
var p linkpreview.Preview
|
||||
var status string
|
||||
var mentions []byte
|
||||
err := row.Scan(&e.PID, &e.UID, &e.CreatedAt, &e.Content, &e.Filepath,
|
||||
&e.ReplyTo, &e.ReplyCount, &e.LastActivity, &e.Deleted,
|
||||
&e.BumpCount, &e.LastBump, &e.Username, &e.Avatar,
|
||||
&p.URL, &p.Kind, &p.Title, &p.Site, &p.Thumb, &status)
|
||||
&e.ImageWarning, &e.ImageCover, &e.ReplyTo, &e.ReplyCount, &e.LastActivity, &e.Deleted,
|
||||
&e.BumpCount, &e.LastBump, &e.Handle, &e.DisplayName, &e.Avatar,
|
||||
&p.URL, &p.Kind, &p.Title, &p.Site, &p.Thumb, &status, &mentions)
|
||||
if err == nil && mentions != nil {
|
||||
err = json.Unmarshal(mentions, &e.Mentions)
|
||||
}
|
||||
switch {
|
||||
case p.Title != "" && status != linkpreview.StatusNone:
|
||||
e.Preview = &p
|
||||
@@ -162,11 +178,11 @@ func (s *Server) handleFeed(w http.ResponseWriter, r *http.Request) error {
|
||||
// handleUserFeed liefert alle Beiträge eines Nutzers chronologisch, Antworten
|
||||
// eingeschlossen.
|
||||
func (s *Server) handleUserFeed(w http.ResponseWriter, r *http.Request) error {
|
||||
uid, err := s.accounts.UID(r.Context(), chi.URLParam(r, "username"))
|
||||
uid, err := s.accounts.UID(r.Context(), chi.URLParam(r, "handle"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := s.feedPage(r, entrySelect+` WHERE e.uid = $1 ORDER BY e.created_at DESC`, uid)
|
||||
entries, err := s.filterPage(r, filter{UID: uid})
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
|
||||
@@ -50,15 +50,24 @@ func (s *Server) handleCreateEntry(w http.ResponseWriter, r *http.Request) error
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
s.Previews.Request(r.Context(), in.linkURL)
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"pid": pid,
|
||||
"content": in.content,
|
||||
"filepath": in.filepath,
|
||||
"reply_to": in.replyTo,
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, createdJSON{PID: pid, Content: in.content, Filepath: in.filepath, ReplyTo: in.replyTo})
|
||||
return nil
|
||||
}
|
||||
|
||||
// createdJSON ist die Antwort auf einen angelegten Beitrag.
|
||||
type createdJSON struct {
|
||||
PID int64 `json:"pid"`
|
||||
Content string `json:"content"`
|
||||
Filepath string `json:"filepath"`
|
||||
ReplyTo int64 `json:"reply_to"`
|
||||
}
|
||||
|
||||
// editedJSON ist die Antwort auf einen bearbeiteten Beitrag.
|
||||
type editedJSON struct {
|
||||
PID int64 `json:"pid"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// readNewEntry prüft das Formular und speichert ein angehängtes Bild.
|
||||
func (s *Server) readNewEntry(r *http.Request) (newEntry, error) {
|
||||
in := newEntry{
|
||||
@@ -91,7 +100,8 @@ func (s *Server) readNewEntry(r *http.Request) (newEntry, error) {
|
||||
}
|
||||
|
||||
// insertEntry speichert den Beitrag und liefert seine pid. Eine Antwort hebt
|
||||
// reply_count und last_activity aller Vorfahren mit an.
|
||||
// reply_count und last_activity aller Vorfahren mit an und benachrichtigt den
|
||||
// Autor des Elternbeitrags; Erwähnte erfahren es in jedem Fall.
|
||||
func (s *Server) insertEntry(ctx context.Context, in newEntry) (int64, error) {
|
||||
var pid int64
|
||||
err := database.InTx(ctx, s.DB, func(tx *sql.Tx) error {
|
||||
@@ -99,10 +109,19 @@ func (s *Server) insertEntry(ctx context.Context, in newEntry) (int64, error) {
|
||||
if pid, err = insertWithFreshPID(ctx, tx, in); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := syncMentions(ctx, tx, pid, in.uid, in.replyTo, in.content, in.created); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := syncTags(ctx, tx, pid, in.content); err != nil {
|
||||
return err
|
||||
}
|
||||
if in.replyTo == 0 {
|
||||
return nil
|
||||
}
|
||||
return bumpAncestors(ctx, tx, in.replyTo, in.created)
|
||||
if err := bumpAncestors(ctx, tx, in.replyTo, in.created); err != nil {
|
||||
return err
|
||||
}
|
||||
return notifyReply(ctx, tx, in, pid)
|
||||
})
|
||||
return pid, err
|
||||
}
|
||||
@@ -162,12 +181,26 @@ func (s *Server) handleEditEntry(w http.ResponseWriter, r *http.Request) error {
|
||||
return apperr.Invalid("entry.empty", "Inhalt darf nicht leer sein.").At("content")
|
||||
}
|
||||
linkURL := linkpreview.Key(content)
|
||||
if _, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE entry SET content = $1, link_url = $2 WHERE pid = $3`, content, linkURL, e.PID); err != nil {
|
||||
// Benachrichtigungen zitieren den Beitrag: der Auszug soll keinen Text
|
||||
// zeigen, den der Autor inzwischen geändert hat.
|
||||
if err := database.InTx(r.Context(), s.DB, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(r.Context(),
|
||||
`UPDATE entry SET content = $1, link_url = $2 WHERE pid = $3`, content, linkURL, e.PID); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(r.Context(),
|
||||
`UPDATE notification SET excerpt = $1 WHERE pid = $2`, excerpt(content), e.PID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := syncTags(r.Context(), tx, e.PID, content); err != nil {
|
||||
return err
|
||||
}
|
||||
return syncMentions(r.Context(), tx, e.PID, e.UID, e.ReplyTo, content, s.Now().Unix())
|
||||
}); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
s.Previews.Request(r.Context(), linkURL)
|
||||
writeJSON(w, http.StatusOK, map[string]any{"pid": e.PID, "content": content})
|
||||
writeJSON(w, http.StatusOK, editedJSON{PID: e.PID, Content: content})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -197,16 +230,39 @@ func (s *Server) handleDeleteEntry(w http.ResponseWriter, r *http.Request) error
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE entry SET deleted = 1, content = '', filepath = '', link_url = '', uid = 0 WHERE pid = $1`,
|
||||
e.PID); err != nil {
|
||||
if err := database.InTx(r.Context(), s.DB, func(tx *sql.Tx) error {
|
||||
return softDeleteEntries(r.Context(), tx, "pid = $1", e.PID)
|
||||
}); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
s.removeMedia(e.Filepath)
|
||||
s.removeMedia(e.ImageCover)
|
||||
writeJSON(w, http.StatusOK, status{"deleted"})
|
||||
return nil
|
||||
}
|
||||
|
||||
// softDeleteEntries löscht alle Beiträge weich, auf die cond (eine
|
||||
// WHERE-Bedingung über entry mit $1 = arg, fest im Code) zutrifft: Inhalt,
|
||||
// Bild, Link und Autor werden geleert, die Zeile bleibt als
|
||||
// [deleted]-Platzhalter. Mit den Beiträgen verschwinden ihre Erwähnungen,
|
||||
// Hashtags und die Benachrichtigungen, die sie zitieren. Die Dateien
|
||||
// (filepath, image_cover) löscht der Aufrufer.
|
||||
func softDeleteEntries(ctx context.Context, tx *sql.Tx, cond string, arg any) error {
|
||||
pids := `(SELECT pid FROM entry WHERE ` + cond + `)`
|
||||
for _, q := range []string{
|
||||
`DELETE FROM mention WHERE pid IN ` + pids,
|
||||
`DELETE FROM entry_tag WHERE pid IN ` + pids,
|
||||
`DELETE FROM notification WHERE pid IN ` + pids,
|
||||
`UPDATE entry SET deleted = 1, content = '', filepath = '', image_warning = '', image_cover = '',
|
||||
link_url = '', uid = 0 WHERE ` + cond,
|
||||
} {
|
||||
if _, err := tx.ExecContext(ctx, q, arg); err != nil {
|
||||
return fmt.Errorf("beiträge löschen: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleReport meldet einen Beitrag, optional mit Grund. Melden darf jeder;
|
||||
// ohne Session ist der Melder anonym (uid 0). Angemeldete legen für denselben
|
||||
// Beitrag keine zweite Meldung an, solange ihre erste offen ist.
|
||||
|
||||
@@ -19,17 +19,24 @@ func serveApp(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, webDir+"/index.html")
|
||||
}
|
||||
|
||||
// serveAssets liefert die gebauten JS/CSS-Dateien. Ihre Namen enthalten einen
|
||||
// Inhalts-Hash, sie ändern sich also nie -> dauerhaft cachebar. Verzeichnisse
|
||||
// gibt es nicht zu sehen (kein Listing).
|
||||
func serveAssets() http.Handler {
|
||||
files := http.FileServer(http.Dir(webDir))
|
||||
// serveFiles liefert Dateien aus dir mit festem Cache-Control, aber ohne
|
||||
// Verzeichnislisting: http.FileServer zeigt sonst für jeden Pfad mit
|
||||
// Schluss-"/" den Inhalt des Verzeichnisses -- unter static/media wäre das die
|
||||
// Liste aller Uploads.
|
||||
func serveFiles(dir, cacheControl string) http.Handler {
|
||||
files := http.FileServer(http.Dir(dir))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/") {
|
||||
// Leer: StripPrefix hat "/static/" selbst zu "" gemacht, das wäre das
|
||||
// Wurzelverzeichnis.
|
||||
if r.URL.Path == "" || strings.HasSuffix(r.URL.Path, "/") {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
w.Header().Set("Cache-Control", cacheControl)
|
||||
files.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// immutable ist das Cache-Control für Dateien, deren Name sich mit dem Inhalt
|
||||
// ändert: gehashte Assets und Uploads mit zufälligem Namen.
|
||||
const immutable = "public, max-age=31536000, immutable"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestServeFilesNoListing: Dateien kommen durch, Verzeichnisse liefern 404
|
||||
// statt einer Liste ihres Inhalts.
|
||||
func TestServeFilesNoListing(t *testing.T) {
|
||||
t.Parallel()
|
||||
dir := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(dir, "media"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "media", "a.jpg"), []byte("x"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := http.StripPrefix("/static/", serveFiles(dir, immutable))
|
||||
for path, want := range map[string]int{
|
||||
"/static/media/a.jpg": http.StatusOK,
|
||||
"/static/media/": http.StatusNotFound,
|
||||
"/static/": http.StatusNotFound,
|
||||
"/static/fehlt.jpg": http.StatusNotFound,
|
||||
} {
|
||||
rr := httptest.NewRecorder()
|
||||
h.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if rr.Code != want {
|
||||
t.Errorf("GET %s: %d, erwartet %d", path, rr.Code, want)
|
||||
}
|
||||
if rr.Code == http.StatusOK && rr.Header().Get("Cache-Control") != immutable {
|
||||
t.Errorf("GET %s: Cache-Control %q", path, rr.Header().Get("Cache-Control"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/database"
|
||||
"kver/internal/pgpkey"
|
||||
)
|
||||
|
||||
// OpenPGP-Schlüssel der Accounts für Ende-zu-Ende-verschlüsselte
|
||||
// Direktnachrichten (notes/schluessel.md). Der Server rechnet nicht mit
|
||||
// ihnen: Er prüft beim Hochladen nur die Struktur (pgpkey), verteilt die
|
||||
// öffentlichen und bewahrt die privaten auf, die der Browser mit der
|
||||
// Passphrase verschlüsselt hat; herausgegeben wird ein privater Schlüssel
|
||||
// nur seinem Konto. Ein Kontopasswort fragt die Schlüsselverwaltung nicht
|
||||
// ab: Sie schützt die Nachrichten vor dem Server, nicht vor einer
|
||||
// übernommenen Session.
|
||||
|
||||
var (
|
||||
errKeyNone = apperr.NotFound("key.not_found", "Kein Schlüssel hinterlegt.")
|
||||
errKeyLost = apperr.NotFound("key.lost", "Der Schlüssel ist als verloren markiert.")
|
||||
errKeyExists = apperr.Conflict("key.exists", "Dieser Schlüssel ist bereits hinterlegt.").At("key")
|
||||
)
|
||||
|
||||
// keyJSON ist ein öffentlicher Schlüssel im Drahtformat. key ist das binäre
|
||||
// Zertifikat (base64); fingerprint hex in Kleinbuchstaben wie bei OpenPGP.js.
|
||||
type keyJSON struct {
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Key []byte `json:"key"`
|
||||
Status string `json:"status"` // current, replaced, lost
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
}
|
||||
|
||||
const keyColumns = `fingerprint, public_key, created_at, replaced_at, lost_at`
|
||||
|
||||
func scanKey(sc interface{ Scan(...any) error }) (keyJSON, error) {
|
||||
var k keyJSON
|
||||
var fp []byte
|
||||
var replaced, lost int64
|
||||
if err := sc.Scan(&fp, &k.Key, &k.CreatedAt, &replaced, &lost); err != nil {
|
||||
return k, err
|
||||
}
|
||||
k.Fingerprint = hex.EncodeToString(fp)
|
||||
switch {
|
||||
case lost > 0:
|
||||
k.Status = "lost"
|
||||
case replaced > 0:
|
||||
k.Status = "replaced"
|
||||
default:
|
||||
k.Status = "current"
|
||||
}
|
||||
return k, nil
|
||||
}
|
||||
|
||||
// handleUserKey liefert den aktuellen Schlüssel eines Nutzers. Ein
|
||||
// verlorener Schlüssel wird nicht mehr ausgeliefert.
|
||||
func (s *Server) handleUserKey(w http.ResponseWriter, r *http.Request) error {
|
||||
uid, err := s.accounts.UID(r.Context(), chi.URLParam(r, "handle"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
k, err := scanKey(s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT `+keyColumns+` FROM account_key WHERE uid = $1 AND replaced_at = 0`, uid))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errKeyNone
|
||||
}
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
if k.Status == "lost" {
|
||||
return errKeyLost
|
||||
}
|
||||
writeJSON(w, http.StatusOK, k)
|
||||
return nil
|
||||
}
|
||||
|
||||
// readCert liest das Formularfeld key (base64 des binären Zertifikats) und
|
||||
// prüft es.
|
||||
func readCert(r *http.Request) ([]byte, [32]byte, error) {
|
||||
cert, err := base64.StdEncoding.DecodeString(r.FormValue("key"))
|
||||
if err != nil || len(cert) == 0 {
|
||||
return nil, [32]byte{}, apperr.Invalid("key.invalid", "Kein lesbarer Schlüssel.").At("key")
|
||||
}
|
||||
fp, err := pgpkey.Fingerprint(cert)
|
||||
switch {
|
||||
case errors.Is(err, pgpkey.ErrTooLarge):
|
||||
return nil, fp, apperr.TooLarge("key.too_large", "Der Schlüssel ist zu groß.").At("key")
|
||||
case errors.Is(err, pgpkey.ErrSecret):
|
||||
// Der private Schlüssel gehört ins Feld secret, verschlüsselt.
|
||||
return nil, fp, apperr.Invalid("key.secret", "Das ist ein privater Schlüssel. Ins Feld key gehört der öffentliche.").At("key")
|
||||
case errors.Is(err, pgpkey.ErrVersion), errors.Is(err, pgpkey.ErrAlgorithm):
|
||||
return nil, fp, apperr.Invalid("key.unsupported", "Nur OpenPGP-v6-Schlüssel mit Ed25519 werden unterstützt.").At("key")
|
||||
case err != nil:
|
||||
return nil, fp, apperr.Invalid("key.invalid", "Kein lesbarer Schlüssel.").At("key")
|
||||
}
|
||||
return cert, fp, nil
|
||||
}
|
||||
|
||||
// readSecret liest das Formularfeld secret (base64 des binären privaten
|
||||
// Schlüssels) und prüft, dass es der verschlüsselte private Schlüssel zum
|
||||
// Fingerprint fp ist.
|
||||
func readSecret(r *http.Request, fp [32]byte) ([]byte, error) {
|
||||
secret, err := base64.StdEncoding.DecodeString(r.FormValue("secret"))
|
||||
if err != nil || len(secret) == 0 {
|
||||
return nil, apperr.Invalid("key.secret_invalid", "Kein lesbarer privater Schlüssel.").At("secret")
|
||||
}
|
||||
switch err := pgpkey.CheckSecret(secret, fp); {
|
||||
case errors.Is(err, pgpkey.ErrTooLarge):
|
||||
return nil, apperr.TooLarge("key.too_large", "Der Schlüssel ist zu groß.").At("secret")
|
||||
case errors.Is(err, pgpkey.ErrUnprotected), errors.Is(err, pgpkey.ErrVersion):
|
||||
// Unverschlüsselt nimmt der Server keinen privaten Schlüssel an.
|
||||
return nil, apperr.Invalid("key.secret_unprotected", "Der private Schlüssel ist nicht mit einer Passphrase (Argon2) geschützt.").At("secret")
|
||||
case errors.Is(err, pgpkey.ErrMismatch):
|
||||
return nil, apperr.Invalid("key.secret_mismatch", "Der private Schlüssel gehört zu einem anderen Schlüssel.").At("secret")
|
||||
case err != nil:
|
||||
return nil, apperr.Invalid("key.secret_invalid", "Kein lesbarer privater Schlüssel.").At("secret")
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
// handleSetKey hinterlegt einen neuen Schlüssel für den eingeloggten Nutzer
|
||||
// -- öffentlich (key) und verschlüsselt privat (secret) -- und markiert den
|
||||
// bisherigen als ersetzt.
|
||||
func (s *Server) handleSetKey(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx, uid := r.Context(), currentUID(r)
|
||||
cert, fp, err := readCert(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
secret, err := readSecret(r, fp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
now := s.Now().Unix()
|
||||
err = database.InTx(ctx, s.DB, func(tx *sql.Tx) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`UPDATE account_key SET replaced_at = $1 WHERE uid = $2 AND replaced_at = 0`, now, uid); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO account_key (uid, fingerprint, public_key, secret_key, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`, uid, fp[:], cert, secret, now)
|
||||
return err
|
||||
})
|
||||
switch {
|
||||
case database.IsUniqueViolation(err, "account_key_fingerprint_key"),
|
||||
database.IsUniqueViolation(err, "idx_account_key_current"):
|
||||
return errKeyExists
|
||||
case err != nil:
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, keyJSON{Fingerprint: hex.EncodeToString(fp[:]), Key: cert, Status: "current", CreatedAt: now})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleKeyLost markiert den aktuellen Schlüssel als verloren, etwa wenn die
|
||||
// Passphrase weg ist. Er wird dann nicht mehr ausgeliefert; danach lässt
|
||||
// sich ein neuer einrichten.
|
||||
func (s *Server) handleKeyLost(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx, uid := r.Context(), currentUID(r)
|
||||
res, err := s.DB.ExecContext(ctx,
|
||||
`UPDATE account_key SET lost_at = $1 WHERE uid = $2 AND replaced_at = 0 AND lost_at = 0`,
|
||||
s.Now().Unix(), uid)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return errKeyNone
|
||||
}
|
||||
writeJSON(w, http.StatusOK, status{"ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleKeySecrets liefert die verschlüsselten privaten Schlüssel des
|
||||
// eingeloggten Nutzers, neueste zuerst: den aktuellen und frühere, damit
|
||||
// ältere Direktnachrichten nach einem Wechsel lesbar bleiben. Ohne die
|
||||
// Passphrase nützen sie niemandem, auch nicht einer gestohlenen Session.
|
||||
func (s *Server) handleKeySecrets(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx, uid := r.Context(), currentUID(r)
|
||||
rows, err := s.DB.QueryContext(ctx,
|
||||
`SELECT fingerprint, secret_key, replaced_at, lost_at FROM account_key
|
||||
WHERE uid = $1 ORDER BY created_at DESC, id DESC`, uid)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
type secretJSON struct {
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Secret []byte `json:"secret"`
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
keys := []secretJSON{}
|
||||
for rows.Next() {
|
||||
var fp, secret []byte
|
||||
var replaced, lost int64
|
||||
if err := rows.Scan(&fp, &secret, &replaced, &lost); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
keys = append(keys, secretJSON{hex.EncodeToString(fp), secret, replaced == 0 && lost == 0})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"keys": keys})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleKeyPassphrase ersetzt den privaten Schlüssel des aktuellen
|
||||
// Schlüssels durch denselben, mit neuer Passphrase verschlüsselt. Die alte
|
||||
// Passphrase prüft der Browser beim Entschlüsseln; der Server sieht nur, dass
|
||||
// es derselbe Schlüssel ist und er geschützt bleibt.
|
||||
func (s *Server) handleKeyPassphrase(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx, uid := r.Context(), currentUID(r)
|
||||
var fpb []byte
|
||||
err := s.DB.QueryRowContext(ctx,
|
||||
`SELECT fingerprint FROM account_key WHERE uid = $1 AND replaced_at = 0`, uid).Scan(&fpb)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errKeyNone
|
||||
}
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
var fp [32]byte
|
||||
copy(fp[:], fpb)
|
||||
secret, err := readSecret(r, fp)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx,
|
||||
`UPDATE account_key SET secret_key = $1 WHERE uid = $2 AND fingerprint = $3`, secret, uid, fpb); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, status{"ok"})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Fixtures: Wegwerf-Schlüssel aus internal/pgpkey/testdata.
|
||||
func fixture(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile("../pgpkey/testdata/" + name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// keyForm baut das Formular für /user/key.
|
||||
func keyForm(cert, secret []byte) url.Values {
|
||||
f := url.Values{"key": {base64.StdEncoding.EncodeToString(cert)}}
|
||||
if secret != nil {
|
||||
f.Set("secret", base64.StdEncoding.EncodeToString(secret))
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// getAny holt urlStr ohne Login und liefert Status und dekodierten Body,
|
||||
// auch bei Fehlern.
|
||||
func getAny(t *testing.T, urlStr string, v any) int {
|
||||
t.Helper()
|
||||
return getAs(t, http.DefaultClient, urlStr, v)
|
||||
}
|
||||
|
||||
// getAs holt urlStr mit dem Client c (und dessen Session).
|
||||
func getAs(t *testing.T, c *http.Client, urlStr string, v any) int {
|
||||
t.Helper()
|
||||
resp, err := c.Get(urlStr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
|
||||
t.Fatalf("decode %s: %v", urlStr, err)
|
||||
}
|
||||
return resp.StatusCode
|
||||
}
|
||||
|
||||
// postCode schickt ein Formular und liefert Status und Fehlercode.
|
||||
func postCode(t *testing.T, c *http.Client, urlStr string, form url.Values) (int, string) {
|
||||
t.Helper()
|
||||
resp := postForm(t, c, urlStr, form)
|
||||
defer resp.Body.Close()
|
||||
var e errorResponse
|
||||
_ = json.NewDecoder(resp.Body).Decode(&e)
|
||||
return resp.StatusCode, e.Error.Code
|
||||
}
|
||||
|
||||
func TestKeys(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
v6, v6b := fixture(t, "v6.pgp"), fixture(t, "v6-2.pgp")
|
||||
locked, lockedB := fixture(t, "v6-locked.pgp"), fixture(t, "v6-2-locked.pgp")
|
||||
fpr := strings.TrimSpace(string(fixture(t, "v6.fpr")))
|
||||
fpr2 := strings.TrimSpace(string(fixture(t, "v6-2.fpr")))
|
||||
keyURL := srv.URL + "/api/u/alice/key"
|
||||
|
||||
var e errorResponse
|
||||
if got := getAny(t, srv.URL+"/api/u/niemand/key", &e); got != http.StatusNotFound {
|
||||
t.Fatalf("unbekannter nutzer: %d", got)
|
||||
}
|
||||
if got := getAny(t, keyURL, &e); got != http.StatusNotFound || e.Error.Code != "key.not_found" {
|
||||
t.Fatalf("ohne schlüssel: %d %s", got, e.Error.Code)
|
||||
}
|
||||
|
||||
// Ablehnungen vor dem ersten Schlüssel.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
c *http.Client
|
||||
form url.Values
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
{"ohne login", newClient(t), keyForm(v6, locked), 401, "auth.required"},
|
||||
{"privater schlüssel", alice, keyForm(fixture(t, "v6-secret.pgp"), locked), 400, "key.secret"},
|
||||
{"v4", alice, keyForm(fixture(t, "v4.pgp"), locked), 400, "key.unsupported"},
|
||||
{"kein base64", alice, url.Values{"key": {"%%%"}}, 400, "key.invalid"},
|
||||
{"leer", alice, url.Values{}, 400, "key.invalid"},
|
||||
} {
|
||||
if st, code := postCode(t, tc.c, srv.URL+"/api/user/key", tc.form); st != tc.status || 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, srv.URL+"/api/user/key", keyForm(v6, locked)); st != http.StatusCreated {
|
||||
t.Fatalf("schlüssel setzen: %d %s", st, code)
|
||||
}
|
||||
var k keyJSON
|
||||
if got := getAny(t, keyURL, &k); got != http.StatusOK || k.Fingerprint != fpr || !bytes.Equal(k.Key, v6) || k.Status != "current" {
|
||||
t.Fatalf("aktueller schlüssel: %d %+v", got, k)
|
||||
}
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key", keyForm(v6, locked)); st != http.StatusConflict || code != "key.exists" {
|
||||
t.Fatalf("doppelt: %d %s", st, code)
|
||||
}
|
||||
// Derselbe Schlüssel gehört nicht zusätzlich bob.
|
||||
if st, code := postCode(t, bob, srv.URL+"/api/user/key", keyForm(v6, locked)); st != http.StatusConflict || code != "key.exists" {
|
||||
t.Fatalf("fremder schlüssel: %d %s", st, code)
|
||||
}
|
||||
|
||||
// Ersetzen: der alte bleibt in der Historie.
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key", keyForm(v6b, lockedB)); st != http.StatusCreated {
|
||||
t.Fatalf("ersetzen: %d %s", st, code)
|
||||
}
|
||||
if getAny(t, keyURL, &k); k.Fingerprint != fpr2 {
|
||||
t.Fatalf("nach ersetzen: %+v", k)
|
||||
}
|
||||
|
||||
// Als verloren markieren.
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key/lost", nil); st != http.StatusOK {
|
||||
t.Fatalf("verloren: %d %s", st, code)
|
||||
}
|
||||
if got := getAny(t, keyURL, &e); got != http.StatusNotFound || e.Error.Code != "key.lost" {
|
||||
t.Fatalf("verloren abrufen: %d %s", got, e.Error.Code)
|
||||
}
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key/lost", nil); st != http.StatusNotFound || code != "key.not_found" {
|
||||
t.Fatalf("doppelt verloren: %d %s", st, code)
|
||||
}
|
||||
// Nach dem Verlust geht ein neuer Schlüssel, nur kein schon bekannter.
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key", keyForm(v6b, lockedB)); st != http.StatusConflict || code != "key.exists" {
|
||||
t.Fatalf("nach verlust bekannter schlüssel: %d %s", st, code)
|
||||
}
|
||||
|
||||
// Konto löschen nimmt die Schlüssel mit.
|
||||
if st := postStatus(t, alice, 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 account_key`).Scan(&n); err != nil || n != 0 {
|
||||
t.Fatalf("schlüssel nach konto-löschung: %d %v", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
// secretsJSON ist die Antwort von /user/keys/secret.
|
||||
type secretsJSON struct {
|
||||
Keys []struct {
|
||||
Fingerprint string
|
||||
Secret []byte
|
||||
Current bool
|
||||
}
|
||||
}
|
||||
|
||||
// TestKeySecret: Der private Schlüssel kommt nur verschlüsselt und passend
|
||||
// zum Zertifikat an, geht nur an das eigene Konto zurück und lässt sich mit
|
||||
// neuer Passphrase ersetzen.
|
||||
func TestKeySecret(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
v6, locked := fixture(t, "v6.pgp"), fixture(t, "v6-locked.pgp")
|
||||
v6b, lockedB := fixture(t, "v6-2.pgp"), fixture(t, "v6-2-locked.pgp")
|
||||
fpr := strings.TrimSpace(string(fixture(t, "v6.fpr")))
|
||||
fpr2 := strings.TrimSpace(string(fixture(t, "v6-2.fpr")))
|
||||
secretForm := func(secret []byte) url.Values {
|
||||
return url.Values{"secret": {base64.StdEncoding.EncodeToString(secret)}}
|
||||
}
|
||||
secretsURL := srv.URL + "/api/user/keys/secret"
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
secret []byte
|
||||
code string
|
||||
}{
|
||||
{"ohne", nil, "key.secret_invalid"},
|
||||
{"ungeschützt", fixture(t, "v6-secret.pgp"), "key.secret_unprotected"},
|
||||
{"ohne argon2", fixture(t, "v6-iter.pgp"), "key.secret_unprotected"},
|
||||
{"anderer schlüssel", lockedB, "key.secret_mismatch"},
|
||||
} {
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key", keyForm(v6, tc.secret)); st != 400 || code != tc.code {
|
||||
t.Errorf("%s: %d %s, erwartet 400 %s", tc.name, st, code, tc.code)
|
||||
}
|
||||
}
|
||||
var got secretsJSON
|
||||
if st := getAs(t, alice, secretsURL, &got); st != http.StatusOK || len(got.Keys) != 0 {
|
||||
t.Fatalf("secrets ohne schlüssel: %d %+v", st, got)
|
||||
}
|
||||
if st := getAs(t, newClient(t), secretsURL, &got); st != http.StatusUnauthorized {
|
||||
t.Fatalf("secrets ohne login: %d", st)
|
||||
}
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key", keyForm(v6, locked)); st != http.StatusCreated {
|
||||
t.Fatalf("schlüssel setzen: %d %s", st, code)
|
||||
}
|
||||
if getAs(t, alice, secretsURL, &got); len(got.Keys) != 1 || got.Keys[0].Fingerprint != fpr || !got.Keys[0].Current || !bytes.Equal(got.Keys[0].Secret, locked) {
|
||||
t.Fatalf("secrets: %+v", got)
|
||||
}
|
||||
// Nur ans eigene Konto.
|
||||
if getAs(t, bob, secretsURL, &got); len(got.Keys) != 0 {
|
||||
t.Fatalf("secrets von bob: %+v", got)
|
||||
}
|
||||
|
||||
// Neue Passphrase: nur derselbe Schlüssel, nur geschützt.
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key/passphrase", secretForm(lockedB)); st != 400 || code != "key.secret_mismatch" {
|
||||
t.Fatalf("passphrase fremder schlüssel: %d %s", st, code)
|
||||
}
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key/passphrase", secretForm(fixture(t, "v6-secret.pgp"))); st != 400 || code != "key.secret_unprotected" {
|
||||
t.Fatalf("passphrase ungeschützt: %d %s", st, code)
|
||||
}
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key/passphrase", secretForm(locked)); st != http.StatusOK {
|
||||
t.Fatalf("passphrase: %d %s", st, code)
|
||||
}
|
||||
|
||||
// Nach dem Ersetzen: beide, der neue zuerst.
|
||||
if st, code := postCode(t, alice, srv.URL+"/api/user/key", keyForm(v6b, lockedB)); st != http.StatusCreated {
|
||||
t.Fatalf("ersetzen: %d %s", st, code)
|
||||
}
|
||||
if getAs(t, alice, secretsURL, &got); len(got.Keys) != 2 ||
|
||||
got.Keys[0].Fingerprint != fpr2 || !got.Keys[0].Current || got.Keys[1].Fingerprint != fpr || got.Keys[1].Current {
|
||||
t.Fatalf("secrets nach ersetzen: %+v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"kver/internal/account"
|
||||
"kver/internal/apperr"
|
||||
)
|
||||
|
||||
// maxMentions: mehr Erwähnungen pro Beitrag werden ignoriert, damit ein
|
||||
// Beitrag nicht die halbe Nutzerschaft benachrichtigen kann.
|
||||
const maxMentions = 10
|
||||
|
||||
// mentionRe findet @handle; davor kein Buchstabe, keine Ziffer, kein "_" --
|
||||
// "mail@example.org" erwähnt niemanden. Das Frontend (format.tsx) nutzt
|
||||
// dieselbe Regel.
|
||||
var mentionRe = regexp.MustCompile(`(?:^|[^\p{L}\p{N}_])@([A-Za-z0-9_]+)`)
|
||||
|
||||
// parseMentions liefert die gültigen Handles im Text, klein, ohne Doppelte,
|
||||
// höchstens maxMentions.
|
||||
func parseMentions(content string) []string {
|
||||
var out []string
|
||||
seen := map[string]bool{}
|
||||
for _, m := range mentionRe.FindAllStringSubmatch(content, -1) {
|
||||
h := strings.ToLower(m[1])
|
||||
if !account.ValidHandle(h) || seen[h] {
|
||||
continue
|
||||
}
|
||||
seen[h] = true
|
||||
out = append(out, h)
|
||||
if len(out) == maxMentions {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// syncMentions gleicht die Erwähnungen des Beitrags pid mit seinem Text ab:
|
||||
// weggefallene verschwinden, neue werden mit der uid gespeichert, die den
|
||||
// Handle jetzt trägt. Benachrichtigt wird, wer vorher nicht erwähnt war --
|
||||
// nicht der Autor selbst und nicht der Autor des Elternbeitrags, der schon von
|
||||
// der Antwort erfährt. Wer gar nicht mehr erwähnt ist, verliert die
|
||||
// Benachrichtigung. Bestehende Erwähnungen behalten ihre uid, auch wenn der
|
||||
// Handle inzwischen jemand anderem gehört.
|
||||
func syncMentions(ctx context.Context, tx *sql.Tx, pid, author, replyTo int64, content string, now int64) error {
|
||||
handles := parseMentions(content)
|
||||
if handles == nil {
|
||||
handles = []string{}
|
||||
}
|
||||
before, err := mentionedUIDs(ctx, tx, pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`DELETE FROM mention WHERE pid = $1 AND NOT (handle = ANY($2))`, pid, handles); err != nil {
|
||||
return fmt.Errorf("erwähnungen abgleichen: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO mention (pid, handle, uid)
|
||||
SELECT $1, handle, uid FROM account WHERE handle = ANY($2)
|
||||
ON CONFLICT DO NOTHING`, pid, handles); err != nil {
|
||||
return fmt.Errorf("erwähnungen speichern: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`DELETE FROM notification WHERE pid = $1 AND kind = $2
|
||||
AND uid NOT IN (SELECT uid FROM mention WHERE pid = $1)`, pid, kindMention); err != nil {
|
||||
return fmt.Errorf("erwähnungen abgleichen: %w", err)
|
||||
}
|
||||
after, err := mentionedUIDs(ctx, tx, pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var parentAuthor int64
|
||||
if replyTo != 0 {
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
`SELECT uid FROM entry WHERE pid = $1`, replyTo).Scan(&parentAuthor); err != nil {
|
||||
return fmt.Errorf("elternbeitrag lesen: %w", err)
|
||||
}
|
||||
}
|
||||
for uid := range after {
|
||||
if before[uid] || uid == author || uid == parentAuthor {
|
||||
continue
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO notification (uid, kind, actor, excerpt, link, pid, created_at)
|
||||
VALUES ($1, $7, $2, $3, $4, $5, $6)`,
|
||||
uid, author, excerpt(content), entryLink(pid), pid, now, kindMention); err != nil {
|
||||
return fmt.Errorf("benachrichtigung anlegen: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// mentionedUIDs liefert, wer im Beitrag pid erwähnt ist.
|
||||
func mentionedUIDs(ctx context.Context, tx *sql.Tx, pid int64) (map[int64]bool, error) {
|
||||
rows, err := tx.QueryContext(ctx, `SELECT DISTINCT uid FROM mention WHERE pid = $1`, pid)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("erwähnungen lesen: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
uids := map[int64]bool{}
|
||||
for rows.Next() {
|
||||
var uid int64
|
||||
if err := rows.Scan(&uid); err != nil {
|
||||
return nil, fmt.Errorf("erwähnungen lesen: %w", err)
|
||||
}
|
||||
uids[uid] = true
|
||||
}
|
||||
return uids, rows.Err()
|
||||
}
|
||||
|
||||
// maxSuggestions: so viele Vorschläge liefert die Autovervollständigung.
|
||||
const maxSuggestions = 8
|
||||
|
||||
// suggestionJSON ist ein Vorschlag für die Autovervollständigung von @handle.
|
||||
type suggestionJSON struct {
|
||||
Handle string `json:"handle"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Avatar string `json:"avatar"`
|
||||
}
|
||||
|
||||
// handleUserSuggest schlägt zu einem angefangenen @handle (q, "@" optional)
|
||||
// Nutzer vor: zuerst Handles, die mit q beginnen, dann Anzeigenamen, die q
|
||||
// enthalten -- "@jö" findet so auch "Jörg @joerg". Leeres q liefert nichts.
|
||||
func (s *Server) handleUserSuggest(w http.ResponseWriter, r *http.Request) error {
|
||||
q := strings.TrimPrefix(strings.TrimSpace(r.URL.Query().Get("q")), "@")
|
||||
list := []suggestionJSON{}
|
||||
if q == "" || utf8.RuneCountInString(q) > account.MaxHandleLen {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"users": list})
|
||||
return nil
|
||||
}
|
||||
prefix := escapeLike(strings.ToLower(q)) + "%"
|
||||
rows, err := s.DB.QueryContext(r.Context(),
|
||||
`SELECT handle, display_name, avatar FROM account
|
||||
WHERE handle LIKE $1 OR display_name ILIKE $2
|
||||
ORDER BY handle LIKE $1 DESC, handle LIMIT $3`,
|
||||
prefix, "%"+escapeLike(q)+"%", maxSuggestions)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var u suggestionJSON
|
||||
if err := rows.Scan(&u.Handle, &u.DisplayName, &u.Avatar); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
list = append(list, u)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"users": list})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseMentions(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
in string
|
||||
want []string
|
||||
}{
|
||||
{"hallo @Bob, und @carol!", []string{"bob", "carol"}},
|
||||
{"@bob @BOB @bob", []string{"bob"}},
|
||||
{"mail@bob.org x@bob", nil},
|
||||
{"@ab @" + "abcdefghijklmnopqrstu", nil}, // zu kurz, zu lang
|
||||
{"(@bob) #tag @_x_", []string{"bob", "_x_"}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := parseMentions(tt.in); !slices.Equal(got, tt.want) {
|
||||
t.Errorf("parseMentions(%q) = %q, erwartet %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
many := ""
|
||||
for i := range 15 {
|
||||
many += fmt.Sprintf(" @user%02d", i)
|
||||
}
|
||||
if n := len(parseMentions(many)); n != maxMentions {
|
||||
t.Errorf("%d Erwähnungen, erwartet höchstens %d", n, maxMentions)
|
||||
}
|
||||
}
|
||||
|
||||
// mentionsOf liest die Erwähnungen eines Beitrags aus dem Thread.
|
||||
func mentionsOf(t *testing.T, c *http.Client, srv *testServer, pid int64) map[string]string {
|
||||
t.Helper()
|
||||
var th struct {
|
||||
Entry struct {
|
||||
Mentions map[string]string `json:"mentions"`
|
||||
} `json:"entry"`
|
||||
}
|
||||
getAs(t, c, fmt.Sprintf("%s/api/entry/%d/thread", srv.URL, pid), &th)
|
||||
return th.Entry.Mentions
|
||||
}
|
||||
|
||||
func notificationsOf(t *testing.T, c *http.Client, srv *testServer) []notificationJSON {
|
||||
t.Helper()
|
||||
var list notificationList
|
||||
getAs(t, c, srv.URL+"/api/notifications", &list)
|
||||
return list.Notifications
|
||||
}
|
||||
|
||||
func TestMentions(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
carol := registerAndLogin(t, srv, "carol")
|
||||
|
||||
root := createEntry(t, alice, srv, post("hallo @Bob und @carol, @alice, mail@bob.org, @niemand"))
|
||||
if got := mentionsOf(t, alice, srv, root); len(got) != 3 || got["bob"] != "bob" || got["alice"] != "alice" {
|
||||
t.Errorf("mentions: %v", got)
|
||||
}
|
||||
for _, c := range []*http.Client{bob, carol} {
|
||||
n := notificationsOf(t, c, srv)
|
||||
if len(n) != 1 || n[0].Kind != "mention" || n[0].Message != "@alice hat dich erwähnt." ||
|
||||
n[0].Link != fmt.Sprintf("/e/%d", root) {
|
||||
t.Errorf("erwähnt: %+v", n)
|
||||
}
|
||||
}
|
||||
if n := notificationsOf(t, alice, srv); len(n) != 0 {
|
||||
t.Errorf("selbst erwähnt: %+v", n)
|
||||
}
|
||||
|
||||
// Antwort samt Erwähnung des Elternautors: nur die Antwort-Benachrichtigung.
|
||||
createEntry(t, bob, srv, reply(root, "danke @alice"))
|
||||
if n := notificationsOf(t, alice, srv); len(n) != 1 || n[0].Kind != "reply" {
|
||||
t.Errorf("antwort mit erwähnung: %+v", n)
|
||||
}
|
||||
|
||||
// Umbenennen: der alte Link führt zur selben Person, nicht zum neuen
|
||||
// Träger des Handles.
|
||||
for _, r := range []struct {
|
||||
c *http.Client
|
||||
handle string
|
||||
}{{bob, "robert"}, {carol, "bob"}} {
|
||||
resp := postForm(t, r.c, srv.URL+"/api/user/handle", url.Values{"handle": {r.handle}})
|
||||
resp.Body.Close()
|
||||
}
|
||||
if got := mentionsOf(t, alice, srv, root); got["bob"] != "robert" || got["carol"] != "bob" {
|
||||
t.Errorf("nach umbenennen: %v", got)
|
||||
}
|
||||
|
||||
// Bearbeiten: weggefallene Erwähnung verschwindet samt Benachrichtigung.
|
||||
resp := postForm(t, alice, fmt.Sprintf("%s/api/entry/%d/edit", srv.URL, root),
|
||||
url.Values{"content": {"hallo @robert"}})
|
||||
resp.Body.Close()
|
||||
if got := mentionsOf(t, alice, srv, root); len(got) != 1 || got["robert"] != "robert" {
|
||||
t.Errorf("nach bearbeiten: %v", got)
|
||||
}
|
||||
if n := notificationsOf(t, carol, srv); len(n) != 0 {
|
||||
t.Errorf("carol nach bearbeiten: %+v", n)
|
||||
}
|
||||
// robert war schon als @bob erwähnt: die Benachrichtigung bleibt die alte
|
||||
// (schon gesehene), keine zweite.
|
||||
if n := notificationsOf(t, bob, srv); len(n) != 1 || !n[0].Seen {
|
||||
t.Errorf("robert nach bearbeiten: %+v", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserSuggest(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
registerAndLogin(t, srv, "joerg")
|
||||
registerAndLogin(t, srv, "jo_ann")
|
||||
registerAndLogin(t, srv, "maxi")
|
||||
resp := postForm(t, alice, srv.URL+"/api/user/display_name", url.Values{"display_name": {"Jörg Joseph"}})
|
||||
resp.Body.Close()
|
||||
|
||||
suggest := func(q string) []string {
|
||||
var out struct {
|
||||
Users []suggestionJSON `json:"users"`
|
||||
}
|
||||
if code := getAs(t, alice, srv.URL+"/api/users/suggest?q="+url.QueryEscape(q), &out); code != http.StatusOK {
|
||||
t.Fatalf("suggest %q: status %d", q, code)
|
||||
}
|
||||
var hs []string
|
||||
for _, u := range out.Users {
|
||||
hs = append(hs, u.Handle)
|
||||
}
|
||||
return hs
|
||||
}
|
||||
for _, tt := range []struct {
|
||||
q string
|
||||
want []string
|
||||
}{
|
||||
{"@Jo", []string{"jo_ann", "joerg", "alice"}}, // Handles zuerst, dann Anzeigename
|
||||
{"jö", []string{"alice"}},
|
||||
{"jo_", []string{"jo_ann"}}, // _ ist kein LIKE-Platzhalter
|
||||
{"", nil},
|
||||
{"xyz", nil},
|
||||
} {
|
||||
if got := suggest(tt.q); !slices.Equal(got, tt.want) {
|
||||
t.Errorf("suggest(%q) = %v, erwartet %v", tt.q, got, tt.want)
|
||||
}
|
||||
}
|
||||
if code := getAny(t, srv.URL+"/api/users/suggest?q=jo", &struct{}{}); code != http.StatusUnauthorized {
|
||||
t.Errorf("ohne Login: %d", code)
|
||||
}
|
||||
}
|
||||
@@ -60,8 +60,11 @@ func secHeaders(next http.Handler) http.Handler {
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "same-origin")
|
||||
// 'wasm-unsafe-eval' erlaubt nur das Kompilieren von WebAssembly (für
|
||||
// Argon2 in OpenPGP.js, notes/schluessel.md), kein eval und keine
|
||||
// Inline-Skripte; Skripte selbst kommen weiter nur von 'self'.
|
||||
h.Set("Content-Security-Policy",
|
||||
"default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
|
||||
"default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -69,18 +72,25 @@ func secHeaders(next http.Handler) http.Handler {
|
||||
var errBadOrigin = apperr.Forbidden("csrf.bad_origin", "Anfrage von fremder Seite abgelehnt")
|
||||
|
||||
// checkOrigin weist zustandsändernde Cross-Site-Requests ab (CSRF-Schutz,
|
||||
// zusätzlich zu SameSite=Lax für ältere Browser bzw. GET-Navigationen).
|
||||
// Browser setzen bei Cross-Site-Requests immer einen Origin-Header; fehlt er
|
||||
// (Nicht-Browser-Clients wie curl, gleiche Site bei manchen Browsern), lassen
|
||||
// wir durch -- der Cookie-Schutz greift dort ohnehin nicht bzw. schon.
|
||||
// zusätzlich zu SameSite=Lax für ältere Browser bzw. GET-Navigationen). Zwei
|
||||
// Quellen, beide vom Browser gesetzt und von Seiten nicht fälschbar:
|
||||
// Sec-Fetch-Site sagt direkt, ob der Request von derselben Origin kommt
|
||||
// (same-origin) oder vom Nutzer selbst ausgeht (none: Adresszeile,
|
||||
// Lesezeichen); Origin wird gegen den Host verglichen. Fehlen beide
|
||||
// (Nicht-Browser-Clients wie curl), lassen wir durch -- der Cookie-Schutz
|
||||
// greift dort ohnehin nicht.
|
||||
func checkOrigin(r *http.Request) error {
|
||||
o := r.Header.Get("Origin")
|
||||
if r.Method == http.MethodGet || r.Method == http.MethodHead || o == "" {
|
||||
if r.Method == http.MethodGet || r.Method == http.MethodHead {
|
||||
return nil
|
||||
}
|
||||
if u, err := url.Parse(o); err != nil || u.Host != r.Host {
|
||||
if site := r.Header.Get("Sec-Fetch-Site"); site != "" && site != "same-origin" && site != "none" {
|
||||
return errBadOrigin
|
||||
}
|
||||
if o := r.Header.Get("Origin"); o != "" {
|
||||
if u, err := url.Parse(o); err != nil || u.Host != r.Host {
|
||||
return errBadOrigin
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -131,8 +141,9 @@ type ctxKey struct{}
|
||||
|
||||
var errAuthRequired = apperr.Unauth("auth.required", "Nicht angemeldet")
|
||||
|
||||
// requireAuth lehnt Anfragen ohne gültige Session ab und legt die uid in den
|
||||
// Context.
|
||||
// requireAuth lehnt Anfragen ohne gültige Session ab und legt die Session in
|
||||
// den Context -- einmal lesen genügt, die Handler holen sie sich von dort
|
||||
// (currentSession, currentUID).
|
||||
func (s *Server) requireAuth(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
sess, ok := s.session(r)
|
||||
@@ -140,14 +151,18 @@ func (s *Server) requireAuth(next http.Handler) http.Handler {
|
||||
s.writeError(w, r, errAuthRequired)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), ctxKey{}, sess.UID)
|
||||
ctx := context.WithValue(r.Context(), ctxKey{}, sess)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// currentSession ist die Session des angemeldeten Nutzers (nur hinter
|
||||
// requireAuth gesetzt).
|
||||
func currentSession(r *http.Request) session {
|
||||
sess, _ := r.Context().Value(ctxKey{}).(session)
|
||||
return sess
|
||||
}
|
||||
|
||||
// currentUID ist die uid des angemeldeten Nutzers (nur hinter requireAuth
|
||||
// gesetzt).
|
||||
func currentUID(r *http.Request) int64 {
|
||||
id, _ := r.Context().Value(ctxKey{}).(int64)
|
||||
return id
|
||||
}
|
||||
func currentUID(r *http.Request) int64 { return currentSession(r).UID }
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/runes"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxNotifications begrenzt die Liste auf die jüngsten Einträge.
|
||||
maxNotifications = 50
|
||||
// excerptRunes: so viel vom Beitrag steht in der Benachrichtigung.
|
||||
excerptRunes = 50
|
||||
)
|
||||
|
||||
// Arten von Benachrichtigungen (Spalte notification.kind, Feld kind der API).
|
||||
const (
|
||||
kindReply = "reply" // Antwort auf einen eigenen Beitrag
|
||||
kindMention = "mention" // in einem Beitrag erwähnt
|
||||
kindBump = "bump" // eigener Beitrag repostet
|
||||
)
|
||||
|
||||
// notificationJSON ist eine Benachrichtigung in der Liste. Seen meldet den
|
||||
// Stand vor dem Abruf: so sieht die Liste, was neu war, obwohl der Abruf
|
||||
// selbst alles als gesehen markiert.
|
||||
type notificationJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
Kind string `json:"kind"`
|
||||
Message string `json:"message"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
Link string `json:"link"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Seen bool `json:"seen"`
|
||||
}
|
||||
|
||||
// excerpt ist der Anfang eines Beitrags für die Benachrichtigung, Leerraum
|
||||
// zusammengefasst.
|
||||
func excerpt(content string) string {
|
||||
e := strings.Join(strings.Fields(content), " ")
|
||||
if short := runes.Truncate(e, excerptRunes); short != e {
|
||||
e = strings.TrimSpace(short) + "…"
|
||||
}
|
||||
return e
|
||||
}
|
||||
|
||||
// entryLink ist der interne Pfad zu einem Beitrag, wie ihn eine
|
||||
// Benachrichtigung trägt.
|
||||
func entryLink(pid int64) string { return fmt.Sprintf("/e/%d", pid) }
|
||||
|
||||
// notificationMessage ist die Zeile, die sagt, was passiert ist. actor ist
|
||||
// der Handle dessen, der geantwortet hat; leer (Reposts, unbekannt) heißt
|
||||
// "Jemand". Den Auszug liefert die API getrennt.
|
||||
func notificationMessage(kind, actor string) string {
|
||||
who := "Jemand"
|
||||
if actor != "" {
|
||||
who = "@" + actor
|
||||
}
|
||||
switch kind {
|
||||
case kindReply:
|
||||
return who + " hat auf deinen Beitrag geantwortet."
|
||||
case kindMention:
|
||||
return who + " hat dich erwähnt."
|
||||
}
|
||||
return who + " hat deinen Beitrag repostet."
|
||||
}
|
||||
|
||||
// notifyReply benachrichtigt den Autor des Elternbeitrags über die Antwort
|
||||
// pid, nicht aber bei Antworten auf sich selbst oder auf gelöschte Beiträge
|
||||
// (uid 0). Zitiert wird die Antwort. Läuft in der Transaktion, die sie anlegt.
|
||||
func notifyReply(ctx context.Context, tx *sql.Tx, in newEntry, pid int64) error {
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO notification (uid, kind, actor, excerpt, link, pid, created_at)
|
||||
SELECT uid, $7, $1, $2, $3, $4, $5 FROM entry
|
||||
WHERE pid = $6 AND uid <> 0 AND uid <> $1`,
|
||||
in.uid, excerpt(in.content), entryLink(pid), pid, in.created, in.replyTo, kindReply); err != nil {
|
||||
return fmt.Errorf("benachrichtigung anlegen: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// notifyBump benachrichtigt den Autor über einen Repost seines Beitrags pid,
|
||||
// außer er hat ihn selbst repostet. Wer repostet, wird nicht gespeichert.
|
||||
func notifyBump(ctx context.Context, tx *sql.Tx, pid, bumper, now int64) error {
|
||||
var author int64
|
||||
var content string
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
`SELECT uid, content FROM entry WHERE pid = $1`, pid).Scan(&author, &content); err != nil {
|
||||
return fmt.Errorf("beitrag lesen: %w", err)
|
||||
}
|
||||
if author == 0 || author == bumper {
|
||||
return nil
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO notification (uid, kind, excerpt, link, pid, created_at)
|
||||
VALUES ($1, $6, $2, $3, $4, $5)`,
|
||||
author, excerpt(content), entryLink(pid), pid, now, kindBump); err != nil {
|
||||
return fmt.Errorf("benachrichtigung anlegen: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleNotifications liefert die jüngsten Benachrichtigungen, neueste
|
||||
// zuerst, und markiert die gelieferten als gesehen.
|
||||
func (s *Server) handleNotifications(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx, uid := r.Context(), currentUID(r)
|
||||
rows, err := s.DB.QueryContext(ctx,
|
||||
`SELECT n.id, n.kind, COALESCE(a.handle, ''), n.excerpt, n.link, n.created_at, n.seen_at > 0
|
||||
FROM notification n LEFT JOIN account a ON a.uid = n.actor AND n.actor <> 0
|
||||
WHERE n.uid = $1 ORDER BY n.id DESC LIMIT $2`, uid, maxNotifications)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
list := []notificationJSON{}
|
||||
for rows.Next() {
|
||||
var n notificationJSON
|
||||
var actor string
|
||||
if err := rows.Scan(&n.ID, &n.Kind, &actor, &n.Excerpt, &n.Link, &n.CreatedAt, &n.Seen); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
n.Message = notificationMessage(n.Kind, actor)
|
||||
list = append(list, n)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
// Nur bis zur jüngsten gelieferten: was während des Abrufs neu kam, hat
|
||||
// noch niemand gesehen.
|
||||
if len(list) > 0 {
|
||||
if _, err := s.DB.ExecContext(ctx,
|
||||
`UPDATE notification SET seen_at = $1 WHERE uid = $2 AND seen_at = 0 AND id <= $3`,
|
||||
s.Now().Unix(), uid, list[0].ID); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"notifications": list})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleNotificationsUnread zählt die ungesehenen Benachrichtigungen (für den
|
||||
// Zähler am Icon).
|
||||
func (s *Server) handleNotificationsUnread(w http.ResponseWriter, r *http.Request) error {
|
||||
var n int64
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT COUNT(*) FROM notification WHERE uid = $1 AND seen_at = 0`, currentUID(r)).Scan(&n); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]int64{"unread": n})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type notificationList struct {
|
||||
Notifications []notificationJSON `json:"notifications"`
|
||||
}
|
||||
|
||||
func unreadNotifications(t *testing.T, c *http.Client, srv *testServer) int {
|
||||
t.Helper()
|
||||
var out struct {
|
||||
Unread int `json:"unread"`
|
||||
}
|
||||
if code := getAs(t, c, srv.URL+"/api/notifications/unread", &out); code != http.StatusOK {
|
||||
t.Fatalf("/notifications/unread: status %d", code)
|
||||
}
|
||||
return out.Unread
|
||||
}
|
||||
|
||||
func TestNotifyReply(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
|
||||
root := createEntry(t, alice, srv, post("frage"))
|
||||
createEntry(t, alice, srv, reply(root, "nachtrag")) // an sich selbst: nichts
|
||||
long := strings.Repeat("wort ", 20)
|
||||
answer := createEntry(t, bob, srv, reply(root, long))
|
||||
|
||||
if n := unreadNotifications(t, alice, srv); n != 1 {
|
||||
t.Fatalf("alice ungesehen: %d, erwartet 1", n)
|
||||
}
|
||||
if n := unreadNotifications(t, bob, srv); n != 0 {
|
||||
t.Errorf("bob ungesehen: %d, erwartet 0", n)
|
||||
}
|
||||
|
||||
var list notificationList
|
||||
getAs(t, alice, srv.URL+"/api/notifications", &list)
|
||||
if len(list.Notifications) != 1 {
|
||||
t.Fatalf("liste: %+v", list)
|
||||
}
|
||||
n := list.Notifications[0]
|
||||
if n.Kind != "reply" || n.Link != fmt.Sprintf("/e/%d", answer) || n.Seen ||
|
||||
n.Message != "@bob hat auf deinen Beitrag geantwortet." || n.Excerpt != strings.TrimSpace(long[:50])+"…" {
|
||||
t.Errorf("benachrichtigung: %+v", n)
|
||||
}
|
||||
// Das Ansehen der Liste markiert alles als gesehen.
|
||||
if c := unreadNotifications(t, alice, srv); c != 0 {
|
||||
t.Errorf("nach dem Ansehen ungesehen: %d", c)
|
||||
}
|
||||
getAs(t, alice, srv.URL+"/api/notifications", &list)
|
||||
if !list.Notifications[0].Seen {
|
||||
t.Error("zweiter Abruf: nicht als gesehen markiert")
|
||||
}
|
||||
|
||||
// Bearbeiten zieht den Auszug nach, ein neuer Handle erscheint sofort,
|
||||
// Löschen nimmt die Benachrichtigung mit.
|
||||
editURL := fmt.Sprintf("%s/api/entry/%d/edit", srv.URL, answer)
|
||||
resp := postForm(t, bob, editURL, url.Values{"content": {"neu"}})
|
||||
resp.Body.Close()
|
||||
resp = postForm(t, bob, srv.URL+"/api/user/handle", url.Values{"handle": {"robert"}})
|
||||
resp.Body.Close()
|
||||
getAs(t, alice, srv.URL+"/api/notifications", &list)
|
||||
if n := list.Notifications[0]; n.Message != "@robert hat auf deinen Beitrag geantwortet." || n.Excerpt != "neu" {
|
||||
t.Errorf("nach Bearbeiten und Umbenennen: %+v", n)
|
||||
}
|
||||
resp = postForm(t, bob, fmt.Sprintf("%s/api/entry/%d/delete", srv.URL, answer), nil)
|
||||
resp.Body.Close()
|
||||
getAs(t, alice, srv.URL+"/api/notifications", &list)
|
||||
if len(list.Notifications) != 0 {
|
||||
t.Errorf("nach dem Löschen: %+v", list.Notifications)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyBump(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
mine := createEntry(t, alice, srv, post("mein erster\nbeitrag"))
|
||||
own := createEntry(t, alice, srv, post("selbst repostet"))
|
||||
|
||||
for _, b := range []struct {
|
||||
c *http.Client
|
||||
pid int64
|
||||
}{{bob, mine}, {alice, own}} {
|
||||
resp := postForm(t, b.c, fmt.Sprintf("%s/api/entry/%d/bump", srv.URL, b.pid), nil)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("bump %d: status %d", b.pid, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
var list notificationList
|
||||
getAs(t, alice, srv.URL+"/api/notifications", &list)
|
||||
if len(list.Notifications) != 1 {
|
||||
t.Fatalf("liste: %+v", list.Notifications)
|
||||
}
|
||||
n := list.Notifications[0]
|
||||
// Wer repostet, wird nicht gespeichert: "Jemand", auch wenn es bob war.
|
||||
if n.Kind != "bump" || n.Link != fmt.Sprintf("/e/%d", mine) ||
|
||||
n.Message != "Jemand hat deinen Beitrag repostet." || n.Excerpt != "mein erster beitrag" {
|
||||
t.Errorf("benachrichtigung: %+v", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotificationsNeedLogin(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
if code := getAny(t, srv.URL+"/api/notifications/unread", &struct{}{}); code != http.StatusUnauthorized {
|
||||
t.Errorf("ohne Login: status %d, erwartet 401", code)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"kver/internal/account"
|
||||
)
|
||||
|
||||
type profileJSON struct {
|
||||
@@ -75,7 +77,7 @@ func TestProfileBio(t *testing.T) {
|
||||
t.Fatalf("bio: erwartet 200, bekam %d", got)
|
||||
}
|
||||
p := getProfile(t, srv, "alice")
|
||||
if !strings.HasPrefix(p.Bio, "Zeile 1\nZeile 2 ö") || len([]rune(p.Bio)) != maxBioRunes {
|
||||
if !strings.HasPrefix(p.Bio, "Zeile 1\nZeile 2 ö") || len([]rune(p.Bio)) != account.MaxBioRunes {
|
||||
t.Fatalf("bio falsch gespeichert: %q (%d Runen)", p.Bio, len([]rune(p.Bio)))
|
||||
}
|
||||
if p.Entries != 2 {
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
// tippt. POST statt GET, damit das Token nicht in der URL und damit im Log
|
||||
// steht.
|
||||
func (s *Server) handleResetCheck(w http.ResponseWriter, r *http.Request) error {
|
||||
username, err := s.accounts.ResetUsername(r.Context(), r.FormValue("token"))
|
||||
handle, err := s.accounts.ResetHandle(r.Context(), r.FormValue("token"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"username": username})
|
||||
writeJSON(w, http.StatusOK, map[string]string{"handle": handle})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) error {
|
||||
if len(fields) > 0 {
|
||||
return errInvalidForm.WithFields(fields)
|
||||
}
|
||||
uid, username, err := s.accounts.ResetPassword(r.Context(), r.FormValue("token"), pass1)
|
||||
uid, handle, err := s.accounts.ResetPassword(r.Context(), r.FormValue("token"), pass1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -42,6 +42,6 @@ func (s *Server) handleReset(w http.ResponseWriter, r *http.Request) error {
|
||||
if err := s.startSession(w, r, uid); err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"username": username})
|
||||
writeJSON(w, http.StatusOK, map[string]string{"handle": handle})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@ package httpapi
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"kver/internal/apperr"
|
||||
)
|
||||
@@ -57,6 +59,8 @@ type errorBody struct {
|
||||
Fields map[string]string `json:"fields,omitempty"`
|
||||
}
|
||||
|
||||
// errorResponse ist die Fehlerantwort, wie Clients sie lesen: "error" plus
|
||||
// eventuelle Zusatzfelder (apperr.Error.Extra) daneben.
|
||||
type errorResponse struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
@@ -69,9 +73,16 @@ func (s *Server) writeError(w http.ResponseWriter, r *http.Request, err error) {
|
||||
if e.Kind == apperr.KindInternal {
|
||||
s.Log.Error("interner fehler", "method", r.Method, "path", r.URL.Path, "err", e.Unwrap())
|
||||
}
|
||||
writeJSON(w, statusOf(e.Kind), errorResponse{errorBody{
|
||||
Code: e.Code, Message: e.Msg, Field: e.Field, Fields: e.Fields,
|
||||
}})
|
||||
if e.RetryAfter > 0 {
|
||||
w.Header().Set("Retry-After", strconv.FormatInt(int64(e.RetryAfter/time.Second), 10))
|
||||
}
|
||||
body := map[string]any{"error": errorBody{Code: e.Code, Message: e.Msg, Field: e.Field, Fields: e.Fields}}
|
||||
for k, v := range e.Extra {
|
||||
if k != "error" {
|
||||
body[k] = v
|
||||
}
|
||||
}
|
||||
writeJSON(w, statusOf(e.Kind), body)
|
||||
}
|
||||
|
||||
// statusOf bildet Kind auf HTTP ab -- die einzige Stelle, an der das passiert.
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"kver/internal/apperr"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxQueryRunes und maxTerms deckeln, wie viele Bedingungen eine Suche
|
||||
// erzeugt -- jede ist ein Scan über den Inhalt.
|
||||
maxQueryRunes = 200
|
||||
maxTerms = 10
|
||||
)
|
||||
|
||||
// tagRe ist ein Hashtag ohne #: Buchstaben, Ziffern, Unterstrich. Damit
|
||||
// enthält ein Tag kein Regex-Sonderzeichen und darf ungeschützt ins Muster.
|
||||
var tagRe = regexp.MustCompile(`^[\p{L}\p{N}_]+$`)
|
||||
|
||||
var (
|
||||
errQueryTooLong = apperr.Invalid("search.too_long", "Suche zu lang.")
|
||||
errBadTag = apperr.Invalid("search.bad_tag", "Hashtags bestehen nur aus Buchstaben, Ziffern und _.").At("tag")
|
||||
)
|
||||
|
||||
// filter wählt Beiträge aus. Alle gesetzten Bedingungen gelten zugleich; der
|
||||
// leere Filter lässt alle nicht gelöschten Beiträge durch. Ergebnisse kommen
|
||||
// neueste zuerst. Grundlage für Suche, Profil-Feed und Hashtags.
|
||||
type filter struct {
|
||||
// Words müssen alle im Inhalt vorkommen, Groß-/Kleinschreibung egal.
|
||||
Words []string
|
||||
// UID ist der Autor, 0 = beliebig.
|
||||
UID int64
|
||||
// Tags (ohne #) müssen alle als ganzes Hashtag vorkommen: #kv trifft
|
||||
// nicht #kver.
|
||||
Tags []string
|
||||
// Roots: nur Wurzelbeiträge, keine Antworten.
|
||||
Roots bool
|
||||
}
|
||||
|
||||
// where liefert die WHERE-Klausel samt Parametern ($1 ...) für entrySelect.
|
||||
func (f filter) where() (string, []any) {
|
||||
conds := []string{"e.deleted = 0"}
|
||||
var args []any
|
||||
arg := func(v any) string {
|
||||
args = append(args, v)
|
||||
return fmt.Sprintf("$%d", len(args))
|
||||
}
|
||||
for _, w := range f.Words {
|
||||
conds = append(conds, "e.content ILIKE "+arg("%"+escapeLike(w)+"%"))
|
||||
}
|
||||
if f.UID != 0 {
|
||||
conds = append(conds, "e.uid = "+arg(f.UID))
|
||||
}
|
||||
for _, t := range f.Tags {
|
||||
conds = append(conds, "e.content ~* "+arg(`(^|[^[:alnum:]_])#`+t+`([^[:alnum:]_]|$)`))
|
||||
}
|
||||
if f.Roots {
|
||||
conds = append(conds, "e.reply_to = 0")
|
||||
}
|
||||
return " WHERE " + strings.Join(conds, " AND "), args
|
||||
}
|
||||
|
||||
// escapeLike schützt die LIKE-Platzhalter, damit "100%" wörtlich gesucht wird.
|
||||
func escapeLike(s string) string {
|
||||
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(s)
|
||||
}
|
||||
|
||||
// filterPage liefert Seite {page} der Beiträge, die f durchlässt. Bei
|
||||
// gleicher Sekunde entscheidet id (Reihenfolge des Anlegens), nicht die
|
||||
// zufällige pid.
|
||||
func (s *Server) filterPage(r *http.Request, f filter) ([]Entry, error) {
|
||||
where, args := f.where()
|
||||
return s.feedPage(r, entrySelect+where+` ORDER BY e.created_at DESC, e.id DESC`, args...)
|
||||
}
|
||||
|
||||
// parseFilter liest einen Filter aus den Query-Parametern: q (Freitext,
|
||||
// Wörter durch Leerzeichen getrennt), user (Handle, @ optional), tag (ein oder
|
||||
// mehrere Hashtags, # optional), roots=1 (keine Antworten).
|
||||
func (s *Server) parseFilter(r *http.Request) (filter, error) {
|
||||
q := r.URL.Query()
|
||||
var f filter
|
||||
text, tags := q.Get("q"), q.Get("tag")
|
||||
if utf8.RuneCountInString(text) > maxQueryRunes || utf8.RuneCountInString(tags) > maxQueryRunes {
|
||||
return f, errQueryTooLong
|
||||
}
|
||||
f.Words = strings.Fields(text)
|
||||
for _, t := range strings.Fields(tags) {
|
||||
t = strings.TrimPrefix(t, "#")
|
||||
if !tagRe.MatchString(t) {
|
||||
return f, errBadTag
|
||||
}
|
||||
f.Tags = append(f.Tags, t)
|
||||
}
|
||||
if len(f.Words)+len(f.Tags) > maxTerms {
|
||||
return f, errQueryTooLong
|
||||
}
|
||||
if name := strings.TrimSpace(q.Get("user")); name != "" {
|
||||
uid, err := s.accounts.UID(r.Context(), name)
|
||||
if err != nil {
|
||||
return f, err
|
||||
}
|
||||
f.UID = uid
|
||||
}
|
||||
f.Roots = q.Get("roots") == "1"
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// handleSearch liefert eine Seite der Beiträge zu den Filtern aus der Query.
|
||||
func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request) error {
|
||||
f, err := s.parseFilter(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries, err := s.filterPage(r, f)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, entries)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func searchPath(q url.Values) string { return "/api/entry/search/0?" + q.Encode() }
|
||||
|
||||
func TestSearch(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
bob := registerAndLogin(t, srv, "bob")
|
||||
|
||||
hello := createEntry(t, alice, srv, post("Hallo Welt #kver"))
|
||||
short := createEntry(t, alice, srv, post("Nur #kv hier"))
|
||||
answer := createEntry(t, bob, srv, reply(hello, "Welt-Antwort zu 100%"))
|
||||
gone := createEntry(t, bob, srv, post("Welt, gleich weg #kver"))
|
||||
resp := postForm(t, bob, fmt.Sprintf("%s/api/entry/%d/delete", srv.URL, gone), nil)
|
||||
resp.Body.Close()
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
q url.Values
|
||||
want []int64
|
||||
}{
|
||||
{"leer", url.Values{}, []int64{answer, short, hello}},
|
||||
{"freitext", url.Values{"q": {"WELT"}}, []int64{answer, hello}},
|
||||
{"alle wörter", url.Values{"q": {"welt hallo"}}, []int64{hello}},
|
||||
{"nur wurzeln", url.Values{"q": {"welt"}, "roots": {"1"}}, []int64{hello}},
|
||||
{"autor", url.Values{"user": {"bob"}}, []int64{answer}},
|
||||
{"autor mit @", url.Values{"user": {"@alice"}, "q": {"hier"}}, []int64{short}},
|
||||
{"hashtag ganz", url.Values{"tag": {"kver"}}, []int64{hello}},
|
||||
{"hashtag kurz", url.Values{"tag": {"#KV"}}, []int64{short}},
|
||||
{"hashtags zugleich", url.Values{"tag": {"kv kver"}}, []int64{}},
|
||||
{"prozent wörtlich", url.Values{"q": {"100%"}}, []int64{answer}},
|
||||
{"unterstrich wörtlich", url.Values{"q": {"Welt_"}}, []int64{}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := feedPIDs(t, srv, searchPath(tc.q)); !slices.Equal(got, tc.want) {
|
||||
t.Errorf("%v: erwartet %v, bekam %v", tc.q, tc.want, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
q url.Values
|
||||
want int
|
||||
}{
|
||||
{"kaputtes hashtag", url.Values{"tag": {"a-b"}}, http.StatusBadRequest},
|
||||
{"unbekannter autor", url.Values{"user": {"niemand"}}, http.StatusNotFound},
|
||||
} {
|
||||
if got := getStatus(t, http.DefaultClient, srv.URL+searchPath(tc.q)); got != tc.want {
|
||||
t.Errorf("%s: status %d, erwartet %d", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"kver/internal/account"
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/charts"
|
||||
"kver/internal/chat"
|
||||
"kver/internal/impression"
|
||||
"kver/internal/linkpreview"
|
||||
"kver/internal/media"
|
||||
@@ -29,6 +30,7 @@ type Deps struct {
|
||||
Previews *linkpreview.Service
|
||||
Charts *charts.Service
|
||||
Impressions *impression.Tracker // optional
|
||||
Chats *chat.Purger // optional
|
||||
// TORNet ist das interne Netz, über das TOR-Anfragen ankommen (siehe
|
||||
// blockTOR); ein ungültiges Prefix schaltet die Sperre ab.
|
||||
TORNet netip.Prefix
|
||||
@@ -94,14 +96,17 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
r.Get("/stats/charts", s.api(s.handleStatsCharts))
|
||||
|
||||
r.Get("/entry/feed/{page}", s.api(s.handleFeed))
|
||||
r.Get("/entry/search/{page}", s.api(s.handleSearch))
|
||||
r.Get("/entry/{pid}/votes", s.api(s.handleVotes))
|
||||
r.Get("/entry/{pid}/thread", s.api(s.handleThread))
|
||||
// Melden darf jeder (anonym ohne Session), gedrosselt pro IP, damit der
|
||||
// offene Endpunkt kein Spam-Kanal wird.
|
||||
r.With(s.limitByIP(10, time.Minute)).Post("/entry/{pid}/report", s.api(s.handleReport))
|
||||
|
||||
r.Get("/u/{username}/info", s.api(s.handleUserPage))
|
||||
r.Get("/u/{username}/feed/{page}", s.api(s.handleUserFeed))
|
||||
r.With(s.limitByIP(120, time.Minute)).Get("/tags/suggest", s.api(s.handleTagSuggest))
|
||||
r.Get("/u/{handle}/info", s.api(s.handleUserPage))
|
||||
r.Get("/u/{handle}/feed/{page}", s.api(s.handleUserFeed))
|
||||
r.Get("/u/{handle}/key", s.api(s.handleUserKey))
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(s.requireAuth)
|
||||
@@ -111,7 +116,8 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
r.Post("/entry/{pid}/edit", s.api(s.handleEditEntry))
|
||||
r.Post("/entry/{pid}/delete", s.api(s.handleDeleteEntry))
|
||||
r.Get("/user/info", s.api(s.handleUserInfo))
|
||||
r.Post("/user/rename", s.api(s.handleUserRename))
|
||||
r.Post("/user/handle", s.api(s.handleSetHandle))
|
||||
r.Post("/user/display_name", s.api(s.handleSetDisplayName))
|
||||
// Gedrosselt wie der Login: wer eine fremde Session hat, soll das
|
||||
// bisherige Passwort nicht durchprobieren können.
|
||||
r.With(s.limitByIP(20, time.Minute)).Post("/user/password", s.api(s.handleUserPassword))
|
||||
@@ -120,6 +126,21 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
r.Post("/user/header/remove", s.api(s.handleRemoveHeader))
|
||||
r.Post("/user/bio", s.api(s.handleSetBio))
|
||||
r.Post("/user/delete", s.api(s.handleUserDelete))
|
||||
// Schlüssel (notes/schluessel.md); die Änderungen gedrosselt.
|
||||
r.Get("/user/keys/secret", s.api(s.handleKeySecrets))
|
||||
// Direktnachrichten (notes/chats.md); Senden gedrosselt gegen Spam.
|
||||
r.With(s.limitByIP(120, time.Minute)).Get("/users/suggest", s.api(s.handleUserSuggest))
|
||||
r.Get("/notifications", s.api(s.handleNotifications))
|
||||
r.Get("/notifications/unread", s.api(s.handleNotificationsUnread))
|
||||
r.Get("/chats", s.api(s.handleChats))
|
||||
r.Get("/chats/{handle}", s.api(s.handleChat))
|
||||
r.With(s.limitByIP(60, time.Minute)).Post("/chats/{handle}", s.api(s.handleSendMessage))
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(s.limitByIP(20, time.Minute))
|
||||
r.Post("/user/key", s.api(s.handleSetKey))
|
||||
r.Post("/user/key/lost", s.api(s.handleKeyLost))
|
||||
r.Post("/user/key/passphrase", s.api(s.handleKeyPassphrase))
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -130,7 +151,8 @@ func (s *Server) apiRoutes(r chi.Router) {
|
||||
func (s *Server) pageRoutes(r chi.Router) {
|
||||
r.With(s.trackImpression).Get("/", serveApp)
|
||||
r.With(s.trackImpression).Get("/e/{pid}", serveApp)
|
||||
r.With(s.trackImpression).Get("/u/{username}", serveApp)
|
||||
r.With(s.trackImpression).Get("/u/{handle}", serveApp)
|
||||
r.Get("/chats/{handle}", serveApp)
|
||||
r.Get("/stats", serveApp)
|
||||
// Das Reset-Token steht im Fragment (#...) und erreicht den Server über
|
||||
// diese Route nie, siehe account/reset.go.
|
||||
@@ -138,7 +160,7 @@ func (s *Server) pageRoutes(r chi.Router) {
|
||||
// Navigationsziele: Profil-Weiche, Platzhalter für kommende Bereiche, die
|
||||
// Info-Seite und die Rechtstexte.
|
||||
for _, p := range []string{
|
||||
"/me", "/search", "/notifications", "/chats", "/settings",
|
||||
"/me", "/search", "/notifications", "/chats", "/settings", "/settings/keys",
|
||||
"/info", "/impressum", "/datenschutz", "/beitragsordnung",
|
||||
} {
|
||||
r.Get(p, serveApp)
|
||||
@@ -147,7 +169,8 @@ func (s *Server) pageRoutes(r chi.Router) {
|
||||
r.Get("/stats.html", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, "/stats", http.StatusMovedPermanently)
|
||||
})
|
||||
r.Handle("/assets/*", serveAssets())
|
||||
// Gebaute JS/CSS-Dateien: Namen mit Inhalts-Hash, dauerhaft cachebar.
|
||||
r.Handle("/assets/*", serveFiles(webDir, immutable))
|
||||
// Alte Adressen der Rechtstexte (bis 2026-10 statische Seiten).
|
||||
for _, name := range []string{"impressum", "datenschutz", "beitragsordnung"} {
|
||||
r.Get("/static/docs/"+name+".html", func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -155,9 +178,11 @@ func (s *Server) pageRoutes(r chi.Router) {
|
||||
})
|
||||
}
|
||||
|
||||
// Hochgeladene Medien + statische Dateien (Schriften, Bilder).
|
||||
// Hochgeladene Medien + statische Dateien (Schriften, Bilder). Uploads
|
||||
// haben zufällige, einmalige Namen (media.Store.create) und sind damit
|
||||
// dauerhaft cachebar; die Assets ändern sich praktisch nie.
|
||||
// nosniff (global via secHeaders) verhindert, dass der Browser eine
|
||||
// durchgereichte (nicht re-kodierte) Datei als HTML/JS interpretiert ->
|
||||
// schließt Polyglot/Stored-XSS über Bild-Uploads.
|
||||
r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
|
||||
r.Handle("/static/*", http.StripPrefix("/static/", serveFiles("static", immutable)))
|
||||
}
|
||||
|
||||
+34
-24
@@ -22,6 +22,9 @@ const (
|
||||
maxSessionTTL = 365 * 24 * time.Hour
|
||||
)
|
||||
|
||||
// session ist eine Sitzung aus der DB. Value ist der Hash des Cookie-Werts
|
||||
// (account.HashToken) -- so steht sie in der Tabelle, der Klartext nur im
|
||||
// Cookie.
|
||||
type session struct {
|
||||
UID int64
|
||||
CreatedAt int64
|
||||
@@ -34,8 +37,7 @@ var (
|
||||
// errBadCredentials ist für "Nutzer existiert nicht" und "Passwort falsch"
|
||||
// absichtlich derselbe Fehler -- sonst wird der Endpunkt zum
|
||||
// Nutzernamen-Orakel.
|
||||
errBadCredentials = apperr.Unauth("auth.bad_credentials", "Nutzername oder Passwort ist falsch.")
|
||||
errNameShort = apperr.Invalid("user.name_short", "Der Nutzername ist zu kurz.").At("user")
|
||||
errBadCredentials = apperr.Unauth("auth.bad_credentials", "Handle oder Passwort ist falsch.")
|
||||
errInvalidForm = apperr.Invalid("user.invalid", "Die Angaben sind unvollständig oder ungültig.")
|
||||
)
|
||||
|
||||
@@ -46,9 +48,9 @@ func (s *Server) session(r *http.Request) (session, bool) {
|
||||
if err != nil || c.Value == "" {
|
||||
return session{}, false
|
||||
}
|
||||
sess := session{Value: c.Value}
|
||||
sess := session{Value: account.HashToken(c.Value)}
|
||||
err = s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT uid, created_at, expires, description FROM session WHERE value = $1`, c.Value,
|
||||
`SELECT uid, created_at, expires, description FROM session WHERE value = $1`, sess.Value,
|
||||
).Scan(&sess.UID, &sess.CreatedAt, &sess.Expires, &sess.Description)
|
||||
if err != nil {
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
@@ -75,14 +77,15 @@ func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) error {
|
||||
writeJSON(w, http.StatusOK, status{"already_logged_in"})
|
||||
return nil
|
||||
}
|
||||
username := account.SanitizeUsername(r.FormValue("user"))
|
||||
if len(username) < account.MinNameLen {
|
||||
return errNameShort
|
||||
// Angemeldet wird mit dem Handle, Groß-/Kleinschreibung und "@" egal.
|
||||
handle := account.NormalizeHandle(r.FormValue("user"))
|
||||
if !account.ValidHandle(handle) {
|
||||
return errBadCredentials
|
||||
}
|
||||
var uid int64
|
||||
var hash []byte
|
||||
err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT uid, password FROM account WHERE username = $1`, username).Scan(&uid, &hash)
|
||||
`SELECT uid, password FROM account WHERE handle = $1`, handle).Scan(&uid, &hash)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errBadCredentials
|
||||
}
|
||||
@@ -109,8 +112,9 @@ func sessionTTL(r *http.Request) time.Duration {
|
||||
return time.Duration(min(sec, int64(maxSessionTTL/time.Second))) * time.Second
|
||||
}
|
||||
|
||||
// startSession legt eine Session an und setzt den Cookie. Nebenbei räumt es
|
||||
// abgelaufene Sessions weg und vermerkt den Login.
|
||||
// startSession legt eine Session an und setzt den Cookie; gespeichert wird
|
||||
// nur der Hash des Tokens. Nebenbei räumt es abgelaufene Sessions weg und
|
||||
// vermerkt den Login.
|
||||
func (s *Server) startSession(w http.ResponseWriter, r *http.Request, uid int64) error {
|
||||
ctx := r.Context()
|
||||
now := s.Now()
|
||||
@@ -124,7 +128,7 @@ func (s *Server) startSession(w http.ResponseWriter, r *http.Request, uid int64)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx,
|
||||
`INSERT INTO session (uid, created_at, expires, description, value) VALUES ($1, $2, $3, '', $4)`,
|
||||
uid, now.Unix(), expires.Unix(), token); err != nil {
|
||||
uid, now.Unix(), expires.Unix(), account.HashToken(token)); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE account SET last_login = $1 WHERE uid = $2`,
|
||||
@@ -177,37 +181,43 @@ func (s *Server) handleSessionInfo(w http.ResponseWriter, r *http.Request) error
|
||||
if !ok {
|
||||
return apperr.Unauth("auth.no_session", "Keine gültige Sitzung.")
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"uid": sess.UID,
|
||||
"created_at": sess.CreatedAt,
|
||||
"expires": sess.Expires,
|
||||
"description": sess.Description,
|
||||
writeJSON(w, http.StatusOK, sessionJSON{
|
||||
UID: sess.UID, CreatedAt: sess.CreatedAt, Expires: sess.Expires, Description: sess.Description,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// sessionJSON ist die Sitzung im Drahtformat (ohne den Token).
|
||||
type sessionJSON struct {
|
||||
UID int64 `json:"uid"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
Expires int64 `json:"expires"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// handleNewUser sammelt alle Validierungsfehler ein, statt beim ersten
|
||||
// abzubrechen -- der Nutzer soll nicht Feld für Feld durchprobieren müssen.
|
||||
func (s *Server) handleNewUser(w http.ResponseWriter, r *http.Request) error {
|
||||
username := account.SanitizeUsername(r.FormValue("user"))
|
||||
handle := account.NormalizeHandle(r.FormValue("handle"))
|
||||
displayName := account.CleanDisplayName(r.FormValue("display_name"))
|
||||
pass1 := r.FormValue("pass1")
|
||||
fields := map[string]string{}
|
||||
if len(username) < account.MinNameLen {
|
||||
fields["user"] = errNameShort.Msg
|
||||
} else if taken, err := s.accounts.NameTaken(r.Context(), username); err != nil {
|
||||
if !account.ValidHandle(handle) {
|
||||
fields["handle"] = account.ErrHandleInvalid.Msg
|
||||
} else if taken, err := s.accounts.HandleTaken(r.Context(), handle); err != nil {
|
||||
return apperr.Internal(err)
|
||||
} else if taken {
|
||||
fields["user"] = account.ErrUsernameTaken.Msg
|
||||
fields["handle"] = account.ErrHandleTaken.Msg
|
||||
}
|
||||
account.CheckNewPassword(pass1, r.FormValue("pass2"), fields)
|
||||
if len(fields) > 0 {
|
||||
return errInvalidForm.WithFields(fields)
|
||||
}
|
||||
// Rennen zwischen Vorab-Prüfung und INSERT: der UNIQUE-Constraint greift,
|
||||
// Create meldet dann ErrUsernameTaken.
|
||||
if _, err := s.accounts.Create(r.Context(), username, pass1); err != nil {
|
||||
// Create meldet dann ErrHandleTaken.
|
||||
if _, err := s.accounts.Create(r.Context(), handle, displayName, pass1); err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"username": username})
|
||||
writeJSON(w, http.StatusCreated, map[string]string{"handle": handle, "display_name": displayName})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"kver/internal/apperr"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxEntryTags: mehr Hashtags pro Beitrag zählen nicht für die Vorschläge.
|
||||
maxEntryTags = 20
|
||||
// maxTagRunes: längere Tags gehen nicht in die Liste (und kein Vorschlag
|
||||
// braucht sie).
|
||||
maxTagRunes = 50
|
||||
)
|
||||
|
||||
// hashtagRe findet #tag wie das Frontend (format.tsx): Buchstaben, Ziffern,
|
||||
// _, davor keines davon.
|
||||
var hashtagRe = regexp.MustCompile(`(?:^|[^\p{L}\p{N}_])#([\p{L}\p{N}_]+)`)
|
||||
|
||||
// parseTags liefert die Hashtags im Text, klein, ohne Doppelte.
|
||||
func parseTags(content string) []string {
|
||||
out := []string{}
|
||||
seen := map[string]bool{}
|
||||
for _, m := range hashtagRe.FindAllStringSubmatch(content, -1) {
|
||||
t := strings.ToLower(m[1])
|
||||
if seen[t] || utf8.RuneCountInString(t) > maxTagRunes {
|
||||
continue
|
||||
}
|
||||
seen[t] = true
|
||||
out = append(out, t)
|
||||
if len(out) == maxEntryTags {
|
||||
break
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// syncTags setzt die Hashtags des Beitrags pid auf die in content.
|
||||
func syncTags(ctx context.Context, tx *sql.Tx, pid int64, content string) error {
|
||||
if _, err := tx.ExecContext(ctx, `DELETE FROM entry_tag WHERE pid = $1`, pid); err != nil {
|
||||
return fmt.Errorf("hashtags abgleichen: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO entry_tag (pid, tag) SELECT $1, unnest($2::text[])`, pid, parseTags(content)); err != nil {
|
||||
return fmt.Errorf("hashtags speichern: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// tagSuggestionJSON ist ein Vorschlag für die Autovervollständigung von #tag.
|
||||
type tagSuggestionJSON struct {
|
||||
Tag string `json:"tag"`
|
||||
Count int64 `json:"count"`
|
||||
}
|
||||
|
||||
// handleTagSuggest schlägt Hashtags vor, die mit q beginnen ("#" optional),
|
||||
// die in den meisten Beiträgen zuerst; leeres q liefert die häufigsten
|
||||
// überhaupt. Gelöschte Beiträge zählen nicht (ihre Tags sind schon weg).
|
||||
func (s *Server) handleTagSuggest(w http.ResponseWriter, r *http.Request) error {
|
||||
q := strings.ToLower(strings.TrimPrefix(strings.TrimSpace(r.URL.Query().Get("q")), "#"))
|
||||
list := []tagSuggestionJSON{}
|
||||
if utf8.RuneCountInString(q) > maxTagRunes {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"tags": list})
|
||||
return nil
|
||||
}
|
||||
rows, err := s.DB.QueryContext(r.Context(),
|
||||
`SELECT tag, COUNT(*) FROM entry_tag WHERE tag LIKE $1
|
||||
GROUP BY tag ORDER BY COUNT(*) DESC, tag LIMIT $2`, escapeLike(q)+"%", maxSuggestions)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var t tagSuggestionJSON
|
||||
if err := rows.Scan(&t.Tag, &t.Count); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
list = append(list, t)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"tags": list})
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseTags(t *testing.T) {
|
||||
t.Parallel()
|
||||
tests := []struct {
|
||||
in string
|
||||
want []string
|
||||
}{
|
||||
{"#Leipzig und #leipzig, #München!", []string{"leipzig", "münchen"}},
|
||||
{"a#b c#d #_x", []string{"_x"}},
|
||||
{"ohne", []string{}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := parseTags(tt.in); !slices.Equal(got, tt.want) {
|
||||
t.Errorf("parseTags(%q) = %q, erwartet %q", tt.in, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func suggestTags(t *testing.T, srv *testServer, q string) []string {
|
||||
t.Helper()
|
||||
var out struct {
|
||||
Tags []tagSuggestionJSON `json:"tags"`
|
||||
}
|
||||
if code := getAny(t, srv.URL+"/api/tags/suggest?q="+url.QueryEscape(q), &out); code != http.StatusOK {
|
||||
t.Fatalf("tags/suggest %q: status %d", q, code)
|
||||
}
|
||||
var got []string
|
||||
for _, x := range out.Tags {
|
||||
got = append(got, fmt.Sprintf("%s:%d", x.Tag, x.Count))
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
func TestTagSuggest(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newTestServer(t)
|
||||
alice := registerAndLogin(t, srv, "alice")
|
||||
createEntry(t, alice, srv, post("#Leipzig #lecker"))
|
||||
createEntry(t, alice, srv, post("wieder #leipzig"))
|
||||
gone := createEntry(t, alice, srv, post("#lecker #ludwig"))
|
||||
edited := createEntry(t, alice, srv, post("#halle"))
|
||||
|
||||
resp := postForm(t, alice, fmt.Sprintf("%s/api/entry/%d/delete", srv.URL, gone), nil)
|
||||
resp.Body.Close()
|
||||
resp = postForm(t, alice, fmt.Sprintf("%s/api/entry/%d/edit", srv.URL, edited), url.Values{"content": {"#leipzig"}})
|
||||
resp.Body.Close()
|
||||
|
||||
for _, tt := range []struct {
|
||||
q string
|
||||
want []string
|
||||
}{
|
||||
{"#Le", []string{"leipzig:3", "lecker:1"}},
|
||||
{"", []string{"leipzig:3", "lecker:1"}},
|
||||
{"h", nil},
|
||||
{"l_", nil}, // _ ist kein LIKE-Platzhalter
|
||||
} {
|
||||
if got := suggestTags(t, srv, tt.q); !slices.Equal(got, tt.want) {
|
||||
t.Errorf("suggest(%q) = %v, erwartet %v", tt.q, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
-129
@@ -6,103 +6,51 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"kver/internal/account"
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/database"
|
||||
"kver/internal/runes"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// notFoundOr bildet sql.ErrNoRows auf account.ErrUserNotFound ab, alles
|
||||
// andere auf einen internen Fehler.
|
||||
func notFoundOr(err error) error {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return account.ErrUserNotFound
|
||||
}
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
|
||||
// maxBioRunes begrenzt die Profilbeschreibung.
|
||||
const maxBioRunes = 300
|
||||
// Die Kontozugriffe liegen in account.Store; hier wird nur gelesen, was im
|
||||
// Request steht, und geantwortet.
|
||||
|
||||
func (s *Server) handleUserPage(w http.ResponseWriter, r *http.Request) error {
|
||||
username := chi.URLParam(r, "username")
|
||||
var uid, createdAt, entries int64
|
||||
var avatar, header, bio string
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT uid, created_at, avatar, header, bio,
|
||||
(SELECT COUNT(*) FROM entry e WHERE e.uid = a.uid AND e.deleted = 0)
|
||||
FROM account a WHERE username = $1`, username,
|
||||
).Scan(&uid, &createdAt, &avatar, &header, &bio, &entries); err != nil {
|
||||
return notFoundOr(err)
|
||||
p, err := s.accounts.Profile(r.Context(), chi.URLParam(r, "handle"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"uid": uid,
|
||||
"username": username,
|
||||
"created_at": createdAt,
|
||||
"avatar": avatar,
|
||||
"header": header,
|
||||
"bio": bio,
|
||||
"entries": entries,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleUserInfo(w http.ResponseWriter, r *http.Request) error {
|
||||
uid := currentUID(r)
|
||||
var createdAt, lastLogin sql.NullInt64
|
||||
var username, avatar string
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT created_at, last_login, username, avatar FROM account WHERE uid = $1`, uid,
|
||||
).Scan(&createdAt, &lastLogin, &username, &avatar); err != nil {
|
||||
return notFoundOr(err)
|
||||
info, err := s.accounts.Info(r.Context(), currentUID(r))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"uid": uid,
|
||||
"username": username,
|
||||
"created_at": createdAt.Int64,
|
||||
"last_login": lastLogin.Int64,
|
||||
"avatar": avatar,
|
||||
})
|
||||
writeJSON(w, http.StatusOK, info)
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleUserRename benennt den eingeloggten Account um. Nichts außer der
|
||||
// account-Zeile referenziert den username (alles hängt an der uid), daher
|
||||
// genügt ein UPDATE.
|
||||
func (s *Server) handleUserRename(w http.ResponseWriter, r *http.Request) error {
|
||||
uid := currentUID(r)
|
||||
name := account.SanitizeUsername(r.FormValue("user"))
|
||||
if len(name) < account.MinNameLen {
|
||||
return errNameShort
|
||||
func (s *Server) handleSetHandle(w http.ResponseWriter, r *http.Request) error {
|
||||
handle, err := s.accounts.SetHandle(r.Context(), currentUID(r), r.FormValue("handle"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var current string
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT username FROM account WHERE uid = $1`, uid).Scan(¤t); err != nil {
|
||||
return notFoundOr(err)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"handle": handle})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) handleSetDisplayName(w http.ResponseWriter, r *http.Request) error {
|
||||
name, err := s.accounts.SetDisplayName(r.Context(), currentUID(r), r.FormValue("display_name"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if name == current {
|
||||
return apperr.Invalid("user.name_unchanged", "Das ist bereits dein Name.").At("user")
|
||||
}
|
||||
if taken, err := s.accounts.NameTaken(r.Context(), name); err != nil {
|
||||
return apperr.Internal(err)
|
||||
} else if taken {
|
||||
return account.ErrUsernameTaken
|
||||
}
|
||||
if _, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE account SET username = $1 WHERE uid = $2`, name, uid); err != nil {
|
||||
// Rennen zwischen Vorab-Prüfung und UPDATE: UNIQUE-Constraint -> 409.
|
||||
if database.IsUniqueViolation(err, "account_username_key") {
|
||||
return account.ErrUsernameTaken
|
||||
}
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"username": name})
|
||||
writeJSON(w, http.StatusOK, map[string]string{"display_name": name})
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -116,65 +64,62 @@ func (s *Server) handleUserPassword(w http.ResponseWriter, r *http.Request) erro
|
||||
if len(fields) > 0 {
|
||||
return errInvalidForm.WithFields(fields)
|
||||
}
|
||||
sess, _ := s.session(r)
|
||||
if err := s.accounts.ChangePassword(r.Context(), currentUID(r), r.FormValue("pass"), pass1, sess.Value); err != nil {
|
||||
return err
|
||||
sess := currentSession(r)
|
||||
if err := s.accounts.ChangePassword(r.Context(), sess.UID, r.FormValue("pass"), pass1, sess.Value); err != nil {
|
||||
return wrongPasswordAt(err, "pass")
|
||||
}
|
||||
writeJSON(w, http.StatusOK, status{"ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handleSetBio setzt die Profilbeschreibung des eingeloggten Nutzers; leer
|
||||
// löscht sie. Klartext, Links macht erst das Frontend klickbar.
|
||||
// wrongPasswordAt hängt an ein falsches Passwort das Formularfeld, in dem es
|
||||
// stand; andere Fehler gehen unverändert durch.
|
||||
func wrongPasswordAt(err error, field string) error {
|
||||
if errors.Is(err, account.ErrWrongPassword) {
|
||||
return account.ErrWrongPassword.At(field)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Server) handleSetBio(w http.ResponseWriter, r *http.Request) error {
|
||||
bio := strings.ReplaceAll(r.FormValue("bio"), "\r\n", "\n")
|
||||
bio = runes.Truncate(strings.TrimSpace(bio), maxBioRunes)
|
||||
if _, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE account SET bio = $1 WHERE uid = $2`, bio, currentUID(r)); err != nil {
|
||||
return apperr.Internal(err)
|
||||
bio, err := s.accounts.SetBio(r.Context(), currentUID(r), r.FormValue("bio"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"bio": bio})
|
||||
return nil
|
||||
}
|
||||
|
||||
// Profilbilder: Spalte in account, zugleich Name des Formularfelds. Die
|
||||
// Abfragen stehen fest im Code, damit kein Spaltenname in SQL zusammengesetzt
|
||||
// wird. Der Self-Join liefert das bisherige Bild (prev sieht die Zeile vor dem
|
||||
// UPDATE), ohne eigene Abfrage davor.
|
||||
var setImageQuery = map[string]string{
|
||||
"avatar": `UPDATE account a SET avatar = $1 FROM account prev
|
||||
WHERE a.uid = $2 AND prev.uid = a.uid RETURNING prev.avatar`,
|
||||
"header": `UPDATE account a SET header = $1 FROM account prev
|
||||
WHERE a.uid = $2 AND prev.uid = a.uid RETURNING prev.header`,
|
||||
}
|
||||
|
||||
// handleSetAvatar speichert ein hochgeladenes Profilbild des eingeloggten
|
||||
// Nutzers und ersetzt ein eventuell vorhandenes.
|
||||
func (s *Server) handleSetAvatar(w http.ResponseWriter, r *http.Request) error {
|
||||
return s.setImage(w, r, "avatar")
|
||||
return s.setImage(w, r, account.Avatar)
|
||||
}
|
||||
|
||||
// handleSetHeader speichert das Header-Bild des Profils.
|
||||
func (s *Server) handleSetHeader(w http.ResponseWriter, r *http.Request) error {
|
||||
return s.setImage(w, r, "header")
|
||||
return s.setImage(w, r, account.Header)
|
||||
}
|
||||
|
||||
// handleRemoveHeader entfernt das Header-Bild; das Profil zeigt dann den
|
||||
// schwarzen Balken.
|
||||
func (s *Server) handleRemoveHeader(w http.ResponseWriter, r *http.Request) error {
|
||||
old, err := s.replaceImage(r.Context(), "header", "", currentUID(r))
|
||||
old, err := s.accounts.SetImage(r.Context(), currentUID(r), account.Header, "")
|
||||
if err != nil {
|
||||
return notFoundOr(err)
|
||||
return err
|
||||
}
|
||||
s.removeMedia(old)
|
||||
writeJSON(w, http.StatusOK, map[string]string{"header": ""})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) setImage(w http.ResponseWriter, r *http.Request, field string) error {
|
||||
// setImage liest das Bild aus dem gleichnamigen Formularfeld, speichert es
|
||||
// und ersetzt das bisherige.
|
||||
func (s *Server) setImage(w http.ResponseWriter, r *http.Request, img account.Image) error {
|
||||
if err := parseUpload(w, r); err != nil {
|
||||
return err
|
||||
}
|
||||
field := string(img)
|
||||
fh := formFile(r, field)
|
||||
if fh == nil {
|
||||
return apperr.Invalid(field+".missing", "Kein Bild hochgeladen.").At(field)
|
||||
@@ -183,10 +128,10 @@ func (s *Server) setImage(w http.ResponseWriter, r *http.Request, field string)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
old, err := s.replaceImage(r.Context(), field, stored, currentUID(r))
|
||||
old, err := s.accounts.SetImage(r.Context(), currentUID(r), img, stored)
|
||||
if err != nil {
|
||||
s.removeMedia(stored)
|
||||
return notFoundOr(err)
|
||||
return err
|
||||
}
|
||||
if old != stored {
|
||||
s.removeMedia(old)
|
||||
@@ -195,13 +140,6 @@ func (s *Server) setImage(w http.ResponseWriter, r *http.Request, field string)
|
||||
return nil
|
||||
}
|
||||
|
||||
// replaceImage setzt die Bildspalte field und liefert den bisherigen Pfad.
|
||||
func (s *Server) replaceImage(ctx context.Context, field, path string, uid int64) (string, error) {
|
||||
var old string
|
||||
err := s.DB.QueryRowContext(ctx, setImageQuery[field], path, uid).Scan(&old)
|
||||
return old, err
|
||||
}
|
||||
|
||||
// handleUserDelete löscht den eingeloggten Account dauerhaft, nach
|
||||
// Bestätigung durch das Passwort (Formularfeld pass1). Sessions, Reset-Links
|
||||
// und Votes werden in einer Transaktion mitgelöscht; die eigenen Beiträge
|
||||
@@ -209,13 +147,8 @@ func (s *Server) replaceImage(ctx context.Context, field, path string, uid int64
|
||||
// Antworten nicht verwaisen. Mediendateien werden danach best effort entfernt.
|
||||
func (s *Server) handleUserDelete(w http.ResponseWriter, r *http.Request) error {
|
||||
ctx, uid := r.Context(), currentUID(r)
|
||||
var hash []byte
|
||||
if err := s.DB.QueryRowContext(ctx,
|
||||
`SELECT password FROM account WHERE uid = $1`, uid).Scan(&hash); err != nil {
|
||||
return notFoundOr(err)
|
||||
}
|
||||
if bcrypt.CompareHashAndPassword(hash, []byte(r.FormValue("pass1"))) != nil {
|
||||
return apperr.Forbidden("auth.bad_password", "Passwort ist falsch.").At("pass1")
|
||||
if err := s.accounts.VerifyPassword(ctx, uid, r.FormValue("pass1")); err != nil {
|
||||
return wrongPasswordAt(err, "pass1")
|
||||
}
|
||||
// Mediendateien einsammeln, bevor die Pfade geleert werden.
|
||||
files, err := s.userMedia(ctx, uid)
|
||||
@@ -223,7 +156,10 @@ func (s *Server) handleUserDelete(w http.ResponseWriter, r *http.Request) error
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
if err := database.InTx(ctx, s.DB, func(tx *sql.Tx) error {
|
||||
return deleteAccount(ctx, tx, uid)
|
||||
if err := deleteUserContent(ctx, tx, uid); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.accounts.Delete(ctx, tx, uid)
|
||||
}); err != nil {
|
||||
return apperr.Internal(err)
|
||||
}
|
||||
@@ -235,11 +171,13 @@ func (s *Server) handleUserDelete(w http.ResponseWriter, r *http.Request) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// userMedia liefert die Mediendateien eines Nutzers: Beitragsbilder, Profil-
|
||||
// und Header-Bild.
|
||||
// userMedia liefert die Mediendateien eines Nutzers: Beitragsbilder samt
|
||||
// verpixelter Varianten, Profil- und Header-Bild.
|
||||
func (s *Server) userMedia(ctx context.Context, uid int64) ([]string, error) {
|
||||
rows, err := s.DB.QueryContext(ctx,
|
||||
`SELECT filepath FROM entry WHERE uid = $1 AND filepath <> ''
|
||||
UNION ALL
|
||||
SELECT image_cover FROM entry WHERE uid = $1 AND image_cover <> ''
|
||||
UNION ALL
|
||||
SELECT avatar FROM account WHERE uid = $1 AND avatar <> ''
|
||||
UNION ALL
|
||||
@@ -259,17 +197,19 @@ func (s *Server) userMedia(ctx context.Context, uid int64) ([]string, error) {
|
||||
return files, rows.Err()
|
||||
}
|
||||
|
||||
func deleteAccount(ctx context.Context, tx *sql.Tx, uid int64) error {
|
||||
// deleteUserContent räumt ab, was von uid im Forum steht: Votes,
|
||||
// Benachrichtigungen an und von ihm, Erwähnungen seiner Person; die Beiträge
|
||||
// werden weich gelöscht (softDeleteEntries nimmt deren Erwähnungen, Tags und
|
||||
// Benachrichtigungen mit).
|
||||
func deleteUserContent(ctx context.Context, tx *sql.Tx, uid int64) error {
|
||||
for _, q := range []string{
|
||||
`DELETE FROM session WHERE uid = $1`,
|
||||
`DELETE FROM password_reset WHERE uid = $1`,
|
||||
`DELETE FROM vote 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 notification WHERE uid = $1 OR actor = $1`,
|
||||
`DELETE FROM mention WHERE uid = $1`,
|
||||
} {
|
||||
if _, err := tx.ExecContext(ctx, q, uid); err != nil {
|
||||
return fmt.Errorf("account löschen: %w", err)
|
||||
return fmt.Errorf("beiträge löschen: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return softDeleteEntries(ctx, tx, "uid = $1", uid)
|
||||
}
|
||||
|
||||
+61
-42
@@ -2,11 +2,14 @@ package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"kver/internal/apperr"
|
||||
"kver/internal/database"
|
||||
)
|
||||
|
||||
// tally ist der Abstimmungsstand eines Beitrags; selected ist die eigene
|
||||
@@ -72,10 +75,15 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) error {
|
||||
if mode != "yes" && mode != "no" {
|
||||
return apperr.Invalid("vote.bad_mode", "Ungültiger Modus (yes oder no)").At("mode")
|
||||
}
|
||||
// Nur auf existierende Beiträge abstimmen, sonst entstehen Waisen-Votes.
|
||||
if _, err := s.entryByPID(r.Context(), pid); err != nil {
|
||||
// Nur auf bestehende, nicht gelöschte Beiträge abstimmen, sonst entstehen
|
||||
// Waisen-Votes.
|
||||
e, err := s.entryByPID(r.Context(), pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Deleted != 0 {
|
||||
return errEntryNotFound
|
||||
}
|
||||
uid := currentUID(r)
|
||||
res, err := s.DB.ExecContext(r.Context(),
|
||||
`DELETE FROM vote WHERE uid = $1 AND pid = $2 AND mode = $3`, uid, pid, mode)
|
||||
@@ -98,6 +106,20 @@ func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) error {
|
||||
// jedem Mal teurer.
|
||||
const bumpStep = int64(24 * time.Hour / time.Second)
|
||||
|
||||
// errBumpCooldown trägt neben dem Fehler retry_after und bump_count, mit
|
||||
// denen das Frontend den Knopf sperrt (WithExtra), und den Header Retry-After.
|
||||
var errBumpCooldown = apperr.RateLimited("entry.bump_cooldown", "Dieser Beitrag wurde erst kürzlich repostet.")
|
||||
|
||||
// bumpJSON ist die Antwort auf einen erfolgreichen Repost.
|
||||
type bumpJSON struct {
|
||||
PID int64 `json:"pid"`
|
||||
BumpCount int64 `json:"bump_count"`
|
||||
LastBump int64 `json:"last_bump"`
|
||||
LastActivity int64 `json:"last_activity"`
|
||||
// RetryAfter: Sekunden bis zum nächsten erlaubten Repost.
|
||||
RetryAfter int64 `json:"retry_after"`
|
||||
}
|
||||
|
||||
// handleBump hebt last_activity eines Beitrags auf jetzt -> er steigt im Feed
|
||||
// bzw. in der Antwortliste eines Threads wieder nach oben. Gegen Spam wächst
|
||||
// der Cooldown linear mit der Zahl bisheriger Bumps; er sitzt am Beitrag
|
||||
@@ -107,48 +129,45 @@ func (s *Server) handleBump(w http.ResponseWriter, r *http.Request) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Beim ersten Bump (bump_count 0) ist die Sperre 0 -> sofort erlaubt. Die
|
||||
// Bedingung sitzt direkt im UPDATE (statt Read-then-Write), damit zwei
|
||||
// gleichzeitige Bumps den Cooldown nicht umgehen können.
|
||||
// Ein Statement liest den Stand und bumpt, wenn der Cooldown vorbei ist
|
||||
// (beim ersten Bump, bump_count 0, ist er 0 -> sofort erlaubt). Die
|
||||
// Bedingung sitzt im UPDATE selbst statt in einem Read-then-Write, damit
|
||||
// zwei gleichzeitige Bumps den Cooldown nicht umgehen können; cur liefert
|
||||
// den Stand davor, auch wenn nicht gebumpt wurde (für die Restzeit).
|
||||
now := s.Now().Unix()
|
||||
res, err := s.DB.ExecContext(r.Context(),
|
||||
`UPDATE entry SET last_activity = $1, bump_count = bump_count + 1, last_bump = $1
|
||||
WHERE pid = $2 AND deleted = 0 AND last_bump + bump_count * $3 <= $1`,
|
||||
now, pid, bumpStep)
|
||||
if err != nil {
|
||||
return apperr.Internal(err)
|
||||
var bumpCount, lastBump int64
|
||||
var bumped bool
|
||||
if err := database.InTx(r.Context(), s.DB, func(tx *sql.Tx) error {
|
||||
err := tx.QueryRowContext(r.Context(),
|
||||
`WITH cur AS (SELECT pid, bump_count, last_bump FROM entry WHERE pid = $2 AND deleted = 0),
|
||||
upd AS (UPDATE entry e SET last_activity = $1, bump_count = e.bump_count + 1, last_bump = $1
|
||||
FROM cur WHERE e.pid = cur.pid AND cur.last_bump + cur.bump_count * $3 <= $1
|
||||
RETURNING e.pid)
|
||||
SELECT cur.bump_count, cur.last_bump, EXISTS (SELECT 1 FROM upd) FROM cur`,
|
||||
now, pid, bumpStep).Scan(&bumpCount, &lastBump, &bumped)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errEntryNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("bump: %w", err)
|
||||
}
|
||||
if !bumped {
|
||||
return nil
|
||||
}
|
||||
bumpCount++
|
||||
return notifyBump(r.Context(), tx, pid, currentUID(r), now)
|
||||
}); err != nil {
|
||||
return err // errEntryNotFound oder (über writeError) ein interner Fehler
|
||||
}
|
||||
var bumpCount, lastBump, deleted int64
|
||||
if err := s.DB.QueryRowContext(r.Context(),
|
||||
`SELECT bump_count, last_bump, deleted FROM entry WHERE pid = $1`, pid).
|
||||
Scan(&bumpCount, &lastBump, &deleted); err != nil || deleted != 0 {
|
||||
return errEntryNotFound
|
||||
if !bumped {
|
||||
remaining := max(lastBump+bumpCount*bumpStep-now, 0)
|
||||
return errBumpCooldown.
|
||||
WithRetryAfter(time.Duration(remaining) * time.Second).
|
||||
WithExtra(map[string]any{"retry_after": remaining, "bump_count": bumpCount})
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
writeBumpCooldown(w, max(lastBump+bumpCount*bumpStep-now, 0), bumpCount)
|
||||
return nil
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"pid": pid,
|
||||
"bump_count": bumpCount,
|
||||
"last_bump": now,
|
||||
"last_activity": now,
|
||||
"retry_after": bumpCount * bumpStep, // bis zum nächsten erlaubten Bump
|
||||
writeJSON(w, http.StatusOK, bumpJSON{
|
||||
PID: pid, BumpCount: bumpCount, LastBump: now, LastActivity: now,
|
||||
RetryAfter: bumpCount * bumpStep,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// writeBumpCooldown ist kein Taxonomie-Fehler: die Antwort trägt neben dem
|
||||
// Fehler Nutzdaten (retry_after, bump_count), mit denen das Frontend den
|
||||
// Button sperrt.
|
||||
func writeBumpCooldown(w http.ResponseWriter, remaining, bumpCount int64) {
|
||||
w.Header().Set("Retry-After", strconv.FormatInt(remaining, 10))
|
||||
writeJSON(w, http.StatusTooManyRequests, map[string]any{
|
||||
"error": errorBody{
|
||||
Code: "entry.bump_cooldown",
|
||||
Message: "Dieser Beitrag wurde erst kürzlich repostet.",
|
||||
},
|
||||
"retry_after": remaining,
|
||||
"bump_count": bumpCount,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package media
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
xdraw "golang.org/x/image/draw"
|
||||
)
|
||||
|
||||
const (
|
||||
coverBlocks = 12 // Pixelblöcke an der langen Kante
|
||||
coverSize = 480 // Zielkante der verpixelten Variante
|
||||
)
|
||||
|
||||
// SaveCover legt neben dem Bild src (relativer Pfad unter Dir) eine stark
|
||||
// verpixelte JPEG-Variante an und liefert deren Pfad. Sie wird statt des
|
||||
// Bilds gezeigt, solange ein Hinweis davor steht. Animierte GIFs werden zum
|
||||
// ersten Frame.
|
||||
func (s Store) SaveCover(src string) (string, error) {
|
||||
data, err := os.ReadFile(s.abs(src))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("bild lesen: %w", err)
|
||||
}
|
||||
img, err := decodeChecked(data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// Erst auf wenige Pixel herunter (CatmullRom mittelt dabei über die
|
||||
// ganze Fläche), dann blockig wieder hoch.
|
||||
small := scale(img, coverBlocks, image.White)
|
||||
b := img.Bounds()
|
||||
w, h := fit(b.Dx(), b.Dy(), coverSize)
|
||||
dst := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
xdraw.NearestNeighbor.Scale(dst, dst.Bounds(), small, small.Bounds(), xdraw.Src, nil)
|
||||
return s.create(path.Dir(src), "cover-*.jpg", encodeJPEG(dst, 80))
|
||||
}
|
||||
@@ -19,8 +19,13 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
xdraw "golang.org/x/image/draw"
|
||||
_ "golang.org/x/image/webp" // WebP-Decoder für image.Decode
|
||||
)
|
||||
|
||||
// Angenommen werden JPEG, PNG, GIF und WebP; die Decoder registrieren sich
|
||||
// über die Importe oben bei image.Decode. Gespeichert wird nie im
|
||||
// Eingangsformat (außer animierte GIFs, siehe SaveUpload), WebP also als JPEG.
|
||||
|
||||
const (
|
||||
// Dir ist das Medienverzeichnis relativ zu Root.
|
||||
Dir = "static/media"
|
||||
@@ -121,11 +126,6 @@ func (s Store) create(dir, pattern string, write func(io.Writer) error) (string,
|
||||
return dir + "/" + filepath.Base(name), nil
|
||||
}
|
||||
|
||||
// isWebP erkennt den RIFF/WEBP-Header.
|
||||
func isWebP(data []byte) bool {
|
||||
return len(data) >= 12 && string(data[:4]) == "RIFF" && string(data[8:12]) == "WEBP"
|
||||
}
|
||||
|
||||
var errGIFTooLarge = errors.New("animiertes GIF zu groß")
|
||||
|
||||
// gifFrames prüft ein GIF gegen Frame- und Pixelbudget und meldet, ob es
|
||||
|
||||
@@ -112,3 +112,35 @@ func TestSaveUploadRejectsBomb(t *testing.T) {
|
||||
t.Error("Text wurde als Bild angenommen")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveCover(t *testing.T) {
|
||||
t.Parallel()
|
||||
root := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(root, Dir), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := Dir + "/bild.png"
|
||||
if err := os.WriteFile(filepath.Join(root, src), pngBytes(t, 1200, 600), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := Store{Root: root}
|
||||
cover, err := s.SaveCover(src)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(cover, Dir+"/cover-") || !strings.HasSuffix(cover, ".jpg") {
|
||||
t.Errorf("pfad %q", cover)
|
||||
}
|
||||
f, err := os.Open(filepath.Join(root, cover))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
cfg, format, err := image.DecodeConfig(f)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if format != "jpeg" || cfg.Width != coverSize || cfg.Height != coverSize/2 {
|
||||
t.Errorf("cover %s %dx%d", format, cfg.Width, cfg.Height)
|
||||
}
|
||||
}
|
||||
|
||||
+4
-19
@@ -4,11 +4,8 @@ import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"os"
|
||||
"path"
|
||||
|
||||
"golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
// ThumbSize ist die Zielkante eines Vorschaubilds (klein, steht neben dem Text).
|
||||
@@ -37,29 +34,17 @@ func (s Store) SaveThumb(data []byte, dest string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeChecked dekodiert data nach der Größenprüfung. WebP wird gezielt
|
||||
// dekodiert statt global registriert -- sonst nähme auch SaveUpload WebP an.
|
||||
// decodeChecked dekodiert data nach der Größenprüfung (alle in media.go
|
||||
// registrierten Formate).
|
||||
func decodeChecked(data []byte) (image.Image, error) {
|
||||
decodeConfig := image.DecodeConfig
|
||||
decode := func(r *bytes.Reader) (image.Image, error) {
|
||||
img, _, err := image.Decode(r)
|
||||
return img, err
|
||||
}
|
||||
if isWebP(data) {
|
||||
decodeConfig = func(r io.Reader) (image.Config, string, error) {
|
||||
c, err := webp.DecodeConfig(r)
|
||||
return c, "webp", err
|
||||
}
|
||||
decode = func(r *bytes.Reader) (image.Image, error) { return webp.Decode(r) }
|
||||
}
|
||||
cfg, _, err := decodeConfig(bytes.NewReader(data))
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bildformat: %w", err)
|
||||
}
|
||||
if err := checkSize(cfg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
img, err := decode(bytes.NewReader(data))
|
||||
img, _, err := image.Decode(bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bild dekodieren: %w", err)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
// SaveUpload speichert ein hochgeladenes Bild und liefert seinen Pfad.
|
||||
//
|
||||
// Standbilder (JPEG/PNG/Einzelbild-GIF) werden auf maxImageSize skaliert und
|
||||
// Standbilder (JPEG/PNG/WebP/Einzelbild-GIF) werden auf maxImageSize skaliert und
|
||||
// dabei durch Decode+Re-Encode sanitisiert. Animierte GIFs würden durch das
|
||||
// Re-Encode auf das erste Frame reduziert -> sie werden stattdessen unverändert
|
||||
// durchgereicht. Die Bytes sind dann NICHT sanitisiert; deshalb liefert der
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
// Package pgpkey prüft hochgeladene OpenPGP-Schlüssel (v6, RFC 9580)
|
||||
// oberflächlich, ohne Krypto. Öffentliche Zertifikate: Paketstruktur lesbar,
|
||||
// erstes Paket ein v6-Ed25519-Hauptschlüssel, kein privates
|
||||
// Schlüsselmaterial; daraus ergibt sich der Fingerprint. Private Schlüssel:
|
||||
// derselbe Fingerprint und alles geheime Material mit Argon2 und AEAD
|
||||
// verschlüsselt (CheckSecret). Signaturen prüft erst der Client mit
|
||||
// OpenPGP.js (notes/schluessel.md).
|
||||
package pgpkey
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// MaxSize begrenzt ein Zertifikat. Ein v6-Schlüssel mit Unterschlüssel,
|
||||
// privat oder öffentlich, bleibt weit darunter (rund 1 KiB).
|
||||
const MaxSize = 16 << 10
|
||||
|
||||
const (
|
||||
tagPKESK = 1
|
||||
tagSecretKey = 5
|
||||
tagPublicKey = 6
|
||||
tagSecretSubkey = 7
|
||||
|
||||
algoEd25519 = 27
|
||||
|
||||
usageAEAD = 253 // S2K-Usage: Schlüsselmaterial per AEAD geschützt
|
||||
s2kArgon2 = 4
|
||||
argon2MinMem = 16 // Speicher-Exponent: 2^16 KiB = 64 MiB, wie OpenPGP.js
|
||||
)
|
||||
|
||||
var (
|
||||
ErrTooLarge = errors.New("zertifikat zu groß")
|
||||
ErrMalformed = errors.New("keine lesbaren OpenPGP-Pakete")
|
||||
ErrNotPublic = errors.New("kein öffentlicher Schlüssel am Anfang")
|
||||
ErrSecret = errors.New("enthält privaten Schlüssel")
|
||||
ErrVersion = errors.New("kein v6-Schlüssel")
|
||||
ErrAlgorithm = errors.New("hauptschlüssel ist nicht Ed25519")
|
||||
|
||||
ErrNotSecret = errors.New("kein privater schlüssel am anfang")
|
||||
ErrUnprotected = errors.New("privater schlüssel nicht mit argon2 und aead geschützt")
|
||||
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
|
||||
// (SHA-256 über das erste Paket, RFC 9580 Abschnitt 5.5.4.3).
|
||||
func Fingerprint(cert []byte) ([32]byte, error) {
|
||||
if len(cert) > MaxSize {
|
||||
return [32]byte{}, ErrTooLarge
|
||||
}
|
||||
var primary []byte
|
||||
for rest := cert; len(rest) > 0; {
|
||||
tag, body, next, err := nextPacket(rest)
|
||||
if err != nil {
|
||||
return [32]byte{}, err
|
||||
}
|
||||
if tag == tagSecretKey || tag == tagSecretSubkey {
|
||||
return [32]byte{}, ErrSecret
|
||||
}
|
||||
if primary == nil {
|
||||
if tag != tagPublicKey {
|
||||
return [32]byte{}, ErrNotPublic
|
||||
}
|
||||
primary = body
|
||||
}
|
||||
rest = next
|
||||
}
|
||||
if primary == nil {
|
||||
return [32]byte{}, ErrMalformed
|
||||
}
|
||||
// Version (1), Erstellzeit (4), Algorithmus (1), ...
|
||||
if len(primary) < 6 || primary[0] != 6 {
|
||||
return [32]byte{}, ErrVersion
|
||||
}
|
||||
if primary[5] != algoEd25519 {
|
||||
return [32]byte{}, ErrAlgorithm
|
||||
}
|
||||
return v6Fingerprint(primary), nil
|
||||
}
|
||||
|
||||
// v6Fingerprint hasht den öffentlichen Teil eines v6-Schlüsselpakets.
|
||||
func v6Fingerprint(pub []byte) [32]byte {
|
||||
h := sha256.New()
|
||||
var hdr [5]byte
|
||||
hdr[0] = 0x9B
|
||||
binary.BigEndian.PutUint32(hdr[1:], uint32(len(pub)))
|
||||
h.Write(hdr[:])
|
||||
h.Write(pub)
|
||||
var fp [32]byte
|
||||
h.Sum(fp[:0])
|
||||
return fp
|
||||
}
|
||||
|
||||
// CheckSecret prüft einen privaten Schlüssel (binär, wie OpenPGP.js ihn
|
||||
// schreibt), bevor der Server ihn aufbewahrt: Er gehört zum Zertifikat mit
|
||||
// Fingerprint fp, und jedes geheime Schlüsselpaket ist mit einer Passphrase
|
||||
// per Argon2 (mindestens 64 MiB) und AEAD verschlüsselt. Ob die Passphrase
|
||||
// stark ist, sieht der Server nicht; die erzeugt der Client.
|
||||
func CheckSecret(secret []byte, fp [32]byte) error {
|
||||
if len(secret) > MaxSize {
|
||||
return ErrTooLarge
|
||||
}
|
||||
first := true
|
||||
for rest := secret; len(rest) > 0; {
|
||||
tag, body, next, err := nextPacket(rest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rest = next
|
||||
if first && tag != tagSecretKey {
|
||||
return ErrNotSecret
|
||||
}
|
||||
if tag != tagSecretKey && tag != tagSecretSubkey {
|
||||
first = false
|
||||
continue
|
||||
}
|
||||
pub, err := splitSecret(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if first && v6Fingerprint(pub) != fp {
|
||||
return ErrMismatch
|
||||
}
|
||||
first = false
|
||||
}
|
||||
if first {
|
||||
return ErrMalformed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// splitSecret trennt ein v6-Paket mit geheimem Schlüssel in den öffentlichen
|
||||
// Teil und prüft den Schutz des geheimen (RFC 9580 Abschnitt 5.5.3):
|
||||
// Version (1), Erstellzeit (4), Algorithmus (1), Länge des öffentlichen
|
||||
// Materials (4), Material; dann S2K-Usage 253, Anzahl der Felder (1),
|
||||
// Chiffre (1), AEAD-Verfahren (1), Länge des S2K-Bezeichners (1) und der
|
||||
// Bezeichner selbst: Typ 4 (Argon2), Salz (16), t, p, Speicher-Exponent.
|
||||
func splitSecret(body []byte) ([]byte, error) {
|
||||
if len(body) < 10 || body[0] != 6 {
|
||||
return nil, ErrVersion
|
||||
}
|
||||
n := 10 + int(binary.BigEndian.Uint32(body[6:10]))
|
||||
if n < 10 || n > len(body) {
|
||||
return nil, ErrMalformed
|
||||
}
|
||||
s := body[n:]
|
||||
if len(s) < 5+20 || s[0] != usageAEAD || s[4] != 20 || s[5] != s2kArgon2 || s[5+19] < argon2MinMem {
|
||||
return nil, ErrUnprotected
|
||||
}
|
||||
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
|
||||
// Header-Format; Teil-Längen und unbestimmte Längen kommen in Zertifikaten
|
||||
// nicht vor und gelten als ungültig.
|
||||
func nextPacket(b []byte) (tag byte, body, rest []byte, err error) {
|
||||
if len(b) < 2 || b[0]&0x80 == 0 {
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
var n, hdr int
|
||||
if b[0]&0x40 != 0 { // neues Format
|
||||
tag = b[0] & 0x3F
|
||||
switch o := int(b[1]); {
|
||||
case o < 192:
|
||||
n, hdr = o, 2
|
||||
case o < 224:
|
||||
if len(b) < 3 {
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
n, hdr = (o-192)<<8+int(b[2])+192, 3
|
||||
case o == 255:
|
||||
if len(b) < 6 {
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
n, hdr = int(binary.BigEndian.Uint32(b[2:6])), 6
|
||||
default:
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
} else { // altes Format
|
||||
tag = (b[0] >> 2) & 0x0F
|
||||
switch b[0] & 3 {
|
||||
case 0:
|
||||
n, hdr = int(b[1]), 2
|
||||
case 1:
|
||||
if len(b) < 3 {
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
n, hdr = int(binary.BigEndian.Uint16(b[1:3])), 3
|
||||
case 2:
|
||||
if len(b) < 5 {
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
n, hdr = int(binary.BigEndian.Uint32(b[1:5])), 5
|
||||
default:
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
}
|
||||
if n < 0 || n > len(b)-hdr {
|
||||
return 0, nil, nil, ErrMalformed
|
||||
}
|
||||
return tag, b[hdr : hdr+n], b[hdr+n:], nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package pgpkey
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 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
|
||||
// privaten Schlüssel dazu mit Argon2 und AEAD, v6-secret ist ungeschützt,
|
||||
// v6-iter mit dem älteren S2K-Verfahren, v6-msg eine signierte Nachricht
|
||||
// von v6 an v6-2; die .fpr-Dateien enthalten den Fingerprint, wie
|
||||
// OpenPGP.js ihn berechnet.
|
||||
func read(t *testing.T, name string) []byte {
|
||||
t.Helper()
|
||||
b, err := os.ReadFile("testdata/" + name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func TestFingerprint(t *testing.T) {
|
||||
for _, tc := range []struct{ cert, fpr string }{
|
||||
{"v6.pgp", "v6.fpr"},
|
||||
{"v6-2.pgp", "v6-2.fpr"},
|
||||
} {
|
||||
fp, err := Fingerprint(read(t, tc.cert))
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %v", tc.cert, err)
|
||||
}
|
||||
want := strings.TrimSpace(string(read(t, tc.fpr)))
|
||||
if got := hex.EncodeToString(fp[:]); got != want {
|
||||
t.Fatalf("%s: fingerprint %s, erwartet %s", tc.cert, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFingerprintRejects(t *testing.T) {
|
||||
v6 := read(t, "v6.pgp")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cert []byte
|
||||
want error
|
||||
}{
|
||||
{"privat", read(t, "v6-secret.pgp"), ErrSecret},
|
||||
{"v4", read(t, "v4.pgp"), ErrVersion},
|
||||
{"leer", nil, ErrMalformed},
|
||||
{"abgeschnitten", v6[:len(v6)-10], ErrMalformed},
|
||||
{"kein paket", []byte("-----BEGIN PGP PUBLIC KEY BLOCK-----"), ErrMalformed},
|
||||
{"zu groß", make([]byte, MaxSize+1), ErrTooLarge},
|
||||
// Erstes Paket ist eine User-ID statt des Schlüssels.
|
||||
{"falsche reihenfolge", append([]byte{0xC0 | 13, 1, 'x'}, v6...), ErrNotPublic},
|
||||
} {
|
||||
if _, err := Fingerprint(tc.cert); !errors.Is(err, tc.want) {
|
||||
t.Errorf("%s: erwartet %v, bekam %v", tc.name, tc.want, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckSecret(t *testing.T) {
|
||||
fp, err := Fingerprint(read(t, "v6.pgp"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := CheckSecret(read(t, "v6-locked.pgp"), fp); err != nil {
|
||||
t.Fatalf("v6-locked: %v", err)
|
||||
}
|
||||
locked := read(t, "v6-locked.pgp")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
secret []byte
|
||||
want error
|
||||
}{
|
||||
{"ungeschützt", read(t, "v6-secret.pgp"), ErrUnprotected},
|
||||
{"ohne argon2", read(t, "v6-iter.pgp"), ErrUnprotected},
|
||||
{"anderer schlüssel", read(t, "v6-2-locked.pgp"), ErrMismatch},
|
||||
{"öffentlich", read(t, "v6.pgp"), ErrNotSecret},
|
||||
{"leer", nil, ErrMalformed},
|
||||
{"abgeschnitten", locked[:len(locked)-10], ErrMalformed},
|
||||
{"zu groß", make([]byte, MaxSize+1), ErrTooLarge},
|
||||
} {
|
||||
if err := CheckSecret(tc.secret, fp); !errors.Is(err, tc.want) {
|
||||
t.Errorf("%s: erwartet %v, bekam %v", tc.name, tc.want, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
+27
@@ -0,0 +1,27 @@
|
||||
// Erzeugt die v6-Fixtures neu (v4.pgp nicht):
|
||||
// node internal/pgpkey/testdata/gen.mjs internal/pgpkey/testdata
|
||||
// Passphrase der geschützten Schlüssel: "probe probe".
|
||||
import * as openpgp from "../../../frontend/node_modules/openpgp/dist/node/openpgp.mjs";
|
||||
import { writeFileSync } from "fs";
|
||||
const out = process.argv[2];
|
||||
const strong = { v6Keys: true, s2kType: openpgp.enums.s2k.argon2, aeadProtect: true };
|
||||
async function gen(name) {
|
||||
const { privateKey, publicKey } = await openpgp.generateKey({
|
||||
type: "curve25519", passphrase: "probe probe", format: "object", config: strong });
|
||||
writeFileSync(`${out}/${name}.pgp`, publicKey.write());
|
||||
writeFileSync(`${out}/${name}-locked.pgp`, privateKey.write());
|
||||
writeFileSync(`${out}/${name}.fpr`, publicKey.getFingerprint() + "\n");
|
||||
return { privateKey, publicKey };
|
||||
}
|
||||
const a = await gen("v6");
|
||||
await gen("v6-2");
|
||||
const open = await openpgp.decryptKey({ privateKey: a.privateKey, passphrase: "probe probe" });
|
||||
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 } });
|
||||
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);
|
||||
Vendored
BIN
Binary file not shown.
BIN
Binary file not shown.
Vendored
+1
@@ -0,0 +1 @@
|
||||
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
@@ -0,0 +1 @@
|
||||
5a1b886df7ffc708d21c27f335df62e0d2ca1afde74c951c88512420a4e43ca7
|
||||
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,738 @@
|
||||
--
|
||||
-- PostgreSQL database dump
|
||||
--
|
||||
|
||||
\restrict sfKzavw6BT7S48XgpklDXrRN4BzPBCBJB1apavBd4jjyastMTwALfb7ctd9PV5I
|
||||
|
||||
-- Dumped from database version 18.6 (Debian 18.6-1.pgdg13+2)
|
||||
-- Dumped by pg_dump version 18.6
|
||||
|
||||
-- Started on 2026-11-22 11:57:31 UTC
|
||||
|
||||
SET statement_timeout = 0;
|
||||
SET lock_timeout = 0;
|
||||
SET idle_in_transaction_session_timeout = 0;
|
||||
SET transaction_timeout = 0;
|
||||
SET client_encoding = 'UTF8';
|
||||
SET standard_conforming_strings = on;
|
||||
SELECT pg_catalog.set_config('search_path', '', false);
|
||||
SET check_function_bodies = false;
|
||||
SET xmloption = content;
|
||||
SET client_min_messages = warning;
|
||||
SET row_security = off;
|
||||
|
||||
--
|
||||
-- TOC entry 4 (class 2615 OID 2200)
|
||||
-- Name: public; Type: SCHEMA; Schema: -; Owner: pg_database_owner
|
||||
--
|
||||
|
||||
CREATE SCHEMA public;
|
||||
|
||||
|
||||
ALTER SCHEMA public OWNER TO pg_database_owner;
|
||||
|
||||
--
|
||||
-- TOC entry 3589 (class 0 OID 0)
|
||||
-- Dependencies: 4
|
||||
-- Name: SCHEMA public; Type: COMMENT; Schema: -; Owner: pg_database_owner
|
||||
--
|
||||
|
||||
COMMENT ON SCHEMA public IS 'standard public schema';
|
||||
|
||||
|
||||
SET default_tablespace = '';
|
||||
|
||||
SET default_table_access_method = heap;
|
||||
|
||||
--
|
||||
-- TOC entry 220 (class 1259 OID 52996)
|
||||
-- Name: account; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.account (
|
||||
id bigint NOT NULL,
|
||||
uid bigint NOT NULL,
|
||||
legacy_name text,
|
||||
password bytea NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
last_login bigint,
|
||||
avatar text DEFAULT ''::text NOT NULL,
|
||||
bio text DEFAULT ''::text NOT NULL,
|
||||
header text DEFAULT ''::text NOT NULL,
|
||||
handle text NOT NULL,
|
||||
display_name text DEFAULT ''::text NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.account OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 219 (class 1259 OID 52995)
|
||||
-- Name: account_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.account ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.account_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 234 (class 1259 OID 77480)
|
||||
-- Name: account_key; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.account_key (
|
||||
id bigint NOT NULL,
|
||||
uid bigint NOT NULL,
|
||||
fingerprint bytea NOT NULL,
|
||||
public_key bytea NOT NULL,
|
||||
secret_key bytea NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
replaced_at bigint DEFAULT 0 NOT NULL,
|
||||
lost_at bigint DEFAULT 0 NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.account_key OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 233 (class 1259 OID 77479)
|
||||
-- Name: account_key_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.account_key ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.account_key_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 224 (class 1259 OID 53032)
|
||||
-- Name: entry; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.entry (
|
||||
id bigint NOT NULL,
|
||||
pid bigint NOT NULL,
|
||||
uid bigint NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
content text DEFAULT ''::text NOT NULL,
|
||||
filepath text DEFAULT ''::text NOT NULL,
|
||||
reply_to bigint DEFAULT 0 NOT NULL,
|
||||
reply_count bigint DEFAULT 0 NOT NULL,
|
||||
last_activity bigint DEFAULT 0 NOT NULL,
|
||||
deleted bigint DEFAULT 0 NOT NULL,
|
||||
bump_count bigint DEFAULT 0 NOT NULL,
|
||||
last_bump bigint DEFAULT 0 NOT NULL,
|
||||
link_url text DEFAULT ''::text NOT NULL,
|
||||
image_warning text DEFAULT ''::text NOT NULL,
|
||||
image_cover text DEFAULT ''::text NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.entry OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 223 (class 1259 OID 53031)
|
||||
-- Name: entry_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.entry ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.entry_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 240 (class 1259 OID 123529)
|
||||
-- Name: entry_tag; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.entry_tag (
|
||||
pid bigint NOT NULL,
|
||||
tag text NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.entry_tag OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 227 (class 1259 OID 53075)
|
||||
-- Name: impression; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.impression (
|
||||
day text NOT NULL,
|
||||
anon_ip text NOT NULL,
|
||||
path text DEFAULT ''::text NOT NULL,
|
||||
asn text DEFAULT ''::text NOT NULL,
|
||||
hits bigint DEFAULT 0 NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.impression OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 232 (class 1259 OID 67157)
|
||||
-- Name: link_preview; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.link_preview (
|
||||
url text NOT NULL,
|
||||
kind text DEFAULT ''::text NOT NULL,
|
||||
title text DEFAULT ''::text NOT NULL,
|
||||
site text DEFAULT ''::text NOT NULL,
|
||||
thumb text DEFAULT ''::text NOT NULL,
|
||||
status text DEFAULT 'pending'::text NOT NULL,
|
||||
fetched_at bigint DEFAULT 0 NOT NULL,
|
||||
attempts integer DEFAULT 0 NOT NULL,
|
||||
retry_at bigint DEFAULT 0 NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.link_preview OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 239 (class 1259 OID 123498)
|
||||
-- Name: mention; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.mention (
|
||||
pid bigint NOT NULL,
|
||||
handle text NOT NULL,
|
||||
uid bigint NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.mention OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 236 (class 1259 OID 77502)
|
||||
-- Name: message; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.message (
|
||||
id bigint NOT NULL,
|
||||
sender bigint NOT NULL,
|
||||
recipient bigint NOT NULL,
|
||||
body bytea NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
read_at bigint DEFAULT 0 NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.message OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 235 (class 1259 OID 77501)
|
||||
-- Name: message_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.message ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.message_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 238 (class 1259 OID 123452)
|
||||
-- Name: notification; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.notification (
|
||||
id bigint NOT NULL,
|
||||
uid bigint NOT NULL,
|
||||
kind text NOT NULL,
|
||||
actor bigint DEFAULT 0 NOT NULL,
|
||||
excerpt text DEFAULT ''::text NOT NULL,
|
||||
link text NOT NULL,
|
||||
pid bigint DEFAULT 0 NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
seen_at bigint DEFAULT 0 NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.notification OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 237 (class 1259 OID 123451)
|
||||
-- Name: notification_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.notification ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.notification_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 231 (class 1259 OID 60666)
|
||||
-- Name: password_reset; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.password_reset (
|
||||
id bigint NOT NULL,
|
||||
uid bigint NOT NULL,
|
||||
token_hash text NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
expires bigint NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.password_reset OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 230 (class 1259 OID 60665)
|
||||
-- Name: password_reset_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.password_reset ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.password_reset_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 229 (class 1259 OID 53091)
|
||||
-- Name: report; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.report (
|
||||
id bigint NOT NULL,
|
||||
pid bigint NOT NULL,
|
||||
uid bigint DEFAULT 0 NOT NULL,
|
||||
reason text DEFAULT ''::text NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
handled bigint DEFAULT 0 NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.report OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 228 (class 1259 OID 53090)
|
||||
-- Name: report_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.report ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.report_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 222 (class 1259 OID 53015)
|
||||
-- Name: session; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.session (
|
||||
id bigint NOT NULL,
|
||||
uid bigint NOT NULL,
|
||||
value text NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
expires bigint NOT NULL,
|
||||
description text DEFAULT ''::text NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.session OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 221 (class 1259 OID 53014)
|
||||
-- Name: session_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.session ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.session_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 226 (class 1259 OID 53062)
|
||||
-- Name: vote; Type: TABLE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE TABLE public.vote (
|
||||
id bigint NOT NULL,
|
||||
uid bigint NOT NULL,
|
||||
pid bigint NOT NULL,
|
||||
mode text NOT NULL
|
||||
);
|
||||
|
||||
|
||||
ALTER TABLE public.vote OWNER TO kver;
|
||||
|
||||
--
|
||||
-- TOC entry 225 (class 1259 OID 53061)
|
||||
-- Name: vote_id_seq; Type: SEQUENCE; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE public.vote ALTER COLUMN id ADD GENERATED ALWAYS AS IDENTITY (
|
||||
SEQUENCE NAME public.vote_id_seq
|
||||
START WITH 1
|
||||
INCREMENT BY 1
|
||||
NO MINVALUE
|
||||
NO MAXVALUE
|
||||
CACHE 1
|
||||
);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3380 (class 2606 OID 114443)
|
||||
-- Name: account account_handle_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.account
|
||||
ADD CONSTRAINT account_handle_key UNIQUE (handle);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3417 (class 2606 OID 77498)
|
||||
-- Name: account_key account_key_fingerprint_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.account_key
|
||||
ADD CONSTRAINT account_key_fingerprint_key UNIQUE (fingerprint);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3419 (class 2606 OID 77496)
|
||||
-- Name: account_key account_key_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.account_key
|
||||
ADD CONSTRAINT account_key_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3382 (class 2606 OID 53009)
|
||||
-- Name: account account_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.account
|
||||
ADD CONSTRAINT account_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3384 (class 2606 OID 53011)
|
||||
-- Name: account account_uid_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.account
|
||||
ADD CONSTRAINT account_uid_key UNIQUE (uid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3386 (class 2606 OID 53013)
|
||||
-- Name: account account_username_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.account
|
||||
ADD CONSTRAINT account_username_key UNIQUE (legacy_name);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3393 (class 2606 OID 53060)
|
||||
-- Name: entry entry_pid_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.entry
|
||||
ADD CONSTRAINT entry_pid_key UNIQUE (pid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3395 (class 2606 OID 53058)
|
||||
-- Name: entry entry_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.entry
|
||||
ADD CONSTRAINT entry_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3435 (class 2606 OID 123537)
|
||||
-- Name: entry_tag entry_tag_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.entry_tag
|
||||
ADD CONSTRAINT entry_tag_pkey PRIMARY KEY (pid, tag);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3406 (class 2606 OID 53089)
|
||||
-- Name: impression impression_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.impression
|
||||
ADD CONSTRAINT impression_pkey PRIMARY KEY (day, anon_ip, path);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3415 (class 2606 OID 67176)
|
||||
-- Name: link_preview link_preview_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.link_preview
|
||||
ADD CONSTRAINT link_preview_pkey PRIMARY KEY (url);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3433 (class 2606 OID 123507)
|
||||
-- Name: mention mention_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.mention
|
||||
ADD CONSTRAINT mention_pkey PRIMARY KEY (pid, handle);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3426 (class 2606 OID 77515)
|
||||
-- Name: message message_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.message
|
||||
ADD CONSTRAINT message_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3430 (class 2606 OID 123471)
|
||||
-- Name: notification notification_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.notification
|
||||
ADD CONSTRAINT notification_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3411 (class 2606 OID 60677)
|
||||
-- Name: password_reset password_reset_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.password_reset
|
||||
ADD CONSTRAINT password_reset_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3413 (class 2606 OID 60679)
|
||||
-- Name: password_reset password_reset_token_hash_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.password_reset
|
||||
ADD CONSTRAINT password_reset_token_hash_key UNIQUE (token_hash);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3409 (class 2606 OID 53106)
|
||||
-- Name: report report_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.report
|
||||
ADD CONSTRAINT report_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3389 (class 2606 OID 53028)
|
||||
-- Name: session session_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.session
|
||||
ADD CONSTRAINT session_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3391 (class 2606 OID 53030)
|
||||
-- Name: session session_value_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.session
|
||||
ADD CONSTRAINT session_value_key UNIQUE (value);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3402 (class 2606 OID 53072)
|
||||
-- Name: vote vote_pkey; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.vote
|
||||
ADD CONSTRAINT vote_pkey PRIMARY KEY (id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3404 (class 2606 OID 53074)
|
||||
-- Name: vote vote_uid_pid_key; Type: CONSTRAINT; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
ALTER TABLE ONLY public.vote
|
||||
ADD CONSTRAINT vote_uid_pid_key UNIQUE (uid, pid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3420 (class 1259 OID 77499)
|
||||
-- Name: idx_account_key_current; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE UNIQUE INDEX idx_account_key_current ON public.account_key USING btree (uid) WHERE (replaced_at = 0);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3421 (class 1259 OID 77500)
|
||||
-- Name: idx_account_key_uid; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_account_key_uid ON public.account_key USING btree (uid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3396 (class 1259 OID 53107)
|
||||
-- Name: idx_entry_last_activity; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_entry_last_activity ON public.entry USING btree (last_activity);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3397 (class 1259 OID 53108)
|
||||
-- Name: idx_entry_reply_to; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_entry_reply_to ON public.entry USING btree (reply_to);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3398 (class 1259 OID 75703)
|
||||
-- Name: idx_entry_siblings; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_entry_siblings ON public.entry USING btree (reply_to, last_activity, pid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3436 (class 1259 OID 123538)
|
||||
-- Name: idx_entry_tag_tag; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_entry_tag_tag ON public.entry_tag USING btree (tag text_pattern_ops);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3399 (class 1259 OID 53109)
|
||||
-- Name: idx_entry_uid; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_entry_uid ON public.entry USING btree (uid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3431 (class 1259 OID 123508)
|
||||
-- Name: idx_mention_uid; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_mention_uid ON public.mention USING btree (uid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3422 (class 1259 OID 77518)
|
||||
-- Name: idx_message_created; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_message_created ON public.message USING btree (created_at);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3423 (class 1259 OID 77516)
|
||||
-- Name: idx_message_pair; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_message_pair ON public.message USING btree (sender, recipient, id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3424 (class 1259 OID 77517)
|
||||
-- Name: idx_message_recipient; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_message_recipient ON public.message USING btree (recipient, id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3427 (class 1259 OID 123473)
|
||||
-- Name: idx_notification_pid; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_notification_pid ON public.notification USING btree (pid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3428 (class 1259 OID 123472)
|
||||
-- Name: idx_notification_uid; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_notification_uid ON public.notification USING btree (uid, id);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3407 (class 1259 OID 53112)
|
||||
-- Name: idx_report_open; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_report_open ON public.report USING btree (handled, created_at);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3387 (class 1259 OID 53111)
|
||||
-- Name: idx_session_uid; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_session_uid ON public.session USING btree (uid);
|
||||
|
||||
|
||||
--
|
||||
-- TOC entry 3400 (class 1259 OID 53110)
|
||||
-- Name: idx_vote_pid; Type: INDEX; Schema: public; Owner: kver
|
||||
--
|
||||
|
||||
CREATE INDEX idx_vote_pid ON public.vote USING btree (pid);
|
||||
|
||||
|
||||
-- Completed on 2026-11-22 11:57:31 UTC
|
||||
|
||||
--
|
||||
-- PostgreSQL database dump complete
|
||||
--
|
||||
|
||||
\unrestrict sfKzavw6BT7S48XgpklDXrRN4BzPBCBJB1apavBd4jjyastMTwALfb7ctd9PV5I
|
||||
|
||||
+123
-15
@@ -28,7 +28,7 @@ Form:
|
||||
| `403` | angemeldet, aber nicht erlaubt (fremder Beitrag, falsches Passwort, TOR, fremder Origin) |
|
||||
| `404` | Objekt oder Endpunkt existiert nicht (`api.not_found`) |
|
||||
| `405` | Endpunkt existiert, aber nicht mit dieser Methode (`api.method_not_allowed`) |
|
||||
| `409` | Konflikt (Nutzername vergeben) |
|
||||
| `409` | Konflikt (Handle vergeben) |
|
||||
| `413` | Upload zu groß |
|
||||
| `429` | zu viele Anfragen (`rate.limited`) oder Repost-Cooldown |
|
||||
| `500` | Serverfehler (`internal`, Ursache nur im Log) |
|
||||
@@ -36,10 +36,12 @@ Form:
|
||||
**Requests** sind `application/x-www-form-urlencoded` bzw. `multipart/form-data`
|
||||
(Uploads). Zeitstempel sind Unix-Sekunden.
|
||||
|
||||
**Auth** läuft über das Cookie `session` (HttpOnly, SameSite=Lax). Geschützte
|
||||
Endpunkte antworten ohne gültige Session mit `401 auth.required`.
|
||||
**Auth** läuft über das Cookie `session` (HttpOnly, SameSite=Lax). Der Server
|
||||
speichert davon nur den SHA-256 (wie bei Reset-Links). Geschützte Endpunkte
|
||||
antworten ohne gültige Session mit `401 auth.required`.
|
||||
|
||||
**CSRF:** Nicht-GET-Requests mit fremdem `Origin`-Header werden mit
|
||||
**CSRF:** Nicht-GET-Requests mit fremdem `Origin`-Header oder mit
|
||||
`Sec-Fetch-Site` ungleich `same-origin`/`none` werden mit
|
||||
`403 csrf.bad_origin` abgewiesen.
|
||||
|
||||
**Rate-Limits** (pro IP): Login, Registrierung und Passwort-Reset 20/min.
|
||||
@@ -50,17 +52,17 @@ Endpunkte antworten ohne gültige Session mit `401 auth.required`.
|
||||
|
||||
| Methode | Pfad | Auth | Request | Erfolg |
|
||||
|---------|------|------|---------|--------|
|
||||
| POST | `/api/auth/login` | – | `user`, `pass`, `timeout` (s, Default 1 Tag, max. 1 Jahr) | `200 {"status":"ok"}` + Cookie; bereits angemeldet: `200 {"status":"already_logged_in"}` |
|
||||
| POST | `/api/auth/newuser` | – | `user` (3–32 Zeichen), `pass1` (min. 10), `pass2` | `201 {"username"}` |
|
||||
| POST | `/api/auth/login` | – | `user` (Handle, Groß/klein und `@` egal), `pass`, `timeout` (s, Default 1 Tag, max. 1 Jahr) | `200 {"status":"ok"}` + Cookie; bereits angemeldet: `200 {"status":"already_logged_in"}` |
|
||||
| POST | `/api/auth/newuser` | – | `handle` (3–20 Zeichen a–z, 0–9, `_`; wird klein geschrieben), `display_name` (optional, max. 32 Zeichen), `pass1` (min. 10), `pass2` | `201 {"handle","display_name"}`; Handle ungültig: `user.handle_invalid`, vergeben: `user.handle_taken` (beides in `fields.handle`) |
|
||||
| POST | `/api/auth/logout` | – | – | `200 {"status":"ok"}`, löscht Cookie |
|
||||
| GET | `/api/auth/sessioninfo` | ✓ | – | `200 {"uid","created_at","expires","description"}`, ohne Session `401` |
|
||||
| POST | `/api/auth/reset/check` | – | `token` | `200 {"username"}`; ungültig/abgelaufen/benutzt: `404 reset.invalid` |
|
||||
| POST | `/api/auth/reset` | – | `token`, `pass1` (min. 10), `pass2` | `200 {"username"}` + Cookie (eingeloggt); löscht alle alten Sessions, Link verbraucht |
|
||||
| POST | `/api/auth/reset/check` | – | `token` | `200 {"handle"}`; ungültig/abgelaufen/benutzt: `404 reset.invalid` |
|
||||
| POST | `/api/auth/reset` | – | `token`, `pass1` (min. 10), `pass2` | `200 {"handle"}` + Cookie (eingeloggt); löscht alle alten Sessions, Link verbraucht |
|
||||
|
||||
Login-Fehler: `401 auth.bad_credentials` (gleich für unbekannten Nutzer und
|
||||
falsches Passwort).
|
||||
|
||||
Reset-Links erzeugt nur der Admin per CLI (`kver reset-link <nutzername>`,
|
||||
Reset-Links erzeugt nur der Admin per CLI (`kver reset-link <handle>`,
|
||||
siehe deploy.md). Sie zeigen auf `/reset#<token>`, gelten 72 h und einmal; ein
|
||||
neuer Link macht ältere desselben Nutzers ungültig. Das Token steht im
|
||||
Fragment und geht nur im POST-Body an die API, damit es nicht in Logs landet.
|
||||
@@ -75,9 +77,15 @@ Ein Beitrag (`Entry`):
|
||||
{ "pid": 123456789, "uid": 42, "created_at": 1700000000, "content": "…",
|
||||
"filepath": "static/media/…", "reply_to": 0, "reply_count": 3,
|
||||
"last_activity": 1700000500, "deleted": 0, "bump_count": 1,
|
||||
"last_bump": 1700000400, "username": "max", "avatar": "static/media/…" }
|
||||
"last_bump": 1700000400, "handle": "max", "display_name": "Max 🌻", "avatar": "static/media/…" }
|
||||
```
|
||||
|
||||
Steht ein Hinweis vor dem Bild (vom Admin gesetzt, `kver cover-image`),
|
||||
trägt der Beitrag zusätzlich `image_warning` (der Hinweistext) und
|
||||
`image_cover` (stark verpixelte JPEG-Variante). Das Frontend zeigt dann erst
|
||||
die Variante mit dem Hinweis und lädt `filepath` erst nach Klick auf „Inhalt
|
||||
anzeigen“. Ohne Hinweis fehlen beide Felder.
|
||||
|
||||
Enthält der Text einen Link, trägt der Beitrag `preview`, sobald der Server
|
||||
die Vorschau des **ersten** Links geholt hat (asynchron nach dem Anlegen bzw.
|
||||
Bearbeiten; vorher und ohne verwertbare Vorschau fehlt das Feld). `url` ist
|
||||
@@ -107,7 +115,9 @@ Antwort). Ohne passenden Nachfahren fehlt das Feld.
|
||||
| Methode | Pfad | Auth | Request | Erfolg |
|
||||
|---------|------|------|---------|--------|
|
||||
| GET | `/api/entry/feed/{page}` | – | – | `200 [Entry]` mit `latest`: Threads nach letzter Aktivität, 20 pro Seite, Seite 0–100, `[]` am Ende |
|
||||
| GET | `/api/entry/search/{page}` | – | `?q=&user=&tag=&roots=1`, alle optional | `200 [Entry]`: nicht gelöschte Beiträge, die alle Filter erfüllen, neueste zuerst, Seiten wie beim Feed. Siehe unten |
|
||||
| GET | `/api/entry/{pid}/thread` | – | – | `200 {"entry", "ancestors": [Entry], "replies": [Entry]}`; `ancestors` Root zuerst, `replies` (max. 100) nach letzter Aktivität, mit `latest` |
|
||||
| GET | `/api/tags/suggest` | – | `?q=` (Anfang eines Hashtags, `#` optional) | `200 {"tags":[{"tag","count"}]}`, höchstens 8 Tags mit diesem Anfang (klein), die in den meisten nicht gelöschten Beiträgen zuerst; leeres q: die häufigsten überhaupt. Rate-Limit pro IP |
|
||||
| GET | `/api/entry/{pid}/votes` | – | – | `200 {"pid","yes","no","selected"}` (`selected`: `yes`/`no`/`none`) |
|
||||
| POST | `/api/entry/{pid}/report` | – | `reason` (optional, max. 500) | `200 {"status":"reported"}`. Ohne Session anonym (uid 0); Angemeldete legen keine zweite offene Meldung an; gelöschte Beiträge `404`; 10/min pro IP |
|
||||
| POST | `/api/entry/create` | ✓ | multipart: `content` (max. 1000), `file` (optional), `reply_to` (optional) | `201 {"pid","content","filepath","reply_to"}` |
|
||||
@@ -122,16 +132,41 @@ antwortet der Endpunkt mit `429 entry.bump_cooldown`. Dazu kommen der Header
|
||||
|
||||
TOR-Anfragen auf `create` werden mit `403 tor.blocked` abgewiesen.
|
||||
|
||||
**Suche** (`internal/httpapi/search.go`, derselbe Filter liefert den
|
||||
Profil-Feed):
|
||||
|
||||
- `q`: Wörter durch Leerzeichen getrennt, jedes muss im Text vorkommen
|
||||
(Teilwort, Groß-/Kleinschreibung egal; `%` und `_` gelten wörtlich)
|
||||
- `user`: Handle, `@` davor erlaubt; unbekannt: `404 user.not_found`
|
||||
- `tag`: ein oder mehrere Hashtags, `#` davor optional, alle müssen
|
||||
vorkommen; ganzes Tag (`kv` trifft nicht `#kver`). Nur Buchstaben,
|
||||
Ziffern, `_`, sonst `400 search.bad_tag`
|
||||
- `roots=1`: keine Antworten
|
||||
- `q` und `tag` je max. 200 Zeichen, zusammen max. 10 Begriffe, sonst
|
||||
`400 search.too_long`. Ohne Filter: alle Beiträge
|
||||
|
||||
---
|
||||
|
||||
### Erwähnungen
|
||||
|
||||
`@handle` im Text (davor kein Buchstabe, keine Ziffer, kein `_`) erwähnt den
|
||||
Nutzer, höchstens 10 pro Beitrag. Gespeichert wird beim Anlegen bzw.
|
||||
Bearbeiten, wem der Handle in diesem Moment gehört (Tabelle `mention`). Jeder
|
||||
Beitrag trägt `mentions`: geschriebener Handle (klein) → heutiger Handle
|
||||
derselben Person, z. B. `{"bob": "robert"}` nach einer Umbenennung. Das
|
||||
Frontend verlinkt nur diese; unbekannte `@…` bleiben Text. Ohne Erwähnungen
|
||||
fehlt das Feld.
|
||||
|
||||
## Nutzer
|
||||
|
||||
| Methode | Pfad | Auth | Request | Erfolg |
|
||||
|---------|------|------|---------|--------|
|
||||
| GET | `/api/u/{username}/info` | – | – | `200 {"uid","username","created_at","avatar","header","bio","entries"}`; `header` leer = kein Header-Bild, `entries` = nicht gelöschte Beiträge |
|
||||
| GET | `/api/u/{username}/feed/{page}` | – | – | `200 [Entry]`: alle Beiträge inkl. Antworten, chronologisch |
|
||||
| GET | `/api/user/info` | ✓ | – | `200 {"uid","username","created_at","last_login","avatar"}` |
|
||||
| POST | `/api/user/rename` | ✓ | `user` | `200 {"username"}`; vergeben: `409 user.name_taken` |
|
||||
| GET | `/api/u/{handle}/info` | – | – | `200 {"uid","handle","display_name","created_at","avatar","header","bio","entries"}`; `header` leer = kein Header-Bild, `entries` = nicht gelöschte Beiträge |
|
||||
| GET | `/api/u/{handle}/feed/{page}` | – | – | `200 [Entry]`: alle Beiträge inkl. Antworten, chronologisch |
|
||||
| GET | `/api/user/info` | ✓ | – | `200 {"uid","handle","display_name","created_at","last_login","avatar"}` |
|
||||
| GET | `/api/users/suggest` | ✓ | `?q=` (angefangener Handle, `@` optional) | `200 {"users":[{"handle","display_name","avatar"}]}`, höchstens 8: zuerst Handles mit diesem Anfang, dann Anzeigenamen, die q enthalten; leeres q: leere Liste. Rate-Limit pro IP |
|
||||
| POST | `/api/user/handle` | ✓ | `handle` | `200 {"handle"}`; ungültig: `400 user.handle_invalid`, unverändert: `400 user.handle_unchanged`, vergeben: `409 user.handle_taken`. Alte `/u/…`-Links laufen danach ins Leere |
|
||||
| POST | `/api/user/display_name` | ✓ | `display_name` | `200 {"display_name"}`: Unicode, ohne Steuerzeichen, Leerraum zusammengefasst, höchstens 32 Zeichen; leer = Handle anzeigen |
|
||||
| POST | `/api/user/password` | ✓ | `pass`, `pass1`, `pass2` | `200 {"status":"ok"}`; beendet alle anderen Sessions; bisheriges Passwort falsch: `403 auth.bad_password`, neues ungültig: `400 user.invalid`; Rate-Limit pro IP |
|
||||
| POST | `/api/user/avatar` | ✓ | multipart: `avatar` | `200 {"avatar"}` |
|
||||
| POST | `/api/user/header` | ✓ | multipart: `header` | `200 {"header"}`, ersetzt ein vorhandenes Header-Bild |
|
||||
@@ -141,6 +176,79 @@ TOR-Anfragen auf `create` werden mit `403 tor.blocked` abgewiesen.
|
||||
|
||||
---
|
||||
|
||||
## Schlüssel
|
||||
|
||||
OpenPGP-v6-Schlüssel für Ende-zu-Ende-verschlüsselte Direktnachrichten
|
||||
(Plan: `notes/schluessel.md`). Der Server prüft beim Hochladen nur die
|
||||
Struktur (`internal/pgpkey`): beim Zertifikat lesbare Pakete, erstes Paket
|
||||
ein v6-Ed25519-Hauptschlüssel, kein privates Schlüsselmaterial, höchstens
|
||||
16 KiB; beim privaten Schlüssel derselbe Fingerprint und jedes geheime Paket
|
||||
mit Argon2 und AEAD verschlüsselt.
|
||||
|
||||
Ein Schlüssel im Drahtformat: `{"fingerprint","key","status","created_at"}`
|
||||
mit `fingerprint` als v6-Fingerprint in Hex (Kleinbuchstaben), `key` als
|
||||
binäres Zertifikat in Base64 und `status` = `current` | `replaced` | `lost`
|
||||
(als verloren markiert).
|
||||
|
||||
| Methode | Pfad | Auth | Request | Erfolg |
|
||||
|---------|------|------|---------|--------|
|
||||
| GET | `/api/u/{handle}/key` | – | – | `200` Schlüssel; keiner: `404 key.not_found`; als verloren markiert: `404 key.lost` |
|
||||
| POST | `/api/user/key` | ✓ | `key`, `secret` (Base64, privat und verschlüsselt) | `201` Schlüssel; der bisherige wird `replaced`. Schon hinterlegt (auch bei anderen): `409 key.exists` |
|
||||
| GET | `/api/user/keys/secret` | ✓ | – | `200 {"keys":[{"fingerprint","secret","current"}]}`: alle eigenen verschlüsselten privaten Schlüssel (Base64), neueste zuerst; `current` beim aktuellen, nicht verlorenen |
|
||||
| POST | `/api/user/key/passphrase` | ✓ | `secret` (Base64) | `200 {"status":"ok"}`; ersetzt den privaten Schlüssel des aktuellen durch denselben mit neuer Passphrase. Keiner: `404 key.not_found` |
|
||||
| POST | `/api/user/key/lost` | ✓ | – | `200 {"status":"ok"}`; markiert den aktuellen Schlüssel als verloren. Keiner: `404 key.not_found` |
|
||||
|
||||
Fehler beim Hochladen: `400 key.invalid` (nicht lesbar), `key.secret`
|
||||
(privater Schlüssel im Feld `key`), `key.unsupported` (nicht v6/Ed25519),
|
||||
`key.secret_invalid` (privater fehlt oder nicht lesbar),
|
||||
`key.secret_unprotected` (nicht mit Argon2 und AEAD verschlüsselt),
|
||||
`key.secret_mismatch` (gehört zu anderem Schlüssel), `413 key.too_large`.
|
||||
Ein Kontopasswort verlangt keiner der Endpunkte (siehe
|
||||
`notes/schluessel.md`). Die POST-Endpunkte sind gedrosselt (20/min pro IP).
|
||||
|
||||
---
|
||||
|
||||
## 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":[{"handle","display_name","avatar","last_at","unread"}]}`, jüngstes Gespräch zuerst |
|
||||
| GET | `/api/chats/{handle}` | ✓ | `?after=id` (optional) | `200 {"messages":[{"id","mine","body","created_at"}]}`, älteste zuerst; die abgerufenen Nachrichten an einen gelten als gelesen |
|
||||
| POST | `/api/chats/{handle}` | ✓ | `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).
|
||||
|
||||
---
|
||||
|
||||
## Benachrichtigungen
|
||||
|
||||
Drei Arten (`kind`):
|
||||
|
||||
- `reply`: jemand hat auf einen eigenen Beitrag geantwortet (nicht bei
|
||||
Antworten an sich selbst), `message` etwa „@bob hat auf deinen Beitrag
|
||||
geantwortet.“, `excerpt` der Anfang der Antwort; `link` führt zur Antwort. Der Handle ist der
|
||||
aktuelle, auch nach einer Umbenennung.
|
||||
- `mention`: jemand hat einen in einem Beitrag erwähnt: „@alice hat dich
|
||||
erwähnt.“, `excerpt` der Anfang des Beitrags. Nicht für den Autor selbst
|
||||
und nicht für den Autor des Elternbeitrags (der bekommt `reply`); wer
|
||||
schon erwähnt war, wird beim Bearbeiten nicht erneut benachrichtigt.
|
||||
- `bump`: jemand hat einen eigenen Beitrag repostet (nicht beim eigenen
|
||||
Repost): „Jemand hat deinen Beitrag repostet.“, `excerpt` der Anfang des
|
||||
Beitrags. Wer repostet, speichert der Server nicht.
|
||||
|
||||
Der Auszug umfasst die ersten 50 Zeichen. Wird der zitierte Beitrag
|
||||
bearbeitet, zieht er nach; wird er gelöscht (auch mit dem Konto), verschwindet
|
||||
die Benachrichtigung.
|
||||
|
||||
| Methode | Pfad | Auth | Request | Erfolg |
|
||||
|---|---|---|---|---|
|
||||
| GET | `/api/notifications` | ✓ | – | `200 {"notifications":[{"id","kind","message","excerpt","link","created_at","seen"}]}`, die 50 jüngsten, neueste zuerst; `seen` ist der Stand vor dem Abruf, der Abruf markiert alle gelieferten als gesehen |
|
||||
| GET | `/api/notifications/unread` | ✓ | – | `200 {"unread"}`: Zahl der ungesehenen |
|
||||
|
||||
## Statistik
|
||||
|
||||
| Methode | Pfad | Erfolg |
|
||||
@@ -153,7 +261,7 @@ TOR-Anfragen auf `create` werden mit `403 tor.blocked` abgewiesen.
|
||||
|
||||
## Seiten (kein JSON)
|
||||
|
||||
`/`, `/e/{pid}`, `/u/{username}` liefern die HTML-Seiten des Frontends und
|
||||
`/`, `/e/{pid}`, `/u/{handle}` liefern die HTML-Seiten des Frontends und
|
||||
zählen anonymisierte Impressions. `/static/*` enthält Uploads und Dokumente,
|
||||
alles andere kommt aus `web/`.
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# 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 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 des Tabs. Die Passphrase merkt
|
||||
sich der Browser 7 Tage ab der Eingabe im `localStorage`
|
||||
(`kver.passphrase`, mit Handle und Ablaufzeit) und entsperrt damit
|
||||
nach dem Neuladen von selbst; passt sie nicht mehr, wird sie vergessen.
|
||||
Logout, neuer Schlüssel oder „als verloren markieren“ sperren und
|
||||
vergessen, „Passphrase ändern“ vergisst die gemerkte.
|
||||
- **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. Die Summe der
|
||||
ungelesenen steht als Zähler am Chat-Symbol (TabBar und Seitenleiste,
|
||||
`useUnread` in `frontend/src/chats.ts`, dieselbe Abfrage wie die
|
||||
Übersicht).
|
||||
- **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“
|
||||
- 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)
|
||||
- Bilder und Anhänge, Gruppen
|
||||
+49
-1
@@ -216,18 +216,66 @@ podman build -t kver .
|
||||
systemctl --user restart kver
|
||||
```
|
||||
|
||||
Einmalig nach dem Update vom 22.11.2026 (Session-Tokens werden seitdem
|
||||
gehasht gespeichert): Die alten Klartext-Zeilen sind nutzlos und würden erst
|
||||
mit ihrem Ablauf (bis zu ein Jahr) verschwinden -- `DELETE FROM session;`
|
||||
räumt sie weg. Alle Nutzer müssen sich danach ohnehin neu anmelden.
|
||||
|
||||
Die App fährt bei SIGTERM sauber herunter (laufende Requests werden zu Ende
|
||||
bedient, dann wird die DB-Verbindung geschlossen).
|
||||
|
||||
## Handles (Umstellung 11/2026)
|
||||
|
||||
Seit der Trennung von Handle (`@name`, a–z 0–9 `_`, Login und Profil-URL)
|
||||
und Anzeigename (frei, Unicode) ist der alte Nutzername Anzeigename und,
|
||||
umgeschrieben (ä→ae, Pinyin, `.`/`-`→`_`, klein, Kollisionen mit Zahl),
|
||||
Handle. Die Umschrift ist gelaufen, ihr Code ist weg; der alte Name bleibt in
|
||||
`account.legacy_name`. Wer sich jetzt mit einem anderen Namen anmelden muss
|
||||
(mehr als nur die Groß-/Kleinschreibung), listet:
|
||||
|
||||
```sh
|
||||
podman exec kver kver handles
|
||||
```
|
||||
|
||||
Die Ausgabe enthält echte Nutzernamen: nicht in Tickets oder Logs kopieren.
|
||||
|
||||
## Passwort zurücksetzen
|
||||
|
||||
Ohne E-Mail-System erzeugt der Admin einen Einmal-Link und gibt ihn dem
|
||||
Nutzer persönlich:
|
||||
|
||||
```sh
|
||||
podman exec kver kver reset-link <nutzername>
|
||||
podman exec kver kver reset-link <handle>
|
||||
```
|
||||
|
||||
Der Link (`/reset#<token>`) gilt 72 Stunden und nur einmal; ein neuer Link
|
||||
macht ältere desselben Nutzers ungültig. Beim Setzen des neuen Passworts
|
||||
werden alle bestehenden Sessions des Nutzers abgemeldet.
|
||||
|
||||
## Meldungen ansehen
|
||||
|
||||
Offene Meldungen, gruppiert nach Beitrag (Link, Autor, Inhalt, darunter jede
|
||||
Meldung mit Zeit, Melder und Grund):
|
||||
|
||||
```sh
|
||||
podman exec kver kver reports
|
||||
```
|
||||
|
||||
Bewusst nur per CLI: Zugriff hat, wer auf dem Server `podman exec` darf; es
|
||||
gibt keine Admin-Rolle und keine Web-Route dafür. Die Ausgabe enthält echte
|
||||
Handles und Inhalte: nicht in Tickets oder Logs kopieren.
|
||||
|
||||
## Bilder hinter einen Hinweis legen
|
||||
|
||||
Für Bilder, die erlaubt sind, aber nicht jedem ungefragt begegnen müssen:
|
||||
|
||||
```sh
|
||||
podman exec kver kver cover-image <pid> 'Darstellung von …'
|
||||
podman exec kver kver uncover-image <pid>
|
||||
```
|
||||
|
||||
`cover-image` legt neben dem Bild eine stark verpixelte Variante an
|
||||
(`cover-*.jpg`); angezeigt wird sie mit dem Hinweis und „Inhalt anzeigen“,
|
||||
das Bild selbst erst nach dem Klick. Erneut aufgerufen ändert es nur den
|
||||
Text. `uncover-image` nimmt den Hinweis weg und löscht die Variante. Die pid
|
||||
steht in der Adresse des Beitrags (`/e/<pid>`) und in `kver reports`.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user