refactor: standardize session cookie configuration
Centralize cookie security options to dynamically detect HTTPS, ensure secure transport, and update client-side auth handlers to use explicit credential inclusion for cookie-based sessions.
This commit is contained in:
1 parent
fde2c86b1e
commit
b42029f67d
8 files changed
+80
-53
No files matched your search
@@ -1,22 +1,18 @@
|
||||
import { createAdminSessionToken } from "@/core/auth/adminSession";
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
clearAdminLoginAttempts,
|
||||
consumeAdminLoginAttempt,
|
||||
verifyAdminCredentials,
|
||||
} from "@/core/auth/adminUsers";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
const SESSION_SECONDS = 8 * 60 * 60;
|
||||
const REMEMBERED_SESSION_SECONDS = 30 * 24 * 60 * 60;
|
||||
|
||||
function constantTimeEqual(left: string, right: string) {
|
||||
const leftHash = createHash("sha256").update(left).digest();
|
||||
const rightHash = createHash("sha256").update(right).digest();
|
||||
return timingSafeEqual(leftHash, rightHash);
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const sessionSecret =
|
||||
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||
@@ -100,13 +96,11 @@ export async function POST(request: NextRequest) {
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
|
||||
response.cookies.set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "strict",
|
||||
path: "/",
|
||||
maxAge,
|
||||
});
|
||||
response.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
getSessionCookieOptions(request, maxAge),
|
||||
);
|
||||
|
||||
return response;
|
||||
} catch {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { getSessionCookieOptions } from "@/core/auth/adminSession";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const SESSION_COOKIE = "datastack_admin_session";
|
||||
|
||||
export async function POST() {
|
||||
export async function POST(request: NextRequest) {
|
||||
const response = NextResponse.json({ success: true });
|
||||
response.cookies.set(SESSION_COOKIE, "", {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "strict",
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
...getSessionCookieOptions(request, 0),
|
||||
expires: new Date(0),
|
||||
});
|
||||
return response;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { createAdminSessionToken } from "@/core/auth/adminSession";
|
||||
import {
|
||||
createAdminSessionToken,
|
||||
getSessionCookieOptions,
|
||||
} from "@/core/auth/adminSession";
|
||||
import {
|
||||
createInitialAdmin,
|
||||
isAdminSetupComplete,
|
||||
@@ -90,13 +93,11 @@ export async function POST(request: NextRequest) {
|
||||
Date.now() + SESSION_SECONDS * 1000,
|
||||
);
|
||||
const response = NextResponse.json({ success: true });
|
||||
response.cookies.set(SESSION_COOKIE, token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
sameSite: "strict",
|
||||
path: "/",
|
||||
maxAge: SESSION_SECONDS,
|
||||
});
|
||||
response.cookies.set(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
getSessionCookieOptions(request, SESSION_SECONDS),
|
||||
);
|
||||
return response;
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
|
||||
@@ -64,10 +64,12 @@ export const Sidebar: React.FC<SidebarProps> = ({
|
||||
setIsSigningOut(true);
|
||||
setSignOutError('');
|
||||
try {
|
||||
const response = await fetch('/api/auth/logout', { method: 'POST' });
|
||||
const response = await fetch('/api/auth/logout', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!response.ok) throw new Error('Unable to sign out. Please try again.');
|
||||
router.replace('/vcon/login');
|
||||
router.refresh();
|
||||
window.location.assign('/vcon/login');
|
||||
} catch (error) {
|
||||
setSignOutError(
|
||||
error instanceof Error ? error.message : 'Unable to sign out. Please try again.',
|
||||
|
||||
@@ -5,7 +5,6 @@ import { FormSwitch } from '@/components/ui/Form';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
function safeNextPath() {
|
||||
@@ -16,7 +15,6 @@ function safeNextPath() {
|
||||
}
|
||||
|
||||
export function AdminLogin() {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState('admin@datastack.dev');
|
||||
const [password, setPassword] = useState('admin12345678');
|
||||
const [remember, setRemember] = useState(true);
|
||||
@@ -50,12 +48,16 @@ export function AdminLogin() {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ email, password, remember }),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new Error(body.error || 'Sign in failed.');
|
||||
router.replace(safeNextPath());
|
||||
router.refresh();
|
||||
const targetPath = safeNextPath();
|
||||
window.location.assign(targetPath);
|
||||
window.setTimeout(() => {
|
||||
setIsSubmitting(false);
|
||||
}, 2500);
|
||||
} catch (submitError) {
|
||||
setErrorMessage(submitError instanceof Error ? submitError.message : 'Unable to sign in.');
|
||||
setIsSubmitting(false);
|
||||
|
||||
@@ -4,7 +4,6 @@ import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { ArrowRight } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
|
||||
export function AdminSetup({
|
||||
@@ -14,7 +13,6 @@ export function AdminSetup({
|
||||
databaseReady?: boolean;
|
||||
initialEmail?: string;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [email, setEmail] = useState(initialEmail || 'admin@datastack.dev');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
@@ -42,12 +40,15 @@ export function AdminSetup({
|
||||
const response = await fetch('/api/auth/setup', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ email, password, setupKey }),
|
||||
});
|
||||
const body = await response.json();
|
||||
if (!response.ok) throw new Error(body.error || 'Admin setup failed.');
|
||||
router.replace('/vcon/dashboard');
|
||||
router.refresh();
|
||||
window.location.assign('/vcon/dashboard');
|
||||
window.setTimeout(() => {
|
||||
setIsSubmitting(false);
|
||||
}, 2500);
|
||||
} catch (submitError) {
|
||||
setErrorMessage(
|
||||
submitError instanceof Error ? submitError.message : 'Admin setup failed.',
|
||||
|
||||
@@ -71,3 +71,35 @@ export async function verifyAdminSessionToken(token: string, secret: string) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function getSessionCookieOptions(request: Request, maxAge: number) {
|
||||
const forwardedProto = request.headers
|
||||
.get("x-forwarded-proto")
|
||||
?.split(",")[0]
|
||||
?.trim()
|
||||
.toLowerCase();
|
||||
const originHeader = request.headers.get("origin")?.toLowerCase() ?? "";
|
||||
const isHttps =
|
||||
forwardedProto === "https" ||
|
||||
originHeader.startsWith("https://") ||
|
||||
request.url.startsWith("https://");
|
||||
|
||||
if (isHttps) {
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "none" as const,
|
||||
partitioned: true,
|
||||
path: "/",
|
||||
maxAge,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
sameSite: "lax" as const,
|
||||
path: "/",
|
||||
maxAge,
|
||||
};
|
||||
}
|
||||
+10
-12
@@ -15,22 +15,20 @@ function isProtectedApi(pathname: string, method: string) {
|
||||
function isSameOriginRequest(request: NextRequest) {
|
||||
const originHeader = request.headers.get("origin");
|
||||
const requestHost = request.headers.get("host");
|
||||
if (!originHeader || !requestHost) return false;
|
||||
const forwardedHost = request.headers
|
||||
.get("x-forwarded-host")
|
||||
?.split(",")[0]
|
||||
?.trim();
|
||||
if (!originHeader || (!requestHost && !forwardedHost)) return false;
|
||||
|
||||
try {
|
||||
const origin = new URL(originHeader);
|
||||
const forwardedProtocol = request.headers
|
||||
.get("x-forwarded-proto")
|
||||
?.split(",")[0]
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const requestProtocol =
|
||||
forwardedProtocol || request.nextUrl.protocol.replace(/:$/, "");
|
||||
const originHost = origin.host.toLowerCase();
|
||||
const matchesHost =
|
||||
(requestHost && originHost === requestHost.toLowerCase()) ||
|
||||
(forwardedHost && originHost === forwardedHost.toLowerCase());
|
||||
|
||||
return (
|
||||
origin.host.toLowerCase() === requestHost.toLowerCase() &&
|
||||
origin.protocol === `${requestProtocol}:`
|
||||
);
|
||||
return Boolean(matchesHost);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user