fix(builder): sanitize HtmlBlock/Countdown/Gallery JS contexts

Entity-escaping alone doesn't protect JS-string or raw-HTML sinks:

- HtmlBlock.toHtml exported props.code raw; now runs it through the
  same purifyHtml (DOMPurify) config already used for the live editor
  preview, so <script>/on*= payloads can't survive export either.
- Countdown.toHtml interpolated targetDate directly into
  `new Date("${targetDate}")` inside an inline <script> -- a value
  like `2026-01-01");alert(1)//` broke out of the string literal. Now
  validated against a strict date/datetime shape and JSON.stringify'd
  before embedding, falling back to `new Date()` for anything invalid.
- Gallery.toHtml's lightbox used
  `onclick="${id}_open('${esc(img.src)}')"`, which a single quote in
  img.src could break out of. Replaced with a `data-lb-src` attribute
  per thumbnail and one delegated click listener on the grid
  (`e.target.closest('[data-lb-src]')`) instead of a per-item inline
  handler string.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-07-12 12:06:07 -07:00
parent 48d0441be3
commit 7179287087
6 changed files with 106 additions and 9 deletions
@@ -0,0 +1,33 @@
import { describe, test, expect } from 'vitest';
import { Gallery } from './Gallery';
const toHtml = (Gallery as any).toHtml;
describe('Gallery.toHtml lightbox uses a delegated listener, not per-item onclick (A4.3)', () => {
test('no per-item inline onclick with interpolated src', () => {
const { html } = toHtml({ images: [{ src: '/a.jpg', alt: 'a' }], lightbox: true }, '');
expect(html).not.toMatch(/onclick="[^"]*_open\(/);
expect(html).toContain('data-lb-src="/a.jpg"');
});
test('a single-quote in src cannot break the handler (no per-item onclick at all)', () => {
const { html } = toHtml({ images: [{ src: "/a'.jpg", alt: 'a' }], lightbox: true }, '');
// no per-item onclick handler exists at all (delegated listener only)
expect(html).not.toMatch(/onclick="[^"]*_open\(/);
// the quote in src is entity-escaped in the data attribute, not raw
expect(html).toContain('data-lb-src="/a&#39;.jpg"');
expect(html).not.toContain(`data-lb-src="/a'.jpg"`);
});
test('emits exactly one delegated click listener', () => {
const { html } = toHtml({ images: [{ src: '/a.jpg' }, { src: '/b.jpg' }], lightbox: true }, '');
const matches = html.match(/addEventListener\(['"]click['"]/g) || [];
expect(matches.length).toBe(1);
});
test('lightbox=false: no data-lb-src, no script', () => {
const { html } = toHtml({ images: [{ src: '/a.jpg' }], lightbox: false }, '');
expect(html).not.toContain('data-lb-src');
expect(html).not.toContain('<script>');
});
});