Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
feat(plugins): add dynamic onPageStyles and onPageScripts viewer-page hooks
Gabe Kangas79c12bbbffdf
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.goindex 05a0b5302e..85f69ea8fe 100644--- a/pluginhost/pluginhost.go+++ b/pluginhost/pluginhost.go@@ -165,10 +165,46 @@ func (p *Host) Actions() []models.ExternalAction {// per plugin asset. Disabled or not-loaded plugins contribute// nothing.func (p *Host) StylesContent() []byte {- return p.readManifestAssets(+ out := p.readManifestAssets(func(m *plugins.Manifest) []string { return m.Styles },"/* plugin: %s — %s */\n",)+ return append(out, p.dynamicStyles()...)+}++// dynamicStyles returns the CSS contributed at request time by every enabled+// plugin's on_page_styles export. The host calls the export for any plugin+// holding ui.modify; a plugin opts in just by exporting the function (no+// manifest field). Output is appended after the static manifest.styles bytes,+// so a plugin can ship a static base and have the hook return only the+// selected override — the later rule wins in the cascade.+func (p *Host) dynamicStyles() []byte {+ if p == nil || p.manager == nil {+ return nil+ }+ var buf bytes.Buffer+ for _, l := range p.manager.Snapshot() {+ if l == nil || l.Manifest == nil {+ continue+ }+ if !manifestHasPermission(l.Manifest, plugins.PermUIModify) {+ continue+ }+ css, err := l.CallPageStyles(context.Background())+ if err != nil {+ log.Warnf("plugin %s: on_page_styles error: %v", l.Manifest.Slug, err)+ continue+ }+ if css == "" {+ continue+ }+ fmt.Fprintf(&buf, "/* plugin: %s — dynamic */\n", l.Manifest.Slug)+ buf.WriteString(css)+ if css[len(css)-1] != '\n' {+ buf.WriteByte('\n')+ }+ }+ return buf.Bytes()}// ScriptsContent mirrors StylesContent for manifest.scripts: returns@@ -176,11 +212,68 @@ func (p *Host) StylesContent() []byte {// plugin, with `// plugin: <slug>` delimiters between contributions.// Appended to the admin's customJavascript by the /customjavascript// handler so the viewer page loads one script tag for both sources.+//+// Each plugin's contribution — static manifest.scripts files and the+// dynamic on_page_scripts output alike — is wrapped in a try/catch so a+// runtime error in one plugin's script doesn't abort the rest of the+// shared bundle (and with it the viewer page). Syntax errors are not+// isolated: parsing the bundle fails before any try block runs.func (p *Host) ScriptsContent() []byte {- return p.readManifestAssets(- func(m *plugins.Manifest) []string { return m.Scripts },- "// plugin: %s — %s\n",- )+ if p == nil || p.manager == nil {+ return nil+ }+ var buf bytes.Buffer+ for _, l := range p.manager.Snapshot() {+ if l == nil || l.Manifest == nil {+ continue+ }+ slug := l.Manifest.Slug+ if l.AssetsFS != nil {+ pluginPrefix := "/plugins/" + slug + "/"+ for _, entry := range l.Manifest.Scripts {+ relPath := strings.TrimPrefix(entry, pluginPrefix)+ data, err := fs.ReadFile(l.AssetsFS, relPath)+ if err != nil {+ log.Warnf("plugin %s: skipping asset %s: %v", slug, relPath, err)+ continue+ }+ writeWrappedScript(&buf, slug, relPath, data)+ }+ }+ if manifestHasPermission(l.Manifest, plugins.PermUIModify) {+ js, err := l.CallPageScripts(context.Background())+ if err != nil {+ log.Warnf("plugin %s: on_page_scripts error: %v", slug, err)+ } else if js != "" {+ writeWrappedScript(&buf, slug, "dynamic", []byte(js))+ }+ }+ }+ return buf.Bytes()+}++// writeWrappedScript appends one plugin script contribution, wrapped in a+// try/catch keyed to the plugin slug so a thrown error is logged to the+// browser console instead of breaking later plugins' scripts.+func writeWrappedScript(buf *bytes.Buffer, slug, source string, code []byte) {+ fmt.Fprintf(buf, "// plugin: %s — %s\ntry {\n", slug, source)+ buf.Write(code)+ if len(code) > 0 && code[len(code)-1] != '\n' {+ buf.WriteByte('\n')+ }+ fmt.Fprintf(buf, "} catch (e) { console.error(%q, e); }\n", "owncast plugin "+slug+" script error:")+}++// manifestHasPermission reports whether the manifest declares perm. Used to+// gate the dynamic style/script hooks on ui.modify at call time, since those+// hooks have no manifest field whose validation could enforce it at load.+func manifestHasPermission(m *plugins.Manifest, perm string) bool {+ for _, granted := range m.Permissions {+ if granted == perm {+ return true+ }+ }+ return false}// PageContent returns the concatenated HTML bytes contributed bydiff --git a/pluginhost/pluginstyles_test.go b/pluginhost/pluginstyles_test.gonew file mode 100644index 0000000000..bb8ea31a2b--- /dev/null+++ b/pluginhost/pluginstyles_test.go@@ -0,0 +1,47 @@+package pluginhost++import (+ "bytes"+ "strings"+ "testing"++ plugins "github.com/owncast/owncast/services/plugins"+)++// writeWrappedScript wraps each plugin's JS in a try/catch so one plugin's+// runtime error can't break the shared /customjavascript bundle.+func TestWriteWrappedScript(t *testing.T) {+ var buf bytes.Buffer+ writeWrappedScript(&buf, "demo", "client.js", []byte("doThing();"))+ out := buf.String()++ for _, want := range []string{+ "// plugin: demo — client.js",+ "try {",+ "doThing();",+ `} catch (e) { console.error("owncast plugin demo script error:", e); }`,+ } {+ if !strings.Contains(out, want) {+ t.Errorf("wrapped script missing %q\n got:\n%s", want, out)+ }+ }++ // A contribution without a trailing newline still gets one before the+ // catch, so the `}` doesn't land on the plugin's last line.+ if !strings.Contains(out, "doThing();\n} catch") {+ t.Errorf("expected newline inserted before catch; got:\n%s", out)+ }+}++func TestManifestHasPermission(t *testing.T) {+ m := &plugins.Manifest{Permissions: []string{"storage.kv", "ui.modify"}}+ if !manifestHasPermission(m, plugins.PermUIModify) {+ t.Error("expected ui.modify to be reported as granted")+ }+ if manifestHasPermission(m, "http.serve") {+ t.Error("did not expect http.serve to be reported as granted")+ }+ if manifestHasPermission(&plugins.Manifest{}, plugins.PermUIModify) {+ t.Error("empty permission list should grant nothing")+ }+}diff --git a/services/plugins/engines/javascript/engine.wasm b/services/plugins/engines/javascript/engine.wasmindex 0af7d7a11f..b2639c78d5 100644Binary files a/services/plugins/engines/javascript/engine.wasm and b/services/plugins/engines/javascript/engine.wasm differdiff --git a/services/plugins/engines/python/engine.wasm b/services/plugins/engines/python/engine.wasmindex 66b2e9d38c..f6528f450b 100644Binary files a/services/plugins/engines/python/engine.wasm and b/services/plugins/engines/python/engine.wasm differdiff --git a/services/plugins/manager.go b/services/plugins/manager.goindex 325534fa56..77c2366455 100644--- a/services/plugins/manager.go+++ b/services/plugins/manager.go@@ -227,6 +227,43 @@ func (p *Loaded) callContentExport(ctx context.Context, export, slug string, usereturn string(out), nil}+// CallPageStyles invokes the plugin's on_page_styles export, returning the+// CSS the plugin wants inlined into the viewer page's customStyles. The host+// calls this for every enabled plugin that holds ui.modify; a plugin opts in+// simply by exporting the function. Returns empty string when the plugin does+// not export on_page_styles. Unlike on_page_content, the call takes no slug or+// user — dynamic styles are global so the /api/config response stays cacheable.+func (p *Loaded) CallPageStyles(ctx context.Context) (string, error) {+ return p.callVoidExport(ctx, "on_page_styles")+}++// CallPageScripts mirrors CallPageStyles for the plugin's on_page_scripts+// export, returning JavaScript to append to the viewer's customJavascript.+func (p *Loaded) CallPageScripts(ctx context.Context) (string, error) {+ return p.callVoidExport(ctx, "on_page_scripts")+}++// callVoidExport invokes an export that takes no input and returns a string.+// Used by the global, user-agnostic dynamic-content hooks (on_page_styles,+// on_page_scripts). Returns empty string when the plugin doesn't export it.+func (p *Loaded) callVoidExport(ctx context.Context, export string) (string, error) {+ p.mu.Lock()+ pl := p.plugin+ p.mu.Unlock()+ if pl == nil || !pl.FunctionExists(export) {+ return "", nil+ }+ callCtx, cancel := context.WithTimeout(ctx, HTTPHandlerTimeout)+ defer cancel()+ p.mu.Lock()+ _, out, err := pl.CallWithContext(callCtx, export, nil)+ 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) {