feat(journal): add EmbedRegistry, YAML boot config, and pair-aware sanitizer
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -117,13 +117,13 @@ func TestEditorOutputPassesPolicy(t *testing.T) {
|
||||
stripped := []struct {
|
||||
name, in, want string
|
||||
}{
|
||||
{"other provider", `<figure data-embed="vimeo" data-id="dQw4w9WgXcQ"></figure>`, `<figure data-id="dQw4w9WgXcQ"></figure>`},
|
||||
{"provider with a suffix", `<figure data-embed="youtube2" data-id="dQw4w9WgXcQ"></figure>`, `<figure data-id="dQw4w9WgXcQ"></figure>`},
|
||||
{"id of 10 characters", `<figure data-embed="youtube" data-id="dQw4w9WgXc"></figure>`, `<figure data-embed="youtube"></figure>`},
|
||||
{"id of 12 characters", `<figure data-embed="youtube" data-id="dQw4w9WgXcQQ"></figure>`, `<figure data-embed="youtube"></figure>`},
|
||||
{"id with a quote", `<figure data-embed="youtube" data-id="dQw4w9"gXcQ"></figure>`, `<figure data-embed="youtube"></figure>`},
|
||||
{"id with a space", `<figure data-embed="youtube" data-id="dQw4w9 gXcQ"></figure>`, `<figure data-embed="youtube"></figure>`},
|
||||
{"id with an angle bracket", `<figure data-embed="youtube" data-id="dQw4w9<gXcQ"></figure>`, `<figure data-embed="youtube"></figure>`},
|
||||
{"other provider", `<figure data-embed="vimeo" data-id="dQw4w9WgXcQ"></figure>`, `<figure></figure>`},
|
||||
{"provider with a suffix", `<figure data-embed="youtube2" data-id="dQw4w9WgXcQ"></figure>`, `<figure></figure>`},
|
||||
{"id of 10 characters", `<figure data-embed="youtube" data-id="dQw4w9WgXc"></figure>`, `<figure></figure>`},
|
||||
{"id of 12 characters", `<figure data-embed="youtube" data-id="dQw4w9WgXcQQ"></figure>`, `<figure></figure>`},
|
||||
{"id with a quote", `<figure data-embed="youtube" data-id="dQw4w9"gXcQ"></figure>`, `<figure></figure>`},
|
||||
{"id with a space", `<figure data-embed="youtube" data-id="dQw4w9 gXcQ"></figure>`, `<figure></figure>`},
|
||||
{"id with an angle bracket", `<figure data-embed="youtube" data-id="dQw4w9<gXcQ"></figure>`, `<figure></figure>`},
|
||||
{"embed attributes on div", `<div data-embed="youtube" data-id="dQw4w9WgXcQ">x</div>`, `<div>x</div>`},
|
||||
{"embed attributes on img", `<img src="/a.jpg" data-embed="youtube" data-id="dQw4w9WgXcQ">`, `<img src="/a.jpg">`},
|
||||
{"embed attributes on p", `<p data-embed="youtube" data-id="dQw4w9WgXcQ">x</p>`, `<p>x</p>`},
|
||||
@@ -135,10 +135,10 @@ func TestEditorOutputPassesPolicy(t *testing.T) {
|
||||
{"negative start", `<ol start="-1"><li>a</li></ol>`, `<ol><li>a</li></ol>`},
|
||||
{"start on ul", `<ul start="3"><li>a</li></ul>`, `<ul><li>a</li></ul>`},
|
||||
{"alt on p", `<p alt="x">y</p>`, `<p>y</p>`},
|
||||
{"upper-case provider", `<figure data-embed="YouTube" data-id="dQw4w9WgXcQ"></figure>`, `<figure data-id="dQw4w9WgXcQ"></figure>`},
|
||||
{"provider with white space", `<figure data-embed=" youtube" data-id="dQw4w9WgXcQ"></figure>`, `<figure data-id="dQw4w9WgXcQ"></figure>`},
|
||||
{"empty id", `<figure data-embed="youtube" data-id=""></figure>`, `<figure data-embed="youtube"></figure>`},
|
||||
{"id with a URL", `<figure data-embed="youtube" data-id="javascript:1"></figure>`, `<figure data-embed="youtube"></figure>`},
|
||||
{"upper-case provider", `<figure data-embed="YouTube" data-id="dQw4w9WgXcQ"></figure>`, `<figure></figure>`},
|
||||
{"provider with white space", `<figure data-embed=" youtube" data-id="dQw4w9WgXcQ"></figure>`, `<figure></figure>`},
|
||||
{"empty id", `<figure data-embed="youtube" data-id=""></figure>`, `<figure></figure>`},
|
||||
{"id with a URL", `<figure data-embed="youtube" data-id="javascript:1"></figure>`, `<figure></figure>`},
|
||||
{"iframe alone", `<iframe src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ"></iframe>`, ``},
|
||||
{"script inside the placeholder", `<figure data-embed="youtube" data-id="dQw4w9WgXcQ"><script>alert(1)</script></figure>`, editorPlaceholder},
|
||||
{"embed attributes on section", `<section data-embed="youtube" data-id="dQw4w9WgXcQ">x</section>`, `<section>x</section>`},
|
||||
|
||||
298
classes/embed_registry.go
Normal file
298
classes/embed_registry.go
Normal file
@@ -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 <figure data-embed="<Key>" data-id="...">
|
||||
// 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
|
||||
}
|
||||
@@ -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 <figure data-embed="youtube" data-id="..."></figure>:
|
||||
// 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: <figure data-embed="<provider>" data-id="<id>">.
|
||||
// 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 <figure> 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 <figure> start tag while all other attributes and children
|
||||
// remain intact.
|
||||
func enforceEmbedPairs(doc string, reg *EmbedRegistry) string {
|
||||
if !strings.Contains(doc, "<figure") {
|
||||
return doc
|
||||
}
|
||||
var (
|
||||
buf bytes.Buffer
|
||||
modified bool
|
||||
)
|
||||
z := xhtml.NewTokenizer(strings.NewReader(doc))
|
||||
for {
|
||||
tt := z.Next()
|
||||
if tt == xhtml.ErrorToken {
|
||||
break
|
||||
}
|
||||
raw := z.Raw()
|
||||
if tt != xhtml.StartTagToken && tt != xhtml.SelfClosingTagToken {
|
||||
buf.Write(raw)
|
||||
continue
|
||||
}
|
||||
if !isFigureTag(raw) {
|
||||
buf.Write(raw)
|
||||
continue
|
||||
}
|
||||
tok := z.Token()
|
||||
var (
|
||||
embedVal, idVal string
|
||||
hasEmbed, hasID bool
|
||||
hasEmbedAttr bool
|
||||
)
|
||||
for _, a := range tok.Attr {
|
||||
if a.Namespace != "" {
|
||||
continue
|
||||
}
|
||||
switch a.Key {
|
||||
case "data-embed":
|
||||
hasEmbed = true
|
||||
hasEmbedAttr = true
|
||||
embedVal = a.Val
|
||||
case "data-id":
|
||||
hasID = true
|
||||
hasEmbedAttr = true
|
||||
idVal = a.Val
|
||||
case "data-aspect", "data-height":
|
||||
hasEmbedAttr = true
|
||||
}
|
||||
}
|
||||
if !hasEmbedAttr || (hasEmbed && hasID && reg.Match(embedVal, idVal)) {
|
||||
buf.Write(raw)
|
||||
continue
|
||||
}
|
||||
filtered := make([]xhtml.Attribute, 0, len(tok.Attr))
|
||||
for _, a := range tok.Attr {
|
||||
if a.Namespace == "" && (a.Key == "data-embed" || a.Key == "data-id" || a.Key == "data-aspect" || a.Key == "data-height") {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, a)
|
||||
}
|
||||
tok.Attr = filtered
|
||||
modified = true
|
||||
buf.WriteString(tok.String())
|
||||
}
|
||||
if !modified {
|
||||
return doc
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
func isFigureTag(raw []byte) bool {
|
||||
const prefix = "<figure"
|
||||
if len(raw) < len(prefix)+1 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(prefix); i++ {
|
||||
c := raw[i]
|
||||
if 'A' <= c && c <= 'Z' {
|
||||
c += 'a' - 'A'
|
||||
}
|
||||
if c != prefix[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
next := raw[len(prefix)]
|
||||
return next == '>' || 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.
|
||||
|
||||
Reference in New Issue
Block a user