refactor: altes Einladungs-Gate (InviteCode/pf_invite) durch Empfehlungsprogramm ersetzen

- Proxy-Sperre für /sign-up, INVITE_REQUIRED, set-invite/consume-invite,
  invites-Router, Admin-Invite-Seite und -Prozeduren, Startcodes in
  pets.create entfernt — Registrierung ist offen
- /join?code=… leitet auf /r/<code> um, /invite auf /einladen; alte geteilte
  Links laufen nicht ins Leere
- InviteCode-Tabelle bleibt nur als Historie (Kontolöschung räumt sie weiter auf)
- Datenschutzerklärung 4b (Empfehlungsprogramm, Herkunftsangabe, pf_ref-Cookie)
  und Nutzungsbedingungen 3b (Programmbedingungen, Bestandsschutz, Missbrauch)
- CLAUDE.md: Abschnitt "Referral program" statt "Invite system"

Build, Typecheck und alle Tests grün.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-01 06:35:22 +02:00
1 parent 78e16c9210
commit 32ba01f7cf
19 files changed
+89 -688

No files matched your search

-5
View File
@@ -66,11 +66,6 @@ ADMIN_OWNER_ID="user_xxxxxxxxxxxxxxxxxxxx"
# Local dev: run `docker run -d -p 6379:6379 redis:7-alpine` or install Redis locally.
REDIS_URL="redis://localhost:6379"
# ── Invite Gate ───────────────────────────────────────────────
# Set to "false" to disable the invite requirement after the Alpha/Beta phase.
# Default: "true" (invite required — enforced in proxy.ts)
INVITE_REQUIRED="true"
# ── Error Monitoring (Sentry) ───────────────────────────────────
# Sentry Dashboard -> Settings -> Projects -> <project> -> Client Keys (DSN)
# Same DSN value in both — server-side (src/instrumentation.ts) and
+8 -6
View File
@@ -44,7 +44,7 @@ The client-side "which pet is currently active" state lives in `src/context/Acti
### tRPC layer
- `src/trpc/init.ts` — context is `{ userId, prisma }` (userId from Clerk `auth()`); `protectedProcedure` throws `UNAUTHORIZED` if `userId` is null and narrows it to non-null in `ctx` for everything downstream.
- `src/trpc/routers/_app.ts` — aggregates ~20 domain routers (pets, posts, stories, milestones, follows, blocks, reports, feed, reactions, comments, reposts, explore, search, notifications, videos, conversations/messages, health, admin, invites, ads). One router file per domain in `src/trpc/routers/`.
- `src/trpc/routers/_app.ts` — aggregates ~20 domain routers (pets, posts, stories, milestones, follows, blocks, reports, feed, reactions, comments, reposts, explore, search, notifications, videos, conversations/messages, health, admin, referrals, referralAdmin, ads). One router file per domain in `src/trpc/routers/`.
- `src/trpc/server.ts` exposes a server-side caller (`createTRPCCaller()`) used inside Server Components/layouts to prefetch without an HTTP round-trip (see `src/app/(app)/layout.tsx`). `src/trpc/client.tsx` + `query-client.ts` wire up the browser-side TanStack Query client.
- Pet-ownership checks go through the shared `assertPetOwnership(prisma, petId, userId)` helper in `src/lib/assert-pet-ownership.ts` — don't reintroduce a local copy of this check in a new router.
@@ -55,14 +55,14 @@ The client-side "which pet is currently active" state lives in `src/context/Acti
### Routing structure
- `(auth)` route group — sign-up/log-in/password reset, unauthenticated.
- `(app)` route group — the authenticated shell (`layout.tsx` does a belt-and-suspenders `auth()` check, redirects to onboarding if the owner has zero pets, redirects banned owners to `/banned`, and consumes a pending invite cookie).
- `(app)` route group — the authenticated shell (`layout.tsx` does a belt-and-suspenders `auth()` check, redirects to onboarding if the owner has zero pets, and redirects banned owners to `/banned`).
- `/p/[secret]/...` — the admin/moderation panel. The path segment itself is the secret (`ADMIN_SECRET` env var); wrong or missing secret returns a bare `404`, not `403`, so the panel's existence isn't revealed.
- `/health-card/[token]` — public, tokenized, no auth (shareable vet record).
- Root-level `/impressum`, `/datenschutz`, `/nutzungsbedingungen` — German legal pages, not under `(app)`, not localized (this is a `next-intl` project but these three routes are fixed-language).
### `src/proxy.ts` (not `middleware.ts`)
Next.js 16 renamed `middleware.ts` to `proxy.ts` — this **is** the middleware; don't go looking for a `middleware.ts` that doesn't exist. It layers three concerns in one Clerk middleware: (1) invite gate — blocks `/sign-up` unless a `pf_invite` cookie is present, unless `INVITE_REQUIRED=false`; (2) admin secret gate — 404s `/p/*` unless the path segment matches `ADMIN_SECRET`; (3) `auth.protect()` for everything else not in the public route matcher.
Next.js 16 renamed `middleware.ts` to `proxy.ts` — this **is** the middleware; don't go looking for a `middleware.ts` that doesn't exist. It layers two concerns in one Clerk middleware: (1) admin secret gate — 404s `/p/*` unless the path segment matches `ADMIN_SECRET`; (2) `auth.protect()` for everything else not in the public route matcher. (The old invite gate on `/sign-up` — `pf_invite` cookie, `INVITE_REQUIRED` — was removed with the referral program; sign-up is open.)
### Media & storage — code has diverged from the original stack plan
@@ -84,11 +84,13 @@ All uploads are presigned/direct-to-storage — media bytes never pass through t
### Admin / moderation panel
Gated by path secret (see `proxy.ts` above) *and* by role at the tRPC layer: `src/trpc/routers/admin.ts`'s `assertAdmin()` allows either `ADMIN_OWNER_ID` (env-configured super-admin bootstrap) or an `AdminRole` row (`SUPER_ADMIN` / `MODERATOR`). Actions are written to `ModerationLog`. Pages live under `src/app/p/[secret]/{users,moderators,posts,reports,ads,invites}`.
Gated by path secret (see `proxy.ts` above) *and* by role at the tRPC layer: `src/trpc/routers/admin.ts`'s `assertAdmin()` allows either `ADMIN_OWNER_ID` (env-configured super-admin bootstrap) or an `AdminRole` row (`SUPER_ADMIN` / `MODERATOR`). Actions are written to `ModerationLog`. Pages live under `src/app/p/[secret]/{users,moderators,posts,reports,ads,referrals,…}`.
### Invite system
### Referral program (Empfehlungsprogramm)
`InviteCode` model (word-prefix + 4-char code, e.g. `PAWS-7K3M`, generated in `src/lib/invite-codes.ts`) gates sign-up via a `pf_invite` cookie set by `/join` and consumed by `/api/auth/consume-invite` right after sign-up (the `(app)` layout redirects there if the cookie is still present). `INVITE_REQUIRED=false` turns the whole gate off for post-beta public launch.
Registration is open; invites are a **Clerk-independent** referral layer on top. Every owner has one permanent, unlimited `Owner.referralCode` (e.g. `BUBI-7K3M`, prefix from the first pet's name — `src/lib/referral-code.ts`). A code is never part of the Clerk sign-up: it is redeemed **after** sign-up, in the onboarding step "Wie hast du von PawFeed erfahren?" (`AcquisitionStep`, web + mobile) or later on `/einladen` (mobile: `/invite`) within `ReferralSettings.redeemWindowDays`. `/r/[code]` is the public landing page (sets a `pf_ref` cookie only to prefill the web onboarding); old `/join?code=` links redirect there. Logic lives in `src/lib/referrals.ts`: redeem sets `Owner.invitedById` and makes both first pets follow each other; an invite **counts** (`referralQualifiedAt`, inviter's denormalized `qualifiedReferralCount` +1) only once the invitee has a pet **and** a first real post — `maybeQualifyReferral()` is called from `posts.create` and the Mux webhook on `READY`; a new post-creating mutation must call it too.
Ranks (`ReferralRank`) are data, fully editable in the admin panel (`/p/[secret]/referrals`, `referral-admin.ts`); only the perk catalog (`ReferralPerk`, `IMPLEMENTED_REFERRAL_PERKS` in `src/lib/referral-ranks.ts`) needs code. Perks are cumulative. Reached ranks are **grandfathered** via `ReferralRankAchievement` — raising a threshold never removes a rank. `Owner.referralRankId`/`referralPerks` are a cache maintained only by `src/lib/referrals.ts` and the set-based `recomputeReferralRanks()` (`src/lib/referral-recompute.ts`, run after every admin rank change); feed cards read them via `petCardSelect`. The legacy `InviteCode` table is history only — nothing writes to it anymore. One-time setup after the schema push: `npx tsx prisma/scripts/referral-setup.ts` (+ `prisma/enable_rls_referrals.sql`).
### Testing
+3 -2
View File
@@ -17,8 +17,9 @@ import { getTypography, type ColorTokens, type Typography } from "../../src/them
/**
* Email/password sign-up — the mobile app's other half of sign-in.tsx (that
* screen only ever covered login, per its own comment "sign-up screens are
* follow-up work"). No invite-code step: INVITE_REQUIRED is globally off on
* the backend since launch (post-beta), unlike web's /join gate.
* follow-up work"). No invite-code step here: registration is open, and a
* referral code is redeemed later in onboarding (AcquisitionStep), never
* as part of the Clerk sign-up itself.
*
* Uses Clerk's "Futures" API (signUp.password(), signUp.verifications,
* signUp.finalize()), matching sign-in.tsx's pattern — see AGENTS.md before
+2 -2
View File
@@ -421,8 +421,8 @@ export function createMockPrisma(): MockPrismaClient {
updateMany: vi.fn(),
count: vi.fn(),
},
// pets.create's idempotent starter-invite-code seeding runs on every call —
// default to "no codes yet" so tests unrelated to invites don't need to stub it.
// Legacy InviteCode table (pre-referral-program one-time codes) — only
// kept as history now; no router writes to it anymore.
inviteCode: {
count: vi.fn().mockResolvedValue(0),
createMany: vi.fn().mockResolvedValue({ count: 0 }),
+4 -137
View File
@@ -1,139 +1,6 @@
"use client";
import { redirect } from "next/navigation";
import { useQuery } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
import { useState } from "react";
import { Check, Copy, Loader2, UserCheck, Clock, Share2 } from "lucide-react";
import { toast } from "sonner";
import { useTranslations, useLocale } from "next-intl";
export default function InvitePage() {
const trpc = useTRPC();
const t = useTranslations("Invite");
const locale = useLocale();
const { data: codes = [], isLoading } = useQuery(trpc.invites.myInvites.queryOptions());
const [copiedId, setCopiedId] = useState<string | null>(null);
const available = codes.filter((c) => !c.usedById && !c.revoked);
const used = codes.filter((c) => c.usedById || c.revoked);
const canShare = typeof navigator !== "undefined" && typeof navigator.share === "function";
function inviteUrl(code: string) {
return `${window.location.origin}/join?code=${code}`;
}
function copyLink(code: string, id: string) {
void navigator.clipboard.writeText(inviteUrl(code)).then(() => {
setCopiedId(id);
toast.success(t("copiedToast"));
setTimeout(() => setCopiedId(null), 2000);
});
}
async function shareLink(code: string) {
try {
await navigator.share({
title: t("shareTitle"),
text: t("shareText"),
url: inviteUrl(code),
});
} catch {
// User cancelled share sheet — no action needed
}
}
if (isLoading) {
return (
<div className="flex justify-center py-24">
<Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
);
}
return (
<div className="max-w-lg mx-auto px-4 py-10 space-y-8">
<div>
<h1 className="text-xl font-semibold">{t("title")}</h1>
<p className="text-sm text-muted-foreground mt-1">
{t("subtitle", { available: available.length, total: codes.length })}
</p>
</div>
{codes.length === 0 ? (
<div className="rounded-xl border border-dashed p-8 text-center text-muted-foreground text-sm">
{t("empty")}
</div>
) : (
<div className="space-y-2">
{codes.map((code) => {
const isUsed = !!code.usedById || code.revoked;
return (
<div
key={code.id}
className={`flex items-center gap-3 rounded-xl border px-4 py-3 transition-colors ${
isUsed
? "border-border/50 bg-muted/30 opacity-60"
: "border-border bg-card hover:bg-accent/30"
}`}
>
{/* Status icon */}
<div className={`shrink-0 ${isUsed ? "text-muted-foreground" : "text-green-500"}`}>
{isUsed ? (
<UserCheck className="h-4 w-4" />
) : (
<Clock className="h-4 w-4" />
)}
</div>
{/* Code */}
<span className={`font-mono text-sm font-medium flex-1 ${isUsed ? "line-through text-muted-foreground" : ""}`}>
{code.code}
</span>
{/* Status label */}
{isUsed ? (
<span className="text-xs text-muted-foreground shrink-0">
{code.revoked ? t("statusRevoked") : t("statusUsed")}
{code.usedAt && !code.revoked
? ` · ${new Date(code.usedAt).toLocaleDateString(locale)}`
: ""}
</span>
) : (
<div className="shrink-0 flex items-center gap-3">
{canShare && (
<button
onClick={() => void shareLink(code.code)}
className="flex items-center gap-1.5 text-xs text-orange-500 hover:text-orange-600 transition-colors font-medium"
>
<Share2 className="h-3.5 w-3.5" />
{t("share")}
</button>
)}
<button
onClick={() => copyLink(code.code, code.id)}
className="flex items-center gap-1.5 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
{copiedId === code.id ? (
<Check className="h-3.5 w-3.5 text-green-500" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
{copiedId === code.id ? t("copied") : t("copy")}
</button>
</div>
)}
</div>
);
})}
</div>
)}
{used.length > 0 && (
<p className="text-xs text-muted-foreground">
{t("usedSummary", { used: used.length, total: codes.length })}
</p>
)}
</div>
);
/** Alte Einladungsseite (Einmal-Codes) — ersetzt durch /einladen. */
export default function LegacyInvitePage() {
redirect("/einladen");
}
-7
View File
@@ -1,6 +1,5 @@
import { redirect } from "next/navigation";
import { auth } from "@clerk/nextjs/server";
import { cookies } from "next/headers";
import { createTRPCCaller } from "@/trpc/server";
import { Sidebar } from "@/components/layout/Sidebar";
import { MobileNav } from "@/components/layout/MobileNav";
@@ -40,12 +39,6 @@ export default async function AppLayout({
redirect("/log-in");
}
// Consume invite code on first login — cookie set by /join page before sign-up
const cookieStore = await cookies();
if (cookieStore.get("pf_invite")?.value) {
redirect("/api/auth/consume-invite");
}
// Fetch the owner's pets via tRPC server caller (scoped by userId)
const caller = await createTRPCCaller();
const [pets, ban, themePref] = await Promise.all([
-87
View File
@@ -1,87 +0,0 @@
import { auth } from "@clerk/nextjs/server";
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { prisma } from "@/lib/prisma";
import { generateInviteCode, INVITE_CODES_PER_USER } from "@/lib/invite-codes";
import { checkRateLimit } from "@/lib/rate-limit";
import { getClientIp } from "@/lib/get-client-ip";
function resolveBase(request: NextRequest): string {
const proto = request.headers.get("x-forwarded-proto") ?? "https";
const host =
request.headers.get("x-forwarded-host") ??
request.headers.get("host") ??
"localhost:3000";
return `${proto}://${host}`;
}
export async function GET(request: NextRequest) {
const { userId } = await auth();
const base = resolveBase(request);
const { success } = await checkRateLimit({
key: `auth.consume-invite:${getClientIp(request)}`,
limit: 20,
windowSeconds: 60,
});
if (!success) {
return NextResponse.redirect(new URL("/", base));
}
if (!userId) {
return NextResponse.redirect(new URL("/log-in", base));
}
const cookieStore = await cookies();
const inviteCode = cookieStore.get("pf_invite")?.value;
const response = NextResponse.redirect(new URL("/", base));
if (inviteCode) {
await consumeInviteCode(userId, inviteCode, getClientIp(request));
response.cookies.delete("pf_invite");
}
return response;
}
async function consumeInviteCode(userId: string, code: string, ip: string | null) {
const invite = await prisma.inviteCode.findUnique({ where: { code } });
if (!invite || invite.usedById || invite.revoked) return;
await prisma.$transaction(async (tx) => {
// Guard the update with usedById: null so a concurrent redemption of the
// same single-use code can't both pass the pre-check above and both
// succeed — only the transaction that wins the race actually flips it.
const claimed = await tx.inviteCode.updateMany({
where: { code, usedById: null, revoked: false },
data: { usedById: userId, usedAt: new Date() },
});
if (claimed.count === 0) return;
await tx.owner.upsert({
where: { id: userId },
create: {
id: userId,
invitedById: invite.issuedById ?? null,
registrationIp: ip,
},
update: {
invitedById: invite.issuedById ?? undefined,
},
});
const existingCodes = await tx.inviteCode.count({
where: { issuedById: userId },
});
if (existingCodes === 0) {
await tx.inviteCode.createMany({
data: Array.from({ length: INVITE_CODES_PER_USER }, () => ({
code: generateInviteCode(),
issuedById: userId,
})),
});
}
});
}
-47
View File
@@ -1,47 +0,0 @@
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { checkRateLimit } from "@/lib/rate-limit";
import { getClientIp } from "@/lib/get-client-ip";
function resolveBase(request: NextRequest): string {
const proto = request.headers.get("x-forwarded-proto") ?? "https";
const host =
request.headers.get("x-forwarded-host") ??
request.headers.get("host") ??
"localhost:3000";
return `${proto}://${host}`;
}
export async function GET(request: NextRequest) {
const base = resolveBase(request);
const { success } = await checkRateLimit({
key: `auth.set-invite:${getClientIp(request)}`,
limit: 20,
windowSeconds: 60,
});
if (!success) {
return NextResponse.redirect(new URL("/join?error=rate-limited", base));
}
const code = request.nextUrl.searchParams.get("code")?.trim().toUpperCase();
if (!code) {
return NextResponse.redirect(new URL("/join?error=missing", base));
}
const invite = await prisma.inviteCode.findUnique({ where: { code } });
if (!invite || invite.usedById || invite.revoked) {
return NextResponse.redirect(new URL("/join?error=invalid", base));
}
const response = NextResponse.redirect(new URL("/sign-up", base));
response.cookies.set("pf_invite", code, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60,
path: "/",
});
return response;
}
+38 -1
View File
@@ -33,7 +33,7 @@ export default function DatenschutzPage() {
) : <>––</>;
return (
<LegalLayout title="Datenschutzerklärung" subtitle="Stand: September 2026 · gemäß DSGVO">
<LegalLayout title="Datenschutzerklärung" subtitle="Stand: Oktober 2026 · gemäß DSGVO">
<LegalSection number="1" title="Verantwortlicher">
<address className="not-italic space-y-0.5">
<p className="font-medium text-foreground">{name}</p>
@@ -167,11 +167,48 @@ export default function DatenschutzPage() {
</p>
</LegalSection>
<LegalSection number="4b" title="Empfehlungsprogramm und Herkunftsangabe">
<p>
Jedes Konto erhält einen persönlichen Einladungscode. Lösen Sie nach Ihrer Registrierung
den Code einer anderen Person ein, speichern wir, wer Sie eingeladen hat und wann, sowie
ob die Einladung gezählt wird (sobald Sie ein Tier angelegt und einen ersten Beitrag
veröffentlicht haben). Für einladende Personen speichern wir die Zahl der gezählten
Einladungen und die erreichten Empfehlungsränge. Rechtsgrundlage ist Art. 6 Abs. 1 lit. b
DSGVO (Durchführung des freiwilligen Empfehlungsprogramms als Teil der
Nutzungsbedingungen).
</p>
<p className="mt-2">
Sichtbar sind diese Daten nur eingeschränkt: Auf Ihrem Tierprofil erscheint „Eingeladen
von“ mit dem Namen des einladenden Tiers; die einladende Person sieht die Namen der Tiere,
die über ihren Code gekommen sind. Auf der öffentlichen Einladungsseite (pawfeed.org/r/…)
werden Name und Profilbild des ersten Tiers der einladenden Person angezeigt, weil diese
den Link selbst teilt.
</p>
<p className="mt-2">
Zur Missbrauchsabwehr (z. B. Mehrfachkonten) können Moderatoren prüfen, ob eingeladene
und einladende Person dieselbe bei der Registrierung erfasste IP-Adresse verwendet haben
(Art. 6 Abs. 1 lit. f DSGVO; berechtigtes Interesse an einem fairen Programm). Eine
automatische Entscheidung findet nicht statt.
</p>
<p className="mt-2">
Im Onboarding fragen wir freiwillig, wie Sie von PawFeed erfahren haben. Die Antwort wird
zu Ihrem Konto gespeichert und nur zusammengefasst ausgewertet, um zu verstehen, über
welche Wege neue Nutzer zu uns finden (Art. 6 Abs. 1 lit. f DSGVO). Sie können die Frage
überspringen.
</p>
</LegalSection>
<LegalSection number="5" title="Cookies und Tracking">
<p>
Wir verwenden technisch notwendige Cookies zur Sitzungsverwaltung. Tracking-Cookies oder
Cookies zu Werbezwecken werden ohne Ihre ausdrückliche Einwilligung nicht gesetzt.
</p>
<p className="mt-2">
Wenn Sie eine Einladungsseite (pawfeed.org/r/…) aufrufen, merkt sich Ihr Browser den dort
angezeigten Einladungscode für bis zu 7 Tage in einem Cookie („pf_ref“), damit er nach der
Registrierung automatisch eingetragen werden kann. Das Cookie enthält nur den Code und
wird nach dem Einlösen gelöscht.
</p>
</LegalSection>
<LegalSection number="6" title="Speicherdauer">
+11 -85
View File
@@ -1,92 +1,18 @@
import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { prisma } from "@/lib/prisma";
import { normalizeReferralCode } from "@/lib/referral-code";
interface JoinPageProps {
searchParams: Promise<{ code?: string; error?: string }>;
}
async function submitCode(formData: FormData) {
"use server";
const code = (formData.get("code") as string | null)?.trim().toUpperCase();
if (!code) redirect("/join?error=missing");
const invite = await prisma.inviteCode.findUnique({ where: { code } });
if (!invite || invite.usedById || invite.revoked) {
redirect(`/join?error=invalid`);
}
const cookieStore = await cookies();
cookieStore.set("pf_invite", code, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
maxAge: 60 * 60,
path: "/",
});
redirect("/sign-up");
searchParams: Promise<{ code?: string; ref?: string }>;
}
/**
* Früher das Einladungs-Gate der Alpha (Einmal-Codes, Cookie pf_invite).
* Seit dem Empfehlungsprogramm ist die Registrierung offen — die Seite
* leitet nur noch weiter, damit alte geteilte Links nicht ins Leere laufen:
* mit gültigem Code auf die Einladungsseite /r/<code>, sonst zur Startseite.
*/
export default async function JoinPage({ searchParams }: JoinPageProps) {
const { code: codeParam, error } = await searchParams;
// Code in URL → hand off to route handler which can set cookies
if (codeParam) {
redirect(`/api/auth/set-invite?code=${encodeURIComponent(codeParam)}`);
}
const errorMessage =
error === "invalid"
? "Ungültiger oder bereits verwendeter Einladungscode."
: error === "missing"
? "Bitte gib einen Einladungscode ein."
: null;
return (
<main className="min-h-screen flex items-center justify-center bg-zinc-950 px-4">
<div className="w-full max-w-sm">
{/* Logo / brand */}
<div className="mb-8 text-center">
<p className="text-2xl font-bold text-zinc-100 tracking-tight">PawFeed</p>
<p className="text-sm text-zinc-500 mt-1">Alpha · Nur auf Einladung</p>
</div>
<div className="rounded-2xl border border-zinc-800 bg-zinc-900 p-6 shadow-xl">
<h1 className="text-lg font-semibold text-zinc-100 mb-1">
Einladungscode eingeben
</h1>
<p className="text-sm text-zinc-500 mb-5">
PawFeed ist aktuell nur per Einladung zugänglich. Du brauchst einen Code von einem Mitglied.
</p>
<form action={submitCode} className="space-y-4">
<div>
<input
name="code"
type="text"
placeholder="z.B. PAWS-X7K2"
autoComplete="off"
autoCapitalize="characters"
spellCheck={false}
className="w-full rounded-lg border border-zinc-700 bg-zinc-800 px-4 py-2.5 text-sm font-mono text-zinc-100 placeholder:text-zinc-600 focus:outline-none focus:ring-2 focus:ring-orange-500 transition-shadow uppercase"
/>
{errorMessage && (
<p className="mt-2 text-xs text-red-400">{errorMessage}</p>
)}
</div>
<button
type="submit"
className="w-full rounded-lg bg-orange-500 hover:bg-orange-600 active:bg-orange-700 px-4 py-2.5 text-sm font-semibold text-white transition-colors"
>
Weiter
</button>
</form>
</div>
<p className="mt-6 text-center text-xs text-zinc-600">
Noch kein Code? Bitte einen Freund, der PawFeed-Mitglied ist.
</p>
</div>
</main>
);
const { code, ref } = await searchParams;
const referralCode = normalizeReferralCode(ref ?? code);
redirect(referralCode ? `/r/${referralCode}` : "/");
}
+22 -1
View File
@@ -3,7 +3,7 @@ import { LegalLayout, LegalSection } from "@/components/legal/LegalLayout";
export default function NutzungsbedingungenPage() {
return (
<LegalLayout title="Nutzungsbedingungen" subtitle="Stand: August 2026">
<LegalLayout title="Nutzungsbedingungen" subtitle="Stand: Oktober 2026">
<LegalSection number="1" title="Geltungsbereich">
<p>
Diese Nutzungsbedingungen gelten für die Nutzung der Plattform PawFeed
@@ -90,6 +90,27 @@ export default function NutzungsbedingungenPage() {
</p>
</LegalSection>
<LegalSection number="3b" title="Empfehlungsprogramm">
<p>
Du kannst Freunde mit deinem persönlichen Einladungscode zu PawFeed einladen. Die
Teilnahme ist freiwillig und kostenlos; eine Registrierung ist auch ohne Einladung
möglich. Eine Einladung zählt, sobald das eingeladene Konto ein Tier angelegt und einen
ersten Beitrag veröffentlicht hat.
</p>
<p className="mt-2">
Für gezählte Einladungen vergeben wir Empfehlungsränge mit digitalen Vorteilen, etwa
Abzeichen, einen farbigen Profilring oder eine Vorstellung auf unseren Kanälen. Ränge und
Vorteile haben keinen Geldwert, sind nicht übertragbar und begründen keinen Anspruch auf
eine bestimmte Leistung. Wir können Schwellen, Ränge und Vorteile ändern oder das Programm
beenden; bereits erreichte Ränge bleiben dabei erhalten.
</p>
<p className="mt-2">
Einladungen über Fake- oder Mehrfachkonten, gekaufte Konten oder andere Umgehungen sind
nicht erlaubt. In solchen Fällen können wir einzelne Einladungen aberkennen und
erreichte Ränge entziehen.
</p>
</LegalSection>
<LegalSection number="4" title="Verbotene Inhalte & Verhaltensregeln">
<p className="mb-2">Folgende Inhalte und Verhaltensweisen sind auf PawFeed untersagt:</p>
<ul className="space-y-1.5">
-202
View File
@@ -1,202 +0,0 @@
"use client";
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useTRPC } from "@/trpc/client";
import { Plus, Loader2, Copy, Check, Ban, UserCheck, Clock } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { toast } from "sonner";
export default function AdminInvitesPage() {
const trpc = useTRPC();
const qc = useQueryClient();
const [copiedId, setCopiedId] = useState<string | null>(null);
const { data: codes = [], isLoading } = useQuery(
trpc.admin.listInviteCodes.queryOptions({ limit: 200 })
);
const invalidate = () =>
void qc.invalidateQueries({ queryKey: trpc.admin.listInviteCodes.queryKey() });
const createRoot = useMutation(
trpc.admin.createRootInvite.mutationOptions({
onSuccess: () => {
invalidate();
toast.success("Root-Einladung erstellt");
},
})
);
const revoke = useMutation(
trpc.admin.revokeInvite.mutationOptions({
onSuccess: () => {
invalidate();
toast.success("Code widerrufen");
},
})
);
const backfill = useMutation(
trpc.admin.backfillInviteCodes.mutationOptions({
onSuccess: (result) => {
invalidate();
toast.success(
result.updated === 0
? "Alle User haben bereits Codes."
: `${result.updated} User haben jetzt ihre Codes erhalten.`
);
},
})
);
function copyLink(code: string, id: string) {
const url = `${window.location.origin}/join?code=${code}`;
void navigator.clipboard.writeText(url).then(() => {
setCopiedId(id);
toast.success("Link kopiert");
setTimeout(() => setCopiedId(null), 2000);
});
}
const available = codes.filter((c) => !c.usedById && !c.revoked);
const used = codes.filter((c) => c.usedById && !c.revoked);
const revoked = codes.filter((c) => c.revoked);
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold text-zinc-100">Invite Codes</h1>
<p className="text-sm text-zinc-500 mt-0.5">
{available.length} verfügbar · {used.length} verwendet · {revoked.length} widerrufen
</p>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant="outline"
onClick={() => backfill.mutate()}
disabled={backfill.isPending}
className="bg-zinc-900 border-zinc-700 text-zinc-300 hover:bg-zinc-800 hover:text-zinc-100"
>
{backfill.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />
) : (
<Plus className="h-4 w-4 mr-1.5" />
)}
Codes nachträglich zuweisen
</Button>
<Button
size="sm"
onClick={() => createRoot.mutate()}
disabled={createRoot.isPending}
className="bg-orange-500 hover:bg-orange-600 text-white"
>
{createRoot.isPending ? (
<Loader2 className="h-4 w-4 animate-spin mr-1.5" />
) : (
<Plus className="h-4 w-4 mr-1.5" />
)}
Root-Code erstellen
</Button>
</div>
</div>
{isLoading ? (
<div className="flex justify-center py-12">
<Loader2 className="h-5 w-5 animate-spin text-zinc-500" />
</div>
) : codes.length === 0 ? (
<p className="text-sm text-zinc-500 text-center py-12">
Noch keine Codes — oben einen Root-Code erstellen.
</p>
) : (
<div className="space-y-2">
{codes.map((code) => {
const isUsed = !!code.usedById;
const isRevoked = code.revoked;
const issuerName = code.issuedBy?.pets?.[0]?.name ?? (code.issuedById ? code.issuedById.slice(0, 12) : null);
return (
<div
key={code.id}
className={`flex items-center gap-3 rounded-xl border px-4 py-3 ${
isRevoked
? "border-zinc-800 bg-zinc-900/50 opacity-50"
: isUsed
? "border-zinc-800 bg-zinc-900"
: "border-zinc-700 bg-zinc-900"
}`}
>
{/* Status icon */}
<div className={`shrink-0 ${isRevoked ? "text-red-500" : isUsed ? "text-zinc-500" : "text-green-500"}`}>
{isRevoked ? (
<Ban className="h-4 w-4" />
) : isUsed ? (
<UserCheck className="h-4 w-4" />
) : (
<Clock className="h-4 w-4" />
)}
</div>
{/* Code */}
<span className={`font-mono text-sm font-medium flex-1 ${isRevoked ? "line-through text-zinc-600" : "text-zinc-100"}`}>
{code.code}
</span>
{/* Issuer */}
<span className="text-xs text-zinc-600 shrink-0">
{issuerName ? `von ${issuerName}` : "Root"}
</span>
{/* Status badge */}
{isRevoked ? (
<Badge variant="secondary" className="text-[10px] shrink-0">Widerrufen</Badge>
) : isUsed ? (
<Badge variant="secondary" className="text-[10px] shrink-0">
Verwendet · {code.usedAt ? new Date(code.usedAt).toLocaleDateString("de-DE") : ""}
</Badge>
) : (
<Badge className="bg-green-800 text-green-200 text-[10px] shrink-0">Verfügbar</Badge>
)}
{/* Actions */}
<div className="flex gap-1 shrink-0">
{!isUsed && !isRevoked && (
<Button
size="sm"
variant="ghost"
className="h-7 w-7 p-0 text-zinc-400 hover:text-zinc-100"
title="Link kopieren"
onClick={() => copyLink(code.code, code.id)}
>
{copiedId === code.id ? (
<Check className="h-3.5 w-3.5 text-green-400" />
) : (
<Copy className="h-3.5 w-3.5" />
)}
</Button>
)}
{!isRevoked && !isUsed && (
<Button
size="sm"
variant="ghost"
className="h-7 w-7 p-0 text-red-400 hover:text-red-300"
title="Code widerrufen"
onClick={() => revoke.mutate({ id: code.id })}
disabled={revoke.isPending}
>
<Ban className="h-3.5 w-3.5" />
</Button>
)}
</div>
</div>
);
})}
</div>
)}
</div>
);
}
-13
View File
@@ -1,13 +0,0 @@
const PREFIXES = ["PAWS", "BARK", "PURR", "WOOF", "MEOW", "TAIL", "PUPS", "FLUF"];
const CHARS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; // no confusable chars (0, 1, I, O)
export function generateInviteCode(): string {
const prefix = PREFIXES[Math.floor(Math.random() * PREFIXES.length)];
const suffix = Array.from(
{ length: 4 },
() => CHARS[Math.floor(Math.random() * CHARS.length)]
).join("");
return `${prefix}-${suffix}`;
}
export const INVITE_CODES_PER_USER = 3;
+1 -1
View File
@@ -4,7 +4,7 @@
* Pure, ohne Server-Abhängigkeiten, damit Web-Client und Tests sie nutzen können.
*/
// Gleicher Zeichensatz wie src/lib/invite-codes.ts — ohne verwechselbare 0/1/I/O.
// Ohne verwechselbare Zeichen (0/1/I/O) — gleicher Zeichensatz wie die früheren Einmal-Codes.
const SUFFIX_CHARS = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const SUFFIX_LENGTH = 4;
const MAX_PREFIX_LENGTH = 6;
-9
View File
@@ -87,15 +87,6 @@ export default clerkMiddleware(
async (auth, request) => {
const { pathname } = request.nextUrl;
// Invite gate: block /sign-up unless the visitor has a valid invite cookie.
// Set INVITE_REQUIRED=false in env to disable for the live/post-beta launch.
if (pathname.startsWith("/sign-up")) {
const inviteRequired = process.env.INVITE_REQUIRED !== "false";
if (inviteRequired && !request.cookies.has("pf_invite")) {
return NextResponse.redirect(new URL("/join", request.url));
}
}
// Admin panel: validate secret path segment before anything else.
// Returns 404 (not 403) — the panel's existence must not be revealed.
if (pathname.startsWith("/p/")) {
-2
View File
@@ -18,7 +18,6 @@ import { videosRouter } from "@/trpc/routers/videos";
import { conversationsRouter, messagesRouter } from "@/trpc/routers/messages";
import { healthRouter } from "@/trpc/routers/health";
import { adminRouter } from "@/trpc/routers/admin";
import { invitesRouter } from "@/trpc/routers/invites";
import { adsRouter } from "@/trpc/routers/ads";
import { legalRouter } from "@/trpc/routers/legal";
import { ownerRouter } from "@/trpc/routers/owner";
@@ -50,7 +49,6 @@ export const appRouter = router({
messages: messagesRouter,
health: healthRouter,
admin: adminRouter,
invites: invitesRouter,
ads: adsRouter,
legal: legalRouter,
owner: ownerRouter,
-56
View File
@@ -1741,62 +1741,6 @@ export const adminRouter = router({
.sort((a, b) => b.actionCount - a.actionCount);
}),
// ─── Invite codes ─────────────────────────────────────────────────────────────
listInviteCodes: protectedProcedure
.input(z.object({ limit: z.number().min(1).max(200).default(100) }))
.query(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
return ctx.prisma.inviteCode.findMany({
orderBy: { createdAt: "desc" },
take: input.limit,
include: {
issuedBy: { select: { id: true, pets: { select: { name: true, nickname: true }, take: 1 } } },
},
});
}),
createRootInvite: protectedProcedure.mutation(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
const { generateInviteCode } = await import("@/lib/invite-codes");
return ctx.prisma.inviteCode.create({
data: { code: generateInviteCode(), issuedById: null },
});
}),
revokeInvite: protectedProcedure
.input(z.object({ id: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
await ctx.prisma.inviteCode.update({
where: { id: input.id },
data: { revoked: true },
});
return { success: true };
}),
backfillInviteCodes: protectedProcedure.mutation(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.SUPER_ADMIN);
const { generateInviteCode, INVITE_CODES_PER_USER } = await import("@/lib/invite-codes");
const ownersWithoutCodes = await ctx.prisma.owner.findMany({
where: { NOT: { issuedInvites: { some: {} } } },
select: { id: true },
});
if (ownersWithoutCodes.length === 0) return { updated: 0 };
await ctx.prisma.inviteCode.createMany({
data: ownersWithoutCodes.flatMap(({ id }) =>
Array.from({ length: INVITE_CODES_PER_USER }, () => ({
code: generateInviteCode(),
issuedById: id,
}))
),
});
return { updated: ownersWithoutCodes.length };
}),
getMaintenanceMode: protectedProcedure.query(async ({ ctx }) => {
await assertAdmin(ctx.prisma, ctx.userId, AdminRoleType.MODERATOR);
return { enabled: await isMaintenanceModeEnabled() };
-11
View File
@@ -1,11 +0,0 @@
import { router, protectedProcedure } from "@/trpc/init";
export const invitesRouter = router({
myInvites: protectedProcedure.query(async ({ ctx }) => {
const codes = await ctx.prisma.inviteCode.findMany({
where: { issuedById: ctx.userId },
orderBy: { createdAt: "asc" },
});
return codes;
}),
});
-14
View File
@@ -1,7 +1,6 @@
import { z } from "zod";
import { TRPCError } from "@trpc/server";
import { router, protectedProcedure } from "@/trpc/init";
import { generateInviteCode, INVITE_CODES_PER_USER } from "@/lib/invite-codes";
import { assertPetOwnership } from "@/lib/assert-pet-ownership";
import { pickLocalizedName } from "@/lib/localized-name";
import { petCardSelect } from "@/repositories/pet-repository";
@@ -33,19 +32,6 @@ export const petsRouter = router({
create: { id: ctx.userId, registrationIp: ctx.ip },
});
// Ensure every owner has starter invite codes (idempotent)
const existingCodes = await ctx.prisma.inviteCode.count({
where: { issuedById: ctx.userId },
});
if (existingCodes === 0) {
await ctx.prisma.inviteCode.createMany({
data: Array.from({ length: INVITE_CODES_PER_USER }, () => ({
code: generateInviteCode(),
issuedById: ctx.userId,
})),
});
}
return ctx.prisma.pet.create({
data: {
ownerId: ctx.userId,