Skip to content

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

Auto-generate plugin settings form from the manifest config

Gabe Kangas93cca019aaba
diff --git a/pluginhost/config_test.go b/pluginhost/config_test.go
new file mode 100644
index 0000000000..2380c941a2
--- /dev/null
+++ b/pluginhost/config_test.go
@@ -0,0 +1,73 @@
+package pluginhost
+
+import (
+ "testing"
+
+ "github.com/owncast/owncast/services/plugins/kv"
+)
+
+func TestCoerceConfigValue(t *testing.T) {
+ cases := []struct {
+ name string
+ fieldType string
+ in any
+ wantErr bool
+ want any
+ }{
+ {"string ok", "string", "hi", false, "hi"},
+ {"string from number rejected", "string", float64(5), true, nil},
+ {"number ok", "number", float64(3), false, float64(3)},
+ {"number from string rejected", "number", "3", true, nil},
+ {"boolean ok", "boolean", true, false, true},
+ {"boolean from string rejected", "boolean", "true", true, nil},
+ {"unknown type passes through", "", map[string]any{"x": 1}, false, map[string]any{"x": 1}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := coerceConfigValue(tc.fieldType, tc.in)
+ if tc.wantErr {
+ if err == nil {
+ t.Fatalf("expected error, got value %v", got)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if tc.fieldType != "" && got != tc.want {
+ t.Fatalf("got %v want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestReadConfigOverrides(t *testing.T) {
+ store := kv.NewMemory()
+
+ // No overrides saved yet → nil.
+ if got := readConfigOverrides(store, "plug"); got != nil {
+ t.Fatalf("expected nil for unset overrides, got %v", got)
+ }
+ // nil store → nil (no panic).
+ if got := readConfigOverrides(nil, "plug"); got != nil {
+ t.Fatalf("expected nil for nil store, got %v", got)
+ }
+
+ if err := store.Namespace("plug").Set(runtimeConfigKey, []byte(`{"password":"s3cret","count":5,"on":true}`)); err != nil {
+ t.Fatal(err)
+ }
+ m := readConfigOverrides(store, "plug")
+ if m["password"] != "s3cret" {
+ t.Fatalf("password: got %v", m["password"])
+ }
+ if m["count"] != float64(5) {
+ t.Fatalf("count: got %v (%T)", m["count"], m["count"])
+ }
+ if m["on"] != true {
+ t.Fatalf("on: got %v", m["on"])
+ }
+ // A different plugin's namespace is isolated.
+ if got := readConfigOverrides(store, "other"); got != nil {
+ t.Fatalf("expected nil for a different plugin, got %v", got)
+ }
+}
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.go
index 32e5b11128..fe3c35440c 100644
--- a/pluginhost/pluginhost.go
+++ b/pluginhost/pluginhost.go
@@ -121,6 +121,60 @@ type Host struct {
// 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
+}
+
+// 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 }
@@ -839,6 +893,15 @@ func (p *Host) handlePluginAction(w http.ResponseWriter, r *http.Request) {
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
@@ -858,6 +921,76 @@ func (p *Host) handlePluginAction(w http.ResponseWriter, r *http.Request) {
writeJSONResponse(w, http.StatusOK, map[string]string{"status": "ok", "slug": 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{"status": "ok", "slug": 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.
@@ -964,7 +1097,16 @@ func wirePluginHostEnv(env *plugins.HostEnv, deps 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)
}
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index 4676003746..95ca2691dc 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -393,6 +393,21 @@ type DiscoveredEntry struct {
// Derived by the SDK and reported via register(), so it's only known once
// the plugin is loaded — empty for discovered-but-not-loaded plugins.
Commands []CommandInfo `json:"commands,omitempty"`
+ // Config is the plugin's manifest-declared config schema (key → field with
+ // type/default/description). The admin UI auto-renders an editable settings
+ // form from it; the saved values are read back by owncast.config.get().
+ Config map[string]ConfigField `json:"config,omitempty"`
+}
+
+// ConfigSchema returns a discovered plugin's manifest config schema (nil if the
+// plugin is unknown or declares no config).
+func (m *Manager) ConfigSchema(slug string) map[string]ConfigField {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ if d, ok := m.discovered[slug]; ok {
+ return d.Config
+ }
+ return nil
}
// ScanInterval is how often the manager re-scans the plugins directory.
@@ -1012,6 +1027,7 @@ func (m *Manager) scan(ctx context.Context) error {
existing.HasInstructions = hasInstructions
existing.PendingPermissions = pendingPermissions(manifest.Permissions, m.approvedSet[manifest.Slug])
existing.AllowedHosts = manifest.Network.AllowedHosts
+ existing.Config = manifest.Config
} else {
m.discovered[manifest.Slug] = &DiscoveredEntry{
Slug: manifest.Slug,
@@ -1027,6 +1043,7 @@ func (m *Manager) scan(ctx context.Context) error {
HasIcon: hasIcon,
HasInstructions: hasInstructions,
PendingPermissions: pendingPermissions(manifest.Permissions, m.approvedSet[manifest.Slug]),
+ Config: manifest.Config,
}
}
m.mu.Unlock()
diff --git a/services/plugins/manager_config_test.go b/services/plugins/manager_config_test.go
new file mode 100644
index 0000000000..d9ef0ea6db
--- /dev/null
+++ b/services/plugins/manager_config_test.go
@@ -0,0 +1,38 @@
+package plugins
+
+import "testing"
+
+func TestManager_ConfigSchema(t *testing.T) {
+ m := seedManager(
+ map[string]*DiscoveredEntry{
+ "with-config": {
+ Slug: "with-config",
+ Config: map[string]ConfigField{
+ "password": {Type: "string", Default: "letmein", Description: "Shared password"},
+ "limit": {Type: "number", Default: float64(10)},
+ },
+ },
+ "no-config": {Slug: "no-config"},
+ },
+ map[string]bool{},
+ nil,
+ )
+
+ sc := m.ConfigSchema("with-config")
+ if sc == nil {
+ t.Fatal("expected a config schema")
+ }
+ if sc["password"].Type != "string" || sc["password"].Default != "letmein" {
+ t.Fatalf("password field wrong: %+v", sc["password"])
+ }
+ if sc["limit"].Type != "number" {
+ t.Fatalf("limit field wrong: %+v", sc["limit"])
+ }
+
+ if m.ConfigSchema("no-config") != nil {
+ t.Fatal("plugin with no config should return nil schema")
+ }
+ if m.ConfigSchema("unknown") != nil {
+ t.Fatal("unknown plugin should return nil schema")
+ }
+}
diff --git a/web/components/admin/plugins/PluginConfigForm.tsx b/web/components/admin/plugins/PluginConfigForm.tsx
new file mode 100644
index 0000000000..e48f4178ad
--- /dev/null
+++ b/web/components/admin/plugins/PluginConfigForm.tsx
@@ -0,0 +1,101 @@
+import React, { FC, useEffect, useState } from 'react';
+import { Alert, Button, Form, Input, InputNumber, Spin, Switch, Typography, message } from 'antd';
+import { useTranslation } from 'next-export-i18n';
+import { Plugin } from '../../../interfaces/plugin';
+import { Localization } from '../../../types/localization';
+import { fetchData, pluginConfigUrl } from '../../../utils/apis';
+
+const { Text } = Typography;
+
+// secretField masks values for keys that look like credentials, so secrets
+// aren't shown in plain text in the admin form.
+const secretField = (key: string) => /secret|password|token|apikey|api_key|\bkey\b/i.test(key);
+
+// PluginConfigForm auto-renders an editable settings form for a plugin from its
+// manifest `config` schema — no plugin-authored HTML. It loads the current
+// effective values (admin overrides, else manifest defaults) and saves changes
+// back through the host config endpoint, which the plugin then reads via
+// owncast.config.get().
+export const PluginConfigForm: FC<{ plugin: Plugin }> = ({ plugin }) => {
+ const { t } = useTranslation();
+ const [form] = Form.useForm();
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const schema = plugin.config || {};
+ const keys = Object.keys(schema);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ setError(null);
+ fetchData(pluginConfigUrl(plugin.slug))
+ .then(values => {
+ if (!cancelled) form.setFieldsValue(values);
+ })
+ .catch(() => {
+ if (!cancelled) setError(t(Localization.Admin.Plugins.configLoadError));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [plugin.slug]);
+
+ const onFinish = async (values: Record<string, any>) => {
+ setSaving(true);
+ setError(null);
+ try {
+ await fetchData(pluginConfigUrl(plugin.slug), { method: 'POST', data: values });
+ message.success(t(Localization.Admin.Plugins.configSaved));
+ } catch (e: any) {
+ setError(e?.message || t(Localization.Admin.Plugins.configSaveError));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (keys.length === 0) {
+ return <Text type="secondary">{t(Localization.Admin.Plugins.configEmpty)}</Text>;
+ }
+ if (loading) {
+ return <Spin />;
+ }
+
+ return (
+ <Form form={form} layout="vertical" onFinish={onFinish}>
+ {error && <Alert type="error" message={error} style={{ marginBottom: 16 }} />}
+ {keys.map(key => {
+ const field = schema[key];
+ const label = field.description || key;
+ if (field.type === 'boolean') {
+ return (
+ <Form.Item key={key} name={key} label={label} valuePropName="checked">
+ <Switch />
+ </Form.Item>
+ );
+ }
+ if (field.type === 'number') {
+ return (
+ <Form.Item key={key} name={key} label={label}>
+ <InputNumber style={{ width: '100%' }} />
+ </Form.Item>
+ );
+ }
+ return (
+ <Form.Item key={key} name={key} label={label}>
+ {secretField(key) ? <Input.Password autoComplete="new-password" /> : <Input />}
+ </Form.Item>
+ );
+ })}
+ <Form.Item>
+ <Button type="primary" htmlType="submit" loading={saving}>
+ {t(Localization.Admin.Plugins.configSave)}
+ </Button>
+ </Form.Item>
+ </Form>
+ );
+};
diff --git a/web/components/admin/plugins/PluginDetail.tsx b/web/components/admin/plugins/PluginDetail.tsx
index d53c4c065d..0bb9855d65 100644
--- a/web/components/admin/plugins/PluginDetail.tsx
+++ b/web/components/admin/plugins/PluginDetail.tsx
@@ -7,6 +7,7 @@ import { Plugin, PluginCommand, PluginPermission } from '../../../interfaces/plu
import { Localization } from '../../../types/localization';
import { fetchText, pluginInstructionsUrl } from '../../../utils/apis';
import { permissionDescriptionKey } from './permissionDescriptions';
+import { PluginConfigForm } from './PluginConfigForm';
import s from './PluginDetail.module.scss';
const { Title, Text, Paragraph } = Typography;
@@ -377,13 +378,37 @@ export const PluginDetail = ({ plugin }: PluginDetailProps) => {
[plugin.hasInstructions, plugin.slug, t],
);
+ // Auto-generated settings form, rendered from the plugin's manifest `config`
+ // schema. Only shown when the plugin declares config fields — no plugin HTML
+ // required.
+ const configTab = useMemo(
+ () =>
+ plugin.config && Object.keys(plugin.config).length > 0
+ ? {
+ key: '__config',
+ label: (
+ <span>
+ <SettingOutlined /> {t(Localization.Admin.Plugins.configTab)}
+ </span>
+ ),
+ children: <PluginConfigForm plugin={plugin} />,
+ }
+ : null,
+ [plugin, t],
+ );
+
const tabs = useMemo(() => {
- const base = [...pageTabs, permissionsTab, ...(commandsTab ? [commandsTab] : [])];
+ const base = [
+ ...pageTabs,
+ permissionsTab,
+ ...(configTab ? [configTab] : []),
+ ...(commandsTab ? [commandsTab] : []),
+ ];
// Instructions sits as the second tab: after the first admin page (or
// after Permissions when the plugin declares no admin pages), so the
// primary page stays the landing tab.
return instructionsTab ? [base[0], instructionsTab, ...base.slice(1)] : base;
- }, [instructionsTab, pageTabs, permissionsTab, commandsTab]);
+ }, [instructionsTab, pageTabs, permissionsTab, configTab, commandsTab]);
return (
<div>
diff --git a/web/i18n/en/translation.json b/web/i18n/en/translation.json
index 03e084d4d7..10d3eab24b 100644
--- a/web/i18n/en/translation.json
+++ b/web/i18n/en/translation.json
@@ -217,6 +217,12 @@
"browseUpdate": "Update to v{{version}}",
"commandColumnHeader": "Command",
"commandsTab": "Commands",
+ "configTab": "Settings",
+ "configSave": "Save",
+ "configSaved": "Settings saved.",
+ "configSaveError": "Could not save settings.",
+ "configLoadError": "Could not load settings.",
+ "configEmpty": "This plugin has no configurable settings.",
"configure": "Configure",
"descriptionColumnHeader": "Description",
"enabledColumn": "Enabled",
diff --git a/web/interfaces/plugin.ts b/web/interfaces/plugin.ts
index 27b122dc51..8e7e1751f2 100644
--- a/web/interfaces/plugin.ts
+++ b/web/interfaces/plugin.ts
@@ -82,6 +82,11 @@ export interface Plugin {
lastError?: string;
discoveredAt: string;
adminPages?: PluginAdminPage[];
+ // config is the plugin's manifest-declared settings schema (key → field).
+ // The admin auto-renders an editable form from it; saved values are read
+ // back by the plugin via owncast.config.get(). Absent when the plugin
+ // declares no config.
+ config?: Record<string, PluginConfigField>;
// commands lists the plugin's chat commands, derived by the SDK and
// reported via register(). Only populated once the plugin is loaded
// (commands aren't in the static manifest). Shown in a Commands tab on the
@@ -89,6 +94,16 @@ export interface Plugin {
commands?: PluginCommand[];
}
+// PluginConfigField is one entry in a plugin's manifest `config` schema,
+// mirroring services/plugins.ConfigField. `type` drives which input the admin
+// form renders (string → text, number → numeric, boolean → switch); `default`
+// is shown until an admin saves an override.
+export interface PluginConfigField {
+ type: string;
+ default?: any;
+ description?: string;
+}
+
// PluginCommand is one chat command a plugin advertises, mirroring
// services/plugins.CommandInfo. Informational: the plugin's own router does
// the matching; this drives the admin Commands tab and the host's !help.
diff --git a/web/types/localization.ts b/web/types/localization.ts
index abfc887f58..0e5fa8d45d 100644
--- a/web/types/localization.ts
+++ b/web/types/localization.ts
@@ -488,6 +488,12 @@ export const Localization = {
permissionsTab: 'Admin.Plugins.permissionsTab',
commandsTab: 'Admin.Plugins.commandsTab',
instructionsTab: 'Admin.Plugins.instructionsTab',
+ configTab: 'Admin.Plugins.configTab',
+ configSave: 'Admin.Plugins.configSave',
+ configSaved: 'Admin.Plugins.configSaved',
+ configSaveError: 'Admin.Plugins.configSaveError',
+ configLoadError: 'Admin.Plugins.configLoadError',
+ configEmpty: 'Admin.Plugins.configEmpty',
instructionsLoadError: 'Admin.Plugins.instructionsLoadError',
permissionColumnHeader: 'Admin.Plugins.permissionColumnHeader',
commandColumnHeader: 'Admin.Plugins.commandColumnHeader',
diff --git a/web/utils/apis.ts b/web/utils/apis.ts
index 130b33f58e..59534cfa24 100644
--- a/web/utils/apis.ts
+++ b/web/utils/apis.ts
@@ -73,6 +73,10 @@ export const pluginActionUrl = (
) => `/api/admin/plugins/${encodeURIComponent(slug)}/${action}`;
export const pluginInstructionsUrl = (slug: string) =>
`/api/admin/plugins/${encodeURIComponent(slug)}/instructions`;
+// Read (GET) / save (POST) a plugin's admin-set config overrides. The admin
+// config form auto-rendered from the plugin's manifest config schema uses this.
+export const pluginConfigUrl = (slug: string) =>
+ `/api/admin/plugins/${encodeURIComponent(slug)}/config`;
// Upload a new custom emoji
export const UPLOAD_EMOJI = `${API_LOCATION}emoji/upload`;