Files
caddy-proxy-manager/app/api/user/link-oauth-start/route.ts
fuomag9 bdd3019214 security: add same-origin CSRF check to state-changing user API routes
Adds checkSameOrigin() helper in auth.ts that validates the Origin header
against the Host header. If Origin is present and mismatched, returns 403.
Applied to all 5 custom POST routes flagged in CPM-003 (NEXT-CSRF-001):
  - change-password, link-oauth-start, unlink-oauth, update-avatar, logout

SameSite=Lax (NextAuth default) already blocks standard cross-site CSRF;
this adds defense-in-depth against subdomain and misconfiguration scenarios.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 01:04:18 +01:00

76 lines
2.3 KiB
TypeScript

import { NextRequest, NextResponse } from "next/server";
import { auth, checkSameOrigin } from "@/src/lib/auth";
import db, { nowIso } from "@/src/lib/db";
import { pendingOAuthLinks } from "@/src/lib/db/schema";
import { eq, and, lt } from "drizzle-orm";
import { registerFailedAttempt } from "@/src/lib/rate-limit";
export async function POST(request: NextRequest) {
const originCheck = checkSameOrigin(request);
if (originCheck) return originCheck;
try {
const session = await auth();
if (!session?.user?.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const userId = Number(session.user.id);
// Rate limiting: prevent OAuth linking spam
const rateLimitKey = `oauth-link:${userId}`;
const rateLimitResult = registerFailedAttempt(rateLimitKey);
if (rateLimitResult.blocked) {
return NextResponse.json(
{ error: "Too many OAuth linking attempts. Please try again later." },
{ status: 429 }
);
}
const body = await request.json();
const { provider } = body;
if (!provider) {
return NextResponse.json({ error: "Provider is required" }, { status: 400 });
}
const userEmail = session.user.email;
if (!userEmail) {
return NextResponse.json({ error: "User email not found" }, { status: 400 });
}
const now = new Date();
const expiresAt = new Date(now.getTime() + 5 * 60 * 1000); // 5 minutes from now
// Clean up old expired entries for all users
await db.delete(pendingOAuthLinks).where(lt(pendingOAuthLinks.expiresAt, nowIso()));
// Delete any existing pending link for THIS USER and this provider
// (unique index will prevent duplicates, but we delete explicitly for clarity)
await db.delete(pendingOAuthLinks).where(
and(
eq(pendingOAuthLinks.userId, userId),
eq(pendingOAuthLinks.provider, provider)
)
);
// Insert new pending link record for THIS USER only
await db.insert(pendingOAuthLinks).values({
userId,
provider,
userEmail,
createdAt: nowIso(),
expiresAt: expiresAt.toISOString()
});
return NextResponse.json({ success: true });
} catch (error) {
console.error("OAuth linking start error:", error);
return NextResponse.json(
{ error: "Failed to start OAuth linking" },
{ status: 500 }
);
}
}