RippleWorkers / src /middleware.ts
damndeepesh
Initialize project with LavinMQ integration and Docker support
c7fbc2e
Raw History Blame Contribute Delete
4.99 kB
import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
import type { NextRequest } from 'next/server';
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
import { createServerClient } from '@supabase/ssr'
export async function middleware(req: NextRequest) {
const path = req.nextUrl.pathname;
// Define protected routes
const isDashboard = path.startsWith('/dashboard');
const isApi = path.startsWith('/api');
// Exclude public routes
const isAuth = path.startsWith('/api/auth');
const isWebhooks = path.startsWith('/api/webhooks');
const isCron = path.startsWith('/api/cron'); // Usually protected by secret header, not session
const isQueue = path.startsWith('/api/queue'); // Protected by QStash signature
// --- Rate Limiting Strategy ---
// 1. Webhooks: High limit (Instagram sends batches)
// 2. Auth: Strict limit (prevent brute force)
// 3. API/Dashboard: Moderate limit (user usage)
// Skip rate limiting for static assets or if Ratelimit not configured
if (!process.env.UPSTASH_REDIS_REST_URL || !process.env.UPSTASH_REDIS_REST_TOKEN) {
// Allow through if vars missing (fail open), but log warning in dev
// console.warn("Upstash Redis credentials missing, skipping rate limiting");
} else {
const ip = (req as any).ip || req.headers.get('x-forwarded-for') || '127.0.0.1';
// Sanitize IP if it's a list (x-forwarded-for)
const clientIp = Array.isArray(ip) ? ip[0] : ip.split(',')[0];
let limit = 20; // Default: 20 req / 10s
let window = '10 s';
if (isWebhooks) {
limit = 100; // 100 req / 10s
} else if (isAuth) {
limit = 10; // 10 req / 10s
} else {
limit = 50; // Dashboard/API
}
// We instantiate a new Ratelimit instance per request type to keep it stateless primarily,
// but leveraging the Redis connection.
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(limit, window as any),
analytics: true,
prefix: "@upstash/ratelimit",
});
const { success, pending, limit: l, reset, remaining } = await ratelimit.limit(`mw_${clientIp}`);
// pending is a promise that needs to be awaited if analytics is enabled?
// Docs say "await pending" to submit analytics if we want to wait, or let it run.
// Vercel might kill it if we don't await, but for latency we skip.
if (!success) {
return NextResponse.json({ error: 'Too Many Requests' }, { status: 429 });
}
}
// --- Supabase Auth Integration ---
let supabaseResponse = NextResponse.next({
request: {
headers: req.headers,
},
})
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return req.cookies.getAll()
},
setAll(cookiesToSet: { name: string, value: string, options?: any }[]) {
cookiesToSet.forEach(({ name, value, options }) =>
req.cookies.set(name, value)
)
supabaseResponse = NextResponse.next({
request: {
headers: req.headers,
},
})
cookiesToSet.forEach(({ name, value, options }) =>
supabaseResponse.cookies.set(name, value, options)
)
},
},
}
)
// IMPORTANT: Avoid writing any logic between createServerClient and
// supabase.auth.getUser(). A simple mistake could make it very hard to debug
// issues with users being randomly logged out.
const {
data: { user },
} = await supabase.auth.getUser()
if (isDashboard) {
// Check for Supabase user first
if (!user) {
// Fallback to NextAuth check (legacy/transition)
// If we are fully mitigating to Supabase, we might want to drop this eventually.
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
if (!token) {
return NextResponse.redirect(new URL('/', req.url));
}
}
}
if (isApi && !isAuth && !isWebhooks && !isCron && !isQueue) {
if (!user) {
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
}
}
return supabaseResponse;
}
export const config = {
matcher: [
'/dashboard/:path*',
'/api/:path*',
],
};