fix(security): prevent arbitrary API keys from accessing dashboard management routes (#1353)

This commit is contained in:
diegosouzapw
2026-04-16 17:29:22 -03:00
parent d868124c36
commit 21bccce4a1

View File

@@ -1,12 +1,35 @@
import { isAuthenticated, isAuthRequired } from "@/shared/utils/apiAuth";
import { isAuthRequired } from "@/shared/utils/apiAuth";
import { createErrorResponse } from "@/lib/api/errorResponse";
import { jwtVerify } from "jose";
import { cookies } from "next/headers";
/**
* Checks if the request is authenticated strictly via a Dashboard Session (JWT Cookie).
* Standard Bearer API keys are rejected for management routes to prevent privilege escalation.
*/
async function isDashboardSessionAuthenticated(): Promise<boolean> {
if (process.env.JWT_SECRET) {
try {
const cookieStore = await cookies();
const token = cookieStore.get("auth_token")?.value;
if (token) {
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
await jwtVerify(token, secret);
return true;
}
} catch {
// Invalid/expired token
}
}
return false;
}
export async function requireManagementAuth(request: Request): Promise<Response | null> {
if (!(await isAuthRequired())) {
return null;
}
if (await isAuthenticated(request)) {
if (await isDashboardSessionAuthenticated()) {
return null;
}