From 3fc656da0f056c02557ea212582ff883d92911a3 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Sat, 28 Nov 2026 13:01:26 +0100 Subject: [PATCH] test(embeds): add Go race tests, Blog Editor Vitest suite, and README docs --- README.md | 40 ++- classes/embed_registry_test.go | 443 +++++++++++++++++++++++++++++++++ tests/blogeditor/embed.test.ts | 165 +++++++++++- 3 files changed, 644 insertions(+), 4 deletions(-) create mode 100644 classes/embed_registry_test.go diff --git a/README.md b/README.md index 5eef3ac..f8ef888 100644 --- a/README.md +++ b/README.md @@ -276,7 +276,7 @@ The prompt `journal_draft_post` (arguments `topic`, required, and `tone`) asks t The element follows the admin field type element contract: the `value` property holds the HTML string; the attributes are `field-name`, `record-id`, `locale`, `ui-locale`, `options`, `disabled` and `invalid`; a bubbling `summer-change` event with `detail.value` fires on user edits only. It styles itself only through the admin `--c-*` variables, in `blogeditor.css` under its tag (TipTap's injected stylesheet is off), and never receives or sends credentials. - **Untouched values.** The element returns the exact string it was given until the user edits; an untouched imported post is saved byte for byte. Setting `value` to the string it currently returns is a no-op. After an edit, top-level blocks that are still equal to the loaded ones keep their original bytes, so editing one paragraph changes only that paragraph. Markup the schema does not model (`footer`, `section`, `aside`, `header`, `nav`, `details`, `style`, `div` and similar blocks, and a `figure` that is not an image with an optional caption) becomes a raw HTML card that shows its source as text and is written back verbatim. On paragraphs, headings, lists, blockquotes, tables, cells, images and links, and on `span` elements, the view-safe unmodelled attributes survive an edit of their block: `class`, `title`, `alt`, `width`, `height`, `colspan`, `rowspan`, `start`, `rel`, `target` and `data-*` (`href` and `src` are kept by the link and image nodes, which check them). Every other attribute, such as `id`, `name`, `style`, `srcset`, `form`, `contenteditable`, `popover`, `itemprop` or an event handler (`on*`), is never rendered into the admin page and is dropped from a block once that block is edited; a `span` left with none of the kept attributes is dropped and its text kept. Untouched documents and untouched blocks keep every stored attribute. -- **Embeds.** The embed button takes a YouTube URL (`youtube.com/watch?v=`, `youtu.be/`, `youtube.com/shorts/`, `youtube.com/embed/`) and stores exactly `
`, where `ID` matches `^[A-Za-z0-9_-]{11}$`. The admin shows a card and never an iframe; the site layer expands the placeholder. Another provider is one entry in `EMBED_PROVIDERS` (`embed.ts`) and one in the layer. +- **Embeds.** By default, the embed button takes a YouTube URL (`youtube.com/watch?v=`, `youtu.be/`, `youtube.com/shorts/`, `youtube.com/embed/`) and stores `
`, where `ID` matches `^[A-Za-z0-9_-]{11}$`. When the application registers additional embed providers (via `golem15.journal.embed_providers` YAML config or `classes.EmbedRegistry` on `backpack.App`), `blogRequestOptions` sends `embedProviders` in the element's `options` JSON and the inline embed form adapts to show a provider selector, an ID input, an optional fallback image (including the shared Media Library picker), alt text, caption, and optional `data-aspect` / `data-height` CLS hints. The TipTap `Embed` node preserves fallback `` and `
` children on round-trip; both the editor card and the preview pane show the fallback image (or a YouTube thumbnail card) and never an iframe. The site layer expands or lazily hydrates the placeholder. - **Preview.** The Preview button (`PodglÄ…d` for `ui-locale` `pl`) is off by default, belongs to each element on its own and shows its state through `aria-pressed`. It splits the editor 50/50; when the element is narrower than about 720px, the pane wraps below the editor. The pane renders the current value from the WYSIWYG or Source tab 300 ms (`PREVIEW_DEBOUNCE_MS` in `preview.ts`) after the last change, and each update reloads the frame. The frame is an `` + + `` + + `bad` + + `Safe` + + `
Safe caption
` + + `` + got, report := reg.SanitizeHTMLReport(in) + assertNoActiveContent(t, got) + if !strings.Contains(got, `data-embed="viz"`) || !strings.Contains(got, `data-id="ok-id"`) { + t.Fatalf("valid embed attributes lost: %q", got) + } + if !strings.Contains(got, `Safe`) { + t.Fatalf("safe fallback img lost: %q", got) + } + if !strings.Contains(got, `
Safe caption
`) { + t.Fatalf("safe figcaption lost: %q", got) + } + if report.Empty() { + t.Fatal("expected non-empty removal report for XSS payload") + } + if err := reg.CheckHTML(in); err == nil { + t.Fatal("CheckHTML = nil for XSS payload, want error") + } + }) +} + +func TestBlogRequestOptionsEmbedProviders(t *testing.T) { + cfg, err := compass.Open(compass.Options{Dir: t.TempDir(), Environ: []string{}}) + if err != nil { + t.Fatal(err) + } + app := backpack.New(cfg) + reg := NewEmbedRegistry() + if err := reg.Register(EmbedProvider{ + Key: "viz", + Name: "Chart", + IDPattern: `^[a-z0-9-]+$`, + Mode: EmbedModeID, + Placeholder: "chart-id", + }); err != nil { + t.Fatal(err) + } + if err := app.Publish(reg); err != nil { + t.Fatal(err) + } + + optsFn := blogRequestOptions(func() *backpack.App { return app }) + opts, err := optsFn(context.Background(), nil) + if err != nil { + t.Fatalf("blogRequestOptions: %v", err) + } + raw, ok := opts["embedProviders"] + if !ok { + t.Fatalf("embedProviders missing from options: %+v", opts) + } + descs, ok := raw.([]EmbedProviderDescriptor) + if !ok { + t.Fatalf("embedProviders type = %T, want []EmbedProviderDescriptor", raw) + } + if len(descs) != 2 || descs[0].Key != "youtube" || descs[1].Key != "viz" { + t.Fatalf("embedProviders = %+v", descs) + } + if descs[1].Name != "Chart" || descs[1].Placeholder != "chart-id" { + t.Fatalf("viz descriptor = %+v", descs[1]) + } +} + +func TestEmbedRegistryConcurrentIsolationRace(t *testing.T) { + regA := NewEmbedRegistry() + if err := regA.Register(EmbedProvider{Key: "viz", IDPattern: `^[a-z0-9-]+$`}); err != nil { + t.Fatal(err) + } + regB := NewEmbedRegistry() + if err := regB.Register(EmbedProvider{Key: "acme", IDPattern: `^acme-[0-9]+$`}); err != nil { + t.Fatal(err) + } + + const workers = 16 + const iterations = 40 + var wg sync.WaitGroup + wg.Add(workers * 2) + + for i := 0; i < workers; i++ { + go func() { + defer wg.Done() + vizHTML := `
` + acmeHTML := `
` + for j := 0; j < iterations; j++ { + if got := regA.SanitizeHTML(vizHTML); got != vizHTML { + t.Errorf("regA rejected viz: %q", got) + } + if got := regA.SanitizeHTML(acmeHTML); got != `
` { + t.Errorf("regA leaked acme: %q", got) + } + } + }() + go func() { + defer wg.Done() + vizHTML := `
` + acmeHTML := `
` + for j := 0; j < iterations; j++ { + if got := regB.SanitizeHTML(acmeHTML); got != acmeHTML { + t.Errorf("regB rejected acme: %q", got) + } + if got := regB.SanitizeHTML(vizHTML); got != `
` { + t.Errorf("regB leaked viz: %q", got) + } + } + }() + } + wg.Wait() +} diff --git a/tests/blogeditor/embed.test.ts b/tests/blogeditor/embed.test.ts index 65e7c93..82c5648 100644 --- a/tests/blogeditor/embed.test.ts +++ b/tests/blogeditor/embed.test.ts @@ -1,9 +1,20 @@ // Embeds, the URL rule, uploads and labels of the Blog Editor (Phase 16.2 // D-04, D-05, D-13, D-18). import { afterEach, describe, expect, it, vi } from 'vitest' -import { EMBED_PROVIDERS, isEmbedProvider, parseEmbedUrl } from '../../assets/src/blogeditor/embed' +import { + DEFAULT_EMBED_PROVIDERS, + EMBED_PROVIDERS, + isEmbedProvider, + isValidAspect, + isValidHeight, + parseEmbedUrl, + resolveEmbedProviders, + validateEmbedId, +} from '../../assets/src/blogeditor/embed' +import { MEDIA_PICK_EVENT, MEDIA_PICK_RESULT_EVENT } from '../../assets/src/blogeditor/element' import { isPolicyUrl } from '../../assets/src/blogeditor/extensions' import { format, labelsFor } from '../../assets/src/blogeditor/labels' +import { previewBody, youtubeThumbnail } from '../../assets/src/blogeditor/preview' import { button, chooseImage, click, fill, form, mount, status } from './helpers' afterEach(() => { @@ -278,3 +289,155 @@ describe('disabled and invalid', () => { expect(el.value).toBe('

a

') }) }) + +describe('dynamic embed providers (Phase 38)', () => { + const customOptions = JSON.stringify({ + embedProviders: [ + { key: 'youtube', name: 'YouTube', idPattern: '^[A-Za-z0-9_-]{11}$', mode: 'url' }, + { + key: 'viz', + name: 'Interactive Chart', + idPattern: '^[a-z0-9][a-z0-9-]{0,63}$', + mode: 'id', + placeholder: 'chart-slug', + }, + ], + }) + + it('resolveEmbedProviders defaults to youtube and ignores invalid keys, regexes, and duplicates', () => { + expect(resolveEmbedProviders(undefined)).toEqual(DEFAULT_EMBED_PROVIDERS) + expect(resolveEmbedProviders([])).toEqual(DEFAULT_EMBED_PROVIDERS) + expect(resolveEmbedProviders('invalid')).toEqual(DEFAULT_EMBED_PROVIDERS) + + const resolved = resolveEmbedProviders([ + { key: 'youtube', name: 'YouTube', idPattern: '^[A-Za-z0-9_-]{11}$', mode: 'url' }, + { key: 'viz', name: 'Chart', idPattern: '[a-z0-9-]+', mode: 'id', placeholder: 'demo-1' }, + { key: 'viz', name: 'Duplicate', idPattern: '^[0-9]+$' }, + { key: '../bad', name: 'Bad Key', idPattern: '^[a-z]+$' }, + { key: 'BadCase', name: 'Upper', idPattern: '^[a-z]+$' }, + { key: 'broken', name: 'Bad Regex', idPattern: '[unclosed' }, + { key: 'empty', name: 'No Pattern', idPattern: '' }, + ]) + expect(resolved.map((p) => p.key)).toEqual(['youtube', 'viz']) + expect(validateEmbedId(resolved, 'viz', 'demo-1')).toBe(true) + expect(validateEmbedId(resolved, 'viz', 'demo-1!')).toBe(false) + expect(validateEmbedId(resolved, 'youtube', 'demo-1')).toBe(false) + expect(validateEmbedId(resolved, 'youtube', ID)).toBe(true) + + expect(isValidAspect('16/9')).toBe(true) + expect(isValidAspect('4 / 3')).toBe(true) + expect(isValidAspect('1.5')).toBe(true) + expect(isValidAspect('16/9; background:red')).toBe(false) + expect(isValidHeight('420')).toBe(true) + expect(isValidHeight('420px')).toBe(true) + expect(isValidHeight('-100px')).toBe(false) + }) + + it('keeps the single URL input form when only youtube is registered', () => { + const { el } = mount('

a

') + click(button(el, 'embed')) + const embedForm = form(el, 'embed')! + expect(embedForm.querySelector('select[name="provider"]')).toBeNull() + expect(embedForm.querySelector('input[name="url"]')).not.toBeNull() + expect(embedForm.querySelector('input[name="embedId"]')).toBeNull() + }) + + it('shows adaptive provider selector, ID fields, and Media Library fallback picker for custom providers', () => { + const { el, changes } = mount('

Intro

', { options: customOptions }) + const picks: Array<{ id: string; mode: string; defaultFolder: string }> = [] + el.addEventListener(MEDIA_PICK_EVENT, (e) => { + picks.push((e as CustomEvent<{ id: string; mode: string; defaultFolder: string }>).detail) + }) + + click(button(el, 'embed')) + const embedForm = form(el, 'embed')! + const select = embedForm.querySelector('select[name="provider"]')! + expect(Array.from(select.options).map((o) => o.value)).toEqual(['youtube', 'viz']) + + // Switch to custom ID-mode provider + select.value = 'viz' + select.dispatchEvent(new Event('change')) + + // Pick fallback image from Media Library + click(embedForm.querySelector('[data-action="pick-fallback"]')) + expect(picks).toHaveLength(1) + expect(picks[0]!.mode).toBe('image') + el.dispatchEvent( + new CustomEvent(MEDIA_PICK_RESULT_EVENT, { + detail: { + id: picks[0]!.id, + item: { + url: '/media/abc123/fallback.webp', + alt: 'Chart preview', + caption: 'Figure 1', + width: 800, + height: 450, + }, + }, + }), + ) + + fill(embedForm.querySelector('input[name="embedId"]'), 'demo-1') + fill(embedForm.querySelector('input[name="aspect"]'), '4/3') + click(embedForm.querySelector('[data-action="insert"]')) + + expect(form(el, 'embed')).toBeNull() + expect(changes).toHaveLength(1) + expect(el.value).toContain( + '
' + + 'Chart preview' + + '
Figure 1
', + ) + }) + + it('TipTap Embed node parses and round-trips custom embed with fallback without RawHtml', () => { + const customHtml = + '
' + + 'Fallback' + + '
Figure 1
' + const docHtml = `

Before

${customHtml}${PLACEHOLDER}

After

` + const { el, editor } = mount(docHtml, { options: customOptions }) + + expect(editor.state.doc.child(1).type.name).toBe('embed') + expect(editor.state.doc.child(1).attrs).toMatchObject({ + provider: 'viz', + id: 'demo-1', + aspect: '4/3', + fallbackSrc: '/media/abc/fallback.webp', + fallbackAlt: 'Fallback', + caption: 'Figure 1', + }) + expect(editor.state.doc.child(2).type.name).toBe('embed') + expect(editor.state.doc.child(2).attrs).toMatchObject({ provider: 'youtube', id: ID }) + + // Edit an unrelated paragraph and verify both embeds round-trip cleanly. + editor.view.dispatch(editor.state.tr.insertText('X', 1)) + expect(el.value).toBe(`

XBefore

${customHtml}${PLACEHOLDER}

After

`) + }) + + it('previewBody renders fallback img and figcaption for custom embeds and youtubeThumbnail for YouTube', () => { + const providers = resolveEmbedProviders([ + { key: 'youtube', name: 'YouTube', idPattern: '^[A-Za-z0-9_-]{11}$', mode: 'url' }, + { key: 'viz', name: 'Interactive Chart', idPattern: '^[a-z0-9-]+$', mode: 'id' }, + ]) + const labels = labelsFor('en') + + const customWithFallback = + '
' + + 'Fallback' + + '
Figure 1
' + const customPreview = previewBody(customWithFallback, labels, providers) + expect(customPreview).toContain('class="embed-card"') + expect(customPreview).toContain('src="/media/abc/fallback.webp"') + expect(customPreview).toContain('alt="Fallback"') + expect(customPreview).toContain('
Figure 1
') + expect(customPreview).not.toContain('img.youtube.com') + + const ytPreview = previewBody(PLACEHOLDER, labels, providers) + expect(ytPreview).toContain(`src="${youtubeThumbnail(ID)}"`) + expect(ytPreview).toContain(`${labels.embedCard}: YouTube ${ID}`) + + const customNoFallback = previewBody('
', labels, providers) + expect(customNoFallback).toContain('Interactive Chart: demo-2 (420px)') + }) +})