feat(auth): harden session management and security
- Implement server-side session revocation on logout - Add IP extraction utility and admin setup error handling - Improve error codes and response consistency for auth endpoints - Refine landing page redirect logic to handle transient DB outages - Update deployment documentation and configuration defaults
This commit is contained in:
1 parent
935f12a1e9
commit
89e4d68690
81 files changed
+11530
-6916
No files matched your search
+12
-12
@@ -4,27 +4,18 @@ import {
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
AdminSetupRequiredError,
|
||||
authenticateAdminCredentials,
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
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 = getAdminSessionSecret();
|
||||
|
||||
@@ -91,7 +82,16 @@ export async function POST(request: NextRequest) {
|
||||
let authResult: { authenticated: boolean; tokenVersion: number };
|
||||
try {
|
||||
authResult = await authenticateAdminCredentials(email, password);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
if (err instanceof AdminSetupRequiredError) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Initial admin setup is required before signing in.",
|
||||
code: err.code,
|
||||
},
|
||||
{ status: 409 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "Admin authentication is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
|
||||
@@ -1,9 +1,25 @@
|
||||
import { getSessionCookieOptions } from "@/core/auth/adminSession";
|
||||
import {
|
||||
revokeAdminSessions,
|
||||
verifyRequestAdminSession,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const token = request.cookies.get(SESSION_COOKIE)?.value;
|
||||
if (token) {
|
||||
try {
|
||||
const check = await verifyRequestAdminSession(token);
|
||||
if (check.valid) {
|
||||
await revokeAdminSessions();
|
||||
}
|
||||
} catch {
|
||||
// Still clear client cookie even if server revocation encounters transient DB error
|
||||
}
|
||||
}
|
||||
|
||||
const response = NextResponse.json({ success: true });
|
||||
response.cookies.set(SESSION_COOKIE, "", {
|
||||
...getSessionCookieOptions(request, 0),
|
||||
|
||||
@@ -22,11 +22,13 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
if (!auth.valid) {
|
||||
const status = auth.reason === "UNAUTHORIZED" ? 401 : 503;
|
||||
const code =
|
||||
auth.reason === "UNAUTHORIZED" ? "SESSION_EXPIRED" : "AUTH_UNAVAILABLE";
|
||||
const message =
|
||||
auth.reason === "UNAUTHORIZED"
|
||||
? "Authentication required."
|
||||
: "Admin authentication is temporarily unavailable.";
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
return NextResponse.json({ error: message, code }, { status });
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -54,11 +56,13 @@ export async function PUT(request: NextRequest) {
|
||||
|
||||
if (!auth.valid) {
|
||||
const status = auth.reason === "UNAUTHORIZED" ? 401 : 503;
|
||||
const code =
|
||||
auth.reason === "UNAUTHORIZED" ? "SESSION_EXPIRED" : "AUTH_UNAVAILABLE";
|
||||
const message =
|
||||
auth.reason === "UNAUTHORIZED"
|
||||
? "Authentication required."
|
||||
: "Admin authentication is temporarily unavailable.";
|
||||
return NextResponse.json({ error: message }, { status });
|
||||
return NextResponse.json({ error: message, code }, { status });
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
@@ -115,7 +119,10 @@ export async function PUT(request: NextRequest) {
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
return NextResponse.json({ error: result.error }, { status: 401 });
|
||||
return NextResponse.json(
|
||||
{ error: result.error, code: "INVALID_PASSWORD" },
|
||||
{ status: 401 },
|
||||
);
|
||||
}
|
||||
|
||||
// Preserve remaining session duration (e.g., 30-day "Remember me" session)
|
||||
|
||||
@@ -4,14 +4,20 @@ import {
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
AdminDatabaseRequiredError,
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
createInitialAdmin,
|
||||
isAdminSetupComplete,
|
||||
requiresPersistentAdminDatabase,
|
||||
verifyAdminSetupKey,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { extractClientIp } from "@/lib/adminAuth";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
const SESSION_SECONDS = 8 * 60 * 60;
|
||||
const SETUP_THROTTLE_BUCKET = "__admin_setup__";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -29,6 +35,17 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
if (requiresPersistentAdminDatabase()) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
"PostgreSQL DATABASE_URL must be configured in production before initial admin setup.",
|
||||
code: "DATABASE_NOT_CONFIGURED",
|
||||
},
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
|
||||
let body: Record<string, unknown>;
|
||||
try {
|
||||
const parsed = await request.json();
|
||||
@@ -61,12 +78,7 @@ export async function POST(request: NextRequest) {
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
if (!verifyAdminSetupKey(setupKey)) {
|
||||
return NextResponse.json(
|
||||
{ error: "The installation key is invalid." },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
if (await isAdminSetupComplete()) {
|
||||
return NextResponse.json(
|
||||
{ error: "Initial admin setup has already been completed." },
|
||||
@@ -74,6 +86,34 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
const clientIp = extractClientIp(request);
|
||||
const throttleDecision = await consumeAdminLoginAttempt(
|
||||
SETUP_THROTTLE_BUCKET,
|
||||
sessionSecret,
|
||||
clientIp,
|
||||
);
|
||||
if (!throttleDecision.allowed) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: "Too many setup attempts. Try again later.",
|
||||
code: "TOO_MANY_ATTEMPTS",
|
||||
},
|
||||
{
|
||||
status: 429,
|
||||
headers: {
|
||||
"Retry-After": String(throttleDecision.retryAfterSeconds),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (!verifyAdminSetupKey(setupKey)) {
|
||||
return NextResponse.json(
|
||||
{ error: "The installation key is invalid." },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
|
||||
const created = await createInitialAdmin(email, password);
|
||||
if (!created) {
|
||||
return NextResponse.json(
|
||||
@@ -82,6 +122,12 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
}
|
||||
|
||||
await clearAdminLoginAttempts(
|
||||
SETUP_THROTTLE_BUCKET,
|
||||
sessionSecret,
|
||||
clientIp,
|
||||
).catch(() => undefined);
|
||||
|
||||
const token = await createAdminSessionToken(
|
||||
email,
|
||||
sessionSecret,
|
||||
@@ -95,7 +141,13 @@ export async function POST(request: NextRequest) {
|
||||
getSessionCookieOptions(request, SESSION_SECONDS),
|
||||
);
|
||||
return response;
|
||||
} catch {
|
||||
} catch (err) {
|
||||
if (err instanceof AdminDatabaseRequiredError) {
|
||||
return NextResponse.json(
|
||||
{ error: err.message, code: err.code },
|
||||
{ status: 503 },
|
||||
);
|
||||
}
|
||||
return NextResponse.json(
|
||||
{ error: "Admin setup is temporarily unavailable." },
|
||||
{ status: 503 },
|
||||
|
||||
Reference in new issue
Block a user