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 {
|
import {
|
||||||
clearAdminLoginAttempts,
|
clearAdminLoginAttempts,
|
||||||
consumeAdminLoginAttempt,
|
consumeAdminLoginAttempt,
|
||||||
verifyAdminCredentials,
|
verifyAdminCredentials,
|
||||||
} from "@/core/auth/adminUsers";
|
} from "@/core/auth/adminUsers";
|
||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { createHash, timingSafeEqual } from "node:crypto";
|
|
||||||
|
|
||||||
const SESSION_COOKIE = "datastack_admin_session";
|
const SESSION_COOKIE = "datastack_admin_session";
|
||||||
const SESSION_SECONDS = 8 * 60 * 60;
|
const SESSION_SECONDS = 8 * 60 * 60;
|
||||||
const REMEMBERED_SESSION_SECONDS = 30 * 24 * 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) {
|
export async function POST(request: NextRequest) {
|
||||||
const sessionSecret =
|
const sessionSecret =
|
||||||
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||||
@@ -100,13 +96,11 @@ export async function POST(request: NextRequest) {
|
|||||||
);
|
);
|
||||||
const response = NextResponse.json({ success: true });
|
const response = NextResponse.json({ success: true });
|
||||||
|
|
||||||
response.cookies.set(SESSION_COOKIE, token, {
|
response.cookies.set(
|
||||||
httpOnly: true,
|
SESSION_COOKIE,
|
||||||
secure: process.env.NODE_ENV === "production",
|
token,
|
||||||
sameSite: "strict",
|
getSessionCookieOptions(request, maxAge),
|
||||||
path: "/",
|
);
|
||||||
maxAge,
|
|
||||||
});
|
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
} catch {
|
} 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";
|
const SESSION_COOKIE = "datastack_admin_session";
|
||||||
|
|
||||||
export async function POST() {
|
export async function POST(request: NextRequest) {
|
||||||
const response = NextResponse.json({ success: true });
|
const response = NextResponse.json({ success: true });
|
||||||
response.cookies.set(SESSION_COOKIE, "", {
|
response.cookies.set(SESSION_COOKIE, "", {
|
||||||
httpOnly: true,
|
...getSessionCookieOptions(request, 0),
|
||||||
secure: process.env.NODE_ENV === "production",
|
|
||||||
sameSite: "strict",
|
|
||||||
path: "/",
|
|
||||||
maxAge: 0,
|
|
||||||
expires: new Date(0),
|
expires: new Date(0),
|
||||||
});
|
});
|
||||||
return response;
|
return response;
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { createAdminSessionToken } from "@/core/auth/adminSession";
|
import {
|
||||||
|
createAdminSessionToken,
|
||||||
|
getSessionCookieOptions,
|
||||||
|
} from "@/core/auth/adminSession";
|
||||||
import {
|
import {
|
||||||
createInitialAdmin,
|
createInitialAdmin,
|
||||||
isAdminSetupComplete,
|
isAdminSetupComplete,
|
||||||
@@ -90,13 +93,11 @@ export async function POST(request: NextRequest) {
|
|||||||
Date.now() + SESSION_SECONDS * 1000,
|
Date.now() + SESSION_SECONDS * 1000,
|
||||||
);
|
);
|
||||||
const response = NextResponse.json({ success: true });
|
const response = NextResponse.json({ success: true });
|
||||||
response.cookies.set(SESSION_COOKIE, token, {
|
response.cookies.set(
|
||||||
httpOnly: true,
|
SESSION_COOKIE,
|
||||||
secure: process.env.NODE_ENV === "production",
|
token,
|
||||||
sameSite: "strict",
|
getSessionCookieOptions(request, SESSION_SECONDS),
|
||||||
path: "/",
|
);
|
||||||
maxAge: SESSION_SECONDS,
|
|
||||||
});
|
|
||||||
return response;
|
return response;
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
|
|||||||
@@ -64,10 +64,12 @@ export const Sidebar: React.FC<SidebarProps> = ({
|
|||||||
setIsSigningOut(true);
|
setIsSigningOut(true);
|
||||||
setSignOutError('');
|
setSignOutError('');
|
||||||
try {
|
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.');
|
if (!response.ok) throw new Error('Unable to sign out. Please try again.');
|
||||||
router.replace('/vcon/login');
|
window.location.assign('/vcon/login');
|
||||||
router.refresh();
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setSignOutError(
|
setSignOutError(
|
||||||
error instanceof Error ? error.message : 'Unable to sign out. Please try again.',
|
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 { Input } from '@/components/ui/Input';
|
||||||
import { ArrowRight } from 'lucide-react';
|
import { ArrowRight } from 'lucide-react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
function safeNextPath() {
|
function safeNextPath() {
|
||||||
@@ -16,7 +15,6 @@ function safeNextPath() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function AdminLogin() {
|
export function AdminLogin() {
|
||||||
const router = useRouter();
|
|
||||||
const [email, setEmail] = useState('admin@datastack.dev');
|
const [email, setEmail] = useState('admin@datastack.dev');
|
||||||
const [password, setPassword] = useState('admin12345678');
|
const [password, setPassword] = useState('admin12345678');
|
||||||
const [remember, setRemember] = useState(true);
|
const [remember, setRemember] = useState(true);
|
||||||
@@ -50,12 +48,16 @@ export function AdminLogin() {
|
|||||||
const response = await fetch('/api/auth/login', {
|
const response = await fetch('/api/auth/login', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
credentials: 'include',
|
||||||
body: JSON.stringify({ email, password, remember }),
|
body: JSON.stringify({ email, password, remember }),
|
||||||
});
|
});
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
if (!response.ok) throw new Error(body.error || 'Sign in failed.');
|
if (!response.ok) throw new Error(body.error || 'Sign in failed.');
|
||||||
router.replace(safeNextPath());
|
const targetPath = safeNextPath();
|
||||||
router.refresh();
|
window.location.assign(targetPath);
|
||||||
|
window.setTimeout(() => {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}, 2500);
|
||||||
} catch (submitError) {
|
} catch (submitError) {
|
||||||
setErrorMessage(submitError instanceof Error ? submitError.message : 'Unable to sign in.');
|
setErrorMessage(submitError instanceof Error ? submitError.message : 'Unable to sign in.');
|
||||||
setIsSubmitting(false);
|
setIsSubmitting(false);
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import { Button } from '@/components/ui/Button';
|
|||||||
import { Input } from '@/components/ui/Input';
|
import { Input } from '@/components/ui/Input';
|
||||||
import { ArrowRight } from 'lucide-react';
|
import { ArrowRight } from 'lucide-react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { useRouter } from 'next/navigation';
|
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
|
||||||
export function AdminSetup({
|
export function AdminSetup({
|
||||||
@@ -14,7 +13,6 @@ export function AdminSetup({
|
|||||||
databaseReady?: boolean;
|
databaseReady?: boolean;
|
||||||
initialEmail?: string;
|
initialEmail?: string;
|
||||||
}) {
|
}) {
|
||||||
const router = useRouter();
|
|
||||||
const [email, setEmail] = useState(initialEmail || 'admin@datastack.dev');
|
const [email, setEmail] = useState(initialEmail || 'admin@datastack.dev');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [confirmPassword, setConfirmPassword] = useState('');
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
@@ -42,12 +40,15 @@ export function AdminSetup({
|
|||||||
const response = await fetch('/api/auth/setup', {
|
const response = await fetch('/api/auth/setup', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
credentials: 'include',
|
||||||
body: JSON.stringify({ email, password, setupKey }),
|
body: JSON.stringify({ email, password, setupKey }),
|
||||||
});
|
});
|
||||||
const body = await response.json();
|
const body = await response.json();
|
||||||
if (!response.ok) throw new Error(body.error || 'Admin setup failed.');
|
if (!response.ok) throw new Error(body.error || 'Admin setup failed.');
|
||||||
router.replace('/vcon/dashboard');
|
window.location.assign('/vcon/dashboard');
|
||||||
router.refresh();
|
window.setTimeout(() => {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}, 2500);
|
||||||
} catch (submitError) {
|
} catch (submitError) {
|
||||||
setErrorMessage(
|
setErrorMessage(
|
||||||
submitError instanceof Error ? submitError.message : 'Admin setup failed.',
|
submitError instanceof Error ? submitError.message : 'Admin setup failed.',
|
||||||
|
|||||||
@@ -71,3 +71,35 @@ export async function verifyAdminSessionToken(token: string, secret: string) {
|
|||||||
return false;
|
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) {
|
function isSameOriginRequest(request: NextRequest) {
|
||||||
const originHeader = request.headers.get("origin");
|
const originHeader = request.headers.get("origin");
|
||||||
const requestHost = request.headers.get("host");
|
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 {
|
try {
|
||||||
const origin = new URL(originHeader);
|
const origin = new URL(originHeader);
|
||||||
const forwardedProtocol = request.headers
|
const originHost = origin.host.toLowerCase();
|
||||||
.get("x-forwarded-proto")
|
const matchesHost =
|
||||||
?.split(",")[0]
|
(requestHost && originHost === requestHost.toLowerCase()) ||
|
||||||
.trim()
|
(forwardedHost && originHost === forwardedHost.toLowerCase());
|
||||||
.toLowerCase();
|
|
||||||
const requestProtocol =
|
|
||||||
forwardedProtocol || request.nextUrl.protocol.replace(/:$/, "");
|
|
||||||
|
|
||||||
return (
|
return Boolean(matchesHost);
|
||||||
origin.host.toLowerCase() === requestHost.toLowerCase() &&
|
|
||||||
origin.protocol === `${requestProtocol}:`
|
|
||||||
);
|
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user