feat(sanitizer): allow safe srcset, sizes, loading, and decoding on inline img elements
This commit is contained in:
@@ -74,6 +74,13 @@ const FREE_TEXT = /^[\s\S]*$/
|
||||
// The embed placeholder written by the Blog Editor (see embeds.ts).
|
||||
const EMBED_PROVIDER = /^youtube$/
|
||||
const EMBED_ID = /^[A-Za-z0-9_-]{11}$/
|
||||
// Responsive image attributes injected by sm-journal-plugin for /media/<short-id>/... items (Phase 37, D-14).
|
||||
const IMG_LOADING = /^(lazy|eager)$/i
|
||||
const IMG_DECODING = /^(async|sync|auto)$/i
|
||||
const IMG_SIZES_SAFE = /^[a-zA-Z0-9\s(),.%:-]+$/
|
||||
const IMG_SIZES_FORBIDDEN = /\b(?:url|expression)\s*\(/i
|
||||
const SRCSET_DESCRIPTOR = /^(?:[1-9][0-9]*w|(?:[0-9]+\.?[0-9]*|\.[0-9]+)x)$/
|
||||
const IMG_ALLOWED_SCHEMES: readonly string[] = ['http', 'https']
|
||||
|
||||
// A value pattern; null marks a URL attribute (checked by allowedUrl) or
|
||||
// style (filtered per property by allowedStyles).
|
||||
@@ -125,7 +132,17 @@ const ELEMENT_ATTRS: Record<string, Record<string, ValueRule>> = {
|
||||
shape: /^(default|circle|rect|poly)$/i,
|
||||
},
|
||||
figure: { 'data-embed': EMBED_PROVIDER, 'data-id': EMBED_ID },
|
||||
img: { src: null, alt: FREE_TEXT, align: IMAGE_ALIGN, ...SIZE, usemap: /^#[\p{L}\p{N}_-]+$/iu },
|
||||
img: {
|
||||
src: null,
|
||||
srcset: null,
|
||||
sizes: null,
|
||||
alt: FREE_TEXT,
|
||||
align: IMAGE_ALIGN,
|
||||
...SIZE,
|
||||
loading: IMG_LOADING,
|
||||
decoding: IMG_DECODING,
|
||||
usemap: /^#[\p{L}\p{N}_-]+$/iu,
|
||||
},
|
||||
time: { datetime: ISO8601 },
|
||||
del: { cite: PARAGRAPH, datetime: ISO8601 },
|
||||
ins: { cite: PARAGRAPH, datetime: ISO8601 },
|
||||
@@ -186,6 +203,38 @@ function allowedUrl(url: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when `srcset` consists exclusively of valid comma-separated image
|
||||
* candidates (`<url> [<width>w | <density>x]`) whose URLs are relative
|
||||
* (e.g. `/media/...`) or use `http:`/`https:`, never `javascript:`, `data:`,
|
||||
* `vbscript:`, or `mailto:`.
|
||||
*/
|
||||
function allowedSrcset(value: string): boolean {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return false
|
||||
const parts = trimmed.split(',')
|
||||
for (const part of parts) {
|
||||
const tokens = part.trim().split(/\s+/).filter(Boolean)
|
||||
if (tokens.length < 1 || tokens.length > 2) return false
|
||||
const candidateUrl = tokens[0]!
|
||||
const scheme = URL_SCHEME.exec(candidateUrl.replace(URL_IGNORED, ''))
|
||||
if (scheme && !IMG_ALLOWED_SCHEMES.includes(scheme[1]!.toLowerCase())) return false
|
||||
try {
|
||||
new URL(candidateUrl, 'https://journal.invalid/')
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
if (tokens.length === 2 && !SRCSET_DESCRIPTOR.test(tokens[1]!)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function allowedSizes(value: string): boolean {
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed) return false
|
||||
return IMG_SIZES_SAFE.test(trimmed) && !IMG_SIZES_FORBIDDEN.test(trimmed)
|
||||
}
|
||||
|
||||
// Runs before sanitize-html's own attribute filter: drops every attribute
|
||||
// whose value fails its pattern. sanitize-html then drops attributes that
|
||||
// are not allowed on the element at all. Lookups are own-property only, so
|
||||
@@ -198,7 +247,18 @@ function filterAttributeValues(tagName: string, attribs: sanitizeHtml.Attributes
|
||||
if (own && Object.hasOwn(own, name)) rule = own[name]
|
||||
else if (Object.hasOwn(GLOBAL_ATTRS, name)) rule = GLOBAL_ATTRS[name]
|
||||
if (rule === undefined) continue
|
||||
if (rule === null ? name === 'style' || allowedUrl(value) : rule.test(value)) kept[name] = value
|
||||
if (rule === null) {
|
||||
if (name === 'style') kept[name] = value
|
||||
else if (name === 'srcset') {
|
||||
if (allowedSrcset(value)) kept[name] = value
|
||||
} else if (name === 'sizes') {
|
||||
if (allowedSizes(value)) kept[name] = value
|
||||
} else if (allowedUrl(value)) {
|
||||
kept[name] = value
|
||||
}
|
||||
} else if (rule.test(value)) {
|
||||
kept[name] = value
|
||||
}
|
||||
}
|
||||
return { tagName, attribs: kept }
|
||||
}
|
||||
@@ -230,6 +290,18 @@ const POLICY: Options = {
|
||||
transformTags: { '*': filterAttributeValues },
|
||||
}
|
||||
|
||||
// Preserve raw srcset values verbatim in KEEP_ALL so sanitize-html's built-in
|
||||
// srcset filter does not strip them before gateJournalHtml compares POLICY vs KEEP_ALL.
|
||||
const KEEP_ALL_SRCSET_ATTR = 'data-__keep-srcset__'
|
||||
function preserveRawSrcset(tagName: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag {
|
||||
if (!Object.hasOwn(attribs, 'srcset')) return { tagName, attribs }
|
||||
const next: sanitizeHtml.Attributes = {}
|
||||
for (const [k, v] of Object.entries(attribs)) {
|
||||
next[k === 'srcset' ? KEEP_ALL_SRCSET_ATTR : k] = v
|
||||
}
|
||||
return { tagName, attribs: next }
|
||||
}
|
||||
|
||||
// The same parser and serializer with nothing refused: the reference that
|
||||
// isSafeJournalHtml compares the policy's output with.
|
||||
const KEEP_ALL: Options = {
|
||||
@@ -241,6 +313,7 @@ const KEEP_ALL: Options = {
|
||||
nonTextTags: [],
|
||||
allowedEmptyAttributes: EMPTY_ATTRS,
|
||||
nonBooleanAttributes: [],
|
||||
transformTags: { '*': preserveRawSrcset },
|
||||
}
|
||||
|
||||
// H1 demotion (the Journal H1 setting, UI-SPEC L7 step 1): every h1 becomes
|
||||
@@ -248,7 +321,7 @@ const KEEP_ALL: Options = {
|
||||
// one in sanitize-html, so the policy's demotion still filters the values.
|
||||
const demoted = (filter: (tag: string, attribs: sanitizeHtml.Attributes) => sanitizeHtml.Tag) => (_tag: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag => ({ tagName: 'h2', attribs: filter('h1', attribs).attribs })
|
||||
const POLICY_DEMOTE_H1: Options = { ...POLICY, transformTags: { ...POLICY.transformTags, h1: demoted(filterAttributeValues) } }
|
||||
const KEEP_ALL_DEMOTE_H1: Options = { ...KEEP_ALL, transformTags: { h1: demoted((tagName, attribs) => ({ tagName, attribs })) } }
|
||||
const KEEP_ALL_DEMOTE_H1: Options = { ...KEEP_ALL, transformTags: { ...KEEP_ALL.transformTags, h1: demoted(preserveRawSrcset) } }
|
||||
|
||||
/** Options of the gate. */
|
||||
export interface JournalHtmlGateOptions {
|
||||
@@ -293,7 +366,8 @@ export function gateJournalHtml(html: string | null | undefined, options: Journa
|
||||
if (!html) return { safe: true, html: '' }
|
||||
const demote = options.demoteH1 === true
|
||||
const clean = sanitizeHtml(html, demote ? POLICY_DEMOTE_H1 : POLICY)
|
||||
return { safe: clean === sanitizeHtml(html, demote ? KEEP_ALL_DEMOTE_H1 : KEEP_ALL), html: clean }
|
||||
const reference = sanitizeHtml(html, demote ? KEEP_ALL_DEMOTE_H1 : KEEP_ALL).replaceAll(`${KEEP_ALL_SRCSET_ATTR}=`, 'srcset=')
|
||||
return { safe: clean === reference, html: clean }
|
||||
}
|
||||
|
||||
/** The body link steps of vue-seo-layer (app/utils/bodyLinks.ts), passed in by the component. */
|
||||
|
||||
@@ -374,6 +374,32 @@ test('a decorative image keeps alt=""', () => {
|
||||
assert.deepEqual(gateJournalHtml('<p><img src="/a.png" alt=""></p>'), { safe: true, html: '<p><img src="/a.png" alt="" /></p>' })
|
||||
})
|
||||
|
||||
test('inline /media/ responsive srcset, sizes, width, height, loading, and decoding survive sanitization', () => {
|
||||
const html =
|
||||
'<p><img src="/media/abc123456789/hero.jpg" srcset="/media/abc123456789/hero-480w.webp 480w, /media/abc123456789/hero-960w.webp 960w, https://cdn.acme.test/media/abc123456789/hero-1600w.webp 1600w" sizes="(max-width: 768px) 100vw, 800px" width="1600" height="900" loading="lazy" decoding="async" alt="Hero" /></p>'
|
||||
assert.equal(sanitizeJournalHtml(html), html)
|
||||
assert.deepEqual(gateJournalHtml(html), { safe: true, html })
|
||||
assert.equal(sanitizeJournalHtml(sanitizeJournalHtml(html)), html)
|
||||
})
|
||||
|
||||
test('unsafe srcset schemes and invalid img attributes are stripped', () => {
|
||||
const cases: Array<[string, string, string]> = [
|
||||
['javascript srcset', '<img src="/media/abc123456789/a.jpg" srcset="javascript:alert(1) 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['data srcset', '<img src="/media/abc123456789/a.jpg" srcset="data:image/svg+xml;base64,PHN2Zz4= 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['mixed safe and javascript srcset', '<img src="/media/abc123456789/a.jpg" srcset="/media/abc123456789/a-480w.webp 480w, javascript:alert(1) 960w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['vbscript srcset', '<img src="/media/abc123456789/a.jpg" srcset="vbscript:msgbox(1) 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['mailto srcset', '<img src="/media/abc123456789/a.jpg" srcset="mailto:a@b.test 480w" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['invalid descriptor', '<img src="/media/abc123456789/a.jpg" srcset="/media/abc123456789/a-480w.webp onload=1" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['unsafe sizes url()', '<img src="/media/abc123456789/a.jpg" sizes="url(https://evil.test/x)" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['invalid loading', '<img src="/media/abc123456789/a.jpg" loading="auto" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
['invalid decoding', '<img src="/media/abc123456789/a.jpg" decoding="fast" />', '<img src="/media/abc123456789/a.jpg" />'],
|
||||
]
|
||||
for (const [name, html, want] of cases) {
|
||||
assert.equal(sanitizeJournalHtml(html), want, name)
|
||||
assert.equal(isSafeJournalHtml(html), false, `${name} reported safe`)
|
||||
}
|
||||
})
|
||||
|
||||
// renderJournalBody runs the UI-SPEC L7 order on the sanitized HTML.
|
||||
function recordingSteps(calls: string[]): JournalBodyLinkSteps {
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user