fix(blog): preserve sanitized content through hydration
Deploy Canina / deploy (push) Successful in 2m12s

This commit is contained in:
devops committed 2026-10-17 11:45:34 +00:00
1 parent 5573bb3568
commit 297aaadbe6
6 files changed
+72 -17

No files matched your search

@@ -4,6 +4,7 @@ import type { Metadata } from 'next';
import BlogPostClient from "../../../components/BlogPostClient";
import { getSeoConfig, formatPageTitle } from "../../../lib/seo";
import { safeJsonLd } from "../../../lib/schema";
import { sanitizeBlogHtml } from "../../../lib/sanitizeBlogHtml";
function safeIso(val: any, fallback?: string): string | undefined {
if (!val) return fallback;
@@ -182,6 +183,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
const publishedIso = safeIso(blog.publishedAt) || safeIso(blog.createdAt) || new Date().toISOString();
const modifiedIso = safeIso(blog.updatedAt) || publishedIso;
const sanitizedContent = sanitizeBlogHtml(blog.content);
const schemaType = blog.schemaType || 'BlogPosting';
const authorSchema = blog.author && (blog.author.firstName || blog.author.lastName)
@@ -279,6 +281,7 @@ export default async function BlogPostPage({ params }: { params: Promise<{ slug:
blog={blog}
publishedDate={publishedDate}
authorName={authorName}
sanitizedContent={sanitizedContent}
/>
</>
);
+6 -6
View File
@@ -297,11 +297,11 @@ export default function BlogPage({
{/* Featured Post Banner */}
{featuredPost && (
<div className="mb-16">
<motion.div
<motion.a
href={`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`}
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className="bg-white rounded-[3.5rem] overflow-hidden border border-medical-gray-200 shadow-2xl flex flex-col lg:flex-row cursor-pointer group hover:border-canina-blue/30 transition-all"
onClick={() => router.push(`/blog/${encodeURIComponent(featuredPost.slug || featuredPost.id)}`)}
>
<div className="lg:w-1/2 aspect-video lg:aspect-auto relative overflow-hidden bg-medical-gray-100">
<SafeImage
@@ -359,7 +359,7 @@ export default function BlogPage({
</div>
</div>
</div>
</motion.div>
</motion.a>
</div>
)}
@@ -375,14 +375,14 @@ export default function BlogPage({
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-8">
{slicedRegularPosts.map((post, idx) => (
<motion.div
<motion.a
key={post.id}
href={`/blog/${encodeURIComponent(post.slug || post.id)}`}
initial={{ opacity: 0, y: 20 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true }}
transition={{ delay: idx * 0.05 }}
className="bg-white rounded-2xl sm:rounded-[2.5rem] overflow-hidden border border-medical-gray-200 shadow-xs sm:shadow-lg group hover:shadow-xl hover:border-canina-blue/30 transition-all cursor-pointer flex flex-col justify-between"
onClick={() => router.push(`/blog/${encodeURIComponent(post.slug || post.id)}`)}
>
<div>
<div className="aspect-[16/10] overflow-hidden relative bg-medical-gray-100">
@@ -440,7 +440,7 @@ export default function BlogPage({
<ArrowLeft className="w-3.5 h-3.5 group-hover:-translate-x-1 transition-transform" />
</div>
</div>
</motion.div>
</motion.a>
))}
</div>
@@ -1,6 +1,5 @@
"use client";
import React, { useState, useEffect } from "react";
import DOMPurify from 'dompurify';
import {
ChevronRight,
Calendar,
@@ -24,9 +23,10 @@ interface BlogPostClientProps {
blog: any;
publishedDate: string;
authorName: string;
sanitizedContent: string;
}
export default function BlogPostClient({ blog, publishedDate, authorName }: BlogPostClientProps) {
export default function BlogPostClient({ blog, publishedDate, authorName, sanitizedContent }: BlogPostClientProps) {
const [copied, setCopied] = useState(false);
const [viewCount, setViewCount] = useState<number>(blog.viewCount || 0);
const [commentName, setCommentName] = useState("");
@@ -176,14 +176,7 @@ export default function BlogPostClient({ blog, publishedDate, authorName }: Blog
{/* Main Rich Content HTML Renderer */}
<div
className="prose prose-base sm:prose-lg max-w-none text-medical-gray-700 leading-loose space-y-5 article-html-content"
dangerouslySetInnerHTML={{
__html: typeof window !== 'undefined'
? DOMPurify.sanitize(blog.content || '', {
ADD_TAGS: ['iframe'],
ADD_ATTR: ['allow', 'allowfullscreen', 'frameborder', 'scrolling'],
})
: blog.content || '',
}}
dangerouslySetInnerHTML={{ __html: sanitizedContent }}
/>
{/* Tags Chip Footer */}
@@ -20,7 +20,7 @@ const blogs=[{id:'1',slug:'joint',title:'Joint article',excerpt:'Mobility guide'
const categories=[{id:'joints',name:'Joints',slug:'joints'},{id:'skin',name:'Skin',slug:'skin'}];
beforeEach(()=>vi.clearAllMocks());
describe('BlogPage',()=>{
it('prioritizes featured post and navigates',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');fireEvent.click(screen.getByText('Skin article'));expect(h.push).toHaveBeenCalledWith('/blog/skin');});
it('renders featured and regular posts as semantic links',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);expect(screen.getAllByRole('heading',{level:2})[0]).toHaveTextContent('Skin article');expect(screen.getByRole('link',{name:/Skin article/})).toHaveAttribute('href','/blog/skin');expect(screen.getByRole('link',{name:/Joint article/})).toHaveAttribute('href','/blog/joint');});
it('combines category, excerpt search and tags then resets empty intersection',()=>{render(<BlogPage blogs={blogs} categories={categories}/>);fireEvent.click(screen.getByRole('button',{name:'Joints'}));expect(h.replace).toHaveBeenCalledWith('/blog?categoryId=joints',{scroll:false});expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماری‌ها، ویتامین‌ها...'),{target:{value:'MOBILITY'}});expect(screen.getByText('Joint article')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#coat'}));expect(screen.getByText('هیچ مقاله‌ای با معیارهای جستجوی شما یافت نشد.')).toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'پاکسازی همه فیلترها'}));expect(screen.getByText('Skin article')).toBeInTheDocument();expect(screen.getByText('Joint article')).toBeInTheDocument();});
it('syncs category with route props',()=>{const view=render(<BlogPage blogs={blogs} categories={categories} initialCategoryId="joints"/>);expect(screen.queryByText('Skin article')).not.toBeInTheDocument();view.rerender(<BlogPage blogs={blogs} categories={categories} initialCategoryId="skin"/>);expect(screen.queryByText('Joint article')).not.toBeInTheDocument();});
it('clears search and toggles tags off',()=>{render(<BlogPage blogs={blogs}/>);fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.queryByText('Skin article')).not.toBeInTheDocument();fireEvent.click(screen.getByRole('button',{name:'#health'}));expect(screen.getByText('Skin article')).toBeInTheDocument();fireEvent.change(screen.getByPlaceholderText('جستجو در موضوعات، بیماری‌ها، ویتامین‌ها...'),{target:{value:'missing'}});fireEvent.click(screen.getByRole('button',{name:'پاک کردن'}));expect(screen.getByText('Skin article')).toBeInTheDocument();});
@@ -80,6 +80,7 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -113,6 +114,7 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -133,6 +135,7 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -170,6 +173,7 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -215,6 +219,7 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -241,6 +246,7 @@ describe("BlogPostClient Component", () => {
render(
<BlogPostClient
blog={mockBlog}
sanitizedContent={mockBlog.content}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
@@ -254,4 +260,25 @@ describe("BlogPostClient Component", () => {
expect(screen.getByText("لینک کپی شد!")).toBeInTheDocument();
});
});
it("renders the server-sanitized article HTML instead of recomputing content in the browser", () => {
const rawContent = "<!--metaTitle: hidden--><p>متن خام متفاوت</p><script>alert(1)</script>";
const sanitizedContent = "<p>اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید</p><h2>راهنمای تغذیه</h2>";
const { container } = render(
<BlogPostClient
blog={{ ...mockBlog, content: rawContent }}
sanitizedContent={sanitizedContent}
publishedDate="۱۵ فروردین ۱۴۰۵"
authorName="دکتر توماس بکر"
/>
);
const article = container.querySelector('.article-html-content');
expect(article?.innerHTML).toBe(sanitizedContent);
expect(article).toHaveTextContent('اگر بچه‌گربه‌ای یتیم پیدا کرده‌اید');
expect(article?.innerHTML).not.toContain('metaTitle');
expect(article?.innerHTML).not.toContain('<script');
});
});
@@ -0,0 +1,32 @@
import sanitizeHtml from "sanitize-html";
const allowedTags = Array.from(new Set([
...sanitizeHtml.defaults.allowedTags,
"img", "iframe", "figure", "figcaption", "table", "thead", "tbody", "tfoot",
"tr", "th", "td", "video", "source", "details", "summary",
]));
export function sanitizeBlogHtml(content: unknown): string {
if (typeof content !== "string" || !content) return "";
return sanitizeHtml(content, {
allowedTags,
allowedAttributes: {
...sanitizeHtml.defaults.allowedAttributes,
"*": ["class", "id", "dir", "lang", "title"],
a: ["href", "name", "target", "rel", "class", "title"],
img: ["src", "alt", "title", "width", "height", "loading", "class"],
iframe: ["src", "title", "width", "height", "allow", "allowfullscreen", "frameborder", "scrolling", "loading", "class"],
video: ["src", "poster", "controls", "preload", "width", "height", "class"],
source: ["src", "type"],
td: ["colspan", "rowspan", "class"],
th: ["colspan", "rowspan", "scope", "class"],
},
allowedSchemes: ["http", "https", "mailto", "tel"],
allowedSchemesByTag: { img: ["http", "https", "data"] },
allowedIframeHostnames: ["www.youtube.com", "youtube.com", "www.aparat.com", "aparat.com"],
transformTags: {
a: sanitizeHtml.simpleTransform("a", { rel: "noopener noreferrer" }, true),
},
});
}