Fix Edge-incompatible middleware; set Node runtime on Prisma/pg routes; add full Romanian Bible import + converter; import data JSON; resync RO bookKeys; stabilize /api/bible/books locale fallback; restart dev server.
This commit is contained in:
135
middleware.ts
135
middleware.ts
@@ -1,7 +1,6 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import type { NextRequest } from 'next/server'
|
||||
import { verifyToken } from '@/lib/auth'
|
||||
import { prisma } from '@/lib/db'
|
||||
// Avoid importing Node-only modules in Middleware (Edge runtime)
|
||||
import createIntlMiddleware from 'next-intl/middleware'
|
||||
|
||||
// Internationalization configuration
|
||||
@@ -10,59 +9,10 @@ const intlMiddleware = createIntlMiddleware({
|
||||
defaultLocale: 'ro'
|
||||
})
|
||||
|
||||
// Rate limiting configuration
|
||||
const RATE_LIMIT_WINDOW = 60 * 1000 // 1 minute
|
||||
const RATE_LIMITS = {
|
||||
general: 100, // 100 requests per minute
|
||||
auth: 5, // 5 auth requests per minute
|
||||
chat: 10, // 10 chat requests per minute
|
||||
search: 20, // 20 search requests per minute
|
||||
}
|
||||
|
||||
async function getRateLimitKey(request: NextRequest, endpoint: string): Promise<string> {
|
||||
const forwarded = request.headers.get('x-forwarded-for')
|
||||
const ip = forwarded ? forwarded.split(',')[0] : request.ip || 'unknown'
|
||||
return `ratelimit:${endpoint}:${ip}`
|
||||
}
|
||||
|
||||
async function checkRateLimit(request: NextRequest, endpoint: string, limit: number): Promise<{ allowed: boolean; remaining: number }> {
|
||||
try {
|
||||
const key = await getRateLimitKey(request, endpoint)
|
||||
const now = Date.now()
|
||||
const windowStart = now - RATE_LIMIT_WINDOW
|
||||
|
||||
// Clean up old entries and count current requests
|
||||
await prisma.$executeRaw`
|
||||
DELETE FROM verse_cache
|
||||
WHERE key LIKE ${key + ':%'}
|
||||
AND created_at < ${new Date(windowStart)}
|
||||
`
|
||||
|
||||
const currentCount = await prisma.$queryRaw<{ count: number }[]>`
|
||||
SELECT COUNT(*) as count
|
||||
FROM verse_cache
|
||||
WHERE key LIKE ${key + ':%'}
|
||||
`
|
||||
|
||||
const requestCount = Number(currentCount[0]?.count || 0)
|
||||
|
||||
if (requestCount >= limit) {
|
||||
return { allowed: false, remaining: 0 }
|
||||
}
|
||||
|
||||
// Record this request
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO verse_cache (key, value, expires_at, created_at)
|
||||
VALUES (${key + ':' + now}, '1', ${new Date(now + RATE_LIMIT_WINDOW)}, ${new Date(now)})
|
||||
`
|
||||
|
||||
return { allowed: true, remaining: limit - requestCount - 1 }
|
||||
} catch (error) {
|
||||
console.error('Rate limit check error:', error)
|
||||
// Allow request on error
|
||||
return { allowed: true, remaining: limit }
|
||||
}
|
||||
}
|
||||
// Note: Avoid using Prisma or any Node-only APIs in Middleware.
|
||||
// Middleware runs on the Edge runtime, where Prisma is not supported.
|
||||
// If rate limiting is needed, implement it inside API route handlers
|
||||
// (Node.js runtime) or via an external service (e.g., Upstash Redis).
|
||||
|
||||
export async function middleware(request: NextRequest) {
|
||||
// Handle internationalization for non-API routes
|
||||
@@ -70,38 +20,7 @@ export async function middleware(request: NextRequest) {
|
||||
return intlMiddleware(request)
|
||||
}
|
||||
|
||||
// Determine endpoint type for rate limiting
|
||||
let endpoint = 'general'
|
||||
let limit = RATE_LIMITS.general
|
||||
|
||||
if (request.nextUrl.pathname.startsWith('/api/auth')) {
|
||||
endpoint = 'auth'
|
||||
limit = RATE_LIMITS.auth
|
||||
} else if (request.nextUrl.pathname.startsWith('/api/chat')) {
|
||||
endpoint = 'chat'
|
||||
limit = RATE_LIMITS.chat
|
||||
} else if (request.nextUrl.pathname.startsWith('/api/bible/search')) {
|
||||
endpoint = 'search'
|
||||
limit = RATE_LIMITS.search
|
||||
}
|
||||
|
||||
// Apply rate limiting to API routes
|
||||
if (request.nextUrl.pathname.startsWith('/api/')) {
|
||||
const rateLimit = await checkRateLimit(request, endpoint, limit)
|
||||
|
||||
const response = rateLimit.allowed
|
||||
? NextResponse.next()
|
||||
: new NextResponse('Too Many Requests', { status: 429 })
|
||||
|
||||
// Add rate limit headers
|
||||
response.headers.set('X-RateLimit-Limit', limit.toString())
|
||||
response.headers.set('X-RateLimit-Remaining', rateLimit.remaining.toString())
|
||||
response.headers.set('X-RateLimit-Reset', (Date.now() + RATE_LIMIT_WINDOW).toString())
|
||||
|
||||
if (!rateLimit.allowed) {
|
||||
return response
|
||||
}
|
||||
}
|
||||
// Skip API rate limiting here to stay Edge-safe
|
||||
|
||||
// Security headers for all responses
|
||||
const response = NextResponse.next()
|
||||
@@ -123,42 +42,12 @@ export async function middleware(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
// Authentication check for protected routes
|
||||
if (request.nextUrl.pathname.startsWith('/api/bookmarks') ||
|
||||
request.nextUrl.pathname.startsWith('/api/notes') ||
|
||||
request.nextUrl.pathname.startsWith('/dashboard')) {
|
||||
|
||||
const token = request.headers.get('authorization')?.replace('Bearer ', '') ||
|
||||
request.cookies.get('authToken')?.value
|
||||
|
||||
// Authentication: perform only lightweight checks in Middleware (Edge).
|
||||
// Defer full JWT verification to API route handlers (Node runtime).
|
||||
if (request.nextUrl.pathname.startsWith('/dashboard')) {
|
||||
const token = request.cookies.get('authToken')?.value
|
||||
if (!token) {
|
||||
if (request.nextUrl.pathname.startsWith('/api/')) {
|
||||
return new NextResponse('Unauthorized', { status: 401 })
|
||||
} else {
|
||||
return NextResponse.redirect(new URL('/', request.url))
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await verifyToken(token)
|
||||
|
||||
// Add user ID to headers for API routes
|
||||
if (request.nextUrl.pathname.startsWith('/api/')) {
|
||||
const requestHeaders = new Headers(request.headers)
|
||||
requestHeaders.set('x-user-id', payload.userId)
|
||||
|
||||
return NextResponse.next({
|
||||
request: {
|
||||
headers: requestHeaders,
|
||||
},
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
if (request.nextUrl.pathname.startsWith('/api/')) {
|
||||
return new NextResponse('Invalid token', { status: 401 })
|
||||
} else {
|
||||
return NextResponse.redirect(new URL('/', request.url))
|
||||
}
|
||||
return NextResponse.redirect(new URL('/', request.url))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,4 +65,4 @@ export const config = {
|
||||
'/api/:path*',
|
||||
'/dashboard/:path*'
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user