feat: rate limit public routes; backfill v0.9.5 changelog for mobile audit

Sign-in/sign-up now throttle at 3 req/10s/IP via better-auth's built-in
rate limiter; /r/ and /s/ share links throttle at 60 req/min/IP via
proxy.ts using the existing Redis-backed limiter (Next 16's Proxy always
runs Node.js, no Edge-runtime blocker after all).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-13 09:32:37 +02:00
parent 6818f10fc4
commit 4960dfc7c6
6 changed files with 58 additions and 4 deletions
+21 -1
View File
@@ -1,9 +1,22 @@
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
import { applyRateLimit } from "@/lib/rate-limit";
const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/s/", "/docs", "/api/v1/openapi.json", "/api/webhooks", "/api/v1/invites/", "/api/internal/"];
const ADMIN_PATHS = ["/admin"];
// Unauthenticated, publicly-linked pages (shared recipes/shopping lists) —
// no per-user identity to key on, so rate-limit by IP to deter scraping.
const IP_RATE_LIMITED_PATHS = ["/r/", "/s/"];
const IP_RATE_LIMIT = 60;
const IP_RATE_LIMIT_WINDOW_SECONDS = 60;
function getClientIp(request: NextRequest): string {
const forwardedFor = request.headers.get("x-forwarded-for");
if (forwardedFor) return forwardedFor.split(",")[0]!.trim();
return request.headers.get("x-real-ip") ?? "unknown";
}
export async function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
@@ -11,7 +24,14 @@ export async function proxy(request: NextRequest) {
const isAdmin = ADMIN_PATHS.some((p) => pathname.startsWith(p));
const isApi = pathname.startsWith("/api/v1");
if (isPublic) return NextResponse.next();
if (isPublic) {
if (IP_RATE_LIMITED_PATHS.some((p) => pathname.startsWith(p))) {
const ip = getClientIp(request);
const limited = await applyRateLimit(`rl:public:${ip}`, IP_RATE_LIMIT, IP_RATE_LIMIT_WINDOW_SECONDS);
if (limited) return limited;
}
return NextResponse.next();
}
// API-key clients authenticate via `Authorization: Bearer ek_...`, not a
// session cookie — they'd otherwise be rejected here before ever reaching