test(embeds): add registry, pair-aware sanitizer, hydration tests, and README docs

This commit is contained in:
Jakub Zych
2026-11-28 13:01:27 +01:00
parent 76132722b0
commit 47de196516
4 changed files with 712 additions and 11 deletions

View File

@@ -0,0 +1,522 @@
// Client-side lazy embed hydration tests (Phase 38, D-08).
// Runs directly under `node --test` using lightweight DOM, IntersectionObserver,
// and matchMedia doubles (zero browser/DOM test-runner dependency).
import { afterEach, test } from 'node:test'
import assert from 'node:assert/strict'
import type { AppContext } from 'vue'
import { createJournalEmbedRegistry, resetJournalEmbedRegistry } from '../app/utils/embedRegistry.ts'
// ---------------------------------------------------------------------------
// Minimal DOM double sufficient for Vue 3 `render(vnode, host)` and
// `useJournalEmbedHydration` / `hydrateEmbedFigure`.
// ---------------------------------------------------------------------------
class FakeNode {
nodeType: number
parentNode: FakeElement | null = null
childNodes: FakeNode[] = []
ownerDocument: FakeDocument
constructor(nodeType: number, ownerDocument: FakeDocument) {
this.nodeType = nodeType
this.ownerDocument = ownerDocument
}
get firstChild(): FakeNode | null {
return this.childNodes[0] ?? null
}
get nextSibling(): FakeNode | null {
if (!this.parentNode) return null
const idx = this.parentNode.childNodes.indexOf(this)
return idx >= 0 ? (this.parentNode.childNodes[idx + 1] ?? null) : null
}
}
class FakeText extends FakeNode {
nodeValue: string
constructor(text: string, ownerDocument: FakeDocument) {
super(3, ownerDocument)
this.nodeValue = String(text)
}
get textContent(): string {
return this.nodeValue
}
set textContent(v: string) {
this.nodeValue = String(v ?? '')
}
}
class FakeComment extends FakeNode {
nodeValue: string
constructor(text: string, ownerDocument: FakeDocument) {
super(8, ownerDocument)
this.nodeValue = String(text)
}
}
class FakeClassList {
private readonly set = new Set<string>()
add(...tokens: string[]): void {
for (const t of tokens) if (t) this.set.add(t)
}
remove(...tokens: string[]): void {
for (const t of tokens) this.set.delete(t)
}
contains(token: string): boolean {
return this.set.has(token)
}
toString(): string {
return [...this.set].join(' ')
}
}
class FakeElement extends FakeNode {
readonly tagName: string
readonly attrs = new Map<string, string>()
readonly classList = new FakeClassList()
readonly style: Record<string, string> = {}
measuredHeight = 0
private _rawInnerHtml = ''
constructor(tagName: string, ownerDocument: FakeDocument) {
super(1, ownerDocument)
this.tagName = tagName.toUpperCase()
}
get className(): string {
return this.classList.toString()
}
set className(val: string) {
for (const t of val.split(/\s+/).filter(Boolean)) this.classList.add(t)
}
get innerHTML(): string {
if (this.childNodes.length === 0) return this._rawInnerHtml
return this.childNodes
.map((c) => {
if (c instanceof FakeText) return c.nodeValue
if (c instanceof FakeComment) return `<!--${c.nodeValue}-->`
if (c instanceof FakeElement) {
const tag = c.tagName.toLowerCase()
const attrStr = [...c.attrs.entries()].map(([k, v]) => ` ${k}="${v}"`).join('')
const cls = c.className ? ` class="${c.className}"` : ''
return `<${tag}${cls}${attrStr}>${c.innerHTML}</${tag}>`
}
return ''
})
.join('')
}
set innerHTML(val: string) {
this.childNodes = []
this._rawInnerHtml = val
}
get textContent(): string {
if (this.childNodes.length === 0) return this._rawInnerHtml
return this.childNodes.map((c) => (c instanceof FakeText || c instanceof FakeElement ? c.textContent : '')).join('')
}
set textContent(val: string) {
this.childNodes = []
this._rawInnerHtml = ''
if (val !== '') this.appendChild(new FakeText(String(val), this.ownerDocument))
}
getAttribute(name: string): string | null {
return this.attrs.get(name) ?? null
}
setAttribute(name: string, value: string): void {
if (name === 'class') this.className = value
else this.attrs.set(name, String(value))
}
removeAttribute(name: string): void {
this.attrs.delete(name)
}
getBoundingClientRect(): { height: number; width: number } {
return { height: this.measuredHeight, width: 800 }
}
appendChild(child: FakeNode): FakeNode {
if (child.parentNode) child.parentNode.removeChild(child)
child.parentNode = this
this.childNodes.push(child)
return child
}
insertBefore(child: FakeNode, anchor: FakeNode | null): FakeNode {
if (child.parentNode) child.parentNode.removeChild(child)
child.parentNode = this
if (!anchor) {
this.childNodes.push(child)
return child
}
const idx = this.childNodes.indexOf(anchor)
if (idx < 0) this.childNodes.push(child)
else this.childNodes.splice(idx, 0, child)
return child
}
removeChild(child: FakeNode): FakeNode {
const idx = this.childNodes.indexOf(child)
if (idx >= 0) {
this.childNodes.splice(idx, 1)
child.parentNode = null
}
return child
}
replaceChildren(...nodes: FakeNode[]): void {
for (const c of this.childNodes) c.parentNode = null
this.childNodes = []
this._rawInnerHtml = ''
for (const n of nodes) this.appendChild(n)
}
querySelectorAll(selector: string): FakeElement[] {
if (selector !== 'figure[data-embed][data-id]') return []
const out: FakeElement[] = []
const walk = (el: FakeElement) => {
for (const c of el.childNodes) {
if (c instanceof FakeElement) {
if (c.tagName === 'FIGURE' && c.attrs.has('data-embed') && c.attrs.has('data-id')) out.push(c)
walk(c)
}
}
}
walk(this)
return out
}
}
class FakeDocument {
createElement(tag: string): FakeElement {
return new FakeElement(tag, this)
}
createElementNS(_ns: string, tag: string): FakeElement {
return new FakeElement(tag, this)
}
createTextNode(text: string): FakeText {
return new FakeText(text, this)
}
createComment(text: string): FakeComment {
return new FakeComment(text, this)
}
}
function makeFigure(
doc: FakeDocument,
attrs: Record<string, string>,
fallbackHtml: string,
measuredHeight = 360,
): FakeElement {
const fig = doc.createElement('figure')
for (const [k, v] of Object.entries(attrs)) fig.setAttribute(k, v)
fig.innerHTML = fallbackHtml
fig.measuredHeight = measuredHeight
return fig
}
const origWindow = globalThis.window
const origIO = globalThis.IntersectionObserver
// Install FakeDocument BEFORE importing `vue` so `@vue/runtime-dom` binds its
// module-level `doc` reference to our lightweight DOM double.
const sharedDoc = new FakeDocument()
;(globalThis as Record<string, unknown>).document = sharedDoc
const { createApp, createVNode, defineComponent, h, inject, onUnmounted, ref, render } = await import('vue')
const { hydrateEmbedFigure, useJournalEmbedHydration } = await import('../app/composables/useJournalEmbedHydration.ts')
afterEach(() => {
resetJournalEmbedRegistry()
if (origWindow === undefined) delete (globalThis as Record<string, unknown>).window
else (globalThis as Record<string, unknown>).window = origWindow
if (origIO === undefined) delete (globalThis as Record<string, unknown>).IntersectionObserver
else (globalThis as Record<string, unknown>).IntersectionObserver = origIO
})
test('hydrateEmbedFigure mounts a plain DOM provider, reserves CLS minHeight, passes reducedMotion, and runs cleanup', async () => {
const doc = new FakeDocument()
const fallback = '<img src="/media/abc/chart.webp" alt="Chart"><figcaption>Fig 1</figcaption>'
const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'chart-1', 'data-aspect': '16/9' }, fallback, 342.4)
let cleanedUp = false
let receivedCtx: Record<string, unknown> | null = null
const registry = createJournalEmbedRegistry({
viz: {
idPattern: /^[a-z0-9-]+$/,
mount(el, ctx) {
receivedCtx = {
id: ctx.id,
provider: ctx.provider,
aspect: ctx.aspect,
fallbackHtml: ctx.fallbackHtml,
isReducedMotion: ctx.isReducedMotion,
reducedMotionValue: ctx.reducedMotion.value,
}
el.textContent = `mounted:${ctx.id}`
return () => {
cleanedUp = true
}
},
},
})
const reducedMotion = ref(true)
const cleanup = await hydrateEmbedFigure(fig as unknown as HTMLElement, registry.get('viz')!, {
id: 'chart-1',
providerName: 'viz',
reducedMotion,
})
assert.ok(cleanup, 'expected cleanup function')
// CLS height reservation from measured fallback box (Math.ceil(342.4) = 343px).
assert.equal(fig.style.minHeight, '343px')
assert.equal(fig.classList.contains('journal-embed--hydrated'), true)
assert.deepEqual(receivedCtx, {
id: 'chart-1',
provider: 'viz',
aspect: '16/9',
fallbackHtml: fallback,
isReducedMotion: true,
reducedMotionValue: true,
})
assert.match(fig.innerHTML, /class="journal-embed__stage"/)
assert.match(fig.innerHTML, /mounted:chart-1/)
cleanup()
assert.equal(cleanedUp, true)
assert.equal(fig.classList.contains('journal-embed--hydrated'), false)
})
test('hydrateEmbedFigure mounts a Vue async component inheriting appContext and unmounts cleanly', async () => {
const doc = new FakeDocument()
;(globalThis as Record<string, unknown>).document = doc
const fallback = '<img src="/media/abc/chart.webp" alt="Chart">'
const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'vue-chart', 'data-height': '420px' }, fallback, 420)
let unmounted = false
const injectedKey = Symbol('app-i18n')
const FakeChart = defineComponent({
props: {
id: { type: String, required: true },
provider: { type: String, required: true },
height: { type: String, default: undefined },
fallbackHtml: { type: String, default: '' },
reducedMotion: { type: Object, required: true },
},
setup(props) {
const injected = inject<string>(injectedKey, 'missing')
onUnmounted(() => {
unmounted = true
})
return () =>
h(
'div',
{ class: 'vue-chart-root' },
`${props.provider}:${props.id}:${props.height}:${injected}:rm=${(props.reducedMotion as { value: boolean }).value}`,
)
},
})
const registry = createJournalEmbedRegistry({
viz: {
idPattern: /^[a-z0-9-]+$/,
component: async () => ({ default: FakeChart }),
},
})
const fakeApp = createApp({ render: () => null })
fakeApp.provide(injectedKey, 'from-nuxt-app')
const appContext = fakeApp._context as AppContext
const reducedMotion = ref(false)
const cleanup = await hydrateEmbedFigure(fig as unknown as HTMLElement, registry.get('viz')!, {
id: 'vue-chart',
providerName: 'viz',
reducedMotion,
appContext,
onError: (err) => {
throw err
},
})
assert.ok(cleanup)
assert.equal(fig.classList.contains('journal-embed--hydrated'), true)
assert.match(fig.innerHTML, /viz:vue-chart:420px:from-nuxt-app:rm=false/)
// Reactive reducedMotion update propagates into the mounted Vue component.
reducedMotion.value = true
await Promise.resolve()
assert.match(fig.innerHTML, /rm=true/)
cleanup()
assert.equal(unmounted, true)
assert.equal(fig.classList.contains('journal-embed--hydrated'), false)
})
test('hydrateEmbedFigure catches rejected import or mount throw and leaves SSR fallback DOM intact', async () => {
const doc = new FakeDocument()
const fallback = '<img src="/media/abc/fallback.webp" alt="Fallback"><figcaption>Still here</figcaption>'
// 1. Rejected dynamic component import
const fig1 = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'broken-import' }, fallback, 300)
const reg1 = createJournalEmbedRegistry({
viz: {
idPattern: /^[a-z0-9-]+$/,
component: async () => {
throw new Error('chunk load failed')
},
},
})
const errors: unknown[] = []
const cleanup1 = await hydrateEmbedFigure(fig1 as unknown as HTMLElement, reg1.get('viz')!, {
id: 'broken-import',
providerName: 'viz',
reducedMotion: ref(false),
onError: (err) => errors.push(err),
})
assert.equal(cleanup1, null)
assert.equal(errors.length, 1)
assert.equal(fig1.innerHTML, fallback)
assert.equal(fig1.classList.contains('journal-embed--hydrated'), false)
// 2. Thrown error inside plain DOM mount
const fig2 = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'broken-mount' }, fallback, 300)
const reg2 = createJournalEmbedRegistry({
viz: {
idPattern: /^[a-z0-9-]+$/,
mount() {
throw new Error('mount exploded')
},
},
})
const cleanup2 = await hydrateEmbedFigure(fig2 as unknown as HTMLElement, reg2.get('viz')!, {
id: 'broken-mount',
providerName: 'viz',
reducedMotion: ref(false),
onError: (err) => errors.push(err),
})
assert.equal(cleanup2, null)
assert.equal(errors.length, 2)
assert.equal(fig2.innerHTML, fallback)
assert.equal(fig2.classList.contains('journal-embed--hydrated'), false)
})
test('useJournalEmbedHydration defers hydration until IntersectionObserver fires and reacts to matchMedia changes', async () => {
const doc = new FakeDocument()
;(globalThis as Record<string, unknown>).document = doc
const motionListeners: Array<(e: { matches: boolean }) => void> = []
const fakeWindow = {
matchMedia: (query: string) => ({
media: query,
matches: false,
addEventListener: (_type: string, fn: (e: { matches: boolean }) => void) => motionListeners.push(fn),
removeEventListener: (_type: string, fn: (e: { matches: boolean }) => void) => {
const idx = motionListeners.indexOf(fn)
if (idx >= 0) motionListeners.splice(idx, 1)
},
}),
}
;(globalThis as Record<string, unknown>).window = fakeWindow
const observed: Array<{
target: unknown
options: { rootMargin?: string } | undefined
trigger: (isIntersecting: boolean) => void
disconnected: boolean
}> = []
class FakeIntersectionObserver {
private readonly cb: (entries: Array<{ isIntersecting: boolean }>, obs: FakeIntersectionObserver) => void
private readonly opts: { rootMargin?: string } | undefined
private record: (typeof observed)[number] | null = null
constructor(cb: (entries: Array<{ isIntersecting: boolean }>, obs: FakeIntersectionObserver) => void, opts?: { rootMargin?: string }) {
this.cb = cb
this.opts = opts
}
observe(target: unknown): void {
this.record = {
target,
options: this.opts,
disconnected: false,
trigger: (isIntersecting: boolean) => this.cb([{ isIntersecting }], this),
}
observed.push(this.record)
}
disconnect(): void {
if (this.record) this.record.disconnected = true
}
}
;(globalThis as Record<string, unknown>).IntersectionObserver = FakeIntersectionObserver
const container = doc.createElement('div')
const fallback = '<img src="/media/abc/chart.webp" alt="Chart">'
const fig = makeFigure(doc, { 'data-embed': 'viz', 'data-id': 'lazy-chart' }, fallback, 320)
container.appendChild(fig)
let mountCalls = 0
let unmountCalls = 0
let seenMotionRef: Readonly<{ value: boolean }> | null = null
const registry = createJournalEmbedRegistry({
viz: {
idPattern: /^[a-z0-9-]+$/,
rootMargin: '250px',
mount(el, ctx) {
mountCalls += 1
seenMotionRef = ctx.reducedMotion
el.textContent = `hydrated:${ctx.id}`
return () => {
unmountCalls += 1
}
},
},
})
// Mount a minimal host Vue component using `useJournalEmbedHydration`.
const html = ref('<figure data-embed="viz" data-id="lazy-chart"></figure>')
const Host = defineComponent({
setup() {
const elRef = ref<HTMLElement | null>(container as unknown as HTMLElement)
useJournalEmbedHydration(elRef, html, { registry })
return () => h('div')
},
})
const appRoot = doc.createElement('div')
render(createVNode(Host), appRoot as unknown as Element)
// Before intersection: observer registered with provider rootMargin, not yet hydrated.
assert.equal(observed.length, 1)
assert.equal(observed[0]!.options?.rootMargin, '250px')
assert.equal(mountCalls, 0)
assert.equal(fig.innerHTML, fallback)
// Non-intersecting event does not trigger hydration.
observed[0]!.trigger(false)
await Promise.resolve()
assert.equal(mountCalls, 0)
// Intersecting event disconnects observer and hydrates the figure.
observed[0]!.trigger(true)
await new Promise((r) => setTimeout(r, 0))
assert.equal(observed[0]!.disconnected, true)
assert.equal(mountCalls, 1)
assert.equal(fig.classList.contains('journal-embed--hydrated'), true)
assert.equal(seenMotionRef!.value, false)
// matchMedia change updates the reactive reducedMotion ref.
assert.equal(motionListeners.length, 1)
motionListeners[0]!({ matches: true })
assert.equal(seenMotionRef!.value, true)
// Unmounting the host component runs embed cleanup and removes matchMedia listener.
render(null, appRoot as unknown as Element)
assert.equal(unmountCalls, 1)
assert.equal(motionListeners.length, 0)
})

View File

@@ -2,11 +2,22 @@
// <figure data-embed="youtube" data-id="ID"></figure>; the sinks render
// expandEmbeds(sanitizeJournalHtml(html)), so the sanitizer runs first and the
// only iframe in the output is the one built from a validated placeholder.
import { test } from 'node:test'
import { afterEach, test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { EMBED_PLACEHOLDER, EMBED_PROVIDERS, expandEmbeds } from '../app/utils/embeds.ts'
import { sanitizeJournalHtml } from '../app/utils/htmlGate.ts'
import {
createJournalEmbedRegistry,
defineJournalEmbedProviders,
getJournalEmbedRegistry,
registerJournalEmbedProvider,
resetJournalEmbedRegistry,
} from '../app/utils/embedRegistry.ts'
import { gateJournalHtml, isSafeJournalHtml, sanitizeJournalHtml } from '../app/utils/htmlGate.ts'
afterEach(() => {
resetJournalEmbedRegistry()
})
const ID = 'dQw4w9WgXcQ'
const PLACEHOLDER = `<figure data-embed="youtube" data-id="${ID}"></figure>`
@@ -175,3 +186,121 @@ test('the iframe src is a fixed host plus the validated id, never stored text',
assert.match(out, /loading="lazy"/)
assert.doesNotMatch(out, /allow="[^"]*(autoplay|camera|microphone|geolocation)/)
})
// ---------------------------------------------------------------------------
// Phase 38: Extensible embed provider registry, pair-aware sanitizer & SSR
// ---------------------------------------------------------------------------
test('registry supports dual registration helpers and rejects prototype-pollution keys', () => {
const scoped = createJournalEmbedRegistry({
viz: { idPattern: /^[a-z0-9][a-z0-9-]{0,63}$/ },
})
assert.equal(scoped.has('youtube'), true)
assert.equal(scoped.has('viz'), true)
assert.equal(scoped.match('viz', 'chart-2026'), true)
assert.equal(scoped.match('viz', 'Chart-2026'), false)
assert.equal(scoped.match('youtube', 'chart-2026'), false)
// Prototype keys never match and cannot be registered.
for (const bad of ['__proto__', 'constructor', 'toString', 'valueOf', '../x', 'YouTube', '']) {
assert.equal(scoped.has(bad), false, bad)
assert.equal(scoped.get(bad), undefined, bad)
assert.equal(scoped.match(bad, 'abc'), false, bad)
assert.throws(() => scoped.register(bad, { idPattern: /^[a-z]+$/ }), /Invalid journal embed provider key/)
}
// Global singleton helpers + reset.
registerJournalEmbedProvider('viz', { idPattern: '^[a-z0-9-]+$' })
defineJournalEmbedProviders({ acme: { idPattern: /^acme-[0-9]+$/ } })
assert.equal(getJournalEmbedRegistry().has('viz'), true)
assert.equal(getJournalEmbedRegistry().has('acme'), true)
resetJournalEmbedRegistry()
assert.equal(getJournalEmbedRegistry().has('viz'), false)
assert.equal(getJournalEmbedRegistry().has('acme'), false)
assert.equal(getJournalEmbedRegistry().has('youtube'), true)
})
test('pair-aware htmlGate allows custom embed with responsive fallback img and strips mismatches/XSS', () => {
registerJournalEmbedProvider('viz', {
idPattern: /^[a-z0-9][a-z0-9-]{0,63}$/,
mount: () => {},
})
const valid =
'<figure data-embed="viz" data-id="lions-mane-studies" data-aspect="16/9" data-height="420px">' +
'<img src="/media/abc123/chart.webp" srcset="/media/abc123/chart-480w.webp 480w, /media/abc123/chart-960w.webp 960w" sizes="(max-width: 768px) 100vw, 800px" alt="Chart" width="800" height="450" />' +
'<figcaption>Figure 1</figcaption>' +
'</figure>'
assert.equal(sanitizeJournalHtml(valid), valid)
assert.equal(isSafeJournalHtml(valid), true)
assert.equal(gateJournalHtml(valid).html, valid)
// Cross-provider ID mismatches strip all embed attributes.
assert.equal(
sanitizeJournalHtml('<figure data-embed="youtube" data-id="lions-mane-studies" data-aspect="16/9"></figure>'),
'<figure></figure>',
)
assert.equal(
sanitizeJournalHtml(`<figure data-embed="viz" data-id="${ID}" data-height="420px"></figure>`),
'<figure></figure>',
)
assert.equal(isSafeJournalHtml('<figure data-embed="youtube" data-id="lions-mane-studies"></figure>'), false)
// Invalid data-aspect / data-height (CSS injection vectors) are stripped.
assert.equal(
sanitizeJournalHtml('<figure data-embed="viz" data-id="ok-id" data-aspect="16/9; background:url(javascript:alert(1))"></figure>'),
'<figure data-embed="viz" data-id="ok-id"></figure>',
)
assert.equal(
sanitizeJournalHtml('<figure data-embed="viz" data-id="ok-id" data-height="-100px"></figure>'),
'<figure data-embed="viz" data-id="ok-id"></figure>',
)
// XSS inside custom embed is stripped while safe fallback survives.
const xss =
'<figure data-embed="viz" data-id="ok-id" data-aspect="4/3">' +
'<script>alert(1)</script>' +
'<iframe src="https://evil.test"></iframe>' +
'<svg onload="alert(1)"><circle r="1"/></svg>' +
'<img src="/media/abc/ok.webp" alt="Safe" onerror="alert(1)">' +
'<figcaption>Caption</figcaption>' +
'</figure>'
const cleaned = sanitizeJournalHtml(xss)
assert.doesNotMatch(cleaned, /<script|<iframe|<svg|onerror|alert/i)
assert.equal(
cleaned,
'<figure data-embed="viz" data-id="ok-id" data-aspect="4/3"><img src="/media/abc/ok.webp" alt="Safe" /><figcaption>Caption</figcaption></figure>',
)
})
test('expandEmbeds preserves SSR fallback + adds classes/CLS styles for client-hydrated providers and allows youtube override', () => {
registerJournalEmbedProvider('viz', {
idPattern: /^[a-z0-9-]+$/,
mount: () => {},
aspectRatio: '16/9',
minHeight: '360px',
})
const raw =
'<figure data-embed="viz" data-id="chart-1" data-aspect="4/3">' +
'<img src="/media/abc/chart.webp" alt="Chart" width="800" height="600">' +
'<figcaption>Figure 1</figcaption>' +
'</figure>'
const expanded = expandEmbeds(sanitizeJournalHtml(raw))
assert.match(expanded, /class="journal-embed journal-embed--viz"/)
assert.match(expanded, /data-embed="viz"/)
assert.match(expanded, /data-id="chart-1"/)
assert.match(expanded, /style="aspect-ratio:4\/3;min-height:360px"/)
assert.match(expanded, /<img src="\/media\/abc\/chart\.webp" alt="Chart" width="800" height="600" \/>/)
assert.match(expanded, /<figcaption>Figure 1<\/figcaption>/)
// Built-in YouTube remains byte-identical.
assert.equal(expandEmbeds(PLACEHOLDER), IFRAME)
// Overriding youtube replaces SSR rendering.
registerJournalEmbedProvider('youtube', {
idPattern: /^[A-Za-z0-9_-]{11}$/,
renderSsr: (id) => `<figure class="custom-yt" data-id="${id}"></figure>`,
})
assert.equal(expandEmbeds(PLACEHOLDER), `<figure class="custom-yt" data-id="${ID}"></figure>`)
})