Skip to content

Commit

Permalink
fix: add DOMPurify for sanitizing HTML to prevent XSS attacks
Browse files Browse the repository at this point in the history
  • Loading branch information
dineshsutihar committed Oct 18, 2024
1 parent 417cb27 commit 753bc7f
Show file tree
Hide file tree
Showing 3 changed files with 451 additions and 6 deletions.
13 changes: 7 additions & 6 deletions app/(app)/articles/[slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { getPost } from "@/server/lib/posts";
import { getCamelCaseFromLower } from "@/utils/utils";
import { generateHTML } from "@tiptap/html";
import { TiptapExtensions } from "@/components/editor/editor/extensions";
import DOMPurify from 'isomorphic-dompurify';

type Props = { params: { slug: string } };

Expand Down Expand Up @@ -68,10 +69,10 @@ const parseJSON = (str: string): any | null => {
}
};

const renderTiptapContent = (jsonContent: JSON) => {
return generateHTML(jsonContent, [
...TiptapExtensions,
]);
const renderSanitizedTiptapContent = (jsonContent: JSON) => {
const rawHtml = generateHTML(jsonContent, [...TiptapExtensions]);
// Sanitize the HTML
return DOMPurify.sanitize(rawHtml);
};

const ArticlePage = async ({ params }: Props) => {
Expand All @@ -83,7 +84,7 @@ const ArticlePage = async ({ params }: Props) => {
const post = await getPost({ slug });

if (!post) {
notFound();
return notFound();
}

const parsedBody = parseJSON(post.body);
Expand All @@ -93,7 +94,7 @@ const ArticlePage = async ({ params }: Props) => {

if (isTiptapContent && parsedBody) {
const jsonContent = parsedBody;
renderedContent = renderTiptapContent(jsonContent);
renderedContent = renderSanitizedTiptapContent(jsonContent);
} else {
const ast = Markdoc.parse(post.body);
const transformedContent = Markdoc.transform(ast, config);
Expand Down
Loading

0 comments on commit 753bc7f

Please sign in to comment.