feat: enhance security by implementing HttpOnly refresh tokens and in-memory access token management

- Added isomorphic-dompurify for improved XSS protection
- Refactored token storage to use in-memory management for access tokens
- Implemented server-side route handlers for OAuth token management
- Introduced security headers in next.config.js
- Removed client-side exposure of client_secret and sensitive tokens
- Updated API interceptors to handle token refresh logic
- Cleaned up cookie management for refresh tokens
This commit is contained in:
hamed
2026-06-20 13:10:17 +03:30
parent a19058d9a2
commit 194ffd889c
29 changed files with 1007 additions and 190 deletions
+13
View File
@@ -2,10 +2,23 @@
import { ThemeProvider } from "next-themes";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
import Cookies from "js-cookie";
import { setAccessToken } from "@/lib/tokenStore";
export function Providers({ children }) {
const router = usePathname();
useEffect(() => {
if (!Cookies.get("userInfo")) return;
fetch("/api/auth/refresh", { method: "POST" })
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (data?.access_token) setAccessToken(data.access_token);
})
.catch(() => {});
}, []);
return (
<ThemeProvider
attribute={router.includes("/panel") ? "class" : "data-"}
+25
View File
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import { axiosInstance } from "@/lib/req";
import { clearRefreshCookie, COOKIE_NAME } from "@/lib/refreshCookie";
export async function POST(request) {
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const host = request.headers.get("host");
const refreshToken = request.cookies.get(COOKIE_NAME)?.value;
if (refreshToken) {
try {
await axiosInstance.post(
`${API_URL}/oauth/logout`,
{ refresh_token: refreshToken },
{ headers: { "Content-Type": "application/json", Authorization: "" } }
);
} catch {
// revoke best-effort; clearing the cookie below is what matters
}
}
const response = NextResponse.json({ success: true }, { status: 200 });
clearRefreshCookie(response, host);
return response;
}
+19 -13
View File
@@ -1,28 +1,34 @@
import { NextResponse } from "next/server";
import { axiosInstance } from "@/lib/req";
import { setRefreshCookie, clearRefreshCookie, COOKIE_NAME } from "@/lib/refreshCookie";
export async function POST(request) {
const { refresh_token } = await request.json();
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const host = request.headers.get("host");
const refreshToken = request.cookies.get(COOKIE_NAME)?.value;
if (!refresh_token) {
return NextResponse.json({ error: "refresh_token is required" }, { status: 400 });
if (!refreshToken) {
return NextResponse.json({ error: "no refresh token" }, { status: 401 });
}
try {
const res = await axiosInstance.post(
`${API_URL}/oauth/token/refresh`,
{ refresh_token },
{
headers: { "Content-Type": "application/json", Authorization: "" },
}
{ refresh_token: refreshToken },
{ headers: { "Content-Type": "application/json", Authorization: "" } }
);
return NextResponse.json(res.data, { status: res.status });
const { access_token, refresh_token, expires_in } = res.data;
const response = NextResponse.json({ access_token, expires_in }, { status: 200 });
setRefreshCookie(response, refresh_token, host);
return response;
} catch (error) {
if (error.response) {
return NextResponse.json(error.response.data, { status: error.response.status });
}
return NextResponse.json({ error: "Refresh request failed" }, { status: 500 });
const response = NextResponse.json(
error.response?.data ?? { error: "Refresh request failed" },
{ status: 401 }
);
clearRefreshCookie(response, host);
return response;
}
}
+15 -7
View File
@@ -1,9 +1,9 @@
import { NextResponse } from "next/server";
import { axiosInstance } from "@/lib/req";
import { setRefreshCookie } from "@/lib/refreshCookie";
export async function POST(request) {
const { uuid, code } = await request.json();
const API_URL = process.env.NEXT_PUBLIC_API_URL;
if (!uuid || !code) {
@@ -13,20 +13,28 @@ export async function POST(request) {
const jsonHeaders = { "Content-Type": "application/json", Authorization: "" };
try {
// مرحله ۱: تأیید OTP — بدون این، oauth/token کد را verified نمی‌بیند
await axiosInstance.post(
const verify = await axiosInstance.post(
`${API_URL}/api/v1/user/verify-code`,
{ uuid, code },
{ headers: jsonHeaders }
);
// مرحله ۲: تبدیل uuid تأییدشده به توکن
const res = await axiosInstance.post(
const grant = verify.data?.data?.grant;
if (!grant) {
return NextResponse.json({ error: "grant not issued" }, { status: 400 });
}
const token = await axiosInstance.post(
`${API_URL}/oauth/token`,
{ grant_type: "mobile", uuid },
{ grant_type: "mobile", grant },
{ headers: jsonHeaders }
);
return NextResponse.json(res.data, { status: res.status });
const { access_token, refresh_token, expires_in } = token.data;
const response = NextResponse.json({ access_token, expires_in }, { status: 200 });
setRefreshCookie(response, refresh_token, request.headers.get("host"));
return response;
} catch (error) {
if (error.response) {
return NextResponse.json(error.response.data, { status: error.response.status });
+6 -1
View File
@@ -8,8 +8,13 @@ import { useState } from "react";
function ModalLogout({ open, handleClose }) {
const router = useRouter();
const [loading, setLoading] = useState(false);
const logout = () => {
const logout = async () => {
setLoading(true);
try {
await fetch("/api/auth/logout", { method: "POST" });
} catch {
// clearing client state below is what matters
}
removeToken();
router.replace("/login");
};
+1 -1
View File
@@ -4,7 +4,7 @@ import Cookies from "js-cookie";
function SendAppo({ hour, setStep, setSelectedSlot, date, setSelectedDate }) {
const sendReq = () => {
const isLogged = Cookies.get("access_token");
const isLogged = Cookies.get("userInfo");
// ذخیره کردن اطلاعات اسلات انتخاب شده
if (hour && date) {
+5 -4
View File
@@ -8,6 +8,7 @@ import { redirect } from "next/navigation";
import { fetchReq } from "@/lib/req";
import { safeJsonParse } from "@/lib/sanitize";
import { buildPatientUser } from "@/lib/representationAdapters";
import { getServerAccessToken } from "@/lib/serverToken";
export default async function Dashboard({ searchParams }) {
const awaitedSearchParams = await searchParams;
@@ -16,9 +17,9 @@ export default async function Dashboard({ searchParams }) {
const ability = defineAbilitiesFor(user);
const cookieStore = await cookies();
const token = cookieStore.get("access_token");
const token = await getServerAccessToken();
if (!ability.can("access", "Dashboard")) {
if (!ability.can("access", "Dashboard") || !token) {
removeToken();
return redirect("/login");
}
@@ -27,7 +28,7 @@ export default async function Dashboard({ searchParams }) {
// may still carry the OTP uuid, which 404s against user-profile.
const userInfo = safeJsonParse(cookieStore.get("userInfo")?.value);
const userUuid = userInfo?.uuid || cookieStore.get("uuid")?.value;
const authHeader = { headers: { Authorization: `Bearer ${token.value}` } };
const authHeader = { headers: { Authorization: `Bearer ${token}` } };
const API = process.env.NEXT_PUBLIC_API_URL;
const [profile, appointmentsRes, paymentsRes] = await Promise.all([
@@ -54,7 +55,7 @@ export default async function Dashboard({ searchParams }) {
return (
<Content
logged={token.value}
logged={true}
params={awaitedSearchParams}
matchedCity={matchedCity}
user={buildPatientUser(profile, extras)}
+12 -9
View File
@@ -3,6 +3,7 @@ import { cookies } from "next/headers";
import { fetchReq } from "@/lib/req";
import { safeJsonParse } from "@/lib/sanitize";
import { adaptRepresentationDashboard } from "@/lib/representationAdapters";
import { getServerAccessToken } from "@/lib/serverToken";
export const dynamic = "force-dynamic";
@@ -13,21 +14,23 @@ async function Dashboard() {
try {
const cookieStore = await cookies();
const userInfo = cookieStore.get("userInfo");
const accessToken = cookieStore.get("access_token");
if (userInfo && accessToken) {
if (userInfo) {
const parsedUserInfo = safeJsonParse(userInfo.value);
const representationUuid = parsedUserInfo?.representation_uuid;
if (representationUuid) {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const accessToken = await getServerAccessToken();
if (accessToken) {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
dashboard = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}/dashboard/monthly?year=${year}&month=${month}`,
{ headers: { Authorization: `Bearer ${accessToken.value}` } }
);
dashboard = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}/dashboard/monthly?year=${year}&month=${month}`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
}
}
}
} catch (error) {
+13 -10
View File
@@ -5,6 +5,7 @@ import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { fetchReq } from "@/lib/req";
import { safeJsonParse } from "@/lib/sanitize";
import { getServerAccessToken } from "@/lib/serverToken";
async function LayoutPanel({ children }) {
const user = await getUser();
@@ -20,22 +21,24 @@ async function LayoutPanel({ children }) {
try {
const cookieStore = await cookies();
const userInfo = cookieStore.get("userInfo");
const accessToken = cookieStore.get("access_token");
if (userInfo && accessToken) {
if (userInfo) {
const parsedUserInfo = safeJsonParse(userInfo.value);
if (!parsedUserInfo) return;
const representationUuid = parsedUserInfo?.representation_uuid;
if (representationUuid) {
representationInfo = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}`,
{
headers: {
Authorization: `Bearer ${accessToken.value}`,
},
}
);
const accessToken = await getServerAccessToken();
if (accessToken) {
representationInfo = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}`,
{
headers: {
Authorization: `Bearer ${accessToken}`,
},
}
);
}
}
}
} catch (error) {
+12 -9
View File
@@ -3,6 +3,7 @@ import { cookies } from "next/headers";
import { fetchReq } from "@/lib/req";
import { safeJsonParse } from "@/lib/sanitize";
import { adaptRepresentationDashboard } from "@/lib/representationAdapters";
import { getServerAccessToken } from "@/lib/serverToken";
export const dynamic = "force-dynamic";
@@ -13,21 +14,23 @@ async function page() {
try {
const cookieStore = await cookies();
const userInfo = cookieStore.get("userInfo");
const accessToken = cookieStore.get("access_token");
if (userInfo && accessToken) {
if (userInfo) {
const parsedUserInfo = safeJsonParse(userInfo.value);
const representationUuid = parsedUserInfo?.representation_uuid;
if (representationUuid) {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
const accessToken = await getServerAccessToken();
if (accessToken) {
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth() + 1;
dashboard = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}/dashboard/monthly?year=${year}&month=${month}`,
{ headers: { Authorization: `Bearer ${accessToken.value}` } }
);
dashboard = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}/dashboard/monthly?year=${year}&month=${month}`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
}
}
}
} catch (error) {
+9 -6
View File
@@ -3,6 +3,7 @@ import { cookies } from "next/headers";
import { fetchReq } from "@/lib/req";
import { safeJsonParse } from "@/lib/sanitize";
import { adaptBankAccount } from "@/lib/representationAdapters";
import { getServerAccessToken } from "@/lib/serverToken";
export const dynamic = "force-dynamic";
@@ -13,17 +14,19 @@ async function UserAccount() {
try {
const cookieStore = await cookies();
const userInfo = cookieStore.get("userInfo");
const accessToken = cookieStore.get("access_token");
if (userInfo && accessToken) {
if (userInfo) {
const parsedUserInfo = safeJsonParse(userInfo.value);
const representationUuid = parsedUserInfo?.representation_uuid;
if (representationUuid) {
representation = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}`,
{ headers: { Authorization: `Bearer ${accessToken.value}` } }
);
const accessToken = await getServerAccessToken();
if (accessToken) {
representation = await fetchReq(
`${API_URL}/api/v1/representation/${representationUuid}`,
{ headers: { Authorization: `Bearer ${accessToken}` } }
);
}
}
}
} catch (error) {