feat(journal): add EmbedRegistry, YAML boot config, and pair-aware sanitizer
This commit is contained in:
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
|
||||
}
|
||||
Reference in New Issue
Block a user