From 2dd97aa25053e560be89856cb034686c2ffbcae3 Mon Sep 17 00:00:00 2001 From: Dennis Westermann Date: Mon, 9 Nov 2026 09:54:43 +0100 Subject: [PATCH] feat: add waitlist with admin approval and invite mails Community members can join a public waitlist (/warteliste) with name, email and consent. Admins approve entries in /admin, which issues a Golden Ticket for Vibecoding Germany without consuming their own three-ticket budget, and sends the invitation via the existing Vibecoding Germany SMTP account (server-side env only). Without SMTP configuration the admin area falls back to mailto and copy-link. - supabase: additive migration 0002 (waitlist_entries, private.admins, join/approve/reject/delete/mark-invited RPCs), owner backfilled as admin - app: waitlist page, admin page, invite API route, nodemailer 10.2.1 - tests: 74 SQL contract checks, 21 app tests - docs: deployment order, SMTP env vars, Flutter contract, validation Co-Authored-By: Claude Opus 5.5 --- app/.env.example | 10 + app/app/admin/page.tsx | 9 + app/app/api/admin/waitlist/invite/route.ts | 124 ++++ app/app/globals.css | 212 +++++++ app/app/warteliste/page.tsx | 10 + app/components/clubhouse.tsx | 13 +- app/components/invite-flow.tsx | 6 + app/components/provider.tsx | 2 + app/components/shell.tsx | 17 +- app/components/tickets.tsx | 6 +- app/components/waitlist.tsx | 669 +++++++++++++++++++++ app/lib/mail.ts | 118 ++++ app/lib/model.ts | 25 + app/lib/repositories/contract.ts | 10 + app/lib/repositories/demo.ts | 111 +++- app/lib/repositories/supabase.ts | 85 ++- app/lib/seed.ts | 27 + app/lib/supabase/database.ts | 20 + app/package-lock.json | 231 +++---- app/package.json | 26 +- app/tests/domain.test.ts | 40 ++ app/tests/mail.test.ts | 58 ++ docs/DEPLOYMENT.md | 10 +- docs/FLUTTER_CONTRACT.md | 15 + docs/VALIDATION.md | 8 + supabase/bootstrap-owner.sql | 6 +- supabase/migrations/0002_waitlist.sql | 130 ++++ supabase/tests/contract.py | 35 ++ 28 files changed, 1903 insertions(+), 130 deletions(-) create mode 100644 app/app/admin/page.tsx create mode 100644 app/app/api/admin/waitlist/invite/route.ts create mode 100644 app/app/warteliste/page.tsx create mode 100644 app/components/waitlist.tsx create mode 100644 app/lib/mail.ts create mode 100644 app/tests/mail.test.ts create mode 100644 supabase/migrations/0002_waitlist.sql diff --git a/app/.env.example b/app/.env.example index 0dc783d..a484728 100644 --- a/app/.env.example +++ b/app/.env.example @@ -4,3 +4,13 @@ NEXT_PUBLIC_DATA_MODE=demo NEXT_PUBLIC_SUPABASE_URL= NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY= # Never put a service-role key in this app. +# Optional, server-only (never NEXT_PUBLIC_*): automatic waitlist invitation mails. +# Without these values the admin area offers "Mail schreiben" (own mail client) and "Link kopieren". +# Enter real credentials only on the server, never in the repository. +SITE_URL=https://humans-only.de +SMTP_HOST= +SMTP_PORT=587 +SMTP_USER= +SMTP_PASSWORD= +SMTP_FROM=Humans Only +SMTP_REPLY_TO= diff --git a/app/app/admin/page.tsx b/app/app/admin/page.tsx new file mode 100644 index 0000000..7369649 --- /dev/null +++ b/app/app/admin/page.tsx @@ -0,0 +1,9 @@ +import type { Metadata } from "next"; +import { AdminPage } from "@/components/waitlist"; +export const metadata: Metadata = { + title: "Admin · Warteliste", + robots: { index: false, follow: false }, +}; +export default function Page() { + return ; +} diff --git a/app/app/api/admin/waitlist/invite/route.ts b/app/app/api/admin/waitlist/invite/route.ts new file mode 100644 index 0000000..d80f6a0 --- /dev/null +++ b/app/app/api/admin/waitlist/invite/route.ts @@ -0,0 +1,124 @@ +import { NextResponse } from "next/server"; +import { config } from "@/lib/config"; +import { buildInviteMail, readMailConfig } from "@/lib/mail"; +import { serverClient } from "@/lib/supabase/server"; + +export const runtime = "nodejs"; +export const dynamic = "force-dynamic"; + +const noStore = { "Cache-Control": "private, no-store" }; +const messages: Record = { + ADMIN_REQUIRED: "Dafür brauchst du Admin-Rechte.", + WAITLIST_NOT_FOUND: "Dieser Eintrag existiert nicht mehr.", + WAITLIST_NOT_APPROVED: "Dieser Eintrag ist noch nicht freigegeben.", + SPACE_FORBIDDEN: "Der Raum Vibecoding Germany vergibt gerade keine Tickets.", +}; +function fail(status: number, error: string) { + return NextResponse.json({ error }, { status, headers: noStore }); +} +function mailConfig() { + const env = process.env; + return readMailConfig({ + SMTP_HOST: env.SMTP_HOST, + SMTP_PORT: env.SMTP_PORT, + SMTP_USER: env.SMTP_USER, + SMTP_PASSWORD: env.SMTP_PASSWORD, + SMTP_FROM: env.SMTP_FROM, + SMTP_REPLY_TO: env.SMTP_REPLY_TO, + SITE_URL: env.SITE_URL, + }); +} + +export async function GET() { + const mail = config.mode === "supabase" ? mailConfig() : null; + return NextResponse.json( + { enabled: Boolean(mail?.enabled) }, + { headers: noStore }, + ); +} + +export async function POST(request: Request) { + if (config.mode !== "supabase") + return fail(404, "Mailversand gibt es nur im Live-Betrieb."); + // CSRF-Schutz: Fremde Seiten können diesen Header nicht ohne CORS-Preflight setzen. + if ( + request.headers.get("x-humans-only") !== "admin" || + !request.headers.get("content-type")?.startsWith("application/json") + ) + return fail(403, "Ungültige Anfrage."); + const mail = mailConfig(); + if (!mail.enabled) + return fail(503, "Mailversand ist auf dem Server nicht eingerichtet."); + let entryId = ""; + try { + const body = (await request.json()) as { entryId?: unknown }; + if (typeof body.entryId === "string") entryId = body.entryId; + } catch {} + if (!/^[0-9a-f-]{36}$/i.test(entryId)) return fail(400, "Ungültiger Eintrag."); + + const client = await serverClient(); + const { data: auth } = await client.auth.getUser(); + if (!auth.user) return fail(401, "Bitte melde dich zuerst an."); + + // Rechte prüft die Datenbank (ADMIN_REQUIRED); die Route handelt als angemeldete Person. + const approved = await client.rpc("approve_waitlist_entry", { + p_entry_id: entryId, + }); + if (approved.error) + return fail( + approved.error.code === "42501" ? 403 : 400, + messages[approved.error.message] || "Die Freigabe hat nicht geklappt.", + ); + const ticket = approved.data!; + if (ticket.redeemed_at) + return fail(409, "Das Ticket wurde schon eingelöst. Keine neue Mail nötig."); + const [entry, inviter] = await Promise.all([ + client.from("waitlist_entries").select("*").eq("id", entryId).single(), + client + .from("profiles") + .select("display_name") + .eq("id", auth.user.id) + .single(), + ]); + if (entry.error || !entry.data) return fail(404, messages.WAITLIST_NOT_FOUND); + + const message = buildInviteMail({ + name: entry.data.name, + code: ticket.code, + expiresAt: ticket.expires_at, + inviterName: inviter.data?.display_name || "Dein Humans-Only-Team", + siteUrl: mail.siteUrl, + canReply: Boolean(mail.replyTo), + }); + try { + const { createTransport } = await import("nodemailer"); + const transport = createTransport({ + host: mail.host, + port: mail.port, + secure: mail.secure, + requireTLS: !mail.secure && mail.host !== "localhost" && mail.host !== "127.0.0.1", + auth: mail.user ? { user: mail.user, pass: mail.password } : undefined, + }); + await transport.sendMail({ + from: mail.from, + to: entry.data.email, + replyTo: mail.replyTo || undefined, + subject: message.subject, + text: message.text, + html: message.html, + }); + } catch (err) { + // Keine SMTP-Details an den Browser; im Server-Log steht der Grund. + console.error("waitlist invite mail failed", entryId, err); + return fail( + 502, + "Freigegeben, aber die Mail konnte nicht verschickt werden. Versuch es gleich noch einmal oder kopiere den Link.", + ); + } + const marked = await client.rpc("mark_waitlist_invited", { + p_entry_id: entryId, + }); + if (marked.error) + console.error("waitlist invite mark failed", entryId, marked.error.message); + return NextResponse.json({ ok: true }, { headers: noStore }); +} diff --git a/app/app/globals.css b/app/app/globals.css index 8e30786..ebee528 100644 --- a/app/app/globals.css +++ b/app/app/globals.css @@ -3167,3 +3167,215 @@ textarea::placeholder { @media (max-width: 760px) { .hero-scribble { display: none; } } +/* Warteliste und Admin-Freigabe. */ +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} +.waitlist-trap { + position: absolute; + left: -10000px; + width: 1px; + height: 1px; + overflow: hidden; +} +label.consent { + display: flex; + gap: 10px; + align-items: flex-start; + font-weight: 400; + font-size: 11px; + line-height: 1.55; + color: var(--ink-muted); + margin: 18px 0 4px; + cursor: pointer; +} +label.consent input[type="checkbox"] { + width: 18px; + height: 18px; + flex: none; + margin-top: 1px; + accent-color: var(--blue); +} +.waitlist-hint { + font-size: 12px; + margin: 16px 0 0; + color: var(--ink-muted); +} +.waitlist-hint a { + font-weight: 700; + color: var(--ink); + text-decoration: underline; + text-underline-offset: 4px; +} +.waitlist-done p { + font-size: 13px; + line-height: 1.65; + color: var(--ink-muted); + margin-bottom: 20px; + overflow-wrap: anywhere; +} +.waitlist-done p strong { + color: var(--ink); +} +.welcome-actions { + display: flex; + flex-wrap: wrap; + gap: 12px; + justify-content: center; +} +.admin-page { + max-width: 900px; +} +.admin-toolbar { + display: flex; + flex-wrap: wrap; + gap: 12px; + align-items: center; + justify-content: space-between; + margin: 28px 0 18px; +} +.admin-filters { + display: flex; + flex-wrap: wrap; + gap: 8px; +} +.admin-filters button { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 7px 12px; + border: 1.5px solid var(--line); + border-radius: 999px; + font-size: 12px; + font-weight: 700; + background: var(--surface-raised); +} +.admin-filters button .nav-count { + font-size: 13px; + width: 20px; + height: 20px; + line-height: 17px; +} +.admin-filters button.active { + background: var(--mango); + color: var(--on-mango); + border-color: var(--on-mango); + box-shadow: 2px 2px 0 var(--on-mango); +} +.admin-filters button.active .nav-count { + border-color: var(--on-mango); +} +.admin-search { + display: flex; + align-items: center; + gap: 8px; + margin: 0; + flex: 1 1 220px; + max-width: 320px; +} +.admin-search input:not([type="range"]):not([type="file"]) { + padding: 9px 11px; + font-size: 13px; +} +.admin-list { + list-style: none; + padding: 0; + margin: 0; + display: grid; + gap: 10px; +} +.admin-row { + display: flex; + flex-wrap: wrap; + gap: 14px; + align-items: center; + justify-content: space-between; + background: var(--surface-raised); + border: 2px solid var(--line); + border-radius: 8px; + padding: 14px 16px; + box-shadow: 3px 3px 0 var(--line); +} +.admin-row.status-rejected { + opacity: 0.7; + box-shadow: none; +} +.admin-person { + display: grid; + gap: 2px; + min-width: 0; + flex: 1 1 240px; +} +.admin-person strong { + font-size: 15px; +} +.admin-person a { + font-size: 13px; + text-decoration: underline; + text-underline-offset: 3px; + overflow-wrap: anywhere; +} +.admin-person small { + font-size: 11px; + color: var(--ink-muted); +} +.admin-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + align-items: center; +} +.admin-actions .button { + font-size: 12px; + padding: 8px 12px; +} +.admin-confirm { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 12px; + font-weight: 700; +} +.admin-empty { + padding: 40px 10px; + text-align: center; + color: var(--ink-muted); + font-size: 14px; + border: 1.5px dashed var(--ink-muted); + border-radius: 8px; +} +.admin-note { + margin-top: 22px; +} +@media (max-width: 760px) { + .admin-search { + max-width: none; + } + .admin-actions { + width: 100%; + } + .admin-page .wallet-heading > .mascot { + display: none; + } +} +.admin-bulk { + display: flex; + flex-wrap: wrap; + gap: 10px; + align-items: center; + margin: 0 0 16px; + font-size: 13px; + font-weight: 700; +} +.admin-bulk .button { + font-size: 12px; + padding: 8px 12px; +} diff --git a/app/app/warteliste/page.tsx b/app/app/warteliste/page.tsx new file mode 100644 index 0000000..297f59a --- /dev/null +++ b/app/app/warteliste/page.tsx @@ -0,0 +1,10 @@ +import type { Metadata } from "next"; +import { WaitlistPage } from "@/components/waitlist"; +export const metadata: Metadata = { + title: "Warteliste", + description: + "Noch kein Goldenes Ticket? Trag dich auf die Warteliste von Humans Only ein.", +}; +export default function Page() { + return ; +} diff --git a/app/components/clubhouse.tsx b/app/components/clubhouse.tsx index b599892..24afdef 100644 --- a/app/components/clubhouse.tsx +++ b/app/components/clubhouse.tsx @@ -77,10 +77,15 @@ export function Clubhouse() { Ein Clubhaus für Menschen mit eigenen Gedanken. Dein Goldenes Ticket macht die Tür auf.

- - Mit Ticket eintreten - - +
+ + Mit Ticket eintreten + + + + Auf die Warteliste + +
); return ( diff --git a/app/components/invite-flow.tsx b/app/components/invite-flow.tsx index 7593005..03a6959 100644 --- a/app/components/invite-flow.tsx +++ b/app/components/invite-flow.tsx @@ -127,6 +127,12 @@ export function InvitePage() { + {!me && ( +

+ Noch kein Ticket?{" "} + Setz dich auf die Warteliste → +

+ )}
diff --git a/app/components/provider.tsx b/app/components/provider.tsx index 4dccdb9..ecb167b 100644 --- a/app/components/provider.tsx +++ b/app/components/provider.tsx @@ -20,6 +20,8 @@ const empty: Snapshot = { tickets: [], votes: [], currentUserId: null, + waitlist: [], + isAdmin: false, }; type ClubContext = { activeSpaceId: string | null; diff --git a/app/components/shell.tsx b/app/components/shell.tsx index 3ca4e3a..52096a9 100644 --- a/app/components/shell.tsx +++ b/app/components/shell.tsx @@ -14,6 +14,7 @@ import { X, Zap, RotateCcw, + ShieldCheck, } from "lucide-react"; import { useClub } from "./provider"; import { config } from "@/lib/config"; @@ -54,11 +55,16 @@ export function Shell({ children }: { children: React.ReactNode }) { } catch {} } const profile = me ? `/u/${me.username}` : "/invite"; - const entry = path === "/invite" || path === "/onboarding"; + const pending = state.waitlist.filter((e) => e.status === "pending").length; + const entry = + path === "/invite" || path === "/onboarding" || path === "/warteliste"; const links = [ { href: "/", label: "Das Clubhaus", Icon: Home }, { href: "/tickets", label: "Goldene Tickets", Icon: Ticket }, { href: profile, label: "Mein Profil", Icon: UserRound }, + ...(state.isAdmin + ? [{ href: "/admin", label: "Warteliste", Icon: ShieldCheck }] + : []), ]; async function signOut() { try { @@ -105,6 +111,9 @@ export function Shell({ children }: { children: React.ReactNode }) { {label === "Goldene Tickets" && ( {me?.invites_left ?? 0} )} + {href === "/admin" && pending > 0 && ( + {pending} + )} ))} @@ -194,6 +203,12 @@ export function Shell({ children }: { children: React.ReactNode }) {
+ {state.isAdmin && ( + + + Warteliste{pending > 0 ? ` (${pending})` : ""} + + )} {me && (
); 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. +

+
void submit(e)}> + + setName(e.target.value)} + placeholder="Vorname Nachname" + required + maxLength={80} + /> + + setEmail(e.target.value)} + placeholder="du@beispiel.de" + required + maxLength={254} + /> + + + {error && ( +

+ {error} +

+ )} + +
+
+ + + Echte Menschen. Handverlesen freigegeben. +
+ Ohne Algorithmus. +
+
+ + {me ? "Zurück ins Clubhaus →" : "Du hast schon ein Ticket? →"} + + + )} +
+
+ ); +} + +type Filter = WaitlistStatus | "all"; +const filters: { key: Filter; label: string }[] = [ + { key: "pending", label: "Offen" }, + { key: "approved", label: "Freigegeben" }, + { key: "rejected", label: "Abgelehnt" }, + { key: "all", label: "Alle" }, +]; +const dateFormat = new Intl.DateTimeFormat("de-DE", { + day: "2-digit", + month: "2-digit", + year: "numeric", + hour: "2-digit", + minute: "2-digit", +}); + +export function AdminPage() { + const { state, me, loading, ready, repository, refresh, report, notify } = + useClub(); + const [filter, setFilter] = useState("pending"); + const [query, setQuery] = useState(""); + const [busy, setBusy] = useState(""); + const [confirmDelete, setConfirmDelete] = useState(""); + const [copied, setCopied] = useState(""); + const [fallback, setFallback] = useState(""); + const [mail, setMail] = useState({ enabled: false, simulated: false }); + const [bulk, setBulk] = useState<"idle" | "confirm" | "running">("idle"); + const [progress, setProgress] = useState(""); + const isAdmin = state.isAdmin; + useEffect(() => { + if (!isAdmin || !ready) return; + let active = true; + Promise.resolve() + .then(() => repository().mailStatus()) + .then((status) => { + if (active) setMail(status); + }) + .catch(() => {}); + return () => { + active = false; + }; + }, [isAdmin, ready, repository]); + const tickets = useMemo( + () => new Map(state.tickets.map((t) => [t.id, t])), + [state.tickets], + ); + const counts = useMemo(() => { + const c = { pending: 0, approved: 0, rejected: 0, all: 0 }; + for (const e of state.waitlist) { + c[e.status] += 1; + c.all += 1; + } + return c; + }, [state.waitlist]); + const visible = useMemo(() => { + const q = query.trim().toLowerCase(); + return state.waitlist + .filter((e) => filter === "all" || e.status === filter) + .filter( + (e) => + !q || + e.name.toLowerCase().includes(q) || + e.email.toLowerCase().includes(q), + ) + .sort((a, b) => + filter === "pending" + ? a.created_at.localeCompare(b.created_at) + : (b.decided_at || b.created_at).localeCompare( + a.decided_at || a.created_at, + ), + ); + }, [state.waitlist, filter, query]); + + if (loading) return ; + if (!me || !state.isAdmin) + return ( +
+

Nur für Gastgeber.

+

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."} +

+
+ +
+
+
+ {filters.map((f) => ( + + ))} +
+ +
+ {mail.enabled && counts.pending > 0 && ( +
+ {bulk === "running" ? ( + Verschicke Einladungen … {progress} + ) : bulk === "confirm" ? ( + <> + + Alle {counts.pending} offenen Anfragen freigeben und + Einladungen verschicken? + + + + + ) : ( + + )} +
+ )} + {fallback && ( +
+ + e.target.select()} + /> +
+ )} + {visible.length === 0 ? ( +

+ {query + ? "Niemand passt zu deiner Suche." + : filter === "pending" + ? "Keine offenen Anfragen. Zeit für einen Kaffee." + : "Hier ist noch niemand."} +

+ ) : ( +
    + {visible.map((entry) => { + const ticket = entry.ticket_id + ? tickets.get(entry.ticket_id) + : undefined; + const redeemed = Boolean(ticket?.redeemed_at); + const expired = + ticket && !redeemed && new Date(ticket.expires_at) <= new Date(); + const working = busy === entry.id || bulk === "running"; + return ( +
  • +
    + {entry.name} + {entry.email} + + Eingetragen {dateFormat.format(new Date(entry.created_at))} + {entry.status === "approved" && + (redeemed + ? " · Ticket eingelöst ✓" + : expired + ? " · Ticket abgelaufen" + : ticket + ? ` · Ticket gültig bis ${new Date(ticket.expires_at).toLocaleDateString("de-DE")}` + : "")} + {entry.status === "rejected" && " · abgelehnt"} + {entry.invited_at && + ` · Mail verschickt ${dateFormat.format(new Date(entry.invited_at))}${ + entry.invite_count > 1 ? ` (${entry.invite_count}×)` : "" + }`} + +
    +
    + {entry.status === "pending" && ( + <> + {mail.enabled ? ( + + ) : ( + + )} + + + )} + {entry.status === "approved" && ticket && !expired && !redeemed && ( + <> + {mail.enabled ? ( + + ) : ( + + + Mail schreiben + + )} + + + )} + {entry.status === "approved" && (expired || !ticket) && ( + + )} + {entry.status === "rejected" && ( + + )} + {confirmDelete === entry.id ? ( + + Endgültig löschen? + + + + ) : ( + + )} +
    +
  • + ); + })} +
+ )} +

+ 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.

+

Goldenes Ticket einlösen →

+

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)