@@ -122,16 +442,52 @@ export function PostCard({ post }: { post: Post }) {
)}
+ {like.people.length > 0 && (
setReply(true)}
- disabled={!me}
+ className="like-summary"
+ onClick={() => setLikers(true)}
>
-
- {replies.length ? `${replies.length} Antworten` : "Antworten"}
+
+ {like.people.slice(0, 3).map((p) => (
+
+ ))}
+
+ {likeSummary(
+ like.people.map((p) =>
+ p.id === me?.id ? "dir" : p.display_name.split(" ")[0],
+ ),
+ )}
+ )}
+
+
+
+ {
+ setCommenting(true);
+ setShowAll(true);
+ setTimeout(
+ () => document.getElementById(`comment-${post.id}`)?.focus(),
+ 30,
+ );
+ }}
+ disabled={!canComment}
+ >
+
+ {replies.length ? replies.length : "Kommentieren"}
+
+ void share()}
+ >
+
+ Teilen
+
+
{post.valuable_votes_count + post.slop_votes_count || "↗"}
- {replies.length > 0 && (
-
- Gespräch ansehen
- {replies.map((item) => {
- const person = state.profiles.find((p) => p.id === item.author_id);
- return (
-
-
@{person?.username}
-
- {item.slop_status === "hidden"
- ? "Diese Antwort wurde ausgeblendet."
- : item.text}
-
- {item.slop_status !== "hidden" && item.audio_url && (
-
- )}
- {item.slop_status !== "hidden" && item.image_url && (
-
- )}
-
- );
- })}
-
+ {(replies.length > 0 || commenting) && (
+
+ {replies.length > visible.length && (
+ setShowAll(true)}
+ >
+ Alle {replies.length} Kommentare ansehen
+
+ )}
+
+ {visible.map((item) => (
+
+ ))}
+
+ {canComment && (
+ setReply(true)} />
+ )}
+
)}
+
+
+ {like.people.map((p) => (
+
+ setLikers(false)}>
+
+ {p.display_name}
+ @{p.username}
+
+
+ ))}
+
+
{me?.id === post.author_id
? "Über deine eigenen Beiträge stimmt deine Nachbarschaft ab."
- : "Ab 3 Slop-Stimmen Überhang wird ein Beitrag ausgeblendet. Eine Wertvoll-Mehrheit vergibt das Qualitätssiegel."}
+ : "Ab 3 Slop-Stimmen Überhang wird ein Beitrag ausgeblendet. Eine Wertvoll-Mehrheit vergibt das Qualitätssiegel. Ein Herz ist davon unabhängig."}
{reply && (
diff --git a/app/components/post-detail.tsx b/app/components/post-detail.tsx
new file mode 100644
index 0000000..94cfb63
--- /dev/null
+++ b/app/components/post-detail.tsx
@@ -0,0 +1,44 @@
+"use client";
+import Link from "next/link";
+import { useClub } from "./provider";
+import { Loading } from "./ui";
+import { PostCard } from "./post-card";
+/** Einzelansicht eines Beitrags, z. B. aus einem geteilten Link. Kommentare sind offen. */
+export function PostDetail({ id }: { id: string }) {
+ const { state, me, loading } = useClub();
+ if (loading) return
;
+ const found = state.posts.find((p) => p.id === id);
+ // Ein geteilter Kommentar öffnet das ganze Gespräch.
+ const post = found?.parent_id
+ ? state.posts.find((p) => p.id === found.parent_id)
+ : found;
+ if (!me || !post)
+ return (
+
+
+ {me
+ ? "Dieser Beitrag ist nicht (mehr) da."
+ : "Beiträge sind für Mitglieder da."}
+
+
+ {me
+ ? "Vielleicht wurde er gelöscht, oder er liegt in einem Raum, in dem du noch nicht Mitglied bist."
+ : "Melde dich an oder tritt mit deinem Goldenen Ticket ein, um das Gespräch zu sehen."}
+
+
+ {me ? "Zum Clubhaus" : "Mit Ticket eintreten"}
+
+
+ );
+ const room =
+ state.spaces.find((s) => s.id === post.space_id)?.name || "Große Lobby";
+ return (
+
+
+ ← Zurück zum Clubhaus
+
+
GESPRÄCH IN {room.toUpperCase()}
+
+
+ );
+}
diff --git a/app/components/profile.tsx b/app/components/profile.tsx
index 21b1ef0..1476300 100644
--- a/app/components/profile.tsx
+++ b/app/components/profile.tsx
@@ -2,18 +2,113 @@
import Link from "next/link";
import {
ArrowRight,
+ ExternalLink,
GitBranch,
+ Globe,
+ Lock,
+ MapPin,
Mic,
+ Settings,
Ticket,
UserRoundCheck,
+ Users,
} from "lucide-react";
import { useClub } from "./provider";
import { Avatar, Loading } from "./ui";
import { AudioPlayer } from "./audio-player";
import { PostCard } from "./post-card";
-export function ProfilePage({ username }: { username: string }) {
+import type { ProfileLink, PublicProfile, Visibility } from "@/lib/model";
+const VISIBILITY_LABEL: Record<
+ Visibility,
+ { text: string; Icon: typeof Users }
+> = {
+ members: { text: "Nur Mitglieder", Icon: Users },
+ public: { text: "Öffentlich", Icon: Globe },
+ hidden: { text: "Zurückhaltend", Icon: Lock },
+};
+function ProfileMeta({
+ pronouns,
+ location,
+}: {
+ pronouns: string;
+ location: string;
+}) {
+ if (!pronouns && !location) return null;
+ return (
+
+ {pronouns && {pronouns} }
+ {location && (
+
+
+ {location}
+
+ )}
+
+ );
+}
+function ProfileLinks({ links }: { links: ProfileLink[] }) {
+ const safe = links.filter((l) => /^https?:\/\//i.test(l.url));
+ if (!safe.length) return null;
+ return (
+
+ );
+}
+/** Was Besucher ohne Login sehen, wenn ein Mitglied sein Profil öffentlich gestellt hat. */
+function PublicProfileView({ profile }: { profile: PublicProfile }) {
+ return (
+
+
+
+ KEIN FILTER NÖTIG.
+
+
+
+
+
MENSCH IM CLUBHAUS
+
+ {profile.display_name}
+ .
+
+
@{profile.username}
+
+ {profile.bio &&
{profile.bio}
}
+
+
+
+ Dieses Profil ist öffentlich. Beiträge und Stimme bleiben im Club.
+
+
+ Mit Ticket eintreten
+
+
+
+
+
+ );
+}
+export function ProfilePage({
+ username,
+ publicProfile = null,
+}: {
+ username: string;
+ publicProfile?: PublicProfile | null;
+}) {
const { state, loading, me } = useClub();
const person = state.profiles.find((p) => p.username === username);
+ if (!person && publicProfile && (loading || !me))
+ return
;
if (loading) return
;
if (!person)
return (
@@ -39,6 +134,14 @@ export function ProfilePage({ username }: { username: string }) {
(p) => p.author_id === person.id && !p.parent_id,
);
const mine = person.id === me?.id;
+ const hearts = state.posts
+ .filter((p) => p.author_id === person.id)
+ .reduce((sum, p) => sum + p.likes_count, 0);
+ // Zurückhaltende Profile zeigen anderen Mitgliedern nur Name, Nutzername und Bild.
+ const restricted = person.visibility === "hidden" && !mine;
+ const showTree = !restricted && (person.show_trust_tree || mine);
+ const showPosts = !restricted && (person.show_posts || mine);
+ const visibility = VISIBILITY_LABEL[person.visibility];
return (
@@ -57,8 +160,46 @@ export function ProfilePage({ username }: { username: string }) {
.
@{person.username}
-
{person.bio}
- {person.voice_intro_url ? (
+ {!restricted && (
+
+
+ {posts.length}
+ {posts.length === 1 ? "Beitrag" : "Beiträge"}
+
+
+ {hearts}
+ {hearts === 1 ? "Herz" : "Herzen"} erhalten
+
+
+ )}
+ {mine && (
+
+
+
+ {visibility.text}
+
+
+
+ Profil bearbeiten
+
+
+ )}
+ {restricted ? (
+
+
+ {person.display_name} zeigt auf dem Profil nur Namen und Bild.
+
+ ) : (
+ <>
+
+ {person.bio &&
{person.bio}
}
+
+ >
+ )}
+ {restricted ? null : person.voice_intro_url ? (
)}
-
- {inviter ? (
-
-
+ {showTree && (
+
+ {inviter ? (
+
+
+
+ Eingeladen von @{inviter.username}
+
+
+
+ ) : (
- Eingeladen von @{inviter.username}
+
+ Gastgeber der ersten Stunde
-
-
- ) : (
-
-
- Gastgeber der ersten Stunde
-
- )}
-
+ )}
+
+ )}
-
-
-
- VERTRAUEN WÄCHST WEITER
-
-
- Gute Menschen kennen
-
- gute Menschen.
-
-
- {person.display_name} bürgt für {children.length}{" "}
- {children.length === 1 ? "Menschen" : "Menschen"} im Clubhaus.
-
-
- {children.map((child) => (
-
-
-
{child.display_name}
-
@{child.username}
-
+ {showTree && (
+
+
+
+ VERTRAUEN WÄCHST WEITER
+
+
+ Gute Menschen kennen
+
+ gute Menschen.
+
+
+ {person.display_name} bürgt für {children.length}{" "}
+ {children.length === 1 ? "Menschen" : "Menschen"} im Clubhaus.
+
+
+ {children.map((child) => (
+
+
+
{child.display_name}
+
@{child.username}
+
+
+ ))}
+
+ {!children.length && (
+
+ Hier beginnt bald ein neuer Ast im Vertrauens-Stammbaum.
+
+ )}
+ {mine && (
+
+
+ {person.invites_left} Goldene Tickets ansehen
+
- ))}
+ )}
+
+ )}
+ {showPosts && (
+
+
Gedanken von {person.display_name}
+ {posts.length ? (
+ posts.map((post) =>
)
+ ) : (
+
Der erste Beitrag kommt bestimmt.
+ )}
- {!children.length && (
-
- Hier beginnt bald ein neuer Ast im Vertrauens-Stammbaum.
-
- )}
- {mine && (
-
-
- {person.invites_left} Goldene Tickets ansehen
-
-
- )}
-
-
-
Gedanken von {person.display_name}
- {posts.length ? (
- posts.map((post) =>
)
- ) : (
-
Der erste Beitrag kommt bestimmt.
- )}
-
+ )}
);
}
diff --git a/app/components/provider.tsx b/app/components/provider.tsx
index ecb167b..19ddfdc 100644
--- a/app/components/provider.tsx
+++ b/app/components/provider.tsx
@@ -11,6 +11,7 @@ import { config } from "@/lib/config";
import { createDemoSnapshot, SPACE_ID } from "@/lib/seed";
import { createRepository } from "@/lib/repositories";
import type { ClubhouseRepository } from "@/lib/repositories/contract";
+import { DEFAULT_NOTIFICATIONS } from "@/lib/model";
import type { Profile, Snapshot } from "@/lib/model";
const empty: Snapshot = {
profiles: [],
@@ -19,7 +20,10 @@ const empty: Snapshot = {
posts: [],
tickets: [],
votes: [],
+ likes: [],
currentUserId: null,
+ email: null,
+ settings: { ...DEFAULT_NOTIFICATIONS },
waitlist: [],
isAdmin: false,
};
diff --git a/app/components/rich-text.tsx b/app/components/rich-text.tsx
new file mode 100644
index 0000000..b87535e
--- /dev/null
+++ b/app/components/rich-text.tsx
@@ -0,0 +1,48 @@
+"use client";
+import Link from "next/link";
+import { Fragment } from "react";
+import { displayUrl, tokenize } from "@/lib/links";
+import { useClub } from "./provider";
+/** Beitragstext mit klickbaren Links und @Erwähnungen. Kein HTML aus Nutzertext. */
+export function RichText({
+ text,
+ className,
+}: {
+ text: string;
+ className?: string;
+}) {
+ const { state } = useClub();
+ return (
+
+ {tokenize(text).map((part, i) => {
+ if (part.kind === "url")
+ return (
+
+ {displayUrl(part.href)}
+
+ );
+ if (
+ part.kind === "mention" &&
+ state.profiles.some((p) => p.username === part.username)
+ )
+ return (
+
+ {part.text}
+
+ );
+ return {part.text} ;
+ })}
+
+ );
+}
diff --git a/app/components/settings.tsx b/app/components/settings.tsx
new file mode 100644
index 0000000..49cb093
--- /dev/null
+++ b/app/components/settings.tsx
@@ -0,0 +1,809 @@
+"use client";
+import * as Tabs from "@radix-ui/react-tabs";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useEffect, useMemo, useRef, useState } from "react";
+import {
+ Bell,
+ Camera,
+ Eye,
+ Globe,
+ LogOut,
+ Mic,
+ Plus,
+ ShieldAlert,
+ Trash2,
+ UserRound,
+ Users,
+ X,
+ Lock,
+} from "lucide-react";
+import { useClub } from "./provider";
+import { Avatar, Loading } from "./ui";
+import { AudioPlayer } from "./audio-player";
+import { VoiceRecorder, type Recording } from "./voice-recorder";
+import { config } from "@/lib/config";
+import { prepareAvatar } from "@/lib/image";
+import { MAX_LINKS } from "@/lib/model";
+import type {
+ NotificationSettings,
+ Profile,
+ ProfileLink,
+ Visibility,
+} from "@/lib/model";
+
+type Draft = {
+ displayName: string;
+ bio: string;
+ location: string;
+ pronouns: string;
+ links: ProfileLink[];
+ visibility: Visibility;
+ showPosts: boolean;
+ showTrustTree: boolean;
+};
+function toDraft(p: Profile): Draft {
+ return {
+ displayName: p.display_name,
+ bio: p.bio,
+ location: p.location,
+ pronouns: p.pronouns,
+ links: p.links.map((l) => ({ ...l })),
+ visibility: p.visibility,
+ showPosts: p.show_posts,
+ showTrustTree: p.show_trust_tree,
+ };
+}
+const VISIBILITY_OPTIONS: {
+ value: Visibility;
+ title: string;
+ text: string;
+ Icon: typeof Users;
+}[] = [
+ {
+ value: "members",
+ title: "Nur Mitglieder",
+ text: "Alle Mitglieder von Humans Only sehen dein Profil. Ohne Login sieht niemand etwas. Das ist die Standard-Einstellung.",
+ Icon: Users,
+ },
+ {
+ value: "public",
+ title: "Öffentlich",
+ text: "Jeder mit dem Link sieht Namen, Bild, Bio, Ort, Pronomen und Links, auch ohne Login und in Suchmaschinen. Beiträge, Vertrauensbaum und deine Stimme bleiben im Club.",
+ Icon: Globe,
+ },
+ {
+ value: "hidden",
+ title: "Zurückhaltend",
+ text: "Andere Mitglieder sehen auf deinem Profil nur Namen, Nutzernamen und Bild. Deine Beiträge im Clubhaus bleiben für Mitglieder sichtbar.",
+ Icon: Lock,
+ },
+];
+
+export function SettingsPage() {
+ const { me, loading } = useClub();
+ if (loading) return ;
+ if (!me)
+ return (
+
+
Einstellungen sind für Mitglieder da.
+
+ Tritt mit deinem Goldenen Ticket ein, um dein Profil zu gestalten.
+
+
+ Mit Ticket eintreten
+
+
+ );
+ return ;
+}
+
+function SettingsBody({ me }: { me: Profile }) {
+ const { repository, refresh, notify } = useClub();
+ const [tab, setTab] = useState("profil");
+ const savedKey = JSON.stringify(toDraft(me));
+ const saved = useMemo(() => JSON.parse(savedKey) as Draft, [savedKey]);
+ const [draft, setDraft] = useState(saved);
+ // Neu laden (Fokus, Realtime) darf ungespeicherte Eingaben nicht überschreiben;
+ // erst wenn sich die gespeicherten Werte selbst ändern, wird das Formular neu aufgesetzt.
+ useEffect(() => setDraft(saved), [saved]);
+ const dirty = JSON.stringify(draft) !== savedKey;
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState("");
+ function set(key: K, value: Draft[K]) {
+ setDraft((d) => ({ ...d, [key]: value }));
+ }
+ async function save(event?: React.FormEvent) {
+ event?.preventDefault();
+ setSaving(true);
+ setError("");
+ try {
+ await repository().updateProfile(draft);
+ await refresh();
+ notify("Dein Profil ist gespeichert.");
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : "Das Profil konnte nicht gespeichert werden.",
+ );
+ } finally {
+ setSaving(false);
+ }
+ }
+ const saveBar = (
+
+
+ {dirty ? "Du hast ungespeicherte Änderungen." : "Alles gespeichert."}
+
+
+ {saving ? "Wird gespeichert …" : "Änderungen speichern"}
+
+
+ );
+ return (
+
+
+ ← Zurück zu deinem Profil
+
+
DEIN PLATZ IM CLUBHAUS
+
+ Einstellungen.
+
+
+
+
+
+ Profil
+
+
+
+ Privatsphäre
+
+
+
+ Mitteilungen
+
+
+
+ Konto
+
+
+
+
+
+
+
+
+ void save(e)}>
+
+ Wer darf dein Profil sehen?
+ {VISIBILITY_OPTIONS.map(({ value, title, text, Icon }) => (
+
+ set("visibility", value)}
+ />
+
+
+ {title}
+ {text}
+
+
+ ))}
+
+ {draft.visibility === "public" && (
+
+ Dein öffentliches Profil erreichst du unter{" "}
+ /u/{me.username} . Wähle „Nur Mitglieder“, um es
+ jederzeit wieder zu schließen.
+
+ )}
+
+ Auf deinem Profil zeigen
+
+ set("showPosts", e.target.checked)}
+ />
+
+ Meine Beiträge
+ Die Liste deiner Gedanken unter dem Profil.
+
+
+
+ set("showTrustTree", e.target.checked)}
+ />
+
+ Vertrauensbaum
+ Wer dich eingeladen hat und für wen du bürgst.
+
+
+
+
+ Diese Einstellungen bestimmen, was deine Profilseite zeigt.
+ Beiträge, die du im Clubhaus schreibst, sehen die Mitglieder des
+ jeweiligen Raums weiterhin.
+
+ {error && (
+
+ {error}
+
+ )}
+ {saveBar}
+
+ So sehen Mitglieder dein Profil
+
+
+
+
+
+
+
+
+
+
+
+ );
+}
+
+function AvatarEditor({ me }: { me: Profile }) {
+ const { repository, refresh, notify, report } = useClub();
+ const input = useRef(null);
+ const [busy, setBusy] = useState(false);
+ async function pick(event: React.ChangeEvent) {
+ const file = event.target.files?.[0];
+ event.target.value = "";
+ if (!file) return;
+ setBusy(true);
+ try {
+ const blob = await prepareAvatar(file);
+ const repo = repository();
+ const path = await repo.upload("avatars", blob);
+ await repo.setAvatar(path);
+ await refresh();
+ notify("Dein Profilbild ist aktualisiert.");
+ } catch (err) {
+ report(err);
+ } finally {
+ setBusy(false);
+ }
+ }
+ async function remove() {
+ setBusy(true);
+ try {
+ await repository().setAvatar(null);
+ await refresh();
+ notify("Dein Profilbild ist entfernt.");
+ } catch (err) {
+ report(err);
+ } finally {
+ setBusy(false);
+ }
+ }
+ return (
+
+
+
+
Profilbild
+
+ JPG, PNG oder WebP. Wir schneiden es quadratisch zu.
+
+
+ void pick(e)}
+ />
+ input.current?.click()}
+ >
+
+ {busy
+ ? "Einen Moment …"
+ : me.avatar_url
+ ? "Bild ändern"
+ : "Bild hochladen"}
+
+ {me.avatar_url && (
+ void remove()}
+ >
+ Bild entfernen
+
+ )}
+
+
+
+ );
+}
+
+/** Die Stimme ist das Herz von Humans Only: hier lässt sie sich neu aufnehmen. */
+function VoiceIntroEditor({ me }: { me: Profile }) {
+ const { repository, refresh, notify, report } = useClub();
+ const [editing, setEditing] = useState(false);
+ const [recording, setRecording] = useState(null);
+ const [active, setActive] = useState(false);
+ const [busy, setBusy] = useState(false);
+ async function save() {
+ if (!recording) return;
+ setBusy(true);
+ try {
+ const repo = repository();
+ const path = await repo.upload("voice-intros", recording.blob);
+ await repo.setVoiceIntro(path, recording.duration);
+ await refresh();
+ setEditing(false);
+ setRecording(null);
+ notify("Deine neue Vorstellung ist gespeichert.");
+ } catch (err) {
+ report(err);
+ } finally {
+ setBusy(false);
+ }
+ }
+ return (
+
+
Deine Stimme
+
+ Bis zu 15 Sekunden: So hören die anderen, wer hinter deinem Profil
+ steckt.
+
+ {me.voice_intro_url && !editing && (
+
+ )}
+ {editing ? (
+ <>
+
+
+ void save()}
+ >
+ {busy ? "Wird gespeichert …" : "Neue Vorstellung speichern"}
+
+ {
+ setEditing(false);
+ setRecording(null);
+ }}
+ >
+ Abbrechen
+
+
+ >
+ ) : (
+
+ setEditing(true)}
+ >
+
+ {me.voice_intro_url ? "Neu aufnehmen" : "Vorstellung aufnehmen"}
+
+
+ )}
+
+ );
+}
+
+const NOTIFICATION_OPTIONS: {
+ key: keyof NotificationSettings;
+ title: string;
+ text: string;
+}[] = [
+ {
+ key: "notify_replies",
+ title: "Antworten auf meine Beiträge",
+ text: "Wenn jemand auf einen deiner Gedanken antwortet.",
+ },
+ {
+ key: "notify_ticket_redeemed",
+ title: "Ein Goldenes Ticket wurde eingelöst",
+ text: "Wenn ein Mensch durch deine Einladung ins Clubhaus kommt.",
+ },
+ {
+ key: "notify_news",
+ title: "Neuigkeiten aus dem Clubhaus",
+ text: "Gelegentlich: neue Räume und Funktionen. Aus, bis du es einschaltest.",
+ },
+];
+
+function NotificationsForm() {
+ const { state, repository, refresh, notify } = useClub();
+ const key = JSON.stringify(state.settings);
+ const saved = useMemo(() => JSON.parse(key) as NotificationSettings, [key]);
+ const [draft, setDraft] = useState(saved);
+ useEffect(() => setDraft(saved), [saved]);
+ const dirty = JSON.stringify(draft) !== key;
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState("");
+ async function save(event: React.FormEvent) {
+ event.preventDefault();
+ setSaving(true);
+ setError("");
+ try {
+ await repository().updateNotifications(draft);
+ await refresh();
+ notify("Deine Mitteilungs-Einstellungen sind gespeichert.");
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : "Das konnte nicht gespeichert werden.",
+ );
+ } finally {
+ setSaving(false);
+ }
+ }
+ return (
+ void save(e)}>
+
+ Per E-Mail benachrichtigen bei
+ {NOTIFICATION_OPTIONS.map(({ key: id, title, text }) => (
+
+
+ setDraft((d) => ({ ...d, [id]: e.target.checked }))
+ }
+ />
+
+ {title}
+ {text}
+
+
+ ))}
+
+
+ Der automatische Versand dieser Mitteilungen ist noch in Vorbereitung.
+ Deine Auswahl wird schon jetzt gespeichert und gilt, sobald er startet.
+
+ {error && (
+
+ {error}
+
+ )}
+
+
+ {dirty ? "Du hast ungespeicherte Änderungen." : "Alles gespeichert."}
+
+
+ {saving ? "Wird gespeichert …" : "Änderungen speichern"}
+
+
+
+ );
+}
+
+function AccountPanel({ me }: { me: Profile }) {
+ const { state, repository, refresh, notify, report } = useClub();
+ const router = useRouter();
+ const [email, setEmail] = useState("");
+ const [emailBusy, setEmailBusy] = useState(false);
+ const [emailError, setEmailError] = useState("");
+ const [confirming, setConfirming] = useState(false);
+ const [typed, setTyped] = useState("");
+ const [deleting, setDeleting] = useState(false);
+ const [deleteError, setDeleteError] = useState("");
+ async function changeEmail(event: React.FormEvent) {
+ event.preventDefault();
+ setEmailBusy(true);
+ setEmailError("");
+ try {
+ await repository().requestEmailChange(email);
+ setEmail("");
+ await refresh();
+ notify(
+ config.mode === "demo"
+ ? "Demo: Deine E-Mail-Adresse ist geändert."
+ : "Wir haben dir eine Bestätigung geschickt. Die Adresse ändert sich erst, wenn du den Link darin öffnest.",
+ );
+ } catch (err) {
+ setEmailError(
+ err instanceof Error
+ ? err.message
+ : "Die Adresse konnte nicht geändert werden.",
+ );
+ } finally {
+ setEmailBusy(false);
+ }
+ }
+ async function signOut() {
+ try {
+ await repository().signOut();
+ await refresh();
+ router.push("/invite");
+ } catch (err) {
+ report(err);
+ }
+ }
+ async function deleteAccount() {
+ setDeleting(true);
+ setDeleteError("");
+ try {
+ await repository().deleteAccount();
+ await refresh();
+ notify("Dein Konto ist gelöscht. Danke, dass du dabei warst.");
+ router.push("/invite");
+ } catch (err) {
+ setDeleteError(
+ err instanceof Error
+ ? err.message
+ : "Das Konto konnte nicht gelöscht werden.",
+ );
+ } finally {
+ setDeleting(false);
+ }
+ }
+ return (
+
+
+ Anmeldung
+
+ Du bist angemeldet als {state.email || "—"}
+
+ void changeEmail(e)}>
+ Neue E-Mail-Adresse
+
+ setEmail(e.target.value)}
+ required
+ />
+
+ {emailBusy ? "Wird gesendet …" : "Ändern"}
+
+
+ {emailError && (
+
+ {emailError}
+
+ )}
+
+ void signOut()}>
+
+ Abmelden
+
+
+
+ Konto löschen
+
+ Dein Profil, deine Beiträge samt den Antworten darauf, deine Stimmen
+ und deine noch offenen Goldenen Tickets werden unwiderruflich
+ gelöscht. Das lässt sich nicht rückgängig machen.
+
+ {!confirming ? (
+ setConfirming(true)}
+ >
+
+ Konto löschen …
+
+ ) : (
+
+
+ Tippe zur Bestätigung deinen Nutzernamen: {me.username}
+
+
+ setTyped(e.target.value)}
+ autoCapitalize="none"
+ autoComplete="off"
+ />
+ void deleteAccount()}
+ >
+ {deleting ? "Wird gelöscht …" : "Endgültig löschen"}
+
+
+
{
+ setConfirming(false);
+ setTyped("");
+ }}
+ >
+ Abbrechen
+
+
+ )}
+ {deleteError && (
+
+ {deleteError}
+
+ )}
+
+
+ );
+}
diff --git a/app/components/shell.tsx b/app/components/shell.tsx
index 52096a9..acede73 100644
--- a/app/components/shell.tsx
+++ b/app/components/shell.tsx
@@ -15,6 +15,7 @@ import {
Zap,
RotateCcw,
ShieldCheck,
+ Settings,
} from "lucide-react";
import { useClub } from "./provider";
import { config } from "@/lib/config";
@@ -62,6 +63,9 @@ export function Shell({ children }: { children: React.ReactNode }) {
{ href: "/", label: "Das Clubhaus", Icon: Home },
{ href: "/tickets", label: "Goldene Tickets", Icon: Ticket },
{ href: profile, label: "Mein Profil", Icon: UserRound },
+ ...(me
+ ? [{ href: "/einstellungen", label: "Einstellungen", Icon: Settings }]
+ : []),
...(state.isAdmin
? [{ href: "/admin", label: "Warteliste", Icon: ShieldCheck }]
: []),
@@ -209,6 +213,12 @@ export function Shell({ children }: { children: React.ReactNode }) {
Warteliste{pending > 0 ? ` (${pending})` : ""}
)}
+ {me && (
+
+
+ Einstellungen
+
+ )}
{me && (
void signOut()}>
diff --git a/app/components/ui.tsx b/app/components/ui.tsx
index eafebdb..dfdfb1a 100644
--- a/app/components/ui.tsx
+++ b/app/components/ui.tsx
@@ -27,7 +27,7 @@ export function Avatar({
profile,
size = "normal",
}: {
- profile: Profile;
+ profile: Pick;
size?: "small" | "normal" | "large";
}) {
return (
diff --git a/app/lib/auth-callback.ts b/app/lib/auth-callback.ts
index c5057ca..06b30d2 100644
--- a/app/lib/auth-callback.ts
+++ b/app/lib/auth-callback.ts
@@ -2,15 +2,21 @@ import { NextResponse } from "next/server";
type ExchangeCode = (code: string) => Promise<{ error: unknown }>;
+/** Nur feste, lokale Ziele — nie eine frei übergebene Adresse (Open Redirect). */
+const NEXT_TARGETS = ["/einstellungen"];
+
export async function handleAuthCallback(
request: Request,
exchangeCode?: ExchangeCode,
) {
- const code = new URL(request.url).searchParams.get("code");
+ const params = new URL(request.url).searchParams;
+ const code = params.get("code");
+ const next = params.get("next");
let location = "/invite?auth_error=1";
if (code && exchangeCode) {
const { error } = await exchangeCode(code);
- if (!error) location = "/onboarding";
+ if (!error)
+ location = next && NEXT_TARGETS.includes(next) ? next : "/onboarding";
}
// Keep redirects on the browser's origin, even behind an internal proxy host.
return new NextResponse(null, {
diff --git a/app/lib/image.ts b/app/lib/image.ts
new file mode 100644
index 0000000..9ea9f67
--- /dev/null
+++ b/app/lib/image.ts
@@ -0,0 +1,56 @@
+const ACCEPTED = ["image/jpeg", "image/png", "image/webp"];
+const MAX_INPUT_BYTES = 20 * 1024 * 1024;
+
+function toBlob(canvas: HTMLCanvasElement, type: string, quality: number) {
+ return new Promise((resolve) =>
+ canvas.toBlob(resolve, type, quality),
+ );
+}
+
+/**
+ * Schneidet ein Profilbild mittig quadratisch zu und verkleinert es (max. 512 px).
+ * So bleibt jeder Upload weit unter dem 5-MB-Limit des Buckets, auch bei Handyfotos.
+ * Nur im Browser nutzbar.
+ */
+export async function prepareAvatar(file: File, size = 512): Promise {
+ if (!ACCEPTED.includes(file.type))
+ throw new Error("Bitte nutze ein JPG-, PNG- oder WebP-Bild.");
+ if (file.size > MAX_INPUT_BYTES)
+ throw new Error(
+ "Das Bild ist größer als 20 MB. Bitte wähle ein kleineres.",
+ );
+ let bitmap: ImageBitmap;
+ try {
+ bitmap = await createImageBitmap(file, { imageOrientation: "from-image" });
+ } catch {
+ throw new Error("Dieses Bild konnte nicht gelesen werden.");
+ }
+ try {
+ const side = Math.min(bitmap.width, bitmap.height);
+ const target = Math.min(size, side);
+ const canvas = document.createElement("canvas");
+ canvas.width = target;
+ canvas.height = target;
+ const context = canvas.getContext("2d");
+ if (!context)
+ throw new Error("Dieses Bild konnte nicht verarbeitet werden.");
+ context.drawImage(
+ bitmap,
+ (bitmap.width - side) / 2,
+ (bitmap.height - side) / 2,
+ side,
+ side,
+ 0,
+ 0,
+ target,
+ target,
+ );
+ const webp = await toBlob(canvas, "image/webp", 0.9);
+ if (webp && webp.type === "image/webp") return webp;
+ const jpeg = await toBlob(canvas, "image/jpeg", 0.9);
+ if (jpeg) return jpeg;
+ throw new Error("Dieses Bild konnte nicht verarbeitet werden.");
+ } finally {
+ bitmap.close();
+ }
+}
diff --git a/app/lib/link-preview-server.ts b/app/lib/link-preview-server.ts
new file mode 100644
index 0000000..9c053ff
--- /dev/null
+++ b/app/lib/link-preview-server.ts
@@ -0,0 +1,213 @@
+import { lookup as dnsLookup } from "node:dns";
+import http from "node:http";
+import https from "node:https";
+import type { LookupFunction } from "node:net";
+import zlib from "node:zlib";
+import {
+ decodeEntities,
+ detectEmbed,
+ isPrivateAddress,
+ parsePreview,
+ safeHref,
+ type LinkPreview,
+} from "./links";
+
+const TIMEOUT_MS = 5000;
+const MAX_BYTES = 600_000;
+const MAX_REDIRECTS = 3;
+const TTL_MS = 6 * 60 * 60 * 1000;
+const cache = new Map();
+
+/**
+ * DNS-Auflösung, die private, Loopback- und Link-Local-Ziele ablehnt. Weil Node genau
+ * diese Adresse für die Verbindung verwendet, hilft auch DNS-Rebinding nicht weiter.
+ */
+const safeLookup: LookupFunction = (hostname, options, callback) => {
+ dnsLookup(hostname, { ...options, all: true }, (err, addresses) => {
+ if (err) return callback(err, "", 0);
+ const list = addresses as unknown as { address: string; family: number }[];
+ const ok = list.filter((a) => !isPrivateAddress(a.address));
+ if (!ok.length || ok.length !== list.length)
+ return callback(
+ Object.assign(new Error("Blocked address"), { code: "EBLOCKED" }),
+ "",
+ 0,
+ );
+ if (options.all) return callback(null, ok as never);
+ callback(null, ok[0].address, ok[0].family);
+ });
+};
+
+type Fetched = { url: string; type: string; body: string };
+
+function fetchOnce(target: URL): Promise {
+ return new Promise((resolve, reject) => {
+ const client = target.protocol === "https:" ? https : http;
+ const req = client.request(
+ target,
+ {
+ method: "GET",
+ lookup: safeLookup,
+ timeout: TIMEOUT_MS,
+ headers: {
+ // Viele Seiten liefern Open-Graph-Daten nur an bekannte Vorschau-Bots aus.
+ "user-agent":
+ "Mozilla/5.0 (compatible; HumansOnlyLinkPreview/1.0; +https://humans-only.de)",
+ accept: "text/html,application/xhtml+xml,application/json;q=0.9",
+ "accept-language": "de-DE,de;q=0.9,en;q=0.7",
+ "accept-encoding": "gzip, deflate, br",
+ },
+ },
+ (res) => {
+ const status = res.statusCode || 0;
+ if (status >= 300 && status < 400 && res.headers.location) {
+ res.resume();
+ return resolve({
+ redirect: new URL(res.headers.location, target).href,
+ });
+ }
+ const type = String(res.headers["content-type"] || "").toLowerCase();
+ if (
+ status < 200 ||
+ status >= 300 ||
+ !(type.includes("html") || type.includes("json"))
+ ) {
+ res.resume();
+ return reject(new Error(`Unusable response ${status} ${type}`));
+ }
+ const encoding = String(res.headers["content-encoding"] || "");
+ const stream =
+ encoding === "gzip"
+ ? res.pipe(zlib.createGunzip())
+ : encoding === "br"
+ ? res.pipe(zlib.createBrotliDecompress())
+ : encoding === "deflate"
+ ? res.pipe(zlib.createInflate())
+ : res;
+ const chunks: Buffer[] = [];
+ let size = 0;
+ let done = false;
+ const finish = () => {
+ if (done) return;
+ done = true;
+ const raw = Buffer.concat(chunks);
+ const charset = type.match(/charset=([\w-]+)/)?.[1];
+ let body: string;
+ try {
+ body = new TextDecoder(charset || "utf-8").decode(raw);
+ } catch {
+ body = raw.toString("utf8");
+ }
+ resolve({ url: target.href, type, body });
+ };
+ stream.on("data", (chunk: Buffer) => {
+ size += chunk.length;
+ chunks.push(chunk);
+ // Der reicht; wir lesen nie ganze Seiten.
+ if (size >= MAX_BYTES) {
+ finish();
+ req.destroy();
+ }
+ });
+ stream.on("end", finish);
+ stream.on("error", (err) => (done ? undefined : reject(err)));
+ },
+ );
+ req.on("timeout", () => req.destroy(new Error("Timeout")));
+ req.on("error", reject);
+ req.end();
+ });
+}
+
+function allowedTarget(raw: string) {
+ const href = safeHref(raw);
+ if (!href) return null;
+ const url = new URL(href);
+ if (url.port && url.port !== "80" && url.port !== "443") return null;
+ if (/^[\d.]+$/.test(url.hostname) || url.hostname.includes(":")) {
+ if (isPrivateAddress(url.hostname)) return null;
+ }
+ if (/(^|\.)(localhost|local|internal|lan|home|arpa)$/i.test(url.hostname))
+ return null;
+ return url;
+}
+
+async function fetchPage(raw: string): Promise {
+ let current = allowedTarget(raw);
+ for (let hop = 0; current && hop <= MAX_REDIRECTS; hop++) {
+ const result = await fetchOnce(current);
+ if (!("redirect" in result)) return result;
+ current = allowedTarget(result.redirect);
+ }
+ throw new Error("Blocked or too many redirects");
+}
+
+/** Spotify und YouTube liefern über oEmbed verlässliche Titel und Cover. */
+async function oembed(href: string): Promise | null> {
+ const embed = detectEmbed(href);
+ if (!embed) return null;
+ const endpoint =
+ embed.provider === "spotify"
+ ? `https://open.spotify.com/oembed?url=${encodeURIComponent(href)}`
+ : `https://www.youtube.com/oembed?format=json&url=${encodeURIComponent(href)}`;
+ try {
+ const page = await fetchPage(endpoint);
+ const data = JSON.parse(page.body) as {
+ title?: string;
+ author_name?: string;
+ thumbnail_url?: string;
+ provider_name?: string;
+ };
+ const image =
+ data.thumbnail_url && /^https:\/\//.test(data.thumbnail_url)
+ ? data.thumbnail_url
+ : null;
+ return {
+ title: decodeEntities(data.title || "").slice(0, 140),
+ description: decodeEntities(data.author_name || "").slice(0, 240),
+ image,
+ siteName: embed.provider === "spotify" ? "Spotify" : "YouTube",
+ };
+ } catch {
+ return null;
+ }
+}
+
+export async function loadLinkPreview(raw: string) {
+ const target = allowedTarget(raw);
+ if (!target) return null;
+ const key = target.href;
+ const hit = cache.get(key);
+ if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
+ let value: LinkPreview | null = null;
+ const embed = detectEmbed(key);
+ const fromOembed = embed ? await oembed(key) : null;
+ // Die Seite selbst liefert Cover und Beschreibung, wenn oEmbed sie nicht hat (Spotify).
+ let page: LinkPreview | null = null;
+ if (!fromOembed?.image) {
+ try {
+ const fetched = await fetchPage(key);
+ if (fetched.type.includes("html"))
+ page = parsePreview(fetched.body, fetched.url);
+ } catch {
+ page = null;
+ }
+ }
+ if (fromOembed?.title || page || embed)
+ value = {
+ // Weiterleitungen dürfen weder Adresse noch Einbettung umbiegen.
+ url: key,
+ title: fromOembed?.title || page?.title || "",
+ description: page?.description || fromOembed?.description || "",
+ image: fromOembed?.image || page?.image || null,
+ siteName:
+ fromOembed?.siteName ||
+ (embed ? (embed.provider === "spotify" ? "Spotify" : "YouTube") : "") ||
+ page?.siteName ||
+ "",
+ embed,
+ };
+ if (cache.size > 500) cache.delete(cache.keys().next().value!);
+ cache.set(key, { at: Date.now(), value });
+ return value;
+}
diff --git a/app/lib/links.ts b/app/lib/links.ts
new file mode 100644
index 0000000..b1b2f60
--- /dev/null
+++ b/app/lib/links.ts
@@ -0,0 +1,295 @@
+/**
+ * Links in Beiträgen: Erkennung im Text, Einbettungen (Spotify, YouTube) und das
+ * Auslesen von Vorschau-Metadaten aus HTML. Alles hier ist rein und läuft in Browser,
+ * Server und Tests gleich. Der eigentliche Netzabruf liegt in link-preview-server.ts.
+ */
+export type Segment =
+ | { kind: "text"; text: string }
+ | { kind: "url"; text: string; href: string }
+ | { kind: "mention"; text: string; username: string };
+
+export type Embed = {
+ provider: "spotify" | "youtube";
+ /** iframe-Quelle, ausschließlich aus geprüften IDs gebaut. */
+ src: string;
+ /** Höhe des Players in Pixeln (YouTube nutzt 16:9 statt fester Höhe). */
+ height: number | null;
+};
+
+export type LinkPreview = {
+ url: string;
+ title: string;
+ description: string;
+ image: string | null;
+ siteName: string;
+ embed: Embed | null;
+};
+
+const TOKEN =
+ /(https?:\/\/[^\s<>"'`]+|www\.[a-z0-9-]+(?:\.[a-z0-9-]+)+[^\s<>"'`]*)|(^|[^\w@/.])@([a-z0-9_]{3,24})\b/gi;
+const TRAILING = /[.,;:!?…»«“”"'’\]}>]/;
+const count = (text: string, ch: string) => text.split(ch).length - 1;
+
+/** Schneidet Satzzeichen am Ende ab, behält aber ausgeglichene Klammern (Wikipedia-Links). */
+function trimUrl(raw: string) {
+ let url = raw;
+ while (url.length) {
+ const ch = url[url.length - 1];
+ if (ch === ")" ? count(url, "(") < count(url, ")") : TRAILING.test(ch))
+ url = url.slice(0, -1);
+ else break;
+ }
+ return url;
+}
+
+/** Normalisiert auf eine sichere http(s)-Adresse oder null. */
+export function safeHref(raw: string) {
+ const withScheme = /^https?:\/\//i.test(raw) ? raw : `https://${raw}`;
+ try {
+ const url = new URL(withScheme);
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
+ if (!url.hostname.includes(".") || url.username || url.password)
+ return null;
+ return url.href;
+ } catch {
+ return null;
+ }
+}
+
+/** Zerlegt Beitragstext in Text, Links und @Erwähnungen. */
+export function tokenize(text: string): Segment[] {
+ const out: Segment[] = [];
+ let last = 0;
+ const push = (t: string) => {
+ if (!t) return;
+ const prev = out[out.length - 1];
+ if (prev?.kind === "text") prev.text += t;
+ else out.push({ kind: "text", text: t });
+ };
+ for (const match of text.matchAll(TOKEN)) {
+ const start = match.index ?? 0;
+ if (match[1]) {
+ const raw = trimUrl(match[1]);
+ const href = safeHref(raw);
+ push(text.slice(last, start));
+ if (href) out.push({ kind: "url", text: raw, href });
+ else push(raw);
+ last = start + raw.length;
+ } else if (match[3]) {
+ const lead = match[2] || "";
+ push(text.slice(last, start) + lead);
+ out.push({
+ kind: "mention",
+ text: `@${match[3]}`,
+ username: match[3].toLowerCase(),
+ });
+ last = start + lead.length + 1 + match[3].length;
+ }
+ }
+ push(text.slice(last));
+ return out;
+}
+
+export function extractUrls(text: string) {
+ return tokenize(text)
+ .filter((s): s is Extract => s.kind === "url")
+ .map((s) => s.href);
+}
+
+/** Erste Adresse im Text: sie bekommt die Vorschau. */
+export function firstUrl(text: string) {
+ return extractUrls(text)[0] || null;
+}
+
+/** Kurze Anzeige für lange Links: Host + gekürzter Pfad. */
+export function displayUrl(href: string, max = 48) {
+ try {
+ const url = new URL(href);
+ const shown =
+ url.hostname.replace(/^www\./, "") +
+ (url.pathname === "/" ? "" : url.pathname) +
+ url.search;
+ return shown.length > max ? `${shown.slice(0, max - 1)}…` : shown;
+ } catch {
+ return href;
+ }
+}
+
+const SPOTIFY_TYPES = [
+ "track",
+ "album",
+ "playlist",
+ "episode",
+ "show",
+ "artist",
+];
+
+/** Erkennt Spotify- und YouTube-Links und baut daraus eine feste Player-Adresse. */
+export function detectEmbed(href: string): Embed | null {
+ let url: URL;
+ try {
+ url = new URL(href);
+ } catch {
+ return null;
+ }
+ const host = url.hostname.replace(/^www\./, "").toLowerCase();
+ if (host === "open.spotify.com") {
+ const parts = url.pathname.split("/").filter(Boolean);
+ // Lokalisierte Pfade wie /intl-de/track/… überspringen.
+ if (parts[0]?.startsWith("intl-")) parts.shift();
+ if (parts[0] === "embed") parts.shift();
+ const [type, id] = parts;
+ if (SPOTIFY_TYPES.includes(type) && /^[A-Za-z0-9]{10,40}$/.test(id || ""))
+ return {
+ provider: "spotify",
+ src: `https://open.spotify.com/embed/${type}/${id}`,
+ height: type === "track" || type === "episode" ? 152 : 352,
+ };
+ return null;
+ }
+ let video: string | null = null;
+ if (host === "youtu.be") video = url.pathname.slice(1).split("/")[0];
+ else if (host === "youtube.com" || host === "m.youtube.com") {
+ if (url.pathname === "/watch") video = url.searchParams.get("v");
+ else {
+ const m = url.pathname.match(/^\/(?:shorts|embed|live)\/([^/]+)/);
+ video = m?.[1] || null;
+ }
+ }
+ if (video && /^[A-Za-z0-9_-]{11}$/.test(video)) {
+ const t = url.searchParams.get("t") || url.searchParams.get("start");
+ const start = t && /^\d+s?$/.test(t) ? `?start=${parseInt(t, 10)}` : "";
+ return {
+ provider: "youtube",
+ src: `https://www.youtube-nocookie.com/embed/${video}${start}`,
+ height: null,
+ };
+ }
+ return null;
+}
+
+const ENTITIES: Record = {
+ amp: "&",
+ lt: "<",
+ gt: ">",
+ quot: '"',
+ apos: "'",
+ nbsp: " ",
+ auml: "ä",
+ ouml: "ö",
+ uuml: "ü",
+ Auml: "Ä",
+ Ouml: "Ö",
+ Uuml: "Ü",
+ szlig: "ß",
+ hellip: "…",
+ ndash: "–",
+ mdash: "—",
+};
+export function decodeEntities(text: string) {
+ return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (all, code: string) => {
+ if (code[0] === "#") {
+ const n =
+ code[1] === "x" || code[1] === "X"
+ ? parseInt(code.slice(2), 16)
+ : parseInt(code.slice(1), 10);
+ return Number.isFinite(n) && n > 0 && n < 0x110000
+ ? String.fromCodePoint(n)
+ : all;
+ }
+ return ENTITIES[code] ?? all;
+ });
+}
+
+function clean(text: string | undefined, max: number) {
+ if (!text) return "";
+ const t = decodeEntities(text).replace(/\s+/g, " ").trim();
+ return t.length > max ? `${t.slice(0, max - 1)}…` : t;
+}
+
+function attr(tag: string, name: string) {
+ const m = tag.match(
+ new RegExp(`\\s${name}\\s*=\\s*("([^"]*)"|'([^']*)'|([^\\s"'>]+))`, "i"),
+ );
+ return m ? (m[2] ?? m[3] ?? m[4] ?? "") : undefined;
+}
+
+/** Liest Open-Graph-, Twitter- und Standard-Metadaten aus dem einer Seite. */
+export function parsePreview(html: string, pageUrl: string): LinkPreview {
+ const head = html.slice(0, 300_000);
+ const meta = new Map();
+ for (const [tag] of head.matchAll(/ ]*>/gi)) {
+ const key = (attr(tag, "property") || attr(tag, "name") || "")
+ .toLowerCase()
+ .trim();
+ const content = attr(tag, "content");
+ if (key && content !== undefined && !meta.has(key)) meta.set(key, content);
+ }
+ const titleTag = head.match(/]*>([\s\S]*?)<\/title>/i)?.[1];
+ const imageRaw =
+ meta.get("og:image:secure_url") ||
+ meta.get("og:image") ||
+ meta.get("twitter:image") ||
+ meta.get("twitter:image:src");
+ let image: string | null = null;
+ if (imageRaw) {
+ try {
+ const resolved = new URL(decodeEntities(imageRaw.trim()), pageUrl);
+ // Nur https: kein Mixed Content, keine data:/javascript:-Adressen.
+ if (resolved.protocol === "https:") image = resolved.href;
+ } catch {}
+ }
+ let host = pageUrl;
+ try {
+ host = new URL(pageUrl).hostname.replace(/^www\./, "");
+ } catch {}
+ return {
+ url: pageUrl,
+ title: clean(
+ meta.get("og:title") || meta.get("twitter:title") || titleTag,
+ 140,
+ ),
+ description: clean(
+ meta.get("og:description") ||
+ meta.get("twitter:description") ||
+ meta.get("description"),
+ 240,
+ ),
+ image,
+ siteName: clean(meta.get("og:site_name"), 60) || host,
+ embed: detectEmbed(pageUrl),
+ };
+}
+
+/** IPv4/IPv6-Adressen, die nie von einem öffentlichen Vorschau-Abruf erreicht werden dürfen. */
+export function isPrivateAddress(address: string) {
+ const ip = address.toLowerCase().replace(/^\[|\]$/g, "");
+ const mapped = ip.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
+ if (mapped) return isPrivateAddress(mapped[1]);
+ const v4 = ip.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
+ if (v4) {
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
+ return (
+ a === 0 ||
+ a === 10 ||
+ a === 127 ||
+ (a === 100 && b >= 64 && b <= 127) ||
+ (a === 169 && b === 254) ||
+ (a === 172 && b >= 16 && b <= 31) ||
+ (a === 192 && b === 168) ||
+ (a === 192 && b === 0) ||
+ (a === 198 && (b === 18 || b === 19)) ||
+ a >= 224
+ );
+ }
+ if (!ip.includes(":")) return true; // Unbekanntes Format: lieber sperren.
+ return (
+ ip === "::" ||
+ ip === "::1" ||
+ /^f[cd]/.test(ip) ||
+ /^fe[89ab]/.test(ip) ||
+ /^ff/.test(ip) ||
+ ip.startsWith("64:ff9b:") ||
+ ip.startsWith("2001:db8")
+ );
+}
diff --git a/app/lib/model.ts b/app/lib/model.ts
index d908a00..a51e962 100644
--- a/app/lib/model.ts
+++ b/app/lib/model.ts
@@ -1,15 +1,20 @@
export type Vote = "valuable" | "slop";
export type SlopStatus =
- | "clean"
- | "under_review"
- | "hidden"
- | "valuable_verified";
+ "clean" | "under_review" | "hidden" | "valuable_verified";
+export type Visibility = "members" | "public" | "hidden";
+export type ProfileLink = { label: string; url: string };
export type Profile = {
id: string;
username: string;
display_name: string;
bio: string;
avatar_url: string | null;
+ location: string;
+ pronouns: string;
+ links: ProfileLink[];
+ visibility: Visibility;
+ show_posts: boolean;
+ show_trust_tree: boolean;
voice_intro_url: string | null;
voice_duration_sec: number | null;
invited_by_id: string | null;
@@ -56,6 +61,13 @@ export type Post = {
slop_status: SlopStatus;
valuable_votes_count: number;
slop_votes_count: number;
+ /** Anzahl „Gefällt mir“. Getrennt von der Community-Prüfung. */
+ likes_count: number;
+ created_at: string;
+};
+export type PostLike = {
+ post_id: string;
+ user_id: string;
created_at: string;
};
export type ContentVote = {
@@ -78,6 +90,37 @@ export type WaitlistEntry = {
invited_at: string | null;
invite_count: number;
};
+export type NotificationSettings = {
+ notify_replies: boolean;
+ notify_ticket_redeemed: boolean;
+ notify_news: boolean;
+};
+export const DEFAULT_NOTIFICATIONS: NotificationSettings = {
+ notify_replies: true,
+ notify_ticket_redeemed: true,
+ notify_news: false,
+};
+export type ProfileUpdate = {
+ displayName: string;
+ bio: string;
+ location: string;
+ pronouns: string;
+ links: ProfileLink[];
+ visibility: Visibility;
+ showPosts: boolean;
+ showTrustTree: boolean;
+};
+/** Das, was ohne Login unter /u/name sichtbar ist (nur bei visibility = public). */
+export type PublicProfile = {
+ username: string;
+ display_name: string;
+ bio: string;
+ avatar_url: string | null;
+ location: string;
+ pronouns: string;
+ links: ProfileLink[];
+ member_since: string;
+};
export type Snapshot = {
profiles: Profile[];
spaces: Space[];
@@ -85,7 +128,13 @@ export type Snapshot = {
posts: Post[];
tickets: Ticket[];
votes: ContentVote[];
+ /** Likes zu den geladenen Beiträgen (alle Personen, nicht nur die eigenen). */
+ likes: PostLike[];
currentUserId: string | null;
+ /** E-Mail-Adresse des angemeldeten Kontos. */
+ email: string | null;
+ /** Eigene Benachrichtigungs-Einstellungen. */
+ settings: NotificationSettings;
/** Nur für Admins gefüllt; für alle anderen leer. */
waitlist: WaitlistEntry[];
isAdmin: boolean;
@@ -157,3 +206,96 @@ export function validateWaitlist(name: string, email: string) {
throw new Error("Bitte gib eine gültige E-Mail-Adresse ein.");
return { name: cleanName, email: cleanEmail };
}
+export const VISIBILITIES: Visibility[] = ["members", "public", "hidden"];
+export const MAX_LINKS = 5;
+/** Ergänzt https://, erlaubt nur http(s) und verlangt einen Hostnamen mit Punkt. */
+export function normalizeLinkUrl(raw: string) {
+ const text = raw.trim();
+ if (!text) throw new Error("Bitte gib die Adresse deines Links ein.");
+ const withScheme = /^[a-z][a-z0-9+.-]*:/i.test(text)
+ ? text
+ : `https://${text}`;
+ let parsed: URL;
+ try {
+ parsed = new URL(withScheme);
+ } catch {
+ throw new Error(`„${text}“ ist keine gültige Adresse.`);
+ }
+ if (
+ (parsed.protocol !== "https:" && parsed.protocol !== "http:") ||
+ !parsed.hostname.includes(".") ||
+ parsed.username ||
+ parsed.password
+ )
+ throw new Error(
+ `„${text}“ ist keine gültige Adresse. Erlaubt sind http- und https-Links.`,
+ );
+ if (parsed.href.length > 200)
+ throw new Error("Ein Link darf höchstens 200 Zeichen haben.");
+ return parsed.href;
+}
+export function linkHost(url: string) {
+ try {
+ return new URL(url).hostname.replace(/^www\./, "");
+ } catch {
+ return url;
+ }
+}
+/** Prüft und bereinigt das Profilformular; wirft verständliche deutsche Fehler. */
+export function validateProfileUpdate(input: ProfileUpdate): ProfileUpdate {
+ const displayName = input.displayName.trim();
+ const location = input.location.trim();
+ const pronouns = input.pronouns.trim();
+ if (!displayName || displayName.length > 60)
+ throw new Error("Bitte gib einen Namen mit höchstens 60 Zeichen ein.");
+ if (input.bio.length > 300)
+ throw new Error("Deine Bio darf höchstens 300 Zeichen haben.");
+ if (location.length > 60)
+ throw new Error("Dein Ort darf höchstens 60 Zeichen haben.");
+ if (pronouns.length > 30)
+ throw new Error("Deine Pronomen dürfen höchstens 30 Zeichen haben.");
+ if (!VISIBILITIES.includes(input.visibility))
+ throw new Error("Bitte wähle, wer dein Profil sehen darf.");
+ const rows = input.links.filter((l) => l.label.trim() || l.url.trim());
+ if (rows.length > MAX_LINKS)
+ throw new Error(`Du kannst höchstens ${MAX_LINKS} Links hinterlegen.`);
+ const links = rows.map((row) => {
+ const url = normalizeLinkUrl(row.url);
+ const label = row.label.trim() || linkHost(url);
+ if (label.length > 40)
+ throw new Error("Ein Link-Titel darf höchstens 40 Zeichen haben.");
+ return { label, url };
+ });
+ return {
+ displayName,
+ bio: input.bio,
+ location,
+ pronouns,
+ links,
+ visibility: input.visibility,
+ showPosts: input.showPosts,
+ showTrustTree: input.showTrustTree,
+ };
+}
+export function validateEmailAddress(email: string) {
+ const clean = email.trim().toLowerCase();
+ if (clean.length > 254 || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(clean))
+ throw new Error("Bitte gib eine gültige E-Mail-Adresse ein.");
+ return clean;
+}
+
+/** Wer einen Beitrag löschen darf: Autor, Gastgeber/Moderation des Raums, Admin. */
+export function canDeletePost(
+ state: Pick,
+ post: Post,
+) {
+ const me = state.currentUserId;
+ if (!me) return false;
+ if (post.author_id === me || state.isAdmin) return true;
+ return state.memberships.some(
+ (m) =>
+ m.space_id === post.space_id &&
+ m.user_id === me &&
+ (m.role === "owner" || m.role === "moderator"),
+ );
+}
diff --git a/app/lib/public-profile.ts b/app/lib/public-profile.ts
new file mode 100644
index 0000000..5352528
--- /dev/null
+++ b/app/lib/public-profile.ts
@@ -0,0 +1,41 @@
+import { config } from "@/lib/config";
+import { serverClient } from "@/lib/supabase/server";
+import type { PublicProfile } from "@/lib/model";
+
+/**
+ * Lädt ein Profil, das sein Mitglied auf „öffentlich“ gestellt hat.
+ * Die Datenbank liefert nur dann etwas, wenn visibility = 'public' (siehe get_public_profile).
+ * Alles andere — auch Fehler — ist für Besucher ohne Login schlicht „nicht gefunden“.
+ */
+export async function loadPublicProfile(
+ username: string,
+): Promise {
+ if (config.mode !== "supabase") return null;
+ if (!/^[a-z0-9_]{3,24}$/.test(username)) return null;
+ try {
+ const client = await serverClient();
+ const { data, error } = await client.rpc("get_public_profile", {
+ p_username: username,
+ });
+ if (error || !data) return null;
+ let avatar_url: string | null = null;
+ if (data.avatar_path) {
+ const signed = await client.storage
+ .from("avatars")
+ .createSignedUrl(data.avatar_path, 3600);
+ avatar_url = signed.data?.signedUrl ?? null;
+ }
+ return {
+ username: data.username,
+ display_name: data.display_name,
+ bio: data.bio,
+ avatar_url,
+ location: data.location,
+ pronouns: data.pronouns,
+ links: Array.isArray(data.links) ? data.links : [],
+ member_since: data.member_since,
+ };
+ } catch {
+ return null;
+ }
+}
diff --git a/app/lib/repositories/contract.ts b/app/lib/repositories/contract.ts
index 178530a..e7ddb30 100644
--- a/app/lib/repositories/contract.ts
+++ b/app/lib/repositories/contract.ts
@@ -1,9 +1,11 @@
import type {
Bucket,
InvitePreview,
+ NotificationSettings,
OnboardingInput,
PostInput,
Profile,
+ ProfileUpdate,
Snapshot,
Ticket,
Vote,
@@ -15,7 +17,22 @@ export interface ClubhouseRepository {
createTicket(spaceId: string): Promise;
createPost(input: PostInput): Promise;
vote(postId: string, vote: Vote): Promise;
+ /** Herz an/aus. Eigene Beiträge können nicht geliked werden. */
+ toggleLike(postId: string): Promise<{ liked: boolean; likes_count: number }>;
+ /** Eigenen Beitrag/Kommentar löschen (Gastgeber/Moderation/Admin auch fremde). */
+ deletePost(postId: string): Promise;
+ /** Neue Sprachvorstellung (1–15 s) setzen. */
+ setVoiceIntro(path: string, duration: number): Promise;
upload(bucket: Bucket, file: Blob): Promise;
+ /** Eigenes Profil speichern (Name, Bio, Ort, Pronomen, Links, Sichtbarkeit). */
+ updateProfile(input: ProfileUpdate): Promise;
+ /** Hochgeladenes Bild als Profilbild setzen; null entfernt es. */
+ setAvatar(path: string | null): Promise;
+ updateNotifications(settings: NotificationSettings): Promise;
+ /** Löst die Bestätigungs-Mail für die neue Adresse aus. */
+ requestEmailChange(email: string): Promise;
+ /** Löscht Konto, Profil, Beiträge und Tickets unwiderruflich. */
+ deleteAccount(): Promise;
requestLogin(email: string): Promise;
verifyLogin(email: string, token: string): Promise;
hasSession(): Promise;
diff --git a/app/lib/repositories/demo.ts b/app/lib/repositories/demo.ts
index 77a3f9a..cd01f81 100644
--- a/app/lib/repositories/demo.ts
+++ b/app/lib/repositories/demo.ts
@@ -1,14 +1,21 @@
-import { createDemoSnapshot } from "@/lib/seed";
+import { createDemoSnapshot, DEMO_EMAIL } from "@/lib/seed";
import {
+ canDeletePost,
+ DEFAULT_NOTIFICATIONS,
moderationStatus,
+ validateEmailAddress,
validateIdentity,
validatePost,
+ validateProfileUpdate,
validateWaitlist,
} from "@/lib/model";
import type {
Bucket,
+ NotificationSettings,
OnboardingInput,
PostInput,
+ Profile,
+ ProfileUpdate,
Snapshot,
Vote,
} from "@/lib/model";
@@ -94,6 +101,12 @@ export function redeemDemoTicket(
display_name: input.displayName.trim(),
bio: input.bio,
avatar_url: null,
+ location: "",
+ pronouns: "",
+ links: [],
+ visibility: "members" as const,
+ show_posts: true,
+ show_trust_tree: true,
voice_intro_url: input.voiceUrl,
voice_duration_sec: input.voiceDuration,
invited_by_id: creator.id,
@@ -165,9 +178,133 @@ export function addDemoPost(state: Snapshot, input: PostInput) {
slop_status: "clean",
valuable_votes_count: 0,
slop_votes_count: 0,
+ likes_count: 0,
created_at: new Date().toISOString(),
});
}
+/** Spiegelt toggle_post_like(): Herz an/aus, nie auf eigene Beiträge. */
+export function toggleDemoLike(state: Snapshot, postId: string) {
+ const user = actor(state);
+ const post = state.posts.find((p) => p.id === postId);
+ if (!post) throw new Error("Beitrag nicht gefunden.");
+ requireSpace(state, post.space_id);
+ if (post.author_id === user.id)
+ throw new Error("Eigene Beiträge kannst du nicht liken.");
+ const before = state.likes.length;
+ state.likes = state.likes.filter(
+ (l) => !(l.post_id === postId && l.user_id === user.id),
+ );
+ const liked = state.likes.length === before;
+ if (liked)
+ state.likes.push({
+ post_id: postId,
+ user_id: user.id,
+ created_at: new Date().toISOString(),
+ });
+ post.likes_count = state.likes.filter((l) => l.post_id === postId).length;
+ return { liked, likes_count: post.likes_count };
+}
+/** Spiegelt delete_post(): entfernt Beitrag samt Antworten, Likes und Stimmen. */
+export function deleteDemoPost(state: Snapshot, postId: string) {
+ actor(state);
+ const post = state.posts.find((p) => p.id === postId);
+ if (!post) throw new Error("Beitrag nicht gefunden.");
+ requireSpace(state, post.space_id);
+ if (!canDeletePost({ ...state, isAdmin: demoIsAdmin(state) }, post))
+ throw new Error("Diesen Beitrag kannst du nicht löschen.");
+ const doomed = new Set();
+ const collect = (id: string) => {
+ doomed.add(id);
+ state.posts
+ .filter((p) => p.parent_id === id && !doomed.has(p.id))
+ .forEach((p) => collect(p.id));
+ };
+ collect(postId);
+ state.posts = state.posts.filter((p) => !doomed.has(p.id));
+ state.votes = state.votes.filter((v) => !doomed.has(v.post_id));
+ state.likes = state.likes.filter((l) => !doomed.has(l.post_id));
+}
+export function setDemoVoiceIntro(
+ state: Snapshot,
+ path: string,
+ duration: number,
+) {
+ const user = actor(state);
+ if (!path || !Number.isFinite(duration) || duration < 1 || duration > 15)
+ throw new Error("Bitte nimm eine Vorstellung von 1 bis 15 Sekunden auf.");
+ user.voice_intro_url = path;
+ user.voice_duration_sec = duration;
+ return user;
+}
+export function updateDemoProfile(state: Snapshot, input: ProfileUpdate) {
+ const user = actor(state);
+ const clean = validateProfileUpdate(input);
+ user.display_name = clean.displayName;
+ user.bio = clean.bio;
+ user.location = clean.location;
+ user.pronouns = clean.pronouns;
+ user.links = clean.links;
+ user.visibility = clean.visibility;
+ user.show_posts = clean.showPosts;
+ user.show_trust_tree = clean.showTrustTree;
+ return user;
+}
+export function setDemoAvatar(state: Snapshot, path: string | null) {
+ const user = actor(state);
+ user.avatar_url = path;
+ return user;
+}
+export function updateDemoNotifications(
+ state: Snapshot,
+ settings: NotificationSettings,
+) {
+ actor(state);
+ state.settings = {
+ notify_replies: Boolean(settings.notify_replies),
+ notify_ticket_redeemed: Boolean(settings.notify_ticket_redeemed),
+ notify_news: Boolean(settings.notify_news),
+ };
+}
+export function changeDemoEmail(state: Snapshot, email: string) {
+ actor(state);
+ state.email = validateEmailAddress(email);
+}
+/** Spiegelt delete_my_account(): Raum-Gastgeber müssen zuerst übergeben; alles Übrige verschwindet kaskadierend. */
+export function deleteDemoAccount(state: Snapshot) {
+ const user = actor(state);
+ if (state.spaces.some((s) => s.owner_id === user.id))
+ throw new Error(
+ "Du bist Gastgeber eines Raums. Übergib ihn zuerst, bevor du dein Konto löschst.",
+ );
+ const doomed = new Set();
+ const collect = (id: string) => {
+ doomed.add(id);
+ state.posts
+ .filter((p) => p.parent_id === id && !doomed.has(p.id))
+ .forEach((p) => collect(p.id));
+ };
+ state.posts
+ .filter((p) => p.author_id === user.id)
+ .forEach((p) => collect(p.id));
+ state.posts = state.posts.filter((p) => !doomed.has(p.id));
+ state.votes = state.votes.filter(
+ (v) => v.voter_id !== user.id && !doomed.has(v.post_id),
+ );
+ state.likes = state.likes.filter(
+ (l) => l.user_id !== user.id && !doomed.has(l.post_id),
+ );
+ for (const post of state.posts)
+ post.likes_count = state.likes.filter((l) => l.post_id === post.id).length;
+ state.memberships = state.memberships.filter((m) => m.user_id !== user.id);
+ state.tickets = state.tickets.filter((t) => t.creator_id !== user.id);
+ for (const t of state.tickets)
+ if (t.redeemed_by_id === user.id) t.redeemed_by_id = null;
+ for (const p of state.profiles)
+ if (p.invited_by_id === user.id) p.invited_by_id = null;
+ state.profiles = state.profiles.filter((p) => p.id !== user.id);
+ state.currentUserId = null;
+ state.settings = { ...DEFAULT_NOTIFICATIONS };
+}
function demoIsAdmin(state: Snapshot) {
return state.spaces.some(
(s) => s.owner_id !== null && s.owner_id === state.currentUserId,
@@ -213,7 +350,8 @@ export function approveDemoWaitlist(
if (existing && (existing.redeemed_at || new Date(existing.expires_at) > now))
return existing;
const space = state.spaces.find((s) => s.slug === "vibecoding-germany");
- if (!space?.owner_id) throw new Error("Dieser Raum vergibt noch keine Tickets.");
+ if (!space?.owner_id)
+ throw new Error("Dieser Raum vergibt noch keine Tickets.");
const ticket = {
id: newId(),
code: newId().replaceAll("-", "").toUpperCase(),
@@ -297,6 +435,29 @@ export function createDemoRepository(): ClubhouseRepository {
throw new Error();
// Ältere Demo-Stände kannten noch keine Warteliste.
if (!Array.isArray(state.waitlist)) state.waitlist = [];
+ // Ältere Demo-Stände kannten noch keine Likes.
+ if (!Array.isArray(state.likes)) state.likes = [];
+ state.posts = state.posts.map((p) => ({
+ ...p,
+ likes_count: p.likes_count ?? 0,
+ }));
+ // Ältere Demo-Stände kannten weder Profil-Einstellungen noch Konto-Daten.
+ state.settings = { ...DEFAULT_NOTIFICATIONS, ...state.settings };
+ if (typeof state.email === "undefined") state.email = DEMO_EMAIL;
+ state.profiles = state.profiles.map(
+ (p): Profile =>
+ ({
+ ...({
+ location: "",
+ pronouns: "",
+ links: [],
+ visibility: "members",
+ show_posts: true,
+ show_trust_tree: true,
+ } satisfies Partial),
+ ...(p as Partial),
+ }) as Profile,
+ );
return state;
} catch {
throw new Error(
@@ -358,6 +519,10 @@ export function createDemoRepository(): ClubhouseRepository {
createPost: (input) => mutate((state) => addDemoPost(state, input)),
vote: (postId, vote) =>
mutate((state) => castDemoVote(state, postId, vote)),
+ toggleLike: (postId) => mutate((state) => toggleDemoLike(state, postId)),
+ deletePost: (postId) => mutate((state) => deleteDemoPost(state, postId)),
+ setVoiceIntro: (path, duration) =>
+ mutate((state) => void setDemoVoiceIntro(state, path, duration)),
async upload(bucket, file) {
validateUpload(bucket, file);
return new Promise((resolve, reject) => {
@@ -368,6 +533,14 @@ export function createDemoRepository(): ClubhouseRepository {
reader.readAsDataURL(file);
});
},
+ updateProfile: (input) =>
+ mutate((state) => void updateDemoProfile(state, input)),
+ setAvatar: (path) => mutate((state) => void setDemoAvatar(state, path)),
+ updateNotifications: (settings) =>
+ mutate((state) => updateDemoNotifications(state, settings)),
+ requestEmailChange: (email) =>
+ mutate((state) => changeDemoEmail(state, email)),
+ deleteAccount: () => mutate((state) => deleteDemoAccount(state)),
async requestLogin() {
await mutate((state) => {
state.currentUserId =
diff --git a/app/lib/repositories/supabase.ts b/app/lib/repositories/supabase.ts
index e30e157..03697e7 100644
--- a/app/lib/repositories/supabase.ts
+++ b/app/lib/repositories/supabase.ts
@@ -1,8 +1,17 @@
import { browserClient } from "@/lib/supabase/browser";
-import { validateIdentity, validatePost, validateWaitlist } from "@/lib/model";
+import {
+ DEFAULT_NOTIFICATIONS,
+ validateEmailAddress,
+ validateIdentity,
+ validatePost,
+ validateProfileUpdate,
+ validateWaitlist,
+} from "@/lib/model";
import { newId, validateUpload } from "./demo";
import type { Bucket, Snapshot } from "@/lib/model";
import type { ClubhouseRepository } from "./contract";
+/** Beiträge der obersten Ebene, die das Clubhaus auf einmal lädt. */
+const FEED_LIMIT = 150;
const messages: Record = {
INVALID_TICKET:
"Dieses Ticket ist ungültig, abgelaufen oder bereits eingelöst.",
@@ -11,8 +20,10 @@ const messages: Record = {
AUTH_REQUIRED: "Bitte melde dich zuerst per E-Mail an.",
PROFILE_REQUIRED: "Bitte schließe zuerst deine Vorstellung ab.",
SPACE_FORBIDDEN: "Du bist noch nicht Mitglied in diesem Raum.",
- POST_FORBIDDEN: "Du kannst diesen Beitrag nicht prüfen.",
+ POST_FORBIDDEN: "Auf diesen Beitrag hast du keinen Zugriff (mehr).",
SELF_VOTE_FORBIDDEN: "Über eigene Beiträge stimmt deine Nachbarschaft ab.",
+ SELF_LIKE_FORBIDDEN: "Eigene Beiträge kannst du nicht liken.",
+ DELETE_FORBIDDEN: "Diesen Beitrag kannst du nicht löschen.",
VOICE_REQUIRED: "Bitte nimm eine Vorstellung von 1 bis 15 Sekunden auf.",
ALREADY_ONBOARDED: "Du bist bereits Mitglied. Willkommen zurück!",
INVALID_NAME: "Bitte gib deinen Namen mit höchstens 80 Zeichen ein.",
@@ -21,6 +32,18 @@ const messages: Record = {
"Gerade tragen sich sehr viele Menschen ein. Bitte versuche es in ein paar Minuten noch einmal.",
ADMIN_REQUIRED: "Dafür brauchst du Admin-Rechte.",
WAITLIST_NOT_FOUND: "Dieser Eintrag existiert nicht mehr.",
+ INVALID_DISPLAY_NAME: "Bitte gib einen Namen mit höchstens 60 Zeichen ein.",
+ INVALID_BIO: "Deine Bio darf höchstens 300 Zeichen haben.",
+ INVALID_LOCATION: "Dein Ort darf höchstens 60 Zeichen haben.",
+ INVALID_PRONOUNS: "Deine Pronomen dürfen höchstens 30 Zeichen haben.",
+ INVALID_LINKS:
+ "Mindestens ein Link ist ungültig. Erlaubt sind bis zu fünf http- oder https-Adressen.",
+ INVALID_VISIBILITY: "Bitte wähle, wer dein Profil sehen darf.",
+ INVALID_SETTINGS: "Diese Einstellung konnte nicht gespeichert werden.",
+ INVALID_MEDIA:
+ "Dieses Bild gehört nicht zu deinem Konto. Bitte lade es neu hoch.",
+ OWNER_CANNOT_DELETE:
+ "Du bist Gastgeber eines Raums. Übergib ihn zuerst, bevor du dein Konto löschst.",
WAITLIST_ALREADY_APPROVED:
"Dieser Mensch ist schon freigegeben und hat ein Ticket.",
};
@@ -76,24 +99,51 @@ export function createSupabaseRepository(): ClubhouseRepository {
posts: [],
tickets: [],
votes: [],
+ likes: [],
currentUserId: null,
+ email: null,
+ settings: { ...DEFAULT_NOTIFICATIONS },
waitlist: [],
isAdmin: false,
};
- const [p, s, m, posts, t, v, admin] = await Promise.all([
+ const [p, s, m, posts, t, v, admin, prefs] = await Promise.all([
client.from("profiles").select("*"),
client.from("spaces").select("*"),
client.from("space_members").select("*"),
client
.from("posts")
.select("*")
+ .is("parent_id", null)
.order("created_at", { ascending: false })
- .limit(100),
+ .limit(FEED_LIMIT),
client.from("invite_tickets").select("*"),
client.from("content_votes").select("*"),
client.rpc("is_admin"),
+ client.from("profile_settings").select("*").maybeSingle(),
]);
- [p, s, m, posts, t, v, admin].forEach((r) => check(r.error));
+ [p, s, m, posts, t, v, admin, prefs].forEach((r) => check(r.error));
+ // Kommentare und Likes gehören zu den geladenen Beiträgen; so verdrängen
+ // lebhafte Gespräche keine Beiträge aus dem Feed.
+ const feedIds = (posts.data || []).map((row) => row.id);
+ const replies = feedIds.length
+ ? await client
+ .from("posts")
+ .select("*")
+ .in("parent_id", feedIds)
+ .order("created_at", { ascending: true })
+ .limit(2000)
+ : { data: [], error: null };
+ check(replies.error);
+ const allPosts = [...(posts.data || []), ...(replies.data || [])];
+ const allIds = allPosts.map((row) => row.id);
+ const likes = allIds.length
+ ? await client
+ .from("post_likes")
+ .select("*")
+ .in("post_id", allIds)
+ .limit(10000)
+ : { data: [], error: null };
+ check(likes.error);
let waitlist: Snapshot["waitlist"] = [];
if (admin.data) {
const w = await client
@@ -115,7 +165,7 @@ export function createSupabaseRepository(): ClubhouseRepository {
),
signPaths(
"post-media",
- (posts.data || []).flatMap((row) => [row.image_url, row.audio_url]),
+ allPosts.flatMap((row) => [row.image_url, row.audio_url]),
),
]);
const profiles = (p.data || []).map((row) => ({
@@ -123,7 +173,7 @@ export function createSupabaseRepository(): ClubhouseRepository {
avatar_url: avatarUrl(row.avatar_url),
voice_intro_url: voiceUrl(row.voice_intro_url),
}));
- const resolvedPosts = (posts.data || []).map((row) => ({
+ const resolvedPosts = allPosts.map((row) => ({
...row,
image_url: postUrl(row.image_url),
audio_url: postUrl(row.audio_url),
@@ -135,7 +185,16 @@ export function createSupabaseRepository(): ClubhouseRepository {
posts: resolvedPosts,
tickets: t.data || [],
votes: v.data || [],
+ likes: likes.data || [],
currentUserId: auth.user.id,
+ email: auth.user.email ?? null,
+ settings: prefs.data
+ ? {
+ notify_replies: prefs.data.notify_replies,
+ notify_ticket_redeemed: prefs.data.notify_ticket_redeemed,
+ notify_news: prefs.data.notify_news,
+ }
+ : { ...DEFAULT_NOTIFICATIONS },
waitlist,
isAdmin: Boolean(admin.data),
};
@@ -187,6 +246,24 @@ export function createSupabaseRepository(): ClubhouseRepository {
});
check(error);
},
+ async toggleLike(postId) {
+ const { data, error } = await client.rpc("toggle_post_like", {
+ p_post_id: postId,
+ });
+ check(error);
+ return data!;
+ },
+ async deletePost(postId) {
+ const { error } = await client.rpc("delete_post", { p_post_id: postId });
+ check(error);
+ },
+ async setVoiceIntro(path, duration) {
+ const { error } = await client.rpc("set_voice_intro", {
+ p_path: path,
+ p_duration_sec: duration,
+ });
+ check(error);
+ },
async upload(bucket, file) {
validateUpload(bucket, file);
const { data, error } = await client.auth.getUser();
@@ -211,6 +288,49 @@ export function createSupabaseRepository(): ClubhouseRepository {
check(result.error);
return path;
},
+ async updateProfile(input) {
+ const clean = validateProfileUpdate(input);
+ const { error } = await client.rpc("update_profile", {
+ p_display_name: clean.displayName,
+ p_bio: clean.bio,
+ p_location: clean.location,
+ p_pronouns: clean.pronouns,
+ p_links: clean.links,
+ p_visibility: clean.visibility,
+ p_show_posts: clean.showPosts,
+ p_show_trust_tree: clean.showTrustTree,
+ });
+ check(error);
+ },
+ async setAvatar(path) {
+ const { error } = await client.rpc("set_avatar", { p_path: path });
+ check(error);
+ },
+ async updateNotifications(settings) {
+ const { error } = await client.rpc("update_notification_settings", {
+ p_replies: settings.notify_replies,
+ p_ticket_redeemed: settings.notify_ticket_redeemed,
+ p_news: settings.notify_news,
+ });
+ check(error);
+ },
+ async requestEmailChange(email) {
+ const clean = validateEmailAddress(email);
+ const { error } = await client.auth.updateUser(
+ { email: clean },
+ {
+ emailRedirectTo: `${window.location.origin}/auth/callback?next=/einstellungen`,
+ },
+ );
+ check(error);
+ },
+ async deleteAccount() {
+ const { error } = await client.rpc("delete_my_account");
+ check(error);
+ // Die Sitzung gehört zu einem gelöschten Konto; lokal abmelden ist hier nur Aufräumen.
+ await client.auth.signOut({ scope: "local" });
+ signed.clear();
+ },
async requestLogin(email) {
const { error } = await client.auth.signInWithOtp({
email,
@@ -304,6 +424,11 @@ export function createSupabaseRepository(): ClubhouseRepository {
{ event: "*", schema: "public", table: "posts" },
schedule,
)
+ .on(
+ "postgres_changes",
+ { event: "*", schema: "public", table: "post_likes" },
+ schedule,
+ )
.subscribe();
const { data } = client.auth.onAuthStateChange(() => {
schedule();
diff --git a/app/lib/seed.ts b/app/lib/seed.ts
index 986ffab..ad78972 100644
--- a/app/lib/seed.ts
+++ b/app/lib/seed.ts
@@ -1,4 +1,6 @@
-import type { Profile, Snapshot } from "./model";
+import { DEFAULT_NOTIFICATIONS } from "./model";
+import type { Post, PostLike, Profile, Snapshot } from "./model";
+export const DEMO_EMAIL = "dennis@demo.humans-only.invalid";
export const DEMO_CODE = "MOIN-VIBECODING";
export const SPACE_ID = "10000000-0000-4000-8000-000000000001";
const ids = ["dennis", "mira", "jonas", "aylin", "lea", "tom"].map(
@@ -45,6 +47,12 @@ export function createDemoSnapshot(): Snapshot {
display_name,
bio,
avatar_url: `/demo/avatar-${username}.svg`,
+ location: "",
+ pronouns: "",
+ links: [],
+ visibility: "members" as const,
+ show_posts: true,
+ show_trust_tree: true,
voice_intro_url: `/demo/intro-${username}.mp3`,
voice_duration_sec: 12,
invited_by_id: i === 0 ? null : ids[i < 4 ? 0 : 1],
@@ -53,9 +61,11 @@ export function createDemoSnapshot(): Snapshot {
created_at: joined,
}),
);
- return {
+ const snapshot: Snapshot = {
profiles,
currentUserId: ids[0],
+ email: DEMO_EMAIL,
+ settings: { ...DEFAULT_NOTIFICATIONS },
isAdmin: true,
waitlist: [
{
@@ -125,6 +135,7 @@ export function createDemoSnapshot(): Snapshot {
slop_status: "valuable_verified",
valuable_votes_count: 3,
slop_votes_count: 0,
+ likes_count: 0,
created_at: "2026-11-04T08:40:00.000Z",
},
{
@@ -139,6 +150,7 @@ export function createDemoSnapshot(): Snapshot {
slop_status: "clean",
valuable_votes_count: 0,
slop_votes_count: 0,
+ likes_count: 0,
created_at: "2026-11-04T07:25:00.000Z",
},
{
@@ -153,6 +165,7 @@ export function createDemoSnapshot(): Snapshot {
slop_status: "under_review",
valuable_votes_count: 0,
slop_votes_count: 2,
+ likes_count: 0,
created_at: "2026-11-03T18:10:00.000Z",
},
{
@@ -167,6 +180,7 @@ export function createDemoSnapshot(): Snapshot {
slop_status: "valuable_verified",
valuable_votes_count: 2,
slop_votes_count: 0,
+ likes_count: 0,
created_at: "2026-11-04T08:00:00.000Z",
},
{
@@ -181,8 +195,39 @@ export function createDemoSnapshot(): Snapshot {
slop_status: "clean",
valuable_votes_count: 0,
slop_votes_count: 0,
+ likes_count: 0,
created_at: "2026-11-03T16:00:00.000Z",
},
+ {
+ id: "30000000-0000-4000-8000-000000000006",
+ author_id: ids[4],
+ space_id: null,
+ text: "Mein Soundtrack für konzentriertes Bauen heute Abend 🎧\nhttps://open.spotify.com/playlist/37i9dQZF1DX8NTLI2TtZa6\n\n@mira, du hattest nach Lo-Fi gefragt!",
+ image_url: null,
+ audio_url: null,
+ audio_duration_sec: null,
+ parent_id: null,
+ slop_status: "clean",
+ valuable_votes_count: 0,
+ slop_votes_count: 0,
+ likes_count: 0,
+ created_at: "2026-11-04T09:10:00.000Z",
+ },
+ {
+ id: "30000000-0000-4000-8000-000000000007",
+ author_id: ids[1],
+ space_id: null,
+ text: "Perfekt, danke! Läuft schon. Mehr davon unter www.vibecoding-germany.de 🙌",
+ image_url: null,
+ audio_url: null,
+ audio_duration_sec: null,
+ parent_id: "30000000-0000-4000-8000-000000000006",
+ slop_status: "clean",
+ valuable_votes_count: 0,
+ slop_votes_count: 0,
+ likes_count: 0,
+ created_at: "2026-11-04T09:30:00.000Z",
+ },
],
tickets: [
{
@@ -218,5 +263,26 @@ export function createDemoSnapshot(): Snapshot {
created_at: joined,
})),
],
+ likes: [],
};
+ // Ein paar Herzen, damit die Demo nicht leer wirkt. Nie auf eigene Beiträge.
+ const hearts: [string, number[]][] = [
+ ["30000000-0000-4000-8000-000000000001", [0, 2, 3, 4]],
+ ["30000000-0000-4000-8000-000000000002", [1, 3]],
+ ["30000000-0000-4000-8000-000000000004", [1, 2, 3, 4, 5]],
+ ["30000000-0000-4000-8000-000000000006", [1, 2]],
+ ["30000000-0000-4000-8000-000000000007", [4]],
+ ];
+ snapshot.likes = hearts.flatMap(([post_id, who]) =>
+ who.map((i): PostLike => ({
+ post_id,
+ user_id: ids[i],
+ created_at: joined,
+ })),
+ );
+ snapshot.posts = snapshot.posts.map((post): Post => ({
+ ...post,
+ likes_count: snapshot.likes.filter((l) => l.post_id === post.id).length,
+ }));
+ return snapshot;
}
diff --git a/app/lib/supabase/database.ts b/app/lib/supabase/database.ts
index cbb008a..e5558bd 100644
--- a/app/lib/supabase/database.ts
+++ b/app/lib/supabase/database.ts
@@ -1,12 +1,15 @@
import type {
Profile,
+ ProfileLink,
Space,
Membership,
Post,
ContentVote,
+ PostLike,
Ticket,
InvitePreview,
WaitlistEntry,
+ NotificationSettings,
} from "@/lib/model";
type Table = {
Row: T;
@@ -22,8 +25,10 @@ export type Database = {
space_members: Table;
posts: Table;
content_votes: Table;
+ post_likes: Table;
invite_tickets: Table;
waitlist_entries: Table;
+ profile_settings: Table;
};
Views: Record;
Functions: {
@@ -55,6 +60,51 @@ export type Database = {
Args: { p_post_id: string; p_vote: string };
Returns: Post;
};
+ update_profile: {
+ Args: {
+ p_display_name: string;
+ p_bio: string;
+ p_location: string;
+ p_pronouns: string;
+ p_links: ProfileLink[];
+ p_visibility: string;
+ p_show_posts: boolean;
+ p_show_trust_tree: boolean;
+ };
+ Returns: Profile;
+ };
+ set_avatar: { Args: { p_path: string | null }; Returns: Profile };
+ toggle_post_like: {
+ Args: { p_post_id: string };
+ Returns: { liked: boolean; likes_count: number };
+ };
+ delete_post: { Args: { p_post_id: string }; Returns: undefined };
+ set_voice_intro: {
+ Args: { p_path: string; p_duration_sec: number };
+ Returns: Profile;
+ };
+ update_notification_settings: {
+ Args: {
+ p_replies: boolean;
+ p_ticket_redeemed: boolean;
+ p_news: boolean;
+ };
+ Returns: NotificationSettings;
+ };
+ get_public_profile: {
+ Args: { p_username: string };
+ Returns: {
+ username: string;
+ display_name: string;
+ bio: string;
+ avatar_path: string | null;
+ location: string;
+ pronouns: string;
+ links: ProfileLink[];
+ member_since: string;
+ } | null;
+ };
+ delete_my_account: { Args: Record; Returns: undefined };
is_admin: { Args: Record; Returns: boolean };
join_waitlist: {
Args: { p_name: string; p_email: string };
diff --git a/app/lib/time.ts b/app/lib/time.ts
new file mode 100644
index 0000000..7426c41
--- /dev/null
+++ b/app/lib/time.ts
@@ -0,0 +1,36 @@
+const units: [Intl.RelativeTimeFormatUnit, number][] = [
+ ["minute", 60],
+ ["hour", 3600],
+ ["day", 86400],
+];
+/** „gerade eben“, „vor 5 Minuten“, „vor 3 Tagen“, danach ein Datum. */
+export function timeAgo(iso: string, now = Date.now()) {
+ const then = new Date(iso).getTime();
+ const seconds = Math.round((now - then) / 1000);
+ if (!Number.isFinite(seconds)) return "";
+ if (seconds < 45) return "gerade eben";
+ const rtf = new Intl.RelativeTimeFormat("de-DE", { numeric: "auto" });
+ if (seconds < 3600) return rtf.format(-Math.round(seconds / 60), units[0][0]);
+ if (seconds < 86400)
+ return rtf.format(-Math.round(seconds / 3600), units[1][0]);
+ if (seconds < 7 * 86400)
+ return rtf.format(-Math.round(seconds / 86400), units[2][0]);
+ return new Date(iso).toLocaleDateString("de-DE", {
+ day: "numeric",
+ month: "short",
+ year:
+ new Date(iso).getFullYear() === new Date(now).getFullYear()
+ ? undefined
+ : "numeric",
+ timeZone: "Europe/Berlin",
+ });
+}
+/** „Gefällt Mira“, „Gefällt Mira und Jonas“, „Gefällt Mira, Jonas und 3 weiteren“. */
+export function likeSummary(names: string[]) {
+ if (!names.length) return "";
+ if (names.length === 1) return `Gefällt ${names[0]}`;
+ if (names.length === 2) return `Gefällt ${names[0]} und ${names[1]}`;
+ const rest = names.length - 2;
+ const others = rest === 1 ? "einer weiteren Person" : `${rest} weiteren`;
+ return `Gefällt ${names[0]}, ${names[1]} und ${others}`;
+}
diff --git a/app/tests/profile.test.ts b/app/tests/profile.test.ts
new file mode 100644
index 0000000..8ebd93d
--- /dev/null
+++ b/app/tests/profile.test.ts
@@ -0,0 +1,254 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createDemoSnapshot, SPACE_ID } from "../lib/seed";
+import {
+ DEFAULT_NOTIFICATIONS,
+ normalizeLinkUrl,
+ validateEmailAddress,
+ validateProfileUpdate,
+} from "../lib/model";
+import type { ProfileUpdate } from "../lib/model";
+import {
+ addDemoPost,
+ changeDemoEmail,
+ deleteDemoAccount,
+ setDemoAvatar,
+ updateDemoNotifications,
+ updateDemoProfile,
+} from "../lib/repositories/demo";
+import { handleAuthCallback } from "../lib/auth-callback";
+
+const valid: ProfileUpdate = {
+ displayName: " Dennis ",
+ bio: "Hallo",
+ location: " Oldenburg ",
+ pronouns: "er/ihm",
+ links: [{ label: "", url: "example.org/me" }],
+ visibility: "public",
+ showPosts: true,
+ showTrustTree: false,
+};
+
+test("link addresses get https, and only http(s) with a real host pass", () => {
+ assert.equal(normalizeLinkUrl("example.org"), "https://example.org/");
+ assert.equal(
+ normalizeLinkUrl(" http://example.org/a?b=1 "),
+ "http://example.org/a?b=1",
+ );
+ for (const bad of [
+ "javascript:alert(1)",
+ "data:text/html,hi",
+ "ftp://example.org",
+ "https://localhost",
+ "https://user:pw@example.org",
+ "not a url",
+ "",
+ " ",
+ ])
+ assert.throws(() => normalizeLinkUrl(bad), bad);
+ assert.throws(
+ () => normalizeLinkUrl(`https://example.org/${"a".repeat(200)}`),
+ /200 Zeichen/,
+ );
+});
+
+test("profile update is trimmed, links get a host-based title", () => {
+ const clean = validateProfileUpdate(valid);
+ assert.equal(clean.displayName, "Dennis");
+ assert.equal(clean.location, "Oldenburg");
+ assert.deepEqual(clean.links, [
+ { label: "example.org", url: "https://example.org/me" },
+ ]);
+ assert.equal(clean.visibility, "public");
+});
+
+test("empty link rows are dropped, the sixth link and bad fields are rejected", () => {
+ assert.deepEqual(
+ validateProfileUpdate({ ...valid, links: [{ label: " ", url: " " }] })
+ .links,
+ [],
+ );
+ const link = { label: "x", url: "https://example.org" };
+ assert.throws(
+ () => validateProfileUpdate({ ...valid, links: Array(6).fill(link) }),
+ /höchstens 5/,
+ );
+ assert.throws(
+ () => validateProfileUpdate({ ...valid, displayName: " " }),
+ /Namen/,
+ );
+ assert.throws(
+ () => validateProfileUpdate({ ...valid, bio: "x".repeat(301) }),
+ /300/,
+ );
+ assert.throws(
+ () => validateProfileUpdate({ ...valid, location: "x".repeat(61) }),
+ /60/,
+ );
+ assert.throws(
+ () => validateProfileUpdate({ ...valid, pronouns: "x".repeat(31) }),
+ /30/,
+ );
+ assert.throws(
+ () =>
+ validateProfileUpdate({
+ ...valid,
+ visibility: "everyone" as unknown as "public",
+ }),
+ /sehen darf/,
+ );
+ assert.throws(
+ () =>
+ validateProfileUpdate({
+ ...valid,
+ links: [{ label: "x".repeat(41), url: "https://example.org" }],
+ }),
+ /40 Zeichen/,
+ );
+});
+
+test("email addresses are validated and lower-cased", () => {
+ assert.equal(validateEmailAddress(" A@Example.ORG "), "a@example.org");
+ assert.throws(() => validateEmailAddress("kaputt"), /gültige/);
+});
+
+test("demo: saving the profile writes every field to the current member only", () => {
+ const s = createDemoSnapshot();
+ const others = JSON.stringify(s.profiles.slice(1));
+ const me = updateDemoProfile(s, valid);
+ assert.equal(me.id, s.currentUserId);
+ assert.equal(me.display_name, "Dennis");
+ assert.equal(me.visibility, "public");
+ assert.equal(me.show_trust_tree, false);
+ assert.equal(me.links[0].url, "https://example.org/me");
+ assert.equal(JSON.stringify(s.profiles.slice(1)), others);
+});
+
+test("demo: invalid updates and logged-out sessions change nothing", () => {
+ const s = createDemoSnapshot();
+ const before = JSON.stringify(s.profiles);
+ assert.throws(() => updateDemoProfile(s, { ...valid, displayName: "" }));
+ assert.equal(JSON.stringify(s.profiles), before);
+ s.currentUserId = null;
+ assert.throws(() => updateDemoProfile(s, valid), /Ticket/);
+ assert.throws(() => setDemoAvatar(s, "x"), /Ticket/);
+});
+
+test("demo: avatar can be set and removed", () => {
+ const s = createDemoSnapshot();
+ assert.equal(
+ setDemoAvatar(s, "data:image/webp;base64,AAAA").avatar_url,
+ "data:image/webp;base64,AAAA",
+ );
+ assert.equal(setDemoAvatar(s, null).avatar_url, null);
+});
+
+test("demo: notification settings and e-mail are stored", () => {
+ const s = createDemoSnapshot();
+ assert.deepEqual(s.settings, DEFAULT_NOTIFICATIONS);
+ updateDemoNotifications(s, {
+ notify_replies: false,
+ notify_ticket_redeemed: false,
+ notify_news: true,
+ });
+ assert.deepEqual(s.settings, {
+ notify_replies: false,
+ notify_ticket_redeemed: false,
+ notify_news: true,
+ });
+ changeDemoEmail(s, "Neu@Example.org");
+ assert.equal(s.email, "neu@example.org");
+ assert.throws(() => changeDemoEmail(s, "nope"));
+});
+
+test("demo: a room host cannot delete the account", () => {
+ const s = createDemoSnapshot();
+ assert.ok(s.spaces.some((sp) => sp.owner_id === s.currentUserId));
+ assert.throws(() => deleteDemoAccount(s), /Gastgeber/);
+ assert.ok(s.profiles.some((p) => p.id === s.currentUserId));
+});
+
+test("demo: deleting an account removes the member, their posts, replies, votes and tickets", () => {
+ const s = createDemoSnapshot();
+ const host = s.currentUserId!;
+ const leaver = s.profiles.find((p) => p.id !== host)!;
+ s.currentUserId = leaver.id;
+ addDemoPost(s, { spaceId: SPACE_ID, text: "Bald weg" });
+ const mine = s.posts[0];
+ s.currentUserId = host;
+ addDemoPost(s, { spaceId: SPACE_ID, text: "Antwort", parentId: mine.id });
+ s.votes.push({
+ id: "v-1",
+ post_id: mine.id,
+ voter_id: host,
+ vote: "valuable",
+ created_at: "2026-11-01T10:00:00.000Z",
+ });
+ s.votes.push({
+ id: "v-2",
+ post_id: s.posts[s.posts.length - 1].id,
+ voter_id: leaver.id,
+ vote: "valuable",
+ created_at: "2026-11-01T10:00:00.000Z",
+ });
+ s.tickets.push({
+ id: "t-1",
+ code: "WEG",
+ creator_id: leaver.id,
+ target_space_id: SPACE_ID,
+ redeemed_by_id: null,
+ redeemed_at: null,
+ expires_at: "2027-01-01T00:00:00.000Z",
+ });
+ const invited = s.profiles.find((p) => p.id !== host && p.id !== leaver.id)!;
+ invited.invited_by_id = leaver.id;
+ s.currentUserId = leaver.id;
+ deleteDemoAccount(s);
+ assert.equal(s.currentUserId, null);
+ assert.ok(!s.profiles.some((p) => p.id === leaver.id));
+ assert.ok(
+ !s.posts.some(
+ (p) =>
+ p.author_id === leaver.id ||
+ p.id === mine.id ||
+ p.parent_id === mine.id,
+ ),
+ );
+ assert.ok(s.posts.length > 0, "posts of other members stay");
+ assert.ok(
+ !s.votes.some((v) => v.voter_id === leaver.id || v.post_id === mine.id),
+ );
+ assert.ok(!s.tickets.some((t) => t.creator_id === leaver.id));
+ assert.ok(!s.memberships.some((m) => m.user_id === leaver.id));
+ assert.equal(
+ s.profiles.find((p) => p.id === invited.id)!.invited_by_id,
+ null,
+ );
+});
+
+test("auth callback honors only the allow-listed settings destination", async () => {
+ const ok = async () => ({ error: null });
+ const target = async (next: string) =>
+ (
+ await handleAuthCallback(
+ new Request(
+ `https://x.test/auth/callback?code=c&next=${encodeURIComponent(next)}`,
+ ),
+ ok,
+ )
+ ).headers.get("Location");
+ assert.equal(await target("/einstellungen"), "/einstellungen");
+ for (const evil of [
+ "https://evil.example",
+ "//evil.example",
+ "/admin",
+ "/einstellungen/../x",
+ "",
+ ])
+ assert.equal(await target(evil), "/onboarding", evil);
+ const failed = await handleAuthCallback(
+ new Request("https://x.test/auth/callback?code=c&next=/einstellungen"),
+ async () => ({ error: new Error("expired") }),
+ );
+ assert.equal(failed.headers.get("Location"), "/invite?auth_error=1");
+});
diff --git a/app/tests/social.test.ts b/app/tests/social.test.ts
new file mode 100644
index 0000000..19a765b
--- /dev/null
+++ b/app/tests/social.test.ts
@@ -0,0 +1,265 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import {
+ detectEmbed,
+ displayUrl,
+ firstUrl,
+ isPrivateAddress,
+ parsePreview,
+ tokenize,
+} from "../lib/links";
+import { likeSummary, timeAgo } from "../lib/time";
+import { canDeletePost } from "../lib/model";
+import { createDemoSnapshot, SPACE_ID } from "../lib/seed";
+import {
+ addDemoPost,
+ deleteDemoAccount,
+ deleteDemoPost,
+ setDemoVoiceIntro,
+ toggleDemoLike,
+} from "../lib/repositories/demo";
+
+test("links in text become clickable segments without trailing punctuation", () => {
+ const parts = tokenize(
+ "Schau mal: https://example.org/a?b=1. Und www.heise.de, oder (https://de.wikipedia.org/wiki/Kiel_(Begriffsklärung))!",
+ );
+ const urls = parts.filter((p) => p.kind === "url").map((p) => p.href);
+ assert.deepEqual(urls, [
+ "https://example.org/a?b=1",
+ "https://www.heise.de/",
+ "https://de.wikipedia.org/wiki/Kiel_(Begriffskl%C3%A4rung)",
+ ]);
+ assert.equal(
+ parts.map((p) => p.text).join(""),
+ "Schau mal: https://example.org/a?b=1. Und www.heise.de, oder (https://de.wikipedia.org/wiki/Kiel_(Begriffsklärung))!",
+ );
+});
+
+test("dangerous or incomplete schemes never become links", () => {
+ const parts = tokenize(
+ "javascript:alert(1) data:text/html,x http://localhost",
+ );
+ assert.equal(parts.filter((p) => p.kind === "url").length, 0);
+});
+
+test("mentions are recognised, e-mail addresses are not", () => {
+ const parts = tokenize("Hallo @Mira und mail@example.org");
+ assert.deepEqual(
+ parts
+ .filter((p) => p.kind === "mention")
+ .map((p) => p.kind === "mention" && p.username),
+ ["mira"],
+ );
+});
+
+test("first url wins the preview; long links are shortened for display", () => {
+ assert.equal(
+ firstUrl("a https://one.org b https://two.org"),
+ "https://one.org/",
+ );
+ assert.equal(firstUrl("kein Link hier"), null);
+ assert.ok(displayUrl(`https://example.org/${"x".repeat(80)}`).endsWith("…"));
+});
+
+test("spotify and youtube links map to fixed player urls", () => {
+ assert.deepEqual(
+ detectEmbed(
+ "https://open.spotify.com/intl-de/track/4uLU6hMCjMI75M1A2tKUQC?si=abc",
+ ),
+ {
+ provider: "spotify",
+ src: "https://open.spotify.com/embed/track/4uLU6hMCjMI75M1A2tKUQC",
+ height: 152,
+ },
+ );
+ assert.equal(
+ detectEmbed("https://open.spotify.com/playlist/37i9dQZF1DX8NTLI2TtZa6")
+ ?.height,
+ 352,
+ );
+ assert.equal(
+ detectEmbed("https://youtu.be/dQw4w9WgXcQ?t=42")?.src,
+ "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ?start=42",
+ );
+ assert.equal(
+ detectEmbed("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=x")?.src,
+ "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",
+ );
+ assert.equal(
+ detectEmbed("https://www.youtube.com/shorts/dQw4w9WgXcQ")?.provider,
+ "youtube",
+ );
+ assert.equal(detectEmbed("https://open.spotify.com/track/