Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
feat(plugins): support dynamic templated content in the UI for plugins
Gabe Kangasd69d52d3bef1
diff --git a/main.go b/main.goindex 5db151319f..70932dfe70 100644--- a/main.go+++ b/main.go@@ -365,8 +365,8 @@ func main() {var pluginActions func() []models.ExternalActionvar pluginCSSContent func() []bytevar pluginJSContent func() []byte- var pluginPageContent func() []byte- var pluginTabs func() []models.PluginTab+ var pluginPageContent func(*http.Request) []byte+ var pluginTabs func(*http.Request) []models.PluginTabif pluginHostInstance != nil {pluginActions = pluginHostInstance.ActionspluginCSSContent = pluginHostInstance.StylesContentdiff --git a/models/pluginTab.go b/models/pluginTab.goindex 8c4fda6453..d0b2128718 100644--- a/models/pluginTab.go+++ b/models/pluginTab.go@@ -1,13 +1,15 @@package models// PluginTab is one viewer-page tab a plugin contributes via-// manifest.tabs. Slug identifies the source plugin (used as the React-// key on the frontend so unmount/remount only fires when a plugin-// goes away); Title is the label shown in the tab bar; HTML is the-// inlined body of the tab's content file. The host emits this list-// as `pluginTabs` on /api/config.+// manifest.tabs. Slug is the composite unique key for this tab+// (pluginSlug/tabSlug) used as the React key on the frontend so+// unmount/remount only fires when a tab's source changes.+// PluginSlug identifies the source plugin for filtering.+// Title is the label shown in the tab bar; HTML is the inlined body.+// The host emits this list as `pluginTabs` on /api/config.type PluginTab struct {- Slug string `json:"slug"`- Title string `json:"title"`- HTML string `json:"html"`+ Slug string `json:"slug"`+ PluginSlug string `json:"pluginSlug"`+ Title string `json:"title"`+ HTML string `json:"html"`}diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.goindex 885cd457a3..acdf0574cc 100644--- a/pluginhost/pluginhost.go+++ b/pluginhost/pluginhost.go@@ -32,6 +32,7 @@ import ("github.com/owncast/owncast/services/plugins""github.com/owncast/owncast/services/plugins/kv""github.com/owncast/owncast/services/stream"+ "github.com/owncast/owncast/utils")// pluginsEnabledConfigKey is the datastore key under which the set of@@ -96,6 +97,10 @@ type Host struct {kv kv.Store// tickCancel stops the once-a-second tick goroutine when the host stops.tickCancel context.CancelFunc+ // getRequestUser resolves a viewer's chat identity from an HTTP request+ // (via the accessToken query parameter). Used by PageContent and Tabs to+ // pass viewer identity to dynamic onPageContent / onTabContent handlers.+ getRequestUser func(*http.Request) *plugins.HostUser}// runtimeActionsConfigKey is the reserved key inside a plugin's own@@ -179,52 +184,111 @@ func (p *Host) ScriptsContent() []byte {}// PageContent returns the concatenated HTML bytes contributed by-// every loaded plugin's manifest.extraPageContent file, each preceded+// every loaded plugin's manifest.extraPageContent, each preceded// by an `<!-- plugin: <slug> ... -->` delimiter for in-page// attribution. The /api/config handler prepends these bytes to the// admin's rendered extraPageContent so plugin HTML lands at the top// of the extra-content block. Markdown rendering is skipped for// plugin HTML so the markdown processor can't mangle it.-func (p *Host) PageContent() []byte {- return p.readManifestAssets(- func(m *plugins.Manifest) []string {- if m.ExtraPageContent == "" {- return nil+func (p *Host) PageContent(r *http.Request) []byte {+ if p == nil || p.manager == nil {+ return nil+ }+ var user *plugins.HostUser+ if p.getRequestUser != nil && r != nil {+ user = p.getRequestUser(r)+ }+ var buf bytes.Buffer+ for _, l := range p.manager.Snapshot() {+ if l == nil || l.Manifest == nil || l.Manifest.ExtraPageContent == nil {+ continue+ }+ epc := l.Manifest.ExtraPageContent+ slug := l.Manifest.Slug+ var html string+ if epc.Content != "" {+ // Static: read from assets/.+ if l.AssetsFS == nil {+ log.Warnf("plugin %s: extraPageContent has content but no AssetsFS", slug)+ continue}- return []string{m.ExtraPageContent}- },- "<!-- plugin: %s — %s -->\n",- )+ pluginPrefix := "/plugins/" + slug + "/"+ relPath := strings.TrimPrefix(epc.Content, pluginPrefix)+ data, err := fs.ReadFile(l.AssetsFS, relPath)+ if err != nil {+ log.Warnf("plugin %s: skipping extraPageContent (%s): %v", slug, relPath, err)+ continue+ }+ html = string(data)+ } else {+ // Dynamic: call on_page_content with the requesting viewer's identity.+ var err error+ html, err = l.CallPageContent(context.Background(), epc.Slug, user)+ if err != nil {+ log.Warnf("plugin %s: on_page_content(%q) error: %v", slug, epc.Slug, err)+ continue+ }+ }+ fmt.Fprintf(&buf, "<!-- plugin: %s — %s -->\n", slug, epc.Slug)+ buf.WriteString(html)+ }+ return buf.Bytes()}// Tabs returns every viewer-page tab contributed by loaded plugins-// via manifest.tabs. Each tab's content file is read from the-// plugin's assets/ directory once per call; tabs whose file can't be-// read are skipped (logged) so a broken file doesn't take down the-// rest of the list. /api/config emits the result as `pluginTabs`,+// via manifest.tabs. Each tab's content is either read from the+// plugin's assets/ directory (static) or fetched by calling the+// plugin's on_tab_content export (dynamic). Tabs whose content can't+// be resolved are skipped (logged) so a broken file doesn't take down+// the rest of the list. /api/config emits the result as `pluginTabs`,// which the viewer page renders alongside the built-in tabs.-func (p *Host) Tabs() []models.PluginTab {+func (p *Host) Tabs(r *http.Request) []models.PluginTab {if p == nil || p.manager == nil {return nil}+ var user *plugins.HostUser+ if p.getRequestUser != nil && r != nil {+ user = p.getRequestUser(r)+ }var out []models.PluginTabfor _, l := range p.manager.Snapshot() {- if l == nil || l.Manifest == nil || l.AssetsFS == nil {+ if l == nil || l.Manifest == nil {continue}- slug := l.Manifest.Slug- pluginPrefix := "/plugins/" + slug + "/"+ pluginSlug := l.Manifest.Slug+ pluginPrefix := "/plugins/" + pluginSlug + "/"for _, tab := range l.Manifest.Tabs {- relPath := strings.TrimPrefix(tab.Content, pluginPrefix)- data, err := fs.ReadFile(l.AssetsFS, relPath)- if err != nil {- log.Warnf("plugin %s: skipping tab %q (%s): %v", slug, tab.Title, relPath, err)- continue+ var html string+ if tab.Content != "" {+ // Static: read from assets/.+ if l.AssetsFS == nil {+ log.Warnf("plugin %s: tab %q has content but no AssetsFS", pluginSlug, tab.Title)+ continue+ }+ relPath := strings.TrimPrefix(tab.Content, pluginPrefix)+ data, err := fs.ReadFile(l.AssetsFS, relPath)+ if err != nil {+ log.Warnf("plugin %s: skipping tab %q (%s): %v", pluginSlug, tab.Title, relPath, err)+ continue+ }+ html = string(data)+ } else {+ // Dynamic: call on_tab_content with the requesting viewer's identity.+ var err error+ html, err = l.CallTabContent(context.Background(), tab.Slug, user)+ if err != nil {+ log.Warnf("plugin %s: on_tab_content(%q) error: %v", pluginSlug, tab.Slug, err)+ continue+ }}+ // Use pluginSlug/tabSlug as the composite React key so two+ // plugins can each have a tab with the same slug without+ // colliding in the viewer page's tab row.out = append(out, models.PluginTab{- Slug: slug,- Title: tab.Title,- HTML: string(data),+ Slug: pluginSlug + "/" + tab.Slug,+ PluginSlug: pluginSlug,+ Title: tab.Title,+ HTML: html,})}}@@ -378,6 +442,7 @@ func New(ctx context.Context, deps Deps) (*Host, error) {requireAdminAuth: deps.RequireAdminAuth,kv: env.KV,tickCancel: tickCancel,+ getRequestUser: env.GetRequestUser,}, nil}@@ -1170,7 +1235,7 @@ func wireRequestHostFns(env *plugins.HostEnv, deps Deps) {env.IsAuthenticated = deps.IsAdminRequestenv.GetRequestUser = func(r *http.Request) *plugins.HostUser {- token := r.URL.Query().Get("accessToken")+ token := utils.ChatAccessTokenFromRequest(r)if token == "" {return nil}diff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.goindex 425a280313..3bf65d1f03 100644--- a/services/plugins/hostfns.go+++ b/services/plugins/hostfns.go@@ -4,6 +4,7 @@ import ("context""encoding/json""fmt"+ "io/fs""net/http""os""strings"@@ -335,7 +336,7 @@ type HostEnv struct {// plugin should be granted, based on its declared permissions. A plugin// only sees imports for permissions it declared; importing anything else// will fail to link at instantiation time.-func BuildHostFunctions(env *HostEnv, manifest *Manifest) []extism.HostFunction {+func BuildHostFunctions(env *HostEnv, manifest *Manifest, assetsFS fs.FS) []extism.HostFunction {var fns []extism.HostFunctiongranted := stringSet(manifest.Permissions)@@ -414,6 +415,8 @@ func BuildHostFunctions(env *HostEnv, manifest *Manifest) []extism.HostFunction// Config is ambient too: reading the plugin's own manifest-declared config// (admin override, else declared default) is benign and needs no grant.fns = append(fns, hostConfigGet(env, manifest))+ // Asset reading is ambient: a plugin reads only files it shipped itself.+ fns = append(fns, hostAssetRead(assetsFS))if granted[PermUIModify] {fns = append(fns,hostAddActions(env, manifest),@@ -799,6 +802,42 @@ func hostConfigGet(env *HostEnv, manifest *Manifest) extism.HostFunction {return fn}+// hostAssetRead backs owncast.assets.read/readText. Reads a file from the+// plugin's bundled assets/ directory. The path must be relative — no ".."+// segments, no leading "/". Returns 0 when assetsFS is nil or the file+// doesn't exist. Ambient — no permission required.+func hostAssetRead(assetsFS fs.FS) extism.HostFunction {+ fn := extism.NewHostFunctionWithStack(+ "owncast_asset_read",+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {+ path, err := p.ReadString(stack[0])+ if err != nil || assetsFS == nil {+ stack[0] = 0+ return+ }+ if strings.Contains(path, "..") || strings.HasPrefix(path, "/") {+ stack[0] = 0+ return+ }+ data, err := fs.ReadFile(assetsFS, path)+ if err != nil {+ stack[0] = 0+ return+ }+ offset, err := p.WriteBytes(data)+ if err != nil {+ stack[0] = 0+ return+ }+ stack[0] = offset+ },+ []extism.ValueType{extism.ValueTypePTR},+ []extism.ValueType{extism.ValueTypePTR},+ )+ fn.SetNamespace("extism:host/user")+ return fn+}+func hostServerEmotes(env *HostEnv) extism.HostFunction {fn := extism.NewHostFunctionWithStack("owncast_server_emotes",diff --git a/services/plugins/manager.go b/services/plugins/manager.goindex c102e09c4b..102b3effb1 100644--- a/services/plugins/manager.go+++ b/services/plugins/manager.go@@ -163,6 +163,46 @@ func (l *Loaded) IsAdminPath(path string) bool {return false}+// CallTabContent invokes the plugin's on_tab_content export with the+// given slug and optional user, returning the rendered HTML. Returns+// empty string when the plugin does not export on_tab_content.+func (p *Loaded) CallTabContent(ctx context.Context, slug string, user *HostUser) (string, error) {+ return p.callContentExport(ctx, "on_tab_content", slug, user)+}++// CallPageContent invokes the plugin's on_page_content export with+// the given slug and optional user, returning the rendered HTML.+// Returns empty string when the plugin does not export on_page_content.+func (p *Loaded) CallPageContent(ctx context.Context, slug string, user *HostUser) (string, error) {+ return p.callContentExport(ctx, "on_page_content", slug, user)+}++func (p *Loaded) callContentExport(ctx context.Context, export, slug string, user *HostUser) (string, error) {+ p.mu.Lock()+ pl := p.plugin+ p.mu.Unlock()+ if pl == nil || !pl.FunctionExists(export) {+ return "", nil+ }+ req := map[string]any{"slug": slug}+ if user != nil {+ req["user"] = user+ }+ input, err := json.Marshal(req)+ if err != nil {+ return "", fmt.Errorf("%s: marshal input: %w", export, err)+ }+ callCtx, cancel := context.WithTimeout(ctx, HTTPHandlerTimeout)+ defer cancel()+ p.mu.Lock()+ _, out, err := pl.CallWithContext(callCtx, export, input)+ p.mu.Unlock()+ if err != nil {+ return "", fmt.Errorf("%s: %w", export, err)+ }+ return string(out), nil+}+// Close releases the underlying wasm instance and any retained file handles// (the .ocpkg zip reader for packaged plugins). Safe to call multiple times.func (l *Loaded) Close(ctx context.Context) {@@ -769,9 +809,7 @@ func loadByPath(ctx context.Context, env *HostEnv, path string) (*Loaded, error)if pub := filepath.Join(parent, "public"); dirExists(pub) {loaded.PublicFS = os.DirFS(pub)}- if as := filepath.Join(parent, "assets"); dirExists(as) {- loaded.AssetsFS = os.DirFS(as)- }+ // AssetsFS is already set by LoadPlugin from the assets/ sibling dir.return loaded, nil}return nil, fmt.Errorf("unsupported plugin file: %s", path)@@ -1078,8 +1116,9 @@ func pendingPermissions(manifestPerms, approved []string) []string {// (the loose-files layout). Used by the test runner so it shares the exact// same load + register + validate path that production uses via Start.//-// AssetsFS on the returned Loaded is left nil — callers that want static-// asset serving should populate it themselves.+// LoadPlugin loads a single plugin given explicit wasm and manifest paths+// (the loose-files layout). Assets are discovered from the assets/ directory+// sibling of the wasm and wired into the plugin at load time.func LoadPlugin(ctx context.Context, env *HostEnv, wasmPath, manifestPath string) (*Loaded, error) {manifestBytes, err := os.ReadFile(manifestPath) //nolint:gosec // G304: plugin paths are admin-controlled, not user inputif err != nil {@@ -1090,7 +1129,11 @@ func LoadPlugin(ctx context.Context, env *HostEnv, wasmPath, manifestPath stringreturn nil, fmt.Errorf("read wasm %s: %w", wasmPath, err)}displayName := strings.TrimSuffix(filepath.Base(wasmPath), ".wasm")- loaded, err := loadFromBytes(ctx, env, manifestBytes, wasmBytes, displayName)+ var assetsFS fs.FS+ if as := filepath.Join(filepath.Dir(wasmPath), "assets"); dirExists(as) {+ assetsFS = os.DirFS(as)+ }+ loaded, err := loadFromBytes(ctx, env, manifestBytes, wasmBytes, displayName, assetsFS)if err != nil {return nil, err}@@ -1099,13 +1142,13 @@ func LoadPlugin(ctx context.Context, env *HostEnv, wasmPath, manifestPath string}// loadFromBytes is the shared core of LoadPlugin and LoadPackage.-func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, wasmBytes []byte, displayName string) (*Loaded, error) {+func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, wasmBytes []byte, displayName string, assetsFS fs.FS) (*Loaded, error) {manifest, err := ParseManifest(manifestBytes)if err != nil {return nil, err}- hostFns := BuildHostFunctions(env, manifest)+ hostFns := BuildHostFunctions(env, manifest, assetsFS)extismManifest := extism.Manifest{Wasm: []extism.Wasm{extism.WasmData{Data: wasmBytes, Name: displayName}},@@ -1183,7 +1226,7 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, wasmBytes [adminPaths = append(adminPaths, page.Path)}- return &Loaded{Manifest: manifest, plugin: p, adminGlobs: adminGlobs, adminPaths: adminPaths}, nil+ return &Loaded{Manifest: manifest, plugin: p, adminGlobs: adminGlobs, adminPaths: adminPaths, AssetsFS: assetsFS}, nil}// requireChatFilterPermission rejects a runtime registration thatdiff --git a/services/plugins/manifest.go b/services/plugins/manifest.goindex f8c86ced1f..f386bd02d6 100644--- a/services/plugins/manifest.go+++ b/services/plugins/manifest.go@@ -78,19 +78,13 @@ type Manifest struct {// ui.modify permission (it's running inside Owncast's chrome)// and http.serve (the host serves the bytes).Scripts []string `json:"scripts,omitempty"`- // ExtraPageContent is an HTML file the plugin contributes to the- // viewer page's extra-content block. The host reads the file's- // bytes and prepends them to the admin's extraPageContent in the- // /api/config response (after the admin's markdown is rendered)- // so plugin HTML never goes through the markdown processor and- // can't be mangled by it. Path rules match styles/scripts (bare- // paths auto-prefix to /plugins/<slug>/, cross-plugin and- // http(s):// URLs rejected, .html extension required). Only one- // file per plugin so the prepended block stays predictable.- // Requires ui.modify (the plugin paints inside Owncast's chrome);- // http.serve is not required because the HTML is inlined into- // the API response, not served as a URL.- ExtraPageContent string `json:"extraPageContent,omitempty"`+ // ExtraPageContent declares the plugin's contribution to the viewer+ // page's extra-content block. When Content is set, the host reads+ // that HTML file's bytes and prepends them to the admin's+ // extraPageContent in the /api/config response. When Content is+ // absent, the host calls on_page_content(slug, user) to get+ // rendered HTML dynamically. Requires ui.modify.+ ExtraPageContent *ExtraPageContent `json:"extraPageContent,omitempty"`// Tabs declares viewer-page tabs the plugin contributes to the// row of tabs Owncast renders next to chat (alongside built-ins// like Followers). Each entry's `content` is a relative path to@@ -100,13 +94,24 @@ type Manifest struct {Tabs []Tab `json:"tabs,omitempty"`}-// Tab is a single viewer-page tab a plugin contributes via-// manifest.tabs. Title is the label shown in the tab bar; Content is-// a relative path to an HTML file the host reads from the plugin's-// assets/ directory and inlines into the tab body.+// Tab declares one viewer-page tab. Title is the label shown in the+// UI. Slug is the stable identifier passed to the plugin's+// onTabContent handler. Content is the optional path to a static HTML+// file under assets/; when omitted the host calls on_tab_content with+// the slug to get rendered HTML.type Tab struct {Title string `json:"title"`- Content string `json:"content"`+ Slug string `json:"slug"`+ Content string `json:"content,omitempty"`+}++// ExtraPageContent declares the plugin's contribution to the viewer+// page's extra-content block. Slug identifies the slot; Content is+// an optional static HTML file path. When Content is absent the host+// calls on_page_content(slug, user) to get rendered HTML.+type ExtraPageContent struct {+ Slug string `json:"slug"`+ Content string `json:"content,omitempty"`}// BotConfig is the chat-bot-specific configuration for plugins that@@ -403,12 +408,8 @@ func (m *Manifest) validateStyles() error {"so it's visible to anyone reviewing the manifest that the " +"plugin restyles Owncast's UI")}- if !m.hasPermission(PermHttpServe) {- return errors.New(- "manifest.styles requires the \"http.serve\" permission so the " +- "host can serve the bundled CSS files at /plugins/<slug>/ " +- "URLs")- }+ // http.serve is not required: the host reads each file from the plugin's+ // assets/ directory and inlines the bytes into customStyles on /api/config.for i, raw := range m.Styles {rewritten, err := rewritePluginAssetPath(m.Slug, raw, ".css")if err != nil {@@ -421,10 +422,9 @@ func (m *Manifest) validateStyles() error {// validateScripts checks manifest.scripts entries and rewrites them// into absolute plugin-namespace URLs. Same rules as validateStyles-// applied to .js files: each becomes a <script src=...> on the viewer-// page, which runs in the chrome's window context. Permission gating-// matches styles (ui.modify + http.serve) since scripts can manipulate-// anything the viewer renders.+// applied to .js files: each is inlined into /customjavascript and+// runs in the viewer's window context. Only ui.modify is required;+// http.serve is not needed since the bytes come from assets/, not a URL.func (m *Manifest) validateScripts() error {if len(m.Scripts) == 0 {return nil@@ -437,12 +437,8 @@ func (m *Manifest) validateScripts() error {"so it's visible to anyone reviewing the manifest that the " +"plugin runs code inside Owncast's chrome")}- if !m.hasPermission(PermHttpServe) {- return errors.New(- "manifest.scripts requires the \"http.serve\" permission so " +- "the host can serve the bundled JavaScript files at " +- "/plugins/<slug>/ URLs")- }+ // http.serve is not required: the host reads each file from the plugin's+ // assets/ directory and inlines the bytes into /customjavascript.for i, raw := range m.Scripts {rewritten, err := rewritePluginAssetPath(m.Slug, raw, ".js")if err != nil {@@ -453,15 +449,8 @@ func (m *Manifest) validateScripts() error {return nil}-// validateExtraPageContent checks manifest.extraPageContent and-// rewrites it into the plugin's namespace. The file's bytes are-// inlined into the /api/config extraPageContent response (prepended-// to the admin's content), not served as a URL, so http.serve is not-// required, but the same path-shape and extension rules apply for-// consistency with styles and scripts. ui.modify is required because-// the contributed HTML lands inside the viewer chrome.func (m *Manifest) validateExtraPageContent() error {- if m.ExtraPageContent == "" {+ if m.ExtraPageContent == nil {return nil}if !m.hasPermission(PermUIModify) {@@ -472,19 +461,19 @@ func (m *Manifest) validateExtraPageContent() error {"it's visible to anyone reviewing the manifest that the " +"plugin paints inside Owncast's chrome")}- rewritten, err := rewritePluginAssetPath(m.Slug, m.ExtraPageContent, ".html")- if err != nil {- return fmt.Errorf("manifest.extraPageContent: %w", err)+ if err := validatePluginSlug("manifest.extraPageContent.slug", m.ExtraPageContent.Slug); err != nil {+ return err+ }+ if m.ExtraPageContent.Content != "" {+ rewritten, err := rewritePluginAssetPath(m.Slug, m.ExtraPageContent.Content, ".html")+ if err != nil {+ return fmt.Errorf("manifest.extraPageContent.content: %w", err)+ }+ m.ExtraPageContent.Content = rewritten}- m.ExtraPageContent = rewrittenreturn nil}-// validateTabs checks manifest.tabs entries and rewrites each tab's-// content path into the plugin's namespace. The host reads the bytes-// from assets/ at request time and inlines the HTML into the tab-// body on /api/config (no URL is served), so only ui.modify is-// required.func (m *Manifest) validateTabs() error {if len(m.Tabs) == 0 {return nil@@ -497,25 +486,43 @@ func (m *Manifest) validateTabs() error {"visible to anyone reviewing the manifest that the " +"plugin paints inside Owncast's chrome")}- // Reject duplicate titles within the same plugin. The frontend- // derives a React key from (slug, title), and a viewer staring at- // a row of two identically-named tabs has no way to tell them- // apart anyway, so making the manifest reject this at load is- // strictly better than silently accepting it.seenTitles := make(map[string]bool, len(m.Tabs))- for i, tab := range m.Tabs {- if strings.TrimSpace(tab.Title) == "" {+ seenSlugs := make(map[string]bool, len(m.Tabs))+ for i := range m.Tabs {+ if strings.TrimSpace(m.Tabs[i].Title) == "" {return fmt.Errorf("manifest.tabs[%d].title is required", i)}- if seenTitles[tab.Title] {- return fmt.Errorf("manifest.tabs[%d].title %q is a duplicate; tab titles must be unique within a plugin", i, tab.Title)+ if seenTitles[m.Tabs[i].Title] {+ return fmt.Errorf("manifest.tabs[%d].title %q is a duplicate; tab titles must be unique within a plugin", i, m.Tabs[i].Title)}- seenTitles[tab.Title] = true- rewritten, err := rewritePluginAssetPath(m.Slug, tab.Content, ".html")- if err != nil {- return fmt.Errorf("manifest.tabs[%d].content: %w", i, err)+ seenTitles[m.Tabs[i].Title] = true+ if err := validatePluginSlug(fmt.Sprintf("manifest.tabs[%d].slug", i), m.Tabs[i].Slug); err != nil {+ return err+ }+ if seenSlugs[m.Tabs[i].Slug] {+ return fmt.Errorf("manifest.tabs[%d].slug %q is a duplicate; tab slugs must be unique within a plugin", i, m.Tabs[i].Slug)+ }+ seenSlugs[m.Tabs[i].Slug] = true+ if m.Tabs[i].Content != "" {+ rewritten, err := rewritePluginAssetPath(m.Slug, m.Tabs[i].Content, ".html")+ if err != nil {+ return fmt.Errorf("manifest.tabs[%d].content: %w", i, err)+ }+ m.Tabs[i].Content = rewritten}- m.Tabs[i].Content = rewritten+ }+ return nil+}++// validatePluginSlug checks that s is a non-empty, valid plugin-style+// slug (lowercase letters/digits/hyphens, starting with a letter, max+// 64 chars). field is used in error messages.+func validatePluginSlug(field, s string) error {+ if strings.TrimSpace(s) == "" {+ return fmt.Errorf("%s is required", field)+ }+ if !slugPattern.MatchString(s) {+ return fmt.Errorf("%s %q must be lowercase letters, digits, and hyphens starting with a letter (max 64 chars)", field, s)}return nil}diff --git a/services/plugins/manifest_test.go b/services/plugins/manifest_test.goindex b2e8c739f0..b23290fbec 100644--- a/services/plugins/manifest_test.go+++ b/services/plugins/manifest_test.go@@ -434,17 +434,15 @@ func TestParseManifest_Styles_RequiresUIModify(t *testing.T) {}}-func TestParseManifest_Styles_RequiresHttpServe(t *testing.T) {+func TestParseManifest_Styles_DoesNotRequireHttpServe(t *testing.T) {+ // styles are inlined from assets/ into /api/config — http.serve is not needed._, err := ParseManifest([]byte(`{"api": "1", "name": "styled", "version": "1.0","permissions": ["ui.modify"],"styles": ["theme.css"]}`))- if err == nil {- t.Fatal("expected error when styles is set without http.serve")- }- if !strings.Contains(err.Error(), "http.serve") {- t.Errorf("error should mention http.serve, got: %v", err)+ if err != nil {+ t.Fatalf("expected no error for styles without http.serve, got: %v", err)}}@@ -524,17 +522,15 @@ func TestParseManifest_Scripts_RequiresUIModify(t *testing.T) {}}-func TestParseManifest_Scripts_RequiresHttpServe(t *testing.T) {+func TestParseManifest_Scripts_DoesNotRequireHttpServe(t *testing.T) {+ // scripts are inlined from assets/ into /customjavascript — http.serve is not needed._, err := ParseManifest([]byte(`{"api": "1", "name": "scripted", "version": "1.0","permissions": ["ui.modify"],"scripts": ["client.js"]}`))- if err == nil {- t.Fatal("expected error when scripts is set without http.serve")- }- if !strings.Contains(err.Error(), "http.serve") {- t.Errorf("error should mention http.serve, got: %v", err)+ if err != nil {+ t.Fatalf("expected no error for scripts without http.serve, got: %v", err)}}@@ -584,13 +580,16 @@ func TestParseManifest_ExtraPageContent_RewritesRelativePath(t *testing.T) {m, err := ParseManifest([]byte(`{"api": "1", "name": "page", "version": "1.0","permissions": ["ui.modify"],- "extraPageContent": "content.html"+ "extraPageContent": {"slug": "test-slot", "content": "content.html"}}`))if err != nil {t.Fatalf("parse: %v", err)}- if m.ExtraPageContent != "/plugins/page/content.html" {- t.Errorf("extraPageContent = %q, want /plugins/page/content.html", m.ExtraPageContent)+ if m.ExtraPageContent == nil {+ t.Fatal("extraPageContent should not be nil")+ }+ if m.ExtraPageContent.Content != "/plugins/page/content.html" {+ t.Errorf("extraPageContent.content = %q, want /plugins/page/content.html", m.ExtraPageContent.Content)}}@@ -598,7 +597,7 @@ func TestParseManifest_ExtraPageContent_DoesNotRequireHttpServe(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "page", "version": "1.0","permissions": ["ui.modify"],- "extraPageContent": "content.html"+ "extraPageContent": {"slug": "test-slot", "content": "content.html"}}`))if err != nil {t.Errorf("extraPageContent should not require http.serve: %v", err)@@ -608,7 +607,7 @@ func TestParseManifest_ExtraPageContent_DoesNotRequireHttpServe(t *testing.T) {func TestParseManifest_ExtraPageContent_RequiresUIModify(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "page", "version": "1.0",- "extraPageContent": "content.html"+ "extraPageContent": {"slug": "test-slot", "content": "content.html"}}`))if err == nil {t.Fatal("expected error when extraPageContent is set without ui.modify")@@ -622,7 +621,7 @@ func TestParseManifest_ExtraPageContent_RejectsCrossPluginPath(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "page", "version": "1.0","permissions": ["ui.modify"],- "extraPageContent": "/plugins/some-other-plugin/content.html"+ "extraPageContent": {"slug": "test-slot", "content": "/plugins/some-other-plugin/content.html"}}`))if err == nil {t.Fatal("expected error: cross-plugin extraPageContent path")@@ -636,7 +635,7 @@ func TestParseManifest_ExtraPageContent_RejectsAbsoluteURL(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "page", "version": "1.0","permissions": ["ui.modify"],- "extraPageContent": "https://cdn.example.com/content.html"+ "extraPageContent": {"slug": "test-slot", "content": "https://cdn.example.com/content.html"}}`))if err == nil {t.Fatal("expected error: absolute URLs rejected for extraPageContent")@@ -650,7 +649,7 @@ func TestParseManifest_ExtraPageContent_RejectsNonHtmlExtension(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "page", "version": "1.0","permissions": ["ui.modify"],- "extraPageContent": "content.htm"+ "extraPageContent": {"slug": "test-slot", "content": "content.htm"}}`))if err == nil {t.Fatal("expected error: only .html extension allowed")@@ -665,16 +664,16 @@ func TestParseManifest_Tabs_RewritesContentPaths(t *testing.T) {"api": "1", "name": "tabbed", "version": "1.0","permissions": ["ui.modify"],"tabs": [- { "title": "Music", "content": "music.html" },- { "title": "Photos", "content": "/photos.html" }+ { "title": "Music", "slug": "music", "content": "music.html" },+ { "title": "Photos", "slug": "photos", "content": "/photos.html" }]}`))if err != nil {t.Fatalf("parse: %v", err)}want := []Tab{- {Title: "Music", Content: "/plugins/tabbed/music.html"},- {Title: "Photos", Content: "/plugins/tabbed/photos.html"},+ {Title: "Music", Slug: "music", Content: "/plugins/tabbed/music.html"},+ {Title: "Photos", Slug: "photos", Content: "/plugins/tabbed/photos.html"},}if len(m.Tabs) != len(want) {t.Fatalf("tabs count: got %d want %d", len(m.Tabs), len(want))@@ -689,7 +688,7 @@ func TestParseManifest_Tabs_RewritesContentPaths(t *testing.T) {func TestParseManifest_Tabs_RequiresUIModify(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "tabbed", "version": "1.0",- "tabs": [{ "title": "Music", "content": "music.html" }]+ "tabs": [{ "title": "Music", "slug": "music", "content": "music.html" }]}`))if err == nil {t.Fatal("expected error when tabs is set without ui.modify")@@ -703,7 +702,7 @@ func TestParseManifest_Tabs_RequiresTitle(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "tabbed", "version": "1.0","permissions": ["ui.modify"],- "tabs": [{ "title": "", "content": "music.html" }]+ "tabs": [{ "title": "", "slug": "music", "content": "music.html" }]}`))if err == nil {t.Fatal("expected error when tab.title is empty")@@ -718,8 +717,8 @@ func TestParseManifest_Tabs_RejectsDuplicateTitles(t *testing.T) {"api": "1", "name": "tabbed", "version": "1.0","permissions": ["ui.modify"],"tabs": [- { "title": "Music", "content": "a.html" },- { "title": "Music", "content": "b.html" }+ { "title": "Music", "slug": "music-a", "content": "a.html" },+ { "title": "Music", "slug": "music-b", "content": "b.html" }]}`))if err == nil {@@ -734,7 +733,7 @@ func TestParseManifest_Tabs_RejectsCrossPluginPath(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "tabbed", "version": "1.0","permissions": ["ui.modify"],- "tabs": [{ "title": "Other", "content": "/plugins/some-other-plugin/x.html" }]+ "tabs": [{ "title": "Other", "slug": "other", "content": "/plugins/some-other-plugin/x.html" }]}`))if err == nil {t.Fatal("expected error: cross-plugin tab content path")@@ -748,7 +747,7 @@ func TestParseManifest_Tabs_RejectsNonHtmlExtension(t *testing.T) {_, err := ParseManifest([]byte(`{"api": "1", "name": "tabbed", "version": "1.0","permissions": ["ui.modify"],- "tabs": [{ "title": "Bad", "content": "music.txt" }]+ "tabs": [{ "title": "Bad", "slug": "bad", "content": "music.txt" }]}`))if err == nil {t.Fatal("expected error: only .html extension allowed for tabs")diff --git a/services/plugins/package.go b/services/plugins/package.goindex ec95354c95..3ce209e275 100644--- a/services/plugins/package.go+++ b/services/plugins/package.go@@ -62,29 +62,32 @@ func LoadPackage(ctx context.Context, env *HostEnv, path string) (*Loaded, error}displayName := strings.TrimSuffix(filepath.Base(path), packageSuffix)- loaded, err := loadFromBytes(ctx, env, manifestBytes, wasmBytes, displayName)++ // Extract assetsFS from the zip before calling loadFromBytes so the+ // owncast_asset_read host function has access to it at instantiation time.+ var assetsFS fs.FS+ if hasZipDir(&zr.Reader, pkgAssetsPrefix) {+ if sub, err := fs.Sub(&zr.Reader, strings.TrimSuffix(pkgAssetsPrefix, "/")); err == nil {+ assetsFS = sub+ }+ }++ loaded, err := loadFromBytes(ctx, env, manifestBytes, wasmBytes, displayName, assetsFS)if err != nil {return nil, err}loaded.WasmPath = pathloaded.pkgCloser = zr- // Mount public/ as the plugin's web-served root and assets/ as- // the internal-only root, when each is present. fs.Sub returns- // an FS that's empty (rather than failing) when the prefix- // doesn't exist, so we check first to keep the nil-means-empty- // invariant the Server (PublicFS) and the manifest-asset reader- // (AssetsFS) rely on.+ // Mount public/ as the plugin's web-served root. AssetsFS is already set+ // by loadFromBytes. fs.Sub returns an FS that's empty (rather than failing)+ // when the prefix doesn't exist, so we check first to keep the+ // nil-means-empty invariant the Server (PublicFS) relies on.if hasZipDir(&zr.Reader, pkgPublicPrefix) {if sub, err := fs.Sub(&zr.Reader, strings.TrimSuffix(pkgPublicPrefix, "/")); err == nil {loaded.PublicFS = sub}}- if hasZipDir(&zr.Reader, pkgAssetsPrefix) {- if sub, err := fs.Sub(&zr.Reader, strings.TrimSuffix(pkgAssetsPrefix, "/")); err == nil {- loaded.AssetsFS = sub- }- }closeOnFail = nil // ownership transferred to Loaded.pkgCloserreturn loaded, nildiff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.jsonindex d42823991a..6f1d4472b8 100644--- a/services/plugins/plugin-contract.json+++ b/services/plugins/plugin-contract.json@@ -22,6 +22,7 @@},"hostFunctions": ["owncast_add_actions",+ "owncast_asset_read","owncast_ban_ip","owncast_chat_clients","owncast_chat_history",diff --git a/test/automated/plugins/tabs-demo.test.js b/test/automated/plugins/tabs-demo.test.jsindex e7edef8747..05e0610ad8 100644--- a/test/automated/plugins/tabs-demo.test.js+++ b/test/automated/plugins/tabs-demo.test.js@@ -19,7 +19,7 @@ test('/api/config pluginTabs advertises both tabs with their inlined HTML', asynconst res = await request.get('/api/config').expect(200);const { pluginTabs } = res.body;expect(Array.isArray(pluginTabs)).toBe(true);- const tabs = pluginTabs.filter((t) => t.slug === PLUGIN);+ const tabs = pluginTabs.filter((t) => t.pluginSlug === PLUGIN);expect(tabs.length).toBe(2);const music = tabs.find((t) => t.title === 'Music');@@ -40,5 +40,5 @@ test('disabling the plugin drops its tabs from /api/config', async () => {const res = await request.get('/api/config').expect(200);const { pluginTabs } = res.body;expect(Array.isArray(pluginTabs)).toBe(true);- expect(pluginTabs.find((t) => t.slug === PLUGIN)).toBeUndefined();+ expect(pluginTabs.find((t) => t.pluginSlug === PLUGIN)).toBeUndefined();});diff --git a/web/interfaces/client-config.model.ts b/web/interfaces/client-config.model.tsindex 8733fa1192..931e576f24 100644--- a/web/interfaces/client-config.model.ts+++ b/web/interfaces/client-config.model.ts@@ -56,7 +56,8 @@ interface SocialHandle {// PluginTab is one viewer-page tab contributed by a plugin via// manifest.tabs. Mirrors models.PluginTab on the backend.export interface PluginTab {- slug: string;+ slug: string; // composite unique key: pluginSlug/tabSlug+ pluginSlug: string; // source plugin identifiertitle: string;html: string;}diff --git a/webserver/handlers/config.go b/webserver/handlers/config.goindex 79cbe87f4b..25c7e66670 100644--- a/webserver/handlers/config.go+++ b/webserver/handlers/config.go@@ -75,17 +75,17 @@ func (h *Handlers) GetWebConfig(w http.ResponseWriter, r *http.Request) {middleware.DisableCache(w)w.Header().Set("Content-Type", "application/json")- configuration := h.getConfigResponse()+ configuration := h.getConfigResponse(r)if err := json.NewEncoder(w).Encode(configuration); err != nil {webutils.BadRequestHandler(w, err)}}-func (h *Handlers) getConfigResponse() webConfigResponse {+func (h *Handlers) getConfigResponse(r *http.Request) webConfigResponse {configRepository := h.configRepositorypageContent := utils.RenderPageContentMarkdown(configRepository.GetExtraPageBodyContent())- pageContent = prependPluginPageContent(pageContent, h.pluginPageContent)+ pageContent = prependPluginPageContent(pageContent, r, h.pluginPageContent)offlineMessage := utils.RenderSimpleMarkdown(configRepository.GetCustomOfflineMessage())socialHandles := configRepository.GetSocialHandles()for i, handle := range socialHandles {@@ -147,7 +147,7 @@ func (h *Handlers) getConfigResponse() webConfigResponse {ChatSpamProtectionDisabled: configRepository.GetChatSpamProtectionEnabled(),ChatRequireAuthentication: configRepository.GetChatRequireAuthentication(),ExternalActions: mergePluginActions(configRepository.GetExternalActions(), h.pluginActions),- PluginTabs: pluginTabsOrEmpty(h.pluginTabs),+ PluginTabs: pluginTabsOrEmpty(r, h.pluginTabs),CustomStyles: mergePluginCSS(configRepository.GetCustomStyles(), h.pluginCSSContent),MaxSocketPayloadSize: config.MaxSocketPayloadSize,Federation: federationResponse,@@ -163,11 +163,11 @@ func (h *Handlers) getConfigResponse() webConfigResponse {// returns nothing. The empty-slice contract keeps the JSON wire// shape stable: `pluginTabs: []` rather than `null`, so the viewer// doesn't need a defensive nil-check before iterating.-func pluginTabsOrEmpty(getter func() []models.PluginTab) []models.PluginTab {+func pluginTabsOrEmpty(r *http.Request, getter func(*http.Request) []models.PluginTab) []models.PluginTab {if getter == nil {return []models.PluginTab{}}- if t := getter(); len(t) > 0 {+ if t := getter(r); len(t) > 0 {return t}return []models.PluginTab{}@@ -179,11 +179,11 @@ func pluginTabsOrEmpty(getter func() []models.PluginTab) []models.PluginTab {// the admin's prose. A nil getter or empty contribution leaves the// admin's value untouched. A newline separates the two sources so// the trailing markup of one can't run into the next.-func prependPluginPageContent(admin string, pluginHTML func() []byte) string {+func prependPluginPageContent(admin string, r *http.Request, pluginHTML func(*http.Request) []byte) string {if pluginHTML == nil {return admin}- bytes := pluginHTML()+ bytes := pluginHTML(r)if len(bytes) == 0 {return admin}diff --git a/webserver/handlers/handlers.go b/webserver/handlers/handlers.goindex ce0f1fa6e0..8be812c9ae 100644--- a/webserver/handlers/handlers.go+++ b/webserver/handlers/handlers.go@@ -79,12 +79,12 @@ type Handlers struct {// contributed by loaded plugins via manifest.extraPageContent.// /api/config prepends these bytes to the admin's rendered// extraPageContent.- pluginPageContent func() []byte+ pluginPageContent func(*http.Request) []byte// pluginTabs returns the list of viewer-page tabs contributed by// loaded plugins via manifest.tabs. /api/config emits this list// as `pluginTabs`; the viewer page renders one tab per entry.- pluginTabs func() []models.PluginTab+ pluginTabs func(*http.Request) []models.PluginTab// previewThumbCache caches thumbnail/preview bytes for a short window// so frequent polling from chat clients doesn't re-read the file@@ -134,11 +134,11 @@ type Deps struct {// PluginPageContent returns the concatenated HTML bytes from// each loaded plugin's manifest.extraPageContent. Wired to the// plugin host's PageContent() method.- PluginPageContent func() []byte+ PluginPageContent func(*http.Request) []byte// PluginTabs returns the list of viewer-page tabs contributed by// loaded plugins via manifest.tabs. Wired to the plugin host's// Tabs() method.- PluginTabs func() []models.PluginTab+ PluginTabs func(*http.Request) []models.PluginTab}// HandleWebsocketConnection routes the /ws websocket upgrade to thediff --git a/webserver/handlers/index.go b/webserver/handlers/index.goindex 53c399efc1..257969d9df 100644--- a/webserver/handlers/index.go+++ b/webserver/handlers/index.go@@ -47,14 +47,14 @@ func (h *Handlers) IndexHandler(w http.ResponseWriter, r *http.Request) {middleware.SetHeaders(w, fmt.Sprintf("nonce-%s", nonceRandom))if isIndexRequest {- h.renderIndexHtml(w, nonceRandom)+ h.renderIndexHtml(w, r, nonceRandom)return}serveWeb(w, r)}-func (h *Handlers) renderIndexHtml(w http.ResponseWriter, nonce string) {+func (h *Handlers) renderIndexHtml(w http.ResponseWriter, r *http.Request, nonce string) {type serverSideContent struct {Name stringSummary string@@ -76,7 +76,7 @@ func (h *Handlers) renderIndexHtml(w http.ResponseWriter, nonce string) {return}- config := h.getConfigResponse()+ config := h.getConfigResponse(r)cb, err := json.Marshal(config)if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)