Skip to content

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

Gek/plugin host integration 001 (#4912)

Gabe Kangas4394cbd2f2a0
diff --git a/.github/workflows/plugin-tests.yaml b/.github/workflows/plugin-tests.yaml
new file mode 100644
index 0000000000..95955fd47e
--- /dev/null
+++ b/.github/workflows/plugin-tests.yaml
@@ -0,0 +1,75 @@
+# Runs the standalone plugin end-to-end integration tests: builds a plugin
+# from the Owncast plugin SDK, loads it into a real Owncast instance, and
+# verifies it filters chat. Mirrors the API test workflow.
+
+name: Automated plugin tests
+
+on:
+ push:
+ paths-ignore:
+ - 'web/**'
+ pull_request:
+ paths-ignore:
+ - 'web/**'
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+
+ steps:
+ - id: skip_check
+ uses: fkirc/skip-duplicate-actions@v5
+ with:
+ concurrent_skipping: 'same_content_newer'
+
+ - name: Check out pull request code
+ uses: actions/checkout@v6
+ if: github.event_name == 'pull_request'
+ with:
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ ref: ${{ github.event.pull_request.head.ref }}
+ fetch-depth: 0
+
+ - name: Fetch base branch for comparison
+ if: github.event_name == 'pull_request'
+ run: |
+ git remote add upstream https://github.com/${{ github.event.pull_request.base.repo.full_name }}.git || true
+ git fetch upstream ${{ github.event.pull_request.base.ref }}
+
+ - name: Check out repository code
+ uses: actions/checkout@v6
+ if: github.event_name == 'push'
+
+ - name: Get changed files
+ id: changed-files-yaml
+ uses: tj-actions/changed-files@v47
+ with:
+ files_yaml: |
+ src:
+ - '**/*.{go,mod,sum}'
+ - 'test/automated/plugins/**'
+
+ - uses: earthly/actions-setup@v1
+ if: steps.changed-files-yaml.outputs.src_any_changed == 'true'
+ with:
+ version: 'latest'
+
+ - name: Earthly version
+ if: steps.changed-files-yaml.outputs.src_any_changed == 'true'
+ run: earthly --version
+
+ - name: Set up QEMU
+ if: steps.changed-files-yaml.outputs.src_any_changed == 'true'
+ id: qemu
+ uses: docker/setup-qemu-action@v4
+ with:
+ image: tonistiigi/binfmt:latest
+ platforms: all
+
+ - name: Run plugin tests
+ if: steps.changed-files-yaml.outputs.src_any_changed == 'true'
+ uses: nick-fields/retry@v4
+ with:
+ timeout_minutes: 15
+ max_attempts: 3
+ command: earthly +plugin-tests
diff --git a/Earthfile b/Earthfile
index 9dba7cf54a..46dec634f9 100644
--- a/Earthfile
+++ b/Earthfile
@@ -225,3 +225,14 @@ hls-tests:
WORKDIR /build/test/automated/hls
RUN npm install
RUN ./run.sh
+
+plugin-tests:
+ FROM --platform=linux/amd64 ghcr.io/gabek/go-crosscompile:latest
+ ENV GOTOOLCHAIN=auto
+ # git clones the plugin SDK; npm builds both the SDK-compiled plugin and
+ # this test suite; gcompat lets the SDK's prebuilt extism-js (glibc) run on
+ # this musl/alpine image.
+ RUN apk add npm git gcompat font-noto && fc-cache -f
+ COPY . /build
+ WORKDIR /build/test/automated/plugins
+ RUN ./run.sh
diff --git a/db/query.sql b/db/query.sql
index 4add1f4778..7b376c2636 100644
--- a/db/query.sql
+++ b/db/query.sql
@@ -108,7 +108,13 @@ SELECT users.id, display_name, display_color, users.created_at, disabled_at, pre
INSERT INTO user_access_tokens(token, user_id) values(?, ?);
-- name: GetUserByAccessToken :one
-SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM users, user_access_tokens WHERE token = ? AND users.id = user_id;
+SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, users.type = 'API' AS is_bot FROM users, user_access_tokens WHERE token = ? AND users.id = user_id;
+
+-- name: GetUserByID :one
+SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot FROM users WHERE id = ?;
+
+-- name: GetUsers :many
+SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot FROM users ORDER BY created_at DESC;
-- name: GetUserDisplayNameByToken :one
SELECT display_name FROM users JOIN user_access_tokens ON users.id = user_access_tokens.user_id WHERE token = ? AND users.disabled_at IS NULL;
diff --git a/db/query.sql.go b/db/query.sql.go
index 625eebfa2e..28b71e1d45 100644
--- a/db/query.sql.go
+++ b/db/query.sql.go
@@ -682,7 +682,7 @@ func (q *Queries) GetUniqueDeliveryInboxes(ctx context.Context) ([]string, error
}
const getUserByAccessToken = `-- name: GetUserByAccessToken :one
-SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes FROM users, user_access_tokens WHERE token = ? AND users.id = user_id
+SELECT users.id, display_name, display_color, users.created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, users.type = 'API' AS is_bot FROM users, user_access_tokens WHERE token = ? AND users.id = user_id
`
type GetUserByAccessTokenRow struct {
@@ -695,6 +695,7 @@ type GetUserByAccessTokenRow struct {
NamechangedAt sql.NullTime
AuthenticatedAt sql.NullTime
Scopes sql.NullString
+ IsBot bool
}
func (q *Queries) GetUserByAccessToken(ctx context.Context, token string) (GetUserByAccessTokenRow, error) {
@@ -710,6 +711,7 @@ func (q *Queries) GetUserByAccessToken(ctx context.Context, token string) (GetUs
&i.NamechangedAt,
&i.AuthenticatedAt,
&i.Scopes,
+ &i.IsBot,
)
return i, err
}
@@ -752,6 +754,41 @@ func (q *Queries) GetUserByAuth(ctx context.Context, arg GetUserByAuthParams) (G
return i, err
}
+const getUserByID = `-- name: GetUserByID :one
+SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot FROM users WHERE id = ?
+`
+
+type GetUserByIDRow struct {
+ ID string
+ DisplayName string
+ DisplayColor int64
+ CreatedAt sql.NullTime
+ DisabledAt sql.NullTime
+ PreviousNames sql.NullString
+ NamechangedAt sql.NullTime
+ AuthenticatedAt sql.NullTime
+ Scopes sql.NullString
+ IsBot bool
+}
+
+func (q *Queries) GetUserByID(ctx context.Context, id string) (GetUserByIDRow, error) {
+ row := q.db.QueryRowContext(ctx, getUserByID, id)
+ var i GetUserByIDRow
+ err := row.Scan(
+ &i.ID,
+ &i.DisplayName,
+ &i.DisplayColor,
+ &i.CreatedAt,
+ &i.DisabledAt,
+ &i.PreviousNames,
+ &i.NamechangedAt,
+ &i.AuthenticatedAt,
+ &i.Scopes,
+ &i.IsBot,
+ )
+ return i, err
+}
+
const getUserDisplayNameByToken = `-- name: GetUserDisplayNameByToken :one
SELECT display_name FROM users JOIN user_access_tokens ON users.id = user_access_tokens.user_id WHERE token = ? AND users.disabled_at IS NULL
`
@@ -763,6 +800,57 @@ func (q *Queries) GetUserDisplayNameByToken(ctx context.Context, token string) (
return display_name, err
}
+const getUsers = `-- name: GetUsers :many
+SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, authenticated_at, scopes, type = 'API' AS is_bot FROM users ORDER BY created_at DESC
+`
+
+type GetUsersRow struct {
+ ID string
+ DisplayName string
+ DisplayColor int64
+ CreatedAt sql.NullTime
+ DisabledAt sql.NullTime
+ PreviousNames sql.NullString
+ NamechangedAt sql.NullTime
+ AuthenticatedAt sql.NullTime
+ Scopes sql.NullString
+ IsBot bool
+}
+
+func (q *Queries) GetUsers(ctx context.Context) ([]GetUsersRow, error) {
+ rows, err := q.db.QueryContext(ctx, getUsers)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var items []GetUsersRow
+ for rows.Next() {
+ var i GetUsersRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.DisplayName,
+ &i.DisplayColor,
+ &i.CreatedAt,
+ &i.DisabledAt,
+ &i.PreviousNames,
+ &i.NamechangedAt,
+ &i.AuthenticatedAt,
+ &i.Scopes,
+ &i.IsBot,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Close(); err != nil {
+ return nil, err
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const isDisplayNameAvailable = `-- name: IsDisplayNameAvailable :one
SELECT count(*) FROM users WHERE display_name = ? AND ( type='API' OR authenticated_at IS NOT NULL ) AND disabled_at IS NULL
`
diff --git a/docs/plugins.md b/docs/plugins.md
new file mode 100644
index 0000000000..0a6d49bfdc
--- /dev/null
+++ b/docs/plugins.md
@@ -0,0 +1,165 @@
+# Plugin host integration
+
+How Owncast runs plugins and how the plugin system is wired into the server.
+This is a contributor-facing overview of the **host side**; it is not a guide
+to writing plugins.
+
+## What plugins are
+
+A plugin is a sandboxed WebAssembly module (authors write JavaScript/TypeScript
+and compile it to wasm). Owncast loads plugins and runs them in-process via
+[Extism](https://extism.org), which uses [Wazero](https://wazero.io) — a pure-Go
+wasm runtime, so there is no CGo and no external process. A plugin can only do
+what its manifest declares as **permissions**, and it can only reach the host
+through a fixed set of **host functions** Owncast provides.
+
+Plugins are optional infrastructure: if the runtime or a plugin fails to start,
+Owncast logs and continues rather than aborting startup.
+
+## Where the code lives
+
+| Path | Responsibility |
+|---|---|
+| `services/plugins/` | The plugin **runtime** — discovery/enable lifecycle (`manager.go`), event + filter fan-out (`dispatcher.go`), the HTTP handler for `/plugins/<name>/*` (`server.go`), the host functions and their types/permissions (`hostfns.go`), the KV store interface (`kv/`), and the SSE hub (`sse.go`). |
+| `pluginhost/` | The **Owncast integration layer** — builds the runtime's `HostEnv` from Owncast services, starts the manager, and exposes the HTTP handlers. This is the only package that knows about both the runtime and Owncast's internals. |
+
+`services/plugins/` is a **vendored copy** of the upstream plugin SDK's
+`host-runtime/plugin` package (`github.com/owncast/plugin-sdk`). See
+[Keeping the runtime in sync](#keeping-the-runtime-in-sync-with-the-sdk) below —
+this is the most important thing to understand before changing it.
+
+## How a plugin call reaches Owncast
+
+The runtime defines host functions in `services/plugins/hostfns.go`, but those
+functions don't know anything about Owncast. Each one just calls a
+function-pointer field on a `HostEnv` struct, e.g.:
+
+```go
+// services/plugins/hostfns.go — runtime, Owncast-agnostic
+func hostVideoConfigRead(env *HostEnv) extism.HostFunction { /* calls env.VideoConfig() */ }
+
+type HostEnv struct {
+ VideoConfig func() VideoConfig // wired by the embedding host
+ // ...
+}
+```
+
+`pluginhost/pluginhost.go` is where Owncast **fills in** those pointers with
+real services. `New(ctx, Deps)` constructs the `HostEnv` and `wirePluginHostEnv`
+sets every field, grouped into helpers:
+
+```go
+// pluginhost/pluginhost.go — Owncast wiring
+func wireVideoConfigHostFns(env *plugins.HostEnv, deps Deps) {
+ cfg := deps.ConfigRepository
+ env.VideoConfig = func() plugins.VideoConfig {
+ variants := cfg.GetStreamOutputVariants()
+ // map Owncast's models.StreamOutputVariant -> the plugin's StreamVariant
+ // ...
+ }
+ env.WriteVideoConfig = func(pluginName string, u plugins.VideoConfigUpdate) error {
+ // persist via cfg.SetStreamLatencyLevel / SetVideoCodec / SetStreamOutputVariants
+ }
+}
+```
+
+Two layers, two responsibilities:
+
+- **`hostfns.go`** defines the plugin-facing API: the host-function names, the
+ permissions that gate them, and the data **types** plugins receive
+ (`VideoConfig`, `StreamBroadcaster`, …). This must match the SDK.
+- **`pluginhost.go`** is the adapter: it reads Owncast's real state
+ (`ConfigRepository`, `stream.Service`, chat, …) and **maps Owncast's internal
+ `models.*` types into the plugin types**. This is Owncast-specific and is
+ expected to differ from the SDK.
+
+The plugin types are deliberately separate from `models.*`: they're a curated,
+stable contract shared with plugins and the TypeScript SDK, so internal model
+refactors don't silently change what plugins see. The mapping is the price of
+that decoupling, and it lives at the boundary on purpose.
+
+## What's wired
+
+`wirePluginHostEnv` wires these subsystems (each behind its declared permission):
+
+- **Chat send** (`chat.send`) — posts under the plugin's own provisioned bot
+ identity (`newPluginChatbotProvisioner`), plus system/action messages and DMs.
+- **Chat read / moderation** (`chat.history`, `chat.moderate`) — history,
+ connected clients, delete message, kick client.
+- **Server reads** (`server.read`) — stream status, server info, socials,
+ federation, metadata tags, and read-only inbound-broadcast telemetry
+ (`stream.Service.GetBroadcaster()`).
+- **Video config** (`videoconfig.read` / `videoconfig.write`) — read and
+ partially update output variants, codec, and latency via `ConfigRepository`.
+ Writes **persist only**; they take effect on the next stream start (the admin
+ UI already shows this), so the host deliberately does **not** restart a live
+ transcoder.
+- **Users** (`users.read` / `users.moderate`) — list/get users, set enabled,
+ ban IP.
+- **Notifications** (`notifications.send`) — Discord, browser push, fediverse.
+- **Storage** — KV backed by Owncast's datastore (`newDatastoreKVStore`), and
+ `storage.upload` for plugin assets.
+- **HTTP** (`http.serve`, `http.sse`) — `req.authenticated` / `req.user` from
+ Owncast's auth middleware, plus the SSE hub for server-pushed events.
+
+## Events and filters
+
+Owncast and plugins communicate through a shared dispatcher
+(`services/dispatcher`), injected as `Deps.Events`:
+
+- Owncast **publishes** events (chat messages, stream lifecycle, moderation, …)
+ to that dispatcher. `pluginhost` registers a listener
+ (`newPluginEventListener`) that forwards them to plugins' `on_event` handlers.
+- For chat, `pluginhost` registers a **filter** (`newPluginChatFilter`) so
+ plugins' `filterChatMessage` handlers run on inbound messages before they're
+ broadcast (redact, drop, rewrite).
+- Plugins can also **emit** custom events to each other; `env.Emit` is wired to
+ the runtime's live dispatcher after the manager starts.
+
+## Lifecycle, persistence, and HTTP
+
+- **Discovery / enable:** the manager scans `<data>/plugins/` and tracks plugins
+ as *discovered* vs *enabled*. Files are never auto-loaded; an admin enables
+ them. The enabled set persists through `configEnabledStore` (Owncast's
+ datastore, key `plugins.enabled`) rather than a JSON file.
+- **HTTP:** `Host.Handler()` serves `/plugins/<name>/*` (mounted in the chi
+ router). `Host.AdminHandler()` serves the admin API: `GET /api/admin/plugins`,
+ `POST /api/admin/plugins/<name>/{enable,disable,reload}`, and the public
+ `GET /api/plugins/actions`.
+
+## Keeping the runtime in sync with the SDK
+
+`services/plugins/` is a copy of the SDK's runtime. The **implementation** may
+diverge for integration (e.g. Owncast adds a datastore-backed enabled-set store),
+but the **plugin API** — the host-function names, permission identifiers, and
+data-type shapes in `hostfns.go` — must stay identical to the SDK. If it
+drifts, plugins built against the SDK can fail to load or receive malformed data
+(this is exactly how the `videoconfig` functions were once missing here).
+
+`services/plugins/contract_test.go` guards this. It re-derives the API surface
+from this repo's `hostfns.go` and compares it to `services/plugins/plugin-contract.json`
+(a snapshot copied verbatim from the SDK). If they differ, the test fails with
+instructions. It checks **only** the API surface, not the `pluginhost.go`
+wiring, so Owncast-specific adapter code is free to differ.
+
+### Adding or changing a host function
+
+Do it in the SDK first, then bring it here:
+
+1. In the SDK (`github.com/owncast/plugin-sdk`), add the host function + type +
+ permission to `host-runtime/plugin/hostfns.go`, expose it in the JS SDK, and
+ regenerate the snapshot: `UPDATE_CONTRACT=1 go test ./plugin/ -run TestPluginContract`.
+2. Copy the changed runtime files **and** `plugin-contract.json` into
+ `services/plugins/` here.
+3. Wire the new `HostEnv` field to real Owncast data in `pluginhost/pluginhost.go`.
+4. `go test ./services/plugins/... ./pluginhost/...` — the contract test passes
+ once the two `hostfns.go` copies agree.
+
+For the SDK side of this system, see the SDK repo's `docs/ARCHITECTURE.md`.
+
+## Tests
+
+- Unit tests live in `services/plugins/` and `pluginhost/`.
+- End-to-end coverage is in `test/automated/plugins/`: it builds the SDK's
+ example plugins from source, installs them into a running Owncast, and
+ exercises chat, filtering, and HTTP through them.
diff --git a/go.mod b/go.mod
index 652f35ca46..1c159a19b2 100644
--- a/go.mod
+++ b/go.mod
@@ -10,9 +10,11 @@ require (
github.com/aws/aws-sdk-go-v2 v1.41.9
github.com/aws/aws-sdk-go-v2/credentials v1.19.19
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2
+ github.com/extism/go-sdk v1.7.1
github.com/go-chi/chi/v5 v5.2.3
github.com/go-fed/activity v1.0.1-0.20220119073622-b14b50eecad0
github.com/go-fed/httpsig v1.1.0
+ github.com/gobwas/glob v0.2.3
github.com/gorilla/websocket v1.5.3
github.com/grafov/m3u8 v0.12.1
github.com/hashicorp/go-retryablehttp v0.7.8
@@ -60,12 +62,14 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
+ github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect
github.com/ebitengine/purego v0.8.4 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/golang-jwt/jwt/v5 v5.2.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
+ github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect
github.com/klauspost/compress v1.18.5 // indirect
github.com/lestrrat-go/strftime v1.1.1 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
@@ -78,9 +82,12 @@ require (
github.com/prometheus/common v0.66.1 // indirect
github.com/prometheus/procfs v0.20.1 // indirect
github.com/sethvargo/go-retry v0.3.0 // indirect
+ github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
+ github.com/tetratelabs/wazero v1.9.0 // indirect
github.com/tklauser/go-sysconf v0.3.15 // indirect
github.com/tklauser/numcpus v0.10.0 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
+ go.opentelemetry.io/proto/otlp v1.3.1 // indirect
go.uber.org/multierr v1.11.0 // indirect
go.yaml.in/yaml/v2 v2.4.2 // indirect
golang.org/x/sync v0.20.0 // indirect
diff --git a/go.sum b/go.sum
index 9e649b3fc0..7de8ff8089 100644
--- a/go.sum
+++ b/go.sum
@@ -12,108 +12,28 @@ github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kk
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
github.com/apapsch/go-jsonmerge/v2 v2.0.0 h1:axGnT1gRIfimI7gJifB699GoE/oq+F2MU7Dml6nw9rQ=
github.com/apapsch/go-jsonmerge/v2 v2.0.0/go.mod h1:lvDnEdqiQrp0O42VQGgmlKpxL1AP2+08jFMw88y4klk=
-github.com/aws/aws-sdk-go-v2 v1.41.2 h1:LuT2rzqNQsauaGkPK/7813XxcZ3o3yePY0Iy891T2ls=
-github.com/aws/aws-sdk-go-v2 v1.41.2/go.mod h1:IvvlAZQXvTXznUPfRVfryiG1fbzE2NGK6m9u39YQ+S4=
-github.com/aws/aws-sdk-go-v2 v1.41.7 h1:DWpAJt66FmnnaRIOT/8ASTucrvuDPZASqhhLey6tLY8=
-github.com/aws/aws-sdk-go-v2 v1.41.7/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
-github.com/aws/aws-sdk-go-v2 v1.41.8 h1:sRs7nG6/RiEBZ/K5UO2sNw0w40U02Nmz1VtARloTZXk=
-github.com/aws/aws-sdk-go-v2 v1.41.8/go.mod h1:4LAfZOPHNVNQEckOACQx60Y8pSRjIkNZQz1w92xpMJc=
github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4=
github.com/aws/aws-sdk-go-v2 v1.41.9/go.mod h1:+HsoOEX80qAVUitj1A2DhCNTjmb3edVyuDypb6LNEeo=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.5 h1:zWFmPmgw4sveAYi1mRqG+E/g0461cJ5M4bJ8/nc6d3Q=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.5/go.mod h1:nVUlMLVV8ycXSb7mSkcNu9e3v/1TJq2RTlrPwhYWr5c=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10 h1:gx1AwW1Iyk9Z9dD9F4akX5gnN3QZwUB20GGKH/I+Rho=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.10/go.mod h1:qqY157uZoqm5OXq/amuaBJyC9hgBCBQnsaWnPe905GY=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.10 h1:EEhmEUFCE1Yhl7vDhNOI5OCL/iKMdkkYFTRpZXNw7m8=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.10/go.mod h1:RnnlFCAlxQCkN2Q379B67USkBMu1PipEEiibzYN5UTE=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.16 h1:r3RJBuU7X9ibt8RHbMjWE6y60QbKBiII6wSrXnapxSU=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.16/go.mod h1:6cx7zqDENJDbBIIWX6P8s0h6hqHC8Avbjh9Dseo27ug=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.17 h1:gP2nkGsS+KMvF/jfFz2Vv2qiiOqWKyPACSzPsqHgoW8=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.17/go.mod h1:Bsew3S/moG5iT77giPj1q8wb/s0RE5/QfH+ASjYtuQc=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.18 h1:GcXQz2M/0ZvMo0v5DakUqbDBeBM1ZNaivkolEF4Esgw=
-github.com/aws/aws-sdk-go-v2/credentials v1.19.18/go.mod h1:sHJ06tMGcD3ZpmMyJqV+VBsGilhSIZPIN+ZFy5Dg0C4=
github.com/aws/aws-sdk-go-v2/credentials v1.19.19 h1:yuFzSV1U0aRNYCQGVaTY2zW2M/L93pYHnXnrJUphYhU=
github.com/aws/aws-sdk-go-v2/credentials v1.19.19/go.mod h1:7y63L1kGzeoDlJaQ3Z578KrnmfBut96JjvJUzGwR+YE=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18 h1:F43zk1vemYIqPAwhjTjYIz0irU2EY7sOb/F5eJ3HuyM=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.18/go.mod h1:w1jdlZXrGKaJcNoL+Nnrj+k5wlpGXqnNrKoP22HvAug=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23 h1:GpT/TrnBYuE5gan2cZbTtvP+JlHsutdmlV2YfEyNde0=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.23/go.mod h1:xYWD6BS9ywC5bS3sz9Xh04whO/hzK2plt2Zkyrp4JuA=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.24 h1:u6kJU2i0va1AgtJsH3RdWKWqHULlTh7zHwb35Womf74=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.24/go.mod h1:7GY+xLcXOFUpCkNwDReft9qOAVg54A4/AnjHIU7sSAY=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25 h1:Uii3frf9ztec/ABM2/FSH9/z7PLzxfpG8h4RpkUFflQ=
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25/go.mod h1:G6kntsA2GorAxDPbap6xgB2F+amSLUF8GJTi7PUoX44=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18 h1:xCeWVjj0ki0l3nruoyP2slHsGArMxeiiaoPN5QZH6YQ=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.18/go.mod h1:r/eLGuGCBw6l36ZRWiw6PaZwPXb6YOj+i/7MizNl5/k=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23 h1:bpd8vxhlQi2r1hiueOw02f/duEPTMK59Q4QMAoTTtTo=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.23/go.mod h1:15DfR2nw+CRHIk0tqNyifu3G1YdAOy68RftkhMDDwYk=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.24 h1:Xhbcf3KugX6vX7SDyUK205Oicyfg7EGuvoVNyP5L6DM=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.24/go.mod h1:rwDgb2HNOGZsnTHylOUedM7Vnl+bCfnXDqUNPsFWYfk=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25 h1:r1+/l6m+WaUJF9HISEsNOLHSNj5EXYQxK8VX6Cz9NlA=
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25/go.mod h1:cKf+D+NMDK1LndD7BowHbBZPgR9V0/5HubH0PFWvA+c=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.18 h1:eZioDaZGJ0tMM4gzmkNIO2aAoQd+je7Ug7TkvAzlmkU=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.18/go.mod h1:CCXwUKAJdoWr6/NcxZ+zsiPr6oH/Q5aTooRGYieAyj4=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24 h1:OQqn11BtaYv1WLUowvcA30MpzIu8Ti4pcLPIIyoKZrA=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.24/go.mod h1:X5ZJyfwVrWA96GzPmUCWFQaEARPR7gCrpq2E92PJwAE=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.25 h1:54CTMmlJ71Rk2dYvM9qZOob+39wjlVja2zDLxCu69Ew=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.25/go.mod h1:BZaHqxsS9vN1fvV5EfEl0OBLOk5+AajWsMu6MjqnZB4=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26 h1:A1PmWU2zfkIm9EyFlJncFXL4W4phML+h8KjltUsCvNQ=
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26/go.mod h1:dY4MRzXEizrD4hqtpKvWVGPX7QleSGGVY+EBolo1RmM=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5 h1:CeY9LUdur+Dxoeldqoun6y4WtJ3RQtzk0JMP2gfUay0=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.5/go.mod h1:AZLZf2fMaahW5s/wMRciu1sYbdsikT/UHwbUjOdEVTc=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9 h1:FLudkZLt5ci0ozzgkVo8BJGwvqNaZbTWb3UcucAateA=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.9/go.mod h1:w7wZ/s9qK7c8g4al+UyoF1Sp/Z45UwMGcqIzLWVQHWk=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 h1:d5/908OJ4bXg8lyjeMPvXetEKqoDoLi5Owy1zNue3yg=
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10/go.mod h1:a57l7Hwh+FWI+we50g5NPJHYUKeJKfXbc4w8SyXu8Ig=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.9 h1:IJRzQTvdpjHRPItx9gzNcz7Y1F+xqAR+xiy9rr5ZYl8=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.9/go.mod h1:Kzm5e6OmNH8VMkgK9t+ry5jEih4Y8whqs+1hrkxim1I=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15 h1:ieLCO1JxUWuxTZ1cRd0GAaeX7O6cIxnwk7tc1LsQhC4=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.15/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.16 h1:tX68nPDCoX0s2ksM7CipWP0QFw2hGDWwUdxI6+eT9ZU=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.16/go.mod h1:e3IzZvQ3kAWNykvE0Tr0RDZCMFInMvhku3qNpcIQXhM=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.17 h1:Zma31M1f9bbD/bsl6haTxupA0+z72L3l2ujKAH37zuI=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.17/go.mod h1:ZNHrGwBST3tZxBCTKbindx0BEdPN0Jnh7yJ7EVnktUM=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos=
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.18 h1:LTRCYFlnnKFlKsyIQxKhJuDuA3ZkrDQMRYm6rXiHlLY=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.18/go.mod h1:XhwkgGG6bHSd00nO/mexWTcTjgd6PjuvWQMqSn2UaEk=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23 h1:pbrxO/kuIwgEsOPLkaHu0O+m4fNgLU8B3vxQ+72jTPw=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.23/go.mod h1:/CMNUqoj46HpS3MNRDEDIwcgEnrtZlKRaHNaHxIFpNA=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.24 h1:CQW2FTrflfoslYWLf3fv7vG28Q219+v8YJS5QTQb2+Y=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.24/go.mod h1:Xfx13T+u3nH6EEzgl9fBSO6nDRmze1FvnZNYkctQ2zw=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25 h1:dD3dhHNglpd98gs72my22Ndqi1hqQGllFFg1F+twfxg=
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25/go.mod h1:0yAbjPfd64gG7mj85RW+fMEYdfBgCRZw8g/oWcL1pjc=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.18 h1:/A/xDuZAVD2BpsS2fftFRo/NoEKQJ8YTnJDEHBy2Gtg=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.18/go.mod h1:hWe9b4f+djUQGmyiGEeOnZv69dtMSgpDRIvNMvuvzvY=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23 h1:03xatSQO4+AM1lTAbnRg5OK528EUg744nW7F73U8DKw=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.23/go.mod h1:M8l3mwgx5ToK7wot2sBBce/ojzgnPzZXUV445gTSyE8=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.24 h1:yPLVC8Lbsw92eepgdIZCChHRNQek5eAvAz5wS+UIpJE=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.24/go.mod h1:H2h39H1AivHYkozUIUYoVJGMUOvdJ4Lv9DLyUSMAjW8=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978=
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.96.1 h1:giB30dEeoar5bgDnkE0q+z7cFjcHaCjulpmPVmuKR84=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.96.1/go.mod h1:071TH4M3botFLWDbzQLfBR7tXYi7Fs2RsXSiH7nlUlY=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 h1:HwxWTbTrIHm5qY+CAEur0s/figc3qwvLWsNkF4RPToo=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0 h1:etqBTKY581iwLL/H/S2sVgk3C9lAsTJFeXWFDsDcWOU=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.101.0/go.mod h1:L2dcoOgS2VSgbPLvpak2NyUPsO1TBN7M45Z4H7DlRc4=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.102.0 h1:gfPQ6do5PZTCc5n/vZUHz/G8McrNrfERGSO+iHvVbCA=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.102.0/go.mod h1:wO6U9egJtCtsZEHG2AAcFf1kUWDRrH0Iif6K3bVmmdE=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.102.1 h1:vttIo8BQwfnhimKRBZBBF3Y38SAIxif72B/M91m9hDk=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.102.1/go.mod h1:2qjInACJr84m/Tm4XXCcVNpejmbKy9kz7TEa6viQHSk=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
-github.com/aws/smithy-go v1.24.1 h1:VbyeNfmYkWoxMVpGUAbQumkODcYmfMRfZ8yQiH30SK0=
-github.com/aws/smithy-go v1.24.1/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
-github.com/aws/smithy-go v1.25.1 h1:J8ERsGSU7d+aCmdQur5Txg6bVoYelvQJgtZehD12GkI=
-github.com/aws/smithy-go v1.25.1/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aws/smithy-go v1.26.0 h1:9ouqbi+NyKP7fV3Te7UElCwdAb6Y8uk7LGwPE5tVe/s=
github.com/aws/smithy-go v1.26.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk=
@@ -129,8 +49,12 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a h1:UwSIFv5g5lIvbGgtf3tVwC7Ky9rmMFBp0RMs+6f6YqE=
+github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
github.com/ebitengine/purego v0.8.4 h1:CF7LEKg5FFOsASUj0+QwaXf8Ht6TlFxg09+S9wz0omw=
github.com/ebitengine/purego v0.8.4/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
+github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
+github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM=
github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE=
github.com/go-chi/chi/v5 v5.2.3 h1:WQIt9uxdsAbgIYgid+BpYc+liqQZGMHRaUwp0JUcvdE=
@@ -142,6 +66,8 @@ github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-test/deep v1.0.1 h1:UQhStjbkDClarlmv0am7OXXO4/GaPdCGiUiMTvi28sg=
github.com/go-test/deep v1.0.1/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA=
+github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
+github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk=
github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
@@ -165,6 +91,8 @@ github.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB1
github.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=
github.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=
github.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=
+github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca h1:T54Ema1DU8ngI+aef9ZhAhNGQhcRTrWxVeG07F+c/Rw=
+github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
github.com/jellydator/ttlcache/v3 v3.4.0 h1:YS4P125qQS0tNhtL6aeYkheEaB/m8HCqdMMP4mnWdTY=
github.com/jellydator/ttlcache/v3 v3.4.0/go.mod h1:Hw9EgjymziQD3yGsQdf1FqFdpp7YjFMd4Srg5EJlgD4=
github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I=
@@ -209,8 +137,8 @@ github.com/nareix/joy5 v0.0.0-20210317075623-2c912ca30590 h1:PnxRU8L8Y2q82vFC2Qd
github.com/nareix/joy5 v0.0.0-20210317075623-2c912ca30590/go.mod h1:XmAOs6UJXpNXRwKk+KY/nv5kL6xXYXyellk+A1pTlko=
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
-github.com/oapi-codegen/runtime v1.4.0 h1:KLOSFOp7UzkbS7Cs1ms6NBEKYr0WmH2wZG0KKbd2er4=
-github.com/oapi-codegen/runtime v1.4.0/go.mod h1:5sw5fxCDmnOzKNYmkVNF8d34kyUeejJEY8HNT2WaPec=
+github.com/oapi-codegen/nullable v1.1.0 h1:eAh8JVc5430VtYVnq00Hrbpag9PFRGWLjxR1/3KntMs=
+github.com/oapi-codegen/nullable v1.1.0/go.mod h1:KUZ3vUzkmEKY90ksAmit2+5juDIhIZhfDl+0PwOQlFY=
github.com/oapi-codegen/runtime v1.4.1 h1:9nwLoI+KrWxzbBcp0jO/R8uXqbik/HUyCvPeU68Y/qo=
github.com/oapi-codegen/runtime v1.4.1/go.mod h1:GwV7hC2hviaMzj+ITfHVRESK5J2W/GefVwIND/bMGvU=
github.com/oschwald/geoip2-golang v1.13.0 h1:Q44/Ldc703pasJeP5V9+aFSZFmBN7DKHbNsSFzQATJI=
@@ -267,6 +195,10 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569 h1:xzABM9let0HLLqFypcxvLmlvEciCHL7+Lv+4vwZqecI=
github.com/teris-io/shortid v0.0.0-20220617161101-71ec9f2aa569/go.mod h1:2Ly+NIftZN4de9zRmENdYbvPQeaVIYKWpLFStLFEBgI=
+github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
+github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
+github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
+github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
github.com/tklauser/go-sysconf v0.3.15 h1:VE89k0criAymJ/Os65CSn1IXaol+1wrsFHEB8Ol49K4=
github.com/tklauser/go-sysconf v0.3.15/go.mod h1:Dmjwr6tYFIseJw7a3dRLJfsHAMXZ3nEnL/aZY+0IuI4=
github.com/tklauser/numcpus v0.10.0 h1:18njr6LDBk1zuna922MgdjQuJFjrdppsZG60sHGfjso=
@@ -283,6 +215,8 @@ github.com/yuin/goldmark-emoji v1.0.6 h1:QWfF2FYaXwL74tfGOW5izeiZepUDroDJfWubQI9
github.com/yuin/goldmark-emoji v1.0.6/go.mod h1:ukxJDKFpdFb5x0a5HqbdlcKtebh086iJpI31LTKmWuA=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
+go.opentelemetry.io/proto/otlp v1.3.1 h1:TrMUixzpM0yuc/znrFTP9MMRh8trP93mkCiDVeXrui0=
+go.opentelemetry.io/proto/otlp v1.3.1/go.mod h1:0X1WI4de4ZsLrrJNLAQbFeLCm3T7yBkR0XqQ7niQU+8=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
@@ -297,10 +231,6 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
-golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
-golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
-golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
-golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
@@ -308,8 +238,6 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
-golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI=
-golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY=
golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
@@ -323,8 +251,6 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
-golang.org/x/net v0.53.0 h1:d+qAbo5L0orcWAr0a9JweQpjXF19LMXJE8Ey7hwOdUA=
-golang.org/x/net v0.53.0/go.mod h1:JvMuJH7rrdiCfbeHoo3fCQU24Lf5JJwT9W3sJFulfgs=
golang.org/x/net v0.54.0 h1:2zJIZAxAHV/OHCDTCOHAYehQzLfSXuf/5SoL/Dv6w/w=
golang.org/x/net v0.54.0/go.mod h1:Sj4oj8jK6XmHpBZU/zWHw3BV3abl4Kvi+Ut7cQcY+cQ=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@@ -351,10 +277,6 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
-golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
-golang.org/x/sys v0.44.0 h1:ildZl3J4uzeKP07r2F++Op7E9B29JRUy+a27EibtBTQ=
-golang.org/x/sys v0.44.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
@@ -366,8 +288,8 @@ golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
-golang.org/x/term v0.42.0 h1:UiKe+zDFmJobeJ5ggPwOshJIVt6/Ft0rcfrXZDLWAWY=
-golang.org/x/term v0.42.0/go.mod h1:Dq/D+snpsbazcBG5+F9Q1n2rXV8Ma+71xEjTRufARgY=
+golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
+golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
@@ -377,8 +299,6 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
-golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
-golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
diff --git a/main.go b/main.go
index 75d432b174..5db151319f 100644
--- a/main.go
+++ b/main.go
@@ -3,6 +3,7 @@ package main
import (
"context"
"flag"
+ "net/http"
"os"
"strconv"
"time"
@@ -21,6 +22,8 @@ import (
"github.com/owncast/owncast/config"
"github.com/owncast/owncast/metrics"
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/pluginhost"
"github.com/owncast/owncast/services/activitypub"
"github.com/owncast/owncast/services/activitypub/apmodels"
apcrypto "github.com/owncast/owncast/services/activitypub/crypto"
@@ -29,6 +32,7 @@ import (
"github.com/owncast/owncast/services/cache"
"github.com/owncast/owncast/services/chat"
"github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/services/rtmp"
"github.com/owncast/owncast/services/stream"
"github.com/owncast/owncast/services/webhooks"
@@ -209,6 +213,12 @@ func main() {
Config: cfg,
})
+ // Shared in-process event dispatcher. Constructed before its producers
+ // and consumers so they all receive it via Deps (no post-construction
+ // wiring): webhooks publishes events to it, chat runs inbound messages
+ // through its filter chain, and the plugin host subscribes.
+ eventDispatcher := dispatcher.New()
+
// Stage 5: cycle-pair services. webhooks + chat both want
// streamSvc.GetStatus, but streamSvc consumes them in turn. Build
// them with a nil GetStatus and rewire in stage 7.
@@ -217,6 +227,7 @@ func main() {
Followers: followersRepository,
ConfigRepository: configRepository,
WebhookRepository: webhookRepository,
+ Events: eventDispatcher,
})
chatSvc := chat.New(chat.Deps{
@@ -227,6 +238,7 @@ func main() {
AuthRepository: authRepository,
ChatMessageRepository: chatMessageRepository,
UserRepository: userRepository,
+ Events: eventDispatcher,
})
// Stage 6: cycle-pair consumers. activitypub + stream sit on top of
@@ -277,6 +289,34 @@ func main() {
})
go metricsSvc.Start()
+ // Plugin host. Optional infrastructure: a failure here disables plugins
+ // but must not abort startup. Constructs the WASM plugin runtime, wires
+ // its host functions to the services above, and exposes the
+ // /plugins/<name>/* HTTP handler mounted by the router below.
+ var pluginContentHandler http.Handler
+ var pluginAdminHandler http.Handler
+ pluginHostInstance, err := pluginhost.New(ctx, pluginhost.Deps{
+ Datastore: dataStore,
+ Chat: chatSvc,
+ Stream: streamSvc,
+ Activitypub: apSvc,
+ Events: eventDispatcher,
+ ConfigRepository: configRepository,
+ UserRepository: userRepository,
+ AuthRepository: authRepository,
+ NotificationsRepository: notificationsRepository,
+ ChatMessageRepository: chatMessageRepository,
+ RequireAdminAuth: mw.RequireAdminAuth,
+ IsAdminRequest: mw.IsAdminRequest,
+ })
+ if err != nil {
+ log.Errorln("plugin host failed to start; plugins disabled:", err)
+ } else {
+ pluginContentHandler = pluginHostInstance.Handler()
+ pluginAdminHandler = pluginHostInstance.AdminHandler()
+ defer pluginHostInstance.Stop(ctx)
+ }
+
// Stage 9: HTTP handler set. *Handlers is the dispatcher the router
// binds methods on; the sub-handlers (admin, fediverse, indieauth,
// moderation) hold their own narrower deps.
@@ -322,6 +362,19 @@ func main() {
UserRepository: userRepository,
})
+ var pluginActions func() []models.ExternalAction
+ var pluginCSSContent func() []byte
+ var pluginJSContent func() []byte
+ var pluginPageContent func() []byte
+ var pluginTabs func() []models.PluginTab
+ if pluginHostInstance != nil {
+ pluginActions = pluginHostInstance.Actions
+ pluginCSSContent = pluginHostInstance.StylesContent
+ pluginJSContent = pluginHostInstance.ScriptsContent
+ pluginPageContent = pluginHostInstance.PageContent
+ pluginTabs = pluginHostInstance.Tabs
+ }
+
h := handlers.NewHandlers(handlers.Deps{
Cache: cacheContainer,
Stream: streamSvc,
@@ -341,10 +394,15 @@ func main() {
NotificationsRepository: notificationsRepository,
APBuilder: apBuilder,
Config: cfg,
+ PluginActions: pluginActions,
+ PluginCSSContent: pluginCSSContent,
+ PluginJSContent: pluginJSContent,
+ PluginPageContent: pluginPageContent,
+ PluginTabs: pluginTabs,
})
// Stage 10: serve. Blocks until shutdown.
- if err := router.Start(cfg, *enableVerboseLogging, h, mw, apSvc.Controllers()); err != nil {
+ if err := router.Start(cfg, *enableVerboseLogging, h, mw, apSvc.Controllers(), pluginContentHandler, pluginAdminHandler); err != nil {
log.Fatalln("failed to start/run the router", err)
}
}
diff --git a/models/pluginTab.go b/models/pluginTab.go
new file mode 100644
index 0000000000..8c4fda6453
--- /dev/null
+++ b/models/pluginTab.go
@@ -0,0 +1,13 @@
+package models
+
+// PluginTab is one viewer-page tab a plugin contributes via
+// manifest.tabs. Slug identifies the source plugin (used as the React
+// key on the frontend so unmount/remount only fires when a plugin
+// goes away); Title is the label shown in the tab bar; HTML is the
+// inlined body of the tab's content file. The host emits this list
+// as `pluginTabs` on /api/config.
+type PluginTab struct {
+ Slug string `json:"slug"`
+ Title string `json:"title"`
+ HTML string `json:"html"`
+}
diff --git a/persistence/userrepository/userrepository.go b/persistence/userrepository/userrepository.go
index ed108043fc..325371c78b 100644
--- a/persistence/userrepository/userrepository.go
+++ b/persistence/userrepository/userrepository.go
@@ -27,6 +27,7 @@ type UserRepository interface {
CreateAnonymousUser(displayName string) (*models.User, string, error)
DeleteExternalAPIUser(token string) error
GetDisabledUsers() []*models.User
+ GetUsers() []*models.User
GetExternalAPIUser() ([]models.ExternalAPIUser, error)
GetExternalAPIUserForAccessTokenAndScope(token string, scope string) (*models.ExternalAPIUser, error)
GetModeratorUsers() []*models.User
@@ -208,40 +209,55 @@ func (r *SqlUserRepository) SetEnabled(userID string, enabled bool) error {
return tx.Commit()
}
-// GetUserByToken will return a user by an access token.
-func (r *SqlUserRepository) GetUserByToken(token string) *models.User {
- u, err := r.datastore.GetQueries().GetUserByAccessToken(context.Background(), token)
- if err != nil {
- return nil
+// userFromColumns builds a *models.User from the column set shared by the
+// sqlc user lookups (GetUserByAccessToken, GetUserByID, GetUsers). IsBot is
+// derived in SQL (users.type = 'API') so callers don't second-guess it.
+func userFromColumns(
+ id, displayName string,
+ displayColor int64,
+ createdAt, disabledAt sql.NullTime,
+ previousNames sql.NullString,
+ namechangedAt, authenticatedAt sql.NullTime,
+ scopes sql.NullString,
+ isBot bool,
+) *models.User {
+ var scopeSlice []string
+ if scopes.Valid {
+ scopeSlice = strings.Split(scopes.String, ",")
}
- var scopes []string
- if u.Scopes.Valid {
- scopes = strings.Split(u.Scopes.String, ",")
+ var disabled *time.Time
+ if disabledAt.Valid {
+ disabled = &disabledAt.Time
}
- var disabledAt *time.Time
- if u.DisabledAt.Valid {
- disabledAt = &u.DisabledAt.Time
+ var authAt *time.Time
+ if authenticatedAt.Valid {
+ authAt = &authenticatedAt.Time
}
- var authenticatedAt *time.Time
- if u.AuthenticatedAt.Valid {
- authenticatedAt = &u.AuthenticatedAt.Time
+ return &models.User{
+ ID: id,
+ DisplayName: displayName,
+ DisplayColor: int(displayColor),
+ CreatedAt: createdAt.Time,
+ DisabledAt: disabled,
+ PreviousNames: strings.Split(previousNames.String, ","),
+ NameChangedAt: &namechangedAt.Time,
+ AuthenticatedAt: authAt,
+ Authenticated: authAt != nil,
+ Scopes: scopeSlice,
+ IsBot: isBot,
}
+}
- return &models.User{
- ID: u.ID,
- DisplayName: u.DisplayName,
- DisplayColor: int(u.DisplayColor),
- CreatedAt: u.CreatedAt.Time,
- DisabledAt: disabledAt,
- PreviousNames: strings.Split(u.PreviousNames.String, ","),
- NameChangedAt: &u.NamechangedAt.Time,
- AuthenticatedAt: authenticatedAt,
- Authenticated: authenticatedAt != nil,
- Scopes: scopes,
+// GetUserByToken will return a user by an access token.
+func (r *SqlUserRepository) GetUserByToken(token string) *models.User {
+ u, err := r.datastore.GetQueries().GetUserByAccessToken(context.Background(), token)
+ if err != nil {
+ return nil
}
+ return userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, u.IsBot)
}
// SetAccessTokenToOwner will reassign an access token to be owned by a
@@ -367,16 +383,11 @@ func (r *SqlUserRepository) setScopesOnUser(userID string, scopes []string) erro
// GetUserByID will return a user by a user ID.
func (r *SqlUserRepository) GetUserByID(id string) *models.User {
- r.datastore.DbLock.Lock()
- defer r.datastore.DbLock.Unlock()
-
- query := "SELECT id, display_name, display_color, created_at, disabled_at, previous_names, namechanged_at, scopes FROM users WHERE id = ?"
- row := r.datastore.DB.QueryRow(query, id)
- if row == nil {
- log.Errorln(row)
+ u, err := r.datastore.GetQueries().GetUserByID(context.Background(), id)
+ if err != nil {
return nil
}
- return r.getUserFromRow(row)
+ return userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, u.IsBot)
}
// GetDisabledUsers will return back all the currently disabled users that are not API users.
@@ -399,6 +410,21 @@ func (r *SqlUserRepository) GetDisabledUsers() []*models.User {
return users
}
+// GetUsers will return all users, most-recently-created first.
+func (r *SqlUserRepository) GetUsers() []*models.User {
+ rows, err := r.datastore.GetQueries().GetUsers(context.Background())
+ if err != nil {
+ log.Errorln(err)
+ return nil
+ }
+
+ users := make([]*models.User, 0, len(rows))
+ for _, u := range rows {
+ users = append(users, userFromColumns(u.ID, u.DisplayName, u.DisplayColor, u.CreatedAt, u.DisabledAt, u.PreviousNames, u.NamechangedAt, u.AuthenticatedAt, u.Scopes, u.IsBot))
+ }
+ return users
+}
+
// GetModeratorUsers will return a list of users with moderator access.
func (r *SqlUserRepository) GetModeratorUsers() []*models.User {
query := `SELECT id, display_name, scopes, display_color, created_at, disabled_at, previous_names, namechanged_at FROM (
@@ -471,37 +497,6 @@ func (r *SqlUserRepository) getUsersFromRows(rows *sql.Rows) []*models.User {
return users
}
-func (r *SqlUserRepository) getUserFromRow(row *sql.Row) *models.User {
- var id string
- var displayName string
- var displayColor int
- var createdAt time.Time
- var disabledAt *time.Time
- var previousUsernames string
- var userNameChangedAt *time.Time
- var scopesString *string
-
- if err := row.Scan(&id, &displayName, &displayColor, &createdAt, &disabledAt, &previousUsernames, &userNameChangedAt, &scopesString); err != nil {
- return nil
- }
-
- var scopes []string
- if scopesString != nil {
- scopes = strings.Split(*scopesString, ",")
- }
-
- return &models.User{
- ID: id,
- DisplayName: displayName,
- DisplayColor: displayColor,
- CreatedAt: createdAt,
- DisabledAt: disabledAt,
- PreviousNames: strings.Split(previousUsernames, ","),
- NameChangedAt: userNameChangedAt,
- Scopes: scopes,
- }
-}
-
// InsertExternalAPIUser will add a new API user to the database.
func (r *SqlUserRepository) InsertExternalAPIUser(token string, name string, color int, scopes []string) error {
log.Traceln("Adding new API user")
diff --git a/pluginhost/dispatcher_test.go b/pluginhost/dispatcher_test.go
new file mode 100644
index 0000000000..02081fe3a2
--- /dev/null
+++ b/pluginhost/dispatcher_test.go
@@ -0,0 +1,103 @@
+package pluginhost
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/services/chat/events"
+ "github.com/owncast/owncast/services/dispatcher"
+ "github.com/owncast/owncast/services/plugins"
+ "github.com/owncast/owncast/services/webhooks"
+)
+
+// The host's chat filter, registered on a real dispatcher, passes messages
+// through unchanged when no plugins are loaded — and the dispatcher delivers
+// the inbound message to it. Exercises the real chat -> dispatcher -> plugin
+// filter seam (full rewriting needs a wasm plugin, covered separately).
+func TestPluginChatFilter_PassesThroughWithNoPlugins(t *testing.T) {
+ d := dispatcher.New()
+ d.AddFilter(newPluginChatFilter(plugins.NewDispatcher(nil)))
+
+ msg := &events.UserMessageEvent{}
+ msg.Body = "hello"
+
+ allow := d.ApplyFilters(context.Background(), dispatcher.Event{Type: models.MessageSent, Payload: msg})
+ if !allow {
+ t.Fatal("message should pass with no plugins loaded")
+ }
+ if msg.Body != "hello" {
+ t.Errorf("body changed unexpectedly: %q", msg.Body)
+ }
+}
+
+// The chat filter only acts on chat-message payloads; anything else passes.
+func TestPluginChatFilter_IgnoresNonChatPayload(t *testing.T) {
+ d := dispatcher.New()
+ d.AddFilter(newPluginChatFilter(plugins.NewDispatcher(nil)))
+
+ if !d.ApplyFilters(context.Background(), dispatcher.Event{Type: "other", Payload: "not a chat message"}) {
+ t.Fatal("non-chat payloads must pass through unchanged")
+ }
+}
+
+// The host's event listener, registered on a real dispatcher, handles both a
+// translatable webhook event and an unrelated payload without panicking. (The
+// plugin notify side fans out to loaded plugins, which needs a wasm plugin to
+// observe; here we verify the dispatcher -> listener wiring and payload guard.)
+func TestPluginEventListener_HandlesPublishedEvents(t *testing.T) {
+ d := dispatcher.New()
+ d.AddListener(newPluginEventListener(plugins.NewDispatcher(nil)))
+
+ // Unrelated payload type: ignored.
+ d.Publish(context.Background(), dispatcher.Event{Type: "x", Payload: 42})
+
+ // A real chat-message webhook event: translated and dispatched to (no) plugins.
+ d.Publish(context.Background(), dispatcher.Event{
+ Type: models.MessageSent,
+ Payload: webhooks.WebhookEvent{
+ Type: models.MessageSent,
+ EventData: &webhooks.WebhookChatMessage{ID: "m1", Body: "hi", User: &models.User{DisplayName: "alice"}},
+ },
+ })
+}
+
+// The dispatcher applies a filter chain to an inbound chat message exactly as
+// chat relies on: filters mutate the message body in place and can drop it.
+// This stands in for a plugin's filterChatMessage (which needs wasm to run)
+// and proves the mechanism the chat hot path depends on.
+func TestDispatcherChatFilterContract(t *testing.T) {
+ d := dispatcher.New()
+ // Rewrite: uppercase the body.
+ d.AddFilter(func(_ context.Context, e dispatcher.Event) bool {
+ if m, ok := e.Payload.(*events.UserMessageEvent); ok {
+ m.Body = strings.ToUpper(m.Body)
+ }
+ return true
+ })
+ // Drop: reject anything containing "SPAM" (post-uppercase).
+ d.AddFilter(func(_ context.Context, e dispatcher.Event) bool {
+ m, ok := e.Payload.(*events.UserMessageEvent)
+ return !ok || !strings.Contains(m.Body, "SPAM")
+ })
+
+ t.Run("rewrites body in place", func(t *testing.T) {
+ msg := &events.UserMessageEvent{}
+ msg.Body = "hello"
+ if !d.ApplyFilters(context.Background(), dispatcher.Event{Payload: msg}) {
+ t.Fatal("expected message to pass")
+ }
+ if msg.Body != "HELLO" {
+ t.Errorf("body = %q, want HELLO", msg.Body)
+ }
+ })
+
+ t.Run("drops a rejected message", func(t *testing.T) {
+ msg := &events.UserMessageEvent{}
+ msg.Body = "spam"
+ if d.ApplyFilters(context.Background(), dispatcher.Event{Payload: msg}) {
+ t.Fatal("expected message to be dropped")
+ }
+ })
+}
diff --git a/pluginhost/pluginchatbot.go b/pluginhost/pluginchatbot.go
new file mode 100644
index 0000000000..913af8992b
--- /dev/null
+++ b/pluginhost/pluginchatbot.go
@@ -0,0 +1,95 @@
+package pluginhost
+
+import (
+ "fmt"
+ "sync"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/persistence/userrepository"
+ "github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/utils"
+)
+
+// pluginChatbotKeyPrefix namespaces the datastore keys that map a plugin
+// to its chatbot user's access token. The key suffix is the plugin's
+// slug so the same chatbot user (and message history) sticks with the
+// plugin across reinstalls; the display-name half of the manifest can
+// change without losing the bot's identity.
+const pluginChatbotKeyPrefix = "plugins.chatbot."
+
+// pluginChatbotProvisioner resolves the persistent chatbot user for a plugin,
+// creating it on first use. The plugin->token mapping is stored in the
+// datastore so the chatbot keeps the same identity (and chat history
+// attribution) across restarts. The chatbot is a type="API" user, so it loads
+// with IsBot=true and the DisplayName the manifest declared at creation
+// time (Manifest.Bot.DisplayName, or Manifest.Name when Bot.DisplayName is
+// empty: ChatDisplayName() picks).
+//
+// Chatbot users are intentionally not removed when a plugin is disabled or
+// uninstalled, so past messages keep their authorship.
+type pluginChatbotProvisioner struct {
+ users userrepository.UserRepository
+ datastore *datastore.Datastore
+
+ mu sync.Mutex
+ cache map[string]*models.User
+}
+
+func newPluginChatbotProvisioner(users userrepository.UserRepository, ds *datastore.Datastore) *pluginChatbotProvisioner {
+ return &pluginChatbotProvisioner{
+ users: users,
+ datastore: ds,
+ cache: make(map[string]*models.User),
+ }
+}
+
+// chatbotUser returns the plugin's chatbot user, creating and persisting one
+// the first time it's needed. Two identity inputs: pluginSlug is the
+// stable cache + datastore key (so the bot identity survives manifest
+// edits to display name), and displayName is what chat viewers see for
+// the bot. displayName is only used on first provisioning; once the
+// user record exists, later calls return the existing record and
+// don't rename it.
+func (p *pluginChatbotProvisioner) chatbotUser(pluginSlug, displayName string) (*models.User, error) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+
+ if user, ok := p.cache[pluginSlug]; ok {
+ return user, nil
+ }
+
+ key := pluginChatbotKeyPrefix + pluginSlug
+ if token, err := p.datastore.GetString(key); err == nil && token != "" {
+ if user := p.users.GetUserByToken(token); user != nil {
+ p.cache[pluginSlug] = user
+ return user, nil
+ }
+ }
+
+ // New chatbot user: pick a sensible display name. Falling back to
+ // the slug here is defensive: the host fn closure already resolves
+ // ChatDisplayName(), so displayName should never be empty in
+ // practice.
+ chosenName := displayName
+ if chosenName == "" {
+ chosenName = pluginSlug
+ }
+
+ token, err := utils.GenerateAccessToken()
+ if err != nil {
+ return nil, err
+ }
+ if err := p.users.InsertExternalAPIUser(token, chosenName, 0, nil); err != nil {
+ return nil, err
+ }
+ if err := p.datastore.SetString(key, token); err != nil {
+ return nil, err
+ }
+
+ user := p.users.GetUserByToken(token)
+ if user == nil {
+ return nil, fmt.Errorf("plugin chatbot user %q not found after creation", pluginSlug)
+ }
+ p.cache[pluginSlug] = user
+ return user, nil
+}
diff --git a/pluginhost/pluginchatbot_test.go b/pluginhost/pluginchatbot_test.go
new file mode 100644
index 0000000000..3ce39786fa
--- /dev/null
+++ b/pluginhost/pluginchatbot_test.go
@@ -0,0 +1,58 @@
+package pluginhost
+
+import (
+ "testing"
+
+ "github.com/owncast/owncast/persistence/userrepository"
+)
+
+func TestPluginChatbotProvisioner(t *testing.T) {
+ ds := newTestDatastore(t)
+ users := userrepository.New(ds)
+ prov := newPluginChatbotProvisioner(users, ds)
+
+ chatbot, err := prov.chatbotUser("uptime-bot", "Uptime Bot")
+ if err != nil {
+ t.Fatalf("chatbotUser: %v", err)
+ }
+ if chatbot == nil {
+ t.Fatal("expected a chatbot user")
+ }
+ if chatbot.DisplayName != "Uptime Bot" {
+ t.Errorf("display name = %q want %q", chatbot.DisplayName, "Uptime Bot")
+ }
+ if !chatbot.IsBot {
+ t.Error("chatbot user should have IsBot=true")
+ }
+
+ // Second call returns the same identity (cache). Passing a different
+ // display name on subsequent calls is a no-op: the user record was
+ // created with the first display name.
+ again, err := prov.chatbotUser("uptime-bot", "Uptime Bot")
+ if err != nil {
+ t.Fatalf("chatbotUser (cached): %v", err)
+ }
+ if again.ID != chatbot.ID {
+ t.Errorf("cached lookup returned a different user: %q vs %q", again.ID, chatbot.ID)
+ }
+
+ // A different plugin slug gets a distinct identity.
+ other, err := prov.chatbotUser("welcome-bot", "Welcome Bot")
+ if err != nil {
+ t.Fatalf("chatbotUser other: %v", err)
+ }
+ if other.ID == chatbot.ID {
+ t.Error("different plugins must get different chatbot users")
+ }
+
+ // A fresh provisioner (cold cache) resolves the same persisted identity,
+ // so the chatbot survives restarts.
+ prov2 := newPluginChatbotProvisioner(users, ds)
+ resolved, err := prov2.chatbotUser("uptime-bot", "Uptime Bot")
+ if err != nil {
+ t.Fatalf("chatbotUser after restart: %v", err)
+ }
+ if resolved.ID != chatbot.ID {
+ t.Errorf("persisted chatbot identity not reused: %q vs %q", resolved.ID, chatbot.ID)
+ }
+}
diff --git a/pluginhost/pluginevents.go b/pluginhost/pluginevents.go
new file mode 100644
index 0000000000..1e1be5f3e6
--- /dev/null
+++ b/pluginhost/pluginevents.go
@@ -0,0 +1,320 @@
+package pluginhost
+
+import (
+ "context"
+ "time"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/services/chat/events"
+ "github.com/owncast/owncast/services/dispatcher"
+ "github.com/owncast/owncast/services/plugins"
+ "github.com/owncast/owncast/services/webhooks"
+)
+
+// Plugin-facing event payload shapes. These mirror the plugin SDK's
+// TypeScript interfaces (ChatMessage, ChatUser, …) so a plugin's typed
+// handlers receive exactly the documented JSON.
+
+type pluginChatMessage struct {
+ ID string `json:"id"`
+ User string `json:"user"`
+ Body string `json:"body"`
+ Timestamp string `json:"timestamp"`
+}
+
+type pluginChatUser struct {
+ ID string `json:"id"`
+ DisplayName string `json:"displayName"`
+ IsBot bool `json:"isBot,omitempty"`
+ IsAuthenticated bool `json:"isAuthenticated,omitempty"`
+ Scopes []string `json:"scopes,omitempty"`
+}
+
+type pluginChatUserRename struct {
+ User pluginChatUser `json:"user"`
+ PreviousName string `json:"previousName"`
+}
+
+type pluginChatMessageModeration struct {
+ MessageID string `json:"messageId"`
+ Visible bool `json:"visible"`
+ Moderator *pluginChatUser `json:"moderator,omitempty"`
+}
+
+type pluginStreamLifecycleEvent struct {
+ StartedAt string `json:"startedAt,omitempty"`
+ StoppedAt string `json:"stoppedAt,omitempty"`
+ Title string `json:"title,omitempty"`
+ Summary string `json:"summary,omitempty"`
+}
+
+type pluginStreamTitleChange struct {
+ From string `json:"from"`
+ To string `json:"to"`
+}
+
+// pluginEvent is one translated event ready to dispatch: a plugin event type
+// and its SDK-shaped payload.
+type pluginEvent struct {
+ eventType string
+ payload any
+}
+
+// newPluginChatFilter returns a dispatcher.Filter that runs the plugin
+// filterChatMessage chain on an inbound chat message, rewriting the message
+// body in place and reporting whether it survived. Plugin errors are
+// fail-open inside the plugin dispatcher, so a broken filter never blocks chat.
+func newPluginChatFilter(pluginDispatcher *plugins.Dispatcher) dispatcher.Filter {
+ return func(ctx context.Context, e dispatcher.Event) bool {
+ msg, ok := e.Payload.(*events.UserMessageEvent)
+ if !ok {
+ return true // not a chat message we filter; let it pass
+ }
+ user := ""
+ if msg.User != nil {
+ user = msg.User.DisplayName
+ }
+ // Carry the timestamp through so filter plugins that gate on it
+ // (slow-mode, rate-limit, etc.) can compare elapsed time. Nano-
+ // precision matters: extism-js's Date.now() returns a frozen
+ // WASI-default value, so plugins can't get wall-clock time on
+ // their own — msg.timestamp is the only source of real-time
+ // resolution they have. RFC3339 second-precision is too coarse
+ // for sub-second rate limits.
+ timestamp := ""
+ if !msg.Timestamp.IsZero() {
+ timestamp = msg.Timestamp.UTC().Format(time.RFC3339Nano)
+ }
+ final, allowed, _ := pluginDispatcher.Filter(ctx, plugins.EventChatMessageReceived, pluginChatMessage{ID: msg.ID, User: user, Body: msg.Body, Timestamp: timestamp})
+ if !allowed {
+ return false
+ }
+ // A plugin holding only chat.filter must not be able to
+ // inject raw HTML into the broadcast. When the filter
+ // returned a modified body, run it back through
+ // RenderAndSanitize so any new <script>/<iframe>/etc the
+ // plugin tried to introduce gets stripped by the same
+ // bluemonday policy userMessageSent already applied to the
+ // original message. Skip the round-trip when nothing
+ // changed so a no-op filter doesn't re-render the body.
+ //
+ // Assign the result to msg.Body directly rather than via
+ // RenderAndSanitizeMessageBody, because that helper resets
+ // RawBody from Body first and would clobber whatever we
+ // stored.
+ next := filteredBody(final, msg.Body)
+ if next != msg.Body {
+ msg.Body = events.RenderAndSanitize(next)
+ }
+ return true
+ }
+}
+
+// filteredBody extracts the body from a filter chain's result. The result is
+// the original pluginChatMessage when no plugin modified it, or a decoded JSON
+// object when one did; fallback covers any unexpected shape.
+func filteredBody(final any, fallback string) string {
+ switch v := final.(type) {
+ case pluginChatMessage:
+ return v.Body
+ case map[string]interface{}:
+ if body, ok := v["body"].(string); ok {
+ return body
+ }
+ }
+ return fallback
+}
+
+// newPluginEventListener returns a dispatcher.Listener that translates each
+// Owncast event (carried as a webhooks.WebhookEvent) into the plugin SDK's
+// payload shape and dispatches it to subscribed plugins. Dispatch runs on its
+// own goroutine so a slow plugin never blocks the event source (the chat hot
+// path).
+func newPluginEventListener(pluginDispatcher *plugins.Dispatcher) dispatcher.Listener {
+ return func(ctx context.Context, e dispatcher.Event) {
+ webhookEvent, ok := e.Payload.(webhooks.WebhookEvent)
+ if !ok {
+ return
+ }
+ // Notifications are fire-and-forget: detach from the publisher's
+ // context so the dispatch isn't cancelled when the publishing call
+ // returns. Per-plugin timeouts still apply inside Dispatch.
+ ctx = context.WithoutCancel(ctx)
+ for _, pe := range translateWebhookEvent(webhookEvent) {
+ // Notify-only on purpose: the inbound-chat path already ran
+ // the filter chain through newPluginChatFilter before the
+ // event was broadcast. Calling Dispatch (filter + notify)
+ // here would re-run every plugin's on_filter on a message
+ // that already survived once, doubling work and double-
+ // triggering rate-limit logic (slow-mode, etc.).
+ go pluginDispatcher.Notify(ctx, pe.eventType, pe.payload)
+ }
+ }
+}
+
+// translateWebhookEvent maps an Owncast webhook event onto the plugin events
+// it should produce (zero, one, or — for a multi-message moderation toggle —
+// several). It's pure so the mapping can be tested without a live dispatcher.
+//
+// Only genuine user chat messages (models.MessageSent) become
+// chat.message.received — system messages and actions (including a plugin's
+// own chat.send output) are intentionally excluded, so plugins don't react to
+// their own posts.
+func translateWebhookEvent(evt webhooks.WebhookEvent) []pluginEvent {
+ switch evt.Type {
+ case models.MessageSent, models.UserJoined, models.UserParted, models.UserNameChanged, models.VisibiltyToggled:
+ return translateChatEvent(evt)
+ case models.StreamStarted, models.StreamStopped, models.StreamTitleUpdated:
+ return translateStreamEvent(evt)
+ }
+ return nil
+}
+
+func translateChatEvent(evt webhooks.WebhookEvent) []pluginEvent {
+ switch evt.Type {
+ case models.MessageSent:
+ return chatMessageEvent(evt)
+
+ case models.UserJoined:
+ data, ok := evt.EventData.(*webhooks.WebhookUserJoinedEventData)
+ if !ok {
+ return nil
+ }
+ return []pluginEvent{{plugins.EventChatUserJoined, toPluginChatUser(data.User)}}
+
+ case models.UserParted:
+ data, ok := evt.EventData.(*webhooks.WebhookUserPartEventData)
+ if !ok {
+ return nil
+ }
+ return []pluginEvent{{plugins.EventChatUserParted, toPluginChatUser(data.User)}}
+
+ case models.UserNameChanged:
+ data, ok := evt.EventData.(*webhooks.WebhookNameChangeEventData)
+ if !ok {
+ return nil
+ }
+ user := toPluginChatUser(data.User)
+ user.DisplayName = data.NewName
+ return []pluginEvent{{plugins.EventChatUserRenamed, pluginChatUserRename{
+ User: user,
+ PreviousName: previousName(data.User),
+ }}}
+
+ case models.VisibiltyToggled:
+ data, ok := evt.EventData.(*webhooks.WebhookVisibilityToggleEventData)
+ if !ok {
+ return nil
+ }
+ var moderator *pluginChatUser
+ if data.User != nil {
+ m := toPluginChatUser(data.User)
+ moderator = &m
+ }
+ // Owncast toggles a set of IDs at once; the SDK payload is
+ // per-message, so fan one event out per affected message.
+ out := make([]pluginEvent, 0, len(data.MessageIDs))
+ for _, id := range data.MessageIDs {
+ out = append(out, pluginEvent{plugins.EventChatMessageModerated, pluginChatMessageModeration{
+ MessageID: id,
+ Visible: data.Visible,
+ Moderator: moderator,
+ }})
+ }
+ return out
+ }
+ return nil
+}
+
+func chatMessageEvent(evt webhooks.WebhookEvent) []pluginEvent {
+ data, ok := evt.EventData.(*webhooks.WebhookChatMessage)
+ if !ok {
+ return nil
+ }
+ // Don't deliver messages authored by a bot (e.g. another plugin's
+ // chat.send, posted under its bot identity) back to plugins. This prevents
+ // echo loops: a plugin that replies to chat would otherwise be re-triggered
+ // by its own reply, forever.
+ if data.User != nil && data.User.IsBot {
+ return nil
+ }
+ // Use RawBody (what the user actually typed), not Body (the HTML-rendered
+ // form like `<p>!broadcaster</p>`). Plugins doing command matching or
+ // content analysis want the raw text; the chat client handles rendering.
+ msg := pluginChatMessage{ID: data.ID, Body: data.RawBody, Timestamp: formatTimePtr(data.Timestamp)}
+ if data.User != nil {
+ msg.User = data.User.DisplayName
+ }
+ return []pluginEvent{{plugins.EventChatMessageReceived, msg}}
+}
+
+func translateStreamEvent(evt webhooks.WebhookEvent) []pluginEvent {
+ switch evt.Type {
+ case models.StreamStarted:
+ return []pluginEvent{{plugins.EventStreamStarted, streamLifecycleEvent(evt.EventData, true)}}
+
+ case models.StreamStopped:
+ return []pluginEvent{{plugins.EventStreamStopped, streamLifecycleEvent(evt.EventData, false)}}
+
+ case models.StreamTitleUpdated:
+ m, ok := evt.EventData.(map[string]interface{})
+ if !ok {
+ return nil
+ }
+ to, _ := m["streamTitle"].(string)
+ // Owncast's title-changed event carries only the new title.
+ return []pluginEvent{{plugins.EventStreamTitleChanged, pluginStreamTitleChange{To: to}}}
+ }
+ return nil
+}
+
+func toPluginChatUser(u *models.User) pluginChatUser {
+ if u == nil {
+ return pluginChatUser{}
+ }
+ return pluginChatUser{
+ ID: u.ID,
+ DisplayName: u.DisplayName,
+ IsBot: u.IsBot,
+ IsAuthenticated: u.Authenticated,
+ Scopes: u.Scopes,
+ }
+}
+
+// previousName returns the user's most recent prior display name, the closest
+// available value for a rename's "from". Empty when there's no history.
+func previousName(u *models.User) string {
+ if u == nil || len(u.PreviousNames) == 0 {
+ return ""
+ }
+ return u.PreviousNames[len(u.PreviousNames)-1]
+}
+
+func formatTimePtr(t *time.Time) string {
+ if t == nil {
+ return ""
+ }
+ return t.UTC().Format(time.RFC3339Nano)
+}
+
+// streamLifecycleEvent builds a stream.started/stopped payload from the
+// map-shaped EventData the webhooks stream builder emits.
+func streamLifecycleEvent(data interface{}, started bool) pluginStreamLifecycleEvent {
+ out := pluginStreamLifecycleEvent{}
+ m, ok := data.(map[string]interface{})
+ if !ok {
+ return out
+ }
+ out.Title, _ = m["streamTitle"].(string)
+ out.Summary, _ = m["summary"].(string)
+ timestamp := ""
+ if t, ok := m["timestamp"].(time.Time); ok {
+ timestamp = t.UTC().Format(time.RFC3339Nano)
+ }
+ if started {
+ out.StartedAt = timestamp
+ } else {
+ out.StoppedAt = timestamp
+ }
+ return out
+}
diff --git a/pluginhost/pluginevents_test.go b/pluginhost/pluginevents_test.go
new file mode 100644
index 0000000000..cb2cffdf38
--- /dev/null
+++ b/pluginhost/pluginevents_test.go
@@ -0,0 +1,203 @@
+package pluginhost
+
+import (
+ "testing"
+ "time"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/services/plugins"
+ "github.com/owncast/owncast/services/webhooks"
+)
+
+func TestTranslateWebhookEvent_ChatMessageOnlyForUserMessages(t *testing.T) {
+ ts := time.Date(2026, 5, 27, 12, 0, 0, 0, time.UTC)
+ evt := webhooks.WebhookEvent{
+ Type: models.MessageSent,
+ EventData: &webhooks.WebhookChatMessage{
+ ID: "m1",
+ // Body is the HTML-rendered form the chat client sees; RawBody is
+ // what plugins receive. Set both, to mirror the production payload.
+ Body: "<p>hello</p>",
+ RawBody: "hello",
+ Timestamp: &ts,
+ User: &models.User{ID: "u1", DisplayName: "alice"},
+ },
+ }
+ out := translateWebhookEvent(evt)
+ if len(out) != 1 {
+ t.Fatalf("expected 1 event, got %d", len(out))
+ }
+ if out[0].eventType != plugins.EventChatMessageReceived {
+ t.Errorf("eventType = %q want %q", out[0].eventType, plugins.EventChatMessageReceived)
+ }
+ msg, ok := out[0].payload.(pluginChatMessage)
+ if !ok {
+ t.Fatalf("payload type = %T want pluginChatMessage", out[0].payload)
+ }
+ if msg.ID != "m1" || msg.Body != "hello" || msg.User != "alice" {
+ t.Errorf("unexpected message payload: %+v", msg)
+ }
+ if msg.Timestamp != "2026-05-27T12:00:00Z" {
+ t.Errorf("timestamp = %q", msg.Timestamp)
+ }
+}
+
+func TestTranslateWebhookEvent_SkipsBotAuthoredMessages(t *testing.T) {
+ // A message a plugin posted (under its bot identity) must not be delivered
+ // back to plugins, or chat-reacting plugins would echo-loop forever.
+ evt := webhooks.WebhookEvent{
+ Type: models.MessageSent,
+ EventData: &webhooks.WebhookChatMessage{
+ ID: "b1",
+ Body: "echo",
+ User: &models.User{DisplayName: "echo-bot", IsBot: true},
+ },
+ }
+ if out := translateWebhookEvent(evt); len(out) != 0 {
+ t.Errorf("bot-authored message should produce no plugin events, got %d", len(out))
+ }
+}
+
+func TestTranslateWebhookEvent_SystemMessageProducesNothing(t *testing.T) {
+ // A plugin's own chat.send posts a system message; it must not become a
+ // chat.message.received event (no feedback loop).
+ evt := webhooks.WebhookEvent{
+ Type: models.SystemMessageSent,
+ EventData: &webhooks.WebhookChatMessage{ID: "s1", Body: "system"},
+ }
+ if out := translateWebhookEvent(evt); len(out) != 0 {
+ t.Errorf("system message should produce no plugin events, got %d", len(out))
+ }
+}
+
+func TestTranslateWebhookEvent_UserJoined(t *testing.T) {
+ evt := webhooks.WebhookEvent{
+ Type: models.UserJoined,
+ EventData: &webhooks.WebhookUserJoinedEventData{
+ User: &models.User{ID: "u1", DisplayName: "bob", IsBot: true, Scopes: []string{"MODERATOR"}},
+ },
+ }
+ out := translateWebhookEvent(evt)
+ if len(out) != 1 || out[0].eventType != plugins.EventChatUserJoined {
+ t.Fatalf("unexpected events: %+v", out)
+ }
+ user, ok := out[0].payload.(pluginChatUser)
+ if !ok {
+ t.Fatalf("payload type = %T want pluginChatUser", out[0].payload)
+ }
+ if user.ID != "u1" || user.DisplayName != "bob" || !user.IsBot || len(user.Scopes) != 1 {
+ t.Errorf("unexpected user payload: %+v", user)
+ }
+}
+
+func TestTranslateWebhookEvent_RenameUsesPreviousName(t *testing.T) {
+ evt := webhooks.WebhookEvent{
+ Type: models.UserNameChanged,
+ EventData: &webhooks.WebhookNameChangeEventData{
+ NewName: "newname",
+ User: &models.User{ID: "u1", DisplayName: "oldname", PreviousNames: []string{"first", "oldname"}},
+ },
+ }
+ out := translateWebhookEvent(evt)
+ if len(out) != 1 || out[0].eventType != plugins.EventChatUserRenamed {
+ t.Fatalf("unexpected events: %+v", out)
+ }
+ rename, ok := out[0].payload.(pluginChatUserRename)
+ if !ok {
+ t.Fatalf("payload type = %T want pluginChatUserRename", out[0].payload)
+ }
+ if rename.User.DisplayName != "newname" {
+ t.Errorf("renamed user display name = %q want newname", rename.User.DisplayName)
+ }
+ if rename.PreviousName != "oldname" {
+ t.Errorf("previousName = %q want oldname", rename.PreviousName)
+ }
+}
+
+func TestTranslateWebhookEvent_VisibilityFansOutPerMessage(t *testing.T) {
+ evt := webhooks.WebhookEvent{
+ Type: models.VisibiltyToggled,
+ EventData: &webhooks.WebhookVisibilityToggleEventData{
+ Visible: false,
+ MessageIDs: []string{"a", "b", "c"},
+ },
+ }
+ out := translateWebhookEvent(evt)
+ if len(out) != 3 {
+ t.Fatalf("expected 3 moderation events, got %d", len(out))
+ }
+ for i, id := range []string{"a", "b", "c"} {
+ mod, ok := out[i].payload.(pluginChatMessageModeration)
+ if !ok {
+ t.Fatalf("payload[%d] type = %T", i, out[i].payload)
+ }
+ if mod.MessageID != id || mod.Visible {
+ t.Errorf("event %d = %+v want id %q visible false", i, mod, id)
+ }
+ }
+}
+
+func TestTranslateWebhookEvent_StreamLifecycle(t *testing.T) {
+ ts := time.Date(2026, 5, 27, 9, 30, 0, 0, time.UTC)
+ started := webhooks.WebhookEvent{
+ Type: models.StreamStarted,
+ EventData: map[string]interface{}{
+ "streamTitle": "Live",
+ "summary": "a show",
+ "timestamp": ts,
+ },
+ }
+ out := translateWebhookEvent(started)
+ if len(out) != 1 || out[0].eventType != plugins.EventStreamStarted {
+ t.Fatalf("unexpected events: %+v", out)
+ }
+ life, ok := out[0].payload.(pluginStreamLifecycleEvent)
+ if !ok {
+ t.Fatalf("payload type = %T", out[0].payload)
+ }
+ if life.StartedAt != "2026-05-27T09:30:00Z" || life.Title != "Live" || life.Summary != "a show" {
+ t.Errorf("unexpected lifecycle payload: %+v", life)
+ }
+ if life.StoppedAt != "" {
+ t.Errorf("started event should not set stoppedAt: %+v", life)
+ }
+}
+
+func TestFilteredBody(t *testing.T) {
+ cases := []struct {
+ name string
+ final any
+ fallback string
+ want string
+ }{
+ {"unchanged passes through the struct", pluginChatMessage{Body: "hello"}, "hello", "hello"},
+ {"modified comes back as a decoded map", map[string]interface{}{"body": "HELLO"}, "hello", "HELLO"},
+ {"map without body uses fallback", map[string]interface{}{"id": "x"}, "hello", "hello"},
+ {"unexpected shape uses fallback", 42, "hello", "hello"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := filteredBody(tc.final, tc.fallback); got != tc.want {
+ t.Errorf("filteredBody = %q want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestTranslateWebhookEvent_TitleChange(t *testing.T) {
+ evt := webhooks.WebhookEvent{
+ Type: models.StreamTitleUpdated,
+ EventData: map[string]interface{}{"streamTitle": "New Title"},
+ }
+ out := translateWebhookEvent(evt)
+ if len(out) != 1 || out[0].eventType != plugins.EventStreamTitleChanged {
+ t.Fatalf("unexpected events: %+v", out)
+ }
+ change, ok := out[0].payload.(pluginStreamTitleChange)
+ if !ok {
+ t.Fatalf("payload type = %T", out[0].payload)
+ }
+ if change.To != "New Title" {
+ t.Errorf("title change To = %q want New Title", change.To)
+ }
+}
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.go
new file mode 100644
index 0000000000..3e3282a076
--- /dev/null
+++ b/pluginhost/pluginhost.go
@@ -0,0 +1,1046 @@
+package pluginhost
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "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"
+)
+
+// pluginsEnabledConfigKey is the datastore key under which the set of
+// admin-enabled plugin names is persisted.
+const pluginsEnabledConfigKey = "plugins.enabled"
+
+// jsonErrorKey is the JSON map key used to surface a single human-readable
+// error string back to the admin UI in error responses.
+const jsonErrorKey = "error"
+
+// 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
+ 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
+}
+
+// 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"
+
+// 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) {
+ p.manager.Stop(ctx)
+}
+
+// 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 {
+ return p.readManifestAssets(
+ func(m *plugins.Manifest) []string { return m.Styles },
+ "/* plugin: %s — %s */\n",
+ )
+}
+
+// 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.
+func (p *Host) ScriptsContent() []byte {
+ return p.readManifestAssets(
+ func(m *plugins.Manifest) []string { return m.Scripts },
+ "// plugin: %s — %s\n",
+ )
+}
+
+// PageContent returns the concatenated HTML bytes contributed by
+// every loaded plugin's manifest.extraPageContent file, 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() []byte {
+ return p.readManifestAssets(
+ func(m *plugins.Manifest) []string {
+ if m.ExtraPageContent == "" {
+ return nil
+ }
+ return []string{m.ExtraPageContent}
+ },
+ "<!-- plugin: %s — %s -->\n",
+ )
+}
+
+// Tabs returns every viewer-page tab contributed by loaded plugins
+// via manifest.tabs. Each tab's content file is read from the
+// plugin's assets/ directory once per call; tabs whose file can't be
+// read 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() []models.PluginTab {
+ if p == nil || p.manager == nil {
+ return nil
+ }
+ var out []models.PluginTab
+ for _, l := range p.manager.Snapshot() {
+ if l == nil || l.Manifest == nil || l.AssetsFS == nil {
+ continue
+ }
+ slug := l.Manifest.Slug
+ pluginPrefix := "/plugins/" + slug + "/"
+ for _, tab := range l.Manifest.Tabs {
+ 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", slug, tab.Title, relPath, err)
+ continue
+ }
+ out = append(out, models.PluginTab{
+ Slug: slug,
+ Title: tab.Title,
+ HTML: string(data),
+ })
+ }
+ }
+ 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)
+ }
+
+ env := &plugins.HostEnv{KV: newDatastoreKVStore(deps.Datastore)}
+ wirePluginHostEnv(env, deps)
+
+ 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))
+
+ server := plugins.NewLiveServer(manager.Snapshot)
+ server.SSE = sseHub
+ server.IsAuthenticated = env.IsAuthenticated
+ server.RequireAdmin = deps.RequireAdminAuth
+ server.GetRequestUser = env.GetRequestUser
+
+ return &Host{
+ manager: manager,
+ server: server,
+ sse: sseHub,
+ configRepository: deps.ConfigRepository,
+ requireAdminAuth: deps.RequireAdminAuth,
+ kv: env.KV,
+ }, 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 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{"status": "ok", "slug": slug, "action": action})
+}
+
+// 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.Install(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))
+}
+
+// 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) {
+ 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)
+ wireNotificationHostFns(env, deps)
+ wireRequestHostFns(env, deps)
+}
+
+// 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(),
+ 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,
+ AudioBitrate: v.AudioBitrate,
+ IsPassthrough: v.IsVideoPassthrough,
+ })
+ }
+ return out
+ }
+
+ env.WriteVideoConfig = func(pluginName string, u plugins.VideoConfigUpdate) error {
+ 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 {
+ variants := make([]models.StreamOutputVariant, 0, len(u.Variants))
+ for _, v := range u.Variants {
+ variants = append(variants, models.StreamOutputVariant{
+ ScaledWidth: v.Width,
+ ScaledHeight: v.Height,
+ Framerate: v.Framerate,
+ VideoBitrate: v.VideoBitrate,
+ AudioBitrate: v.AudioBitrate,
+ IsVideoPassthrough: v.IsPassthrough,
+ })
+ }
+ 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),
+ }
+ if msg.User != nil {
+ hm.User = msg.User.DisplayName
+ }
+ 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) {
+ if err := chatSvc.SetMessagesVisibility([]string{messageID}, false); err != nil {
+ log.Errorln("plugin", pluginName, "delete message:", err)
+ }
+ }
+
+ env.KickClient = func(pluginName string, clientID uint64) {
+ if c, ok := chatSvc.FindClientByID(uint(clientID)); ok {
+ chatSvc.DisconnectClients([]*chat.Client{c})
+ }
+ }
+}
+
+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
+ }
+
+ 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) {
+ if err := users.SetEnabled(userID, enabled); err != nil {
+ log.Errorln("plugin", pluginName, "set user enabled:", err)
+ return
+ }
+ if !enabled {
+ if clients, err := chatSvc.GetClientsForUser(userID); err == nil {
+ chatSvc.DisconnectClients(clients)
+ }
+ }
+ }
+
+ env.BanIP = func(pluginName, ip string) {
+ if err := deps.AuthRepository.BanIPAddress(ip, "banned by plugin "+pluginName); err != nil {
+ log.Errorln("plugin", pluginName, "ban ip:", err)
+ }
+ }
+}
+
+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 := r.URL.Query().Get("accessToken")
+ 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.
+func toHostUser(u *models.User) plugins.HostUser {
+ hu := plugins.HostUser{
+ ID: u.ID,
+ DisplayName: u.DisplayName,
+ PreviousNames: u.PreviousNames,
+ Scopes: u.Scopes,
+ IsBot: u.IsBot,
+ IsAuthenticated: u.Authenticated,
+ CreatedAt: u.CreatedAt.UTC().Format(time.RFC3339Nano),
+ }
+ if u.DisabledAt != nil {
+ hu.DisabledAt = u.DisabledAt.UTC().Format(time.RFC3339Nano)
+ }
+ 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
+}
diff --git a/pluginhost/pluginkv.go b/pluginhost/pluginkv.go
new file mode 100644
index 0000000000..a0b80bae6c
--- /dev/null
+++ b/pluginhost/pluginkv.go
@@ -0,0 +1,62 @@
+package pluginhost
+
+import (
+ "database/sql"
+ "errors"
+
+ "github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/plugins/kv"
+)
+
+// pluginKVKeyPrefix namespaces plugin KV entries within Owncast's shared
+// config datastore so they don't collide with server config keys.
+const pluginKVKeyPrefix = "plugins.kv."
+
+// datastoreKVStore implements the plugin runtime's kv.Store on top of
+// Owncast's native key/value datastore. Each plugin's keys live under
+// "plugins.kv.<plugin>." so plugins can neither read nor overwrite each
+// other's data.
+type datastoreKVStore struct {
+ datastore *datastore.Datastore
+}
+
+func newDatastoreKVStore(ds *datastore.Datastore) *datastoreKVStore {
+ return &datastoreKVStore{datastore: ds}
+}
+
+func (s *datastoreKVStore) Namespace(plugin string) kv.Namespace {
+ return &datastoreKVNamespace{datastore: s.datastore, prefix: pluginKVKeyPrefix + plugin + "."}
+}
+
+// Close is a no-op: the datastore's lifecycle is owned by Owncast, not the
+// plugin host.
+func (s *datastoreKVStore) Close() error { return nil }
+
+type datastoreKVNamespace struct {
+ datastore *datastore.Datastore
+ prefix string
+}
+
+func (n *datastoreKVNamespace) Get(key string) ([]byte, error) {
+ value, err := n.datastore.GetString(n.prefix + key)
+ if err != nil {
+ // Only a missing key (or unset on a fresh install) reads as
+ // nil, matching the kv.Store contract. Anything else is a
+ // real persistence error (decode/type/database) that the
+ // plugin needs to see; silently translating to nil would
+ // look like data loss to the plugin.
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ return nil, err
+ }
+ return []byte(value), nil
+}
+
+func (n *datastoreKVNamespace) Set(key string, value []byte) error {
+ return n.datastore.SetString(n.prefix+key, string(value))
+}
+
+func (n *datastoreKVNamespace) Delete(key string) error {
+ return n.datastore.Delete(n.prefix + key)
+}
diff --git a/pluginhost/pluginkv_test.go b/pluginhost/pluginkv_test.go
new file mode 100644
index 0000000000..3fb0e5ffce
--- /dev/null
+++ b/pluginhost/pluginkv_test.go
@@ -0,0 +1,92 @@
+package pluginhost
+
+import (
+ "bytes"
+ "path/filepath"
+ "testing"
+
+ "github.com/owncast/owncast/services/datastore"
+)
+
+func newTestDatastore(t *testing.T) *datastore.Datastore {
+ t.Helper()
+ ds, err := datastore.SetupPersistence(filepath.Join(t.TempDir(), "test.db"), t.TempDir())
+ if err != nil {
+ t.Fatalf("setup datastore: %v", err)
+ }
+ return ds
+}
+
+func TestDatastoreKVStore(t *testing.T) {
+ store := newDatastoreKVStore(newTestDatastore(t))
+ ns := store.Namespace("p1")
+
+ t.Run("get missing returns nil", func(t *testing.T) {
+ got, err := ns.Get("missing")
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if got != nil {
+ t.Errorf("expected nil, got %q", got)
+ }
+ })
+
+ t.Run("set then get round-trip", func(t *testing.T) {
+ if err := ns.Set("k", []byte("hello")); err != nil {
+ t.Fatalf("set: %v", err)
+ }
+ got, err := ns.Get("k")
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if !bytes.Equal(got, []byte("hello")) {
+ t.Errorf("got %q want %q", got, "hello")
+ }
+ })
+
+ t.Run("overwrite", func(t *testing.T) {
+ _ = ns.Set("ow", []byte("first"))
+ _ = ns.Set("ow", []byte("second"))
+ got, _ := ns.Get("ow")
+ if !bytes.Equal(got, []byte("second")) {
+ t.Errorf("got %q want %q", got, "second")
+ }
+ })
+
+ t.Run("binary value round-trip", func(t *testing.T) {
+ blob := []byte{0x00, 0xff, 0x10, 'a', 0x00, 0x7f}
+ if err := ns.Set("bin", blob); err != nil {
+ t.Fatalf("set: %v", err)
+ }
+ got, _ := ns.Get("bin")
+ if !bytes.Equal(got, blob) {
+ t.Errorf("binary value corrupted: got %v want %v", got, blob)
+ }
+ })
+
+ t.Run("delete then get returns nil", func(t *testing.T) {
+ _ = ns.Set("del", []byte("v"))
+ if err := ns.Delete("del"); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ got, _ := ns.Get("del")
+ if got != nil {
+ t.Errorf("after delete got %q want nil", got)
+ }
+ })
+
+ t.Run("namespaces are isolated", func(t *testing.T) {
+ a := store.Namespace("plugin-a")
+ b := store.Namespace("plugin-b")
+ _ = a.Set("shared", []byte("a-value"))
+ _ = b.Set("shared", []byte("b-value"))
+ gotA, _ := a.Get("shared")
+ gotB, _ := b.Get("shared")
+ if !bytes.Equal(gotA, []byte("a-value")) {
+ t.Errorf("plugin-a got %q want %q", gotA, "a-value")
+ }
+ if !bytes.Equal(gotB, []byte("b-value")) {
+ t.Errorf("plugin-b got %q want %q", gotB, "b-value")
+ }
+ })
+}
diff --git a/pluginhost/registry.go b/pluginhost/registry.go
new file mode 100644
index 0000000000..c20d3e1dd0
--- /dev/null
+++ b/pluginhost/registry.go
@@ -0,0 +1,236 @@
+package pluginhost
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+ "time"
+
+ log "github.com/sirupsen/logrus"
+
+ "github.com/owncast/owncast/services/plugins"
+)
+
+// Registry browse / install. By default the host points at the
+// public catalog (DefaultPluginRegistry); operators can override
+// with OWNCAST_PLUGIN_REGISTRY (set it to a private/self-hosted
+// directory's API base, e.g. http://localhost:8088 for a local
+// directory backend during development). The host appends bare
+// resource paths to that base (`/plugins`, `/plugins/<slug>`), so
+// the env var must point at whatever URL the registry's API answers
+// from; the platform's /api/* rewrite or its absence is the
+// operator's concern, not the host's.
+
+// registryHTTPClient has a tight timeout because a slow or unreachable
+// registry shouldn't hang the admin UI. The full install flow
+// (list-fetch + .ocpkg download) needs to complete within a few
+// requests' worth of time.
+var registryHTTPClient = &http.Client{Timeout: 30 * time.Second}
+
+// DefaultPluginRegistry is the URL the Owncast host points at when
+// OWNCAST_PLUGIN_REGISTRY isn't set. It's the public catalog the
+// Owncast project runs, so every Owncast instance gets a working
+// Browse tab out of the box without per-deployment configuration.
+// Operators who want a different catalog (a private/self-hosted
+// directory, a staging instance, etc.) set the env var to override.
+const DefaultPluginRegistry = "https://owncast.directory/api"
+
+// registryBase reads the operator's configured registry URL from
+// OWNCAST_PLUGIN_REGISTRY, falling back to the public catalog when
+// unset. Trims any trailing slash so callers can safely concatenate
+// path segments.
+func registryBase() string {
+ v := os.Getenv("OWNCAST_PLUGIN_REGISTRY")
+ if v == "" {
+ v = DefaultPluginRegistry
+ }
+ return strings.TrimRight(v, "/")
+}
+
+// handleRegistryRoute dispatches /api/admin/plugin-registry/<action>
+// to the matching handler. Strips an optional trailing slash so the
+// admin frontend's slash-canonicalizing redirect doesn't 404 against
+// our routes. Registered as a prefix-handler in AdminHandler.
+func (p *Host) handleRegistryRoute(w http.ResponseWriter, r *http.Request) {
+ rest := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/admin/plugin-registry/"), "/")
+ switch rest {
+ case "list":
+ p.handleRegistryList(w, r)
+ case "install":
+ p.handleRegistryInstall(w, r)
+ default:
+ http.NotFound(w, r)
+ }
+}
+
+// handleRegistryList proxies the registry's public plugin listing.
+// Used by the admin's "Browse plugins" view so the frontend talks
+// only to its own origin (no extra CORS plumbing for the registry).
+func (p *Host) handleRegistryList(w http.ResponseWriter, _ *http.Request) {
+ base := registryBase()
+ if base == "" {
+ writeJSONResponse(w, http.StatusOK, []any{})
+ return
+ }
+ resp, err := registryHTTPClient.Get(base + "/plugins")
+ if err != nil {
+ writeJSONResponse(w, http.StatusBadGateway, map[string]string{jsonErrorKey: "registry fetch: " + err.Error()})
+ return
+ }
+ defer resp.Body.Close()
+ body, _ := io.ReadAll(io.LimitReader(resp.Body, 5<<20)) // 5 MiB cap on registry response
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(resp.StatusCode)
+ _, _ = w.Write(body) //nolint:gosec // G705 false positive: bytes are JSON from a trusted upstream
+}
+
+// registryInstallRequest is the body shape posted by the admin UI.
+// Slug identifies the plugin in the registry (the registry's primary
+// key); version pins a specific release.
+type registryInstallRequest struct {
+ Slug string `json:"slug"`
+ Version string `json:"version"`
+}
+
+// handleRegistryInstall fetches a plugin from the configured registry,
+// verifies its SHA256 against the registry's metadata, and installs
+// it via the existing Manager.Install path. Same trust prompts and
+// re-approval flow as a manual upload.
+func (p *Host) handleRegistryInstall(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ var req registryInstallRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: "invalid request body"})
+ return
+ }
+ if req.Slug == "" || req.Version == "" {
+ writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: "slug and version required"})
+ return
+ }
+
+ base := registryBase()
+ if base == "" {
+ writeJSONResponse(w, http.StatusServiceUnavailable, map[string]string{jsonErrorKey: "plugin registry is not configured on this server"})
+ return
+ }
+
+ // Fetch the plugin detail from the registry to learn the canonical
+ // downloadURL + sha256 for the requested version. We don't trust
+ // any URL the admin frontend might have constructed locally; the
+ // registry's metadata is the source of truth.
+ detail, err := fetchRegistryDetail(base, req.Slug)
+ if err != nil {
+ writeJSONResponse(w, http.StatusBadGateway, map[string]string{jsonErrorKey: err.Error()})
+ return
+ }
+ match := findVersion(detail, req.Version)
+ if match == nil {
+ writeJSONResponse(w, http.StatusNotFound, map[string]string{jsonErrorKey: fmt.Sprintf("version %q not found in registry for plugin %q", req.Version, req.Slug)})
+ return
+ }
+
+ // Pull the bytes from the registry's CDN. LimitReader caps how
+ // much we'll read so a hostile registry can't fill memory.
+ pkgBytes, err := downloadOcpkg(match.DownloadURL)
+ if err != nil {
+ writeJSONResponse(w, http.StatusBadGateway, map[string]string{jsonErrorKey: err.Error()})
+ return
+ }
+
+ // SHA256 over the downloaded bytes must match the registry's
+ // stated digest. This is integrity, not authenticity: it tells us
+ // the CDN delivered what the registry says is the package, not
+ // that the registry itself is trustworthy.
+ sum := sha256.Sum256(pkgBytes)
+ if hex.EncodeToString(sum[:]) != match.SHA256 {
+ writeJSONResponse(w, http.StatusBadGateway, map[string]string{jsonErrorKey: "downloaded package hash does not match registry metadata"})
+ return
+ }
+
+ entry, err := p.manager.Install(r.Context(), pkgBytes)
+ if err != nil {
+ writeJSONResponse(w, http.StatusBadRequest, map[string]string{jsonErrorKey: err.Error()})
+ return
+ }
+ log.Infof("plugin %q [%s] v%s installed from registry by admin", entry.DisplayName, entry.Slug, entry.Version)
+ writeJSONResponse(w, http.StatusOK, entry)
+}
+
+// registryVersion is the subset of the registry's per-version payload
+// we need to install a package.
+type registryVersion struct {
+ Version string `json:"version"`
+ SHA256 string `json:"sha256"`
+ DownloadURL string `json:"downloadURL"`
+}
+
+type registryDetail struct {
+ Slug string `json:"slug"`
+ Versions []registryVersion `json:"versions"`
+}
+
+// fetchRegistryDetail GETs the registry's detail endpoint for a
+// single plugin and decodes only the fields we use for install. The
+// registry can return extra fields without breaking us. Slug is the
+// registry's primary identifier, matching the URL segment used here.
+func fetchRegistryDetail(base, slug string) (*registryDetail, error) {
+ resp, err := registryHTTPClient.Get(base + "/plugins/" + url.PathEscape(slug))
+ if err != nil {
+ return nil, fmt.Errorf("registry fetch: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode == http.StatusNotFound {
+ return nil, fmt.Errorf("plugin %q not in registry", slug)
+ }
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("registry returned %s", resp.Status)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 5<<20))
+ if err != nil {
+ return nil, fmt.Errorf("read registry response: %w", err)
+ }
+ var detail registryDetail
+ if err := json.Unmarshal(body, &detail); err != nil {
+ return nil, fmt.Errorf("decode registry response: %w", err)
+ }
+ return &detail, nil
+}
+
+func findVersion(detail *registryDetail, version string) *registryVersion {
+ for i := range detail.Versions {
+ if detail.Versions[i].Version == version {
+ return &detail.Versions[i]
+ }
+ }
+ return nil
+}
+
+// downloadOcpkg streams the .ocpkg URL the registry pointed at into a
+// byte slice, capped at MaxUploadBytes (same limit as direct uploads).
+func downloadOcpkg(downloadURL string) ([]byte, error) {
+ resp, err := registryHTTPClient.Get(downloadURL)
+ if err != nil {
+ return nil, fmt.Errorf("download .ocpkg: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, fmt.Errorf("download .ocpkg: status %s", resp.Status)
+ }
+ pkgBytes, err := io.ReadAll(io.LimitReader(resp.Body, plugins.MaxUploadBytes+1))
+ if err != nil {
+ return nil, fmt.Errorf("read .ocpkg body: %w", err)
+ }
+ if int64(len(pkgBytes)) > plugins.MaxUploadBytes {
+ return nil, fmt.Errorf("downloaded .ocpkg exceeds %d-byte cap", plugins.MaxUploadBytes)
+ }
+ return pkgBytes, nil
+}
diff --git a/pluginhost/registry_test.go b/pluginhost/registry_test.go
new file mode 100644
index 0000000000..ed44a4f442
--- /dev/null
+++ b/pluginhost/registry_test.go
@@ -0,0 +1,365 @@
+package pluginhost
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/owncast/owncast/services/plugins"
+)
+
+// Tests covering /api/admin/plugin-registry/* — the in-Owncast browse
+// + install endpoints. Each test that needs the install path uses a
+// real Manager pointing at a temp plugins directory and a fake
+// registry HTTP server (httptest.NewServer) so the SHA256 + download
+// + Manager.Install chain runs end to end against trusted bytes.
+
+// findExampleWasm returns the bundled hello-world example wasm path,
+// skipping if it isn't built. The example lives in the sibling
+// owncast-plugin-sdk repo since the SDK split.
+func findExampleWasm(t *testing.T) string {
+ t.Helper()
+ _, thisFile, _, _ := runtime.Caller(0)
+ repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..")
+ candidates := []string{
+ filepath.Join(repoRoot, "owncast-plugin-sdk", "examples", "js", "hello-world", "hello-world.wasm"),
+ filepath.Join(repoRoot, "..", "owncast-plugin-sdk", "examples", "js", "hello-world", "hello-world.wasm"),
+ }
+ for _, c := range candidates {
+ if _, err := os.Stat(c); err == nil {
+ return c
+ }
+ }
+ t.Skipf("example wasm not built in any of %v; run npm run build in examples/js/hello-world first", candidates)
+ return ""
+}
+
+// buildPackageBytes assembles an in-memory .ocpkg with the given
+// manifest + wasm + optional assets. Mirrors the host's accepted
+// shape (plugin.manifest.json + plugin.wasm at the zip root).
+func buildPackageBytes(t *testing.T, manifest []byte, wasm []byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ mw, err := zw.Create("plugin.manifest.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := mw.Write(manifest); err != nil {
+ t.Fatal(err)
+ }
+ ww, err := zw.Create("plugin.wasm")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := ww.Write(wasm); err != nil {
+ t.Fatal(err)
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func helloWorldManifest() []byte {
+ return []byte(`{
+ "api": "1",
+ "name": "hello-world",
+ "version": "0.1.0",
+ "description": "hello-world plugin for registry tests",
+ "permissions": []
+ }`)
+}
+
+// newTestHost spins up a Manager rooted at a fresh temp dir and wraps
+// it in a Host with only the fields the registry handlers touch. The
+// rest of the Host's deps (kv, sse, etc.) stay nil because the
+// browse/install paths don't reach them.
+func newTestHost(t *testing.T) *Host {
+ t.Helper()
+ dir := t.TempDir()
+ mgr := plugins.NewManager(dir, &plugins.HostEnv{})
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatalf("manager start: %v", err)
+ }
+ t.Cleanup(func() { mgr.Stop(context.Background()) })
+ return &Host{manager: mgr}
+}
+
+// withRegistryEnv sets OWNCAST_PLUGIN_REGISTRY for the duration of a
+// test and restores it afterward. Hides the t.Setenv ceremony so
+// individual tests stay short.
+func withRegistryEnv(t *testing.T, url string) {
+ t.Helper()
+ t.Setenv("OWNCAST_PLUGIN_REGISTRY", url)
+}
+
+// --- pure unit tests ---
+
+func TestFindVersion(t *testing.T) {
+ detail := &registryDetail{
+ Slug: "demo",
+ Versions: []registryVersion{
+ {Version: "0.2.0", SHA256: "b", DownloadURL: "u-b"},
+ {Version: "0.1.0", SHA256: "a", DownloadURL: "u-a"},
+ },
+ }
+ if v := findVersion(detail, "0.1.0"); v == nil || v.SHA256 != "a" {
+ t.Errorf("findVersion(0.1.0) = %v, want SHA=a", v)
+ }
+ if v := findVersion(detail, "0.2.0"); v == nil || v.SHA256 != "b" {
+ t.Errorf("findVersion(0.2.0) = %v, want SHA=b", v)
+ }
+ if v := findVersion(detail, "9.9.9"); v != nil {
+ t.Errorf("findVersion of unknown version should be nil, got %v", v)
+ }
+}
+
+func TestRegistryBase_TrimsTrailingSlash(t *testing.T) {
+ t.Setenv("OWNCAST_PLUGIN_REGISTRY", "https://owncast.directory/")
+ if got := registryBase(); got != "https://owncast.directory" {
+ t.Errorf("registryBase trimmed = %q, want %q", got, "https://owncast.directory")
+ }
+}
+
+func TestRegistryBase_UsesDefaultWhenUnset(t *testing.T) {
+ // Unset OWNCAST_PLUGIN_REGISTRY falls through to the public catalog
+ // so every Owncast instance gets a working Browse tab out of the
+ // box without per-deployment configuration.
+ t.Setenv("OWNCAST_PLUGIN_REGISTRY", "")
+ if got := registryBase(); got != DefaultPluginRegistry {
+ t.Errorf("registryBase unset = %q, want %q", got, DefaultPluginRegistry)
+ }
+}
+
+// --- /api/admin/plugin-registry/list ---
+
+func TestHandleRegistryList_ProxiesUpstream(t *testing.T) {
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/plugins" {
+ t.Errorf("upstream path = %q, want /plugins", r.URL.Path)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`[{"name":"demo","summary":"hi"}]`))
+ }))
+ t.Cleanup(upstream.Close)
+
+ withRegistryEnv(t, upstream.URL)
+ host := newTestHost(t)
+
+ rec := httptest.NewRecorder()
+ host.handleRegistryList(rec, httptest.NewRequest(http.MethodGet, "/api/admin/plugin-registry/list", nil))
+
+ if rec.Code != http.StatusOK {
+ t.Errorf("status = %d, want 200", rec.Code)
+ }
+ if got := strings.TrimSpace(rec.Body.String()); got != `[{"name":"demo","summary":"hi"}]` {
+ t.Errorf("body = %q", got)
+ }
+}
+
+func TestHandleRegistryList_BadGatewayOnUpstreamDown(t *testing.T) {
+ // Pointing at a port that's certainly closed (port 1 is reserved).
+ withRegistryEnv(t, "http://127.0.0.1:1")
+ host := newTestHost(t)
+
+ rec := httptest.NewRecorder()
+ host.handleRegistryList(rec, httptest.NewRequest(http.MethodGet, "/api/admin/plugin-registry/list", nil))
+
+ if rec.Code != http.StatusBadGateway {
+ t.Errorf("status = %d, want 502", rec.Code)
+ }
+}
+
+// --- /api/admin/plugin-registry/install ---
+
+func TestHandleRegistryInstall_RejectsNonPost(t *testing.T) {
+ host := newTestHost(t)
+ rec := httptest.NewRecorder()
+ host.handleRegistryInstall(rec, httptest.NewRequest(http.MethodGet, "/api/admin/plugin-registry/install", nil))
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Errorf("status = %d, want 405", rec.Code)
+ }
+}
+
+func TestHandleRegistryInstall_RejectsMissingFields(t *testing.T) {
+ host := newTestHost(t)
+ for _, body := range []string{`{}`, `{"slug":""}`, `{"version":"0.1.0"}`} {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/admin/plugin-registry/install", strings.NewReader(body))
+ host.handleRegistryInstall(rec, req)
+ if rec.Code != http.StatusBadRequest {
+ t.Errorf("body=%s: status = %d, want 400", body, rec.Code)
+ }
+ }
+}
+
+func TestHandleRegistryInstall_VersionNotFound(t *testing.T) {
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Registry detail returns versions, but not the one we asked for.
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"slug":"demo","versions":[{"version":"0.2.0","sha256":"x","downloadURL":"u"}]}`))
+ }))
+ t.Cleanup(upstream.Close)
+
+ withRegistryEnv(t, upstream.URL)
+ host := newTestHost(t)
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/admin/plugin-registry/install",
+ strings.NewReader(`{"slug":"demo","version":"0.1.0"}`))
+ host.handleRegistryInstall(rec, req)
+
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("status = %d, want 404 (body=%s)", rec.Code, rec.Body.String())
+ }
+}
+
+func TestHandleRegistryInstall_SHA256Mismatch(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ pkg := buildPackageBytes(t, helloWorldManifest(), wasmBytes)
+
+ upstream := newRegistryStub(t, "hello-world", "0.1.0", pkg, "deadbeef-wrong-hash")
+ withRegistryEnv(t, upstream.URL)
+ host := newTestHost(t)
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/admin/plugin-registry/install",
+ strings.NewReader(`{"slug":"hello-world","version":"0.1.0"}`))
+ host.handleRegistryInstall(rec, req)
+
+ if rec.Code != http.StatusBadGateway {
+ t.Errorf("status = %d, want 502 (body=%s)", rec.Code, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "hash") {
+ t.Errorf("error should mention hash mismatch, got %s", rec.Body.String())
+ }
+}
+
+func TestHandleRegistryInstall_Success(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ pkg := buildPackageBytes(t, helloWorldManifest(), wasmBytes)
+ sum := sha256.Sum256(pkg)
+ sha := hex.EncodeToString(sum[:])
+
+ upstream := newRegistryStub(t, "hello-world", "0.1.0", pkg, sha)
+ withRegistryEnv(t, upstream.URL)
+ host := newTestHost(t)
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/admin/plugin-registry/install",
+ strings.NewReader(`{"slug":"hello-world","version":"0.1.0"}`))
+ host.handleRegistryInstall(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200 (body=%s)", rec.Code, rec.Body.String())
+ }
+ // The Manager.Install path drops the .ocpkg into the manager's
+ // plugins directory. Confirm by walking List() rather than poking
+ // at the filesystem so we don't couple to the path layout.
+ entries := host.manager.List()
+ if len(entries) != 1 {
+ t.Fatalf("manager has %d entries, want 1", len(entries))
+ }
+ if entries[0].Slug != "hello-world" {
+ t.Errorf("entry slug = %q, want hello-world", entries[0].Slug)
+ }
+ if entries[0].Version != "0.1.0" {
+ t.Errorf("entry version = %q, want 0.1.0", entries[0].Version)
+ }
+}
+
+// --- /api/admin/plugin-registry/<unknown> ---
+
+func TestHandleRegistryRoute_DispatchesActions(t *testing.T) {
+ // Point at a stub that 404s the install detail lookup. That keeps
+ // the install case as a clean "registry reachable but rejects" path
+ // without depending on the (removed) unconfigured-503 behavior.
+ upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/plugins" {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`[]`))
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ t.Cleanup(upstream.Close)
+ withRegistryEnv(t, upstream.URL)
+ host := newTestHost(t)
+
+ cases := []struct {
+ path string
+ method string
+ wantStatus int
+ }{
+ {"/api/admin/plugin-registry/list", http.MethodGet, http.StatusOK},
+ {"/api/admin/plugin-registry/list/", http.MethodGet, http.StatusOK}, // trailing-slash variant
+ {"/api/admin/plugin-registry/install", http.MethodPost, http.StatusBadGateway},
+ {"/api/admin/plugin-registry/unknown", http.MethodGet, http.StatusNotFound},
+ }
+ for _, tc := range cases {
+ var body io.Reader
+ if tc.method == http.MethodPost {
+ body = strings.NewReader(`{"slug":"x","version":"y"}`)
+ }
+ rec := httptest.NewRecorder()
+ host.handleRegistryRoute(rec, httptest.NewRequest(tc.method, tc.path, body))
+ if rec.Code != tc.wantStatus {
+ t.Errorf("%s %s: status = %d, want %d", tc.method, tc.path, rec.Code, tc.wantStatus)
+ }
+ }
+}
+
+// --- test helpers ---
+
+// newRegistryStub returns an httptest server that emulates the
+// directory's /plugins/<slug> detail endpoint plus a download URL
+// the install handler will GET to retrieve the .ocpkg bytes. The
+// stubbed sha256 is whatever the caller passes, so tests can force
+// a mismatch by passing a wrong digest. Note the bare /plugins
+// path: the host proxy appends `/plugins/<slug>` to its configured
+// OWNCAST_PLUGIN_REGISTRY base, treating that base as the API root
+// the same way the directory frontend treats its API_HOST.
+//
+// The detail handler reflects the incoming request's Host header back
+// into the downloadURL so we don't have to know httptest's port in
+// advance.
+func newRegistryStub(t *testing.T, slug, version string, pkg []byte, sha string) *httptest.Server {
+ t.Helper()
+ mux := http.NewServeMux()
+ mux.HandleFunc("/plugins/"+slug, func(w http.ResponseWriter, r *http.Request) {
+ downloadURL := fmt.Sprintf("http://%s/ocpkg/%s", r.Host, slug)
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "slug": slug,
+ "versions": []map[string]any{
+ {
+ "version": version,
+ "sha256": sha,
+ "downloadURL": downloadURL,
+ },
+ },
+ })
+ })
+ mux.HandleFunc("/ocpkg/"+slug, func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/zip")
+ _, _ = w.Write(pkg)
+ })
+ srv := httptest.NewServer(mux)
+ t.Cleanup(srv.Close)
+ return srv
+}
diff --git a/services/chat/chat.go b/services/chat/chat.go
index 9fe1f8ef43..b027691dd6 100644
--- a/services/chat/chat.go
+++ b/services/chat/chat.go
@@ -21,6 +21,7 @@ import (
"github.com/owncast/owncast/persistence/userrepository"
"github.com/owncast/owncast/services/chat/events"
"github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/services/webhooks"
)
@@ -33,6 +34,7 @@ type Deps struct {
AuthRepository authrepository.AuthRepository
ChatMessageRepository chatmessagerepository.ChatMessageRepository
UserRepository userrepository.UserRepository
+ Events *dispatcher.Dispatcher
}
// New constructs a chat Service. Call Start to launch the broadcast
@@ -45,6 +47,7 @@ func New(deps Deps) *Service {
s.authRepository = deps.AuthRepository
s.chatMessageRepository = deps.ChatMessageRepository
s.userRepository = deps.UserRepository
+ s.events = deps.Events
return s
}
@@ -143,6 +146,50 @@ func (s *Service) SendSystemMessage(text string, ephemeral bool) error {
return nil
}
+// SendMessageAsBot broadcasts and persists a chat message authored by a bot
+// user, running it through the same render/sanitize, broadcast, webhook, and
+// persistence path as a message from a connected client.
+//
+// The user MUST have IsBot=true. This is deliberately the only chat-send API
+// that accepts a user identity — there's no general "send as any user" path,
+// so a plugin (the only thing that can reach this) cannot impersonate a real
+// chatter. The plugin host's chatbot provisioner creates exactly one bot
+// identity per plugin (with IsBot=true and DisplayName=plugin name) and
+// passes it here when the plugin calls owncast.chat.send.
+func (s *Service) SendMessageAsBot(user *models.User, text string) error {
+ if user == nil {
+ return errors.New("SendMessageAsBot requires a user")
+ }
+ if !user.IsBot {
+ return errors.New("SendMessageAsBot: user must be a bot (IsBot=true) — impersonating a non-bot is not allowed")
+ }
+
+ event := events.UserMessageEvent{}
+ event.Body = text
+ event.SetDefaults() // generates ID + timestamp, renders and sanitizes the body
+ // SetDefaults doesn't set Type (the websocket-inbound path picks it up
+ // from the client JSON). We're synthesizing the event server-side, so set
+ // it explicitly — without this the message is stored with an empty
+ // eventType, and the web frontend can't categorize it and crashes when
+ // rendering chat history.
+ event.Type = events.MessageSent
+ event.User = user
+
+ if event.Empty() {
+ return nil
+ }
+
+ if err := s.Broadcast(event.GetBroadcastPayload()); err != nil {
+ return err
+ }
+
+ s.webhooks.SendChatEvent(&event)
+ s.chatMessagesSentCounter.Inc()
+ s.chatMessageRepository.SaveUserMessage(event)
+
+ return nil
+}
+
// SendFediverseAction sends a message indicating some Fediverse engagement took place.
func (s *Service) SendFediverseAction(eventType string, userAccountName string, image *string, body string, link string) error {
message := events.FediverseEngagementEvent{
diff --git a/services/chat/events.go b/services/chat/events.go
index 2752def2ae..080b7e62d6 100644
--- a/services/chat/events.go
+++ b/services/chat/events.go
@@ -1,6 +1,7 @@
package chat
import (
+ "context"
"encoding/json"
"fmt"
"strings"
@@ -9,7 +10,9 @@ import (
log "github.com/sirupsen/logrus"
"github.com/owncast/owncast/config"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/services/chat/events"
+ "github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/utils"
)
@@ -165,6 +168,12 @@ func (s *Service) userMessageSent(eventData chatClientEvent) {
return
}
+ // Run inbound-message filters (plugin filterChatMessage handlers) before
+ // broadcast. A filter may rewrite event.Body in place or drop the message.
+ if s.events != nil && !s.events.ApplyFilters(context.Background(), dispatcher.Event{Type: models.MessageSent, Payload: &event}) {
+ return
+ }
+
payload := event.GetBroadcastPayload()
if err := s.Broadcast(payload); err != nil {
log.Errorln("error broadcasting UserMessageEvent payload", err)
diff --git a/services/chat/server.go b/services/chat/server.go
index d47f6edb47..23b99de816 100644
--- a/services/chat/server.go
+++ b/services/chat/server.go
@@ -19,6 +19,7 @@ import (
"github.com/owncast/owncast/persistence/userrepository"
"github.com/owncast/owncast/services/chat/events"
"github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/services/geoip"
"github.com/owncast/owncast/services/webhooks"
"github.com/owncast/owncast/utils"
@@ -52,6 +53,11 @@ type Service struct {
// (welcome messages, recent-disconnect heuristics).
getStatus func() models.Status
+ // events is the shared dispatcher. Inbound user messages are run through
+ // its filter chain before broadcast, letting consumers (the plugin host)
+ // rewrite or drop them. nil means no filtering.
+ events *dispatcher.Dispatcher
+
// configRepository provides server-side chat settings consulted on each
// inbound message (slur/spam filters, established-users-only mode,
// auth requirement, welcome message text, etc.).
diff --git a/services/datastore/cache.go b/services/datastore/cache.go
index 92ecc59805..96d255ad4b 100644
--- a/services/datastore/cache.go
+++ b/services/datastore/cache.go
@@ -24,3 +24,11 @@ func (ds *Datastore) SetCachedValue(key string, b []byte) {
ds.cache[key] = b
}
+
+// DeleteCachedValue removes key from the cache.
+func (ds *Datastore) DeleteCachedValue(key string) {
+ ds.cacheLock.Lock()
+ defer ds.cacheLock.Unlock()
+
+ delete(ds.cache, key)
+}
diff --git a/services/datastore/datastore.go b/services/datastore/datastore.go
index f9d8261459..85e9f5782f 100644
--- a/services/datastore/datastore.go
+++ b/services/datastore/datastore.go
@@ -109,6 +109,18 @@ func (ds *Datastore) Save(e models.ConfigEntry) error {
return nil
}
+// Delete removes the entry for key. A missing key is not an error.
+func (ds *Datastore) Delete(key string) error {
+ ds.DbLock.Lock()
+ defer ds.DbLock.Unlock()
+
+ if _, err := ds.DB.Exec("DELETE FROM datastore WHERE key = ?", key); err != nil {
+ return err
+ }
+ ds.DeleteCachedValue(key)
+ return nil
+}
+
// Setup will perform initial initialization using the provided database
// handle. Called by SetupPersistence with the freshly opened *sql.DB.
func (ds *Datastore) Setup(db *sql.DB) {
diff --git a/services/dispatcher/dispatcher.go b/services/dispatcher/dispatcher.go
new file mode 100644
index 0000000000..71aca717bf
--- /dev/null
+++ b/services/dispatcher/dispatcher.go
@@ -0,0 +1,99 @@
+// Package dispatcher is a tiny in-process publish/subscribe + filter mediator.
+//
+// It lets event producers (chat, webhooks, …) notify and filter through a
+// single neutral component that consumers (the plugin host today, other
+// subsystems in future) subscribe to. Producers depend on the dispatcher and
+// call it; consumers register handlers on it. Neither side has to know about,
+// import, or be mutated by the other — which keeps every service on plain
+// constructor injection instead of post-construction setters.
+//
+// Construct one in the composition root and inject it everywhere; it depends
+// on nothing.
+package dispatcher
+
+import (
+ "context"
+ "sync"
+)
+
+// Event is a named event with an arbitrary payload. Producers and consumers
+// agree on the concrete payload type for each event Type (e.g. a
+// *events.UserMessageEvent for a chat message).
+type Event struct {
+ Type string
+ Payload any
+}
+
+// Listener is notified of an event that has already happened. Listeners run
+// synchronously in the producer's goroutine, so they must not block — offload
+// slow work (e.g. wasm plugin calls) to a goroutine.
+type Listener func(ctx context.Context, event Event)
+
+// Filter inspects an event before it takes effect and reports whether it
+// should proceed; returning false drops the event. A filter may mutate the
+// payload in place (it's passed by pointer) to rewrite the event.
+type Filter func(ctx context.Context, event Event) (allow bool)
+
+// Dispatcher fans events out to registered listeners and runs them through
+// registered filters. Use New to construct one.
+type Dispatcher struct {
+ mu sync.RWMutex
+ listeners []Listener
+ filters []Filter
+}
+
+// New constructs an empty Dispatcher.
+func New() *Dispatcher {
+ return &Dispatcher{}
+}
+
+// AddListener registers l to be notified of every published event. Intended
+// to be called during composition, before events start flowing.
+func (d *Dispatcher) AddListener(l Listener) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.listeners = append(d.listeners, l)
+}
+
+// AddFilter appends f to the filter chain. Filters run in registration order
+// and any may drop the event.
+func (d *Dispatcher) AddFilter(f Filter) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.filters = append(d.filters, f)
+}
+
+// Publish notifies every registered listener of event, in registration order.
+// The listener slice is copied under the lock before iteration; the
+// outer functions are called without the lock held so a listener that
+// re-publishes (or calls AddListener) doesn't deadlock, and a
+// concurrent AddListener can't mutate the slice we're iterating.
+func (d *Dispatcher) Publish(ctx context.Context, event Event) {
+ d.mu.RLock()
+ listeners := make([]Listener, len(d.listeners))
+ copy(listeners, d.listeners)
+ d.mu.RUnlock()
+
+ for _, l := range listeners {
+ l(ctx, event)
+ }
+}
+
+// ApplyFilters runs event through the filter chain and reports whether it
+// survived. Filters may mutate the payload in place. With no filters
+// registered the event always passes. Same copy-under-lock discipline
+// as Publish: AddFilter on another goroutine can't race with the
+// iteration here.
+func (d *Dispatcher) ApplyFilters(ctx context.Context, event Event) (allow bool) {
+ d.mu.RLock()
+ filters := make([]Filter, len(d.filters))
+ copy(filters, d.filters)
+ d.mu.RUnlock()
+
+ for _, f := range filters {
+ if !f(ctx, event) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/services/dispatcher/dispatcher_test.go b/services/dispatcher/dispatcher_test.go
new file mode 100644
index 0000000000..845ef5db84
--- /dev/null
+++ b/services/dispatcher/dispatcher_test.go
@@ -0,0 +1,79 @@
+package dispatcher
+
+import (
+ "context"
+ "sync"
+ "testing"
+)
+
+func TestPublishFansOutToListeners(t *testing.T) {
+ d := New()
+ var got []string
+ d.AddListener(func(_ context.Context, e Event) { got = append(got, "a:"+e.Type) })
+ d.AddListener(func(_ context.Context, e Event) { got = append(got, "b:"+e.Type) })
+
+ d.Publish(context.Background(), Event{Type: "x"})
+
+ if len(got) != 2 || got[0] != "a:x" || got[1] != "b:x" {
+ t.Fatalf("listeners not invoked in order: %v", got)
+ }
+}
+
+func TestApplyFiltersPassesWhenNoneRegistered(t *testing.T) {
+ d := New()
+ if !d.ApplyFilters(context.Background(), Event{Type: "x"}) {
+ t.Fatal("expected pass with no filters registered")
+ }
+}
+
+func TestApplyFiltersRunsChainAndMutatesInPlace(t *testing.T) {
+ d := New()
+ d.AddFilter(func(_ context.Context, e Event) bool {
+ *e.Payload.(*string) += "-1"
+ return true
+ })
+ d.AddFilter(func(_ context.Context, e Event) bool {
+ *e.Payload.(*string) += "-2"
+ return true
+ })
+
+ body := "body"
+ if !d.ApplyFilters(context.Background(), Event{Type: "x", Payload: &body}) {
+ t.Fatal("expected event to pass")
+ }
+ if body != "body-1-2" {
+ t.Errorf("in-place mutation chain = %q, want %q", body, "body-1-2")
+ }
+}
+
+func TestApplyFiltersDropStopsChain(t *testing.T) {
+ d := New()
+ ran := 0
+ d.AddFilter(func(_ context.Context, _ Event) bool { ran++; return false })
+ d.AddFilter(func(_ context.Context, _ Event) bool { ran++; return true })
+
+ if d.ApplyFilters(context.Background(), Event{Type: "x"}) {
+ t.Fatal("expected event to be dropped")
+ }
+ if ran != 1 {
+ t.Errorf("filters run = %d, want 1 (chain should stop at the drop)", ran)
+ }
+}
+
+func TestPublishWithNoListeners(t *testing.T) {
+ // Publishing with nothing registered must be a safe no-op.
+ New().Publish(context.Background(), Event{Type: "x"})
+}
+
+func TestConcurrentRegisterAndDispatch(t *testing.T) {
+ // Registration and dispatch must be race-free (run with -race).
+ d := New()
+ var wg sync.WaitGroup
+ for i := 0; i < 25; i++ {
+ wg.Add(3)
+ go func() { defer wg.Done(); d.AddListener(func(context.Context, Event) {}) }()
+ go func() { defer wg.Done(); d.Publish(context.Background(), Event{Type: "x"}) }()
+ go func() { defer wg.Done(); d.ApplyFilters(context.Background(), Event{Type: "x"}) }()
+ }
+ wg.Wait()
+}
diff --git a/services/plugins/contract_test.go b/services/plugins/contract_test.go
new file mode 100644
index 0000000000..374aa35ac6
--- /dev/null
+++ b/services/plugins/contract_test.go
@@ -0,0 +1,200 @@
+package plugins
+
+import (
+ "encoding/json"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "os"
+ "path/filepath"
+ "regexp"
+ "runtime"
+ "sort"
+ "strconv"
+ "strings"
+ "testing"
+)
+
+// This guards against this vendored copy of the plugin runtime silently
+// drifting from the upstream SDK's wire contract. services/plugins is a copy
+// of github.com/owncast/plugin-sdk's host-runtime/plugin package; the
+// implementation is allowed to fork for Owncast integration, but the *wire
+// contract* (host-function names, permission identifiers, serialized type
+// shapes) must stay identical, or plugins and the TypeScript SDK break.
+//
+// plugin-contract.json is the SDK's published contract, copied in verbatim.
+// This test re-derives the contract from THIS repo's hostfns.go and compares.
+// If it fails, this copy has fallen behind (or ahead of) the SDK — re-sync the
+// runtime and copy the SDK's host-runtime/plugin/plugin-contract.json here.
+//
+// The extractor below is a verbatim copy of the SDK's
+// host-runtime/plugin/contract_test.go extractor; keep it identical so the
+// produced contract is comparable byte-for-byte.
+
+// hostFnNameRe matches an actual host-function name exactly — not the error
+// strings ("owncast_x from %s: ...") that also begin with the prefix.
+var hostFnNameRe = regexp.MustCompile(`^owncast_[a-z_]+$`)
+
+type contract struct {
+ Permissions map[string]string `json:"permissions"`
+ HostFunctions []string `json:"hostFunctions"`
+ WireTypes map[string]map[string]string `json:"wireTypes"`
+}
+
+func buildContractFromSource(t *testing.T, src string) contract {
+ t.Helper()
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "hostfns.go", src, 0)
+ if err != nil {
+ t.Fatalf("parse hostfns.go: %v", err)
+ }
+
+ c := contract{
+ Permissions: map[string]string{},
+ WireTypes: map[string]map[string]string{},
+ }
+
+ fnSet := map[string]bool{}
+ ast.Inspect(f, func(n ast.Node) bool {
+ lit, ok := n.(*ast.BasicLit)
+ if ok && lit.Kind == token.STRING {
+ if s, err := strconv.Unquote(lit.Value); err == nil && hostFnNameRe.MatchString(s) {
+ fnSet[s] = true
+ }
+ }
+ return true
+ })
+ for name := range fnSet {
+ c.HostFunctions = append(c.HostFunctions, name)
+ }
+ sort.Strings(c.HostFunctions)
+
+ for _, decl := range f.Decls {
+ gd, ok := decl.(*ast.GenDecl)
+ if !ok {
+ continue
+ }
+ switch gd.Tok {
+ case token.CONST:
+ for _, spec := range gd.Specs {
+ vs, ok := spec.(*ast.ValueSpec)
+ if !ok {
+ continue
+ }
+ for i, name := range vs.Names {
+ if !strings.HasPrefix(name.Name, "Perm") || i >= len(vs.Values) {
+ continue
+ }
+ if lit, ok := vs.Values[i].(*ast.BasicLit); ok && lit.Kind == token.STRING {
+ if v, err := strconv.Unquote(lit.Value); err == nil {
+ c.Permissions[name.Name] = v
+ }
+ }
+ }
+ }
+ case token.TYPE:
+ for _, spec := range gd.Specs {
+ ts, ok := spec.(*ast.TypeSpec)
+ if !ok {
+ continue
+ }
+ st, ok := ts.Type.(*ast.StructType)
+ if !ok {
+ continue
+ }
+ fields := map[string]string{}
+ for _, field := range st.Fields.List {
+ tag := jsonTagName(field.Tag)
+ if tag == "" || tag == "-" {
+ continue
+ }
+ fields[tag] = exprTypeString(field.Type)
+ }
+ if len(fields) > 0 {
+ c.WireTypes[ts.Name.Name] = fields
+ }
+ }
+ }
+ }
+ return c
+}
+
+func jsonTagName(tag *ast.BasicLit) string {
+ if tag == nil {
+ return ""
+ }
+ raw, err := strconv.Unquote(tag.Value)
+ if err != nil {
+ return ""
+ }
+ for _, part := range strings.Fields(raw) {
+ if strings.HasPrefix(part, "json:") {
+ v, err := strconv.Unquote(strings.TrimPrefix(part, "json:"))
+ if err != nil {
+ return ""
+ }
+ return strings.Split(v, ",")[0]
+ }
+ }
+ return ""
+}
+
+func exprTypeString(e ast.Expr) string {
+ switch t := e.(type) {
+ case *ast.Ident:
+ return t.Name
+ case *ast.StarExpr:
+ return "*" + exprTypeString(t.X)
+ case *ast.ArrayType:
+ return "[]" + exprTypeString(t.Elt)
+ case *ast.SelectorExpr:
+ return exprTypeString(t.X) + "." + t.Sel.Name
+ case *ast.MapType:
+ return "map[" + exprTypeString(t.Key) + "]" + exprTypeString(t.Value)
+ default:
+ return "?"
+ }
+}
+
+func marshalContract(t *testing.T, c contract) []byte {
+ t.Helper()
+ data, err := json.MarshalIndent(c, "", " ")
+ if err != nil {
+ t.Fatalf("marshal contract: %v", err)
+ }
+ return append(data, '\n')
+}
+
+func TestPluginContractMatchesSDK(t *testing.T) {
+ _, thisFile, _, _ := runtime.Caller(0)
+ repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..")
+
+ src, err := os.ReadFile(filepath.Join(repoRoot, "services/plugins/hostfns.go"))
+ if err != nil {
+ t.Fatalf("read hostfns.go: %v", err)
+ }
+ gotJSON := marshalContract(t, buildContractFromSource(t, string(src)))
+
+ want, err := os.ReadFile(filepath.Join(repoRoot, "services/plugins/plugin-contract.json"))
+ if err != nil {
+ t.Fatalf("read plugin-contract.json: %v", err)
+ }
+
+ if string(gotJSON) != string(want) {
+ t.Errorf(`Owncast's bundled plugin runtime is out of sync with the plugin SDK.
+
+The plugin host functions, permissions, or data shapes in services/plugins no
+longer match what the SDK (github.com/owncast/plugin-sdk) publishes, so plugins
+built against the SDK may not work correctly against this build of Owncast.
+
+This usually means a change landed in the SDK but wasn't copied here yet (or a
+change was made here without updating the SDK). To fix:
+
+ 1. Make the change in the SDK first and regenerate its snapshot there:
+ UPDATE_CONTRACT=1 go test ./plugin/ -run TestPluginContract
+ 2. Copy the SDK's host-runtime/plugin/plugin-contract.json over
+ services/plugins/plugin-contract.json here, and bring
+ services/plugins/hostfns.go in line with the SDK.
+ 3. Re-run this test — it passes once the two sides match.`)
+ }
+}
diff --git a/services/plugins/dispatcher.go b/services/plugins/dispatcher.go
new file mode 100644
index 0000000000..3fe76a8940
--- /dev/null
+++ b/services/plugins/dispatcher.go
@@ -0,0 +1,274 @@
+package plugins
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "sort"
+ "sync"
+ "time"
+)
+
+// Envelope is the JSON payload passed across the plugin boundary for every
+// event. Plugins receive this serialized via Host.inputString().
+type Envelope struct {
+ EventType string `json:"eventType"`
+ Payload any `json:"payload"`
+}
+
+type FilterAction string
+
+const (
+ FilterPass FilterAction = "pass"
+ FilterModify FilterAction = "modify"
+ FilterDrop FilterAction = "drop"
+)
+
+type FilterResult struct {
+ Action FilterAction `json:"action"`
+ Payload any `json:"payload,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+// Dispatcher fans events to subscribed plugins. It holds a snapshot function
+// rather than a static slice so the Manager can enable/disable plugins at
+// runtime and the dispatcher will always see the current set.
+type Dispatcher struct {
+ snapshot func() []*Loaded
+}
+
+// NewDispatcher builds a dispatcher over a fixed plugin set. Use this in
+// tests and any context where the plugin set doesn't change after construction.
+func NewDispatcher(loaded []*Loaded) *Dispatcher {
+ snap := loaded
+ return &Dispatcher{snapshot: func() []*Loaded { return snap }}
+}
+
+// NewLiveDispatcher builds a dispatcher backed by a snapshot function — the
+// Manager passes its Snapshot method here so admin enable/disable shows up
+// immediately without restarting the host.
+func NewLiveDispatcher(snapshot func() []*Loaded) *Dispatcher {
+ return &Dispatcher{snapshot: snapshot}
+}
+
+// MaxEmitDepth caps how deep host_emit_event recursion is allowed to go.
+// Above this, the dispatcher silently drops the event and logs once. This
+// stops a plugin that emits an event it itself subscribes to from blowing
+// the stack.
+const MaxEmitDepth = 8
+
+// FilterTimeout caps how long a single filter call can run before the host
+// cancels it and fails-open (same semantics as a thrown error: skip this
+// filter, continue with the previous payload, count as a strike toward
+// auto-disable). The chain is unbounded; per-filter caps are sufficient
+// because a runaway plugin in slot 1 doesn't block slot 2.
+//
+// Declared as a var (not const) so tests that need to exercise post-call
+// safeguards — e.g. the output-size check — can stretch this temporarily.
+// Production callers should treat it as read-only.
+var FilterTimeout = 50 * time.Millisecond
+
+type depthKey struct{}
+
+func emitDepth(ctx context.Context) int {
+ if v, ok := ctx.Value(depthKey{}).(int); ok {
+ return v
+ }
+ return 0
+}
+
+// Dispatch runs the filter chain for an event, then fans the (possibly
+// modified) payload out as notifications. If the filter chain drops the
+// event, no notifications fire.
+func (d *Dispatcher) Dispatch(ctx context.Context, eventType string, payload any) {
+ depth := emitDepth(ctx)
+ if depth >= MaxEmitDepth {
+ fmt.Fprintf(os.Stderr, "dispatcher: max emit depth %d reached for %q — dropping\n", MaxEmitDepth, eventType)
+ return
+ }
+ ctx = context.WithValue(ctx, depthKey{}, depth+1)
+
+ final, allowed, reason := d.Filter(ctx, eventType, payload)
+ if !allowed {
+ fmt.Fprintf(os.Stderr, "[filtered] %s dropped: %s\n", eventType, reason)
+ return
+ }
+ d.Notify(ctx, eventType, final)
+}
+
+// Filter runs the ordered filter chain for an event. Plugin errors are
+// fail-open — the event passes through that plugin unchanged. Returns the
+// final payload, whether the event survived, and a drop reason if not.
+func (d *Dispatcher) Filter(ctx context.Context, eventType string, payload any) (any, bool, string) {
+ type subbed struct {
+ plugin *Loaded
+ priority int
+ }
+ var chain []subbed
+ for _, p := range d.snapshot() {
+ for _, s := range p.Manifest.Subscriptions.Filter {
+ if s.Event == eventType {
+ chain = append(chain, subbed{p, s.Priority})
+ }
+ }
+ }
+ sort.SliceStable(chain, func(i, j int) bool {
+ if chain[i].priority != chain[j].priority {
+ return chain[i].priority < chain[j].priority
+ }
+ return chain[i].plugin.Manifest.Slug < chain[j].plugin.Manifest.Slug
+ })
+
+ current := payload
+ for _, c := range chain {
+ if c.plugin.IsDisabled() {
+ // Auto-disabled by the strike system; skip silently.
+ continue
+ }
+ result, err := callOnFilter(ctx, c.plugin, eventType, current)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "plugin %s: on_filter(%s) failed (fail-open): %v\n", c.plugin.Manifest.Slug, eventType, err)
+ if c.plugin.recordFilterFailure() {
+ fmt.Fprintf(os.Stderr, "plugin %s: auto-disabled after %d consecutive filter failures\n",
+ c.plugin.Manifest.Slug, FilterStrikeThreshold)
+ }
+ continue
+ }
+ c.plugin.recordFilterSuccess()
+ switch result.Action {
+ case FilterPass, "":
+ // payload unchanged
+ case FilterModify:
+ current = result.Payload
+ case FilterDrop:
+ return nil, false, result.Reason
+ default:
+ fmt.Fprintf(os.Stderr, "plugin %s: unknown filter action %q (fail-open)\n", c.plugin.Manifest.Slug, result.Action)
+ }
+ }
+ return current, true, ""
+}
+
+func callOnFilter(ctx context.Context, p *Loaded, eventType string, payload any) (*FilterResult, error) {
+ if !p.plugin.FunctionExists("on_filter") {
+ return nil, fmt.Errorf("plugin does not export on_filter")
+ }
+ envelope, err := json.Marshal(Envelope{EventType: eventType, Payload: payload})
+ if err != nil {
+ return nil, fmt.Errorf("marshal envelope: %w", err)
+ }
+ // Per-call deadline. FilterTimeout has to cover BOTH waiting for the
+ // per-plugin mutex AND the wasm call itself: an HTTP request or
+ // on_event in flight on the same plugin holds p.mu, so a naive
+ // deadline started after Lock() could let the chat hot path stall
+ // for the full duration of that other call before the filter clock
+ // even starts. Bounding both phases with one context keeps the
+ // chat path responsive even when the plugin is otherwise busy.
+ callCtx, cancel := context.WithTimeout(ctx, FilterTimeout)
+ defer cancel()
+ if err := lockWithContext(callCtx, &p.mu); err != nil {
+ return nil, fmt.Errorf("on_filter timed out after %s waiting for plugin mutex", FilterTimeout)
+ }
+ defer p.mu.Unlock()
+ _, out, err := p.plugin.CallWithContext(callCtx, "on_filter", envelope)
+ if err != nil {
+ if errors.Is(err, context.DeadlineExceeded) || callCtx.Err() == context.DeadlineExceeded {
+ return nil, fmt.Errorf("on_filter timed out after %s", FilterTimeout)
+ }
+ return nil, fmt.Errorf("call on_filter: %w", err)
+ }
+ if len(out) > MaxFilterOutputBytes {
+ return nil, fmt.Errorf("on_filter output too large: %d bytes (max %d)", len(out), MaxFilterOutputBytes)
+ }
+ var result FilterResult
+ if err := json.Unmarshal(out, &result); err != nil {
+ return nil, fmt.Errorf("parse on_filter result: %w", err)
+ }
+ return &result, nil
+}
+
+// Notify fans an event out to every plugin subscribed to it via
+// `subscriptions.notify`. Plugins run in parallel; errors are logged but
+// don't affect other plugins or the caller.
+func (d *Dispatcher) Notify(ctx context.Context, eventType string, payload any) {
+ envelope := Envelope{EventType: eventType, Payload: payload}
+ encoded, err := json.Marshal(envelope)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "dispatcher: marshal envelope for %s: %v\n", eventType, err)
+ return
+ }
+
+ var wg sync.WaitGroup
+ for _, p := range d.snapshot() {
+ if !subscribed(p.Manifest.Subscriptions.Notify, eventType) {
+ continue
+ }
+ wg.Add(1)
+ go func(p *Loaded) {
+ defer wg.Done()
+ if err := callOnEvent(ctx, p, encoded); err != nil {
+ fmt.Fprintf(os.Stderr, "plugin %s: on_event(%s) failed: %v\n", p.Manifest.Slug, eventType, err)
+ }
+ }(p)
+ }
+ wg.Wait()
+}
+
+func subscribed(subs []Subscription, eventType string) bool {
+ for _, s := range subs {
+ if s.Event == eventType {
+ return true
+ }
+ }
+ return false
+}
+
+func callOnEvent(ctx context.Context, p *Loaded, input []byte) error {
+ if !p.plugin.FunctionExists("on_event") {
+ return fmt.Errorf("plugin does not export on_event")
+ }
+ // Extism plugins are not safe for concurrent calls; serialize per-plugin.
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ callCtx, cancel := context.WithTimeout(ctx, NotifyTimeout)
+ defer cancel()
+ _, _, err := p.plugin.CallWithContext(callCtx, "on_event", input)
+ if err != nil {
+ if errors.Is(err, context.DeadlineExceeded) || callCtx.Err() == context.DeadlineExceeded {
+ return fmt.Errorf("on_event timed out after %s", NotifyTimeout)
+ }
+ }
+ return err
+}
+
+// lockWithContext attempts to acquire mu, but gives up if ctx fires
+// first. Go's sync.Mutex can't be cancelled mid-Lock, so when the
+// context expires before the lock is acquired we spawn a throwaway
+// goroutine that drops the lock as soon as the kernel eventually
+// grants it. That goroutine is bounded by the original Lock duration
+// and exits cleanly; the caller treats the timeout as an error.
+//
+// This matters for the chat filter hot path: another call on the
+// same plugin (an HTTP handler, an on_event) can hold p.mu for many
+// seconds, and a plain Lock() inside Filter would let the chat path
+// stall for that whole window before the filter's own deadline even
+// started.
+func lockWithContext(ctx context.Context, mu *sync.Mutex) error {
+ locked := make(chan struct{})
+ go func() {
+ mu.Lock()
+ close(locked)
+ }()
+ select {
+ case <-locked:
+ return nil
+ case <-ctx.Done():
+ go func() {
+ <-locked
+ mu.Unlock()
+ }()
+ return ctx.Err()
+ }
+}
diff --git a/services/plugins/dispatcher_test.go b/services/plugins/dispatcher_test.go
new file mode 100644
index 0000000000..dab3867a53
--- /dev/null
+++ b/services/plugins/dispatcher_test.go
@@ -0,0 +1,58 @@
+package plugins
+
+import (
+ "context"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestFilterTimeoutErrorShape verifies the error-string the dispatcher
+// produces when CallWithContext returns a deadline-exceeded error. The
+// real Wazero-level cancellation is verified separately by integration
+// tests; this is the Go-side conversion shape that the strike system and
+// the host log key off of.
+func TestFilterTimeoutErrorShape(t *testing.T) {
+ ctx, cancel := context.WithTimeout(context.Background(), 0)
+ defer cancel()
+ time.Sleep(time.Millisecond)
+ if !errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ t.Fatalf("test setup: expected deadline exceeded, got %v", ctx.Err())
+ }
+ formatted := formatFilterTimeoutError(ctx.Err())
+ if !strings.Contains(formatted.Error(), "timed out") {
+ t.Errorf("expected timeout error string, got %v", formatted)
+ }
+ if !strings.Contains(formatted.Error(), FilterTimeout.String()) {
+ t.Errorf("expected error to mention %s, got %v", FilterTimeout, formatted)
+ }
+}
+
+// formatFilterTimeoutError mirrors the shape callOnFilter produces so we
+// can test conversion without instantiating a real wasm plugin.
+func formatFilterTimeoutError(err error) error {
+ if errors.Is(err, context.DeadlineExceeded) {
+ return errors.New("on_filter timed out after " + FilterTimeout.String())
+ }
+ return err
+}
+
+// TestFilterTimeoutCountsAsStrike confirms that a timeout-induced failure
+// goes through the strike system just like a thrown error would. The
+// dispatcher already calls recordFilterFailure on any returned error, so
+// this is a direct check of the strike accumulator.
+func TestFilterTimeoutCountsAsStrike(t *testing.T) {
+ l := &Loaded{Manifest: &Manifest{DisplayName: "slow-filter"}}
+ for i := 0; i < FilterStrikeThreshold-1; i++ {
+ if disabled := l.recordFilterFailure(); disabled {
+ t.Fatalf("disabled too early at strike %d", i+1)
+ }
+ }
+ if disabled := l.recordFilterFailure(); !disabled {
+ t.Fatal("threshold-th strike should trigger auto-disable")
+ }
+ if !l.IsDisabled() {
+ t.Fatal("IsDisabled should be true after threshold reached")
+ }
+}
diff --git a/services/plugins/events.go b/services/plugins/events.go
new file mode 100644
index 0000000000..f819ebdd1b
--- /dev/null
+++ b/services/plugins/events.go
@@ -0,0 +1,27 @@
+package plugins
+
+// Built-in Owncast event types. These mirror the SDK's `Events` const so the
+// host and plugins agree on names without typo risk. Plugin-emitted custom
+// events are arbitrary strings; define those at the call site.
+const (
+ // Chat events.
+ EventChatMessageReceived = "chat.message.received"
+ EventChatUserJoined = "chat.user.joined"
+ EventChatUserParted = "chat.user.parted"
+ EventChatUserRenamed = "chat.user.renamed"
+ EventChatMessageModerated = "chat.message.moderated"
+
+ // Stream lifecycle events.
+ EventStreamStarted = "stream.started"
+ EventStreamStopped = "stream.stopped"
+ EventStreamTitleChanged = "stream.title.changed"
+
+ // Fediverse events. Engagement (follow/like/repost) carries only
+ // actor + target metadata; mention/reply also carry the post content
+ // so plugins can act on what was actually said.
+ EventFediverseFollow = "fediverse.follow"
+ EventFediverseLike = "fediverse.like"
+ EventFediverseRepost = "fediverse.repost"
+ EventFediverseMention = "fediverse.mention"
+ EventFediverseReply = "fediverse.reply"
+)
diff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.go
new file mode 100644
index 0000000000..e738699262
--- /dev/null
+++ b/services/plugins/hostfns.go
@@ -0,0 +1,1291 @@
+package plugins
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "strings"
+
+ extism "github.com/extism/go-sdk"
+ "github.com/owncast/owncast/services/plugins/kv"
+)
+
+var _ = (*http.Request)(nil) // ensure import retained for the HostEnv signature
+
+// Permission identifiers. The manifest declares which a plugin needs; only
+// the corresponding wasm imports are wired into the plugin instance.
+const (
+ PermStorageKV = "storage.kv"
+ PermStorageUpload = "storage.upload"
+ PermChatSend = "chat.send"
+ PermChatHistory = "chat.history"
+ PermChatModerate = "chat.moderate"
+ // PermChatFilter is required for any plugin that subscribes to
+ // filterChatMessage. The host refuses to load a plugin whose
+ // runtime-declared filter subscriptions include the chat-message
+ // event without this permission, so a plugin can't silently start
+ // dropping or rewriting chat without the admin's consent.
+ PermChatFilter = "chat.filter"
+ PermNetworkFetch = "network.fetch"
+ PermEmitEvent = "events.emit"
+ PermHttpServe = "http.serve"
+ PermHttpSSE = "http.sse"
+ PermServerRead = "server.read"
+ PermNotificationsSend = "notifications.send"
+ PermUsersRead = "users.read"
+ PermUsersModerate = "users.moderate"
+ PermFediversePost = "fediverse.post"
+ PermVideoConfigRead = "videoconfig.read"
+ PermVideoConfigWrite = "videoconfig.write"
+ // PermUIModify lets a plugin add UI surfaces to Owncast: admin pages
+ // (manifest.admin.pages) and viewer action buttons (manifest.actions).
+ // A plugin can serve HTTP on /plugins/<name>/ without this permission
+ // (e.g. for headless APIs), but cannot publish anything that shows up
+ // in the admin UI or viewer chrome without opting in explicitly.
+ PermUIModify = "ui.modify"
+)
+
+// ChatSendKind distinguishes how a plugin asked to post to chat. All sends
+// post under the plugin's own chat identity — provisioned by the host at
+// install time as a chat user with IsBot=true and DisplayName=plugin name.
+// Plugins cannot post under arbitrary or other users' identities; to use a
+// different chat name, ship as a different plugin.
+type ChatSendKind int
+
+const (
+ ChatSendBot ChatSendKind = iota // owncast.chat.send — posts as the plugin's bot
+ ChatSendAction // owncast.chat.sendAction — italic, "/me" style
+ ChatSendSystem // owncast.chat.system — server-announcement style, no user identity, body is HTML
+)
+
+// ChatSendRequest is everything the host needs to dispatch a chat post made
+// by a plugin. The host looks up the plugin's bot access token and posts
+// through Owncast's normal chat pipeline using that token.
+//
+// Two identity fields, not one: PluginSlug is the stable identifier used to
+// look up the bot's persistent access token (it's how the chatbot user is
+// indexed in the datastore, and how the cache keys), while BotDisplayName is
+// the human-readable name shown to chat viewers. The split exists so a plugin
+// authored as "Awesome Echo Bot" (display) with slug "awesome-echo-bot"
+// (identifier) shows the friendly name in chat instead of the slug.
+type ChatSendRequest struct {
+ PluginSlug string
+ BotDisplayName string
+ Kind ChatSendKind
+ Text string
+}
+
+// StreamInfo is what owncast.stream.current() returns to a plugin. Wired to
+// real Owncast state in production; in the PoC the demo binary fills it in.
+type StreamInfo struct {
+ Online bool `json:"online"`
+ Title string `json:"title,omitempty"`
+ Summary string `json:"summary,omitempty"`
+ Viewers int `json:"viewers"`
+ StartedAt string `json:"startedAt,omitempty"` // ISO-8601, empty when offline
+ LatencyLevel int `json:"latencyLevel,omitempty"`
+}
+
+// ServerInfo is what owncast.server.info() returns to a plugin.
+type ServerInfo struct {
+ Name string `json:"name,omitempty"`
+ URL string `json:"url,omitempty"`
+ Summary string `json:"summary,omitempty"`
+ WelcomeMessage string `json:"welcomeMessage,omitempty"`
+ Version string `json:"version,omitempty"`
+}
+
+// StreamBroadcaster is what owncast.stream.broadcaster() returns — details
+// about the currently-connected inbound broadcast. Zero-valued when offline.
+type StreamBroadcaster struct {
+ RemoteAddr string `json:"remoteAddr,omitempty"`
+ Codecs []string `json:"codecs,omitempty"`
+ Resolution string `json:"resolution,omitempty"`
+ Framerate int `json:"framerate,omitempty"`
+ Bitrates []int `json:"bitrates,omitempty"`
+}
+
+// StreamVariant is one configured output rendition, part of the VideoConfig
+// returned/accepted by owncast.videoConfig.read()/write().
+type StreamVariant struct {
+ Width int `json:"width"`
+ Height int `json:"height"`
+ Framerate int `json:"framerate"`
+ VideoBitrate int `json:"videoBitrate"`
+ AudioBitrate int `json:"audioBitrate"`
+ IsPassthrough bool `json:"isPassthrough"`
+}
+
+// VideoConfig is the current output/transcoding configuration returned by
+// owncast.videoConfig.read(). These are settable knobs (see VideoConfigUpdate),
+// as opposed to read-only inbound-broadcast telemetry (StreamBroadcaster).
+// Requires the videoconfig.read permission.
+type VideoConfig struct {
+ LatencyLevel int `json:"latencyLevel"`
+ Codec string `json:"codec"`
+ Variants []StreamVariant `json:"variants"`
+}
+
+// VideoConfigUpdate is a partial change passed to owncast.videoConfig.write().
+// Nil/omitted fields are left unchanged, so a plugin can set just the latency
+// level without disturbing the configured output variants. Requires the
+// videoconfig.write permission.
+type VideoConfigUpdate struct {
+ LatencyLevel *int `json:"latencyLevel,omitempty"`
+ Codec *string `json:"codec,omitempty"`
+ Variants []StreamVariant `json:"variants,omitempty"`
+}
+
+// SocialHandle is one entry returned by owncast.server.socials().
+type SocialHandle struct {
+ Platform string `json:"platform"`
+ URL string `json:"url"`
+ Icon string `json:"icon,omitempty"`
+}
+
+// FederationInfo is what owncast.server.federation() returns.
+type FederationInfo struct {
+ Enabled bool `json:"enabled"`
+ Username string `json:"username,omitempty"`
+ IsPrivate bool `json:"isPrivate,omitempty"`
+}
+
+// FediversePayload is what a plugin passes to owncast.notifications.fediverse.
+type FediversePayload struct {
+ Type string `json:"type"` // "follow", "like", "repost", or a custom string
+ Body string `json:"body"`
+ Image string `json:"image,omitempty"`
+ Link string `json:"link,omitempty"`
+}
+
+// HostChatMessage is the shape returned by ChatHistory. Wider than the
+// onChatMessage event payload — production wires this to whatever the chat
+// repository hands back; tests construct it directly.
+type HostChatMessage struct {
+ ID string `json:"id"`
+ User string `json:"user"`
+ Body string `json:"body"`
+ Timestamp string `json:"timestamp"`
+}
+
+// BrowserPushPayload is what a plugin asks Owncast to send via the
+// configured browser push channel.
+type BrowserPushPayload struct {
+ Title string `json:"title"`
+ Body string `json:"body,omitempty"`
+ URL string `json:"url,omitempty"`
+}
+
+// HostUser is the shape returned by Users() / UserGet().
+type HostUser struct {
+ ID string `json:"id"`
+ DisplayName string `json:"displayName"`
+ PreviousNames []string `json:"previousNames,omitempty"`
+ CreatedAt string `json:"createdAt,omitempty"`
+ DisabledAt string `json:"disabledAt,omitempty"` // ISO-8601 if banned, empty otherwise
+ Scopes []string `json:"scopes,omitempty"`
+ IsBot bool `json:"isBot,omitempty"`
+ IsAuthenticated bool `json:"isAuthenticated,omitempty"`
+}
+
+// HostChatClient is the shape returned by ChatClients() — a connected chat
+// session, not a User (one user may have several clients).
+type HostChatClient struct {
+ ID uint64 `json:"id"`
+ UserID string `json:"userId,omitempty"`
+ DisplayName string `json:"displayName,omitempty"`
+ ConnectedAt string `json:"connectedAt,omitempty"`
+ UserAgent string `json:"userAgent,omitempty"`
+ IPAddress string `json:"ipAddress,omitempty"`
+ MessageCount int `json:"messageCount"`
+}
+
+// UploadResult is what storage.upload returns to the plugin.
+type UploadResult struct {
+ URL string `json:"url"`
+}
+
+// HostEnv is everything host functions need to do their job. Function-pointer
+// fields are wired by the host (the production Owncast binary, the demo
+// binary, or the test runner); each host function reads them lazily at call
+// time so that fields wired post-load (Emit) work correctly.
+type HostEnv struct {
+ KV kv.Store
+ OnChat func(ChatSendRequest)
+ Emit func(ctx context.Context, eventType string, payload any)
+ StreamCurrent func() StreamInfo
+ ServerInfo func() ServerInfo
+ Broadcaster func() StreamBroadcaster // server.read (read-only telemetry)
+ Tags func() []string // server.read
+ VideoConfig func() VideoConfig // videoconfig.read
+ ChatHistory func(limit int) []HostChatMessage
+ ChatClients func() []HostChatClient // chat.history
+ DeleteMessage func(pluginName, messageID string) // chat.moderate
+ KickClient func(pluginName string, clientID uint64) // chat.moderate
+ SendDiscord func(pluginName, text string) // notifications.send
+ SendBrowserPush func(pluginName string, p BrowserPushPayload)
+ Users func() []HostUser // users.read
+ UserGet func(id string) (HostUser, bool) // users.read
+ SetUserEnabled func(pluginName, userID string, enabled bool, reason string) // users.moderate
+ BanIP func(pluginName, ip string) // users.moderate
+ UploadStorage func(pluginName, name string, data []byte) (string, error) // storage.upload
+ Socials func() []SocialHandle // server.read
+ Federation func() FederationInfo // server.read
+ // WriteVideoConfig applies a partial video/transcoding configuration
+ // change. Returns an error the plugin can see if the host rejects the
+ // config (e.g. an invalid variant). videoconfig.write permission required.
+ WriteVideoConfig func(pluginName string, u VideoConfigUpdate) error
+ SendFediverse func(pluginName string, p FediversePayload) // notifications.send
+ SendChatTo func(pluginName string, clientID uint64, text string) // chat.send
+ // PostFediverse publishes a public, text-only note to the fediverse
+ // on the streamer's behalf. Returns the resulting post URL. The host is
+ // responsible for rate-limiting (max 5/hour per plugin by default) and
+ // for honoring the admin's "disable plugin fediverse posting" toggle.
+ // fediverse.post permission required.
+ PostFediverse func(pluginName, text string) (url string, err error)
+ // IsAuthenticated is forwarded to plugin.Server (which uses it both to
+ // gate admin paths and to populate req.authenticated). Optional; nil
+ // means "no auth available" — admin paths always return 401.
+ IsAuthenticated func(r *http.Request) bool
+ // GetRequestUser returns the User the request came from when the request
+ // carries a user-token (not admin Basic Auth). Plugins see this in
+ // req.user. Optional; nil → req.user is always omitted.
+ GetRequestUser func(r *http.Request) *HostUser
+ // SSE fans plugin-published events out to browser clients connected to
+ // the plugin's host-owned event stream. The plugin only publishes (via
+ // the owncast_sse_send host function, gated by http.sse); the host owns
+ // the long-lived connections. Optional; nil → owncast.sse.send is a
+ // no-op even if the plugin declared http.sse.
+ SSE *SSEHub
+}
+
+// BuildHostFunctions returns the list of extism host functions a single
+// plugin should be granted, based on its declared permissions. A plugin
+// only sees imports for permissions it declared; importing anything else
+// will fail to link at instantiation time.
+func BuildHostFunctions(env *HostEnv, manifest *Manifest) []extism.HostFunction {
+ var fns []extism.HostFunction
+ granted := stringSet(manifest.Permissions)
+
+ if granted[PermStorageKV] {
+ ns := env.KV.Namespace(manifest.Slug)
+ fns = append(fns, hostKVGet(ns), hostKVSet(ns))
+ }
+ if granted[PermChatSend] {
+ // Chat send fns capture both slug and chat display name in
+ // their closure: slug routes to the right bot user, display
+ // name is what chat viewers see.
+ chatDisplay := manifest.ChatDisplayName()
+ fns = append(fns,
+ hostSendChat(env.OnChat, manifest.Slug, chatDisplay),
+ hostSendChatAction(env.OnChat, manifest.Slug, chatDisplay),
+ hostSendChatSystem(env.OnChat, manifest.Slug, chatDisplay),
+ hostSendChatTo(env, manifest.Slug),
+ )
+ }
+ if granted[PermEmitEvent] {
+ fns = append(fns, hostEmitEvent(env, manifest.Slug))
+ }
+ if granted[PermServerRead] {
+ fns = append(fns,
+ hostStreamCurrent(env),
+ hostServerInfo(env),
+ hostServerSocials(env),
+ hostServerFederation(env),
+ hostStreamBroadcaster(env),
+ hostServerTags(env),
+ )
+ }
+ if granted[PermChatHistory] {
+ fns = append(fns, hostChatHistory(env))
+ }
+ if granted[PermChatModerate] {
+ fns = append(fns,
+ hostDeleteMessage(env, manifest.Slug),
+ hostKickClient(env, manifest.Slug),
+ )
+ }
+ if granted[PermNotificationsSend] {
+ fns = append(fns,
+ hostSendDiscord(env, manifest.Slug),
+ hostSendBrowserPush(env, manifest.Slug),
+ hostSendFediverse(env, manifest.Slug),
+ )
+ }
+ if granted[PermChatHistory] {
+ fns = append(fns, hostChatClients(env))
+ }
+ if granted[PermUsersRead] {
+ fns = append(fns, hostUsersList(env), hostUserGet(env))
+ }
+ if granted[PermUsersModerate] {
+ fns = append(fns,
+ hostUserSetEnabled(env, manifest.Slug),
+ hostBanIP(env, manifest.Slug),
+ )
+ }
+ if granted[PermStorageUpload] {
+ fns = append(fns, hostStorageUpload(env, manifest.Slug))
+ }
+ if granted[PermFediversePost] {
+ fns = append(fns, hostFediversePost(env, manifest.Slug))
+ }
+ if granted[PermHttpSSE] {
+ fns = append(fns, hostSSESend(env, manifest.Slug))
+ }
+ if granted[PermUIModify] {
+ fns = append(fns,
+ hostAddActions(env, manifest),
+ hostClearActions(env, manifest.Slug),
+ )
+ }
+ fns = append(fns, videoConfigHostFunctions(env, manifest, granted)...)
+ return fns
+}
+
+// videoConfigHostFunctions returns the videoconfig.read / videoconfig.write
+// host functions a plugin is granted. Split out of BuildHostFunctions to keep
+// that function's cyclomatic complexity in check.
+func videoConfigHostFunctions(env *HostEnv, manifest *Manifest, granted map[string]bool) []extism.HostFunction {
+ var fns []extism.HostFunction
+ if granted[PermVideoConfigRead] {
+ fns = append(fns, hostVideoConfigRead(env))
+ }
+ if granted[PermVideoConfigWrite] {
+ fns = append(fns, hostVideoConfigWrite(env, manifest.Slug))
+ }
+ return fns
+}
+
+// hostSSESend backs owncast.sse.send(channel, event, data). It publishes a
+// single Server-Sent-Event to every browser currently connected to this
+// plugin's <channel> stream. Fire-and-forget: the call returns as soon as
+// the frame is queued to each client, so it never blocks the plugin on a
+// slow browser. Requires the http.sse permission.
+func hostSSESend(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_sse_send",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ channel, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ event, err := p.ReadString(stack[1])
+ if err != nil {
+ return
+ }
+ data, err := p.ReadBytes(stack[2])
+ if err != nil {
+ return
+ }
+ if env.SSE == nil {
+ return
+ }
+ env.SSE.Publish(pluginName, channel, event, data)
+ },
+ []extism.ValueType{extism.ValueTypePTR, extism.ValueTypePTR, extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostFediversePost(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_fediverse_post",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ text, err := p.ReadString(stack[0])
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ if env.PostFediverse == nil {
+ stack[0] = 0
+ return
+ }
+ url, err := env.PostFediverse(pluginName, text)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_fediverse_post from %s: %v\n", pluginName, err)
+ stack[0] = 0
+ return
+ }
+ result, err := json.Marshal(map[string]string{"url": url})
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(result)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostChatClients(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_chat_clients",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var clients []HostChatClient
+ if env.ChatClients != nil {
+ clients = env.ChatClients()
+ }
+ if clients == nil {
+ clients = []HostChatClient{}
+ }
+ data, err := json.Marshal(clients)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostUsersList(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_users_list",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var users []HostUser
+ if env.Users != nil {
+ users = env.Users()
+ }
+ if users == nil {
+ users = []HostUser{}
+ }
+ data, err := json.Marshal(users)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostUserGet(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_user_get",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ id, err := p.ReadString(stack[0])
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ if env.UserGet == nil {
+ stack[0] = 0
+ return
+ }
+ user, ok := env.UserGet(id)
+ if !ok {
+ stack[0] = 0
+ return
+ }
+ data, err := json.Marshal(user)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostUserSetEnabled(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_user_set_enabled",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ id, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ enabled := stack[1] != 0
+ reason, _ := p.ReadString(stack[2])
+ if env.SetUserEnabled != nil {
+ env.SetUserEnabled(pluginName, id, enabled, reason)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR, extism.ValueTypeI32, extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostBanIP(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_ban_ip",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ ip, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ if env.BanIP != nil {
+ env.BanIP(pluginName, ip)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostServerSocials(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_server_socials",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var socials []SocialHandle
+ if env.Socials != nil {
+ socials = env.Socials()
+ }
+ if socials == nil {
+ socials = []SocialHandle{}
+ }
+ data, err := json.Marshal(socials)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostServerFederation(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_server_federation",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var info FederationInfo
+ if env.Federation != nil {
+ info = env.Federation()
+ }
+ data, err := json.Marshal(info)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSendFediverse(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_notify_fediverse",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ payloadBytes, err := p.ReadBytes(stack[0])
+ if err != nil {
+ return
+ }
+ var payload FediversePayload
+ if err := json.Unmarshal(payloadBytes, &payload); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_notify_fediverse from %s: invalid JSON: %v\n", pluginName, err)
+ return
+ }
+ if env.SendFediverse != nil {
+ env.SendFediverse(pluginName, payload)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSendChatTo(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_send_chat_to",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ clientID := stack[0]
+ text, err := p.ReadString(stack[1])
+ if err != nil {
+ return
+ }
+ if env.SendChatTo != nil {
+ env.SendChatTo(pluginName, clientID, text)
+ }
+ },
+ []extism.ValueType{extism.ValueTypeI64, extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostStorageUpload(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_storage_upload",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ name, err := p.ReadString(stack[0])
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ data, err := p.ReadBytes(stack[1])
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ if env.UploadStorage == nil {
+ stack[0] = 0
+ return
+ }
+ url, err := env.UploadStorage(pluginName, name, data)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_storage_upload from %s: %v\n", pluginName, err)
+ stack[0] = 0
+ return
+ }
+ result, err := json.Marshal(UploadResult{URL: url})
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(result)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{extism.ValueTypePTR, extism.ValueTypePTR},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostDeleteMessage(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_delete_message",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ id, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ if env.DeleteMessage != nil {
+ env.DeleteMessage(pluginName, id)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostKickClient(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_kick_client",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ clientID := stack[0]
+ if env.KickClient != nil {
+ env.KickClient(pluginName, clientID)
+ }
+ },
+ []extism.ValueType{extism.ValueTypeI64},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSendDiscord(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_notify_discord",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ text, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ if env.SendDiscord != nil {
+ env.SendDiscord(pluginName, text)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSendBrowserPush(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_notify_browser_push",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ payloadBytes, err := p.ReadBytes(stack[0])
+ if err != nil {
+ return
+ }
+ var payload BrowserPushPayload
+ if err := json.Unmarshal(payloadBytes, &payload); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_notify_browser_push from %s: invalid JSON: %v\n", pluginName, err)
+ return
+ }
+ if env.SendBrowserPush != nil {
+ env.SendBrowserPush(pluginName, payload)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostChatHistory(env *HostEnv) extism.HostFunction {
+ const defaultLimit = 50
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_chat_history",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ limit := int(int32(stack[0])) //nolint:gosec // G115: truncation is intentional; non-positive results fall back to defaultLimit
+ if limit <= 0 {
+ limit = defaultLimit
+ }
+ var msgs []HostChatMessage
+ if env.ChatHistory != nil {
+ msgs = env.ChatHistory(limit)
+ }
+ if msgs == nil {
+ msgs = []HostChatMessage{}
+ }
+ data, err := json.Marshal(msgs)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{extism.ValueTypeI32},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostEmitEvent(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_emit_event",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ eventType, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ payloadBytes, err := p.ReadBytes(stack[1])
+ if err != nil {
+ return
+ }
+ var payload any
+ if len(payloadBytes) > 0 {
+ if err := json.Unmarshal(payloadBytes, &payload); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_emit_event from %s: invalid JSON payload: %v\n", pluginName, err)
+ return
+ }
+ }
+ if env.Emit == nil {
+ return
+ }
+ env.Emit(ctx, eventType, payload)
+ },
+ []extism.ValueType{extism.ValueTypePTR, extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSendChat(sink func(ChatSendRequest), pluginSlug, botDisplayName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_send_chat",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ text, err := p.ReadString(stack[0])
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_send_chat: read string: %v\n", err)
+ return
+ }
+ if sink != nil {
+ sink(ChatSendRequest{
+ PluginSlug: pluginSlug,
+ BotDisplayName: botDisplayName,
+ Kind: ChatSendBot,
+ Text: text,
+ })
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSendChatSystem(sink func(ChatSendRequest), pluginSlug, botDisplayName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_send_chat_system",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ body, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ if sink != nil {
+ sink(ChatSendRequest{
+ PluginSlug: pluginSlug,
+ BotDisplayName: botDisplayName,
+ Kind: ChatSendSystem,
+ Text: body,
+ })
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostSendChatAction(sink func(ChatSendRequest), pluginSlug, botDisplayName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_send_chat_action",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ text, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ if sink != nil {
+ sink(ChatSendRequest{
+ PluginSlug: pluginSlug,
+ BotDisplayName: botDisplayName,
+ Kind: ChatSendAction,
+ Text: text,
+ })
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostStreamCurrent(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_stream_current",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var info StreamInfo
+ if env.StreamCurrent != nil {
+ info = env.StreamCurrent()
+ }
+ data, err := json.Marshal(info)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostServerInfo(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_server_info",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var info ServerInfo
+ if env.ServerInfo != nil {
+ info = env.ServerInfo()
+ }
+ data, err := json.Marshal(info)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostStreamBroadcaster(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_stream_broadcaster",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var info StreamBroadcaster
+ if env.Broadcaster != nil {
+ info = env.Broadcaster()
+ }
+ data, err := json.Marshal(info)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostServerTags(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_server_tags",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var tags []string
+ if env.Tags != nil {
+ tags = env.Tags()
+ }
+ if tags == nil {
+ tags = []string{}
+ }
+ data, err := json.Marshal(tags)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostVideoConfigRead(env *HostEnv) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_video_config_read",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ var cfg VideoConfig
+ if env.VideoConfig != nil {
+ cfg = env.VideoConfig()
+ }
+ if cfg.Variants == nil {
+ cfg.Variants = []StreamVariant{}
+ }
+ data, err := json.Marshal(cfg)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+// hostVideoConfigWrite backs owncast.videoConfig.write(config). It applies a
+// partial video/transcoding configuration change via the host. Returns a
+// JSON {ok, error?} result so the plugin can react to a rejected config.
+// Requires the videoconfig.write permission.
+func hostVideoConfigWrite(env *HostEnv, pluginName string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_video_config_write",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ payloadBytes, err := p.ReadBytes(stack[0])
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ var update VideoConfigUpdate
+ if err := json.Unmarshal(payloadBytes, &update); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_video_config_write from %s: invalid JSON: %v\n", pluginName, err)
+ stack[0] = 0
+ return
+ }
+ result := map[string]any{"ok": true}
+ if env.WriteVideoConfig != nil {
+ if err := env.WriteVideoConfig(pluginName, update); err != nil {
+ result = map[string]any{"ok": false, "error": err.Error()}
+ }
+ }
+ data, err := json.Marshal(result)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(data)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostKVGet(ns kv.Namespace) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_kv_get",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ key, err := p.ReadString(stack[0])
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ val, err := ns.Get(key)
+ if err != nil || val == nil {
+ stack[0] = 0
+ return
+ }
+ offset, err := p.WriteBytes(val)
+ if err != nil {
+ stack[0] = 0
+ return
+ }
+ stack[0] = offset
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{extism.ValueTypePTR},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+func hostKVSet(ns kv.Namespace) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_kv_set",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ key, err := p.ReadString(stack[0])
+ if err != nil {
+ return
+ }
+ val, err := p.ReadBytes(stack[1])
+ if err != nil {
+ return
+ }
+ if err := ns.Set(key, val); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_kv_set: %v\n", err)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR, extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+// 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 plugin host reads this key on
+// every /api/config request and returns manifest.actions ++ this list
+// to viewers.
+const RuntimeActionsConfigKey = "owncast.actions"
+
+// hostAddActions backs owncast.actions.add(actions). Takes a JSON array
+// of ActionButton entries, validates each (title required, exactly one
+// of url/html, relative URLs rewritten into this plugin's namespace,
+// cross-plugin URLs rejected), and appends to the runtime list in the
+// plugin's config.
+//
+// Requires the ui.modify permission; invalid input is logged but not
+// surfaced back to the plugin.
+func hostAddActions(env *HostEnv, manifest *Manifest) extism.HostFunction {
+ pluginSlug := manifest.Slug
+ hasHTTPServe := false
+ for _, perm := range manifest.Permissions {
+ if perm == PermHttpServe {
+ hasHTTPServe = true
+ break
+ }
+ }
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_add_actions",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ payloadBytes, err := p.ReadBytes(stack[0])
+ if err != nil {
+ return
+ }
+ var incoming []ActionButton
+ if err := json.Unmarshal(payloadBytes, &incoming); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: invalid JSON: %v\n", pluginSlug, err)
+ return
+ }
+ normalized, err := validateRuntimeActions(pluginSlug, hasHTTPServe, incoming)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: %v\n", pluginSlug, err)
+ return
+ }
+ if env.KV == nil {
+ return
+ }
+ ns := env.KV.Namespace(pluginSlug)
+ var existing []ActionButton
+ if raw, err := ns.Get(RuntimeActionsConfigKey); err == nil && len(raw) > 0 {
+ _ = json.Unmarshal(raw, &existing)
+ }
+ combined := make([]ActionButton, 0, len(existing)+len(normalized))
+ combined = append(combined, existing...)
+ combined = append(combined, normalized...)
+ out, err := json.Marshal(combined)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: marshal: %v\n", pluginSlug, err)
+ return
+ }
+ if err := ns.Set(RuntimeActionsConfigKey, out); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_add_actions from %s: kv write: %v\n", pluginSlug, err)
+ }
+ },
+ []extism.ValueType{extism.ValueTypePTR},
+ []extism.ValueType{},
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+// hostClearActions backs owncast.actions.clear(). Removes the runtime
+// list from the plugin's config so only manifest.actions remain in the
+// effective set returned by /api/config.
+func hostClearActions(env *HostEnv, pluginSlug string) extism.HostFunction {
+ fn := extism.NewHostFunctionWithStack(
+ "owncast_clear_actions",
+ func(ctx context.Context, p *extism.CurrentPlugin, stack []uint64) {
+ if env.KV == nil {
+ return
+ }
+ if err := env.KV.Namespace(pluginSlug).Delete(RuntimeActionsConfigKey); err != nil {
+ fmt.Fprintf(os.Stderr, "owncast_clear_actions from %s: %v\n", pluginSlug, err)
+ }
+ },
+ nil,
+ nil,
+ )
+ fn.SetNamespace("extism:host/user")
+ return fn
+}
+
+// validateRuntimeActions checks and rewrites plugin-supplied action
+// entries using the same rules as manifest validation, so the runtime
+// path can't accept a malformed entry or a cross-plugin URL.
+func validateRuntimeActions(pluginSlug string, hasHTTPServe bool, actions []ActionButton) ([]ActionButton, error) {
+ pluginPrefix := "/plugins/" + pluginSlug + "/"
+ for i := range actions {
+ a := &actions[i]
+ if a.Title == "" {
+ return nil, fmt.Errorf("actions[%d].title is required", i)
+ }
+ hasURL, hasHTML := a.Url != "", a.Html != ""
+ if hasURL == hasHTML {
+ return nil, fmt.Errorf("actions[%d]: exactly one of url or html is required", i)
+ }
+ if !hasURL {
+ continue
+ }
+ if strings.HasPrefix(a.Url, "/") && !strings.HasPrefix(a.Url, "/plugins/") {
+ a.Url = pluginPrefix + strings.TrimPrefix(a.Url, "/")
+ }
+ if strings.HasPrefix(a.Url, pluginPrefix) && !hasHTTPServe {
+ return nil, fmt.Errorf("actions[%d].url targets this plugin (%s) but http.serve permission is not declared", i, a.Url)
+ }
+ if strings.HasPrefix(a.Url, "/plugins/") && !strings.HasPrefix(a.Url, pluginPrefix) {
+ return nil, fmt.Errorf("actions[%d].url points at another plugin's namespace: %s", i, a.Url)
+ }
+ }
+ for i := range actions {
+ rewritten, err := rewriteActionIcon(pluginPrefix, hasHTTPServe, actions[i].Icon)
+ if err != nil {
+ return nil, fmt.Errorf("actions[%d].icon: %w", i, err)
+ }
+ actions[i].Icon = rewritten
+ }
+ return actions, nil
+}
diff --git a/services/plugins/kv/kv_test.go b/services/plugins/kv/kv_test.go
new file mode 100644
index 0000000000..1330c58e57
--- /dev/null
+++ b/services/plugins/kv/kv_test.go
@@ -0,0 +1,147 @@
+package kv
+
+import (
+ "bytes"
+ "sync"
+ "testing"
+)
+
+// The in-memory implementation must satisfy the Store interface contract.
+// Host-provided backends (e.g. Owncast's datastore-backed store) are tested
+// in their own package against the same behaviors.
+func TestStoreContract(t *testing.T) {
+ t.Run("memory", func(t *testing.T) {
+ runStoreSuite(t, func() (Store, func()) {
+ return NewMemory(), func() {}
+ })
+ })
+}
+
+func runStoreSuite(t *testing.T, openStore func() (Store, func())) {
+ t.Helper()
+
+ t.Run("get missing returns nil", func(t *testing.T) {
+ s, cleanup := openStore()
+ defer cleanup()
+ ns := s.Namespace("p1")
+ got, err := ns.Get("missing")
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if got != nil {
+ t.Errorf("expected nil, got %q", got)
+ }
+ })
+
+ t.Run("set then get round-trip", func(t *testing.T) {
+ s, cleanup := openStore()
+ defer cleanup()
+ ns := s.Namespace("p1")
+ if err := ns.Set("k", []byte("hello")); err != nil {
+ t.Fatalf("set: %v", err)
+ }
+ got, err := ns.Get("k")
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if !bytes.Equal(got, []byte("hello")) {
+ t.Errorf("get returned %q, want %q", got, "hello")
+ }
+ })
+
+ t.Run("overwrite", func(t *testing.T) {
+ s, cleanup := openStore()
+ defer cleanup()
+ ns := s.Namespace("p1")
+ ns.Set("k", []byte("first"))
+ ns.Set("k", []byte("second"))
+ got, _ := ns.Get("k")
+ if !bytes.Equal(got, []byte("second")) {
+ t.Errorf("overwrite failed: got %q want %q", got, "second")
+ }
+ })
+
+ t.Run("delete", func(t *testing.T) {
+ s, cleanup := openStore()
+ defer cleanup()
+ ns := s.Namespace("p1")
+ ns.Set("k", []byte("v"))
+ if err := ns.Delete("k"); err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ got, _ := ns.Get("k")
+ if got != nil {
+ t.Errorf("after delete, got %q want nil", got)
+ }
+ })
+
+ t.Run("delete missing is no-op", func(t *testing.T) {
+ s, cleanup := openStore()
+ defer cleanup()
+ ns := s.Namespace("p1")
+ if err := ns.Delete("never-set"); err != nil {
+ t.Errorf("delete on missing should be no-op, got: %v", err)
+ }
+ })
+
+ t.Run("namespaces are isolated", func(t *testing.T) {
+ s, cleanup := openStore()
+ defer cleanup()
+ a := s.Namespace("plugin-a")
+ b := s.Namespace("plugin-b")
+ a.Set("shared-key", []byte("a-value"))
+ b.Set("shared-key", []byte("b-value"))
+
+ gotA, _ := a.Get("shared-key")
+ gotB, _ := b.Get("shared-key")
+ if !bytes.Equal(gotA, []byte("a-value")) {
+ t.Errorf("plugin-a got %q want %q", gotA, "a-value")
+ }
+ if !bytes.Equal(gotB, []byte("b-value")) {
+ t.Errorf("plugin-b got %q want %q", gotB, "b-value")
+ }
+
+ // Delete in A must not affect B.
+ a.Delete("shared-key")
+ gotA2, _ := a.Get("shared-key")
+ gotB2, _ := b.Get("shared-key")
+ if gotA2 != nil {
+ t.Errorf("plugin-a after delete: got %q want nil", gotA2)
+ }
+ if !bytes.Equal(gotB2, []byte("b-value")) {
+ t.Errorf("plugin-b after a's delete: got %q want %q", gotB2, "b-value")
+ }
+ })
+
+ t.Run("returned bytes are owned by caller", func(t *testing.T) {
+ // Mutating the returned slice must not corrupt the store.
+ s, cleanup := openStore()
+ defer cleanup()
+ ns := s.Namespace("p1")
+ ns.Set("k", []byte("hello"))
+ got, _ := ns.Get("k")
+ for i := range got {
+ got[i] = 'X'
+ }
+ again, _ := ns.Get("k")
+ if !bytes.Equal(again, []byte("hello")) {
+ t.Errorf("mutating returned slice corrupted store: got %q", again)
+ }
+ })
+}
+
+func TestMemory_ConcurrentAccess(t *testing.T) {
+ // Smoke test for the mutex — race detector should catch issues.
+ s := NewMemory()
+ ns := s.Namespace("p1")
+ var wg sync.WaitGroup
+ for i := 0; i < 50; i++ {
+ wg.Add(1)
+ go func(i int) {
+ defer wg.Done()
+ ns.Set("k", []byte("v"))
+ ns.Get("k")
+ }(i)
+ }
+ wg.Wait()
+}
diff --git a/services/plugins/kv/memory.go b/services/plugins/kv/memory.go
new file mode 100644
index 0000000000..015fdd9d74
--- /dev/null
+++ b/services/plugins/kv/memory.go
@@ -0,0 +1,74 @@
+package kv
+
+import "sync"
+
+// NewMemory returns an in-memory Store. Used by the test runner so each
+// scenario gets fresh state without touching disk.
+func NewMemory() Store {
+ return &memoryStore{namespaces: map[string]*memoryNamespace{}}
+}
+
+type memoryStore struct {
+ mu sync.Mutex
+ namespaces map[string]*memoryNamespace
+}
+
+func (s *memoryStore) Close() error { return nil }
+
+func (s *memoryStore) Namespace(plugin string) Namespace {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ ns, ok := s.namespaces[plugin]
+ if !ok {
+ ns = &memoryNamespace{data: map[string][]byte{}}
+ s.namespaces[plugin] = ns
+ }
+ return ns
+}
+
+type memoryNamespace struct {
+ mu sync.Mutex
+ data map[string][]byte
+}
+
+func (n *memoryNamespace) Get(key string) ([]byte, error) {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ v, ok := n.data[key]
+ if !ok {
+ return nil, nil
+ }
+ out := make([]byte, len(v))
+ copy(out, v)
+ return out, nil
+}
+
+func (n *memoryNamespace) Set(key string, value []byte) error {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ cp := make([]byte, len(value))
+ copy(cp, value)
+ n.data[key] = cp
+ return nil
+}
+
+func (n *memoryNamespace) Delete(key string) error {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ delete(n.data, key)
+ return nil
+}
+
+// Snapshot returns a copy of all data in the namespace. Useful for tests
+// that want to assert on final KV state.
+func (n *memoryNamespace) Snapshot() map[string][]byte {
+ n.mu.Lock()
+ defer n.mu.Unlock()
+ out := make(map[string][]byte, len(n.data))
+ for k, v := range n.data {
+ cp := make([]byte, len(v))
+ copy(cp, v)
+ out[k] = cp
+ }
+ return out
+}
diff --git a/services/plugins/kv/store.go b/services/plugins/kv/store.go
new file mode 100644
index 0000000000..cb872a3dd1
--- /dev/null
+++ b/services/plugins/kv/store.go
@@ -0,0 +1,20 @@
+// Package kv is a namespaced key/value store. Each plugin gets its own
+// namespace so plugins cannot read or overwrite each other's keys.
+//
+// NewMemory provides an in-memory implementation for tests. The host
+// supplies the production backend by implementing Store — Owncast backs it
+// with its native config datastore.
+package kv
+
+type Store interface {
+ // Namespace returns a handle scoped to a single plugin name. Calls on the
+ // returned handle only see keys within that plugin's namespace.
+ Namespace(plugin string) Namespace
+ Close() error
+}
+
+type Namespace interface {
+ Get(key string) ([]byte, error)
+ Set(key string, value []byte) error
+ Delete(key string) error
+}
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
new file mode 100644
index 0000000000..af44d8bbbd
--- /dev/null
+++ b/services/plugins/manager.go
@@ -0,0 +1,1336 @@
+package plugins
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ extism "github.com/extism/go-sdk"
+ "github.com/gobwas/glob"
+ log "github.com/sirupsen/logrus"
+)
+
+// Loaded represents a successfully-loaded plugin. The sidecar manifest is the
+// source of truth for identity and permissions; subscriptions are populated
+// from the runtime register() call (the SDK derives them from the plugin's
+// handlers, so authors don't maintain a duplicate list).
+//
+// Extism plugin instances are not safe for concurrent calls. The mutex
+// serializes calls to a single plugin while still allowing different plugins
+// to run in parallel.
+//
+// PublicFS is the web-served file root for this plugin at
+// /plugins/<slug>/<file>, or nil when the plugin ships nothing under
+// public/. Populated from a `public/` directory in the .ocpkg (or a
+// <name>-public/ sibling for loose-files plugins). plugin.Server reads
+// through this interface.
+//
+// AssetsFS is the internal-only file root the host reads for manifest
+// fields that inline file contents (styles, scripts, extraPageContent),
+// or nil when the plugin ships nothing under assets/. Files under
+// assets/ are never reachable through the plugin's URL space; authors
+// can therefore put source CSS/JS/HTML the host inlines into
+// /api/config or /customjavascript without the same files also being
+// downloadable directly. Populated from an `assets/` directory in the
+// .ocpkg (or a <name>-assets/ sibling for loose-files plugins).
+type Loaded struct {
+ Manifest *Manifest
+ WasmPath string
+ PublicFS fs.FS
+ AssetsFS fs.FS
+ adminGlobs []glob.Glob // compiled from manifest.admin.pages[].path
+ adminPaths []string // original path strings, used for "page gates descendants" prefix-matching
+ plugin *extism.Plugin
+ mu sync.Mutex
+ failureMu sync.Mutex
+ filterFails int
+ disabled atomic.Bool
+ // pkgCloser holds the file-backed zip reader for .ocpkg plugins so the
+ // underlying file stays open for PublicFS / AssetsFS reads. nil for
+ // loose-files plugins. Closed by Loaded.Close.
+ pkgCloser io.Closer
+}
+
+// FilterStrikeThreshold is the number of consecutive filter failures a
+// plugin can rack up before the dispatcher auto-disables it for the rest
+// of the session. The fail-open semantics still apply on the path to the
+// strike — events flow normally; the strike just prevents the host from
+// drowning in log noise from a permanently-broken plugin.
+const FilterStrikeThreshold = 5
+
+// Sandbox caps. A misbehaving plugin should fail its own call; the host
+// stays up. These are deliberately generous — realistic plugins won't
+// come close. Per-plugin manifest overrides are a future TODO.
+const (
+ // MaxWasmPages caps a plugin's wasm linear memory. 1 page = 64 KiB,
+ // so 1024 = 64 MiB. QuickJS itself takes a few MB; this leaves
+ // comfortable room for plugin state.
+ MaxWasmPages = 1024
+
+ // MaxExtismHTTPResponseBytes caps the body of any outbound HTTP
+ // request extism's built-in http_request makes on the plugin's
+ // behalf. Matches the inbound HTTP response cap.
+ MaxExtismHTTPResponseBytes = 10 << 20 // 10 MiB
+
+ // MaxExtismVarBytes caps extism's internal per-plugin Var KV (a
+ // separate store from our owncast.kv namespace). We don't expose
+ // it but defense in depth.
+ MaxExtismVarBytes = 1 << 20 // 1 MiB
+
+ // MaxRegisterOutputBytes caps the JSON the SDK emits from register().
+ // In practice this is a kilobyte or two (manifest echo) — the cap is
+ // just to prevent a buggy or malicious plugin from causing a huge
+ // allocation at load time.
+ MaxRegisterOutputBytes = 256 << 10 // 256 KiB
+
+ // MaxFilterOutputBytes caps the JSON a plugin's on_filter returns.
+ // Filter results carry the (possibly modified) event payload —
+ // chat messages, etc. — which are small in any realistic case.
+ MaxFilterOutputBytes = 1 << 20 // 1 MiB
+
+ // MaxHTTPHandlerOutputBytes caps the JSON envelope a plugin returns
+ // from on_http_request (status + headers + body). Sized to leave
+ // headroom over MaxHTTPResponseBodyBytes (server.go); the inner body
+ // is then checked again post-unmarshal.
+ MaxHTTPHandlerOutputBytes = 12 << 20 // 12 MiB
+
+ // NotifyTimeout caps a single on_event call. Notification handlers
+ // can do real work (kv writes, owncast.* host calls), but they
+ // shouldn't stall — events fire on the chat hot path.
+ NotifyTimeout = 500 * time.Millisecond
+
+ // HTTPHandlerTimeout caps a single on_http_request call. HTTP
+ // handlers may legitimately do work (fetch upstream, compute), so
+ // this is looser than NotifyTimeout but still bounded.
+ HTTPHandlerTimeout = 5 * time.Second
+)
+
+// IsDisabled reports whether the plugin has been auto-disabled by the
+// strike system. Disabled plugins are skipped by both the filter chain
+// and the notification dispatcher.
+func (l *Loaded) IsDisabled() bool {
+ return l.disabled.Load()
+}
+
+func (l *Loaded) recordFilterFailure() bool {
+ l.failureMu.Lock()
+ defer l.failureMu.Unlock()
+ l.filterFails++
+ if l.filterFails >= FilterStrikeThreshold && !l.disabled.Load() {
+ l.disabled.Store(true)
+ return true
+ }
+ return false
+}
+
+func (l *Loaded) recordFilterSuccess() {
+ l.failureMu.Lock()
+ defer l.failureMu.Unlock()
+ l.filterFails = 0
+}
+
+// IsAdminPath reports whether the request path (relative to the plugin's
+// namespace, e.g. "/admin/foo") is gated by one of the declared admin
+// pages. A declared page path gates itself, anything under it as a path
+// prefix (so "/admin" gates "/admin/api/x"), and anything its glob
+// matches (so "/admin/*" still works as it did when authors wrote an
+// explicit wildcard). Used by Server to require authentication on
+// admin-only routes.
+func (l *Loaded) IsAdminPath(path string) bool {
+ for i, g := range l.adminGlobs {
+ if g.Match(path) {
+ return true
+ }
+ // Page paths gate their descendants too, so a declaration of
+ // "/admin" automatically covers "/admin/api/settings" without
+ // the author having to spell out a glob.
+ if lit := l.adminPaths[i]; lit != "" && strings.HasPrefix(path, lit+"/") {
+ return true
+ }
+ }
+ return false
+}
+
+// Close releases the underlying wasm instance and any retained file handles
+// (the .ocpkg zip reader for packaged plugins). Safe to call multiple times.
+func (l *Loaded) Close(ctx context.Context) {
+ if l.plugin != nil {
+ _ = l.plugin.Close(ctx)
+ l.plugin = nil
+ }
+ if l.pkgCloser != nil {
+ _ = l.pkgCloser.Close()
+ l.pkgCloser = nil
+ }
+}
+
+// Manager tracks plugins across two states:
+//
+// - Discovered: a file in the plugins directory whose manifest parsed
+// successfully. The host knows it exists and can show it to an admin.
+// No wasm instance, no events delivered.
+//
+// - Loaded: discovered + an admin has explicitly enabled it. Wasm
+// instantiated, events flow.
+//
+// The enabled set persists via an EnabledStore so admin choices survive
+// host restarts (a JSON file by default; Owncast backs it with native
+// config). Files appearing in the plugins directory are auto-detected (scan
+// every ScanInterval) but never auto-loaded — the admin clicks Enable.
+type Manager struct {
+ pluginsDir string
+ enabledStore EnabledStore
+ env *HostEnv
+
+ mu sync.RWMutex
+ discovered map[string]*DiscoveredEntry // keyed by manifest.name
+ loaded map[string]*Loaded // subset of discovered that's currently running
+ enabledSet map[string]bool // names the admin has enabled
+ approvedSet map[string][]string // plugin name -> sorted approved permission set
+
+ scanInterval time.Duration
+ cancel context.CancelFunc // stops the scan loop
+ scanCh chan struct{} // pings to force a scan (testing / admin trigger)
+}
+
+// DiscoveredEntry is the public view of a discovered plugin: what the
+// admin UI lists, and what the registry's install endpoint returns
+// to the host. Two name-like fields:
+//
+// - Slug is the canonical identifier (URL segment, KV namespace,
+// file path, registry primary key). Stable, lowercase, hyphenated.
+// - DisplayName is the human-readable name the admin sees in lists.
+// Set by the plugin author; can contain any characters.
+//
+// BotDisplayName, when non-empty, overrides DisplayName as the chat
+// identity for plugins that post to chat. Empty means "use
+// DisplayName" (resolved at chat-send time, not here).
+type DiscoveredEntry struct {
+ Slug string `json:"slug"`
+ DisplayName string `json:"name"`
+ BotDisplayName string `json:"botDisplayName,omitempty"`
+ Version string `json:"version,omitempty"`
+ Description string `json:"description,omitempty"`
+ Permissions []string `json:"permissions,omitempty"`
+ Path string `json:"path"`
+ Enabled bool `json:"enabled"`
+ Loaded bool `json:"loaded"`
+ // AutoDisabled is set when the dispatcher's strike system stopped
+ // invoking the plugin (too many consecutive filter failures).
+ // Enabled stays true so the admin can see what they originally chose,
+ // but the plugin isn't doing any work; reload or fix-and-rebuild to
+ // reset the strike counter.
+ AutoDisabled bool `json:"autoDisabled,omitempty"`
+ // HasIcon reports whether the plugin ships an icon.png alongside its
+ // manifest (top-level in the .ocpkg, or <base>.icon.png next to a
+ // loose .wasm). The admin UI fetches the bytes from
+ // /api/plugins/<name>/icon when this is true; no http.serve
+ // permission is required to ship one.
+ HasIcon bool `json:"hasIcon,omitempty"`
+ // HasInstructions reports whether the plugin ships an INSTRUCTIONS.md
+ // alongside its manifest (top-level in the .ocpkg, or
+ // <base>.INSTRUCTIONS.md next to a loose .wasm). The admin UI fetches
+ // the markdown from /api/admin/plugins/<name>/instructions when this is
+ // true and renders it in a details tab; no permission is required to
+ // ship one.
+ HasInstructions bool `json:"hasInstructions,omitempty"`
+ // PendingPermissions lists permissions the current manifest declares
+ // that the admin has not yet approved. Non-empty means the plugin was
+ // updated on disk to request more access than was originally granted;
+ // the plugin will not load until the admin re-enables it (which
+ // captures a fresh approval snapshot covering the new set).
+ PendingPermissions []string `json:"pendingPermissions,omitempty"`
+ // AllowedHosts mirrors manifest.network.allowedHosts so the admin
+ // UI can show the host scope alongside the network.fetch
+ // permission entry. Empty for plugins that don't request
+ // network.fetch; the host's load-time validator rejects
+ // network.fetch without an entry, so a present permission
+ // without a non-empty list never occurs.
+ AllowedHosts []string `json:"allowedHosts,omitempty"`
+ LastError string `json:"lastError,omitempty"`
+ DiscoveredAt time.Time `json:"discoveredAt"`
+ AdminPages []AdminPage `json:"adminPages,omitempty"`
+}
+
+// ScanInterval is how often the manager re-scans the plugins directory.
+const ScanInterval = 2 * time.Second
+
+// NewManager constructs a Manager that persists its enabled set to a
+// .enabled.json file in pluginsDir. Owncast wires NewManagerWithStore
+// instead, backing the enabled set with native config storage.
+func NewManager(pluginsDir string, env *HostEnv) *Manager {
+ store := newFileEnabledStore(filepath.Join(pluginsDir, ".enabled.json"))
+ return NewManagerWithStore(pluginsDir, env, store)
+}
+
+// NewManagerWithStore is NewManager with an explicit EnabledStore, letting
+// the host persist the enabled set wherever it likes (e.g. Owncast's config
+// datastore) instead of a JSON file in the plugins directory.
+func NewManagerWithStore(pluginsDir string, env *HostEnv, store EnabledStore) *Manager {
+ return &Manager{
+ pluginsDir: pluginsDir,
+ enabledStore: store,
+ env: env,
+ discovered: make(map[string]*DiscoveredEntry),
+ loaded: make(map[string]*Loaded),
+ enabledSet: make(map[string]bool),
+ approvedSet: make(map[string][]string),
+ scanInterval: ScanInterval,
+ scanCh: make(chan struct{}, 1),
+ }
+}
+
+// Start does the initial scan, loads everything in the enabled set, and
+// begins a background scan loop. Stop() cancels the loop.
+func (m *Manager) Start(ctx context.Context) error {
+ if err := m.loadEnabledSet(); err != nil {
+ return fmt.Errorf("load enabled set: %w", err)
+ }
+ if err := m.scan(ctx); err != nil {
+ return fmt.Errorf("initial scan: %w", err)
+ }
+ // Capture an approval baseline for any plugin enabled before the
+ // approved-permissions snapshot existed (older persisted state, or a
+ // fresh first run that pre-seeded enabled names). Without this,
+ // existing installs would see every permission as "pending" and the
+ // plugin would auto-disable on the next start.
+ if m.captureMissingApprovals() {
+ if err := m.saveEnabledSet(); err != nil {
+ fmt.Fprintf(os.Stderr, "persist enabled set: %v\n", err)
+ }
+ }
+ // Auto-load anything in the enabled set that isn't already loaded
+ // AND whose approved-permission set covers the current manifest.
+ // Every reason a load doesn't complete is surfaced both in the
+ // server log (so an operator inspecting `journalctl` sees it) and
+ // in the DiscoveredEntry's LastError (so the admin UI's plugin
+ // list shows a non-empty status hint). Without that, the entry
+ // sits at "enabled, not loaded" with no indication of why.
+ for name, enabled := range m.enabledSet {
+ if !enabled {
+ continue
+ }
+ if pending := m.pendingForLocked(name); len(pending) > 0 {
+ log.Warnf("plugin %s: not loaded at startup; declares unapproved permissions %s; admin needs to re-approve in the plugin's detail view",
+ name, strings.Join(pending, ", "))
+ m.mu.Lock()
+ if d, ok := m.discovered[name]; ok {
+ d.PendingPermissions = pending
+ d.LastError = "permissions need admin approval; re-enable from the plugin's detail view"
+ }
+ m.mu.Unlock()
+ continue
+ }
+ if err := m.loadInternal(ctx, name); err != nil {
+ log.Warnf("plugin %s: load failed at startup: %v", name, err)
+ // loadInternal already set LastError on the entry; the
+ // log line above adds the operator-visible trail.
+ continue
+ }
+ if _, loaded := m.loaded[name]; !loaded {
+ // Defensive: loadInternal returned nil but the plugin
+ // didn't land in m.loaded. Shouldn't happen, but if it
+ // ever does, the admin UI's "enabled, not loaded" entry
+ // gets a non-empty LastError so the bug surfaces.
+ log.Warnf("plugin %s: load returned no error but plugin is not in the loaded set", name)
+ m.mu.Lock()
+ if d, ok := m.discovered[name]; ok {
+ d.LastError = "internal: load returned no error but plugin failed to register; check the server log"
+ }
+ m.mu.Unlock()
+ }
+ }
+ scanCtx, cancel := context.WithCancel(ctx)
+ m.cancel = cancel
+ go m.scanLoop(scanCtx)
+ return nil
+}
+
+// Stop cancels the scan loop and closes all loaded plugins.
+func (m *Manager) Stop(ctx context.Context) {
+ if m.cancel != nil {
+ m.cancel()
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, l := range m.loaded {
+ l.Close(ctx)
+ }
+ m.loaded = map[string]*Loaded{}
+}
+
+// List returns a snapshot of all discovered plugins for admin UI.
+func (m *Manager) List() []DiscoveredEntry {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ out := make([]DiscoveredEntry, 0, len(m.discovered))
+ for name, d := range m.discovered {
+ entry := *d
+ entry.Enabled = m.enabledSet[name]
+ l, isLoaded := m.loaded[name]
+ entry.Loaded = isLoaded
+ if isLoaded {
+ entry.AutoDisabled = l.IsDisabled()
+ }
+ out = append(out, entry)
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Slug < out[j].Slug })
+ return out
+}
+
+// Snapshot returns the currently-loaded plugins. Dispatcher and Server call
+// this on every operation so changes from Enable/Disable take effect
+// without restarting anything.
+func (m *Manager) Snapshot() []*Loaded {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ out := make([]*Loaded, 0, len(m.loaded))
+ for _, l := range m.loaded {
+ out = append(out, l)
+ }
+ return out
+}
+
+// Enable marks a discovered plugin as enabled, captures the current
+// manifest's permission set as the approved baseline (so any later
+// expansion triggers a re-approval flow), persists the choice, and
+// loads the plugin. No-op if already loaded.
+func (m *Manager) Enable(ctx context.Context, name string) error {
+ m.mu.Lock()
+ d, ok := m.discovered[name]
+ if !ok {
+ m.mu.Unlock()
+ return fmt.Errorf("plugin %q not discovered", name)
+ }
+ if m.enabledSet[name] {
+ // Already enabled in the persisted set; just make sure it's loaded.
+ if _, ok := m.loaded[name]; ok {
+ m.mu.Unlock()
+ return nil
+ }
+ }
+ m.enabledSet[name] = true
+ snapshot := append([]string(nil), d.Permissions...)
+ sort.Strings(snapshot)
+ m.approvedSet[name] = snapshot
+ d.PendingPermissions = nil
+ m.mu.Unlock()
+ if err := m.saveEnabledSet(); err != nil {
+ return fmt.Errorf("persist enabled set: %w", err)
+ }
+ err := m.loadInternal(ctx, name)
+ return err
+}
+
+// validateUploadedPackage checks an uploaded .ocpkg's bytes and returns
+// its manifest. Pulled out of Install so the validation steps and the
+// (lock + write + scan) plumbing don't combine into one long function.
+func validateUploadedPackage(packageBytes []byte) (*Manifest, error) {
+ if len(packageBytes) == 0 {
+ return nil, fmt.Errorf("upload is empty")
+ }
+ if len(packageBytes) > MaxUploadBytes {
+ return nil, fmt.Errorf("upload exceeds %d-byte cap", MaxUploadBytes)
+ }
+ zr, err := zip.NewReader(bytes.NewReader(packageBytes), int64(len(packageBytes)))
+ if err != nil {
+ return nil, fmt.Errorf("not a valid .ocpkg: %w", err)
+ }
+ manifestBytes, err := readZipFile(zr, pkgManifestFilename)
+ if err != nil {
+ return nil, fmt.Errorf("missing manifest: %w", err)
+ }
+ if _, err := readZipFile(zr, pkgWasmFilename); err != nil {
+ return nil, fmt.Errorf("missing compiled plugin: %w", err)
+ }
+ manifest, err := ParseManifest(manifestBytes)
+ if err != nil {
+ return nil, fmt.Errorf("invalid manifest: %w", err)
+ }
+ return manifest, nil
+}
+
+// destPathForInstall picks the on-disk path for an installed plugin.
+// Prefers an existing discovered entry's path so an update replaces the
+// same file even if the previous file was named non-canonically;
+// otherwise falls back to <pluginsDir>/<name>.ocpkg.
+func (m *Manager) destPathForInstall(name string) string {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ if existing, ok := m.discovered[name]; ok && strings.HasSuffix(existing.Path, packageSuffix) {
+ return existing.Path
+ }
+ return filepath.Join(m.pluginsDir, name+packageSuffix)
+}
+
+// atomicWritePackage writes packageBytes to destPath via a sibling temp
+// file + rename, so a partial write never leaves a half-baked .ocpkg in
+// the plugins directory for scan to trip over.
+//
+// destPath is computed from the uploaded plugin's manifest.slug
+// (validated by slugPattern at parse time, so no slashes or dots), but
+// the safety isn't visible at the rename site. Re-validating that the
+// resolved destination sits under pluginsDir keeps the property local
+// to this function and defends against a future caller that constructs
+// destPath some other way.
+func atomicWritePackage(pluginsDir, destPath string, packageBytes []byte) error {
+ cleanDir, err := filepath.Abs(filepath.Clean(pluginsDir))
+ if err != nil {
+ return fmt.Errorf("resolve plugins dir: %w", err)
+ }
+ cleanDest, err := filepath.Abs(filepath.Clean(destPath))
+ if err != nil {
+ return fmt.Errorf("resolve install path: %w", err)
+ }
+ if !strings.HasPrefix(cleanDest, cleanDir+string(os.PathSeparator)) {
+ return fmt.Errorf("refusing to install outside plugins dir: %s", destPath)
+ }
+
+ tmpFile, err := os.CreateTemp(pluginsDir, ".upload-*"+packageSuffix)
+ if err != nil {
+ return fmt.Errorf("create temp file: %w", err)
+ }
+ tmpPath := tmpFile.Name()
+ cleanup := tmpPath
+ defer func() {
+ if cleanup != "" {
+ _ = os.Remove(cleanup)
+ }
+ }()
+ if _, err := tmpFile.Write(packageBytes); err != nil {
+ _ = tmpFile.Close()
+ return fmt.Errorf("write upload: %w", err)
+ }
+ if err := tmpFile.Close(); err != nil {
+ return fmt.Errorf("close upload: %w", err)
+ }
+ if err := os.Rename(tmpPath, cleanDest); err != nil {
+ return fmt.Errorf("install at %s: %w", cleanDest, err)
+ }
+ cleanup = ""
+ return nil
+}
+
+// MaxUploadBytes is the cap on package bytes Install will accept. Larger
+// uploads are rejected before any file is written so a malformed or hostile
+// upload can't fill the plugins directory.
+const MaxUploadBytes = 50 * 1024 * 1024
+
+// Install validates a .ocpkg's contents, writes it into the plugins
+// directory, and forces a scan so the new (or updated) plugin shows up
+// in the next List() without waiting for the scan tick. The destination
+// filename is derived from the manifest's name, not from the uploaded
+// name, so an admin can't drop a file outside the plugins directory by
+// abusing the upload filename, and a plugin update from a differently
+// named .ocpkg ends up replacing the right file. Returns the discovered
+// entry for the installed plugin.
+func (m *Manager) Install(ctx context.Context, packageBytes []byte) (*DiscoveredEntry, error) {
+ manifest, err := validateUploadedPackage(packageBytes)
+ if err != nil {
+ return nil, err
+ }
+ destPath := m.destPathForInstall(manifest.Slug)
+ if err := atomicWritePackage(m.pluginsDir, destPath, packageBytes); err != nil {
+ return nil, err
+ }
+ // Force an immediate scan so the upload appears in List() before
+ // this call returns.
+ if err := m.scan(ctx); err != nil {
+ return nil, fmt.Errorf("scan after install: %w", err)
+ }
+
+ m.mu.RLock()
+ entry, ok := m.discovered[manifest.Slug]
+ var snapshot DiscoveredEntry
+ if ok {
+ snapshot = *entry
+ }
+ m.mu.RUnlock()
+ if !ok {
+ return nil, fmt.Errorf("scan did not pick up the installed plugin %q", manifest.Slug)
+ }
+ return &snapshot, nil
+}
+
+// Disable unloads a plugin and persists the choice. No-op if already disabled.
+func (m *Manager) Disable(ctx context.Context, name string) error {
+ m.mu.Lock()
+ if _, ok := m.discovered[name]; !ok {
+ m.mu.Unlock()
+ return fmt.Errorf("plugin %q not discovered", name)
+ }
+ delete(m.enabledSet, name)
+ loaded := m.loaded[name]
+ delete(m.loaded, name)
+ m.mu.Unlock()
+ if err := m.saveEnabledSet(); err != nil {
+ // Don't bail — we've already removed from the in-memory set.
+ fmt.Fprintf(os.Stderr, "persist enabled set: %v\n", err)
+ }
+ if loaded != nil {
+ loaded.Close(ctx)
+ }
+ return nil
+}
+
+// Uninstall unloads a plugin, deletes its file from the plugins
+// directory, and clears the admin's persisted state (enabled flag and
+// approved-permissions snapshot) for that plugin. The plugin's
+// per-plugin config store is intentionally preserved so an accidental
+// uninstall followed by a reinstall doesn't lose the streamer's
+// settings.
+func (m *Manager) Uninstall(ctx context.Context, name string) error {
+ m.mu.Lock()
+ entry, ok := m.discovered[name]
+ if !ok {
+ m.mu.Unlock()
+ return fmt.Errorf("plugin %q not discovered", name)
+ }
+ path := entry.Path
+ loaded := m.loaded[name]
+ delete(m.loaded, name)
+ delete(m.discovered, name)
+ delete(m.enabledSet, name)
+ delete(m.approvedSet, name)
+ m.mu.Unlock()
+
+ if loaded != nil {
+ loaded.Close(ctx)
+ }
+
+ // Persist the cleared enabled + approved state before touching the
+ // file, so a crash between the two leaves at worst a still-present
+ // file with no in-memory references (the next scan will rediscover
+ // it as a fresh install, which is the safer of the two outcomes).
+ if err := m.saveEnabledSet(); err != nil {
+ fmt.Fprintf(os.Stderr, "persist enabled set after uninstall: %v\n", err)
+ }
+
+ // Delete the .ocpkg (or the loose .wasm + sidecar manifest pair).
+ // A missing file is fine; the scan that picks up our state change
+ // would have dropped the entry anyway.
+ if err := removePluginFiles(path); err != nil {
+ return fmt.Errorf("delete plugin file: %w", err)
+ }
+ return nil
+}
+
+// removePluginFiles deletes the on-disk artifacts that correspond to a
+// discovered plugin's path. For a .ocpkg this is just the one file. For
+// the loose-files layout it's the .wasm, the sibling .manifest.json, the
+// optional icon/instructions siblings, and the optional <base>-assets/
+// directory.
+func removePluginFiles(path string) error {
+ if err := os.Remove(path); err != nil && !os.IsNotExist(err) {
+ return err
+ }
+ if strings.HasSuffix(path, ".wasm") {
+ base := strings.TrimSuffix(path, ".wasm")
+ _ = os.Remove(base + ".manifest.json")
+ _ = os.Remove(base + ".icon.png")
+ _ = os.Remove(base + "." + PluginInstructionsFilename)
+ _ = os.RemoveAll(base + "-assets")
+ }
+ return nil
+}
+
+// Reload unloads and reloads a plugin. Plugin author rebuilt → admin
+// triggers a reload to pick up the new wasm AND the new manifest without
+// restarting the host or waiting for the next discovery scan tick.
+// Plugin must currently be enabled (otherwise call Enable instead).
+func (m *Manager) Reload(ctx context.Context, name string) error {
+ m.mu.Lock()
+ entry, ok := m.discovered[name]
+ if !ok {
+ m.mu.Unlock()
+ return fmt.Errorf("plugin %q not discovered", name)
+ }
+ if !m.enabledSet[name] {
+ m.mu.Unlock()
+ return fmt.Errorf("plugin %q is not enabled; use Enable to load it", name)
+ }
+ path := entry.Path
+ loaded := m.loaded[name]
+ delete(m.loaded, name)
+ m.mu.Unlock()
+ if loaded != nil {
+ loaded.Close(ctx)
+ }
+
+ // Re-read the manifest from disk so any author-side edits (new admin
+ // pages, version bump, permission changes) surface immediately. A
+ // failure here is logged but not fatal; the wasm reload below can
+ // still succeed and the stale metadata will refresh on the next
+ // scanLoop tick.
+ if manifest, err := readManifestForPath(path); err == nil {
+ m.mu.Lock()
+ if existing, ok := m.discovered[name]; ok {
+ existing.Version = manifest.Version
+ existing.Description = manifest.Description
+ existing.Permissions = manifest.Permissions
+ existing.AdminPages = manifest.Admin.Pages
+ existing.PendingPermissions = pendingPermissions(manifest.Permissions, m.approvedSet[name])
+ }
+ m.mu.Unlock()
+ } else {
+ fmt.Fprintf(os.Stderr, "plugin %q reload: re-reading manifest failed: %v\n", name, err)
+ }
+
+ return m.loadInternal(ctx, name)
+}
+
+// loadInternal performs the actual load and inserts into m.loaded. Assumes
+// the caller has already verified the plugin is discovered + enabled.
+// Refuses to load a plugin whose current manifest declares permissions
+// the admin has not yet approved.
+func (m *Manager) loadInternal(ctx context.Context, name string) error {
+ m.mu.RLock()
+ d, ok := m.discovered[name]
+ approved := m.approvedSet[name]
+ m.mu.RUnlock()
+ if !ok {
+ return fmt.Errorf("plugin %q not discovered", name)
+ }
+ if pending := pendingPermissions(d.Permissions, approved); len(pending) > 0 {
+ err := fmt.Errorf("plugin %q declares new permissions that need admin approval: %s",
+ name, strings.Join(pending, ", "))
+ m.mu.Lock()
+ if existing, ok := m.discovered[name]; ok {
+ existing.PendingPermissions = pending
+ existing.LastError = err.Error()
+ }
+ m.mu.Unlock()
+ return err
+ }
+
+ loaded, err := loadByPath(ctx, m.env, d.Path)
+ if err != nil {
+ m.mu.Lock()
+ m.discovered[name].LastError = err.Error()
+ m.mu.Unlock()
+ return err
+ }
+
+ m.mu.Lock()
+ m.loaded[name] = loaded
+ m.discovered[name].LastError = ""
+ m.mu.Unlock()
+ return nil
+}
+
+// loadByPath dispatches to LoadPlugin or LoadPackage based on file suffix.
+// For loose-files plugins it reads PublicFS and AssetsFS from `public/`
+// and `assets/` directories in the same parent directory as the wasm,
+// matching the layout authors keep in their plugin source tree.
+func loadByPath(ctx context.Context, env *HostEnv, path string) (*Loaded, error) {
+ switch {
+ case strings.HasSuffix(path, packageSuffix):
+ return LoadPackage(ctx, env, path)
+ case strings.HasSuffix(path, ".wasm"):
+ manifestPath := strings.TrimSuffix(path, ".wasm") + ".manifest.json"
+ loaded, err := LoadPlugin(ctx, env, path, manifestPath)
+ if err != nil {
+ return nil, err
+ }
+ parent := filepath.Dir(path)
+ if pub := filepath.Join(parent, "public"); dirExists(pub) {
+ loaded.PublicFS = os.DirFS(pub)
+ }
+ if as := filepath.Join(parent, "assets"); dirExists(as) {
+ loaded.AssetsFS = os.DirFS(as)
+ }
+ return loaded, nil
+ }
+ return nil, fmt.Errorf("unsupported plugin file: %s", path)
+}
+
+// dirExists reports whether path is an existing directory. Pulled out
+// so loadByPath reads cleanly when it checks two sibling directories.
+func dirExists(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && info.IsDir()
+}
+
+// scan re-reads the plugins directory, updates the discovered map, and
+// unloads anything whose underlying file has gone away.
+func (m *Manager) scan(ctx context.Context) error {
+ entries, err := os.ReadDir(m.pluginsDir)
+ if err != nil {
+ return fmt.Errorf("read plugins dir %q: %w", m.pluginsDir, err)
+ }
+
+ seen := make(map[string]bool)
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ name := entry.Name()
+ if !strings.HasSuffix(name, ".wasm") && !strings.HasSuffix(name, packageSuffix) {
+ continue
+ }
+ path := filepath.Join(m.pluginsDir, name)
+ manifest, err := readManifestForPath(path)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "discover %s: %v\n", name, err)
+ continue
+ }
+ seen[manifest.Slug] = true
+
+ hasIcon := hasPluginIcon(path)
+ hasInstructions := hasPluginInstructions(path)
+
+ m.mu.Lock()
+ if existing, ok := m.discovered[manifest.Slug]; ok {
+ // Already discovered; refresh manifest metadata in case it changed.
+ existing.DisplayName = manifest.DisplayName
+ existing.BotDisplayName = manifest.Bot.DisplayName
+ existing.Version = manifest.Version
+ existing.Description = manifest.Description
+ existing.Permissions = manifest.Permissions
+ existing.Path = path
+ existing.AdminPages = manifest.Admin.Pages
+ existing.HasIcon = hasIcon
+ existing.HasInstructions = hasInstructions
+ existing.PendingPermissions = pendingPermissions(manifest.Permissions, m.approvedSet[manifest.Slug])
+ existing.AllowedHosts = manifest.Network.AllowedHosts
+ } else {
+ m.discovered[manifest.Slug] = &DiscoveredEntry{
+ Slug: manifest.Slug,
+ DisplayName: manifest.DisplayName,
+ BotDisplayName: manifest.Bot.DisplayName,
+ Version: manifest.Version,
+ Description: manifest.Description,
+ Permissions: manifest.Permissions,
+ AllowedHosts: manifest.Network.AllowedHosts,
+ Path: path,
+ DiscoveredAt: time.Now(),
+ AdminPages: manifest.Admin.Pages,
+ HasIcon: hasIcon,
+ HasInstructions: hasInstructions,
+ PendingPermissions: pendingPermissions(manifest.Permissions, m.approvedSet[manifest.Slug]),
+ }
+ }
+ m.mu.Unlock()
+ }
+
+ // Anything we knew about but didn't see this scan: gone from disk.
+ var removed []string
+ m.mu.RLock()
+ for name := range m.discovered {
+ if !seen[name] {
+ removed = append(removed, name)
+ }
+ }
+ m.mu.RUnlock()
+
+ for _, name := range removed {
+ m.mu.Lock()
+ delete(m.discovered, name)
+ loaded := m.loaded[name]
+ delete(m.loaded, name)
+ m.mu.Unlock()
+ if loaded != nil {
+ loaded.Close(ctx)
+ }
+ }
+ return nil
+}
+
+func (m *Manager) scanLoop(ctx context.Context) {
+ ticker := time.NewTicker(m.scanInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ case <-m.scanCh:
+ }
+ if err := m.scan(ctx); err != nil {
+ fmt.Fprintf(os.Stderr, "scan error: %v\n", err)
+ }
+ }
+}
+
+// readManifestForPath parses the manifest of a discovered file without
+// instantiating the wasm. Used during scan; cheap enough to run every
+// few seconds.
+func readManifestForPath(path string) (*Manifest, error) {
+ switch {
+ case strings.HasSuffix(path, packageSuffix):
+ return readManifestFromPackage(path)
+ case strings.HasSuffix(path, ".wasm"):
+ manifestPath := strings.TrimSuffix(path, ".wasm") + ".manifest.json"
+ data, err := os.ReadFile(manifestPath) //nolint:gosec // G304: plugin paths are admin-controlled, not user input
+ if err != nil {
+ return nil, fmt.Errorf("read sidecar manifest: %w", err)
+ }
+ return ParseManifest(data)
+ }
+ return nil, fmt.Errorf("unsupported file type: %s", path)
+}
+
+// Persistence: a tiny JSON file under the plugins directory listing the
+// names the admin has enabled along with the permission set the admin
+// approved at enable time. Survives restarts.
+
+// EnabledStore persists per-plugin admin choices: the enabled set, plus
+// the permission set the admin approved the last time each plugin was
+// enabled. The default is a JSON file in the plugins directory
+// (fileEnabledStore); integrated into Owncast it is backed by the native
+// config datastore (see NewManagerWithStore).
+type EnabledStore interface {
+ // Load returns the persisted state. A fresh store returns an empty
+ // StoreData and a nil error.
+ Load() (StoreData, error)
+ // Save replaces the persisted state atomically.
+ Save(StoreData) error
+}
+
+// StoreData is the persisted admin state for the plugin manager.
+type StoreData struct {
+ // Enabled is the sorted set of plugin names the admin has enabled.
+ Enabled []string
+ // ApprovedPermissions maps plugin name to the sorted permission set
+ // the admin approved the last time that plugin was enabled. If a
+ // plugin appears in Enabled but not here, the next manager startup
+ // captures its current manifest perms as the baseline.
+ ApprovedPermissions map[string][]string
+}
+
+func (m *Manager) loadEnabledSet() error {
+ data, err := m.enabledStore.Load()
+ if err != nil {
+ return err
+ }
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ for _, name := range data.Enabled {
+ m.enabledSet[name] = true
+ }
+ for name, perms := range data.ApprovedPermissions {
+ clone := append([]string(nil), perms...)
+ sort.Strings(clone)
+ m.approvedSet[name] = clone
+ }
+ return nil
+}
+
+func (m *Manager) saveEnabledSet() error {
+ m.mu.RLock()
+ names := make([]string, 0, len(m.enabledSet))
+ for name, enabled := range m.enabledSet {
+ if enabled {
+ names = append(names, name)
+ }
+ }
+ approvals := make(map[string][]string, len(m.approvedSet))
+ for name, perms := range m.approvedSet {
+ clone := append([]string(nil), perms...)
+ approvals[name] = clone
+ }
+ m.mu.RUnlock()
+ sort.Strings(names)
+ return m.enabledStore.Save(StoreData{Enabled: names, ApprovedPermissions: approvals})
+}
+
+// enabledFileContents is the on-disk JSON shape for fileEnabledStore.
+type enabledFileContents struct {
+ Enabled []string `json:"enabled"`
+ ApprovedPermissions map[string][]string `json:"approvedPermissions,omitempty"`
+}
+
+// fileEnabledStore persists the enabled set to a JSON file. It's the default
+// for the standalone runtime and tests; Owncast supplies a config-backed
+// EnabledStore instead.
+type fileEnabledStore struct {
+ path string
+}
+
+func newFileEnabledStore(path string) *fileEnabledStore {
+ return &fileEnabledStore{path: path}
+}
+
+func (s *fileEnabledStore) Load() (StoreData, error) {
+ data, err := os.ReadFile(s.path)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return StoreData{}, nil
+ }
+ return StoreData{}, err
+ }
+ var f enabledFileContents
+ if err := json.Unmarshal(data, &f); err != nil {
+ return StoreData{}, err
+ }
+ return StoreData(f), nil
+}
+
+func (s *fileEnabledStore) Save(d StoreData) error {
+ contents := enabledFileContents(d)
+ data, err := json.MarshalIndent(contents, "", " ")
+ if err != nil {
+ return err
+ }
+ return os.WriteFile(s.path, data, 0o600)
+}
+
+// pendingForLocked returns the permissions the current manifest declares
+// that the admin has not yet approved. Caller need not hold the
+// manager's lock; this helper acquires its own RLock.
+func (m *Manager) pendingForLocked(name string) []string {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ d, ok := m.discovered[name]
+ if !ok {
+ return nil
+ }
+ return pendingPermissions(d.Permissions, m.approvedSet[name])
+}
+
+// captureMissingApprovals fills in approval baselines for any plugin in
+// the enabled set that doesn't already have one. Used on startup so an
+// existing install (where the approved-permissions field didn't exist
+// in the persisted state) doesn't suddenly see every permission as
+// pending. After capturing, clears PendingPermissions on the affected
+// entries so List() reflects the silent baseline. Returns true when any
+// new baseline was captured (caller is expected to persist).
+func (m *Manager) captureMissingApprovals() bool {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ changed := false
+ for name, enabled := range m.enabledSet {
+ if !enabled {
+ continue
+ }
+ if _, hasApproval := m.approvedSet[name]; hasApproval {
+ continue
+ }
+ d, ok := m.discovered[name]
+ if !ok {
+ continue
+ }
+ snapshot := append([]string(nil), d.Permissions...)
+ sort.Strings(snapshot)
+ m.approvedSet[name] = snapshot
+ d.PendingPermissions = nil
+ changed = true
+ }
+ return changed
+}
+
+// pendingPermissions returns the permissions in manifestPerms that aren't
+// in approved. Both inputs are treated as case-sensitive strings; the
+// result is sorted and may be nil when there's no gap.
+func pendingPermissions(manifestPerms, approved []string) []string {
+ if len(manifestPerms) == 0 {
+ return nil
+ }
+ approvedIdx := make(map[string]bool, len(approved))
+ for _, p := range approved {
+ approvedIdx[p] = true
+ }
+ var pending []string
+ for _, p := range manifestPerms {
+ if !approvedIdx[p] {
+ pending = append(pending, p)
+ }
+ }
+ sort.Strings(pending)
+ return pending
+}
+
+// LoadPlugin loads a single plugin given explicit wasm and manifest paths
+// (the loose-files layout). Used by the test runner so it shares the exact
+// same load + register + validate path that production uses via Start.
+//
+// AssetsFS on the returned Loaded is left nil — callers that want static
+// asset serving should populate it themselves.
+func LoadPlugin(ctx context.Context, env *HostEnv, wasmPath, manifestPath string) (*Loaded, error) {
+ manifestBytes, err := os.ReadFile(manifestPath) //nolint:gosec // G304: plugin paths are admin-controlled, not user input
+ if err != nil {
+ return nil, fmt.Errorf("read manifest %s: %w", manifestPath, err)
+ }
+ wasmBytes, err := os.ReadFile(wasmPath) //nolint:gosec // G304: plugin paths are admin-controlled, not user input
+ if err != nil {
+ return nil, fmt.Errorf("read wasm %s: %w", wasmPath, err)
+ }
+ displayName := strings.TrimSuffix(filepath.Base(wasmPath), ".wasm")
+ loaded, err := loadFromBytes(ctx, env, manifestBytes, wasmBytes, displayName)
+ if err != nil {
+ return nil, err
+ }
+ loaded.WasmPath = wasmPath
+ return loaded, nil
+}
+
+// loadFromBytes is the shared core of LoadPlugin and LoadPackage.
+func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, wasmBytes []byte, displayName string) (*Loaded, error) {
+ manifest, err := ParseManifest(manifestBytes)
+ if err != nil {
+ return nil, err
+ }
+
+ hostFns := BuildHostFunctions(env, manifest)
+
+ extismManifest := extism.Manifest{
+ Wasm: []extism.Wasm{extism.WasmData{Data: wasmBytes, Name: displayName}},
+ Timeout: 10_000, // milliseconds; enables Wazero's WithCloseOnContextDone
+ // Sandbox caps. A plugin that exceeds these gets an error from the
+ // next Call; the host stays up. Defaults are generous enough for
+ // realistic plugins; per-plugin manifest overrides are a future TODO.
+ Memory: &extism.ManifestMemory{
+ MaxPages: MaxWasmPages, // wasm linear memory cap
+ MaxHttpResponseBytes: MaxExtismHTTPResponseBytes, // outbound http body cap
+ MaxVarBytes: MaxExtismVarBytes, // extism's internal Var KV
+ },
+ }
+ for _, p := range manifest.Permissions {
+ if p == PermNetworkFetch {
+ // Manifest validation already required AllowedHosts to be
+ // non-empty when network.fetch is granted, so passing the
+ // list through is safe — admins explicitly authorized this
+ // scope by approving the manifest at install time.
+ extismManifest.AllowedHosts = append([]string(nil), manifest.Network.AllowedHosts...)
+ break
+ }
+ }
+ p, err := extism.NewPlugin(ctx, extismManifest, extism.PluginConfig{EnableWasi: true}, hostFns)
+ if err != nil {
+ return nil, fmt.Errorf("instantiate wasm: %w", err)
+ }
+ p.SetLogger(func(level extism.LogLevel, message string) {
+ fmt.Fprintf(os.Stderr, "[%s] %s\n", displayName, message)
+ })
+
+ if !p.FunctionExists("register") {
+ _ = p.Close(ctx)
+ return nil, fmt.Errorf("plugin does not export register()")
+ }
+ _, regOut, err := p.Call("register", nil)
+ if err != nil {
+ _ = p.Close(ctx)
+ return nil, fmt.Errorf("call register(): %w", err)
+ }
+ if len(regOut) > MaxRegisterOutputBytes {
+ _ = p.Close(ctx)
+ return nil, fmt.Errorf("register() output too large: %d bytes (max %d)", len(regOut), MaxRegisterOutputBytes)
+ }
+ var runtime Manifest
+ if err := json.Unmarshal(regOut, &runtime); err != nil {
+ _ = p.Close(ctx)
+ return nil, fmt.Errorf("parse register() output: %w", err)
+ }
+ if err := manifest.AgreesWith(&runtime); err != nil {
+ _ = p.Close(ctx)
+ return nil, fmt.Errorf("manifest/runtime mismatch: %w", err)
+ }
+ if err := requireChatFilterPermission(manifest, runtime.Subscriptions); err != nil {
+ _ = p.Close(ctx)
+ return nil, err
+ }
+ manifest.Subscriptions = runtime.Subscriptions
+
+ var adminGlobs []glob.Glob
+ var adminPaths []string
+ for _, page := range manifest.Admin.Pages {
+ g, err := glob.Compile(page.Path)
+ if err != nil {
+ _ = p.Close(ctx)
+ return nil, fmt.Errorf("manifest.admin.pages: invalid path glob %q: %w", page.Path, err)
+ }
+ adminGlobs = append(adminGlobs, g)
+ adminPaths = append(adminPaths, page.Path)
+ }
+
+ return &Loaded{Manifest: manifest, plugin: p, adminGlobs: adminGlobs, adminPaths: adminPaths}, nil
+}
+
+// requireChatFilterPermission rejects a runtime registration that
+// subscribes to filterChatMessage without declaring the chat.filter
+// permission. Modifying or dropping every chat message is a meaningful
+// side-effect, so an admin must opt in at install time by granting it.
+func requireChatFilterPermission(manifest *Manifest, subs Subscriptions) error {
+ if !manifest.hasPermission(PermChatFilter) {
+ for _, s := range subs.Filter {
+ if s.Event == EventChatMessageReceived {
+ return fmt.Errorf(
+ "plugin subscribes to filterChatMessage but does not declare "+
+ "the %q permission. Add %q to the manifest's permissions "+
+ "so an admin can see at install time that this plugin "+
+ "reads or modifies every chat message",
+ PermChatFilter, PermChatFilter,
+ )
+ }
+ }
+ }
+ return nil
+}
+
+// PluginIconFilename is the conventional filename a plugin uses to ship
+// an icon. For .ocpkg plugins it lives at the root of the zip; for loose
+// .wasm files it sits next to the wasm as "<base>.icon.png" so multiple
+// plugins in one directory don't collide.
+const PluginIconFilename = "icon.png"
+
+// hasPluginIcon reports whether the plugin at path bundles an icon.
+// Called per-scan, so it has to be cheap — a single zip central-
+// directory read for packaged plugins, or a stat for loose files.
+func hasPluginIcon(path string) bool {
+ switch {
+ case strings.HasSuffix(path, packageSuffix):
+ zr, err := zip.OpenReader(path)
+ if err != nil {
+ return false
+ }
+ defer zr.Close()
+ for _, f := range zr.File {
+ if f.Name == PluginIconFilename {
+ return true
+ }
+ }
+ return false
+ case strings.HasSuffix(path, ".wasm"):
+ iconPath := strings.TrimSuffix(path, ".wasm") + ".icon.png"
+ _, err := os.Stat(iconPath)
+ return err == nil
+ }
+ return false
+}
+
+// IconBytes returns the raw bytes of the plugin's icon.png, or an error
+// if the plugin isn't discovered or doesn't ship one. Callers should
+// serve the bytes with content-type image/png.
+//
+// Read on-demand from disk on each call: icons are tiny, requests are
+// rare (admin UI only), and reading fresh means an admin who swaps the
+// icon between two scans gets the new one without a host restart.
+func (m *Manager) IconBytes(name string) ([]byte, error) {
+ m.mu.RLock()
+ entry, ok := m.discovered[name]
+ if !ok {
+ m.mu.RUnlock()
+ return nil, fmt.Errorf("plugin %q not discovered", name)
+ }
+ path := entry.Path
+ hasIcon := entry.HasIcon
+ m.mu.RUnlock()
+ if !hasIcon {
+ return nil, fmt.Errorf("plugin %q has no icon", name)
+ }
+
+ switch {
+ case strings.HasSuffix(path, packageSuffix):
+ zr, err := zip.OpenReader(path)
+ if err != nil {
+ return nil, fmt.Errorf("open package %s: %w", path, err)
+ }
+ defer zr.Close()
+ for _, f := range zr.File {
+ if f.Name != PluginIconFilename {
+ continue
+ }
+ rc, err := f.Open()
+ if err != nil {
+ return nil, fmt.Errorf("open icon entry: %w", err)
+ }
+ defer rc.Close()
+ return io.ReadAll(rc)
+ }
+ return nil, fmt.Errorf("plugin %q icon entry vanished between scan and read", name)
+ case strings.HasSuffix(path, ".wasm"):
+ iconPath := strings.TrimSuffix(path, ".wasm") + ".icon.png"
+ return os.ReadFile(iconPath) //nolint:gosec // G304: plugin paths are admin-controlled, not user input
+ }
+ return nil, fmt.Errorf("plugin %q: unsupported file type for icon lookup", name)
+}
+
+// PluginInstructionsFilename is the conventional filename a plugin uses to
+// ship author-written usage instructions. For .ocpkg plugins it lives at
+// the root of the zip; for loose .wasm files it sits next to the wasm as
+// "<base>.INSTRUCTIONS.md" so multiple plugins in one directory don't
+// collide. The content is markdown, rendered by the admin UI.
+const PluginInstructionsFilename = "INSTRUCTIONS.md"
+
+// hasPluginInstructions reports whether the plugin at path bundles an
+// INSTRUCTIONS.md. Called per-scan, so it has to be cheap — a single zip
+// central-directory read for packaged plugins, or a stat for loose files.
+func hasPluginInstructions(path string) bool {
+ switch {
+ case strings.HasSuffix(path, packageSuffix):
+ zr, err := zip.OpenReader(path)
+ if err != nil {
+ return false
+ }
+ defer zr.Close()
+ for _, f := range zr.File {
+ if f.Name == PluginInstructionsFilename {
+ return true
+ }
+ }
+ return false
+ case strings.HasSuffix(path, ".wasm"):
+ instructionsPath := strings.TrimSuffix(path, ".wasm") + "." + PluginInstructionsFilename
+ _, err := os.Stat(instructionsPath)
+ return err == nil
+ }
+ return false
+}
+
+// InstructionsBytes returns the raw markdown of the plugin's
+// INSTRUCTIONS.md, or an error if the plugin isn't discovered or doesn't
+// ship one. Callers should serve the bytes with content-type text/markdown.
+//
+// Read on-demand from disk on each call: instructions are small, requests
+// are rare (admin UI only), and reading fresh means an admin who swaps the
+// file between two scans gets the new content without a host restart.
+func (m *Manager) InstructionsBytes(name string) ([]byte, error) {
+ m.mu.RLock()
+ entry, ok := m.discovered[name]
+ if !ok {
+ m.mu.RUnlock()
+ return nil, fmt.Errorf("plugin %q not discovered", name)
+ }
+ path := entry.Path
+ has := entry.HasInstructions
+ m.mu.RUnlock()
+ if !has {
+ return nil, fmt.Errorf("plugin %q has no instructions", name)
+ }
+
+ switch {
+ case strings.HasSuffix(path, packageSuffix):
+ zr, err := zip.OpenReader(path)
+ if err != nil {
+ return nil, fmt.Errorf("open package %s: %w", path, err)
+ }
+ defer zr.Close()
+ for _, f := range zr.File {
+ if f.Name != PluginInstructionsFilename {
+ continue
+ }
+ rc, err := f.Open()
+ if err != nil {
+ return nil, fmt.Errorf("open instructions entry: %w", err)
+ }
+ defer rc.Close()
+ return io.ReadAll(rc)
+ }
+ return nil, fmt.Errorf("plugin %q instructions entry vanished between scan and read", name)
+ case strings.HasSuffix(path, ".wasm"):
+ instructionsPath := strings.TrimSuffix(path, ".wasm") + "." + PluginInstructionsFilename
+ return os.ReadFile(instructionsPath) //nolint:gosec // G304: plugin paths are admin-controlled, not user input
+ }
+ return nil, fmt.Errorf("plugin %q: unsupported file type for instructions lookup", name)
+}
diff --git a/services/plugins/manager_test.go b/services/plugins/manager_test.go
new file mode 100644
index 0000000000..8f2b401f67
--- /dev/null
+++ b/services/plugins/manager_test.go
@@ -0,0 +1,628 @@
+package plugins
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+)
+
+// makePluginFiles drops a sidecar wasm + manifest pair into dir. The manifest
+// name is what the manager keys discovered/enabled state by.
+func makePluginFiles(t *testing.T, dir, name string, wasmBytes []byte) {
+ t.Helper()
+ // Version must match what the bundled example's register() returns —
+ // the host enforces manifest/runtime agreement at load time.
+ manifest := map[string]any{
+ "api": "1",
+ "name": name,
+ "version": "0.1.0",
+ "description": name + " for tests",
+ "permissions": []string{},
+ }
+ mb, err := json.Marshal(manifest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, name+".manifest.json"), mb, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, name+".wasm"), wasmBytes, 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestManager_DiscoversWithoutLoading(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, err := os.ReadFile(wasmPath)
+ if err != nil {
+ t.Fatalf("read example wasm: %v", err)
+ }
+
+ dir := t.TempDir()
+ makePluginFiles(t, dir, "hello-world", wasmBytes)
+
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(context.Background())
+
+ entries := mgr.List()
+ if len(entries) != 1 {
+ t.Fatalf("expected 1 discovered, got %d", len(entries))
+ }
+ if entries[0].Slug != "hello-world" {
+ t.Errorf("slug: got %q want hello-world", entries[0].Slug)
+ }
+ if entries[0].Loaded {
+ t.Error("plugin should not be loaded — admin never enabled it")
+ }
+ if entries[0].Enabled {
+ t.Error("plugin should not be enabled — admin never enabled it")
+ }
+ if len(mgr.Snapshot()) != 0 {
+ t.Errorf("snapshot should be empty for un-enabled plugin, got %d", len(mgr.Snapshot()))
+ }
+}
+
+func TestManager_EnableLoadsAndPersists(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+
+ dir := t.TempDir()
+ makePluginFiles(t, dir, "hello-world", wasmBytes)
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+
+ if err := mgr.Enable(ctx, "hello-world"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ if len(mgr.Snapshot()) != 1 {
+ t.Errorf("snapshot count after enable: got %d want 1", len(mgr.Snapshot()))
+ }
+
+ // Persistence: stop, start a fresh manager, plugin should auto-load.
+ mgr.Stop(ctx)
+
+ mgr2 := NewManager(dir, &HostEnv{})
+ if err := mgr2.Start(ctx); err != nil {
+ t.Fatalf("restart: %v", err)
+ }
+ defer mgr2.Stop(ctx)
+
+ if len(mgr2.Snapshot()) != 1 {
+ t.Errorf("snapshot count after restart: got %d want 1 (enabled set should persist)",
+ len(mgr2.Snapshot()))
+ }
+}
+
+func TestManager_DisableUnloadsButKeepsDiscovered(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+
+ dir := t.TempDir()
+ makePluginFiles(t, dir, "hello-world", wasmBytes)
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ if err := mgr.Enable(ctx, "hello-world"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ if err := mgr.Disable(ctx, "hello-world"); err != nil {
+ t.Fatalf("disable: %v", err)
+ }
+ if len(mgr.Snapshot()) != 0 {
+ t.Errorf("snapshot after disable: got %d want 0", len(mgr.Snapshot()))
+ }
+ entries := mgr.List()
+ if len(entries) != 1 {
+ t.Errorf("discovered list after disable: got %d want 1", len(entries))
+ }
+ if entries[0].Enabled {
+ t.Error("entry should not be marked enabled after disable")
+ }
+}
+
+func TestManager_ScanRemovesDeletedFiles(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+
+ dir := t.TempDir()
+ makePluginFiles(t, dir, "hello-world", wasmBytes)
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ mgr.scanInterval = 20 * time.Millisecond
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ if len(mgr.List()) != 1 {
+ t.Fatalf("setup: expected 1 discovered, got %d", len(mgr.List()))
+ }
+
+ // Delete both files; the next scan should drop the entry.
+ if err := os.Remove(filepath.Join(dir, "hello-world.wasm")); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Remove(filepath.Join(dir, "hello-world.manifest.json")); err != nil {
+ t.Fatal(err)
+ }
+
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ if len(mgr.List()) == 0 {
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ t.Errorf("expected scan to drop deleted plugin within 2s, still have %d", len(mgr.List()))
+}
+
+func TestManager_EnableUnknownPluginErrors(t *testing.T) {
+ dir := t.TempDir()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(context.Background())
+
+ err := mgr.Enable(context.Background(), "does-not-exist")
+ if err == nil {
+ t.Error("expected error enabling unknown plugin")
+ }
+}
+
+// rewriteManifestPerms updates the sidecar manifest's permissions field
+// without touching name or version, simulating an author dropping a new
+// .ocpkg whose manifest declares additional permissions.
+func rewriteManifestPerms(t *testing.T, dir, name string, perms []string) {
+ t.Helper()
+ manifest := map[string]any{
+ "api": "1",
+ "name": name,
+ "version": "0.1.0",
+ "description": name + " for tests",
+ "permissions": perms,
+ }
+ mb, err := json.Marshal(manifest)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(dir, name+".manifest.json"), mb, 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestPendingPermissions(t *testing.T) {
+ cases := []struct {
+ name string
+ manifest []string
+ approved []string
+ want []string
+ }{
+ {"empty manifest", nil, []string{"a"}, nil},
+ {"all approved", []string{"a", "b"}, []string{"a", "b"}, nil},
+ {"new perm pending", []string{"a", "b"}, []string{"a"}, []string{"b"}},
+ {"approved superset", []string{"a"}, []string{"a", "b"}, nil},
+ {"no approval baseline", []string{"a", "b"}, nil, []string{"a", "b"}},
+ {"unsorted manifest order", []string{"c", "a"}, []string{"a"}, []string{"c"}},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := pendingPermissions(tc.manifest, tc.approved)
+ if !stringSliceEqual(got, tc.want) {
+ t.Errorf("pendingPermissions(%v, %v) = %v, want %v",
+ tc.manifest, tc.approved, got, tc.want)
+ }
+ })
+ }
+}
+
+func stringSliceEqual(a, b []string) bool {
+ if len(a) != len(b) {
+ return false
+ }
+ for i := range a {
+ if a[i] != b[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func TestManager_EnableCapturesApprovalBaseline(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ dir := t.TempDir()
+ makePluginFiles(t, dir, "hello-world", wasmBytes)
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ if err := mgr.Enable(ctx, "hello-world"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+
+ // The on-disk .enabled.json should now contain an empty approved-perm
+ // list for hello-world (the bundled manifest has no permissions).
+ raw, err := os.ReadFile(filepath.Join(dir, ".enabled.json"))
+ if err != nil {
+ t.Fatalf("read enabled file: %v", err)
+ }
+ var f enabledFileContents
+ if err := json.Unmarshal(raw, &f); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if _, ok := f.ApprovedPermissions["hello-world"]; !ok {
+ t.Errorf("expected approved perm entry for hello-world after enable; got %v", f.ApprovedPermissions)
+ }
+}
+
+func TestManager_PermExpansionAutoDisables(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ dir := t.TempDir()
+ makePluginFiles(t, dir, "hello-world", wasmBytes)
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ if err := mgr.Enable(ctx, "hello-world"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ mgr.Stop(ctx)
+
+ // Author updates the manifest on disk to declare a permission the
+ // admin never approved. The wasm itself stays put (so AgreesWith
+ // still passes: empty runtime perms is a subset of any manifest set).
+ rewriteManifestPerms(t, dir, "hello-world", []string{"chat.send"})
+
+ mgr2 := NewManager(dir, &HostEnv{})
+ if err := mgr2.Start(ctx); err != nil {
+ t.Fatalf("restart: %v", err)
+ }
+ defer mgr2.Stop(ctx)
+
+ entries := mgr2.List()
+ if len(entries) != 1 {
+ t.Fatalf("expected 1 discovered, got %d", len(entries))
+ }
+ entry := entries[0]
+ if !entry.Enabled {
+ t.Error("admin intent should survive: Enabled=true")
+ }
+ if entry.Loaded {
+ t.Error("plugin must not load while permissions are pending approval")
+ }
+ if !stringSliceEqual(entry.PendingPermissions, []string{"chat.send"}) {
+ t.Errorf("PendingPermissions = %v, want [chat.send]", entry.PendingPermissions)
+ }
+ if len(mgr2.Snapshot()) != 0 {
+ t.Errorf("snapshot must be empty: plugin is pending approval, got %d loaded", len(mgr2.Snapshot()))
+ }
+}
+
+func TestManager_ReEnableApprovesAndLoads(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ dir := t.TempDir()
+ makePluginFiles(t, dir, "hello-world", wasmBytes)
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ if err := mgr.Enable(ctx, "hello-world"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ mgr.Stop(ctx)
+
+ rewriteManifestPerms(t, dir, "hello-world", []string{"chat.send"})
+
+ mgr2 := NewManager(dir, &HostEnv{})
+ if err := mgr2.Start(ctx); err != nil {
+ t.Fatalf("restart: %v", err)
+ }
+ defer mgr2.Stop(ctx)
+
+ // Sanity: still pending.
+ if entries := mgr2.List(); entries[0].Loaded {
+ t.Fatal("plugin should not be loaded before re-enable")
+ }
+
+ // Admin re-enables; this captures the expanded perm set as the new
+ // approved baseline, clears PendingPermissions, and loads the plugin.
+ if err := mgr2.Enable(ctx, "hello-world"); err != nil {
+ t.Fatalf("re-enable: %v", err)
+ }
+ entries := mgr2.List()
+ if len(entries[0].PendingPermissions) != 0 {
+ t.Errorf("PendingPermissions should be cleared after re-enable, got %v",
+ entries[0].PendingPermissions)
+ }
+ if !entries[0].Loaded {
+ t.Error("plugin should be loaded after re-enable")
+ }
+}
+
+func TestManager_ExistingInstallGetsApprovalBaseline(t *testing.T) {
+ // An installation that predates the approved-permissions field: the
+ // enabled file lists the plugin but has no approved perms map. On
+ // next Start, the manager should silently capture the current
+ // manifest perms as the baseline rather than treat them as pending.
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ dir := t.TempDir()
+ rewriteManifestPerms(t, dir, "hello-world", []string{"chat.send"})
+ if err := os.WriteFile(filepath.Join(dir, "hello-world.wasm"), wasmBytes, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // Legacy enabled.json: enabled set only, no approvals.
+ legacy := []byte(`{"enabled":["hello-world"]}`)
+ if err := os.WriteFile(filepath.Join(dir, ".enabled.json"), legacy, 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ entries := mgr.List()
+ if len(entries) != 1 {
+ t.Fatalf("expected 1 discovered, got %d", len(entries))
+ }
+ if len(entries[0].PendingPermissions) != 0 {
+ t.Errorf("existing install should not flag any pending perms, got %v",
+ entries[0].PendingPermissions)
+ }
+ if !entries[0].Loaded {
+ t.Error("existing install should load on next Start without re-approval")
+ }
+}
+
+// buildPackageBytes builds an in-memory .ocpkg with the given manifest and
+// wasm bytes (and optional assets) using the same on-disk layout the
+// scan path expects.
+func buildPackageBytes(t *testing.T, manifest []byte, wasm []byte, assets map[string][]byte) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ if manifest != nil {
+ w, err := zw.Create(pkgManifestFilename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Write(manifest); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if wasm != nil {
+ w, err := zw.Create(pkgWasmFilename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Write(wasm); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for name, data := range assets {
+ w, err := zw.Create(pkgAssetsPrefix + name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := w.Write(data); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+func TestManager_Install_WritesPackageAndDiscovers(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+
+ dir := t.TempDir()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(context.Background())
+
+ pkg := buildPackageBytes(t, validManifestBytes(), wasmBytes, nil)
+ entry, err := mgr.Install(context.Background(), pkg)
+ if err != nil {
+ t.Fatalf("install: %v", err)
+ }
+ if entry.Slug != "hello-world" {
+ t.Errorf("entry slug: got %q want hello-world", entry.Slug)
+ }
+ expectedPath := filepath.Join(dir, "hello-world.ocpkg")
+ if _, err := os.Stat(expectedPath); err != nil {
+ t.Errorf("expected file %s to exist after install: %v", expectedPath, err)
+ }
+ if len(mgr.List()) != 1 {
+ t.Errorf("install should leave one discovered plugin, got %d", len(mgr.List()))
+ }
+}
+
+func TestManager_Install_RejectsEmptyUpload(t *testing.T) {
+ mgr := NewManager(t.TempDir(), &HostEnv{})
+ _, err := mgr.Install(context.Background(), nil)
+ if err == nil {
+ t.Fatal("expected error for empty upload")
+ }
+}
+
+func TestManager_Install_RejectsOversizedUpload(t *testing.T) {
+ mgr := NewManager(t.TempDir(), &HostEnv{})
+ oversized := make([]byte, MaxUploadBytes+1)
+ _, err := mgr.Install(context.Background(), oversized)
+ if err == nil {
+ t.Fatal("expected error for oversized upload")
+ }
+ if !strings.Contains(err.Error(), "cap") {
+ t.Errorf("error should mention the cap: got %v", err)
+ }
+}
+
+func TestManager_Install_RejectsNonOcpkg(t *testing.T) {
+ mgr := NewManager(t.TempDir(), &HostEnv{})
+ _, err := mgr.Install(context.Background(), []byte("not a zip"))
+ if err == nil {
+ t.Fatal("expected error for garbage upload")
+ }
+}
+
+func TestManager_Install_RejectsMissingManifest(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+
+ mgr := NewManager(t.TempDir(), &HostEnv{})
+ pkg := buildPackageBytes(t, nil, wasmBytes, nil)
+ _, err := mgr.Install(context.Background(), pkg)
+ if err == nil {
+ t.Fatal("expected error for package missing manifest")
+ }
+ if !strings.Contains(err.Error(), "manifest") {
+ t.Errorf("error should mention manifest: got %v", err)
+ }
+}
+
+func TestManager_Uninstall_DeletesFileAndClearsState(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ dir := t.TempDir()
+
+ ctx := context.Background()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(ctx); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(ctx)
+
+ pkg := buildPackageBytes(t, validManifestBytes(), wasmBytes, nil)
+ if _, err := mgr.Install(ctx, pkg); err != nil {
+ t.Fatalf("install: %v", err)
+ }
+ if err := mgr.Enable(ctx, "hello-world"); err != nil {
+ t.Fatalf("enable: %v", err)
+ }
+ if len(mgr.Snapshot()) != 1 {
+ t.Fatalf("expected 1 loaded before uninstall, got %d", len(mgr.Snapshot()))
+ }
+
+ if err := mgr.Uninstall(ctx, "hello-world"); err != nil {
+ t.Fatalf("uninstall: %v", err)
+ }
+ if len(mgr.List()) != 0 {
+ t.Errorf("expected 0 discovered after uninstall, got %d", len(mgr.List()))
+ }
+ if len(mgr.Snapshot()) != 0 {
+ t.Errorf("expected 0 loaded after uninstall, got %d", len(mgr.Snapshot()))
+ }
+ if _, err := os.Stat(filepath.Join(dir, "hello-world.ocpkg")); !os.IsNotExist(err) {
+ t.Errorf("expected .ocpkg file to be removed, stat err = %v", err)
+ }
+
+ // Persistence: the cleared state survives a restart. A fresh manager
+ // should see no enabled set and no approval entry.
+ mgr.Stop(ctx)
+ mgr2 := NewManager(dir, &HostEnv{})
+ if err := mgr2.Start(ctx); err != nil {
+ t.Fatalf("restart: %v", err)
+ }
+ defer mgr2.Stop(ctx)
+ raw, err := os.ReadFile(filepath.Join(dir, ".enabled.json"))
+ if err == nil {
+ var f enabledFileContents
+ if err := json.Unmarshal(raw, &f); err != nil {
+ t.Fatalf("decode persisted state: %v", err)
+ }
+ if len(f.Enabled) != 0 {
+ t.Errorf("enabled set should be empty after uninstall, got %v", f.Enabled)
+ }
+ if _, ok := f.ApprovedPermissions["hello-world"]; ok {
+ t.Error("approval snapshot should be cleared after uninstall")
+ }
+ }
+}
+
+func TestManager_Uninstall_UnknownPluginErrors(t *testing.T) {
+ mgr := NewManager(t.TempDir(), &HostEnv{})
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(context.Background())
+ err := mgr.Uninstall(context.Background(), "nothing-here")
+ if err == nil {
+ t.Fatal("expected error uninstalling unknown plugin")
+ }
+}
+
+func TestManager_Install_UpdatesExistingPlugin(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+
+ dir := t.TempDir()
+ mgr := NewManager(dir, &HostEnv{})
+ if err := mgr.Start(context.Background()); err != nil {
+ t.Fatalf("start: %v", err)
+ }
+ defer mgr.Stop(context.Background())
+
+ // First install: hello-world 0.1.0
+ pkg1 := buildPackageBytes(t, validManifestBytes(), wasmBytes, nil)
+ if _, err := mgr.Install(context.Background(), pkg1); err != nil {
+ t.Fatalf("first install: %v", err)
+ }
+
+ // Second install of the same plugin name with a bumped description.
+ updated := []byte(`{
+ "api": "1",
+ "name": "hello-world",
+ "version": "0.1.0",
+ "description": "updated description",
+ "permissions": []
+ }`)
+ pkg2 := buildPackageBytes(t, updated, wasmBytes, nil)
+ entry, err := mgr.Install(context.Background(), pkg2)
+ if err != nil {
+ t.Fatalf("second install: %v", err)
+ }
+ if entry.Description != "updated description" {
+ t.Errorf("description after update: got %q want %q", entry.Description, "updated description")
+ }
+ if len(mgr.List()) != 1 {
+ t.Errorf("update should not duplicate the entry, got %d", len(mgr.List()))
+ }
+}
diff --git a/services/plugins/manifest.go b/services/plugins/manifest.go
new file mode 100644
index 0000000000..f8c86ced1f
--- /dev/null
+++ b/services/plugins/manifest.go
@@ -0,0 +1,631 @@
+package plugins
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "regexp"
+ "strings"
+)
+
+const SupportedAPIVersion = "1"
+
+// slugPattern is the validation pattern for both explicit and
+// auto-derived plugin slugs. The slug becomes the plugin's URL
+// segment, on-disk filename, KV namespace, and registry identifier,
+// so it has to stay narrow: lowercase letters/digits/hyphens, has to
+// start with a letter, max 64 chars.
+var slugPattern = regexp.MustCompile(`^[a-z][a-z0-9-]{0,63}$`)
+
+type Subscription struct {
+ Event string `json:"event"`
+ Priority int `json:"priority,omitempty"`
+}
+
+type Subscriptions struct {
+ Notify []Subscription `json:"notify,omitempty"`
+ Filter []Subscription `json:"filter,omitempty"`
+}
+
+type ConfigField struct {
+ Type string `json:"type"`
+ Default any `json:"default,omitempty"`
+ Description string `json:"description,omitempty"`
+}
+
+type Manifest struct {
+ API string `json:"api"`
+ // DisplayName is the user-facing plugin name shown in admin lists,
+ // the Browse cards on the registry, and (by default) as the
+ // in-chat bot identity. Mapped from the JSON `name` field for
+ // author ergonomics (authors write `"name": "Awesome Echo Bot"`
+ // in their manifest; the Go side treats it as a display string).
+ DisplayName string `json:"name"`
+ // Slug is the plugin's canonical identifier: URL segment, KV
+ // namespace, on-disk filename, registry primary key. Lowercase,
+ // hyphenated, matches slugPattern. Authors can pin it via the
+ // JSON `slug` field; if empty, it's auto-derived from
+ // DisplayName at parse time by slugify.
+ Slug string `json:"slug,omitempty"`
+ Version string `json:"version"`
+ Description string `json:"description,omitempty"`
+ Bot BotConfig `json:"bot,omitempty"`
+ Subscriptions Subscriptions `json:"subscriptions"`
+ Permissions []string `json:"permissions,omitempty"`
+ Config map[string]ConfigField `json:"config,omitempty"`
+ Admin AdminConfig `json:"admin,omitempty"`
+ Actions []ActionButton `json:"actions,omitempty"`
+ Network NetworkConfig `json:"network,omitempty"`
+ // Styles is a list of CSS files the plugin contributes to the
+ // viewer page (the public streaming page). Each entry is a path
+ // relative to the plugin's own URL namespace: bare paths like
+ // "theme.css" and "/theme.css" auto-prefix to
+ // /plugins/<slug>/theme.css, fully-qualified plugin paths like
+ // "/plugins/<slug>/theme.css" pass through as-is, and paths in
+ // any other plugin's namespace are rejected. CSS injects into
+ // the global scope, so a plugin author can restyle anything the
+ // viewer page renders. Requires the ui.modify permission and the
+ // plugin must ship the referenced files (typically under
+ // `assets/`) with http.serve declared.
+ Styles []string `json:"styles,omitempty"`
+ // Scripts is a list of JavaScript files the plugin contributes
+ // to the viewer page. Each entry follows the same path rules as
+ // Styles (bare/relative paths auto-prefix to /plugins/<slug>/,
+ // cross-plugin and absolute http(s):// URLs are rejected) and
+ // has to end in .js. Each entry renders as a <script src=...
+ // async> tag on the viewer page, so the code runs in the same
+ // global window context as the viewer chrome. Requires the
+ // ui.modify permission (it's running inside Owncast's chrome)
+ // and http.serve (the host serves the bytes).
+ Scripts []string `json:"scripts,omitempty"`
+ // ExtraPageContent is an HTML file the plugin contributes to the
+ // viewer page's extra-content block. The host reads the file's
+ // bytes and prepends them to the admin's extraPageContent in the
+ // /api/config response (after the admin's markdown is rendered)
+ // so plugin HTML never goes through the markdown processor and
+ // can't be mangled by it. Path rules match styles/scripts (bare
+ // paths auto-prefix to /plugins/<slug>/, cross-plugin and
+ // http(s):// URLs rejected, .html extension required). Only one
+ // file per plugin so the prepended block stays predictable.
+ // Requires ui.modify (the plugin paints inside Owncast's chrome);
+ // http.serve is not required because the HTML is inlined into
+ // the API response, not served as a URL.
+ ExtraPageContent string `json:"extraPageContent,omitempty"`
+ // Tabs declares viewer-page tabs the plugin contributes to the
+ // row of tabs Owncast renders next to chat (alongside built-ins
+ // like Followers). Each entry's `content` is a relative path to
+ // an HTML file under `assets/`; the host reads the bytes and
+ // inlines them into the tab body on /api/config. Path and
+ // extension rules match ExtraPageContent.
+ Tabs []Tab `json:"tabs,omitempty"`
+}
+
+// Tab is a single viewer-page tab a plugin contributes via
+// manifest.tabs. Title is the label shown in the tab bar; Content is
+// a relative path to an HTML file the host reads from the plugin's
+// assets/ directory and inlines into the tab body.
+type Tab struct {
+ Title string `json:"title"`
+ Content string `json:"content"`
+}
+
+// BotConfig is the chat-bot-specific configuration for plugins that
+// post to chat. Optional; defaults to the plugin's DisplayName when
+// unset. Wrapped in a struct so future fields (avatar URL, name
+// color) can land here without flat-namespace pollution on the
+// manifest.
+type BotConfig struct {
+ // DisplayName is what viewers see when the plugin posts to chat.
+ // Falls back to Manifest.DisplayName at the call site
+ // (ChatDisplayName()).
+ DisplayName string `json:"displayName,omitempty"`
+}
+
+// ChatDisplayName resolves the name the chat bot should post as.
+// Bot.DisplayName wins when set, otherwise the plugin's DisplayName.
+// Always non-empty post-Validate because DisplayName is required.
+func (m *Manifest) ChatDisplayName() string {
+ if m.Bot.DisplayName != "" {
+ return m.Bot.DisplayName
+ }
+ return m.DisplayName
+}
+
+// NetworkConfig narrows what hosts a plugin with the `network.fetch`
+// permission can reach. The host passes AllowedHosts straight through to
+// extism's manifest AllowedHosts; each entry is a hostname glob (e.g.
+// "api.discord.com", "*.weather.com", "*").
+//
+// Plugins that declare `network.fetch` MUST declare a non-empty
+// AllowedHosts list — the wildcard "*" is allowed but has to be written
+// out so admins reviewing the manifest see the scope they're granting.
+type NetworkConfig struct {
+ AllowedHosts []string `json:"allowedHosts,omitempty"`
+}
+
+// ActionButton declares an entry the Owncast UI surfaces as an external
+// action — a clickable button that loads a URL (in a modal or new tab) or
+// shows raw HTML when pressed. Buttons declared here are merged with the
+// admin-configured external actions while the plugin is enabled; when the
+// plugin is disabled they disappear.
+//
+// Shape matches Owncast's existing ExternalAction. Exactly one of Url or
+// Html must be set.
+//
+// Url ergonomics: if Url starts with "/" but not "/plugins/", it's treated
+// as a relative path inside this plugin's namespace and the host rewrites
+// it to "/plugins/<name><url>" at validation time. Absolute http(s) URLs
+// and explicit "/plugins/<name>/..." paths are accepted as-is.
+type ActionButton struct {
+ Title string `json:"title"`
+ Url string `json:"url,omitempty"`
+ Html string `json:"html,omitempty"`
+ Icon string `json:"icon,omitempty"`
+ Color string `json:"color,omitempty"`
+ Description string `json:"description,omitempty"`
+ OpenExternally bool `json:"openExternally,omitempty"`
+}
+
+// AdminConfig declares admin-only surfaces a plugin exposes. The Owncast
+// admin web UI lists these in the "Plugins" section; each page renders the
+// plugin's content at /plugins/<name>/<path>. Paths declared here are
+// auth-gated by the host — unauthenticated requests get 401 before
+// reaching the plugin.
+type AdminConfig struct {
+ Pages []AdminPage `json:"pages,omitempty"`
+}
+
+type AdminPage struct {
+ Title string `json:"title"`
+ // Path is a glob (e.g. "/admin", "/admin/*"). Requests under
+ // /plugins/<name>/<rest> are checked against each glob and require
+ // admin authentication when any match.
+ Path string `json:"path"`
+ Icon string `json:"icon,omitempty"`
+}
+
+func ParseManifest(b []byte) (*Manifest, error) {
+ var m Manifest
+ if err := json.Unmarshal(b, &m); err != nil {
+ return nil, fmt.Errorf("parse manifest json: %w", err)
+ }
+ if err := m.Validate(); err != nil {
+ return nil, err
+ }
+ return &m, nil
+}
+
+func (m *Manifest) Validate() error {
+ if m.API != SupportedAPIVersion {
+ return fmt.Errorf("unsupported api version %q (host supports %q)", m.API, SupportedAPIVersion)
+ }
+ if m.DisplayName == "" {
+ return errors.New("manifest.name is required")
+ }
+ if m.Version == "" {
+ return errors.New("manifest.version is required")
+ }
+ if err := m.resolveSlug(); err != nil {
+ return err
+ }
+ if err := m.validateAdminPages(); err != nil {
+ return err
+ }
+ if err := m.validateNetwork(); err != nil {
+ return err
+ }
+ if err := m.validateActions(); err != nil {
+ return err
+ }
+ if err := m.validateStyles(); err != nil {
+ return err
+ }
+ if err := m.validateScripts(); err != nil {
+ return err
+ }
+ if err := m.validateExtraPageContent(); err != nil {
+ return err
+ }
+ return m.validateTabs()
+}
+
+// resolveSlug fills in m.Slug when the author didn't pin one
+// explicitly, and validates the resulting slug against slugPattern.
+// Called from Validate, so every Manifest returned by ParseManifest
+// has Slug populated and well-formed.
+func (m *Manifest) resolveSlug() error {
+ if m.Slug == "" {
+ derived, err := slugify(m.DisplayName)
+ if err != nil {
+ return fmt.Errorf("could not auto-generate a slug from manifest.name %q: %w; set manifest.slug explicitly", m.DisplayName, err)
+ }
+ m.Slug = derived
+ }
+ if !slugPattern.MatchString(m.Slug) {
+ return fmt.Errorf("manifest.slug %q is invalid; must match %s", m.Slug, slugPattern.String())
+ }
+ return nil
+}
+
+// slugify turns a free-form display name into a URL-safe slug
+// matching slugPattern. The pipeline: ASCII-lowercase letters and
+// digits pass through; every other rune (whitespace, punctuation,
+// non-ASCII) collapses to a single hyphen; leading and trailing
+// hyphens are trimmed. Non-ASCII names degrade noisily (e.g.
+// "Café Helper" becomes "caf-helper"), so authors with diacritics
+// or non-Latin scripts should pin `slug` explicitly in the
+// manifest instead of relying on derivation.
+//
+// Returns an error when the result is empty (the input had no
+// usable characters) or doesn't start with a letter (e.g.
+// "123 Plugin" produces "123-plugin", which fails the
+// start-with-letter rule); in either case the author has to pin
+// slug explicitly.
+func slugify(input string) (string, error) {
+ var sb strings.Builder
+ prevHyphen := false
+ for _, r := range input {
+ switch {
+ case r >= 'a' && r <= 'z':
+ sb.WriteRune(r)
+ prevHyphen = false
+ case r >= 'A' && r <= 'Z':
+ sb.WriteRune(r + ('a' - 'A'))
+ prevHyphen = false
+ case r >= '0' && r <= '9':
+ sb.WriteRune(r)
+ prevHyphen = false
+ default:
+ if !prevHyphen && sb.Len() > 0 {
+ sb.WriteRune('-')
+ prevHyphen = true
+ }
+ }
+ }
+ out := strings.TrimRight(sb.String(), "-")
+ if out == "" {
+ return "", errors.New("slugified value is empty")
+ }
+ if !slugPattern.MatchString(out) {
+ return "", fmt.Errorf("slugified value %q does not match the required pattern", out)
+ }
+ return out, nil
+}
+
+// hasPermission reports whether the manifest declares the given permission.
+func (m *Manifest) hasPermission(perm string) bool {
+ for _, p := range m.Permissions {
+ if p == perm {
+ return true
+ }
+ }
+ return false
+}
+
+func (m *Manifest) validateAdminPages() error {
+ for i, page := range m.Admin.Pages {
+ if page.Title == "" {
+ return fmt.Errorf("manifest.admin.pages[%d].title is required", i)
+ }
+ if page.Path == "" {
+ return fmt.Errorf("manifest.admin.pages[%d].path is required", i)
+ }
+ }
+ return nil
+}
+
+func (m *Manifest) validateNetwork() error {
+ if m.hasPermission(PermNetworkFetch) && len(m.Network.AllowedHosts) == 0 {
+ return errors.New(
+ "manifest declares network.fetch but no network.allowedHosts; " +
+ "list the hostnames you'll reach (globs OK, e.g. \"api.discord.com\", " +
+ "\"*.weather.com\") or [\"*\"] for any host")
+ }
+ for i, host := range m.Network.AllowedHosts {
+ if strings.TrimSpace(host) == "" {
+ return fmt.Errorf("manifest.network.allowedHosts[%d] is empty", i)
+ }
+ }
+ return nil
+}
+
+func (m *Manifest) validateActions() error {
+ // Action buttons are the only UI surface a plugin can place inside
+ // Owncast's own chrome (the viewer action bar). Self-contained admin
+ // pages and static content served under /plugins/<name>/ are baseline
+ // plugin functionality and don't gate on this.
+ if len(m.Actions) > 0 && !m.hasPermission(PermUIModify) {
+ return errors.New(
+ "manifest.actions is set but the manifest does not declare " +
+ "the \"ui.modify\" permission; plugins that contribute viewer " +
+ "action buttons must opt in to ui.modify so it's visible to " +
+ "anyone reviewing the manifest that the plugin places UI " +
+ "inside Owncast's chrome")
+ }
+ pluginPrefix := "/plugins/" + m.Slug + "/"
+ hasHTTPServe := m.hasPermission(PermHttpServe)
+ for i := range m.Actions {
+ a := &m.Actions[i]
+ if a.Title == "" {
+ return fmt.Errorf("manifest.actions[%d].title is required", i)
+ }
+ hasURL, hasHTML := a.Url != "", a.Html != ""
+ if hasURL == hasHTML {
+ return fmt.Errorf("manifest.actions[%d]: exactly one of url or html is required", i)
+ }
+ if !hasURL {
+ continue
+ }
+ // Relative path inside the plugin's own namespace? Rewrite.
+ if strings.HasPrefix(a.Url, "/") && !strings.HasPrefix(a.Url, "/plugins/") {
+ a.Url = pluginPrefix + strings.TrimPrefix(a.Url, "/")
+ }
+ // http.serve required when the action points back into the plugin.
+ if strings.HasPrefix(a.Url, pluginPrefix) && !hasHTTPServe {
+ return fmt.Errorf("manifest.actions[%d].url targets this plugin (%s) but http.serve permission is not declared",
+ i, a.Url)
+ }
+ // Paths in other plugins' namespaces aren't allowed — catches typos
+ // and prevents one plugin from advertising another's UI.
+ if strings.HasPrefix(a.Url, "/plugins/") && !strings.HasPrefix(a.Url, pluginPrefix) {
+ return fmt.Errorf("manifest.actions[%d].url points at another plugin's namespace: %s", i, a.Url)
+ }
+ }
+ for i := range m.Actions {
+ rewritten, err := rewriteActionIcon(pluginPrefix, hasHTTPServe, m.Actions[i].Icon)
+ if err != nil {
+ return fmt.Errorf("manifest.actions[%d].icon: %w", i, err)
+ }
+ m.Actions[i].Icon = rewritten
+ }
+ return nil
+}
+
+// validateStyles checks manifest.styles entries and rewrites them
+// into absolute plugin-namespace URLs. Rules mirror manifest.actions
+// (relative paths auto-prefix to /plugins/<slug>/, cross-plugin paths
+// rejected, http.serve required since the host serves the bytes), but
+// stricter on the external-URL front: http(s):// targets are rejected
+// outright. Admins reviewing the manifest see every URL that will be
+// injected into their viewer's global CSS scope, so the list should
+// be exhaustive and self-contained. Plugins that need external assets
+// (fonts, etc.) can @import or @font-face them from inside the
+// bundled CSS, which is what the admin reviewed.
+func (m *Manifest) validateStyles() error {
+ if len(m.Styles) == 0 {
+ return nil
+ }
+ if !m.hasPermission(PermUIModify) {
+ return errors.New(
+ "manifest.styles is set but the manifest does not declare " +
+ "the \"ui.modify\" permission; plugins that inject CSS " +
+ "into the viewer's global scope must opt in to ui.modify " +
+ "so it's visible to anyone reviewing the manifest that the " +
+ "plugin restyles Owncast's UI")
+ }
+ if !m.hasPermission(PermHttpServe) {
+ return errors.New(
+ "manifest.styles requires the \"http.serve\" permission so the " +
+ "host can serve the bundled CSS files at /plugins/<slug>/ " +
+ "URLs")
+ }
+ for i, raw := range m.Styles {
+ rewritten, err := rewritePluginAssetPath(m.Slug, raw, ".css")
+ if err != nil {
+ return fmt.Errorf("manifest.styles[%d]: %w", i, err)
+ }
+ m.Styles[i] = rewritten
+ }
+ return nil
+}
+
+// validateScripts checks manifest.scripts entries and rewrites them
+// into absolute plugin-namespace URLs. Same rules as validateStyles
+// applied to .js files: each becomes a <script src=...> on the viewer
+// page, which runs in the chrome's window context. Permission gating
+// matches styles (ui.modify + http.serve) since scripts can manipulate
+// anything the viewer renders.
+func (m *Manifest) validateScripts() error {
+ if len(m.Scripts) == 0 {
+ return nil
+ }
+ if !m.hasPermission(PermUIModify) {
+ return errors.New(
+ "manifest.scripts is set but the manifest does not declare " +
+ "the \"ui.modify\" permission; plugins that inject " +
+ "JavaScript into the viewer page must opt in to ui.modify " +
+ "so it's visible to anyone reviewing the manifest that the " +
+ "plugin runs code inside Owncast's chrome")
+ }
+ if !m.hasPermission(PermHttpServe) {
+ return errors.New(
+ "manifest.scripts requires the \"http.serve\" permission so " +
+ "the host can serve the bundled JavaScript files at " +
+ "/plugins/<slug>/ URLs")
+ }
+ for i, raw := range m.Scripts {
+ rewritten, err := rewritePluginAssetPath(m.Slug, raw, ".js")
+ if err != nil {
+ return fmt.Errorf("manifest.scripts[%d]: %w", i, err)
+ }
+ m.Scripts[i] = rewritten
+ }
+ return nil
+}
+
+// validateExtraPageContent checks manifest.extraPageContent and
+// rewrites it into the plugin's namespace. The file's bytes are
+// inlined into the /api/config extraPageContent response (prepended
+// to the admin's content), not served as a URL, so http.serve is not
+// required, but the same path-shape and extension rules apply for
+// consistency with styles and scripts. ui.modify is required because
+// the contributed HTML lands inside the viewer chrome.
+func (m *Manifest) validateExtraPageContent() error {
+ if m.ExtraPageContent == "" {
+ return nil
+ }
+ if !m.hasPermission(PermUIModify) {
+ return errors.New(
+ "manifest.extraPageContent is set but the manifest does not " +
+ "declare the \"ui.modify\" permission; plugins that inject " +
+ "HTML into the viewer page must opt in to ui.modify so " +
+ "it's visible to anyone reviewing the manifest that the " +
+ "plugin paints inside Owncast's chrome")
+ }
+ rewritten, err := rewritePluginAssetPath(m.Slug, m.ExtraPageContent, ".html")
+ if err != nil {
+ return fmt.Errorf("manifest.extraPageContent: %w", err)
+ }
+ m.ExtraPageContent = rewritten
+ return nil
+}
+
+// validateTabs checks manifest.tabs entries and rewrites each tab's
+// content path into the plugin's namespace. The host reads the bytes
+// from assets/ at request time and inlines the HTML into the tab
+// body on /api/config (no URL is served), so only ui.modify is
+// required.
+func (m *Manifest) validateTabs() error {
+ if len(m.Tabs) == 0 {
+ return nil
+ }
+ if !m.hasPermission(PermUIModify) {
+ return errors.New(
+ "manifest.tabs is set but the manifest does not declare " +
+ "the \"ui.modify\" permission; plugins that add tabs " +
+ "to the viewer page must opt in to ui.modify so it's " +
+ "visible to anyone reviewing the manifest that the " +
+ "plugin paints inside Owncast's chrome")
+ }
+ // Reject duplicate titles within the same plugin. The frontend
+ // derives a React key from (slug, title), and a viewer staring at
+ // a row of two identically-named tabs has no way to tell them
+ // apart anyway, so making the manifest reject this at load is
+ // strictly better than silently accepting it.
+ seenTitles := make(map[string]bool, len(m.Tabs))
+ for i, tab := range m.Tabs {
+ if strings.TrimSpace(tab.Title) == "" {
+ return fmt.Errorf("manifest.tabs[%d].title is required", i)
+ }
+ if seenTitles[tab.Title] {
+ return fmt.Errorf("manifest.tabs[%d].title %q is a duplicate; tab titles must be unique within a plugin", i, tab.Title)
+ }
+ seenTitles[tab.Title] = true
+ rewritten, err := rewritePluginAssetPath(m.Slug, tab.Content, ".html")
+ if err != nil {
+ return fmt.Errorf("manifest.tabs[%d].content: %w", i, err)
+ }
+ m.Tabs[i].Content = rewritten
+ }
+ return nil
+}
+
+// rewritePluginAssetPath normalizes a single asset entry from a
+// styles/scripts list into the plugin's /plugins/<slug>/<file>
+// namespace and enforces the extension. Shared by validateStyles and
+// validateScripts because the rules are identical apart from the file
+// extension and the error context the caller wraps around it.
+func rewritePluginAssetPath(slug, raw, requiredExt string) (string, error) {
+ if strings.TrimSpace(raw) == "" {
+ return "", errors.New("entry is empty")
+ }
+ if strings.HasPrefix(raw, "http://") || strings.HasPrefix(raw, "https://") {
+ return "", fmt.Errorf("cannot be an absolute URL (%q); bundle the file under assets/ and reference it by path", raw)
+ }
+ pluginPrefix := "/plugins/" + slug + "/"
+ path := raw
+ switch {
+ case strings.HasPrefix(path, "/plugins/"):
+ // Already-absolute plugin path: must be in our own namespace.
+ case strings.HasPrefix(path, "/"):
+ path = pluginPrefix + strings.TrimPrefix(path, "/")
+ default:
+ path = pluginPrefix + path
+ }
+ if !strings.HasPrefix(path, pluginPrefix) {
+ return "", fmt.Errorf("points at another plugin's namespace: %s", path)
+ }
+ if !strings.HasSuffix(strings.ToLower(path), requiredExt) {
+ return "", fmt.Errorf("must end in %s (got %q)", requiredExt, raw)
+ }
+ return path, nil
+}
+
+// rewriteActionIcon applies the same path-handling rules to a button's
+// icon URL as we do to the button's url: a same-origin relative path is
+// rewritten into this plugin's namespace; an http(s) URL is left alone;
+// a cross-plugin path is rejected. Empty input passes through (icons
+// are optional).
+func rewriteActionIcon(pluginPrefix string, hasHTTPServe bool, icon string) (string, error) {
+ if icon == "" {
+ return "", nil
+ }
+ if strings.HasPrefix(icon, "http://") || strings.HasPrefix(icon, "https://") {
+ return icon, nil
+ }
+ if strings.HasPrefix(icon, "/") && !strings.HasPrefix(icon, "/plugins/") {
+ icon = pluginPrefix + strings.TrimPrefix(icon, "/")
+ }
+ if strings.HasPrefix(icon, pluginPrefix) && !hasHTTPServe {
+ return "", fmt.Errorf("targets this plugin (%s) but http.serve permission is not declared", icon)
+ }
+ if strings.HasPrefix(icon, "/plugins/") && !strings.HasPrefix(icon, pluginPrefix) {
+ return "", fmt.Errorf("points at another plugin's namespace: %s", icon)
+ }
+ return icon, nil
+}
+
+// AgreesWith reports whether the runtime registration `other` is consistent
+// with the sidecar manifest. The sidecar declares identity and permissions;
+// the runtime must not exceed declared permissions. Subscriptions are derived
+// by the SDK at runtime, so they aren't validated here.
+//
+// Identity is checked on Slug (the canonical identifier), not DisplayName:
+// the runtime side may not echo DisplayName back identically (the SDK doesn't
+// have to), but Slug is mechanically derived/declared the same way on both
+// sides, so it's the reliable identity column. When the runtime side ships
+// a Slug field, the two slugs are compared directly. When it doesn't (older
+// SDK that only emits DisplayName), the slug is derived from the runtime
+// DisplayName the same way ParseManifest derives it on the sidecar side
+// and the comparison falls through to the same result.
+func (m *Manifest) AgreesWith(other *Manifest) error {
+ // Resolve the slug on both sides: a sidecar that didn't go through
+ // ParseManifest (e.g. a test fixture) won't have Slug populated, but
+ // it should still produce the same identity from its DisplayName.
+ resolveSlug := func(x *Manifest) string {
+ if x.Slug != "" {
+ return x.Slug
+ }
+ if x.DisplayName == "" {
+ return ""
+ }
+ derived, err := slugify(x.DisplayName)
+ if err != nil {
+ return ""
+ }
+ return derived
+ }
+ mySlug := resolveSlug(m)
+ otherSlug := resolveSlug(other)
+ if mySlug != otherSlug {
+ return fmt.Errorf("slug mismatch: manifest=%q register=%q", mySlug, otherSlug)
+ }
+ if m.Version != other.Version {
+ return fmt.Errorf("version mismatch: manifest=%q register=%q", m.Version, other.Version)
+ }
+ declared := stringSet(m.Permissions)
+ for _, p := range other.Permissions {
+ if !declared[p] {
+ return fmt.Errorf("plugin requested permission %q at runtime not declared in manifest", p)
+ }
+ }
+ return nil
+}
+
+func stringSet(items []string) map[string]bool {
+ out := make(map[string]bool, len(items))
+ for _, i := range items {
+ out[i] = true
+ }
+ return out
+}
diff --git a/services/plugins/manifest_test.go b/services/plugins/manifest_test.go
new file mode 100644
index 0000000000..b2e8c739f0
--- /dev/null
+++ b/services/plugins/manifest_test.go
@@ -0,0 +1,879 @@
+package plugins
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestParseManifest_Valid(t *testing.T) {
+ in := []byte(`{
+ "api": "1",
+ "name": "demo",
+ "version": "1.2.3",
+ "description": "a demo plugin",
+ "permissions": ["chat.send", "storage.kv"]
+ }`)
+ m, err := ParseManifest(in)
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if m.DisplayName != "demo" {
+ t.Errorf("name: got %q want %q", m.DisplayName, "demo")
+ }
+ if m.Version != "1.2.3" {
+ t.Errorf("version: got %q want %q", m.Version, "1.2.3")
+ }
+ if len(m.Permissions) != 2 {
+ t.Errorf("permissions: got %v want 2 entries", m.Permissions)
+ }
+}
+
+func TestParseManifest_RejectsBadAPIVersion(t *testing.T) {
+ in := []byte(`{"api": "99", "name": "x", "version": "1.0.0"}`)
+ if _, err := ParseManifest(in); err == nil {
+ t.Fatal("expected error for unsupported api version, got nil")
+ } else if !strings.Contains(err.Error(), "unsupported api version") {
+ t.Errorf("error mentions api version: got %v", err)
+ }
+}
+
+func TestParseManifest_RequiresName(t *testing.T) {
+ in := []byte(`{"api": "1", "version": "1.0.0"}`)
+ if _, err := ParseManifest(in); err == nil {
+ t.Fatal("expected error for missing name, got nil")
+ } else if !strings.Contains(err.Error(), "name") {
+ t.Errorf("error mentions name: got %v", err)
+ }
+}
+
+func TestParseManifest_RequiresVersion(t *testing.T) {
+ in := []byte(`{"api": "1", "name": "x"}`)
+ if _, err := ParseManifest(in); err == nil {
+ t.Fatal("expected error for missing version, got nil")
+ } else if !strings.Contains(err.Error(), "version") {
+ t.Errorf("error mentions version: got %v", err)
+ }
+}
+
+func TestParseManifest_RejectsMalformedJSON(t *testing.T) {
+ in := []byte(`{not valid json`)
+ if _, err := ParseManifest(in); err == nil {
+ t.Fatal("expected error for malformed json, got nil")
+ }
+}
+
+func TestAgreesWith_HappyPath(t *testing.T) {
+ sidecar := &Manifest{
+ API: "1", DisplayName: "demo", Version: "1.0.0",
+ Permissions: []string{"chat.send", "storage.kv"},
+ }
+ runtime := &Manifest{
+ API: "1", DisplayName: "demo", Version: "1.0.0",
+ Permissions: []string{"chat.send"}, // subset OK
+ }
+ if err := sidecar.AgreesWith(runtime); err != nil {
+ t.Errorf("expected agreement, got error: %v", err)
+ }
+}
+
+func TestAgreesWith_SlugMismatch(t *testing.T) {
+ // AgreesWith identity-checks on Slug. When the runtime side ships no
+ // explicit slug, the host derives one from the runtime DisplayName the
+ // same way ParseManifest does on the sidecar side, so a clean string
+ // like "demo" vs "other" still trips the mismatch path.
+ sidecar := &Manifest{API: "1", DisplayName: "demo", Slug: "demo", Version: "1.0.0"}
+ runtime := &Manifest{API: "1", DisplayName: "other", Version: "1.0.0"}
+ err := sidecar.AgreesWith(runtime)
+ if err == nil || !strings.Contains(err.Error(), "slug mismatch") {
+ t.Errorf("expected slug mismatch error, got: %v", err)
+ }
+}
+
+func TestAgreesWith_VersionMismatch(t *testing.T) {
+ sidecar := &Manifest{API: "1", DisplayName: "demo", Version: "1.0.0"}
+ runtime := &Manifest{API: "1", DisplayName: "demo", Version: "2.0.0"}
+ err := sidecar.AgreesWith(runtime)
+ if err == nil || !strings.Contains(err.Error(), "version mismatch") {
+ t.Errorf("expected version mismatch error, got: %v", err)
+ }
+}
+
+func TestAgreesWith_RuntimeExceedsDeclaredPermissions(t *testing.T) {
+ sidecar := &Manifest{
+ API: "1", DisplayName: "demo", Version: "1.0.0",
+ Permissions: []string{"chat.send"},
+ }
+ runtime := &Manifest{
+ API: "1", DisplayName: "demo", Version: "1.0.0",
+ Permissions: []string{"chat.send", "events.emit"}, // events.emit not declared
+ }
+ err := sidecar.AgreesWith(runtime)
+ if err == nil {
+ t.Fatal("expected error for runtime claiming undeclared permission, got nil")
+ }
+ if !strings.Contains(err.Error(), "events.emit") {
+ t.Errorf("error mentions the undeclared permission: got %v", err)
+ }
+}
+
+func TestStrikeSystem_FilterFailuresAutoDisable(t *testing.T) {
+ l := &Loaded{Manifest: &Manifest{DisplayName: "x"}}
+ for i := 0; i < FilterStrikeThreshold-1; i++ {
+ if disabled := l.recordFilterFailure(); disabled {
+ t.Fatalf("disabled too early at strike %d", i+1)
+ }
+ if l.IsDisabled() {
+ t.Fatalf("IsDisabled() returned true at strike %d", i+1)
+ }
+ }
+ if disabled := l.recordFilterFailure(); !disabled {
+ t.Fatal("recordFilterFailure should have reported newly-disabled on the threshold strike")
+ }
+ if !l.IsDisabled() {
+ t.Fatal("IsDisabled() should be true after threshold reached")
+ }
+ // Subsequent failures don't re-trigger the "newly disabled" signal.
+ if disabled := l.recordFilterFailure(); disabled {
+ t.Error("recordFilterFailure should not report newly-disabled twice")
+ }
+}
+
+func TestStrikeSystem_SuccessResetsCounter(t *testing.T) {
+ l := &Loaded{Manifest: &Manifest{DisplayName: "x"}}
+ // Rack up almost enough strikes to disable.
+ for i := 0; i < FilterStrikeThreshold-1; i++ {
+ l.recordFilterFailure()
+ }
+ // One success should reset the counter.
+ l.recordFilterSuccess()
+ if l.IsDisabled() {
+ t.Fatal("success should have prevented auto-disable on the next failure batch")
+ }
+ // We can rack up failures again without tripping the threshold immediately.
+ for i := 0; i < FilterStrikeThreshold-1; i++ {
+ if disabled := l.recordFilterFailure(); disabled {
+ t.Fatalf("disabled too early after reset, at strike %d", i+1)
+ }
+ }
+}
+
+func TestAgreesWith_SidecarMayDeclareMoreThanRuntimeUses(t *testing.T) {
+ // The asymmetry: sidecar is the upper bound. Plugin author can declare
+ // more than they end up using.
+ sidecar := &Manifest{
+ API: "1", DisplayName: "demo", Version: "1.0.0",
+ Permissions: []string{"chat.send", "storage.kv", "network.fetch"},
+ }
+ runtime := &Manifest{
+ API: "1", DisplayName: "demo", Version: "1.0.0",
+ Permissions: []string{"chat.send"},
+ }
+ if err := sidecar.AgreesWith(runtime); err != nil {
+ t.Errorf("sidecar should allow runtime to use subset of declared perms; got: %v", err)
+ }
+}
+
+func TestParseManifest_Action_RelativeURLIsRewritten(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["http.serve", "ui.modify"],
+ "actions": [{"title": "Dashboard", "url": "/dashboard"}]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if len(m.Actions) != 1 || m.Actions[0].Url != "/plugins/stats/dashboard" {
+ t.Errorf("url should auto-prefix to /plugins/stats/dashboard, got %q", m.Actions[0].Url)
+ }
+}
+
+func TestParseManifest_Action_BareSlashIsRewritten(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["http.serve", "ui.modify"],
+ "actions": [{"title": "Dashboard", "url": "/"}]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if m.Actions[0].Url != "/plugins/stats/" {
+ t.Errorf("url '/' should rewrite to /plugins/stats/, got %q", m.Actions[0].Url)
+ }
+}
+
+func TestParseManifest_Action_ExplicitPluginPathPreserved(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["http.serve", "ui.modify"],
+ "actions": [{"title": "Dashboard", "url": "/plugins/stats/foo"}]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if m.Actions[0].Url != "/plugins/stats/foo" {
+ t.Errorf("explicit plugin path should be preserved, got %q", m.Actions[0].Url)
+ }
+}
+
+func TestParseManifest_Action_ExternalURLPreserved(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"title": "External", "url": "https://example.com/help"}]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if m.Actions[0].Url != "https://example.com/help" {
+ t.Errorf("absolute URL should be preserved, got %q", m.Actions[0].Url)
+ }
+}
+
+func TestParseManifest_Action_MissingHttpServePerm(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"title": "Dashboard", "url": "/dashboard"}]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: action targets self but http.serve not declared")
+ }
+ if !strings.Contains(err.Error(), "http.serve") {
+ t.Errorf("error should mention http.serve, got: %v", err)
+ }
+}
+
+func TestParseManifest_Action_PointsAtOtherPlugin(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"title": "Other", "url": "/plugins/other-plugin/page"}]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: action points at another plugin's namespace")
+ }
+ if !strings.Contains(err.Error(), "other plugin's namespace") {
+ t.Errorf("error should call out cross-plugin URL, got: %v", err)
+ }
+}
+
+func TestParseManifest_Action_IconRelativeIsRewritten(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["http.serve", "ui.modify"],
+ "actions": [{"title": "Dashboard", "url": "/dashboard", "icon": "/star.png"}]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if m.Actions[0].Icon != "/plugins/stats/star.png" {
+ t.Errorf("icon should auto-prefix to /plugins/stats/star.png, got %q", m.Actions[0].Icon)
+ }
+}
+
+func TestParseManifest_Action_IconExternalPreserved(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"title": "External", "url": "https://example.com", "icon": "https://cdn.example.com/star.png"}]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if m.Actions[0].Icon != "https://cdn.example.com/star.png" {
+ t.Errorf("absolute icon URL should be preserved, got %q", m.Actions[0].Icon)
+ }
+}
+
+func TestParseManifest_Action_IconMissingHttpServePerm(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"title": "External", "url": "https://example.com", "icon": "/star.png"}]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: icon targets self but http.serve not declared")
+ }
+ if !strings.Contains(err.Error(), "http.serve") {
+ t.Errorf("error should mention http.serve, got: %v", err)
+ }
+}
+
+func TestParseManifest_Action_IconPointsAtOtherPlugin(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"title": "External", "url": "https://example.com", "icon": "/plugins/other-plugin/star.png"}]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: icon points at another plugin's namespace")
+ }
+ if !strings.Contains(err.Error(), "other plugin's namespace") {
+ t.Errorf("error should call out cross-plugin icon, got: %v", err)
+ }
+}
+
+func TestParseManifest_Action_TitleRequired(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"url": "https://example.com"}]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: title required")
+ }
+}
+
+func TestParseManifest_Action_UrlXorHtml(t *testing.T) {
+ cases := []struct {
+ name, body string
+ }{
+ {"both", `{"title": "x", "url": "https://e.com", "html": "<p>x</p>"}`},
+ {"neither", `{"title": "x"}`},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [` + c.body + `]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: exactly one of url or html is required")
+ }
+ })
+ }
+}
+
+func TestParseManifest_Action_HtmlOnly(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "actions": [{"title": "Info", "html": "<p>hello</p>"}]
+ }`))
+ if err != nil {
+ t.Fatalf("html-only action should be valid (no http.serve needed): %v", err)
+ }
+ if m.Actions[0].Html != "<p>hello</p>" {
+ t.Errorf("html lost: %q", m.Actions[0].Html)
+ }
+}
+
+func TestParseManifest_UIModify_RequiredForActions(t *testing.T) {
+ // A plugin that contributes a viewer action button must declare
+ // "ui.modify" so the surface is visible in the permission list.
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "actions": [{"title": "x", "url": "https://example.com"}]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: actions without ui.modify permission")
+ }
+ if !strings.Contains(err.Error(), "ui.modify") {
+ t.Errorf("error should mention ui.modify, got: %v", err)
+ }
+}
+
+func TestParseManifest_AdminPages_NoUIModifyRequired(t *testing.T) {
+ // Admin pages live in their own /plugins/<name>/admin namespace and
+ // don't alter Owncast's existing UI, so they're baseline plugin
+ // functionality, no ui.modify permission required.
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "stats", "version": "1.0",
+ "permissions": ["http.serve"],
+ "admin": {"pages": [{"title": "x", "path": "/admin"}]}
+ }`))
+ if err != nil {
+ t.Errorf("admin.pages should not require ui.modify: %v", err)
+ }
+}
+
+func TestParseManifest_UIModify_NotRequiredWhenNoUI(t *testing.T) {
+ // A plugin that doesn't declare any UI surfaces should not be forced
+ // to declare ui.modify — the permission is opt-in only for plugins
+ // that contribute to the host's UI.
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "headless", "version": "1.0"
+ }`))
+ if err != nil {
+ t.Errorf("headless plugin with no UI surfaces should be valid: %v", err)
+ }
+}
+
+func TestParseManifest_Styles_RewritesRelativePaths(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "styled", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "styles": ["theme.css", "/extra.css", "/plugins/styled/another.css"]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ want := []string{"/plugins/styled/theme.css", "/plugins/styled/extra.css", "/plugins/styled/another.css"}
+ if len(m.Styles) != len(want) {
+ t.Fatalf("styles count: got %v want %v", m.Styles, want)
+ }
+ for i, w := range want {
+ if m.Styles[i] != w {
+ t.Errorf("styles[%d] = %q, want %q", i, m.Styles[i], w)
+ }
+ }
+}
+
+func TestParseManifest_Styles_RequiresUIModify(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "styled", "version": "1.0",
+ "permissions": ["http.serve"],
+ "styles": ["theme.css"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error when styles is set without ui.modify")
+ }
+ if !strings.Contains(err.Error(), "ui.modify") {
+ t.Errorf("error should mention ui.modify, got: %v", err)
+ }
+}
+
+func TestParseManifest_Styles_RequiresHttpServe(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "styled", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "styles": ["theme.css"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error when styles is set without http.serve")
+ }
+ if !strings.Contains(err.Error(), "http.serve") {
+ t.Errorf("error should mention http.serve, got: %v", err)
+ }
+}
+
+func TestParseManifest_Styles_RejectsCrossPluginPath(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "styled", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "styles": ["/plugins/some-other-plugin/theme.css"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: cross-plugin style path")
+ }
+ if !strings.Contains(err.Error(), "another plugin's namespace") {
+ t.Errorf("error should call out cross-plugin path, got: %v", err)
+ }
+}
+
+func TestParseManifest_Styles_RejectsAbsoluteURL(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "styled", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "styles": ["https://fonts.example.com/theme.css"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: absolute URLs rejected for styles")
+ }
+ if !strings.Contains(err.Error(), "absolute URL") {
+ t.Errorf("error should call out absolute URL, got: %v", err)
+ }
+}
+
+func TestParseManifest_Styles_RejectsNonCssExtension(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "styled", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "styles": ["theme.scss"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: only .css extension allowed")
+ }
+ if !strings.Contains(err.Error(), ".css") {
+ t.Errorf("error should call out .css, got: %v", err)
+ }
+}
+
+func TestParseManifest_Scripts_RewritesRelativePaths(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "scripted", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "scripts": ["client.js", "/extra.js", "/plugins/scripted/another.js"]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ want := []string{"/plugins/scripted/client.js", "/plugins/scripted/extra.js", "/plugins/scripted/another.js"}
+ if len(m.Scripts) != len(want) {
+ t.Fatalf("scripts count: got %v want %v", m.Scripts, want)
+ }
+ for i, w := range want {
+ if m.Scripts[i] != w {
+ t.Errorf("scripts[%d] = %q, want %q", i, m.Scripts[i], w)
+ }
+ }
+}
+
+func TestParseManifest_Scripts_RequiresUIModify(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "scripted", "version": "1.0",
+ "permissions": ["http.serve"],
+ "scripts": ["client.js"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error when scripts is set without ui.modify")
+ }
+ if !strings.Contains(err.Error(), "ui.modify") {
+ t.Errorf("error should mention ui.modify, got: %v", err)
+ }
+}
+
+func TestParseManifest_Scripts_RequiresHttpServe(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "scripted", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "scripts": ["client.js"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error when scripts is set without http.serve")
+ }
+ if !strings.Contains(err.Error(), "http.serve") {
+ t.Errorf("error should mention http.serve, got: %v", err)
+ }
+}
+
+func TestParseManifest_Scripts_RejectsCrossPluginPath(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "scripted", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "scripts": ["/plugins/some-other-plugin/client.js"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: cross-plugin script path")
+ }
+ if !strings.Contains(err.Error(), "another plugin's namespace") {
+ t.Errorf("error should call out cross-plugin path, got: %v", err)
+ }
+}
+
+func TestParseManifest_Scripts_RejectsAbsoluteURL(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "scripted", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "scripts": ["https://cdn.example.com/client.js"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: absolute URLs rejected for scripts")
+ }
+ if !strings.Contains(err.Error(), "absolute URL") {
+ t.Errorf("error should call out absolute URL, got: %v", err)
+ }
+}
+
+func TestParseManifest_Scripts_RejectsNonJsExtension(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "scripted", "version": "1.0",
+ "permissions": ["ui.modify", "http.serve"],
+ "scripts": ["client.ts"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: only .js extension allowed")
+ }
+ if !strings.Contains(err.Error(), ".js") {
+ t.Errorf("error should call out .js, got: %v", err)
+ }
+}
+
+func TestParseManifest_ExtraPageContent_RewritesRelativePath(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "page", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "extraPageContent": "content.html"
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if m.ExtraPageContent != "/plugins/page/content.html" {
+ t.Errorf("extraPageContent = %q, want /plugins/page/content.html", m.ExtraPageContent)
+ }
+}
+
+func TestParseManifest_ExtraPageContent_DoesNotRequireHttpServe(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "page", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "extraPageContent": "content.html"
+ }`))
+ if err != nil {
+ t.Errorf("extraPageContent should not require http.serve: %v", err)
+ }
+}
+
+func TestParseManifest_ExtraPageContent_RequiresUIModify(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "page", "version": "1.0",
+ "extraPageContent": "content.html"
+ }`))
+ if err == nil {
+ t.Fatal("expected error when extraPageContent is set without ui.modify")
+ }
+ if !strings.Contains(err.Error(), "ui.modify") {
+ t.Errorf("error should mention ui.modify, got: %v", err)
+ }
+}
+
+func TestParseManifest_ExtraPageContent_RejectsCrossPluginPath(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "page", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "extraPageContent": "/plugins/some-other-plugin/content.html"
+ }`))
+ if err == nil {
+ t.Fatal("expected error: cross-plugin extraPageContent path")
+ }
+ if !strings.Contains(err.Error(), "another plugin's namespace") {
+ t.Errorf("error should call out cross-plugin path, got: %v", err)
+ }
+}
+
+func TestParseManifest_ExtraPageContent_RejectsAbsoluteURL(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "page", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "extraPageContent": "https://cdn.example.com/content.html"
+ }`))
+ if err == nil {
+ t.Fatal("expected error: absolute URLs rejected for extraPageContent")
+ }
+ if !strings.Contains(err.Error(), "absolute URL") {
+ t.Errorf("error should call out absolute URL, got: %v", err)
+ }
+}
+
+func TestParseManifest_ExtraPageContent_RejectsNonHtmlExtension(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "page", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "extraPageContent": "content.htm"
+ }`))
+ if err == nil {
+ t.Fatal("expected error: only .html extension allowed")
+ }
+ if !strings.Contains(err.Error(), ".html") {
+ t.Errorf("error should call out .html, got: %v", err)
+ }
+}
+
+func TestParseManifest_Tabs_RewritesContentPaths(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "tabbed", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "tabs": [
+ { "title": "Music", "content": "music.html" },
+ { "title": "Photos", "content": "/photos.html" }
+ ]
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ want := []Tab{
+ {Title: "Music", Content: "/plugins/tabbed/music.html"},
+ {Title: "Photos", Content: "/plugins/tabbed/photos.html"},
+ }
+ if len(m.Tabs) != len(want) {
+ t.Fatalf("tabs count: got %d want %d", len(m.Tabs), len(want))
+ }
+ for i, w := range want {
+ if m.Tabs[i] != w {
+ t.Errorf("tabs[%d] = %+v, want %+v", i, m.Tabs[i], w)
+ }
+ }
+}
+
+func TestParseManifest_Tabs_RequiresUIModify(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "tabbed", "version": "1.0",
+ "tabs": [{ "title": "Music", "content": "music.html" }]
+ }`))
+ if err == nil {
+ t.Fatal("expected error when tabs is set without ui.modify")
+ }
+ if !strings.Contains(err.Error(), "ui.modify") {
+ t.Errorf("error should mention ui.modify, got: %v", err)
+ }
+}
+
+func TestParseManifest_Tabs_RequiresTitle(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "tabbed", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "tabs": [{ "title": "", "content": "music.html" }]
+ }`))
+ if err == nil {
+ t.Fatal("expected error when tab.title is empty")
+ }
+ if !strings.Contains(err.Error(), "title is required") {
+ t.Errorf("error should call out title, got: %v", err)
+ }
+}
+
+func TestParseManifest_Tabs_RejectsDuplicateTitles(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "tabbed", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "tabs": [
+ { "title": "Music", "content": "a.html" },
+ { "title": "Music", "content": "b.html" }
+ ]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: duplicate tab titles")
+ }
+ if !strings.Contains(err.Error(), "duplicate") {
+ t.Errorf("error should call out duplicate, got: %v", err)
+ }
+}
+
+func TestParseManifest_Tabs_RejectsCrossPluginPath(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "tabbed", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "tabs": [{ "title": "Other", "content": "/plugins/some-other-plugin/x.html" }]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: cross-plugin tab content path")
+ }
+ if !strings.Contains(err.Error(), "another plugin's namespace") {
+ t.Errorf("error should call out cross-plugin path, got: %v", err)
+ }
+}
+
+func TestParseManifest_Tabs_RejectsNonHtmlExtension(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "tabbed", "version": "1.0",
+ "permissions": ["ui.modify"],
+ "tabs": [{ "title": "Bad", "content": "music.txt" }]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: only .html extension allowed for tabs")
+ }
+ if !strings.Contains(err.Error(), ".html") {
+ t.Errorf("error should call out .html, got: %v", err)
+ }
+}
+
+func TestParseManifest_Network_AllowedHostsRequiredWithFetch(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "demo", "version": "1.0",
+ "permissions": ["network.fetch"]
+ }`))
+ if err == nil {
+ t.Fatal("expected error: network.fetch requires allowedHosts")
+ }
+ if !strings.Contains(err.Error(), "network.allowedHosts") {
+ t.Errorf("error should reference network.allowedHosts: %v", err)
+ }
+}
+
+func TestParseManifest_Network_AllowedHostsEmptyWithFetch(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "demo", "version": "1.0",
+ "permissions": ["network.fetch"],
+ "network": { "allowedHosts": [] }
+ }`))
+ if err == nil {
+ t.Fatal("expected error: empty allowedHosts with network.fetch")
+ }
+}
+
+func TestParseManifest_Network_PassesThroughHosts(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "demo", "version": "1.0",
+ "permissions": ["network.fetch"],
+ "network": { "allowedHosts": ["api.discord.com", "*.weather.com"] }
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if len(m.Network.AllowedHosts) != 2 ||
+ m.Network.AllowedHosts[0] != "api.discord.com" ||
+ m.Network.AllowedHosts[1] != "*.weather.com" {
+ t.Errorf("allowedHosts not preserved: %v", m.Network.AllowedHosts)
+ }
+}
+
+func TestParseManifest_Network_ExplicitWildcardOK(t *testing.T) {
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "demo", "version": "1.0",
+ "permissions": ["network.fetch"],
+ "network": { "allowedHosts": ["*"] }
+ }`))
+ if err != nil {
+ t.Fatalf("explicit \"*\" should be valid: %v", err)
+ }
+ if len(m.Network.AllowedHosts) != 1 || m.Network.AllowedHosts[0] != "*" {
+ t.Errorf("wildcard not preserved: %v", m.Network.AllowedHosts)
+ }
+}
+
+func TestParseManifest_Network_BlankHostRejected(t *testing.T) {
+ _, err := ParseManifest([]byte(`{
+ "api": "1", "name": "demo", "version": "1.0",
+ "permissions": ["network.fetch"],
+ "network": { "allowedHosts": ["api.example.com", " "] }
+ }`))
+ if err == nil {
+ t.Fatal("expected error: blank host in allowedHosts")
+ }
+}
+
+func TestParseManifest_Network_NoFetchPermissionAllowsAnyShape(t *testing.T) {
+ // A manifest with allowedHosts but without network.fetch is valid;
+ // the field is just inert.
+ m, err := ParseManifest([]byte(`{
+ "api": "1", "name": "demo", "version": "1.0",
+ "network": { "allowedHosts": ["api.discord.com"] }
+ }`))
+ if err != nil {
+ t.Fatalf("parse: %v", err)
+ }
+ if len(m.Network.AllowedHosts) != 1 {
+ t.Errorf("allowedHosts should be preserved even without fetch perm: %v", m.Network.AllowedHosts)
+ }
+}
+
+func TestRequireChatFilterPermission_RejectsWhenMissing(t *testing.T) {
+ // A plugin that subscribes to filterChatMessage at register-time must
+ // declare the chat.filter permission in its manifest. The host refuses
+ // to load otherwise so the admin can't be surprised by a plugin that
+ // silently starts rewriting chat.
+ m := &Manifest{DisplayName: "stealth", Permissions: nil}
+ subs := Subscriptions{
+ Filter: []Subscription{{Event: EventChatMessageReceived, Priority: 100}},
+ }
+ err := requireChatFilterPermission(m, subs)
+ if err == nil {
+ t.Fatal("expected error when filterChatMessage is subscribed without chat.filter")
+ }
+ if !strings.Contains(err.Error(), PermChatFilter) {
+ t.Errorf("error should mention %q, got: %v", PermChatFilter, err)
+ }
+}
+
+func TestRequireChatFilterPermission_AcceptsWhenDeclared(t *testing.T) {
+ m := &Manifest{DisplayName: "honest", Permissions: []string{PermChatFilter}}
+ subs := Subscriptions{
+ Filter: []Subscription{{Event: EventChatMessageReceived, Priority: 100}},
+ }
+ if err := requireChatFilterPermission(m, subs); err != nil {
+ t.Errorf("declared chat.filter should accept: %v", err)
+ }
+}
+
+func TestRequireChatFilterPermission_NoOpWhenNoFilterSubscription(t *testing.T) {
+ // A plugin that doesn't subscribe to filterChatMessage at all should
+ // pass through, regardless of whether it declares chat.filter.
+ m := &Manifest{DisplayName: "passive", Permissions: nil}
+ subs := Subscriptions{
+ Filter: []Subscription{{Event: "some-other-event", Priority: 100}},
+ }
+ if err := requireChatFilterPermission(m, subs); err != nil {
+ t.Errorf("non-chat filter subscription should not require chat.filter: %v", err)
+ }
+}
diff --git a/services/plugins/package.go b/services/plugins/package.go
new file mode 100644
index 0000000000..ec95354c95
--- /dev/null
+++ b/services/plugins/package.go
@@ -0,0 +1,136 @@
+package plugins
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "fmt"
+ "io/fs"
+ "path/filepath"
+ "strings"
+)
+
+// The .ocpkg ("Owncast plugin package") format is a zip archive with four
+// well-known entries:
+//
+// plugin.manifest.json required, the sidecar manifest
+// plugin.wasm required, the compiled plugin module
+// public/... optional, files served at /plugins/<name>/<path>
+// assets/... optional, files the host reads internally for
+// manifest fields that inline content
+// (styles, scripts, extraPageContent); never
+// reachable through the plugin's URL space.
+//
+// File names inside the archive are canonical regardless of the plugin's name
+// so the host doesn't have to read the manifest to discover the wasm path.
+// The plugin's name still comes from manifest.name, not the .ocpkg filename.
+const (
+ packageSuffix = ".ocpkg"
+ pkgManifestFilename = "plugin.manifest.json"
+ pkgWasmFilename = "plugin.wasm"
+ pkgPublicPrefix = "public/"
+ pkgAssetsPrefix = "assets/"
+)
+
+// LoadPackage loads a plugin from a .ocpkg file. The archive is opened with
+// a file-backed reader so only the central directory and the manifest/wasm
+// entries actually enter memory; per-asset reads happen on demand when the
+// HTTP server fetches them. The *zip.ReadCloser is retained on the returned
+// Loaded so the underlying file stays open for AssetsFS lookups, and is
+// closed when Loaded.Close runs.
+func LoadPackage(ctx context.Context, env *HostEnv, path string) (*Loaded, error) {
+ zr, err := zip.OpenReader(path)
+ if err != nil {
+ return nil, fmt.Errorf("open %s as zip: %w", path, err)
+ }
+ // Until we hand ownership to the returned Loaded, any error path must
+ // close zr or we leak the file handle.
+ closeOnFail := zr
+ defer func() {
+ if closeOnFail != nil {
+ _ = closeOnFail.Close()
+ }
+ }()
+
+ manifestBytes, err := readZipFile(&zr.Reader, pkgManifestFilename)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", filepath.Base(path), err)
+ }
+ wasmBytes, err := readZipFile(&zr.Reader, pkgWasmFilename)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", filepath.Base(path), err)
+ }
+
+ displayName := strings.TrimSuffix(filepath.Base(path), packageSuffix)
+ loaded, err := loadFromBytes(ctx, env, manifestBytes, wasmBytes, displayName)
+ if err != nil {
+ return nil, err
+ }
+ loaded.WasmPath = path
+ loaded.pkgCloser = zr
+
+ // Mount public/ as the plugin's web-served root and assets/ as
+ // the internal-only root, when each is present. fs.Sub returns
+ // an FS that's empty (rather than failing) when the prefix
+ // doesn't exist, so we check first to keep the nil-means-empty
+ // invariant the Server (PublicFS) and the manifest-asset reader
+ // (AssetsFS) rely on.
+ if hasZipDir(&zr.Reader, pkgPublicPrefix) {
+ if sub, err := fs.Sub(&zr.Reader, strings.TrimSuffix(pkgPublicPrefix, "/")); err == nil {
+ loaded.PublicFS = sub
+ }
+ }
+ if hasZipDir(&zr.Reader, pkgAssetsPrefix) {
+ if sub, err := fs.Sub(&zr.Reader, strings.TrimSuffix(pkgAssetsPrefix, "/")); err == nil {
+ loaded.AssetsFS = sub
+ }
+ }
+
+ closeOnFail = nil // ownership transferred to Loaded.pkgCloser
+ return loaded, nil
+}
+
+// readManifestFromPackage reads just the plugin.manifest.json entry from a
+// .ocpkg file without instantiating the wasm. Used by Manager.scan() — runs
+// every couple seconds, so the file-backed reader matters: a multi-gigabyte
+// .ocpkg sitting in plugins/ costs only a central-directory read per scan,
+// not a full slurp into memory.
+func readManifestFromPackage(path string) (*Manifest, error) {
+ zr, err := zip.OpenReader(path)
+ if err != nil {
+ return nil, fmt.Errorf("open %s as zip: %w", path, err)
+ }
+ defer zr.Close()
+ manifestBytes, err := readZipFile(&zr.Reader, pkgManifestFilename)
+ if err != nil {
+ return nil, fmt.Errorf("%s: %w", filepath.Base(path), err)
+ }
+ return ParseManifest(manifestBytes)
+}
+
+func readZipFile(zr *zip.Reader, name string) ([]byte, error) {
+ for _, f := range zr.File {
+ if f.Name == name {
+ rc, err := f.Open()
+ if err != nil {
+ return nil, fmt.Errorf("open %s: %w", name, err)
+ }
+ defer rc.Close()
+ buf := &bytes.Buffer{}
+ if _, err := buf.ReadFrom(rc); err != nil {
+ return nil, fmt.Errorf("read %s: %w", name, err)
+ }
+ return buf.Bytes(), nil
+ }
+ }
+ return nil, fmt.Errorf("missing required entry %q", name)
+}
+
+func hasZipDir(zr *zip.Reader, prefix string) bool {
+ for _, f := range zr.File {
+ if strings.HasPrefix(f.Name, prefix) {
+ return true
+ }
+ }
+ return false
+}
diff --git a/services/plugins/package_test.go b/services/plugins/package_test.go
new file mode 100644
index 0000000000..c2bcf1ee03
--- /dev/null
+++ b/services/plugins/package_test.go
@@ -0,0 +1,318 @@
+package plugins
+
+import (
+ "archive/zip"
+ "bytes"
+ "context"
+ "io"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+// findExampleWasm returns the path to a real example wasm we can use to make
+// happy-path package tests realistic. Tests that need actual wasm bytes
+// t.Skip() if no example has been built yet. Looks in the in-tree examples
+// directory first, then falls back to the sibling owncast-plugin-sdk
+// checkout (where examples live after the SDK split).
+func findExampleWasm(t *testing.T) string {
+ t.Helper()
+ _, thisFile, _, _ := runtime.Caller(0)
+ repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..")
+ candidates := []string{
+ filepath.Join(repoRoot, "examples", "js", "hello-world", "hello-world.wasm"),
+ filepath.Join(repoRoot, "..", "owncast-plugin-sdk", "examples", "js", "hello-world", "hello-world.wasm"),
+ }
+ for _, c := range candidates {
+ if _, err := os.Stat(c); err == nil {
+ return c
+ }
+ }
+ t.Skipf("example wasm not built in any of %v; run npm run build in examples/js/hello-world first", candidates)
+ return ""
+}
+
+// buildPkg writes a .ocpkg-shaped zip to a temp file and returns the path.
+func buildPkg(t *testing.T, entries map[string][]byte) string {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "test.ocpkg")
+ f, err := os.Create(path)
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ defer f.Close()
+ zw := zip.NewWriter(f)
+ for name, data := range entries {
+ w, err := zw.Create(name)
+ if err != nil {
+ t.Fatalf("zip create %s: %v", name, err)
+ }
+ if _, err := w.Write(data); err != nil {
+ t.Fatalf("zip write %s: %v", name, err)
+ }
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatalf("zip close: %v", err)
+ }
+ return path
+}
+
+func validManifestBytes() []byte {
+ return []byte(`{
+ "api": "1",
+ "name": "hello-world",
+ "version": "0.1.0",
+ "description": "test",
+ "permissions": []
+ }`)
+}
+
+func TestLoadPackage_MissingManifest(t *testing.T) {
+ path := buildPkg(t, map[string][]byte{
+ pkgWasmFilename: {0x00}, // not parsed; the manifest check fails first
+ })
+ _, err := LoadPackage(context.Background(), &HostEnv{}, path)
+ if err == nil {
+ t.Fatal("expected error for missing manifest, got nil")
+ }
+ if !strings.Contains(err.Error(), pkgManifestFilename) {
+ t.Errorf("error mentions manifest filename: got %v", err)
+ }
+}
+
+func TestLoadPackage_MissingWasm(t *testing.T) {
+ path := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ })
+ _, err := LoadPackage(context.Background(), &HostEnv{}, path)
+ if err == nil {
+ t.Fatal("expected error for missing wasm, got nil")
+ }
+ if !strings.Contains(err.Error(), pkgWasmFilename) {
+ t.Errorf("error mentions wasm filename: got %v", err)
+ }
+}
+
+func TestLoadPackage_CorruptZip(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "bad.ocpkg")
+ if err := os.WriteFile(path, []byte("this is not a zip file at all"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ _, err := LoadPackage(context.Background(), &HostEnv{}, path)
+ if err == nil {
+ t.Fatal("expected error for corrupt zip, got nil")
+ }
+}
+
+func TestLoadPackage_MalformedManifestJSON(t *testing.T) {
+ path := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: []byte(`{not valid json`),
+ pkgWasmFilename: {0x00},
+ })
+ _, err := LoadPackage(context.Background(), &HostEnv{}, path)
+ if err == nil {
+ t.Fatal("expected error for malformed manifest, got nil")
+ }
+}
+
+func TestLoadPackage_MissingPathReturnsError(t *testing.T) {
+ _, err := LoadPackage(context.Background(), &HostEnv{}, "/nonexistent/path/foo.ocpkg")
+ if err == nil {
+ t.Fatal("expected error for missing file, got nil")
+ }
+}
+
+func TestLoadPackage_AssetsExposedAsFS(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, err := os.ReadFile(wasmPath)
+ if err != nil {
+ t.Fatalf("read example wasm: %v", err)
+ }
+ path := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ pkgWasmFilename: wasmBytes,
+ pkgAssetsPrefix + "index.html": []byte("<h1>hi</h1>"),
+ pkgAssetsPrefix + "sub/style.css": []byte("body{}"),
+ })
+
+ loaded, err := LoadPackage(context.Background(), &HostEnv{}, path)
+ if err != nil {
+ t.Fatalf("load: %v", err)
+ }
+ defer loaded.Close(context.Background())
+
+ if loaded.AssetsFS == nil {
+ t.Fatal("expected AssetsFS to be set when assets/ present in archive")
+ }
+
+ got, err := fs.ReadFile(loaded.AssetsFS, "index.html")
+ if err != nil {
+ t.Fatalf("read assets/index.html: %v", err)
+ }
+ if !bytes.Equal(got, []byte("<h1>hi</h1>")) {
+ t.Errorf("index.html: got %q want %q", got, "<h1>hi</h1>")
+ }
+
+ got, err = fs.ReadFile(loaded.AssetsFS, "sub/style.css")
+ if err != nil {
+ t.Fatalf("read nested asset: %v", err)
+ }
+ if !bytes.Equal(got, []byte("body{}")) {
+ t.Errorf("sub/style.css: got %q", got)
+ }
+}
+
+func TestLoadPackage_NoAssetsLeavesFSNil(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ path := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ pkgWasmFilename: wasmBytes,
+ })
+
+ loaded, err := LoadPackage(context.Background(), &HostEnv{}, path)
+ if err != nil {
+ t.Fatalf("load: %v", err)
+ }
+ defer loaded.Close(context.Background())
+
+ if loaded.AssetsFS != nil {
+ t.Error("expected AssetsFS to be nil when archive has no assets/")
+ }
+}
+
+// Verify that arbitrary file content (incl. binary) round-trips through the
+// zip reader. Belt-and-suspenders for the in-memory zip approach.
+func TestLoadPackage_BinaryAssetsIntact(t *testing.T) {
+ wasmPath := findExampleWasm(t)
+ wasmBytes, _ := os.ReadFile(wasmPath)
+ // Random-ish binary payload — a sentinel image-like byte sequence.
+ binary := []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x01, 0x02, 0x03}
+ path := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ pkgWasmFilename: wasmBytes,
+ pkgAssetsPrefix + "logo.png": binary,
+ })
+
+ loaded, err := LoadPackage(context.Background(), &HostEnv{}, path)
+ if err != nil {
+ t.Fatalf("load: %v", err)
+ }
+ defer loaded.Close(context.Background())
+
+ got, err := fs.ReadFile(loaded.AssetsFS, "logo.png")
+ if err != nil {
+ t.Fatalf("read: %v", err)
+ }
+ if !bytes.Equal(got, binary) {
+ t.Errorf("binary asset corrupted:\n want %v\n got %v", binary, got)
+ }
+}
+
+// readZipFile is exercised heavily above, but verify it directly with a tiny
+// constructed archive so its error path is independently tested.
+func TestReadZipFile_Missing(t *testing.T) {
+ var buf bytes.Buffer
+ zw := zip.NewWriter(&buf)
+ w, _ := zw.Create("present.txt")
+ io.WriteString(w, "hi")
+ zw.Close()
+
+ zr, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
+ if err != nil {
+ t.Fatalf("zip reader: %v", err)
+ }
+ if _, err := readZipFile(zr, "missing.txt"); err == nil {
+ t.Error("expected error for missing entry, got nil")
+ }
+}
+
+func TestHasPluginInstructions_Package(t *testing.T) {
+ with := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ pkgWasmFilename: {0x00},
+ PluginInstructionsFilename: []byte("# Hello"),
+ })
+ if !hasPluginInstructions(with) {
+ t.Error("expected hasPluginInstructions=true for package with INSTRUCTIONS.md")
+ }
+
+ without := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ pkgWasmFilename: {0x00},
+ })
+ if hasPluginInstructions(without) {
+ t.Error("expected hasPluginInstructions=false for package without INSTRUCTIONS.md")
+ }
+}
+
+func TestHasPluginInstructions_LooseFiles(t *testing.T) {
+ dir := t.TempDir()
+ wasmPath := filepath.Join(dir, "demo.wasm")
+ if err := os.WriteFile(wasmPath, []byte{0x00}, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if hasPluginInstructions(wasmPath) {
+ t.Error("expected false when sibling INSTRUCTIONS.md absent")
+ }
+ if err := os.WriteFile(filepath.Join(dir, "demo."+PluginInstructionsFilename), []byte("# hi"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if !hasPluginInstructions(wasmPath) {
+ t.Error("expected true when sibling <base>.INSTRUCTIONS.md present")
+ }
+}
+
+func TestInstructionsBytes_Package(t *testing.T) {
+ body := []byte("# Setup\n\nDo the thing.")
+ path := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ pkgWasmFilename: {0x00},
+ PluginInstructionsFilename: body,
+ })
+
+ mgr := NewManager(filepath.Dir(path), &HostEnv{})
+ if err := mgr.scan(context.Background()); err != nil {
+ t.Fatalf("scan: %v", err)
+ }
+
+ entries := mgr.List()
+ if len(entries) != 1 {
+ t.Fatalf("expected 1 discovered, got %d", len(entries))
+ }
+ if !entries[0].HasInstructions {
+ t.Error("expected HasInstructions=true in discovered entry")
+ }
+
+ got, err := mgr.InstructionsBytes("hello-world")
+ if err != nil {
+ t.Fatalf("InstructionsBytes: %v", err)
+ }
+ if !bytes.Equal(got, body) {
+ t.Errorf("instructions: got %q want %q", got, body)
+ }
+}
+
+func TestInstructionsBytes_NoInstructions(t *testing.T) {
+ path := buildPkg(t, map[string][]byte{
+ pkgManifestFilename: validManifestBytes(),
+ pkgWasmFilename: {0x00},
+ })
+ mgr := NewManager(filepath.Dir(path), &HostEnv{})
+ if err := mgr.scan(context.Background()); err != nil {
+ t.Fatalf("scan: %v", err)
+ }
+ if _, err := mgr.InstructionsBytes("hello-world"); err == nil {
+ t.Error("expected error for plugin without instructions")
+ }
+}
+
+func TestInstructionsBytes_NotDiscovered(t *testing.T) {
+ mgr := NewManager(t.TempDir(), &HostEnv{})
+ if _, err := mgr.InstructionsBytes("ghost"); err == nil {
+ t.Error("expected error for undiscovered plugin")
+ }
+}
diff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.json
new file mode 100644
index 0000000000..d39ce32e52
--- /dev/null
+++ b/services/plugins/plugin-contract.json
@@ -0,0 +1,146 @@
+{
+ "permissions": {
+ "PermChatFilter": "chat.filter",
+ "PermChatHistory": "chat.history",
+ "PermChatModerate": "chat.moderate",
+ "PermChatSend": "chat.send",
+ "PermEmitEvent": "events.emit",
+ "PermFediversePost": "fediverse.post",
+ "PermHttpSSE": "http.sse",
+ "PermHttpServe": "http.serve",
+ "PermNetworkFetch": "network.fetch",
+ "PermNotificationsSend": "notifications.send",
+ "PermServerRead": "server.read",
+ "PermStorageKV": "storage.kv",
+ "PermStorageUpload": "storage.upload",
+ "PermUIModify": "ui.modify",
+ "PermUsersModerate": "users.moderate",
+ "PermUsersRead": "users.read",
+ "PermVideoConfigRead": "videoconfig.read",
+ "PermVideoConfigWrite": "videoconfig.write"
+ },
+ "hostFunctions": [
+ "owncast_add_actions",
+ "owncast_ban_ip",
+ "owncast_chat_clients",
+ "owncast_chat_history",
+ "owncast_clear_actions",
+ "owncast_delete_message",
+ "owncast_emit_event",
+ "owncast_fediverse_post",
+ "owncast_kick_client",
+ "owncast_kv_get",
+ "owncast_kv_set",
+ "owncast_notify_browser_push",
+ "owncast_notify_discord",
+ "owncast_notify_fediverse",
+ "owncast_send_chat",
+ "owncast_send_chat_action",
+ "owncast_send_chat_system",
+ "owncast_send_chat_to",
+ "owncast_server_federation",
+ "owncast_server_info",
+ "owncast_server_socials",
+ "owncast_server_tags",
+ "owncast_sse_send",
+ "owncast_storage_upload",
+ "owncast_stream_broadcaster",
+ "owncast_stream_current",
+ "owncast_user_get",
+ "owncast_user_set_enabled",
+ "owncast_users_list",
+ "owncast_video_config_read",
+ "owncast_video_config_write"
+ ],
+ "wireTypes": {
+ "BrowserPushPayload": {
+ "body": "string",
+ "title": "string",
+ "url": "string"
+ },
+ "FederationInfo": {
+ "enabled": "bool",
+ "isPrivate": "bool",
+ "username": "string"
+ },
+ "FediversePayload": {
+ "body": "string",
+ "image": "string",
+ "link": "string",
+ "type": "string"
+ },
+ "HostChatClient": {
+ "connectedAt": "string",
+ "displayName": "string",
+ "id": "uint64",
+ "ipAddress": "string",
+ "messageCount": "int",
+ "userAgent": "string",
+ "userId": "string"
+ },
+ "HostChatMessage": {
+ "body": "string",
+ "id": "string",
+ "timestamp": "string",
+ "user": "string"
+ },
+ "HostUser": {
+ "createdAt": "string",
+ "disabledAt": "string",
+ "displayName": "string",
+ "id": "string",
+ "isAuthenticated": "bool",
+ "isBot": "bool",
+ "previousNames": "[]string",
+ "scopes": "[]string"
+ },
+ "ServerInfo": {
+ "name": "string",
+ "summary": "string",
+ "url": "string",
+ "version": "string",
+ "welcomeMessage": "string"
+ },
+ "SocialHandle": {
+ "icon": "string",
+ "platform": "string",
+ "url": "string"
+ },
+ "StreamBroadcaster": {
+ "bitrates": "[]int",
+ "codecs": "[]string",
+ "framerate": "int",
+ "remoteAddr": "string",
+ "resolution": "string"
+ },
+ "StreamInfo": {
+ "latencyLevel": "int",
+ "online": "bool",
+ "startedAt": "string",
+ "summary": "string",
+ "title": "string",
+ "viewers": "int"
+ },
+ "StreamVariant": {
+ "audioBitrate": "int",
+ "framerate": "int",
+ "height": "int",
+ "isPassthrough": "bool",
+ "videoBitrate": "int",
+ "width": "int"
+ },
+ "UploadResult": {
+ "url": "string"
+ },
+ "VideoConfig": {
+ "codec": "string",
+ "latencyLevel": "int",
+ "variants": "[]StreamVariant"
+ },
+ "VideoConfigUpdate": {
+ "codec": "*string",
+ "latencyLevel": "*int",
+ "variants": "[]StreamVariant"
+ }
+ }
+}
diff --git a/services/plugins/safeguards_test.go b/services/plugins/safeguards_test.go
new file mode 100644
index 0000000000..d7ee87ecff
--- /dev/null
+++ b/services/plugins/safeguards_test.go
@@ -0,0 +1,226 @@
+package plugins
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+)
+
+// findSafeguardStressWasm locates the safeguard-stress example. Tests skip
+// (rather than fail) if it hasn't been built, mirroring the pattern used by
+// findExampleWasm.
+func findSafeguardStressWasm(t *testing.T) (wasmPath, manifestPath string) {
+ t.Helper()
+ _, thisFile, _, _ := runtime.Caller(0)
+ repoRoot := filepath.Join(filepath.Dir(thisFile), "..", "..")
+ wasmPath = filepath.Join(repoRoot, "examples", "js", "safeguard-stress", "safeguard-stress.wasm")
+ manifestPath = filepath.Join(repoRoot, "examples", "js", "safeguard-stress", "plugin.manifest.json")
+ if _, err := os.Stat(wasmPath); err != nil {
+ t.Skipf("safeguard-stress wasm not built; run tools/build-plugin.sh examples/js/safeguard-stress")
+ }
+ return wasmPath, manifestPath
+}
+
+// loadStress is the common setup for safeguard tests — loads the
+// safeguard-stress plugin with a no-op HostEnv. Returns the loaded plugin
+// and a cleanup func.
+func loadStress(t *testing.T) (*Loaded, func()) {
+ t.Helper()
+ wasmPath, manifestPath := findSafeguardStressWasm(t)
+ ctx := context.Background()
+ loaded, err := LoadPlugin(ctx, &HostEnv{}, wasmPath, manifestPath)
+ if err != nil {
+ t.Fatalf("load: %v", err)
+ }
+ return loaded, func() { loaded.Close(ctx) }
+}
+
+// --- Filter safeguards ---
+
+func TestSafeguard_FilterHugeOutputRejected(t *testing.T) {
+ loaded, cleanup := loadStress(t)
+ defer cleanup()
+
+ // QuickJS serializing a 1 MB JSON output legitimately doesn't fit in
+ // the 50 ms production timeout — the timeout would fire first and we'd
+ // never reach the size check. Production safety in practice comes from
+ // the timeout; this test stretches the timeout to verify the *separate*
+ // size-cap defense (which would matter for faster runtimes returning
+ // a pre-allocated huge buffer instantly).
+ orig := FilterTimeout
+ FilterTimeout = 10 * time.Second
+ defer func() { FilterTimeout = orig }()
+
+ _, err := callOnFilter(context.Background(), loaded, "chat.message.received", map[string]any{
+ "cmd": "huge-output",
+ })
+ if err == nil {
+ t.Fatal("expected error for huge filter output, got nil")
+ }
+ if !strings.Contains(err.Error(), "too large") {
+ t.Errorf("expected size error, got %v", err)
+ }
+}
+
+func TestSafeguard_FilterSpinTriggersTimeout(t *testing.T) {
+ loaded, cleanup := loadStress(t)
+ defer cleanup()
+
+ start := time.Now()
+ _, err := callOnFilter(context.Background(), loaded, "chat.message.received", map[string]any{
+ "cmd": "spin",
+ })
+ elapsed := time.Since(start)
+
+ if err == nil {
+ t.Fatal("expected timeout error, got nil")
+ }
+ if !strings.Contains(err.Error(), "timed out") {
+ t.Errorf("expected timeout in error, got %v", err)
+ }
+ // 50 ms cap + generous slack for QuickJS cancellation latency. If this
+ // takes seconds, the cancellation isn't working.
+ if elapsed > 2*time.Second {
+ t.Errorf("filter spin took %v — timeout enforcement is too slow", elapsed)
+ }
+}
+
+func TestSafeguard_FilterFailuresAccumulateStrikes(t *testing.T) {
+ loaded, cleanup := loadStress(t)
+ defer cleanup()
+
+ ctx := context.Background()
+ for i := 0; i < FilterStrikeThreshold; i++ {
+ if loaded.IsDisabled() {
+ t.Fatalf("plugin disabled too early at iteration %d", i)
+ }
+ _, err := callOnFilter(ctx, loaded, "chat.message.received", map[string]any{"cmd": "huge-output"})
+ if err == nil {
+ t.Fatalf("iteration %d: expected error", i)
+ }
+ // Mirror dispatcher.Filter's strike bookkeeping.
+ loaded.recordFilterFailure()
+ }
+ if !loaded.IsDisabled() {
+ t.Fatal("plugin should be disabled after threshold reached")
+ }
+}
+
+// --- Notification safeguards ---
+
+func TestSafeguard_NotifyTimeoutEnforced(t *testing.T) {
+ loaded, cleanup := loadStress(t)
+ defer cleanup()
+
+ envelope, _ := json.Marshal(Envelope{
+ EventType: "chat.message.received",
+ Payload: map[string]any{"cmd": "spin"},
+ })
+
+ start := time.Now()
+ err := callOnEvent(context.Background(), loaded, envelope)
+ elapsed := time.Since(start)
+
+ if err == nil {
+ t.Fatal("expected timeout error, got nil")
+ }
+ if !strings.Contains(err.Error(), "timed out") {
+ t.Errorf("expected timeout in error, got %v", err)
+ }
+ if elapsed > 2*time.Second {
+ t.Errorf("on_event spin took %v — timeout enforcement is too slow", elapsed)
+ }
+}
+
+// --- HTTP handler safeguards ---
+
+func TestSafeguard_HTTPHandlerTimeoutReturns504(t *testing.T) {
+ loaded, cleanup := loadStress(t)
+ defer cleanup()
+
+ server := NewServer([]*Loaded{loaded})
+ req := httptest.NewRequest("GET", "/plugins/safeguard-stress/spin", nil)
+ rec := httptest.NewRecorder()
+
+ start := time.Now()
+ server.ServeHTTP(rec, req)
+ elapsed := time.Since(start)
+
+ if rec.Code != http.StatusGatewayTimeout {
+ t.Errorf("status: got %d want %d (body: %q)", rec.Code, http.StatusGatewayTimeout, rec.Body.String())
+ }
+ // Allow some slack over the 5s cap for cancellation latency.
+ if elapsed > 10*time.Second {
+ t.Errorf("HTTP spin took %v — timeout enforcement is too slow", elapsed)
+ }
+}
+
+func TestSafeguard_HTTPHandlerHugeOutputRejected(t *testing.T) {
+ loaded, cleanup := loadStress(t)
+ defer cleanup()
+
+ server := NewServer([]*Loaded{loaded})
+ req := httptest.NewRequest("GET", "/plugins/safeguard-stress/huge", nil)
+ rec := httptest.NewRecorder()
+ server.ServeHTTP(rec, req)
+
+ if rec.Code != http.StatusInternalServerError {
+ t.Errorf("status: got %d want 500", rec.Code)
+ }
+ if !strings.Contains(rec.Body.String(), "too large") {
+ t.Errorf("body should mention size: got %q", rec.Body.String())
+ }
+}
+
+// --- Wasm memory cap ---
+
+func TestSafeguard_WasmMemoryCapPreventsHugeAllocation(t *testing.T) {
+ loaded, cleanup := loadStress(t)
+ defer cleanup()
+
+ _, err := callOnFilter(context.Background(), loaded, "chat.message.received", map[string]any{
+ "cmd": "alloc",
+ })
+ if err == nil {
+ t.Fatal("expected error when plugin tries to allocate past MaxWasmPages, got nil")
+ }
+ // The exact error wording depends on whether QuickJS surfaces this as
+ // an OOM throw or wazero rejects the memory.grow. Either way, the call
+ // must fail rather than the host swallowing a 64+ MB allocation.
+}
+
+// --- Manifest sandbox values ---
+
+// Verifies the constants are actually wired into the extism manifest at load
+// time. A regression that drops the Memory block would silently re-open the
+// crash vector this file exists to prevent.
+func TestSafeguard_ManifestSandboxConstantsSet(t *testing.T) {
+ // Sanity-check the values themselves haven't been zeroed. The actual
+ // wiring is verified by TestSafeguard_WasmMemoryCapPreventsHugeAllocation
+ // (functional test); this guards against silent removal.
+ if MaxWasmPages == 0 {
+ t.Error("MaxWasmPages is 0 — wasm memory is uncapped")
+ }
+ if MaxExtismHTTPResponseBytes == 0 {
+ t.Error("MaxExtismHTTPResponseBytes is 0 — outbound HTTP body is uncapped")
+ }
+ if MaxFilterOutputBytes == 0 {
+ t.Error("MaxFilterOutputBytes is 0 — filter output is uncapped")
+ }
+ if MaxHTTPHandlerOutputBytes == 0 {
+ t.Error("MaxHTTPHandlerOutputBytes is 0 — HTTP handler output is uncapped")
+ }
+ if NotifyTimeout == 0 {
+ t.Error("NotifyTimeout is 0 — on_event has no per-call cap")
+ }
+ if HTTPHandlerTimeout == 0 {
+ t.Error("HTTPHandlerTimeout is 0 — on_http_request has no per-call cap")
+ }
+}
diff --git a/services/plugins/server.go b/services/plugins/server.go
new file mode 100644
index 0000000000..b5dd5b9f75
--- /dev/null
+++ b/services/plugins/server.go
@@ -0,0 +1,554 @@
+package plugins
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "io/fs"
+ "net/http"
+ "os"
+ "path"
+ "strings"
+ "time"
+)
+
+// Server is an http.Handler that serves /plugins/<name>/* — first by
+// looking for a static asset on the plugin's PublicFS, then falling through
+// to the plugin's on_http_request wasm export. Plugins without the
+// http.serve permission produce 404 regardless.
+//
+// Asset storage is abstracted via io/fs so loose-files plugins (os.DirFS),
+// packaged plugins (.ocpkg via zip.Reader), and any future layout share the
+// same serving code.
+//
+// Mount this on the parent router at /plugins/, e.g.
+//
+// mux.Handle("/plugins/", server)
+type Server struct {
+ // snapshot returns the currently-loaded plugins. Called per-request so
+ // admin enable/disable takes effect immediately.
+ snapshot func() []*Loaded
+ // IsAuthenticated reports whether an incoming HTTP request carries
+ // authenticated-admin credentials. Used to populate req.authenticated
+ // for the plugin's dynamic handler (so a plugin page can render
+ // differently for authenticated viewers without owning auth itself).
+ // Admin-path gating is done via RequireAdmin, not by checking this and
+ // writing a 401 here — that's the host's responsibility.
+ // nil = always false (no auth available).
+ IsAuthenticated func(*http.Request) bool
+ // RequireAdmin wraps a handler in the host's admin Basic Auth
+ // middleware. The plugin static server calls it when a request lands
+ // on a manifest-declared admin path so the 401 (realm, CORS, log line)
+ // comes from one place in the codebase instead of being duplicated
+ // here. nil = admin paths cannot be served (404).
+ RequireAdmin func(http.HandlerFunc) http.HandlerFunc
+ // GetRequestUser returns the user identity attached to the request
+ // (when the request came with a user-token, not admin auth). nil →
+ // req.user is always omitted from the envelope.
+ GetRequestUser func(*http.Request) *HostUser
+ // SSE is the host-owned hub that backs the reserved
+ // /plugins/<name>/_sse/<channel> endpoint. The host holds these
+ // long-lived connections; plugins push to them via owncast.sse.send.
+ // nil → the _sse endpoint returns 503.
+ SSE *SSEHub
+}
+
+// SSEReservedPrefix is the request path (relative to the plugin namespace)
+// the host reserves for Server-Sent-Events streams. A request to
+// /plugins/<name>/_sse/<channel> connects to the plugin's <channel> stream;
+// the segment after the prefix is the channel name (empty = default).
+// Plugins cannot serve their own routes under this prefix.
+const SSEReservedPrefix = "/_sse"
+
+// SSEKeepAliveInterval is how often the host writes an SSE comment line to
+// an idle stream so proxies don't close it for inactivity.
+const SSEKeepAliveInterval = 15 * time.Second
+
+// HTTP enforcement limits. Per-plugin, per-request.
+const (
+ MaxHTTPRequestBodyBytes = 1 << 20 // 1 MB
+ MaxHTTPResponseBodyBytes = 10 << 20 // 10 MB
+)
+
+// adminStyleHrefs are the host's stylesheet URLs auto-injected into HTML
+// responses on a plugin's manifest-declared admin paths. It's a single
+// dedicated sheet that styles plain HTML elements (input, button, table,
+// label, …) with the Owncast theme tokens — not the surrounding admin's
+// AntD-specific stylesheets, which only apply to .ant-* class selectors
+// the plugin pages don't use.
+//
+// The file is served by the Owncast HTTP server (from web/public/styles/
+// in dev, from the bundled admin assets in prod), so the same origin-
+// relative URL works in both modes.
+var adminStyleHrefs = []string{
+ "/styles/admin/plugin-iframe.css",
+}
+
+// adminStyleSnippet is the bytes injected into HTML responses on admin
+// paths. Built once at startup so the per-request cost is just a single
+// substring search + concatenation.
+var adminStyleSnippet = buildAdminStyleSnippet(adminStyleHrefs)
+
+// adminStyleMarker is a sentinel attribute on the injected <link> tags
+// so the injector is idempotent: if a plugin's HTML already includes our
+// snippet (e.g. baked in by their build), we don't add it again.
+const adminStyleMarker = `data-owncast-admin-style="1"`
+
+func buildAdminStyleSnippet(hrefs []string) []byte {
+ var b bytes.Buffer
+ for _, h := range hrefs {
+ fmt.Fprintf(&b, `<link rel="stylesheet" href=%q %s>`, h, adminStyleMarker)
+ }
+ return b.Bytes()
+}
+
+// injectAdminStyles returns html with the admin-stylesheet snippet inserted
+// before </head>, or — when no </head> is present — prepended. Idempotent:
+// returns the input unchanged when the snippet's marker is already in the
+// document. text/html responses on a manifest-declared admin path go
+// through this; nothing else.
+func injectAdminStyles(html []byte) []byte {
+ if bytes.Contains(html, []byte(adminStyleMarker)) {
+ return html
+ }
+ if i := bytes.Index(bytes.ToLower(html), []byte("</head>")); i >= 0 {
+ out := make([]byte, 0, len(html)+len(adminStyleSnippet))
+ out = append(out, html[:i]...)
+ out = append(out, adminStyleSnippet...)
+ out = append(out, html[i:]...)
+ return out
+ }
+ // No <head> — prepend so styles still apply. Browsers tolerate a
+ // <link> at the top of a body-only document.
+ out := make([]byte, 0, len(html)+len(adminStyleSnippet))
+ out = append(out, adminStyleSnippet...)
+ out = append(out, html...)
+ return out
+}
+
+// allowedResponseHeaders is the set of headers a plugin response is allowed
+// to set. We block headers that would let a plugin override Owncast's own
+// transport-security, CSP, or server-identification headers. Set-Cookie
+// is allowed: a plugin's response defaults to a Path scoped to its own
+// /plugins/<name>/ namespace, so cookies don't leak into the rest of
+// Owncast unless the plugin explicitly broadens them. CORS headers
+// (Access-Control-*) are matched via prefix below.
+var allowedResponseHeaders = map[string]bool{
+ "content-type": true,
+ "content-encoding": true,
+ "content-language": true,
+ "cache-control": true,
+ "last-modified": true,
+ "etag": true,
+ "location": true,
+ "vary": true,
+ "link": true,
+ "set-cookie": true,
+}
+
+func isAllowedResponseHeader(name string) bool {
+ lower := strings.ToLower(name)
+ if allowedResponseHeaders[lower] {
+ return true
+ }
+ if strings.HasPrefix(lower, "access-control-") {
+ return true
+ }
+ return false
+}
+
+// NewServer constructs an HTTP handler over a fixed plugin set. Used in
+// tests and any context where the plugin set doesn't change after
+// construction. Each plugin's PublicFS is used for static asset serving;
+// plugins with nil PublicFS just don't serve static files.
+func NewServer(loaded []*Loaded) *Server {
+ snap := loaded
+ return &Server{snapshot: func() []*Loaded { return snap }}
+}
+
+// NewLiveServer constructs an HTTP handler backed by a snapshot function —
+// the Manager passes its Snapshot method here so admin enable/disable takes
+// effect on subsequent requests without restarting the host.
+func NewLiveServer(snapshot func() []*Loaded) *Server {
+ return &Server{snapshot: snapshot}
+}
+
+func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ // Path: /plugins/<name>/<rest>. We're mounted at /plugins/, so
+ // r.URL.Path starts with /plugins/. Strip and split.
+ rel := strings.TrimPrefix(r.URL.Path, "/plugins/")
+ parts := strings.SplitN(rel, "/", 2)
+ if parts[0] == "" {
+ http.NotFound(w, r)
+ return
+ }
+ name := parts[0]
+ p := s.lookup(name)
+ if p == nil {
+ http.NotFound(w, r)
+ return
+ }
+
+ rest := "/"
+ if len(parts) > 1 {
+ rest = "/" + parts[1]
+ }
+
+ // Admin-only routes (declared in the plugin's manifest) are gated by
+ // the host's admin auth middleware before the plugin sees the request.
+ // We invoke RequireAdmin directly so the 401 — realm, CORS, log line —
+ // comes from middleware/auth.go rather than being duplicated here.
+ if p.IsAdminPath(rest) {
+ if s.RequireAdmin == nil {
+ http.NotFound(w, r)
+ return
+ }
+ s.RequireAdmin(func(w http.ResponseWriter, r *http.Request) {
+ s.serveAuthorized(w, r, p, rest, true)
+ })(w, r)
+ return
+ }
+
+ authenticated := false
+ if s.IsAuthenticated != nil {
+ authenticated = s.IsAuthenticated(r)
+ }
+ s.serveAuthorized(w, r, p, rest, authenticated)
+}
+
+// serveAuthorized runs the rest of the plugin request pipeline (SSE,
+// permission gate, static asset, dynamic handler) after the admin-path
+// check has been resolved. authenticated is the boolean handed to the
+// plugin's dynamic handler — true on admin paths (callers reach this via
+// RequireAdmin's success continuation), the IsAuthenticated predicate
+// otherwise.
+//
+// An HTML response served on a manifest-declared admin path also gets the
+// host's admin stylesheet injected so the plugin iframe matches the
+// surrounding admin visually with no plugin-author opt-in.
+func (s *Server) serveAuthorized(w http.ResponseWriter, r *http.Request, p *Loaded, rest string, authenticated bool) {
+ injectStyles := p.IsAdminPath(rest)
+
+ // Host-reserved Server-Sent-Events endpoint. Gated on http.sse
+ // (independent of http.serve) and handled entirely by the host — the
+ // plugin never sees these requests.
+ if rest == SSEReservedPrefix || strings.HasPrefix(rest, SSEReservedPrefix+"/") {
+ if !pluginHasPermission(p.Manifest, PermHttpSSE) {
+ http.NotFound(w, r)
+ return
+ }
+ channel := strings.TrimPrefix(strings.TrimPrefix(rest, SSEReservedPrefix), "/")
+ s.serveSSE(w, r, p, channel)
+ return
+ }
+
+ if !pluginHasPermission(p.Manifest, PermHttpServe) {
+ http.NotFound(w, r)
+ return
+ }
+
+ if s.tryStatic(w, r, p, rest, injectStyles) {
+ return
+ }
+ // Strip the trailing slash before handing the path to the plugin's
+ // dynamic handler so plugin code can match canonical no-slash form
+ // regardless of how the URL was canonicalized upstream. Next.js dev's
+ // trailingSlash:true rewrites every URL to a slash-terminated form,
+ // which would otherwise force every plugin to accept both /foo and
+ // /foo/ in its on_http_request switch. Static asset serving keeps the
+ // original path so directory-vs-file resolution is unaffected.
+ dynamicPath := rest
+ if len(dynamicPath) > 1 && strings.HasSuffix(dynamicPath, "/") {
+ dynamicPath = strings.TrimRight(dynamicPath, "/")
+ }
+ s.serveDynamic(w, r, p, dynamicPath, authenticated, injectStyles)
+}
+
+// serveSSE holds a long-lived Server-Sent-Events connection open and streams
+// frames the plugin publishes to (plugin, channel). The connection is owned
+// entirely by the host: no plugin wasm call is made here and the per-plugin
+// mutex is never taken, so an idle stream costs only a goroutine. The loop
+// exits when the client disconnects (request context cancelled).
+func (s *Server) serveSSE(w http.ResponseWriter, r *http.Request, p *Loaded, channel string) {
+ if s.SSE == nil {
+ http.Error(w, "server-sent events not available", http.StatusServiceUnavailable)
+ return
+ }
+ flusher, ok := w.(http.Flusher)
+ if !ok {
+ http.Error(w, "streaming unsupported", http.StatusInternalServerError)
+ return
+ }
+
+ stream, unsubscribe, ok := s.SSE.Subscribe(p.Manifest.Slug, channel)
+ if !ok {
+ http.Error(w, "too many event-stream connections for this plugin", http.StatusServiceUnavailable)
+ return
+ }
+ defer unsubscribe()
+
+ h := w.Header()
+ h.Set("Content-Type", "text/event-stream")
+ h.Set("Cache-Control", "no-cache")
+ h.Set("Connection", "keep-alive")
+ w.WriteHeader(http.StatusOK)
+ flusher.Flush()
+
+ keepAlive := time.NewTicker(SSEKeepAliveInterval)
+ defer keepAlive.Stop()
+
+ ctx := r.Context()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case frame := <-stream:
+ if _, err := w.Write(frame); err != nil {
+ return
+ }
+ flusher.Flush()
+ case <-keepAlive.C:
+ if _, err := io.WriteString(w, ": keep-alive\n\n"); err != nil {
+ return
+ }
+ flusher.Flush()
+ }
+ }
+}
+
+// lookup returns the currently-loaded plugin with the given slug, or nil
+// if there isn't one. Called per-request against the live snapshot.
+// The lookup key is the manifest slug (also the URL segment under
+// /plugins/<slug>/), not the human-readable display name.
+func (s *Server) lookup(slug string) *Loaded {
+ for _, p := range s.snapshot() {
+ if p.Manifest.Slug == slug {
+ return p
+ }
+ }
+ return nil
+}
+
+func pluginHasPermission(m *Manifest, perm string) bool {
+ for _, p := range m.Permissions {
+ if p == perm {
+ return true
+ }
+ }
+ return false
+}
+
+func (s *Server) tryStatic(w http.ResponseWriter, r *http.Request, loaded *Loaded, requestPath string, injectStyles bool) bool {
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ return false
+ }
+ if loaded.PublicFS == nil {
+ return false
+ }
+
+ // fs.FS paths must be slash-separated, without a leading slash, and
+ // can't contain ".." segments — path.Clean handles the first two; the
+ // fs.ValidPath check rejects traversal.
+ cleaned := strings.TrimPrefix(path.Clean("/"+requestPath), "/")
+ if cleaned == "" {
+ cleaned = "."
+ }
+ if !fs.ValidPath(cleaned) {
+ return false
+ }
+
+ info, err := fs.Stat(loaded.PublicFS, cleaned)
+ if err != nil {
+ return false
+ }
+ if info.IsDir() {
+ indexPath := path.Join(cleaned, "index.html")
+ idx, err := fs.Stat(loaded.PublicFS, indexPath)
+ if err != nil || idx.IsDir() {
+ return false
+ }
+ // Standard directory-index behavior: if the request URL doesn't end
+ // with a slash, redirect to the canonical slash form before serving
+ // the index.html. Without this the browser's base URL stays at the
+ // parent path and any relative links in the page (`./api/settings`,
+ // `<img src="logo.png">`, etc.) resolve to the wrong place.
+ if !strings.HasSuffix(r.URL.Path, "/") {
+ // Not an open redirect — destination is the request's own path
+ // with a trailing slash, not an attacker-controlled URL.
+ http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently) //nolint:gosec // G710
+ return true
+ }
+ serveAssetFile(w, r, loaded.PublicFS, indexPath, idx, injectStyles)
+ return true
+ }
+ serveAssetFile(w, r, loaded.PublicFS, cleaned, info, injectStyles)
+ return true
+}
+
+// serveAssetFile reads a file from the plugin's AssetsFS into memory and
+// hands it to http.ServeContent. Reading into memory avoids the seekability
+// problems with non-file-backed fs.FS implementations (zip entries aren't
+// seekable as ReadClosers); plugin assets are small enough that this is
+// fine in practice. http.ServeContent gives us correct content-type
+// sniffing, range support, ETag/conditional-GET handling — without
+// net/http.ServeFile's path-canonicalization redirects.
+//
+// injectStyles=true rewrites HTML responses to include the host's admin
+// stylesheet links before serving — only set by serveAuthorized when the
+// path is on a manifest-declared admin route.
+func serveAssetFile(w http.ResponseWriter, r *http.Request, root fs.FS, name string, info fs.FileInfo, injectStyles bool) {
+ data, err := fs.ReadFile(root, name)
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+ if injectStyles && isHTMLName(name) {
+ data = injectAdminStyles(data)
+ }
+ modtime := info.ModTime()
+ if modtime.IsZero() {
+ modtime = time.Time{} // ServeContent skips Last-Modified if zero
+ }
+ http.ServeContent(w, r, path.Base(name), modtime, bytes.NewReader(data))
+}
+
+func isHTMLName(name string) bool {
+ lower := strings.ToLower(name)
+ return strings.HasSuffix(lower, ".html") || strings.HasSuffix(lower, ".htm")
+}
+
+func (s *Server) serveDynamic(w http.ResponseWriter, r *http.Request, p *Loaded, requestPath string, authenticated bool, injectStyles bool) {
+ // p.plugin can be nil during shutdown (Loaded.Close clears it) or in
+ // tests that only exercise the static path. Either way, no plugin
+ // instance means no dynamic handler.
+ if p.plugin == nil || !p.plugin.FunctionExists("on_http_request") {
+ http.NotFound(w, r)
+ return
+ }
+
+ body, err := io.ReadAll(io.LimitReader(r.Body, MaxHTTPRequestBodyBytes+1))
+ if err != nil {
+ http.Error(w, "request body read error", http.StatusBadRequest)
+ return
+ }
+ if int64(len(body)) > MaxHTTPRequestBodyBytes {
+ http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
+ return
+ }
+
+ envelopeJSON, err := s.buildRequestEnvelope(r, requestPath, authenticated, body)
+ if err != nil {
+ http.Error(w, "internal error", http.StatusInternalServerError)
+ return
+ }
+
+ callCtx, cancel := context.WithTimeout(r.Context(), HTTPHandlerTimeout)
+ defer cancel()
+ p.mu.Lock()
+ _, out, err := p.plugin.CallWithContext(callCtx, "on_http_request", envelopeJSON)
+ p.mu.Unlock()
+ if err != nil {
+ if errors.Is(err, context.DeadlineExceeded) || callCtx.Err() == context.DeadlineExceeded {
+ http.Error(w, "plugin timed out", http.StatusGatewayTimeout)
+ fmt.Fprintf(os.Stderr, "plugin %s: on_http_request timed out after %s\n", p.Manifest.Slug, HTTPHandlerTimeout)
+ return
+ }
+ http.Error(w, "plugin error", http.StatusInternalServerError)
+ fmt.Fprintf(os.Stderr, "plugin %s: on_http_request failed: %v\n", p.Manifest.Slug, err)
+ return
+ }
+ if len(out) > MaxHTTPHandlerOutputBytes {
+ http.Error(w, "plugin response too large", http.StatusInternalServerError)
+ fmt.Fprintf(os.Stderr, "plugin %s: on_http_request output too large: %d bytes (max %d)\n",
+ p.Manifest.Slug, len(out), MaxHTTPHandlerOutputBytes)
+ return
+ }
+
+ writePluginHTTPResponse(w, out, injectStyles)
+}
+
+// buildRequestEnvelope marshals the JSON envelope passed to a plugin's
+// on_http_request export.
+func (s *Server) buildRequestEnvelope(r *http.Request, requestPath string, authenticated bool, body []byte) ([]byte, error) {
+ envelope := map[string]any{
+ "method": r.Method,
+ "path": requestPath,
+ "query": flattenValues(r.URL.Query()),
+ "headers": flattenValues(r.Header),
+ "body": string(body),
+ "remoteAddr": r.RemoteAddr,
+ "authenticated": authenticated,
+ }
+ if s.GetRequestUser != nil {
+ if user := s.GetRequestUser(r); user != nil {
+ envelope["user"] = user
+ }
+ }
+ return json.Marshal(envelope)
+}
+
+// writePluginHTTPResponse parses a plugin's on_http_request output envelope
+// and writes it to the client, filtering disallowed headers.
+//
+// injectStyles=true rewrites an HTML response (Content-Type starting with
+// text/html) to include the host's admin stylesheet links — same behavior
+// as static HTML assets, so a plugin returning admin HTML from
+// on_http_request gets the iframe theme automatically.
+func writePluginHTTPResponse(w http.ResponseWriter, out []byte, injectStyles bool) {
+ var resp struct {
+ Status int `json:"status"`
+ Headers map[string]string `json:"headers"`
+ Body string `json:"body"`
+ }
+ if err := json.Unmarshal(out, &resp); err != nil {
+ http.Error(w, "plugin returned invalid response", http.StatusInternalServerError)
+ return
+ }
+ if resp.Status == 0 {
+ resp.Status = http.StatusOK
+ }
+ if len(resp.Body) > MaxHTTPResponseBodyBytes {
+ http.Error(w, "plugin response too large", http.StatusInternalServerError)
+ return
+ }
+
+ body := resp.Body
+ if injectStyles && responseIsHTML(resp.Headers) {
+ body = string(injectAdminStyles([]byte(body)))
+ }
+
+ for k, v := range resp.Headers {
+ if !isAllowedResponseHeader(k) {
+ continue
+ }
+ w.Header().Set(k, v)
+ }
+ w.WriteHeader(resp.Status)
+ _, _ = io.WriteString(w, body)
+}
+
+// responseIsHTML reports whether the plugin-declared headers identify the
+// response body as HTML. Case-insensitive on the header name; only the
+// media type prefix is inspected so charset/boundary parameters don't
+// matter.
+func responseIsHTML(headers map[string]string) bool {
+ for k, v := range headers {
+ if strings.EqualFold(k, "content-type") {
+ return strings.HasPrefix(strings.ToLower(strings.TrimSpace(v)), "text/html")
+ }
+ }
+ return false
+}
+
+func flattenValues(v map[string][]string) map[string]string {
+ out := make(map[string]string, len(v))
+ for k, vs := range v {
+ if len(vs) > 0 {
+ out[k] = vs[0]
+ }
+ }
+ return out
+}
diff --git a/services/plugins/server_sse_test.go b/services/plugins/server_sse_test.go
new file mode 100644
index 0000000000..a85548ec9c
--- /dev/null
+++ b/services/plugins/server_sse_test.go
@@ -0,0 +1,189 @@
+package plugins
+
+import (
+ "bufio"
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gobwas/glob"
+)
+
+// sseServer builds a Server with a single "demo" plugin and the given hub.
+// adminGlobs (if any) are compiled into the plugin's admin-path set so the
+// reserved _sse endpoint can be exercised under admin gating.
+func sseServer(t *testing.T, perms []string, hub *SSEHub, adminGlobs ...string) *Server {
+ t.Helper()
+ var globs []glob.Glob
+ for _, g := range adminGlobs {
+ globs = append(globs, glob.MustCompile(g))
+ }
+ loaded := &Loaded{
+ Manifest: &Manifest{API: "1", DisplayName: "demo", Slug: "demo", Version: "1.0.0", Permissions: perms},
+ adminGlobs: globs,
+ }
+ s := NewServer([]*Loaded{loaded})
+ s.SSE = hub
+ return s
+}
+
+func TestServer_SSE_NotFoundWithoutPermission(t *testing.T) {
+ // http.serve alone does not grant the reserved SSE endpoint.
+ s := sseServer(t, []string{"http.serve"}, NewSSEHub())
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, httptest.NewRequest("GET", "/plugins/demo/_sse/overlay", nil))
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("without http.sse: status %d want %d", rec.Code, http.StatusNotFound)
+ }
+}
+
+func TestServer_SSE_ServiceUnavailableWhenHubNil(t *testing.T) {
+ // Permission granted but the host wired no hub → 503, not a panic.
+ s := sseServer(t, []string{"http.sse"}, nil)
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, httptest.NewRequest("GET", "/plugins/demo/_sse/overlay", nil))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Errorf("nil hub: status %d want %d", rec.Code, http.StatusServiceUnavailable)
+ }
+}
+
+func TestServer_SSE_ServiceUnavailableAtConnectionCap(t *testing.T) {
+ hub := NewSSEHub()
+ hub.maxPerPlugin = 0 // every connection is over the cap
+ s := sseServer(t, []string{"http.sse"}, hub)
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, httptest.NewRequest("GET", "/plugins/demo/_sse/overlay", nil))
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Errorf("over cap: status %d want %d", rec.Code, http.StatusServiceUnavailable)
+ }
+}
+
+func TestServer_SSE_AdminChannelRequiresAuth(t *testing.T) {
+ // A channel matching an admin glob is auth-gated like any admin path.
+ // The server delegates the 401 to the host's RequireAdmin middleware
+ // (the real one in production is middleware.RequireAdminAuth); here
+ // we stub it with a always-reject wrapper so we observe the 401.
+ s := sseServer(t, []string{"http.sse"}, NewSSEHub(), "/_sse/*")
+ s.RequireAdmin = func(http.HandlerFunc) http.HandlerFunc {
+ return func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, "Unauthorized", http.StatusUnauthorized)
+ }
+ }
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, httptest.NewRequest("GET", "/plugins/demo/_sse/admin-stats", nil))
+ if rec.Code != http.StatusUnauthorized {
+ t.Errorf("admin SSE channel without auth: status %d want %d", rec.Code, http.StatusUnauthorized)
+ }
+}
+
+func TestServer_SSE_StreamsPublishedFrames(t *testing.T) {
+ // Both the named-channel and default-channel routing forms should connect
+ // and stream a frame the plugin publishes to the matching channel.
+ cases := []struct{ name, path, channel string }{
+ {"named channel", "/_sse/overlay", "overlay"},
+ {"default channel", "/_sse", ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ hub := NewSSEHub()
+ srv := httptest.NewServer(sseServer(t, []string{"http.sse"}, hub))
+ defer srv.Close()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, "GET", srv.URL+"/plugins/demo"+tc.path, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("connect: status %d want %d", resp.StatusCode, http.StatusOK)
+ }
+ if ct := resp.Header.Get("Content-Type"); ct != "text/event-stream" {
+ t.Errorf("Content-Type = %q want text/event-stream", ct)
+ }
+
+ // The handler subscribes on its own goroutine; wait for it before
+ // publishing so the frame isn't dropped before anyone's listening.
+ waitForSSESubscribers(t, hub, "demo", tc.channel, 1)
+
+ if n := hub.Publish("demo", tc.channel, "emoji", []byte("🦉")); n != 1 {
+ t.Fatalf("expected delivery to the connected client, got %d", n)
+ }
+
+ frame := readSSEFrame(t, resp.Body)
+ if !strings.Contains(frame, "event: emoji\n") || !strings.Contains(frame, "data: 🦉\n") {
+ t.Errorf("unexpected SSE frame: %q", frame)
+ }
+
+ // Client disconnect must release the subscription.
+ cancel()
+ waitForSSESubscribers(t, hub, "demo", tc.channel, 0)
+ })
+ }
+}
+
+// waitForSSESubscribers polls the hub until (plugin, channel) has exactly want
+// subscribers, failing the test on timeout.
+func waitForSSESubscribers(t *testing.T, h *SSEHub, plugin, channel string, want int) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ h.mu.Lock()
+ got := len(h.subscribers[sseKey(plugin, channel)])
+ h.mu.Unlock()
+ if got == want {
+ return
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("timed out waiting for %d subscriber(s) on %s/%s (have %d)", want, plugin, channel, got)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+}
+
+// readSSEFrame reads from an event-stream body until one complete data frame
+// (terminated by a blank line) is read, skipping any keep-alive comments.
+func readSSEFrame(t *testing.T, body io.Reader) string {
+ t.Helper()
+ type result struct {
+ frame string
+ err error
+ }
+ done := make(chan result, 1)
+ go func() {
+ r := bufio.NewReader(body)
+ var b strings.Builder
+ for {
+ line, err := r.ReadString('\n')
+ b.WriteString(line)
+ if err != nil {
+ done <- result{b.String(), err}
+ return
+ }
+ if line == "\n" && strings.Contains(b.String(), "data:") {
+ done <- result{b.String(), nil}
+ return
+ }
+ }
+ }()
+ select {
+ case res := <-done:
+ if res.err != nil && !strings.Contains(res.frame, "data:") {
+ t.Fatalf("reading SSE frame: %v (got %q)", res.err, res.frame)
+ }
+ return res.frame
+ case <-time.After(3 * time.Second):
+ t.Fatal("timed out reading SSE frame")
+ return ""
+ }
+}
diff --git a/services/plugins/server_test.go b/services/plugins/server_test.go
new file mode 100644
index 0000000000..5217a200fe
--- /dev/null
+++ b/services/plugins/server_test.go
@@ -0,0 +1,284 @@
+package plugins
+
+import (
+ "io/fs"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+ "testing/fstest"
+
+ "github.com/gobwas/glob"
+)
+
+// Thin wrappers so the test code reads cleanly. These are only used by the
+// path-traversal test, which needs a real on-disk root boundary.
+func osMkdirAll(path string) error { return os.MkdirAll(path, 0o755) }
+func osDirFS(path string) fs.FS { return os.DirFS(path) }
+func osWriteFile(t *testing.T, path string, data []byte) {
+ t.Helper()
+ if err := os.WriteFile(path, data, 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// Build a Server with a single synthetic plugin that has no extism instance
+// (we only exercise static-asset paths here). For tests that need the dynamic
+// handler, use a real built wasm via the LoadPlugin / LoadPackage path.
+func staticOnlyServer(t *testing.T, perms []string, assets fstest.MapFS) *Server {
+ t.Helper()
+ loaded := &Loaded{
+ Manifest: &Manifest{
+ API: "1", DisplayName: "demo", Slug: "demo", Version: "1.0.0", Permissions: perms,
+ },
+ PublicFS: assets,
+ }
+ return NewServer([]*Loaded{loaded})
+}
+
+func TestServer_NotFound_UnknownPlugin(t *testing.T) {
+ s := staticOnlyServer(t, []string{"http.serve"}, fstest.MapFS{})
+ req := httptest.NewRequest("GET", "/plugins/nonexistent/anything", nil)
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("unknown plugin: status %d want %d", rec.Code, http.StatusNotFound)
+ }
+}
+
+func TestServer_NotFound_WithoutHttpServePermission(t *testing.T) {
+ // Plugin exists but never declared http.serve — should appear as not-found.
+ s := staticOnlyServer(t, []string{} /* no http.serve */, fstest.MapFS{
+ "index.html": {Data: []byte("hi")},
+ })
+ req := httptest.NewRequest("GET", "/plugins/demo/index.html", nil)
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Errorf("no http.serve permission: status %d want %d", rec.Code, http.StatusNotFound)
+ }
+}
+
+func TestServer_StaticFile(t *testing.T) {
+ s := staticOnlyServer(t, []string{"http.serve"}, fstest.MapFS{
+ "style.css": {Data: []byte("body { color: red; }")},
+ })
+ req := httptest.NewRequest("GET", "/plugins/demo/style.css", nil)
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Errorf("status: got %d want 200", rec.Code)
+ }
+ if !strings.Contains(rec.Body.String(), "color: red") {
+ t.Errorf("body: got %q", rec.Body.String())
+ }
+}
+
+func TestServer_DirectoryServesIndexHTML(t *testing.T) {
+ s := staticOnlyServer(t, []string{"http.serve"}, fstest.MapFS{
+ "index.html": {Data: []byte("<h1>root</h1>")},
+ "sub/index.html": {Data: []byte("<h1>sub</h1>")},
+ })
+
+ // Slash-terminated directory URLs serve the index.html directly. Without
+ // a trailing slash, the server issues a 301 to the canonical slash form
+ // so the browser's base URL is right for any relative links on the page.
+ for _, tc := range []struct {
+ path string
+ wantStatus int
+ wantBody string
+ wantLocation string
+ }{
+ {path: "/plugins/demo/", wantStatus: http.StatusOK, wantBody: "<h1>root</h1>"},
+ {path: "/plugins/demo/sub/", wantStatus: http.StatusOK, wantBody: "<h1>sub</h1>"},
+ {path: "/plugins/demo/sub", wantStatus: http.StatusMovedPermanently, wantLocation: "/plugins/demo/sub/"},
+ } {
+ req := httptest.NewRequest("GET", tc.path, nil)
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, req)
+ if rec.Code != tc.wantStatus {
+ t.Errorf("%s: status %d want %d", tc.path, rec.Code, tc.wantStatus)
+ continue
+ }
+ if tc.wantBody != "" && rec.Body.String() != tc.wantBody {
+ t.Errorf("%s: body %q want %q", tc.path, rec.Body.String(), tc.wantBody)
+ }
+ if tc.wantLocation != "" && rec.Header().Get("Location") != tc.wantLocation {
+ t.Errorf("%s: Location %q want %q", tc.path, rec.Header().Get("Location"), tc.wantLocation)
+ }
+ }
+}
+
+func TestServer_InjectsAdminStylesOnAdminPath(t *testing.T) {
+ // HTML served on a manifest-declared admin path gets the host's admin
+ // stylesheet link injected before </head>, so the plugin iframe matches
+ // the surrounding admin visually without plugin-author opt-in.
+ loaded := &Loaded{
+ Manifest: &Manifest{
+ API: "1", DisplayName: "demo", Slug: "demo", Version: "1.0.0",
+ Permissions: []string{"http.serve"},
+ },
+ PublicFS: fstest.MapFS{
+ "admin/index.html": {Data: []byte("<html><head><title>x</title></head><body>hi</body></html>")},
+ "index.html": {Data: []byte("<html><head></head><body>public</body></html>")},
+ },
+ adminGlobs: []glob.Glob{glob.MustCompile("/admin/*")},
+ adminPaths: []string{"/admin/*"},
+ }
+ s := NewServer([]*Loaded{loaded})
+ // IsAuthenticated returns true so the admin-path gate lets the request through.
+ s.IsAuthenticated = func(*http.Request) bool { return true }
+ s.RequireAdmin = func(h http.HandlerFunc) http.HandlerFunc { return h }
+
+ // Admin path: snippet present.
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, httptest.NewRequest("GET", "/plugins/demo/admin/", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("admin path status %d want 200; body=%q", rec.Code, rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), adminStyleMarker) {
+ t.Errorf("admin HTML did not contain injected stylesheet marker; body=%q", rec.Body.String())
+ }
+ if !strings.Contains(rec.Body.String(), "/styles/admin/plugin-iframe.css") {
+ t.Errorf("admin HTML missing plugin-iframe.css link; body=%q", rec.Body.String())
+ }
+
+ // Public path: snippet absent (we don't theme non-admin pages).
+ rec = httptest.NewRecorder()
+ s.ServeHTTP(rec, httptest.NewRequest("GET", "/plugins/demo/", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("public path status %d want 200; body=%q", rec.Code, rec.Body.String())
+ }
+ if strings.Contains(rec.Body.String(), adminStyleMarker) {
+ t.Errorf("public HTML should not have injected stylesheet marker; body=%q", rec.Body.String())
+ }
+}
+
+func TestInjectAdminStyles_Idempotent(t *testing.T) {
+ html := []byte("<html><head></head><body></body></html>")
+ once := injectAdminStyles(html)
+ twice := injectAdminStyles(once)
+ if string(once) != string(twice) {
+ t.Errorf("second pass changed the document\nfirst: %q\nsecond: %q", once, twice)
+ }
+}
+
+func TestInjectAdminStyles_NoHeadStillInjects(t *testing.T) {
+ // A body-only fragment still gets the link prepended so the iframe is
+ // themed even when the plugin emits a bare HTML snippet.
+ html := []byte("<body>just a fragment</body>")
+ out := injectAdminStyles(html)
+ if !strings.Contains(string(out), adminStyleMarker) {
+ t.Errorf("expected marker in output: %q", out)
+ }
+ if !strings.HasPrefix(string(out), "<link") {
+ t.Errorf("expected link prepended, got: %q", out)
+ }
+}
+
+// TestServer_PathTraversal_CannotEscapePublicRoot verifies that traversal
+// attempts ("../") in the URL cannot reach files outside the plugin's
+// PublicFS root. This is the actual security property — that the on-disk
+// boundary of the public directory is respected.
+func TestServer_PathTraversal_CannotEscapePublicRoot(t *testing.T) {
+ // Sibling directory layout:
+ // <tmp>/
+ // plugin-public/ ← this becomes the plugin's PublicFS
+ // safe.txt
+ // forbidden/
+ // secret.txt ← must NOT be reachable via traversal
+ root := t.TempDir()
+ pluginPublic := root + "/plugin-public"
+ forbidden := root + "/forbidden"
+ for _, d := range []string{pluginPublic, forbidden} {
+ if err := osMkdirAll(d); err != nil {
+ t.Fatal(err)
+ }
+ }
+ osWriteFile(t, pluginPublic+"/safe.txt", []byte("safe content"))
+ osWriteFile(t, forbidden+"/secret.txt", []byte("FORBIDDEN_CONTENT"))
+
+ loaded := &Loaded{
+ Manifest: &Manifest{
+ API: "1", DisplayName: "demo", Slug: "demo", Version: "1.0.0",
+ Permissions: []string{"http.serve"},
+ },
+ PublicFS: osDirFS(pluginPublic),
+ }
+ s := NewServer([]*Loaded{loaded})
+
+ // Sanity: in-root file is reachable
+ {
+ req := httptest.NewRequest("GET", "/plugins/demo/safe.txt", nil)
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "safe content") {
+ t.Fatalf("baseline reachability broken: status=%d body=%q", rec.Code, rec.Body.String())
+ }
+ }
+
+ // Real test: every traversal attempt must NOT return forbidden content.
+ traversalPaths := []string{
+ "/plugins/demo/../forbidden/secret.txt",
+ "/plugins/demo/../../forbidden/secret.txt",
+ "/plugins/demo/./../forbidden/secret.txt",
+ "/plugins/demo/safe.txt/../../forbidden/secret.txt",
+ }
+ for _, p := range traversalPaths {
+ req := httptest.NewRequest("GET", p, nil)
+ req.URL.Path = p
+ rec := httptest.NewRecorder()
+ s.ServeHTTP(rec, req)
+ if strings.Contains(rec.Body.String(), "FORBIDDEN_CONTENT") {
+ t.Errorf("%s: traversal escaped PublicFS root: %q", p, rec.Body.String())
+ }
+ }
+}
+
+func TestServer_NonGetFallsThroughStatic(t *testing.T) {
+ // POST to a static asset path shouldn't serve the file. (Static is
+ // read-only; non-GET/HEAD requests fall through to the dynamic handler.)
+ s := staticOnlyServer(t, []string{"http.serve"}, fstest.MapFS{
+ "data.txt": {Data: []byte("static data")},
+ })
+ req := httptest.NewRequest("POST", "/plugins/demo/data.txt", strings.NewReader(""))
+ rec := httptest.NewRecorder()
+ func() {
+ defer func() { _ = recover() }() // would dereference nil plugin
+ s.ServeHTTP(rec, req)
+ }()
+ if strings.Contains(rec.Body.String(), "static data") {
+ t.Errorf("POST returned static content: %q", rec.Body.String())
+ }
+}
+
+func TestIsAllowedResponseHeader(t *testing.T) {
+ allowed := []string{
+ "Content-Type", "content-type", "CONTENT-TYPE", // case-insensitive
+ "Cache-Control", "ETag", "Last-Modified", "Location", "Vary",
+ "Access-Control-Allow-Origin", "Access-Control-Allow-Methods",
+ "Content-Encoding", "Content-Language", "Link",
+ "Set-Cookie", "set-cookie", // plugins can set cookies in their own namespace
+ }
+ for _, h := range allowed {
+ if !isAllowedResponseHeader(h) {
+ t.Errorf("%q should be allowed", h)
+ }
+ }
+
+ denied := []string{
+ "Authorization",
+ "WWW-Authenticate",
+ "X-Custom-Plugin-Header",
+ "Content-Security-Policy", // host owns CSP, not plugins
+ "Strict-Transport-Security", // host owns transport security
+ "Server", // host identifies itself
+ "X-Frame-Options",
+ }
+ for _, h := range denied {
+ if isAllowedResponseHeader(h) {
+ t.Errorf("%q should be DENIED but was allowed", h)
+ }
+ }
+}
diff --git a/services/plugins/sse.go b/services/plugins/sse.go
new file mode 100644
index 0000000000..51d0cc85e7
--- /dev/null
+++ b/services/plugins/sse.go
@@ -0,0 +1,138 @@
+package plugins
+
+import (
+ "strings"
+ "sync"
+)
+
+// DefaultMaxSSEConnectionsPerPlugin caps how many simultaneous
+// Server-Sent-Events connections a single plugin may hold open. The limit
+// is per-plugin so one plugin can't exhaust the host's file descriptors or
+// memory at the expense of others.
+const DefaultMaxSSEConnectionsPerPlugin = 64
+
+// sseClient is one connected browser. The host owns the connection; the
+// stream goroutine reads pre-framed bytes off send and flushes them to the
+// client. The buffer absorbs short bursts; a client that can't keep up has
+// messages dropped (see SSEHub.Publish) rather than stalling the publisher.
+type sseClient struct {
+ send chan []byte
+}
+
+// SSEHub fans plugin-emitted events out to connected browser clients.
+//
+// It is the host-owned half of the SSE capability: plugins never hold the
+// HTTP connection (their wasm calls are short and mutex-serialized), they
+// only Publish. The hub holds the long-lived connections and delivers to
+// them. Conceptually it's the event dispatcher with browser clients as the
+// sink instead of other plugins.
+//
+// Subscribers are keyed by (plugin, channel) so a plugin can run several
+// independent streams (e.g. "overlay" and "admin-stats") and so one
+// plugin's clients never receive another's events.
+type SSEHub struct {
+ mu sync.Mutex
+ subscribers map[string]map[*sseClient]struct{}
+ connectionCounts map[string]int
+ maxPerPlugin int
+}
+
+// NewSSEHub constructs an empty hub with the default per-plugin connection
+// cap.
+func NewSSEHub() *SSEHub {
+ return &SSEHub{
+ subscribers: make(map[string]map[*sseClient]struct{}),
+ connectionCounts: make(map[string]int),
+ maxPerPlugin: DefaultMaxSSEConnectionsPerPlugin,
+ }
+}
+
+func sseKey(pluginName, channel string) string {
+ return pluginName + "\x00" + channel
+}
+
+// Subscribe registers a browser client for (pluginName, channel). It
+// returns a receive-only channel of pre-framed SSE bytes and an unsubscribe
+// func the caller MUST invoke when the connection ends. ok is false when
+// the plugin is already at its connection cap, in which case the caller
+// should reject the request.
+func (h *SSEHub) Subscribe(pluginName, channel string) (<-chan []byte, func(), bool) {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+
+ if h.connectionCounts[pluginName] >= h.maxPerPlugin {
+ return nil, nil, false
+ }
+
+ client := &sseClient{send: make(chan []byte, 16)}
+ key := sseKey(pluginName, channel)
+ if h.subscribers[key] == nil {
+ h.subscribers[key] = make(map[*sseClient]struct{})
+ }
+ h.subscribers[key][client] = struct{}{}
+ h.connectionCounts[pluginName]++
+
+ var once sync.Once
+ unsubscribe := func() {
+ once.Do(func() {
+ h.mu.Lock()
+ defer h.mu.Unlock()
+ if subs, ok := h.subscribers[key]; ok {
+ delete(subs, client)
+ if len(subs) == 0 {
+ delete(h.subscribers, key)
+ }
+ }
+ h.connectionCounts[pluginName]--
+ })
+ }
+
+ return client.send, unsubscribe, true
+}
+
+// Publish frames event+data once and delivers it to every client subscribed
+// to (pluginName, channel). Delivery is non-blocking per client: if a
+// client's buffer is full (a slow consumer), the message is dropped for that
+// client. This keeps a single slow browser from blocking the publishing
+// plugin call — correctness of the live stream is best-effort by design.
+// Returns the number of clients the frame was delivered to.
+//
+// The send happens under the hub lock; sends are non-blocking, so the lock
+// is held only briefly. Because clients are removed from the map under the
+// same lock by unsubscribe, Publish never sends to a torn-down client.
+func (h *SSEHub) Publish(pluginName, channel, event string, data []byte) int {
+ frame := frameSSE(event, data)
+
+ h.mu.Lock()
+ defer h.mu.Unlock()
+
+ delivered := 0
+ for client := range h.subscribers[sseKey(pluginName, channel)] {
+ select {
+ case client.send <- frame:
+ delivered++
+ default:
+ // Slow client; drop this frame rather than block the publisher.
+ }
+ }
+ return delivered
+}
+
+// frameSSE formats one Server-Sent-Events message. A named event becomes an
+// "event:" line; the data is split across "data:" lines (SSE requires one
+// per newline) and terminated by a blank line.
+func frameSSE(event string, data []byte) []byte {
+ var b strings.Builder
+ if event != "" {
+ b.WriteString("event: ")
+ b.WriteString(event)
+ b.WriteByte('\n')
+ }
+ for _, line := range strings.Split(string(data), "\n") {
+ b.WriteString("data: ")
+ b.WriteString(line)
+ b.WriteByte('\n')
+ }
+ b.WriteByte('\n')
+ return []byte(b.String())
+}
diff --git a/services/plugins/sse_test.go b/services/plugins/sse_test.go
new file mode 100644
index 0000000000..e7d75d7615
--- /dev/null
+++ b/services/plugins/sse_test.go
@@ -0,0 +1,134 @@
+package plugins
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestSSEHubPublishFansOutToSubscribers(t *testing.T) {
+ h := NewSSEHub()
+
+ a, unsubA, ok := h.Subscribe("p1", "overlay")
+ if !ok {
+ t.Fatal("first subscribe should succeed")
+ }
+ defer unsubA()
+ b, unsubB, ok := h.Subscribe("p1", "overlay")
+ if !ok {
+ t.Fatal("second subscribe should succeed")
+ }
+ defer unsubB()
+
+ if n := h.Publish("p1", "overlay", "emoji", []byte("🦉")); n != 2 {
+ t.Fatalf("expected delivery to 2 clients, got %d", n)
+ }
+
+ for _, ch := range []<-chan []byte{a, b} {
+ frame := string(<-ch)
+ if !strings.Contains(frame, "event: emoji\n") || !strings.Contains(frame, "data: 🦉\n") {
+ t.Errorf("unexpected SSE frame: %q", frame)
+ }
+ if !strings.HasSuffix(frame, "\n\n") {
+ t.Errorf("frame must end with a blank line: %q", frame)
+ }
+ }
+}
+
+func TestSSEHubIsolatesByPluginAndChannel(t *testing.T) {
+ h := NewSSEHub()
+
+ other, unsub, _ := h.Subscribe("p2", "overlay")
+ defer unsub()
+ wrongChannel, unsub2, _ := h.Subscribe("p1", "stats")
+ defer unsub2()
+
+ // No subscribers on p1/overlay → zero deliveries, and neither of the
+ // other subscriptions should receive anything.
+ if n := h.Publish("p1", "overlay", "x", []byte("y")); n != 0 {
+ t.Fatalf("expected 0 deliveries, got %d", n)
+ }
+ select {
+ case f := <-other:
+ t.Errorf("p2 subscriber should not receive p1 events, got %q", f)
+ case f := <-wrongChannel:
+ t.Errorf("p1/stats subscriber should not receive p1/overlay events, got %q", f)
+ default:
+ }
+}
+
+func TestSSEHubUnsubscribeStopsDelivery(t *testing.T) {
+ h := NewSSEHub()
+
+ ch, unsub, _ := h.Subscribe("p1", "c")
+ unsub()
+
+ if n := h.Publish("p1", "c", "e", []byte("d")); n != 0 {
+ t.Fatalf("expected 0 deliveries after unsubscribe, got %d", n)
+ }
+ // Unsubscribe must be idempotent (the stream handler defers it, and it
+ // may also run on context cancel).
+ unsub()
+ select {
+ case f := <-ch:
+ t.Errorf("no frame expected after unsubscribe, got %q", f)
+ default:
+ }
+}
+
+func TestSSEHubPerPluginConnectionCap(t *testing.T) {
+ h := NewSSEHub()
+ h.maxPerPlugin = 2
+
+ _, u1, ok1 := h.Subscribe("p1", "c")
+ _, u2, ok2 := h.Subscribe("p1", "c")
+ _, _, ok3 := h.Subscribe("p1", "c")
+ if !ok1 || !ok2 {
+ t.Fatal("first two subscribes should succeed under the cap")
+ }
+ if ok3 {
+ t.Fatal("third subscribe should be rejected by the per-plugin cap")
+ }
+
+ // A different plugin is unaffected by p1's cap.
+ if _, u, ok := h.Subscribe("p2", "c"); !ok {
+ t.Fatal("other plugin should not be affected by p1's cap")
+ } else {
+ u()
+ }
+
+ // Freeing a slot lets a new connection in.
+ u1()
+ if _, u, ok := h.Subscribe("p1", "c"); !ok {
+ t.Fatal("subscribe should succeed after a slot is freed")
+ } else {
+ u()
+ }
+ u2()
+}
+
+func TestSSEHubDropsFramesForSlowClient(t *testing.T) {
+ h := NewSSEHub()
+ _, unsub, _ := h.Subscribe("p1", "c") // never drained
+ defer unsub()
+
+ // The client buffer is 16; publishing well beyond it must not block and
+ // must report fewer deliveries than sends once the buffer fills.
+ delivered := 0
+ for i := 0; i < 100; i++ {
+ delivered += h.Publish("p1", "c", "e", []byte("d"))
+ }
+ if delivered == 0 {
+ t.Fatal("expected some deliveries before the buffer filled")
+ }
+ if delivered >= 100 {
+ t.Fatalf("expected dropped frames for the undrained client, delivered=%d", delivered)
+ }
+}
+
+func TestFrameSSEMultilineData(t *testing.T) {
+ got := string(frameSSE("", []byte("line1\nline2")))
+ want := "data: line1\ndata: line2\n\n"
+ if got != want {
+ t.Errorf("frameSSE multiline = %q, want %q", got, want)
+ }
+}
diff --git a/services/webhooks/webhooks.go b/services/webhooks/webhooks.go
index af6602f03d..87a1832efb 100644
--- a/services/webhooks/webhooks.go
+++ b/services/webhooks/webhooks.go
@@ -6,11 +6,13 @@
package webhooks
import (
+ "context"
"sync"
"time"
"github.com/owncast/owncast/models"
"github.com/owncast/owncast/services/activitypub/persistence/followersrepository"
+ "github.com/owncast/owncast/services/dispatcher"
)
// BaseWebhookData contains common fields shared across all webhook event data.
@@ -82,6 +84,13 @@ func (s *Service) SendEventToWebhooks(payload WebhookEvent) {
// optional waitgroup so callers (tests, batched senders) can wait for
// all destinations to be drained.
func (s *Service) sendEventToWebhooks(payload WebhookEvent, wg *sync.WaitGroup) {
+ // Publish to the shared dispatcher so in-process consumers (e.g. the
+ // plugin host) see every event, even when no HTTP webhook destinations
+ // are configured for it.
+ if s.events != nil {
+ s.events.Publish(context.Background(), dispatcher.Event{Type: payload.Type, Payload: payload})
+ }
+
webhooks := s.webhookRepository.GetWebhooksForEvent(payload.Type)
for _, webhook := range webhooks {
diff --git a/services/webhooks/webhooks_test.go b/services/webhooks/webhooks_test.go
index 28d4302f15..6dc793a047 100644
--- a/services/webhooks/webhooks_test.go
+++ b/services/webhooks/webhooks_test.go
@@ -2,6 +2,7 @@ package webhooks
import (
"bytes"
+ "context"
"encoding/json"
"fmt"
"net/http"
@@ -19,6 +20,7 @@ import (
"github.com/owncast/owncast/persistence/webhookrepository"
"github.com/owncast/owncast/services/chat/events"
"github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/dispatcher"
)
func fakeGetStatus() models.Status {
@@ -108,6 +110,36 @@ func TestPublicSend(t *testing.T) {
wg.Wait()
}
+// Every event dispatched to webhooks is also published to the shared
+// dispatcher, regardless of whether any HTTP webhook destinations exist —
+// this is how in-process consumers (the plugin host) receive events.
+func TestSendEventPublishesToDispatcher(t *testing.T) {
+ d := dispatcher.New()
+ var got []dispatcher.Event
+ d.AddListener(func(_ context.Context, e dispatcher.Event) {
+ got = append(got, e)
+ })
+
+ svc := New(Deps{
+ GetStatus: fakeGetStatus,
+ ConfigRepository: configrepository.New(testDatastore),
+ WebhookRepository: webhookrepository.New(testDatastore),
+ Events: d,
+ })
+
+ svc.SendEventToWebhooks(WebhookEvent{Type: models.MessageSent, EventData: struct{}{}})
+
+ if len(got) != 1 {
+ t.Fatalf("expected the event published to the dispatcher, got %d", len(got))
+ }
+ if got[0].Type != models.MessageSent {
+ t.Errorf("dispatched event type = %q, want %q", got[0].Type, models.MessageSent)
+ }
+ if _, ok := got[0].Payload.(WebhookEvent); !ok {
+ t.Errorf("dispatched payload type = %T, want webhooks.WebhookEvent", got[0].Payload)
+ }
+}
+
// Make sure that events are only sent to interested endpoints.
func TestRouting(t *testing.T) {
eventTypes := []models.EventType{models.ChatActionSent, models.UserJoined, events.UserParted}
diff --git a/services/webhooks/workerpool.go b/services/webhooks/workerpool.go
index 57030f8b96..85b0166fca 100644
--- a/services/webhooks/workerpool.go
+++ b/services/webhooks/workerpool.go
@@ -13,6 +13,7 @@ import (
"github.com/owncast/owncast/persistence/configrepository"
"github.com/owncast/owncast/persistence/webhookrepository"
"github.com/owncast/owncast/services/activitypub/persistence/followersrepository"
+ "github.com/owncast/owncast/services/dispatcher"
)
// Job bundles a single webhook destination + payload for a worker.
@@ -47,6 +48,11 @@ type Service struct {
// consulted when dispatching events as well as when marking a
// destination as used after a successful send.
webhookRepository webhookrepository.WebhookRepository
+
+ // events is the shared dispatcher every event is published to, so
+ // in-process consumers (the plugin host today, other subsystems later)
+ // receive them without this service knowing who they are.
+ events *dispatcher.Dispatcher
}
// Deps lists every collaborator a *Service needs at construction.
@@ -55,6 +61,7 @@ type Deps struct {
Followers followersrepository.FollowersRepository
ConfigRepository configrepository.ConfigRepository
WebhookRepository webhookrepository.WebhookRepository
+ Events *dispatcher.Dispatcher
}
// New constructs an idle webhook Service. Call Start to launch the
@@ -66,6 +73,7 @@ func New(deps Deps) *Service {
followers: deps.Followers,
configRepository: deps.ConfigRepository,
webhookRepository: deps.WebhookRepository,
+ events: deps.Events,
}
}
diff --git a/test/automated/activitypub/entrypoint.sh b/test/automated/activitypub/entrypoint.sh
index 834e5af97e..8dd3ff5324 100755
--- a/test/automated/activitypub/entrypoint.sh
+++ b/test/automated/activitypub/entrypoint.sh
@@ -1,4 +1,5 @@
#!/bin/bash
+# shellcheck disable=SC2317 # cleanup() is invoked via trap, not direct call
set -e
# Generate mkcert certificates for the test domains.
@@ -10,11 +11,28 @@ mkcert -cert-file "${CERT_DIR}/cert.pem" \
-key-file "${CERT_DIR}/key.pem" \
owncast.local snac.local localhost 127.0.0.1
+# This container runs as root and the repo is bind-mounted from the host, so
+# anything the test writes into the tree (Owncast's ./data dir, created mode
+# 0700, and any built owncast binary) lands on the host owned by root and the
+# invoking user can't remove it. Hand those artifacts back on exit. HOST_UID/
+# HOST_GID are set by run.sh; when unset (entrypoint run directly) this is a
+# no-op.
+cleanup() {
+ if [[ -n "${HOST_UID}" && -n "${HOST_GID}" ]]; then
+ chown -R "${HOST_UID}:${HOST_GID}" /owncast/test/automated/activitypub 2>/dev/null || true
+ fi
+}
+trap cleanup EXIT
+
# Change CWD away from the mounted repo root so Owncast doesn't pick up the
# host's (possibly wrong-architecture) ffmpeg binary via ./ffmpeg detection.
# Stay inside the git repo so `git rev-parse --show-toplevel` still works.
cd /owncast/test/automated/activitypub
-# Run the specified test script (default: test-federation.sh)
+# Run the specified test script (default: test-federation.sh). Not exec'd, so
+# the cleanup trap above still runs afterward; the test's exit code is preserved.
TEST_SCRIPT="${1:-test-federation.sh}"
-exec "/owncast/test/automated/activitypub/${TEST_SCRIPT}"
+set +e
+"/owncast/test/automated/activitypub/${TEST_SCRIPT}"
+exit_code=$?
+exit "${exit_code}"
diff --git a/test/automated/activitypub/run.sh b/test/automated/activitypub/run.sh
index faebb28938..c0a8e32aff 100755
--- a/test/automated/activitypub/run.sh
+++ b/test/automated/activitypub/run.sh
@@ -31,6 +31,11 @@ done
# Always skip interactive prompts inside the container
ENV_ARGS+=("-e" "CI=true")
+# Pass the host user/group so the container can hand any files it writes into
+# the bind-mounted repo (notably Owncast's data dir) back to us on exit,
+# instead of leaving them owned by root and unremovable.
+ENV_ARGS+=("-e" "HOST_UID=$(id -u)" "-e" "HOST_GID=$(id -g)")
+
# Port-forward when KEEP_RUNNING is set so the user can access the services
EXTRA_ARGS=()
if [[ "${KEEP_RUNNING}" == "true" ]]; then
diff --git a/test/automated/plugins/.gitignore b/test/automated/plugins/.gitignore
new file mode 100644
index 0000000000..f3b576f013
--- /dev/null
+++ b/test/automated/plugins/.gitignore
@@ -0,0 +1,3 @@
+node_modules/
+package-lock.json
+ffmpeg
diff --git a/test/automated/plugins/echo-bot.test.js b/test/automated/plugins/echo-bot.test.js
new file mode 100644
index 0000000000..a79819cbde
--- /dev/null
+++ b/test/automated/plugins/echo-bot.test.js
@@ -0,0 +1,46 @@
+// End-to-end: echo-bot (built from the SDK) receives a chat message via its
+// onChatMessage handler and replies with owncast.chat.send, posting under its
+// own bot identity. Also verifies the host doesn't loop on the bot's reply.
+const { test, expect, beforeAll } = require('@jest/globals');
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const { registerChat, sendChatMessage } = require('./lib/chat');
+const { enableOnly, sleep, ADMIN } = require('./lib/plugins');
+
+const PLUGIN = 'echo-bot';
+// Bot display name as declared in the example manifest's `bot.displayName`.
+// The chat-bot user posts under this string, independent of the plugin's
+// slug or display name.
+const BOT_DISPLAY_NAME = 'Example Echo';
+
+beforeAll(async () => {
+ await enableOnly(PLUGIN);
+});
+
+test('echoes a chat message once, under its own bot identity (no loop)', async () => {
+ const { accessToken } = await registerChat();
+ const probe = 'echo-probe-' + Date.now();
+ sendChatMessage({ body: probe, type: 'CHAT' }, accessToken);
+
+ // user message -> onChatMessage -> chat.send (as the bot) -> persisted.
+ await sleep(3000);
+
+ const messages = (
+ await request
+ .get('/api/admin/chat/messages')
+ .auth(...ADMIN)
+ .expect(200)
+ ).body;
+ const echoes = messages.filter(
+ (m) =>
+ m.user &&
+ m.user.displayName === BOT_DISPLAY_NAME &&
+ typeof m.body === 'string' &&
+ m.body.includes(probe),
+ );
+
+ // Exactly one: the bot reacted to the user's message, but its own reply
+ // (authored by a bot) was not delivered back to it, so it didn't loop.
+ expect(echoes.length).toBe(1);
+});
diff --git a/test/automated/plugins/lib/chat.js b/test/automated/plugins/lib/chat.js
new file mode 100644
index 0000000000..5828ac6ef1
--- /dev/null
+++ b/test/automated/plugins/lib/chat.js
@@ -0,0 +1,23 @@
+// Minimal chat helpers for the plugin integration tests: register an
+// anonymous chat user and send a message over the websocket. (Mirrors
+// test/automated/api/lib/chat.js, trimmed to what these tests need.)
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+const WebSocket = require('ws');
+
+async function registerChat() {
+ const response = await request.post('/api/chat/register');
+ return response.body;
+}
+
+function sendChatMessage(message, accessToken) {
+ const ws = new WebSocket(`ws://localhost:8080/ws?accessToken=${accessToken}`);
+ ws.on('open', function () {
+ ws.send(JSON.stringify(message), function () {
+ ws.close();
+ });
+ });
+}
+
+module.exports.registerChat = registerChat;
+module.exports.sendChatMessage = sendChatMessage;
diff --git a/test/automated/plugins/lib/plugins.js b/test/automated/plugins/lib/plugins.js
new file mode 100644
index 0000000000..7347ba4d31
--- /dev/null
+++ b/test/automated/plugins/lib/plugins.js
@@ -0,0 +1,50 @@
+// Helpers for driving the plugin admin API during the integration tests.
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const ADMIN = ['admin', 'abc123'];
+
+// Every example plugin this suite installs. The tests share one Owncast
+// instance, so enableOnly() unloads the others to keep each test isolated.
+const ALL = [
+ 'profanity-filter',
+ 'echo-bot',
+ 'overlay',
+ 'styles-demo',
+ 'scripts-demo',
+ 'viewer-gate',
+ 'page-content-demo',
+ 'tabs-demo',
+];
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+// enableOnly loads `name`, unloads every other example, and waits for the
+// manager to instantiate the wasm runtime. The enable call returns 200 only
+// when the plugin actually loaded, so this also asserts a successful load.
+async function enableOnly(name) {
+ for (const plugin of ALL) {
+ if (plugin === name) {
+ continue;
+ }
+ await request
+ .post(`/api/admin/plugins/${plugin}/disable`)
+ .auth(...ADMIN)
+ .expect(200);
+ }
+ await request
+ .post(`/api/admin/plugins/${name}/enable`)
+ .auth(...ADMIN)
+ .expect(200);
+ await sleep(1500);
+}
+
+async function listPlugins() {
+ const res = await request
+ .get('/api/admin/plugins')
+ .auth(...ADMIN)
+ .expect(200);
+ return res.body;
+}
+
+module.exports = { enableOnly, listPlugins, sleep, ADMIN };
diff --git a/test/automated/plugins/overlay.test.js b/test/automated/plugins/overlay.test.js
new file mode 100644
index 0000000000..7dcb0f8892
--- /dev/null
+++ b/test/automated/plugins/overlay.test.js
@@ -0,0 +1,38 @@
+// End-to-end: overlay (built from the SDK) serves a static page and a dynamic
+// JSON endpoint backed by the owncast.chat.history() host function, exercising
+// the plugin HTTP-serving path in a running Owncast instance.
+const { test, expect, beforeAll } = require('@jest/globals');
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const { registerChat, sendChatMessage } = require('./lib/chat');
+const { enableOnly, sleep } = require('./lib/plugins');
+
+const PLUGIN = 'overlay';
+
+beforeAll(async () => {
+ await enableOnly(PLUGIN);
+});
+
+test('serves its static overlay page at /plugins/overlay/', async () => {
+ const res = await request.get('/plugins/overlay/').expect(200);
+ expect(res.headers['content-type']).toMatch(/html/);
+ expect(res.text.length).toBeGreaterThan(0);
+});
+
+test('serves a dynamic API backed by chat.history()', async () => {
+ // Seed a chat message, then read it back through the plugin's own endpoint.
+ const { accessToken } = await registerChat();
+ const probe = 'overlay-probe-' + Date.now();
+ sendChatMessage({ body: probe, type: 'CHAT' }, accessToken);
+ await sleep(2000);
+
+ const res = await request.get('/plugins/overlay/api/messages').expect(200);
+ expect(res.headers['content-type']).toMatch(/json/);
+
+ const messages = res.body.messages || [];
+ const found = messages.some(
+ (m) => typeof m.body === 'string' && m.body.includes(probe),
+ );
+ expect(found).toBe(true);
+});
diff --git a/test/automated/plugins/package.json b/test/automated/plugins/package.json
new file mode 100644
index 0000000000..6629e43191
--- /dev/null
+++ b/test/automated/plugins/package.json
@@ -0,0 +1,23 @@
+{
+ "name": "owncast-plugin-integration-tests",
+ "version": "1.0.0",
+ "private": true,
+ "description": "End-to-end tests that build a plugin from the SDK and run it inside Owncast.",
+ "scripts": {
+ "test": "jest *.test.js"
+ },
+ "license": "ISC",
+ "dependencies": {
+ "supertest": "^6.3.2",
+ "ws": "^7.5.9"
+ },
+ "devDependencies": {
+ "jest": "^29.7.0",
+ "jest-jasmine2": "^29.7.0"
+ },
+ "jest": {
+ "verbose": true,
+ "maxWorkers": 1,
+ "testRunner": "jest-jasmine2"
+ }
+}
diff --git a/test/automated/plugins/page-content-demo.test.js b/test/automated/plugins/page-content-demo.test.js
new file mode 100644
index 0000000000..055b79528d
--- /dev/null
+++ b/test/automated/plugins/page-content-demo.test.js
@@ -0,0 +1,39 @@
+// End-to-end: page-content-demo (built from the SDK) ships an HTML
+// file in `manifest.extraPageContent`. The host reads the file's
+// bytes from the plugin and prepends them to the admin's rendered
+// extraPageContent on /api/config, so plugin HTML lands at the top
+// of the viewer page's extra-content block. Verifies the full
+// pipeline against a running Owncast instance.
+const { test, expect, beforeAll } = require('@jest/globals');
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const { enableOnly } = require('./lib/plugins');
+
+const PLUGIN = 'page-content-demo';
+
+beforeAll(async () => {
+ await enableOnly(PLUGIN);
+});
+
+test('/api/config extraPageContent contains the plugin HTML with a delimiter naming the source', async () => {
+ const res = await request.get('/api/config').expect(200);
+ const { extraPageContent } = res.body;
+ expect(typeof extraPageContent).toBe('string');
+ // Each plugin contribution is wrapped with an HTML comment naming
+ // the source so a reader can attribute the markup back.
+ expect(extraPageContent).toMatch(/<!-- plugin: page-content-demo /);
+ // Plugin's marker id should be inline.
+ expect(extraPageContent).toMatch(/plugin-page-content-demo-banner/);
+});
+
+test('disabling the plugin drops its HTML from /api/config extraPageContent', async () => {
+ // Switch to a different plugin so page-content-demo unloads. Pick
+ // one without `extraPageContent` so the assertion is unambiguous.
+ await enableOnly('echo-bot');
+ const res = await request.get('/api/config').expect(200);
+ const { extraPageContent } = res.body;
+ expect(typeof extraPageContent).toBe('string');
+ expect(extraPageContent).not.toMatch(/plugin: page-content-demo/);
+ expect(extraPageContent).not.toMatch(/plugin-page-content-demo-banner/);
+});
diff --git a/test/automated/plugins/profanity-filter.test.js b/test/automated/plugins/profanity-filter.test.js
new file mode 100644
index 0000000000..8ca0da8bc7
--- /dev/null
+++ b/test/automated/plugins/profanity-filter.test.js
@@ -0,0 +1,62 @@
+// End-to-end: profanity-filter (built from the SDK) filters chat through its
+// filterChatMessage handler in a running Owncast instance.
+const { test, expect, beforeAll } = require('@jest/globals');
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const { registerChat, sendChatMessage } = require('./lib/chat');
+const { enableOnly, listPlugins, sleep, ADMIN } = require('./lib/plugins');
+
+const PLUGIN = 'profanity-filter';
+
+beforeAll(async () => {
+ await enableOnly(PLUGIN);
+});
+
+test('the plugin is discovered, enabled, and loaded', async () => {
+ // Look up by slug: that's the stable identifier the admin API keys on.
+ // The display `name` is now a free-form label ("Profanity Filter").
+ const entry = (await listPlugins()).find((p) => p.slug === PLUGIN);
+ expect(entry).toBeDefined();
+ expect(entry.enabled).toBe(true);
+ expect(entry.loaded).toBe(true);
+});
+
+test('redacts profanity from chat messages', async () => {
+ const { accessToken } = await registerChat();
+ sendChatMessage({ body: 'what the hell', type: 'CHAT' }, accessToken);
+ await sleep(2000);
+
+ const messages = (
+ await request
+ .get('/api/admin/chat/messages')
+ .auth(...ADMIN)
+ .expect(200)
+ ).body;
+ const message = messages.find(
+ (m) => typeof m.body === 'string' && m.body.includes('what the'),
+ );
+
+ expect(message).toBeDefined();
+ // "hell" is redacted by the plugin; the body is the rendered (HTML) message.
+ expect(message.body).toBe('<p>what the ****</p>');
+});
+
+test('leaves clean messages untouched', async () => {
+ const { accessToken } = await registerChat();
+ sendChatMessage({ body: 'hello everyone', type: 'CHAT' }, accessToken);
+ await sleep(2000);
+
+ const messages = (
+ await request
+ .get('/api/admin/chat/messages')
+ .auth(...ADMIN)
+ .expect(200)
+ ).body;
+ const message = messages.find(
+ (m) => typeof m.body === 'string' && m.body.includes('hello everyone'),
+ );
+
+ expect(message).toBeDefined();
+ expect(message.body).toBe('<p>hello everyone</p>');
+});
diff --git a/test/automated/plugins/run.sh b/test/automated/plugins/run.sh
new file mode 100755
index 0000000000..c25368b222
--- /dev/null
+++ b/test/automated/plugins/run.sh
@@ -0,0 +1,85 @@
+#!/bin/bash
+
+# Standalone end-to-end plugin integration test.
+#
+# Unlike the Go unit tests, this builds plugins from source using the Owncast
+# plugin SDK (so no WASM is bundled in this repo), installs them into a real
+# Owncast instance, and verifies they actually run by exercising chat and HTTP
+# through them. Run by CI via the Earthly `+plugin-tests` target.
+#
+# The plugins built here are the SDK's own examples — the suite tracks them
+# rather than maintaining plugin source in this repo.
+#
+# Env overrides:
+# PLUGIN_SDK_DIR path to an existing SDK checkout; if set, no clone happens
+# (use this for local runs: PLUGIN_SDK_DIR=~/src/plugin-sdk ./run.sh)
+# PLUGIN_SDK_REPO git URL of the plugin SDK (default: owncast/plugin-sdk)
+# PLUGIN_SDK_REF branch/tag/sha to build from (default: main)
+
+set -e
+
+source ../tools.sh
+
+REPO_ROOT="$(git rev-parse --show-toplevel)"
+PLUGIN_SDK_DIR="${PLUGIN_SDK_DIR:-}"
+PLUGIN_SDK_REPO="${PLUGIN_SDK_REPO:-https://github.com/owncast/plugin-sdk}"
+PLUGIN_SDK_REF="${PLUGIN_SDK_REF:-main}"
+
+# SDK example plugins exercised by the tests in this directory.
+PLUGIN_NAMES=(profanity-filter echo-bot overlay styles-demo scripts-demo viewer-gate page-content-demo tabs-demo)
+
+PLUGIN_DIR="${REPO_ROOT}/data/plugins"
+
+# Resolve the SDK source: an existing local checkout, or a fresh clone.
+if [[ -n "$PLUGIN_SDK_DIR" ]]; then
+ echo "Using local plugin SDK at ${PLUGIN_SDK_DIR}"
+ SDK_DIR="$PLUGIN_SDK_DIR"
+ CLONED_SDK=0
+else
+ echo "Cloning the plugin SDK (${PLUGIN_SDK_REPO}@${PLUGIN_SDK_REF})..."
+ SDK_DIR="$(mktemp -d)"
+ CLONED_SDK=1
+ # Never block on an interactive credential prompt — fail clearly instead.
+ export GIT_TERMINAL_PROMPT=0
+ git clone --depth 1 --branch "$PLUGIN_SDK_REF" "$PLUGIN_SDK_REPO" "$SDK_DIR"
+fi
+
+# Tear down the installed plugins (and the SDK clone, but never a local SDK
+# checkout the caller pointed us at) on top of tools.sh's server/database
+# cleanup, which `finish` performs.
+plugins_finish() {
+ rm -rf "$PLUGIN_DIR"
+ if [[ "$CLONED_SDK" == "1" ]]; then
+ rm -rf "$SDK_DIR"
+ fi
+ finish
+}
+trap plugins_finish EXIT
+
+# Install the SDK package's own dependencies. The build CLI (owncast-plugin)
+# runs from sdks/js/bin and requires esbuild/jszip resolvable from there, and
+# its postinstall fetches extism-js + binaryen. build-plugin.sh only installs
+# each example's deps, not the SDK package's, so do it here once up front.
+echo "Installing plugin SDK build dependencies..."
+(cd "${SDK_DIR}/sdks/js" && npm install --no-audit --no-fund)
+
+echo "Building example plugins..."
+rm -rf "$PLUGIN_DIR"
+mkdir -p "$PLUGIN_DIR"
+for name in "${PLUGIN_NAMES[@]}"; do
+ echo " building ${name}..."
+ # build-plugin.sh runs `npm install` (whose postinstall fetches extism-js
+ # and friends) then `npm run build`, emitting an .ocpkg into the SDK's
+ # plugins/ directory.
+ (cd "$SDK_DIR" && ./tools/build-plugin.sh "examples/js/${name}")
+ cp "${SDK_DIR}/plugins/${name}.ocpkg" "${PLUGIN_DIR}/"
+done
+
+# Install the JS test framework for this suite.
+npm install --quiet --no-progress
+
+install_ffmpeg
+start_owncast
+
+# Run the tests against the running instance.
+npm test
diff --git a/test/automated/plugins/scripts-demo.test.js b/test/automated/plugins/scripts-demo.test.js
new file mode 100644
index 0000000000..6095a2b182
--- /dev/null
+++ b/test/automated/plugins/scripts-demo.test.js
@@ -0,0 +1,38 @@
+// End-to-end: scripts-demo (built from the SDK) ships a JS file in
+// `manifest.scripts`. The host reads the file's bytes from the plugin
+// and appends them to the admin's customJavascript at the
+// /customjavascript endpoint, so the viewer loads one <script> tag
+// covering both sources. Verifies the full pipeline against a
+// running Owncast instance.
+const { test, expect, beforeAll } = require('@jest/globals');
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const { enableOnly } = require('./lib/plugins');
+
+const PLUGIN = 'scripts-demo';
+
+beforeAll(async () => {
+ await enableOnly(PLUGIN);
+});
+
+test('/customjavascript contains the plugin script with a delimiter naming the source', async () => {
+ const res = await request.get('/customjavascript').expect(200);
+ expect(res.headers['content-type']).toMatch(/javascript/);
+ // The host prefixes each plugin contribution with a comment naming
+ // the source so devtools can attribute a behavior back to whichever
+ // plugin shipped it.
+ expect(res.text).toMatch(/\/\/ plugin: scripts-demo /);
+ // Plugin's own JS body should be inline.
+ expect(res.text).toMatch(/__pluginScriptsDemoLoaded/);
+ expect(res.text).toMatch(/\[scripts-demo\] plugin script loaded/);
+});
+
+test('disabling the plugin drops its JS from /customjavascript', async () => {
+ // Switch to a different plugin so scripts-demo unloads. Pick one
+ // without `scripts` so the assertion is unambiguous.
+ await enableOnly('echo-bot');
+ const res = await request.get('/customjavascript').expect(200);
+ expect(res.text).not.toMatch(/plugin: scripts-demo/);
+ expect(res.text).not.toMatch(/__pluginScriptsDemoLoaded/);
+});
diff --git a/test/automated/plugins/styles-demo.test.js b/test/automated/plugins/styles-demo.test.js
new file mode 100644
index 0000000000..3796f6cc8e
--- /dev/null
+++ b/test/automated/plugins/styles-demo.test.js
@@ -0,0 +1,42 @@
+// End-to-end: styles-demo (built from the SDK) ships a CSS file in
+// `manifest.styles`. The host reads the file's bytes from the plugin
+// and appends them to the admin's customStyles on /api/config, so
+// the viewer renders one inline <style> block covering both
+// sources. Verifies the full pipeline against a running Owncast
+// instance.
+const { test, expect, beforeAll } = require('@jest/globals');
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const { enableOnly } = require('./lib/plugins');
+
+const PLUGIN = 'styles-demo';
+
+beforeAll(async () => {
+ await enableOnly(PLUGIN);
+});
+
+test('/api/config customStyles contains the plugin CSS with a delimiter naming the source', async () => {
+ const res = await request.get('/api/config').expect(200);
+ const { customStyles } = res.body;
+ expect(typeof customStyles).toBe('string');
+ // The host prefixes each plugin contribution with a comment naming
+ // the source plugin so devtools "view source" can attribute a rule
+ // back to whichever plugin shipped it.
+ expect(customStyles).toMatch(/\/\* plugin: styles-demo /);
+ // Plugin's own CSS body should be inline.
+ expect(customStyles).toMatch(/--plugin-styles-demo-loaded/);
+ expect(customStyles).toMatch(/body::before/);
+});
+
+test('disabling the plugin drops its CSS from /api/config customStyles', async () => {
+ // Switch to a different plugin so styles-demo unloads. Any of the
+ // other examples works; pick one without `styles` so the assertion
+ // is unambiguous.
+ await enableOnly('echo-bot');
+ const res = await request.get('/api/config').expect(200);
+ const { customStyles } = res.body;
+ expect(typeof customStyles).toBe('string');
+ expect(customStyles).not.toMatch(/plugin: styles-demo/);
+ expect(customStyles).not.toMatch(/--plugin-styles-demo-loaded/);
+});
diff --git a/test/automated/plugins/tabs-demo.test.js b/test/automated/plugins/tabs-demo.test.js
new file mode 100644
index 0000000000..e7edef8747
--- /dev/null
+++ b/test/automated/plugins/tabs-demo.test.js
@@ -0,0 +1,44 @@
+// End-to-end: tabs-demo (built from the SDK) declares two viewer-page
+// tabs in manifest.tabs. The host reads each tab's content file from
+// the plugin's assets/ directory and inlines the HTML into the
+// pluginTabs[] array on /api/config. Verifies the full pipeline
+// against a running Owncast instance.
+const { test, expect, beforeAll } = require('@jest/globals');
+var request = require('supertest');
+request = request('http://127.0.0.1:8080');
+
+const { enableOnly } = require('./lib/plugins');
+
+const PLUGIN = 'tabs-demo';
+
+beforeAll(async () => {
+ await enableOnly(PLUGIN);
+});
+
+test('/api/config pluginTabs advertises both tabs with their inlined HTML', async () => {
+ const res = await request.get('/api/config').expect(200);
+ const { pluginTabs } = res.body;
+ expect(Array.isArray(pluginTabs)).toBe(true);
+ const tabs = pluginTabs.filter((t) => t.slug === PLUGIN);
+ expect(tabs.length).toBe(2);
+
+ const music = tabs.find((t) => t.title === 'Music');
+ expect(music).toBeDefined();
+ expect(music.html).toMatch(/plugin-tabs-demo-music/);
+ expect(music.html).toMatch(/What we're listening to/);
+
+ const schedule = tabs.find((t) => t.title === 'Schedule');
+ expect(schedule).toBeDefined();
+ expect(schedule.html).toMatch(/plugin-tabs-demo-schedule/);
+ expect(schedule.html).toMatch(/Stream schedule/);
+});
+
+test('disabling the plugin drops its tabs from /api/config', async () => {
+ // Switch to a different plugin so tabs-demo unloads. Pick one
+ // without manifest.tabs so the assertion is unambiguous.
+ await enableOnly('echo-bot');
+ const res = await request.get('/api/config').expect(200);
+ const { pluginTabs } = res.body;
+ expect(Array.isArray(pluginTabs)).toBe(true);
+ expect(pluginTabs.find((t) => t.slug === PLUGIN)).toBeUndefined();
+});
diff --git a/test/automated/upgrades/README.md b/test/automated/upgrades/README.md
index 103a718d53..cc3c107203 100644
--- a/test/automated/upgrades/README.md
+++ b/test/automated/upgrades/README.md
@@ -1,5 +1,7 @@
# Automated Owncast releases and upgrade test
+The list of releases is fetched dynamically from the GitHub API, so the test always covers every published release without needing to be updated by hand. Running it requires `curl` and `jq`.
+
## Upgrades in succession tests
This test will automatically download each release, one after another, to verify they all run in order. It concludes by creating a build from the `develop` branch and running the upgrade to that in order to verify the upcoming release.
diff --git a/test/automated/upgrades/run.sh b/test/automated/upgrades/run.sh
index 0138b93fec..4c6e8e0aca 100755
--- a/test/automated/upgrades/run.sh
+++ b/test/automated/upgrades/run.sh
@@ -3,21 +3,39 @@
# This script will download all the releases of Owncast and test them
# to ensure that upgrades work as expected. It will also test the
# development branch as the final test.
-# It is hard coded to run under 64bit intel linux.
+# The release list is fetched dynamically from the GitHub API so it stays
+# current as new versions are published.
+# It is hard coded to run under 64bit intel linux, and requires curl and jq.
# set -o errexit
set -o pipefail
-releases=(
- "https://github.com/owncast/owncast/releases/download/v0.0.6/owncast-0.0.6-linux-64bit.zip"
- "https://github.com/owncast/owncast/releases/download/v0.0.7/owncast-0.0.7-linux-64bit.zip"
- "https://github.com/owncast/owncast/releases/download/v0.0.8/owncast-0.0.8-linux-64bit.zip"
- "https://github.com/owncast/owncast/releases/download/v0.0.9/owncast-0.0.9-linux-64bit.zip"
- "https://github.com/owncast/owncast/releases/download/v0.0.10/owncast-0.0.10-linux-64bit.zip"
- "https://github.com/owncast/owncast/releases/download/v0.0.11/owncast-0.0.11-linux-64bit.zip"
- "https://github.com/owncast/owncast/releases/download/v0.0.12/owncast-0.0.12-linux-64bit.zip"
- "https://github.com/owncast/owncast/releases/download/v0.0.13/owncast-0.0.13-linux-64bit.zip"
-)
+if ! command -v jq >/dev/null 2>&1; then
+ echo "Error: 'jq' is required to fetch the list of releases but was not found." >&2
+ exit 1
+fi
+
+# Fetch the list of linux 64-bit release download URLs from the GitHub API,
+# sorted oldest to newest. This keeps the test against the full set of
+# published releases without hard-coding versions that go out of date.
+fetch_release_urls() {
+ curl -sL -H "Accept: application/vnd.github+json" \
+ "https://api.github.com/repos/owncast/owncast/releases?per_page=100" |
+ jq -r '.[]
+ | select(.prerelease == false and .draft == false)
+ | .assets[]
+ | select(.name | test("linux-64bit\\.zip$"))
+ | .browser_download_url' |
+ sort -V
+}
+
+echo "Fetching the list of Owncast releases from GitHub..."
+mapfile -t releases < <(fetch_release_urls)
+
+if [ ${#releases[@]} -eq 0 ]; then
+ echo "Error: failed to fetch any releases from the GitHub API." >&2
+ exit 1
+fi
echo "--------------------------------------------"
echo "Owncast releases upgrade test."
@@ -51,7 +69,7 @@ test_release() {
build_development() {
echo "Building test release from current development branch..."
cd src || exit
- git clone https://github.com/owncast/owncast
+ git clone --depth 1 https://github.com/owncast/owncast
cd owncast || exit
earthly +package --platform="linux/amd64"
mv dist/owncast-develop-linux-64bit.zip ../../releases/owncast-develop-linux-64bit.zip
diff --git a/web/components/admin/MainLayout.tsx b/web/components/admin/MainLayout.tsx
index fb07b8f6d3..cd2bc93cef 100644
--- a/web/components/admin/MainLayout.tsx
+++ b/web/components/admin/MainLayout.tsx
@@ -5,9 +5,13 @@ import { differenceInSeconds } from 'date-fns';
import { useRouter } from 'next/router';
import { Layout, Menu, Alert, Button, Space, Tooltip } from 'antd';
+import { useTranslation } from 'next-export-i18n';
import classNames from 'classnames';
import dynamic from 'next/dynamic';
-import { upgradeVersionAvailable } from '../../utils/apis';
+import { fetchData, PLUGINS_LIST, upgradeVersionAvailable } from '../../utils/apis';
+import { Plugin } from '../../interfaces/plugin';
+import { PluginIcon } from './plugins/PluginIcon';
+import { Localization } from '../../types/localization';
import { parseSecondsToDurationString } from '../../utils/format';
import { OwncastLogo } from '../common/OwncastLogo/OwncastLogo';
@@ -58,6 +62,10 @@ const ExperimentOutlined = dynamic(() => import('@ant-design/icons/ExperimentOut
ssr: false,
});
+const AppstoreOutlined = dynamic(() => import('@ant-design/icons/AppstoreOutlined'), {
+ ssr: false,
+});
+
const EditOutlined = dynamic(() => import('@ant-design/icons/EditOutlined'), {
ssr: false,
});
@@ -75,6 +83,7 @@ export type MainLayoutProps = {
};
export const MainLayout: FC<MainLayoutProps> = ({ children }) => {
+ const { t } = useTranslation();
const context = useContext(ServerStatusContext);
const { serverConfig, online, broadcaster, versionNumber, error: serverError } = context || {};
const { instanceDetails, chatDisabled, federation } = serverConfig;
@@ -107,6 +116,26 @@ export const MainLayout: FC<MainLayoutProps> = ({ children }) => {
checkForUpgrade();
}, [versionNumber]);
+ // Plugins with declared admin pages drive the sidebar's Plugins
+ // submenu. Fetched once on mount; the admin would refresh the page to
+ // see the submenu reflect newly enabled/disabled plugins.
+ const [plugins, setPlugins] = useState<Plugin[]>([]);
+ useEffect(() => {
+ let cancelled = false;
+ fetchData(PLUGINS_LIST)
+ .then(result => {
+ if (cancelled) return;
+ setPlugins(Array.isArray(result) ? result : []);
+ })
+ .catch(() => {
+ // Sidebar still works without the submenu — the top-level Plugins
+ // link to the overview page remains. Silent on error.
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
useEffect(() => {
setCurrentStreamTitle(instanceDetails.streamTitle);
}, [instanceDetails]);
@@ -273,6 +302,35 @@ export const MainLayout: FC<MainLayoutProps> = ({ children }) => {
icon: <ExperimentOutlined />,
children: integrationsMenu,
},
+ {
+ key: 'plugins-menu',
+ label: t(Localization.Admin.Plugins.sidebarTitle),
+ icon: <AppstoreOutlined />,
+ children: [
+ {
+ key: '/admin/plugins',
+ label: <Link href="/admin/plugins">{t(Localization.Admin.Plugins.overview)}</Link>,
+ },
+ // One entry per loaded plugin that declares at least one admin
+ // page, so the admin can jump straight to a plugin's config
+ // without going through the overview + Configure button. URL is
+ // a static route plus an id query param (the plugin's slug)
+ // because the admin UI is statically exported and can't
+ // enumerate plugin identifiers at build time. Sidebar labels use
+ // the human-readable display name.
+ ...plugins
+ .filter(p => (p.adminPages?.length ?? 0) > 0)
+ .map(p => ({
+ key: `/admin/plugins/configure?id=${p.slug}`,
+ label: (
+ <Link href={{ pathname: '/admin/plugins/configure', query: { id: p.slug } }}>
+ {p.name}
+ </Link>
+ ),
+ icon: <PluginIcon plugin={p} size="sidebar" />,
+ })),
+ ],
+ },
upgradeVersion && {
type: 'divider',
key: 'upgrade-divider',
@@ -307,6 +365,16 @@ export const MainLayout: FC<MainLayoutProps> = ({ children }) => {
);
}, []);
+ // The per-plugin configure page is a query-string route
+ // (/admin/plugins/configure?id=...), so the literal-key match above
+ // doesn't fire when navigating to a specific plugin. Open the plugins
+ // submenu whenever the URL is anywhere in /admin/plugins.
+ useEffect(() => {
+ if (route && route.startsWith('/admin/plugins')) {
+ setOpenKeys(prev => (prev.includes('plugins-menu') ? prev : [...prev, 'plugins-menu']));
+ }
+ }, [route]);
+
return (
<Layout id="admin-page" className={appClass}>
<Head>
diff --git a/web/components/admin/plugins/BrowseRegistry.module.scss b/web/components/admin/plugins/BrowseRegistry.module.scss
new file mode 100644
index 0000000000..18cb2993dd
--- /dev/null
+++ b/web/components/admin/plugins/BrowseRegistry.module.scss
@@ -0,0 +1,72 @@
+// Layout for the registry browse modal. The cards lay out as a
+// fixed-width icon on the left, the bulk of the metadata in the
+// middle, and a primary action on the right.
+
+.error {
+ margin-bottom: 16px;
+}
+
+.loader {
+ display: flex;
+ justify-content: center;
+ padding: 32px 0;
+}
+
+.list {
+ width: 100%;
+}
+
+.row {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+}
+
+.icon {
+ flex: 0 0 auto;
+
+ img {
+ width: 48px;
+ height: 48px;
+ border-radius: 6px;
+ object-fit: contain;
+ }
+}
+
+// Puzzle-piece SVG placeholder for plugins without a bundled icon.
+// currentColor on the SVG stroke picks up the surrounding text color,
+// so it adapts to light/dark themes without per-theme styling.
+.iconFallback {
+ width: 48px;
+ height: 48px;
+ padding: 8px;
+ border-radius: 6px;
+ background: rgb(128 128 128 / 12%);
+ color: rgb(128 128 128 / 85%);
+}
+
+.body {
+ flex: 1 1 auto;
+ min-width: 0;
+}
+
+.title {
+ font-size: 14px;
+ margin-bottom: 4px;
+}
+
+.summary {
+ margin-bottom: 8px !important;
+}
+
+// Row of permission tags between the summary and the optional tag
+// row. Small bottom margin so the tag row underneath doesn't visually
+// merge into the permissions when both are present.
+.permissions {
+ margin-bottom: 6px;
+}
+
+.actions {
+ flex: 0 0 auto;
+ align-self: center;
+}
diff --git a/web/components/admin/plugins/BrowseRegistry.tsx b/web/components/admin/plugins/BrowseRegistry.tsx
new file mode 100644
index 0000000000..b5704a6d53
--- /dev/null
+++ b/web/components/admin/plugins/BrowseRegistry.tsx
@@ -0,0 +1,229 @@
+import React, { useState } from 'react';
+import { Alert, Button, Card, Empty, Space, Spin, Tag, Tooltip, Typography } from 'antd';
+import { useTranslation } from 'next-export-i18n';
+import { Localization } from '../../../types/localization';
+import { PuzzlePiece } from './PluginIcon';
+import { permissionDescriptionKey, permissionNameKey } from './permissionDescriptions';
+import s from './BrowseRegistry.module.scss';
+
+const { Text, Paragraph } = Typography;
+
+// RegistryManifest is the embedded plugin.manifest.json from inside the
+// .ocpkg, surfaced by the registry so the Browse tab can preview what
+// a plugin asks for before the admin clicks Install. Only the fields
+// the UI actually renders are typed here; the registry can send extra
+// fields without breaking the page.
+export type RegistryManifest = {
+ permissions?: string[];
+};
+
+// One published plugin in the registry's browse payload. Mirrors the
+// publishedPluginView shape from the directory's plugin_browse.go;
+// keep these aligned. `slug` is the canonical identifier (URL segment,
+// install request body); `name` is the human-readable display name.
+export type RegistryPlugin = {
+ slug: string;
+ name: string;
+ summary?: string;
+ homepage?: string;
+ tags?: string[];
+ iconURL?: string;
+ authorName?: string;
+ latest?: {
+ version: string;
+ sizeBytes?: number;
+ sha256?: string;
+ // Embedded manifest for the latest version. The registry inlines
+ // it so Browse cards can show permissions (and other manifest
+ // metadata) without a second round-trip per card.
+ manifest?: RegistryManifest;
+ };
+ versions?: { version: string }[];
+};
+
+export type BrowseRegistryProps = {
+ // Map of installed plugin slug -> currently-installed version, so
+ // each card can decide whether to render Install / Installed /
+ // Update.
+ installedVersions: Map<string, string>;
+ // The registry's published plugins. Fetched by the parent so the
+ // same data backs the Browse tab and the Installed tab's
+ // "update available" tags.
+ registry: RegistryPlugin[];
+ registryLoading: boolean;
+ // Non-null when the registry fetch failed (network error, host
+ // returned a non-2xx, etc.). Renders the "catalog unavailable"
+ // state with a retry button. `null` means the fetch succeeded
+ // (the array may still be empty: that's the "no plugins published
+ // yet" state, distinct from "catalog is offline").
+ registryError?: string | null;
+ // Called when the admin clicks Install or Update. The parent runs
+ // the registry-install endpoint, refreshes both lists, and (for
+ // non-enabled plugins) opens the InstallConfirmModal.
+ onInstall: (slug: string, version: string) => Promise<void>;
+ // Called when the admin clicks Retry after a catalog fetch
+ // failure. Should re-attempt the registry list fetch.
+ onRetry?: () => void;
+};
+
+// BrowseRegistry renders the publicly-available plugins as a list of
+// cards inside the Browse tab. The bytes never pass through the
+// browser: the Owncast host downloads from the registry, verifies
+// SHA256, and runs the same Install path as a manual .ocpkg upload.
+export const BrowseRegistry = ({
+ installedVersions,
+ registry,
+ registryLoading,
+ registryError = null,
+ onInstall,
+ onRetry,
+}: BrowseRegistryProps) => {
+ const { t } = useTranslation();
+ // Names whose install POST is in flight; per-card spinner state so
+ // multiple installs don't lock the whole list.
+ const [installing, setInstalling] = useState<Set<string>>(new Set());
+
+ const triggerInstall = async (plugin: RegistryPlugin) => {
+ if (!plugin.latest) return;
+ const { slug } = plugin;
+ setInstalling(prev => new Set(prev).add(slug));
+ try {
+ await onInstall(slug, plugin.latest.version);
+ } finally {
+ setInstalling(prev => {
+ const next = new Set(prev);
+ next.delete(slug);
+ return next;
+ });
+ }
+ };
+
+ if (registryLoading) {
+ return (
+ <div className={s.loader}>
+ <Spin />
+ </div>
+ );
+ }
+
+ // Catalog unreachable: distinct from the empty-but-reachable state.
+ // Shows the actual error (network, 502, etc.) so an admin
+ // troubleshooting a misconfigured OWNCAST_PLUGIN_REGISTRY env or a
+ // down upstream has something concrete to act on.
+ if (registryError !== null) {
+ return (
+ <Alert
+ type="warning"
+ showIcon
+ message={t(Localization.Admin.Plugins.browseUnavailableTitle)}
+ description={
+ <Space direction="vertical" size={8}>
+ <Text>{t(Localization.Admin.Plugins.browseUnavailableDescription)}</Text>
+ <Text type="secondary">
+ <code>{registryError}</code>
+ </Text>
+ {onRetry && (
+ <Button size="small" onClick={onRetry}>
+ {t(Localization.Admin.Plugins.browseUnavailableRetry)}
+ </Button>
+ )}
+ </Space>
+ }
+ />
+ );
+ }
+
+ if (registry.length === 0) {
+ return <Empty description={t(Localization.Admin.Plugins.browseEmpty)} />;
+ }
+
+ return (
+ <Space direction="vertical" size="middle" className={s.list}>
+ {registry.map(plugin => {
+ const installedVersion = installedVersions.get(plugin.slug);
+ const latestVersion = plugin.latest?.version;
+ const isInstalled = installedVersion !== undefined;
+ const hasUpdate =
+ isInstalled && latestVersion !== undefined && installedVersion !== latestVersion;
+
+ let actionButton: React.ReactNode;
+ if (!plugin.latest) {
+ actionButton = <Button disabled>{t(Localization.Admin.Plugins.browseInstall)}</Button>;
+ } else if (hasUpdate) {
+ actionButton = (
+ <Button
+ type="primary"
+ loading={installing.has(plugin.slug)}
+ onClick={() => triggerInstall(plugin)}
+ >
+ {t(Localization.Admin.Plugins.browseUpdate, { version: latestVersion })}
+ </Button>
+ );
+ } else if (isInstalled) {
+ actionButton = <Button disabled>{t(Localization.Admin.Plugins.browseInstalled)}</Button>;
+ } else {
+ actionButton = (
+ <Button
+ type="primary"
+ loading={installing.has(plugin.slug)}
+ onClick={() => triggerInstall(plugin)}
+ >
+ {t(Localization.Admin.Plugins.browseInstall)}
+ </Button>
+ );
+ }
+
+ return (
+ <Card key={plugin.slug} size="small">
+ <div className={s.row}>
+ <div className={s.icon}>
+ {plugin.iconURL ? (
+ <img src={plugin.iconURL} alt="" />
+ ) : (
+ <PuzzlePiece className={s.iconFallback} />
+ )}
+ </div>
+ <div className={s.body}>
+ <div className={s.title}>
+ <strong>{plugin.name}</strong>
+ {plugin.latest && <Text type="secondary"> v{plugin.latest.version}</Text>}
+ </div>
+ {plugin.summary && <Paragraph className={s.summary}>{plugin.summary}</Paragraph>}
+ {plugin.latest?.manifest?.permissions &&
+ plugin.latest.manifest.permissions.length > 0 && (
+ // Permissions the plugin's manifest declares, so the
+ // admin sees the scope they'd be granting before
+ // clicking Install. Each tag shows the short label;
+ // the tooltip carries the full plain-language
+ // description. Same maps as the Installed tab so the
+ // copy stays in lock-step between views.
+ <Space size={[4, 4]} wrap className={s.permissions}>
+ {plugin.latest.manifest.permissions.map(perm => {
+ const nameKey = permissionNameKey[perm];
+ const descKey = permissionDescriptionKey[perm];
+ const label = nameKey ? t(nameKey) : perm;
+ const description = descKey ? t(descKey) : perm;
+ return (
+ <Tooltip key={perm} title={description}>
+ <Tag>{label}</Tag>
+ </Tooltip>
+ );
+ })}
+ </Space>
+ )}
+ {plugin.tags && plugin.tags.length > 0 && (
+ <Space size={[4, 4]} wrap>
+ {plugin.tags.map(tag => (
+ <Tag key={tag}>{tag}</Tag>
+ ))}
+ </Space>
+ )}
+ </div>
+ <div className={s.actions}>{actionButton}</div>
+ </div>
+ </Card>
+ );
+ })}
+ </Space>
+ );
+};
diff --git a/web/components/admin/plugins/InstallConfirmModal.tsx b/web/components/admin/plugins/InstallConfirmModal.tsx
new file mode 100644
index 0000000000..b97646832d
--- /dev/null
+++ b/web/components/admin/plugins/InstallConfirmModal.tsx
@@ -0,0 +1,88 @@
+import React from 'react';
+import { List, Modal, Space, Typography } from 'antd';
+import { useTranslation } from 'next-export-i18n';
+import { Plugin, PluginPermission } from '../../../interfaces/plugin';
+import { Localization } from '../../../types/localization';
+import { permissionDescriptionKey, permissionNameKey } from './permissionDescriptions';
+
+const { Paragraph } = Typography;
+
+export type InstallConfirmModalProps = {
+ // The just-installed plugin, or null when the modal should be
+ // hidden. Open state is derived from this rather than a separate
+ // boolean so the parent only owns one piece of state.
+ plugin: Plugin | null;
+ onCancel: () => void;
+ onEnable: () => void;
+};
+
+// InstallConfirmModal pops after a plugin is downloaded + installed
+// from the registry. Lists the permissions the plugin's manifest
+// declares (in plain language, with descriptions on hover) and asks
+// the admin whether to enable it right now. Cancel leaves the plugin
+// installed but disabled; the admin can flip the switch later from
+// the Installed tab.
+export const InstallConfirmModal = ({ plugin, onCancel, onEnable }: InstallConfirmModalProps) => {
+ const { t } = useTranslation();
+ const permissions = plugin?.permissions || [];
+ const name = plugin?.name ?? '';
+
+ return (
+ <Modal
+ open={!!plugin}
+ title={t(Localization.Admin.Plugins.installConfirmTitle, { name })}
+ onCancel={onCancel}
+ onOk={onEnable}
+ okText={t(Localization.Admin.Plugins.installConfirmEnable)}
+ cancelText={t(Localization.Admin.Plugins.installConfirmCancel)}
+ okButtonProps={{ type: 'primary' }}
+ >
+ {permissions.length === 0 ? (
+ <Paragraph>{t(Localization.Admin.Plugins.installConfirmNoPermissions)}</Paragraph>
+ ) : (
+ <>
+ <Paragraph>{t(Localization.Admin.Plugins.installConfirmPrompt)}</Paragraph>
+ <List
+ size="small"
+ bordered
+ dataSource={permissions}
+ renderItem={p => {
+ const nameKey = permissionNameKey[p];
+ const descKey = permissionDescriptionKey[p];
+ // network.fetch carries an extra dimension to the trust
+ // decision: which hosts the plugin is allowed to reach.
+ // Show the manifest.network.allowedHosts list under this
+ // row's description so the admin sees the host scope
+ // alongside the permission itself before approving.
+ const allowedHosts =
+ p === PluginPermission.NetworkFetch ? (plugin?.allowedHosts ?? []) : [];
+ const descText = descKey ? t(descKey) : null;
+ const description =
+ allowedHosts.length > 0 ? (
+ <Space direction="vertical" size={4}>
+ {descText && <span>{descText}</span>}
+ <span>
+ {t(Localization.Admin.Plugins.allowedHostsLabel)}{' '}
+ {allowedHosts.map((host, idx) => (
+ <React.Fragment key={host}>
+ {idx > 0 && ', '}
+ <code>{host}</code>
+ </React.Fragment>
+ ))}
+ </span>
+ </Space>
+ ) : (
+ descText
+ );
+ return (
+ <List.Item>
+ <List.Item.Meta title={nameKey ? t(nameKey) : p} description={description} />
+ </List.Item>
+ );
+ }}
+ />
+ </>
+ )}
+ </Modal>
+ );
+};
diff --git a/web/components/admin/plugins/PluginDetail.module.scss b/web/components/admin/plugins/PluginDetail.module.scss
new file mode 100644
index 0000000000..37003d5959
--- /dev/null
+++ b/web/components/admin/plugins/PluginDetail.module.scss
@@ -0,0 +1,39 @@
+// PluginDetail's per-plugin view. The iframe sits flush against the
+// admin panel (no chrome of its own), and the metadata header uses a
+// scss-driven class instead of inline style props so we can keep the
+// component focused on data shape.
+
+.container {
+ width: 100%;
+}
+
+.title {
+ margin-bottom: 0;
+}
+
+.version {
+ font-size: 14px;
+ font-weight: normal;
+ margin-left: 8px;
+}
+
+.iframe {
+ width: 100%;
+ height: 70vh;
+ border: none;
+ background: transparent;
+}
+
+// Rendered markdown of a plugin's INSTRUCTIONS.md. Constrain the line
+// length for readability and let headings/lists use their default flow.
+.instructions {
+ max-width: 760px;
+
+ img {
+ max-width: 100%;
+ }
+
+ pre {
+ overflow-x: auto;
+ }
+}
diff --git a/web/components/admin/plugins/PluginDetail.tsx b/web/components/admin/plugins/PluginDetail.tsx
new file mode 100644
index 0000000000..938bbe8533
--- /dev/null
+++ b/web/components/admin/plugins/PluginDetail.tsx
@@ -0,0 +1,343 @@
+import React, { useEffect, useMemo, useState } from 'react';
+import { Alert, Space, Spin, Table, Tabs, Tag, Typography } from 'antd';
+import { useTranslation } from 'next-export-i18n';
+import dynamic from 'next/dynamic';
+import ReactMarkdown from 'react-markdown';
+import { Plugin, PluginPermission } from '../../../interfaces/plugin';
+import { Localization } from '../../../types/localization';
+import { fetchText, pluginInstructionsUrl } from '../../../utils/apis';
+import { permissionDescriptionKey } from './permissionDescriptions';
+import s from './PluginDetail.module.scss';
+
+const { Title, Text, Paragraph } = Typography;
+
+// Manifest `icon` fields are short semantic names. Map them to AntD icons
+// so the gear/wrench/etc. a plugin author wrote shows up on the tab. Names
+// without a mapping fall through to no icon (and we'll just show the
+// title), which is what we'd otherwise have rendered anyway.
+const SettingOutlined = dynamic(() => import('@ant-design/icons/SettingOutlined'), { ssr: false });
+const ToolOutlined = dynamic(() => import('@ant-design/icons/ToolOutlined'), { ssr: false });
+const UserOutlined = dynamic(() => import('@ant-design/icons/UserOutlined'), { ssr: false });
+const LockOutlined = dynamic(() => import('@ant-design/icons/LockOutlined'), { ssr: false });
+const InfoCircleOutlined = dynamic(() => import('@ant-design/icons/InfoCircleOutlined'), {
+ ssr: false,
+});
+const AppstoreOutlined = dynamic(() => import('@ant-design/icons/AppstoreOutlined'), {
+ ssr: false,
+});
+const FileTextOutlined = dynamic(() => import('@ant-design/icons/FileTextOutlined'), {
+ ssr: false,
+});
+const BellOutlined = dynamic(() => import('@ant-design/icons/BellOutlined'), { ssr: false });
+
+const pageIconForName = (name?: string): React.ReactNode => {
+ if (!name) return null;
+ switch (name.toLowerCase()) {
+ case 'gear':
+ case 'settings':
+ case 'cog':
+ return <SettingOutlined />;
+ case 'wrench':
+ case 'tool':
+ return <ToolOutlined />;
+ case 'user':
+ case 'users':
+ return <UserOutlined />;
+ case 'lock':
+ case 'security':
+ return <LockOutlined />;
+ case 'info':
+ case 'about':
+ return <InfoCircleOutlined />;
+ case 'apps':
+ case 'plugin':
+ return <AppstoreOutlined />;
+ case 'docs':
+ case 'page':
+ return <FileTextOutlined />;
+ case 'bell':
+ case 'notifications':
+ return <BellOutlined />;
+ default:
+ return null;
+ }
+};
+
+export type PluginDetailProps = {
+ plugin: Plugin;
+};
+
+// pluginAdminUrl builds the iframe URL as a same-origin absolute path.
+// Globs that end in /* are stripped to the literal prefix; the plugin's
+// own router serves anything beneath. A trailing "/" is appended when
+// the path looks like a directory (no file extension on the last
+// segment) so the host doesn't 301-redirect to canonicalize, which
+// Next.js dev's trailing-slash handling can otherwise compose into a
+// redirect loop. Paths whose last segment has an extension (e.g.
+// "/admin/page.html") are left alone so the host actually serves the
+// file instead of looking up a same-named directory.
+const pluginAdminUrl = (pluginSlug: string, path: string): string => {
+ let normalized = path;
+ if (normalized.endsWith('/*')) {
+ normalized = normalized.slice(0, -2) || '/';
+ } else if (normalized.endsWith('*')) {
+ normalized = normalized.slice(0, -1);
+ }
+ if (!normalized.startsWith('/')) {
+ normalized = `/${normalized}`;
+ }
+ const lastSegment = normalized.split('/').filter(Boolean).pop() ?? '';
+ const looksLikeFile = lastSegment.includes('.');
+ if (!looksLikeFile && !normalized.endsWith('/')) {
+ normalized = `${normalized}/`;
+ }
+ return `/plugins/${encodeURIComponent(pluginSlug)}${normalized}`;
+};
+
+// PluginInstructions fetches the plugin's bundled INSTRUCTIONS.md and
+// renders it as markdown. The endpoint serves raw markdown (admin-gated),
+// so we read it as text and hand it to ReactMarkdown. Fetched on mount and
+// whenever the slug changes (navigating between plugins).
+const PluginInstructions = ({ slug }: { slug: string }) => {
+ const { t } = useTranslation();
+ const [markdown, setMarkdown] = useState<string | null>(null);
+ const [error, setError] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ setMarkdown(null);
+ setError(false);
+ fetchText(pluginInstructionsUrl(slug))
+ .then(text => {
+ if (!cancelled) setMarkdown(text);
+ })
+ .catch(() => {
+ if (!cancelled) setError(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [slug]);
+
+ if (error) {
+ return (
+ <Alert type="error" showIcon message={t(Localization.Admin.Plugins.instructionsLoadError)} />
+ );
+ }
+ if (markdown === null) {
+ return <Spin />;
+ }
+ return (
+ <div className={s.instructions}>
+ <ReactMarkdown>{markdown}</ReactMarkdown>
+ </div>
+ );
+};
+
+// PluginDetail renders the per-plugin view: metadata header + a tab for
+// each admin page declared in the plugin's manifest. Each tab body is an
+// iframe pointing at the plugin's own HTTP namespace.
+//
+// Declared pages are de-duplicated by the iframe URL they resolve to —
+// manifests commonly list both `/admin` and `/admin/*` so the host's
+// auth gating covers the page and anything beneath it, but for the user
+// those are one logical page, not two tabs.
+export const PluginDetail = ({ plugin }: PluginDetailProps) => {
+ const { t } = useTranslation();
+ const uniquePages = useMemo(() => {
+ const seen = new Set<string>();
+ return (plugin.adminPages ?? [])
+ .map(page => ({ ...page, url: pluginAdminUrl(plugin.slug, page.path) }))
+ .filter(page => {
+ if (seen.has(page.url)) return false;
+ seen.add(page.url);
+ return true;
+ });
+ }, [plugin.adminPages, plugin.slug]);
+
+ const pendingSet = useMemo(
+ () => new Set(plugin.pendingPermissions ?? []),
+ [plugin.pendingPermissions],
+ );
+
+ const permissionRows = useMemo(
+ () =>
+ (plugin.permissions ?? []).map(perm => {
+ const key = permissionDescriptionKey[perm];
+ return {
+ key: perm,
+ permission: perm,
+ description: key ? t(key) : '-',
+ // network.fetch carries an extra dimension to the trust
+ // decision: which hosts the plugin is allowed to reach.
+ // Surface manifest.network.allowedHosts on this row so the
+ // admin sees the host scope alongside the permission.
+ allowedHosts:
+ perm === PluginPermission.NetworkFetch ? (plugin.allowedHosts ?? []) : undefined,
+ pending: pendingSet.has(perm),
+ };
+ }),
+ [plugin.permissions, plugin.allowedHosts, pendingSet, t],
+ );
+
+ const permissionsTab = useMemo(
+ () => ({
+ key: '__permissions',
+ label: t(Localization.Admin.Plugins.permissionsTab),
+ children:
+ permissionRows.length === 0 ? (
+ <Alert
+ type="info"
+ showIcon
+ message={t(Localization.Admin.Plugins.noPermissionsTitle)}
+ description={t(Localization.Admin.Plugins.noPermissionsDescription)}
+ />
+ ) : (
+ <Space direction="vertical" size={12} style={{ width: '100%' }}>
+ {pendingSet.size > 0 && (
+ <Alert
+ type="warning"
+ showIcon
+ message={t(Localization.Admin.Plugins.statusPendingApproval)}
+ description={t(Localization.Admin.Plugins.statusPendingApprovalTooltip)}
+ />
+ )}
+ <Table
+ dataSource={permissionRows}
+ pagination={false}
+ size="middle"
+ columns={[
+ {
+ title: t(Localization.Admin.Plugins.permissionColumnHeader),
+ dataIndex: 'permission',
+ key: 'permission',
+ width: 220,
+ render: (v: string, row: { pending: boolean; allowedHosts?: string[] }) =>
+ row.pending ? (
+ <Space size={6}>
+ <code>{v}</code>
+ <Tag color="orange">
+ {t(Localization.Admin.Plugins.statusPendingApproval)}
+ </Tag>
+ </Space>
+ ) : (
+ <code>{v}</code>
+ ),
+ },
+ {
+ title: t(Localization.Admin.Plugins.descriptionColumnHeader),
+ dataIndex: 'description',
+ key: 'description',
+ render: (v: string, row: { allowedHosts?: string[]; pending: boolean }) =>
+ row.allowedHosts && row.allowedHosts.length > 0 ? (
+ <Space direction="vertical" size={4}>
+ <span>{v}</span>
+ <span>
+ {t(Localization.Admin.Plugins.allowedHostsLabel)}{' '}
+ {row.allowedHosts.map((host, idx) => (
+ <React.Fragment key={host}>
+ {idx > 0 && ', '}
+ <code>{host}</code>
+ </React.Fragment>
+ ))}
+ </span>
+ </Space>
+ ) : (
+ v
+ ),
+ },
+ ]}
+ />
+ </Space>
+ ),
+ }),
+ [permissionRows, pendingSet, t],
+ );
+
+ const pageTabs = useMemo(
+ () =>
+ uniquePages.map(page => {
+ const icon = pageIconForName(page.icon);
+ return {
+ key: page.url,
+ label: icon ? (
+ <span>
+ {icon} {page.title}
+ </span>
+ ) : (
+ page.title
+ ),
+ children: (
+ <iframe
+ title={`${plugin.name} – ${page.title}`}
+ src={page.url}
+ sandbox="allow-same-origin allow-scripts allow-forms allow-popups"
+ className={s.iframe}
+ />
+ ),
+ };
+ }),
+ [uniquePages, plugin.name],
+ );
+
+ const instructionsTab = useMemo(
+ () =>
+ plugin.hasInstructions
+ ? {
+ key: '__instructions',
+ label: (
+ <span>
+ <FileTextOutlined /> {t(Localization.Admin.Plugins.instructionsTab)}
+ </span>
+ ),
+ children: <PluginInstructions slug={plugin.slug} />,
+ }
+ : null,
+ [plugin.hasInstructions, plugin.slug, t],
+ );
+
+ const tabs = useMemo(() => {
+ const base = [...pageTabs, permissionsTab];
+ // 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]);
+
+ return (
+ <div>
+ <Space direction="vertical" size={16} className={s.container}>
+ <Space direction="vertical" size={4}>
+ <Title level={3} className={s.title}>
+ {plugin.name}
+ {plugin.version && (
+ <Text type="secondary" className={s.version}>
+ v{plugin.version}
+ </Text>
+ )}
+ </Title>
+ {plugin.description && <Paragraph>{plugin.description}</Paragraph>}
+ </Space>
+
+ {plugin.lastError && (
+ <Alert
+ type="error"
+ showIcon
+ message={t(Localization.Admin.Plugins.pluginErrorTitle)}
+ description={plugin.lastError}
+ />
+ )}
+
+ {/*
+ Uncontrolled tabs: AntD picks defaultActiveKey on mount and
+ manages selection state internally. The `key` prop ties the
+ tab state to the plugin slug, so navigating between plugins
+ (same component, new props) remounts the Tabs and resets the
+ active tab to the new plugin's first one instead of carrying
+ the stale selection across.
+ */}
+ <Tabs key={plugin.slug} defaultActiveKey={tabs[0]?.key} items={tabs} />
+ </Space>
+ </div>
+ );
+};
diff --git a/web/components/admin/plugins/PluginIcon.module.scss b/web/components/admin/plugins/PluginIcon.module.scss
new file mode 100644
index 0000000000..b64cd77ee1
--- /dev/null
+++ b/web/components/admin/plugins/PluginIcon.module.scss
@@ -0,0 +1,22 @@
+// PluginIcon: same component renders in two contexts, scaled
+// differently. The puzzle-piece SVG inherits the surrounding text
+// color via currentColor, so a missing-icon plugin matches the visual
+// weight of named-icon plugins in both the list and the sidebar.
+
+.list {
+ width: 32px;
+ height: 32px;
+ border-radius: 6px;
+ object-fit: cover;
+ flex-shrink: 0;
+ color: var(--theme-color-text-muted, var(--theme-color-components-text-on-light, currentColor));
+}
+
+.sidebar {
+ width: 16px;
+ height: 16px;
+ border-radius: 3px;
+ object-fit: cover;
+ vertical-align: middle;
+ margin-right: 12px;
+}
diff --git a/web/components/admin/plugins/PluginIcon.tsx b/web/components/admin/plugins/PluginIcon.tsx
new file mode 100644
index 0000000000..477abfd0f4
--- /dev/null
+++ b/web/components/admin/plugins/PluginIcon.tsx
@@ -0,0 +1,51 @@
+import React from 'react';
+import { Plugin } from '../../../interfaces/plugin';
+import s from './PluginIcon.module.scss';
+
+export type PluginIconProps = {
+ plugin: Pick<Plugin, 'slug' | 'hasIcon'>;
+ // size controls which class set the wrapper uses; the default sidebar
+ // entries want a small inline glyph, the plugins-list table cells want
+ // a larger square.
+ size?: 'list' | 'sidebar';
+};
+
+// PuzzlePiece is the fallback when a plugin doesn't bundle its own
+// icon.png. The single path describes a classic puzzle piece (knob on
+// the top, socket on the right) and uses currentColor so it inherits
+// the surrounding text color, including the AntD menu's hover and
+// selected states. Exported so the registry browse modal can render
+// the same placeholder for plugins whose icon URL isn't set.
+export const PuzzlePiece = ({ className }: { className?: string }) => (
+ <svg
+ viewBox="0 0 24 24"
+ className={className}
+ role="presentation"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth={1.6}
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ >
+ <path d="M10 4V3a2 2 0 1 1 4 0v1h4a2 2 0 0 1 2 2v4h-1a2 2 0 1 0 0 4h1v4a2 2 0 0 1-2 2h-4v-1a2 2 0 1 0-4 0v1H6a2 2 0 0 1-2-2v-4h1a2 2 0 1 0 0-4H4V6a2 2 0 0 1 2-2h4z" />
+ </svg>
+);
+
+// PluginIcon renders the plugin's icon.png when one was bundled, or a
+// puzzle-piece placeholder otherwise. Used by both the admin plugin
+// list (large size) and the sidebar (small size). `size` selects the
+// wrapper class; layout lives in PluginIcon.module.scss so the same
+// img/svg works in both contexts.
+export const PluginIcon = ({ plugin, size = 'list' }: PluginIconProps) => {
+ const className = size === 'sidebar' ? s.sidebar : s.list;
+ if (plugin.hasIcon) {
+ return (
+ <img
+ src={`/api/plugins/${encodeURIComponent(plugin.slug)}/icon`}
+ alt=""
+ className={className}
+ />
+ );
+ }
+ return <PuzzlePiece className={className} />;
+};
diff --git a/web/components/admin/plugins/PluginsList.module.scss b/web/components/admin/plugins/PluginsList.module.scss
new file mode 100644
index 0000000000..3809a6f160
--- /dev/null
+++ b/web/components/admin/plugins/PluginsList.module.scss
@@ -0,0 +1,44 @@
+// PluginsList row-level styles. The table itself is AntD-managed; these
+// classes apply to specific cells (small secondary text for version /
+// description, and the inline load-error alert).
+
+.secondaryText {
+ font-size: 12px;
+}
+
+.errorAlert {
+ margin-top: 6px;
+}
+
+// Per-row layout: icon + metadata side-by-side. The icon comes from
+// PluginIcon, which falls back to a puzzle-piece SVG for plugins
+// without a bundled icon.png.
+.pluginCell {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+}
+
+// Popconfirm content for the uninstall button. AntD's Popconfirm in this
+// version exposes a single `title` slot, so the two-line prompt is laid
+// out here in our own classes.
+.uninstallPrompt {
+ max-width: 320px;
+}
+
+.uninstallPromptTitle {
+ font-weight: 600;
+ margin-bottom: 4px;
+}
+
+.uninstallPromptDescription {
+ font-weight: normal;
+ font-size: 13px;
+}
+
+// Tag rendered next to the plugin's version when the registry has a
+// newer version. Cursor-pointer to hint it's clickable (wrapped in a
+// Popconfirm).
+.updateTag {
+ cursor: pointer;
+}
diff --git a/web/components/admin/plugins/PluginsList.tsx b/web/components/admin/plugins/PluginsList.tsx
new file mode 100644
index 0000000000..f33a52d568
--- /dev/null
+++ b/web/components/admin/plugins/PluginsList.tsx
@@ -0,0 +1,264 @@
+import React from 'react';
+import { Alert, Button, Popconfirm, Space, Switch, Table, Tag, Tooltip, Typography } from 'antd';
+import { useTranslation } from 'next-export-i18n';
+import dynamic from 'next/dynamic';
+import { Plugin } from '../../../interfaces/plugin';
+import { Localization } from '../../../types/localization';
+import { permissionDescriptionKey, permissionNameKey } from './permissionDescriptions';
+import { PluginIcon } from './PluginIcon';
+import s from './PluginsList.module.scss';
+
+const { Text } = Typography;
+
+// Lazy-loaded icons match the pattern used elsewhere in admin/.
+const ReloadOutlined = dynamic(() => import('@ant-design/icons/ReloadOutlined'), { ssr: false });
+const WarningFilled = dynamic(() => import('@ant-design/icons/WarningFilled'), { ssr: false });
+const AppstoreOutlined = dynamic(() => import('@ant-design/icons/AppstoreOutlined'), {
+ ssr: false,
+});
+const DeleteOutlined = dynamic(() => import('@ant-design/icons/DeleteOutlined'), { ssr: false });
+
+export type PluginsListProps = {
+ plugins: Plugin[];
+ loading: boolean;
+ // Plugin names whose enable/disable request is in flight — drives the Switch
+ // spinner. Per-plugin (not a single global flag) so two concurrent toggles
+ // don't lock the whole table.
+ togglingNames: Set<string>;
+ // Same idea for the Reload button.
+ reloadingNames: Set<string>;
+ // And for the Uninstall button.
+ uninstallingNames: Set<string>;
+ // Map of plugin name -> newer version available in the registry.
+ // Each entry shows up as a clickable "Update available" tag next
+ // to the installed version. Optional so the component works fine
+ // when the registry isn't configured.
+ availableUpdates?: Map<string, string>;
+ onToggleEnabled: (plugin: Plugin, enabled: boolean) => Promise<void> | void;
+ onReload: (plugin: Plugin) => Promise<void> | void;
+ onUninstall: (plugin: Plugin) => Promise<void> | void;
+ // Called when the admin clicks an "Update available" tag. The
+ // parent runs the registry-install endpoint with the new version
+ // (treated as a fresh install path: same SHA256 check, same
+ // post-install confirmation modal).
+ onUpdate?: (plugin: Plugin, version: string) => Promise<void> | void;
+ onSelect: (plugin: Plugin) => void;
+};
+
+// PluginsList renders one row per discovered plugin with metadata, an
+// enable/disable toggle, a reload button, and a click-to-detail action.
+// Plugins that declare manifest.admin.pages expose a "View" button that takes
+// the admin to the per-plugin detail with embedded iframe(s).
+export const PluginsList = ({
+ plugins,
+ loading,
+ togglingNames,
+ reloadingNames,
+ uninstallingNames,
+ availableUpdates,
+ onToggleEnabled,
+ onReload,
+ onUninstall,
+ onUpdate,
+ onSelect,
+}: PluginsListProps) => {
+ const { t } = useTranslation();
+ const columns = [
+ {
+ title: t(Localization.Admin.Plugins.pluginColumn),
+ key: 'name',
+ render: (_: unknown, plugin: Plugin) => (
+ <div className={s.pluginCell}>
+ <PluginIcon plugin={plugin} size="list" />
+ <Space direction="vertical" size={2}>
+ <Text strong>{plugin.name}</Text>
+ {plugin.version && (
+ <Space size={6} align="center">
+ <Text type="secondary" className={s.secondaryText}>
+ v{plugin.version}
+ </Text>
+ {availableUpdates?.has(plugin.slug) && onUpdate && (
+ <Popconfirm
+ title={t(Localization.Admin.Plugins.updateConfirmTitle, {
+ name: plugin.name,
+ version: availableUpdates.get(plugin.slug),
+ })}
+ okText={t(Localization.Admin.Plugins.updateConfirmOk)}
+ cancelText={t(Localization.Admin.Plugins.updateConfirmCancel)}
+ okButtonProps={{ type: 'primary' }}
+ onConfirm={() => onUpdate(plugin, availableUpdates.get(plugin.slug) as string)}
+ >
+ <Tag color="blue" className={s.updateTag}>
+ {t(Localization.Admin.Plugins.updateAvailable, {
+ version: availableUpdates.get(plugin.slug),
+ })}
+ </Tag>
+ </Popconfirm>
+ )}
+ </Space>
+ )}
+ {plugin.description && (
+ <Text type="secondary" className={s.secondaryText}>
+ {plugin.description}
+ </Text>
+ )}
+ {plugin.lastError && (
+ <Alert
+ type="error"
+ showIcon
+ icon={<WarningFilled />}
+ message={t(Localization.Admin.Plugins.pluginFailedToLoad)}
+ description={plugin.lastError}
+ className={s.errorAlert}
+ />
+ )}
+ </Space>
+ </div>
+ ),
+ },
+ {
+ title: t(Localization.Admin.Plugins.permissionsColumn),
+ key: 'permissions',
+ render: (_: unknown, plugin: Plugin) => {
+ if (!plugin.permissions || plugin.permissions.length === 0) {
+ return <Text type="secondary">{t(Localization.Admin.Plugins.none)}</Text>;
+ }
+ return (
+ <Space size={[4, 4]} wrap>
+ {plugin.permissions.map(p => {
+ const nameKey = permissionNameKey[p];
+ const descKey = permissionDescriptionKey[p];
+ const label = nameKey ? t(nameKey) : p;
+ const description = descKey ? t(descKey) : p;
+ return (
+ <Tooltip key={p} title={description}>
+ <Tag>{label}</Tag>
+ </Tooltip>
+ );
+ })}
+ </Space>
+ );
+ },
+ },
+ {
+ title: t(Localization.Admin.Plugins.statusColumn),
+ key: 'status',
+ render: (_: unknown, plugin: Plugin) => {
+ if ((plugin.pendingPermissions?.length ?? 0) > 0) {
+ return (
+ <Tooltip title={t(Localization.Admin.Plugins.statusPendingApprovalTooltip)}>
+ <Tag color="orange">{t(Localization.Admin.Plugins.statusPendingApproval)}</Tag>
+ </Tooltip>
+ );
+ }
+ if (plugin.lastError) {
+ return <Tag color="red">{t(Localization.Admin.Plugins.statusError)}</Tag>;
+ }
+ if (plugin.autoDisabled) {
+ return (
+ <Tooltip title={t(Localization.Admin.Plugins.statusAutoDisabledTooltip)}>
+ <Tag color="red">{t(Localization.Admin.Plugins.statusAutoDisabled)}</Tag>
+ </Tooltip>
+ );
+ }
+ if (plugin.loaded) {
+ return <Tag color="green">{t(Localization.Admin.Plugins.statusRunning)}</Tag>;
+ }
+ if (plugin.enabled) {
+ return <Tag color="orange">{t(Localization.Admin.Plugins.statusEnabledNotLoaded)}</Tag>;
+ }
+ return <Tag>{t(Localization.Admin.Plugins.statusDisabled)}</Tag>;
+ },
+ },
+ {
+ title: t(Localization.Admin.Plugins.enabledColumn),
+ key: 'enabled',
+ render: (_: unknown, plugin: Plugin) => {
+ if ((plugin.pendingPermissions?.length ?? 0) > 0) {
+ return (
+ <Tooltip title={t(Localization.Admin.Plugins.approveTooltip)}>
+ <Button
+ type="primary"
+ loading={togglingNames.has(plugin.slug)}
+ onClick={() => onToggleEnabled(plugin, true)}
+ >
+ {t(Localization.Admin.Plugins.approveButton)}
+ </Button>
+ </Tooltip>
+ );
+ }
+ return (
+ <Switch
+ checked={plugin.enabled}
+ loading={togglingNames.has(plugin.slug)}
+ onChange={checked => onToggleEnabled(plugin, checked)}
+ aria-label={t(Localization.Admin.Plugins.toggleAria, { name: plugin.name })}
+ />
+ );
+ },
+ },
+ {
+ title: '',
+ key: 'actions',
+ render: (_: unknown, plugin: Plugin) => (
+ <Space>
+ <Tooltip title={t(Localization.Admin.Plugins.reloadTooltip)}>
+ <Button
+ icon={<ReloadOutlined />}
+ loading={reloadingNames.has(plugin.slug)}
+ onClick={() => onReload(plugin)}
+ disabled={!plugin.enabled}
+ />
+ </Tooltip>
+ {/*
+ Every plugin has a details page now (permissions tab, plus an
+ instructions tab and any admin-page tabs the manifest declares),
+ so the details button is always shown.
+ */}
+ <Tooltip title={t(Localization.Admin.Plugins.openPluginAdmin)}>
+ <Button icon={<AppstoreOutlined />} onClick={() => onSelect(plugin)}>
+ {t(Localization.Admin.Plugins.configure)}
+ </Button>
+ </Tooltip>
+ <Popconfirm
+ title={
+ <div className={s.uninstallPrompt}>
+ <div className={s.uninstallPromptTitle}>
+ {t(Localization.Admin.Plugins.uninstallConfirmTitle)}
+ </div>
+ <div className={s.uninstallPromptDescription}>
+ {t(Localization.Admin.Plugins.uninstallConfirmDescription, {
+ name: plugin.name,
+ })}
+ </div>
+ </div>
+ }
+ okText={t(Localization.Admin.Plugins.uninstallConfirmOk)}
+ cancelText={t(Localization.Admin.Plugins.uninstallConfirmCancel)}
+ okButtonProps={{ danger: true }}
+ onConfirm={() => onUninstall(plugin)}
+ >
+ <Tooltip title={t(Localization.Admin.Plugins.uninstallTooltip)}>
+ <Button
+ danger
+ icon={<DeleteOutlined />}
+ loading={uninstallingNames.has(plugin.slug)}
+ aria-label={t(Localization.Admin.Plugins.uninstallAria, { name: plugin.name })}
+ />
+ </Tooltip>
+ </Popconfirm>
+ </Space>
+ ),
+ },
+ ];
+
+ return (
+ <Table
+ rowKey={p => p.slug}
+ columns={columns}
+ dataSource={plugins}
+ loading={loading}
+ pagination={false}
+ />
+ );
+};
diff --git a/web/components/admin/plugins/permissionDescriptions.ts b/web/components/admin/plugins/permissionDescriptions.ts
new file mode 100644
index 0000000000..467ff45e61
--- /dev/null
+++ b/web/components/admin/plugins/permissionDescriptions.ts
@@ -0,0 +1,55 @@
+import { PluginPermission } from '../../../interfaces/plugin';
+import { Localization } from '../../../types/localization';
+
+// permissionDescriptionKey maps a plugin permission identifier to the
+// i18n key for its plain-language description. Used in the plugins
+// list (as tooltips on each permission tag) and in the per-plugin
+// detail view (as the description column in the Permissions tab).
+// Keep in lock-step with Localization.Admin.Plugins.Permissions and
+// the host-side constants in services/plugins/hostfns.go.
+export const permissionDescriptionKey: Record<string, string> = {
+ [PluginPermission.StorageKV]: Localization.Admin.Plugins.Permissions.storageKv,
+ [PluginPermission.StorageUpload]: Localization.Admin.Plugins.Permissions.storageUpload,
+ [PluginPermission.ChatSend]: Localization.Admin.Plugins.Permissions.chatSend,
+ [PluginPermission.ChatHistory]: Localization.Admin.Plugins.Permissions.chatHistory,
+ [PluginPermission.ChatModerate]: Localization.Admin.Plugins.Permissions.chatModerate,
+ [PluginPermission.NetworkFetch]: Localization.Admin.Plugins.Permissions.networkFetch,
+ [PluginPermission.EventsEmit]: Localization.Admin.Plugins.Permissions.eventsEmit,
+ [PluginPermission.HttpServe]: Localization.Admin.Plugins.Permissions.httpServe,
+ [PluginPermission.HttpSse]: Localization.Admin.Plugins.Permissions.httpSse,
+ [PluginPermission.ServerRead]: Localization.Admin.Plugins.Permissions.serverRead,
+ [PluginPermission.NotificationsSend]: Localization.Admin.Plugins.Permissions.notificationsSend,
+ [PluginPermission.UsersRead]: Localization.Admin.Plugins.Permissions.usersRead,
+ [PluginPermission.UsersModerate]: Localization.Admin.Plugins.Permissions.usersModerate,
+ [PluginPermission.FediversePost]: Localization.Admin.Plugins.Permissions.fediversePost,
+ [PluginPermission.VideoConfigRead]: Localization.Admin.Plugins.Permissions.videoconfigRead,
+ [PluginPermission.VideoConfigWrite]: Localization.Admin.Plugins.Permissions.videoconfigWrite,
+ [PluginPermission.UIModify]: Localization.Admin.Plugins.Permissions.uiModify,
+ [PluginPermission.ChatFilter]: Localization.Admin.Plugins.Permissions.chatFilter,
+};
+
+// permissionNameKey maps a permission identifier to the i18n key for
+// its short plain-language label (e.g. "Send chat messages"). Used on
+// the permission Tags in the plugins list, alongside the full
+// description in a hover tooltip.
+export const permissionNameKey: Record<string, string> = {
+ [PluginPermission.StorageKV]: Localization.Admin.Plugins.PermissionNames.storageKv,
+ [PluginPermission.StorageUpload]: Localization.Admin.Plugins.PermissionNames.storageUpload,
+ [PluginPermission.ChatSend]: Localization.Admin.Plugins.PermissionNames.chatSend,
+ [PluginPermission.ChatHistory]: Localization.Admin.Plugins.PermissionNames.chatHistory,
+ [PluginPermission.ChatModerate]: Localization.Admin.Plugins.PermissionNames.chatModerate,
+ [PluginPermission.NetworkFetch]: Localization.Admin.Plugins.PermissionNames.networkFetch,
+ [PluginPermission.EventsEmit]: Localization.Admin.Plugins.PermissionNames.eventsEmit,
+ [PluginPermission.HttpServe]: Localization.Admin.Plugins.PermissionNames.httpServe,
+ [PluginPermission.HttpSse]: Localization.Admin.Plugins.PermissionNames.httpSse,
+ [PluginPermission.ServerRead]: Localization.Admin.Plugins.PermissionNames.serverRead,
+ [PluginPermission.NotificationsSend]:
+ Localization.Admin.Plugins.PermissionNames.notificationsSend,
+ [PluginPermission.UsersRead]: Localization.Admin.Plugins.PermissionNames.usersRead,
+ [PluginPermission.UsersModerate]: Localization.Admin.Plugins.PermissionNames.usersModerate,
+ [PluginPermission.FediversePost]: Localization.Admin.Plugins.PermissionNames.fediversePost,
+ [PluginPermission.VideoConfigRead]: Localization.Admin.Plugins.PermissionNames.videoconfigRead,
+ [PluginPermission.VideoConfigWrite]: Localization.Admin.Plugins.PermissionNames.videoconfigWrite,
+ [PluginPermission.UIModify]: Localization.Admin.Plugins.PermissionNames.uiModify,
+ [PluginPermission.ChatFilter]: Localization.Admin.Plugins.PermissionNames.chatFilter,
+};
diff --git a/web/components/layouts/Main/Main.tsx b/web/components/layouts/Main/Main.tsx
index 5e4d5cb363..7f1ae56ed1 100644
--- a/web/components/layouts/Main/Main.tsx
+++ b/web/components/layouts/Main/Main.tsx
@@ -99,6 +99,11 @@ export const Main: FC = () => {
<PushNotificationServiceWorker />
<TitleNotifier name={name} />
<Theme />
+ {/*
+ /customjavascript serves the admin's custom JS followed by
+ every loaded plugin's manifest.scripts content (concatenated
+ server-side). One <script> tag covers both.
+ */}
<Script strategy="afterInteractive" src="/customjavascript" />
<Layout ref={layoutRef} className={styles.layout}>
<Header
diff --git a/web/components/theme/Theme.tsx b/web/components/theme/Theme.tsx
index 70ab0013aa..0ef79927e2 100644
--- a/web/components/theme/Theme.tsx
+++ b/web/components/theme/Theme.tsx
@@ -36,6 +36,11 @@ export const Theme: FC = () => {
`,
}}
/>
+ {/*
+ customStyles is the admin's CSS followed by every loaded
+ plugin's manifest.styles content (concatenated server-side).
+ One inline <style> block carries both.
+ */}
<style
dangerouslySetInnerHTML={{
__html: `
diff --git a/web/components/ui/Content/Content.tsx b/web/components/ui/Content/Content.tsx
index fed0573d16..c90e61a2f0 100644
--- a/web/components/ui/Content/Content.tsx
+++ b/web/components/ui/Content/Content.tsx
@@ -126,6 +126,7 @@ export const Content: FC = () => {
chatRequireAuthentication,
federation,
notifications,
+ pluginTabs,
} = clientConfig;
const [showNotifyReminder, setShowNotifyReminder] = useState(false);
const [showNotifyModal, setShowNotifyModal] = useState(false);
@@ -146,7 +147,11 @@ export const Content: FC = () => {
const { openExternally, url } = action;
if (url) {
- const updatedUrl = new URL(url);
+ // Plugin-contributed actions can use root-relative URLs (e.g.
+ // "/plugins/<name>/") that the host validates and rewrites. Pass
+ // window.location.origin as the base so URL() accepts both
+ // absolute external URLs and same-origin plugin paths.
+ const updatedUrl = new URL(url, window.location.origin);
updatedUrl.searchParams.append('instance', currentBrowserWindowUrl);
if (currentUser) {
@@ -312,6 +317,7 @@ export const Content: FC = () => {
tags={tags}
socialHandles={socialHandles}
extraPageContent={extraPageContent}
+ pluginTabs={pluginTabs}
setShowFollowModal={setShowFollowModal}
supportFediverseFeatures={supportFediverseFeatures}
online={online}
@@ -324,6 +330,7 @@ export const Content: FC = () => {
tags={tags}
socialHandles={socialHandles}
extraPageContent={extraPageContent}
+ pluginTabs={pluginTabs}
setShowFollowModal={setShowFollowModal}
supportFediverseFeatures={supportFediverseFeatures}
/>
diff --git a/web/components/ui/Content/DesktopContent.tsx b/web/components/ui/Content/DesktopContent.tsx
index e27af33c8a..3434c40203 100644
--- a/web/components/ui/Content/DesktopContent.tsx
+++ b/web/components/ui/Content/DesktopContent.tsx
@@ -3,6 +3,7 @@ import dynamic from 'next/dynamic';
import { TabsProps } from 'antd';
import { ErrorBoundary } from 'react-error-boundary';
import { SocialLink } from '../../../interfaces/social-link.model';
+import { PluginTab } from '../../../interfaces/client-config.model';
import styles from './Content.module.scss';
import { CustomPageContent } from '../CustomPageContent/CustomPageContent';
import { ContentHeader } from '../../common/ContentHeader/ContentHeader';
@@ -14,6 +15,7 @@ export type DesktopContentProps = {
tags: string[];
socialHandles: SocialLink[];
extraPageContent: string;
+ pluginTabs: PluginTab[];
setShowFollowModal: (show: boolean) => void;
supportFediverseFeatures: boolean;
};
@@ -40,6 +42,7 @@ export const DesktopContent: FC<DesktopContentProps> = ({
tags,
socialHandles,
extraPageContent,
+ pluginTabs,
setShowFollowModal,
supportFediverseFeatures,
}) => {
@@ -58,6 +61,22 @@ export const DesktopContent: FC<DesktopContentProps> = ({
if (supportFediverseFeatures) {
items.push({ label: 'Followers', key: '3', children: followersTabContent });
}
+ // Plugin-contributed tabs render after the built-ins. Key is the
+ // slug+title combination; the host's validator rejects duplicate
+ // titles within a plugin, so this pair is unique across all
+ // plugin tabs and stable across renders (no index-as-key
+ // anti-pattern).
+ (pluginTabs || []).forEach(tab => {
+ items.push({
+ label: tab.title,
+ key: `plugin-${tab.slug}-${tab.title}`,
+ children: (
+ <div className={styles.bottomPageContentContainer}>
+ <CustomPageContent content={tab.html} />
+ </div>
+ ),
+ });
+ });
return (
<ErrorBoundary
diff --git a/web/components/ui/Content/MobileContent.tsx b/web/components/ui/Content/MobileContent.tsx
index 02a3759faa..755ba071af 100644
--- a/web/components/ui/Content/MobileContent.tsx
+++ b/web/components/ui/Content/MobileContent.tsx
@@ -4,6 +4,7 @@ import { TabsProps } from 'antd';
import { ErrorBoundary } from 'react-error-boundary';
import classNames from 'classnames';
import { SocialLink } from '../../../interfaces/social-link.model';
+import { PluginTab } from '../../../interfaces/client-config.model';
import styles from './Content.module.scss';
import { CustomPageContent } from '../CustomPageContent/CustomPageContent';
import { ContentHeader } from '../../common/ContentHeader/ContentHeader';
@@ -15,6 +16,7 @@ export type MobileContentProps = {
tags: string[];
socialHandles: SocialLink[];
extraPageContent: string;
+ pluginTabs: PluginTab[];
setShowFollowModal: (show: boolean) => void;
supportFediverseFeatures: boolean;
online: boolean;
@@ -50,6 +52,7 @@ export const MobileContent: FC<MobileContentProps> = ({
tags,
socialHandles,
extraPageContent,
+ pluginTabs,
setShowFollowModal,
supportFediverseFeatures,
online,
@@ -76,6 +79,22 @@ export const MobileContent: FC<MobileContentProps> = ({
if (supportFediverseFeatures) {
items.push({ label: 'Followers', key: '1', children: followersTabContent });
}
+ // Plugin-contributed tabs render after the built-ins. Key is the
+ // slug+title combination; the host's validator rejects duplicate
+ // titles within a plugin, so this pair is unique across all
+ // plugin tabs and stable across renders (no index-as-key
+ // anti-pattern).
+ (pluginTabs || []).forEach(tab => {
+ items.push({
+ label: tab.title,
+ key: `plugin-${tab.slug}-${tab.title}`,
+ children: (
+ <div className={styles.bottomPageContentContainer}>
+ <CustomPageContent content={tab.html} />
+ </div>
+ ),
+ });
+ });
return (
<ErrorBoundary
diff --git a/web/i18n/en/translation.json b/web/i18n/en/translation.json
index 189fa582a2..d8e040611f 100644
--- a/web/i18n/en/translation.json
+++ b/web/i18n/en/translation.json
@@ -142,7 +142,114 @@
"emojiPageDescription": "Here you can upload new custom emojis for usage in the chat. When uploading a new emoji, the filename without extension will be used as emoji name. Additionally, emoji names are case-insensitive. For best results, ensure all emoji have unique names.",
"emojiUploadBulkGuide": "Want to upload custom emojis in bulk? Check out our <a href=\"https://owncast.online/docs/chat/emoji\" rel=\"noopener noreferrer\" target=\"_blank\">Emoji guide</a>.",
"emojis": "Emojis",
- "uploadNewEmoji": "Upload new emoji"
+ "uploadNewEmoji": "Upload new emoji",
+ "Plugins": {
+ "overview": "All plugins",
+ "configure": "Configure",
+ "permissionsTab": "Permissions",
+ "instructionsTab": "Instructions",
+ "instructionsLoadError": "Could not load this plugin's instructions.",
+ "permissionColumnHeader": "Permission",
+ "descriptionColumnHeader": "Description",
+ "allowedHostsLabel": "Allowed hosts:",
+ "noPermissionsTitle": "No permissions",
+ "noPermissionsDescription": "This plugin does not declare any permissions in its manifest.",
+ "notFoundTitle": "Plugin not found",
+ "notFoundDescription": "No plugin named \"{{name}}\" is currently registered.",
+ "errorTitle": "Plugin admin error",
+ "Permissions": {
+ "storageKv": "Read and write a per-plugin key-value store that persists across reloads.",
+ "storageUpload": "Upload files to Owncast’s public files area for browser-accessible URLs.",
+ "chatSend": "Post chat messages as the plugin’s own bot identity.",
+ "chatHistory": "Read recent chat messages.",
+ "chatModerate": "Hide chat messages and ban users.",
+ "networkFetch": "Make outbound HTTP requests to other services.",
+ "eventsEmit": "Publish custom events that other plugins can subscribe to.",
+ "httpServe": "Serve HTTP requests at /plugins/<name>/ (static assets and a dynamic handler).",
+ "httpSse": "Push Server-Sent-Events to subscribed browser clients.",
+ "serverRead": "Read Owncast configuration and current server state.",
+ "notificationsSend": "Send broadcaster notifications via the configured channels.",
+ "usersRead": "Read the chat user list and per-user details.",
+ "usersModerate": "Disable or re-enable chat users.",
+ "fediversePost": "Post a public note to the fediverse from the configured Owncast account.",
+ "videoconfigRead": "Read stream and video output configuration (encoders, variants).",
+ "videoconfigWrite": "Modify stream and video output configuration.",
+ "uiModify": "Make changes to the Owncast user interface.",
+ "chatFilter": "Inspect and modify chat messages before they are broadcast, or drop them entirely."
+ },
+ "PermissionNames": {
+ "storageKv": "Store data",
+ "storageUpload": "Upload files",
+ "chatSend": "Send chat messages",
+ "chatHistory": "Read chat history",
+ "chatModerate": "Moderate chat",
+ "networkFetch": "Make outbound HTTP requests",
+ "eventsEmit": "Emit events",
+ "httpServe": "Serve HTTP",
+ "httpSse": "Push realtime updates",
+ "serverRead": "Read server state",
+ "notificationsSend": "Send notifications",
+ "usersRead": "Read user list",
+ "usersModerate": "Moderate users",
+ "fediversePost": "Post to the fediverse",
+ "videoconfigRead": "Read video settings",
+ "videoconfigWrite": "Change video settings",
+ "uiModify": "Add UI elements",
+ "chatFilter": "Filter chat messages"
+ },
+ "sidebarTitle": "Plugins",
+ "pageTitle": "Plugins",
+ "pageDescription": "Plugins extend Owncast with new functionality. You can install plugins from this catalog, upload your own, or build your own.",
+ "refresh": "Refresh",
+ "pluginColumn": "Plugin",
+ "permissionsColumn": "Permissions",
+ "statusColumn": "Status",
+ "enabledColumn": "Enabled",
+ "none": "none",
+ "pluginFailedToLoad": "Plugin failed to load",
+ "statusError": "error",
+ "statusRunning": "running",
+ "statusEnabledNotLoaded": "enabled, not loaded",
+ "statusDisabled": "disabled",
+ "reloadTooltip": "Reload this plugin",
+ "openPluginAdmin": "Open plugin admin",
+ "toggleAria": "Toggle {{name}}",
+ "pluginErrorTitle": "Plugin error",
+ "statusAutoDisabled": "auto-disabled",
+ "statusAutoDisabledTooltip": "The host stopped invoking this plugin after repeated failures. Reload it to retry.",
+ "statusPendingApproval": "needs re-approval",
+ "statusPendingApprovalTooltip": "This plugin's manifest now requests more permissions than were originally approved. Review the new permissions in the plugin details, then click Approve to accept the new set and load the plugin.",
+ "approveButton": "Approve",
+ "approveTooltip": "Approve the expanded permission set and load the plugin.",
+ "uploadButton": "Upload plugin",
+ "uploadSuccess": "Installed {{name}}",
+ "tabInstalled": "Installed",
+ "tabBrowse": "Browse",
+ "browseEmpty": "No plugins are available in the registry yet.",
+ "browseInstall": "Install",
+ "browseInstalled": "Installed",
+ "browseUpdate": "Update to v{{version}}",
+ "browseUnavailableTitle": "The plugin catalog is currently unavailable",
+ "browseUnavailableDescription": "Owncast can't reach the plugin catalog right now. You can still upload .ocpkg files directly from the Installed tab.",
+ "browseUnavailableRetry": "Retry",
+ "updateAvailable": "Update available: v{{version}}",
+ "updateConfirmTitle": "Update {{name}} to v{{version}}?",
+ "updateConfirmOk": "Update",
+ "updateConfirmCancel": "Cancel",
+ "installConfirmTitle": "Enable {{name}}?",
+ "installConfirmPrompt": "This plugin uses these capabilities:",
+ "installConfirmNoPermissions": "This plugin doesn't request any permissions.",
+ "installConfirmEnable": "Enable plugin",
+ "installConfirmCancel": "Maybe later",
+ "installEnabledSuccess": "Enabled {{name}}",
+ "uninstallTooltip": "Uninstall this plugin",
+ "uninstallAria": "Uninstall {{name}}",
+ "uninstallConfirmTitle": "Uninstall plugin?",
+ "uninstallConfirmDescription": "This removes \"{{name}}\" from the server.",
+ "uninstallConfirmOk": "Uninstall",
+ "uninstallConfirmCancel": "Cancel",
+ "uninstallSuccess": "Uninstalled {{name}}"
+ }
},
"Common": {
"poweredByOwncastVersion": "Powered by <a href='https://owncast.online'>Owncast v{{versionNumber}}</a>"
@@ -230,4 +337,4 @@
"noPluralKey": "This key has no plural variants - {{count}} things",
"simpleKey": "Simple translation text"
}
-}
+}
\ No newline at end of file
diff --git a/web/interfaces/client-config.model.ts b/web/interfaces/client-config.model.ts
index 897f7f74c8..8733fa1192 100644
--- a/web/interfaces/client-config.model.ts
+++ b/web/interfaces/client-config.model.ts
@@ -11,7 +11,15 @@ export interface ClientConfig {
chatDisabled: boolean;
chatRequireAuthentication: boolean;
externalActions: any[];
+ // customStyles is the admin's CSS plus the concatenated content of
+ // every loaded plugin's manifest.styles entries (the host
+ // pre-merges them server-side). Theme.tsx renders this as one
+ // inline <style> block.
customStyles: string;
+ // pluginTabs is the list of viewer-page tabs contributed by
+ // loaded plugins via manifest.tabs. DesktopContent / MobileContent
+ // render one tab per entry alongside the built-in tabs.
+ pluginTabs: PluginTab[];
appearanceVariables: Map<string, string>;
maxSocketPayloadSize: number;
federation: Federation;
@@ -45,6 +53,14 @@ interface SocialHandle {
icon: string;
}
+// PluginTab is one viewer-page tab contributed by a plugin via
+// manifest.tabs. Mirrors models.PluginTab on the backend.
+export interface PluginTab {
+ slug: string;
+ title: string;
+ html: string;
+}
+
export function makeEmptyClientConfig(): ClientConfig {
return {
name: '',
@@ -59,6 +75,7 @@ export function makeEmptyClientConfig(): ClientConfig {
chatRequireAuthentication: false,
externalActions: [],
customStyles: '',
+ pluginTabs: [],
appearanceVariables: new Map(),
maxSocketPayloadSize: 0,
federation: {
diff --git a/web/interfaces/plugin.ts b/web/interfaces/plugin.ts
new file mode 100644
index 0000000000..a131d43268
--- /dev/null
+++ b/web/interfaces/plugin.ts
@@ -0,0 +1,91 @@
+// PluginPermission enumerates the permission identifiers the host
+// accepts in plugin.manifest.json. Mirrors the constants in the host's
+// services/plugins/hostfns.go; keep in lock-step.
+//
+// Use this enum anywhere the frontend needs to reason about a specific
+// permission (e.g. branching on `network.fetch` to surface allowed
+// hosts). Avoid bare string literals so refactors and rename checks
+// are mechanical, and the typechecker catches typos.
+export const PluginPermission = {
+ StorageKV: 'storage.kv',
+ StorageUpload: 'storage.upload',
+ ChatSend: 'chat.send',
+ ChatHistory: 'chat.history',
+ ChatModerate: 'chat.moderate',
+ ChatFilter: 'chat.filter',
+ UsersRead: 'users.read',
+ UsersModerate: 'users.moderate',
+ NetworkFetch: 'network.fetch',
+ EventsEmit: 'events.emit',
+ HttpServe: 'http.serve',
+ HttpSse: 'http.sse',
+ ServerRead: 'server.read',
+ VideoConfigRead: 'videoconfig.read',
+ VideoConfigWrite: 'videoconfig.write',
+ NotificationsSend: 'notifications.send',
+ FediversePost: 'fediverse.post',
+ UIModify: 'ui.modify',
+} as const;
+
+// The const above and this type intentionally share a name: TypeScript
+// merges value-space and type-space declarations, so `PluginPermission`
+// works as both an enum-like namespace and a string-literal union. The
+// eslint no-redeclare rule doesn't model this; suppress it here.
+// eslint-disable-next-line no-redeclare
+export type PluginPermission = (typeof PluginPermission)[keyof typeof PluginPermission];
+
+// Plugin describes a discovered plugin as returned by GET /api/admin/plugins.
+// Mirrors services/plugins.DiscoveredEntry on the backend. Two name-like
+// fields: `slug` is the canonical identifier used in URLs and action
+// endpoints; `name` is the human-readable display name shown in lists.
+export interface Plugin {
+ slug: string;
+ name: string;
+ // botDisplayName, when present, is what the plugin uses as its chat
+ // identity. Empty/undefined means "use name". Shown in the admin's
+ // plugin list so the operator knows what viewers will see in chat.
+ botDisplayName?: string;
+ version?: string;
+ description?: string;
+ permissions?: string[];
+ path: string;
+ enabled: boolean;
+ loaded: boolean;
+ // autoDisabled is set when the host's strike system stopped invoking
+ // the plugin after consecutive filter failures. The admin's enabled
+ // choice is preserved, but the plugin isn't doing any work until it's
+ // reloaded or rebuilt.
+ autoDisabled?: boolean;
+ // hasIcon is true when the plugin ships an icon.png alongside its
+ // manifest. The admin UI fetches the bytes from
+ // /api/plugins/<slug>/icon and renders them in the list and sidebar.
+ hasIcon?: boolean;
+ // hasInstructions is true when the plugin ships an INSTRUCTIONS.md
+ // alongside its manifest. The admin UI fetches the markdown from
+ // /api/admin/plugins/<slug>/instructions and renders it in an
+ // Instructions tab on the plugin's details page.
+ hasInstructions?: boolean;
+ // pendingPermissions lists permissions the manifest now declares that
+ // the admin has not yet approved. Non-empty means the plugin was
+ // updated on disk to ask for more access than was originally granted;
+ // the plugin is held in a not-loaded state until the admin re-enables
+ // it (which captures a fresh approval snapshot covering the new set).
+ pendingPermissions?: string[];
+ // allowedHosts mirrors manifest.network.allowedHosts. Populated when
+ // the plugin requests network.fetch; the admin UI surfaces this list
+ // alongside the network.fetch permission entry so an admin reviewing
+ // the plugin sees the host scope the plugin is allowed to reach.
+ allowedHosts?: string[];
+ lastError?: string;
+ discoveredAt: string;
+ adminPages?: PluginAdminPage[];
+}
+
+// PluginAdminPage is a single admin-only page declared in a plugin's
+// manifest.admin.pages entry. The body is rendered as an iframe to
+// /plugins/<slug><path>.
+export interface PluginAdminPage {
+ title: string;
+ path: string;
+ icon?: string;
+}
diff --git a/web/next.config.js b/web/next.config.js
index c2a8962156..9100cf4a0c 100644
--- a/web/next.config.js
+++ b/web/next.config.js
@@ -22,6 +22,21 @@ async function rewrites() {
source: '/api/:path*',
destination: 'http://localhost:8080/api/:path*', // Proxy to Backend to work around CORS.
},
+ // Plugin admin iframes proxied so they're same-origin to the admin UI
+ // in dev. Two patterns: the first matches slash-terminated URLs and
+ // preserves the trailing slash through the rewrite; the second handles
+ // everything else. Without the slash-preserving variant the backend
+ // 301-redirects /plugins/<name>/admin to /plugins/<name>/admin/ to
+ // canonicalize the directory, the proxy strips the slash again, and
+ // the iframe runs into an infinite redirect loop.
+ {
+ source: '/plugins/:path*/',
+ destination: 'http://localhost:8080/plugins/:path*/',
+ },
+ {
+ source: '/plugins/:path*',
+ destination: 'http://localhost:8080/plugins/:path*',
+ },
{
source: '/hls/:path*',
destination: 'http://localhost:8080/hls/:path*', // Proxy to Backend to work around CORS.
diff --git a/web/package-lock.json b/web/package-lock.json
index 453005c3a1..9493593c48 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -65,7 +65,7 @@
"yaml": "2.9.0"
},
"devDependencies": {
- "@babel/core": "7.29.7",
+ "@babel/core": "7.29.0",
"@babel/preset-react": "^7.25.7",
"@commitlint/cli": "^20.0.0",
"@commitlint/config-conventional": "^20.0.0",
@@ -87,8 +87,8 @@
"@types/sanitize-html": "^2.9.0",
"@types/ua-parser-js": "0.7.39",
"@types/video.js": "^7.3.50",
- "@typescript-eslint/eslint-plugin": "8.60.0",
- "@typescript-eslint/parser": "8.60.0",
+ "@typescript-eslint/eslint-plugin": "8.59.4",
+ "@typescript-eslint/parser": "8.59.4",
"babel-loader": "10.1.1",
"chromatic": "16.10.1",
"css-loader": "7.1.4",
@@ -239,12 +239,12 @@
"license": "ISC"
},
"node_modules/@babel/code-frame": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
- "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",
+ "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",
"license": "MIT",
"dependencies": {
- "@babel/helper-validator-identifier": "^7.29.7",
+ "@babel/helper-validator-identifier": "^7.28.5",
"js-tokens": "^4.0.0",
"picocolors": "^1.1.1"
},
@@ -253,29 +253,29 @@
}
},
"node_modules/@babel/compat-data": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
- "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz",
+ "integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/core": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
- "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
- "license": "MIT",
- "dependencies": {
- "@babel/code-frame": "^7.29.7",
- "@babel/generator": "^7.29.7",
- "@babel/helper-compilation-targets": "^7.29.7",
- "@babel/helper-module-transforms": "^7.29.7",
- "@babel/helpers": "^7.29.7",
- "@babel/parser": "^7.29.7",
- "@babel/template": "^7.29.7",
- "@babel/traverse": "^7.29.7",
- "@babel/types": "^7.29.7",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
+ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.29.0",
+ "@babel/generator": "^7.29.0",
+ "@babel/helper-compilation-targets": "^7.28.6",
+ "@babel/helper-module-transforms": "^7.28.6",
+ "@babel/helpers": "^7.28.6",
+ "@babel/parser": "^7.29.0",
+ "@babel/template": "^7.28.6",
+ "@babel/traverse": "^7.29.0",
+ "@babel/types": "^7.29.0",
"@jridgewell/remapping": "^2.3.5",
"convert-source-map": "^2.0.0",
"debug": "^4.1.0",
@@ -301,13 +301,13 @@
}
},
"node_modules/@babel/generator": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz",
- "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==",
+ "version": "7.29.1",
+ "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz",
+ "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==",
"license": "MIT",
"dependencies": {
- "@babel/parser": "^7.29.7",
- "@babel/types": "^7.29.7",
+ "@babel/parser": "^7.29.0",
+ "@babel/types": "^7.29.0",
"@jridgewell/gen-mapping": "^0.3.12",
"@jridgewell/trace-mapping": "^0.3.28",
"jsesc": "^3.0.2"
@@ -317,25 +317,25 @@
}
},
"node_modules/@babel/helper-annotate-as-pure": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz",
- "integrity": "sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw==",
+ "version": "7.27.3",
+ "resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.27.3.tgz",
+ "integrity": "sha512-fXSwMQqitTGeHLBC08Eq5yXz2m37E4pJX1qAU1+2cNedz/ifv/bVXft90VeSav5nFO61EcNgwr0aJxbyPaWBPg==",
"license": "MIT",
"dependencies": {
- "@babel/types": "^7.29.7"
+ "@babel/types": "^7.27.3"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-compilation-targets": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
- "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
+ "version": "7.28.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",
+ "integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",
"license": "MIT",
"dependencies": {
- "@babel/compat-data": "^7.29.7",
- "@babel/helper-validator-option": "^7.29.7",
+ "@babel/compat-data": "^7.28.6",
+ "@babel/helper-validator-option": "^7.27.1",
"browserslist": "^4.24.0",
"lru-cache": "^5.1.1",
"semver": "^6.3.1"
@@ -455,9 +455,9 @@
}
},
"node_modules/@babel/helper-globals": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz",
- "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==",
+ "version": "7.28.0",
+ "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz",
+ "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -477,27 +477,27 @@
}
},
"node_modules/@babel/helper-module-imports": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz",
- "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==",
+ "version": "7.28.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz",
+ "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==",
"license": "MIT",
"dependencies": {
- "@babel/traverse": "^7.29.7",
- "@babel/types": "^7.29.7"
+ "@babel/traverse": "^7.28.6",
+ "@babel/types": "^7.28.6"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-module-transforms": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz",
- "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==",
+ "version": "7.28.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz",
+ "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==",
"license": "MIT",
"dependencies": {
- "@babel/helper-module-imports": "^7.29.7",
- "@babel/helper-validator-identifier": "^7.29.7",
- "@babel/traverse": "^7.29.7"
+ "@babel/helper-module-imports": "^7.28.6",
+ "@babel/helper-validator-identifier": "^7.28.5",
+ "@babel/traverse": "^7.28.6"
},
"engines": {
"node": ">=6.9.0"
@@ -519,9 +519,9 @@
}
},
"node_modules/@babel/helper-plugin-utils": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz",
- "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==",
+ "version": "7.28.6",
+ "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz",
+ "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -575,27 +575,27 @@
}
},
"node_modules/@babel/helper-string-parser": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
- "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
+ "version": "7.27.1",
+ "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz",
+ "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
- "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "version": "7.28.5",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz",
+ "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-option": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
- "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
+ "version": "7.27.1",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",
+ "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -616,25 +616,25 @@
}
},
"node_modules/@babel/helpers": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
- "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
+ "version": "7.29.2",
+ "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz",
+ "integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==",
"license": "MIT",
"dependencies": {
- "@babel/template": "^7.29.7",
- "@babel/types": "^7.29.7"
+ "@babel/template": "^7.28.6",
+ "@babel/types": "^7.29.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz",
- "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==",
+ "version": "7.29.3",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.3.tgz",
+ "integrity": "sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==",
"license": "MIT",
"dependencies": {
- "@babel/types": "^7.29.7"
+ "@babel/types": "^7.29.0"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -880,13 +880,13 @@
}
},
"node_modules/@babel/plugin-syntax-jsx": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz",
- "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==",
+ "version": "7.28.6",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.28.6.tgz",
+ "integrity": "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-plugin-utils": "^7.29.7"
+ "@babel/helper-plugin-utils": "^7.28.6"
},
"engines": {
"node": ">=6.9.0"
@@ -1699,13 +1699,13 @@
}
},
"node_modules/@babel/plugin-transform-react-display-name": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.29.7.tgz",
- "integrity": "sha512-+1wdDMGNb4UPeY3Q4L5yLiYe6TXPXubs4NjrgRFw13hPRLJfEMw2Q5OXkee6/IfdqePIeW4Jjwe3aBh7SdKz4Q==",
+ "version": "7.28.0",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.28.0.tgz",
+ "integrity": "sha512-D6Eujc2zMxKjfa4Zxl4GHMsmhKKZ9VpcqIchJLvwTxad9zWIYulwYItBovpDOoNLISpcZSXoDJ5gaGbQUDqViA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-plugin-utils": "^7.29.7"
+ "@babel/helper-plugin-utils": "^7.27.1"
},
"engines": {
"node": ">=6.9.0"
@@ -1715,17 +1715,17 @@
}
},
"node_modules/@babel/plugin-transform-react-jsx": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.29.7.tgz",
- "integrity": "sha512-WsZulLVBUHXVj2cUcPVx6UE21TpalB6bHbSFErKT0Ib++ax24jjXe73FqlWvdylFOjiuPHYi6VCcgRad1ItN+A==",
+ "version": "7.28.6",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.28.6.tgz",
+ "integrity": "sha512-61bxqhiRfAACulXSLd/GxqmAedUSrRZIu/cbaT18T1CetkTmtDN15it7i80ru4DVqRK1WMxQhXs+Lf9kajm5Ow==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-annotate-as-pure": "^7.29.7",
- "@babel/helper-module-imports": "^7.29.7",
- "@babel/helper-plugin-utils": "^7.29.7",
- "@babel/plugin-syntax-jsx": "^7.29.7",
- "@babel/types": "^7.29.7"
+ "@babel/helper-annotate-as-pure": "^7.27.3",
+ "@babel/helper-module-imports": "^7.28.6",
+ "@babel/helper-plugin-utils": "^7.28.6",
+ "@babel/plugin-syntax-jsx": "^7.28.6",
+ "@babel/types": "^7.28.6"
},
"engines": {
"node": ">=6.9.0"
@@ -1735,13 +1735,13 @@
}
},
"node_modules/@babel/plugin-transform-react-jsx-development": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.29.7.tgz",
- "integrity": "sha512-Xfy3UVMF04+ypnFbkhvfqtmvwfe92qwQdbGZVonhE+6v35GzlofmOnA1szaZqzb9xYWr0nl1e5EMmzi0DNON1g==",
+ "version": "7.27.1",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-development/-/plugin-transform-react-jsx-development-7.27.1.tgz",
+ "integrity": "sha512-ykDdF5yI4f1WrAolLqeF3hmYU12j9ntLQl/AOG1HAS21jxyg1Q0/J/tpREuYLfatGdGmXp/3yS0ZA76kOlVq9Q==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/plugin-transform-react-jsx": "^7.29.7"
+ "@babel/plugin-transform-react-jsx": "^7.27.1"
},
"engines": {
"node": ">=6.9.0"
@@ -1751,14 +1751,14 @@
}
},
"node_modules/@babel/plugin-transform-react-pure-annotations": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.29.7.tgz",
- "integrity": "sha512-H5E+HBgDpr6Q5t+Aj11tL7XkIui1jhbIoArVQnqjgXo5/3YxkN7ZEBcWF4RQlB0T4rrxJQbXS6kiFV6B7XTqUA==",
+ "version": "7.27.1",
+ "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-pure-annotations/-/plugin-transform-react-pure-annotations-7.27.1.tgz",
+ "integrity": "sha512-JfuinvDOsD9FVMTHpzA/pBLisxpv1aSf+OIV8lgH3MuWrks19R27e6a6DipIg4aX1Zm9Wpb04p8wljfKrVSnPA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-annotate-as-pure": "^7.29.7",
- "@babel/helper-plugin-utils": "^7.29.7"
+ "@babel/helper-annotate-as-pure": "^7.27.1",
+ "@babel/helper-plugin-utils": "^7.27.1"
},
"engines": {
"node": ">=6.9.0"
@@ -2142,18 +2142,18 @@
}
},
"node_modules/@babel/preset-react": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.29.7.tgz",
- "integrity": "sha512-C+PV1TFUPTmBQGoPBL8j2QmLpZ117YTCwxIZeJOM96GbYMFSc7/pOXU5lVykwnZxyTqQxRsvoRk6f2FktZgGHA==",
+ "version": "7.28.5",
+ "resolved": "https://registry.npmjs.org/@babel/preset-react/-/preset-react-7.28.5.tgz",
+ "integrity": "sha512-Z3J8vhRq7CeLjdC58jLv4lnZ5RKFUJWqH5emvxmv9Hv3BD1T9R/Im713R4MTKwvFaV74ejZ3sM01LyEKk4ugNQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@babel/helper-plugin-utils": "^7.29.7",
- "@babel/helper-validator-option": "^7.29.7",
- "@babel/plugin-transform-react-display-name": "^7.29.7",
- "@babel/plugin-transform-react-jsx": "^7.29.7",
- "@babel/plugin-transform-react-jsx-development": "^7.29.7",
- "@babel/plugin-transform-react-pure-annotations": "^7.29.7"
+ "@babel/helper-plugin-utils": "^7.27.1",
+ "@babel/helper-validator-option": "^7.27.1",
+ "@babel/plugin-transform-react-display-name": "^7.28.0",
+ "@babel/plugin-transform-react-jsx": "^7.27.1",
+ "@babel/plugin-transform-react-jsx-development": "^7.27.1",
+ "@babel/plugin-transform-react-pure-annotations": "^7.27.1"
},
"engines": {
"node": ">=6.9.0"
@@ -2367,31 +2367,31 @@
}
},
"node_modules/@babel/template": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz",
- "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==",
+ "version": "7.28.6",
+ "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
+ "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.29.7",
- "@babel/parser": "^7.29.7",
- "@babel/types": "^7.29.7"
+ "@babel/code-frame": "^7.28.6",
+ "@babel/parser": "^7.28.6",
+ "@babel/types": "^7.28.6"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/traverse": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz",
- "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz",
+ "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==",
"license": "MIT",
"dependencies": {
- "@babel/code-frame": "^7.29.7",
- "@babel/generator": "^7.29.7",
- "@babel/helper-globals": "^7.29.7",
- "@babel/parser": "^7.29.7",
- "@babel/template": "^7.29.7",
- "@babel/types": "^7.29.7",
+ "@babel/code-frame": "^7.29.0",
+ "@babel/generator": "^7.29.0",
+ "@babel/helper-globals": "^7.28.0",
+ "@babel/parser": "^7.29.0",
+ "@babel/template": "^7.28.6",
+ "@babel/types": "^7.29.0",
"debug": "^4.3.1"
},
"engines": {
@@ -2399,13 +2399,13 @@
}
},
"node_modules/@babel/types": {
- "version": "7.29.7",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz",
- "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==",
+ "version": "7.29.0",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz",
+ "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==",
"license": "MIT",
"dependencies": {
- "@babel/helper-string-parser": "^7.29.7",
- "@babel/helper-validator-identifier": "^7.29.7"
+ "@babel/helper-string-parser": "^7.27.1",
+ "@babel/helper-validator-identifier": "^7.28.5"
},
"engines": {
"node": ">=6.9.0"
@@ -6679,6 +6679,7 @@
"version": "2.5.6",
"resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.6.tgz",
"integrity": "sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==",
+ "dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
@@ -6718,6 +6719,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6738,6 +6740,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6758,6 +6761,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6778,6 +6782,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6798,6 +6803,7 @@
"cpu": [
"arm"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6818,6 +6824,7 @@
"cpu": [
"arm"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6838,6 +6845,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6858,6 +6866,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6878,6 +6887,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6898,6 +6908,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6918,6 +6929,7 @@
"cpu": [
"arm64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6938,6 +6950,7 @@
"cpu": [
"ia32"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6958,6 +6971,7 @@
"cpu": [
"x64"
],
+ "dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6975,6 +6989,7 @@
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
+ "dev": true,
"license": "MIT",
"optional": true,
"engines": {
@@ -9155,17 +9170,17 @@
}
},
"node_modules/@typescript-eslint/eslint-plugin": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.60.0.tgz",
- "integrity": "sha512-QYb/sa74/s7OKMbACMjrYnGspj9Hs5YI5aaffSL65UfeBUzVzBJfVo3oWSpbzPurvm7yaCCo2Lk7lVj610HqKw==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.59.4.tgz",
+ "integrity": "sha512-PegsU+XfyJJNjd4+u/k6f9yTyp0lEXXiPopUNobZcIAUJFGICFLN+sP0Rb3JehVmiij1Ph0dFGYqODoRo/2+6A==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/regexpp": "^4.12.2",
- "@typescript-eslint/scope-manager": "8.60.0",
- "@typescript-eslint/type-utils": "8.60.0",
- "@typescript-eslint/utils": "8.60.0",
- "@typescript-eslint/visitor-keys": "8.60.0",
+ "@typescript-eslint/scope-manager": "8.59.4",
+ "@typescript-eslint/type-utils": "8.59.4",
+ "@typescript-eslint/utils": "8.59.4",
+ "@typescript-eslint/visitor-keys": "8.59.4",
"ignore": "^7.0.5",
"natural-compare": "^1.4.0",
"ts-api-utils": "^2.5.0"
@@ -9178,22 +9193,22 @@
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
- "@typescript-eslint/parser": "^8.60.0",
+ "@typescript-eslint/parser": "^8.59.4",
"eslint": "^8.57.0 || ^9.0.0 || ^10.0.0",
"typescript": ">=4.8.4 <6.1.0"
}
},
"node_modules/@typescript-eslint/parser": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.60.0.tgz",
- "integrity": "sha512-fcqpj/MyK4sxDPcbe7STNPbpQL4RLZOPWuaTmwZYuc+hJKzRf58yRxfhqGpc6PIq9ZyfSBpfHgmUHmHs0KwHwg==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.59.4.tgz",
+ "integrity": "sha512-zORHqO/tuhxY1zWuTvMUqddRxpiFJ72xVfcNoWpqdLjs6lfPbuQBJuW4pk+49/uBMy7Ssr4bzgjiKmmDB1UbZQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/scope-manager": "8.60.0",
- "@typescript-eslint/types": "8.60.0",
- "@typescript-eslint/typescript-estree": "8.60.0",
- "@typescript-eslint/visitor-keys": "8.60.0",
+ "@typescript-eslint/scope-manager": "8.59.4",
+ "@typescript-eslint/types": "8.59.4",
+ "@typescript-eslint/typescript-estree": "8.59.4",
+ "@typescript-eslint/visitor-keys": "8.59.4",
"debug": "^4.4.3"
},
"engines": {
@@ -9209,14 +9224,14 @@
}
},
"node_modules/@typescript-eslint/project-service": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.60.0.tgz",
- "integrity": "sha512-aZu74NNKJeUWqCjDddzdiKaS82dgYgV/vmf+Ui3ZdZejmgfXR/q+pRumgobnQ2cCJTgGTWp4ypiwsuofFubavg==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.59.4.tgz",
+ "integrity": "sha512-Ly00Vu4oAacfDeHp2Zg85ioNG6l8HG+tN1D7J+xTHSxu9y0awYKJ2zH1rFBn8ZSfuGK+7FxK3Cgl3uAz0aZZLg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/tsconfig-utils": "^8.60.0",
- "@typescript-eslint/types": "^8.60.0",
+ "@typescript-eslint/tsconfig-utils": "^8.59.4",
+ "@typescript-eslint/types": "^8.59.4",
"debug": "^4.4.3"
},
"engines": {
@@ -9231,14 +9246,14 @@
}
},
"node_modules/@typescript-eslint/scope-manager": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.60.0.tgz",
- "integrity": "sha512-pFzqhllJMs+jghLQWzV00ds39xLzuyqPSev5pd8f4Ir0rtKR3ZLUB4/4dhjOFighWb9larvtfJvqL+4yKDI3Xw==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.59.4.tgz",
+ "integrity": "sha512-mUeR/3H1WrTAddJrwut8OoPjfauaztMQmRwV5fQTUyNVJCLiUXXe4lGEyYIL2oFDpP7UtgbGJXCt72wT0z2S3Q==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.60.0",
- "@typescript-eslint/visitor-keys": "8.60.0"
+ "@typescript-eslint/types": "8.59.4",
+ "@typescript-eslint/visitor-keys": "8.59.4"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -9249,9 +9264,9 @@
}
},
"node_modules/@typescript-eslint/tsconfig-utils": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.60.0.tgz",
- "integrity": "sha512-BZPR3RGYlAXnly6ymAxfkVn5rCbZzQNou0rxv3GfWZ8cTQp+hhVd73khbGLAd8k1TlAPLISH337M+tAgAnaJDQ==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.59.4.tgz",
+ "integrity": "sha512-DLCpnKgD4alVxTBSKulK+gU1KCqOgUXfDRDXh2mZgzokQKa/70ax93I2uVO3m/LLvIAtWZIFoiifudmIqAxpMA==",
"dev": true,
"license": "MIT",
"engines": {
@@ -9266,15 +9281,15 @@
}
},
"node_modules/@typescript-eslint/type-utils": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.60.0.tgz",
- "integrity": "sha512-SX46wEUtitCpq7AN38HkUU/+zvUpdKf7ephtWAFgckH8O7PQIyL5gvrhQgBLuEYgLfuKWOVvWVskMbuFHAz5xg==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.59.4.tgz",
+ "integrity": "sha512-uonTuPAAKr9XaBGqJ3LjYTh72zy5DyGesljO9gtmk/eFW0W1fRHjnwVYKB35Lm8d5Q5CluEW3gPHjTvZTmgrfA==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.60.0",
- "@typescript-eslint/typescript-estree": "8.60.0",
- "@typescript-eslint/utils": "8.60.0",
+ "@typescript-eslint/types": "8.59.4",
+ "@typescript-eslint/typescript-estree": "8.59.4",
+ "@typescript-eslint/utils": "8.59.4",
"debug": "^4.4.3",
"ts-api-utils": "^2.5.0"
},
@@ -9291,9 +9306,9 @@
}
},
"node_modules/@typescript-eslint/types": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.60.0.tgz",
- "integrity": "sha512-AsE7x2XaAK+CVbeih0Fvbn+r1qHxtpLDJ3XUuFcIinT318T90yHMJC+Zgv+jUuDjQQd06HKwxnDu6sz1IcTilA==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.59.4.tgz",
+ "integrity": "sha512-F1o7WJcCq+bc8dwcO/YsSEOudAH8RDtaOhM6wcAQhcUsFhnWQl81JKy48q1hoxAU0qrzM89+31GYh1515Zde3Q==",
"dev": true,
"license": "MIT",
"engines": {
@@ -9305,16 +9320,16 @@
}
},
"node_modules/@typescript-eslint/typescript-estree": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.60.0.tgz",
- "integrity": "sha512-3AcZNBGMClm6CXDyo8kYvVGT/sx29sS0oBsIb9oZI2gunA4Vm2M3YHzRLPvsUBBsl+yB5FPtltq7gGH0iTlp9g==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.59.4.tgz",
+ "integrity": "sha512-F+RuOmcDXo4+TPdfd/TCLS3m2nw8gE9XXyZLrA3JBfaA5tz9TtdkyD3YJFmPxulyc2cKbEok/CvFE3MgSLWnag==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/project-service": "8.60.0",
- "@typescript-eslint/tsconfig-utils": "8.60.0",
- "@typescript-eslint/types": "8.60.0",
- "@typescript-eslint/visitor-keys": "8.60.0",
+ "@typescript-eslint/project-service": "8.59.4",
+ "@typescript-eslint/tsconfig-utils": "8.59.4",
+ "@typescript-eslint/types": "8.59.4",
+ "@typescript-eslint/visitor-keys": "8.59.4",
"debug": "^4.4.3",
"minimatch": "^10.2.2",
"semver": "^7.7.3",
@@ -9333,16 +9348,16 @@
}
},
"node_modules/@typescript-eslint/utils": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.60.0.tgz",
- "integrity": "sha512-HtXuPfrHTyBDkameWpl+vJb1Uevu2tznAyahM1Oc4AENidCLTPiZDWIo4GfcxNdC/RcfGcadzzkqbRG87dUrQA==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.59.4.tgz",
+ "integrity": "sha512-cYXeNAUsG4lJo5dbc1FcKm+JwIWrj1/UpTORsC6tGMjEZ81DYcvIr9/ueikhMa/Y/gDQYGp+YX9/xQrXje5BJw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@eslint-community/eslint-utils": "^4.9.1",
- "@typescript-eslint/scope-manager": "8.60.0",
- "@typescript-eslint/types": "8.60.0",
- "@typescript-eslint/typescript-estree": "8.60.0"
+ "@typescript-eslint/scope-manager": "8.59.4",
+ "@typescript-eslint/types": "8.59.4",
+ "@typescript-eslint/typescript-estree": "8.59.4"
},
"engines": {
"node": "^18.18.0 || ^20.9.0 || >=21.1.0"
@@ -9357,13 +9372,13 @@
}
},
"node_modules/@typescript-eslint/visitor-keys": {
- "version": "8.60.0",
- "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.60.0.tgz",
- "integrity": "sha512-9WI52t8ZGLVGrPMBet25yAftqY/n95+zmoUUtJBBQTKDSKUu7OsPTroT2op7U9JatkoRccL0YkWDNMFfC4Sjxg==",
+ "version": "8.59.4",
+ "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.59.4.tgz",
+ "integrity": "sha512-U3gxVaDVnuZKhSspW/MzMxE1kq7zOdc072FcSNoqA1I9p8HyKbBFfEHoWckBAMgNMph4MamwS5iTVzFmrnt8TQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@typescript-eslint/types": "8.60.0",
+ "@typescript-eslint/types": "8.59.4",
"eslint-visitor-keys": "^5.0.0"
},
"engines": {
@@ -13176,9 +13191,9 @@
"license": "MIT"
},
"node_modules/cypress": {
- "version": "15.16.0",
- "resolved": "https://registry.npmjs.org/cypress/-/cypress-15.16.0.tgz",
- "integrity": "sha512-fy0M0c9xDLEp4v9y7LLKFeAQhIdDsobxDSKpD3JcZpqQefjy9TSzEyVV3HA0zu7hUi0bGHlSYlI7ASub8wgR9A==",
+ "version": "15.15.0",
+ "resolved": "https://registry.npmjs.org/cypress/-/cypress-15.15.0.tgz",
+ "integrity": "sha512-N8qBv3AUYn6xfIG73O5O58kTClUBSZ7a3C08IQFkSGTUdEauJ3BqwTFb/f9KPZgadftoZjllC0XSwD7xNNolbA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
@@ -13203,6 +13218,7 @@
"eventemitter2": "6.4.7",
"execa": "4.1.0",
"executable": "^4.1.1",
+ "extract-zip": "2.0.1",
"fs-extra": "^9.1.0",
"hasha": "5.2.2",
"is-installed-globally": "~0.4.0",
@@ -13221,7 +13237,7 @@
"tree-kill": "1.2.2",
"tslib": "1.14.1",
"untildify": "^4.0.0",
- "yauzl": "^3.3.1"
+ "yauzl": "^2.10.0"
},
"bin": {
"cypress": "bin/cypress"
@@ -13247,20 +13263,6 @@
"dev": true,
"license": "0BSD"
},
- "node_modules/cypress/node_modules/yauzl": {
- "version": "3.3.1",
- "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.3.1.tgz",
- "integrity": "sha512-RNPCUkiE/ZgO4w8i9U5yDQVHaFDdnzaFANElRvpJteCspvmv2VqrRb9lvS6odVD+jqI/zDsxAHJVsafpcheVQQ==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "buffer-crc32": "~0.2.3",
- "pend": "~1.2.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
"node_modules/cytoscape": {
"version": "3.33.1",
"resolved": "https://registry.npmjs.org/cytoscape/-/cytoscape-3.33.1.tgz",
@@ -16063,7 +16065,6 @@
"integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",
"dev": true,
"license": "BSD-2-Clause",
- "optional": true,
"dependencies": {
"debug": "^4.1.1",
"get-stream": "^5.1.0",
@@ -16245,7 +16246,6 @@
"integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
"dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"pend": "~1.2.0"
}
@@ -24511,6 +24511,7 @@
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
+ "dev": true,
"license": "MIT",
"optional": true
},
@@ -35476,7 +35477,6 @@
"integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
"dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"buffer-crc32": "~0.2.3",
"fd-slicer": "~1.1.0"
diff --git a/web/pages/admin/plugins.module.scss b/web/pages/admin/plugins.module.scss
new file mode 100644
index 0000000000..1998ccaa9b
--- /dev/null
+++ b/web/pages/admin/plugins.module.scss
@@ -0,0 +1,12 @@
+// Plugin list page layout: the title + Refresh button row sits at the
+// top with a full-width space-between, and the page-level error alert
+// has a small breathing room above the table.
+
+.titleRow {
+ justify-content: space-between;
+ width: 100%;
+}
+
+.errorAlert {
+ margin-bottom: 16px;
+}
diff --git a/web/pages/admin/plugins.tsx b/web/pages/admin/plugins.tsx
new file mode 100644
index 0000000000..e55839a9fc
--- /dev/null
+++ b/web/pages/admin/plugins.tsx
@@ -0,0 +1,357 @@
+import React, { ReactElement, useCallback, useEffect, useMemo, useState } from 'react';
+import { Alert, Button, message, Space, Tabs, Typography, Upload } from 'antd';
+import type { UploadProps } from 'antd';
+import dynamic from 'next/dynamic';
+import { useRouter } from 'next/router';
+import { useTranslation } from 'next-export-i18n';
+import { AdminLayout } from '../../components/layouts/AdminLayout';
+import {
+ fetchData,
+ PLUGIN_REGISTRY_INSTALL,
+ PLUGIN_REGISTRY_LIST,
+ PLUGIN_UPLOAD,
+ PLUGINS_LIST,
+ pluginActionUrl,
+} from '../../utils/apis';
+import { Plugin } from '../../interfaces/plugin';
+import { PluginsList } from '../../components/admin/plugins/PluginsList';
+import { BrowseRegistry, RegistryPlugin } from '../../components/admin/plugins/BrowseRegistry';
+import { InstallConfirmModal } from '../../components/admin/plugins/InstallConfirmModal';
+import { Localization } from '../../types/localization';
+import s from './plugins.module.scss';
+
+const { Title, Paragraph } = Typography;
+
+const ReloadOutlined = dynamic(() => import('@ant-design/icons/ReloadOutlined'), { ssr: false });
+const UploadOutlined = dynamic(() => import('@ant-design/icons/UploadOutlined'), { ssr: false });
+
+const Plugins = () => {
+ const { t } = useTranslation();
+ const router = useRouter();
+ const [plugins, setPlugins] = useState<Plugin[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ // Names of plugins whose enable/disable POST is in flight. Drives the per-row
+ // spinner on the Switch so the admin sees the action is happening (the
+ // enable/disable round-trip includes a wasm load and can take a moment).
+ const [togglingNames, setTogglingNames] = useState<Set<string>>(new Set());
+ // Same idea for the Reload button — independent from togglingNames because
+ // the two actions are independent (and visually distinct).
+ const [reloadingNames, setReloadingNames] = useState<Set<string>>(new Set());
+ // And for the Uninstall button.
+ const [uninstallingNames, setUninstallingNames] = useState<Set<string>>(new Set());
+ // Tracks which tab is active so the tab-bar extras (Upload +
+ // Refresh) only show when they're contextually relevant to the
+ // Installed view.
+ const [activeTab, setActiveTab] = useState('installed');
+ // The just-installed plugin awaiting an enable/cancel decision in
+ // the InstallConfirmModal. Null when no modal is open.
+ const [pendingEnable, setPendingEnable] = useState<Plugin | null>(null);
+ // Registry list, used both by the Browse tab and by the Installed
+ // tab's "update available" tags. Fetched at the page level so a
+ // single source of truth feeds both views.
+ const [registryPlugins, setRegistryPlugins] = useState<RegistryPlugin[]>([]);
+ const [registryLoading, setRegistryLoading] = useState(true);
+ // registryError is set when the registry fetch fails (network error, host
+ // returned 5xx, etc.) so the Browse tab can distinguish "the catalog is
+ // unreachable" from "the catalog is reachable but empty". `null` covers
+ // both the loading and the empty-but-reachable cases.
+ const [registryError, setRegistryError] = useState<string | null>(null);
+
+ const loadPlugins = useCallback(async () => {
+ try {
+ const result = await fetchData(PLUGINS_LIST);
+ setPlugins(Array.isArray(result) ? result : []);
+ setError(null);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ // Registry fetch is independent of the installed-list fetch: a
+ // misconfigured or unreachable registry shouldn't block the
+ // Installed tab. On failure we set registryError so the Browse tab
+ // renders a "catalog unavailable" message with a retry button,
+ // distinct from the legitimately-empty case.
+ const loadRegistry = useCallback(async () => {
+ setRegistryLoading(true);
+ try {
+ const result = await fetchData(PLUGIN_REGISTRY_LIST);
+ setRegistryPlugins(Array.isArray(result) ? result : []);
+ setRegistryError(null);
+ } catch (e) {
+ setRegistryPlugins([]);
+ setRegistryError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setRegistryLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ loadPlugins();
+ loadRegistry();
+ }, [loadPlugins, loadRegistry]);
+
+ // Map of installed plugin slug -> currently-installed version.
+ // Browse cards use this to decide whether to render "Install" /
+ // "Installed" / "Update". Keys on slug (the canonical identifier),
+ // not display name, so two plugins with the same display string
+ // don't collide.
+ const installedVersions = useMemo(
+ () =>
+ new Map<string, string>(
+ plugins.filter(p => Boolean(p.version)).map(p => [p.slug, p.version as string]),
+ ),
+ [plugins],
+ );
+
+ // Map of installed plugin slug -> newer version available in the
+ // registry. Empty when the installed and registry versions match
+ // (or the plugin isn't in the registry at all). PluginsList renders
+ // the entries as "update available" tags in the version line.
+ const availableUpdates = useMemo(
+ () =>
+ new Map<string, string>(
+ plugins.flatMap(p => {
+ const reg = registryPlugins.find(r => r.slug === p.slug);
+ const latest = reg?.latest?.version;
+ if (p.version && latest && latest !== p.version) {
+ return [[p.slug, latest] as [string, string]];
+ }
+ return [];
+ }),
+ ),
+ [plugins, registryPlugins],
+ );
+
+ const handleToggleEnabled = async (plugin: Plugin, enabled: boolean) => {
+ setTogglingNames(prev => {
+ const next = new Set(prev);
+ next.add(plugin.slug);
+ return next;
+ });
+ try {
+ await fetchData(pluginActionUrl(plugin.slug, enabled ? 'enable' : 'disable'), {
+ method: 'POST',
+ });
+ await loadPlugins();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setTogglingNames(prev => {
+ const next = new Set(prev);
+ next.delete(plugin.slug);
+ return next;
+ });
+ }
+ };
+
+ // AntD's Upload calls customRequest with one file at a time. The request
+ // is multipart with a single 'plugin' field, matching the server-side
+ // form field name. We avoid AntD's automatic file-list display because
+ // the result we care about is the refreshed plugin list, not the
+ // intermediate upload state.
+ const uploadProps: UploadProps = {
+ name: 'plugin',
+ accept: '.ocpkg',
+ showUploadList: false,
+ multiple: false,
+ customRequest: async ({ file, onSuccess, onError }) => {
+ const blob = file as Blob;
+ const form = new FormData();
+ form.append('plugin', blob, (file as File).name);
+ try {
+ const res = await fetch(PLUGIN_UPLOAD, { method: 'POST', body: form });
+ if (!res.ok) {
+ const body = await res.text();
+ let detail = body;
+ try {
+ detail = JSON.parse(body).error ?? body;
+ } catch {
+ /* not JSON, use raw body */
+ }
+ throw new Error(detail || `upload failed: ${res.status}`);
+ }
+ const entry = (await res.json()) as Plugin;
+ message.success(t(Localization.Admin.Plugins.uploadSuccess, { name: entry.name }));
+ await loadPlugins();
+ onSuccess?.(entry);
+ } catch (e) {
+ const msg = e instanceof Error ? e.message : String(e);
+ setError(msg);
+ onError?.(e as Error);
+ }
+ },
+ };
+
+ const handleUninstall = async (plugin: Plugin) => {
+ setUninstallingNames(prev => {
+ const next = new Set(prev);
+ next.add(plugin.slug);
+ return next;
+ });
+ try {
+ await fetchData(pluginActionUrl(plugin.slug, 'uninstall'), { method: 'POST' });
+ message.success(t(Localization.Admin.Plugins.uninstallSuccess, { name: plugin.name }));
+ await loadPlugins();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setUninstallingNames(prev => {
+ const next = new Set(prev);
+ next.delete(plugin.slug);
+ return next;
+ });
+ }
+ };
+
+ const handleReload = async (plugin: Plugin) => {
+ setReloadingNames(prev => {
+ const next = new Set(prev);
+ next.add(plugin.slug);
+ return next;
+ });
+ try {
+ await fetchData(pluginActionUrl(plugin.slug, 'reload'), { method: 'POST' });
+ await loadPlugins();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setReloadingNames(prev => {
+ const next = new Set(prev);
+ next.delete(plugin.slug);
+ return next;
+ });
+ }
+ };
+
+ // Called when the admin clicks "Enable plugin" in the post-install
+ // confirmation modal. Reuses the same enable endpoint the Switch
+ // hits, so the re-approval and load-failure paths are identical.
+ const handleEnableAfterInstall = async () => {
+ const plugin = pendingEnable;
+ setPendingEnable(null);
+ if (!plugin) return;
+ try {
+ await fetchData(pluginActionUrl(plugin.slug, 'enable'), { method: 'POST' });
+ message.success(t(Localization.Admin.Plugins.installEnabledSuccess, { name: plugin.name }));
+ await loadPlugins();
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ }
+ };
+
+ // Common path for "fetch the registry's bytes for (name, version)
+ // and run Manager.Install". Shared between the Browse tab's Update
+ // button and the Installed tab's "update available" tag so both
+ // surface the same post-install confirmation flow.
+ const installFromRegistry = useCallback(
+ async (slug: string, version: string) => {
+ const entry = (await fetchData(PLUGIN_REGISTRY_INSTALL, {
+ method: 'POST',
+ data: { slug, version },
+ })) as Plugin;
+ message.success(t(Localization.Admin.Plugins.uploadSuccess, { name: entry.name }));
+ await loadPlugins();
+ await loadRegistry();
+ // Only prompt to enable for plugins that aren't already
+ // running. Updates of enabled plugins keep their enabled state
+ // unless the new manifest expanded permissions (in which case
+ // the host marks them auto-disabled and the modal shows the
+ // new perms).
+ if (!entry.enabled) {
+ setPendingEnable(entry);
+ }
+ },
+ [loadPlugins, loadRegistry, t],
+ );
+
+ const installedTab = (
+ <PluginsList
+ plugins={plugins}
+ loading={loading}
+ togglingNames={togglingNames}
+ reloadingNames={reloadingNames}
+ uninstallingNames={uninstallingNames}
+ availableUpdates={availableUpdates}
+ onToggleEnabled={handleToggleEnabled}
+ onReload={handleReload}
+ onUninstall={handleUninstall}
+ onUpdate={(plugin, version) => installFromRegistry(plugin.slug, version)}
+ onSelect={p => router.push({ pathname: '/admin/plugins/configure', query: { id: p.slug } })}
+ />
+ );
+
+ const browseTab = (
+ <BrowseRegistry
+ installedVersions={installedVersions}
+ registry={registryPlugins}
+ registryLoading={registryLoading}
+ registryError={registryError}
+ onInstall={installFromRegistry}
+ onRetry={loadRegistry}
+ />
+ );
+
+ // Tab-bar actions for the Installed view: Upload + Refresh. Lives
+ // in the AntD Tabs `tabBarExtraContent` slot so the buttons sit
+ // inline with the tab labels on the right edge. We hide them on
+ // the Browse tab since neither action applies there.
+ const installedActions = (
+ <Space>
+ <Upload {...uploadProps}>
+ <Button icon={<UploadOutlined />}>{t(Localization.Admin.Plugins.uploadButton)}</Button>
+ </Upload>
+ <Button icon={<ReloadOutlined />} onClick={loadPlugins}>
+ {t(Localization.Admin.Plugins.refresh)}
+ </Button>
+ </Space>
+ );
+
+ return (
+ <div>
+ <Title>{t(Localization.Admin.Plugins.pageTitle)}</Title>
+ <Paragraph>{t(Localization.Admin.Plugins.pageDescription)}</Paragraph>
+
+ {error && (
+ <Alert
+ type="error"
+ showIcon
+ closable
+ message={t(Localization.Admin.Plugins.errorTitle)}
+ description={error}
+ onClose={() => setError(null)}
+ className={s.errorAlert}
+ />
+ )}
+
+ <Tabs
+ activeKey={activeTab}
+ onChange={setActiveTab}
+ tabBarExtraContent={activeTab === 'installed' ? installedActions : undefined}
+ items={[
+ {
+ key: 'installed',
+ label: t(Localization.Admin.Plugins.tabInstalled),
+ children: installedTab,
+ },
+ { key: 'browse', label: t(Localization.Admin.Plugins.tabBrowse), children: browseTab },
+ ]}
+ />
+
+ <InstallConfirmModal
+ plugin={pendingEnable}
+ onCancel={() => setPendingEnable(null)}
+ onEnable={handleEnableAfterInstall}
+ />
+ </div>
+ );
+};
+
+Plugins.getLayout = function getLayout(page: ReactElement) {
+ return <AdminLayout page={page} />;
+};
+
+export default Plugins;
diff --git a/web/pages/admin/plugins/configure.module.scss b/web/pages/admin/plugins/configure.module.scss
new file mode 100644
index 0000000000..4e1a1766d6
--- /dev/null
+++ b/web/pages/admin/plugins/configure.module.scss
@@ -0,0 +1,7 @@
+// Loading state for /admin/plugins/configure: a centered spinner while
+// the plugin list fetch is in flight.
+
+.loading {
+ padding: 32px;
+ text-align: center;
+}
diff --git a/web/pages/admin/plugins/configure.tsx b/web/pages/admin/plugins/configure.tsx
new file mode 100644
index 0000000000..dad552ddaf
--- /dev/null
+++ b/web/pages/admin/plugins/configure.tsx
@@ -0,0 +1,102 @@
+import React, { ReactElement, useCallback, useEffect, useState } from 'react';
+import { Alert, Spin } from 'antd';
+import { useRouter } from 'next/router';
+import { useTranslation } from 'next-export-i18n';
+import { AdminLayout } from '../../../components/layouts/AdminLayout';
+import { fetchData, PLUGINS_LIST } from '../../../utils/apis';
+import { Plugin } from '../../../interfaces/plugin';
+import { PluginDetail } from '../../../components/admin/plugins/PluginDetail';
+import { Localization } from '../../../types/localization';
+import s from './configure.module.scss';
+
+// Per-plugin admin view at /admin/plugins/configure/?id=<plugin-id>.
+// The `id` query parameter is the plugin's slug (canonical identifier).
+// The URL param is named `id` to keep author/operator-facing surfaces
+// free of the slug jargon; internal code and the manifest still call
+// it slug.
+//
+// Why a query-string route and not a dynamic /admin/plugins/[id]/ route:
+// the admin UI is statically exported (next.config.js sets output: 'export'
+// for non-dev), and plugin identifiers are discovered at runtime by the
+// Owncast server. A dynamic Next.js route would either fail the static
+// export or require build-time enumeration we can't provide. A static
+// page with a runtime query param sidesteps both: one HTML file is
+// generated, all plugin-selection logic runs client-side off router.query.
+//
+// The plugin list fetch itself primes the admin session cookie as a side
+// effect of the RequireAdminAuth middleware on the host, so by the time
+// we render the iframe the browser has a cookie that authenticates the
+// iframe's top-level GET (which can't carry a custom header).
+const PluginConfigurePage = () => {
+ const { t } = useTranslation();
+ const router = useRouter();
+ const idParam = router.query.id;
+ const slug = typeof idParam === 'string' ? idParam : undefined;
+
+ const [plugin, setPlugin] = useState<Plugin | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const [notFound, setNotFound] = useState(false);
+
+ const load = useCallback(async () => {
+ if (!slug) {
+ setLoading(false);
+ return;
+ }
+ setLoading(true);
+ try {
+ const result = await fetchData(PLUGINS_LIST);
+ const list: Plugin[] = Array.isArray(result) ? result : [];
+ const found = list.find(p => p.slug === slug) ?? null;
+ setPlugin(found);
+ setNotFound(found === null);
+ setError(null);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setLoading(false);
+ }
+ }, [slug]);
+
+ useEffect(() => {
+ if (router.isReady) load();
+ }, [router.isReady, load]);
+
+ if (!router.isReady || (loading && !plugin)) {
+ return (
+ <div className={s.loading}>
+ <Spin />
+ </div>
+ );
+ }
+
+ if (error) {
+ return (
+ <Alert
+ type="error"
+ showIcon
+ message={t(Localization.Admin.Plugins.errorTitle)}
+ description={error}
+ />
+ );
+ }
+
+ if (notFound || !plugin) {
+ return (
+ <Alert
+ type="warning"
+ showIcon
+ message={t(Localization.Admin.Plugins.notFoundTitle)}
+ description={t(Localization.Admin.Plugins.notFoundDescription, { name: slug ?? '' })}
+ />
+ );
+ }
+
+ return <PluginDetail plugin={plugin} />;
+};
+
+PluginConfigurePage.getLayout = function getLayout(page: ReactElement) {
+ return <AdminLayout page={page} />;
+};
+
+export default PluginConfigurePage;
diff --git a/web/public/mockServiceWorker.js b/web/public/mockServiceWorker.js
index a1e52b4778..a0eaf7aa57 100644
--- a/web/public/mockServiceWorker.js
+++ b/web/public/mockServiceWorker.js
@@ -7,42 +7,42 @@
* - Please do NOT modify this file.
*/
-const PACKAGE_VERSION = '2.14.2'
-const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
-const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
-const activeClientIds = new Set()
+const PACKAGE_VERSION = '2.14.6';
+const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82';
+const IS_MOCKED_RESPONSE = Symbol('isMockedResponse');
+const activeClientIds = new Set();
addEventListener('install', function () {
- self.skipWaiting()
-})
+ self.skipWaiting();
+});
addEventListener('activate', function (event) {
- event.waitUntil(self.clients.claim())
-})
+ event.waitUntil(self.clients.claim());
+});
addEventListener('message', async function (event) {
- const clientId = Reflect.get(event.source || {}, 'id')
+ const clientId = Reflect.get(event.source || {}, 'id');
if (!clientId || !self.clients) {
- return
+ return;
}
- const client = await self.clients.get(clientId)
+ const client = await self.clients.get(clientId);
if (!client) {
- return
+ return;
}
const allClients = await self.clients.matchAll({
type: 'window',
- })
+ });
switch (event.data) {
case 'KEEPALIVE_REQUEST': {
sendToClient(client, {
type: 'KEEPALIVE_RESPONSE',
- })
- break
+ });
+ break;
}
case 'INTEGRITY_CHECK_REQUEST': {
@@ -52,12 +52,12 @@ addEventListener('message', async function (event) {
packageVersion: PACKAGE_VERSION,
checksum: INTEGRITY_CHECKSUM,
},
- })
- break
+ });
+ break;
}
case 'MOCK_ACTIVATE': {
- activeClientIds.add(clientId)
+ activeClientIds.add(clientId);
sendToClient(client, {
type: 'MOCKING_ENABLED',
@@ -67,54 +67,51 @@ addEventListener('message', async function (event) {
frameType: client.frameType,
},
},
- })
- break
+ });
+ break;
}
case 'CLIENT_CLOSED': {
- activeClientIds.delete(clientId)
+ activeClientIds.delete(clientId);
- const remainingClients = allClients.filter((client) => {
- return client.id !== clientId
- })
+ const remainingClients = allClients.filter(client => {
+ return client.id !== clientId;
+ });
// Unregister itself when there are no more clients
if (remainingClients.length === 0) {
- self.registration.unregister()
+ self.registration.unregister();
}
- break
+ break;
}
}
-})
+});
addEventListener('fetch', function (event) {
- const requestInterceptedAt = Date.now()
+ const requestInterceptedAt = Date.now();
// Bypass navigation requests.
if (event.request.mode === 'navigate') {
- return
+ return;
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
- if (
- event.request.cache === 'only-if-cached' &&
- event.request.mode !== 'same-origin'
- ) {
- return
+ if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
+ return;
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
// after it's been terminated (still remains active until the next reload).
if (activeClientIds.size === 0) {
- return
+ return;
}
- const requestId = crypto.randomUUID()
- event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
-})
+ const requestId = crypto.randomUUID();
+ event.respondWith(handleRequest(event, requestId, requestInterceptedAt));
+});
/**
* @param {FetchEvent} event
@@ -122,23 +119,18 @@ addEventListener('fetch', function (event) {
* @param {number} requestInterceptedAt
*/
async function handleRequest(event, requestId, requestInterceptedAt) {
- const client = await resolveMainClient(event)
- const requestCloneForEvents = event.request.clone()
- const response = await getResponse(
- event,
- client,
- requestId,
- requestInterceptedAt,
- )
+ const client = await resolveMainClient(event);
+ const requestCloneForEvents = event.request.clone();
+ const response = await getResponse(event, client, requestId, requestInterceptedAt);
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
- const serializedRequest = await serializeRequest(requestCloneForEvents)
+ const serializedRequest = await serializeRequest(requestCloneForEvents);
// Clone the response so both the client and the library could consume it.
- const responseClone = response.clone()
+ const responseClone = response.clone();
sendToClient(
client,
@@ -160,10 +152,10 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
},
},
responseClone.body ? [serializedRequest.body, responseClone.body] : [],
- )
+ );
}
- return response
+ return response;
}
/**
@@ -175,30 +167,30 @@ async function handleRequest(event, requestId, requestInterceptedAt) {
* @returns {Promise<Client | undefined>}
*/
async function resolveMainClient(event) {
- const client = await self.clients.get(event.clientId)
+ const client = await self.clients.get(event.clientId);
if (activeClientIds.has(event.clientId)) {
- return client
+ return client;
}
if (client?.frameType === 'top-level') {
- return client
+ return client;
}
const allClients = await self.clients.matchAll({
type: 'window',
- })
+ });
return allClients
- .filter((client) => {
+ .filter(client => {
// Get only those clients that are currently visible.
- return client.visibilityState === 'visible'
+ return client.visibilityState === 'visible';
})
- .find((client) => {
+ .find(client => {
// Find the client ID that's recorded in the
// set of clients that have registered the worker.
- return activeClientIds.has(client.id)
- })
+ return activeClientIds.has(client.id);
+ });
}
/**
@@ -211,36 +203,34 @@ async function resolveMainClient(event) {
async function getResponse(event, client, requestId, requestInterceptedAt) {
// Clone the request because it might've been already used
// (i.e. its body has been read and sent to the client).
- const requestClone = event.request.clone()
+ const requestClone = event.request.clone();
function passthrough() {
// Cast the request headers to a new Headers instance
// so the headers can be manipulated with.
- const headers = new Headers(requestClone.headers)
+ const headers = new Headers(requestClone.headers);
// Remove the "accept" header value that marked this request as passthrough.
// This prevents request alteration and also keeps it compliant with the
// user-defined CORS policies.
- const acceptHeader = headers.get('accept')
+ const acceptHeader = headers.get('accept');
if (acceptHeader) {
- const values = acceptHeader.split(',').map((value) => value.trim())
- const filteredValues = values.filter(
- (value) => value !== 'msw/passthrough',
- )
+ const values = acceptHeader.split(',').map(value => value.trim());
+ const filteredValues = values.filter(value => value !== 'msw/passthrough');
if (filteredValues.length > 0) {
- headers.set('accept', filteredValues.join(', '))
+ headers.set('accept', filteredValues.join(', '));
} else {
- headers.delete('accept')
+ headers.delete('accept');
}
}
- return fetch(requestClone, { headers })
+ return fetch(requestClone, { headers });
}
// Bypass mocking when the client is not active.
if (!client) {
- return passthrough()
+ return passthrough();
}
// Bypass initial page load requests (i.e. static assets).
@@ -248,11 +238,11 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
// means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
// and is not ready to handle requests.
if (!activeClientIds.has(client.id)) {
- return passthrough()
+ return passthrough();
}
// Notify the client that a request has been intercepted.
- const serializedRequest = await serializeRequest(event.request)
+ const serializedRequest = await serializeRequest(event.request);
const clientMessage = await sendToClient(
client,
{
@@ -264,19 +254,19 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
},
},
[serializedRequest.body],
- )
+ );
switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
- return respondWithMock(clientMessage.data)
+ return respondWithMock(clientMessage.data);
}
case 'PASSTHROUGH': {
- return passthrough()
+ return passthrough();
}
}
- return passthrough()
+ return passthrough();
}
/**
@@ -287,21 +277,18 @@ async function getResponse(event, client, requestId, requestInterceptedAt) {
*/
function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
- const channel = new MessageChannel()
+ const channel = new MessageChannel();
- channel.port1.onmessage = (event) => {
+ channel.port1.onmessage = event => {
if (event.data && event.data.error) {
- return reject(event.data.error)
+ return reject(event.data.error);
}
- resolve(event.data)
- }
+ resolve(event.data);
+ };
- client.postMessage(message, [
- channel.port2,
- ...transferrables.filter(Boolean),
- ])
- })
+ client.postMessage(message, [channel.port2, ...transferrables.filter(Boolean)]);
+ });
}
/**
@@ -314,17 +301,17 @@ function respondWithMock(response) {
// instance will have status code set to 0. Since it's not possible to create
// a Response instance with status code 0, handle that use-case separately.
if (response.status === 0) {
- return Response.error()
+ return Response.error();
}
- const mockedResponse = new Response(response.body, response)
+ const mockedResponse = new Response(response.body, response);
Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
value: true,
enumerable: true,
- })
+ });
- return mockedResponse
+ return mockedResponse;
}
/**
@@ -345,5 +332,5 @@ async function serializeRequest(request) {
referrerPolicy: request.referrerPolicy,
body: await request.arrayBuffer(),
keepalive: request.keepalive,
- }
+ };
}
diff --git a/web/public/styles/admin/plugin-iframe.css b/web/public/styles/admin/plugin-iframe.css
new file mode 100644
index 0000000000..c3a3ed1f06
--- /dev/null
+++ b/web/public/styles/admin/plugin-iframe.css
@@ -0,0 +1,310 @@
+/*
+ * plugin-iframe.css — auto-injected by the Owncast plugin host into HTML
+ * served on a plugin's manifest-declared admin paths. Gives plain HTML
+ * elements (no AntD class names) an Owncast-themed look so a plugin's
+ * admin iframe sits visually inside the surrounding admin without the
+ * plugin author having to manage styling themselves.
+ *
+ * Scope is deliberately narrow: theme tokens, base typography, links,
+ * forms, buttons, tables. Not trying to be a UI kit — just "this looks
+ * like it belongs". Plugins remain free to add their own styles on top.
+ *
+ * Token values are mirrored from web/styles/variables.css. Keep in sync
+ * if those tokens change.
+ */
+
+:root {
+ --color-owncast-palette-0: #12161d; /* Dark primary */
+ --color-owncast-palette-1: #2d3748; /* Dark secondary */
+ --color-owncast-palette-3: #e2e8f0; /* Light primary (admin bg) */
+ --color-owncast-palette-4: #fff; /* Light secondary */
+ --color-owncast-palette-6: #6544e9; /* Action / link */
+ --color-owncast-palette-7: #7a5cf3; /* Action hover */
+ --color-owncast-palette-8: #b6b3c6; /* Disabled */
+ --color-owncast-palette-10: #5d5f72; /* Neutral gray */
+ --color-owncast-palette-14: #f0f3f8; /* Light background */
+ --color-owncast-palette-15: #eff1f4; /* Lighter background (cards) */
+ --color-owncast-palette-error: #ff4b39;
+ --color-owncast-palette-warning: #ffc655;
+ --theme-color-background-main: var(--color-owncast-palette-3);
+ --theme-color-content-bg: var(--color-owncast-palette-15);
+ --theme-color-text: var(--color-owncast-palette-0);
+ --theme-color-text-muted: var(--color-owncast-palette-10);
+ --theme-color-action: var(--color-owncast-palette-6);
+ --theme-color-action-hover: var(--color-owncast-palette-7);
+ --theme-color-action-disabled: var(--color-owncast-palette-8);
+ --theme-color-button-text: var(--color-owncast-palette-4);
+ --theme-color-form-bg: var(--color-owncast-palette-4);
+ --theme-color-form-border: var(--color-owncast-palette-8);
+ --theme-color-form-border-focus: var(--theme-color-action);
+ --theme-color-error: var(--color-owncast-palette-error);
+ --theme-rounded-corners: 9px;
+ --theme-font-body:
+ 'Inter', system-ui, -apple-system, blinkmacsystemfont, 'Segoe UI', roboto, 'Helvetica Neue',
+ arial, sans-serif;
+ --theme-font-display:
+ 'Poppins', system-ui, -apple-system, blinkmacsystemfont, 'Segoe UI', roboto, 'Helvetica Neue',
+ arial, sans-serif;
+}
+
+html,
+body {
+ margin: 0;
+ padding: 0;
+ background: var(--theme-color-background-main);
+ color: var(--theme-color-text);
+ font-family: var(--theme-font-body);
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+/* Headings — display font, matches the surrounding admin's heading style. */
+h1,
+h2,
+h3,
+h4,
+h5,
+h6 {
+ font-family: var(--theme-font-display);
+ color: var(--theme-color-text);
+ margin: 0 0 12px;
+ font-weight: 600;
+ line-height: 1.25;
+}
+
+h1 {
+ font-size: 24px;
+}
+
+h2 {
+ font-size: 20px;
+}
+
+h3 {
+ font-size: 17px;
+}
+
+h4 {
+ font-size: 15px;
+}
+
+p {
+ margin: 0 0 12px;
+}
+
+a {
+ color: var(--theme-color-action);
+ text-decoration: none;
+}
+
+a:hover {
+ color: var(--theme-color-action-hover);
+ text-decoration: underline;
+}
+
+hr {
+ border: 0;
+ border-top: 1px solid var(--color-owncast-palette-8);
+ margin: 16px 0;
+}
+
+code,
+pre,
+kbd,
+samp {
+ font-family: ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace;
+ font-size: 0.9em;
+ background: var(--color-owncast-palette-14);
+ border-radius: 4px;
+}
+
+code {
+ padding: 1px 4px;
+}
+
+pre {
+ padding: 8px 12px;
+ overflow-x: auto;
+ line-height: 1.4;
+}
+
+pre code {
+ padding: 0;
+ background: transparent;
+}
+
+/*
+ * Forms — give plain inputs the same boxed look AntD uses, without the
+ * .ant-input class machinery. label/input pairs work in any layout.
+ */
+form {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ max-width: 520px;
+}
+
+label {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ font-weight: 500;
+ color: var(--theme-color-text);
+}
+
+/*
+ * Inputs: only target form fields, not all type=* buttons.
+ * Excludes button-like inputs via :not().
+ */
+input:not(
+ [type='button'],
+ [type='submit'],
+ [type='reset'],
+ [type='checkbox'],
+ [type='radio'],
+ [type='range'],
+ [type='color']
+),
+textarea,
+select {
+ font-family: inherit;
+ font-size: 14px;
+ color: var(--theme-color-text);
+ background: var(--theme-color-form-bg);
+ border: 1px solid var(--theme-color-form-border);
+ border-radius: var(--theme-rounded-corners);
+ padding: 6px 10px;
+ outline: none;
+ transition:
+ border-color 120ms ease,
+ box-shadow 120ms ease;
+ width: 100%;
+ box-sizing: border-box;
+}
+
+input:not(
+ [type='button'],
+ [type='submit'],
+ [type='reset'],
+ [type='checkbox'],
+ [type='radio'],
+ [type='range'],
+ [type='color']
+ ):focus,
+textarea:focus,
+select:focus {
+ border-color: var(--theme-color-form-border-focus);
+ box-shadow: 0 0 0 2px rgb(101 68 233 / 15%);
+}
+
+input:disabled,
+textarea:disabled,
+select:disabled {
+ background: var(--color-owncast-palette-14);
+ color: var(--theme-color-text-muted);
+ cursor: not-allowed;
+}
+
+textarea {
+ min-height: 80px;
+ resize: vertical;
+}
+
+/*
+ * Buttons — primary look (button, input[type=submit]) and a secondary
+ * outline variant (button[type='button'] or a .secondary class authors
+ * can opt into). Mirrors AntD's primary/default split at a glance.
+ */
+button,
+input[type='submit'],
+input[type='button'],
+input[type='reset'] {
+ font-family: inherit;
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 1;
+ padding: 8px 16px;
+ border-radius: var(--theme-rounded-corners);
+ border: 1px solid var(--theme-color-action);
+ background: var(--theme-color-action);
+ color: var(--theme-color-button-text);
+ cursor: pointer;
+ transition:
+ background 120ms ease,
+ border-color 120ms ease;
+}
+
+button:hover,
+input[type='submit']:hover,
+input[type='button']:hover {
+ background: var(--theme-color-action-hover);
+ border-color: var(--theme-color-action-hover);
+}
+
+button:disabled,
+input[type='submit']:disabled,
+input[type='button']:disabled {
+ background: var(--theme-color-action-disabled);
+ border-color: var(--theme-color-action-disabled);
+ cursor: not-allowed;
+}
+
+/* Secondary/outline variant — authors add class="secondary" to opt in. */
+button.secondary,
+input[type='reset'] {
+ background: transparent;
+ color: var(--theme-color-action);
+}
+
+button.secondary:hover,
+input[type='reset']:hover {
+ background: rgb(101 68 233 / 8%);
+ color: var(--theme-color-action-hover);
+}
+
+/* Tables — minimal, readable. */
+table {
+ border-collapse: collapse;
+ width: 100%;
+ background: var(--theme-color-form-bg);
+ border-radius: var(--theme-rounded-corners);
+ overflow: hidden;
+}
+
+th,
+td {
+ text-align: left;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--color-owncast-palette-14);
+}
+
+th {
+ background: var(--color-owncast-palette-14);
+ font-weight: 600;
+ color: var(--theme-color-text);
+}
+
+tr:last-child td {
+ border-bottom: none;
+}
+
+/* Cards — semantic <section> or <article> gets a soft container look. */
+section,
+article,
+fieldset {
+ background: var(--theme-color-form-bg);
+ border: 1px solid var(--color-owncast-palette-14);
+ border-radius: var(--theme-rounded-corners);
+ padding: 16px;
+ margin: 0 0 16px;
+}
+
+fieldset legend {
+ font-weight: 600;
+ padding: 0 6px;
+}
+
+/* Tiny utility for muted/secondary text — opt-in via class. */
+.muted {
+ color: var(--theme-color-text-muted);
+}
diff --git a/web/stories/ReadwriteChat.stories.tsx b/web/stories/ReadwriteChat.stories.tsx
index 2552a10189..054a0bc077 100644
--- a/web/stories/ReadwriteChat.stories.tsx
+++ b/web/stories/ReadwriteChat.stories.tsx
@@ -41,6 +41,7 @@ const Page = () => {
socialHandles: [],
externalActions: [],
customStyles: '',
+ pluginTabs: [],
maxSocketPayloadSize: 0,
federation: undefined,
notifications: undefined,
diff --git a/web/types/localization.ts b/web/types/localization.ts
index 3ba45ca53a..d1e246c902 100644
--- a/web/types/localization.ts
+++ b/web/types/localization.ts
@@ -322,6 +322,120 @@ export const Localization = {
cannotEditAfterCreated: 'Admin.AccessTokens.cannotEditAfterCreated',
selectAll: 'Admin.AccessTokens.selectAll',
},
+
+ // Plugins admin (overview list, per-plugin detail, sidebar submenu)
+ Plugins: {
+ sidebarTitle: 'Admin.Plugins.sidebarTitle',
+ overview: 'Admin.Plugins.overview',
+ pageTitle: 'Admin.Plugins.pageTitle',
+ pageDescription: 'Admin.Plugins.pageDescription',
+ refresh: 'Admin.Plugins.refresh',
+ pluginColumn: 'Admin.Plugins.pluginColumn',
+ permissionsColumn: 'Admin.Plugins.permissionsColumn',
+ statusColumn: 'Admin.Plugins.statusColumn',
+ enabledColumn: 'Admin.Plugins.enabledColumn',
+ none: 'Admin.Plugins.none',
+ pluginFailedToLoad: 'Admin.Plugins.pluginFailedToLoad',
+ statusError: 'Admin.Plugins.statusError',
+ statusRunning: 'Admin.Plugins.statusRunning',
+ statusEnabledNotLoaded: 'Admin.Plugins.statusEnabledNotLoaded',
+ statusDisabled: 'Admin.Plugins.statusDisabled',
+ statusAutoDisabled: 'Admin.Plugins.statusAutoDisabled',
+ statusAutoDisabledTooltip: 'Admin.Plugins.statusAutoDisabledTooltip',
+ statusPendingApproval: 'Admin.Plugins.statusPendingApproval',
+ statusPendingApprovalTooltip: 'Admin.Plugins.statusPendingApprovalTooltip',
+ approveButton: 'Admin.Plugins.approveButton',
+ approveTooltip: 'Admin.Plugins.approveTooltip',
+ uploadButton: 'Admin.Plugins.uploadButton',
+ uploadSuccess: 'Admin.Plugins.uploadSuccess',
+ tabInstalled: 'Admin.Plugins.tabInstalled',
+ tabBrowse: 'Admin.Plugins.tabBrowse',
+ browseEmpty: 'Admin.Plugins.browseEmpty',
+ browseInstall: 'Admin.Plugins.browseInstall',
+ browseInstalled: 'Admin.Plugins.browseInstalled',
+ browseUpdate: 'Admin.Plugins.browseUpdate',
+ browseUnavailableTitle: 'Admin.Plugins.browseUnavailableTitle',
+ browseUnavailableDescription: 'Admin.Plugins.browseUnavailableDescription',
+ browseUnavailableRetry: 'Admin.Plugins.browseUnavailableRetry',
+ updateAvailable: 'Admin.Plugins.updateAvailable',
+ updateConfirmTitle: 'Admin.Plugins.updateConfirmTitle',
+ updateConfirmOk: 'Admin.Plugins.updateConfirmOk',
+ updateConfirmCancel: 'Admin.Plugins.updateConfirmCancel',
+ installConfirmTitle: 'Admin.Plugins.installConfirmTitle',
+ installConfirmPrompt: 'Admin.Plugins.installConfirmPrompt',
+ installConfirmNoPermissions: 'Admin.Plugins.installConfirmNoPermissions',
+ installConfirmEnable: 'Admin.Plugins.installConfirmEnable',
+ installConfirmCancel: 'Admin.Plugins.installConfirmCancel',
+ installEnabledSuccess: 'Admin.Plugins.installEnabledSuccess',
+ uninstallTooltip: 'Admin.Plugins.uninstallTooltip',
+ uninstallAria: 'Admin.Plugins.uninstallAria',
+ uninstallConfirmTitle: 'Admin.Plugins.uninstallConfirmTitle',
+ uninstallConfirmDescription: 'Admin.Plugins.uninstallConfirmDescription',
+ uninstallConfirmOk: 'Admin.Plugins.uninstallConfirmOk',
+ uninstallConfirmCancel: 'Admin.Plugins.uninstallConfirmCancel',
+ uninstallSuccess: 'Admin.Plugins.uninstallSuccess',
+ reloadTooltip: 'Admin.Plugins.reloadTooltip',
+ openPluginAdmin: 'Admin.Plugins.openPluginAdmin',
+ toggleAria: 'Admin.Plugins.toggleAria',
+ pluginErrorTitle: 'Admin.Plugins.pluginErrorTitle',
+ configure: 'Admin.Plugins.configure',
+ permissionsTab: 'Admin.Plugins.permissionsTab',
+ instructionsTab: 'Admin.Plugins.instructionsTab',
+ instructionsLoadError: 'Admin.Plugins.instructionsLoadError',
+ permissionColumnHeader: 'Admin.Plugins.permissionColumnHeader',
+ descriptionColumnHeader: 'Admin.Plugins.descriptionColumnHeader',
+ allowedHostsLabel: 'Admin.Plugins.allowedHostsLabel',
+ noPermissionsTitle: 'Admin.Plugins.noPermissionsTitle',
+ noPermissionsDescription: 'Admin.Plugins.noPermissionsDescription',
+ notFoundTitle: 'Admin.Plugins.notFoundTitle',
+ notFoundDescription: 'Admin.Plugins.notFoundDescription',
+ errorTitle: 'Admin.Plugins.errorTitle',
+ // Permission identifiers mirror services/plugins/hostfns.go; keep
+ // the keys here in lock-step with those constants.
+ Permissions: {
+ storageKv: 'Admin.Plugins.Permissions.storageKv',
+ storageUpload: 'Admin.Plugins.Permissions.storageUpload',
+ chatSend: 'Admin.Plugins.Permissions.chatSend',
+ chatHistory: 'Admin.Plugins.Permissions.chatHistory',
+ chatModerate: 'Admin.Plugins.Permissions.chatModerate',
+ networkFetch: 'Admin.Plugins.Permissions.networkFetch',
+ eventsEmit: 'Admin.Plugins.Permissions.eventsEmit',
+ httpServe: 'Admin.Plugins.Permissions.httpServe',
+ httpSse: 'Admin.Plugins.Permissions.httpSse',
+ serverRead: 'Admin.Plugins.Permissions.serverRead',
+ notificationsSend: 'Admin.Plugins.Permissions.notificationsSend',
+ usersRead: 'Admin.Plugins.Permissions.usersRead',
+ usersModerate: 'Admin.Plugins.Permissions.usersModerate',
+ fediversePost: 'Admin.Plugins.Permissions.fediversePost',
+ videoconfigRead: 'Admin.Plugins.Permissions.videoconfigRead',
+ videoconfigWrite: 'Admin.Plugins.Permissions.videoconfigWrite',
+ uiModify: 'Admin.Plugins.Permissions.uiModify',
+ chatFilter: 'Admin.Plugins.Permissions.chatFilter',
+ },
+ // Short plain-language labels for each permission. Shown on
+ // permission Tags in the plugins list with the full description
+ // surfaced via tooltip on hover.
+ PermissionNames: {
+ storageKv: 'Admin.Plugins.PermissionNames.storageKv',
+ storageUpload: 'Admin.Plugins.PermissionNames.storageUpload',
+ chatSend: 'Admin.Plugins.PermissionNames.chatSend',
+ chatHistory: 'Admin.Plugins.PermissionNames.chatHistory',
+ chatModerate: 'Admin.Plugins.PermissionNames.chatModerate',
+ networkFetch: 'Admin.Plugins.PermissionNames.networkFetch',
+ eventsEmit: 'Admin.Plugins.PermissionNames.eventsEmit',
+ httpServe: 'Admin.Plugins.PermissionNames.httpServe',
+ httpSse: 'Admin.Plugins.PermissionNames.httpSse',
+ serverRead: 'Admin.Plugins.PermissionNames.serverRead',
+ notificationsSend: 'Admin.Plugins.PermissionNames.notificationsSend',
+ usersRead: 'Admin.Plugins.PermissionNames.usersRead',
+ usersModerate: 'Admin.Plugins.PermissionNames.usersModerate',
+ fediversePost: 'Admin.Plugins.PermissionNames.fediversePost',
+ videoconfigRead: 'Admin.Plugins.PermissionNames.videoconfigRead',
+ videoconfigWrite: 'Admin.Plugins.PermissionNames.videoconfigWrite',
+ uiModify: 'Admin.Plugins.PermissionNames.uiModify',
+ chatFilter: 'Admin.Plugins.PermissionNames.chatFilter',
+ },
+ },
},
/**
diff --git a/web/utils/apis.ts b/web/utils/apis.ts
index 23542c60ce..e9145f5db7 100644
--- a/web/utils/apis.ts
+++ b/web/utils/apis.ts
@@ -60,6 +60,20 @@ export const CHAT_HISTORY = `${API_LOCATION}chat/messages`;
// Get chat history
export const UPDATE_CHAT_MESSGAE_VIZ = `/api/admin/chat/messagevisibility`;
+// Plugin management endpoints. Relative URLs go through Next.js's dev proxy
+// (next.config.js rewrites /api/* to the backend), avoiding cross-origin
+// fetches; in production the admin UI is same-origin so they resolve directly.
+export const PLUGINS_LIST = `/api/admin/plugins`;
+export const PLUGIN_UPLOAD = `/api/admin/plugins`;
+export const PLUGIN_REGISTRY_LIST = `/api/admin/plugin-registry/list`;
+export const PLUGIN_REGISTRY_INSTALL = `/api/admin/plugin-registry/install`;
+export const pluginActionUrl = (
+ slug: string,
+ action: 'enable' | 'disable' | 'reload' | 'uninstall',
+) => `/api/admin/plugins/${encodeURIComponent(slug)}/${action}`;
+export const pluginInstructionsUrl = (slug: string) =>
+ `/api/admin/plugins/${encodeURIComponent(slug)}/instructions`;
+
// Upload a new custom emoji
export const UPLOAD_EMOJI = `${API_LOCATION}emoji/upload`;
@@ -151,6 +165,33 @@ export async function fetchData(url: string, options?: FetchOptions) {
return json;
}
+// fetchText mirrors fetchData's admin auth handling but returns the raw
+// response body as text instead of parsing JSON. Used for endpoints that
+// serve plain text/markdown (e.g. a plugin's INSTRUCTIONS.md).
+export async function fetchText(url: string, options?: FetchOptions) {
+ const { method = 'GET', auth = true } = options || {};
+
+ // eslint-disable-next-line no-undef
+ const requestOptions: RequestInit = {
+ method,
+ };
+
+ if (auth && ADMIN_USERNAME && ADMIN_STREAMKEY) {
+ const encoded = btoa(`${ADMIN_USERNAME}:${ADMIN_STREAMKEY}`);
+ requestOptions.headers = {
+ Authorization: `Basic ${encoded}`,
+ };
+ requestOptions.mode = 'cors';
+ requestOptions.credentials = 'include';
+ }
+
+ const response = await fetch(url, requestOptions);
+ if (!response.ok) {
+ throw new Error(`An error has occurred: ${response.status}`);
+ }
+ return response.text();
+}
+
export async function getUnauthedData(url: string, options?: FetchOptions) {
const opts = {
method: 'GET',
diff --git a/webserver/handlers/config.go b/webserver/handlers/config.go
index d594199e46..79cbe87f4b 100644
--- a/webserver/handlers/config.go
+++ b/webserver/handlers/config.go
@@ -16,19 +16,29 @@ import (
)
type webConfigResponse struct {
- AppearanceVariables map[string]string `json:"appearanceVariables"`
- Name string `json:"name"`
- CustomStyles string `json:"customStyles"`
- StreamTitle string `json:"streamTitle,omitempty"` // What's going on with the current stream
- OfflineMessage string `json:"offlineMessage"`
- Logo string `json:"logo"`
- Version string `json:"version"`
- SocketHostOverride string `json:"socketHostOverride,omitempty"`
- ExtraPageContent string `json:"extraPageContent"`
- Summary string `json:"summary"`
- Tags []string `json:"tags"`
- SocialHandles []models.SocialHandle `json:"socialHandles"`
- ExternalActions []models.ExternalAction `json:"externalActions"`
+ AppearanceVariables map[string]string `json:"appearanceVariables"`
+ Name string `json:"name"`
+ // CustomStyles is the admin-configured CSS plus the concatenated
+ // content of every loaded plugin's manifest.styles entries (each
+ // preceded by a `/* plugin: <slug> ... */` delimiter for
+ // devtools attribution). The viewer renders this as one inline
+ // <style> block so plugins can theme the page without each plugin
+ // needing its own <link> tag.
+ CustomStyles string `json:"customStyles"`
+ StreamTitle string `json:"streamTitle,omitempty"` // What's going on with the current stream
+ OfflineMessage string `json:"offlineMessage"`
+ Logo string `json:"logo"`
+ Version string `json:"version"`
+ SocketHostOverride string `json:"socketHostOverride,omitempty"`
+ ExtraPageContent string `json:"extraPageContent"`
+ Summary string `json:"summary"`
+ Tags []string `json:"tags"`
+ SocialHandles []models.SocialHandle `json:"socialHandles"`
+ ExternalActions []models.ExternalAction `json:"externalActions"`
+ // PluginTabs is the list of viewer-page tabs contributed by
+ // loaded plugins via manifest.tabs. The viewer page renders one
+ // tab per entry alongside the built-in tabs (Followers, About).
+ PluginTabs []models.PluginTab `json:"pluginTabs"`
Notifications notificationsConfigResponse `json:"notifications"`
Federation federationConfigResponse `json:"federation"`
MaxSocketPayloadSize int `json:"maxSocketPayloadSize"`
@@ -75,6 +85,7 @@ func (h *Handlers) GetWebConfig(w http.ResponseWriter, r *http.Request) {
func (h *Handlers) getConfigResponse() webConfigResponse {
configRepository := h.configRepository
pageContent := utils.RenderPageContentMarkdown(configRepository.GetExtraPageBodyContent())
+ pageContent = prependPluginPageContent(pageContent, h.pluginPageContent)
offlineMessage := utils.RenderSimpleMarkdown(configRepository.GetCustomOfflineMessage())
socialHandles := configRepository.GetSocialHandles()
for i, handle := range socialHandles {
@@ -135,8 +146,9 @@ func (h *Handlers) getConfigResponse() webConfigResponse {
ChatDisabled: configRepository.GetChatDisabled(),
ChatSpamProtectionDisabled: configRepository.GetChatSpamProtectionEnabled(),
ChatRequireAuthentication: configRepository.GetChatRequireAuthentication(),
- ExternalActions: configRepository.GetExternalActions(),
- CustomStyles: configRepository.GetCustomStyles(),
+ ExternalActions: mergePluginActions(configRepository.GetExternalActions(), h.pluginActions),
+ PluginTabs: pluginTabsOrEmpty(h.pluginTabs),
+ CustomStyles: mergePluginCSS(configRepository.GetCustomStyles(), h.pluginCSSContent),
MaxSocketPayloadSize: config.MaxSocketPayloadSize,
Federation: federationResponse,
Notifications: notificationsResponse,
@@ -146,6 +158,90 @@ func (h *Handlers) getConfigResponse() webConfigResponse {
}
}
+// pluginTabsOrEmpty returns the host's plugin-tab list, or an empty
+// (non-nil) slice when the getter is unset (no plugin host) or
+// returns nothing. The empty-slice contract keeps the JSON wire
+// shape stable: `pluginTabs: []` rather than `null`, so the viewer
+// doesn't need a defensive nil-check before iterating.
+func pluginTabsOrEmpty(getter func() []models.PluginTab) []models.PluginTab {
+ if getter == nil {
+ return []models.PluginTab{}
+ }
+ if t := getter(); len(t) > 0 {
+ return t
+ }
+ return []models.PluginTab{}
+}
+
+// prependPluginPageContent puts plugin-contributed HTML in front of
+// the admin's rendered extraPageContent. Plugin HTML lands at the top
+// of the extra-content block so plugins can announce themselves above
+// the admin's prose. A nil getter or empty contribution leaves the
+// admin's value untouched. A newline separates the two sources so
+// the trailing markup of one can't run into the next.
+func prependPluginPageContent(admin string, pluginHTML func() []byte) string {
+ if pluginHTML == nil {
+ return admin
+ }
+ bytes := pluginHTML()
+ if len(bytes) == 0 {
+ return admin
+ }
+ prefix := string(bytes)
+ if admin == "" {
+ return prefix
+ }
+ if prefix[len(prefix)-1] != '\n' {
+ prefix += "\n"
+ }
+ return prefix + admin
+}
+
+// mergePluginCSS appends plugin-contributed CSS bytes to the admin's
+// custom CSS so the viewer renders one inline <style> block covering
+// both. A nil getter (no plugin host) or empty contribution leaves
+// the admin's value untouched. A newline separates the two sources
+// so a stylesheet that doesn't terminate in one can't trail into the
+// plugin block.
+func mergePluginCSS(admin string, pluginCSS func() []byte) string {
+ if pluginCSS == nil {
+ return admin
+ }
+ bytes := pluginCSS()
+ if len(bytes) == 0 {
+ return admin
+ }
+ if admin == "" {
+ return string(bytes)
+ }
+ if admin[len(admin)-1] != '\n' {
+ admin += "\n"
+ }
+ return admin + string(bytes)
+}
+
+// mergePluginActions appends plugin-contributed action buttons to the
+// admin-configured list so the viewer sees both in one externalActions
+// array. Admin entries stay first (and so render first in the UI) — a
+// plugin can extend the action set but can't reorder or replace what
+// the admin defined. A nil getter (no plugin host) makes this a no-op.
+func mergePluginActions(
+ configured []models.ExternalAction,
+ pluginActions func() []models.ExternalAction,
+) []models.ExternalAction {
+ if pluginActions == nil {
+ return configured
+ }
+ contributed := pluginActions()
+ if len(contributed) == 0 {
+ return configured
+ }
+ out := make([]models.ExternalAction, 0, len(configured)+len(contributed))
+ out = append(out, configured...)
+ out = append(out, contributed...)
+ return out
+}
+
// GetAllSocialPlatforms will return a list of all social platform types.
func GetAllSocialPlatforms(w http.ResponseWriter, r *http.Request) {
middleware.EnableCors(w)
diff --git a/webserver/handlers/customJavascript.go b/webserver/handlers/customJavascript.go
index 882233fedd..8a0bee7778 100644
--- a/webserver/handlers/customJavascript.go
+++ b/webserver/handlers/customJavascript.go
@@ -4,8 +4,23 @@ import (
"net/http"
)
-// ServeCustomJavascript will serve optional custom Javascript.
+// ServeCustomJavascript serves the admin's custom JavaScript followed
+// by the concatenated JS contributed by every loaded plugin's
+// manifest.scripts entries (each preceded by a `// plugin: <slug>
+// ...` delimiter for devtools attribution). The viewer loads a single
+// <script> tag pointing at this endpoint so plugins can extend the
+// page without each plugin needing its own <script> tag.
func (h *Handlers) ServeCustomJavascript(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
- _, _ = w.Write([]byte(h.configRepository.GetCustomJavascript()))
+ body := []byte(h.configRepository.GetCustomJavascript())
+ if h.pluginJSContent != nil {
+ pluginJS := h.pluginJSContent()
+ if len(pluginJS) > 0 {
+ if len(body) > 0 && body[len(body)-1] != '\n' {
+ body = append(body, '\n')
+ }
+ body = append(body, pluginJS...)
+ }
+ }
+ _, _ = w.Write(body)
}
diff --git a/webserver/handlers/handlers.go b/webserver/handlers/handlers.go
index f580774c4c..ce0f1fa6e0 100644
--- a/webserver/handlers/handlers.go
+++ b/webserver/handlers/handlers.go
@@ -8,6 +8,7 @@ import (
"github.com/owncast/owncast/config"
"github.com/owncast/owncast/metrics"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/persistence/chatmessagerepository"
"github.com/owncast/owncast/persistence/configrepository"
"github.com/owncast/owncast/persistence/notificationsrepository"
@@ -53,6 +54,38 @@ type Handlers struct {
apBuilder *apmodels.Builder
cfg *config.Config
+ // pluginActions, when non-nil, returns the current set of action
+ // buttons contributed by loaded plugins. Merged into the
+ // externalActions list returned by GetWebConfig so the viewer sees
+ // plugin actions alongside admin-defined ones. nil = no plugin host
+ // (boot disabled or failed).
+ pluginActions func() []models.ExternalAction
+
+ // pluginCSSContent, when non-nil, returns the concatenated CSS
+ // bytes contributed by loaded plugins that declared `styles` in
+ // their manifest. /api/config appends these bytes to the admin's
+ // customStyles so the viewer renders one inline <style> block
+ // covering both sources. nil = no plugin host.
+ pluginCSSContent func() []byte
+
+ // pluginJSContent mirrors pluginCSSContent for JavaScript: the
+ // concatenated JS bytes contributed by loaded plugins. The
+ // /customjavascript handler appends these to the admin's
+ // customJavascript so the viewer loads one <script> tag covering
+ // both sources.
+ pluginJSContent func() []byte
+
+ // pluginPageContent returns the concatenated HTML bytes
+ // contributed by loaded plugins via manifest.extraPageContent.
+ // /api/config prepends these bytes to the admin's rendered
+ // extraPageContent.
+ pluginPageContent func() []byte
+
+ // pluginTabs returns the list of viewer-page tabs contributed by
+ // loaded plugins via manifest.tabs. /api/config emits this list
+ // as `pluginTabs`; the viewer page renders one tab per entry.
+ pluginTabs func() []models.PluginTab
+
// previewThumbCache caches thumbnail/preview bytes for a short window
// so frequent polling from chat clients doesn't re-read the file
// every request.
@@ -85,6 +118,27 @@ type Deps struct {
NotificationsRepository notificationsrepository.NotificationsRepository
APBuilder *apmodels.Builder
Config *config.Config
+ // PluginActions is an optional getter that returns action buttons
+ // contributed by loaded plugins. Wired by main.go to the plugin host's
+ // Actions() method; nil when the plugin host is disabled.
+ PluginActions func() []models.ExternalAction
+ // PluginCSSContent is an optional getter that returns the
+ // concatenated CSS bytes contributed by loaded plugins. Wired by
+ // main.go to the plugin host's StylesContent() method; nil when
+ // the plugin host is disabled.
+ PluginCSSContent func() []byte
+ // PluginJSContent mirrors PluginCSSContent for JavaScript: the
+ // concatenated JS bytes contributed by loaded plugins. Wired to
+ // the plugin host's ScriptsContent() method.
+ PluginJSContent func() []byte
+ // PluginPageContent returns the concatenated HTML bytes from
+ // each loaded plugin's manifest.extraPageContent. Wired to the
+ // plugin host's PageContent() method.
+ PluginPageContent func() []byte
+ // PluginTabs returns the list of viewer-page tabs contributed by
+ // loaded plugins via manifest.tabs. Wired to the plugin host's
+ // Tabs() method.
+ PluginTabs func() []models.PluginTab
}
// HandleWebsocketConnection routes the /ws websocket upgrade to the
@@ -115,6 +169,11 @@ func NewHandlers(deps Deps) *Handlers {
notificationsRepository: deps.NotificationsRepository,
apBuilder: deps.APBuilder,
cfg: deps.Config,
+ pluginActions: deps.PluginActions,
+ pluginCSSContent: deps.PluginCSSContent,
+ pluginJSContent: deps.PluginJSContent,
+ pluginPageContent: deps.PluginPageContent,
+ pluginTabs: deps.PluginTabs,
previewThumbCache: ttlcache.New(
ttlcache.WithTTL[string, []byte](15),
ttlcache.WithCapacity[string, []byte](1),
diff --git a/webserver/router/middleware/adminsession.go b/webserver/router/middleware/adminsession.go
new file mode 100644
index 0000000000..151a1dd5c9
--- /dev/null
+++ b/webserver/router/middleware/adminsession.go
@@ -0,0 +1,140 @@
+package middleware
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "net/http"
+ "strings"
+ "sync"
+ "time"
+)
+
+// adminSessionCookieName is the cookie carrying an opaque admin session
+// token. It's sent on every request to the Owncast origin, so the host's
+// admin auth check accepts it as an alternative to a Basic Auth header
+// for clients that cannot inject one (notably plugin admin iframes).
+const adminSessionCookieName = "owncast_admin_session"
+
+// adminSessionTTL is how long a minted session is good for. The admin UI
+// re-mints lazily, so an idle admin tab will silently get a fresh cookie
+// on its next plugin-iframe navigation.
+const adminSessionTTL = 8 * time.Hour
+
+// adminSessionTokenBytes is the entropy of a minted session token before
+// hex encoding. 32 bytes → 64 hex chars, comfortably resistant to guessing.
+const adminSessionTokenBytes = 32
+
+// adminSessionStore is an in-memory map of opaque session tokens to their
+// expiry. Sessions are not persisted across restarts — the admin re-mints
+// on the next request when the cookie no longer validates.
+type adminSessionStore struct {
+ mu sync.Mutex
+ sessions map[string]time.Time
+}
+
+func newAdminSessionStore() *adminSessionStore {
+ return &adminSessionStore{sessions: make(map[string]time.Time)}
+}
+
+// mint generates a fresh token, records it with TTL adminSessionTTL, and
+// returns the token. The caller is responsible for surfacing it to the
+// client (typically as a Set-Cookie).
+func (s *adminSessionStore) mint() (string, error) {
+ buf := make([]byte, adminSessionTokenBytes)
+ if _, err := rand.Read(buf); err != nil {
+ return "", err
+ }
+ token := hex.EncodeToString(buf)
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.sessions[token] = time.Now().Add(adminSessionTTL)
+ s.gcLocked(time.Now())
+ return token, nil
+}
+
+// valid reports whether token is a currently-active session. An unknown
+// or expired token returns false; expired tokens are pruned as a side
+// effect so the map doesn't grow unboundedly.
+func (s *adminSessionStore) valid(token string) bool {
+ if token == "" {
+ return false
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ expiry, ok := s.sessions[token]
+ if !ok {
+ return false
+ }
+ if time.Now().After(expiry) {
+ delete(s.sessions, token)
+ return false
+ }
+ return true
+}
+
+// gcLocked drops any sessions whose expiry has passed. Called under mu
+// from mint() so the cost is amortized over new sessions; the map size
+// is bounded by concurrent admins, which is small.
+func (s *adminSessionStore) gcLocked(now time.Time) {
+ for token, expiry := range s.sessions {
+ if now.After(expiry) {
+ delete(s.sessions, token)
+ }
+ }
+}
+
+// hasValidAdminSessionCookie reports whether r carries an admin session
+// cookie that is currently active. Used as an alternative auth path in
+// IsAdminRequest for clients that cannot inject the Authorization header.
+func (m *Middleware) hasValidAdminSessionCookie(r *http.Request) bool {
+ c, err := r.Cookie(adminSessionCookieName)
+ if err != nil {
+ return false
+ }
+ return m.adminSessions.valid(c.Value)
+}
+
+// ensureAdminSessionCookie mints an admin session and sets the cookie
+// on w when r doesn't already carry a valid one. Called from
+// RequireAdminAuth after Basic Auth succeeds, so every authenticated
+// admin API call keeps the cookie fresh as a side effect — there is no
+// explicit "log in" endpoint the client must remember to call.
+//
+// A mint failure is silently swallowed; the admin API call itself still
+// succeeds, and the next authenticated call will retry. The cookie is
+// best-effort: if it's missing or expired, callers that can fall back
+// to Basic Auth (the admin UI itself) keep working, and only contexts
+// that can't (iframes) will get a one-time browser prompt.
+func (m *Middleware) ensureAdminSessionCookie(w http.ResponseWriter, r *http.Request) {
+ if m.hasValidAdminSessionCookie(r) {
+ return
+ }
+ token, err := m.adminSessions.mint()
+ if err != nil {
+ return
+ }
+ // Secure mirrors whether the request itself came in over TLS:
+ // always-on would silently break Owncast admin deployments running
+ // over plain HTTP on a LAN, and always-off downgrades cookie
+ // security on every HTTPS deployment. Reading r.TLS catches direct
+ // HTTPS; checking X-Forwarded-Proto catches the common reverse-proxy
+ // case where TLS terminates upstream.
+ secure := r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
+ // gosec G124: Secure is a constant `true`/`false` rather than a
+ // literal, but it's request-scheme-aware (set when TLS is in play,
+ // cleared when the admin is on a LAN HTTP deployment). The linter
+ // can't model that and would force a single hard-coded value.
+ http.SetCookie(w, &http.Cookie{ //nolint:gosec // G124: see comment above
+ Name: adminSessionCookieName,
+ Value: token,
+ Path: "/",
+ MaxAge: int(adminSessionTTL.Seconds()),
+ HttpOnly: true,
+ Secure: secure,
+ // SameSite=Lax so the cookie reaches same-origin iframe loads and
+ // top-level navigations triggered from the admin UI, without
+ // being sent on third-party requests.
+ SameSite: http.SameSiteLaxMode,
+ })
+}
diff --git a/webserver/router/middleware/adminsession_test.go b/webserver/router/middleware/adminsession_test.go
new file mode 100644
index 0000000000..3e09c81de0
--- /dev/null
+++ b/webserver/router/middleware/adminsession_test.go
@@ -0,0 +1,130 @@
+package middleware
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+)
+
+func TestAdminSessionStore_MintValidateExpire(t *testing.T) {
+ s := newAdminSessionStore()
+
+ token, err := s.mint()
+ if err != nil {
+ t.Fatalf("mint: %v", err)
+ }
+ if token == "" {
+ t.Fatal("mint returned empty token")
+ }
+ if !s.valid(token) {
+ t.Error("freshly minted token should validate")
+ }
+
+ // Force expiry by rewriting the recorded time, then confirm validate
+ // returns false and the entry is pruned.
+ s.mu.Lock()
+ s.sessions[token] = time.Now().Add(-1 * time.Minute)
+ s.mu.Unlock()
+
+ if s.valid(token) {
+ t.Error("expired token should not validate")
+ }
+ s.mu.Lock()
+ _, present := s.sessions[token]
+ s.mu.Unlock()
+ if present {
+ t.Error("expired token should have been pruned from store")
+ }
+}
+
+func TestAdminSessionStore_ValidRejectsUnknownAndEmpty(t *testing.T) {
+ s := newAdminSessionStore()
+ if s.valid("") {
+ t.Error("empty token should not validate")
+ }
+ if s.valid("not-a-real-token") {
+ t.Error("unknown token should not validate")
+ }
+}
+
+func TestEnsureAdminSessionCookie_SetsWhenAbsent(t *testing.T) {
+ m := &Middleware{adminSessions: newAdminSessionStore()}
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/admin/anything", nil)
+ m.ensureAdminSessionCookie(rec, req)
+
+ res := rec.Result()
+ defer res.Body.Close()
+
+ var cookie *http.Cookie
+ for _, c := range res.Cookies() {
+ if c.Name == adminSessionCookieName {
+ cookie = c
+ break
+ }
+ }
+ if cookie == nil {
+ t.Fatalf("response did not set %s cookie", adminSessionCookieName)
+ }
+ if cookie.Value == "" {
+ t.Error("cookie has empty value")
+ }
+ if !cookie.HttpOnly {
+ t.Error("cookie should be HttpOnly")
+ }
+ if cookie.SameSite != http.SameSiteLaxMode {
+ t.Errorf("cookie SameSite = %v want %v", cookie.SameSite, http.SameSiteLaxMode)
+ }
+ if cookie.Path != "/" {
+ t.Errorf("cookie Path = %q want %q", cookie.Path, "/")
+ }
+ if !m.adminSessions.valid(cookie.Value) {
+ t.Error("minted cookie value should validate against store")
+ }
+}
+
+func TestEnsureAdminSessionCookie_NoOpWhenAlreadyValid(t *testing.T) {
+ // A request that already carries a valid cookie should not mint a new
+ // one — otherwise every authenticated API call would rotate the token
+ // and create a growing list of live sessions per admin.
+ m := &Middleware{adminSessions: newAdminSessionStore()}
+ existing, _ := m.adminSessions.mint()
+
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, "/api/admin/anything", nil)
+ req.AddCookie(&http.Cookie{Name: adminSessionCookieName, Value: existing})
+
+ m.ensureAdminSessionCookie(rec, req)
+
+ res := rec.Result()
+ defer res.Body.Close()
+ if len(res.Cookies()) != 0 {
+ t.Errorf("expected no Set-Cookie when cookie already valid, got %d", len(res.Cookies()))
+ }
+}
+
+func TestHasValidAdminSessionCookie(t *testing.T) {
+ m := &Middleware{adminSessions: newAdminSessionStore()}
+ token, _ := m.adminSessions.mint()
+
+ // Missing cookie → false.
+ req := httptest.NewRequest(http.MethodGet, "/anything", nil)
+ if m.hasValidAdminSessionCookie(req) {
+ t.Error("no cookie should not validate")
+ }
+
+ // Unknown token → false.
+ req.AddCookie(&http.Cookie{Name: adminSessionCookieName, Value: "bogus"})
+ if m.hasValidAdminSessionCookie(req) {
+ t.Error("unknown cookie value should not validate")
+ }
+
+ // Valid minted token → true.
+ req = httptest.NewRequest(http.MethodGet, "/anything", nil)
+ req.AddCookie(&http.Cookie{Name: adminSessionCookieName, Value: token})
+ if !m.hasValidAdminSessionCookie(req) {
+ t.Error("minted cookie should validate")
+ }
+}
diff --git a/webserver/router/middleware/auth.go b/webserver/router/middleware/auth.go
index 3e91d749d9..87d0648103 100644
--- a/webserver/router/middleware/auth.go
+++ b/webserver/router/middleware/auth.go
@@ -17,15 +17,41 @@ type ExternalAccessTokenHandlerFunc func(models.ExternalAPIUser, http.ResponseWr
// UserAccessTokenHandlerFunc is a function that is called after validing user access.
type UserAccessTokenHandlerFunc func(models.User, http.ResponseWriter, *http.Request)
-// RequireAdminAuth wraps a handler requiring HTTP basic auth for it using the given
-// the stream key as the password and and a hardcoded "admin" for username.
+// adminAuthRealm is the WWW-Authenticate realm string used by every admin
+// auth challenge in Owncast. Anything that gates on admin Basic Auth (the
+// main admin API, the plugin management API, plugin admin pages) must
+// challenge with this exact realm so the browser shares one credential
+// cache across all of them.
+const adminAuthRealm = "Owncast Authenticated Request"
+
+// IsAdminRequest reports whether r carries valid admin credentials. The
+// Owncast admin UI sends Basic Auth on every API call; embedded contexts
+// that cannot inject a custom Authorization header (notably plugin admin
+// iframes) authenticate via the admin session cookie instead. Shared by
+// RequireAdminAuth and any caller that needs the same check without
+// rejecting the request (e.g. a handler filling an "authenticated"
+// boolean on a downstream payload).
+func (m *Middleware) IsAdminRequest(r *http.Request) bool {
+ if user, pass, ok := r.BasicAuth(); ok {
+ if subtle.ConstantTimeCompare([]byte(user), []byte("admin")) == 1 &&
+ utils.CompareHash(m.configRepository.GetAdminPassword(), pass) == nil {
+ return true
+ }
+ }
+ return m.hasValidAdminSessionCookie(r)
+}
+
+// RequireAdminAuth wraps a handler requiring HTTP basic auth for it using
+// the admin password as the password and a hardcoded "admin" for username.
+//
+// As a side effect, a valid Basic Auth request also primes an admin
+// session cookie. Embedded contexts that can't inject the Authorization
+// header (notably plugin admin iframes) authenticate via that cookie on
+// their next same-origin request, so the user isn't prompted by the
+// browser's native Basic Auth dialog.
func (m *Middleware) RequireAdminAuth(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
- username := "admin"
- password := m.configRepository.GetAdminPassword()
- realm := "Owncast Authenticated Request"
-
- // Alow CORS only for localhost:3000 to support Owncast development.
+ // Allow CORS only for localhost:3000 to support Owncast development.
validAdminHost := "http://localhost:3000"
w.Header().Set("Access-Control-Allow-Origin", validAdminHost)
w.Header().Set("Access-Control-Allow-Credentials", "true")
@@ -38,16 +64,19 @@ func (m *Middleware) RequireAdminAuth(handler http.HandlerFunc) http.HandlerFunc
return
}
- user, pass, ok := r.BasicAuth()
-
- // Failed
- if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || utils.CompareHash(password, pass) != nil {
- w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
+ if !m.IsAdminRequest(r) {
+ w.Header().Set("WWW-Authenticate", `Basic realm="`+adminAuthRealm+`"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
log.Debugln("Failed admin authentication")
return
}
+ // Prime the admin session cookie if the request authenticated via
+ // Basic Auth and doesn't already carry a valid cookie. No-op when
+ // the cookie is already fresh, so most admin API calls don't pay
+ // for it (and don't rotate the token unnecessarily).
+ m.ensureAdminSessionCookie(w, r)
+
handler(w, r)
}
}
diff --git a/webserver/router/middleware/middleware.go b/webserver/router/middleware/middleware.go
index 10a49aeab4..92ab2b640d 100644
--- a/webserver/router/middleware/middleware.go
+++ b/webserver/router/middleware/middleware.go
@@ -14,6 +14,11 @@ type Middleware struct {
configRepository configrepository.ConfigRepository
authRepository authrepository.AuthRepository
userRepository userrepository.UserRepository
+ // adminSessions holds opaque admin session tokens. The admin UI mints
+ // one after authenticating with Basic Auth, and embedded contexts
+ // (plugin admin iframes) that cannot inject the Authorization header
+ // themselves authenticate via this cookie instead.
+ adminSessions *adminSessionStore
}
// Deps lists the services *Middleware consumes.
@@ -29,5 +34,6 @@ func New(deps Deps) *Middleware {
configRepository: deps.ConfigRepository,
authRepository: deps.AuthRepository,
userRepository: deps.UserRepository,
+ adminSessions: newAdminSessionStore(),
}
}
diff --git a/webserver/router/router.go b/webserver/router/router.go
index 41b3c9b308..ee46a49dfd 100644
--- a/webserver/router/router.go
+++ b/webserver/router/router.go
@@ -26,7 +26,7 @@ import (
// mw carries the methodified HTTP middleware (admin basic-auth, federation
// content-type gating). apc carries the methodified ActivityPub HTTP
// handler set.
-func Start(cfg *config.Config, enableVerboseLogging bool, h *handlers.Handlers, mw *middleware.Middleware, apc *apcontrollers.Controllers) error {
+func Start(cfg *config.Config, enableVerboseLogging bool, h *handlers.Handlers, mw *middleware.Middleware, apc *apcontrollers.Controllers, pluginContent http.Handler, pluginAdmin http.Handler) error {
// @behlers New Router
r := chi.NewRouter()
@@ -57,6 +57,13 @@ func Start(cfg *config.Config, enableVerboseLogging bool, h *handlers.Handlers,
// Single AP object
r.HandleFunc("/federation/*", mw.RequireActivityPubOrRedirect(apc.ObjectHandler))
+ // Plugin-served content: /plugins/<name>/* (static assets, dynamic
+ // on_http_request handlers, and host-owned SSE streams). nil when the
+ // plugin host is disabled or failed to start.
+ if pluginContent != nil {
+ r.Handle("/plugins/*", pluginContent)
+ }
+
// The primary web app.
r.HandleFunc("/*", h.IndexHandler)
@@ -69,6 +76,24 @@ func Start(cfg *config.Config, enableVerboseLogging bool, h *handlers.Handlers,
rootHandler := r
m := http.NewServeMux()
+ // Plugin management API. Mounted on the outer mux (beside the OpenAPI
+ // /api router, which owns /api/* via chi) so these routes don't collide
+ // with the generated handler. nil when the plugin host is disabled.
+ if pluginAdmin != nil {
+ m.Handle("/api/admin/plugins", pluginAdmin)
+ m.Handle("/api/admin/plugins/", pluginAdmin)
+ // Plugin registry browse + install. Sibling prefix of
+ // /api/admin/plugins/ so the trailing-slash matcher above
+ // doesn't claim these paths. The pluginAdmin mux dispatches
+ // the action (list / install) internally.
+ m.Handle("/api/admin/plugin-registry/", pluginAdmin)
+ m.Handle("/api/plugins/actions", pluginAdmin)
+ // Plugin icons: GET /api/plugins/<name>/icon. The pluginAdmin
+ // mux narrows on the /icon suffix internally; this prefix
+ // mount just routes the namespace.
+ m.Handle("/api/plugins/", pluginAdmin)
+ }
+
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/debug/vars":