Spaces:
Runtime error
Runtime error
File size: 7,070 Bytes
cd8bd0a | 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 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | import { NextResponse } from "next/server";
import { getAuditRequestContext, logAuditEvent } from "@/lib/compliance/index";
import { getSettings } from "@/lib/localDb";
import { SignJWT } from "jose";
import { cookies } from "next/headers";
import {
ensurePersistentManagementPasswordHash,
getStoredManagementPassword,
verifyManagementPassword,
} from "@/lib/auth/managementPassword";
import { loginSchema } from "@/shared/validation/schemas";
import { isValidationFailure, validateBody } from "@/shared/validation/helpers";
import { checkLoginGuard, clearLoginAttempts, recordLoginFailure } from "@/server/auth/loginGuard";
// SECURITY: No hardcoded fallback — JWT_SECRET must be configured.
if (!process.env.JWT_SECRET) {
console.error("[SECURITY] FATAL: JWT_SECRET is not set. Login authentication is disabled.");
}
function getJwtSecret(): Uint8Array {
return new TextEncoder().encode(process.env.JWT_SECRET || "");
}
// Test seam for cookie store injection without affecting runtime behavior.
export const authRouteInternals = {
getCookieStore: cookies,
};
export async function POST(request) {
const auditContext = getAuditRequestContext(request);
try {
// Fail-fast if JWT_SECRET is not configured
if (!process.env.JWT_SECRET) {
logAuditEvent({
action: "auth.login.misconfigured",
actor: "system",
target: "dashboard-auth",
resourceType: "auth_session",
status: "failed",
ipAddress: auditContext.ipAddress || undefined,
requestId: auditContext.requestId,
metadata: { reason: "missing_jwt_secret" },
});
return NextResponse.json(
{ error: "Server misconfigured: JWT_SECRET not set. Contact administrator." },
{ status: 500 }
);
}
let rawBody;
try {
rawBody = await request.json();
} catch {
return NextResponse.json(
{
error: {
message: "Invalid request",
details: [{ field: "body", message: "Invalid JSON body" }],
},
},
{ status: 400 }
);
}
// Zod validation
const validation = validateBody(loginSchema, rawBody);
if (isValidationFailure(validation)) {
return NextResponse.json({ error: validation.error }, { status: 400 });
}
const password = typeof validation.data.password === "string" ? validation.data.password : "";
if (!password) {
return NextResponse.json({ error: "Invalid password payload" }, { status: 400 });
}
const settings = await getSettings();
const bruteForceEnabled = settings.bruteForceProtection !== false;
const clientIp = auditContext.ipAddress || null;
const guardCheck = checkLoginGuard(clientIp, { enabled: bruteForceEnabled });
if (!guardCheck.allowed) {
logAuditEvent({
action: "auth.login.locked",
actor: "anonymous",
target: "dashboard-auth",
resourceType: "auth_session",
status: "failed",
ipAddress: clientIp || undefined,
requestId: auditContext.requestId,
metadata: { retryAfterSeconds: guardCheck.retryAfterSeconds || 0 },
});
return NextResponse.json(
{ error: "Too many failed attempts. Try again later." },
{
status: 429,
headers: guardCheck.retryAfterSeconds
? { "Retry-After": String(guardCheck.retryAfterSeconds) }
: {},
}
);
}
const passwordState = await ensurePersistentManagementPasswordHash({
settings,
source: "auth.login",
});
const storedHash = getStoredManagementPassword(passwordState.settings);
if (!storedHash) {
logAuditEvent({
action: "auth.login.setup_required",
actor: "anonymous",
target: "dashboard-auth",
resourceType: "auth_session",
status: "failed",
ipAddress: auditContext.ipAddress || undefined,
requestId: auditContext.requestId,
metadata: { reason: "missing_persisted_password" },
});
return NextResponse.json(
{ error: "No password configured. Complete onboarding first.", needsSetup: true },
{ status: 403 }
);
}
const isValid = await verifyManagementPassword(password, storedHash);
if (isValid) {
const forceSecureCookie = process.env.AUTH_COOKIE_SECURE === "true";
const forwardedProtoHeader = request.headers.get("x-forwarded-proto") || "";
const forwardedProto = forwardedProtoHeader.split(",")[0].trim().toLowerCase();
const isHttpsRequest = forwardedProto === "https" || request.nextUrl?.protocol === "https:";
const useSecureCookie = forceSecureCookie || isHttpsRequest;
const token = await new SignJWT({ authenticated: true })
.setProtectedHeader({ alg: "HS256" })
.setExpirationTime("30d")
.sign(getJwtSecret());
const cookieStore = await authRouteInternals.getCookieStore();
cookieStore.set("auth_token", token, {
httpOnly: true,
secure: useSecureCookie,
sameSite: "lax",
path: "/",
});
logAuditEvent({
action: "auth.login.success",
actor: "admin",
target: "dashboard-auth",
resourceType: "auth_session",
status: "success",
ipAddress: auditContext.ipAddress || undefined,
requestId: auditContext.requestId,
metadata: {
hasStoredPassword: Boolean(storedHash),
passwordMigrated: passwordState.migrated,
secureCookie: useSecureCookie,
},
});
clearLoginAttempts(clientIp);
return NextResponse.json({ success: true });
}
const failureDecision = recordLoginFailure(clientIp, { enabled: bruteForceEnabled });
logAuditEvent({
action: "auth.login.failed",
actor: "anonymous",
target: "dashboard-auth",
resourceType: "auth_session",
status: "failed",
ipAddress: auditContext.ipAddress || undefined,
requestId: auditContext.requestId,
metadata: { reason: "invalid_password", lockedOut: failureDecision.allowed === false },
});
if (!failureDecision.allowed) {
return NextResponse.json(
{ error: "Too many failed attempts. Try again later." },
{
status: 429,
headers: failureDecision.retryAfterSeconds
? { "Retry-After": String(failureDecision.retryAfterSeconds) }
: {},
}
);
}
return NextResponse.json({ error: "Invalid password" }, { status: 401 });
} catch (error) {
console.error("[AUTH] Login failed:", error);
logAuditEvent({
action: "auth.login.error",
actor: "system",
target: "dashboard-auth",
resourceType: "auth_session",
status: "failed",
ipAddress: auditContext.ipAddress || undefined,
requestId: auditContext.requestId,
metadata: {
message: error instanceof Error ? error.message : "unknown_error",
},
});
return NextResponse.json({ error: "Internal server error" }, { status: 500 });
}
}
|