Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/lib/actions/renderSanitizedHtml.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { renderSanitizedHtml } from './renderSanitizedHtml';
import { describe, it, expect, beforeEach } from 'vitest';

describe('renderSanitizedHtml action', () => {
let node: HTMLElement;

beforeEach(() => {
node = document.createElement('div');
});

it('should sanitize and render HTML', () => {
renderSanitizedHtml(node, '<h1>Hello</h1><script>alert("xss")</script>');
expect(node.innerHTML).toBe('<h1>Hello</h1>');
});

it('should update the HTML', () => {
const action = renderSanitizedHtml(node, '<h1>Hello</h1>');
expect(node.innerHTML).toBe('<h1>Hello</h1>');

if (action && action.update) {
action.update('<h2>World</h2>');
}
expect(node.innerHTML).toBe('<h2>World</h2>');
});
});
14 changes: 14 additions & 0 deletions src/lib/actions/renderSanitizedHtml.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import purify from 'isomorphic-dompurify';
import type { Action } from 'svelte/action';

export const renderSanitizedHtml: Action<HTMLElement, string> = (node, html) => {
const fragment = purify.sanitize(html, { RETURN_DOM_FRAGMENT: true });
node.replaceChildren(fragment);

return {
update(newHtml: string) {
const fragment = purify.sanitize(newHtml, { RETURN_DOM_FRAGMENT: true });
node.replaceChildren(fragment);
}
};
};
10 changes: 4 additions & 6 deletions src/routes/blog/[entry]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
import { page } from '$app/stores';
import { blogEntries } from '$lib/helpers/blogProvider';
import type { BlogEntry } from '$lib/types';
import purify from 'isomorphic-dompurify';
import { parse } from 'marked';
import { reveal } from '$lib/actions/reveal';
import { renderSanitizedHtml } from '$lib/actions/renderSanitizedHtml';

let content = $state('');

Expand All @@ -17,7 +17,7 @@
async function loadContent(entry: BlogEntry | undefined) {
if (!entry) return;
const response = await fetch(`/blog_md/${entry.content_md}`);
content = purify.sanitize(await parse(await response.text()));
content = await parse(await response.text());
}
</script>

Expand Down Expand Up @@ -62,9 +62,7 @@
prose-code:bg-background-card prose-code:px-1.5
prose-code:py-0.5 prose-code:text-sm prose-code:text-text prose-ol:text-text-muted prose-ul:text-text-muted prose-li:marker:text-primary/40
[&_a]:break-all [&_p]:whitespace-pre-wrap"
>
<!-- eslint-disable-next-line svelte/no-at-html-tags -->
{@html content}
</article>
use:renderSanitizedHtml={content}
></article>
</section>
</div>
Loading