From 32ba01f7cfbff73be54f83513750b8aab57a91e0 Mon Sep 17 00:00:00 2001
From: neodk2004
Date: Thu, 1 Oct 2026 06:35:22 +0200
Subject: [PATCH] refactor: altes Einladungs-Gate (InviteCode/pf_invite) durch
Empfehlungsprogramm ersetzen
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
- 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/ 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
---
.env.example | 5 -
CLAUDE.md | 14 +-
mobile/app/(auth)/sign-up.tsx | 5 +-
src/__tests__/helpers/prisma-mock.ts | 4 +-
src/app/(app)/invite/page.tsx | 141 +---------------
src/app/(app)/layout.tsx | 7 -
src/app/api/auth/consume-invite/route.ts | 87 ----------
src/app/api/auth/set-invite/route.ts | 47 ------
src/app/datenschutz/page.tsx | 39 ++++-
src/app/join/page.tsx | 96 ++---------
src/app/nutzungsbedingungen/page.tsx | 23 ++-
src/app/p/[secret]/invites/page.tsx | 202 -----------------------
src/lib/invite-codes.ts | 13 --
src/lib/referral-code.ts | 2 +-
src/proxy.ts | 9 -
src/trpc/routers/_app.ts | 2 -
src/trpc/routers/admin.ts | 56 -------
src/trpc/routers/invites.ts | 11 --
src/trpc/routers/pets.ts | 14 --
19 files changed, 89 insertions(+), 688 deletions(-)
delete mode 100644 src/app/api/auth/consume-invite/route.ts
delete mode 100644 src/app/api/auth/set-invite/route.ts
delete mode 100644 src/app/p/[secret]/invites/page.tsx
delete mode 100644 src/lib/invite-codes.ts
delete mode 100644 src/trpc/routers/invites.ts
diff --git a/.env.example b/.env.example
index 79a6f64..aea54e2 100644
--- a/.env.example
+++ b/.env.example
@@ -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 -> -> Client Keys (DSN)
# Same DSN value in both — server-side (src/instrumentation.ts) and
diff --git a/CLAUDE.md b/CLAUDE.md
index 275cc23..11d4c61 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -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
diff --git a/mobile/app/(auth)/sign-up.tsx b/mobile/app/(auth)/sign-up.tsx
index 90abada..373b47a 100644
--- a/mobile/app/(auth)/sign-up.tsx
+++ b/mobile/app/(auth)/sign-up.tsx
@@ -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
diff --git a/src/__tests__/helpers/prisma-mock.ts b/src/__tests__/helpers/prisma-mock.ts
index 35e2468..bf3a139 100644
--- a/src/__tests__/helpers/prisma-mock.ts
+++ b/src/__tests__/helpers/prisma-mock.ts
@@ -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 }),
diff --git a/src/app/(app)/invite/page.tsx b/src/app/(app)/invite/page.tsx
index 289aa06..215ca1a 100644
--- a/src/app/(app)/invite/page.tsx
+++ b/src/app/(app)/invite/page.tsx
@@ -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(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 (
-
@@ -167,11 +167,48 @@ export default function DatenschutzPage() {
+
+
+ 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).
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+
Wir verwenden technisch notwendige Cookies zur Sitzungsverwaltung. Tracking-Cookies oder
Cookies zu Werbezwecken werden ohne Ihre ausdrückliche Einwilligung nicht gesetzt.
+
+ 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.
+
diff --git a/src/app/join/page.tsx b/src/app/join/page.tsx
index 5b93963..eb6b16c 100644
--- a/src/app/join/page.tsx
+++ b/src/app/join/page.tsx
@@ -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/, 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 (
-
-
- {/* Logo / brand */}
-
-
PawFeed
-
Alpha · Nur auf Einladung
-
-
-
-
- Einladungscode eingeben
-
-
- PawFeed ist aktuell nur per Einladung zugänglich. Du brauchst einen Code von einem Mitglied.
-
-
-
-
-
-
- Noch kein Code? Bitte einen Freund, der PawFeed-Mitglied ist.
-
Diese Nutzungsbedingungen gelten für die Nutzung der Plattform PawFeed
@@ -90,6 +90,27 @@ export default function NutzungsbedingungenPage() {
+
+
+ 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.
+
+
+ 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.
+
+
+ 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.
+
+
+
Folgende Inhalte und Verhaltensweisen sind auf PawFeed untersagt: