feat(embeds): add extensible embed registry, universal plugin, and pair-aware sanitizer

This commit is contained in:
Jakub Zych
2026-11-28 12:49:35 +01:00
parent 4c3f9b4568
commit babd3a95b9
6 changed files with 482 additions and 75 deletions

View File

@@ -5,12 +5,13 @@
// inline styles, goldmark's footnote roles, dir="auto" and two chat
// transcript data attributes. URLs must be http, https, mailto or relative.
//
// The Blog Editor's own output adds exactly five rules, the same five the Go
// policy has: figure data-embed (youtube only) and data-id (an 11-character
// video id), which carry the embed placeholder that embeds.ts expands after
// sanitizing; img alt with any text (the editor's free-text alt field, ""
// for a decorative image); ol start (an integer); and a rel holding only the
// tokens nofollow, sponsored and ugc (the editor's link form, Phase 33).
// The Blog Editor's own output adds rules matching the Go policy: figure
// data-embed/data-id (pair-aware against the active embed registry) plus
// optional data-aspect/data-height for CLS reservation, which carry the embed
// placeholder that embeds.ts expands or hydrates after sanitizing; img alt with
// any text (the editor's free-text alt field, "" for a decorative image); ol
// start (an integer); and a rel holding only the tokens nofollow, sponsored
// and ugc (the editor's link form, Phase 33).
// tests/fixtures/editor-corpus.json, a byte copy of the editor's corpus,
// pins them. target is never kept: the outbound rules add it after
// sanitizing (renderJournalBody).
@@ -27,6 +28,7 @@
// See docs/decisions/0001-sanitize-html.md.
import sanitizeHtml from 'sanitize-html'
import { EMBED_ASPECT, EMBED_HEIGHT, getJournalEmbedRegistry, type JournalEmbedRegistry } from './embedRegistry.ts'
/** Elements of bluemonday's UGC policy, plus footer. */
export const JOURNAL_ALLOWED_TAGS: readonly string[] = [
@@ -71,9 +73,6 @@ const LINK_REL = /^(nofollow|sponsored|ugc)( (nofollow|sponsored|ugc))*$/
// '?', '"' and more. Any value is accepted, as bluemonday's p.AllowAttrs("alt")
// does; sanitize-html escapes attribute values on output and alt carries no URL.
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
@@ -131,7 +130,12 @@ const ELEMENT_ATTRS: Record<string, Record<string, ValueRule>> = {
rel: SPACE_SEPARATED_TOKENS,
shape: /^(default|circle|rect|poly)$/i,
},
figure: { 'data-embed': EMBED_PROVIDER, 'data-id': EMBED_ID },
figure: {
'data-embed': null,
'data-id': null,
'data-aspect': EMBED_ASPECT,
'data-height': EMBED_HEIGHT,
},
img: {
src: null,
srcset: null,
@@ -239,28 +243,52 @@ function allowedSizes(value: string): boolean {
// 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
// a tag or attribute named "constructor" or "toString" finds no rule.
function filterAttributeValues(tagName: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag {
const own = Object.hasOwn(ELEMENT_ATTRS, tagName) ? ELEMENT_ATTRS[tagName] : undefined
const kept: sanitizeHtml.Attributes = {}
for (const [name, value] of Object.entries(attribs)) {
let rule: ValueRule | undefined
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) {
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)) {
// On `<figure>`, `(data-embed, data-id)` are validated pair-aware against the
// active embed registry; `data-aspect` and `data-height` are kept only on a
// validated embed figure.
function makeFilterAttributeValues(registry: JournalEmbedRegistry) {
return function filterAttributeValues(tagName: string, attribs: sanitizeHtml.Attributes): sanitizeHtml.Tag {
const own = Object.hasOwn(ELEMENT_ATTRS, tagName) ? ELEMENT_ATTRS[tagName] : undefined
const kept: sanitizeHtml.Attributes = {}
const isFigure = tagName === 'figure'
let validEmbedPair = false
if (isFigure) {
const rawEmbed = Object.hasOwn(attribs, 'data-embed') ? attribs['data-embed'] : undefined
const rawId = Object.hasOwn(attribs, 'data-id') ? attribs['data-id'] : undefined
validEmbedPair = typeof rawEmbed === 'string' && typeof rawId === 'string' && registry.match(rawEmbed, rawId)
}
for (const [name, value] of Object.entries(attribs)) {
if (isFigure && (name === 'data-embed' || name === 'data-id')) {
if (validEmbedPair) kept[name] = value
continue
}
if (isFigure && name === 'data-aspect') {
if (validEmbedPair && EMBED_ASPECT.test(value)) kept[name] = value
continue
}
if (isFigure && name === 'data-height') {
if (validEmbedPair && EMBED_HEIGHT.test(value)) kept[name] = value
continue
}
let rule: ValueRule | undefined
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) {
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
}
} else if (rule.test(value)) {
kept[name] = value
}
return { tagName, attribs: kept }
}
return { tagName, attribs: kept }
}
const allowedAttributes: Record<string, string[]> = { '*': Object.keys(GLOBAL_ATTRS) }
@@ -274,7 +302,7 @@ type Options = sanitizeHtml.IOptions & { allowedEmptyAttributes: string[] }
// them as name="", so an empty value compares equal.
const EMPTY_ATTRS = ['alt', 'title', 'summary', 'abbr', 'itemscope', 'open', 'nowrap']
const POLICY: Options = {
const BASE_POLICY: Omit<Options, 'transformTags'> = {
allowedTags: [...JOURNAL_ALLOWED_TAGS],
allowedAttributes,
allowedStyles: { '*': ALLOWED_STYLES },
@@ -287,7 +315,6 @@ const POLICY: Options = {
// content is never shown as text (bluemonday skips the same content).
disallowedTagsMode: 'discard',
nonTextTags: ['script', 'style', 'textarea', 'option', 'noscript', 'title', 'iframe', 'noembed', 'noframes', 'object', 'xmp', 'template'],
transformTags: { '*': filterAttributeValues },
}
// Preserve raw srcset values verbatim in KEEP_ALL so sanitize-html's built-in
@@ -320,9 +347,16 @@ const KEEP_ALL: Options = {
// an h2 with the same attributes. A tag's own transform replaces the '*'
// 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: { ...KEEP_ALL.transformTags, h1: demoted(preserveRawSrcset) } }
function buildPolicy(demoteH1: boolean, registry: JournalEmbedRegistry): Options {
const filter = makeFilterAttributeValues(registry)
return {
...BASE_POLICY,
transformTags: demoteH1 ? { '*': filter, h1: demoted(filter) } : { '*': filter },
}
}
/** Options of the gate. */
export interface JournalHtmlGateOptions {
/**
@@ -331,6 +365,11 @@ export interface JournalHtmlGateOptions {
* H1. Default false, the HTML as written.
*/
demoteH1?: boolean
/**
* Optional embed provider registry override. Defaults to the active global
* registry (`getJournalEmbedRegistry()`).
*/
embedRegistry?: JournalEmbedRegistry
}
/**
@@ -343,7 +382,8 @@ export interface JournalHtmlGateOptions {
*/
export function sanitizeJournalHtml(html: string | null | undefined, options: JournalHtmlGateOptions = {}): string {
if (!html) return ''
return sanitizeHtml(html, options.demoteH1 ? POLICY_DEMOTE_H1 : POLICY)
const registry = options.embedRegistry ?? getJournalEmbedRegistry()
return sanitizeHtml(html, buildPolicy(options.demoteH1 === true, registry))
}
/**
@@ -351,8 +391,8 @@ export function sanitizeJournalHtml(html: string | null | undefined, options: Jo
* attribute or text and only normalizes how the markup is written. The
* counterpart of the plugin's CheckHTML. Null or empty input is safe.
*/
export function isSafeJournalHtml(html: string | null | undefined): boolean {
return gateJournalHtml(html).safe
export function isSafeJournalHtml(html: string | null | undefined, options: JournalHtmlGateOptions = {}): boolean {
return gateJournalHtml(html, options).safe
}
/**
@@ -365,7 +405,8 @@ export function isSafeJournalHtml(html: string | null | undefined): boolean {
export function gateJournalHtml(html: string | null | undefined, options: JournalHtmlGateOptions = {}): { safe: boolean; html: string } {
if (!html) return { safe: true, html: '' }
const demote = options.demoteH1 === true
const clean = sanitizeHtml(html, demote ? POLICY_DEMOTE_H1 : POLICY)
const registry = options.embedRegistry ?? getJournalEmbedRegistry()
const clean = sanitizeHtml(html, buildPolicy(demote, registry))
const reference = sanitizeHtml(html, demote ? KEEP_ALL_DEMOTE_H1 : KEEP_ALL).replaceAll(`${KEEP_ALL_SRCSET_ATTR}=`, 'srcset=')
return { safe: clean === reference, html: clean }
}
@@ -408,7 +449,7 @@ export interface JournalBodyOptions extends JournalHtmlGateOptions {
* escaped markup to sanitized output, never re-reads the raw input.
*/
export function renderJournalBody(html: string | null | undefined, options: JournalBodyOptions = {}, steps?: JournalBodyLinkSteps | null): string {
let out = sanitizeJournalHtml(html, { demoteH1: options.demoteH1 === true })
let out = sanitizeJournalHtml(html, { demoteH1: options.demoteH1 === true, embedRegistry: options.embedRegistry })
if (!out || !steps) return out
const links = Array.isArray(options.autolinks) ? options.autolinks : []
const max = Number(options.autolinkMax) || 0