csrf token and browser detection

This commit is contained in:
Ahmet Kilinc
2025-07-16 00:44:42 +01:00
parent d5c52557df
commit 5178732c4c
4 changed files with 235 additions and 57 deletions
+149 -24
View File
@@ -4,51 +4,179 @@ import { waitlist } from "@opencut/db/schema";
import { nanoid } from "nanoid";
import { waitlistRateLimit } from "@/lib/rate-limit";
import { z } from "zod";
import { env } from "@/env";
import { cookies } from "next/headers";
import crypto from "crypto";
const waitlistSchema = z.object({
email: z.string().email("Invalid email format").min(1, "Email is required"),
});
const CSRF_TOKEN_NAME = "waitlist-csrf";
const TOKEN_EXPIRY = 60 * 60 * 1000;
function validateBrowserRequest(request: NextRequest): boolean {
const origin = request.headers.get("origin");
const referer = request.headers.get("referer");
const userAgent = request.headers.get("user-agent") || "";
const secFetchSite = request.headers.get("sec-fetch-site");
const secFetchMode = request.headers.get("sec-fetch-mode");
const secFetchDest = request.headers.get("sec-fetch-dest");
const contentType = request.headers.get("content-type");
const accept = request.headers.get("accept");
if (env.NODE_ENV === "development") {
console.log("=== Validating Browser Request ===");
console.log("Origin:", origin);
console.log("Referer:", referer);
console.log("User-Agent:", userAgent);
console.log("Sec-Fetch-Site:", secFetchSite);
console.log("Sec-Fetch-Mode:", secFetchMode);
console.log("Sec-Fetch-Dest:", secFetchDest);
console.log("Content-Type:", contentType);
console.log("Accept:", accept);
}
const allowedOrigins =
env.NODE_ENV === "development" ? ["http://localhost:3000", "http://127.0.0.1:3000"] : ["https://opencut.app", "https://www.opencut.app"];
if (!origin || !allowedOrigins.includes(origin)) {
console.log("Failed: Invalid origin");
return false;
}
if (!referer || !referer.startsWith(origin)) {
console.log("Failed: Invalid referer");
return false;
}
const suspiciousUserAgents = [
"curl",
"wget",
"postman",
"insomnia",
"thunder client",
"httpie",
"python-requests",
"node-fetch",
"axios",
"scrapy",
"httpclient",
"okhttp",
"libwww-perl",
"python-urllib",
"go-http-client",
"java/",
"apache-httpclient",
];
const lowerUserAgent = userAgent.toLowerCase();
if (!userAgent || suspiciousUserAgents.some((agent) => lowerUserAgent.includes(agent))) {
console.log("Failed: Suspicious user agent");
return false;
}
const hasBrowserIndicators =
lowerUserAgent.includes("mozilla/") ||
lowerUserAgent.includes("chrome/") ||
lowerUserAgent.includes("safari/") ||
lowerUserAgent.includes("firefox/") ||
lowerUserAgent.includes("edge/");
if (!hasBrowserIndicators) {
console.log("Failed: No browser indicators in user agent");
return false;
}
if (secFetchSite && secFetchSite !== "same-origin") {
console.log("Failed: Invalid Sec-Fetch-Site:", secFetchSite);
return false;
}
if (secFetchMode && secFetchMode !== "cors") {
console.log("Failed: Invalid Sec-Fetch-Mode:", secFetchMode);
return false;
}
if (secFetchDest && secFetchDest !== "empty") {
console.log("Failed: Invalid Sec-Fetch-Dest:", secFetchDest);
return false;
}
if (!contentType || !contentType.includes("application/json")) {
console.log("Failed: Invalid Content-Type");
return false;
}
if (!accept || (!accept.includes("application/json") && !accept.includes("*/*"))) {
console.log("Failed: Invalid Accept header");
return false;
}
console.log("Browser validation passed!");
return true;
}
async function validateCSRFToken(request: NextRequest): Promise<boolean> {
const clientToken = request.headers.get("x-csrf-token");
if (!clientToken) return false;
const cookieStore = await cookies();
const cookieValue = cookieStore.get(CSRF_TOKEN_NAME)?.value;
if (!cookieValue) return false;
const [token, timestamp, signature] = cookieValue.split(":");
if (!token || !timestamp || !signature) return false;
if (clientToken !== token) return false;
const now = Date.now();
const tokenTime = parseInt(timestamp);
if (now - tokenTime > TOKEN_EXPIRY) return false;
const expectedSignature = crypto
.createHmac("sha256", env.BETTER_AUTH_SECRET || "fallback-secret")
.update(`${token}:${timestamp}`)
.digest("hex");
return signature === expectedSignature;
}
export async function POST(request: NextRequest) {
// Rate limit check
const identifier = request.headers.get("x-forwarded-for") ?? "127.0.0.1";
const { success } = await waitlistRateLimit.limit(identifier);
if (!success) {
return NextResponse.json(
{ error: "Too many requests. Please try again later." },
{ status: 429 }
);
return NextResponse.json({ error: "Too many requests. Please try again later." }, { status: 429 });
}
if (!validateBrowserRequest(request)) {
await new Promise((resolve) => setTimeout(resolve, Math.random() * 2000 + 1000));
return NextResponse.json({ error: "Invalid request" }, { status: 403 });
}
const isValidToken = await validateCSRFToken(request);
if (!isValidToken) {
return NextResponse.json({ error: "Invalid security token" }, { status: 403 });
}
try {
const body = await request.json();
const { email } = waitlistSchema.parse(body);
// Check if email already exists
const existingEmail = await db
.select()
.from(waitlist)
.where(eq(waitlist.email, email.toLowerCase()))
.limit(1);
const existingEmail = await db.select().from(waitlist).where(eq(waitlist.email, email.toLowerCase())).limit(1);
if (existingEmail.length > 0) {
return NextResponse.json(
{ error: "Email already registered" },
{ status: 409 }
);
return NextResponse.json({ error: "Email already registered" }, { status: 409 });
}
// Add to waitlist
await db.insert(waitlist).values({
id: nanoid(),
email: email.toLowerCase(),
});
return NextResponse.json(
{ message: "Successfully joined waitlist!" },
{ status: 201 }
);
return NextResponse.json({ message: "Successfully joined waitlist!" }, { status: 201 });
} catch (error) {
if (error instanceof z.ZodError) {
const firstError = error.errors[0];
@@ -56,9 +184,6 @@ export async function POST(request: NextRequest) {
}
console.error("Waitlist signup error:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
@@ -0,0 +1,47 @@
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import crypto from "crypto";
import { env } from "@/env";
const CSRF_TOKEN_NAME = "waitlist-csrf";
const TOKEN_EXPIRY = 60 * 60 * 1000;
export async function GET(request: NextRequest) {
const referer = request.headers.get("referer");
const host = request.headers.get("host");
if (referer) {
const refererUrl = new URL(referer);
const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"];
if (!allowedHosts.some((allowed) => refererUrl.host === allowed || refererUrl.host.endsWith(allowed))) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
} else if (host) {
const allowedHosts = env.NODE_ENV === "development" ? ["localhost:3000", "127.0.0.1:3000"] : ["opencut.app", "www.opencut.app"];
if (!allowedHosts.some((allowed) => host === allowed || host.endsWith(allowed))) {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
} else {
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
}
const token = crypto.randomBytes(32).toString("hex");
const timestamp = Date.now();
const signature = crypto
.createHmac("sha256", env.BETTER_AUTH_SECRET || "fallback-secret")
.update(`${token}:${timestamp}`)
.digest("hex");
const cookieStore = await cookies();
cookieStore.set(CSRF_TOKEN_NAME, `${token}:${timestamp}:${signature}`, {
httpOnly: true,
secure: env.NODE_ENV === "production",
sameSite: "strict",
maxAge: TOKEN_EXPIRY / 1000,
path: "/",
});
return NextResponse.json({ token });
}
+38 -33
View File
@@ -4,7 +4,7 @@ import { motion } from "motion/react";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { ArrowRight } from "lucide-react";
import { useState } from "react";
import { useState, useEffect } from "react";
import { toast } from "sonner";
import Image from "next/image";
@@ -13,6 +13,20 @@ import { Handlebars } from "./handlebars";
export function Hero() {
const [email, setEmail] = useState("");
const [isSubmitting, setIsSubmitting] = useState(false);
const [csrfToken, setCsrfToken] = useState<string | null>(null);
useEffect(() => {
fetch("/api/waitlist/token", {
credentials: "include",
})
.then((res) => res.json())
.then((data) => {
if (data.token) {
setCsrfToken(data.token);
}
})
.catch((err) => console.error("Failed to fetch CSRF token:", err));
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
@@ -24,6 +38,13 @@ export function Hero() {
return;
}
if (!csrfToken) {
toast.error("Security error", {
description: "Please refresh the page and try again.",
});
return;
}
setIsSubmitting(true);
try {
@@ -31,7 +52,9 @@ export function Hero() {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-CSRF-Token": csrfToken,
},
credentials: "include",
body: JSON.stringify({ email: email.trim() }),
});
@@ -42,11 +65,15 @@ export function Hero() {
description: "You'll be notified when we launch.",
});
setEmail("");
fetch("/api/waitlist/token", { credentials: "include" })
.then((res) => res.json())
.then((data) => {
if (data.token) setCsrfToken(data.token);
});
} else {
toast.error("Oops!", {
description:
(data as { error: string }).error ||
"Something went wrong. Please try again.",
description: (data as { error: string }).error || "Something went wrong. Please try again.",
});
}
} catch (error) {
@@ -60,13 +87,7 @@ export function Hero() {
return (
<div className="min-h-[calc(100vh-4.5rem)] supports-[height:100dvh]:min-h-[calc(100dvh-4.5rem)] flex flex-col justify-between items-center text-center px-4">
<Image
className="absolute top-0 left-0 -z-50 size-full object-cover"
src="/landing-page-bg.png"
height={1903.5}
width={1269}
alt="landing-page.bg"
/>
<Image className="absolute top-0 left-0 -z-50 size-full object-cover" src="/landing-page-bg.png" height={1903.5} width={1269} alt="landing-page.bg" />
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
@@ -89,20 +110,11 @@ export function Hero() {
animate={{ opacity: 1 }}
transition={{ delay: 0.4, duration: 0.8 }}
>
A simple but powerful video editor that gets the job done. Works on
any platform.
A simple but powerful video editor that gets the job done. Works on any platform.
</motion.p>
<motion.div
className="mt-12 flex gap-8 justify-center"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ delay: 0.6, duration: 0.8 }}
>
<form
onSubmit={handleSubmit}
className="flex gap-3 w-full max-w-lg flex-col sm:flex-row"
>
<motion.div className="mt-12 flex gap-8 justify-center" initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ delay: 0.6, duration: 0.8 }}>
<form onSubmit={handleSubmit} className="flex gap-3 w-full max-w-lg flex-col sm:flex-row">
<div className="relative w-full">
<Input
type="email"
@@ -110,19 +122,12 @@ export function Hero() {
className="h-11 text-base flex-1"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isSubmitting}
disabled={isSubmitting || !csrfToken}
required
/>
</div>
<Button
type="submit"
size="lg"
className="px-6 h-11 text-base !bg-foreground"
disabled={isSubmitting}
>
<span className="relative z-10">
{isSubmitting ? "Joining..." : "Join waitlist"}
</span>
<Button type="submit" size="lg" className="px-6 h-11 text-base !bg-foreground" disabled={isSubmitting || !csrfToken}>
<span className="relative z-10">{isSubmitting ? "Joining..." : "Join waitlist"}</span>
<ArrowRight className="relative z-10 ml-0.5 h-4 w-4 inline-block" />
</Button>
</form>
+1
View File
@@ -12,4 +12,5 @@ export const waitlistRateLimit = new Ratelimit({
redis,
limiter: Ratelimit.slidingWindow(5, "1 m"), // 5 requests per minute
analytics: true,
prefix: "waitlist-rate-limit",
});