Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
feat(plugins): pass chat user identity to plugin http hooks + add filesystem access to plugins
Gabe Kangas3e92c9138d50
diff --git a/docs/plugins.md b/docs/plugins.mdindex 0a6d49bfdc..72b1f2db35 100644--- a/docs/plugins.md+++ b/docs/plugins.md@@ -97,8 +97,12 @@ that decoupling, and it lives at the boundary on purpose.- **Users** (`users.read` / `users.moderate`) — list/get users, set enabled,ban IP.- **Notifications** (`notifications.send`) — Discord, browser push, fediverse.-- **Storage** — KV backed by Owncast's datastore (`newDatastoreKVStore`), and- `storage.upload` for plugin assets.+- **Storage** — KV backed by Owncast's datastore (`newDatastoreKVStore`),+ `storage.upload` for browser-accessible plugin assets (written under+ `public/`), and `storage.fs` for a private, sandboxed filesystem+ (`data/plugin-data/<slug>/`) the plugin can read/write/list/delete within.+ The host rejects any `storage.fs` path that escapes the plugin's own+ directory, and the bytes are never served over HTTP.- **HTTP** (`http.serve`, `http.sse`) — `req.authenticated` / `req.user` fromOwncast's auth middleware, plus the SSE hub for server-pushed events.diff --git a/pluginhost/filesystem_test.go b/pluginhost/filesystem_test.gonew file mode 100644index 0000000000..fd031680ab--- /dev/null+++ b/pluginhost/filesystem_test.go@@ -0,0 +1,144 @@+package pluginhost++import (+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/owncast/owncast/services/plugins"+)++// resolvePluginSandboxPath is the security boundary for the storage.fs+// host functions: every plugin-supplied path must resolve to somewhere+// inside that plugin's own sandbox, no matter how the plugin tries to+// climb out. These tests pin that contract.++func TestResolvePluginSandboxPath_StaysInsideSandbox(t *testing.T) {+ root := t.TempDir()+ sandbox := filepath.Join(root, "my-plugin")++ cases := []struct {+ name string+ rel string+ want string // path relative to the sandbox, after resolution+ }{+ {"simple file", "notes.txt", "notes.txt"},+ {"nested file", "cache/today.json", "cache/today.json"},+ {"empty path is the sandbox root", "", "."},+ {"dot is the sandbox root", ".", "."},+ {"leading slash is rooted at the sandbox", "/etc/passwd", "etc/passwd"},+ {"single parent collapses inside", "../secret", "secret"},+ {"many parents collapse inside", "../../../../etc/passwd", "etc/passwd"},+ {"interior parent is normalized", "a/b/../c", "a/c"},+ {"sneaky mixed traversal", "foo/../../bar", "bar"},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got, err := resolvePluginSandboxPath(root, "my-plugin", tc.rel)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ want := filepath.Join(sandbox, tc.want)+ if got != want {+ t.Fatalf("resolvePluginSandboxPath(%q) = %q, want %q", tc.rel, got, want)+ }+ if got != sandbox && !strings.HasPrefix(got, sandbox+string(os.PathSeparator)) {+ t.Fatalf("resolved path %q escaped sandbox %q", got, sandbox)+ }+ })+ }+}++func TestResolvePluginSandboxPath_IsolatesPlugins(t *testing.T) {+ root := t.TempDir()+ // One plugin must never resolve a path into another plugin's sandbox,+ // even by spelling the sibling's name through a traversal sequence.+ got, err := resolvePluginSandboxPath(root, "plugin-a", "../plugin-b/data.json")+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ sibling := filepath.Join(root, "plugin-b")+ if got == sibling || strings.HasPrefix(got, sibling+string(os.PathSeparator)) {+ t.Fatalf("plugin-a resolved into plugin-b's sandbox: %q", got)+ }+ if want := filepath.Join(root, "plugin-a", "plugin-b", "data.json"); got != want {+ t.Fatalf("got %q, want %q", got, want)+ }+}++// TestFilesystemHostFns_RoundTrip exercises the wired closures end to end+// against a sandbox rooted at a temp dir, confirming write/read/list/+// exists/delete agree and that a traversal attempt is refused.+func TestFilesystemHostFns_RoundTrip(t *testing.T) {+ root := t.TempDir()+ env := &plugins.HostEnv{}+ wireFilesystemHostFnsWithRoot(env, root)++ const slug = "demo"+ if err := env.FSWrite(slug, "sub/greeting.txt", []byte("hello")); err != nil {+ t.Fatalf("FSWrite: %v", err)+ }++ // The bytes landed inside the plugin's sandbox, nowhere else.+ onDisk := filepath.Join(root, slug, "sub", "greeting.txt")+ if data, err := os.ReadFile(onDisk); err != nil || string(data) != "hello" {+ t.Fatalf("expected file at %q with %q, got data=%q err=%v", onDisk, "hello", data, err)+ }++ if data, err := env.FSRead(slug, "sub/greeting.txt"); err != nil || string(data) != "hello" {+ t.Fatalf("FSRead = %q, %v; want %q", data, err, "hello")+ }++ names, err := env.FSList(slug, "sub")+ if err != nil {+ t.Fatalf("FSList: %v", err)+ }+ if len(names) != 1 || names[0] != "greeting.txt" {+ t.Fatalf("FSList = %v, want [greeting.txt]", names)+ }++ if ok, err := env.FSExists(slug, "sub/greeting.txt"); err != nil || !ok {+ t.Fatalf("FSExists = %v, %v; want true", ok, err)+ }+ if ok, err := env.FSExists(slug, "sub/missing.txt"); err != nil || ok {+ t.Fatalf("FSExists(missing) = %v, %v; want false", ok, err)+ }++ if err := env.FSDelete(slug, "sub/greeting.txt"); err != nil {+ t.Fatalf("FSDelete: %v", err)+ }+ if ok, _ := env.FSExists(slug, "sub/greeting.txt"); ok {+ t.Fatalf("file still exists after delete")+ }++ // Listing a directory that doesn't exist is empty, not an error.+ if names, err := env.FSList(slug, "never-created"); err != nil || len(names) != 0 {+ t.Fatalf("FSList(missing dir) = %v, %v; want empty, nil", names, err)+ }++ // A traversal attempt is neutralized, not leaked: "../escape.txt"+ // collapses to a file inside the plugin's own sandbox, and nothing is+ // written to the parent (sibling-plugin / data-dir) level.+ if err := env.FSWrite(slug, "../escape.txt", []byte("x")); err != nil {+ t.Fatalf("FSWrite (traversal) should be contained, not error: %v", err)+ }+ if _, err := os.Stat(filepath.Join(root, "escape.txt")); !os.IsNotExist(err) {+ t.Fatalf("traversal write leaked a file outside the sandbox")+ }+ if _, err := os.Stat(filepath.Join(root, slug, "escape.txt")); err != nil {+ t.Fatalf("traversal write should have landed inside the sandbox: %v", err)+ }+}++func TestFilesystemHostFns_RejectsOversizedWrite(t *testing.T) {+ root := t.TempDir()+ env := &plugins.HostEnv{}+ wireFilesystemHostFnsWithRoot(env, root)++ tooBig := make([]byte, maxPluginFileBytes+1)+ if err := env.FSWrite("demo", "big.bin", tooBig); err == nil {+ t.Fatalf("expected oversized write to be rejected")+ }+}diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.goindex 3e3282a076..b5c05b718f 100644--- a/pluginhost/pluginhost.go+++ b/pluginhost/pluginhost.go@@ -640,6 +640,123 @@ func wirePluginHostEnv(env *plugins.HostEnv, deps Deps) {wireUserHostFns(env, deps)wireNotificationHostFns(env, deps)wireRequestHostFns(env, deps)+ wireFilesystemHostFns(env)+}++// pluginDataRootDirName is the directory under config.DataDirectory that+// holds each plugin's private, sandboxed filesystem (storage.fs). It is+// deliberately separate from the plugins install/scan directory+// (config.DataDirectory/plugins) so a plugin's writable data can never be+// mistaken for, or collide with, an installed package or its assets.+const pluginDataRootDirName = "plugin-data"++// maxPluginFileBytes caps a single storage.fs write. It bounds how much a+// misbehaving plugin can write in one call; the host's overall disk use is+// still the admin's responsibility.+const maxPluginFileBytes = 50 << 20 // 50 MiB++// resolvePluginSandboxPath maps a plugin-supplied relative path to an+// absolute path inside that plugin's sandbox (root/<pluginName>), and+// guarantees the result cannot escape it. rel is treated as rooted before+// cleaning, so "../", absolute paths, and other traversal tricks all+// collapse back inside the sandbox; a defensive prefix check rejects+// anything that still lands outside. pluginName is the plugin slug, which+// the manifest layer has already constrained to [a-z][a-z0-9-]*, so it+// cannot itself contain separators or "..".+func resolvePluginSandboxPath(root, pluginName, rel string) (string, error) {+ sandbox, err := filepath.Abs(filepath.Join(root, pluginName))+ if err != nil {+ return "", err+ }+ // Rooting rel at "/" before Clean neutralizes leading "../" segments:+ // filepath.Clean("/"+"../../etc") == "/etc", which then joins back under+ // the sandbox rather than above it.+ full := filepath.Join(sandbox, filepath.Clean("/"+rel))+ if full != sandbox && !strings.HasPrefix(full, sandbox+string(os.PathSeparator)) {+ return "", fmt.Errorf("path %q escapes the plugin sandbox", rel)+ }+ return full, nil+}++// wireFilesystemHostFns implements the storage.fs host functions against a+// per-plugin sandbox directory under config.DataDirectory/plugin-data.+func wireFilesystemHostFns(env *plugins.HostEnv) {+ wireFilesystemHostFnsWithRoot(env, filepath.Join(config.DataDirectory, pluginDataRootDirName))+}++// wireFilesystemHostFnsWithRoot is wireFilesystemHostFns with the sandbox+// parent directory injected, so tests can point the storage.fs functions at+// a temp directory instead of the real data directory.+func wireFilesystemHostFnsWithRoot(env *plugins.HostEnv, root string) {+ env.FSRead = func(pluginName, path string) ([]byte, error) {+ full, err := resolvePluginSandboxPath(root, pluginName, path)+ if err != nil {+ return nil, err+ }+ // gosec G304: full is confined to the plugin's sandbox by+ // resolvePluginSandboxPath, which rejects any path that escapes it.+ return os.ReadFile(full) //nolint:gosec // G304: path sandboxed above+ }++ env.FSWrite = func(pluginName, path string, data []byte) error {+ if len(data) > maxPluginFileBytes {+ return fmt.Errorf("file is %d bytes; the limit is %d", len(data), maxPluginFileBytes)+ }+ full, err := resolvePluginSandboxPath(root, pluginName, path)+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(full), 0o700); err != nil {+ return err+ }+ // gosec G304: full is confined to the plugin's sandbox by+ // resolvePluginSandboxPath, which rejects any path that escapes it.+ return os.WriteFile(full, data, 0o600) //nolint:gosec // G304: path sandboxed above+ }++ env.FSList = func(pluginName, dir string) ([]string, error) {+ full, err := resolvePluginSandboxPath(root, pluginName, dir)+ if err != nil {+ return nil, err+ }+ entries, err := os.ReadDir(full)+ if err != nil {+ if os.IsNotExist(err) {+ return []string{}, nil+ }+ return nil, err+ }+ names := make([]string, 0, len(entries))+ for _, e := range entries {+ names = append(names, e.Name())+ }+ return names, nil+ }++ env.FSDelete = func(pluginName, path string) error {+ full, err := resolvePluginSandboxPath(root, pluginName, path)+ if err != nil {+ return err+ }+ // os.Remove deletes a file or an empty directory only; it won't+ // recursively wipe a populated subtree, which keeps a single+ // delete call from being more destructive than the plugin asked.+ return os.Remove(full)+ }++ env.FSExists = func(pluginName, path string) (bool, error) {+ full, err := resolvePluginSandboxPath(root, pluginName, path)+ if err != nil {+ return false, err+ }+ if _, err := os.Stat(full); err != nil {+ if os.IsNotExist(err) {+ return false, nil+ }+ return false, err+ }+ return true, nil+ }}// wireVideoConfigHostFns wires the settable video/transcoding configuration:diff --git a/services/chat/server.go b/services/chat/server.goindex 23b99de816..20c54b9961 100644--- a/services/chat/server.go+++ b/services/chat/server.go@@ -269,13 +269,24 @@ func (s *Service) HandleClientConnection(w http.ResponseWriter, r *http.Request)return true}- conn, err := upgrader.Upgrade(w, r, nil)+ // Read the access token before upgrading so we can set the chat identity+ // cookie on the handshake response — once the connection is upgraded the+ // underlying ResponseWriter is hijacked and can no longer set headers.+ // This covers returning users whose token predates the cookie, since+ // every chat session opens a websocket with the token in the query.+ accessToken := r.URL.Query().Get("accessToken")+ var responseHeader http.Header+ if accessToken != "" {+ responseHeader = http.Header{}+ utils.AddChatAccessTokenCookieHeader(responseHeader, r, accessToken)+ }++ conn, err := upgrader.Upgrade(w, r, responseHeader)if err != nil {log.Debugln(err)return}- accessToken := r.URL.Query().Get("accessToken")if accessToken == "" {log.Errorln("Access token is required")// Return HTTP status codediff --git a/services/plugins/events.go b/services/plugins/events.goindex f819ebdd1b..9d4837fa1c 100644--- a/services/plugins/events.go+++ b/services/plugins/events.go@@ -16,6 +16,14 @@ const (EventStreamStopped = "stream.stopped"EventStreamTitleChanged = "stream.title.changed"+ // SSE connection lifecycle. Fired to the plugin that owns a+ // Server-Sent-Events channel when a browser opens or closes a connection+ // to it, so the plugin can track who is currently connected. The payload+ // is an SSEConnectionEvent. Requires the http.sse permission (the same+ // gate as serving the stream).+ EventSSEConnect = "sse.connect"+ EventSSEDisconnect = "sse.disconnect"+// Fediverse events. Engagement (follow/like/repost) carries only// actor + target metadata; mention/reply also carry the post content// so plugins can act on what was actually said.diff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.goindex e738699262..0f1638115f 100644--- a/services/plugins/hostfns.go+++ b/services/plugins/hostfns.go@@ -19,9 +19,16 @@ var _ = (*http.Request)(nil) // ensure import retained for the HostEnv signatureconst (PermStorageKV = "storage.kv"PermStorageUpload = "storage.upload"- PermChatSend = "chat.send"- PermChatHistory = "chat.history"- PermChatModerate = "chat.moderate"+ // PermStorageFS grants a plugin a private, sandboxed area on disk+ // (data/plugin-data/<slug>/) it can read, write, list, and delete+ // within. Unlike storage.upload (which publishes browser-accessible+ // files under public/), this storage is server-side only and never+ // exposed over HTTP. A plugin cannot reach outside its own directory+ // or read another plugin's files.+ PermStorageFS = "storage.fs"+ PermChatSend = "chat.send"+ PermChatHistory = "chat.history"+ PermChatModerate = "chat.moderate"// PermChatFilter is required for any plugin that subscribes to// filterChatMessage. The host refuses to load a plugin whose// runtime-declared filter subscriptions include the chat-message@@ -47,6 +54,10 @@ const (PermUIModify = "ui.modify")+// resultErrorKey is the JSON key host functions use to return an error+// string to the plugin in their {ok, error?} result envelope.+const resultErrorKey = "error"+// ChatSendKind distinguishes how a plugin asked to post to chat. All sends// post under the plugin's own chat identity — provisioned by the host at// install time as a chat user with IsBot=true and DisplayName=plugin name.@@ -207,6 +218,19 @@ type UploadResult struct {URL string `json:"url"`}+// SSEConnectionEvent is the payload for the sse.connect / sse.disconnect+// events, fired when a browser opens or closes one of the plugin's+// Server-Sent-Events streams. ConnectionID is unique for the life of the host+// process, so a plugin can pair a disconnect with its connect and count+// distinct connections (e.g. one user open in several tabs). User is the+// resolved chat user when the connection carried a chat identity, and is+// omitted for anonymous viewers.+type SSEConnectionEvent struct {+ Channel string `json:"channel"`+ ConnectionID uint64 `json:"connectionId"`+ User *HostUser `json:"user,omitempty"`+}+// HostEnv is everything host functions need to do their job. Function-pointer// fields are wired by the host (the production Owncast binary, the demo// binary, or the test runner); each host function reads them lazily at call@@ -231,8 +255,16 @@ type HostEnv struct {SetUserEnabled func(pluginName, userID string, enabled bool, reason string) // users.moderateBanIP func(pluginName, ip string) // users.moderateUploadStorage func(pluginName, name string, data []byte) (string, error) // storage.upload- Socials func() []SocialHandle // server.read- Federation func() FederationInfo // server.read+ // Sandboxed per-plugin filesystem (storage.fs). Each plugin sees only+ // its own directory under data/plugin-data/<slug>/; the host rejects any+ // path that escapes it. Paths are relative to that root.+ FSRead func(pluginName, path string) ([]byte, error) // storage.fs+ FSWrite func(pluginName, path string, data []byte) error+ FSList func(pluginName, dir string) ([]string, error)+ FSDelete func(pluginName, path string) error+ FSExists func(pluginName, path string) (bool, error)+ Socials func() []SocialHandle // server.read+ Federation func() FederationInfo // server.read// WriteVideoConfig applies a partial video/transcoding configuration// change. Returns an error the plugin can see if the host rejects the// config (e.g. an invalid variant). videoconfig.write permission required.@@ -326,9 +358,7 @@ func BuildHostFunctions(env *HostEnv, manifest *Manifest) []extism.HostFunctionhostBanIP(env, manifest.Slug),)}- if granted[PermStorageUpload] {- fns = append(fns, hostStorageUpload(env, manifest.Slug))- }+ fns = append(fns, storageHostFunctions(env, manifest, granted)...)if granted[PermFediversePost] {fns = append(fns, hostFediversePost(env, manifest.Slug))}@@ -345,6 +375,26 @@ func BuildHostFunctions(env *HostEnv, manifest *Manifest) []extism.HostFunctionreturn fns}+// storageHostFunctions returns the storage.upload / storage.fs host functions+// a plugin is granted. Split out of BuildHostFunctions to keep that function's+// cyclomatic complexity in check.+func storageHostFunctions(env *HostEnv, manifest *Manifest, granted map[string]bool) []extism.HostFunction {+ var fns []extism.HostFunction+ if granted[PermStorageUpload] {+ fns = append(fns, hostStorageUpload(env, manifest.Slug))+ }+ if granted[PermStorageFS] {+ fns = append(fns,+ hostFSRead(env, manifest.Slug),+ hostFSWrite(env, manifest.Slug),+ hostFSList(env, manifest.Slug),+ hostFSDelete(env, manifest.Slug),+ hostFSExists(env, manifest.Slug),+ )+ }+ return fns+}+// videoConfigHostFunctions returns the videoconfig.read / videoconfig.write// host functions a plugin is granted. Split out of BuildHostFunctions to keep// that function's cyclomatic complexity in check.@@ -711,6 +761,191 @@ func hostStorageUpload(env *HostEnv, pluginName string) extism.HostFunction {return fn}+// hostFSRead backs owncast.fs.read(path). Returns the file's raw bytes,+// or 0 (null to the plugin) when the path is missing, escapes the+// sandbox, or can't be read. Requires the storage.fs permission.+func hostFSRead(env *HostEnv, pluginName string) extism.HostFunction {+ fn := extism.NewHostFunctionWithStack(+ "owncast_fs_read",+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {+ path, err := p.ReadString(stack[0])+ if err != nil || env.FSRead == nil {+ stack[0] = 0+ return+ }+ data, err := env.FSRead(pluginName, path)+ if err != nil {+ fmt.Fprintf(os.Stderr, "owncast_fs_read from %s: %v\n", pluginName, err)+ 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+}++// hostFSWrite backs owncast.fs.write(path, data). Creates parent+// directories as needed and writes the bytes, returning a JSON+// {ok, error?} result so the plugin can react to a rejected write+// (sandbox escape, oversized payload, disk error). Requires storage.fs.+func hostFSWrite(env *HostEnv, pluginName string) extism.HostFunction {+ fn := extism.NewHostFunctionWithStack(+ "owncast_fs_write",+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {+ path, err := p.ReadString(stack[0])+ if err != nil {+ stack[0] = 0+ return+ }+ data, err := p.ReadBytes(stack[1])+ if err != nil {+ stack[0] = 0+ return+ }+ result := map[string]any{"ok": true}+ if env.FSWrite == nil {+ result = map[string]any{"ok": false, resultErrorKey: "filesystem unavailable"}+ } else if err := env.FSWrite(pluginName, path, data); err != nil {+ fmt.Fprintf(os.Stderr, "owncast_fs_write from %s: %v\n", pluginName, err)+ result = map[string]any{"ok": false, resultErrorKey: err.Error()}+ }+ out, err := json.Marshal(result)+ if err != nil {+ stack[0] = 0+ return+ }+ offset, err := p.WriteBytes(out)+ if err != nil {+ stack[0] = 0+ return+ }+ stack[0] = offset+ },+ []extism.ValueType{extism.ValueTypePTR, extism.ValueTypePTR},+ []extism.ValueType{extism.ValueTypePTR},+ )+ fn.SetNamespace("extism:host/user")+ return fn+}++// hostFSList backs owncast.fs.list(dir). Returns a JSON array of the+// entry names (files and subdirectories) directly inside dir. A missing+// directory lists as empty rather than erroring. Requires storage.fs.+func hostFSList(env *HostEnv, pluginName string) extism.HostFunction {+ fn := extism.NewHostFunctionWithStack(+ "owncast_fs_list",+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {+ dir, err := p.ReadString(stack[0])+ if err != nil || env.FSList == nil {+ stack[0] = 0+ return+ }+ names, err := env.FSList(pluginName, dir)+ if err != nil {+ fmt.Fprintf(os.Stderr, "owncast_fs_list from %s: %v\n", pluginName, err)+ stack[0] = 0+ return+ }+ if names == nil {+ names = []string{}+ }+ data, err := json.Marshal(names)+ 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+}++// hostFSDelete backs owncast.fs.delete(path). Removes a single file or+// empty directory, returning a JSON {ok, error?} result. Requires+// storage.fs.+func hostFSDelete(env *HostEnv, pluginName string) extism.HostFunction {+ fn := extism.NewHostFunctionWithStack(+ "owncast_fs_delete",+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {+ path, err := p.ReadString(stack[0])+ if err != nil {+ stack[0] = 0+ return+ }+ result := map[string]any{"ok": true}+ if env.FSDelete == nil {+ result = map[string]any{"ok": false, resultErrorKey: "filesystem unavailable"}+ } else if err := env.FSDelete(pluginName, path); err != nil {+ fmt.Fprintf(os.Stderr, "owncast_fs_delete from %s: %v\n", pluginName, err)+ result = map[string]any{"ok": false, resultErrorKey: err.Error()}+ }+ out, err := json.Marshal(result)+ if err != nil {+ stack[0] = 0+ return+ }+ offset, err := p.WriteBytes(out)+ 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+}++// hostFSExists backs owncast.fs.exists(path). Returns 1 if the path+// exists inside the sandbox, 0 otherwise (including on a sandbox-escape+// attempt or stat error). Requires storage.fs.+func hostFSExists(env *HostEnv, pluginName string) extism.HostFunction {+ fn := extism.NewHostFunctionWithStack(+ "owncast_fs_exists",+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {+ path, err := p.ReadString(stack[0])+ if err != nil || env.FSExists == nil {+ stack[0] = 0+ return+ }+ exists, err := env.FSExists(pluginName, path)+ if err != nil {+ fmt.Fprintf(os.Stderr, "owncast_fs_exists from %s: %v\n", pluginName, err)+ stack[0] = 0+ return+ }+ if exists {+ stack[0] = 1+ } else {+ stack[0] = 0+ }+ },+ []extism.ValueType{extism.ValueTypePTR},+ []extism.ValueType{extism.ValueTypeI32},+ )+ fn.SetNamespace("extism:host/user")+ return fn+}+func hostDeleteMessage(env *HostEnv, pluginName string) extism.HostFunction {fn := extism.NewHostFunctionWithStack("owncast_delete_message",@@ -1091,7 +1326,7 @@ func hostVideoConfigWrite(env *HostEnv, pluginName string) extism.HostFunction {result := map[string]any{"ok": true}if env.WriteVideoConfig != nil {if err := env.WriteVideoConfig(pluginName, update); err != nil {- result = map[string]any{"ok": false, "error": err.Error()}+ result = map[string]any{"ok": false, resultErrorKey: err.Error()}}}data, err := json.Marshal(result)diff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.jsonindex d39ce32e52..ad020997e8 100644--- a/services/plugins/plugin-contract.json+++ b/services/plugins/plugin-contract.json@@ -11,6 +11,7 @@"PermNetworkFetch": "network.fetch","PermNotificationsSend": "notifications.send","PermServerRead": "server.read",+ "PermStorageFS": "storage.fs","PermStorageKV": "storage.kv","PermStorageUpload": "storage.upload","PermUIModify": "ui.modify",@@ -28,6 +29,11 @@"owncast_delete_message","owncast_emit_event","owncast_fediverse_post",+ "owncast_fs_delete",+ "owncast_fs_exists",+ "owncast_fs_list",+ "owncast_fs_read",+ "owncast_fs_write","owncast_kick_client","owncast_kv_get","owncast_kv_set",@@ -94,6 +100,11 @@"previousNames": "[]string","scopes": "[]string"},+ "SSEConnectionEvent": {+ "channel": "string",+ "connectionId": "uint64",+ "user": "*HostUser"+ },"ServerInfo": {"name": "string","summary": "string",diff --git a/services/plugins/server.go b/services/plugins/server.goindex b5dd5b9f75..097bd88cf5 100644--- a/services/plugins/server.go+++ b/services/plugins/server.go@@ -269,9 +269,13 @@ func (s *Server) serveAuthorized(w http.ResponseWriter, r *http.Request, p *Load// serveSSE holds a long-lived Server-Sent-Events connection open and streams// frames the plugin publishes to (plugin, channel). The connection is owned-// entirely by the host: no plugin wasm call is made here and the per-plugin-// mutex is never taken, so an idle stream costs only a goroutine. The loop-// exits when the client disconnects (request context cancelled).+// entirely by the host: the per-plugin mutex is never taken during streaming,+// so an idle stream costs only a goroutine. The loop exits when the client+// disconnects (request context cancelled).+//+// The plugin is notified of the connection opening and closing via the+// sse.connect / sse.disconnect events (a single short wasm call each, around+// the stream, not during it) so it can track who is connected.func (s *Server) serveSSE(w http.ResponseWriter, r *http.Request, p *Loaded, channel string) {if s.SSE == nil {http.Error(w, "server-sent events not available", http.StatusServiceUnavailable)@@ -283,13 +287,22 @@ func (s *Server) serveSSE(w http.ResponseWriter, r *http.Request, p *Loaded, chareturn}- stream, unsubscribe, ok := s.SSE.Subscribe(p.Manifest.Slug, channel)+ stream, unsubscribe, connID, ok := s.SSE.Subscribe(p.Manifest.Slug, channel)if !ok {http.Error(w, "too many event-stream connections for this plugin", http.StatusServiceUnavailable)return}defer unsubscribe()+ // Resolve the connecting chat user (if any) once, and tell the plugin who+ // connected. The matching disconnect fires when this handler returns.+ var user *HostUser+ if s.GetRequestUser != nil {+ user = s.GetRequestUser(r)+ }+ s.notifySSEConnection(p, EventSSEConnect, channel, connID, user)+ defer s.notifySSEConnection(p, EventSSEDisconnect, channel, connID, user)+h := w.Header()h.Set("Content-Type", "text/event-stream")h.Set("Cache-Control", "no-cache")@@ -319,6 +332,36 @@ func (s *Server) serveSSE(w http.ResponseWriter, r *http.Request, p *Loaded, cha}}+// sseConnectionEnvelope marshals the on_event payload delivered to a plugin+// for an SSE connect/disconnect.+func sseConnectionEnvelope(eventType, channel string, connID uint64, user *HostUser) ([]byte, error) {+ return json.Marshal(Envelope{+ EventType: eventType,+ Payload: SSEConnectionEvent{Channel: channel, ConnectionID: connID, User: user},+ })+}++// notifySSEConnection fires an sse.connect / sse.disconnect event to the+// plugin that owns the channel, carrying the channel, connection id, and the+// resolved chat user (if any). It is best-effort: a plugin that doesn't export+// on_event or doesn't handle the event is a silent no-op, and any error is+// logged but never affects the stream. A fresh context is used because the+// disconnect path fires after the request context has already been cancelled.+func (s *Server) notifySSEConnection(p *Loaded, eventType, channel string, connID uint64, user *HostUser) {+ if p.plugin == nil || !p.plugin.FunctionExists("on_event") {+ return+ }+ envelope, err := sseConnectionEnvelope(eventType, channel, connID, user)+ if err != nil {+ return+ }+ ctx, cancel := context.WithTimeout(context.Background(), NotifyTimeout)+ defer cancel()+ if err := callOnEvent(ctx, p, envelope); err != nil {+ fmt.Fprintf(os.Stderr, "plugin %s: %s notify failed: %v\n", p.Manifest.Slug, eventType, err)+ }+}+// lookup returns the currently-loaded plugin with the given slug, or nil// if there isn't one. Called per-request against the live snapshot.// The lookup key is the manifest slug (also the URL segment under@@ -473,11 +516,21 @@ func (s *Server) serveDynamic(w http.ResponseWriter, r *http.Request, p *Loaded,// buildRequestEnvelope marshals the JSON envelope passed to a plugin's// on_http_request export.func (s *Server) buildRequestEnvelope(r *http.Request, requestPath string, authenticated bool, body []byte) ([]byte, error) {+ // Redact the credentials a request may carry so a sandboxed plugin never+ // sees the raw access token. Identity reaches the plugin only via the+ // host-resolved, trusted req.user below. The Cookie header carries the+ // chat identity cookie (and admin session); the accessToken query param+ // is the legacy token source.+ headers := flattenValues(r.Header)+ delete(headers, "Cookie")+ query := flattenValues(r.URL.Query())+ delete(query, "accessToken")+envelope := map[string]any{"method": r.Method,"path": requestPath,- "query": flattenValues(r.URL.Query()),- "headers": flattenValues(r.Header),+ "query": query,+ "headers": headers,"body": string(body),"remoteAddr": r.RemoteAddr,"authenticated": authenticated,diff --git a/services/plugins/server_envelope_test.go b/services/plugins/server_envelope_test.gonew file mode 100644index 0000000000..2c69fff87c--- /dev/null+++ b/services/plugins/server_envelope_test.go@@ -0,0 +1,76 @@+package plugins++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// The host hands a plugin a trusted, resolved req.user but must never leak the+// raw access token the request carried (cookie or accessToken query param).+func TestBuildRequestEnvelope_RedactsTokenAndForwardsUser(t *testing.T) {+ s := NewServer(nil)+ s.GetRequestUser = func(r *http.Request) *HostUser {+ return &HostUser{ID: "u-1", DisplayName: "Ann", IsAuthenticated: true}+ }++ req := httptest.NewRequest(http.MethodGet, "/plugins/demo/api/me?accessToken=secret&keep=yes", nil)+ req.Header.Set("Cookie", "owncast_chat_token=secret; theme=dark")+ req.Header.Set("X-Demo", "hi")++ raw, err := s.buildRequestEnvelope(req, "/api/me", false, nil)+ if err != nil {+ t.Fatalf("buildRequestEnvelope: %v", err)+ }++ var env struct {+ Query map[string]string `json:"query"`+ Headers map[string]string `json:"headers"`+ User *HostUser `json:"user"`+ }+ if err := json.Unmarshal(raw, &env); err != nil {+ t.Fatalf("unmarshal envelope: %v", err)+ }++ // The raw access token must never reach the plugin.+ if _, ok := env.Query["accessToken"]; ok {+ t.Error("accessToken query param was not redacted")+ }+ if _, ok := env.Headers["Cookie"]; ok {+ t.Error("Cookie header was not redacted")+ }++ // Non-sensitive query params and headers still pass through.+ if env.Query["keep"] != "yes" {+ t.Errorf("benign query param dropped: got %q", env.Query["keep"])+ }+ if env.Headers["X-Demo"] != "hi" {+ t.Errorf("benign header dropped: got %q", env.Headers["X-Demo"])+ }++ // Identity still reaches the plugin via the trusted, host-resolved user.+ if env.User == nil || env.User.ID != "u-1" {+ t.Errorf("expected req.user forwarded, got %+v", env.User)+ }+}++// With no GetRequestUser wired (or no identity on the request), the envelope+// simply omits user, which plugins treat as optional.+func TestBuildRequestEnvelope_OmitsUserWhenAbsent(t *testing.T) {+ s := NewServer(nil) // GetRequestUser left nil++ req := httptest.NewRequest(http.MethodGet, "/plugins/demo/api/me", nil)+ raw, err := s.buildRequestEnvelope(req, "/api/me", false, nil)+ if err != nil {+ t.Fatalf("buildRequestEnvelope: %v", err)+ }++ var env map[string]any+ if err := json.Unmarshal(raw, &env); err != nil {+ t.Fatalf("unmarshal envelope: %v", err)+ }+ if _, ok := env["user"]; ok {+ t.Error("expected user to be omitted when no identity is present")+ }+}diff --git a/services/plugins/sse.go b/services/plugins/sse.goindex 51d0cc85e7..e0e551c7f9 100644--- a/services/plugins/sse.go+++ b/services/plugins/sse.go@@ -3,6 +3,7 @@ package pluginsimport ("strings""sync"+ "sync/atomic")// DefaultMaxSSEConnectionsPerPlugin caps how many simultaneous@@ -35,6 +36,9 @@ type SSEHub struct {subscribers map[string]map[*sseClient]struct{}connectionCounts map[string]intmaxPerPlugin int+ // nextConnID hands out a process-unique id per connection so the host can+ // tell a plugin which connection opened/closed (see SSEConnectionEvent).+ nextConnID atomic.Uint64}// NewSSEHub constructs an empty hub with the default per-plugin connection@@ -52,18 +56,19 @@ func sseKey(pluginName, channel string) string {}// Subscribe registers a browser client for (pluginName, channel). It-// returns a receive-only channel of pre-framed SSE bytes and an unsubscribe-// func the caller MUST invoke when the connection ends. ok is false when-// the plugin is already at its connection cap, in which case the caller-// should reject the request.-func (h *SSEHub) Subscribe(pluginName, channel string) (<-chan []byte, func(), bool) {+// returns a receive-only channel of pre-framed SSE bytes, an unsubscribe+// func the caller MUST invoke when the connection ends, and a process-unique+// connection id. ok is false when the plugin is already at its connection+// cap, in which case the caller should reject the request.+func (h *SSEHub) Subscribe(pluginName, channel string) (<-chan []byte, func(), uint64, bool) {h.mu.Lock()defer h.mu.Unlock()if h.connectionCounts[pluginName] >= h.maxPerPlugin {- return nil, nil, false+ return nil, nil, 0, false}+ connID := h.nextConnID.Add(1)client := &sseClient{send: make(chan []byte, 16)}key := sseKey(pluginName, channel)if h.subscribers[key] == nil {@@ -87,7 +92,7 @@ func (h *SSEHub) Subscribe(pluginName, channel string) (<-chan []byte, func(), b})}- return client.send, unsubscribe, true+ return client.send, unsubscribe, connID, true}// Publish frames event+data once and delivers it to every client subscribeddiff --git a/services/plugins/sse_connection_test.go b/services/plugins/sse_connection_test.gonew file mode 100644index 0000000000..2d4a8105a4--- /dev/null+++ b/services/plugins/sse_connection_test.go@@ -0,0 +1,74 @@+package plugins++import (+ "encoding/json"+ "testing"+)++// Each subscription gets a distinct, non-zero connection id so a plugin can+// pair a disconnect with its connect and tell concurrent connections apart.+func TestSSEHubAssignsUniqueConnectionIDs(t *testing.T) {+ h := NewSSEHub()++ _, u1, id1, ok1 := h.Subscribe("p1", "c")+ _, u2, id2, ok2 := h.Subscribe("p1", "c")+ _, u3, id3, ok3 := h.Subscribe("p2", "other")+ if !ok1 || !ok2 || !ok3 {+ t.Fatal("subscribes should succeed")+ }+ defer u1()+ defer u2()+ defer u3()++ if id1 == 0 || id2 == 0 || id3 == 0 {+ t.Errorf("connection ids must be non-zero, got %d %d %d", id1, id2, id3)+ }+ if id1 == id2 || id1 == id3 || id2 == id3 {+ t.Errorf("connection ids must be unique, got %d %d %d", id1, id2, id3)+ }+}++// The sse.connect / sse.disconnect payload carries the channel, connection id,+// and the resolved user (omitted when anonymous).+func TestSSEConnectionEnvelope(t *testing.T) {+ user := &HostUser{ID: "u-1", DisplayName: "Ann", IsAuthenticated: true}+ raw, err := sseConnectionEnvelope(EventSSEConnect, "presence", 7, user)+ if err != nil {+ t.Fatalf("sseConnectionEnvelope: %v", err)+ }++ var env struct {+ EventType string `json:"eventType"`+ Payload SSEConnectionEvent `json:"payload"`+ }+ if err := json.Unmarshal(raw, &env); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if env.EventType != EventSSEConnect {+ t.Errorf("eventType: got %q, want %q", env.EventType, EventSSEConnect)+ }+ if env.Payload.Channel != "presence" {+ t.Errorf("channel: got %q", env.Payload.Channel)+ }+ if env.Payload.ConnectionID != 7 {+ t.Errorf("connectionId: got %d, want 7", env.Payload.ConnectionID)+ }+ if env.Payload.User == nil || env.Payload.User.ID != "u-1" {+ t.Errorf("user not carried through: %+v", env.Payload.User)+ }++ // Anonymous connection: user is omitted entirely from the JSON.+ raw, err = sseConnectionEnvelope(EventSSEDisconnect, "presence", 8, nil)+ if err != nil {+ t.Fatalf("sseConnectionEnvelope (anon): %v", err)+ }+ var generic struct {+ Payload map[string]any `json:"payload"`+ }+ if err := json.Unmarshal(raw, &generic); err != nil {+ t.Fatalf("unmarshal anon: %v", err)+ }+ if _, ok := generic.Payload["user"]; ok {+ t.Error("user should be omitted for an anonymous connection")+ }+}diff --git a/services/plugins/sse_test.go b/services/plugins/sse_test.goindex e7d75d7615..08e603b31f 100644--- a/services/plugins/sse_test.go+++ b/services/plugins/sse_test.go@@ -8,12 +8,12 @@ import (func TestSSEHubPublishFansOutToSubscribers(t *testing.T) {h := NewSSEHub()- a, unsubA, ok := h.Subscribe("p1", "overlay")+ a, unsubA, _, ok := h.Subscribe("p1", "overlay")if !ok {t.Fatal("first subscribe should succeed")}defer unsubA()- b, unsubB, ok := h.Subscribe("p1", "overlay")+ b, unsubB, _, ok := h.Subscribe("p1", "overlay")if !ok {t.Fatal("second subscribe should succeed")}@@ -37,9 +37,9 @@ func TestSSEHubPublishFansOutToSubscribers(t *testing.T) {func TestSSEHubIsolatesByPluginAndChannel(t *testing.T) {h := NewSSEHub()- other, unsub, _ := h.Subscribe("p2", "overlay")+ other, unsub, _, _ := h.Subscribe("p2", "overlay")defer unsub()- wrongChannel, unsub2, _ := h.Subscribe("p1", "stats")+ wrongChannel, unsub2, _, _ := h.Subscribe("p1", "stats")defer unsub2()// No subscribers on p1/overlay → zero deliveries, and neither of the@@ -59,7 +59,7 @@ func TestSSEHubIsolatesByPluginAndChannel(t *testing.T) {func TestSSEHubUnsubscribeStopsDelivery(t *testing.T) {h := NewSSEHub()- ch, unsub, _ := h.Subscribe("p1", "c")+ ch, unsub, _, _ := h.Subscribe("p1", "c")unsub()if n := h.Publish("p1", "c", "e", []byte("d")); n != 0 {@@ -79,9 +79,9 @@ func TestSSEHubPerPluginConnectionCap(t *testing.T) {h := NewSSEHub()h.maxPerPlugin = 2- _, u1, ok1 := h.Subscribe("p1", "c")- _, u2, ok2 := h.Subscribe("p1", "c")- _, _, ok3 := h.Subscribe("p1", "c")+ _, u1, _, ok1 := h.Subscribe("p1", "c")+ _, u2, _, ok2 := h.Subscribe("p1", "c")+ _, _, _, ok3 := h.Subscribe("p1", "c")if !ok1 || !ok2 {t.Fatal("first two subscribes should succeed under the cap")}@@ -90,7 +90,7 @@ func TestSSEHubPerPluginConnectionCap(t *testing.T) {}// A different plugin is unaffected by p1's cap.- if _, u, ok := h.Subscribe("p2", "c"); !ok {+ if _, u, _, ok := h.Subscribe("p2", "c"); !ok {t.Fatal("other plugin should not be affected by p1's cap")} else {u()@@ -98,7 +98,7 @@ func TestSSEHubPerPluginConnectionCap(t *testing.T) {// Freeing a slot lets a new connection in.u1()- if _, u, ok := h.Subscribe("p1", "c"); !ok {+ if _, u, _, ok := h.Subscribe("p1", "c"); !ok {t.Fatal("subscribe should succeed after a slot is freed")} else {u()@@ -108,7 +108,7 @@ func TestSSEHubPerPluginConnectionCap(t *testing.T) {func TestSSEHubDropsFramesForSlowClient(t *testing.T) {h := NewSSEHub()- _, unsub, _ := h.Subscribe("p1", "c") // never drained+ _, unsub, _, _ := h.Subscribe("p1", "c") // never draineddefer unsub()// The client buffer is 16; publishing well beyond it must not block anddiff --git a/utils/chataccesstoken.go b/utils/chataccesstoken.gonew file mode 100644index 0000000000..f67eb87b6f--- /dev/null+++ b/utils/chataccesstoken.go@@ -0,0 +1,74 @@+package utils++import (+ "net/http"+ "strings"+ "time"+)++// ChatAccessTokenCookieName is the cookie carrying a chat user's access+// token. It is set when a user registers or connects to chat so that all+// subsequent same-origin web requests (notably to plugin HTTP handlers under+// /plugins/) carry the user's identity without the frontend having to append+// the token to every URL. The host resolves the token to a user server-side;+// the raw token is never handed to plugins.+const ChatAccessTokenCookieName = "owncast_chat_token" //nolint:gosec // cookie name, not a credential++// chatAccessTokenCookieTTL is how long the identity cookie persists. Access+// tokens themselves don't expire, so this is generous. The cookie is+// refreshed on every chat connection anyway.+const chatAccessTokenCookieTTL = 365 * 24 * time.Hour++// requestIsSecure reports whether the request reached us over TLS, either+// directly (r.TLS) or via a TLS-terminating reverse proxy (X-Forwarded-Proto).+// Used to set the Secure cookie attribute only when it won't break a plain+// HTTP LAN deployment. Mirrors the admin session cookie logic.+func requestIsSecure(r *http.Request) bool {+ return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")+}++// chatAccessTokenCookie builds the identity cookie for the given token.+// HttpOnly keeps it out of reach of page JavaScript (the frontend already+// holds the token in localStorage, so nothing needs to read it from here),+// and SameSite=Lax sends it on same-origin requests and top-level navigations+// without leaking it to third-party sites.+func chatAccessTokenCookie(r *http.Request, token string) *http.Cookie {+ return &http.Cookie{ //nolint:gosec // Secure is set conditionally via requestIsSecure to support plain-HTTP LAN deployments; HttpOnly and SameSite are always set.+ Name: ChatAccessTokenCookieName,+ Value: token,+ Path: "/",+ MaxAge: int(chatAccessTokenCookieTTL.Seconds()),+ HttpOnly: true,+ Secure: requestIsSecure(r),+ SameSite: http.SameSiteLaxMode,+ }+}++// SetChatAccessTokenCookie writes the identity cookie to an HTTP response.+func SetChatAccessTokenCookie(w http.ResponseWriter, r *http.Request, token string) {+ if token == "" {+ return+ }+ http.SetCookie(w, chatAccessTokenCookie(r, token))+}++// AddChatAccessTokenCookieHeader adds the identity cookie to a header map.+// This is the path used for the WebSocket handshake response, where the+// cookie must be supplied as part of the upgrade response headers rather than+// written to a ResponseWriter after the connection is hijacked.+func AddChatAccessTokenCookieHeader(h http.Header, r *http.Request, token string) {+ if token == "" {+ return+ }+ h.Add("Set-Cookie", chatAccessTokenCookie(r, token).String())+}++// ChatAccessTokenFromRequest extracts a chat user's access token from a+// request, preferring the identity cookie and falling back to the legacy+// accessToken query parameter so existing callers keep working.+func ChatAccessTokenFromRequest(r *http.Request) string {+ if c, err := r.Cookie(ChatAccessTokenCookieName); err == nil && c.Value != "" {+ return c.Value+ }+ return r.URL.Query().Get("accessToken")+}diff --git a/utils/chataccesstoken_test.go b/utils/chataccesstoken_test.gonew file mode 100644index 0000000000..68198fa8ed--- /dev/null+++ b/utils/chataccesstoken_test.go@@ -0,0 +1,125 @@+package utils++import (+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestChatAccessTokenFromRequest(t *testing.T) {+ tests := []struct {+ name string+ cookie string // cookie value; "" means no cookie set+ query string // accessToken query value; "" means absent+ want string+ }{+ {name: "cookie preferred over query", cookie: "ck", query: "qp", want: "ck"},+ {name: "cookie only", cookie: "ck", query: "", want: "ck"},+ {name: "query fallback", cookie: "", query: "qp", want: "qp"},+ {name: "empty cookie falls back to query", cookie: "", query: "qp", want: "qp"},+ {name: "neither", cookie: "", query: "", want: ""},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ target := "/api/thing"+ if tt.query != "" {+ target += "?accessToken=" + tt.query+ }+ r := httptest.NewRequest(http.MethodGet, target, nil)+ if tt.cookie != "" {+ r.AddCookie(&http.Cookie{Name: ChatAccessTokenCookieName, Value: tt.cookie})+ }+ if got := ChatAccessTokenFromRequest(r); got != tt.want {+ t.Errorf("got %q, want %q", got, tt.want)+ }+ })+ }+}++func TestSetChatAccessTokenCookie_Attributes(t *testing.T) {+ r := httptest.NewRequest(http.MethodPost, "/api/chat/register", nil)+ r.Header.Set("X-Forwarded-Proto", "https") // simulate TLS-terminating proxy+ rec := httptest.NewRecorder()++ SetChatAccessTokenCookie(rec, r, "tok-123")++ cookies := rec.Result().Cookies()+ if len(cookies) != 1 {+ t.Fatalf("expected 1 cookie, got %d", len(cookies))+ }+ c := cookies[0]+ if c.Name != ChatAccessTokenCookieName {+ t.Errorf("name: got %q, want %q", c.Name, ChatAccessTokenCookieName)+ }+ if c.Value != "tok-123" {+ t.Errorf("value: got %q", c.Value)+ }+ if !c.HttpOnly {+ t.Error("cookie should be HttpOnly so page JS can't read the token")+ }+ if c.SameSite != http.SameSiteLaxMode {+ t.Errorf("SameSite: got %v, want Lax", c.SameSite)+ }+ if c.Path != "/" {+ t.Errorf("path: got %q, want /", c.Path)+ }+ if !c.Secure {+ t.Error("Secure should be set when the request arrived over https")+ }+ if c.MaxAge <= 0 {+ t.Errorf("expected a positive MaxAge, got %d", c.MaxAge)+ }+}++func TestSetChatAccessTokenCookie_InsecureOnPlainHTTP(t *testing.T) {+ r := httptest.NewRequest(http.MethodPost, "/api/chat/register", nil) // no TLS, no X-Forwarded-Proto+ rec := httptest.NewRecorder()++ SetChatAccessTokenCookie(rec, r, "tok-123")++ cookies := rec.Result().Cookies()+ if len(cookies) != 1 {+ t.Fatalf("expected 1 cookie, got %d", len(cookies))+ }+ if cookies[0].Secure {+ t.Error("Secure must not be set on a plain-HTTP request, or LAN deployments break")+ }+}++func TestSetChatAccessTokenCookie_EmptyTokenNoOp(t *testing.T) {+ r := httptest.NewRequest(http.MethodPost, "/api/chat/register", nil)+ rec := httptest.NewRecorder()++ SetChatAccessTokenCookie(rec, r, "")++ if len(rec.Result().Cookies()) != 0 {+ t.Error("no cookie should be set for an empty token")+ }+}++func TestAddChatAccessTokenCookieHeader(t *testing.T) {+ r := httptest.NewRequest(http.MethodGet, "/ws?accessToken=tok", nil)+ h := http.Header{}++ AddChatAccessTokenCookieHeader(h, r, "tok")++ setCookie := h.Get("Set-Cookie")+ if setCookie == "" {+ t.Fatal("expected a Set-Cookie header for the handshake response")+ }++ // Parse it back the way a browser would, via a response.+ resp := http.Response{Header: http.Header{"Set-Cookie": h["Set-Cookie"]}}+ cookies := resp.Cookies()+ if len(cookies) != 1 || cookies[0].Name != ChatAccessTokenCookieName || cookies[0].Value != "tok" {+ t.Fatalf("unexpected parsed cookie: %+v", cookies)+ }++ // Empty token must not add a header.+ h2 := http.Header{}+ AddChatAccessTokenCookieHeader(h2, r, "")+ if h2.Get("Set-Cookie") != "" {+ t.Error("no Set-Cookie should be added for an empty token")+ }+}diff --git a/web/components/admin/plugins/PluginDetail.tsx b/web/components/admin/plugins/PluginDetail.tsxindex 938bbe8533..9f66a3b649 100644--- a/web/components/admin/plugins/PluginDetail.tsx+++ b/web/components/admin/plugins/PluginDetail.tsx@@ -271,7 +271,14 @@ export const PluginDetail = ({ plugin }: PluginDetailProps) => {<iframetitle={`${plugin.name} – ${page.title}`}src={page.url}- sandbox="allow-same-origin allow-scripts allow-forms allow-popups"+ // allow-downloads: plugin admin pages can trigger file+ // downloads (e.g. exporting data the plugin stored).+ // allow-modals: lets them use confirm()/alert()/prompt()+ // for destructive-action confirmations. Both are normal+ // capabilities of an admin page; the page is same-origin and+ // admin-gated, so neither widens the trust boundary that+ // allow-same-origin + allow-scripts already grants.+ sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-downloads allow-modals"className={s.iframe}/>),diff --git a/web/components/admin/plugins/permissionDescriptions.ts b/web/components/admin/plugins/permissionDescriptions.tsindex 467ff45e61..911d6a84b3 100644--- a/web/components/admin/plugins/permissionDescriptions.ts+++ b/web/components/admin/plugins/permissionDescriptions.ts@@ -10,6 +10,7 @@ import { Localization } from '../../../types/localization';export const permissionDescriptionKey: Record<string, string> = {[PluginPermission.StorageKV]: Localization.Admin.Plugins.Permissions.storageKv,[PluginPermission.StorageUpload]: Localization.Admin.Plugins.Permissions.storageUpload,+ [PluginPermission.StorageFS]: Localization.Admin.Plugins.Permissions.storageFs,[PluginPermission.ChatSend]: Localization.Admin.Plugins.Permissions.chatSend,[PluginPermission.ChatHistory]: Localization.Admin.Plugins.Permissions.chatHistory,[PluginPermission.ChatModerate]: Localization.Admin.Plugins.Permissions.chatModerate,@@ -35,6 +36,7 @@ export const permissionDescriptionKey: Record<string, string> = {export const permissionNameKey: Record<string, string> = {[PluginPermission.StorageKV]: Localization.Admin.Plugins.PermissionNames.storageKv,[PluginPermission.StorageUpload]: Localization.Admin.Plugins.PermissionNames.storageUpload,+ [PluginPermission.StorageFS]: Localization.Admin.Plugins.PermissionNames.storageFs,[PluginPermission.ChatSend]: Localization.Admin.Plugins.PermissionNames.chatSend,[PluginPermission.ChatHistory]: Localization.Admin.Plugins.PermissionNames.chatHistory,[PluginPermission.ChatModerate]: Localization.Admin.Plugins.PermissionNames.chatModerate,diff --git a/web/i18n/en/translation.json b/web/i18n/en/translation.jsonindex d8e040611f..395af8a778 100644--- a/web/i18n/en/translation.json+++ b/web/i18n/en/translation.json@@ -160,6 +160,7 @@"Permissions": {"storageKv": "Read and write a per-plugin key-value store that persists across reloads.","storageUpload": "Upload files to Owncast’s public files area for browser-accessible URLs.",+ "storageFs": "Read and write files in a private, server-side directory only this plugin can access.","chatSend": "Post chat messages as the plugin’s own bot identity.","chatHistory": "Read recent chat messages.","chatModerate": "Hide chat messages and ban users.",@@ -180,6 +181,7 @@"PermissionNames": {"storageKv": "Store data","storageUpload": "Upload files",+ "storageFs": "Read and write files","chatSend": "Send chat messages","chatHistory": "Read chat history","chatModerate": "Moderate chat",diff --git a/web/interfaces/plugin.ts b/web/interfaces/plugin.tsindex a131d43268..7a383a1890 100644--- a/web/interfaces/plugin.ts+++ b/web/interfaces/plugin.ts@@ -9,6 +9,7 @@export const PluginPermission = {StorageKV: 'storage.kv',StorageUpload: 'storage.upload',+ StorageFS: 'storage.fs',ChatSend: 'chat.send',ChatHistory: 'chat.history',ChatModerate: 'chat.moderate',diff --git a/web/types/localization.ts b/web/types/localization.tsindex d1e246c902..676a59ee1c 100644--- a/web/types/localization.ts+++ b/web/types/localization.ts@@ -395,6 +395,7 @@ export const Localization = {Permissions: {storageKv: 'Admin.Plugins.Permissions.storageKv',storageUpload: 'Admin.Plugins.Permissions.storageUpload',+ storageFs: 'Admin.Plugins.Permissions.storageFs',chatSend: 'Admin.Plugins.Permissions.chatSend',chatHistory: 'Admin.Plugins.Permissions.chatHistory',chatModerate: 'Admin.Plugins.Permissions.chatModerate',@@ -418,6 +419,7 @@ export const Localization = {PermissionNames: {storageKv: 'Admin.Plugins.PermissionNames.storageKv',storageUpload: 'Admin.Plugins.PermissionNames.storageUpload',+ storageFs: 'Admin.Plugins.PermissionNames.storageFs',chatSend: 'Admin.Plugins.PermissionNames.chatSend',chatHistory: 'Admin.Plugins.PermissionNames.chatHistory',chatModerate: 'Admin.Plugins.PermissionNames.chatModerate',diff --git a/webserver/handlers/chat.go b/webserver/handlers/chat.goindex 561aebe994..c9942e89c0 100644--- a/webserver/handlers/chat.go+++ b/webserver/handlers/chat.go@@ -97,6 +97,10 @@ func (h *Handlers) RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Requw.Header().Set("Content-Type", "application/json")middleware.DisableCache(w)+ // Set the chat identity cookie so subsequent same-origin web requests+ // (e.g. to plugin HTTP handlers) carry this user's identity.+ utils.SetChatAccessTokenCookie(w, r, accessToken)+webutils.WriteResponse(w, response)}