Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Report plugin mutation errors to plugins (#5106)
Gabe Kangasd2dc5e9e5854
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.goindex dbb6c34b85..d229137e1f 100644--- a/pluginhost/pluginhost.go+++ b/pluginhost/pluginhost.go@@ -1717,16 +1717,20 @@ func wireChatReadHostFns(env *plugins.HostEnv, deps Deps) {func wireChatModerationHostFns(env *plugins.HostEnv, deps Deps) {chatSvc := deps.Chat- env.DeleteMessage = func(pluginName, messageID string) {+ env.DeleteMessage = func(pluginName, messageID string) error {if err := chatSvc.SetMessagesVisibility([]string{messageID}, false); err != nil {- log.Errorln("plugin", pluginName, "delete message:", err)+ return err}+ return nil}- env.KickClient = func(pluginName string, clientID uint64) {- if c, ok := chatSvc.FindClientByID(uint(clientID)); ok {- chatSvc.DisconnectClients([]*chat.Client{c})+ env.KickClient = func(pluginName string, clientID uint64) error {+ c, ok := chatSvc.FindClientByID(uint(clientID))+ if !ok {+ return fmt.Errorf("chat client %d not found", clientID)}+ chatSvc.DisconnectClients([]*chat.Client{c})+ return nil}}@@ -1850,22 +1854,20 @@ func wireUserHostFns(env *plugins.HostEnv, deps Deps) {return toHostUser(u), true}- env.SetUserEnabled = func(pluginName, userID string, enabled bool, reason string) {+ env.SetUserEnabled = func(pluginName, userID string, enabled bool, reason string) error {if err := users.SetEnabled(userID, enabled); err != nil {- log.Errorln("plugin", pluginName, "set user enabled:", err)- return+ return err}if !enabled {if clients, err := chatSvc.GetClientsForUser(userID); err == nil {chatSvc.DisconnectClients(clients)}}+ return nil}- env.BanIP = func(pluginName, ip string) {- if err := deps.AuthRepository.BanIPAddress(ip, "banned by plugin "+pluginName); err != nil {- log.Errorln("plugin", pluginName, "ban ip:", err)- }+ env.BanIP = func(pluginName, ip string) error {+ return deps.AuthRepository.BanIPAddress(ip, "banned by plugin "+pluginName)}}diff --git a/services/plugins/contract_test.go b/services/plugins/contract_test.goindex 6fb2501628..0db0836d3b 100644--- a/services/plugins/contract_test.go+++ b/services/plugins/contract_test.go@@ -178,6 +178,8 @@ func TestOperationResultsUseErrorAsTheOnlyFailureSignal(t *testing.T) {"video config write failure": {VideoConfigWriteResult{Error: "failed"}, `{"error":"failed"}`},"auth session success": {GrantSessionResult{}, `{}`},"auth session failure": {GrantSessionResult{Error: "failed"}, `{"error":"failed"}`},+ "action add success": {ActionResult{}, `{}`},+ "action add failure": {ActionResult{Error: "failed"}, `{"error":"failed"}`},}for name, test := range tests {t.Run(name, func(t *testing.T) {diff --git a/services/plugins/engines/javascript/engine.wasm b/services/plugins/engines/javascript/engine.wasmindex 6b7f85cec6..00fd4b84be 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 300c588c7d..7328ee0277 100644Binary files a/services/plugins/engines/python/engine.wasm and b/services/plugins/engines/python/engine.wasm differdiff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.goindex 4495413c31..a2dc462883 100644--- a/services/plugins/hostfns.go+++ b/services/plugins/hostfns.go@@ -372,10 +372,10 @@ type HostEnv struct {Tags func() []string // server.readVideoConfig func() VideoConfig // videoconfig.readChatHistory func(limit int) []HostChatMessage- ChatClients func() []HostChatClient // chat.history- DeleteMessage func(pluginName, messageID string) // chat.moderate- KickClient func(pluginName string, clientID uint64) // chat.moderate- SendDiscord func(pluginName, text string) // notifications.send+ ChatClients func() []HostChatClient // chat.history+ DeleteMessage func(pluginName, messageID string) error // chat.moderate+ KickClient func(pluginName string, clientID uint64) error // chat.moderate+ SendDiscord func(pluginName, text string) // notifications.sendSendBrowserPush func(pluginName string, p BrowserPushPayload)Users func() []HostUser // users.readUserGet func(id string) (HostUser, bool) // users.read@@ -397,9 +397,9 @@ type HostEnv struct {// cookie itself is cleared via the request-scoped sink regardless; this is// for any additional cleanup. Optional; nil → no-op.EndSession func(pluginName string)- SetUserEnabled func(pluginName, userID string, enabled bool, reason string) // users.moderate- BanIP func(pluginName, ip string) // users.moderate- UploadStorage func(pluginName, name string, data []byte) (string, error) // storage.upload+ SetUserEnabled func(pluginName, userID string, enabled bool, reason string) error // users.moderate+ BanIP func(pluginName, ip string) error // users.moderate+ UploadStorage func(pluginName, name string, data []byte) (string, error) // storage.upload// Sandboxed per-plugin filesystem (storage.fs). Each plugin sees only// its own directory under data/plugin-storage/<slug>/files/, and the host// rejects any path that escapes it. Paths are relative to that root.@@ -959,6 +959,11 @@ type UserRegisterResult struct {Error string `json:"error,omitempty"`}+// ActionResult reports whether a plugin mutation failed.+type ActionResult struct {+ Error string `json:"error,omitempty"`+}+// GrantSessionRequest is the JSON payload a plugin sends to owncast.auth.grantSession.type GrantSessionRequest struct {UserID string `json:"userId"`@@ -1108,21 +1113,33 @@ func hostUserSetEnabled(env *HostEnv) extism.HostFunction {func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {ident, ok := resolveCaller(ctx, "owncast_user_set_enabled", PermUsersModerate)if !ok {+ stack[0] = 0return}pluginName := ident.slugid, err := p.ReadString(stack[0])if err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: "read user ID: " + err.Error()})return}enabled := stack[1] != 0- reason, _ := p.ReadString(stack[2])- if env.SetUserEnabled != nil {- env.SetUserEnabled(pluginName, id, enabled, reason)+ reason, err := p.ReadString(stack[2])+ if err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: "read reason: " + err.Error()})+ return}+ if env.SetUserEnabled == nil {+ stack[0] = writeJSON(p, ActionResult{Error: "users.moderate is not available on this host"})+ return+ }+ if err := env.SetUserEnabled(pluginName, id, enabled, reason); err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: err.Error()})+ return+ }+ stack[0] = writeJSON(p, ActionResult{})},[]extism.ValueType{extism.ValueTypePTR, extism.ValueTypeI64, extism.ValueTypePTR},- []extism.ValueType{},+ []extism.ValueType{extism.ValueTypePTR},)fn.SetNamespace("extism:host/user")return fn@@ -1134,19 +1151,27 @@ func hostBanIP(env *HostEnv) extism.HostFunction {func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {id, ok := resolveCaller(ctx, "owncast_ban_ip", PermUsersModerate)if !ok {+ stack[0] = 0return}pluginName := id.slugip, err := p.ReadString(stack[0])if err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: "read IP: " + err.Error()})return}- if env.BanIP != nil {- env.BanIP(pluginName, ip)+ if env.BanIP == nil {+ stack[0] = writeJSON(p, ActionResult{Error: "users.moderate is not available on this host"})+ return+ }+ if err := env.BanIP(pluginName, ip); err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: err.Error()})+ return}+ stack[0] = writeJSON(p, ActionResult{})},[]extism.ValueType{extism.ValueTypePTR},- []extism.ValueType{},+ []extism.ValueType{extism.ValueTypePTR},)fn.SetNamespace("extism:host/user")return fn@@ -1649,19 +1674,27 @@ func hostDeleteMessage(env *HostEnv) extism.HostFunction {func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {ident, ok := resolveCaller(ctx, "owncast_delete_message", PermChatModerate)if !ok {+ stack[0] = 0return}pluginName := ident.slugid, err := p.ReadString(stack[0])if err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: "read message ID: " + err.Error()})+ return+ }+ if env.DeleteMessage == nil {+ stack[0] = writeJSON(p, ActionResult{Error: "chat.moderate is not available on this host"})return}- if env.DeleteMessage != nil {- env.DeleteMessage(pluginName, id)+ if err := env.DeleteMessage(pluginName, id); err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: err.Error()})+ return}+ stack[0] = writeJSON(p, ActionResult{})},[]extism.ValueType{extism.ValueTypePTR},- []extism.ValueType{},+ []extism.ValueType{extism.ValueTypePTR},)fn.SetNamespace("extism:host/user")return fn@@ -1673,16 +1706,23 @@ func hostKickClient(env *HostEnv) extism.HostFunction {func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {id, ok := resolveCaller(ctx, "owncast_kick_client", PermChatModerate)if !ok {+ stack[0] = 0return}pluginName := id.slugclientID := stack[0]- if env.KickClient != nil {- env.KickClient(pluginName, clientID)+ if env.KickClient == nil {+ stack[0] = writeJSON(p, ActionResult{Error: "chat.moderate is not available on this host"})+ return}+ if err := env.KickClient(pluginName, clientID); err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: err.Error()})+ return+ }+ stack[0] = writeJSON(p, ActionResult{})},[]extism.ValueType{extism.ValueTypeI64},- []extism.ValueType{},+ []extism.ValueType{extism.ValueTypePTR},)fn.SetNamespace("extism:host/user")return fn@@ -2155,31 +2195,41 @@ func hostKVSet() extism.HostFunction {func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {id, ok := resolveCaller(ctx, "owncast_kv_set", PermStorageKV)if !ok {+ stack[0] = 0return}ns := id.kvNamespacekey, err := p.ReadString(stack[0])if err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: "read key: " + err.Error()})return}val, err := p.ReadBytes(stack[1])if err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: "read value: " + err.Error()})return}if len(key) > MaxKVKeyBytes {- fmt.Fprintf(os.Stderr, "owncast_kv_set from %s: key is %d bytes, limit is %d — dropped\n", id.slug, len(key), MaxKVKeyBytes)+ message := fmt.Sprintf("key is %d bytes, limit is %d", len(key), MaxKVKeyBytes)+ fmt.Fprintf(os.Stderr, "owncast_kv_set from %s: %s — dropped\n", id.slug, message)+ stack[0] = writeJSON(p, ActionResult{Error: message})return}if len(val) > MaxKVValueBytes {- fmt.Fprintf(os.Stderr, "owncast_kv_set from %s: value is %d bytes, limit is %d — dropped\n", id.slug, len(val), MaxKVValueBytes)+ message := fmt.Sprintf("value is %d bytes, limit is %d", len(val), MaxKVValueBytes)+ fmt.Fprintf(os.Stderr, "owncast_kv_set from %s: %s — dropped\n", id.slug, message)+ stack[0] = writeJSON(p, ActionResult{Error: message})return}if err := ns.Set(key, val); err != nil {fmt.Fprintf(os.Stderr, "owncast_kv_set: %v\n", err)+ stack[0] = writeJSON(p, ActionResult{Error: "kv write: " + err.Error()})+ return}+ stack[0] = writeJSON(p, ActionResult{})},[]extism.ValueType{extism.ValueTypePTR, extism.ValueTypePTR},- []extism.ValueType{},+ []extism.ValueType{extism.ValueTypePTR},)fn.SetNamespace("extism:host/user")return fn@@ -2198,14 +2248,15 @@ const RuntimeActionsConfigKey = "owncast.actions"// cross-plugin URLs rejected), and appends to the runtime list in the// plugin's config.//-// Requires the ui.modify permission; invalid input is logged but not-// surfaced back to the plugin.+// Requires the ui.modify permission. The returned error describes why the+// action list was rejected or could not be persisted.func hostAddActions(env *HostEnv) extism.HostFunction {fn := extism.NewHostFunctionWithStack("owncast_add_actions",func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {id, ok := resolveCaller(ctx, "owncast_add_actions", PermUIModify)if !ok {+ stack[0] = 0return}manifest := id.manifest@@ -2219,19 +2270,25 @@ func hostAddActions(env *HostEnv) extism.HostFunction {}payloadBytes, err := p.ReadBytes(stack[0])if err != nil {+ stack[0] = writeJSON(p, ActionResult{Error: "read payload: " + err.Error()})return}var incoming []ActionButtonif err := json.Unmarshal(payloadBytes, &incoming); err != nil {- fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: invalid JSON: %v\n", pluginSlug, err)+ message := "invalid JSON: " + err.Error()+ fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: %s\n", pluginSlug, message)+ stack[0] = writeJSON(p, ActionResult{Error: message})return}normalized, err := validateRuntimeActions(pluginSlug, hasHTTPServe, incoming)if err != nil {fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: %v\n", pluginSlug, err)+ stack[0] = writeJSON(p, ActionResult{Error: err.Error()})return}if env.KV == nil {+ message := "storage is not available on this host"+ stack[0] = writeJSON(p, ActionResult{Error: message})return}ns := env.KV.Namespace(pluginSlug)@@ -2244,15 +2301,20 @@ func hostAddActions(env *HostEnv) extism.HostFunction {combined = append(combined, normalized...)out, err := json.Marshal(combined)if err != nil {- fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: marshal: %v\n", pluginSlug, err)+ message := "marshal: " + err.Error()+ fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: %s\n", pluginSlug, message)+ stack[0] = writeJSON(p, ActionResult{Error: message})return}if err := ns.Set(RuntimeActionsConfigKey, out); err != nil {fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: kv write: %v\n", pluginSlug, err)+ stack[0] = writeJSON(p, ActionResult{Error: "kv write: " + err.Error()})+ return}+ stack[0] = writeJSON(p, ActionResult{})},[]extism.ValueType{extism.ValueTypePTR},- []extism.ValueType{},+ []extism.ValueType{extism.ValueTypePTR},)fn.SetNamespace("extism:host/user")return fn@@ -2267,18 +2329,23 @@ func hostClearActions(env *HostEnv) extism.HostFunction {func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {id, ok := resolveCaller(ctx, "owncast_clear_actions", PermUIModify)if !ok {+ stack[0] = 0return}pluginSlug := id.slugif env.KV == nil {+ stack[0] = writeJSON(p, ActionResult{Error: "storage is not available on this host"})return}if err := env.KV.Namespace(pluginSlug).Delete(RuntimeActionsConfigKey); err != nil {fmt.Fprintf(os.Stderr, "owncast_clear_actions from %s: %v\n", pluginSlug, err)+ stack[0] = writeJSON(p, ActionResult{Error: err.Error()})+ return}+ stack[0] = writeJSON(p, ActionResult{})},nil,- nil,+ []extism.ValueType{extism.ValueTypePTR},)fn.SetNamespace("extism:host/user")return fndiff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.jsonindex 95337d696c..f77afb8c7a 100644--- a/services/plugins/plugin-contract.json+++ b/services/plugins/plugin-contract.json@@ -76,6 +76,9 @@"owncast_video_config_write"],"wireTypes": {+ "ActionResult": {+ "error": "string"+ },"BrowserPushPayload": {"body": "string","title": "string",diff --git a/services/plugins/shared_engine_test.go b/services/plugins/shared_engine_test.goindex 8a5e6de719..d2061bd381 100644--- a/services/plugins/shared_engine_test.go+++ b/services/plugins/shared_engine_test.go@@ -93,6 +93,74 @@ module.exports = definePlugin({}}+func TestSharedEngineActionValidationErrorReachesJavaScript(t *testing.T) {+ ctx := context.Background()+ compiledEngines.resetForTest(ctx)+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })++ env, sends, mu := captureEnv()+ script := `+const { definePlugin, owncast } = require("@owncast/plugin-sdk");+module.exports = definePlugin({+ onChatMessage() {+ try {+ owncast.actions.add({ title: "broken" });+ } catch (err) {+ owncast.chat.send(err.message);+ }+ }+});`+ loaded := loadShared(t, ctx, env, RuntimeJavaScript, "action-errors", script,+ []string{PermChatSend, PermUIModify})+ defer loaded.Close(ctx)++ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{loaded} })+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "hi"))++ mu.Lock()+ defer mu.Unlock()+ if len(*sends) != 1 {+ t.Fatalf("expected one error message, got %d: %+v", len(*sends), *sends)+ }+ if got := (*sends)[0].Text; got != "actions[0]: exactly one of url or html is required" {+ t.Fatalf("action error = %q", got)+ }+}++func TestSharedEngineActionPermissionErrorReachesJavaScript(t *testing.T) {+ ctx := context.Background()+ compiledEngines.resetForTest(ctx)+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })++ env, sends, mu := captureEnv()+ script := `+const { definePlugin, owncast } = require("@owncast/plugin-sdk");+module.exports = definePlugin({+ onChatMessage() {+ try {+ owncast.actions.add({ title: "blocked" });+ } catch (err) {+ owncast.chat.send(err.message);+ }+ }+});`+ loaded := loadShared(t, ctx, env, RuntimeJavaScript, "action-permission-errors", script,+ []string{PermChatSend})+ defer loaded.Close(ctx)++ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{loaded} })+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "hi"))++ mu.Lock()+ defer mu.Unlock()+ if len(*sends) != 1 {+ t.Fatalf("expected one permission error message, got %d: %+v", len(*sends), *sends)+ }+ if got := (*sends)[0].Text; got != "owncast.actions.add failed" {+ t.Fatalf("permission error = %q", got)+ }+}+// TestSharedEnginePermissionGate is the R1 check: a plugin that calls a host// function for a permission it was not granted must be denied at call time// (the shared engine links every host import, so the gate is the only@@ -443,6 +511,68 @@ func assertHasCommand(t *testing.T, l *Loaded, name, desc string) {t.Errorf("%s: register() did not report command %q; got %+v", l.Manifest.Slug, name, l.Manifest.Commands)}+func TestSharedEngineActionValidationErrorReachesPython(t *testing.T) {+ ctx := context.Background()+ compiledEngines.resetForTest(ctx)+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })++ env, sends, mu := captureEnv()+ script := `[email protected]_chat_message+def handle(msg):+ try:+ owncast.actions.add({"title": "broken"})+ except Exception as err:+ owncast.chat.send(str(err))+`+ loaded := loadShared(t, ctx, env, RuntimePython, "python-action-errors", script,+ []string{PermChatSend, PermUIModify})+ defer loaded.Close(ctx)++ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{loaded} })+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "hi"))++ mu.Lock()+ defer mu.Unlock()+ if len(*sends) != 1 {+ t.Fatalf("expected one error message, got %d: %+v", len(*sends), *sends)+ }+ if got := (*sends)[0].Text; got != "actions[0]: exactly one of url or html is required" {+ t.Fatalf("action error = %q", got)+ }+}++func TestSharedEngineActionPermissionErrorReachesPython(t *testing.T) {+ ctx := context.Background()+ compiledEngines.resetForTest(ctx)+ t.Cleanup(func() { compiledEngines.resetForTest(ctx) })++ env, sends, mu := captureEnv()+ script := `[email protected]_chat_message+def handle(msg):+ try:+ owncast.actions.add({"title": "blocked"})+ except Exception as err:+ owncast.chat.send(str(err))+`+ loaded := loadShared(t, ctx, env, RuntimePython, "python-action-permission-errors", script,+ []string{PermChatSend})+ defer loaded.Close(ctx)++ d := NewLiveDispatcher(func() []*Loaded { return []*Loaded{loaded} })+ d.Dispatch(ctx, EventChatMessageReceived, chatPayload("alice", "hi"))++ mu.Lock()+ defer mu.Unlock()+ if len(*sends) != 1 {+ t.Fatalf("expected one permission error message, got %d: %+v", len(*sends), *sends)+ }+ if got := (*sends)[0].Text; got != "owncast.actions.add failed" {+ t.Fatalf("permission error = %q", got)+ }+}+func TestSharedEnginePythonRegister(t *testing.T) {ctx := context.Background()compiledEngines.resetForTest(ctx)