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 ( -
- -
- ); - } - - return ( -
-
-

{t("title")}

-

- {t("subtitle", { available: available.length, total: codes.length })} -

-
- - {codes.length === 0 ? ( -
- {t("empty")} -
- ) : ( -
- {codes.map((code) => { - const isUsed = !!code.usedById || code.revoked; - return ( -
- {/* Status icon */} -
- {isUsed ? ( - - ) : ( - - )} -
- - {/* Code */} - - {code.code} - - - {/* Status label */} - {isUsed ? ( - - {code.revoked ? t("statusRevoked") : t("statusUsed")} - {code.usedAt && !code.revoked - ? ` · ${new Date(code.usedAt).toLocaleDateString(locale)}` - : ""} - - ) : ( -
- {canShare && ( - - )} - -
- )} -
- ); - })} -
- )} - - {used.length > 0 && ( -

- {t("usedSummary", { used: used.length, total: codes.length })} -

- )} -
- ); +/** Alte Einladungsseite (Einmal-Codes) — ersetzt durch /einladen. */ +export default function LegacyInvitePage() { + redirect("/einladen"); } diff --git a/src/app/(app)/layout.tsx b/src/app/(app)/layout.tsx index 99ccf8d..2bc6ea0 100644 --- a/src/app/(app)/layout.tsx +++ b/src/app/(app)/layout.tsx @@ -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([ diff --git a/src/app/api/auth/consume-invite/route.ts b/src/app/api/auth/consume-invite/route.ts deleted file mode 100644 index 98ff846..0000000 --- a/src/app/api/auth/consume-invite/route.ts +++ /dev/null @@ -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, - })), - }); - } - }); -} diff --git a/src/app/api/auth/set-invite/route.ts b/src/app/api/auth/set-invite/route.ts deleted file mode 100644 index b80d8e1..0000000 --- a/src/app/api/auth/set-invite/route.ts +++ /dev/null @@ -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; -} diff --git a/src/app/datenschutz/page.tsx b/src/app/datenschutz/page.tsx index df5093c..323dacc 100644 --- a/src/app/datenschutz/page.tsx +++ b/src/app/datenschutz/page.tsx @@ -33,7 +33,7 @@ export default function DatenschutzPage() { ) : <>––; return ( - +

{name}

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

- -
-
- - {errorMessage && ( -

{errorMessage}

- )} -
- -
-
- -

- Noch kein Code? Bitte einen Freund, der PawFeed-Mitglied ist. -

-
-
- ); + const { code, ref } = await searchParams; + const referralCode = normalizeReferralCode(ref ?? code); + redirect(referralCode ? `/r/${referralCode}` : "/"); } diff --git a/src/app/nutzungsbedingungen/page.tsx b/src/app/nutzungsbedingungen/page.tsx index 15bc689..a429dc1 100644 --- a/src/app/nutzungsbedingungen/page.tsx +++ b/src/app/nutzungsbedingungen/page.tsx @@ -3,7 +3,7 @@ import { LegalLayout, LegalSection } from "@/components/legal/LegalLayout"; export default function NutzungsbedingungenPage() { return ( - +

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:

    diff --git a/src/app/p/[secret]/invites/page.tsx b/src/app/p/[secret]/invites/page.tsx deleted file mode 100644 index 1e4d786..0000000 --- a/src/app/p/[secret]/invites/page.tsx +++ /dev/null @@ -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(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 ( -
    -
    -
    -

    Invite Codes

    -

    - {available.length} verfügbar · {used.length} verwendet · {revoked.length} widerrufen -

    -
    -
    - - -
    -
    - - {isLoading ? ( -
    - -
    - ) : codes.length === 0 ? ( -

    - Noch keine Codes — oben einen Root-Code erstellen. -

    - ) : ( -
    - {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 ( -
    - {/* Status icon */} -
    - {isRevoked ? ( - - ) : isUsed ? ( - - ) : ( - - )} -
    - - {/* Code */} - - {code.code} - - - {/* Issuer */} - - {issuerName ? `von ${issuerName}` : "Root"} - - - {/* Status badge */} - {isRevoked ? ( - Widerrufen - ) : isUsed ? ( - - Verwendet · {code.usedAt ? new Date(code.usedAt).toLocaleDateString("de-DE") : ""} - - ) : ( - Verfügbar - )} - - {/* Actions */} -
    - {!isUsed && !isRevoked && ( - - )} - {!isRevoked && !isUsed && ( - - )} -
    -
    - ); - })} -
    - )} -
    - ); -} diff --git a/src/lib/invite-codes.ts b/src/lib/invite-codes.ts deleted file mode 100644 index 5be5925..0000000 --- a/src/lib/invite-codes.ts +++ /dev/null @@ -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; diff --git a/src/lib/referral-code.ts b/src/lib/referral-code.ts index f316aa3..8077f0f 100644 --- a/src/lib/referral-code.ts +++ b/src/lib/referral-code.ts @@ -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; diff --git a/src/proxy.ts b/src/proxy.ts index 226403e..cc4ae52 100644 --- a/src/proxy.ts +++ b/src/proxy.ts @@ -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/")) { diff --git a/src/trpc/routers/_app.ts b/src/trpc/routers/_app.ts index 965092b..f2dece4 100644 --- a/src/trpc/routers/_app.ts +++ b/src/trpc/routers/_app.ts @@ -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, diff --git a/src/trpc/routers/admin.ts b/src/trpc/routers/admin.ts index 061f77b..4d5ebd4 100644 --- a/src/trpc/routers/admin.ts +++ b/src/trpc/routers/admin.ts @@ -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() }; diff --git a/src/trpc/routers/invites.ts b/src/trpc/routers/invites.ts deleted file mode 100644 index 0391527..0000000 --- a/src/trpc/routers/invites.ts +++ /dev/null @@ -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; - }), -}); diff --git a/src/trpc/routers/pets.ts b/src/trpc/routers/pets.ts index 871cccc..f7ac164 100644 --- a/src/trpc/routers/pets.ts +++ b/src/trpc/routers/pets.ts @@ -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,