refactor(auth): standardize session management and security
- Centralize secret retrieval using `getAdminSessionSecret` - Replace manual session parsing with `verifyRequestAdminSession` utility - Tighten API validation and improve security headers handling - Enforce environment variable security for production deployments
This commit is contained in:
1 parent
34519c07df
commit
177ed4a844
78 files changed
+6748
-3157
No files matched your search
+102
-79
@@ -1,11 +1,12 @@
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
getAdminSessionSecret,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
authenticateAdminCredentials,
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
verifyAdminCredentials,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
@@ -13,10 +14,19 @@ const SESSION_COOKIE = "datastack_admin_session";
|
||||
const SESSION_SECONDS = 8 * 60 * 60;
|
||||
const REMEMBERED_SESSION_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
function extractClientIp(request: NextRequest) {
|
||||
const forwardedFor = request.headers.get("x-forwarded-for");
|
||||
if (forwardedFor) {
|
||||
const first = forwardedFor.split(",")[0]?.trim();
|
||||
if (first) return first;
|
||||
}
|
||||
const realIp = request.headers.get("x-real-ip")?.trim();
|
||||
if (realIp) return realIp;
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const sessionSecret =
|
||||
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||
"datastack-admin-session-default-secret-32-chars";
|
||||
const sessionSecret = getAdminSessionSecret();
|
||||
|
||||
if (!sessionSecret || sessionSecret.length < 32) {
|
||||
return NextResponse.json(
|
||||
@@ -27,86 +37,99 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const body = await request.json();
|
||||
const email =
|
||||
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
const password = typeof body.password === "string" ? body.password : "";
|
||||
if (!email || password.length === 0 || password.length > 1024) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
let throttleDecision;
|
||||
try {
|
||||
throttleDecision = await consumeAdminLoginAttempt(email, sessionSecret);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
if (!throttleDecision.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many sign-in attempts. Try again later." },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Retry-After": String(throttleDecision.retryAfterSeconds),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let authenticated = false;
|
||||
try {
|
||||
authenticated = await verifyAdminCredentials(email, password);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
if (!authenticated) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await clearAdminLoginAttempts(email, sessionSecret);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const remember = body.remember === true;
|
||||
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
||||
const expiresAt = Date.now() + maxAge * 1000;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
expiresAt,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
response.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
getSessionCookieOptions(request, maxAge),
|
||||
);
|
||||
|
||||
return response;
|
||||
const parsed = await request.json();
|
||||
body =
|
||||
parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {};
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid login request." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const email =
|
||||
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
const password = typeof body.password === "string" ? body.password : "";
|
||||
if (!email || password.length === 0 || password.length > 1024) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
const clientIp = extractClientIp(request);
|
||||
|
||||
let throttleDecision;
|
||||
try {
|
||||
throttleDecision = await consumeAdminLoginAttempt(
|
||||
email,
|
||||
sessionSecret,
|
||||
clientIp,
|
||||
);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
if (!throttleDecision.allowed) {
|
||||
return NextResponse.json(
|
||||
{ error: "Too many sign-in attempts. Try again later." },
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Retry-After": String(throttleDecision.retryAfterSeconds),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let authResult: { authenticated: boolean; tokenVersion: number };
|
||||
try {
|
||||
authResult = await authenticateAdminCredentials(email, password);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
if (!authResult.authenticated) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid email or password." },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
await clearAdminLoginAttempts(email, sessionSecret, clientIp);
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
const remember = body.remember === true;
|
||||
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
||||
const expiresAt = Date.now() + maxAge * 1000;
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
expiresAt,
|
||||
authResult.tokenVersion,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
response.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
getSessionCookieOptions(request, maxAge),
|
||||
);
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
getAdminSessionPayload,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
getAdminAccountInfo,
|
||||
updateAdminAccount,
|
||||
verifyRequestAdminSession,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
@@ -17,51 +17,69 @@ function validEmail(email: string) {
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const sessionSecret =
|
||||
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||
"datastack-admin-session-default-secret-32-chars";
|
||||
const token = request.cookies.get(SESSION_COOKIE)?.value || "";
|
||||
const session = await getAdminSessionPayload(token, sessionSecret);
|
||||
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
||||
const auth = await verifyRequestAdminSession(token);
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required." },
|
||||
{ status: 401 },
|
||||
);
|
||||
if (!auth.valid) {
|
||||
const status = auth.reason === "UNAUTHORIZED" ? 401 : 503;
|
||||
const message =
|
||||
auth.reason === "UNAUTHORIZED"
|
||||
? "Authentication required."
|
||||
: "Admin authentication is temporarily unavailable.";
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
const account = await getAdminAccountInfo(session.email);
|
||||
return NextResponse.json({
|
||||
profile: {
|
||||
email: account.email,
|
||||
role: "Owner",
|
||||
storageMode: account.storageMode,
|
||||
createdAt: account.createdAt,
|
||||
sessionExpiresAt: new Date(session.expiresAt).toISOString(),
|
||||
},
|
||||
});
|
||||
try {
|
||||
const account = await getAdminAccountInfo(auth.session.email);
|
||||
return NextResponse.json({
|
||||
profile: {
|
||||
email: account.email,
|
||||
role: "Owner",
|
||||
storageMode: account.storageMode,
|
||||
createdAt: account.createdAt,
|
||||
sessionExpiresAt: new Date(auth.session.expiresAt).toISOString(),
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Unable to load admin profile." },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest) {
|
||||
const sessionSecret =
|
||||
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||
"datastack-admin-session-default-secret-32-chars";
|
||||
const token = request.cookies.get(SESSION_COOKIE)?.value || "";
|
||||
const session = await getAdminSessionPayload(token, sessionSecret);
|
||||
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
||||
const auth = await verifyRequestAdminSession(token);
|
||||
|
||||
if (!session) {
|
||||
if (!auth.valid) {
|
||||
const status = auth.reason === "UNAUTHORIZED" ? 401 : 503;
|
||||
const message =
|
||||
auth.reason === "UNAUTHORIZED"
|
||||
? "Authentication required."
|
||||
: "Admin authentication is temporarily unavailable.";
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = await request.json();
|
||||
body =
|
||||
parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {};
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Authentication required." },
|
||||
{ status: 401 },
|
||||
{ error: "Invalid profile payload." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const nextEmail =
|
||||
typeof body.email === "string"
|
||||
? body.email.trim().toLowerCase()
|
||||
: session.email;
|
||||
: auth.session.email;
|
||||
const currentPassword =
|
||||
typeof body.currentPassword === "string" ? body.currentPassword : "";
|
||||
const newPassword =
|
||||
@@ -88,7 +106,7 @@ export async function PUT(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const account = await getAdminAccountInfo(session.email);
|
||||
const account = await getAdminAccountInfo(auth.session.email);
|
||||
const result = await updateAdminAccount({
|
||||
currentEmail: account.email,
|
||||
currentPassword,
|
||||
@@ -103,13 +121,14 @@ export async function PUT(request: NextRequest) {
|
||||
// Preserve remaining session duration (e.g., 30-day "Remember me" session)
|
||||
const remainingSeconds = Math.max(
|
||||
SESSION_SECONDS,
|
||||
Math.ceil((session.expiresAt - Date.now()) / 1000),
|
||||
Math.ceil((auth.session.expiresAt - Date.now()) / 1000),
|
||||
);
|
||||
const expiresAt = Date.now() + remainingSeconds * 1000;
|
||||
const nextToken = await createAdminSessionToken(
|
||||
result.email,
|
||||
sessionSecret,
|
||||
auth.sessionSecret,
|
||||
expiresAt,
|
||||
result.tokenVersion,
|
||||
);
|
||||
|
||||
const response = NextResponse.json({
|
||||
@@ -133,7 +152,7 @@ export async function PUT(request: NextRequest) {
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Unable to update profile." },
|
||||
{ status: 400 },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
getAdminSessionSecret,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
@@ -20,9 +21,7 @@ function validEmail(email: string) {
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const sessionSecret =
|
||||
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||
"datastack-admin-session-default-secret-32-chars";
|
||||
const sessionSecret = getAdminSessionSecret();
|
||||
if (!sessionSecret || sessionSecret.length < 32) {
|
||||
return NextResponse.json(
|
||||
{ error: "Admin session configuration is unavailable." },
|
||||
@@ -30,8 +29,21 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = await request.json();
|
||||
body =
|
||||
parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
||||
? (parsed as Record<string, unknown>)
|
||||
: {};
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid setup request payload." },
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const email =
|
||||
typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
|
||||
const password = typeof body.password === "string" ? body.password : "";
|
||||
@@ -74,6 +86,7 @@ export async function POST(request: NextRequest) {
|
||||
email,
|
||||
sessionSecret,
|
||||
Date.now() + SESSION_SECONDS * 1000,
|
||||
1,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
response.cookies.set(
|
||||
|
||||
Reference in new issue
Block a user