test(embeds): add Go race tests, Blog Editor Vitest suite, and README docs
This commit is contained in:
40
README.md
40
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 `<figure data-embed="youtube" data-id="ID"></figure>`, 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 `<figure data-embed="youtube" data-id="ID"></figure>`, 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 `<img>` and `<figcaption>` 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 `<iframe srcdoc>` with an empty `sandbox` attribute, so no scripts run and its origin is opaque. It has `referrerpolicy="no-referrer"` and a Content-Security-Policy meta (`PREVIEW_CSP`) that allows only inline styles and images. The preview copy leaves out `script`, `iframe`, `frame`, `frameset`, `object`, `embed`, `meta`, `base` and `link` elements and event handler attributes. YouTube placeholders show as thumbnail cards loaded from img.youtube.com, never as a player; these and the post's own images are the only network traffic the pane makes. The styling is post-body typography, with the `--c-*` values read from the element at render time or neutral defaults. Previewing never fires `summer-change` and never changes the value, so an untouched post is still saved byte for byte.
|
||||
- **Headings (J1).** The element reads `headingLevels` from its `options` (the field types serve them per form request, see [headings and links](#headings-and-links)): `[2, 3, 4]` while the H1 setting is on, when the toolbar offers H2 to H4 and a pasted or loaded `<h1>` is parsed as an H2, so the editor never holds an H1; `[1, 2, 3, 4]` while it is off, with an H1 button first. Stored H5 and H6 still parse. The Source tab accepts any HTML; the server decides what is stored.
|
||||
- **Outline (J2).** A full-width bar between the editor and the status line shows the heading count and, when there are any, the problem count; it starts collapsed and never takes focus. Opened, it lists the headings in document order with their level, indented 12px per level, and flags a skipped level (the page title is the H1), an empty heading, a heading that is only a link and, while the H1 setting is on, an H1 in the Source tab; then the links whose whole text is on the generic list (`genericAnchors` option). It recomputes 300 ms (`OUTLINE_DEBOUNCE_MS`) after a change, from the Source text in the Source tab. Activating a heading puts the caret in it. It never edits the content.
|
||||
@@ -306,7 +306,7 @@ The plugin registers two admin form field types (`journal.Plugin.FormFieldTypes`
|
||||
| `blogeditor` | One HTML string in a host column (category content). | `uploadFolder` |
|
||||
| `mlblogeditor` | One HTML string per content locale, stored like `mlmarkdown`: the default locale in the host column, the others as translations (post content). | `htmlColumn`, `uploadFolder` |
|
||||
|
||||
Both types also serve two options per form request (`pact.FormFieldType.RequestOptions`): `headingLevels` (`[2, 3, 4]` while the H1 setting is on, `[1, 2, 3, 4]` while it is off) and `genericAnchors` (the settings' generic link texts, `classes.GenericAnchors`). A `fields.yaml` option of the same name wins.
|
||||
Both types also serve three options per form request (`pact.FormFieldType.RequestOptions`): `headingLevels` (`[2, 3, 4]` while the H1 setting is on, `[1, 2, 3, 4]` while it is off), `genericAnchors` (the settings' generic link texts, `classes.GenericAnchors`), and `embedProviders` (the registered embed provider descriptors from `classes.EmbedRegistryFrom(app)`). A `fields.yaml` option of the same name wins.
|
||||
|
||||
Both types show the element's Preview pane, and previewing never changes what a save stores.
|
||||
|
||||
@@ -435,6 +435,38 @@ The request is a `POST` to the URL with `Authorization: Bearer <token>`, `Conten
|
||||
|-----|----------------------|-------|
|
||||
| `golem15.journal.tag_pages` | `SUMMER_GOLEM15__JOURNAL__TAG_PAGES` | Whether the host site has tag pages, default `true`. With `false`, `journal-tag` items resolve to nothing, tag descriptions carry empty URLs and tag paths never match, for sites whose frontend turns tag routes off. |
|
||||
|
||||
### Embed providers
|
||||
|
||||
The Journal plugin pre-registers `youtube` (`id_pattern: ^[A-Za-z0-9_-]{11}$`, `mode: url`) on an app-scoped `*classes.EmbedRegistry` published on `backpack.App` during `Plugin.Register`. Applications can declare additional custom embed providers in YAML under `golem15.journal.embed_providers` (merged during `Plugin.Boot`) and/or register them programmatically in Go via `classes.EmbedRegistryFrom(app).Register(...)`:
|
||||
|
||||
```yaml
|
||||
# config/golem15/journal.yaml (or under golem15.journal in config)
|
||||
embed_providers:
|
||||
viz:
|
||||
name: "Interactive Chart"
|
||||
id_pattern: "^[a-z0-9][a-z0-9-]{0,63}$"
|
||||
mode: "id"
|
||||
placeholder: "acme-chart-slug"
|
||||
```
|
||||
|
||||
```go
|
||||
if reg := classes.EmbedRegistryFrom(app); reg != nil {
|
||||
if err := reg.Register(classes.EmbedProvider{
|
||||
Key: "viz",
|
||||
Name: "Interactive Chart",
|
||||
IDPattern: `^[a-z0-9][a-z0-9-]{0,63}$`,
|
||||
Mode: classes.EmbedModeID,
|
||||
Placeholder: "acme-chart-slug",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- **Boot validation.** Provider keys must match `^[a-z][a-z0-9_-]{0,31}$`, `id_pattern` must compile as a Go regular expression (automatically anchored with `^(?:...)$`), and `mode` must be `"url"` or `"id"` (default `"id"`). Invalid definitions fail boot with an error naming the provider.
|
||||
- **Pair-aware HTML sanitization.** `FormatHTML`, `SanitizeHTML`, `SanitizeHTMLReport`, and `CheckHTML` (both registry-scoped and default package-level helpers) validate `(data-embed, data-id)` as a pair on `<figure>` so an ID valid for `viz` is never accepted on `data-embed="youtube"` or vice versa. Optional CLS-reservation hints `data-aspect` (`^[1-9][0-9]{0,3}(?:\s*/\s*[1-9][0-9]{0,3}|\.[0-9]{1,4})?$`) and `data-height` (`^[1-9][0-9]{0,3}(?:px)?$`) are allowed only on `<figure>` elements with a valid `(data-embed, data-id)` pair; invalid or mismatched attributes are stripped and reported in `SanitizeHTMLReport` / rejected by `CheckHTML`.
|
||||
- **Static fallback children.** Fallback markup inside `<figure data-embed="...">` (such as `<img src="/media/..." alt="...">` and `<figcaption>`) is sanitized by the standard UGC policy, stripping `<script>`, `<style>`, `<iframe>`, `<svg>`, event handlers, and unsafe URLs while preserving responsive Media Library fallback images (`classes.EnrichMediaHTML` enriches `/media/<short-id>/...` fallbacks automatically).
|
||||
|
||||
## API reference
|
||||
|
||||
| Identifier | Description |
|
||||
@@ -481,7 +513,9 @@ The request is a `POST` to the URL with `Authorization: Bearer <token>`, `Conten
|
||||
| `models.Settings` | Singleton settings row; `TableName` is `golem15_journal_settings`; `ContentH1ToH2` and `GenericAnchors` hold the Headings and links tab. |
|
||||
| `models.All` | Models registered by this plugin. |
|
||||
| `updates.All` | gormigrate steps registered by this plugin. |
|
||||
| `classes.BlogEditorTypes` | The `blogeditor` and `mlblogeditor` field types: Decode through `SanitizeHTMLReport` with removal notices and, while the H1 setting is on, `ConvertH1` with the conversion notice; Load with the markdown fallback, list text, the image upload and the per-request `headingLevels` and `genericAnchors` options. |
|
||||
| `classes.BlogEditorTypes` | The `blogeditor` and `mlblogeditor` field types: Decode through `SanitizeHTMLReport` with removal notices and, while the H1 setting is on, `ConvertH1` with the conversion notice; Load with the markdown fallback, list text, the image upload and the per-request `headingLevels`, `genericAnchors`, and `embedProviders` options. |
|
||||
| `classes.EmbedRegistry`, `classes.NewEmbedRegistry`, `classes.EmbedRegistryFrom` | Thread-safe app-scoped embed provider registry (pre-populated with `youtube`), YAML boot loader (`LoadFromConfig`), pair-aware HTML sanitization methods (`FormatHTML`, `SanitizeHTML`, `SanitizeHTMLReport`, `FormatTranslation`, `CheckHTML`), and `EditorDescriptors` for the Blog Editor. |
|
||||
| `classes.EmbedProvider`, `classes.EmbedProviderDescriptor`, `classes.EmbedProvidersConfigKey`, `classes.EmbedModeURL`, `classes.EmbedModeID` | Embed provider definition, Blog Editor JSON descriptor, YAML config key `golem15.journal.embed_providers`, and input mode constants. |
|
||||
| `classes.EditorH1Converted`, `classes.EditorH1ConvertedCategory` | The phrase keys of the H1 conversion notice for a post and for a category. |
|
||||
| `classes.H1ToH2Key` | `golem15.journal.content_h1_to_h2`, the config key of the H1 setting when no settings row exists. |
|
||||
| `classes.EffectiveH1ToH2` | The one reader of the H1 setting: the settings row, else the config key, else true. |
|
||||
|
||||
443
classes/embed_registry_test.go
Normal file
443
classes/embed_registry_test.go
Normal file
@@ -0,0 +1,443 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
)
|
||||
|
||||
func openEmbedYAMLConfig(t *testing.T, yamlBody string) *compass.Config {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "golem15.yaml"), []byte(yamlBody), 0o600); err != nil {
|
||||
t.Fatalf("write golem15.yaml: %v", err)
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{}})
|
||||
if err != nil {
|
||||
t.Fatalf("compass.Open: %v", err)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func TestEmbedRegistryDefaultAndRegistration(t *testing.T) {
|
||||
t.Run("default registry has youtube only", func(t *testing.T) {
|
||||
reg := NewEmbedRegistry()
|
||||
providers := reg.Providers()
|
||||
if len(providers) != 1 || providers[0].Key != "youtube" {
|
||||
t.Fatalf("Providers() = %+v, want [youtube]", providers)
|
||||
}
|
||||
if providers[0].Mode != EmbedModeURL {
|
||||
t.Fatalf("youtube Mode = %q, want %q", providers[0].Mode, EmbedModeURL)
|
||||
}
|
||||
if !reg.Match("youtube", "dQw4w9WgXcQ") {
|
||||
t.Fatal("expected youtube to match valid 11-char ID")
|
||||
}
|
||||
if reg.Match("viz", "demo-chart") {
|
||||
t.Fatal("expected unregistered provider to not match")
|
||||
}
|
||||
if got := EmbedRegistryFrom(nil); got != defaultEmbedRegistry {
|
||||
t.Fatal("EmbedRegistryFrom(nil) did not return defaultEmbedRegistry")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("Go registration adds custom providers and defaults mode to id", func(t *testing.T) {
|
||||
reg := NewEmbedRegistry()
|
||||
if err := reg.Register(EmbedProvider{
|
||||
Key: "viz",
|
||||
Name: "Interactive Visualization",
|
||||
IDPattern: `[a-z0-9][a-z0-9-]{0,63}`,
|
||||
Placeholder: "my-chart-id",
|
||||
}); err != nil {
|
||||
t.Fatalf("Register(viz): %v", err)
|
||||
}
|
||||
if err := reg.Register(EmbedProvider{
|
||||
Key: "calc",
|
||||
IDPattern: `^[a-z]+_[0-9]+$`,
|
||||
}); err != nil {
|
||||
t.Fatalf("Register(calc): %v", err)
|
||||
}
|
||||
providers := reg.Providers()
|
||||
if len(providers) != 3 {
|
||||
t.Fatalf("len(Providers) = %d, want 3", len(providers))
|
||||
}
|
||||
// Deterministic order: youtube first, then sorted keys.
|
||||
gotKeys := []string{providers[0].Key, providers[1].Key, providers[2].Key}
|
||||
if !slices.Equal(gotKeys, []string{"youtube", "calc", "viz"}) {
|
||||
t.Fatalf("provider order = %v, want [youtube calc viz]", gotKeys)
|
||||
}
|
||||
if providers[1].Name != "calc" || providers[1].Mode != EmbedModeID {
|
||||
t.Fatalf("calc defaults: %+v", providers[1])
|
||||
}
|
||||
if !reg.Match("viz", "lions-mane-studies") {
|
||||
t.Fatal("expected viz to match lions-mane-studies")
|
||||
}
|
||||
// Anchoring check: partial match must fail even when IDPattern was unanchored.
|
||||
if reg.Match("viz", "lions-mane-studies!") || reg.Match("viz", "BAD/lions-mane-studies") {
|
||||
t.Fatal("expected unanchored partial match to be rejected")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("YAML golem15.journal.embed_providers merges cleanly", func(t *testing.T) {
|
||||
cfg := openEmbedYAMLConfig(t, `
|
||||
journal:
|
||||
embed_providers:
|
||||
viz:
|
||||
name: "Interactive Chart"
|
||||
id_pattern: "^[a-z0-9][a-z0-9-]{0,63}$"
|
||||
mode: "id"
|
||||
placeholder: "chart-slug"
|
||||
acme_widget:
|
||||
id_pattern: "^w-[0-9]{1,6}$"
|
||||
`)
|
||||
reg := NewEmbedRegistry()
|
||||
if err := reg.LoadFromConfig(cfg); err != nil {
|
||||
t.Fatalf("LoadFromConfig: %v", err)
|
||||
}
|
||||
if !reg.Match("youtube", "dQw4w9WgXcQ") {
|
||||
t.Fatal("expected youtube to remain registered after YAML merge")
|
||||
}
|
||||
if !reg.Match("viz", "beta-glucans-2026") {
|
||||
t.Fatal("expected viz from YAML to match")
|
||||
}
|
||||
if !reg.Match("acme_widget", "w-42") {
|
||||
t.Fatal("expected acme_widget from YAML to match")
|
||||
}
|
||||
descs := reg.EditorDescriptors()
|
||||
if len(descs) != 3 || descs[0].Key != "youtube" || descs[1].Key != "acme_widget" || descs[2].Key != "viz" {
|
||||
t.Fatalf("EditorDescriptors = %+v", descs)
|
||||
}
|
||||
if descs[2].Name != "Interactive Chart" || descs[2].Placeholder != "chart-slug" || descs[2].Mode != EmbedModeID {
|
||||
t.Fatalf("viz descriptor = %+v", descs[2])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid keys, regexes, and modes fail loudly naming the provider", func(t *testing.T) {
|
||||
reg := NewEmbedRegistry()
|
||||
badProviders := []struct {
|
||||
name string
|
||||
p EmbedProvider
|
||||
want string
|
||||
}{
|
||||
{"path traversal key", EmbedProvider{Key: "../x", IDPattern: `^[a-z]+$`}, "../x"},
|
||||
{"uppercase key", EmbedProvider{Key: "YouTube", IDPattern: `^[a-z]+$`}, "YouTube"},
|
||||
{"empty key", EmbedProvider{Key: "", IDPattern: `^[a-z]+$`}, `""`},
|
||||
{"missing pattern", EmbedProvider{Key: "viz", IDPattern: ""}, "viz"},
|
||||
{"invalid regex", EmbedProvider{Key: "viz", IDPattern: `[unclosed`}, "viz"},
|
||||
{"invalid mode", EmbedProvider{Key: "viz", IDPattern: `^[a-z]+$`, Mode: "iframe"}, "viz"},
|
||||
}
|
||||
for _, tc := range badProviders {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := reg.Register(tc.p)
|
||||
if err == nil {
|
||||
t.Fatalf("Register(%+v) = nil, want error", tc.p)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("error %q does not name %q", err.Error(), tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// YAML boot failure on invalid regex / invalid key / invalid mode.
|
||||
yamlBad := []struct {
|
||||
name string
|
||||
yaml string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "bad regex in yaml",
|
||||
yaml: "journal:\n embed_providers:\n broken_viz:\n id_pattern: \"[bad\"\n",
|
||||
want: "broken_viz",
|
||||
},
|
||||
{
|
||||
name: "bad key in yaml",
|
||||
yaml: "journal:\n embed_providers:\n BadKey:\n id_pattern: \"^[a-z]+$\"\n",
|
||||
want: "BadKey",
|
||||
},
|
||||
{
|
||||
name: "bad mode in yaml",
|
||||
yaml: "journal:\n embed_providers:\n calc:\n id_pattern: \"^[a-z]+$\"\n mode: \"script\"\n",
|
||||
want: "calc",
|
||||
},
|
||||
{
|
||||
name: "non-map providers",
|
||||
yaml: "journal:\n embed_providers: \"not-a-map\"\n",
|
||||
want: EmbedProvidersConfigKey,
|
||||
},
|
||||
}
|
||||
for _, tc := range yamlBad {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := openEmbedYAMLConfig(t, tc.yaml)
|
||||
r := NewEmbedRegistry()
|
||||
err := r.LoadFromConfig(cfg)
|
||||
if err == nil {
|
||||
t.Fatalf("LoadFromConfig(%s) = nil, want error", tc.name)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("error %q does not mention %q", err.Error(), tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestEmbedRegistryPairAwareSanitizationAndFallbackXSS(t *testing.T) {
|
||||
reg := NewEmbedRegistry()
|
||||
if err := reg.Register(EmbedProvider{
|
||||
Key: "viz",
|
||||
Name: "Visualization",
|
||||
IDPattern: `^[a-z0-9][a-z0-9-]{0,63}$`,
|
||||
Mode: EmbedModeID,
|
||||
}); err != nil {
|
||||
t.Fatalf("Register(viz): %v", err)
|
||||
}
|
||||
|
||||
t.Run("valid custom embed with fallback img, figcaption, and data-aspect passes byte-for-byte", func(t *testing.T) {
|
||||
doc := `<figure data-embed="viz" data-id="lions-mane-studies" data-aspect="16/9"><img src="/media/abc123/chart.webp" alt="Chart" width="800" height="450"><figcaption>Caption</figcaption></figure>`
|
||||
if got := reg.SanitizeHTML(doc); got != doc {
|
||||
t.Fatalf("SanitizeHTML:\n got %q\nwant %q", got, doc)
|
||||
}
|
||||
got, report := reg.SanitizeHTMLReport(doc)
|
||||
if got != doc || !report.Empty() {
|
||||
t.Fatalf("SanitizeHTMLReport: got=%q report=%+v, want unchanged & empty report", got, report)
|
||||
}
|
||||
if err := reg.CheckHTML(doc); err != nil {
|
||||
t.Fatalf("CheckHTML = %v, want nil", err)
|
||||
}
|
||||
formatted, err := reg.FormatHTML(doc)
|
||||
if err != nil {
|
||||
t.Fatalf("FormatHTML err = %v", err)
|
||||
}
|
||||
if strings.TrimSpace(formatted) != doc {
|
||||
t.Fatalf("FormatHTML:\n got %q\nwant %q", strings.TrimSpace(formatted), doc)
|
||||
}
|
||||
assertNoActiveContent(t, formatted)
|
||||
})
|
||||
|
||||
t.Run("valid data-height passes", func(t *testing.T) {
|
||||
for _, h := range []string{"420", "420px"} {
|
||||
doc := `<figure data-embed="viz" data-id="demo-1" data-height="` + h + `"></figure>`
|
||||
if got := reg.SanitizeHTML(doc); got != doc {
|
||||
t.Fatalf("data-height=%q: got %q, want %q", h, got, doc)
|
||||
}
|
||||
if err := reg.CheckHTML(doc); err != nil {
|
||||
t.Fatalf("data-height=%q: CheckHTML = %v", h, err)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("cross-provider mismatch strips data-embed and data-id and fails CheckHTML", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "viz ID on youtube",
|
||||
in: `<figure data-embed="youtube" data-id="lions-mane-studies"></figure>`,
|
||||
want: `<figure></figure>`,
|
||||
},
|
||||
{
|
||||
name: "youtube ID with uppercase on viz",
|
||||
in: `<figure data-embed="viz" data-id="dQw4w9WgXcQ"></figure>`,
|
||||
want: `<figure></figure>`,
|
||||
},
|
||||
{
|
||||
name: "mismatch also strips data-aspect and data-height",
|
||||
in: `<figure data-embed="youtube" data-id="lions-mane-studies" data-aspect="16/9" data-height="420px"></figure>`,
|
||||
want: `<figure></figure>`,
|
||||
},
|
||||
{
|
||||
name: "orphan data-aspect without embed pair",
|
||||
in: `<figure data-aspect="16/9"><img src="/media/a/b.webp" alt="x"></figure>`,
|
||||
want: `<figure><img src="/media/a/b.webp" alt="x"></figure>`,
|
||||
},
|
||||
{
|
||||
name: "orphan data-height without embed pair",
|
||||
in: `<figure data-height="420px"></figure>`,
|
||||
want: `<figure></figure>`,
|
||||
},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got, report := reg.SanitizeHTMLReport(tc.in)
|
||||
if got != tc.want {
|
||||
t.Fatalf("SanitizeHTMLReport:\n got %q\nwant %q", got, tc.want)
|
||||
}
|
||||
if report.Empty() || report.AttributeCount == 0 {
|
||||
t.Fatalf("expected removed attributes in report, got %+v", report)
|
||||
}
|
||||
if err := reg.CheckHTML(tc.in); err == nil {
|
||||
t.Fatalf("CheckHTML(%q) = nil, want error", tc.in)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("CSS-injection data-aspect and data-height are stripped while valid embed survives", func(t *testing.T) {
|
||||
badAspects := []string{
|
||||
`16/9; background:url(javascript:alert(1))`,
|
||||
`expression(alert(1))`,
|
||||
`0/9`,
|
||||
`auto`,
|
||||
}
|
||||
for _, bad := range badAspects {
|
||||
in := `<figure data-embed="viz" data-id="ok-id" data-aspect="` + bad + `"></figure>`
|
||||
got, report := reg.SanitizeHTMLReport(in)
|
||||
want := `<figure data-embed="viz" data-id="ok-id"></figure>`
|
||||
if got != want {
|
||||
t.Fatalf("bad data-aspect %q: got %q, want %q", bad, got, want)
|
||||
}
|
||||
if !slices.Contains(report.Attributes, "data-aspect") {
|
||||
t.Fatalf("bad data-aspect %q: report.Attributes = %v", bad, report.Attributes)
|
||||
}
|
||||
if err := reg.CheckHTML(in); err == nil {
|
||||
t.Fatalf("bad data-aspect %q: CheckHTML = nil, want error", bad)
|
||||
}
|
||||
}
|
||||
|
||||
badHeights := []string{
|
||||
`-100px`,
|
||||
`420px; background:red`,
|
||||
`expression(alert(1))`,
|
||||
`100vh`,
|
||||
`0px`,
|
||||
}
|
||||
for _, bad := range badHeights {
|
||||
in := `<figure data-embed="viz" data-id="ok-id" data-height="` + bad + `"></figure>`
|
||||
got, report := reg.SanitizeHTMLReport(in)
|
||||
want := `<figure data-embed="viz" data-id="ok-id"></figure>`
|
||||
if got != want {
|
||||
t.Fatalf("bad data-height %q: got %q, want %q", bad, got, want)
|
||||
}
|
||||
if !slices.Contains(report.Attributes, "data-height") {
|
||||
t.Fatalf("bad data-height %q: report.Attributes = %v", bad, report.Attributes)
|
||||
}
|
||||
if err := reg.CheckHTML(in); err == nil {
|
||||
t.Fatalf("bad data-height %q: CheckHTML = nil, want error", bad)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("XSS inside custom embed figure is stripped while safe fallback img and figcaption survive", func(t *testing.T) {
|
||||
in := `<figure data-embed="viz" data-id="ok-id" data-aspect="16/9">` +
|
||||
`<script>alert(1)</script>` +
|
||||
`<style>body{display:none}</style>` +
|
||||
`<iframe src="https://evil.test"></iframe>` +
|
||||
`<svg onload="alert(1)"><circle r="1"/></svg>` +
|
||||
`<img src="javascript:alert(1)" alt="bad">` +
|
||||
`<img src="/media/abc/safe.webp" alt="Safe" onerror="alert(1)">` +
|
||||
`<figcaption>Safe caption</figcaption>` +
|
||||
`</figure>`
|
||||
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, `<img src="/media/abc/safe.webp" alt="Safe">`) {
|
||||
t.Fatalf("safe fallback img lost: %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `<figcaption>Safe caption</figcaption>`) {
|
||||
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 := `<figure data-embed="viz" data-id="chart-1"></figure>`
|
||||
acmeHTML := `<figure data-embed="acme" data-id="acme-42"></figure>`
|
||||
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 != `<figure></figure>` {
|
||||
t.Errorf("regA leaked acme: %q", got)
|
||||
}
|
||||
}
|
||||
}()
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
vizHTML := `<figure data-embed="viz" data-id="chart-1"></figure>`
|
||||
acmeHTML := `<figure data-embed="acme" data-id="acme-42"></figure>`
|
||||
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 != `<figure></figure>` {
|
||||
t.Errorf("regB leaked viz: %q", got)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -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('<p>a</p>')
|
||||
})
|
||||
})
|
||||
|
||||
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('<p>a</p>')
|
||||
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('<p>Intro</p>', { 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<HTMLSelectElement>('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(
|
||||
'<figure data-embed="viz" data-id="demo-1" data-aspect="4/3">' +
|
||||
'<img src="/media/abc123/fallback.webp" alt="Chart preview" width="800" height="450">' +
|
||||
'<figcaption>Figure 1</figcaption></figure>',
|
||||
)
|
||||
})
|
||||
|
||||
it('TipTap Embed node parses and round-trips custom embed with fallback without RawHtml', () => {
|
||||
const customHtml =
|
||||
'<figure data-embed="viz" data-id="demo-1" data-aspect="4/3">' +
|
||||
'<img src="/media/abc/fallback.webp" alt="Fallback">' +
|
||||
'<figcaption>Figure 1</figcaption></figure>'
|
||||
const docHtml = `<p>Before</p>${customHtml}${PLACEHOLDER}<p>After</p>`
|
||||
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(`<p>XBefore</p>${customHtml}${PLACEHOLDER}<p>After</p>`)
|
||||
})
|
||||
|
||||
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 =
|
||||
'<figure data-embed="viz" data-id="demo-1" data-aspect="16/9">' +
|
||||
'<img src="/media/abc/fallback.webp" alt="Fallback" width="800" height="450">' +
|
||||
'<figcaption>Figure 1</figcaption></figure>'
|
||||
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('<figcaption>Figure 1</figcaption>')
|
||||
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('<figure data-embed="viz" data-id="demo-2" data-height="420px"></figure>', labels, providers)
|
||||
expect(customNoFallback).toContain('Interactive Chart: demo-2 (420px)')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user