feat(security): replace Firebase with Cloudflare Turnstile bot verification
This commit is contained in:
@@ -1,140 +0,0 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import {
|
||||
createFirebaseSessionCookie,
|
||||
verifyFirebaseIdToken,
|
||||
isFirebaseAdminConfigured,
|
||||
} from '@/lib/firebase/admin';
|
||||
import { getServerUser, SESSION_COOKIE_NAME } from '@/lib/firebase/serverAuth';
|
||||
|
||||
/**
|
||||
* Validates that requests come from the same origin to mitigate CSRF attacks.
|
||||
* In production, the Origin header MUST be present and match the host.
|
||||
*/
|
||||
function isValidOrigin(req: NextRequest): boolean {
|
||||
const origin = req.headers.get('origin');
|
||||
const host = req.headers.get('host');
|
||||
|
||||
if (!host) return false;
|
||||
|
||||
// In production, always require an Origin header on mutating requests
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
if (!origin) return false;
|
||||
try {
|
||||
const originUrl = new URL(origin);
|
||||
return originUrl.host === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// In development, allow missing Origin (e.g. curl / local testing)
|
||||
if (!origin) return true;
|
||||
|
||||
try {
|
||||
const originUrl = new URL(origin);
|
||||
return originUrl.host === host;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/auth/session
|
||||
* Securely creates an httpOnly session cookie after client authentication.
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
if (!isValidOrigin(req)) {
|
||||
return NextResponse.json({ error: 'Invalid origin / CSRF rejection' }, { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await req.json().catch(() => ({}));
|
||||
const idToken = body.idToken;
|
||||
|
||||
if (!idToken || typeof idToken !== 'string') {
|
||||
return NextResponse.json({ error: 'Valid idToken required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const res = NextResponse.json({ success: true });
|
||||
|
||||
const fiveDaysInMs = 60 * 60 * 24 * 5 * 1000;
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
if (isFirebaseAdminConfigured()) {
|
||||
// Cryptographically mint a Firebase Session Cookie
|
||||
const sessionCookie = await createFirebaseSessionCookie(idToken, fiveDaysInMs);
|
||||
|
||||
if (sessionCookie) {
|
||||
res.cookies.set(SESSION_COOKIE_NAME, sessionCookie, {
|
||||
maxAge: Math.floor(fiveDaysInMs / 1000),
|
||||
httpOnly: true,
|
||||
secure: isProduction,
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
// Could not mint a server cookie even though admin is configured — reject
|
||||
return NextResponse.json({ error: 'Session creation failed' }, { status: 500 });
|
||||
}
|
||||
|
||||
// Admin SDK not configured: verify the ID token signature directly (dev mode only)
|
||||
if (isProduction) {
|
||||
return NextResponse.json({ error: 'Auth backend not configured' }, { status: 503 });
|
||||
}
|
||||
|
||||
// Fallback: Dev only — store raw ID token with 1-hour expiry
|
||||
res.cookies.set(SESSION_COOKIE_NAME, idToken, {
|
||||
maxAge: 3600,
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
});
|
||||
|
||||
return res;
|
||||
} catch (error: any) {
|
||||
console.error('[Auth API] Session creation error:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to create session' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/auth/session
|
||||
* Clears the session cookie on logout.
|
||||
*/
|
||||
export async function DELETE(req: NextRequest) {
|
||||
if (!isValidOrigin(req)) {
|
||||
return NextResponse.json({ error: 'Invalid origin / CSRF rejection' }, { status: 403 });
|
||||
}
|
||||
|
||||
const res = NextResponse.json({ success: true, message: 'Logged out successfully' });
|
||||
res.cookies.set(SESSION_COOKIE_NAME, '', {
|
||||
maxAge: 0,
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
path: '/',
|
||||
sameSite: 'lax',
|
||||
});
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/auth/session
|
||||
* Returns the currently authenticated user's profile claims.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
try {
|
||||
const user = await getServerUser(req);
|
||||
return NextResponse.json({
|
||||
authenticated: Boolean(user),
|
||||
user: user || null,
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json({ authenticated: false, user: null });
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { getToolById, getToolBySlug } from '@/lib/config/loader';
|
||||
import { getEndpointById } from '@/lib/catalog/loader';
|
||||
import { checkRateLimits, recordUsage } from '@/lib/api/rateLimiter';
|
||||
import { checkFileSignature, executeBackendTryIt, isCircuitOpen } from '@/lib/api/requestBuilder';
|
||||
import { verifyTurnstileToken } from '@/lib/turnstile';
|
||||
|
||||
let _visitorCookieMaxAge: number | null = null;
|
||||
function getVisitorCookieMaxAge(): number {
|
||||
@@ -82,6 +83,28 @@ export async function POST(req: NextRequest, { params }: { params: { toolId: str
|
||||
|
||||
try {
|
||||
const formData = await req.formData();
|
||||
|
||||
// Cloudflare Turnstile Bot & Abuse Verification
|
||||
const turnstileToken =
|
||||
(formData.get('cf-turnstile-response') as string | null) ||
|
||||
req.headers.get('cf-turnstile-response');
|
||||
|
||||
const turnstileResult = await verifyTurnstileToken(turnstileToken, ip);
|
||||
if (!turnstileResult.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
state: 'failed',
|
||||
error: {
|
||||
code: 'BOT_VERIFICATION_FAILED',
|
||||
message:
|
||||
turnstileResult.message ||
|
||||
'Cloudflare Turnstile verification failed. Please complete the security check.',
|
||||
retryable: true,
|
||||
},
|
||||
},
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Primary image extraction: check 'image' first, then common aliases
|
||||
let file = formData.get('image') as File | null;
|
||||
|
||||
+9
-14
@@ -5,8 +5,6 @@ import { getSiteConfig, getAllCategories, getAllTools } from '@/lib/config/loade
|
||||
import { Navbar } from '@/components/ui/Navbar';
|
||||
import { Footer } from '@/components/ui/Footer';
|
||||
import { SmoothScrollProvider } from '@/components/ui/SmoothScrollProvider';
|
||||
import { AuthProvider } from '@/lib/firebase/AuthContext';
|
||||
import { AuthModal } from '@/components/auth/AuthModal';
|
||||
|
||||
const poppinsFont = Poppins({
|
||||
subsets: ['latin'],
|
||||
@@ -178,18 +176,15 @@ export default function RootLayout({
|
||||
</head>
|
||||
<body className="min-h-screen flex flex-col antialiased bg-paper text-ink relative font-sans overflow-x-clip">
|
||||
<SmoothScrollProvider>
|
||||
<AuthProvider>
|
||||
<a href="#main-content" className="skip-link">Skip to main content</a>
|
||||
<Navbar
|
||||
config={config}
|
||||
currentLocale="en"
|
||||
categories={categories}
|
||||
totalToolsCount={tools.length}
|
||||
/>
|
||||
<main id="main-content" className="flex-1">{children}</main>
|
||||
<Footer config={config} currentLocale="en" />
|
||||
<AuthModal />
|
||||
</AuthProvider>
|
||||
<a href="#main-content" className="skip-link">Skip to main content</a>
|
||||
<Navbar
|
||||
config={config}
|
||||
currentLocale="en"
|
||||
categories={categories}
|
||||
totalToolsCount={tools.length}
|
||||
/>
|
||||
<main id="main-content" className="flex-1">{children}</main>
|
||||
<Footer config={config} currentLocale="en" />
|
||||
</SmoothScrollProvider>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user