diff --git a/app/plugins/journal-embeds.ts b/app/plugins/journal-embeds.ts new file mode 100644 index 0000000..f9e3f64 --- /dev/null +++ b/app/plugins/journal-embeds.ts @@ -0,0 +1,16 @@ +// Universal Nuxt plugin syncing `app.config.ts` (`journal.embeds`) into the +// active Journal embed registry on both SSR and client before page components +// render, so `htmlGate.ts`, `embeds.ts`, and `useJournalEmbedHydration.ts` +// agree on the exact same provider set. +import { defineJournalEmbedProviders, type JournalEmbedProvider } from '../utils/embedRegistry.ts' + +export default defineNuxtPlugin({ + name: 'journal-embeds', + enforce: 'pre', + setup() { + const appConfig = useAppConfig() as { journal?: { embeds?: Record } } + if (appConfig?.journal?.embeds) { + defineJournalEmbedProviders(appConfig.journal.embeds) + } + }, +}) diff --git a/app/utils/embedRegistry.ts b/app/utils/embedRegistry.ts new file mode 100644 index 0000000..1213f37 --- /dev/null +++ b/app/utils/embedRegistry.ts @@ -0,0 +1,244 @@ +// Extensible embed provider registry for vue-journal-layer. +// +// Pure TypeScript with zero Nuxt imports so unit tests run directly under +// `node --test`. Consuming Nuxt apps register custom providers via +// `app.config.ts` (`journal.embeds`, synced by `app/plugins/journal-embeds.ts`) +// and/or a Nuxt plugin calling `registerJournalEmbedProvider` / +// `defineJournalEmbedProviders`. +// +// Both `htmlGate.ts` (pair-aware sanitization) and `embeds.ts` / +// `useJournalEmbedHydration.ts` (SSR expansion + client lazy hydration) read +// from the same registry. Lookups use `Map` exclusively so prototype keys +// (`__proto__`, `constructor`, `toString`) are never matched. + +/** Allowed embed provider key format (mirrors sm-journal-plugin). */ +export const EMBED_PROVIDER_KEY = /^[a-z][a-z0-9_-]{0,31}$/ + +/** Allowed `data-aspect` token (e.g. `16/9`, `4 / 3`, `1.5`), zero CSS injection vectors. */ +export const EMBED_ASPECT = /^[1-9][0-9]{0,3}(?:\s*\/\s*[1-9][0-9]{0,3}|\.[0-9]{1,4})?$/ + +/** Allowed `data-height` token (e.g. `420`, `420px`), zero CSS injection vectors. */ +export const EMBED_HEIGHT = /^[1-9][0-9]{0,3}(?:px)?$/ + +/** Context passed to a provider's optional SSR renderer. */ +export interface JournalEmbedSsrContext { + provider: string + innerHtml: string + aspect?: string + height?: string +} + +/** Context passed to a provider's client-side `mount` callback. */ +export interface JournalEmbedMountContext { + id: string + provider: string + figure: HTMLElement + aspect?: string + height?: string + fallbackHtml: string + reducedMotion: Readonly<{ value: boolean }> + isReducedMotion: boolean +} + +/** Provider registration shape accepted by `app.config.ts` and plugin helpers. */ +export interface JournalEmbedProvider { + /** Pattern a `data-id` value must match (anchored automatically). */ + idPattern: RegExp | string + /** + * Optional SSR expansion hook. Returning a string replaces the `
` + * element during `expandEmbeds`; returning `undefined` or `null` leaves it + * for client hydration or untouched. + */ + renderSsr?: (id: string, ctx: JournalEmbedSsrContext) => string | undefined | null + /** Optional Vue async component loader for client-side lazy hydration. */ + component?: () => Promise + /** Optional plain DOM mount callback for client-side lazy hydration. */ + mount?: (el: HTMLElement, ctx: JournalEmbedMountContext) => void | (() => void) | Promise void)> + /** Default CLS aspect-ratio token (validated against `EMBED_ASPECT`). */ + aspectRatio?: string + /** Default CLS min-height token (validated against `EMBED_HEIGHT`). */ + minHeight?: string + /** `IntersectionObserver` rootMargin override (default `'200px'`). */ + rootMargin?: string +} + +/** Normalized provider stored inside `JournalEmbedRegistry`. */ +export interface NormalizedJournalEmbedProvider { + readonly key: string + readonly idPattern: RegExp + readonly renderSsr?: JournalEmbedProvider['renderSsr'] + readonly component?: JournalEmbedProvider['component'] + readonly mount?: JournalEmbedProvider['mount'] + readonly aspectRatio?: string + readonly minHeight?: string + readonly rootMargin?: string + /** Internal flag distinguishing the built-in default YouTube provider. */ + readonly _builtinYoutube?: boolean +} + +function normalizeCssHeight(value: string): string { + return value.endsWith('px') ? value : `${value}px` +} + +function buildClsStyle(aspect?: string, height?: string): string { + const parts: string[] = [] + if (aspect && EMBED_ASPECT.test(aspect)) parts.push(`aspect-ratio:${aspect.replace(/\s+/g, '')}`) + if (height && EMBED_HEIGHT.test(height)) parts.push(`min-height:${normalizeCssHeight(height)}`) + return parts.join(';') +} + +/** Built-in privacy-enhanced YouTube provider (100% SSR byte-compatible default). */ +export const YOUTUBE_EMBED_PROVIDER: JournalEmbedProvider = Object.freeze({ + idPattern: /^[A-Za-z0-9_-]{11}$/, + renderSsr(id: string, ctx: JournalEmbedSsrContext): string | undefined { + if (ctx.innerHtml !== '') return undefined + const style = buildClsStyle(ctx.aspect, ctx.height) + const styleAttr = style ? ` style="${style}"` : '' + return ( + `
` + + `' + + '
' + ) + }, +}) + +function normalizeIdPattern(name: string, pattern: RegExp | string): RegExp { + let raw: RegExp + if (pattern instanceof RegExp) { + raw = pattern + } else if (typeof pattern === 'string' && pattern.length > 0) { + try { + raw = new RegExp(pattern) + } catch (err) { + throw new Error(`Invalid idPattern for journal embed provider "${name}": ${String(err)}`) + } + } else { + throw new Error(`Journal embed provider "${name}" must provide a RegExp or non-empty string idPattern`) + } + const flags = raw.flags.replace(/[gy]/g, '') + return new RegExp(`^(?:${raw.source})$`, flags) +} + +function normalizeProvider(name: string, provider: JournalEmbedProvider): NormalizedJournalEmbedProvider { + if (!EMBED_PROVIDER_KEY.test(name)) { + throw new Error(`Invalid journal embed provider key "${name}": must match ${EMBED_PROVIDER_KEY.source}`) + } + if (!provider || typeof provider !== 'object') { + throw new Error(`Journal embed provider "${name}" must be an object`) + } + const idPattern = normalizeIdPattern(name, provider.idPattern) + let aspectRatio: string | undefined + if (provider.aspectRatio !== undefined) { + const trimmed = provider.aspectRatio.trim() + if (!EMBED_ASPECT.test(trimmed)) { + throw new Error(`Invalid aspectRatio "${provider.aspectRatio}" for journal embed provider "${name}"`) + } + aspectRatio = trimmed + } + let minHeight: string | undefined + if (provider.minHeight !== undefined) { + const trimmed = provider.minHeight.trim() + if (!EMBED_HEIGHT.test(trimmed)) { + throw new Error(`Invalid minHeight "${provider.minHeight}" for journal embed provider "${name}"`) + } + minHeight = trimmed + } + return Object.freeze({ + key: name, + idPattern, + renderSsr: provider.renderSsr, + component: provider.component, + mount: provider.mount, + aspectRatio, + minHeight, + rootMargin: typeof provider.rootMargin === 'string' && provider.rootMargin.trim() ? provider.rootMargin.trim() : undefined, + _builtinYoutube: provider === YOUTUBE_EMBED_PROVIDER, + }) +} + +/** Prototype-safe registry of allowed Journal embed providers. */ +export class JournalEmbedRegistry { + private readonly providers = new Map() + + register(name: string, provider: JournalEmbedProvider): this { + this.providers.set(name, normalizeProvider(name, provider)) + return this + } + + define(map: Record | null | undefined): this { + if (!map || typeof map !== 'object') return this + for (const key of Object.keys(map)) { + const provider = map[key] + if (provider !== undefined) this.register(key, provider) + } + return this + } + + get(name: string): NormalizedJournalEmbedProvider | undefined { + if (!EMBED_PROVIDER_KEY.test(name)) return undefined + return this.providers.get(name) + } + + has(name: string): boolean { + if (!EMBED_PROVIDER_KEY.test(name)) return false + return this.providers.has(name) + } + + match(name: string, id: string): boolean { + const provider = this.get(name) + if (!provider || typeof id !== 'string') return false + return provider.idPattern.test(id) + } + + keys(): string[] { + return [...this.providers.keys()] + } + + entries(): Array<[string, NormalizedJournalEmbedProvider]> { + return [...this.providers.entries()] + } + + clone(): JournalEmbedRegistry { + const copy = new JournalEmbedRegistry() + for (const [k, v] of this.providers.entries()) copy.providers.set(k, v) + return copy + } +} + +/** Creates a new embed registry, pre-populated with built-in `youtube` by default. */ +export function createJournalEmbedRegistry( + initial?: Record | null, + includeDefaults = true, +): JournalEmbedRegistry { + const registry = new JournalEmbedRegistry() + if (includeDefaults) registry.register('youtube', YOUTUBE_EMBED_PROVIDER) + if (initial) registry.define(initial) + return registry +} + +let activeRegistry = createJournalEmbedRegistry() + +/** Returns the active module-level Journal embed registry. */ +export function getJournalEmbedRegistry(): JournalEmbedRegistry { + return activeRegistry +} + +/** Registers or overrides a single embed provider on the active registry. */ +export function registerJournalEmbedProvider(name: string, provider: JournalEmbedProvider): JournalEmbedRegistry { + return activeRegistry.register(name, provider) +} + +/** Registers or overrides a map of embed providers on the active registry. */ +export function defineJournalEmbedProviders( + map: Record | null | undefined, +): JournalEmbedRegistry { + return activeRegistry.define(map) +} + +/** Resets the active registry back to the default built-in `youtube` provider (for tests). */ +export function resetJournalEmbedRegistry(): JournalEmbedRegistry { + activeRegistry = createJournalEmbedRegistry() + return activeRegistry +} diff --git a/app/utils/embeds.ts b/app/utils/embeds.ts index ffe12b3..3ded5d7 100644 --- a/app/utils/embeds.ts +++ b/app/utils/embeds.ts @@ -1,20 +1,27 @@ // Embed expansion for Journal HTML. The Blog Editor (Journal plugin, -// assets/src/blogeditor/embed.ts) never stores an iframe: it writes the -// placeholder
, and the -// plugin's bluemonday policy (classes/format_html.go) keeps exactly that, with -// data-embed matching ^youtube$ and data-id matching ^[A-Za-z0-9_-]{11}$. -// htmlGate.ts mirrors those two rules, so the placeholder survives the layer's -// sanitizer too. +// assets/src/blogeditor/embed.ts) never stores an iframe: it writes a +// `
` placeholder (optionally +// with `data-aspect`, `data-height`, and sanitized static fallback children +// such as `` and `
`). Both `sm-journal-plugin` and +// `htmlGate.ts` validate `(data-embed, data-id)` pair-aware against the +// registered embed providers. // // expandEmbeds is the very last step before v-html, after sanitizeJournalHtml: // its input is always sanitizer output, and its output is never sanitized -// again (the sanitizer strips every iframe, including the one built here). The -// regex matches the serialization sanitize-html gives the placeholder: -// attribute order kept, double quotes, empty figure. Only a known provider -// with a valid id becomes an iframe, whose src is a fixed host plus that id; -// anything else is returned unchanged and stays an inert empty figure. +// again (the sanitizer strips every iframe, including the one built here). +// Built-in `youtube` expands empty placeholders to a privacy-enhanced iframe +// on youtube-nocookie.com; client-hydrated providers (`component` or `mount`) +// keep their SSR fallback DOM intact with `journal-embed` classes and optional +// CLS layout reservation (`aspect-ratio` / `min-height`). -/** One allowlisted embed provider. */ +import { + EMBED_ASPECT, + EMBED_HEIGHT, + getJournalEmbedRegistry, + type JournalEmbedRegistry, +} from './embedRegistry.ts' + +/** One allowlisted embed provider (legacy shape kept for backward compatibility). */ export type EmbedProvider = { /** The id a placeholder must match to expand. */ id: RegExp @@ -40,24 +47,123 @@ export const EMBED_PROVIDERS: Readonly> = Object.f */ export const EMBED_PLACEHOLDER = /
]*)" data-id="([^"<>]*)"><\/figure>/g +// Matches a sanitize-html serialized `
...
` (lowercase tag, +// single-space-separated double-quoted attributes, no nested `
`). +const EMBED_FIGURE_RE = /]*")+)>((?:(?!<\/?figure\b)[\s\S])*?)<\/figure>/g +const ATTR_PAIR_RE = / ([a-z][a-z0-9-]*)="([^"<>]*)"/g + +function normalizeCssHeight(value: string): string { + return value.endsWith('px') ? value : `${value}px` +} + +function mergeClasses(existing: string | undefined, required: readonly string[]): string { + const tokens = existing ? existing.split(/\s+/).filter(Boolean) : [] + for (const cls of required) { + if (!tokens.includes(cls)) tokens.push(cls) + } + return tokens.join(' ') +} + +function mergeClsStyle(existing: string | undefined, aspect?: string, height?: string): string | undefined { + const decls = existing + ? existing + .split(';') + .map((s) => s.trim()) + .filter(Boolean) + : [] + const hasProp = (prop: string) => decls.some((d) => d.toLowerCase().startsWith(`${prop}:`)) + if (aspect && EMBED_ASPECT.test(aspect) && !hasProp('aspect-ratio')) { + decls.push(`aspect-ratio:${aspect.replace(/\s+/g, '')}`) + } + if (height && EMBED_HEIGHT.test(height) && !hasProp('min-height')) { + decls.push(`min-height:${normalizeCssHeight(height)}`) + } + return decls.length > 0 ? decls.join(';') : undefined +} + /** - * Replaces every placeholder whose provider is in EMBED_PROVIDERS and whose - * id passes the provider's pattern with a figure holding the provider's - * iframe. Every other match is returned unchanged. Empty input gives "". - * Call it on sanitizeJournalHtml output only, and never sanitize its result. + * Expands validated embed placeholders using the active (or supplied) + * `JournalEmbedRegistry`: + * - Providers with `renderSsr` (e.g. built-in `youtube` on an empty figure) + * emit their SSR HTML directly. + * - Client-hydrated providers (`component` or `mount`) preserve the `
` + * and its static SSR fallback children while adding `journal-embed` / + * `journal-embed--` classes and safe CLS `aspect-ratio` / + * `min-height` reservation styles. + * - Unknown providers or mismatched IDs remain untouched and inert. + * + * Call on `sanitizeJournalHtml` output only, and never sanitize its result. */ -export function expandEmbeds(html: string | null | undefined): string { +export function expandEmbeds( + html: string | null | undefined, + registry: JournalEmbedRegistry = getJournalEmbedRegistry(), +): string { if (!html) return '' - return html.replace(EMBED_PLACEHOLDER, (match: string, provider: string, id: string) => { - if (!Object.hasOwn(EMBED_PROVIDERS, provider)) return match - const p = EMBED_PROVIDERS[provider]! - if (!p.id.test(id)) return match - return ( - `
` + - `' + - '
' - ) + return html.replace(EMBED_FIGURE_RE, (match: string, attrText: string, innerHtml: string) => { + const attrs: Array<[string, string]> = [] + const byName = new Map() + for (const m of attrText.matchAll(ATTR_PAIR_RE)) { + const name = m[1]! + const value = m[2]! + attrs.push([name, value]) + if (!byName.has(name)) byName.set(name, value) + } + + const providerName = byName.get('data-embed') + const id = byName.get('data-id') + if (!providerName || !id) return match + + const provider = registry.get(providerName) + if (!provider || !provider.idPattern.test(id)) return match + + const rawAspect = byName.get('data-aspect') + const rawHeight = byName.get('data-height') + const aspect = rawAspect && EMBED_ASPECT.test(rawAspect) ? rawAspect : undefined + const height = rawHeight && EMBED_HEIGHT.test(rawHeight) ? rawHeight : undefined + + if (provider.renderSsr) { + if (provider._builtinYoutube) { + // Built-in YouTube keeps strict placeholder shape: data-embed before + // data-id, no extra attributes beyond data-aspect/data-height, empty body. + const allowedKeys = new Set(['data-embed', 'data-id', 'data-aspect', 'data-height']) + const embedIdx = attrs.findIndex(([k]) => k === 'data-embed') + const idIdx = attrs.findIndex(([k]) => k === 'data-id') + const allAllowed = attrs.every(([k]) => allowedKeys.has(k)) + if (innerHtml !== '' || !allAllowed || embedIdx < 0 || idIdx < 0 || embedIdx > idIdx) { + return match + } + } + const rendered = provider.renderSsr(id, { provider: providerName, innerHtml, aspect, height }) + if (typeof rendered === 'string') return rendered + } + + if (provider.component || provider.mount) { + const nextClass = mergeClasses(byName.get('class'), ['journal-embed', `journal-embed--${providerName}`]) + const nextStyle = mergeClsStyle(byName.get('style'), aspect ?? provider.aspectRatio, height ?? provider.minHeight) + const outAttrs: Array<[string, string]> = [] + let wroteClass = false + let wroteStyle = false + for (const [k, v] of attrs) { + if (k === 'class') { + if (!wroteClass) { + outAttrs.push(['class', nextClass]) + wroteClass = true + } + } else if (k === 'style') { + if (!wroteStyle && nextStyle) { + outAttrs.push(['style', nextStyle]) + wroteStyle = true + } + } else { + outAttrs.push([k, v]) + } + } + if (!wroteClass) outAttrs.unshift(['class', nextClass]) + if (!wroteStyle && nextStyle) outAttrs.push(['style', nextStyle]) + const serialized = outAttrs.map(([k, v]) => ` ${k}="${v}"`).join('') + return `${innerHtml}
` + } + + return match }) } diff --git a/app/utils/htmlGate.ts b/app/utils/htmlGate.ts index 4e5e872..998e14f 100644 --- a/app/utils/htmlGate.ts +++ b/app/utils/htmlGate.ts @@ -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//... 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> = { 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 `
`, `(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 = { '*': 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 = { 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 diff --git a/tests/embeds.test.ts b/tests/embeds.test.ts index 3604833..2565968 100644 --- a/tests/embeds.test.ts +++ b/tests/embeds.test.ts @@ -82,8 +82,8 @@ test('a placeholder smuggling an iframe or extra attributes expands only its val }) test('a malformed placeholder stays an empty figure after the sink', () => { - assert.equal(sink(`
`), '
') - assert.equal(sink(`
`), `
`) + assert.equal(sink(`
`), '
') + assert.equal(sink(`
`), '
') assert.equal(iframeCount(sink(`
`)), 0) }) diff --git a/tests/htmlGate.test.ts b/tests/htmlGate.test.ts index 8141205..3c9d188 100644 --- a/tests/htmlGate.test.ts +++ b/tests/htmlGate.test.ts @@ -247,10 +247,10 @@ test('the embed placeholder survives two sanitizer passes (payload, then sink)', test('embed attributes outside the four editor rules are still stripped', () => { const cases: Array<[string, string, string]> = [ - ['other provider', '
', '
'], - ['10-character id', '
', '
'], - ['12-character id', '
', '
'], - ['id with a quote', '
', '
'], + ['other provider', '
', '
'], + ['10-character id', '
', '
'], + ['12-character id', '
', '
'], + ['id with a quote', '
', '
'], ['data-id on div', '
x
', '
x
'], ['data-id on img', '', ''], ['other data attribute on figure', '
', PLACEHOLDER], @@ -308,11 +308,11 @@ test('the four editor rules accept exactly the editor values (D-05 amended mirro test('the Go policy negatives are stripped the same way here', () => { const cases: Array<[string, string, string]> = [ - ['upper-case provider', '
', '
'], - ['provider with a suffix', '
', '
'], - ['empty id', '
', '
'], - ['id with a URL', '
', '
'], - ['id with a space', '
', '
'], + ['upper-case provider', '
', '
'], + ['provider with a suffix', '
', '
'], + ['empty id', '
', '
'], + ['id with a URL', '
', '
'], + ['id with a space', '
', '
'], ['embed attributes on p', '

x

', '

x

'], ['embed attributes on a', 'x', 'x'], ['data attribute alone on figure', '
', '
'],