Skip to content

Commit

Permalink
Avoid double DOM parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
ai committed Jan 23, 2024
1 parent 5f73b8a commit 4fb44d0
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 15 deletions.
4 changes: 2 additions & 2 deletions core/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ const ALLOWED_TAGS = [

let DOMPurify: ReturnType<typeof createDOMPurify> | undefined

export function sanitizeHTML(html: string): string {
export function sanitizeDOM(html: string): HTMLElement {
if (!DOMPurify) DOMPurify = createDOMPurify(window)
return DOMPurify.sanitize(html, { ALLOWED_TAGS })
return DOMPurify.sanitize(html, { ALLOWED_TAGS, RETURN_DOM: true })
}

export function parseRichTranslation(text: string): string {
Expand Down
6 changes: 3 additions & 3 deletions core/test/html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ import './dom-parser.js'
import { equal } from 'node:assert'
import { test } from 'node:test'

import { parseLink, parseRichTranslation, sanitizeHTML } from '../index.js'
import { parseLink, parseRichTranslation, sanitizeDOM } from '../index.js'

test('sanitizes HTML', () => {
equal(
sanitizeHTML(
sanitizeDOM(
'<script>alert("XSS")</script>' +
'<b>Safe</b>' +
'<form></form>' +
'<iframe//src=jAva&Tab;script:alert(3)>'
),
).innerHTML,
'<b>Safe</b>'
)
})
Expand Down
23 changes: 23 additions & 0 deletions web/ui/formatted-text.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<script lang="ts">
/* We escape and have XSS tests */
/* eslint svelte/no-at-html-tags: "off" */
import { sanitizeDOM } from '@slowreader/core'
export let html: string
let node: HTMLDivElement | undefined
$: if (node) {
node.innerHTML = ''
node.replaceChildren(...sanitizeDOM(html).childNodes)
}
</script>

<div bind:this={node} class="formatted-text"></div>

<style>
.formatted-text :global(img) {
max-width: 100%;
}
</style>
13 changes: 3 additions & 10 deletions web/ui/post-card.svelte
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
<script lang="ts">
/* We escape and have XSS tests */
/* eslint svelte/no-at-html-tags: "off" */
import {
type FeedValue,
type FilterAction,
type OriginPost,
sanitizeHTML
} from '@slowreader/core'
import type { FeedValue, FilterAction, OriginPost } from '@slowreader/core'
import Card from './card.svelte'
import FormattedText from './formatted-text.svelte'
export let post: OriginPost
export let author: FeedValue | undefined = undefined
Expand All @@ -34,7 +27,7 @@
{/if}
</h1>
{/if}
{@html sanitizeHTML(post.intro ?? post.full ?? '')}
<FormattedText html={post.intro ?? post.full ?? ''} />
</div>
</Card>

Expand Down

0 comments on commit 4fb44d0

Please sign in to comment.