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
24 changes: 24 additions & 0 deletions internal/utils/markdown_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,27 @@ func TestMarked(t *testing.T) {
assert.NoError(t, err)
assert.NotEmpty(t, html)
}

func TestMarkedRejectsDataURLs(t *testing.T) {
for _, content := range []string{
`<a href="data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==">link</a>`,
`[link](data:text/html,hello)`,
`<a href="d&#x09;ata:text/html,hello">link</a>`,
`<img src="data:text/html,hello">`,
`![image](data:image/svg+xml,%3Csvg%3E)`,
} {
t.Run(content, func(t *testing.T) {
html, err := Marked(content)
assert.NoError(t, err)
assert.NotContains(t, html, "href=")
assert.NotContains(t, html, "src=")
})
}
}

func TestMarkedPreservesWebURLs(t *testing.T) {
html, err := Marked(`[link](https://example.com) ![image](https://example.com/image.png)`)
assert.NoError(t, err)
assert.Contains(t, html, `href="https://example.com"`)
assert.Contains(t, html, `src="https://example.com/image.png"`)
}
22 changes: 22 additions & 0 deletions ui/artalk/src/lib/marked.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,26 @@ const answer = 42

expect(renderMarkdown(`${delimiter}x${delimiter}`)).toContain('<span>math</span>')
})

it.each(['native', 'data-src'] as const)(
'filters data URLs through the comment/preview renderer with %s images',
(imgLazyLoad) => {
initMarked({ markedOptions: {}, imgLazyLoad })
const html = renderMarkdown(`
[link](data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==)

<a href="data:text/html,hello">raw HTML link</a>

![unsafe](data:image/svg+xml,%3Csvg%3E)

![safe](data:image/png;base64,AA==)
`)
expect(html).not.toContain('data:text/html')
expect(html).not.toContain('data:image/svg+xml')
expect(html).toContain(
`${imgLazyLoad === 'data-src' ? 'data-src' : 'src'}="data:image/png;base64,AA=="`,
)
expect(html).toContain('raw HTML link</a>')
},
)
})
71 changes: 68 additions & 3 deletions ui/artalk/src/lib/sanitizer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,89 @@ import { describe, expect, it } from 'vitest'
import { sanitize } from './sanitizer'

describe('HTML sanitizer', () => {
it('keeps the existing tags, attributes, classes, styles, and schemes', () => {
it('keeps allowed tags, attributes, classes, styles, and schemes', () => {
const html = sanitize(`
<a href="mailto:test@example.com" target="_blank" class="drop">mail</a>
<a href="data:text/plain,hello">data</a>
<a href="https://example.com">web</a>
<code class="hljs language-ts">code</code>
<span class="hljs-keyword" style="color: #abc;">keyword</span>
<img src="data:image/png;base64,AA==" class="lazyload" loading="lazy" alt="image">
`)

expect(html).toContain('<a href="mailto:test@example.com" target="_blank">mail</a>')
expect(html).toContain('<a href="data:text/plain,hello">data</a>')
expect(html).toContain('<a href="https://example.com">web</a>')
expect(html).toContain('<code class="hljs language-ts">code</code>')
expect(html).toContain('<span class="hljs-keyword" style="color: #abc;">keyword</span>')
expect(html).toContain(
'<img src="data:image/png;base64,AA==" class="lazyload" loading="lazy" alt="image">',
)
})

it.each([
'data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==',
'data:text/plain,hello',
'data:image/png;base64,AA==',
'data:,hello',
'DATA:text/html,hello',
'data&#58;text/html,hello',
'd&#x09;ata:text/html,hello',
' &#x0a;data:text/html,hello',
])('removes data URLs from links: %s', (url) => {
expect(sanitize(`<a href="${url}" target="_blank">link</a>`)).toBe(
'<a target="_blank">link</a>',
)
})

describe.each(['src', 'data-src'])('image %s', (attribute) => {
it.each(['png', 'jpeg', 'gif', 'webp', 'avif', 'bmp'])(
'preserves inline %s images',
(format) => {
const url = `data:image/${format};base64,AA==`
expect(sanitize(`<img ${attribute}="${url}" alt="image">`)).toBe(
`<img ${attribute}="${url}" alt="image">`,
)
},
)

it.each(['data:image/png,%89PNG', 'data:IMAGE/PNG;BASE64,AA=='])(
'preserves percent-encoded or mixed-case image URLs: %s',
(url) => {
expect(sanitize(`<img ${attribute}="${url}">`)).toBe(`<img ${attribute}="${url}">`)
},
)

it.each([
'data:text/html,hello',
'data:text/javascript,alert(1)',
'data:application/javascript,alert(1)',
'data:image/svg+xml,%3Csvg%20onload=alert(1)%3E',
'data:,hello',
'data:image/png+xml,hello',
'data:image/png;unknown,hello',
'data:image/png;base64',
'DATA:text/html,hello',
'd&#x09;ata:text/html,hello',
'javascript:alert(1)',
'java&#x0a;script:alert(1)',
'vbscript:msgbox(1)',
'blob:https://example.com/id',
])('removes non-raster or malformed data URLs: %s', (url) => {
expect(sanitize(`<img ${attribute}="${url}" alt="image">`)).toBe('<img alt="image">')
})
})

it.each([
'http://example.com',
'https://example.com',
'mailto:test@example.com',
'/path',
'//example.com/path',
'#reply',
'?page=2',
])('preserves ordinary links: %s', (url) => {
expect(sanitize(`<a href="${url}">link</a>`)).toBe(`<a href="${url}">link</a>`)
})

it('removes executable markup and attributes outside the per-tag allowlist', () => {
const html = sanitize(`
<script>alert(1)</script>
Expand Down
23 changes: 18 additions & 5 deletions ui/artalk/src/lib/sanitizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,9 @@ const allowedAttributes = [
...new Set([...globalAttributes, ...Object.values(tagAttributes).flatMap((v) => [...v])]),
]
const urlAttributes = new Set(['href', 'src', 'data-src'])
const allowedSchemes = new Set(['http', 'https', 'mailto', 'data'])
const allowedSchemes = new Set(['http', 'https', 'mailto'])

function hasAllowedScheme(value: string): boolean {
function hasAllowedURL(value: string, tag: string, attribute: string): boolean {
// Browsers ignore ASCII control characters inside a URL scheme. Remove them
// before checking so values such as "java\nscript:" cannot bypass the filter.
const normalized = [...value]
Expand All @@ -79,6 +79,15 @@ function hasAllowedScheme(value: string): boolean {
})
.join('')
const scheme = /^([a-z][a-z\d+.-]*):/i.exec(normalized)?.[1].toLowerCase()
if (scheme === 'data') {
// Inline data is only for raster images, including lazy-loaded images.
// Never allow navigable data documents or SVG/HTML payloads.
return (
tag === 'img' &&
(attribute === 'src' || attribute === 'data-src') &&
/^data:image\/(?:png|jpeg|gif|webp|avif|bmp)(?:;base64)?,/i.test(normalized)
)
}
return !scheme || allowedSchemes.has(scheme)
}

Expand All @@ -93,7 +102,10 @@ function filterAttributes(root: HTMLTemplateElement): void {
continue
}

if (urlAttributes.has(attribute.name) && !hasAllowedScheme(attribute.value)) {
if (
urlAttributes.has(attribute.name) &&
!hasAllowedURL(attribute.value, tag, attribute.name)
) {
element.removeAttribute(attribute.name)
}
}
Expand All @@ -114,14 +126,15 @@ function filterAttributes(root: HTMLTemplateElement): void {

export function sanitize(content: string): string {
// Keep Artalk's existing HTML allowlist while using a maintained, non-regex
// parser. The second pass enforces the original per-tag attribute rules.
// parser. The second pass enforces per-tag attributes and URL restrictions.
const sanitized = DOMPurify.sanitize(content, {
ALLOWED_TAGS: allowedTags,
ALLOWED_ATTR: allowedAttributes,
ALLOW_ARIA_ATTR: false,
ALLOW_DATA_ATTR: false,
ALLOW_UNKNOWN_PROTOCOLS: true,
ADD_DATA_URI_TAGS: ['a'],
// Validate lazy image URLs in the same second pass as img[src].
ADD_URI_SAFE_ATTR: ['data-src'],
})
const template = document.createElement('template')
template.innerHTML = sanitized
Expand Down
Loading