Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

78.5 KB
Raw Blame
package pluginhost

import (
	"bytes"
	"context"
	"crypto/rand"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"io/fs"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"sync/atomic"
	"time"

	log "github.com/sirupsen/logrus"

	"github.com/owncast/owncast/config"
	"github.com/owncast/owncast/models"
	"github.com/owncast/owncast/notifications/browser"
	"github.com/owncast/owncast/notifications/discord"
	"github.com/owncast/owncast/persistence/authrepository"
	"github.com/owncast/owncast/persistence/chatmessagerepository"
	"github.com/owncast/owncast/persistence/configrepository"
	"github.com/owncast/owncast/persistence/notificationsrepository"
	"github.com/owncast/owncast/persistence/userrepository"
	"github.com/owncast/owncast/services/activitypub"
	"github.com/owncast/owncast/services/chat"
	"github.com/owncast/owncast/services/chat/events"
	"github.com/owncast/owncast/services/datastore"
	"github.com/owncast/owncast/services/dispatcher"
	"github.com/owncast/owncast/services/plugins"
	"github.com/owncast/owncast/services/plugins/kv"
	"github.com/owncast/owncast/services/stream"
	"github.com/owncast/owncast/services/transcoder"
	"github.com/owncast/owncast/utils"
)

// pluginsEnabledConfigKey is the datastore key under which the set of
// admin-enabled plugin names is persisted.
const pluginsEnabledConfigKey = "plugins.enabled"

// JSON map keys used in the admin API's small status/error response bodies.
const (
	// jsonErrorKey surfaces a single human-readable error string to the admin UI.
	jsonErrorKey = "error"
	// jsonSlugKey echoes back the plugin a mutating request acted on.
	jsonSlugKey = "slug"
	// jsonStatusKey carries the "ok" acknowledgement of a mutating request.
	jsonStatusKey = "status"
)

// pluginsApprovedPermsConfigKey is the datastore key under which the
// per-plugin admin-approved permission snapshots are persisted (as a
// JSON-encoded map keyed by plugin name).
const pluginsApprovedPermsConfigKey = "plugins.approvedPermissions"

// Deps bundles the Owncast services the plugin runtime adapts into
// HostEnv host functions. Everything here is already constructed in the main
// composition root and passed in by reference.
type Deps struct {
	Datastore               *datastore.Datastore
	Chat                    *chat.Service
	Stream                  *stream.Service
	Activitypub             *activitypub.Service
	Events                  *dispatcher.Dispatcher
	ConfigRepository        configrepository.ConfigRepository
	UserRepository          userrepository.UserRepository
	AuthRepository          *authrepository.SqlAuthRepository
	NotificationsRepository notificationsrepository.NotificationsRepository
	ChatMessageRepository   chatmessagerepository.ChatMessageRepository

	// RequireAdminAuth wraps a handler with the host's admin Basic Auth
	// middleware. The plugin host uses it on management endpoints and on
	// manifest-declared admin paths inside the plugin static server, so
	// auth (realm, CORS, credential check) comes from one implementation
	// instead of being duplicated here.
	RequireAdminAuth func(http.HandlerFunc) http.HandlerFunc
	// IsAdminRequest is the predicate behind RequireAdminAuth, exposed as a
	// boolean for paths that don't reject unauthenticated requests but need
	// to know whether the caller is an authenticated admin (e.g. the
	// req.authenticated field passed to a plugin's HTTP handler).
	IsAdminRequest func(*http.Request) bool
}

// Host owns the running plugin runtime: the manager (discovery +
// enable/disable lifecycle), the HTTP handler that serves /plugins/<name>/*,
// and the SSE hub backing host-owned event streams.
type Host struct {
	manager          *plugins.Manager
	server           *plugins.Server
	sse              *plugins.SSEHub
	sqlStore         *pluginSQLStore
	configRepository configrepository.ConfigRepository
	// requireAdminAuth is the host's admin Basic Auth middleware, plumbed
	// in from main.go so the management API and the plugin static server
	// share one credential check (realm, logging, etc.) with the rest of
	// the admin API.
	requireAdminAuth func(http.HandlerFunc) http.HandlerFunc
	// kv is the per-plugin config store the runtime hands plugins. The
	// host reads each plugin's reserved actionsOverrideConfigKey from
	// this store to let a plugin override its manifest-declared action
	// buttons at runtime (e.g. an admin page that lets the streamer
	// rename buttons without rebuilding the plugin).
	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
	// authSecret is the HMAC key the viewer-auth gate uses to mint and verify
	// session cookies. The same persisted secret is used by GrantSession (wired
	// into the host env). Empty if it could not be established.
	authSecret []byte
	// userByToken resolves a viewer's identity from their access token, used by
	// the onAuthCheck re-validation hook to build the identity it passes the
	// gate plugin.
	userByToken      func(token string) *plugins.HostUser
	authGateSettings atomic.Value
}

// AuthGateAccessMode is the operator-selected boundary of the viewer gate.
// Modes are cumulative: each mode includes everything protected by the one
// before it.
type AuthGateAccessMode string

const (
	AuthGateAccessWebsiteOnly            AuthGateAccessMode = "website-only"
	AuthGateAccessWebsiteAndStream       AuthGateAccessMode = "website-and-stream"
	AuthGateAccessWebsiteStreamAndStatus AuthGateAccessMode = "website-stream-and-status"
)

// AuthGateSettings are host-owned settings for a plugin that declares
// auth.gate.
type AuthGateSettings struct {
	AccessMode AuthGateAccessMode `json:"accessMode"`
}

func defaultAuthGateSettings() AuthGateSettings {
	return AuthGateSettings{AccessMode: AuthGateAccessWebsiteOnly}
}

func (s AuthGateSettings) valid() bool {
	switch s.AccessMode {
	case AuthGateAccessWebsiteOnly,
		AuthGateAccessWebsiteAndStream,
		AuthGateAccessWebsiteStreamAndStatus:
		return true
	default:
		return false
	}
}

func (s AuthGateSettings) protectsStream() bool {
	return s.AccessMode == AuthGateAccessWebsiteAndStream ||
		s.AccessMode == AuthGateAccessWebsiteStreamAndStatus
}

func (s AuthGateSettings) blocksStreamStatusRequests() bool {
	return s.AccessMode == AuthGateAccessWebsiteStreamAndStatus
}

type authGateSettingsSnapshot struct {
	slug     string
	settings AuthGateSettings
}

const authGateSettingsKey = "owncast.auth-gate-settings"

// runtimeActionsConfigKey is the reserved key inside a plugin's own
// config namespace that holds action buttons the plugin has added at
// runtime via owncast.actions.add. The host's Actions() reader returns
// manifest.actions ++ this list on every /api/config request.
const runtimeActionsConfigKey = "owncast.actions"

// runtimeConfigKey is the reserved key inside a plugin's own config namespace
// that holds the admin-set overrides for its manifest-declared config fields.
// The admin config form writes this; owncast.config.get reads it (via the
// wired env.ConfigValue) so a plugin sees the admin's values, falling back to
// the manifest default for any key the admin hasn't set.
const runtimeConfigKey = "owncast.config"

// readConfigOverrides returns the admin-set config overrides for a plugin from
// its KV namespace, or nil when none are set / the store is unavailable.
func readConfigOverrides(store kv.Store, slug string) map[string]any {
	if store == nil {
		return nil
	}
	raw, err := store.Namespace(slug).Get(runtimeConfigKey)
	if err != nil || len(raw) == 0 {
		return nil
	}

	var m map[string]any
	if err := json.Unmarshal(raw, &m); err != nil {
		return nil
	}
	return m
}

// authGateSettingsFor returns the operator's access policy for a gate plugin,
// memoized in a single-slot snapshot because it is read on every request,
// including the per-segment HLS hot path.
//
// A storage failure or a corrupt value is not cached: it returns the
// website-only default for this request and retries on the next one, rather
// than pinning a wrong policy until restart.
func (p *Host) authGateSettingsFor(slug string) AuthGateSettings {
	snapshot, ok := p.authGateSettings.Load().(authGateSettingsSnapshot)
	if ok && snapshot.slug == slug {
		return snapshot.settings
	}
	defaults := defaultAuthGateSettings()
	if p.kv == nil {
		return defaults
	}

	raw, err := p.kv.Namespace(slug).Get(authGateSettingsKey)
	if err != nil {
		log.Warnf("plugin auth: could not read gate settings for %q, using defaults: %v", slug, err)
		return defaults
	}

	settings := defaults
	if len(raw) > 0 {
		var stored AuthGateSettings
		if err := json.Unmarshal(raw, &stored); err != nil {
			log.Warnf("plugin auth: gate settings for %q are unreadable, using defaults: %v", slug, err)
			return defaults
		}
		if !stored.valid() {
			log.Warnf("plugin auth: gate settings for %q have unsupported access mode %q, using defaults", slug, stored.AccessMode)
			return defaults
		}
		settings = stored
	}
	p.authGateSettings.Store(authGateSettingsSnapshot{slug: slug, settings: settings})
	return settings
}

func (p *Host) saveAuthGateSettings(slug string, settings AuthGateSettings) error {
	if !settings.valid() {
		return fmt.Errorf("unsupported authentication access mode %q", settings.AccessMode)
	}
	data, err := json.Marshal(settings)
	if err != nil {
		return err
	}
	if p.kv == nil {
		return fmt.Errorf("settings storage unavailable")
	}
	if err := p.kv.Namespace(slug).Set(authGateSettingsKey, data); err != nil {
		return err
	}
	p.authGateSettings.Store(authGateSettingsSnapshot{slug: slug, settings: settings})
	return nil
}

// DirectoryAvailable reports whether the active auth gate permits public
// directory metadata. The most restrictive access mode disables directory
// access along with public stream status.
func (p *Host) DirectoryAvailable() bool {
	slug, _ := p.manager.ActiveAuthGate()
	return slug == "" || !p.authGateSettingsFor(slug).blocksStreamStatusRequests()
}

// coerceConfigValue validates an incoming admin-set value against a config
// field's declared type and returns the normalized value to store. JSON decodes
// numbers as float64 and booleans as bool; we accept those and reject mismatches
// so a plugin's config.get sees the type it declared. Unknown/blank types pass
// through unchanged.
func coerceConfigValue(fieldType string, v any) (any, error) {
	switch fieldType {
	case "string":
		s, ok := v.(string)
		if !ok {
			return nil, fmt.Errorf("expected a string")
		}
		return s, nil
	case "number":
		f, ok := v.(float64)
		if !ok {
			return nil, fmt.Errorf("expected a number")
		}
		return f, nil
	case "boolean":
		b, ok := v.(bool)
		if !ok {
			return nil, fmt.Errorf("expected a boolean")
		}
		return b, nil
	default:
		return v, nil
	}
}

// Handler is the http.Handler for /plugins/<name>/* (static assets, dynamic
// on_http_request, and the reserved _sse endpoint).
func (p *Host) Handler() http.Handler { return p.server }

// Stop closes all loaded plugins.
func (p *Host) Stop(ctx context.Context) {
	if p.tickCancel != nil {
		p.tickCancel()
	}
	p.manager.Stop(ctx)
	// Unload callbacks close databases for loaded plugins; closeAll also
	// handles any database opened during a final in-flight call.
	if p.sqlStore != nil {
		p.sqlStore.closeAll()
	}
}

// Actions returns every action-button currently contributed by loaded
// plugins, projected into the shape Owncast's web config uses for
// admin-defined externalActions. Empty when no plugins declare actions
// (or no plugins are loaded). Called from handlers.GetWebConfig so the
// viewer-facing config endpoint surfaces plugin and admin actions in a
// single list, without each consumer needing to know about plugins.
//
// For each plugin, the effective list is manifest.Actions ++ any
// buttons the plugin has added at runtime via owncast.actions.add
// (read from runtimeActionsConfigKey in the plugin's own config).
func (p *Host) Actions() []models.ExternalAction {
	if p == nil || p.manager == nil {
		return nil
	}
	loaded := p.manager.Snapshot()
	var out []models.ExternalAction
	for _, l := range loaded {
		actions := p.actionsForPlugin(l)
		for _, a := range actions {
			out = append(out, models.ExternalAction{
				URL:            a.Url,
				HTML:           a.Html,
				Title:          a.Title,
				Description:    a.Description,
				Icon:           a.Icon,
				Color:          a.Color,
				OpenExternally: a.OpenExternally,
			})
		}
	}
	return out
}

// StylesContent returns the concatenated CSS bytes contributed by
// every currently-loaded plugin. Each plugin's manifest.styles files
// are read from the plugin's AssetsFS (the static-asset root inside
// the ocpkg) and joined with delimiter comments naming the source
// plugin, so devtools "view source" still attributes a rule to the
// plugin that shipped it. The bytes are folded into the existing
// customStyles config field at request time, so the viewer page
// renders a single inline <style> block instead of one <link> tag
// per plugin asset. Disabled or not-loaded plugins contribute
// nothing.
func (p *Host) StylesContent() []byte {
	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()
}

// themeVarDeclRe matches a theme custom-property declaration in CSS,
// e.g. `--theme-color-action:` or `--theme-rounded-corners:`. The
// capture group is the variable name without the leading `--`, which
// matches the keys the admin Appearance UI uses for its color swatches
// (e.g. "theme-color-action").
var themeVarDeclRe = regexp.MustCompile(`--(theme-color-[a-z0-9-]+|theme-rounded-corners)\s*:`)

// StyleContributors returns one entry per enabled plugin (holding
// ui.modify) that contributes any CSS to the viewer page, covering both
// static manifest.styles and on_page_styles output — the same sources
// StylesContent concatenates. Plugins that contribute nothing are
// omitted, so a non-empty result means the admin's appearance settings
// are being combined with plugin styling. The viewer renders plugin
// styles below the admin's appearance variables and custom CSS, so the
// admin wins on overlap; this report lets the admin UI say so and point
// at the affected swatches.
func (p *Host) StyleContributors() []models.PluginStyleInfo {
	if p == nil || p.manager == nil {
		return nil
	}
	var out []models.PluginStyleInfo
	for _, l := range p.manager.Snapshot() {
		if l == nil || l.Manifest == nil {
			continue
		}
		if !manifestHasPermission(l.Manifest, plugins.PermUIModify) {
			continue
		}
		css := p.pluginStyleCSS(l)
		if len(css) == 0 {
			continue
		}
		out = append(out, models.PluginStyleInfo{
			Slug:         l.Manifest.Slug,
			Name:         l.Manifest.DisplayName,
			DeclaredVars: declaredThemeVars(css),
		})
	}
	return out
}

// pluginStyleCSS returns the CSS a single plugin contributes to the
// viewer page: its static manifest.styles files (read from the plugin's
// AssetsFS) followed by its on_page_styles output. It mirrors the
// per-plugin slice of StylesContent/dynamicStyles so the admin-facing
// token scan sees exactly what the viewer renders.
func (p *Host) pluginStyleCSS(l *plugins.Loaded) []byte {
	var buf bytes.Buffer
	if l.AssetsFS != nil {
		pluginPrefix := "/plugins/" + l.Manifest.Slug + "/"
		for _, entry := range l.Manifest.Styles {
			relPath := strings.TrimPrefix(entry, pluginPrefix)
			data, err := fs.ReadFile(l.AssetsFS, relPath)
			if err != nil {
				continue
			}
			buf.Write(data)
			if len(data) > 0 && data[len(data)-1] != '\n' {
				buf.WriteByte('\n')
			}
		}
	}
	if css, err := l.CallPageStyles(context.Background()); err == nil && css != "" {
		buf.WriteString(css)
	}
	return buf.Bytes()
}

// declaredThemeVars returns the sorted, de-duplicated set of theme
// custom-property names declared in a CSS blob (without the leading
// `--`), e.g. ["theme-color-action", "theme-rounded-corners"]. The
// names match the keys the admin Appearance UI uses, so it can badge
// the swatches a plugin also sets.
func declaredThemeVars(css []byte) []string {
	matches := themeVarDeclRe.FindAllSubmatch(css, -1)
	if len(matches) == 0 {
		return nil
	}
	seen := make(map[string]struct{}, len(matches))
	var vars []string
	for _, m := range matches {
		name := string(m[1])
		if _, ok := seen[name]; ok {
			continue
		}
		seen[name] = struct{}{}
		vars = append(vars, name)
	}
	sort.Strings(vars)
	return vars
}

// ScriptsContent mirrors StylesContent for manifest.scripts: returns
// the concatenated JavaScript bytes contributed by every loaded
// 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 {
	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 by
// 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(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
			}
			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 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(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.PluginTab
	for _, l := range p.manager.Snapshot() {
		if l == nil || l.Manifest == nil {
			continue
		}
		pluginSlug := l.Manifest.Slug
		pluginPrefix := "/plugins/" + pluginSlug + "/"
		for _, tab := range l.Manifest.OrderedTabs() {
			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:       pluginSlug + "/" + tab.Slug,
				PluginSlug: pluginSlug,
				Title:      tab.Title,
				HTML:       html,
			})
		}
	}
	return out
}

// readManifestAssets walks every loaded plugin, calls pick() to get
// the manifest entries to include (Styles or Scripts), and reads each
// file from the plugin's AssetsFS. delimiter is a Printf format
// taking (slug, relPath) used as a per-contribution header. Files
// that can't be read are skipped (logged) so a broken asset doesn't
// take down the rest of the bundle.
//
// The manifest entries arrive as rewritten plugin-namespace URLs
// (e.g. "/plugins/styles-demo/theme.css"); the file inside the
// AssetsFS lives at the path beneath the plugin prefix
// ("theme.css"), so the lookup is a prefix strip.
func (p *Host) readManifestAssets(pick func(*plugins.Manifest) []string, delimiter string) []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 || l.AssetsFS == nil {
			continue
		}
		entries := pick(l.Manifest)
		if len(entries) == 0 {
			continue
		}
		pluginPrefix := "/plugins/" + l.Manifest.Slug + "/"
		for _, entry := range entries {
			relPath := strings.TrimPrefix(entry, pluginPrefix)
			data, err := fs.ReadFile(l.AssetsFS, relPath)
			if err != nil {
				log.Warnf("plugin %s: skipping asset %s: %v", l.Manifest.Slug, relPath, err)
				continue
			}
			fmt.Fprintf(&buf, delimiter, l.Manifest.Slug, relPath)
			buf.Write(data)
			if len(data) > 0 && data[len(data)-1] != '\n' {
				buf.WriteByte('\n')
			}
		}
	}
	return buf.Bytes()
}

// actionsForPlugin returns the plugin's manifest action list with any
// runtime additions appended. Kept separate so Actions() reads cleanly
// and the append logic can be tested independently.
func (p *Host) actionsForPlugin(l *plugins.Loaded) []plugins.ActionButton {
	combined := l.Manifest.Actions
	if p.kv == nil {
		return combined
	}
	raw, err := p.kv.Namespace(l.Manifest.Slug).Get(runtimeActionsConfigKey)
	if err != nil || len(raw) == 0 {
		return combined
	}
	var extras []plugins.ActionButton
	if err := json.Unmarshal(raw, &extras); err != nil {
		return combined
	}
	return append(combined, extras...)
}

// New builds the HostEnv from Owncast services, constructs and
// starts the plugin manager, and returns the assembled host. Plugins are
// optional infrastructure: callers should log and continue on error rather
// than aborting startup.
func New(ctx context.Context, deps Deps) (*Host, error) {
	pluginsDir := filepath.Join(config.DataDirectory, "plugins")
	if err := os.MkdirAll(pluginsDir, 0o700); err != nil {
		return nil, fmt.Errorf("create plugins directory: %w", err)
	}

	if err := migrateLegacyPluginFilesystemStorage(config.DataDirectory); err != nil {
		return nil, err
	}

	sqlStore, err := newPluginSQLStore(filepath.Join(config.DataDirectory, pluginStorageRootDirName))
	if err != nil {
		return nil, err
	}
	env := &plugins.HostEnv{KV: newDatastoreKVStore(deps.Datastore)}
	wirePluginHostEnv(env, deps)

	env.SQLExec = sqlStore.exec
	env.SQLQuery = sqlStore.query
	env.AcquireSQLLease = sqlStore.acquire
	sseHub := plugins.NewSSEHub()
	env.SSE = sseHub

	enabledStore := &configEnabledStore{datastore: deps.Datastore}
	manager := plugins.NewManagerWithStore(pluginsDir, env, enabledStore)
	if err := manager.Start(ctx); err != nil {
		return nil, fmt.Errorf("start plugin manager: %w", err)
	}

	// Boot summary — show every discovered plugin with its status and the
	// permissions it asks for. Per-plugin "loaded" lines come from the
	// manager itself; this gives the full picture (including disabled ones)
	// so the admin doesn't need to hit the API to see what's installed.
	logPluginSummary(manager.List())

	// Emit delivers plugin-published custom events to other plugins'
	// subscribers. Wired post-Start because it reads the live plugin set.
	pluginDispatcher := plugins.NewLiveDispatcher(manager.Snapshot)
	env.Emit = pluginDispatcher.Dispatch

	// Subscribe to the shared event dispatcher: deliver Owncast's events
	// (chat, stream lifecycle, moderation, …) to plugins' notify handlers,
	// and run plugin filterChatMessage handlers on inbound chat messages
	// before they're broadcast.
	deps.Events.AddListener(newPluginEventListener(pluginDispatcher))
	deps.Events.AddFilter(newPluginChatFilter(pluginDispatcher))

	// Built-in `!help`: aggregate every plugin's declarations into a system
	// message. The original message also reaches ordinary chat and matching
	// plugin command handlers.
	deps.Events.AddListener(newHelpResponder(manager.Snapshot, func(text string) {
		if err := deps.Chat.SendSystemMessage(text, false); err != nil {
			log.Errorln("plugin !help:", err)
		}
	}))

	// Host-driven timers: plugins can't setTimeout in the sandbox, so
	// owncast.timer.* asks the host to schedule callbacks. The hub resolves a
	// plugin slug to its live instance to call back; cancelling a plugin's
	// timers on unload is wired through the manager's onUnload hook.
	timerHub := plugins.NewTimerHub(func(slug string) *plugins.Loaded {
		for _, l := range manager.Snapshot() {
			if l.Manifest.Slug == slug {
				return l
			}
		}
		return nil
	})
	env.Timer = timerHub
	// On unload (disable/reload/uninstall/disk-removal) cancel the plugin's
	// pending timers and close its open SSE streams. SQL is tied directly to
	// Loaded.Close so failed loads and package preflights release it too.
	manager.SetOnUnload(func(slug string) {
		timerHub.CancelForPlugin(slug)
		sseHub.CloseForPlugin(slug)
	})

	// Fire a once-a-second tick to plugins that subscribe (onTick), and which
	// also drives nothing else — host-scheduled timers run independently. The
	// goroutine is stopped when the host stops.
	tickCtx, tickCancel := context.WithCancel(context.Background())
	go func() {
		t := time.NewTicker(time.Second)
		defer t.Stop()
		for {
			select {
			case <-tickCtx.Done():
				return
			case <-t.C:
				pluginDispatcher.Notify(tickCtx, plugins.EventTick, plugins.TickEvent{Now: time.Now().UnixMilli()})
			}
		}
	}()

	server := plugins.NewLiveServer(manager.Snapshot)
	server.SSE = sseHub
	server.IsAuthenticated = env.IsAuthenticated
	server.RequireAdmin = deps.RequireAdminAuth
	server.GetRequestUser = env.GetRequestUser

	// The gate session signing secret is read once here (idempotent: it returns
	// the persisted secret, generating one on first use) so the gate middleware
	// and GrantSession share the same key.
	authSecret, err := ensureSigningSecret(deps.Datastore)
	if err != nil {
		log.Errorln("plugin auth: could not establish session signing secret:", err)
	}

	host := &Host{
		manager:          manager,
		sqlStore:         sqlStore,
		server:           server,
		sse:              sseHub,
		configRepository: deps.ConfigRepository,
		requireAdminAuth: deps.RequireAdminAuth,
		kv:               env.KV,
		tickCancel:       tickCancel,
		getRequestUser:   env.GetRequestUser,
		authSecret:       authSecret,
		userByToken: func(token string) *plugins.HostUser {
			u := deps.UserRepository.GetUserByToken(token)
			if u == nil {
				return nil
			}
			hu := toHostUser(u)
			return &hu
		},
	}
	host.authGateSettings.Store(authGateSettingsSnapshot{})
	return host, nil
}

// AdminHandler returns the HTTP handler for plugin management:
//
//	GET  /api/admin/plugins                       list discovered plugins (admin)
//	POST /api/admin/plugins/<name>/enable|disable|reload  toggle a plugin (admin)
//	GET  /api/admin/plugins/<name>/instructions   bundled INSTRUCTIONS.md markdown (admin)
//	GET  /api/plugins/actions                     merged action-button list (public)
//
// It's mounted by the router on the outer mux so it sits beside, not inside,
// the OpenAPI-generated /api router.
func (p *Host) AdminHandler() http.Handler {
	mux := http.NewServeMux()

	// Admin-protected routes go through the host's RequireAdminAuth
	// middleware — same realm, same CORS handling, same logging as the
	// rest of /api/admin/*.
	requireAdmin := p.requireAdminAuth
	if requireAdmin == nil {
		// Defensive: a caller built Host without wiring the middleware.
		// Treat as "always reject" so a misconfigured boot doesn't expose
		// the management API.
		requireAdmin = func(http.HandlerFunc) http.HandlerFunc {
			return func(w http.ResponseWriter, _ *http.Request) {
				http.Error(w, "admin auth not configured", http.StatusUnauthorized)
			}
		}
	}

	mux.Handle("/api/admin/plugins", requireAdmin(func(w http.ResponseWriter, r *http.Request) {
		switch r.Method {
		case http.MethodGet:
			writeJSONResponse(w, http.StatusOK, p.manager.List())
		case http.MethodPost:
			p.handlePluginUpload(w, r)
		default:
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		}
	}))

	// Registry browse + install. Sibling prefix so the catch-all
	// /api/admin/plugins/ trailing-slash matcher below doesn't swallow
	// them. Registered as a prefix (trailing slash) and dispatched
	// internally so /list and /list/ both work — the admin frontend's
	// Next.js dev server 308-redirects every URL to its slash variant
	// because of trailingSlash:true in next.config.js.
	mux.Handle("/api/admin/plugin-registry/", requireAdmin(p.handleRegistryRoute))

	mux.Handle("/api/admin/plugins/", requireAdmin(p.handlePluginAction))

	mux.HandleFunc("/api/plugins/actions", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		actions := make([]plugins.ActionButton, 0)
		for _, loaded := range p.manager.Snapshot() {
			actions = append(actions, loaded.Manifest.Actions...)
		}
		writeJSONResponse(w, http.StatusOK, actions)
	})

	// Plugin icon. Public on purpose: the admin UI renders these in the
	// plugin list and the sidebar via an <img> tag, which doesn't carry
	// the Authorization header, and the bytes themselves aren't
	// sensitive. The host reads icon.png directly from the package on
	// each request, so an admin who swaps the icon gets the new one
	// without reloading the plugin.
	mux.HandleFunc("/api/plugins/", func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		const prefix = "/api/plugins/"
		const suffix = "/icon"
		rest := strings.TrimPrefix(r.URL.Path, prefix)
		if !strings.HasSuffix(rest, suffix) {
			http.NotFound(w, r)
			return
		}
		name := strings.TrimSuffix(rest, suffix)
		if name == "" || strings.ContainsAny(name, "/") {
			http.NotFound(w, r)
			return
		}
		data, err := p.manager.IconBytes(name)
		if err != nil {
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", "image/png")
		w.Header().Set("Cache-Control", "no-cache")
		// gosec G705: not XSS. We've set Content-Type to image/png and the
		// bytes come from the plugin's bundled icon.png, written by the
		// admin who installed the plugin (not user-controlled input).
		_, _ = w.Write(data) //nolint:gosec // G705 false positive: image/png body
	})

	return mux
}

func writeJSONResponse(w http.ResponseWriter, status int, body any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(body)
}

// logPluginSummary writes the boot inventory of plugins to the Owncast log:
// every discovered plugin, its enabled/disabled (and loaded) status, and the
// permissions it declares. Errors from a failed load are surfaced as warnings
// so an admin sees them in the console without checking the admin API.
func logPluginSummary(entries []plugins.DiscoveredEntry) {
	log.Infof("plugins: %d discovered", len(entries))
	for _, e := range entries {
		status := "disabled"
		if e.Enabled {
			status = "enabled"
			if !e.Loaded {
				status = "enabled (load failed)"
			}
		}
		permPart := "with no permissions"
		if len(e.Permissions) > 0 {
			permPart = "with permissions: " + strings.Join(e.Permissions, ", ")
		}
		nameDisplay := e.DisplayName
		if nameDisplay == "" {
			nameDisplay = e.Slug
		}
		log.Infof("  - %s [%s] v%s %s %s", nameDisplay, e.Slug, e.Version, status, permPart)
		if e.LastError != "" {
			log.Warnf("    last error: %s", e.LastError)
		}
	}
}

// handlePluginAction dispatches POST /api/admin/plugins/<slug>/<action>
// to the matching Manager operation (enable, disable, reload, uninstall).
// The URL segment is the plugin's slug, not its display name; Manager
// keys every operation on slug.
func (p *Host) handlePluginAction(w http.ResponseWriter, r *http.Request) {
	slug, action, ok := strings.Cut(strings.TrimPrefix(r.URL.Path, "/api/admin/plugins/"), "/")
	if !ok || slug == "" || action == "" {
		http.Error(w, "expected /<slug>/<action>", http.StatusBadRequest)
		return
	}

	// GET /api/admin/plugins/<slug>/instructions serves the bundled
	// INSTRUCTIONS.md as raw markdown; the admin UI renders it in a details
	// tab. Read fresh from disk on each request so a swapped file shows up
	// without reloading the plugin.
	if action == "instructions" {
		if r.Method != http.MethodGet {
			http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
			return
		}
		data, err := p.manager.InstructionsBytes(slug)
		if err != nil {
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", "text/markdown; charset=utf-8")
		w.Header().Set("Cache-Control", "no-cache")
		// gosec G705 (XSS via taint): the route is admin-authenticated,
		// the response Content-Type is text/markdown (not text/html), and
		// the bytes are the admin's own uploaded INSTRUCTIONS.md content.
		// The admin UI renders them through ReactMarkdown, which sanitizes
		// before insertion.
		_, _ = w.Write(data) //nolint:gosec // G705
		return
	}
	if action == "auth-settings" {
		p.handleAuthGateSettings(w, r, slug)
		return
	}

	// GET/POST /api/admin/plugins/<slug>/config reads and writes the admin's
	// overrides for the plugin's manifest-declared config fields. The admin UI
	// auto-renders a form from the schema (returned with the plugin list) and
	// saves through here.
	if action == "config" {
		p.handlePluginConfig(w, r, slug)
		return
	}

	if r.Method != http.MethodPost {
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	err, known := p.dispatchPluginAction(r.Context(), slug, action)
	if !known {
		http.Error(w, "unknown action; expected enable, disable, reload, or uninstall", http.StatusBadRequest)
		return
	}
	if err != nil {
		writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: err.Error()})
		return
	}
	if action == "uninstall" {
		log.Infof("plugin %q uninstalled by admin", slug)
	}
	writeJSONResponse(w, http.StatusOK, map[string]string{jsonStatusKey: "ok", jsonSlugKey: slug, "action": action})
}

// handlePluginConfig serves the admin config form's backend:
//
//	GET  /api/admin/plugins/<slug>/config  → current effective values
//	     (admin override if set, else the manifest default) per declared key
//	POST /api/admin/plugins/<slug>/config  → save overrides ({key: value})
//
// POST validates each key against the manifest schema (declared + correct
// type) and persists the result in the plugin's KV namespace, where
// owncast.config.get reads it back.
func (p *Host) handlePluginConfig(w http.ResponseWriter, r *http.Request, slug string) {
	schema := p.manager.ConfigSchema(slug)
	if schema == nil {
		// Unknown plugin, or one that declares no config — nothing to edit.
		http.NotFound(w, r)
		return
	}

	switch r.Method {
	case http.MethodGet:
		overrides := readConfigOverrides(p.kv, slug)
		out := make(map[string]any, len(schema))
		for key, field := range schema {
			if v, ok := overrides[key]; ok {
				out[key] = v
			} else {
				out[key] = field.Default
			}
		}
		writeJSONResponse(w, http.StatusOK, out)

	case http.MethodPost:
		var incoming map[string]any
		if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&incoming); err != nil {
			http.Error(w, "invalid JSON body", http.StatusBadRequest)
			return
		}
		saved := make(map[string]any, len(incoming))
		for key, raw := range incoming {
			field, declared := schema[key]
			if !declared {
				writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: fmt.Sprintf("unknown config key %q", key)})
				return
			}
			v, err := coerceConfigValue(field.Type, raw)
			if err != nil {
				writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: fmt.Sprintf("config %q: %v", key, err)})
				return
			}
			saved[key] = v
		}
		data, err := json.Marshal(saved)
		if err != nil {
			http.Error(w, "internal error", http.StatusInternalServerError)
			return
		}
		if p.kv == nil {
			http.Error(w, "config storage unavailable", http.StatusInternalServerError)
			return
		}
		if err := p.kv.Namespace(slug).Set(runtimeConfigKey, data); err != nil {
			writeJSONResponse(w, http.StatusInternalServerError, map[string]string{jsonErrorKey: err.Error()})
			return
		}
		writeJSONResponse(w, http.StatusOK, map[string]string{jsonStatusKey: "ok", jsonSlugKey: slug})

	default:
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
	}
}

func (p *Host) handleAuthGateSettings(w http.ResponseWriter, r *http.Request, slug string) {
	if !p.manager.IsAuthGate(slug) {
		http.NotFound(w, r)
		return
	}

	switch r.Method {
	case http.MethodGet:
		writeJSONResponse(w, http.StatusOK, p.authGateSettingsFor(slug))
	case http.MethodPost:
		var settings AuthGateSettings
		decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
		decoder.DisallowUnknownFields()
		if err := decoder.Decode(&settings); err != nil || !settings.valid() {
			http.Error(w, "invalid authentication access mode", http.StatusBadRequest)
			return
		}
		if err := p.saveAuthGateSettings(slug, settings); err != nil {
			writeJSONResponse(w, http.StatusInternalServerError, map[string]string{jsonErrorKey: err.Error()})
			return
		}
		writeJSONResponse(w, http.StatusOK, map[string]string{jsonStatusKey: "ok", jsonSlugKey: slug})
	default:
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
	}
}

// dispatchPluginAction calls the Manager method for one of the admin
// actions. Returns (operationError, true) for a known action, or
// (nil, false) when action is unrecognized.
func (p *Host) dispatchPluginAction(ctx context.Context, slug, action string) (error, bool) {
	switch action {
	case "enable":
		return p.manager.Enable(ctx, slug), true
	case "disable":
		return p.manager.Disable(ctx, slug), true
	case "reload":
		return p.manager.Reload(ctx, slug), true
	case "uninstall":
		return p.manager.Uninstall(ctx, slug), true
	}
	return nil, false
}

// handlePluginUpload accepts a multipart upload of a .ocpkg file from
// the admin UI, validates it, writes it into the plugins directory under
// the manifest's name (not the uploaded filename), and forces a scan
// so the new entry appears in the next list. Caps the request body at
// the manager's MaxUploadBytes to keep a hostile upload from filling
// memory before the validation gate runs.
func (p *Host) handlePluginUpload(w http.ResponseWriter, r *http.Request) {
	// MaxBytesReader returns an error as soon as the limit is exceeded,
	// so we never read more than this into memory.
	r.Body = http.MaxBytesReader(w, r.Body, plugins.MaxUploadBytes)
	// The MaxBytesReader above caps the multipart parse; gosec G120's
	// pattern match doesn't see that wrapping, so it's a false positive.
	if err := r.ParseMultipartForm(plugins.MaxUploadBytes); err != nil { //nolint:gosec // G120: bound via MaxBytesReader above
		writeJSONResponse(w, http.StatusRequestEntityTooLarge, map[string]string{jsonErrorKey: err.Error()})
		return
	}
	file, header, err := r.FormFile("plugin")
	if err != nil {
		writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: "expected a file under form field 'plugin': " + err.Error()})
		return
	}
	defer file.Close()
	if !strings.HasSuffix(strings.ToLower(header.Filename), ".ocpkg") {
		writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: "filename must end in .ocpkg"})
		return
	}
	packageBytes, err := io.ReadAll(file)
	if err != nil {
		writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: "read upload: " + err.Error()})
		return
	}
	entry, err := p.manager.InstallUploaded(r.Context(), packageBytes)
	if err != nil {
		writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: err.Error()})
		return
	}
	log.Infof("plugin %q [%s] v%s installed by admin", entry.DisplayName, entry.Slug, entry.Version)
	writeJSONResponse(w, http.StatusOK, entry)
}

// configEnabledStore persists the enabled-plugin set and per-plugin
// admin-approved permission snapshots in Owncast's config datastore
// instead of a .enabled.json file.
type configEnabledStore struct {
	datastore *datastore.Datastore
}

func (s *configEnabledStore) Load() (plugins.StoreData, error) {
	names, err := s.datastore.GetStringSlice(pluginsEnabledConfigKey)
	if err != nil {
		// Unset on a fresh install: start with no plugins enabled.
		return plugins.StoreData{}, nil
	}
	out := plugins.StoreData{Enabled: names}
	raw, err := s.datastore.GetString(pluginsApprovedPermsConfigKey)
	if err == nil && raw != "" {
		var approvals map[string][]string
		if err := json.Unmarshal([]byte(raw), &approvals); err == nil {
			out.ApprovedPermissions = approvals
		}
	}
	return out, nil
}

func (s *configEnabledStore) Save(d plugins.StoreData) error {
	if err := s.datastore.SetStringSlice(pluginsEnabledConfigKey, d.Enabled); err != nil {
		return err
	}
	if len(d.ApprovedPermissions) == 0 {
		return s.datastore.SetString(pluginsApprovedPermsConfigKey, "")
	}
	encoded, err := json.Marshal(d.ApprovedPermissions)
	if err != nil {
		return fmt.Errorf("encode approved permissions: %w", err)
	}
	return s.datastore.SetString(pluginsApprovedPermsConfigKey, string(encoded))
}

func wirePluginLoggingHostFn(env *plugins.HostEnv) {
	env.Log = func(pluginName string, level plugins.PluginLogLevel, message string) {
		switch level {
		case plugins.PluginLogWarning:
			log.Warnf("plugin %s: %s", pluginName, message)
		case plugins.PluginLogError:
			log.Errorf("plugin %s: %s", pluginName, message)
		default:
			log.Infof("plugin %s: %s", pluginName, message)
		}
	}
}

// wirePluginHostEnv connects each HostEnv host-function pointer to the
// corresponding Owncast service call. Closures read services lazily so they
// observe current config/state on every call.
func wirePluginHostEnv(env *plugins.HostEnv, deps Deps) {
	wirePluginLoggingHostFn(env)
	chatbots := newPluginChatbotProvisioner(deps.UserRepository, deps.Datastore)
	wireChatSendHostFns(env, deps, chatbots)
	wireChatReadHostFns(env, deps)
	wireChatModerationHostFns(env, deps)
	wireServerReadHostFns(env, deps)
	wireVideoConfigHostFns(env, deps)
	wireUserHostFns(env, deps)
	wireAuthHostFns(env, deps)
	wireNotificationHostFns(env, deps)

	// Resolve admin-set config overrides for owncast.config.get. Without this
	// the host returns manifest defaults only; with it, values saved via the
	// admin config form take effect. Reads the plugin's own KV namespace.
	env.ConfigValue = func(slug, key string) (any, bool) {
		v, ok := readConfigOverrides(env.KV, slug)[key]
		return v, ok
	}
	wireRequestHostFns(env, deps)
	wireFilesystemHostFns(env)
}

// pluginStorageRootDirName is the directory under config.DataDirectory that
// holds everything a plugin stores on disk, one subdirectory per plugin. 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 pluginStorageRootDirName = "plugin-storage"

// legacyPluginDataRootDirName is where storage.fs data lived before SQL storage
// gave every plugin one parent directory for all of its on-disk data.
const legacyPluginDataRootDirName = "plugin-data"

// Inside a plugin's storage directory, its two kinds of storage get their own
// subdirectory: plugin-storage/<slug>/files for storage.fs and
// plugin-storage/<slug>/db for storage.sql.
//
// The split is what keeps a database out of reach of the filesystem API. The
// storage.fs sandbox is rooted at files/, so db/ is not merely a path the
// resolver refuses, it is outside the tree the plugin can name at all. That
// matters: max_page_count only refuses to grow a database, so a plugin that
// could write its own database file would simply pre-seed one larger than its
// quota and the host would open it. Reserving filenames inside a shared
// directory would be the fragile version of this, since it would have to keep
// pace with SQLite's journal and WAL sidecar naming forever.
//
// Keeping the trees apart also keeps the two quotas independent, so the limit a
// plugin hits never depends on which API it wrote with first.
const (
	pluginFilesDirName    = "files"
	pluginDatabaseDirName = "db"
)

// pluginStorageDir returns one plugin's storage subtree, the parent of both
// files/ and db/.
func pluginStorageDir(root, pluginName string) string {
	return filepath.Join(root, pluginName)
}

// migrateLegacyPluginFilesystemStorage moves existing storage.fs data into the
// files/ subtree before any plugin can access it. Rename keeps each plugin's
// migration atomic on the data volume. A conflicting destination is refused
// rather than hiding or overwriting either copy. Unrecognized files remain in
// the legacy root and do not block well-formed plugin directories.
func migrateLegacyPluginFilesystemStorage(dataDir string) error {
	legacyRoot := filepath.Join(dataDir, legacyPluginDataRootDirName)
	entries, err := os.ReadDir(legacyRoot)
	if os.IsNotExist(err) {
		return nil
	}
	if err != nil {
		return fmt.Errorf("read legacy plugin storage: %w", err)
	}

	storageRoot := filepath.Join(dataDir, pluginStorageRootDirName)
	for _, entry := range entries {
		if !entry.IsDir() {
			log.Warnf("Skipping unexpected file in legacy plugin storage: %s", entry.Name())
			continue
		}
		source := filepath.Join(legacyRoot, entry.Name())
		destinationParent := pluginStorageDir(storageRoot, entry.Name())
		destination := filepath.Join(destinationParent, pluginFilesDirName)
		if _, err := os.Stat(destination); err == nil {
			return fmt.Errorf("migrate legacy plugin storage for %q: destination already exists", entry.Name())
		} else if !os.IsNotExist(err) {
			return fmt.Errorf("inspect plugin storage destination for %q: %w", entry.Name(), err)
		}
		if err := os.MkdirAll(destinationParent, 0o700); err != nil {
			return fmt.Errorf("create plugin storage directory for %q: %w", entry.Name(), err)
		}
		if err := os.Rename(source, destination); err != nil {
			return fmt.Errorf("migrate legacy plugin storage for %q: %w", entry.Name(), err)
		}
		log.Infof("Migrated plugin filesystem storage for %s", entry.Name())
	}
	if err := os.Remove(legacyRoot); err != nil && !os.IsNotExist(err) {
		log.Warnf("Unable to remove legacy plugin storage directory: %v", err)
	}
	return nil
}

// maxPluginFileBytes caps a single storage.fs write. It bounds how much a
// misbehaving plugin can write in one call.
const maxPluginFileBytes = 50 << 20 // 50 MiB

// maxPluginDataBytes caps a plugin's total storage.fs footprint, so it can't
// fill the host disk with many files that each fit under maxPluginFileBytes.
const maxPluginDataBytes = 256 << 20 // 256 MiB per plugin

// dirSize returns the total size of regular files under dir, or 0 if dir does
// not exist yet.
// ponytail: O(files) walk on every write; if a plugin writes heavily into a
// large tree, switch to a cached running total per sandbox.
func dirSize(dir string) (int64, error) {
	var total int64
	err := filepath.WalkDir(dir, func(_ string, d os.DirEntry, err error) error {
		if err != nil {
			if os.IsNotExist(err) {
				return nil // sandbox not created yet, or an entry vanished mid-walk
			}
			return err
		}
		if d.IsDir() {
			return nil
		}
		info, err := d.Info()
		if err != nil {
			if os.IsNotExist(err) {
				return nil
			}
			return err
		}
		total += info.Size()
		return nil
	})
	return total, err
}

// resolvePluginSandboxPath maps a plugin-supplied relative path to an absolute
// path inside that plugin's storage.fs sandbox
// (root/<pluginName>/files), 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 "..".
//
// Because the sandbox is files/ rather than the whole per-plugin directory, the
// same containment check that stops a plugin reaching another plugin's data also
// stops it reaching its own database.
func resolvePluginSandboxPath(root, pluginName, rel string) (string, error) {
	return resolveContainedPath(filepath.Join(pluginStorageDir(root, pluginName), pluginFilesDirName), rel)
}

// resolvePluginDatabasePath is the same containment guarantee for the host's own
// use of the db/ subtree. A plugin never supplies one of these paths, so this
// exists to keep the layout in one place rather than to defend a boundary.
func resolvePluginDatabasePath(root, pluginName, rel string) (string, error) {
	return resolveContainedPath(filepath.Join(pluginStorageDir(root, pluginName), pluginDatabaseDirName), rel)
}

// resolveContainedPath joins rel under sandbox and refuses any result that
// lands outside it.
func resolveContainedPath(sandbox, rel string) (string, error) {
	sandbox, err := filepath.Abs(sandbox)
	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
}

// fsQuotaCheck rejects a write that would push the plugin's sandbox over the
// aggregate quota. full is the absolute path being written; when it already
// exists it's excluded from the current total, since the write overwrites it
// in place rather than growing the footprint.
//
// It walks files/ only, so a plugin's database never consumes its filesystem
// quota and the two limits stay independent.
func fsQuotaCheck(root, pluginName, full string, addBytes int) error {
	used, err := dirSize(filepath.Join(pluginStorageDir(root, pluginName), pluginFilesDirName))
	if err != nil {
		return err
	}
	var existing int64
	if info, statErr := os.Stat(full); statErr == nil && !info.IsDir() {
		existing = info.Size()
	}
	if used-existing+int64(addBytes) > maxPluginDataBytes {
		return fmt.Errorf("write would exceed the plugin's %d-byte storage quota", maxPluginDataBytes)
	}
	return nil
}

// wireFilesystemHostFns implements the storage.fs host functions against each
// plugin's files/ subdirectory under config.DataDirectory/plugin-storage.
func wireFilesystemHostFns(env *plugins.HostEnv) {
	wireFilesystemHostFnsWithRoot(env, filepath.Join(config.DataDirectory, pluginStorageRootDirName))
}

// 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
		}
		// Enforce the per-plugin aggregate quota: the single-file cap alone
		// still lets a plugin fill the disk with many files.
		if err := fsQuotaCheck(root, pluginName, full, len(data)); 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
	}
}

func validateVideoConfigUpdate(u plugins.VideoConfigUpdate) error {
	if u.Autoplay != nil {
		if err := u.Autoplay.Validate(); err != nil {
			return err
		}
	}
	if u.Codec != nil && !transcoder.IsCodecSupported(*u.Codec) {
		return fmt.Errorf("invalid video codec %q", *u.Codec)
	}
	return nil
}

// wireVideoConfigHostFns wires the settable video/transcoding configuration:
// videoconfig.read (owncast.videoConfig.read) and videoconfig.write
// (owncast.videoConfig.write). The plugin-facing VideoConfig/StreamVariant
// shapes are a curated, stable wire contract — the mapping to/from Owncast's
// internal models.StreamOutputVariant lives here, at the boundary.
func wireVideoConfigHostFns(env *plugins.HostEnv, deps Deps) {
	cfg := deps.ConfigRepository

	env.VideoConfig = func() plugins.VideoConfig {
		variants := cfg.GetStreamOutputVariants()
		out := plugins.VideoConfig{
			LatencyLevel: cfg.GetStreamLatencyLevel().Level,
			Codec:        cfg.GetVideoCodec(),
			Autoplay:     cfg.GetAutoplay(),
			Variants:     make([]plugins.StreamVariant, 0, len(variants)),
		}
		for _, v := range variants {
			out.Variants = append(out.Variants, plugins.StreamVariant{
				Width:         v.ScaledWidth,
				Height:        v.ScaledHeight,
				Framerate:     v.Framerate,
				VideoBitrate:  v.VideoBitrate,
				CPUUsageLevel: v.CPUUsageLevel,
				IsPassthrough: v.IsVideoPassthrough,
			})
		}
		return out
	}

	env.WriteVideoConfig = func(pluginName string, u plugins.VideoConfigUpdate) error {
		if err := validateVideoConfigUpdate(u); err != nil {
			return err
		}
		if u.Autoplay != nil {
			if err := cfg.SetAutoplay(*u.Autoplay); err != nil {
				return err
			}
		}
		if u.LatencyLevel != nil {
			if err := cfg.SetStreamLatencyLevel(float64(*u.LatencyLevel)); err != nil {
				return err
			}
		}
		if u.Codec != nil {
			if err := cfg.SetVideoCodec(*u.Codec); err != nil {
				return err
			}
		}
		if u.Variants != nil {
			existing := cfg.GetStreamOutputVariants()
			variants := make([]models.StreamOutputVariant, 0, len(u.Variants))
			for i, v := range u.Variants {
				variant := models.StreamOutputVariant{}
				if i < len(existing) {
					variant = existing[i]
				}
				variant.ScaledWidth = v.Width
				variant.ScaledHeight = v.Height
				variant.Framerate = v.Framerate
				variant.VideoBitrate = v.VideoBitrate
				variant.CPUUsageLevel = v.CPUUsageLevel
				variant.IsVideoPassthrough = v.IsPassthrough
				variants = append(variants, variant)
			}
			if err := cfg.SetStreamOutputVariants(variants); err != nil {
				return err
			}
		}
		// Mirror the admin video-config handlers: persist only. The change
		// takes effect on the next stream start (the admin UI already shows
		// this), so we deliberately do NOT restart a live transcoder.
		log.Infof("plugin %q changed video config via videoconfig.write; will take effect on next stream start", pluginName)
		return nil
	}
}

func wireChatSendHostFns(env *plugins.HostEnv, deps Deps, chatbots *pluginChatbotProvisioner) {
	chatSvc := deps.Chat

	env.OnChat = func(req plugins.ChatSendRequest) {
		switch req.Kind {
		case plugins.ChatSendAction:
			if err := chatSvc.SendSystemAction(req.Text, false); err != nil {
				log.Errorln("plugin", req.PluginSlug, "chat action:", err)
			}
		case plugins.ChatSendSystem:
			if err := chatSvc.SendSystemMessage(req.Text, false); err != nil {
				log.Errorln("plugin", req.PluginSlug, "chat system message:", err)
			}
		default: // ChatSendBot — post under the plugin's own chatbot identity.
			// Use slug for the bot's persistent identity (cache + datastore
			// key), and BotDisplayName for the human-readable handle viewers
			// see in chat. BotDisplayName falls back to the plugin's display
			// name in the host fn closure, so it's always non-empty here.
			chatbot, err := chatbots.chatbotUser(req.PluginSlug, req.BotDisplayName)
			if err != nil {
				log.Errorln("plugin", req.PluginSlug, "resolve chatbot user:", err)
				return
			}
			if err := chatSvc.SendMessageAsBot(chatbot, req.Text); err != nil {
				log.Errorln("plugin", req.PluginSlug, "chat send:", err)
			}
		}
	}

	env.SendChatTo = func(pluginSlug string, clientID uint64, text string) {
		chatSvc.SendSystemMessageToClient(uint(clientID), text)
	}
}

func wireChatReadHostFns(env *plugins.HostEnv, deps Deps) {
	chatSvc := deps.Chat

	env.ChatHistory = func(limit int) []plugins.HostChatMessage {
		history := deps.ChatMessageRepository.GetChatHistory()
		out := make([]plugins.HostChatMessage, 0, len(history))
		for _, item := range history {
			msg, ok := item.(events.UserMessageEvent)
			if !ok {
				continue
			}
			hm := plugins.HostChatMessage{
				ID:        msg.ID,
				Body:      msg.Body,
				Timestamp: msg.Timestamp.UTC().Format(time.RFC3339Nano),
			}
			hm.User = toHostUserPtr(msg.User)
			out = append(out, hm)
		}
		if limit > 0 && len(out) > limit {
			out = out[len(out)-limit:]
		}
		return out
	}

	env.ChatClients = func() []plugins.HostChatClient {
		clients := chatSvc.GetClients()
		out := make([]plugins.HostChatClient, 0, len(clients))
		for _, c := range clients {
			hc := plugins.HostChatClient{
				ID:           uint64(c.Id),
				ConnectedAt:  c.ConnectedAt.UTC().Format(time.RFC3339Nano),
				UserAgent:    c.UserAgent,
				IPAddress:    c.IPAddress,
				MessageCount: c.MessageCount,
			}
			if c.User != nil {
				hc.UserID = c.User.ID
				hc.DisplayName = c.User.DisplayName
			}
			out = append(out, hc)
		}
		return out
	}
}

func wireChatModerationHostFns(env *plugins.HostEnv, deps Deps) {
	chatSvc := deps.Chat

	env.DeleteMessage = func(pluginName, messageID string) error {
		if err := chatSvc.SetMessagesVisibility([]string{messageID}, false, nil); err != nil {
			return err
		}
		return nil
	}

	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
	}
}

func wireServerReadHostFns(env *plugins.HostEnv, deps Deps) {
	cfg := deps.ConfigRepository
	streamSvc := deps.Stream

	env.StreamCurrent = func() plugins.StreamInfo {
		status := streamSvc.GetStatus()
		info := plugins.StreamInfo{
			Online:       status.Online,
			Title:        cfg.GetStreamTitle(),
			Summary:      cfg.GetServerSummary(),
			Viewers:      status.ViewerCount,
			LatencyLevel: cfg.GetStreamLatencyLevel().Level,
		}
		if status.LastConnectTime != nil && status.LastConnectTime.Valid {
			info.StartedAt = status.LastConnectTime.Time.UTC().Format(time.RFC3339Nano)
		}
		return info
	}

	env.ServerInfo = func() plugins.ServerInfo {
		return plugins.ServerInfo{
			Name:           cfg.GetServerName(),
			URL:            cfg.GetServerURL(),
			Summary:        cfg.GetServerSummary(),
			WelcomeMessage: cfg.GetServerWelcomeMessage(),
			Version:        config.VersionNumber,
		}
	}

	env.Socials = func() []plugins.SocialHandle {
		handles := cfg.GetSocialHandles()
		out := make([]plugins.SocialHandle, 0, len(handles))
		for _, h := range handles {
			out = append(out, plugins.SocialHandle{Platform: h.Platform, URL: h.URL, Icon: h.Icon})
		}
		return out
	}

	// Emotes exposes the server's custom chat emotes (the same set the public
	// /api/emoji endpoint serves) so plugins can render or filter `:code:`
	// emotes server-side. URLs are server-relative, matching /api/emoji.
	env.Emotes = func() []plugins.Emote {
		list := datastore.GetEmojiList()
		out := make([]plugins.Emote, 0, len(list))
		for _, e := range list {
			emote := plugins.Emote{}
			if e.Name != nil {
				emote.Name = *e.Name
			}
			if e.Url != nil {
				emote.URL = *e.Url
			}
			out = append(out, emote)
		}
		return out
	}

	env.Federation = func() plugins.FederationInfo {
		return plugins.FederationInfo{
			Enabled:   cfg.GetFederationEnabled(),
			Username:  cfg.GetFederationUsername(),
			IsPrivate: cfg.GetFederationIsPrivate(),
		}
	}

	env.Tags = func() []string {
		return cfg.GetServerMetadataTags()
	}

	// Broadcaster is read-only telemetry about the inbound feed (nil between
	// streams), distinct from the settable video config below.
	env.Broadcaster = func() plugins.StreamBroadcaster {
		b := streamSvc.GetBroadcaster()
		if b == nil {
			return plugins.StreamBroadcaster{}
		}
		d := b.StreamDetails
		codecs := make([]string, 0, 2)
		if d.VideoCodec != "" {
			codecs = append(codecs, d.VideoCodec)
		}
		if d.AudioCodec != "" {
			codecs = append(codecs, d.AudioCodec)
		}
		out := plugins.StreamBroadcaster{
			RemoteAddr: b.RemoteAddr,
			Codecs:     codecs,
			Framerate:  int(d.VideoFramerate),
		}
		if d.Width > 0 || d.Height > 0 {
			out.Resolution = fmt.Sprintf("%dx%d", d.Width, d.Height)
		}
		if d.VideoBitrate > 0 {
			out.Bitrates = []int{d.VideoBitrate}
		}
		return out
	}
}

func wireUserHostFns(env *plugins.HostEnv, deps Deps) {
	users := deps.UserRepository
	chatSvc := deps.Chat

	env.Users = func() []plugins.HostUser {
		all := users.GetUsers()
		out := make([]plugins.HostUser, 0, len(all))
		for _, u := range all {
			out = append(out, toHostUser(u))
		}
		return out
	}

	env.UserGet = func(id string) (plugins.HostUser, bool) {
		u := users.GetUserByID(id)
		if u == nil {
			return plugins.HostUser{}, false
		}
		return toHostUser(u), true
	}

	env.SetUserEnabled = func(pluginName, userID string, enabled bool, reason string) error {
		if err := users.SetEnabled(userID, enabled, reason); err != nil {
			return err
		}
		if !enabled {
			if clients, err := chatSvc.GetClientsForUser(userID); err == nil {
				chatSvc.DisconnectClients(clients)
			}
		}
		return nil
	}

	env.BanIP = func(pluginName, ip string) error {
		return deps.AuthRepository.BanIPAddress(ip, "banned by plugin "+pluginName)
	}
}

// pluginAuthSigningSecretKey is where the gate session signing secret is
// persisted. Generated once on first use; rotating it (clearing the row)
// invalidates every outstanding session.
const pluginAuthSigningSecretKey = "plugin_auth_signing_secret" //nolint:gosec // G101: datastore key name, not a credential.

// ensureSigningSecret returns the persisted gate session signing secret,
// generating and storing one on first use.
func ensureSigningSecret(ds *datastore.Datastore) ([]byte, error) {
	if hexStr, err := ds.GetString(pluginAuthSigningSecretKey); err == nil && hexStr != "" {
		if b, derr := hex.DecodeString(hexStr); derr == nil && len(b) > 0 {
			return b, nil
		}
	}
	secret := make([]byte, 32)
	if _, err := rand.Read(secret); err != nil {
		return nil, err
	}
	if err := ds.SetString(pluginAuthSigningSecretKey, hex.EncodeToString(secret)); err != nil {
		return nil, err
	}
	return secret, nil
}

// pluginGrantableScopes are the user scopes a viewer-auth plugin may assign via
// owncast.users.register. MODERATOR and the chat-send scopes map cleanly from
// an external provider's roles; HAS_ADMIN_ACCESS — the scope that unlocks the
// external admin API — is intentionally excluded so a login plugin can't mint
// administrative access.
var pluginGrantableScopes = map[string]bool{
	models.ModeratorScopeKey:          true,
	models.ScopeCanSendChatMessages:   true,
	models.ScopeCanSendSystemMessages: true,
}

// validatePluginGrantedScopes rejects any scope a plugin is not allowed to
// assign through users.register, so the whole registration fails up front
// rather than silently dropping (or, worse, applying) an unintended scope.
func validatePluginGrantedScopes(scopes []string) error {
	for _, s := range scopes {
		if !pluginGrantableScopes[s] {
			return fmt.Errorf("plugin may not grant scope %q", s)
		}
	}
	return nil
}

// validateProfileURL rejects a plugin-supplied profile URL that isn't a plain
// http(s) link. The URL is stored as a verified identity and rendered as a
// clickable public link later, so a non-http scheme (javascript:, data:) or a
// hostless value must fail at registration rather than ship to a browser. An
// empty URL is allowed: a gate-only plugin surfaces nothing publicly.
func validateProfileURL(profileURL string) error {
	if profileURL == "" {
		return nil
	}
	u, err := url.Parse(profileURL)
	if err != nil {
		return fmt.Errorf("invalid profile URL: %w", err)
	}
	if (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
		return fmt.Errorf("profile URL must be an http(s) link")
	}
	return nil
}

func generatedDisplayName(displayName string) string {
	if displayName == "" {
		return utils.GeneratePhrase()
	}
	return displayName
}

// wireAuthHostFns wires the viewer-authentication host functions: register an
// authenticated user for an external (plugin-provided) identity, and mint a
// signed gate session for them.
func wireAuthHostFns(env *plugins.HostEnv, deps Deps) {
	users := deps.UserRepository

	secret, err := ensureSigningSecret(deps.Datastore)
	if err != nil {
		log.Errorln("plugin auth: could not establish session signing secret:", err)
		// Leave RegisterUser/GrantSession unset: the host functions then report
		// "not available" to the plugin rather than minting unsigned sessions.
		return
	}

	env.RegisterUser = registerPluginUser(users)
	env.GrantSession = grantPluginSession(users, secret)
}

func registerPluginUser(users userrepository.UserRepository) func(string, plugins.UserRegisterRequest) (string, error) {
	return func(pluginName string, req plugins.UserRegisterRequest) (string, error) {
		// Validate requested scopes and the profile URL against their boundaries
		// BEFORE creating any user, so a disallowed scope (e.g. HAS_ADMIN_ACCESS)
		// or a bad URL fails cleanly without leaving an orphan account.
		if err := validatePluginGrantedScopes(req.Scopes); err != nil {
			return "", err
		}
		if err := validateProfileURL(req.ProfileURL); err != nil {
			return "", err
		}
		// The identity is keyed by (provider=plugin slug, auth_key=authId), so
		// two auth plugins can't collide on, or impersonate, each other's users.
		var userID string
		if existing := users.GetUserByPluginAuth(pluginName, req.AuthID); existing != nil {
			userID = existing.ID
		} else {
			user, _, err := users.CreateAnonymousUser(generatedDisplayName(req.DisplayName))
			if err != nil {
				return "", err
			}
			// Profile fields are captured at registration only. is_public is the
			// user's consent and must not be silently re-flipped by the plugin on
			// later logins; profileUrl/handle staleness is a worthwhile trade for
			// not adding an update path until the public UI needs one.
			// ponytail: capture-on-create; add UpdateAuth when the badge UI lands.
			fields := &models.LinkedIdentityFields{
				Provider:   pluginName,
				ProfileURL: req.ProfileURL,
				Handle:     req.Handle,
				Public:     req.Public,
			}
			if err := users.AddAuth(user.ID, req.AuthID, models.PluginAuth, fields); err != nil {
				// AddAuth failed after the user was created — most likely a
				// concurrent registration won the race against the unique plugin
				// identity index. Don't leave the half-built user (with its access
				// token) orphaned: drop it, and if the identity now resolves, adopt
				// the winner so the racing login still succeeds as one user.
				if delErr := users.DeleteUser(user.ID); delErr != nil {
					log.Errorln("plugin", pluginName, "cleanup user after failed auth link:", delErr)
				}
				winner := users.GetUserByPluginAuth(pluginName, req.AuthID)
				if winner == nil {
					return "", err
				}
				userID = winner.ID
			} else {
				if err := users.SetUserAsAuthenticated(user.ID); err != nil {
					log.Errorln("plugin", pluginName, "set user authenticated:", err)
				}
				userID = user.ID
			}
		}
		// Map the provider's roles onto Owncast scopes (e.g. MODERATOR), applied
		// on every login so an upstream role change takes effect. The scopes
		// were allow-listed above.
		if len(req.Scopes) > 0 {
			if err := users.SetUserScopes(userID, req.Scopes); err != nil {
				log.Errorln("plugin", pluginName, "set user scopes:", err)
			}
		}
		return userID, nil
	}
}

func grantPluginSession(users userrepository.UserRepository, secret []byte) func(string, string, int64) (string, error) {
	return func(pluginName, userID string, ttlSeconds int64) (string, error) {
		// Only mint a session for a user THIS plugin registered. RegisterUser
		// namespaces every plugin identity by slug; mirror that here so a gate
		// plugin can't grant a session impersonating an arbitrary existing user
		// (e.g. a moderator) just by naming their id.
		if !users.UserRegisteredByPlugin(pluginName, userID) {
			return "", fmt.Errorf("user %q was not registered by plugin %q", userID, pluginName)
		}
		// Mint an access token for this session and carry it (signed) in the
		// cookie, so the chat /ws path can resolve the viewer via the existing
		// GetUserByToken lookup. Login is infrequent, so a token per session is
		// acceptable.
		token, err := utils.GenerateAccessToken()
		if err != nil {
			return "", err
		}
		if err := users.AddAccessTokenForUser(token, userID); err != nil {
			return "", err
		}
		ttl := plugins.ClampSessionTTL(ttlSeconds)
		exp := time.Now().Add(ttl).Unix()
		return plugins.SignSession(secret, token, exp), nil
	}
}

func wireNotificationHostFns(env *plugins.HostEnv, deps Deps) {
	cfg := deps.ConfigRepository

	env.SendDiscord = func(pluginName, text string) {
		dc := cfg.GetDiscordConfig()
		if !dc.Enabled || dc.Webhook == "" {
			return
		}
		notifier, err := discord.New(cfg.GetServerName(), cfg.GetServerURL()+"/logo", dc.Webhook)
		if err != nil {
			log.Errorln("plugin", pluginName, "discord:", err)
			return
		}
		if err := notifier.Send(text); err != nil {
			log.Errorln("plugin", pluginName, "discord send:", err)
		}
	}

	env.SendBrowserPush = func(pluginName string, p plugins.BrowserPushPayload) {
		publicKey, err := cfg.GetBrowserPushPublicKey()
		if err != nil {
			return
		}
		privateKey, err := cfg.GetBrowserPushPrivateKey()
		if err != nil {
			return
		}
		notifier, err := browser.New(deps.Datastore, publicKey, privateKey)
		if err != nil {
			log.Errorln("plugin", pluginName, "browser push:", err)
			return
		}
		destinations, err := deps.NotificationsRepository.GetNotificationDestinationsForChannel(notificationsrepository.BrowserPushNotification)
		if err != nil {
			return
		}
		for _, destination := range destinations {
			if _, err := notifier.Send(destination, p.Title, p.Body); err != nil {
				log.Debugln("plugin", pluginName, "browser push send:", err)
			}
		}
	}

	env.SendFediverse = func(pluginName string, p plugins.FediversePayload) {
		var image *string
		if p.Image != "" {
			image = &p.Image
		}
		if err := deps.Chat.SendFediverseAction(p.Type, cfg.GetFederationUsername(), image, p.Body, p.Link); err != nil {
			log.Errorln("plugin", pluginName, "fediverse action:", err)
		}
	}

	env.PostFediverse = func(pluginName, text string) (string, error) {
		// Owncast publishes the note but does not return its URL.
		if err := deps.Activitypub.SendPublicFederatedMessage(text); err != nil {
			return "", err
		}
		return "", nil
	}
}

func wireRequestHostFns(env *plugins.HostEnv, deps Deps) {
	cfg := deps.ConfigRepository
	users := deps.UserRepository

	env.UploadStorage = func(pluginName, name string, data []byte) (string, error) {
		return uploadPluginAsset(cfg, pluginName, name, data)
	}

	env.IsAuthenticated = deps.IsAdminRequest

	env.GetRequestUser = func(r *http.Request) *plugins.HostUser {
		token := utils.ChatAccessTokenFromRequest(r)
		if token == "" {
			// Fall back to the viewer-auth gate session: the gate middleware
			// verified the signed cookie and stashed the access token it
			// carries in the request context. This is what lets a plugin's
			// onHttpRequest (and page/tab content) see req.user for a viewer
			// who authenticated through the gate rather than via a chat token.
			token = plugins.SessionTokenFromContext(r.Context())
		}
		if token == "" {
			return nil
		}
		u := users.GetUserByToken(token)
		if u == nil {
			return nil
		}
		hu := toHostUser(u)
		return &hu
	}
}

// toHostUser maps an Owncast user model onto the plugin-facing HostUser. It is
// the single projection of an Owncast user to what a plugin sees: the sender
// identity on every chat payload (chat.message.received, joins/parts/renames/
// moderation, chat.history()) and the record returned by Users() / UserGet(),
// so the exposed surface can't drift between them. A nil user maps to the zero
// HostUser.
func toHostUser(u *models.User) plugins.HostUser {
	if u == nil {
		return plugins.HostUser{}
	}
	hu := plugins.HostUser{
		ID:              u.ID,
		DisplayName:     u.DisplayName,
		DisplayColor:    u.DisplayColor,
		PreviousNames:   u.PreviousNames,
		Scopes:          u.Scopes,
		IsBot:           u.IsBot,
		IsAuthenticated: u.Authenticated,
	}
	if !u.CreatedAt.IsZero() {
		hu.CreatedAt = u.CreatedAt.UTC().Format(time.RFC3339Nano)
	}
	if u.DisabledAt != nil {
		hu.DisabledAt = u.DisabledAt.UTC().Format(time.RFC3339Nano)
	}
	return hu
}

// toHostUserPtr is the pointer form for payloads where the user is optional
// (chat.message.received, moderation, chat.history()): nil user in, nil out.
func toHostUserPtr(u *models.User) *plugins.HostUser {
	if u == nil {
		return nil
	}
	hu := toHostUser(u)
	return &hu
}

// uploadPluginAsset writes a plugin upload under the public files directory
// and returns the URL it is served at. Names are flattened to their base to
// prevent path traversal. S3-backed storage is a follow-up.
func uploadPluginAsset(cfg configrepository.ConfigRepository, pluginName, name string, data []byte) (string, error) {
	safeName := filepath.Base(filepath.Clean("/" + name))
	if safeName == "." || safeName == "/" || safeName == "" {
		return "", fmt.Errorf("invalid upload name %q", name)
	}
	dir := filepath.Join(config.PublicFilesPath, "plugins", pluginName)
	if err := os.MkdirAll(dir, 0o700); err != nil {
		return "", err
	}
	if err := os.WriteFile(filepath.Join(dir, safeName), data, 0o600); err != nil {
		return "", err
	}
	url := strings.TrimSuffix(cfg.GetServerURL(), "/") + "/public/plugins/" + pluginName + "/" + safeName
	return url, nil
}