From 55ac26e0d3f6992d725e9cd98b38a8d8f58ac5a6 Mon Sep 17 00:00:00 2001 From: Jakub Zych Date: Sat, 28 Nov 2026 12:40:33 +0100 Subject: [PATCH] feat(journal): add EmbedRegistry, YAML boot config, and pair-aware sanitizer --- classes/blog_editor.go | 66 ++++--- classes/editor_policy_test.go | 22 +-- classes/embed_registry.go | 298 +++++++++++++++++++++++++++++++ classes/format_html.go | 238 +++++++++++++++++------- config/config.yaml | 14 ++ console/import_posts.go | 24 ++- controllers/api/posts.go | 8 +- controllers/api/posts_helpers.go | 17 +- controllers/posts.go | 7 +- plugin.go | 27 +++ 10 files changed, 603 insertions(+), 118 deletions(-) create mode 100644 classes/embed_registry.go diff --git a/classes/blog_editor.go b/classes/blog_editor.go index e3b50ea..7004530 100644 --- a/classes/blog_editor.go +++ b/classes/blog_editor.go @@ -90,6 +90,7 @@ var ( func BlogEditorTypes(app func() *backpack.App) []pact.FormFieldType { upload := uploadBlogImage(app) decode := decodeBlogHTMLFor(app) + load := loadBlogHTMLFor(app) options := blogRequestOptions(app) return []pact.FormFieldType{ { @@ -100,7 +101,7 @@ func BlogEditorTypes(app func() *backpack.App) []pact.FormFieldType { Options: []string{"uploadFolder"}, CheckOptions: checkBlogOptions, Decode: decode, - Load: loadBlogHTML, + Load: load, ListValue: blogListValue, Upload: upload, RequestOptions: options, @@ -114,7 +115,7 @@ func BlogEditorTypes(app func() *backpack.App) []pact.FormFieldType { Options: []string{"htmlColumn", "uploadFolder"}, CheckOptions: checkBlogOptions, Decode: decode, - Load: loadBlogHTML, + Load: load, ListValue: blogListValue, Upload: upload, RequestOptions: options, @@ -168,7 +169,8 @@ func checkUploadFolder(folder string) error { // or answer nil; the setting is then read from the database alone. func decodeBlogHTMLFor(app func() *backpack.App) func(context.Context, pact.FormFieldValue) (pact.FormFieldDecoded, error) { return func(ctx context.Context, in pact.FormFieldValue) (pact.FormFieldDecoded, error) { - out, err := decodeBlogHTML(ctx, in) + a := appInstance(app) + out, err := decodeBlogHTMLWith(ctx, in, EmbedRegistryFrom(a)) if err != nil { return out, err } @@ -201,12 +203,14 @@ func h1ConvertedNotice(record any) string { // blogRequestOptions is the Blog Editor types' RequestOptions (33-01 // P33-02, UI-SPEC C28): headingLevels, [2, 3, 4] while the H1 setting is on -// and [1, 2, 3, 4] while it is off (J1), and genericAnchors, the settings' -// generic link texts (J2, J3). Both are read per schema request, so a -// changed setting reaches the next form that opens. db may be nil; the +// and [1, 2, 3, 4] while it is off (J1), genericAnchors, the settings' +// generic link texts (J2, J3), and embedProviders, the registered embed +// providers from the app's EmbedRegistry. All are read per schema request, so +// a changed setting reaches the next form that opens. db may be nil; the // defaults then apply. fields.yaml options with the same names win. func blogRequestOptions(app func() *backpack.App) func(context.Context, *gorm.DB) (map[string]any, error) { return func(ctx context.Context, db *gorm.DB) (map[string]any, error) { + a := appInstance(app) levels := []int{2, 3, 4} if !EffectiveH1ToH2(ctx, db, appConfig(app)) { levels = []int{1, 2, 3, 4} @@ -214,29 +218,35 @@ func blogRequestOptions(app func() *backpack.App) func(context.Context, *gorm.DB return map[string]any{ "headingLevels": levels, "genericAnchors": GenericAnchors(ctx, db), + "embedProviders": EmbedRegistryFrom(a).EditorDescriptors(), }, nil } } +func appInstance(app func() *backpack.App) *backpack.App { + if app == nil { + return nil + } + return app() +} + // appConfig is the config of the application app answers, nil when there // is none. func appConfig(app func() *backpack.App) *compass.Config { - if app == nil { - return nil - } - a := app() + a := appInstance(app) if a == nil { return nil } return a.Config } -// decodeBlogHTML stores the HTML policy's output for a submitted value: the -// exact submitted bytes with no notice when the policy keeps everything, -// otherwise the stripped HTML with notices naming what was removed. nil -// decodes to the empty string; any other value that is not a string is -// refused. -func decodeBlogHTML(_ context.Context, in pact.FormFieldValue) (pact.FormFieldDecoded, error) { +// decodeBlogHTML stores the HTML policy's output for a submitted value using +// the default embed registry. +func decodeBlogHTML(ctx context.Context, in pact.FormFieldValue) (pact.FormFieldDecoded, error) { + return decodeBlogHTMLWith(ctx, in, defaultEmbedRegistry) +} + +func decodeBlogHTMLWith(_ context.Context, in pact.FormFieldValue, reg *EmbedRegistry) (pact.FormFieldDecoded, error) { var text string switch v := in.Value.(type) { case nil: @@ -246,7 +256,7 @@ func decodeBlogHTML(_ context.Context, in pact.FormFieldValue) (pact.FormFieldDe default: return pact.FormFieldDecoded{}, &pact.FormFieldError{Messages: []string{editorContentInvalid}} } - clean, report := SanitizeHTMLReport(text) + clean, report := reg.SanitizeHTMLReport(text) return pact.FormFieldDecoded{Value: clean, Notices: removalNotices(report)}, nil } @@ -304,7 +314,17 @@ func removalNames(names []string, cut bool) string { // - Any other value is markdown, served as the htmlColumn attribute, or as // FormatHTML of the value when that is empty or cannot be read (the // value itself when rendering fails). -func loadBlogHTML(_ context.Context, in pact.FormFieldValue) (any, error) { +func loadBlogHTMLFor(app func() *backpack.App) func(context.Context, pact.FormFieldValue) (any, error) { + return func(ctx context.Context, in pact.FormFieldValue) (any, error) { + return loadBlogHTMLWith(ctx, in, EmbedRegistryFrom(appInstance(app))) + } +} + +func loadBlogHTML(ctx context.Context, in pact.FormFieldValue) (any, error) { + return loadBlogHTMLWith(ctx, in, defaultEmbedRegistry) +} + +func loadBlogHTMLWith(_ context.Context, in pact.FormFieldValue, reg *EmbedRegistry) (any, error) { text := storedText(in.Value) column, _ := in.Options["htmlColumn"].(string) if column == "" { @@ -327,14 +347,14 @@ func loadBlogHTML(_ context.Context, in pact.FormFieldValue) (any, error) { } return text, nil case LooksLikeHTML(text): - if html == "" || sameStoredHTML(text, html) { + if html == "" || sameStoredHTMLWith(text, html, reg) { return text, nil } return html, nil case html != "": return html, nil } - rendered, err := FormatHTML(text) + rendered, err := reg.FormatHTML(text) if err != nil { return text, nil } @@ -346,8 +366,12 @@ func loadBlogHTML(_ context.Context, in pact.FormFieldValue) (any, error) { // white space at either end ignored. It is false when rendered came from // rendering text as markdown in a way that changed it. func sameStoredHTML(text, rendered string) bool { + return sameStoredHTMLWith(text, rendered, defaultEmbedRegistry) +} + +func sameStoredHTMLWith(text, rendered string, reg *EmbedRegistry) bool { rendered = strings.TrimSpace(rendered) - return rendered == strings.TrimSpace(text) || rendered == strings.TrimSpace(SanitizeHTML(text)) + return rendered == strings.TrimSpace(text) || rendered == strings.TrimSpace(reg.SanitizeHTML(text)) } // storedText is a stored column value as text: a string, a *string (nil is diff --git a/classes/editor_policy_test.go b/classes/editor_policy_test.go index 076c0d0..e87dea3 100644 --- a/classes/editor_policy_test.go +++ b/classes/editor_policy_test.go @@ -117,13 +117,13 @@ func TestEditorOutputPassesPolicy(t *testing.T) { stripped := []struct { name, in, want string }{ - {"other provider", `
`, `
`}, - {"provider with a suffix", `
`, `
`}, - {"id of 10 characters", `
`, `
`}, - {"id of 12 characters", `
`, `
`}, - {"id with a quote", `
`, `
`}, - {"id with a space", `
`, `
`}, - {"id with an angle bracket", `
`, `
`}, + {"other provider", `
`, `
`}, + {"provider with a suffix", `
`, `
`}, + {"id of 10 characters", `
`, `
`}, + {"id of 12 characters", `
`, `
`}, + {"id with a quote", `
`, `
`}, + {"id with a space", `
`, `
`}, + {"id with an angle bracket", `
`, `
`}, {"embed attributes on div", `
x
`, `
x
`}, {"embed attributes on img", ``, ``}, {"embed attributes on p", `

x

`, `

x

`}, @@ -135,10 +135,10 @@ func TestEditorOutputPassesPolicy(t *testing.T) { {"negative start", `
  1. a
`, `
  1. a
`}, {"start on ul", ``, ``}, {"alt on p", `

y

`, `

y

`}, - {"upper-case provider", `
`, `
`}, - {"provider with white space", `
`, `
`}, - {"empty id", `
`, `
`}, - {"id with a URL", `
`, `
`}, + {"upper-case provider", `
`, `
`}, + {"provider with white space", `
`, `
`}, + {"empty id", `
`, `
`}, + {"id with a URL", `
`, `
`}, {"iframe alone", ``, ``}, {"script inside the placeholder", `
`, editorPlaceholder}, {"embed attributes on section", `
x
`, `
x
`}, diff --git a/classes/embed_registry.go b/classes/embed_registry.go new file mode 100644 index 0000000..a27fc0c --- /dev/null +++ b/classes/embed_registry.go @@ -0,0 +1,298 @@ +package classes + +import ( + "fmt" + "regexp" + "slices" + "strings" + "sync" + + "git.golem15.com/golem15/summercms/modules/backpack" + "git.golem15.com/golem15/summercms/modules/compass" + "github.com/microcosm-cc/bluemonday" +) + +// EmbedProvidersConfigKey is the compass config path under which applications +// can declare custom Journal embed providers in YAML. +const EmbedProvidersConfigKey = "golem15.journal.embed_providers" + +// Embed provider input modes for the Blog Editor. +const ( + EmbedModeURL = "url" + EmbedModeID = "id" +) + +var ( + embedProviderKeyPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{0,31}$`) + embedAspectPattern = regexp.MustCompile(`^[1-9][0-9]{0,3}(?:\s*/\s*[1-9][0-9]{0,3}|\.[0-9]{1,4})?$`) + embedHeightPattern = regexp.MustCompile(`^[1-9][0-9]{0,3}(?:px)?$`) + + // defaultEmbedRegistry is the immutable youtube-only registry used when + // callers invoke package-level HTML helpers without a backpack.App. + defaultEmbedRegistry = NewEmbedRegistry() +) + +// EmbedProvider describes one allowed
+// provider in Journal HTML and the Blog Editor. +type EmbedProvider struct { + Key string + Name string + IDPattern string + Mode string // "url" or "id" (defaults to "id") + Placeholder string +} + +// EmbedProviderDescriptor is the JSON shape sent to the Blog Editor in +// RequestOptions under "embedProviders". +type EmbedProviderDescriptor struct { + Key string `json:"key"` + Name string `json:"name"` + IDPattern string `json:"idPattern"` + Mode string `json:"mode"` + Placeholder string `json:"placeholder,omitempty"` +} + +type compiledEmbedProvider struct { + provider EmbedProvider + re *regexp.Regexp +} + +// EmbedRegistry holds the registered embed providers for a Journal instance +// and caches the corresponding bluemonday HTML policy. +type EmbedRegistry struct { + mu sync.RWMutex + providers map[string]compiledEmbedProvider + policy *bluemonday.Policy +} + +// NewEmbedRegistry returns a new registry pre-populated with the built-in +// YouTube provider. +func NewEmbedRegistry() *EmbedRegistry { + r := &EmbedRegistry{ + providers: make(map[string]compiledEmbedProvider), + } + _ = r.Register(EmbedProvider{ + Key: "youtube", + Name: "YouTube", + IDPattern: `^[A-Za-z0-9_-]{11}$`, + Mode: EmbedModeURL, + }) + return r +} + +// EmbedRegistryFrom returns the *EmbedRegistry published on app, or the +// default youtube-only registry when app is nil or has none published. +func EmbedRegistryFrom(app *backpack.App) *EmbedRegistry { + if app != nil { + if reg, ok := app.Lookup[*EmbedRegistry](); ok && reg != nil { + return reg + } + } + return defaultEmbedRegistry +} + +// Register validates and adds or replaces an embed provider on r. +func (r *EmbedRegistry) Register(p EmbedProvider) error { + if r == nil { + return fmt.Errorf("embed provider: registry is nil") + } + p.Key = strings.TrimSpace(p.Key) + if !embedProviderKeyPattern.MatchString(p.Key) { + return fmt.Errorf("embed provider %q: key must match %s", p.Key, embedProviderKeyPattern.String()) + } + p.IDPattern = strings.TrimSpace(p.IDPattern) + if p.IDPattern == "" { + return fmt.Errorf("embed provider %q: id_pattern is required", p.Key) + } + if _, err := regexp.Compile(p.IDPattern); err != nil { + return fmt.Errorf("embed provider %q: invalid id_pattern %q: %w", p.Key, p.IDPattern, err) + } + anchored, err := regexp.Compile("^(?:" + p.IDPattern + ")$") + if err != nil { + return fmt.Errorf("embed provider %q: invalid id_pattern %q: %w", p.Key, p.IDPattern, err) + } + p.Mode = strings.TrimSpace(p.Mode) + if p.Mode == "" { + p.Mode = EmbedModeID + } + if p.Mode != EmbedModeURL && p.Mode != EmbedModeID { + return fmt.Errorf("embed provider %q: mode must be %q or %q, got %q", p.Key, EmbedModeURL, EmbedModeID, p.Mode) + } + p.Name = strings.TrimSpace(p.Name) + if p.Name == "" { + p.Name = p.Key + } + p.Placeholder = strings.TrimSpace(p.Placeholder) + + r.mu.Lock() + if r.providers == nil { + r.providers = make(map[string]compiledEmbedProvider) + } + r.providers[p.Key] = compiledEmbedProvider{provider: p, re: anchored} + r.policy = nil + r.mu.Unlock() + return nil +} + +// LoadFromConfig merges YAML embed providers declared under +// golem15.journal.embed_providers into r. Invalid provider keys, missing or +// uncompilable id_pattern values, or unknown modes return an error naming the +// provider. +func (r *EmbedRegistry) LoadFromConfig(cfg *compass.Config) error { + if cfg == nil { + return nil + } + raw, ok := cfg.Lookup(EmbedProvidersConfigKey) + if !ok || raw == nil { + return nil + } + entries, ok := raw.(map[string]any) + if !ok { + return fmt.Errorf("%s: expected a map of provider definitions", EmbedProvidersConfigKey) + } + if len(entries) == 0 { + return nil + } + keys := make([]string, 0, len(entries)) + for k := range entries { + keys = append(keys, k) + } + slices.Sort(keys) + + for _, key := range keys { + spec, ok := entries[key].(map[string]any) + if !ok { + return fmt.Errorf("%s.%s: expected a map", EmbedProvidersConfigKey, key) + } + name, err := optionalConfigString(spec, "name", key) + if err != nil { + return err + } + idPattern, err := optionalConfigString(spec, "id_pattern", key) + if err != nil { + return err + } + mode, err := optionalConfigString(spec, "mode", key) + if err != nil { + return err + } + placeholder, err := optionalConfigString(spec, "placeholder", key) + if err != nil { + return err + } + if err := r.Register(EmbedProvider{ + Key: key, + Name: name, + IDPattern: idPattern, + Mode: mode, + Placeholder: placeholder, + }); err != nil { + return err + } + } + return nil +} + +func optionalConfigString(m map[string]any, field, provider string) (string, error) { + v, exists := m[field] + if !exists || v == nil { + return "", nil + } + s, ok := v.(string) + if !ok { + return "", fmt.Errorf("embed provider %q: %s must be a string", provider, field) + } + return s, nil +} + +// Providers returns a deterministic snapshot of all registered providers: +// "youtube" first when present, followed by remaining providers sorted by key. +func (r *EmbedRegistry) Providers() []EmbedProvider { + compiled := r.snapshot() + out := make([]EmbedProvider, len(compiled)) + for i, cp := range compiled { + out[i] = cp.provider + } + return out +} + +// EditorDescriptors returns the JSON-serializable descriptors sent to the Blog +// Editor in RequestOptions. +func (r *EmbedRegistry) EditorDescriptors() []EmbedProviderDescriptor { + providers := r.Providers() + out := make([]EmbedProviderDescriptor, len(providers)) + for i, p := range providers { + out[i] = EmbedProviderDescriptor{ + Key: p.Key, + Name: p.Name, + IDPattern: p.IDPattern, + Mode: p.Mode, + Placeholder: p.Placeholder, + } + } + return out +} + +// Match reports whether provider is registered and id matches that provider's +// compiled IDPattern. +func (r *EmbedRegistry) Match(provider, id string) bool { + if r == nil { + r = defaultEmbedRegistry + } + r.mu.RLock() + cp, ok := r.providers[provider] + r.mu.RUnlock() + return ok && cp.re.MatchString(id) +} + +// Policy returns the cached *bluemonday.Policy for the currently registered +// providers, building it lazily on first use or after Register. +func (r *EmbedRegistry) Policy() *bluemonday.Policy { + if r == nil { + r = defaultEmbedRegistry + } + r.mu.RLock() + if r.policy != nil { + p := r.policy + r.mu.RUnlock() + return p + } + r.mu.RUnlock() + + r.mu.Lock() + defer r.mu.Unlock() + if r.policy == nil { + r.policy = newHTMLPolicyFor(r.snapshotLocked()) + } + return r.policy +} + +func (r *EmbedRegistry) snapshot() []compiledEmbedProvider { + if r == nil { + r = defaultEmbedRegistry + } + r.mu.RLock() + defer r.mu.RUnlock() + return r.snapshotLocked() +} + +func (r *EmbedRegistry) snapshotLocked() []compiledEmbedProvider { + keys := make([]string, 0, len(r.providers)) + hasYT := false + for k := range r.providers { + if k == "youtube" { + hasYT = true + continue + } + keys = append(keys, k) + } + slices.Sort(keys) + out := make([]compiledEmbedProvider, 0, len(r.providers)) + if hasYT { + out = append(out, r.providers["youtube"]) + } + for _, k := range keys { + out = append(out, r.providers[k]) + } + return out +} diff --git a/classes/format_html.go b/classes/format_html.go index a706c97..ef647b1 100644 --- a/classes/format_html.go +++ b/classes/format_html.go @@ -22,18 +22,19 @@ var ( goldmark.WithExtensions(extension.Footnote, extension.Table), goldmark.WithParserOptions(parser.WithAttribute()), // Winter's Markdown::parse passes raw HTML through, so imported HTML - // bodies round-trip (D-03, PHP parity); htmlPolicy then sanitizes the - // rendered result on every write path. + // bodies round-trip (D-03, PHP parity); the registry HTML policy then + // sanitizes the rendered result on every write path. goldmark.WithRendererOptions(html.WithUnsafe()), ) - // htmlPolicy is the allow-list for stored journal HTML. - htmlPolicy = newHTMLPolicy() + // htmlPolicy is the default youtube-only bluemonday policy. + htmlPolicy = defaultEmbedRegistry.Policy() ) -// newHTMLPolicy extends bluemonday's UGC policy only with what goldmark -// renders and what the imported posts and categories use. -func newHTMLPolicy() *bluemonday.Policy { +// newHTMLPolicyFor extends bluemonday's UGC policy only with what goldmark +// renders, what imported posts and categories use, and the registered embed +// providers. +func newHTMLPolicyFor(providers []compiledEmbedProvider) *bluemonday.Policy { p := bluemonday.UGCPolicy() // Winter neither adds nor requires rel="nofollow", so links keep their // stored form. @@ -54,14 +55,22 @@ func newHTMLPolicy() *bluemonday.Policy { p.AllowAttrs("dir").Matching(regexp.MustCompile(`(?i)^(ltr|rtl|auto)$`)).Globally() p.AllowAttrs("data-message-author-role", "data-message-id"). Matching(regexp.MustCompile(`^[A-Za-z0-9_-]+$`)).OnElements("div") - // Blog Editor output (Phase 16.2 D-05), exactly what the editor writes - // and nothing more; plan 02's editor-corpus.json pins it - // (TestEditorOutputPassesPolicy) and the site layer mirrors these rules. - // The embed placeholder
: - // the provider name and the 11-character video id, on figure only. The - // layer expands it; no iframe is ever stored. - p.AllowAttrs("data-embed").Matching(regexp.MustCompile(`^youtube$`)).OnElements("figure") - p.AllowAttrs("data-id").Matching(regexp.MustCompile(`^[A-Za-z0-9_-]{11}$`)).OnElements("figure") + // Embed placeholders:
. + // bluemonday validates each attribute independently against the union of + // registered providers and id patterns; enforceEmbedPairs then verifies + // that each figure's data-id matches its own data-embed provider's pattern. + if len(providers) > 0 { + keys := make([]string, len(providers)) + pats := make([]string, len(providers)) + for i, cp := range providers { + keys[i] = regexp.QuoteMeta(cp.provider.Key) + pats[i] = "(?:" + cp.provider.IDPattern + ")" + } + p.AllowAttrs("data-embed").Matching(regexp.MustCompile("^(?:" + strings.Join(keys, "|") + ")$")).OnElements("figure") + p.AllowAttrs("data-id").Matching(regexp.MustCompile("^(?:" + strings.Join(pats, "|") + ")$")).OnElements("figure") + p.AllowAttrs("data-aspect").Matching(embedAspectPattern).OnElements("figure") + p.AllowAttrs("data-height").Matching(embedHeightPattern).OnElements("figure") + } // The editor's alt field takes free text, which UGC's Paragraph pattern // cuts at ':', '?', '"' and more. bluemonday accepts an attribute when // any of its rules matches and escapes the value on output; alt carries @@ -78,30 +87,31 @@ func newHTMLPolicy() *bluemonday.Policy { } // FormatHTML converts journal post markdown to stored HTML using goldmark -// footnote, table, and attribute extensions. Raw HTML in the source passes -// through the renderer, as it does in Winter's Markdown::parse. The result is -// then sanitized with a bluemonday allow-list that strips, as Winter's -// Html::clean does, what it does not allow: script, style, iframe, object, -// embed, form, base and meta elements, event handler attributes, and URLs -// other than http, https, mailto and relative ones. HTML that the policy -// keeps whole is returned byte for byte, so imported bodies round-trip. It -// does not call cabana.RenderMarkdown, whose admin preview stays without -// unsafe HTML. +// footnote, table, and attribute extensions and the default embed registry. func FormatHTML(src string) (string, error) { + return defaultEmbedRegistry.FormatHTML(src) +} + +// FormatHTML converts journal post markdown to stored HTML using goldmark +// footnote, table, and attribute extensions, then sanitizes the result with +// r's policy and pair-aware embed validation. +func (r *EmbedRegistry) FormatHTML(src string) (string, error) { var buf bytes.Buffer if err := markdownEngine.Convert([]byte(strings.TrimSpace(src)), &buf); err != nil { return "", fmt.Errorf("journal: markdown: %w", err) } - return SanitizeHTML(buf.String()), nil + return r.SanitizeHTML(buf.String()), nil } -// SanitizeHTML filters doc, which is HTML and not markdown, through the -// FormatHTML allow-list and strips what the policy does not allow. HTML the -// policy keeps whole is returned byte for byte. It is the gate for -// content_html supplied without markdown, such as a translation that carries -// only content_html. It is the string half of SanitizeHTMLReport. +// SanitizeHTML filters doc through the default embed registry allow-list. func SanitizeHTML(doc string) string { - out, _ := SanitizeHTMLReport(doc) + return defaultEmbedRegistry.SanitizeHTML(doc) +} + +// SanitizeHTML filters doc, which is HTML and not markdown, through r's +// allow-list and strips what the policy does not allow. +func (r *EmbedRegistry) SanitizeHTML(doc string) string { + out, _ := r.SanitizeHTMLReport(doc) return out } @@ -156,17 +166,23 @@ func addRemovalName(names []string, cut bool, name string) ([]string, bool) { return append(names, name), cut } -// SanitizeHTMLReport is SanitizeHTML with a report of what the policy -// removed. HTML the policy keeps whole is returned byte for byte with an -// empty report. Otherwise the policy's output is returned and the report is -// built by aligning the start tags of doc with those of the output in order -// (the policy only removes, it never adds or reorders): an input tag without -// a counterpart is a removed element, and an attribute of a matched tag that -// the output lacks or holds with another value is a removed attribute. -// Comments are counted on their own. The report is empty exactly when the -// returned string equals doc. +// SanitizeHTMLReport is SanitizeHTML with a report of what the default policy +// removed. func SanitizeHTMLReport(doc string) (string, HTMLRemovals) { - clean, changed := sanitizeHTML(doc) + return defaultEmbedRegistry.SanitizeHTMLReport(doc) +} + +// SanitizeHTMLReport is SanitizeHTML with a report of what r's policy removed. +// HTML the policy keeps whole is returned byte for byte with an empty report. +// Otherwise the policy's output is returned and the report is built by +// aligning the start tags of doc with those of the output in order (the policy +// only removes, it never adds or reorders): an input tag without a counterpart +// is a removed element, and an attribute of a matched tag that the output +// lacks or holds with another value is a removed attribute. Comments are +// counted on their own. The report is empty exactly when the returned string +// equals doc. +func (r *EmbedRegistry) SanitizeHTMLReport(doc string) (string, HTMLRemovals) { + clean, changed := r.sanitizeHTML(doc) if !changed || clean == doc { return doc, HTMLRemovals{} } @@ -293,20 +309,26 @@ func alignTags(in, out []reportTag, same func(in, out reportTag) bool) []int { return match } +// FormatTranslation sets attrs["content_html"] for one locale's translated +// post attributes using the default embed registry. +func FormatTranslation(attrs map[string]any) error { + return defaultEmbedRegistry.FormatTranslation(attrs) +} + // FormatTranslation sets attrs["content_html"] for one locale's translated // post attributes, so a translated content_html is stored under the same // policy as the host column. When attrs["content"] is not blank, content_html -// is rendered from it with FormatHTML and a supplied content_html is +// is rendered from it with r.FormatHTML and a supplied content_html is // replaced, as the host column is always derived from content. Otherwise a -// supplied, non-null content_html is sanitized with SanitizeHTML; a value +// supplied, non-null content_html is sanitized with r.SanitizeHTML; a value // that is not a string is sanitized as its text form. attrs without content // or content_html is left unchanged. -func FormatTranslation(attrs map[string]any) error { +func (r *EmbedRegistry) FormatTranslation(attrs map[string]any) error { if attrs == nil { return nil } if content := textOf(attrs["content"]); strings.TrimSpace(content) != "" { - html, err := FormatHTML(content) + html, err := r.FormatHTML(content) if err != nil { return err } @@ -314,7 +336,7 @@ func FormatTranslation(attrs map[string]any) error { return nil } if v, has := attrs["content_html"]; has && v != nil { - attrs["content_html"] = SanitizeHTML(textOf(v)) + attrs["content_html"] = r.SanitizeHTML(textOf(v)) } return nil } @@ -330,33 +352,127 @@ func textOf(v any) string { } } -// CheckHTML reports whether the FormatHTML allow-list would remove or -// change any element, attribute or text in doc: it returns an error when it -// would, nil when the policy keeps doc whole. Since Phase 16.2 no admin or -// API write path refuses with it (admin saves strip and report through -// SanitizeHTMLReport, D-10 amended); it is the predicate counterpart of the -// site layer's isSafeJournalHtml, and the policy cross-check tests use it. +// CheckHTML reports whether the default FormatHTML allow-list would remove or +// change any element, attribute or text in doc. func CheckHTML(doc string) error { - if _, changed := sanitizeHTML(doc); changed { + return defaultEmbedRegistry.CheckHTML(doc) +} + +// CheckHTML reports whether r's allow-list would remove or change any element, +// attribute or text in doc: it returns an error when it would, nil when the +// policy keeps doc whole. +func (r *EmbedRegistry) CheckHTML(doc string) error { + if _, changed := r.sanitizeHTML(doc); changed { return errors.New("journal: HTML contains elements, attributes or URLs that are not allowed") } return nil } -// sanitizeHTML returns doc unchanged when htmlPolicy keeps all of it, and the -// policy's output with changed set otherwise. Keeping all of it means doc and -// the policy output tokenize to the same HTML tokens, so an output that only -// re-escapes text or attribute values is not a change. A tag that repeats an -// attribute is always a change: the tokenizer keeps only the first of them, -// so the comparison would not see the others in the stored bytes. -func sanitizeHTML(doc string) (string, bool) { - clean := htmlPolicy.Sanitize(doc) +// sanitizeHTML returns doc unchanged when r's policy and pair-aware embed +// validation keep all of it, and the cleaned output with changed set otherwise. +func (r *EmbedRegistry) sanitizeHTML(doc string) (string, bool) { + if r == nil { + r = defaultEmbedRegistry + } + clean := r.Policy().Sanitize(doc) + clean = enforceEmbedPairs(clean, r) if sameTokens(doc, clean) { return doc, false } return clean, true } +// enforceEmbedPairs verifies that every
carrying embed attributes +// has a valid (data-embed, data-id) pair matching that provider's compiled +// pattern on reg. When mismatched or incomplete (or when data-aspect / +// data-height appear without a valid embed pair), those embed attributes are +// stripped from the
start tag while all other attributes and children +// remain intact. +func enforceEmbedPairs(doc string, reg *EmbedRegistry) string { + if !strings.Contains(doc, "' || next == '/' || isHTMLSpace(next) +} + // sameTokens reports whether a and b tokenize to the same sequence of HTML // tokens: type, tag name or decoded text, and the set of decoded attributes. // It is false when either repeats an attribute in a tag. diff --git a/config/config.yaml b/config/config.yaml index 1ecfd78..c53f4b9 100644 --- a/config/config.yaml +++ b/config/config.yaml @@ -28,3 +28,17 @@ related_count: 3 # override takes a comma-separated list, e.g. # SUMMER_GOLEM15__JOURNAL__IMAGE_WIDTHS=480,960. image_widths: [480, 800, 1200] + +# Custom embed providers for
. +# "youtube" is always pre-registered. Additional providers declared here are +# merged at boot alongside providers registered via classes.EmbedRegistry on +# backpack.App. +# +# Example: +# embed_providers: +# chart: +# name: Interactive Chart +# id_pattern: "^[a-z0-9][a-z0-9-]{0,63}$" +# mode: id +# placeholder: "monthly-revenue-2026" +embed_providers: {} diff --git a/console/import_posts.go b/console/import_posts.go index 9d206d6..a8b8519 100644 --- a/console/import_posts.go +++ b/console/import_posts.go @@ -69,7 +69,7 @@ failed".`, path := flagOrDefault(in, "path", defaultExportPath) force := flagOn(in, "force") dry := flagOn(in, "dry-run") - stats, err := ImportFromDirConfig(ctx, mustDB(app), appConfig(app), path, force, dry, out, nil) + stats, err := ImportFromDirApp(ctx, mustDB(app), app, path, force, dry, out, nil) if err != nil { return err } @@ -98,6 +98,16 @@ func ImportFromDir(ctx context.Context, gdb *gorm.DB, dir string, force, dry boo // setting is on, every H1 the import stores becomes an H2, counted in // ImportStats.H1Converted. func ImportFromDirConfig(ctx context.Context, gdb *gorm.DB, cfg *compass.Config, dir string, force, dry bool, out bonfire.Output, guard ImportGuard) (ImportStats, error) { + return importFromDirWith(ctx, gdb, cfg, classes.EmbedRegistryFrom(nil), dir, force, dry, out, guard) +} + +// ImportFromDirApp is ImportFromDirConfig using app's config and registered +// EmbedRegistry for HTML sanitization. +func ImportFromDirApp(ctx context.Context, gdb *gorm.DB, app *backpack.App, dir string, force, dry bool, out bonfire.Output, guard ImportGuard) (ImportStats, error) { + return importFromDirWith(ctx, gdb, appConfig(app), classes.EmbedRegistryFrom(app), dir, force, dry, out, guard) +} + +func importFromDirWith(ctx context.Context, gdb *gorm.DB, cfg *compass.Config, reg *classes.EmbedRegistry, dir string, force, dry bool, out bonfire.Output, guard ImportGuard) (ImportStats, error) { var stats ImportStats if gdb == nil { return stats, fmt.Errorf("journal: database is not configured") @@ -142,7 +152,7 @@ func ImportFromDirConfig(ctx context.Context, gdb *gorm.DB, cfg *compass.Config, stats.Failed++ continue } - result, converted, err := importPost(ctx, tx, data, force, dry, h1ToH2, out, guard) + result, converted, err := importPost(ctx, tx, reg, data, force, dry, h1ToH2, out, guard) if err != nil { return err } @@ -174,7 +184,7 @@ func ImportFromDirConfig(ctx context.Context, gdb *gorm.DB, cfg *compass.Config, // importPost writes one post file. converted is the number of H1 headings // stored as H2 (h1ToH2 on); a dry run converts nothing. -func importPost(ctx context.Context, db *gorm.DB, data PostFile, force, dry, h1ToH2 bool, out bonfire.Output, guard ImportGuard) (string, int, error) { +func importPost(ctx context.Context, db *gorm.DB, reg *classes.EmbedRegistry, data PostFile, force, dry, h1ToH2 bool, out bonfire.Output, guard ImportGuard) (string, int, error) { var existing models.Post err := db.Where("slug = ?", data.Slug).Take(&existing).Error found := err == nil @@ -219,7 +229,7 @@ func importPost(ctx context.Context, db *gorm.DB, data PostFile, force, dry, h1T return "failed", 0, err } } - html, err := classes.FormatHTML(post.Content) + html, err := reg.FormatHTML(post.Content) if err != nil { return "failed", 0, err } @@ -240,7 +250,7 @@ func importPost(ctx context.Context, db *gorm.DB, data PostFile, force, dry, h1T if err := syncCategories(ctx, db, post, data, out); err != nil { return "failed", 0, err } - n, err := syncTranslations(ctx, db, post, data.Translations, h1ToH2) + n, err := syncTranslations(ctx, db, reg, post, data.Translations, h1ToH2) if err != nil { return "failed", 0, err } @@ -351,7 +361,7 @@ func titleFromSlug(slug string) string { // syncTranslations writes the file's translations and returns the number // of H1 headings stored as H2 (h1ToH2 on). -func syncTranslations(ctx context.Context, db *gorm.DB, post *models.Post, translations map[string]map[string]any, h1ToH2 bool) (int, error) { +func syncTranslations(ctx context.Context, db *gorm.DB, reg *classes.EmbedRegistry, post *models.Post, translations map[string]map[string]any, h1ToH2 bool) (int, error) { if len(translations) == 0 { return 0, nil } @@ -360,7 +370,7 @@ func syncTranslations(ctx context.Context, db *gorm.DB, post *models.Post, trans for locale, attrs := range translations { // A translated content_html is derived from content or sanitized, // as the host column is; Winter's ImportPosts stored it verbatim. - if err := classes.FormatTranslation(attrs); err != nil { + if err := reg.FormatTranslation(attrs); err != nil { return 0, err } if h1ToH2 { diff --git a/controllers/api/posts.go b/controllers/api/posts.go index d7e52ab..639ef31 100644 --- a/controllers/api/posts.go +++ b/controllers/api/posts.go @@ -285,7 +285,7 @@ func Store(app *backpack.App) http.HandlerFunc { writeAPIError(w, http.StatusBadRequest, errValidationFailed) return } - post, verrs := buildNewPost(r, db.WithContext(r.Context()), pr, body) + post, verrs := buildNewPost(r, db.WithContext(r.Context()), app, pr, body) if verrs != nil { writeValidation(w, verrs) return @@ -305,7 +305,7 @@ func Store(app *backpack.App) http.HandlerFunc { if err := tx.Create(post).Error; err != nil { return err } - tags, err := applyPostAssocs(ctx, tx, post, body, h1) + tags, err := applyPostAssocs(ctx, tx, app, post, body, h1) if err != nil { return err } @@ -362,7 +362,7 @@ func Update(app *backpack.App) http.HandlerFunc { // D-92/D-102: the values before the write, for the RecordSaved // subscribers hear (a slug changed over MCP gets its redirect). before := snapshotPost(r.Context(), db.WithContext(r.Context()), post, body) - if verrs := applyPostUpdate(r, db.WithContext(r.Context()), post, body); verrs != nil { + if verrs := applyPostUpdate(r, db.WithContext(r.Context()), app, post, body); verrs != nil { writeValidation(w, verrs) return } @@ -383,7 +383,7 @@ func Update(app *backpack.App) http.HandlerFunc { if err := tx.Save(post).Error; err != nil { return err } - tags, err := applyPostAssocs(ctx, tx, post, body, h1) + tags, err := applyPostAssocs(ctx, tx, app, post, body, h1) if err != nil { return err } diff --git a/controllers/api/posts_helpers.go b/controllers/api/posts_helpers.go index 3848851..fabec67 100644 --- a/controllers/api/posts_helpers.go +++ b/controllers/api/posts_helpers.go @@ -500,7 +500,7 @@ func generateUniqueSlug(db *gorm.DB, title string, exceptID uint) string { } } -func buildNewPost(r *http.Request, db *gorm.DB, pr *bouncer.Principal, body map[string]any) (*models.Post, map[string][]string) { +func buildNewPost(r *http.Request, db *gorm.DB, app *backpack.App, pr *bouncer.Principal, body map[string]any) (*models.Post, map[string][]string) { errs := map[string][]string{} title := strings.TrimSpace(asString(body["title"])) if title == "" { @@ -534,7 +534,7 @@ func buildNewPost(r *http.Request, db *gorm.DB, pr *bouncer.Principal, body map[ if len(errs) > 0 { return nil, errs } - html, err := classes.FormatHTML(content) + html, err := classes.EmbedRegistryFrom(app).FormatHTML(content) if err != nil { return nil, map[string][]string{"content": {err.Error()}} } @@ -563,7 +563,7 @@ func buildNewPost(r *http.Request, db *gorm.DB, pr *bouncer.Principal, body map[ return post, nil } -func applyPostUpdate(r *http.Request, db *gorm.DB, post *models.Post, body map[string]any) map[string][]string { +func applyPostUpdate(r *http.Request, db *gorm.DB, app *backpack.App, post *models.Post, body map[string]any) map[string][]string { errs := map[string][]string{} if _, has := body["title"]; has { title := strings.TrimSpace(asString(body["title"])) @@ -590,7 +590,7 @@ func applyPostUpdate(r *http.Request, db *gorm.DB, post *models.Post, body map[s if strings.TrimSpace(content) == "" { errs["content"] = []string{"The content field is required."} } else { - html, err := classes.FormatHTML(content) + html, err := classes.EmbedRegistryFrom(app).FormatHTML(content) if err != nil { errs["content"] = []string{err.Error()} } else { @@ -708,7 +708,7 @@ func asUintSlice(raw any) ([]uint, bool) { // // h1 converts H1 in the translated content while the H1 setting is on; it // may be nil. -func applyPostAssocs(ctx context.Context, db *gorm.DB, post *models.Post, body map[string]any, h1 *h1Conversion) (created []models.Tag, err error) { +func applyPostAssocs(ctx context.Context, db *gorm.DB, app *backpack.App, post *models.Post, body map[string]any, h1 *h1Conversion) (created []models.Tag, err error) { if _, has := body["categories"]; has { ids, _ := asUintSlice(body["categories"]) if err := db.Where("post_id = ?", post.ID).Delete(&models.PostCategory{}).Error; err != nil { @@ -736,7 +736,7 @@ func applyPostAssocs(ctx context.Context, db *gorm.DB, post *models.Post, body m } } if raw, has := body["translations"]; has { - if err := syncTranslations(ctx, db, post, raw, h1); err != nil { + if err := syncTranslations(ctx, db, app, post, raw, h1); err != nil { return nil, err } } @@ -788,11 +788,12 @@ func resolveTagIDs(db *gorm.DB, raw any) (ids []uint, created []models.Tag, err return ids, created, nil } -func syncTranslations(ctx context.Context, db *gorm.DB, post *models.Post, raw any, h1 *h1Conversion) error { +func syncTranslations(ctx context.Context, db *gorm.DB, app *backpack.App, post *models.Post, raw any, h1 *h1Conversion) error { m, ok := raw.(map[string]any) if !ok { return nil } + reg := classes.EmbedRegistryFrom(app) fields := []string{"title", "slug", "content", "content_html", "excerpt", "metadata"} for locale, v := range m { attrs, ok := v.(map[string]any) @@ -802,7 +803,7 @@ func syncTranslations(ctx context.Context, db *gorm.DB, post *models.Post, raw a // Every translated content_html goes through the host column's // policy: derived from content, or sanitized when only content_html // is supplied. Winter stored a supplied content_html verbatim. - if err := classes.FormatTranslation(attrs); err != nil { + if err := reg.FormatTranslation(attrs); err != nil { return err } h1.convertTranslation(locale, attrs) diff --git a/controllers/posts.go b/controllers/posts.go index 190e3f2..9c65e4e 100644 --- a/controllers/posts.go +++ b/controllers/posts.go @@ -12,7 +12,6 @@ import ( "git.golem15.com/golem15/summercms/modules/backpack" "git.golem15.com/golem15/summercms/modules/bouncer" "git.golem15.com/golem15/summercms/modules/cabana" - "git.golem15.com/golem15/summercms/modules/compass" "git.golem15.com/golem15/summercms/modules/pact" "gorm.io/gorm" ) @@ -352,11 +351,7 @@ func (c postsAdminController) runExportPosts(ctx context.Context, in pact.AdminA func (c postsAdminController) runImportPosts(ctx context.Context, in pact.AdminActionInput) (pact.AdminActionResult, error) { path, dry, force := console.IOPayloadPath(in.Payload, "journal-export") - var cfg *compass.Config - if app := c.application(); app != nil { - cfg = app.Config - } - stats, err := console.ImportFromDirConfig(ctx, c.db(ctx), cfg, path, force, dry, nil, func(post *models.Post) error { + stats, err := console.ImportFromDirApp(ctx, c.db(ctx), c.application(), path, force, dry, nil, func(post *models.Post) error { return refuseUnpublishedWrite(ctx, post) }) if err != nil { diff --git a/plugin.go b/plugin.go index a7ae842..692657e 100644 --- a/plugin.go +++ b/plugin.go @@ -51,17 +51,44 @@ func (p *Plugin) Requires() []string { return []string{"golem15.translate"} } func (p *Plugin) Register(app *backpack.App) error { p.app = app + if app != nil { + if existing, ok := app.Lookup[*classes.EmbedRegistry](); !ok || existing == nil { + if err := app.Publish(classes.NewEmbedRegistry()); err != nil { + return err + } + } + } return nil } func (p *Plugin) Boot(app *backpack.App) error { p.app = app + if err := p.wireEmbedProviders(app); err != nil { + return err + } if err := p.wireSiteCache(app); err != nil { return err } return p.wireSearch(app) } +func (p *Plugin) wireEmbedProviders(app *backpack.App) error { + if app == nil || app.Config == nil { + return nil + } + reg, ok := app.Lookup[*classes.EmbedRegistry]() + if !ok || reg == nil { + reg = classes.NewEmbedRegistry() + if err := app.Publish(reg); err != nil { + return err + } + } + if err := reg.LoadFromConfig(app.Config); err != nil { + return fmt.Errorf("golem15.journal: %w", err) + } + return nil +} + // wireSiteCache keeps the Journal's deprecated purge keys working for one // release. When the framework keys site_cache.purge_url or purge_token are // set, the framework owns the purger (cooler.Install, cooler.SiteCacheFromApp)