From 41dfcb6918e6069cffdc21f84aeb22b0b7906028 Mon Sep 17 00:00:00 2001 From: austinkelsay Date: Mon, 30 Sep 2024 19:28:03 -0500 Subject: [PATCH] Update middleware to combine techniques for detecting external requests --- src/middleware.js | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/middleware.js b/src/middleware.js index 22b5cf7..602bd47 100644 --- a/src/middleware.js +++ b/src/middleware.js @@ -14,7 +14,6 @@ export const config = { export default async function combinedMiddleware(request) { const ip = request.ip ?? '127.0.0.1'; const pathname = request.nextUrl.pathname; - const vercelBypass = request.headers.get('x-vercel-protection-bypass'); // Allow access to .well-known paths if (pathname.startsWith('/.well-known')) { @@ -24,8 +23,8 @@ export default async function combinedMiddleware(request) { : NextResponse.redirect(new URL('/blocked', request.url)); } - // Check if the request is coming from a Vercel deployment - if (!vercelBypass) { + // Check if the request is internal + if (!isInternalRequest(request)) { return new NextResponse(JSON.stringify({ error: 'Forbidden' }), { status: 403, headers: { 'Content-Type': 'application/json' } @@ -37,4 +36,22 @@ export default async function combinedMiddleware(request) { return success ? NextResponse.next() : NextResponse.redirect(new URL('/blocked', request.url)); +} + +function isInternalRequest(request) { + // Check if the request is from the same origin + const requestHost = request.headers.get('host'); + const requestProtocol = request.headers.get('x-forwarded-proto') || 'http'; + const requestOrigin = `${requestProtocol}://${requestHost}`; + + // Check if the request has a referer from the same origin + const referer = request.headers.get('referer'); + + // Allow requests with no referer (direct API calls from your app) + if (!referer) { + return true; + } + + // Check if the referer matches the request origin + return referer.startsWith(requestOrigin); } \ No newline at end of file