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

@@ -33,28 +33,76 @@ Route paths are configuration, not files. The layer's page components live in `a
- **Body links and images**: the CMS's phrase auto-links, the outbound link rules (nofollow or sponsored from the domain lists; new tab, `noopener` and a visually hidden hint while the CMS's links_new_tab is on) and lazy, async body images, applied at SSR on the sanitized body.
- **Breadcrumbs and pagination**: `<SeoBreadcrumbs>` at the top of every journal page (`journal.breadcrumbs`), and `JournalPagination` as `<SeoPagination>` with the journal's class names.
- **HTML sanitizer**: post bodies and category content go through `sanitizeJournalHtml` before `v-html` and before they reach the SSR payload. It is [sanitize-html](https://github.com/apostrophecms/sanitize-html) with the Journal API's own allow-list: the usual content elements, `footer`, `class`, schema.org microdata, the `color`, `font-size`, `font-weight` and `text-align` inline styles, and `http`, `https`, `mailto` or relative URLs. Five rules keep the Journal Blog Editor's own markup, mirroring the API's policy: `data-embed` (`youtube`) and `data-id` (an 11-character video id) on `figure`, `alt` with any text on `img` (`alt=""` of a decorative image included), an integer `start` on `ol`, and a `rel` of only `nofollow`, `sponsored` and `ugc` on `a`. `target` is never kept; the outbound link rules add it. With `{ demoteH1: true }`, `h1` headings come out as `h2`. Anything else (`script`, `style`, `iframe`, `svg`, forms, event-handler attributes, `javascript:` URLs in any spelling) is removed and the rest of the value is kept, so a post never renders blank because of one stray tag. Server and browser produce the same string, so hydration matches. See `docs/decisions/0001-sanitize-html.md`.
- **Embeds**: YouTube videos added in the Journal Blog Editor render as privacy-enhanced iframes (see [Embeds](#embeds)).
- **Embeds**: built-in YouTube privacy-enhanced iframes plus an app-extensible embed provider registry (`app.config.ts` and Nuxt plugin helpers) with SSR static fallback preservation, CLS height reservation, `IntersectionObserver` lazy hydration, and `prefers-reduced-motion` support (see [Embeds](#embeds)).
- **i18n**: English and Polish UI strings, registered only for the locales the app enables.
## Embeds
The Journal Blog Editor never stores an iframe. It stores a placeholder:
The Journal Blog Editor never stores an iframe or inline `<script>`. It stores a `<figure>` placeholder with optional static fallback markup:
```html
<!-- Built-in YouTube -->
<figure data-embed="youtube" data-id="dQw4w9WgXcQ"></figure>
<!-- Custom interactive embed with static SSR fallback -->
<figure data-embed="viz" data-id="acme-chart-1" data-aspect="16/9">
<img src="/media/abc123/chart.webp" alt="Chart overview" width="800" height="450">
<figcaption>Figure 1</figcaption>
</figure>
```
`expandEmbeds(html)` in `app/utils/embeds.ts` turns it into:
### Default YouTube behavior
`youtube` (`idPattern: /^[A-Za-z0-9_-]{11}$/`) is registered by default in `app/utils/embedRegistry.ts`. `expandEmbeds(html)` in `app/utils/embeds.ts` turns an empty `<figure data-embed="youtube" data-id="..."></figure>` into the same privacy-enhanced iframe:
```html
<figure class="journal-embed journal-embed--youtube"><iframe src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ" title="YouTube video" loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allow="encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe></figure>
```
- **Allowlist:** `EMBED_PROVIDERS` holds one provider, `youtube`, whose id must match `^[A-Za-z0-9_-]{11}$`. The iframe `src` is always `https://www.youtube-nocookie.com/embed/` plus that id. `EMBED_PLACEHOLDER` matches the placeholder exactly as the editor writes it (`data-embed` then `data-id`, double quotes, empty figure). Any other figure, provider or id is left unchanged and renders as an empty figure.
- **Order:** sanitize first, expand last. `JournalPostBody` renders `expandEmbeds(sanitizeJournalHtml(html))` and `JournalCategoryHeader` does the same with the category content. The payload transforms (`toPostView`, the category page) only sanitize, so the payload carries the placeholder. The expansion's output is never sanitized again, because the sanitizer removes every iframe, including this one. A raw `<iframe>` in stored HTML is removed by the sanitizer before the expansion runs, so the only iframe on a page is one built from a validated placeholder.
- **Styles:** `.journal-embed` is a full-width block with a 16 / 9 aspect ratio; its iframe fills it without a border. `.journal-embed--youtube` marks the provider for app styles.
- **Overrides:** an app that replaces `JournalPostBody` or `JournalCategoryHeader` and wants embeds calls `expandEmbeds` on the sanitized string, never before sanitizing.
- **Content-Security-Policy:** a site that sends a CSP needs `frame-src https://www.youtube-nocookie.com`.
Apps may optionally override `youtube` in the registry (for example to render a click-to-play facade instead of an eager SSR iframe).
### Registering custom embed providers
Consuming Nuxt apps can register custom embed providers via **`app.config.ts`** (`journal.embeds`, synced on both SSR and client by `app/plugins/journal-embeds.ts`) and/or a **Nuxt plugin** calling `registerJournalEmbedProvider` / `defineJournalEmbedProviders` from `app/utils/embedRegistry.ts`:
```ts
// app/app.config.ts
export default defineAppConfig({
journal: {
embeds: {
viz: {
idPattern: /^[a-z0-9][a-z0-9-]{0,63}$/,
component: () => import('~/components/EmbedViz.vue'),
aspectRatio: '16/9',
rootMargin: '200px',
},
},
},
})
```
```ts
// app/plugins/custom-embeds.ts (runs on both SSR and client)
export default defineNuxtPlugin(() => {
registerJournalEmbedProvider('acme', {
idPattern: /^acme-[0-9]{1,6}$/,
mount(el, ctx) {
// Plain DOM mount callback with reactive ctx.reducedMotion & ctx.fallbackHtml
el.textContent = `Widget ${ctx.id}`
return () => {
el.replaceChildren()
}
},
})
})
```
- **Sanitizer parity:** Registered providers automatically feed `sanitizeJournalHtml`, `gateJournalHtml`, `isSafeJournalHtml`, and `renderJournalBody` with pair-aware `(data-embed, data-id)` validation (so an ID valid for `viz` is never accepted on `data-embed="youtube"`). Validated `data-aspect` (`16/9`, `4/3`, `1.5`) and `data-height` (`420`, `420px`) attributes are allowed only on valid embed figures; fallback `<img>` (including `srcset`/`sizes`/`width`/`height`) and `<figcaption>` children pass the UGC allow-list while `<script>`, `<style>`, `<iframe>`, `<svg>`, and event handlers are stripped. Prototype keys (`__proto__`, `constructor`, `toString`) are rejected by `Map`-based lookups.
- **Order:** sanitize first, expand/hydrate last. `JournalPostBody` and `JournalCategoryHeader` call `expandEmbeds(renderJournalBody(...))` / `expandEmbeds(sanitizeJournalHtml(...))` and wire `useJournalEmbedHydration`. The payload transforms (`toPostView`, `CategoryPage.vue`) only sanitize, so the SSR payload carries the clean `<figure>` markup.
- **SSR static fallback & CLS reservation:** For client-hydrated providers (`component` or `mount`, without `renderSsr`), `expandEmbeds` preserves the SSR fallback `<img>` + `<figcaption>` intact, adds `journal-embed journal-embed--<provider>`, and applies validated `aspect-ratio` / `min-height` inline styles. Before swapping in the hydrated widget on the client, `hydrateEmbedFigure` measures the fallback box height and sets `min-height` to prevent cumulative layout shift (CLS).
- **Lazy hydration, `prefers-reduced-motion`, and resilience:** `useJournalEmbedHydration` observes each validated `<figure data-embed>` with `IntersectionObserver` (default `rootMargin: '200px'`), passes a reactive `reducedMotion` ref synced with `window.matchMedia('(prefers-reduced-motion: reduce)')`, mounts Vue async components via `createVNode` + `render` inheriting `nuxtApp.vueApp._context` (so i18n, router, and Pinia work inside hydrated embeds) or invokes `mount(el, ctx)`, and cleans up on unmount or HTML updates. If dynamic import or mount throws, the error is caught and the SSR static fallback DOM remains intact.
- **Styles:** `.journal-embed--youtube` and iframe embeds default to a `16 / 9` full-width frame; custom embeds render their fallback image, `<figcaption>`, and `.journal-embed__stage` naturally, adding `.journal-embed--hydrated` once mounted.
- **Content-Security-Policy:** The hydration runtime is strictly `script-src 'self'` compliant (no `eval`, no `new Function`, no inline `<script>`). Sites using the built-in YouTube iframe still need `frame-src https://www.youtube-nocookie.com`.
## Usage

View File

@@ -14,6 +14,8 @@
/** Allowed embed provider key format (mirrors sm-journal-plugin). */
export const EMBED_PROVIDER_KEY = /^[a-z][a-z0-9_-]{0,31}$/
const RESERVED_PROVIDER_KEYS = new Set(['constructor', 'prototype'])
/** 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})?$/
@@ -122,7 +124,7 @@ function normalizeIdPattern(name: string, pattern: RegExp | string): RegExp {
}
function normalizeProvider(name: string, provider: JournalEmbedProvider): NormalizedJournalEmbedProvider {
if (!EMBED_PROVIDER_KEY.test(name)) {
if (!EMBED_PROVIDER_KEY.test(name) || RESERVED_PROVIDER_KEYS.has(name)) {
throw new Error(`Invalid journal embed provider key "${name}": must match ${EMBED_PROVIDER_KEY.source}`)
}
if (!provider || typeof provider !== 'object') {

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>`)
})