);
const space = state.spaces.find((s) => s.slug === "vibecoding-germany");
- const tickets = state.tickets.filter((t) => t.creator_id === me.id);
+ // Tickets aus Wartelisten-Freigaben laufen über den Admin-Bereich, nicht über das eigene Budget.
+ const waitlistTickets = new Set(state.waitlist.map((e) => e.ticket_id));
+ const tickets = state.tickets.filter(
+ (t) => t.creator_id === me.id && !waitlistTickets.has(t.id),
+ );
const canIssue =
space &&
state.memberships.some(
diff --git a/app/components/waitlist.tsx b/app/components/waitlist.tsx
new file mode 100644
index 0000000..f4cf28d
--- /dev/null
+++ b/app/components/waitlist.tsx
@@ -0,0 +1,669 @@
+"use client";
+import Link from "next/link";
+import { useEffect, useMemo, useState } from "react";
+import {
+ ArrowRight,
+ Check,
+ ClipboardList,
+ Copy,
+ Mail,
+ RotateCcw,
+ Search,
+ Send,
+ Trash2,
+ UserRoundCheck,
+ X,
+} from "lucide-react";
+import type { Ticket, WaitlistEntry, WaitlistStatus } from "@/lib/model";
+import { useClub } from "./provider";
+import { Loading, Mascot } from "./ui";
+
+export function WaitlistPage() {
+ const { repository, ready, me } = useClub();
+ const [name, setName] = useState("");
+ const [email, setEmail] = useState("");
+ const [consent, setConsent] = useState(false);
+ const [trap, setTrap] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [done, setDone] = useState(false);
+ async function submit(event: React.FormEvent) {
+ event.preventDefault();
+ setError("");
+ // Honeypot: Bots füllen das versteckte Feld, Menschen nicht.
+ if (trap) {
+ setDone(true);
+ return;
+ }
+ setBusy(true);
+ try {
+ await repository().joinWaitlist(name, email);
+ setDone(true);
+ } catch (err) {
+ setError(
+ err instanceof Error
+ ? err.message
+ : "Das hat gerade nicht geklappt. Bitte versuche es noch einmal.",
+ );
+ } finally {
+ setBusy(false);
+ }
+ }
+ return (
+
+
+ BALD GEHT DIE TÜR AUF.
+
+ Setz dich
+
+ auf die
+
+ Liste.
+
+
+
+
+ Moin!
+
+ Ich merk mir dich.
+
+
+
Karl-Dieter schreibt dich auf.
+
+
+
+
+
+ Moin!
+
+ Ich merk mir dich.
+
+
+
+
+
+ {done ? (
+
+
+ Du stehst
+
+ auf der Liste.
+
+
+ Danke, {name.trim().split(" ")[0] || "Mensch"}! Sobald dein Platz
+ frei ist, bekommst du dein Goldenes Ticket per E-Mail an{" "}
+ {email.trim()}. Wenn du dich schon eingetragen
+ hattest, bleibt alles beim Alten.
+
+
+ Zur Startseite →
+
+
+ ) : (
+ <>
+
+ Noch kein Ticket?
+
+ Kein Problem.
+
+
+ Humans Only startet mit der Vibecoding-Germany-Community. Trag
+ dich ein, wir schalten dich frei und schicken dir dein Goldenes
+ Ticket per Mail.
+
Dieser Bereich ist für die Admins von Humans Only reserviert.
+
+ Zurück ins Clubhaus
+
+
+
+ );
+
+ function inviteUrl(ticket: Ticket) {
+ return `${window.location.origin}/invite?code=${encodeURIComponent(ticket.code)}`;
+ }
+ function mailto(entry: WaitlistEntry, ticket: Ticket) {
+ const first = entry.name.split(" ")[0];
+ const until = new Date(ticket.expires_at).toLocaleDateString("de-DE");
+ const body = [
+ `Moin ${first},`,
+ "",
+ "du hattest dich auf die Warteliste von Humans Only gesetzt – jetzt ist dein Platz frei!",
+ "",
+ "Mit diesem Goldenen Ticket kommst du ins Clubhaus und direkt in den Raum Vibecoding Germany:",
+ inviteUrl(ticket),
+ "",
+ `Das Ticket ist bis ${until} gültig und nur einmal einlösbar. Beim Eintreten nimmst du eine kurze Sprach-Vorstellung auf (höchstens 15 Sekunden) – so wissen alle, dass hier echte Menschen sind.`,
+ "",
+ "Bis gleich im Clubhaus!",
+ me?.display_name || "",
+ ].join("\n");
+ // "@" bleibt lesbar (manche Mailprogramme dekodieren %40 nicht); nur URL-Sonderzeichen kodieren.
+ const to = entry.email.replace(/[?%\s]/g, encodeURIComponent);
+ return `mailto:${to}?subject=${encodeURIComponent(
+ "Dein Goldenes Ticket für Humans Only",
+ )}&body=${encodeURIComponent(body)}`;
+ }
+ async function run(id: string, action: () => Promise, message: string) {
+ setBusy(id);
+ try {
+ await action();
+ await refresh();
+ notify(message);
+ } catch (err) {
+ report(err);
+ } finally {
+ setBusy("");
+ }
+ }
+ const demoNote = mail.simulated ? " (Demo: keine echte Mail verschickt)" : "";
+ function invite(entry: WaitlistEntry) {
+ return run(
+ entry.id,
+ () => repository().sendWaitlistInvite(entry.id),
+ `Einladung an ${entry.email} ist raus.${demoNote}`,
+ );
+ }
+ async function inviteAllPending() {
+ const queue = state.waitlist
+ .filter((e) => e.status === "pending")
+ .sort((a, b) => a.created_at.localeCompare(b.created_at));
+ setBulk("running");
+ let sent = 0;
+ try {
+ for (const entry of queue) {
+ setProgress(`${sent + 1} von ${queue.length}: ${entry.name}`);
+ await repository().sendWaitlistInvite(entry.id);
+ sent += 1;
+ }
+ notify(`${sent} Einladungen verschickt.${demoNote}`);
+ } catch (err) {
+ report(
+ new Error(
+ `${sent} von ${queue.length} verschickt, dann Abbruch: ${
+ err instanceof Error ? err.message : "unbekannter Fehler"
+ }`,
+ ),
+ );
+ } finally {
+ setBulk("idle");
+ setProgress("");
+ await refresh();
+ }
+ }
+ async function copy(entry: WaitlistEntry, ticket: Ticket) {
+ const url = inviteUrl(ticket);
+ try {
+ if (!navigator.clipboard) throw new Error();
+ await navigator.clipboard.writeText(url);
+ setCopied(entry.id);
+ } catch {
+ setFallback(url);
+ }
+ }
+
+ return (
+
+
+
+ ADMIN · WARTELISTE
+
+ Wer darf
+
+ rein?
+
+
+ Freigeben stellt ein Goldenes Ticket für Vibecoding Germany aus.
+ Dein eigenes Drei-Ticket-Budget bleibt unberührt.{" "}
+ {mail.enabled
+ ? "Die Einladung geht direkt per Mail raus."
+ : "Danach Mail schreiben oder Link kopieren und verschicken."}
+
+ {query
+ ? "Niemand passt zu deiner Suche."
+ : filter === "pending"
+ ? "Keine offenen Anfragen. Zeit für einen Kaffee."
+ : "Hier ist noch niemand."}
+
+ Freigegebene Tickets sind 30 Tage gültig und nur einmal einlösbar. Im
+ Profil der neuen Person steht „Eingeladen von @{me.username}“. Löschen
+ entfernt nur den Wartelisten-Eintrag; ein schon verschicktes Ticket
+ bleibt gültig.
+
+
+ );
+}
diff --git a/app/lib/mail.ts b/app/lib/mail.ts
new file mode 100644
index 0000000..fceac8a
--- /dev/null
+++ b/app/lib/mail.ts
@@ -0,0 +1,118 @@
+// Nur serverseitig verwenden. SMTP-Zugangsdaten kommen ausschließlich aus Server-Umgebungsvariablen
+// (niemals NEXT_PUBLIC_*), damit sie nicht in Browser-Bundles landen.
+export type MailConfig =
+ | { enabled: false; reason: string }
+ | {
+ enabled: true;
+ host: string;
+ port: number;
+ secure: boolean;
+ user: string;
+ password: string;
+ from: string;
+ replyTo: string;
+ siteUrl: string;
+ };
+
+type MailEnv = {
+ SMTP_HOST?: string;
+ SMTP_PORT?: string;
+ SMTP_USER?: string;
+ SMTP_PASSWORD?: string;
+ SMTP_FROM?: string;
+ SMTP_REPLY_TO?: string;
+ SITE_URL?: string;
+};
+
+export function readMailConfig(env: MailEnv): MailConfig {
+ const host = env.SMTP_HOST?.trim();
+ const from = env.SMTP_FROM?.trim();
+ const site = env.SITE_URL?.trim();
+ if (!host || !from || !site)
+ return {
+ enabled: false,
+ reason: "SMTP_HOST, SMTP_FROM und SITE_URL sind nicht gesetzt.",
+ };
+ let siteUrl: string;
+ try {
+ const url = new URL(site);
+ if (url.protocol !== "https:" && url.hostname !== "localhost")
+ throw new Error();
+ siteUrl = url.origin;
+ } catch {
+ return { enabled: false, reason: "SITE_URL ist keine gültige https-URL." };
+ }
+ const port = Number(env.SMTP_PORT || 587);
+ if (!Number.isInteger(port) || port < 1 || port > 65535)
+ return { enabled: false, reason: "SMTP_PORT ist ungültig." };
+ return {
+ enabled: true,
+ host,
+ port,
+ secure: port === 465,
+ user: env.SMTP_USER?.trim() || "",
+ password: env.SMTP_PASSWORD || "",
+ from,
+ replyTo: env.SMTP_REPLY_TO?.trim() || "",
+ siteUrl,
+ };
+}
+
+function escapeHtml(value: string) {
+ return value
+ .replaceAll("&", "&")
+ .replaceAll("<", "<")
+ .replaceAll(">", ">")
+ .replaceAll('"', """)
+ .replaceAll("'", "'");
+}
+
+export function buildInviteMail(input: {
+ name: string;
+ code: string;
+ expiresAt: string;
+ inviterName: string;
+ siteUrl: string;
+ canReply: boolean;
+}) {
+ const footer = input.canReply
+ ? "Du bekommst diese Mail, weil du dich auf der Warteliste von Humans Only eingetragen hast. Antworte einfach, wenn wir deinen Eintrag löschen sollen."
+ : "Du bekommst diese Mail, weil du dich auf der Warteliste von Humans Only eingetragen hast.";
+ const first = input.name.trim().split(/\s+/)[0] || "Mensch";
+ const url = `${input.siteUrl}/invite?code=${encodeURIComponent(input.code)}`;
+ const until = new Date(input.expiresAt).toLocaleDateString("de-DE", {
+ timeZone: "Europe/Berlin",
+ });
+ const subject = "Dein Goldenes Ticket für Humans Only";
+ const text = [
+ `Moin ${first},`,
+ "",
+ "du hattest dich auf die Warteliste von Humans Only gesetzt – jetzt ist dein Platz frei!",
+ "",
+ "Mit diesem Goldenen Ticket kommst du ins Clubhaus und direkt in den Raum Vibecoding Germany:",
+ url,
+ "",
+ `Das Ticket ist bis ${until} gültig und nur einmal einlösbar. Beim Eintreten nimmst du eine kurze Sprach-Vorstellung auf (höchstens 15 Sekunden) – so wissen alle, dass hier echte Menschen sind.`,
+ "",
+ "Bis gleich im Clubhaus!",
+ input.inviterName,
+ "",
+ "--",
+ footer,
+ ].join("\n");
+ const html = `
+
+
HUMANS ONLY®
+
+
Moin ${escapeHtml(first)},
+
du hattest dich auf die Warteliste von Humans Only gesetzt – jetzt ist dein Platz frei!
+
Mit deinem Goldenen Ticket kommst du ins Clubhaus und direkt in den Raum Vibecoding Germany.
Gültig bis ${escapeHtml(until)}, nur einmal einlösbar. Beim Eintreten nimmst du eine kurze Sprach-Vorstellung auf (höchstens 15 Sekunden) – so wissen alle, dass hier echte Menschen sind.
+
Falls der Button nicht geht: ${escapeHtml(url)}
+
Bis gleich im Clubhaus! ${escapeHtml(input.inviterName)}
+
+
${escapeHtml(footer)}
+
`;
+ return { subject, text, html, url };
+}
diff --git a/app/lib/model.ts b/app/lib/model.ts
index b922e4f..d908a00 100644
--- a/app/lib/model.ts
+++ b/app/lib/model.ts
@@ -65,6 +65,19 @@ export type ContentVote = {
vote: Vote;
created_at: string;
};
+export type WaitlistStatus = "pending" | "approved" | "rejected";
+export type WaitlistEntry = {
+ id: string;
+ name: string;
+ email: string;
+ status: WaitlistStatus;
+ ticket_id: string | null;
+ created_at: string;
+ decided_at: string | null;
+ decided_by: string | null;
+ invited_at: string | null;
+ invite_count: number;
+};
export type Snapshot = {
profiles: Profile[];
spaces: Space[];
@@ -73,6 +86,9 @@ export type Snapshot = {
tickets: Ticket[];
votes: ContentVote[];
currentUserId: string | null;
+ /** Nur für Admins gefüllt; für alle anderen leer. */
+ waitlist: WaitlistEntry[];
+ isAdmin: boolean;
};
export type InvitePreview = {
valid: boolean;
@@ -132,3 +148,12 @@ export function validatePost(input: PostInput) {
)
throw new Error("Sprachnotizen dürfen 1 bis 60 Sekunden dauern.");
}
+export function validateWaitlist(name: string, email: string) {
+ const cleanName = name.trim();
+ const cleanEmail = email.trim().toLowerCase();
+ if (!cleanName || cleanName.length > 80)
+ throw new Error("Bitte gib deinen Namen mit höchstens 80 Zeichen ein.");
+ if (cleanEmail.length > 254 || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(cleanEmail))
+ throw new Error("Bitte gib eine gültige E-Mail-Adresse ein.");
+ return { name: cleanName, email: cleanEmail };
+}
diff --git a/app/lib/repositories/contract.ts b/app/lib/repositories/contract.ts
index a074963..178530a 100644
--- a/app/lib/repositories/contract.ts
+++ b/app/lib/repositories/contract.ts
@@ -21,4 +21,14 @@ export interface ClubhouseRepository {
hasSession(): Promise;
signOut(): Promise;
subscribe(onChange: () => void): () => void;
+ /** Öffentlich: gleiche Antwort für neue und bereits bekannte Adressen. */
+ joinWaitlist(name: string, email: string): Promise;
+ /** Admin: stellt ein Goldenes Ticket aus (ohne eigenes Budget) und gibt es zurück. */
+ approveWaitlist(entryId: string): Promise;
+ /** Admin: ist automatischer Mailversand auf dem Server eingerichtet? */
+ mailStatus(): Promise<{ enabled: boolean; simulated: boolean }>;
+ /** Admin: freigeben (falls nötig) und Einladungsmail über den Server verschicken. */
+ sendWaitlistInvite(entryId: string): Promise;
+ rejectWaitlist(entryId: string): Promise;
+ deleteWaitlist(entryId: string): Promise;
}
diff --git a/app/lib/repositories/demo.ts b/app/lib/repositories/demo.ts
index d130389..77a3f9a 100644
--- a/app/lib/repositories/demo.ts
+++ b/app/lib/repositories/demo.ts
@@ -1,5 +1,10 @@
import { createDemoSnapshot } from "@/lib/seed";
-import { moderationStatus, validateIdentity, validatePost } from "@/lib/model";
+import {
+ moderationStatus,
+ validateIdentity,
+ validatePost,
+ validateWaitlist,
+} from "@/lib/model";
import type {
Bucket,
OnboardingInput,
@@ -163,6 +168,91 @@ export function addDemoPost(state: Snapshot, input: PostInput) {
created_at: new Date().toISOString(),
});
}
+function demoIsAdmin(state: Snapshot) {
+ return state.spaces.some(
+ (s) => s.owner_id !== null && s.owner_id === state.currentUserId,
+ );
+}
+function requireAdmin(state: Snapshot) {
+ if (!demoIsAdmin(state)) throw new Error("Dafür brauchst du Admin-Rechte.");
+}
+function findEntry(state: Snapshot, entryId: string) {
+ const entry = state.waitlist.find((e) => e.id === entryId);
+ if (!entry) throw new Error("Dieser Eintrag existiert nicht mehr.");
+ return entry;
+}
+export function joinDemoWaitlist(
+ state: Snapshot,
+ name: string,
+ email: string,
+ now = new Date(),
+) {
+ const clean = validateWaitlist(name, email);
+ if (state.waitlist.some((e) => e.email.toLowerCase() === clean.email)) return;
+ state.waitlist.push({
+ id: newId(),
+ name: clean.name,
+ email: clean.email,
+ status: "pending",
+ ticket_id: null,
+ created_at: now.toISOString(),
+ decided_at: null,
+ decided_by: null,
+ invited_at: null,
+ invite_count: 0,
+ });
+}
+export function approveDemoWaitlist(
+ state: Snapshot,
+ entryId: string,
+ now = new Date(),
+) {
+ requireAdmin(state);
+ const entry = findEntry(state, entryId);
+ const existing = state.tickets.find((t) => t.id === entry.ticket_id);
+ 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.");
+ const ticket = {
+ id: newId(),
+ code: newId().replaceAll("-", "").toUpperCase(),
+ creator_id: state.currentUserId!,
+ target_space_id: space.id,
+ redeemed_by_id: null,
+ redeemed_at: null,
+ expires_at: new Date(now.getTime() + 30 * 86400000).toISOString(),
+ };
+ state.tickets.push(ticket);
+ entry.status = "approved";
+ entry.ticket_id = ticket.id;
+ entry.decided_at = now.toISOString();
+ entry.decided_by = state.currentUserId;
+ return ticket;
+}
+/** Demo: simuliert den Versand und protokolliert ihn nur lokal. */
+export function inviteDemoWaitlist(state: Snapshot, entryId: string) {
+ const ticket = approveDemoWaitlist(state, entryId);
+ if (ticket.redeemed_at)
+ throw new Error("Das Ticket wurde schon eingelöst. Keine neue Mail nötig.");
+ const entry = findEntry(state, entryId);
+ entry.invited_at = new Date().toISOString();
+ entry.invite_count += 1;
+}
+export function rejectDemoWaitlist(state: Snapshot, entryId: string) {
+ requireAdmin(state);
+ const entry = findEntry(state, entryId);
+ if (entry.status === "approved")
+ throw new Error("Dieser Mensch ist schon freigegeben und hat ein Ticket.");
+ entry.status = "rejected";
+ entry.decided_at = new Date().toISOString();
+ entry.decided_by = state.currentUserId;
+}
+export function deleteDemoWaitlist(state: Snapshot, entryId: string) {
+ requireAdmin(state);
+ findEntry(state, entryId);
+ state.waitlist = state.waitlist.filter((e) => e.id !== entryId);
+}
export function validateUpload(bucket: Bucket, file: Blob) {
const type = file.type.split(";")[0];
const image = ["image/jpeg", "image/png", "image/webp"].includes(type);
@@ -205,6 +295,8 @@ export function createDemoRepository(): ClubhouseRepository {
!Array.isArray(state.spaces)
)
throw new Error();
+ // Ältere Demo-Stände kannten noch keine Warteliste.
+ if (!Array.isArray(state.waitlist)) state.waitlist = [];
return state;
} catch {
throw new Error(
@@ -232,7 +324,9 @@ export function createDemoRepository(): ClubhouseRepository {
}
return {
async load() {
- return read();
+ const state = read();
+ const isAdmin = demoIsAdmin(state);
+ return { ...state, isAdmin, waitlist: isAdmin ? state.waitlist : [] };
},
async inspectInvite(code) {
const state = read();
@@ -289,6 +383,19 @@ export function createDemoRepository(): ClubhouseRepository {
state.currentUserId = null;
});
},
+ joinWaitlist: (name, email) =>
+ mutate((state) => joinDemoWaitlist(state, name, email)),
+ approveWaitlist: (entryId) =>
+ mutate((state) => approveDemoWaitlist(state, entryId)),
+ async mailStatus() {
+ return { enabled: true, simulated: true };
+ },
+ sendWaitlistInvite: (entryId) =>
+ mutate((state) => inviteDemoWaitlist(state, entryId)),
+ rejectWaitlist: (entryId) =>
+ mutate((state) => rejectDemoWaitlist(state, entryId)),
+ deleteWaitlist: (entryId) =>
+ mutate((state) => deleteDemoWaitlist(state, entryId)),
subscribe(onChange) {
const storage = (event: StorageEvent) => {
if (event.key === DEMO_STORAGE_KEY) onChange();
diff --git a/app/lib/repositories/supabase.ts b/app/lib/repositories/supabase.ts
index e5f581b..e30e157 100644
--- a/app/lib/repositories/supabase.ts
+++ b/app/lib/repositories/supabase.ts
@@ -1,5 +1,5 @@
import { browserClient } from "@/lib/supabase/browser";
-import { validateIdentity, validatePost } from "@/lib/model";
+import { validateIdentity, validatePost, validateWaitlist } from "@/lib/model";
import { newId, validateUpload } from "./demo";
import type { Bucket, Snapshot } from "@/lib/model";
import type { ClubhouseRepository } from "./contract";
@@ -15,6 +15,14 @@ const messages: Record = {
SELF_VOTE_FORBIDDEN: "Über eigene Beiträge stimmt deine Nachbarschaft ab.",
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.",
+ INVALID_EMAIL: "Bitte gib eine gültige E-Mail-Adresse ein.",
+ WAITLIST_BUSY:
+ "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.",
+ WAITLIST_ALREADY_APPROVED:
+ "Dieser Mensch ist schon freigegeben und hat ein Ticket.",
};
function check(error: { message: string; code?: string } | null) {
if (!error) return;
@@ -69,8 +77,10 @@ export function createSupabaseRepository(): ClubhouseRepository {
tickets: [],
votes: [],
currentUserId: null,
+ waitlist: [],
+ isAdmin: false,
};
- const [p, s, m, posts, t, v] = await Promise.all([
+ const [p, s, m, posts, t, v, admin] = await Promise.all([
client.from("profiles").select("*"),
client.from("spaces").select("*"),
client.from("space_members").select("*"),
@@ -81,8 +91,19 @@ export function createSupabaseRepository(): ClubhouseRepository {
.limit(100),
client.from("invite_tickets").select("*"),
client.from("content_votes").select("*"),
+ client.rpc("is_admin"),
]);
- [p, s, m, posts, t, v].forEach((r) => check(r.error));
+ [p, s, m, posts, t, v, admin].forEach((r) => check(r.error));
+ let waitlist: Snapshot["waitlist"] = [];
+ if (admin.data) {
+ const w = await client
+ .from("waitlist_entries")
+ .select("*")
+ .order("created_at", { ascending: true })
+ .limit(1000);
+ check(w.error);
+ waitlist = w.data || [];
+ }
const [avatarUrl, voiceUrl, postUrl] = await Promise.all([
signPaths(
"avatars",
@@ -115,6 +136,8 @@ export function createSupabaseRepository(): ClubhouseRepository {
tickets: t.data || [],
votes: v.data || [],
currentUserId: auth.user.id,
+ waitlist,
+ isAdmin: Boolean(admin.data),
};
return snapshot;
},
@@ -212,6 +235,62 @@ export function createSupabaseRepository(): ClubhouseRepository {
check(error);
signed.clear();
},
+ async joinWaitlist(name, email) {
+ const clean = validateWaitlist(name, email);
+ const { error } = await client.rpc("join_waitlist", {
+ p_name: clean.name,
+ p_email: clean.email,
+ });
+ check(error);
+ },
+ async approveWaitlist(entryId) {
+ const { data, error } = await client.rpc("approve_waitlist_entry", {
+ p_entry_id: entryId,
+ });
+ check(error);
+ return data!;
+ },
+ async mailStatus() {
+ try {
+ const res = await fetch("/api/admin/waitlist/invite", {
+ cache: "no-store",
+ });
+ const body = (await res.json()) as { enabled?: boolean };
+ return { enabled: Boolean(res.ok && body.enabled), simulated: false };
+ } catch {
+ return { enabled: false, simulated: false };
+ }
+ },
+ async sendWaitlistInvite(entryId) {
+ const res = await fetch("/api/admin/waitlist/invite", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ "x-humans-only": "admin",
+ },
+ body: JSON.stringify({ entryId }),
+ });
+ if (!res.ok) {
+ const body = (await res.json().catch(() => ({}))) as {
+ error?: string;
+ };
+ throw new Error(
+ body.error || "Die Einladung konnte nicht verschickt werden.",
+ );
+ }
+ },
+ async rejectWaitlist(entryId) {
+ const { error } = await client.rpc("reject_waitlist_entry", {
+ p_entry_id: entryId,
+ });
+ check(error);
+ },
+ async deleteWaitlist(entryId) {
+ const { error } = await client.rpc("delete_waitlist_entry", {
+ p_entry_id: entryId,
+ });
+ check(error);
+ },
subscribe(onChange) {
let scheduled: ReturnType | undefined;
const schedule = () => {
diff --git a/app/lib/seed.ts b/app/lib/seed.ts
index 2b9ce55..986ffab 100644
--- a/app/lib/seed.ts
+++ b/app/lib/seed.ts
@@ -56,6 +56,33 @@ export function createDemoSnapshot(): Snapshot {
return {
profiles,
currentUserId: ids[0],
+ isAdmin: true,
+ waitlist: [
+ {
+ id: "50000000-0000-4000-8000-000000000001",
+ name: "Paula Beispiel",
+ email: "paula@example.org",
+ status: "pending",
+ ticket_id: null,
+ created_at: "2026-11-08T09:30:00.000Z",
+ decided_at: null,
+ decided_by: null,
+ invited_at: null,
+ invite_count: 0,
+ },
+ {
+ id: "50000000-0000-4000-8000-000000000002",
+ name: "Ben Muster",
+ email: "ben@example.org",
+ status: "pending",
+ ticket_id: null,
+ created_at: "2026-11-08T18:05:00.000Z",
+ decided_at: null,
+ decided_by: null,
+ invited_at: null,
+ invite_count: 0,
+ },
+ ],
spaces: [
{
id: SPACE_ID,
diff --git a/app/lib/supabase/database.ts b/app/lib/supabase/database.ts
index 2ad62c6..cbb008a 100644
--- a/app/lib/supabase/database.ts
+++ b/app/lib/supabase/database.ts
@@ -6,6 +6,7 @@ import type {
ContentVote,
Ticket,
InvitePreview,
+ WaitlistEntry,
} from "@/lib/model";
type Table = {
Row: T;
@@ -22,6 +23,7 @@ export type Database = {
posts: Table;
content_votes: Table;
invite_tickets: Table;
+ waitlist_entries: Table;
};
Views: Record;
Functions: {
@@ -53,6 +55,24 @@ export type Database = {
Args: { p_post_id: string; p_vote: string };
Returns: Post;
};
+ is_admin: { Args: Record; Returns: boolean };
+ join_waitlist: {
+ Args: { p_name: string; p_email: string };
+ Returns: undefined;
+ };
+ approve_waitlist_entry: { Args: { p_entry_id: string }; Returns: Ticket };
+ reject_waitlist_entry: {
+ Args: { p_entry_id: string };
+ Returns: undefined;
+ };
+ mark_waitlist_invited: {
+ Args: { p_entry_id: string };
+ Returns: WaitlistEntry;
+ };
+ delete_waitlist_entry: {
+ Args: { p_entry_id: string };
+ Returns: undefined;
+ };
};
Enums: Record;
CompositeTypes: Record;
diff --git a/app/package-lock.json b/app/package-lock.json
index 3968a2c..0cff61d 100644
--- a/app/package-lock.json
+++ b/app/package-lock.json
@@ -14,6 +14,7 @@
"@supabase/supabase-js": "^2.0.0",
"lucide-react": "^0.468.0",
"next": "15.5.29",
+ "nodemailer": "10.2.1",
"qrcode.react": "^4.2.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
@@ -22,6 +23,7 @@
"@eslint/eslintrc": "^3.0.0",
"@tailwindcss/typography": "^0.5.16",
"@types/node": "^22.0.0",
+ "@types/nodemailer": "^8.0.2",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"autoprefixer": "^10.4.20",
@@ -342,6 +344,111 @@
"node": ">= 10"
}
},
+ "node_modules/@next/swc-darwin-x64": {
+ "version": "15.5.29",
+ "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.29.tgz",
+ "integrity": "sha512-FzrcEzMZVcp/SqFXCW5SXyPil10bB9l5wpTBapEs9ZMqke3W+hyC5mNAdAa1divn+4SZ7LD5BtK67XvK7SucWQ==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-gnu": {
+ "version": "15.5.29",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.29.tgz",
+ "integrity": "sha512-FWbWE5P313Yy5062vgY9UspNz/t6Ve/s35X9v6YU7ilsbhqKGabPBPIWcMEPhyomeRdwfv19NAITkU2FFIhGwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-arm64-musl": {
+ "version": "15.5.29",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.29.tgz",
+ "integrity": "sha512-xjTHrVisb9GeDSNFOwJI+4UJrKdwlpjz95q8sEvQh46yUp3+JikNcf26pode/HlHktSdJwcHx3iVMCjfPcnU+A==",
+ "cpu": [
+ "arm64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-gnu": {
+ "version": "15.5.29",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.29.tgz",
+ "integrity": "sha512-5WqW7kHscT02wyF8TlbYv9+zx3KhnQeZwk+FkTCr1r7TuvMrqqOZ3RDkdDKl3O0M0Er3VuQEzoEIrj8VX5fjaw==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-linux-x64-musl": {
+ "version": "15.5.29",
+ "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.29.tgz",
+ "integrity": "sha512-I0QJ1Be9vtdq5FABhNcSbkELllA91WnhG+m4BjJHCn1bXAIL8AuDABIKIJ7Bz84T/sIkZP6TvOEWJcKckrX3yQ==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-arm64-msvc": {
+ "version": "15.5.29",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.29.tgz",
+ "integrity": "sha512-q4fQFWtR7nH7ZDhU8RIvwNW0S/nHImaZkoOSw7rOXFgoP51HTesm8/8P/w3ACjc9GxqytXj0LZZesykK3arFBw==",
+ "cpu": [
+ "arm64"
+ ],
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@next/swc-win32-x64-msvc": {
+ "version": "15.5.29",
+ "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.29.tgz",
+ "integrity": "sha512-putWQ+CTEJunAPIPDPfb06Kc4emhYpdM5FoCDHSkC/ym7Dy2xOBMPgBjBbRkw2Hp5/550ACYxCmUtV4k4ui3Iw==",
+ "cpu": [
+ "x64"
+ ],
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"dev": true,
@@ -916,6 +1023,16 @@
"undici-types": "~6.21.0"
}
},
+ "node_modules/@types/nodemailer": {
+ "version": "8.0.2",
+ "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.2.tgz",
+ "integrity": "sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/react": {
"version": "19.3.0",
"devOptional": true,
@@ -3725,6 +3842,15 @@
"node": ">=18"
}
},
+ "node_modules/nodemailer": {
+ "version": "10.2.1",
+ "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-10.2.1.tgz",
+ "integrity": "sha512-ZrDNsPFoDMwefNs7sJwrYiEJ/CG4ClJWDZv05iNJsEBWa8GRDry1QJHTJxsuTAY9eDDKjX4k+q3SxslXJOao7w==",
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
"node_modules/normalize-path": {
"version": "3.0.0",
"dev": true,
@@ -5429,111 +5555,6 @@
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
- },
- "node_modules/@next/swc-darwin-x64": {
- "version": "15.5.29",
- "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.5.29.tgz",
- "integrity": "sha512-FzrcEzMZVcp/SqFXCW5SXyPil10bB9l5wpTBapEs9ZMqke3W+hyC5mNAdAa1divn+4SZ7LD5BtK67XvK7SucWQ==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-arm64-gnu": {
- "version": "15.5.29",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.5.29.tgz",
- "integrity": "sha512-FWbWE5P313Yy5062vgY9UspNz/t6Ve/s35X9v6YU7ilsbhqKGabPBPIWcMEPhyomeRdwfv19NAITkU2FFIhGwA==",
- "cpu": [
- "arm64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-arm64-musl": {
- "version": "15.5.29",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.5.29.tgz",
- "integrity": "sha512-xjTHrVisb9GeDSNFOwJI+4UJrKdwlpjz95q8sEvQh46yUp3+JikNcf26pode/HlHktSdJwcHx3iVMCjfPcnU+A==",
- "cpu": [
- "arm64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-x64-gnu": {
- "version": "15.5.29",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.5.29.tgz",
- "integrity": "sha512-5WqW7kHscT02wyF8TlbYv9+zx3KhnQeZwk+FkTCr1r7TuvMrqqOZ3RDkdDKl3O0M0Er3VuQEzoEIrj8VX5fjaw==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-linux-x64-musl": {
- "version": "15.5.29",
- "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.5.29.tgz",
- "integrity": "sha512-I0QJ1Be9vtdq5FABhNcSbkELllA91WnhG+m4BjJHCn1bXAIL8AuDABIKIJ7Bz84T/sIkZP6TvOEWJcKckrX3yQ==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "linux"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-win32-arm64-msvc": {
- "version": "15.5.29",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.5.29.tgz",
- "integrity": "sha512-q4fQFWtR7nH7ZDhU8RIvwNW0S/nHImaZkoOSw7rOXFgoP51HTesm8/8P/w3ACjc9GxqytXj0LZZesykK3arFBw==",
- "cpu": [
- "arm64"
- ],
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- }
- },
- "node_modules/@next/swc-win32-x64-msvc": {
- "version": "15.5.29",
- "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.5.29.tgz",
- "integrity": "sha512-putWQ+CTEJunAPIPDPfb06Kc4emhYpdM5FoCDHSkC/ym7Dy2xOBMPgBjBbRkw2Hp5/550ACYxCmUtV4k4ui3Iw==",
- "cpu": [
- "x64"
- ],
- "optional": true,
- "os": [
- "win32"
- ],
- "engines": {
- "node": ">= 10"
- }
}
}
}
diff --git a/app/package.json b/app/package.json
index 3bfcf60..fc6ef2d 100644
--- a/app/package.json
+++ b/app/package.json
@@ -16,30 +16,32 @@
"test": "tsx --test tests/*.test.ts"
},
"dependencies": {
- "next": "15.5.29",
- "react": "^19.1.0",
- "react-dom": "^19.1.0",
- "@supabase/supabase-js": "^2.0.0",
- "@supabase/ssr": "^0.8.0",
"@radix-ui/react-dialog": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
+ "@supabase/ssr": "^0.8.0",
+ "@supabase/supabase-js": "^2.0.0",
"lucide-react": "^0.468.0",
- "qrcode.react": "^4.2.0"
+ "next": "15.5.29",
+ "nodemailer": "10.2.1",
+ "qrcode.react": "^4.2.0",
+ "react": "^19.1.0",
+ "react-dom": "^19.1.0"
},
"devDependencies": {
- "typescript": "~5.9.3",
+ "@eslint/eslintrc": "^3.0.0",
+ "@tailwindcss/typography": "^0.5.16",
"@types/node": "^22.0.0",
+ "@types/nodemailer": "^8.0.2",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
+ "autoprefixer": "^10.4.20",
"eslint": "^9.0.0",
"eslint-config-next": "15.5.29",
- "@eslint/eslintrc": "^3.0.0",
+ "postcss": "^8.5.0",
"tailwindcss": "^3.4.17",
"tailwindcss-animate": "^1.0.7",
- "@tailwindcss/typography": "^0.5.16",
- "postcss": "^8.5.0",
- "autoprefixer": "^10.4.20",
- "tsx": "^4.19.0"
+ "tsx": "^4.19.0",
+ "typescript": "~5.9.3"
},
"overrides": {
"next": {
diff --git a/app/tests/domain.test.ts b/app/tests/domain.test.ts
index 7b6dee2..5ee82bf 100644
--- a/app/tests/domain.test.ts
+++ b/app/tests/domain.test.ts
@@ -159,3 +159,43 @@ test("status ordering and username constraints", () => {
/15 Sekunden/,
);
});
+test("waitlist join is case-insensitive idempotent and validates input", async () => {
+ const { joinDemoWaitlist } = await import("../lib/repositories/demo");
+ const s = createDemoSnapshot();
+ const before = s.waitlist.length;
+ joinDemoWaitlist(s, " Erika Muster ", "Erika@Example.org");
+ joinDemoWaitlist(s, "Erika Doppelt", "erika@example.ORG");
+ assert.equal(s.waitlist.length, before + 1);
+ const entry = s.waitlist.at(-1)!;
+ assert.equal(entry.name, "Erika Muster");
+ assert.equal(entry.email, "erika@example.org");
+ assert.equal(entry.status, "pending");
+ assert.throws(() => joinDemoWaitlist(s, "X", "kein-mail"), /E-Mail/);
+ assert.throws(() => joinDemoWaitlist(s, " ", "a@b.de"), /Namen/);
+});
+test("admin approval issues a ticket without consuming the admin budget", async () => {
+ const { approveDemoWaitlist, rejectDemoWaitlist, deleteDemoWaitlist } =
+ await import("../lib/repositories/demo");
+ const s = createDemoSnapshot();
+ const admin = s.profiles[0];
+ const budget = admin.invites_left;
+ const [first, second] = s.waitlist;
+ const ticket = approveDemoWaitlist(s, first.id);
+ assert.equal(admin.invites_left, budget);
+ assert.equal(first.status, "approved");
+ assert.equal(first.ticket_id, ticket.id);
+ assert.equal(ticket.creator_id, admin.id);
+ assert.equal(ticket.target_space_id, SPACE_ID);
+ assert.equal(approveDemoWaitlist(s, first.id).id, ticket.id);
+ assert.throws(() => rejectDemoWaitlist(s, first.id), /freigegeben/);
+ rejectDemoWaitlist(s, second.id);
+ assert.equal(second.status, "rejected");
+ deleteDemoWaitlist(s, second.id);
+ assert(!s.waitlist.some((e) => e.id === second.id));
+});
+test("non-admins cannot approve waitlist entries", async () => {
+ const { approveDemoWaitlist } = await import("../lib/repositories/demo");
+ const s = createDemoSnapshot();
+ s.currentUserId = s.profiles[1].id;
+ assert.throws(() => approveDemoWaitlist(s, s.waitlist[0].id), /Admin/);
+});
diff --git a/app/tests/mail.test.ts b/app/tests/mail.test.ts
new file mode 100644
index 0000000..53fde20
--- /dev/null
+++ b/app/tests/mail.test.ts
@@ -0,0 +1,58 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { buildInviteMail, readMailConfig } from "../lib/mail";
+import { createDemoSnapshot } from "../lib/seed";
+import { inviteDemoWaitlist } from "../lib/repositories/demo";
+
+test("mail stays disabled until host, sender and https site URL are set", () => {
+ assert.equal(readMailConfig({}).enabled, false);
+ assert.equal(
+ readMailConfig({ SMTP_HOST: "smtp.example.org", SMTP_FROM: "a@b.de" })
+ .enabled,
+ false,
+ );
+ assert.equal(
+ readMailConfig({
+ SMTP_HOST: "smtp.example.org",
+ SMTP_FROM: "a@b.de",
+ SITE_URL: "http://humans-only.de",
+ }).enabled,
+ false,
+ );
+ const cfg = readMailConfig({
+ SMTP_HOST: "smtp.example.org",
+ SMTP_PORT: "465",
+ SMTP_FROM: "Humans Only ",
+ SITE_URL: "https://humans-only.de/irgendwas",
+ });
+ assert(cfg.enabled);
+ assert.equal(cfg.siteUrl, "https://humans-only.de");
+ assert.equal(cfg.secure, true);
+ assert.equal(cfg.port, 465);
+});
+test("invite mail uses the canonical site URL and escapes names", () => {
+ const mail = buildInviteMail({
+ name: 'Eve "Hack"',
+ code: "ABC123",
+ expiresAt: "2026-12-09T10:00:00.000Z",
+ inviterName: "Dennis",
+ siteUrl: "https://humans-only.de",
+ canReply: false,
+ });
+ assert.equal(mail.url, "https://humans-only.de/invite?code=ABC123");
+ assert(mail.text.includes(mail.url));
+ assert(mail.text.includes("9.12.2026"));
+ assert(!mail.html.includes("Eve"));
+ assert(mail.html.includes("<b>Eve</b>"));
+ assert(!mail.text.includes("Antworte"));
+});
+test("demo invite approves once and logs each send", () => {
+ const s = createDemoSnapshot();
+ const entry = s.waitlist[0];
+ inviteDemoWaitlist(s, entry.id);
+ inviteDemoWaitlist(s, entry.id);
+ assert.equal(entry.status, "approved");
+ assert.equal(entry.invite_count, 2);
+ assert(entry.invited_at);
+ assert.equal(s.tickets.filter((t) => t.id === entry.ticket_id).length, 1);
+});
diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md
index 906b2d2..379c296 100644
--- a/docs/DEPLOYMENT.md
+++ b/docs/DEPLOYMENT.md
@@ -9,7 +9,7 @@ Stand 2026-11-07. Dieses Dokument beschreibt die **neue** Anwendung. Die ursprü
## Neue Supabase-Instanz
1. Neues Projekt erstellen. Auth, PostgreSQL und Storage sind gemeinsame Infrastruktur für Web/Flutter.
-2. Migration `supabase/migrations/0001_humans_only_v2_core.sql` anwenden, danach `supabase/seed.sql`. Nicht gegen die Legacy-Datenbank ausführen.
+2. Migrationen `supabase/migrations/0001_humans_only_v2_core.sql` und `0002_waitlist.sql` in dieser Reihenfolge anwenden, danach `supabase/seed.sql`. Nicht gegen die Legacy-Datenbank ausführen.
3. Für den ersten Gastgeber einen echten Auth-Account im Dashboard erstellen bzw. per Login anlegen. Mit administrativer DB-Verbindung `supabase/bootstrap-owner.sql` und den dort genannten `psql -v`-Argumenten ausführen. Seed zuerst; derselbe Owner ist wiederholbar, ein anderer Owner wird zurückgewiesen. Der Scriptaufruf zeigt keine DB-Passwörter im Beispiel.
4. In Supabase Auth den gewünschten Site URL setzen und exakte Redirect-URLs erlauben, z. B. `https://club.example.org/auth/callback` und für lokale Tests `http://localhost:3000/auth/callback`. Keine beliebigen Redirect-Wildcards nötig.
5. Für PKCE-Magic-Links das Supabase-Mailtemplate mit `{{ .ConfirmationURL }}` verwenden. Wer alternativ den sichtbaren E-Mail-Code-Einstieg nutzt, ergänzt im Template `{{ .Token }}`. Supabase Mail/SMTP, Versandlimits und Bestätigung am echten Projekt prüfen. Die UI unterstützt einen wiederkehrenden Member-Login ohne neues Ticket. Ausstehende Tickets werden maximal eine Stunde browserlokal vorgemerkt; bei einem anderen Gerät muss der Code erneut eingegeben werden.
@@ -46,6 +46,14 @@ Lokal geprüftes SQL ist nicht dasselbe wie ein gehosteter Integrationstest. Am
- Safari/iOS und Android: Audioformat, Permission-Abbruch, 15-/60-Sekunden-Stopp, Playback, QR-Link und PWA-Installation.
- Supabase Auth-Rate-Limits, E-Mail-Zustellung, Backups und vertrauenswürdige Wartung für nicht referenzierte Uploads passend zum Betrieb konfigurieren. Keine falschen Identitäts-/Anti-Bot-Garantien aus Voice-Aufnahmen ableiten.
+## Warteliste und Admin-Bereich
+
+`/warteliste` ist öffentlich: Name, E-Mail und Einwilligung. `/admin` zeigt Admins (`private.admins`) offene, freigegebene und abgelehnte Einträge. „Freigeben & einladen“ stellt ein Goldenes Ticket aus und verschickt die Einladung direkt; „Alle offenen einladen“ arbeitet die Liste nacheinander ab. Jeder erfolgreiche Versand wird protokolliert (`invited_at`, `invite_count`).
+
+Der Versand läuft serverseitig über `POST /api/admin/waitlist/invite` und denselben SMTP-Zugang, den Vibecoding Germany und Supabase-Auth nutzen. Die Route handelt mit der Sitzung der angemeldeten Person; Admin-Rechte prüft die Datenbank. Dafür in der `.env.production` des Releases auf dem VPS **ohne** `NEXT_PUBLIC_`-Präfix setzen: `SITE_URL=https://humans-only.de`, `SMTP_HOST`, `SMTP_PORT` (587 STARTTLS oder 465 TLS), `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_FROM` (z. B. `Humans Only `), optional `SMTP_REPLY_TO`. Die Werte werden zur Laufzeit gelesen; nach Änderung den PM2-Prozess neu starten. Zugangsdaten nie ins Repository. Ohne diese Werte fällt der Admin-Bereich auf „Mail schreiben“ (eigenes Mailprogramm) und „Link kopieren“ zurück. Versandlimits des SMTP-Anbieters beachten; bei einem Fehler bricht „Alle einladen“ ab und meldet, wie viele raus sind.
+
+**Reihenfolge am bestehenden Live-Projekt:** zuerst `0002_waitlist.sql` anwenden (macht den vorhandenen Gastgeber automatisch zum Admin), danach die neue Web-Version ausrollen. Die neue Web-Version ruft `is_admin()` beim Laden auf und funktioniert ohne Migration nicht. Weitere Admins nur per vertrauenswürdiger DB-Verbindung: `insert into private.admins(user_id) values('');`.
+
`can_invite=false` für ein Profil entzieht dessen Ausgabe- und Einlöserechte auch für bestehende Tickets. Das setzt nur eine vertrauenswürdige Administration, keine Browser-Komponente. Automatische Sanktionen und ein Admin-UI sind nicht Teil des Durchstichs.
## Produktiver Stand — 2026-11-07
diff --git a/docs/FLUTTER_CONTRACT.md b/docs/FLUTTER_CONTRACT.md
index 289a9c1..4f0ea8b 100644
--- a/docs/FLUTTER_CONTRACT.md
+++ b/docs/FLUTTER_CONTRACT.md
@@ -106,6 +106,21 @@ Status-Reihenfolge ist deterministisch:
Stabile Fehlermeldungen: `AUTH_REQUIRED`, `PROFILE_REQUIRED`, `INVALID_TICKET`, `ALREADY_ONBOARDED`, `INVITES_REVOKED`, `NO_INVITES_LEFT`, `SPACE_FORBIDDEN`, `VOICE_REQUIRED`, `INVALID_PARENT`, `INVALID_MEDIA`, `POST_FORBIDDEN`, `SELF_VOTE_FORBIDDEN`, `INVALID_VOTE`. Berechtigungsfehler nutzen überwiegend SQLSTATE `42501`; Eindeutigkeitsfehler `23505`, Constraints `23514`. Fehler lokal übersetzen und Inputs behalten. Fehlerstatus niemals als Erfolg behandeln.
+### Warteliste (Migration `0002_waitlist.sql`)
+
+Zusätzliche, rein additive Tabelle `waitlist_entries` (`id`, `name`, `email`, `status` = `pending|approved|rejected`, `ticket_id`, `created_at`, `decided_at`, `decided_by`, `invited_at`, `invite_count`). Die sechs Kern-Tabellen bleiben unverändert. Admins stehen in `private.admins` (kein Client-Zugriff); der Gastgeber von Vibecoding Germany ist erster Admin.
+
+| RPC | Rolle | Verhalten |
+| :--- | :--- | :--- |
+| `join_waitlist(p_name, p_email)` | anon, authenticated | Trägt ein. Gleiche Antwort für neue und bekannte Adressen (E-Mail case-insensitiv eindeutig). Fehler: `INVALID_NAME`, `INVALID_EMAIL`, `WAITLIST_BUSY` (mehr als 60 Einträge in 10 Minuten). |
+| `is_admin()` | authenticated | `true` für Admins. |
+| `approve_waitlist_entry(p_entry_id)` | Admin | Stellt ein Goldenes Ticket für Vibecoding Germany aus (30 Tage, `creator_id` = Admin), ohne `invites_left` zu verbrauchen. Wiederholung liefert dasselbe gültige Ticket, nach Ablauf ein neues. Gibt `invite_tickets` zurück. |
+| `reject_waitlist_entry(p_entry_id)` | Admin | Nur für nicht freigegebene Einträge (`WAITLIST_ALREADY_APPROVED`). |
+| `mark_waitlist_invited(p_entry_id)` | Admin | Protokolliert einen erfolgreichen Mailversand (nur freigegebene Einträge, sonst `WAITLIST_NOT_APPROVED`). Den Versand selbst übernimmt der Web-Server. |
+| `delete_waitlist_entry(p_entry_id)` | Admin | Löscht den Eintrag (z. B. auf Wunsch). Ein bereits ausgestelltes Ticket bleibt gültig. |
+
+`waitlist_entries` ist nur für Admins per `select` lesbar; direkte Schreibzugriffe sind gesperrt. Fehler ohne Admin-Rechte: `ADMIN_REQUIRED`.
+
## 4. Lesen, RLS und Realtime
RLS ist auf allen sechs Tabellen aktiv. Anonyme Nutzer sehen keine Clubdaten; nur die schmale Ticketvorschau ist öffentlich. Authentifizierte Nutzer ohne Profil sehen ebenfalls keine Clubdaten. Mitglieder lesen Profile, Raum-Metadaten, die Lobby und ihre eigenen Räume. `space_members` ist nur innerhalb eigener Räume sichtbar. `invite_tickets` sehen nur Aussteller oder eingelöster Gast; `content_votes` nur der eigene Voter. Der Client darf auf den Tabellen ausschließlich lesen, alle fachlichen Änderungen laufen über RPC.
diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md
index 8acf97c..7cc707f 100644
--- a/docs/VALIDATION.md
+++ b/docs/VALIDATION.md
@@ -1,5 +1,13 @@
# Validierung — Humans Only 2.0
+## Warteliste (Branch `feat/waitlist`, 2026-11-09, lokal)
+
+- SQL-Vertragstest `python3 supabase/tests/contract.py` auf isoliertem PostgreSQL: 74/74 bestanden, davon 23 neue Wartelisten-Prüfungen (anonymes Eintragen, case-insensitive Idempotenz, Validierung, keine anonymen/Nicht-Admin-Lesezugriffe, keine Direktwrites, Freigabe ohne Budgetverbrauch, wiederholte Freigabe, Ablehnen/Löschen, Admin-Backfill aus bestehendem Owner).
+- `npm run lint`, `npm run typecheck`, `npm test` (21/21) und `npm run build` grün.
+- Demo-Modus im Browser bei 375 px und Desktop: Eintragen, Admin-Liste, Freigabe, vorausgefüllte Mail, Ticket-Wallet unverändert, Nicht-Admin sieht `/admin` gesperrt und keinen Navigationseintrag. Kein horizontales Scrollen.
+- Mailversand: SQL-Protokollierung (`mark_waitlist_invited`) in den 74 SQL-Prüfungen; Konfigurations-, Escaping- und Demo-Tests (21/21 App-Tests); Versand der echten Mail-Vorlage über nodemailer an einen lokalen SMTP-Testserver angenommen; HTML-Mail visuell geprüft; Admin-UI mit simuliertem Versand inkl. „Alle einladen“ geprüft.
+- Nicht nachgewiesen: Migration, `join_waitlist` und die Versand-Route am gehosteten Supabase-Projekt mit echter Sitzung, echte Zustellung über den Vibecoding-Germany-SMTP (Spam-Einstufung, Limits).
+
## Callback-Regression 2026-11-07
Der Benutzer bestätigt den Empfang der Anmeldemail. Supabase protokolliert den erfolgreichen PKCE-Codeaustausch; die anschließende Weiterleitung führt jedoch zu `https://localhost:3218/onboarding`. Auch der Aufruf ohne Code ist auf beiden öffentlichen Domains reproduzierbar betroffen: HTTP 307 mit `Location: https://localhost:3218/invite?auth_error=1`.
diff --git a/supabase/bootstrap-owner.sql b/supabase/bootstrap-owner.sql
index 58bc80d..e4c9db9 100644
--- a/supabase/bootstrap-owner.sql
+++ b/supabase/bootstrap-owner.sql
@@ -9,13 +9,17 @@ begin
select * into room from public.spaces where slug='vibecoding-germany' for update;
if room.id is null then raise exception 'Run seed.sql first'; end if;
if room.owner_id is not null then
- if room.owner_id=desired and exists(select 1 from public.space_members where space_id=room.id and user_id=desired and role='owner') then return; end if;
+ if room.owner_id=desired and exists(select 1 from public.space_members where space_id=room.id and user_id=desired and role='owner') then
+ if to_regclass('private.admins') is not null then execute 'insert into private.admins(user_id) values($1) on conflict do nothing' using desired; end if;
+ return;
+ end if;
raise exception 'Space already has a different owner; no profile was created';
end if;
insert into public.profiles(id,username,display_name,bio)
values(desired,lower(current_setting('ho.bootstrap_username')),current_setting('ho.bootstrap_name'),'Gastgeber von Vibecoding Germany.');
update public.spaces set owner_id=desired where id=room.id;
insert into public.space_members(space_id,user_id,role) values(room.id,desired,'owner');
+ if to_regclass('private.admins') is not null then execute 'insert into private.admins(user_id) values($1) on conflict do nothing' using desired; end if;
end;
$$;
commit;
diff --git a/supabase/migrations/0002_waitlist.sql b/supabase/migrations/0002_waitlist.sql
new file mode 100644
index 0000000..cc9097e
--- /dev/null
+++ b/supabase/migrations/0002_waitlist.sql
@@ -0,0 +1,130 @@
+-- Humans Only 2.0 — Warteliste und Admin-Freigabe.
+-- Additiv: die sechs Kern-Tabellen und ihre RPCs bleiben unverändert.
+-- Admins liegen in private.admins (kein Client-Zugriff). Die Warteliste ist nur für Admins lesbar.
+begin;
+
+create table private.admins (
+ user_id uuid primary key references public.profiles(id) on delete cascade,
+ created_at timestamptz not null default now()
+);
+revoke all on private.admins from public, anon, authenticated;
+-- Der bestehende Gastgeber von Vibecoding Germany wird erster Admin (idempotent).
+insert into private.admins(user_id)
+select owner_id from public.spaces where slug='vibecoding-germany' and owner_id is not null
+on conflict do nothing;
+
+create function private.is_admin() returns boolean
+language sql stable security definer set search_path = ''
+as $$ select exists(select 1 from private.admins where user_id = (select auth.uid())); $$;
+revoke all on function private.is_admin() from public, anon;
+grant execute on function private.is_admin() to authenticated;
+
+create table public.waitlist_entries (
+ id uuid primary key default gen_random_uuid(),
+ name text not null check (length(btrim(name)) between 1 and 80),
+ email text not null check (length(email) <= 254 and email ~ '^[^@\s]+@[^@\s]+\.[^@\s]+$'),
+ status text not null default 'pending' check (status in ('pending','approved','rejected')),
+ ticket_id uuid unique references public.invite_tickets(id) on delete set null,
+ created_at timestamptz not null default now(),
+ decided_at timestamptz,
+ decided_by uuid references public.profiles(id) on delete set null,
+ invited_at timestamptz,
+ invite_count integer not null default 0 check (invite_count >= 0),
+ check ((status = 'pending') = (decided_at is null))
+);
+create unique index waitlist_unique_email on public.waitlist_entries(lower(email));
+create index waitlist_by_status on public.waitlist_entries(status, created_at);
+alter table public.waitlist_entries enable row level security;
+revoke all on public.waitlist_entries from anon, authenticated;
+grant select on public.waitlist_entries to authenticated;
+create policy waitlist_admin_read on public.waitlist_entries for select to authenticated using ((select private.is_admin()));
+
+create function public.is_admin() returns boolean
+language sql stable security definer set search_path = ''
+as $$ select private.is_admin(); $$;
+
+-- Öffentlich: gleiche Antwort für neue und bekannte Adressen (keine Enumeration).
+create function public.join_waitlist(p_name text, p_email text) returns void
+language plpgsql security definer set search_path = ''
+as $$
+declare clean_name text := btrim(coalesce(p_name,'')); clean_email text := lower(btrim(coalesce(p_email,'')));
+begin
+ if length(clean_name) not between 1 and 80 then raise exception 'INVALID_NAME'; end if;
+ if length(clean_email) > 254 or clean_email !~ '^[^@\s]+@[^@\s]+\.[^@\s]+$' then raise exception 'INVALID_EMAIL'; end if;
+ -- Grobe globale Bremse gegen Massen-Eintragungen.
+ if (select count(*) from public.waitlist_entries where created_at > now() - interval '10 minutes') >= 60 then
+ raise exception 'WAITLIST_BUSY';
+ end if;
+ insert into public.waitlist_entries(name,email) values(clean_name,clean_email)
+ on conflict ((lower(email))) do nothing;
+end;
+$$;
+
+-- Admin: stellt ein Goldenes Ticket für Vibecoding Germany aus, ohne das eigene Drei-Ticket-Budget zu verbrauchen.
+-- Wiederholte Freigabe liefert das vorhandene Ticket zurück.
+create function public.approve_waitlist_entry(p_entry_id uuid) returns public.invite_tickets
+language plpgsql security definer set search_path = ''
+as $$
+declare entry public.waitlist_entries; room public.spaces; result public.invite_tickets;
+begin
+ if not private.is_admin() then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if;
+ select * into entry from public.waitlist_entries where id=p_entry_id for update;
+ if entry.id is null then raise exception 'WAITLIST_NOT_FOUND'; end if;
+ if entry.ticket_id is not null then
+ select * into result from public.invite_tickets where id=entry.ticket_id;
+ if result.id is not null and (result.redeemed_at is not null or result.expires_at > now()) then
+ update public.waitlist_entries set status='approved', decided_at=coalesce(decided_at,now()), decided_by=coalesce(decided_by,auth.uid()) where id=entry.id;
+ return result;
+ end if;
+ end if;
+ select * into room from public.spaces where slug='vibecoding-germany' and owner_id is not null and access_type='invite';
+ if room.id is null or not private.in_space(room.id) then raise exception 'SPACE_FORBIDDEN' using errcode='42501'; end if;
+ insert into public.invite_tickets(code,creator_id,target_space_id)
+ values(upper(replace(gen_random_uuid()::text,'-','') || replace(gen_random_uuid()::text,'-','')),auth.uid(),room.id) returning * into result;
+ update public.waitlist_entries set status='approved', ticket_id=result.id, decided_at=now(), decided_by=auth.uid() where id=entry.id;
+ return result;
+end;
+$$;
+
+create function public.reject_waitlist_entry(p_entry_id uuid) returns void
+language plpgsql security definer set search_path = ''
+as $$
+declare entry public.waitlist_entries;
+begin
+ if not private.is_admin() then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if;
+ select * into entry from public.waitlist_entries where id=p_entry_id for update;
+ if entry.id is null then raise exception 'WAITLIST_NOT_FOUND'; end if;
+ if entry.status='approved' then raise exception 'WAITLIST_ALREADY_APPROVED'; end if;
+ update public.waitlist_entries set status='rejected', decided_at=now(), decided_by=auth.uid() where id=entry.id;
+end;
+$$;
+
+-- Löschen auf Wunsch der Person (DSGVO). Ein bereits ausgestelltes Ticket bleibt gültig.
+create function public.delete_waitlist_entry(p_entry_id uuid) returns void
+language plpgsql security definer set search_path = ''
+as $$
+begin
+ if not private.is_admin() then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if;
+ delete from public.waitlist_entries where id=p_entry_id;
+ if not found then raise exception 'WAITLIST_NOT_FOUND'; end if;
+end;
+$$;
+
+-- Admin: protokolliert den erfolgreichen Mailversand (die Mail selbst verschickt der Web-Server per SMTP).
+create function public.mark_waitlist_invited(p_entry_id uuid) returns public.waitlist_entries
+language plpgsql security definer set search_path = ''
+as $$
+declare result public.waitlist_entries;
+begin
+ if not private.is_admin() then raise exception 'ADMIN_REQUIRED' using errcode='42501'; end if;
+ update public.waitlist_entries set invited_at=now(), invite_count=invite_count+1
+ where id=p_entry_id and status='approved' and ticket_id is not null returning * into result;
+ if result.id is null then raise exception 'WAITLIST_NOT_APPROVED'; end if;
+ return result;
+end;
+$$;
+
+revoke all on function public.is_admin(), public.join_waitlist(text,text), public.approve_waitlist_entry(uuid), public.reject_waitlist_entry(uuid), public.delete_waitlist_entry(uuid), public.mark_waitlist_invited(uuid) from public, anon, authenticated;
+grant execute on function public.join_waitlist(text,text) to anon, authenticated;
+grant execute on function public.is_admin(), public.approve_waitlist_entry(uuid), public.reject_waitlist_entry(uuid), public.delete_waitlist_entry(uuid), public.mark_waitlist_invited(uuid) to authenticated;
+commit;
diff --git a/supabase/tests/contract.py b/supabase/tests/contract.py
index 2d68ebb..7828568 100644
--- a/supabase/tests/contract.py
+++ b/supabase/tests/contract.py
@@ -60,6 +60,8 @@ def deny(name,uid,query,expected):
check('migration and idempotent seed execute',sql('select count(*) from public.spaces').stdout.strip()=='1')
sql('insert into auth.users(id) values '+','.join("('"+u(i)+"')" for i in range(1,41)))
load(root/'supabase/bootstrap-owner.sql',['-v','owner_id='+u(1),'-v','username=owner','-v','display_name=Owner'])
+ load(root/'supabase/migrations/0002_waitlist.sql')
+ check('waitlist migration makes existing owner admin',sql("select count(*) from private.admins where user_id='"+u(1)+"'").stdout.strip()=='1')
check('owner bootstrap binds owner and membership',sql("select count(*) from public.spaces s join public.space_members m on m.space_id=s.id where s.owner_id='"+u(1)+"' and m.user_id=s.owner_id and m.role='owner'").stdout.strip()=='1')
load(root/'supabase/bootstrap-owner.sql',['-v','owner_id='+u(1),'-v','username=owner','-v','display_name=Owner'])
check('same-owner bootstrap is idempotent',sql("select count(*) from public.space_members where user_id='"+u(1)+"'").stdout.strip()=='1')
@@ -133,6 +135,39 @@ def redeem(n): return asuser(u(n),"select (public.redeem_invite('"+tickets[0]+"'
r=asuser(u(6),"delete from storage.objects where name='"+u(6)+"/room.png'",False)
check('objects cannot be deleted',r.returncode!=0 or 'DELETE 0' in r.stdout)
check('all buckets private',sql('select bool_and(not public) from storage.buckets').stdout.strip()=='t')
+ # Warteliste
+ asuser('',"select public.join_waitlist('Erika Muster','Erika@Example.org')",role='anon')
+ asuser('',"select public.join_waitlist('Erika Doppelt','erika@example.ORG ')",role='anon')
+ check('waitlist join is case-insensitive idempotent',sql("select count(*)||','||min(name) from public.waitlist_entries").stdout.strip()=='1,Erika Muster')
+ asuser('',"select public.join_waitlist('Max','max@example.org')",role='anon')
+ r=asuser('',"select public.join_waitlist('Bad','not-an-email')",False,role='anon'); check('waitlist rejects invalid email',r.returncode!=0 and 'INVALID_EMAIL' in r.stderr)
+ r=asuser('',"select public.join_waitlist(' ','a@b.de')",False,role='anon'); check('waitlist rejects blank name',r.returncode!=0 and 'INVALID_NAME' in r.stderr)
+ r=asuser('','select * from public.waitlist_entries',False,role='anon'); check('anonymous cannot read waitlist',r.returncode!=0 and 'permission denied' in r.stderr)
+ deny('anonymous cannot insert waitlist directly','',"insert into public.waitlist_entries(name,email) values ('x','x@y.de')",'permission denied')
+ check('member without admin sees no waitlist',scalar(u(6),'select count(*) from public.waitlist_entries')=='0')
+ check('is_admin false for member',scalar(u(6),'select public.is_admin()')=='f')
+ check('is_admin true for owner',scalar(u(1),'select public.is_admin()')=='t')
+ entry=sql("select id from public.waitlist_entries where email='erika@example.org'").stdout.strip()
+ other=sql("select id from public.waitlist_entries where email='max@example.org'").stdout.strip()
+ deny('member cannot approve waitlist',u(6),"select public.approve_waitlist_entry('"+entry+"')",'ADMIN_REQUIRED')
+ deny('direct waitlist status change denied',u(1),"update public.waitlist_entries set status='approved'",'permission denied')
+ check('admin reads waitlist',scalar(u(1),'select count(*) from public.waitlist_entries')=='2')
+ budget=sql("select invites_left from public.profiles where id='"+u(1)+"'").stdout.strip()
+ code=scalar(u(1),"select (public.approve_waitlist_entry('"+entry+"')).code")
+ check('approval issues valid invite',json.loads(scalar('',"select public.inspect_invite('"+code+"')"))['valid'])
+ check('approval does not consume admin budget',sql("select invites_left from public.profiles where id='"+u(1)+"'").stdout.strip()==budget)
+ check('approval links ticket and status',sql("select e.status||','||(t.code='"+code+"') from public.waitlist_entries e join public.invite_tickets t on t.id=e.ticket_id where e.id='"+entry+"'").stdout.strip()=='approved,true')
+ check('repeat approval returns same ticket',scalar(u(1),"select (public.approve_waitlist_entry('"+entry+"')).code")==code)
+ deny('approved entry cannot be rejected',u(1),"select public.reject_waitlist_entry('"+entry+"')",'WAITLIST_ALREADY_APPROVED')
+ deny('member cannot mark invited',u(6),"select public.mark_waitlist_invited('"+entry+"')",'ADMIN_REQUIRED')
+ deny('pending entry cannot be marked invited',u(1),"select public.mark_waitlist_invited('"+other+"')",'WAITLIST_NOT_APPROVED')
+ asuser(u(1),"select public.mark_waitlist_invited('"+entry+"')"); asuser(u(1),"select public.mark_waitlist_invited('"+entry+"')")
+ check('invite mail is logged per send',sql("select invite_count||','||(invited_at is not null) from public.waitlist_entries where id='"+entry+"'").stdout.strip()=='2,true')
+ asuser(u(1),"select public.reject_waitlist_entry('"+other+"')")
+ check('reject marks entry',sql("select status||','||(decided_by='"+u(1)+"') from public.waitlist_entries where id='"+other+"'").stdout.strip()=='rejected,true')
+ asuser(u(1),"select public.delete_waitlist_entry('"+other+"')")
+ check('admin can delete entry',sql("select count(*) from public.waitlist_entries where id='"+other+"'").stdout.strip()=='0')
+ deny('member cannot delete entry',u(6),"select public.delete_waitlist_entry('"+entry+"')",'ADMIN_REQUIRED')
r=cmd(['psql','-X','-v','ON_ERROR_STOP=1','-v','owner_id='+u(40),'-v','username=wrongowner','-v','display_name=Wrong Owner','-f',str(root/'supabase/bootstrap-owner.sql')],env=env)
exists=sql("select count(*) from public.profiles where id='"+u(40)+"'").stdout.strip()
check('bootstrap refuses a different existing owner without side effects',r.returncode!=0 and exists=='0','exit='+str(r.returncode)+', newly admitted profile='+exists)