Spaces:
Runtime error
Runtime error
File size: 4,987 Bytes
c7fbc2e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | 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*',
],
};
|