Skip to content

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

feat: add authentication access modes

Gabe Kangas75ae2a29814d
diff --git a/docs/plugin-auth-gate-design.md b/docs/plugin-auth-gate-design.md
index da27e5a5d8..90418f6464 100644
--- a/docs/plugin-auth-gate-design.md
+++ b/docs/plugin-auth-gate-design.md
@@ -1,7 +1,8 @@
-# Plugin-based Viewer Authentication ("Auth Gate") — Design
+# Plugin-based Viewer Authentication ("Auth Gate"): Design
-Status: draft for review (no code yet)
-Branch: `plugin-auth-gate` (worktree off `develop`)
+Status: implemented. See `pluginhost/authgate.go` for the middleware,
+`pluginhost/pluginhost.go` for the settings store and admin endpoint, and
+`yp/` for directory behavior.
## Goal
@@ -14,18 +15,34 @@ with a first-class plugin capability.
The plugin is the **identity provider**; Owncast core is the **gatekeeper and
session authority**.
-## Scope decision: gate the whole web server
+## Scope decision: gate the web surface, with an operator-chosen edge
-When auth is on, the **entire web server is gated** — not just the HTML page.
-The viewer page (`/`), the video (`/hls/*`), chat (`/ws`), and the API are all
-behind the gate. Consequence, accepted: **the stream is only viewable through
-Owncast's own web UI** — VLC/QuickTime/other native players can't carry the
-session and therefore can't play a gated stream.
+The gate is opt-out. Every request is challenged unless a named exemption
+applies, so the viewer page (`/`), `/api/config`, chat, and the rest of the
+public API are behind it.
-Gating only the HTML page was rejected: the page embeds nothing secret, and the
-HLS URL would remain openly fetchable, so it would be privacy theater.
+The operator chooses one cumulative access mode. Native players such as VLC,
+QuickTime, mobile apps, and restreamers cannot complete a browser login or carry
+a session cookie. Any mode that gates `/hls/*` blocks those players.
-### External storage (S3/CDN) caveat — DOCUMENT, don't block
+The access mode is stored per gate plugin and selected on the plugin's
+**Authentication** tab:
+
+| Access mode | Effect |
+|---|---|
+| Website only (default) | The web UI requires sign-in. `/hls/*`, `/api/status`, and directory listing stay public. |
+| Website, video players, and other resources | Also gates `/hls/*`. Native players without a browser session are blocked. `/api/status` and directory listing stay public. |
+| Website, video players, and server status requests | Gates the web UI, `/hls/*`, and `/api/status`. Directory listing is disabled. |
+
+The modes are cumulative. There is no status-only mode that hides
+`/api/status` while leaving HLS public.
+
+The default is deliberately the least disruptive. Enabling a gate on a running
+instance protects the website without breaking players or monitoring that
+already work. Operators who need the video itself private select one of the
+stream-protection modes and accept losing native players.
+
+### External storage (S3/CDN) caveat: document, do not block
Under S3 storage, `rewritePlaylistLocations` rewrites playlists to **absolute
remote URLs**, so segments are fetched directly from S3/CDN and never touch the
@@ -36,30 +53,52 @@ Owncast server. The gate cannot see those requests.
- But under S3 the segment URLs themselves are world-readable, so a *leaked or
shared* segment URL remains fetchable.
-Therefore: **gate + local storage = airtight; gate + S3 = good friction, not
-airtight.** This is a documentation item for operators and plugin authors, not a
-hard block.
+Therefore: **stream protection + local storage = airtight. Stream protection +
+S3 = good friction, not airtight.** This is a documentation item for operators
+and plugin authors, not a hard block.
## Architecture
### The plugin is out of the per-request hot path
-Once auth is on, every request hits the gate, including each HLS segment (a live
-viewer pulls a new segment every ~2-4s × N viewers). Calling into the plugin's
-embedded JS/Python engine per request would melt the server. So:
+Once auth is on, every non-exempt request hits the gate. Under stream
+protection that includes each HLS segment (a live viewer pulls a new segment
+every ~2-4s × N viewers). Calling into the plugin's embedded JS/Python engine
+per request would melt the server. So:
- **The plugin runs the login flow only** (infrequent: ~once per viewer session),
over its existing `onHttpRequest` routes under `/plugins/<slug>/*`.
- **Core mints and checks a signed session cookie.** The per-request gate check
- is pure Go (verify signature + expiry) — no DB lookup, no engine call.
+ is pure Go (verify signature + expiry), no DB lookup and no engine call.
+- **The access policy is memoized.** Settings are read from the plugin's KV
+ namespace once and cached in an atomic snapshot, so the hot path does not
+ touch storage either. A read failure is not cached: it falls back to the
+ defaults for that request and retries on the next one.
### Three tiers of checking
| Tier | When | Cost | What happens |
|------|------|------|--------------|
-| 1 | every request (`/hls/*`, images, `/ws`, API) | Go-only: verify cookie signature + expiry | valid → pass; invalid/absent → 302 to login |
-| 2 | `/` (index navigation) only | optional engine call: `onAuthCheck` | re-validate against provider; `ok`/`refresh`/`deny` |
-| 3 | n/a | — | (no per-request denylist; revocation is Tier 2) |
+| 1 | every non-exempt request | Go-only: verify cookie signature + expiry | valid passes. Invalid or absent gets a 302 for GET/HEAD, 401 otherwise |
+| 2 | `/` (index navigation) only, with a valid session | optional engine call: `onAuthCheck` | re-validate against provider, returning `ok`/`refresh`/`deny` |
+| 3 | n/a | none | no per-request denylist, revocation is Tier 2 |
+
+Which requests are exempt is decided by a single named list in
+`pluginhost/authgate.go`. Adding a bypass means adding a named, individually
+testable rule there, in the open:
+
+| Exemption | Why | Conditional on |
+|---|---|---|
+| `admin` | `/admin/*` and `/api/admin/*` carry their own credential and have their own gate, so an operator can always disable a broken gate | never |
+| `static-assets` | files that actually exist in the embedded web build, which the admin app needs to render. HTML entry points are excluded, so the viewer UI stays gated | never |
+| `active-gate-plugin` | the login screen and OAuth callback must be reachable while signed out. Only the *active* gate's namespace, not every plugin | never |
+| `external-api` | `/api/integrations/*` validates its own bearer token per route | never |
+| `directory-api` | `/api/yp` is anonymous public metadata by design, and the YP handler itself refuses when listing is off | never |
+| `third-party-player` | `/hls/*` for players that cannot log in | off when "protect the stream" is on |
+| `stream-status` | `/api/status` for uptime monitors | off when "block stream status" is on |
+
+A valid session is checked before any exemption, so a signed-in viewer is never
+bounced off a path the policy closed to anonymous callers.
### The session cookie = a signed carrier for the existing access token
@@ -80,7 +119,7 @@ Two readers, one cookie, both keyed on the access token you already understand:
| Path | Reader | Mechanism |
|------|--------|-----------|
-| `/`, `/hls/*`, images | gate | verify signature + expiry → pass (no DB; this is why it's signed) |
+| `/`, gated `/hls/*`, page assets | gate | verify signature + expiry → pass (no DB; this is why it's signed) |
| `/ws`, chat REST | chat | extract `accessToken` → `GetUserByToken(accessToken)` → existing chat identity path |
Why signed rather than a raw token in a cookie:
@@ -107,8 +146,9 @@ the access token from the gate cookie" fallback.
```ts
// Identity — find-or-create the user for an external identity, link + authenticate it.
-// Core namespaces authId by plugin slug internally (github-auth:github:583231),
-// so plugins cannot collide or spoof each other's users.
+// Pass the raw external id. Core stores your slug in the auth row's provider
+// column and scopes lookups to (provider, authId), so plugins cannot collide
+// or spoof each other's users. Do not prefix authId yourself.
owncast.users.register({ authId: string, displayName?: string, scopes?: string[] })
: { userId: string }
@@ -196,22 +236,35 @@ The gate's posture is **decoupled from plugin runtime health**:
The existing auto-disable-on-strikes must resolve to **closed + loud admin
alert**, never to a silently open site.
-### Exemption set (bypass the gate)
+### Where the access policy lives
-Principle: **the gate covers only the otherwise-public surface; any route that
-already enforces its own credential bypasses it.**
+The access mode is host-owned, not plugin config. A gate plugin cannot widen or
+narrow its own reach. It is keyed per plugin under the reserved KV key
+`owncast.auth-gate-settings` in that plugin's namespace, so each gate keeps its
+own policy. Switching gates does not carry one provider's choice over to
+another.
-- the designated gate plugin's namespace `/plugins/<slug>/*` + its static assets
- (bootstrap)
-- `/admin/*` — already `RequireAdminAuth`
-- all external-API-token routes — already `RequireExternalAPIAccessToken`
- (a valid Bearer client carries no cookie; gating would 302 it into login)
-- health/liveness endpoint (if present)
+The admin UI shows an **Authentication** tab for any installed plugin that
+declares `auth.gate`, whether or not it is currently enabled, so an operator can
+set the mode before arming the gate. It is backed by
+`GET`/`POST /api/admin/plugins/<slug>/auth-settings`. The endpoint accepts
+`website-only`, `website-and-stream`, or `website-stream-and-status` as the
+`accessMode`. It returns 404 for plugins that do not declare the permission and
+rejects unknown fields or unsupported modes.
-**Everything else is gated, including `/api/status` and embeds** — leaking
-live-status / viewer count to anonymous visitors would undercut the privacy goal.
-A future "advertise live status even when gated" option would be an explicit
-operator opt-in, not a default bypass.
+### Directory interaction
+
+`/api/yp` is never challenged by the gate. The Owncast Directory fetches it
+anonymously: the registration key travels in the server-to-directory ping, not
+in the directory's read of this endpoint, so there is no credential to check.
+The payload is public metadata by design.
+
+The `website-stream-and-status` mode does not gate `/api/yp`. It switches the
+directory off. `Host.DirectoryAvailable()` reports the policy, and the YP
+service consults it in two places: `GetYPResponse` answers 404, and the outbound
+ping is skipped so the instance stops announcing itself to a directory that can
+no longer read it. A listed stream cannot function without a readable status
+endpoint, so status protection and directory availability move together.
### Session credential details
@@ -222,8 +275,11 @@ operator opt-in, not a default bypass.
panic button). Mechanically required: core verifies on the hot path without
calling the plugin, so core must hold the secret. Plugin authors never touch it.
(The OAuth *client* secret is a separate, plugin-config concern.)
-- **TTL: operator-configurable, default 24h**, with **sliding refresh** on each
- `/` load. TTL is a real security knob because it's the revocation backstop.
+- **TTL is plugin-requested** via `grantSession({ ttl })`, defaulting to
+ `DefaultSessionTTL` (24h) and capped at `MaxSessionTTL` (30 days). It is a
+ real security knob because it is the revocation backstop: `onAuthCheck` only
+ runs on a page load, so an idle revoked viewer lingers until the cookie
+ expires.
## The chat / identity bridge
@@ -250,36 +306,44 @@ Handlers: `onHttpRequest` (routes `/`, `/callback`, `/logout`) + optional
`<serverURL>/plugins/github-auth/callback`.
- CSRF `state` stored in `storage.kv` with a short TTL, keyed to `return_to`.
-## Open / deferred items
-
-- **`onAuthCheck` precise input fields** (above is the proposed shape).
-- **Admin UX**: callback-URL display + "configure before enabling" guidance +
- the "enabling gates the whole site" warning. Author-built page; core supplies
- `server.info()`.
-- **Signing secret config key + rotation UI** in core admin.
-- **Static maintenance page** for the fail-closed state.
-- **Hard per-session revocation** (KV denylist) — explicitly deferred; revocation
- is page-load granularity via `onAuthCheck`.
-
-## Implementation surface (where code lands)
-
-**Owncast core** (`services/plugins` is the single source of truth; runtime
-features go here):
-- Gate middleware in the chi chain (`webserver/router`), with the exemption set.
-- Signed session cookie mint/verify + persisted signing secret in config.
-- Host functions `owncast.users.register`, `owncast.auth.grantSession`,
- `owncast.auth.endSession`; new plugin `AuthType`; per-plugin `authId` namespacing.
-- `auth.gate` + `users.register` permission enforcement.
-- `Manager.Enable` single-gate guard; fail-closed wiring + auto-disable → closed.
-- `/ws` + chat REST cookie fallback (`HandleClientConnection`).
-- `onAuthCheck` dispatch on the index path; fail-closed on error.
-- Static "auth unavailable" page.
-
-**Plugin SDK** (`owncast-plugin-sdk`, JS + Python in parallel):
-- Type/handler for `onAuthCheck`; facades for `users.register`,
- `auth.grantSession`, `auth.endSession`.
-- `auth.gate` / `users.register` permission docs; manifest validation.
-- Wire-protocol doc updates; author guide section.
-- Example plugin (`github-auth`) in `examples/js` **and** `examples/python`
- (kept in sync, README + INSTRUCTIONS).
-```
+## Still deferred
+
+- **Hard per-session revocation** (KV denylist). Revocation stays at page-load
+ granularity via `onAuthCheck`, with the cookie TTL as the backstop.
+- **Signing secret rotation UI.** The secret is generated and persisted
+ automatically, but rotating it (which invalidates every session) has no admin
+ control yet.
+- **Cross-gate policy migration.** Access settings are per plugin, so switching
+ gate providers means setting the policy again on the new one. That is the
+ intended behavior, not a gap, but an operator may be surprised by it.
+
+## Where the code lives
+
+**Owncast core:**
+- `pluginhost/authgate.go`: middleware, exemption list, gate decision,
+ `onAuthCheck` dispatch, fail-closed page.
+- `pluginhost/pluginhost.go`: `AuthGateSettings`, the memoized settings store,
+ `DirectoryAvailable`, and the `auth-settings` admin endpoint.
+- `services/plugins/authsession.go`: cookie mint/verify, TTL clamping, the
+ request-scoped grant sink.
+- `services/plugins/manager.go`: `ActiveAuthGate`, `IsAuthGate`, and the
+ single-gate guard in `Enable`.
+- `yp/`: directory ping and `/api/yp`, both gated on `DirectoryAvailable`.
+- `web/components/admin/plugins/AuthGateSettingsForm.tsx`: the Authentication
+ tab.
+
+**Plugin SDK** (`owncast-plugin-sdk`, JS and Python in parallel): the
+`onAuthCheck` handler type, facades for `users.register`, `auth.grantSession`,
+and `auth.endSession`, permission docs, and the `github-auth` / `basic-auth`
+examples.
+
+## Test coverage
+
+| Area | Where |
+|---|---|
+| Cookie sign/verify, expiry, tampering | `services/plugins/authsession_test.go` |
+| Single-gate guard, `ActiveAuthGate`, `IsAuthGate` | `services/plugins/manager_authgate_test.go` |
+| Exemption list and gate decision, full policy matrix | `pluginhost/authgate_test.go` |
+| Middleware: credential rejection, 302/401 split, identity propagation, fail-closed, revocation clearing the cookie | `pluginhost/authgate_middleware_test.go` |
+| Settings endpoint, persistence, corrupt-value fallback | `pluginhost/authgate_settings_test.go` |
+| Directory 404 and ping suppression | `yp/api_test.go` |
diff --git a/main.go b/main.go
index 80b5714aeb..f37004f5e9 100644
--- a/main.go
+++ b/main.go
@@ -332,6 +332,9 @@ func main() {
pluginContentHandler = pluginHostInstance.Handler()
pluginAdminHandler = pluginHostInstance.AdminHandler()
viewerAuthGate = pluginHostInstance.AuthGateMiddleware()
+ // The gate's access policy can disable directory listing, so YP has
+ // to consult it before pinging or answering /api/yp.
+ ypSvc.SetDirectoryAvailable(pluginHostInstance.DirectoryAvailable)
defer pluginHostInstance.Stop(ctx)
}
diff --git a/pluginhost/authgate.go b/pluginhost/authgate.go
index 1f272cea58..3ede896ccf 100644
--- a/pluginhost/authgate.go
+++ b/pluginhost/authgate.go
@@ -43,17 +43,17 @@ const authUnavailableHTML = `<!doctype html><html><head><meta charset="utf-8">`
`<p>This site requires sign-in, but the authentication plugin is not ` +
`currently available. Please try again shortly.</p></body></html>`
-// decideGate is the pure decision for one request: allow it, send it to the
-// login screen, or serve the fail-closed page. gateSlug is the enabled
-// auth.gate plugin's slug ("" when none is enabled); gateLoaded reports whether
-// that plugin is actually running.
// The viewer-auth gate is opt-out: every request is gated unless a rule here
// exempts it. Keeping the exemptions as a small, named, individually-testable
-// list — rather than string compares buried in the decision — makes the policy
+// list, rather than string compares buried in the decision, makes the policy
// explicit: adding a bypass means adding a named rule, in the open, here.
+//
+// Some rules are conditional on the operator's access policy, so every rule
+// receives the active gate's settings. A rule that ignores them is
+// unconditional.
type gateExemption struct {
name string
- allow func(r *http.Request, gateSlug string) bool
+ allow func(r *http.Request, gateSlug string, settings AuthGateSettings) bool
}
var gateExemptions = []gateExemption{
@@ -61,6 +61,9 @@ var gateExemptions = []gateExemption{
{"static-assets", exemptStaticAssets},
{"active-gate-plugin", exemptActiveGatePluginRoutes},
{"external-api", exemptExternalAPIRoutes},
+ {"directory-api", exemptDirectoryAPI},
+ {"third-party-player", exemptThirdPartyPlayerRoutes},
+ {"stream-status", exemptStreamStatus},
}
// externalAPIPrefix is the namespace for third-party API routes. Each handler
@@ -83,7 +86,7 @@ var webFS = static.GetWeb()
// not assets — serving them unauthenticated would leak the viewer UI.
// - HLS media (/hls/*.ts, *.m3u8): it lives in the HLS store, not the web
// embed, so fs.Stat here never finds it.
-func exemptStaticAssets(r *http.Request, _ string) bool {
+func exemptStaticAssets(r *http.Request, _ string, _ AuthGateSettings) bool {
p := strings.TrimPrefix(r.URL.Path, "/")
if p == "" || strings.HasSuffix(p, ".html") {
return false
@@ -99,7 +102,7 @@ func exemptStaticAssets(r *http.Request, _ string) bool {
// admin SPA (/admin/*) and the admin API (/api/admin/*); the latter often
// authenticates via the admin session cookie rather than an Authorization
// header, so the self-credentialed rule alone would miss it.
-func exemptAdminRoutes(r *http.Request, _ string) bool {
+func exemptAdminRoutes(r *http.Request, _ string, _ AuthGateSettings) bool {
p := r.URL.Path
return p == "/admin" || strings.HasPrefix(p, "/admin/") ||
p == "/api/admin" || strings.HasPrefix(p, "/api/admin/")
@@ -109,7 +112,7 @@ func exemptAdminRoutes(r *http.Request, _ string) bool {
// reachable while unauthenticated — it serves the login screen, the auth
// callback, and its assets. Dynamic: only the currently-enabled gate plugin is
// exempt; every other plugin's routes stay gated.
-func exemptActiveGatePluginRoutes(r *http.Request, gateSlug string) bool {
+func exemptActiveGatePluginRoutes(r *http.Request, gateSlug string, _ AuthGateSettings) bool {
if gateSlug == "" {
return false
}
@@ -130,15 +133,42 @@ func exemptActiveGatePluginRoutes(r *http.Request, gateSlug string) bool {
// let an anonymous visitor walk straight through the gate to the page and the
// live video. Gating is opt-out: a credential a route never checks must never
// be a bypass on that route.
-func exemptExternalAPIRoutes(r *http.Request, _ string) bool {
+func exemptExternalAPIRoutes(r *http.Request, _ string, _ AuthGateSettings) bool {
return strings.HasPrefix(r.URL.Path, externalAPIPrefix)
}
+// exemptDirectoryAPI keeps the Owncast Directory protocol reachable. The
+// payload is public metadata by design (the directory fetches it anonymously,
+// it carries no registration token), so the gate never challenges it. When the
+// operator blocks public stream status the directory is disabled outright and
+// the YP handler itself answers 404, which is why this rule is unconditional.
+func exemptDirectoryAPI(r *http.Request, _ string, _ AuthGateSettings) bool {
+ return r.URL.Path == "/api/yp"
+}
+
+// exemptThirdPartyPlayerRoutes keeps the HLS playlist and segments reachable
+// for players that cannot complete a browser login (VLC, ffplay, mobile apps).
+// It applies only to the website-only access mode.
+//
+// Caveat: this only covers HLS served by Owncast. With an external storage
+// provider and a custom video serving endpoint the media never passes through
+// this middleware and cannot be gated here at all.
+func exemptThirdPartyPlayerRoutes(r *http.Request, _ string, settings AuthGateSettings) bool {
+ return !settings.protectsStream() && strings.HasPrefix(r.URL.Path, "/hls/")
+}
+
+// exemptStreamStatus keeps the public stream-status endpoint reachable so
+// uptime monitors and "is it live" tooling keep working behind a gate. It is
+// disabled only by the most restrictive access mode.
+func exemptStreamStatus(r *http.Request, _ string, settings AuthGateSettings) bool {
+ return !settings.blocksStreamStatusRequests() && r.URL.Path == "/api/status"
+}
+
// gateExemptionFor returns the name of the first exemption that applies, or ""
// if the request is subject to the gate.
-func gateExemptionFor(r *http.Request, gateSlug string) string {
+func gateExemptionFor(r *http.Request, gateSlug string, settings AuthGateSettings) string {
for _, e := range gateExemptions {
- if e.allow(r, gateSlug) {
+ if e.allow(r, gateSlug, settings) {
return e.name
}
}
@@ -149,7 +179,7 @@ func gateExemptionFor(r *http.Request, gateSlug string) string {
// signing secret exists (without one an armed gate can't verify sessions, so it
// fails closed); sessionValid reports whether the request carries a valid
// session cookie (the middleware verifies it once, up front).
-func decideGate(r *http.Request, gateSlug string, gateLoaded bool, secretConfigured bool, sessionValid bool) (gateOutcome, string) {
+func decideGate(r *http.Request, gateSlug string, gateLoaded bool, secretConfigured bool, sessionValid bool, settings AuthGateSettings) (gateOutcome, string) {
// Gate off: no enabled auth.gate plugin.
if gateSlug == "" {
return gateAllow, ""
@@ -166,7 +196,7 @@ func decideGate(r *http.Request, gateSlug string, gateLoaded bool, secretConfigu
// Explicit, opt-out policy: anything on the named exemption list bypasses
// the gate (this also keeps admin + the gate plugin's own routes reachable
// while the gate is unavailable, so a broken gate can be recovered from).
- if gateExemptionFor(r, gateSlug) != "" {
+ if gateExemptionFor(r, gateSlug, settings) != "" {
return gateAllow, ""
}
@@ -189,55 +219,66 @@ func decideGate(r *http.Request, gateSlug string, gateLoaded bool, secretConfigu
func (h *Host) AuthGateMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- now := time.Now().Unix()
- secretConfigured := len(h.authSecret) > 0
-
- // Verify the session once, up front, and propagate the identity it
- // carries into the request context — for ALL requests with a valid
- // cookie, including exempt paths (so the gate plugin's own login
- // screen can tell the viewer is already signed in) and chat (/ws).
- sessionValid := false
- sessionToken := ""
- if secretConfigured {
- if token, ok := plugins.SessionFromRequest(h.authSecret, r, now); ok {
- sessionValid = true
- sessionToken = token
- r = r.WithContext(plugins.WithSessionToken(r.Context(), token))
- }
- }
-
slug, loaded := h.manager.ActiveAuthGate()
- outcome, loginURL := decideGate(r, slug, loaded, secretConfigured, sessionValid)
- switch outcome {
- case gateAllow:
- // On the viewer's page load, let the active gate plugin
- // re-validate (and optionally revoke or refresh) the session via
- // onAuthCheck. Only when the allow is due to a real session on a
- // non-exempt index navigation — not for exempt paths or API/asset
- // requests.
- if sessionValid && slug != "" && isIndexNavigation(r) && gateExemptionFor(r, slug) == "" {
- h.runAuthCheckOnIndex(w, r, next, slug, sessionToken)
- return
- }
- next.ServeHTTP(w, r)
- case gateUnavailable:
- w.Header().Set("Content-Type", "text/html; charset=utf-8")
- w.WriteHeader(http.StatusServiceUnavailable)
- _, _ = io.WriteString(w, authUnavailableHTML)
- case gateLogin:
- // Redirect navigations; 401 anything else so XHR/API callers
- // get a status they can act on instead of an HTML body.
- if r.Method == http.MethodGet || r.Method == http.MethodHead {
- //nolint:gosec // G710: loginURL is a same-origin /plugins/<slug>/ path with a query-escaped return_to, not attacker-controlled.
- http.Redirect(w, r, loginURL, http.StatusFound)
- } else {
- http.Error(w, "authentication required", http.StatusUnauthorized)
- }
- }
+ h.serveGated(w, r, next, slug, loaded)
})
}
}
+// serveGated applies the gate to one request against an already-resolved gate
+// state. Split from AuthGateMiddleware so the whole policy, including the
+// fail-closed branch, is reachable in tests without a running plugin runtime.
+func (h *Host) serveGated(w http.ResponseWriter, r *http.Request, next http.Handler, slug string, loaded bool) {
+ now := time.Now().Unix()
+ secretConfigured := len(h.authSecret) > 0
+
+ // Verify the session once, up front, and propagate the identity it
+ // carries into the request context — for ALL requests with a valid
+ // cookie, including exempt paths (so the gate plugin's own login
+ // screen can tell the viewer is already signed in) and chat (/ws).
+ sessionValid := false
+ sessionToken := ""
+ if secretConfigured {
+ if token, ok := plugins.SessionFromRequest(h.authSecret, r, now); ok {
+ sessionValid = true
+ sessionToken = token
+ r = r.WithContext(plugins.WithSessionToken(r.Context(), token))
+ }
+ }
+
+ settings := defaultAuthGateSettings()
+ if slug != "" {
+ settings = h.authGateSettingsFor(slug)
+ }
+ outcome, loginURL := decideGate(r, slug, loaded, secretConfigured, sessionValid, settings)
+ switch outcome {
+ case gateAllow:
+ // On the viewer's page load, let the active gate plugin
+ // re-validate (and optionally revoke or refresh) the session via
+ // onAuthCheck. Only when the allow is due to a real session on a
+ // non-exempt index navigation — not for exempt paths or API/asset
+ // requests.
+ if sessionValid && slug != "" && isIndexNavigation(r) && gateExemptionFor(r, slug, settings) == "" {
+ h.runAuthCheckOnIndex(w, r, next, slug, sessionToken)
+ return
+ }
+ next.ServeHTTP(w, r)
+ case gateUnavailable:
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ _, _ = io.WriteString(w, authUnavailableHTML)
+ case gateLogin:
+ // Redirect navigations; 401 anything else so XHR/API callers
+ // get a status they can act on instead of an HTML body.
+ if r.Method == http.MethodGet || r.Method == http.MethodHead {
+ //nolint:gosec // G710: loginURL is a same-origin /plugins/<slug>/ path with a query-escaped return_to, not attacker-controlled.
+ http.Redirect(w, r, loginURL, http.StatusFound)
+ } else {
+ http.Error(w, "authentication required", http.StatusUnauthorized)
+ }
+ }
+}
+
// authVerdict is the JSON a gate plugin's onAuthCheck returns.
type authVerdict struct {
Action string `json:"action"` // "ok" | "refresh" | "deny"
diff --git a/pluginhost/authgate_middleware_test.go b/pluginhost/authgate_middleware_test.go
new file mode 100644
index 0000000000..41a6b811ad
--- /dev/null
+++ b/pluginhost/authgate_middleware_test.go
@@ -0,0 +1,360 @@
+package pluginhost
+
+// End-to-end tests for the gate middleware itself, as opposed to the pure
+// decision in authgate_test.go. These exercise the parts that actually hold the
+// credential: cookie verification, the 302-vs-401 split, identity propagation
+// into the request context, and the onAuthCheck revocation path.
+//
+// serveGated takes the resolved gate state as arguments, so the whole policy —
+// including the fail-closed branch, which needs a gate that is enabled but not
+// running — is reachable without a wasm runtime.
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ plugins "github.com/owncast/owncast/services/plugins"
+ "github.com/owncast/owncast/services/plugins/kv"
+)
+
+const testGateSlug = "gate"
+
+var testAuthSecret = []byte("test-signing-secret-not-a-real-one")
+
+// gatedHost builds a Host wired for the gate middleware, with the access policy
+// pre-seeded so the settings read never touches storage.
+func gatedHost(t *testing.T, settings AuthGateSettings) *Host {
+ t.Helper()
+ h := &Host{authSecret: testAuthSecret, kv: kv.NewMemory()}
+ h.authGateSettings.Store(authGateSettingsSnapshot{slug: testGateSlug, settings: settings})
+ return h
+}
+
+// nextRecorder is the downstream handler. It records whether the gate let the
+// request through, and what identity it propagated.
+type nextRecorder struct {
+ served bool
+ token string
+}
+
+func (n *nextRecorder) handler() http.Handler {
+ return http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
+ n.served = true
+ n.token = plugins.SessionTokenFromContext(r.Context())
+ })
+}
+
+// sessionCookie returns a valid gate cookie for token, expiring in ttl.
+func sessionCookie(token string, ttl time.Duration) *http.Cookie {
+ signed := plugins.SignSession(testAuthSecret, token, time.Now().Add(ttl).Unix())
+ return plugins.NewSessionCookie(signed, ttl, false)
+}
+
+func TestServeGated_NoGateIsAPassthrough(t *testing.T) {
+ h := gatedHost(t, defaultAuthGateSettings())
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ h.serveGated(w, httptest.NewRequest(http.MethodGet, "/", nil), next.handler(), "", false)
+
+ if !next.served {
+ t.Fatal("no enabled gate must be a passthrough")
+ }
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+}
+
+func TestServeGated_AnonymousViewerIsRedirectedWithReturnTo(t *testing.T) {
+ h := gatedHost(t, defaultAuthGateSettings())
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ r := httptest.NewRequest(http.MethodGet, "/?utm=x", nil)
+ h.serveGated(w, r, next.handler(), testGateSlug, true)
+
+ if next.served {
+ t.Fatal("anonymous viewer reached the downstream handler")
+ }
+ if w.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302", w.Code)
+ }
+ want := "/plugins/" + testGateSlug + "/?return_to=%2F%3Futm%3Dx"
+ if got := w.Header().Get("Location"); got != want {
+ t.Fatalf("Location = %q, want %q", got, want)
+ }
+}
+
+// A browser navigation gets an HTML redirect; anything else gets a status an
+// XHR or API caller can act on.
+func TestServeGated_NonNavigationGets401(t *testing.T) {
+ for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodDelete} {
+ t.Run(method, func(t *testing.T) {
+ h := gatedHost(t, defaultAuthGateSettings())
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ h.serveGated(w, httptest.NewRequest(method, "/api/chat", nil), next.handler(), testGateSlug, true)
+
+ if next.served {
+ t.Fatal("unauthenticated request reached the downstream handler")
+ }
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("status = %d, want 401", w.Code)
+ }
+ })
+ }
+}
+
+func TestServeGated_ValidSessionPassesAndPropagatesIdentity(t *testing.T) {
+ h := gatedHost(t, defaultAuthGateSettings())
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ // Not the index: index navigation additionally runs onAuthCheck, which is
+ // covered separately below.
+ r := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ r.AddCookie(sessionCookie("access-token-123", time.Hour))
+ h.serveGated(w, r, next.handler(), testGateSlug, true)
+
+ if !next.served {
+ t.Fatalf("valid session was rejected (status %d)", w.Code)
+ }
+ if next.token != "access-token-123" {
+ t.Fatalf("propagated token = %q, want access-token-123", next.token)
+ }
+}
+
+// The credential is a signed cookie, so the gate must reject every way of
+// presenting a bad one. Each of these previously had no coverage above the
+// crypto primitive.
+func TestServeGated_RejectsBadCredentials(t *testing.T) {
+ valid := sessionCookie("access-token-123", time.Hour)
+
+ tests := []struct {
+ name string
+ cookie *http.Cookie
+ }{
+ {"no cookie", nil},
+ {"expired session", sessionCookie("access-token-123", -time.Minute)},
+ {"tampered payload", &http.Cookie{
+ Name: valid.Name,
+ Value: strings.Replace(valid.Value, valid.Value[:4], "AAAA", 1),
+ }},
+ {"signature stripped", &http.Cookie{
+ Name: valid.Name,
+ Value: strings.Split(valid.Value, ".")[0],
+ }},
+ {"garbage", &http.Cookie{Name: valid.Name, Value: "not-a-token"}},
+ {"token signed with another secret", func() *http.Cookie {
+ other := plugins.SignSession([]byte("a different secret"), "access-token-123", time.Now().Add(time.Hour).Unix())
+ return plugins.NewSessionCookie(other, time.Hour, false)
+ }()},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ h := gatedHost(t, defaultAuthGateSettings())
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ r := httptest.NewRequest(http.MethodGet, "/", nil)
+ if tc.cookie != nil {
+ r.AddCookie(tc.cookie)
+ }
+ h.serveGated(w, r, next.handler(), testGateSlug, true)
+
+ if next.served {
+ t.Fatal("gate accepted an invalid credential")
+ }
+ if w.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302 to login", w.Code)
+ }
+ })
+ }
+}
+
+// An armed gate whose plugin is not running must fail closed, and must not be
+// talked out of it by a would-be viewer.
+func TestServeGated_FailsClosedWhenGateUnavailable(t *testing.T) {
+ h := gatedHost(t, defaultAuthGateSettings())
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ h.serveGated(w, httptest.NewRequest(http.MethodGet, "/", nil), next.handler(), testGateSlug, false)
+
+ if next.served {
+ t.Fatal("request served while the gate was unavailable")
+ }
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want 503", w.Code)
+ }
+}
+
+// Losing the signing secret means sessions cannot be verified at all, so the
+// gate must close rather than wave everyone through.
+func TestServeGated_FailsClosedWithoutASigningSecret(t *testing.T) {
+ h := &Host{kv: kv.NewMemory()}
+ h.authGateSettings.Store(authGateSettingsSnapshot{slug: testGateSlug, settings: defaultAuthGateSettings()})
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ h.serveGated(w, httptest.NewRequest(http.MethodGet, "/", nil), next.handler(), testGateSlug, true)
+
+ if next.served {
+ t.Fatal("request served with no signing secret configured")
+ }
+ if w.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status = %d, want 503", w.Code)
+ }
+}
+
+// An operator must always be able to reach the admin API to disable a gate that
+// has broken the site, even while the gate is failing closed.
+func TestServeGated_AdminStaysReachableWhileFailingClosed(t *testing.T) {
+ h := gatedHost(t, AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus})
+ for _, path := range []string{"/admin/plugins", "/api/admin/plugins/gate/disable"} {
+ t.Run(path, func(t *testing.T) {
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ h.serveGated(w, httptest.NewRequest(http.MethodGet, path, nil), next.handler(), testGateSlug, false)
+
+ if !next.served {
+ t.Fatalf("admin path %s was blocked (status %d)", path, w.Code)
+ }
+ })
+ }
+}
+
+// The access modes, exercised through the real middleware rather than the pure
+// decision, including the status codes third-party clients actually see.
+func TestServeGated_AccessPolicyThroughMiddleware(t *testing.T) {
+ tests := []struct {
+ name string
+ settings AuthGateSettings
+ path string
+ wantPass bool
+ }{
+ {"website-only lets a player fetch the playlist", defaultAuthGateSettings(), "/hls/stream.m3u8", true},
+ {"website-only lets a monitor read status", defaultAuthGateSettings(), "/api/status", true},
+ {"website-only still gates the viewer page", defaultAuthGateSettings(), "/", false},
+ {"website-and-stream blocks the playlist", AuthGateSettings{AccessMode: AuthGateAccessWebsiteAndStream}, "/hls/stream.m3u8", false},
+ {"website-and-stream blocks segments", AuthGateSettings{AccessMode: AuthGateAccessWebsiteAndStream}, "/hls/0/stream0.ts", false},
+ {"website-and-stream leaves status public", AuthGateSettings{AccessMode: AuthGateAccessWebsiteAndStream}, "/api/status", true},
+ {"website-stream-and-status blocks status", AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus}, "/api/status", false},
+ {"website-stream-and-status also blocks HLS", AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus}, "/hls/stream.m3u8", false},
+ {"directory endpoint is never gate-challenged", AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus}, "/api/yp", true},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ h := gatedHost(t, tc.settings)
+ next := &nextRecorder{}
+ w := httptest.NewRecorder()
+
+ h.serveGated(w, httptest.NewRequest(http.MethodGet, tc.path, nil), next.handler(), testGateSlug, true)
+
+ if next.served != tc.wantPass {
+ t.Fatalf("%s: served = %v want %v (status %d)", tc.path, next.served, tc.wantPass, w.Code)
+ }
+ })
+ }
+}
+
+// denySession is the revocation primitive: a gate that says "this viewer is no
+// longer entitled" must actually strip the credential, not merely redirect. A
+// redirect alone would leave the cookie in place and the viewer signed in.
+func TestDenySession_ClearsTheCookieAndBounces(t *testing.T) {
+ h := gatedHost(t, defaultAuthGateSettings())
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest(http.MethodGet, "/", nil)
+ r.AddCookie(sessionCookie("access-token-123", time.Hour))
+
+ h.denySession(w, r, testGateSlug, false)
+
+ if w.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302", w.Code)
+ }
+ cookies := w.Result().Cookies()
+ if len(cookies) != 1 {
+ t.Fatalf("got %d cookies, want exactly the cleared session cookie", len(cookies))
+ }
+ cleared := cookies[0]
+ if cleared.Value != "" || cleared.MaxAge >= 0 {
+ t.Fatalf("session cookie was not cleared: value=%q maxAge=%d", cleared.Value, cleared.MaxAge)
+ }
+
+ // Prove it: a request replaying the cleared cookie no longer authenticates.
+ replay := httptest.NewRequest(http.MethodGet, "/", nil)
+ replay.AddCookie(cleared)
+ if _, ok := plugins.SessionFromRequest(testAuthSecret, replay, time.Now().Unix()); ok {
+ t.Fatal("cleared cookie still verifies as a valid session")
+ }
+}
+
+// The refresh verdict re-issues the cookie for sliding expiry. The new cookie
+// must carry the same identity and still verify.
+func TestRefreshedSessionCookieStaysValid(t *testing.T) {
+ ttl := plugins.ClampSessionTTL(0)
+ refreshed := plugins.SignSession(testAuthSecret, "access-token-123", time.Now().Add(ttl).Unix())
+ cookie := plugins.NewSessionCookie(refreshed, ttl, false)
+
+ r := httptest.NewRequest(http.MethodGet, "/", nil)
+ r.AddCookie(cookie)
+
+ token, ok := plugins.SessionFromRequest(testAuthSecret, r, time.Now().Unix())
+ if !ok {
+ t.Fatal("refreshed cookie does not verify")
+ }
+ if token != "access-token-123" {
+ t.Fatalf("refreshed token = %q, want access-token-123", token)
+ }
+}
+
+// onAuthCheck runs only where the gate intends it to: a viewer landing on the
+// page. It must not fire on assets, API calls, or exempt paths, or a revocation
+// check would run on the HLS hot path.
+func TestIsIndexNavigation(t *testing.T) {
+ tests := []struct {
+ method string
+ path string
+ want bool
+ }{
+ {http.MethodGet, "/", true},
+ {http.MethodHead, "/", true},
+ {http.MethodPost, "/", false},
+ {http.MethodGet, "/index.html", false},
+ {http.MethodGet, "/api/config", false},
+ {http.MethodGet, "/hls/0/stream0.ts", false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.method+" "+tc.path, func(t *testing.T) {
+ if got := isIndexNavigation(httptest.NewRequest(tc.method, tc.path, nil)); got != tc.want {
+ t.Fatalf("isIndexNavigation = %v want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+// callAuthCheck must report an error (which the caller turns into a deny) when
+// it cannot build the identity to hand the plugin, rather than returning a
+// zero verdict that reads as "ok".
+func TestCallAuthCheck_FailsClosedWithoutAnIdentity(t *testing.T) {
+ t.Run("no user resolver wired", func(t *testing.T) {
+ h := &Host{}
+ if _, err := h.callAuthCheck(t.Context(), testGateSlug, "tok"); err == nil {
+ t.Fatal("expected an error when no user resolver is configured")
+ }
+ })
+
+ t.Run("token resolves to no user", func(t *testing.T) {
+ h := &Host{userByToken: func(string) *plugins.HostUser { return nil }}
+ if _, err := h.callAuthCheck(t.Context(), testGateSlug, "tok"); err == nil {
+ t.Fatal("expected an error when the token resolves to no user")
+ }
+ })
+}
diff --git a/pluginhost/authgate_settings_test.go b/pluginhost/authgate_settings_test.go
new file mode 100644
index 0000000000..1055c45255
--- /dev/null
+++ b/pluginhost/authgate_settings_test.go
@@ -0,0 +1,241 @@
+package pluginhost
+
+// Tests for the admin-facing access-policy endpoint and the settings store
+// behind it. The endpoint decides what an operator can change and for which
+// plugin, and the store decides what the gate enforces on every request, so
+// both need to be honest about failure.
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/owncast/owncast/services/plugins"
+ "github.com/owncast/owncast/services/plugins/kv"
+)
+
+// hostWithDiscoveredPlugins writes one .ocpkg per manifest into a temp plugins
+// directory and starts a real Manager over it, so IsAuthGate is answered from
+// genuine manifest discovery rather than a stub.
+func hostWithDiscoveredPlugins(t *testing.T, manifests map[string][]byte) *Host {
+ t.Helper()
+ dir := t.TempDir()
+ for slug, manifest := range manifests {
+ pkg := buildPackageBytes(t, manifest, []byte("\x00asm\x01\x00\x00\x00"))
+ if err := os.WriteFile(filepath.Join(dir, slug+".ocpkg"), pkg, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ mgr := plugins.NewManager(dir, &plugins.HostEnv{})
+ if err := mgr.Start(t.Context()); err != nil {
+ t.Fatalf("manager start: %v", err)
+ }
+ t.Cleanup(func() { mgr.Stop(t.Context()) })
+ return &Host{manager: mgr, kv: kv.NewMemory()}
+}
+
+func gateManifest(slug string) []byte {
+ return []byte(`{
+ "api": "1",
+ "name": "` + slug + `",
+ "slug": "` + slug + `",
+ "version": "0.1.0",
+ "description": "auth gate fixture",
+ "permissions": ["auth.gate"]
+ }`)
+}
+
+func chatbotManifest(slug string) []byte {
+ return []byte(`{
+ "api": "1",
+ "name": "` + slug + `",
+ "slug": "` + slug + `",
+ "version": "0.1.0",
+ "description": "non-gate fixture",
+ "permissions": ["chat.send"]
+ }`)
+}
+
+func settingsRequest(t *testing.T, method, slug, body string) *http.Request {
+ t.Helper()
+ target := "/api/admin/plugins/" + slug + "/auth-settings"
+ if body == "" {
+ return httptest.NewRequest(method, target, nil)
+ }
+ return httptest.NewRequest(method, target, strings.NewReader(body))
+}
+
+// Settings must only be offered for plugins that can actually become the gate.
+// Exposing them elsewhere would imply a plugin controls site access when it
+// cannot.
+func TestAuthGateSettings_OnlyForPluginsDeclaringAuthGate(t *testing.T) {
+ h := hostWithDiscoveredPlugins(t, map[string][]byte{
+ "gate": gateManifest("gate"),
+ "chatbot": chatbotManifest("chatbot"),
+ })
+
+ t.Run("gate plugin is served", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ h.handleAuthGateSettings(w, settingsRequest(t, http.MethodGet, "gate", ""), "gate")
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ })
+
+ t.Run("non-gate plugin is not", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ h.handleAuthGateSettings(w, settingsRequest(t, http.MethodGet, "chatbot", ""), "chatbot")
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+ })
+
+ t.Run("unknown plugin is not", func(t *testing.T) {
+ w := httptest.NewRecorder()
+ h.handleAuthGateSettings(w, settingsRequest(t, http.MethodGet, "nope", ""), "nope")
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+ })
+}
+
+// The default is the compatibility contract: a freshly enabled gate protects
+// the website and nothing else.
+func TestAuthGateSettings_DefaultsAreWebsiteOnly(t *testing.T) {
+ h := hostWithDiscoveredPlugins(t, map[string][]byte{"gate": gateManifest("gate")})
+ w := httptest.NewRecorder()
+
+ h.handleAuthGateSettings(w, settingsRequest(t, http.MethodGet, "gate", ""), "gate")
+
+ var got AuthGateSettings
+ if err := json.NewDecoder(w.Body).Decode(&got); err != nil {
+ t.Fatal(err)
+ }
+ if got.AccessMode != AuthGateAccessWebsiteOnly {
+ t.Fatalf("default access mode = %q, want %q", got.AccessMode, AuthGateAccessWebsiteOnly)
+ }
+}
+
+func TestAuthGateSettings_SaveThenReadBack(t *testing.T) {
+ h := hostWithDiscoveredPlugins(t, map[string][]byte{"gate": gateManifest("gate")})
+
+ post := httptest.NewRecorder()
+ body := `{"accessMode":"website-stream-and-status"}`
+ h.handleAuthGateSettings(post, settingsRequest(t, http.MethodPost, "gate", body), "gate")
+ if post.Code != http.StatusOK {
+ t.Fatalf("save status = %d, want 200: %s", post.Code, post.Body)
+ }
+
+ // Read back through the endpoint.
+ get := httptest.NewRecorder()
+ h.handleAuthGateSettings(get, settingsRequest(t, http.MethodGet, "gate", ""), "gate")
+ var got AuthGateSettings
+ if err := json.NewDecoder(get.Body).Decode(&got); err != nil {
+ t.Fatal(err)
+ }
+ if got.AccessMode != AuthGateAccessWebsiteStreamAndStatus {
+ t.Fatalf("read back access mode = %q, want %q", got.AccessMode, AuthGateAccessWebsiteStreamAndStatus)
+ }
+
+ // And through the path the gate itself uses on every request.
+ if enforced := h.authGateSettingsFor("gate"); enforced != got {
+ t.Fatalf("enforced %+v != stored %+v", enforced, got)
+ }
+}
+
+// A saved policy has to survive the in-memory cache being dropped, otherwise
+// the gate would silently revert to defaults after a restart.
+func TestAuthGateSettings_SurviveACacheReset(t *testing.T) {
+ h := hostWithDiscoveredPlugins(t, map[string][]byte{"gate": gateManifest("gate")})
+ if err := h.saveAuthGateSettings("gate", AuthGateSettings{AccessMode: AuthGateAccessWebsiteAndStream}); err != nil {
+ t.Fatal(err)
+ }
+
+ h.authGateSettings.Store(authGateSettingsSnapshot{})
+ if got := h.authGateSettingsFor("gate"); got.AccessMode != AuthGateAccessWebsiteAndStream {
+ t.Fatalf("after cache reset got %q, want %q", got.AccessMode, AuthGateAccessWebsiteAndStream)
+ }
+}
+
+func TestAuthGateSettings_RejectsBadInput(t *testing.T) {
+ h := hostWithDiscoveredPlugins(t, map[string][]byte{"gate": gateManifest("gate")})
+
+ tests := []struct {
+ name string
+ body string
+ }{
+ {"malformed JSON", `{"accessMode":`},
+ {"wrong value type", `{"accessMode":true}`},
+ {"unsupported mode", `{"accessMode":"status-only"}`},
+ {"missing mode", `{}`},
+ {"unknown field", `{"accessMode":"website-only","protectEverything":true}`},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ h.handleAuthGateSettings(w, settingsRequest(t, http.MethodPost, "gate", tc.body), "gate")
+ if w.Code != http.StatusBadRequest {
+ t.Fatalf("status = %d, want 400", w.Code)
+ }
+ if got := h.authGateSettingsFor("gate"); got.AccessMode != AuthGateAccessWebsiteOnly {
+ t.Fatalf("rejected input changed the access mode: %q", got.AccessMode)
+ }
+ })
+ }
+}
+
+func TestAuthGateSettings_RejectsUnsupportedMethods(t *testing.T) {
+ h := hostWithDiscoveredPlugins(t, map[string][]byte{"gate": gateManifest("gate")})
+ for _, method := range []string{http.MethodPut, http.MethodDelete, http.MethodPatch} {
+ t.Run(method, func(t *testing.T) {
+ w := httptest.NewRecorder()
+ h.handleAuthGateSettings(w, settingsRequest(t, method, "gate", `{}`), "gate")
+ if w.Code != http.StatusMethodNotAllowed {
+ t.Fatalf("status = %d, want 405", w.Code)
+ }
+ })
+ }
+}
+
+// A corrupt or unreadable stored policy must fall back to the documented
+// defaults rather than to whatever a partial decode produced, and must not be
+// cached, so a later good read still wins.
+func TestAuthGateSettingsFor_CorruptValueFallsBackToDefaults(t *testing.T) {
+ h := &Host{kv: kv.NewMemory()}
+ h.authGateSettings.Store(authGateSettingsSnapshot{})
+ if err := h.kv.Namespace("gate").Set(authGateSettingsKey, []byte("{not json")); err != nil {
+ t.Fatal(err)
+ }
+
+ if got := h.authGateSettingsFor("gate"); got != defaultAuthGateSettings() {
+ t.Fatalf("corrupt settings produced %+v, want defaults", got)
+ }
+
+ // Not cached: writing a good value takes effect without a restart.
+ if err := h.saveAuthGateSettings("gate", AuthGateSettings{AccessMode: AuthGateAccessWebsiteAndStream}); err != nil {
+ t.Fatal(err)
+ }
+ if got := h.authGateSettingsFor("gate"); got.AccessMode != AuthGateAccessWebsiteAndStream {
+ t.Fatalf("after repair got %q, want %q", got.AccessMode, AuthGateAccessWebsiteAndStream)
+ }
+}
+
+// DirectoryAvailable is what YP consults before pinging the directory and
+// before answering /api/yp. A plugin that merely declares auth.gate, without
+// being enabled as the active gate, must not switch the directory off.
+// (Enforcement of the "off" case lives in the YP service and is tested there.)
+func TestDirectoryAvailable_UnenabledPluginPolicyIsIgnored(t *testing.T) {
+ h := hostWithDiscoveredPlugins(t, map[string][]byte{"gate": gateManifest("gate")})
+ h.authGateSettings.Store(authGateSettingsSnapshot{
+ slug: "gate",
+ settings: AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus},
+ })
+
+ if !h.DirectoryAvailable() {
+ t.Fatal("a discovered-but-not-enabled plugin's policy must not disable the directory")
+ }
+}
diff --git a/pluginhost/authgate_test.go b/pluginhost/authgate_test.go
index 53fbfb0fae..2791c84d4c 100644
--- a/pluginhost/authgate_test.go
+++ b/pluginhost/authgate_test.go
@@ -36,14 +36,14 @@ func TestDecideGate(t *testing.T) {
{"valid session survives a gate-plugin outage", newReq("GET", "/", ""), "github-auth", false, true, true, gateAllow},
{"external-api route allowed", newReq("GET", "/api/integrations/status", "Bearer xyz"), "github-auth", true, true, false, gateAllow},
// An Authorization header must NOT be a bypass on routes that never
- // check it — these are the gate-defeat vectors the exemption scoping fixes.
+ // check it. The HLS case below is public by explicit policy.
{"auth header on viewer page is gated", newReq("GET", "/", "Bearer xyz"), "github-auth", true, true, false, gateLogin},
- {"auth header on HLS segment is gated", newReq("GET", "/hls/0.ts", "anything"), "github-auth", true, true, false, gateLogin},
+ {"auth header on HLS segment is allowed in website-only mode", newReq("GET", "/hls/0.ts", "anything"), "github-auth", true, true, false, gateAllow},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- got, loginURL := decideGate(tc.req, tc.slug, tc.loaded, tc.secretConfigured, tc.sessionValid)
+ got, loginURL := decideGate(tc.req, tc.slug, tc.loaded, tc.secretConfigured, tc.sessionValid, defaultAuthGateSettings())
if got != tc.wantOutcome {
t.Fatalf("outcome: got %d want %d", got, tc.wantOutcome)
}
@@ -80,7 +80,7 @@ func TestGateExemptions(t *testing.T) {
{"external-api route exempt even without a header (route 401s itself)", req("/api/integrations/status", ""), "g", "external-api"},
// An Authorization header is NOT a bypass off the external-API namespace.
{"auth header on viewer page is NOT a bypass", req("/", "Bearer t"), "g", ""},
- {"auth header on HLS is NOT a bypass", req("/hls/0.ts", "Bearer t"), "g", ""},
+ {"auth header on HLS is allowed in website-only mode", req("/hls/0.ts", "Bearer t"), "g", "third-party-player"},
{"auth header on public api/config is NOT a bypass", req("/api/config", "Bearer t"), "g", ""},
// Real files in the embedded web build are exempt (resolved by fs.Stat).
{"admin stylesheet exempt", req("/styles/admin/chat.css", ""), "g", "static-assets"},
@@ -89,15 +89,116 @@ func TestGateExemptions(t *testing.T) {
// The SPA index is a page, not an asset → gated (would leak the viewer UI).
{"index.html is a page, gated", req("/index.html", ""), "g", ""},
// HLS media isn't in the web embed, so it's never matched here.
- {"HLS segment is NOT a web asset, stays gated", req("/hls/stream/0.ts", ""), "g", ""},
- {"plain viewer path is gated", req("/hls/0.ts", ""), "g", ""},
+ {"HLS segment is an external-player exemption", req("/hls/stream/0.ts", ""), "g", "third-party-player"},
+ {"plain viewer path is an external-player exemption", req("/hls/0.ts", ""), "g", "third-party-player"},
{"plugin path with no active gate is gated", req("/plugins/g", ""), "", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- if got := gateExemptionFor(tc.req, tc.gateSlug); got != tc.want {
+ if got := gateExemptionFor(tc.req, tc.gateSlug, defaultAuthGateSettings()); got != tc.want {
t.Fatalf("gateExemptionFor: got %q want %q", got, tc.want)
}
})
}
}
+
+// TestAuthGateAccessPolicyMatrix walks every access mode against the paths
+// whose treatment the mode is supposed to change, plus the paths it must never
+// change. Table-complete on purpose: this is the whole operator-facing
+// contract for what a gate does and does not cover.
+func TestAuthGateAccessPolicyMatrix(t *testing.T) {
+ websiteOnly := defaultAuthGateSettings()
+ websiteAndStream := AuthGateSettings{AccessMode: AuthGateAccessWebsiteAndStream}
+ websiteStreamAndStatus := AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus}
+
+ tests := []struct {
+ mode string
+ settings AuthGateSettings
+ path string
+ want gateOutcome
+ }{
+ // Website-only (the default): the viewer UI is the only thing gated.
+ {"website-only", websiteOnly, "/", gateLogin},
+ {"website-only", websiteOnly, "/embed/video", gateLogin},
+ {"website-only", websiteOnly, "/api/config", gateLogin},
+ {"website-only", websiteOnly, "/hls/stream.m3u8", gateAllow},
+ {"website-only", websiteOnly, "/hls/0/stream0.ts", gateAllow},
+ {"website-only", websiteOnly, "/api/status", gateAllow},
+ {"website-only", websiteOnly, "/api/yp", gateAllow},
+
+ // The second mode adds HLS while leaving status public.
+ {"website-and-stream", websiteAndStream, "/hls/stream.m3u8", gateLogin},
+ {"website-and-stream", websiteAndStream, "/hls/0/stream0.ts", gateLogin},
+ {"website-and-stream", websiteAndStream, "/api/status", gateAllow},
+ {"website-and-stream", websiteAndStream, "/api/yp", gateAllow},
+ {"website-and-stream", websiteAndStream, "/", gateLogin},
+
+ // The final mode adds stream status. The directory endpoint stays past
+ // the gate and is switched off by the YP handler instead.
+ {"website-stream-and-status", websiteStreamAndStatus, "/hls/0/stream0.ts", gateLogin},
+ {"website-stream-and-status", websiteStreamAndStatus, "/api/status", gateLogin},
+ {"website-stream-and-status", websiteStreamAndStatus, "/api/yp", gateAllow},
+
+ // No mode may ever re-gate the recovery or self-credentialed surfaces.
+ {"website-stream-and-status", websiteStreamAndStatus, "/admin", gateAllow},
+ {"website-stream-and-status", websiteStreamAndStatus, "/admin/plugins", gateAllow},
+ {"website-stream-and-status", websiteStreamAndStatus, "/api/admin/plugins", gateAllow},
+ {"website-stream-and-status", websiteStreamAndStatus, "/plugins/gate/", gateAllow},
+ {"website-stream-and-status", websiteStreamAndStatus, "/api/integrations/streamtitle", gateAllow},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.mode+" "+tc.path, func(t *testing.T) {
+ r := httptest.NewRequest(http.MethodGet, tc.path, nil)
+ got, _ := decideGate(r, "gate", true, true, false, tc.settings)
+ if got != tc.want {
+ t.Fatalf("%s %s: outcome got %d want %d", tc.mode, tc.path, got, tc.want)
+ }
+ })
+ }
+}
+
+// A valid session must outrank every access mode: a signed-in viewer never gets
+// bounced off a path the mode closed to anonymous callers.
+func TestAuthGateSessionOutranksPolicy(t *testing.T) {
+ settings := AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus}
+ for _, path := range []string{"/", "/hls/0/stream0.ts", "/api/status", "/api/config"} {
+ r := httptest.NewRequest(http.MethodGet, path, nil)
+ if got, _ := decideGate(r, "gate", true, true, true, settings); got != gateAllow {
+ t.Fatalf("%s with a valid session: got %d want gateAllow", path, got)
+ }
+ }
+}
+
+// An access mode must never turn a fail-closed gate into an open one, and a
+// broken gate must not start blocking paths the operator declared public.
+func TestAuthGateBrokenGateInteractsCorrectlyWithPolicy(t *testing.T) {
+ tests := []struct {
+ name string
+ path string
+ settings AuthGateSettings
+ loaded bool
+ secretConfigured bool
+ want gateOutcome
+ }{
+ {"gated path, plugin not loaded", "/", defaultAuthGateSettings(), false, true, gateUnavailable},
+ {"gated path, no signing secret", "/", defaultAuthGateSettings(), true, false, gateUnavailable},
+ {"protected stream, plugin not loaded", "/hls/0.ts", AuthGateSettings{AccessMode: AuthGateAccessWebsiteAndStream}, false, true, gateUnavailable},
+ {"blocked status, no signing secret", "/api/status", AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus}, true, false, gateUnavailable},
+ // Paths the mode leaves public stay public: a broken gate must not take
+ // down HLS or status for operators who never gated them.
+ {"public stream survives a broken gate", "/hls/0.ts", defaultAuthGateSettings(), false, true, gateAllow},
+ {"public status survives a broken gate", "/api/status", defaultAuthGateSettings(), false, true, gateAllow},
+ // And the recovery surfaces are always reachable.
+ {"admin survives a broken gate", "/admin/plugins", AuthGateSettings{AccessMode: AuthGateAccessWebsiteStreamAndStatus}, false, false, gateAllow},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ r := httptest.NewRequest(http.MethodGet, tc.path, nil)
+ got, _ := decideGate(r, "gate", tc.loaded, tc.secretConfigured, false, tc.settings)
+ if got != tc.want {
+ t.Fatalf("got %d want %d", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.go
index 83268d9c60..6c277c29bf 100644
--- a/pluginhost/pluginhost.go
+++ b/pluginhost/pluginhost.go
@@ -16,6 +16,7 @@ import (
"regexp"
"sort"
"strings"
+ "sync/atomic"
"time"
log "github.com/sirupsen/logrus"
@@ -44,9 +45,15 @@ import (
// 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"
+// JSON map keys used in the admin API's small status/error response bodies.
+const (
+ // jsonErrorKey surfaces a single human-readable error string to the admin UI.
+ jsonErrorKey = "error"
+ // jsonSlugKey echoes back the plugin a mutating request acted on.
+ jsonSlugKey = "slug"
+ // jsonStatusKey carries the "ok" acknowledgement of a mutating request.
+ jsonStatusKey = "status"
+)
// pluginsApprovedPermsConfigKey is the datastore key under which the
// per-plugin admin-approved permission snapshots are persisted (as a
@@ -114,9 +121,58 @@ type Host struct {
// userByToken resolves a viewer's identity from their access token, used by
// the onAuthCheck re-validation hook to build the identity it passes the
// gate plugin.
- userByToken func(token string) *plugins.HostUser
+ userByToken func(token string) *plugins.HostUser
+ authGateSettings atomic.Value
+}
+
+// AuthGateAccessMode is the operator-selected boundary of the viewer gate.
+// Modes are cumulative: each mode includes everything protected by the one
+// before it.
+type AuthGateAccessMode string
+
+const (
+ AuthGateAccessWebsiteOnly AuthGateAccessMode = "website-only"
+ AuthGateAccessWebsiteAndStream AuthGateAccessMode = "website-and-stream"
+ AuthGateAccessWebsiteStreamAndStatus AuthGateAccessMode = "website-stream-and-status"
+)
+
+// AuthGateSettings are host-owned settings for a plugin that declares
+// auth.gate.
+type AuthGateSettings struct {
+ AccessMode AuthGateAccessMode `json:"accessMode"`
+}
+
+func defaultAuthGateSettings() AuthGateSettings {
+ return AuthGateSettings{AccessMode: AuthGateAccessWebsiteOnly}
+}
+
+func (s AuthGateSettings) valid() bool {
+ switch s.AccessMode {
+ case AuthGateAccessWebsiteOnly,
+ AuthGateAccessWebsiteAndStream,
+ AuthGateAccessWebsiteStreamAndStatus:
+ return true
+ default:
+ return false
+ }
+}
+
+func (s AuthGateSettings) protectsStream() bool {
+ return s.AccessMode == AuthGateAccessWebsiteAndStream ||
+ s.AccessMode == AuthGateAccessWebsiteStreamAndStatus
+}
+
+func (s AuthGateSettings) blocksStreamStatusRequests() bool {
+ return s.AccessMode == AuthGateAccessWebsiteStreamAndStatus
+}
+
+type authGateSettingsSnapshot struct {
+ slug string
+ settings AuthGateSettings
}
+const authGateSettingsKey = "owncast.auth-gate-settings"
+
// runtimeActionsConfigKey is the reserved key inside a plugin's own
// config namespace that holds action buttons the plugin has added at
// runtime via owncast.actions.add. The host's Actions() reader returns
@@ -140,6 +196,7 @@ func readConfigOverrides(store kv.Store, slug string) map[string]any {
if err != nil || len(raw) == 0 {
return nil
}
+
var m map[string]any
if err := json.Unmarshal(raw, &m); err != nil {
return nil
@@ -147,6 +204,72 @@ func readConfigOverrides(store kv.Store, slug string) map[string]any {
return m
}
+// authGateSettingsFor returns the operator's access policy for a gate plugin,
+// memoized in a single-slot snapshot because it is read on every request,
+// including the per-segment HLS hot path.
+//
+// A storage failure or a corrupt value is not cached: it returns the
+// website-only default for this request and retries on the next one, rather
+// than pinning a wrong policy until restart.
+func (p *Host) authGateSettingsFor(slug string) AuthGateSettings {
+ snapshot, ok := p.authGateSettings.Load().(authGateSettingsSnapshot)
+ if ok && snapshot.slug == slug {
+ return snapshot.settings
+ }
+ defaults := defaultAuthGateSettings()
+ if p.kv == nil {
+ return defaults
+ }
+
+ raw, err := p.kv.Namespace(slug).Get(authGateSettingsKey)
+ if err != nil {
+ log.Warnf("plugin auth: could not read gate settings for %q, using defaults: %v", slug, err)
+ return defaults
+ }
+
+ settings := defaults
+ if len(raw) > 0 {
+ var stored AuthGateSettings
+ if err := json.Unmarshal(raw, &stored); err != nil {
+ log.Warnf("plugin auth: gate settings for %q are unreadable, using defaults: %v", slug, err)
+ return defaults
+ }
+ if !stored.valid() {
+ log.Warnf("plugin auth: gate settings for %q have unsupported access mode %q, using defaults", slug, stored.AccessMode)
+ return defaults
+ }
+ settings = stored
+ }
+ p.authGateSettings.Store(authGateSettingsSnapshot{slug: slug, settings: settings})
+ return settings
+}
+
+func (p *Host) saveAuthGateSettings(slug string, settings AuthGateSettings) error {
+ if !settings.valid() {
+ return fmt.Errorf("unsupported authentication access mode %q", settings.AccessMode)
+ }
+ data, err := json.Marshal(settings)
+ if err != nil {
+ return err
+ }
+ if p.kv == nil {
+ return fmt.Errorf("settings storage unavailable")
+ }
+ if err := p.kv.Namespace(slug).Set(authGateSettingsKey, data); err != nil {
+ return err
+ }
+ p.authGateSettings.Store(authGateSettingsSnapshot{slug: slug, settings: settings})
+ return nil
+}
+
+// DirectoryAvailable reports whether the active auth gate permits public
+// directory metadata. The most restrictive access mode disables directory
+// access along with public stream status.
+func (p *Host) DirectoryAvailable() bool {
+ slug, _ := p.manager.ActiveAuthGate()
+ return slug == "" || !p.authGateSettingsFor(slug).blocksStreamStatusRequests()
+}
+
// coerceConfigValue validates an incoming admin-set value against a config
// field's declared type and returns the normalized value to store. JSON decodes
// numbers as float64 and booleans as bool; we accept those and reject mismatches
@@ -726,7 +849,7 @@ func New(ctx context.Context, deps Deps) (*Host, error) {
log.Errorln("plugin auth: could not establish session signing secret:", err)
}
- return &Host{
+ host := &Host{
manager: manager,
sqlStore: sqlStore,
server: server,
@@ -745,7 +868,9 @@ func New(ctx context.Context, deps Deps) (*Host, error) {
hu := toHostUser(u)
return &hu
},
- }, nil
+ }
+ host.authGateSettings.Store(authGateSettingsSnapshot{})
+ return host, nil
}
// AdminHandler returns the HTTP handler for plugin management:
@@ -917,6 +1042,10 @@ func (p *Host) handlePluginAction(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write(data) //nolint:gosec // G705
return
}
+ if action == "auth-settings" {
+ p.handleAuthGateSettings(w, r, slug)
+ return
+ }
// GET/POST /api/admin/plugins/<slug>/config reads and writes the admin's
// overrides for the plugin's manifest-declared config fields. The admin UI
@@ -943,7 +1072,7 @@ func (p *Host) handlePluginAction(w http.ResponseWriter, r *http.Request) {
if action == "uninstall" {
log.Infof("plugin %q uninstalled by admin", slug)
}
- writeJSONResponse(w, http.StatusOK, map[string]string{"status": "ok", "slug": slug, "action": action})
+ writeJSONResponse(w, http.StatusOK, map[string]string{jsonStatusKey: "ok", jsonSlugKey: slug, "action": action})
}
// handlePluginConfig serves the admin config form's backend:
@@ -1009,13 +1138,40 @@ func (p *Host) handlePluginConfig(w http.ResponseWriter, r *http.Request, slug s
writeJSONResponse(w, http.StatusInternalServerError, map[string]string{jsonErrorKey: err.Error()})
return
}
- writeJSONResponse(w, http.StatusOK, map[string]string{"status": "ok", "slug": slug})
+ writeJSONResponse(w, http.StatusOK, map[string]string{jsonStatusKey: "ok", jsonSlugKey: slug})
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
+func (p *Host) handleAuthGateSettings(w http.ResponseWriter, r *http.Request, slug string) {
+ if !p.manager.IsAuthGate(slug) {
+ http.NotFound(w, r)
+ return
+ }
+
+ switch r.Method {
+ case http.MethodGet:
+ writeJSONResponse(w, http.StatusOK, p.authGateSettingsFor(slug))
+ case http.MethodPost:
+ var settings AuthGateSettings
+ decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&settings); err != nil || !settings.valid() {
+ http.Error(w, "invalid authentication access mode", http.StatusBadRequest)
+ return
+ }
+ if err := p.saveAuthGateSettings(slug, settings); err != nil {
+ writeJSONResponse(w, http.StatusInternalServerError, map[string]string{jsonErrorKey: err.Error()})
+ return
+ }
+ writeJSONResponse(w, http.StatusOK, map[string]string{jsonStatusKey: "ok", jsonSlugKey: slug})
+ default:
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ }
+}
+
// dispatchPluginAction calls the Manager method for one of the admin
// actions. Returns (operationError, true) for a known action, or
// (nil, false) when action is unrecognized.
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index 402da49252..1bc7962855 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -12,6 +12,7 @@ import (
"os"
"path/filepath"
"runtime/debug"
+ "slices"
"sort"
"strings"
"sync"
@@ -463,6 +464,16 @@ func (m *Manager) ConfigSchema(slug string) map[string]ConfigField {
return nil
}
+// IsAuthGate reports whether a discovered plugin declares the auth.gate
+// permission. It is used to expose host-owned authentication settings only for
+// plugins that can actually become the viewer-authentication gate.
+func (m *Manager) IsAuthGate(slug string) bool {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ d := m.discovered[slug]
+ return d != nil && declaresAuthGate(d.Permissions)
+}
+
// ScanInterval is how often the manager re-scans the plugins directory.
const ScanInterval = 2 * time.Second
@@ -605,7 +616,7 @@ func (m *Manager) ActiveAuthGate() (slug string, loaded bool) {
continue
}
d := m.discovered[name]
- if d == nil || !hasPerm(d.Permissions, PermAuthGate) {
+ if d == nil || !declaresAuthGate(d.Permissions) {
continue
}
_, isLoaded := m.loaded[name]
@@ -614,14 +625,10 @@ func (m *Manager) ActiveAuthGate() (slug string, loaded bool) {
return "", false
}
-// hasPerm reports whether perms contains want.
-func hasPerm(perms []string, want string) bool {
- for _, p := range perms {
- if p == want {
- return true
- }
- }
- return false
+// declaresAuthGate reports whether a manifest's permission list claims the
+// viewer-authentication gate.
+func declaresAuthGate(perms []string) bool {
+ return slices.Contains(perms, PermAuthGate)
}
// Snapshot returns the currently-loaded, active plugins. Dispatcher and Server
@@ -673,12 +680,12 @@ func (m *Manager) Enable(ctx context.Context, name string) error {
}
// Only one auth.gate plugin may be enabled at a time — the viewer-auth gate
// is singular (two gates would be ambiguous). Refuse to enable a second.
- if hasPerm(d.Permissions, PermAuthGate) {
+ if declaresAuthGate(d.Permissions) {
for other, on := range m.enabledSet {
if !on || other == name {
continue
}
- if od := m.discovered[other]; od != nil && hasPerm(od.Permissions, PermAuthGate) {
+ if od := m.discovered[other]; od != nil && declaresAuthGate(od.Permissions) {
m.mu.Unlock()
return fmt.Errorf("cannot enable %q: another authentication-gate plugin (%q) is already enabled; disable it first", d.Slug, od.Slug)
}
diff --git a/services/plugins/manager_authgate_test.go b/services/plugins/manager_authgate_test.go
index f9d1a73be7..485db4645d 100644
--- a/services/plugins/manager_authgate_test.go
+++ b/services/plugins/manager_authgate_test.go
@@ -73,3 +73,33 @@ func TestManager_ActiveAuthGate(t *testing.T) {
t.Fatalf("ActiveAuthGate with no gate: got %q want empty", slug)
}
}
+
+// IsAuthGate decides whether the admin UI offers host-owned access-policy
+// settings for a plugin. It must answer on the declared permission alone, not
+// on whether the plugin happens to be enabled, so an operator can review the
+// policy before arming the gate.
+func TestManager_IsAuthGate(t *testing.T) {
+ m := seedManager(
+ map[string]*DiscoveredEntry{
+ "gate-on": {Slug: "gate-on", Permissions: []string{PermAuthGate}},
+ "gate-off": {Slug: "gate-off", Permissions: []string{PermAuthGate}},
+ "chatbot": {Slug: "chatbot", Permissions: []string{"chat.send", "chat.history"}},
+ "nothing": {Slug: "nothing"},
+ },
+ map[string]bool{"gate-on": true, "chatbot": true},
+ nil,
+ )
+
+ cases := map[string]bool{
+ "gate-on": true,
+ "gate-off": true,
+ "chatbot": false,
+ "nothing": false,
+ "unknown": false,
+ }
+ for slug, want := range cases {
+ if got := m.IsAuthGate(slug); got != want {
+ t.Errorf("IsAuthGate(%q) = %v, want %v", slug, got, want)
+ }
+ }
+}
diff --git a/web/components/admin/plugins/AuthGateSettingsForm.tsx b/web/components/admin/plugins/AuthGateSettingsForm.tsx
new file mode 100644
index 0000000000..3db607a3f0
--- /dev/null
+++ b/web/components/admin/plugins/AuthGateSettingsForm.tsx
@@ -0,0 +1,99 @@
+import { FC, useEffect, useState } from 'react';
+import { Alert, Button, Form, Radio, Space, Spin, Typography, message } from 'antd';
+import { useTranslation } from 'next-export-i18n';
+import { Plugin } from '../../../interfaces/plugin';
+import { Localization } from '../../../types/localization';
+import { authGateSettingsUrl, fetchData } from '../../../utils/apis';
+
+const { Paragraph, Text } = Typography;
+
+type AuthGateAccessMode = 'website-only' | 'website-and-stream' | 'website-stream-and-status';
+
+type AuthGateSettings = {
+ accessMode: AuthGateAccessMode;
+};
+
+export const AuthGateSettingsForm: FC<{ plugin: Plugin }> = ({ plugin }) => {
+ const { t } = useTranslation();
+ const [form] = Form.useForm<AuthGateSettings>();
+ const [loading, setLoading] = useState(true);
+ const [saving, setSaving] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ setError(null);
+ fetchData(authGateSettingsUrl(plugin.slug))
+ .then(values => {
+ if (!cancelled) form.setFieldsValue(values);
+ })
+ .catch(() => {
+ if (!cancelled) setError(t(Localization.Admin.Plugins.authSettingsLoadError));
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [plugin.slug]);
+
+ const onFinish = async (values: AuthGateSettings) => {
+ setSaving(true);
+ setError(null);
+ try {
+ await fetchData(authGateSettingsUrl(plugin.slug), { method: 'POST', data: values });
+ message.success(t(Localization.Admin.Plugins.authSettingsSaved));
+ } catch (e: unknown) {
+ const errorMessage =
+ e instanceof Error ? e.message : t(Localization.Admin.Plugins.authSettingsSaveError);
+ setError(errorMessage);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (loading) return <Spin />;
+
+ return (
+ <Form form={form} layout="vertical" onFinish={onFinish}>
+ {error && <Alert type="error" message={error} style={{ marginBottom: 16 }} />}
+ <Paragraph>
+ <Text>{t(Localization.Admin.Plugins.authSettingsDescription)}</Text>
+ </Paragraph>
+ <Form.Item name="accessMode" label={t(Localization.Admin.Plugins.authSettingsAccessMode)}>
+ <Radio.Group>
+ <Space direction="vertical" size="middle">
+ <Radio value="website-only">
+ <Text strong>{t(Localization.Admin.Plugins.authSettingsWebsiteOnly)}</Text>
+ <br />
+ <Text type="secondary">
+ {t(Localization.Admin.Plugins.authSettingsWebsiteOnlyDescription)}
+ </Text>
+ </Radio>
+ <Radio value="website-and-stream">
+ <Text strong>{t(Localization.Admin.Plugins.authSettingsWebsiteAndStream)}</Text>
+ <br />
+ <Text type="secondary">
+ {t(Localization.Admin.Plugins.authSettingsWebsiteAndStreamDescription)}
+ </Text>
+ </Radio>
+ <Radio value="website-stream-and-status">
+ <Text strong>{t(Localization.Admin.Plugins.authSettingsWebsiteStreamAndStatus)}</Text>
+ <br />
+ <Text type="secondary">
+ {t(Localization.Admin.Plugins.authSettingsWebsiteStreamAndStatusDescription)}
+ </Text>
+ </Radio>
+ </Space>
+ </Radio.Group>
+ </Form.Item>
+ <Form.Item>
+ <Button type="primary" htmlType="submit" loading={saving}>
+ {t(Localization.Admin.Plugins.authSettingsSave)}
+ </Button>
+ </Form.Item>
+ </Form>
+ );
+};
diff --git a/web/components/admin/plugins/BrowseRegistry.tsx b/web/components/admin/plugins/BrowseRegistry.tsx
index 752e846ed8..c6a0fa1f8d 100644
--- a/web/components/admin/plugins/BrowseRegistry.tsx
+++ b/web/components/admin/plugins/BrowseRegistry.tsx
@@ -83,6 +83,7 @@ const categoryNameKey: Record<string, string> = {
video: Localization.Admin.Plugins.Categories.video,
analytics: Localization.Admin.Plugins.Categories.analytics,
games: Localization.Admin.Plugins.Categories.games,
+ 'viewer-ui': Localization.Admin.Plugins.Categories.viewerUi,
'admin-utilities': Localization.Admin.Plugins.Categories.adminUtilities,
examples: Localization.Admin.Plugins.Categories.examples,
other: Localization.Admin.Plugins.Categories.other,
diff --git a/web/components/admin/plugins/PluginDetail.tsx b/web/components/admin/plugins/PluginDetail.tsx
index 8136f5ab01..d4d1c9a5b2 100644
--- a/web/components/admin/plugins/PluginDetail.tsx
+++ b/web/components/admin/plugins/PluginDetail.tsx
@@ -8,6 +8,7 @@ import { Localization } from '../../../types/localization';
import { fetchText, pluginInstructionsUrl } from '../../../utils/apis';
import { permissionDescriptionKey } from './permissionDescriptions';
import { PluginConfigForm } from './PluginConfigForm';
+import { AuthGateSettingsForm } from './AuthGateSettingsForm';
import s from './PluginDetail.module.scss';
const { Title, Text, Paragraph } = Typography;
@@ -394,11 +395,27 @@ export const PluginDetail = ({ plugin }: PluginDetailProps) => {
: null,
[plugin, t],
);
+ const authGateSettingsTab = useMemo(
+ () =>
+ plugin.permissions?.includes(PluginPermission.AuthGate)
+ ? {
+ key: '__auth-settings',
+ label: (
+ <span>
+ <LockOutlined /> {t(Localization.Admin.Plugins.authSettingsTab)}
+ </span>
+ ),
+ children: <AuthGateSettingsForm plugin={plugin} />,
+ }
+ : null,
+ [plugin, t],
+ );
const tabs = useMemo(() => {
const base = [
...pageTabs,
permissionsTab,
+ ...(authGateSettingsTab ? [authGateSettingsTab] : []),
...(configTab ? [configTab] : []),
...(commandsTab ? [commandsTab] : []),
];
@@ -406,7 +423,7 @@ export const PluginDetail = ({ plugin }: PluginDetailProps) => {
// 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, configTab, commandsTab]);
+ }, [instructionsTab, pageTabs, permissionsTab, authGateSettingsTab, configTab, commandsTab]);
return (
<div>
diff --git a/web/i18n/en/translation.json b/web/i18n/en/translation.json
index ce697a4f1e..5453d7fb4c 100644
--- a/web/i18n/en/translation.json
+++ b/web/i18n/en/translation.json
@@ -1,493 +1,504 @@
{
- "Admin": {
- "AccessTokens": {
- "createNewAccessToken": "Create New Access token",
- "nameDescription": "The name will be displayed as the chat user when sending messages with this access token.",
- "namePlaceholder": "Name of bot, service, or integration",
- "selectAll": "Select all",
- "selectPermissions": "Select the permissions this access token will have. It cannot be edited after it's created."
- },
- "Actions": {
- "createNewAction": "Create New Action",
- "createNewActionTitle": "Create New Action",
- "customHtml": "Custom HTML",
- "description": "External action URLs are 3rd party UI you can display, embedded, into your Owncast page when a user clicks on a button to launch your action.",
- "descriptionPlaceholder": "Optional description",
- "editActionTitle": "Edit Action",
- "htmlEmbedPlaceholder": "HTML embed code (required)",
- "iconPlaceholder": "https://myserver.com/action/icon.png (optional)",
- "linkOrEmbedUrl": "Link or embed an URL",
- "modalDescription": "Add the URL for the external action you want to present.",
- "onlyHttpsSupported": "Only HTTPS URLs and embeds are supported.",
- "openExternally": "Open in a new tab instead of within your page.",
- "optionalBackgroundColor": "Optional background color of the action button.",
- "readMoreAboutActions": "Read more about external actions.",
- "readMoreLink": "Read more about how to use actions, with examples, at",
- "selectActionType": "Select an action type",
- "title": "External Actions",
- "titlePlaceholder": "Your action title (required)",
- "urlPlaceholder": "https://myserver.com/action (required)"
- },
- "Appearance": {
- "alsoSetByPlugin": "also set by {{plugins}}",
- "alsoSetByPluginTooltip": "Your value takes priority here. Use Reset to Defaults to fall back to the color from {{plugins}}.",
- "pluginStylingActive": "Plugin styling is active",
- "pluginStylingDescription": "These plugins are applying their own styles to your site, combined with the colors you set here: {{plugins}}. Your settings are applied on top, so they win where they overlap. If the page doesn't look the way you expect, use Reset to Defaults below to let the plugin styling show through, or disable the plugin from the Plugins page."
- },
- "Autoplay": {
- "description": "Choose whether the stream starts playing on its own when a viewer opens your page.",
- "optionAlwaysDescription": "The stream always starts on its own the moment someone opens the page. It plays with sound where the browser allows it, and starts muted everywhere else.",
- "optionAlwaysLabel": "Always",
- "optionOffDescription": "Viewers will press play to start watching.",
- "optionOffLabel": "Never",
- "optionSoundOnlyDescription": "The stream starts on its own, but only when the viewer's browser allows sound to play as well. Otherwise the viewer presses play. It never starts silently. Different browsers handle this differently.",
- "optionSoundOnlyLabel": "Only if sound is available",
- "title": "Autoplay"
- },
- "EditFavicon": {
- "label": "Favicon",
- "resetButton": "Reset",
- "resetConfirmCancel": "No",
- "resetConfirmOk": "Yes",
- "resetConfirmTitle": "Reset to default favicon?",
- "tip": "Upload a custom favicon (PNG or ICO format, max 200KB). This icon appears in browser tabs and bookmarks."
- },
- "EditInstanceDetails": {
- "directoryDescription": "Increase your audience by appearing in the <a href=\"https://owncast.directory\" target=\"_blank\" rel=\"noreferrer\"><strong>Owncast Directory</strong></a>. This is an external service run by the Owncast project. <a href=\"https://owncast.online/docs/directory/?source=admin\" target=\"_blank\" rel=\"noopener noreferrer\">Learn more</a>.",
- "offlineMessageDescription": "The offline message is displayed to your page visitors when you're not streaming. Markdown is supported.",
- "serverUrlRequiredForDirectory": "You must set your <strong>Server URL</strong> above to enable the directory."
- },
- "FeaturedStreams": {
- "actions": "Actions",
- "added": "Added",
- "approveButton": "Approve",
- "approvalResent": "Approval resent.",
- "confirmNo": "No",
- "confirmYes": "Yes",
- "directoryListingsDescription": "These directories follow your server so they can list your stream. Each one receives your live status. Remove one to stop sending it your status and drop your server from its listing.",
- "directoryListingsEmpty": "No directories are featuring your stream yet.",
- "directoryListingsTitle": "Directories listing you",
- "directoryRemoved": "Removed from the directory.",
- "enterStreamUrl": "Please enter a stream URL",
- "enterValidUrl": "Please enter a valid URL",
- "failedToApprove": "Failed to approve the feature request",
- "failedToFeature": "Failed to feature stream",
- "failedToReject": "Failed to reject the feature request",
- "failedToRemoveDirectory": "Failed to remove from the directory.",
- "failedToResendApproval": "Failed to resend the approval.",
- "failedToUnfeature": "Failed to unfeature the stream",
- "featureRequestApproved": "Feature request approved",
- "featureRequestRejected": "Feature request rejected",
- "featureRequestsDescription": "These Owncast servers have asked to show your stream in their featured streams directory. Approve a server to let it display your live status.",
- "featureRequestsTitle": "Requests to feature your stream",
- "featureStreamAction": "Feature Stream",
- "featureStreamButton": "Feature Live Stream",
- "featuringYouTab": "Featuring you",
- "federationSettings": "Federation settings",
- "lastChecked": "Last Checked",
- "modalTitle": "Feature Live Stream",
- "never": "Never",
- "offline": "Offline",
- "online": "Online",
- "onlyDefaultPortSupported": "Only the default HTTPS port (443) is supported",
- "onlyHttpsSupported": "Only HTTPS URLs are supported",
- "pageDescription": "Feature other Owncast streams to display their streaming status on your server. When enabled, visitors can discover and navigate to other featured streams through a dedicated \"Featured\" tab on your main page.",
- "pageDescriptionSecondary": "This creates a network effect, allowing users to discover and navigate to other Owncast servers easily. It also gives visitors somewhere to go if your stream is offline.",
- "pageTitle": "Featured Streams",
- "pendingApproval": "Pending approval",
- "rejectButton": "Reject",
- "removeFromDirectoryButton": "Remove",
- "removeFromDirectoryConfirm": "Remove your server from this directory?",
- "resendApprovalButton": "Resend approval",
- "requirementDefaultPort": "The stream must be on the default HTTPS port (443)",
- "requirementFeaturedStreams": "The stream must support featured streams",
- "requirementHttps": "The stream must be accessible via HTTPS",
- "requirementOwncast": "The stream must be an Owncast instance",
- "socialFeaturesRequired": "Social features must be enabled",
- "socialFeaturesRequiredDesc": "before you can feature other streams.",
- "status": "Status",
- "streamFeaturedSuccess": "Stream featured",
- "streamName": "Stream Name",
- "streamRequirements": "Stream Requirements",
- "streamTitle": "Stream Title",
- "streamUnfeaturedSuccess": "Stream unfeatured",
- "streamUrlHelp": "Enter the URL of an Owncast stream (e.g., stream.example.com)",
- "streamUrlLabel": "Stream URL",
- "streamUrlPlaceholder": "stream.example.com",
- "streamsYouFeatureTab": "Streams you feature",
- "unfeatureButton": "Unfeature",
- "unfeatureConfirm": "Unfeature {{name}}?",
- "unsupportedFeaturedStreams": "This Owncast server does not support featured streams yet. Ask the server owner to upgrade Owncast.",
- "url": "URL"
- },
- "HardwareInfo": {
- "cpu": "CPU",
- "disk": "Disk",
- "memory": "Memory",
- "noDetails": "No hardware details have been collected yet.",
- "pleaseWait": "Please wait",
- "title": "Hardware Info",
- "used": "used"
- },
- "Help": {
- "bugButton": "Report an issue",
- "bugDescription": "If something seems broken, let us know so it can be fixed.",
- "bugTitle": "Found a bug?",
- "commonTasks": "Common tasks",
- "communityButton": "Join the community chat",
- "communityDescription": "Chat with the Owncast community on Matrix. It's the fastest way to get answers.",
- "communityTitle": "Have a question?",
- "copied": "Copied to clipboard.",
- "copySupportInfo": "Copy support info",
- "discussions": "GitHub discussions",
- "documentation": "Documentation",
- "fediverse": "Follow Owncast on the Fediverse",
- "fixButton": "Troubleshooting guide",
- "fixDescription": "Work through common problems with the troubleshooting guide.",
- "fixTitle": "Something not working?",
- "gettingStarted": "It doesn't look like you've streamed yet. The quickstart guide walks you through sending your first stream.",
- "gettingStartedLink": "Read the quickstart",
- "groupCustomize": "Customize",
- "groupExtend": "Extend Owncast",
- "groupGrow": "Grow your audience",
- "groupSetup": "Set up your stream",
- "learnMore": "Learn more",
- "moreResources": "More resources",
- "openSettings": "Open settings",
- "releaseNotes": "Release notes",
- "searchPlaceholder": "Search the documentation",
- "supportInfo": "Support info",
- "supportInfoDescription": "Copy your server's version, video configuration and recent errors to include when reporting a bug or asking for help.",
- "taskApis": "Build add-ons with the developer APIs",
- "taskBroadcasting": "Connect your broadcasting software",
- "taskChat": "Manage chat and moderation",
- "taskDirectory": "List your stream in the directory",
- "taskEmbed": "Embed your stream into another site",
- "taskFediverse": "Share your stream on the Fediverse",
- "taskNotifications": "Notify viewers when you go live",
- "taskPlugins": "Add functionality with plugins",
- "taskSsl": "Set up SSL and proxies",
- "taskStorage": "Use external storage or a CDN",
- "taskVideoQuality": "Tweak video quality and latency",
- "taskWebsite": "Customize your website and appearance",
- "title": "How can we help you?",
- "upgradeAvailable": "A new version of Owncast is available.",
- "upgradeLink": "Visit the upgrade page"
- },
- "LogTable": {
- "error": "Error",
- "info": "Info",
- "level": "Level",
- "logs": "Logs",
- "message": "Message",
- "timestamp": "Timestamp",
- "warning": "Warning"
- },
- "NewsFeed": {
- "link": "Link",
- "noNews": "No news.",
- "title": "News & Updates from Owncast"
- },
- "Plugins": {
- "Categories": {
- "adminUtilities": "Admin utilities",
- "analytics": "Analytics & stats",
- "authentication": "Authentication",
- "chatBots": "Chat bots",
- "chatFilters": "Chat filters",
- "examples": "Examples",
- "games": "Games & fun",
- "integrations": "Integrations",
- "moderation": "Moderation",
- "notifications": "Notifications",
- "other": "Other",
- "overlays": "Overlays & widgets",
- "themes": "Themes",
- "video": "Video & streaming"
- },
- "PermissionNames": {
- "authGate": "Gate viewer access",
- "chatFilter": "Filter chat messages",
- "chatHistory": "Read chat history",
- "chatModerate": "Moderate chat",
- "chatSend": "Send chat messages",
- "eventsEmit": "Emit events",
- "fediverseInbound": "Receive fediverse activity",
- "fediversePost": "Post to the fediverse",
- "httpServe": "Serve HTTP",
- "httpSse": "Push realtime updates",
- "networkFetch": "Make outbound HTTP requests",
- "notificationsSend": "Send notifications",
- "serverRead": "Read server state",
- "storageFs": "Read and write files",
- "storageKv": "Store data",
- "storageSql": "SQL database",
- "storageUpload": "Upload files",
- "uiModify": "Add UI elements",
- "usersModerate": "Moderate users",
- "usersRead": "Read user list",
- "usersRegister": "Sign in viewers",
- "videoconfigRead": "Read video settings",
- "videoconfigWrite": "Change video settings"
- },
- "Permissions": {
- "authGate": "Act as a viewer-authentication gate, signing viewers in and controlling their access to the site.",
- "chatFilter": "Inspect and modify chat messages before they are broadcast, or drop them entirely.",
- "chatHistory": "Read recent chat messages.",
- "chatModerate": "Hide chat messages and ban users.",
- "chatSend": "Post chat messages as the plugin’s own bot identity.",
- "eventsEmit": "Publish custom events that other plugins can subscribe to.",
- "fediverseInbound": "Receive verified inbound fediverse activity, including follows, likes, reposts, quotes, mentions, replies, and raw activities.",
- "fediversePost": "Post a public note to the fediverse from the configured Owncast account.",
- "httpServe": "Serve HTTP requests at /plugins/<name>/ (static assets and a dynamic handler).",
- "httpSse": "Push Server-Sent-Events to subscribed browser clients.",
- "networkFetch": "Make outbound HTTP requests to other services.",
- "notificationsSend": "Send broadcaster notifications via the configured channels.",
- "serverRead": "Read Owncast configuration and current server state.",
- "storageFs": "Read and write files in a private, server-side directory only this plugin can access.",
- "storageKv": "Read and write a per-plugin key-value store that persists across reloads.",
- "storageSql": "Read and write a private per-plugin SQLite database with bounded size and results. It is not included in Owncast backups.",
- "storageUpload": "Upload files to Owncast’s public files area for browser-accessible URLs.",
- "uiModify": "Make changes to the Owncast user interface.",
- "usersModerate": "Disable or re-enable chat users.",
- "usersRead": "Read the chat user list and per-user details.",
- "usersRegister": "Create and sign in Owncast users for an external identity (such as an OAuth or social account).",
- "videoconfigRead": "Read stream and video output configuration (encoders, variants).",
- "videoconfigWrite": "Modify stream and video output configuration."
- },
- "allowedHostsLabel": "Allowed hosts:",
- "approveButton": "Approve",
- "approveTooltip": "Approve the expanded permission set and load the plugin.",
- "browseAuthor": "by {{name}}",
- "browseClearFilters": "Clear filters",
- "browseEmpty": "No plugins are available in the registry yet.",
- "browseFilterAuthor": "Filter by author",
- "browseFilterCategory": "Filter by category",
- "browseFilterPermissions": "Filter by permissions",
- "browseFilteredEmpty": "No plugins match the current filters.",
- "browseInstall": "Install",
- "browseInstalled": "Installed",
- "browsePreviewAlt": "{{name}} preview screenshot",
- "browseSearch": "Search plugins",
- "browseUnavailableDescription": "Owncast can't reach the plugin catalog right now. You can still upload .ocpkg files directly from the Installed tab.",
- "browseUnavailableRetry": "Retry",
- "browseUnavailableTitle": "The plugin catalog is currently unavailable",
- "browseUpdate": "Update to v{{version}}",
- "commandColumnHeader": "Command",
- "commandsTab": "Commands",
- "configEmpty": "This plugin has no configurable settings.",
- "configLoadError": "Could not load settings.",
- "configSave": "Save",
- "configSaveError": "Could not save settings.",
- "configSaved": "Settings saved.",
- "configTab": "Settings",
- "configure": "Configure",
- "descriptionColumnHeader": "Description",
- "enabledColumn": "Enabled",
- "errorTitle": "Plugin admin error",
- "installConfirmCancel": "Maybe later",
- "installConfirmEnable": "Enable plugin",
- "installConfirmNoPermissions": "This plugin doesn't request any permissions.",
- "installConfirmPrompt": "This plugin uses these capabilities:",
- "installConfirmTitle": "Enable {{name}}?",
- "installEnabledSuccess": "Enabled {{name}}",
- "instructionsLoadError": "Could not load this plugin's instructions.",
- "instructionsTab": "Instructions",
- "modOnlyTag": "mods only",
- "noPermissionsDescription": "This plugin does not declare any permissions in its manifest.",
- "noPermissionsTitle": "No permissions",
- "none": "none",
- "notFoundDescription": "No plugin named \"{{name}}\" is currently registered.",
- "notFoundTitle": "Plugin not found",
- "openPluginAdmin": "Open plugin admin",
- "overview": "All plugins",
- "pageDescription": "Plugins extend Owncast with new functionality. You can install plugins from this catalog, upload your own, or build your own.",
- "pageTitle": "Plugins",
- "permissionColumnHeader": "Permission",
- "permissionsColumn": "Permissions",
- "permissionsTab": "Permissions",
- "pluginColumn": "Plugin",
- "pluginErrorTitle": "Plugin error",
- "pluginFailedToLoad": "Plugin failed to load",
- "refresh": "Refresh",
- "reloadTooltip": "Reload this plugin",
- "sidebarTitle": "Plugins",
- "statusAutoDisabled": "auto-disabled",
- "statusAutoDisabledTooltip": "The host stopped invoking this plugin after repeated failures. Reload it to retry.",
- "statusColumn": "Status",
- "statusDisabled": "disabled",
- "statusEnabledNotLoaded": "enabled, not loaded",
- "statusError": "error",
- "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.",
- "statusRunning": "running",
- "tabBrowse": "Browse",
- "tabInstalled": "Installed",
- "toggleAria": "Toggle {{name}}",
- "uninstallAria": "Uninstall {{name}}",
- "uninstallConfirmCancel": "Cancel",
- "uninstallConfirmDescription": "This removes \"{{name}}\" from the server.",
- "uninstallConfirmOk": "Uninstall",
- "uninstallConfirmTitle": "Uninstall plugin?",
- "uninstallSuccess": "Uninstalled {{name}}",
- "uninstallTooltip": "Uninstall this plugin",
- "updateAvailable": "Update available: v{{version}}",
- "updateConfirmCancel": "Cancel",
- "updateConfirmOk": "Update",
- "updateConfirmTitle": "Update {{name}} to v{{version}}?",
- "uploadButton": "Upload plugin",
- "uploadSuccess": "Installed {{name}}"
- },
- "StatusMessages": {
- "autoplayUpdated": "Autoplay setting updated.",
- "convertingEmoji": "Converting emoji...",
- "deletingEmoji": "Deleting emoji...",
- "emojiDeleted": "Emoji deleted",
- "emojiUploadedSuccessfully": "Emoji uploaded successfully!",
- "fileSizeTooBig": "File size is too big: {{size}}",
- "fileTypeNotSupported": "File type is not supported: {{type}}",
- "latencyBufferUpdated": "Latency buffer level updated.",
- "pleaseEnterTag": "Please enter a tag",
- "tagAlreadyUsed": "This tag is already used!",
- "tagsUpdated": "Tags updated.",
- "thereWasAnError": "There was an error: {{message}}",
- "updated": "Updated.",
- "uploadingEmoji": "Uploading emoji...",
- "variantsUpdated": "Variants updated",
- "videoCodecUpdated": "Video codec updated."
- },
- "Users": {
- "pageDescription": "Everyone known to your server: chat viewers, authenticated and plugin-created users, and API integrations. Change moderator access, ban, or permanently remove users.",
- "pageTitle": "Users"
- },
- "VideoVariantForm": {
- "bitrateDisabledPassthrough": "Bitrate selection is disabled when Video Passthrough is enabled.",
- "bitrateGoodForHigh": "Good for high speed & high bitrate viewers.",
- "bitrateGoodForMost": "Good for most viewers, bandwidths and resolutions.",
- "bitrateGoodForSlow": "Good for slow, mobile and low bitrate viewers.",
- "bitrateValueKbps": "{{bitrate}} kbps"
- },
- "ViewerInfo": {
- "currentStream": "Current stream",
- "currentViewers": "Current viewers",
- "last12Hours": "Last 12 hours",
- "last24Hours": "Last 24 hours",
- "last30Days": "Last 30 days",
- "last3Months": "Last 3 months",
- "last6Months": "Last 6 months",
- "last7Days": "Last 7 days",
- "maxViewers": "Max viewers",
- "maxViewersLastStream": "Max viewers last stream",
- "maxViewersThisStream": "Max viewers this stream",
- "noData": "No viewer data has been collected yet.",
- "pleaseWait": "Please wait",
- "title": "Viewer Info",
- "viewers": "Viewers"
- },
- "Webhooks": {
- "webhookSecret": "Set up a new webhook secret",
- "createNewWebhook": "Create New Webhook",
- "selectAll": "Select all",
- "selectEvents": "Select the events that will be sent to this webhook.",
- "webhookUrlPlaceholder": "https://myserver.com/webhook"
- },
- "deleteEmoji": "Delete emoji",
- "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"
- },
- "Common": {
- "poweredByOwncastVersion": "Powered by <a href='https://owncast.online'>Owncast v{{versionNumber}}</a>"
- },
- "Frontend": {
- "BrowserNotifyModal": {
- "allowButton": "Allow",
- "blockButton": "Block",
- "deniedDescription": "To enable push notifications from {{hostname}} access your browser permissions for this site and turn on notifications. Then reload this page to apply your updated settings on this site. <a href='https://owncast.online/docs/notifications'>Learn more.</a>",
- "deniedTitle": "Notifications are blocked on your device",
- "enabledDescription": "To disable push notifications from {{hostname}} access your browser permissions for this site and turn off notifications. <a href='https://owncast.online/docs/notifications'>Learn more.</a>",
- "enabledTitle": "Notifications are enabled",
- "errorMessage": "Error registering for live notifications: {{message}}. Make sure you're not inside a private browser environment or have previously disabled notifications for this stream.",
- "errorTitle": "Browser Notification Error",
- "iosAddButton": "Add",
- "iosAddToHomeScreen": "Add to Home Screen",
- "iosAllowPrompt": "Allow",
- "iosComeBack": "Come back to this screen and enable notifications.",
- "iosDescription": "It takes a couple extra steps to make sure you get notified when your favorite streams go live.",
- "iosNameAndTap": "Give this link a name and tap the new icon on your home screen",
- "iosShareButton": "share",
- "iosTitle": "Get notified on iOS",
- "learnMore": "Learn more",
- "learnMoreAboutNotifications": "<a href='https://owncast.online/docs/notifications/#browser-notifications'>Learn more</a> about Owncast browser notifications.",
- "mainDescription": "Get notified right in the browser each time this stream goes live.",
- "permissionWantsTo": "{{hostname}} wants to",
- "showNotifications": "Show notifications",
- "unsupported": "Browser notifications are not supported in your browser.",
- "unsupportedLocal": "Browser notifications are not supported for local servers."
- },
- "Chat": {
- "authenticateToChat": "Authenticate to chat",
- "moderatorNotification": "You are now a moderator.",
- "nameChangeText": "is now known as",
- "userJoined": "joined the chat.",
- "userLeft": "left the chat."
- },
- "FollowModal": {
- "description": "By following this stream you'll get notified on the Fediverse when it goes live. Now is a great time to",
- "followButton": "Follow",
- "followError": "Follow Error",
- "instructions": "Enter your username @server to follow",
- "joinFediverse": "Join the Fediverse",
- "learnFediverse": "learn about the Fediverse",
- "newToYou": "if it's new to you.",
- "placeholder": "Your fediverse account @account@server",
- "redirectMessage": "You'll be redirected to your Fediverse server and asked to confirm the action.",
- "unableToFollow": "Unable to follow."
- },
- "Footer": {
- "contribute": "Contribute",
- "documentation": "Documentation",
- "source": "Source"
- },
- "Header": {
- "chatOffline": "Chat is offline",
- "chatWillBeAvailable": "Chat will be available when the stream is live.",
- "skipToContent": "Skip to page content",
- "skipToFooter": "Skip to footer",
- "skipToOfflineMessage": "Skip to offline message",
- "skipToPlayer": "Skip to player"
- },
- "NameChangeModal": {
- "authInfo": "You can also authenticate an IndieAuth or Fediverse account via the \"Authenticate\" menu.",
- "buttonText": "Change name",
- "colorLabel": "Your Color",
- "description": "Your chat display name is what people see when you send chat messages.",
- "overLimit": "Over limit",
- "placeholder": "Your chat display name"
- },
- "StreamsTab": {
- "errorLoadingStreams": "Error loading streams",
- "loadingStreams": "Loading featured streams...",
- "noFeaturedStreams": "No featured streams available"
- },
- "chatDisabled": "Chat is disabled",
- "chatEmbedTitle": "{{name}} Chat",
- "chatOffline": "Chat is offline",
- "componentError": "Error: {{message}}",
- "helloWorld": "Hello world",
- "lastLiveAgo": "Last live {{timeAgo}} ago",
- "offlineBasic": "This stream is offline. Check back soon!",
- "offlineFediverseOnly": "This stream is offline. <span class='follow-link'>Follow</span> {{fediverseAccount}} on the Fediverse to see the next time {{streamer}} goes live.",
- "offlineNotifyAndFediverse": "This stream is offline. You can <span class='notify-link'>be notified</span> the next time {{streamer}} goes live or <span class='follow-link'>follow</span> {{fediverseAccount}} on the Fediverse.",
- "offlineNotifyOnly": "This stream is offline. <span class='notify-link'>Be notified</span> the next time {{streamer}} goes live.",
- "showAllTabs": "Show all tabs",
- "unmute": "Unmute"
- },
- "Testing": {
- "itemCount": "You have {{count}} items",
- "messageCount": "You have {{count}} messages from {{sender}}",
- "noPluralKey": "This key has no plural variants - {{count}} things",
- "simpleKey": "Simple translation text"
- }
-}
\ No newline at end of file
+ "Admin": {
+ "AccessTokens": {
+ "createNewAccessToken": "Create New Access token",
+ "nameDescription": "The name will be displayed as the chat user when sending messages with this access token.",
+ "namePlaceholder": "Name of bot, service, or integration",
+ "selectAll": "Select all",
+ "selectPermissions": "Select the permissions this access token will have. It cannot be edited after it's created."
+ },
+ "Actions": {
+ "createNewAction": "Create New Action",
+ "createNewActionTitle": "Create New Action",
+ "customHtml": "Custom HTML",
+ "description": "External action URLs are 3rd party UI you can display, embedded, into your Owncast page when a user clicks on a button to launch your action.",
+ "descriptionPlaceholder": "Optional description",
+ "editActionTitle": "Edit Action",
+ "htmlEmbedPlaceholder": "HTML embed code (required)",
+ "iconPlaceholder": "https://myserver.com/action/icon.png (optional)",
+ "linkOrEmbedUrl": "Link or embed an URL",
+ "modalDescription": "Add the URL for the external action you want to present.",
+ "onlyHttpsSupported": "Only HTTPS URLs and embeds are supported.",
+ "openExternally": "Open in a new tab instead of within your page.",
+ "optionalBackgroundColor": "Optional background color of the action button.",
+ "readMoreAboutActions": "Read more about external actions.",
+ "readMoreLink": "Read more about how to use actions, with examples, at",
+ "selectActionType": "Select an action type",
+ "title": "External Actions",
+ "titlePlaceholder": "Your action title (required)",
+ "urlPlaceholder": "https://myserver.com/action (required)"
+ },
+ "Appearance": {
+ "alsoSetByPlugin": "also set by {{plugins}}",
+ "alsoSetByPluginTooltip": "Your value takes priority here. Use Reset to Defaults to fall back to the color from {{plugins}}.",
+ "pluginStylingActive": "Plugin styling is active",
+ "pluginStylingDescription": "These plugins are applying their own styles to your site, combined with the colors you set here: {{plugins}}. Your settings are applied on top, so they win where they overlap. If the page doesn't look the way you expect, use Reset to Defaults below to let the plugin styling show through, or disable the plugin from the Plugins page."
+ },
+ "Autoplay": {
+ "description": "Choose whether the stream starts playing on its own when a viewer opens your page.",
+ "optionAlwaysDescription": "The stream always starts on its own the moment someone opens the page. It plays with sound where the browser allows it, and starts muted everywhere else.",
+ "optionAlwaysLabel": "Always",
+ "optionOffDescription": "Viewers will press play to start watching.",
+ "optionOffLabel": "Never",
+ "optionSoundOnlyDescription": "The stream starts on its own, but only when the viewer's browser allows sound to play as well. Otherwise the viewer presses play. It never starts silently. Different browsers handle this differently.",
+ "optionSoundOnlyLabel": "Only if sound is available",
+ "title": "Autoplay"
+ },
+ "EditFavicon": {
+ "label": "Favicon",
+ "resetButton": "Reset",
+ "resetConfirmCancel": "No",
+ "resetConfirmOk": "Yes",
+ "resetConfirmTitle": "Reset to default favicon?",
+ "tip": "Upload a custom favicon (PNG or ICO format, max 200KB). This icon appears in browser tabs and bookmarks."
+ },
+ "EditInstanceDetails": {
+ "directoryDescription": "Increase your audience by appearing in the <a href=\"https://owncast.directory\" target=\"_blank\" rel=\"noreferrer\"><strong>Owncast Directory</strong></a>. This is an external service run by the Owncast project. <a href=\"https://owncast.online/docs/directory/?source=admin\" target=\"_blank\" rel=\"noopener noreferrer\">Learn more</a>.",
+ "offlineMessageDescription": "The offline message is displayed to your page visitors when you're not streaming. Markdown is supported.",
+ "serverUrlRequiredForDirectory": "You must set your <strong>Server URL</strong> above to enable the directory."
+ },
+ "FeaturedStreams": {
+ "actions": "Actions",
+ "added": "Added",
+ "approveButton": "Approve",
+ "approvalResent": "Approval resent.",
+ "confirmNo": "No",
+ "confirmYes": "Yes",
+ "directoryListingsDescription": "These directories follow your server so they can list your stream. Each one receives your live status. Remove one to stop sending it your status and drop your server from its listing.",
+ "directoryListingsEmpty": "No directories are featuring your stream yet.",
+ "directoryListingsTitle": "Directories listing you",
+ "directoryRemoved": "Removed from the directory.",
+ "enterStreamUrl": "Please enter a stream URL",
+ "enterValidUrl": "Please enter a valid URL",
+ "failedToApprove": "Failed to approve the feature request",
+ "failedToFeature": "Failed to feature stream",
+ "failedToReject": "Failed to reject the feature request",
+ "failedToRemoveDirectory": "Failed to remove from the directory.",
+ "failedToResendApproval": "Failed to resend the approval.",
+ "failedToUnfeature": "Failed to unfeature the stream",
+ "featureRequestApproved": "Feature request approved",
+ "featureRequestRejected": "Feature request rejected",
+ "featureRequestsDescription": "These Owncast servers have asked to show your stream in their featured streams directory. Approve a server to let it display your live status.",
+ "featureRequestsTitle": "Requests to feature your stream",
+ "featureStreamAction": "Feature Stream",
+ "featureStreamButton": "Feature Live Stream",
+ "featuringYouTab": "Featuring you",
+ "federationSettings": "Federation settings",
+ "lastChecked": "Last Checked",
+ "modalTitle": "Feature Live Stream",
+ "never": "Never",
+ "offline": "Offline",
+ "online": "Online",
+ "onlyDefaultPortSupported": "Only the default HTTPS port (443) is supported",
+ "onlyHttpsSupported": "Only HTTPS URLs are supported",
+ "pageDescription": "Feature other Owncast streams to display their streaming status on your server. When enabled, visitors can discover and navigate to other featured streams through a dedicated \"Featured\" tab on your main page.",
+ "pageDescriptionSecondary": "This creates a network effect, allowing users to discover and navigate to other Owncast servers easily. It also gives visitors somewhere to go if your stream is offline.",
+ "pageTitle": "Featured Streams",
+ "pendingApproval": "Pending approval",
+ "rejectButton": "Reject",
+ "removeFromDirectoryButton": "Remove",
+ "removeFromDirectoryConfirm": "Remove your server from this directory?",
+ "resendApprovalButton": "Resend approval",
+ "requirementDefaultPort": "The stream must be on the default HTTPS port (443)",
+ "requirementFeaturedStreams": "The stream must support featured streams",
+ "requirementHttps": "The stream must be accessible via HTTPS",
+ "requirementOwncast": "The stream must be an Owncast instance",
+ "socialFeaturesRequired": "Social features must be enabled",
+ "socialFeaturesRequiredDesc": "before you can feature other streams.",
+ "status": "Status",
+ "streamFeaturedSuccess": "Stream featured",
+ "streamName": "Stream Name",
+ "streamRequirements": "Stream Requirements",
+ "streamTitle": "Stream Title",
+ "streamUnfeaturedSuccess": "Stream unfeatured",
+ "streamUrlHelp": "Enter the URL of an Owncast stream (e.g., stream.example.com)",
+ "streamUrlLabel": "Stream URL",
+ "streamUrlPlaceholder": "stream.example.com",
+ "streamsYouFeatureTab": "Streams you feature",
+ "unfeatureButton": "Unfeature",
+ "unfeatureConfirm": "Unfeature {{name}}?",
+ "unsupportedFeaturedStreams": "This Owncast server does not support featured streams yet. Ask the server owner to upgrade Owncast.",
+ "url": "URL"
+ },
+ "HardwareInfo": {
+ "cpu": "CPU",
+ "disk": "Disk",
+ "memory": "Memory",
+ "noDetails": "No hardware details have been collected yet.",
+ "pleaseWait": "Please wait",
+ "title": "Hardware Info",
+ "used": "used"
+ },
+ "Help": {
+ "bugButton": "Report an issue",
+ "bugDescription": "If something seems broken, let us know so it can be fixed.",
+ "bugTitle": "Found a bug?",
+ "commonTasks": "Common tasks",
+ "communityButton": "Join the community chat",
+ "communityDescription": "Chat with the Owncast community on Matrix. It's the fastest way to get answers.",
+ "communityTitle": "Have a question?",
+ "copied": "Copied to clipboard.",
+ "copySupportInfo": "Copy support info",
+ "discussions": "GitHub discussions",
+ "documentation": "Documentation",
+ "fediverse": "Follow Owncast on the Fediverse",
+ "fixButton": "Troubleshooting guide",
+ "fixDescription": "Work through common problems with the troubleshooting guide.",
+ "fixTitle": "Something not working?",
+ "gettingStarted": "It doesn't look like you've streamed yet. The quickstart guide walks you through sending your first stream.",
+ "gettingStartedLink": "Read the quickstart",
+ "groupCustomize": "Customize",
+ "groupExtend": "Extend Owncast",
+ "groupGrow": "Grow your audience",
+ "groupSetup": "Set up your stream",
+ "learnMore": "Learn more",
+ "moreResources": "More resources",
+ "openSettings": "Open settings",
+ "releaseNotes": "Release notes",
+ "searchPlaceholder": "Search the documentation",
+ "supportInfo": "Support info",
+ "supportInfoDescription": "Copy your server's version, video configuration and recent errors to include when reporting a bug or asking for help.",
+ "taskApis": "Build add-ons with the developer APIs",
+ "taskBroadcasting": "Connect your broadcasting software",
+ "taskChat": "Manage chat and moderation",
+ "taskDirectory": "List your stream in the directory",
+ "taskEmbed": "Embed your stream into another site",
+ "taskFediverse": "Share your stream on the Fediverse",
+ "taskNotifications": "Notify viewers when you go live",
+ "taskPlugins": "Add functionality with plugins",
+ "taskSsl": "Set up SSL and proxies",
+ "taskStorage": "Use external storage or a CDN",
+ "taskVideoQuality": "Tweak video quality and latency",
+ "taskWebsite": "Customize your website and appearance",
+ "title": "How can we help you?",
+ "upgradeAvailable": "A new version of Owncast is available.",
+ "upgradeLink": "Visit the upgrade page"
+ },
+ "LogTable": {
+ "error": "Error",
+ "info": "Info",
+ "level": "Level",
+ "logs": "Logs",
+ "message": "Message",
+ "timestamp": "Timestamp",
+ "warning": "Warning"
+ },
+ "NewsFeed": {
+ "link": "Link",
+ "noNews": "No news.",
+ "title": "News & Updates from Owncast"
+ },
+ "Plugins": {
+ "Categories": {
+ "adminUtilities": "Admin utilities",
+ "analytics": "Analytics & stats",
+ "authentication": "Authentication",
+ "chatBots": "Chat bots",
+ "chatFilters": "Chat filters",
+ "examples": "Examples",
+ "games": "Games & fun",
+ "integrations": "Integrations",
+ "moderation": "Moderation",
+ "notifications": "Notifications",
+ "other": "Other",
+ "overlays": "Overlays & widgets",
+ "themes": "Themes",
+ "video": "Video & streaming",
+ "viewerUi": "Viewer UI"
+ },
+ "PermissionNames": {
+ "authGate": "Gate viewer access",
+ "chatFilter": "Filter chat messages",
+ "chatHistory": "Read chat history",
+ "chatModerate": "Moderate chat",
+ "chatSend": "Send chat messages",
+ "eventsEmit": "Emit events",
+ "fediverseInbound": "Receive fediverse activity",
+ "fediversePost": "Post to the fediverse",
+ "httpServe": "Serve HTTP",
+ "httpSse": "Push realtime updates",
+ "networkFetch": "Make outbound HTTP requests",
+ "notificationsSend": "Send notifications",
+ "serverRead": "Read server state",
+ "storageFs": "Read and write files",
+ "storageKv": "Store data",
+ "storageUpload": "Upload files",
+ "uiModify": "Add UI elements",
+ "usersModerate": "Moderate users",
+ "usersRead": "Read user list",
+ "usersRegister": "Sign in viewers",
+ "videoconfigRead": "Read video settings",
+ "videoconfigWrite": "Change video settings"
+ },
+ "Permissions": {
+ "authGate": "Act as a viewer-authentication gate, signing viewers in and controlling their access to the site.",
+ "chatFilter": "Inspect and modify chat messages before they are broadcast, or drop them entirely.",
+ "chatHistory": "Read recent chat messages.",
+ "chatModerate": "Hide chat messages and ban users.",
+ "chatSend": "Post chat messages as the plugin’s own bot identity.",
+ "eventsEmit": "Publish custom events that other plugins can subscribe to.",
+ "fediverseInbound": "Receive verified inbound fediverse activity, including follows, likes, reposts, quotes, mentions, replies, and raw activities.",
+ "fediversePost": "Post a public note to the fediverse from the configured Owncast account.",
+ "httpServe": "Serve HTTP requests at /plugins/<name>/ (static assets and a dynamic handler).",
+ "httpSse": "Push Server-Sent-Events to subscribed browser clients.",
+ "networkFetch": "Make outbound HTTP requests to other services.",
+ "notificationsSend": "Send broadcaster notifications via the configured channels.",
+ "serverRead": "Read Owncast configuration and current server state.",
+ "storageFs": "Read and write files in a private, server-side directory only this plugin can access.",
+ "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.",
+ "uiModify": "Make changes to the Owncast user interface.",
+ "usersModerate": "Disable or re-enable chat users.",
+ "usersRead": "Read the chat user list and per-user details.",
+ "usersRegister": "Create and sign in Owncast users for an external identity (such as an OAuth or social account).",
+ "videoconfigRead": "Read stream and video output configuration (encoders, variants).",
+ "videoconfigWrite": "Modify stream and video output configuration."
+ },
+ "allowedHostsLabel": "Allowed hosts:",
+ "approveButton": "Approve",
+ "approveTooltip": "Approve the expanded permission set and load the plugin.",
+ "browseAuthor": "by {{name}}",
+ "browseClearFilters": "Clear filters",
+ "browseEmpty": "No plugins are available in the registry yet.",
+ "browseFilterAuthor": "Filter by author",
+ "browseFilterCategory": "Filter by category",
+ "browseFilterPermissions": "Filter by permissions",
+ "browseFilteredEmpty": "No plugins match the current filters.",
+ "browseInstall": "Install",
+ "browseInstalled": "Installed",
+ "browsePreviewAlt": "{{name}} preview screenshot",
+ "browseSearch": "Search plugins",
+ "browseUnavailableDescription": "Owncast can't reach the plugin catalog right now. You can still upload .ocpkg files directly from the Installed tab.",
+ "browseUnavailableRetry": "Retry",
+ "browseUnavailableTitle": "The plugin catalog is currently unavailable",
+ "browseUpdate": "Update to v{{version}}",
+ "commandColumnHeader": "Command",
+ "commandsTab": "Commands",
+ "configEmpty": "This plugin has no configurable settings.",
+ "configLoadError": "Could not load settings.",
+ "configSave": "Save",
+ "authSettingsTab": "Authentication",
+ "authSettingsDescription": "Choose which viewer resources require a valid authentication session while this plugin is the active gate.",
+ "authSettingsAccessMode": "Access mode",
+ "authSettingsWebsiteOnly": "Website only",
+ "authSettingsWebsiteOnlyDescription": "The website requires authentication. HLS players, server status requests, and Owncast Directory listing remain public.",
+ "authSettingsWebsiteAndStream": "Website, video players, and other resources",
+ "authSettingsWebsiteAndStreamDescription": "Owncast-hosted HLS also requires authentication, so VLC and other players without a browser session cannot play the stream. Server status requests and Owncast Directory listing remain public.",
+ "authSettingsWebsiteStreamAndStatus": "Website, video players, and server status requests",
+ "authSettingsWebsiteStreamAndStatusDescription": "The website, Owncast-hosted HLS, and /api/status require authentication. Owncast Directory listing is disabled.",
+ "authSettingsSave": "Save authentication settings",
+ "authSettingsSaved": "Authentication settings saved.",
+ "authSettingsLoadError": "Could not load authentication settings.",
+ "authSettingsSaveError": "Could not save authentication settings.",
+ "configTab": "Settings",
+ "configSaveError": "Could not save settings.",
+ "configSaved": "Settings saved.",
+ "descriptionColumnHeader": "Description",
+ "enabledColumn": "Enabled",
+ "errorTitle": "Plugin admin error",
+ "installConfirmCancel": "Maybe later",
+ "installConfirmEnable": "Enable plugin",
+ "installConfirmNoPermissions": "This plugin doesn't request any permissions.",
+ "installConfirmPrompt": "This plugin uses these capabilities:",
+ "installConfirmTitle": "Enable {{name}}?",
+ "installEnabledSuccess": "Enabled {{name}}",
+ "instructionsLoadError": "Could not load this plugin's instructions.",
+ "instructionsTab": "Instructions",
+ "modOnlyTag": "mods only",
+ "noPermissionsDescription": "This plugin does not declare any permissions in its manifest.",
+ "noPermissionsTitle": "No permissions",
+ "none": "none",
+ "notFoundDescription": "No plugin named \"{{name}}\" is currently registered.",
+ "notFoundTitle": "Plugin not found",
+ "openPluginAdmin": "Open plugin admin",
+ "overview": "All plugins",
+ "pageDescription": "Plugins extend Owncast with new functionality. You can install plugins from this catalog, upload your own, or build your own.",
+ "pageTitle": "Plugins",
+ "permissionColumnHeader": "Permission",
+ "permissionsColumn": "Permissions",
+ "permissionsTab": "Permissions",
+ "pluginColumn": "Plugin",
+ "pluginErrorTitle": "Plugin error",
+ "pluginFailedToLoad": "Plugin failed to load",
+ "refresh": "Refresh",
+ "reloadTooltip": "Reload this plugin",
+ "sidebarTitle": "Plugins",
+ "statusAutoDisabled": "auto-disabled",
+ "statusAutoDisabledTooltip": "The host stopped invoking this plugin after repeated failures. Reload it to retry.",
+ "statusColumn": "Status",
+ "statusDisabled": "disabled",
+ "statusEnabledNotLoaded": "enabled, not loaded",
+ "statusError": "error",
+ "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.",
+ "statusRunning": "running",
+ "tabBrowse": "Browse",
+ "tabInstalled": "Installed",
+ "toggleAria": "Toggle {{name}}",
+ "uninstallAria": "Uninstall {{name}}",
+ "uninstallConfirmCancel": "Cancel",
+ "uninstallConfirmDescription": "This removes \"{{name}}\" from the server.",
+ "uninstallConfirmOk": "Uninstall",
+ "uninstallConfirmTitle": "Uninstall plugin?",
+ "uninstallSuccess": "Uninstalled {{name}}",
+ "uninstallTooltip": "Uninstall this plugin",
+ "updateAvailable": "Update available: v{{version}}",
+ "updateConfirmCancel": "Cancel",
+ "updateConfirmOk": "Update",
+ "updateConfirmTitle": "Update {{name}} to v{{version}}?",
+ "uploadButton": "Upload plugin",
+ "uploadSuccess": "Installed {{name}}"
+ },
+ "StatusMessages": {
+ "autoplayUpdated": "Autoplay setting updated.",
+ "convertingEmoji": "Converting emoji...",
+ "deletingEmoji": "Deleting emoji...",
+ "emojiDeleted": "Emoji deleted",
+ "emojiUploadedSuccessfully": "Emoji uploaded successfully!",
+ "fileSizeTooBig": "File size is too big: {{size}}",
+ "fileTypeNotSupported": "File type is not supported: {{type}}",
+ "latencyBufferUpdated": "Latency buffer level updated.",
+ "pleaseEnterTag": "Please enter a tag",
+ "tagAlreadyUsed": "This tag is already used!",
+ "tagsUpdated": "Tags updated.",
+ "thereWasAnError": "There was an error: {{message}}",
+ "updated": "Updated.",
+ "uploadingEmoji": "Uploading emoji...",
+ "variantsUpdated": "Variants updated",
+ "videoCodecUpdated": "Video codec updated."
+ },
+ "Users": {
+ "pageDescription": "Everyone known to your server: chat viewers, authenticated and plugin-created users, and API integrations. Change moderator access, ban, or permanently remove users.",
+ "pageTitle": "Users"
+ },
+ "VideoVariantForm": {
+ "bitrateDisabledPassthrough": "Bitrate selection is disabled when Video Passthrough is enabled.",
+ "bitrateGoodForHigh": "Good for high speed & high bitrate viewers.",
+ "bitrateGoodForMost": "Good for most viewers, bandwidths and resolutions.",
+ "bitrateGoodForSlow": "Good for slow, mobile and low bitrate viewers.",
+ "bitrateValueKbps": "{{bitrate}} kbps"
+ },
+ "ViewerInfo": {
+ "currentStream": "Current stream",
+ "currentViewers": "Current viewers",
+ "last12Hours": "Last 12 hours",
+ "last24Hours": "Last 24 hours",
+ "last30Days": "Last 30 days",
+ "last3Months": "Last 3 months",
+ "last6Months": "Last 6 months",
+ "last7Days": "Last 7 days",
+ "maxViewers": "Max viewers",
+ "maxViewersLastStream": "Max viewers last stream",
+ "maxViewersThisStream": "Max viewers this stream",
+ "noData": "No viewer data has been collected yet.",
+ "pleaseWait": "Please wait",
+ "title": "Viewer Info",
+ "viewers": "Viewers"
+ },
+ "Webhooks": {
+ "webhookSecret": "Set up a new webhook secret",
+ "createNewWebhook": "Create New Webhook",
+ "selectAll": "Select all",
+ "selectEvents": "Select the events that will be sent to this webhook.",
+ "webhookUrlPlaceholder": "https://myserver.com/webhook"
+ },
+ "deleteEmoji": "Delete emoji",
+ "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"
+ },
+ "Common": {
+ "poweredByOwncastVersion": "Powered by <a href='https://owncast.online'>Owncast v{{versionNumber}}</a>"
+ },
+ "Frontend": {
+ "BrowserNotifyModal": {
+ "allowButton": "Allow",
+ "blockButton": "Block",
+ "deniedDescription": "To enable push notifications from {{hostname}} access your browser permissions for this site and turn on notifications. Then reload this page to apply your updated settings on this site. <a href='https://owncast.online/docs/notifications'>Learn more.</a>",
+ "deniedTitle": "Notifications are blocked on your device",
+ "enabledDescription": "To disable push notifications from {{hostname}} access your browser permissions for this site and turn off notifications. <a href='https://owncast.online/docs/notifications'>Learn more.</a>",
+ "enabledTitle": "Notifications are enabled",
+ "errorMessage": "Error registering for live notifications: {{message}}. Make sure you're not inside a private browser environment or have previously disabled notifications for this stream.",
+ "errorTitle": "Browser Notification Error",
+ "iosAddButton": "Add",
+ "iosAddToHomeScreen": "Add to Home Screen",
+ "iosAllowPrompt": "Allow",
+ "iosComeBack": "Come back to this screen and enable notifications.",
+ "iosDescription": "It takes a couple extra steps to make sure you get notified when your favorite streams go live.",
+ "iosNameAndTap": "Give this link a name and tap the new icon on your home screen",
+ "iosShareButton": "share",
+ "iosTitle": "Get notified on iOS",
+ "learnMore": "Learn more",
+ "learnMoreAboutNotifications": "<a href='https://owncast.online/docs/notifications/#browser-notifications'>Learn more</a> about Owncast browser notifications.",
+ "mainDescription": "Get notified right in the browser each time this stream goes live.",
+ "permissionWantsTo": "{{hostname}} wants to",
+ "showNotifications": "Show notifications",
+ "unsupported": "Browser notifications are not supported in your browser.",
+ "unsupportedLocal": "Browser notifications are not supported for local servers."
+ },
+ "Chat": {
+ "authenticateToChat": "Authenticate to chat",
+ "moderatorNotification": "You are now a moderator.",
+ "nameChangeText": "is now known as",
+ "userJoined": "joined the chat.",
+ "userLeft": "left the chat."
+ },
+ "FollowModal": {
+ "description": "By following this stream you'll get notified on the Fediverse when it goes live. Now is a great time to",
+ "followButton": "Follow",
+ "followError": "Follow Error",
+ "instructions": "Enter your username @server to follow",
+ "joinFediverse": "Join the Fediverse",
+ "learnFediverse": "learn about the Fediverse",
+ "newToYou": "if it's new to you.",
+ "placeholder": "Your fediverse account @account@server",
+ "redirectMessage": "You'll be redirected to your Fediverse server and asked to confirm the action.",
+ "unableToFollow": "Unable to follow."
+ },
+ "Footer": {
+ "contribute": "Contribute",
+ "documentation": "Documentation",
+ "source": "Source"
+ },
+ "Header": {
+ "chatOffline": "Chat is offline",
+ "chatWillBeAvailable": "Chat will be available when the stream is live.",
+ "skipToContent": "Skip to page content",
+ "skipToFooter": "Skip to footer",
+ "skipToOfflineMessage": "Skip to offline message",
+ "skipToPlayer": "Skip to player"
+ },
+ "NameChangeModal": {
+ "authInfo": "You can also authenticate an IndieAuth or Fediverse account via the \"Authenticate\" menu.",
+ "buttonText": "Change name",
+ "colorLabel": "Your Color",
+ "description": "Your chat display name is what people see when you send chat messages.",
+ "overLimit": "Over limit",
+ "placeholder": "Your chat display name"
+ },
+ "StreamsTab": {
+ "errorLoadingStreams": "Error loading streams",
+ "loadingStreams": "Loading featured streams...",
+ "noFeaturedStreams": "No featured streams available"
+ },
+ "chatDisabled": "Chat is disabled",
+ "chatEmbedTitle": "{{name}} Chat",
+ "chatOffline": "Chat is offline",
+ "componentError": "Error: {{message}}",
+ "helloWorld": "Hello world",
+ "lastLiveAgo": "Last live {{timeAgo}} ago",
+ "offlineBasic": "This stream is offline. Check back soon!",
+ "offlineFediverseOnly": "This stream is offline. <span class='follow-link'>Follow</span> {{fediverseAccount}} on the Fediverse to see the next time {{streamer}} goes live.",
+ "offlineNotifyAndFediverse": "This stream is offline. You can <span class='notify-link'>be notified</span> the next time {{streamer}} goes live or <span class='follow-link'>follow</span> {{fediverseAccount}} on the Fediverse.",
+ "offlineNotifyOnly": "This stream is offline. <span class='notify-link'>Be notified</span> the next time {{streamer}} goes live.",
+ "showAllTabs": "Show all tabs",
+ "unmute": "Unmute"
+ },
+ "Testing": {
+ "itemCount": "You have {{count}} items",
+ "messageCount": "You have {{count}} messages from {{sender}}",
+ "noPluralKey": "This key has no plural variants - {{count}} things",
+ "simpleKey": "Simple translation text"
+ }
+}
diff --git a/web/tests/BrowseRegistryFilters.test.tsx b/web/tests/BrowseRegistryFilters.test.tsx
index 76cc44dcc8..f659bac025 100644
--- a/web/tests/BrowseRegistryFilters.test.tsx
+++ b/web/tests/BrowseRegistryFilters.test.tsx
@@ -37,7 +37,7 @@ const plugins: RegistryPlugin[] = [
slug: 'beta',
name: 'Beta Plugin',
authorName: 'Bob',
- latest: { version: '2.0.0', manifest: { permissions: ['chat.send'], category: 'overlays' } },
+ latest: { version: '2.0.0', manifest: { permissions: ['chat.send'], category: 'viewer-ui' } },
},
{
slug: 'gamma',
@@ -134,11 +134,11 @@ describe('BrowseRegistry filters', () => {
it('shows the filtered-empty state and clears filters', () => {
renderRegistry();
- // Alice + overlays matches nothing: Alice authored a chat-bot.
+ // Alice + viewer UI matches nothing: Alice authored a chat-bot.
openSelect(AUTHOR_PLACEHOLDER);
clickOption('Alice');
openSelect(CATEGORY_PLACEHOLDER);
- clickOption('Admin.Plugins.Categories.overlays');
+ clickOption('Admin.Plugins.Categories.viewerUi');
expect(visiblePlugins()).toEqual([]);
expect(screen.getByText('Admin.Plugins.browseFilteredEmpty')).toBeInTheDocument();
fireEvent.click(screen.getByText('Admin.Plugins.browseClearFilters'));
@@ -165,8 +165,8 @@ describe('BrowseRegistry filters', () => {
expect(screen.getByText('Admin.Plugins.Categories.chatBots')).toBeInTheDocument();
});
- it('renders a category tag from the embedded manifest fallback', () => {
+ it('renders a viewer UI category tag from the embedded manifest fallback', () => {
renderRegistry([plugins[1]]);
- expect(screen.getByText('Admin.Plugins.Categories.overlays')).toBeInTheDocument();
+ expect(screen.getByText('Admin.Plugins.Categories.viewerUi')).toBeInTheDocument();
});
});
diff --git a/web/types/localization.ts b/web/types/localization.ts
index 48bb67fcd9..93424a243e 100644
--- a/web/types/localization.ts
+++ b/web/types/localization.ts
@@ -541,9 +541,24 @@ export const Localization = {
instructionsTab: 'Admin.Plugins.instructionsTab',
configTab: 'Admin.Plugins.configTab',
configSave: 'Admin.Plugins.configSave',
- configSaved: 'Admin.Plugins.configSaved',
configSaveError: 'Admin.Plugins.configSaveError',
+ configSaved: 'Admin.Plugins.configSaved',
configLoadError: 'Admin.Plugins.configLoadError',
+ authSettingsTab: 'Admin.Plugins.authSettingsTab',
+ authSettingsDescription: 'Admin.Plugins.authSettingsDescription',
+ authSettingsAccessMode: 'Admin.Plugins.authSettingsAccessMode',
+ authSettingsWebsiteOnly: 'Admin.Plugins.authSettingsWebsiteOnly',
+ authSettingsWebsiteOnlyDescription: 'Admin.Plugins.authSettingsWebsiteOnlyDescription',
+ authSettingsWebsiteAndStream: 'Admin.Plugins.authSettingsWebsiteAndStream',
+ authSettingsWebsiteAndStreamDescription:
+ 'Admin.Plugins.authSettingsWebsiteAndStreamDescription',
+ authSettingsWebsiteStreamAndStatus: 'Admin.Plugins.authSettingsWebsiteStreamAndStatus',
+ authSettingsWebsiteStreamAndStatusDescription:
+ 'Admin.Plugins.authSettingsWebsiteStreamAndStatusDescription',
+ authSettingsSave: 'Admin.Plugins.authSettingsSave',
+ authSettingsSaved: 'Admin.Plugins.authSettingsSaved',
+ authSettingsLoadError: 'Admin.Plugins.authSettingsLoadError',
+ authSettingsSaveError: 'Admin.Plugins.authSettingsSaveError',
configEmpty: 'Admin.Plugins.configEmpty',
instructionsLoadError: 'Admin.Plugins.instructionsLoadError',
permissionColumnHeader: 'Admin.Plugins.permissionColumnHeader',
@@ -571,6 +586,7 @@ export const Localization = {
video: 'Admin.Plugins.Categories.video',
analytics: 'Admin.Plugins.Categories.analytics',
games: 'Admin.Plugins.Categories.games',
+ viewerUi: 'Admin.Plugins.Categories.viewerUi',
adminUtilities: 'Admin.Plugins.Categories.adminUtilities',
examples: 'Admin.Plugins.Categories.examples',
other: 'Admin.Plugins.Categories.other',
diff --git a/web/utils/apis.ts b/web/utils/apis.ts
index 1a40c64c87..9c0c398f89 100644
--- a/web/utils/apis.ts
+++ b/web/utils/apis.ts
@@ -83,6 +83,8 @@ export const pluginInstructionsUrl = (slug: string) =>
// config form auto-rendered from the plugin's manifest config schema uses this.
export const pluginConfigUrl = (slug: string) =>
`/api/admin/plugins/${encodeURIComponent(slug)}/config`;
+export const authGateSettingsUrl = (slug: string) =>
+ `/api/admin/plugins/${encodeURIComponent(slug)}/auth-settings`;
// Upload a new custom emoji
export const UPLOAD_EMOJI = `${API_LOCATION}emoji/upload`;
diff --git a/yp/api.go b/yp/api.go
index 0f520fa5d9..ff35552bb8 100644
--- a/yp/api.go
+++ b/yp/api.go
@@ -28,6 +28,10 @@ type ypDetailsResponse struct {
// GetYPResponse gets the status of the server for YP purposes.
func (yp *YP) GetYPResponse(w http.ResponseWriter, r *http.Request) {
+ if yp.directoryAvailable != nil && !yp.directoryAvailable() {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
if !yp.configRepository.GetDirectoryEnabled() {
w.WriteHeader(http.StatusNotFound)
return
diff --git a/yp/api_test.go b/yp/api_test.go
new file mode 100644
index 0000000000..301521964a
--- /dev/null
+++ b/yp/api_test.go
@@ -0,0 +1,126 @@
+package yp
+
+// The directory endpoint is public by design: the Owncast Directory fetches it
+// anonymously, with no token, so the viewer-auth gate deliberately never
+// challenges it. That makes this handler the only place the "directory is
+// switched off" decision is enforced, which is what these tests pin down.
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/persistence/configrepository"
+)
+
+// stubConfig implements only the getters the YP paths touch. The embedded
+// interface is nil on purpose: any other call panics loudly instead of
+// silently returning a zero value.
+type stubConfig struct {
+ configrepository.ConfigRepository
+ directoryEnabled bool
+}
+
+func (s stubConfig) GetDirectoryEnabled() bool { return s.directoryEnabled }
+func (s stubConfig) GetServerName() string { return "Test Server" }
+func (s stubConfig) GetServerSummary() string { return "summary" }
+func (s stubConfig) GetStreamTitle() string { return "title" }
+func (s stubConfig) GetNSFW() bool { return false }
+func (s stubConfig) GetServerMetadataTags() []string { return nil }
+func (s stubConfig) GetSocialHandles() []models.SocialHandle { return nil }
+func (s stubConfig) GetServerURL() string { return "https://example.com" }
+
+func newYP(directoryEnabled bool, directoryAvailable func() bool) *YP {
+ y := New(Deps{
+ GetStatus: func() models.Status { return models.Status{Online: true} },
+ ConfigRepository: stubConfig{directoryEnabled: directoryEnabled},
+ })
+ if directoryAvailable != nil {
+ y.SetDirectoryAvailable(directoryAvailable)
+ }
+ return y
+}
+
+func getYP(t *testing.T, y *YP) *httptest.ResponseRecorder {
+ t.Helper()
+ w := httptest.NewRecorder()
+ y.GetYPResponse(w, httptest.NewRequest(http.MethodGet, "/api/yp", nil))
+ return w
+}
+
+func TestGetYPResponse_ServedWhenDirectoryEnabledAndAvailable(t *testing.T) {
+ w := getYP(t, newYP(true, func() bool { return true }))
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ var body ypDetailsResponse
+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {
+ t.Fatal(err)
+ }
+ if body.Name != "Test Server" {
+ t.Fatalf("name = %q, want Test Server", body.Name)
+ }
+}
+
+// This is the enforcement that moved out of the gate middleware: when the
+// operator blocks public stream status, the gate stops challenging /api/yp and
+// this handler is what refuses to answer.
+func TestGetYPResponse_404WhenTheGateBlocksTheDirectory(t *testing.T) {
+ w := getYP(t, newYP(true, func() bool { return false }))
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+ if w.Body.Len() != 0 {
+ t.Fatalf("blocked directory leaked a body: %q", w.Body.String())
+ }
+}
+
+func TestGetYPResponse_404WhenDirectoryListingIsOff(t *testing.T) {
+ w := getYP(t, newYP(false, func() bool { return true }))
+
+ if w.Code != http.StatusNotFound {
+ t.Fatalf("status = %d, want 404", w.Code)
+ }
+}
+
+// The plugin host is optional: with no host wired, the policy hook is nil and
+// the directory must behave exactly as it did before gates existed.
+func TestGetYPResponse_NoPluginHostLeavesDirectoryWorking(t *testing.T) {
+ if w := getYP(t, newYP(true, nil)); w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", w.Code)
+ }
+ if w := getYP(t, newYP(false, nil)); w.Code != http.StatusNotFound {
+ t.Fatalf("directory off: status = %d, want 404", w.Code)
+ }
+}
+
+// A blocked directory must also stop the outbound ping, otherwise the instance
+// keeps announcing itself to a directory that can no longer read it.
+func TestPing_SkippedWhenTheGateBlocksTheDirectory(t *testing.T) {
+ tests := []struct {
+ name string
+ directoryEnabled bool
+ directoryAvailable func() bool
+ }{
+ {"gate blocks the directory", true, func() bool { return false }},
+ {"directory listing is off", false, func() bool { return true }},
+ {"both off", false, func() bool { return false }},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ y := newYP(tc.directoryEnabled, tc.directoryAvailable)
+ // GetServerURL is only reached once both checks pass; the stub
+ // would otherwise send a real request. Reaching it means the
+ // guard failed to stop the ping.
+ y.getStatus = func() models.Status {
+ t.Fatal("ping proceeded past the directory-availability guard")
+ return models.Status{}
+ }
+ y.ping()
+ })
+ }
+}
diff --git a/yp/yp.go b/yp/yp.go
index 8cb2687686..76ba74fadf 100644
--- a/yp/yp.go
+++ b/yp/yp.go
@@ -32,10 +32,10 @@ type YP struct {
// server URL/name, registration key, etc.) read on each ping and on
// every YP API response.
configRepository configrepository.ConfigRepository
-
- // inErrorState tracks whether we've already logged an error for the
- // current configuration to avoid spamming the log on repeated pings.
- inErrorState bool
+ // directoryAvailable is controlled by the active auth gate. A blocked
+ // stream-status policy disables both pings and the public YP response.
+ directoryAvailable func() bool
+ inErrorState bool
}
// Deps lists the explicit dependencies for the YP service.
@@ -73,6 +73,11 @@ func (yp *YP) SetGetStatus(fn func() models.Status) {
yp.getStatus = fn
}
+// SetDirectoryAvailable wires the auth-gate policy after plugin host startup.
+func (yp *YP) SetDirectoryAvailable(fn func() bool) {
+ yp.directoryAvailable = fn
+}
+
// Start is run when a live stream begins to start pinging YP.
func (yp *YP) Start() {
yp.timer = time.NewTicker(pingInterval)
@@ -88,28 +93,42 @@ func (yp *YP) Stop() {
yp.timer.Stop()
}
-func (yp *YP) ping() {
+// shouldPing reports whether this instance is currently in a state where
+// announcing itself to the directory makes sense: the gate's access policy
+// allows directory listing, the operator has listing switched on, the stream
+// is live, and the configured public URL is usable.
+func (yp *YP) shouldPing() (instanceURL string, ok bool) {
+ if yp.directoryAvailable != nil && !yp.directoryAvailable() {
+ return "", false
+ }
if !yp.configRepository.GetDirectoryEnabled() {
- return
+ return "", false
}
// Hack: Don't allow ping'ing when offline.
// It shouldn't even be trying to, but on some instances the ping timer isn't stopping.
if !yp.getStatus().Online {
- return
+ return "", false
}
myInstanceURL := yp.configRepository.GetServerURL()
if myInstanceURL == "" {
log.Warnln("Server URL not set in the configuration. Directory access is disabled until this is set.")
- return
+ return "", false
}
- isValidInstanceURL := isURL(myInstanceURL)
- if myInstanceURL == "" || !isValidInstanceURL {
+ if !isURL(myInstanceURL) {
if !yp.inErrorState {
log.Warnln("YP Error: unable to use", myInstanceURL, "as a public instance URL. Fix this value in your configuration.")
}
yp.inErrorState = true
+ return "", false
+ }
+ return myInstanceURL, true
+}
+
+func (yp *YP) ping() {
+ myInstanceURL, ok := yp.shouldPing()
+ if !ok {
return
}