fix: resolve critical bugs and security issues across the project

Security:
- Disable SSL verification only in development (lib/req.js)
- Wrap all JSON.parse(cookie) calls in try-catch via safeJsonParse utility
- Sanitize dangerouslySetInnerHTML in blog/clinic with sanitizeHtml utility
- Fix open redirect in payment page — validate URL origin before redirect
- Fix cookie cleanup on 401 — use js-cookie with correct domain scope

Performance:
- Wrap ItemDoctor with React.memo to prevent unnecessary re-renders
- Replace <img> with Next.js <Image> in blog Caption component

Functionality:
- Fix memory leak in Recode.js — store intervals in refs, cleanup on unmount
- Add null guard on retryIcon.current before classList manipulation
- Fix getParsedUserInfo in helper to handle malformed cookie gracefully

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
hamed
2026-06-07 09:19:20 +03:30
co-authored by Claude Sonnet 4.6
parent 1aa9f82d2a
commit 59e0a0fe4f
13 changed files with 104 additions and 33 deletions
+2 -1
View File
@@ -1,3 +1,4 @@
import { memo } from "react";
import Image from "next/image";
import { Button } from "@mui/material";
import Link from "next/link";
@@ -109,4 +110,4 @@ function ItemDoctor({ doctor, loading, setDoctors, priority = false }) {
);
}
export default ItemDoctor;
export default memo(ItemDoctor);
+3 -1
View File
@@ -4,6 +4,7 @@ import { getUser } from "@/lib/auth";
import { redirect } from "next/navigation";
import { cookies } from "next/headers";
import { fetchReq } from "@/lib/req";
import { safeJsonParse } from "@/lib/sanitize";
async function LayoutPanel({ children }) {
const user = await getUser();
@@ -22,7 +23,8 @@ async function LayoutPanel({ children }) {
const accessToken = cookieStore.get("access_token");
if (userInfo && accessToken) {
const parsedUserInfo = JSON.parse(userInfo.value);
const parsedUserInfo = safeJsonParse(userInfo.value);
if (!parsedUserInfo) return;
const representationUuid = parsedUserInfo?.representation_uuid;
if (representationUuid) {
+7 -2
View File
@@ -199,8 +199,13 @@ export default function PaymentDetailsPage() {
<>
<button
onClick={() => {
const paymentUrl = `${process.env.NEXT_PUBLIC_API_URL}/payment/${payment.uuid}`;
window.location.href = paymentUrl;
try {
const apiOrigin = new URL(process.env.NEXT_PUBLIC_API_URL).origin;
const paymentUrl = new URL(`/payment/${payment.uuid}`, apiOrigin);
if (paymentUrl.origin === apiOrigin) {
window.location.href = paymentUrl.href;
}
} catch {}
}}
className="flex-1 bg-[#5559CE] hover:bg-[#4448b3] text-white font-bold py-3 px-6 rounded-lg transition-colors"
>
+3 -2
View File
@@ -4,6 +4,7 @@ import { useEffect, useState } from "react";
import { request } from "@/services/response";
import Cookies from "js-cookie";
import Container from "./Container";
import { safeJsonParse } from "@/lib/sanitize";
const defaultData = {
phone: { value: "", isEdit: false },
@@ -39,7 +40,7 @@ function AppointmentPage({ doctor, disabledDates, matchedCity }) {
setIsLoading(true);
const userInfo = Cookies.get("userInfo");
const parsedData = userInfo && JSON.parse(userInfo);
const parsedData = safeJsonParse(userInfo);
const usernameFromCookie = parsedData?.username || "";
// ابتدا شماره موبایل را از Cookie ست می‌کنیم
@@ -112,7 +113,7 @@ function AppointmentPage({ doctor, disabledDates, matchedCity }) {
const refetchUserData = async () => {
if (step === 3) {
const userInfo = Cookies.get("userInfo");
const parsedData = userInfo && JSON.parse(userInfo);
const parsedData = safeJsonParse(userInfo);
const usernameFromCookie = parsedData?.username || "";
if (userInfo && parsedData && !data.uuid) {
+11 -6
View File
@@ -1,4 +1,6 @@
import React from "react";
import Image from "next/image";
import { sanitizeHtml } from "@/lib/sanitize";
function Caption({ data }) {
const imageUrl = data?.images?.[0]?.url;
@@ -6,16 +8,19 @@ function Caption({ data }) {
return (
<>
{imageUrl && imageUrl.trim() !== "" && (
<img
className="rounded-[8px] overflow-hidden w-full object-cover"
src={imageUrl}
alt={data?.title || "blog cover"}
/>
<div className="relative w-full aspect-video rounded-[8px] overflow-hidden">
<Image
src={imageUrl}
alt={data?.title || "blog cover"}
fill
className="object-cover"
/>
</div>
)}
{data?.body?.value && (
<div
className="my-[12px] sm:my-[16px] md:my-[20px] lg:my-[24px] text-[#525252] text-[14px] md:text-[15px] lg:text-[16px] font-normal leading-[26px] sm:leading-[28px] md:leading-[30px] lg:leading-[32px]"
dangerouslySetInnerHTML={{ __html: data.body.value }}
dangerouslySetInnerHTML={{ __html: sanitizeHtml(data.body.value) }}
/>
)}
</>
@@ -1,6 +1,7 @@
import { useState } from "react";
import { Button } from "@mui/material";
import MultilineLoading from "@/app/component/loading/Multiline";
import { sanitizeHtml } from "@/lib/sanitize";
function TextDetail({ data }) {
const [isMore, setIsMore] = useState(false);
@@ -20,7 +21,7 @@ function TextDetail({ data }) {
"after:bg-[linear-gradient(transparent,#FAFAFA)] max-h-[200px] after:absolute"
}
`}
dangerouslySetInnerHTML={{ __html: data?.caption }}
dangerouslySetInnerHTML={{ __html: sanitizeHtml(data?.caption) }}
></p>
</MultilineLoading>
{data?.caption?.length > 180 && (
@@ -5,6 +5,7 @@ import List from "./List";
import Head from "./Head";
import { request } from "@/services/response";
import Cookies from "js-cookie";
import { safeJsonParse } from "@/lib/sanitize";
function Transactions({ user, loading }) {
const [payments, setPayments] = useState([]);
@@ -23,7 +24,8 @@ function Transactions({ user, loading }) {
return;
}
const parsedData = JSON.parse(userInfo);
const parsedData = safeJsonParse(userInfo);
if (!parsedData) { setIsLoading(false); return; }
const userId = parsedData.id || parsedData.uuid;
if (!userId) {
+28 -8
View File
@@ -2,45 +2,66 @@ import RetryLogin from "@/components/icons/RetryLogin";
import { changeNumToDefault } from "@/helper";
import { request } from "@/services/response";
import { Button } from "@mui/material";
import { useEffect, useRef } from "react";
const time_resend_code = 120;
function Recode({ retryIcon, timer, setUuid, num, setTimer }) {
const timerIntervalRef = useRef(null);
const animIntervalRef = useRef(null);
useEffect(() => {
return () => {
if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
if (animIntervalRef.current) clearInterval(animIntervalRef.current);
};
}, []);
const handleTimer = () => {
setTimer("loading");
if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
setTimeout(() => {
setTimer(time_resend_code);
let timePresent = time_resend_code;
const timerInterval = setInterval(() => {
timerIntervalRef.current = setInterval(() => {
timePresent--;
setTimer(timePresent);
!timePresent && clearInterval(timerInterval);
if (!timePresent) {
clearInterval(timerIntervalRef.current);
timerIntervalRef.current = null;
}
}, 1000);
}, 1000);
};
const rotateIcon = () => {
if (!retryIcon.current) return;
retryIcon.current.classList.add("retry-icon");
setTimeout(() => {
retryIcon.current && retryIcon.current.classList.remove("retry-icon");
retryIcon.current?.classList.remove("retry-icon");
}, 1000);
};
const handleReq = () => {
rotateIcon();
const interval = setInterval(() => {
if (animIntervalRef.current) clearInterval(animIntervalRef.current);
animIntervalRef.current = setInterval(() => {
rotateIcon();
}, 1200);
request
.sendCode(changeNumToDefault(num), "")
.then((response) => {
clearInterval(interval);
clearInterval(animIntervalRef.current);
animIntervalRef.current = null;
if (response.uuid) {
setUuid(response.uuid);
handleTimer();
}
})
.catch(() => clearInterval(interval));
.catch(() => {
clearInterval(animIntervalRef.current);
animIntervalRef.current = null;
});
};
return (
@@ -49,7 +70,6 @@ function Recode({ retryIcon, timer, setUuid, num, setTimer }) {
disabled={typeof timer === "number" && timer !== 0}
onClick={() => {
if (!timer && timer !== "loading") {
// handleTimer();
handleReq();
}
}}
+6 -2
View File
@@ -217,8 +217,12 @@ export function hasDataChanged(previousData, newData) {
export const getParsedUserInfo = () => {
const user = Cookies.get("userInfo");
const parsedUserInfo = user && JSON.parse(user);
return parsedUserInfo;
if (!user) return null;
try {
return JSON.parse(user);
} catch {
return null;
}
};
export const handleTimeExpiresToken = (expires_in) => {
+4 -3
View File
@@ -1,4 +1,5 @@
import { AbilityBuilder, createMongoAbility } from "@casl/ability";
import { safeJsonParse } from "./sanitize";
export function defineAbilitiesFor(user) {
const { can, cannot, build } = new AbilityBuilder(createMongoAbility);
@@ -6,9 +7,9 @@ export function defineAbilitiesFor(user) {
if (user) {
can("access", "Dashboard");
cannot("access", "Login");
const parsedData = JSON.parse(user.value);
if (parsedData.roles && Object.values(parsedData.roles).includes("representation")) {
const parsedData = safeJsonParse(user.value);
const roles = parsedData?.roles;
if (roles && Array.isArray(Object.values(roles)) && Object.values(roles).includes("representation")) {
can("access", "Panel");
}
} else {
+3 -4
View File
@@ -1,11 +1,10 @@
import axios from "axios";
import https from "https";
// Create axios instance with SSL verification disabled for development
const axiosInstance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
...(process.env.NODE_ENV === "development" && {
httpsAgent: new https.Agent({ rejectUnauthorized: false }),
}),
});
export const fetchReq = async (url, headers) => {
+26
View File
@@ -0,0 +1,26 @@
const DANGEROUS_TAGS = ['script', 'iframe', 'object', 'embed', 'link', 'meta', 'base', 'form'];
export function sanitizeHtml(html) {
if (!html || typeof html !== 'string') return '';
let sanitized = html;
DANGEROUS_TAGS.forEach((tag) => {
const openClose = new RegExp(`<${tag}[\\s\\S]*?(?:<\\/${tag}>|/?>)`, 'gi');
sanitized = sanitized.replace(openClose, '');
});
sanitized = sanitized.replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]*)/gi, '');
sanitized = sanitized.replace(/(?:javascript|vbscript):/gi, '');
return sanitized;
}
export function safeJsonParse(str, fallback = null) {
if (!str) return fallback;
try {
return JSON.parse(str);
} catch {
return fallback;
}
}
+6 -2
View File
@@ -1,6 +1,5 @@
import axios from "axios";
import Cookies from "js-cookie";
import "react-toastify/dist/ReactToastify.css";
const BASE_URL = process.env.NEXT_PUBLIC_API_URL;
@@ -35,8 +34,13 @@ api.interceptors.response.use(
},
(error) => {
if (error?.response?.status === 401 && typeof window !== "undefined") {
const hostname = window.location.hostname;
const domain = hostname.includes("localhost")
? undefined
: `.${hostname.split(".").slice(-2).join(".")}`;
const opts = { path: "/", ...(domain && { domain }) };
["access_token", "refresh_token", "uuid", "userInfo"].forEach((key) => {
document.cookie = `${key}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
Cookies.remove(key, opts);
});
window.location.href = "/login";
}