Skip to content

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

Add inbound Fediverse plugin hooks (#5039)

Gabe Kangasfaa95733e9b7
diff --git a/FEDERATION.md b/FEDERATION.md
index 3605b4bc32..085947fadc 100644
--- a/FEDERATION.md
+++ b/FEDERATION.md
@@ -34,7 +34,7 @@ Owncast actors do not follow other actors. The `following` collection endpoint r
| Activity | Object | Send | Receive | Notes |
|----------|--------|:----:|:-------:|-------|
-| `Create` | `Note` | Yes | No | Sent on go-live and manual fediverse posts. Incoming posts are ignored. |
+| `Create` | `Note` | Yes | Yes | Sent on go-live and manual fediverse posts. Qualifying inbound notes produce plugin mention or reply events only. |
| `Update` | `Service` | Yes | No | Sent when server profile changes. |
| `Update` | `Person` | No | Yes | Updates cached follower profile information. |
| `Follow` | - | No | Yes | Queued for approval if private mode is enabled. |
@@ -46,7 +46,7 @@ Owncast actors do not follow other actors. The `following` collection endpoint r
| `Accept` | `QuoteRequest` | Yes | No | Sent when the quoted post exists and quoting is allowed. Carries the `QuoteAuthorization` stamp IRI in `result`. |
| `Reject` | `QuoteRequest` | Yes | No | Sent for unknown posts, while in private mode, or when quoting is disabled. |
-Owncast is a broadcast-only service. It does not follow other actors or accept incoming posts.
+Owncast is a broadcast-only service. It does not follow other actors. Inbound posts are not displayed as a social timeline or federated onward.
## Notes
@@ -80,6 +80,21 @@ Owncast implements the quoted-server side of [FEP-044f](https://codeberg.org/fed
- Quoting can be turned off by the operator in the admin under the Social configuration ("Allow quotes"). It is enabled by default.
- Owncast does not author quote posts and does not revoke previously issued stamps.
+## Plugin Integration
+
+Inbound Fediverse activities can produce internal plugin events. These subscriptions are not external HTTP webhooks. A plugin must declare the `fediverse.inbound` permission to subscribe to `fediverse.follow`, `fediverse.like`, `fediverse.repost`, `fediverse.mention`, `fediverse.reply`, `fediverse.quote`, or `fediverse.activity`.
+
+All inbox requests must pass HTTP signature verification and the activity actor must share an origin with the verified signing key owner. After those checks, `fediverse.activity` receives the raw JSON object in addition to any specialized event the activity produces.
+
+Inbound `Create(Note)` activities have narrower requirements for mention and reply events. The `Create` must contain exactly one actor and exactly one `Note`. The note must have an IRI and exactly one `attributedTo` value that matches the activity actor. The resolved actor must also match the activity actor.
+
+- A note whose first `inReplyTo` IRI identifies a locally authored post produces `fediverse.reply`.
+- Any other qualifying note produces `fediverse.mention` only when the `Create` or `Note` addresses the local actor in `to` or `cc`.
+
+These inbound notes are delivered to plugins. Owncast does not add them to a social timeline or federate them onward.
+
+An accepted `QuoteRequest` produces `fediverse.quote` after Owncast signs and queues the acceptance. Its payload contains the remote actor and the target, which is the locally authored quoted post. Rejected quote requests do not produce this event.
+
## Addressing
Public posts are addressed to:
@@ -138,7 +153,7 @@ Owncast supports blocking at the domain and individual actor level. Blocked enti
- Owncast uses `Service` actor type, not `Person`
- There is no `following` collection (Owncast does not follow accounts)
-- Owncast does not accept incoming posts (`Create` from remote actors is ignored)
+- Owncast does not display inbound `Create(Note)` activities as social timeline posts or federate them onward. Qualifying mentions and replies are delivered only to plugins
- Engagement (`Like`, `Announce`) can be displayed in the live chat if enabled
- The `sensitive` flag indicates NSFW content for the entire stream
diff --git a/main.go b/main.go
index 23bd5cd7ec..80b5714aeb 100644
--- a/main.go
+++ b/main.go
@@ -261,6 +261,7 @@ func main() {
Builder: apBuilder,
Signer: apSigner,
Resolver: apResolver,
+ Events: eventDispatcher,
Config: cfg,
})
apSvc.Start()
diff --git a/models/eventType.go b/models/eventType.go
index f6983f0873..3c16f51daa 100644
--- a/models/eventType.go
+++ b/models/eventType.go
@@ -14,6 +14,18 @@ const (
UserNameChanged EventType = "NAME_CHANGE"
// FediverseEngagementFollow is the event sent when a user follows the stream.
FediverseEngagementFollow EventType = "FEDIVERSE_ENGAGEMENT_FOLLOW"
+ // FediverseEngagementLike is the internal event sent when a remote user likes a local post.
+ FediverseEngagementLike EventType = "FEDIVERSE_ENGAGEMENT_LIKE"
+ // FediverseEngagementRepost is the internal event sent when a remote user reposts a local post.
+ FediverseEngagementRepost EventType = "FEDIVERSE_ENGAGEMENT_REPOST"
+ // FediverseEngagementQuote is the internal event sent when a remote user quotes a local post.
+ FediverseEngagementQuote EventType = "FEDIVERSE_ENGAGEMENT_QUOTE"
+ // FediverseMention is the internal event sent when a remote post mentions the stream.
+ FediverseMention EventType = "FEDIVERSE_MENTION"
+ // FediverseReply is the internal event sent when a remote user replies to a local post.
+ FediverseReply EventType = "FEDIVERSE_REPLY"
+ // FediverseActivity is the internal event carrying a verified inbound ActivityPub activity.
+ FediverseActivity EventType = "FEDIVERSE_ACTIVITY"
// VisibiltyToggled is the event sent when a chat message's visibility changes.
VisibiltyToggled EventType = "VISIBILITY-UPDATE"
// PING is a ping message.
diff --git a/pluginhost/pluginevents.go b/pluginhost/pluginevents.go
index 3efd575222..634b7893c7 100644
--- a/pluginhost/pluginevents.go
+++ b/pluginhost/pluginevents.go
@@ -2,9 +2,12 @@ package pluginhost
import (
"context"
+ "encoding/json"
+ "strings"
"time"
"github.com/owncast/owncast/models"
+ activityevents "github.com/owncast/owncast/services/activitypub/events"
"github.com/owncast/owncast/services/chat/events"
"github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/services/plugins"
@@ -169,21 +172,20 @@ func newHelpResponder(snapshot func() []*plugins.Loaded, post func(text string))
}
// newPluginEventListener returns a dispatcher.Listener that translates each
-// Owncast event (carried as a webhooks.WebhookEvent) into the plugin SDK's
-// payload shape and dispatches it to subscribed plugins. Dispatch runs on its
-// own goroutine so a slow plugin never blocks the event source (the chat hot
-// path).
+// Owncast event into the plugin SDK's payload shape and dispatches it to
+// subscribed plugins. Dispatch runs on its own goroutine so a slow plugin
+// never blocks the event source (the chat hot path).
func newPluginEventListener(pluginDispatcher *plugins.Dispatcher) dispatcher.Listener {
return func(ctx context.Context, e dispatcher.Event) {
- webhookEvent, ok := e.Payload.(webhooks.WebhookEvent)
- if !ok {
+ events := translatePluginEvent(e)
+ if len(events) == 0 {
return
}
// Notifications are fire-and-forget: detach from the publisher's
// context so the dispatch isn't cancelled when the publishing call
// returns. Per-plugin timeouts still apply inside Dispatch.
ctx = context.WithoutCancel(ctx)
- for _, pe := range translateWebhookEvent(webhookEvent) {
+ for _, pe := range events {
// Notify-only on purpose: the inbound-chat path already ran
// the filter chain through newPluginChatFilter before the
// event was broadcast. Calling Dispatch (filter + notify)
@@ -195,6 +197,61 @@ func newPluginEventListener(pluginDispatcher *plugins.Dispatcher) dispatcher.Lis
}
}
+// translatePluginEvent maps shared webhook events and internal ActivityPub
+// events onto plugin events. It is pure so each contract can be tested without
+// a live dispatcher.
+func translatePluginEvent(evt dispatcher.Event) []pluginEvent {
+ if webhookEvent, ok := evt.Payload.(webhooks.WebhookEvent); ok {
+ return translateWebhookEvent(webhookEvent)
+ }
+ return translateFediverseEvent(evt)
+}
+
+func translateFediverseEvent(evt dispatcher.Event) []pluginEvent {
+ switch evt.Type {
+ case models.FediverseActivity:
+ payload, ok := evt.Payload.(json.RawMessage)
+ if !ok {
+ return nil
+ }
+ return []pluginEvent{{plugins.EventFediverseActivity, payload}}
+ case models.FediverseEngagementLike, models.FediverseEngagementRepost, models.FediverseEngagementQuote:
+ payload, ok := evt.Payload.(*activityevents.FediverseEngagementEvent)
+ if !ok || payload == nil {
+ return nil
+ }
+ translated := *payload
+ translated.Actor.Handle = normalizeFediverseHandle(translated.Actor.Handle)
+ var eventType string
+ switch evt.Type {
+ case models.FediverseEngagementLike:
+ eventType = plugins.EventFediverseLike
+ case models.FediverseEngagementRepost:
+ eventType = plugins.EventFediverseRepost
+ case models.FediverseEngagementQuote:
+ eventType = plugins.EventFediverseQuote
+ }
+ return []pluginEvent{{eventType, translated}}
+ case models.FediverseMention, models.FediverseReply:
+ payload, ok := evt.Payload.(*activityevents.FediverseInboundPostEvent)
+ if !ok || payload == nil {
+ return nil
+ }
+ translated := *payload
+ translated.Actor.Handle = normalizeFediverseHandle(translated.Actor.Handle)
+ eventType := plugins.EventFediverseMention
+ if evt.Type == models.FediverseReply {
+ eventType = plugins.EventFediverseReply
+ }
+ return []pluginEvent{{eventType, translated}}
+ }
+ return nil
+}
+
+func normalizeFediverseHandle(handle string) string {
+ return "@" + strings.TrimLeft(handle, "@")
+}
+
// translateWebhookEvent maps an Owncast webhook event onto the plugin events
// it should produce (zero, one, or — for a multi-message moderation toggle —
// several). It's pure so the mapping can be tested without a live dispatcher.
@@ -209,6 +266,21 @@ func translateWebhookEvent(evt webhooks.WebhookEvent) []pluginEvent {
return translateChatEvent(evt)
case models.StreamStarted, models.StreamStopped, models.StreamTitleUpdated:
return translateStreamEvent(evt)
+ case models.FediverseEngagementFollow:
+ data, ok := evt.EventData.(*webhooks.WebhookFediverseEngagementFollowEventData)
+ if !ok || data == nil {
+ return nil
+ }
+ return []pluginEvent{{
+ plugins.EventFediverseFollow,
+ activityevents.FediverseEngagementEvent{
+ Actor: activityevents.FediverseActor{
+ Name: data.Name,
+ Handle: normalizeFediverseHandle(data.Username),
+ Image: data.Image,
+ },
+ },
+ }}
}
return nil
}
diff --git a/pluginhost/pluginevents_test.go b/pluginhost/pluginevents_test.go
index 41b015ba48..fb3229c6e8 100644
--- a/pluginhost/pluginevents_test.go
+++ b/pluginhost/pluginevents_test.go
@@ -1,10 +1,13 @@
package pluginhost
import (
+ "encoding/json"
"testing"
"time"
"github.com/owncast/owncast/models"
+ activityevents "github.com/owncast/owncast/services/activitypub/events"
+ "github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/services/plugins"
"github.com/owncast/owncast/services/webhooks"
)
@@ -51,6 +54,141 @@ func TestTranslateWebhookEvent_ChatMessageOnlyForUserMessages(t *testing.T) {
}
}
+func TestTranslatePluginEvent_FediverseEvents(t *testing.T) {
+ actor := activityevents.FediverseActor{
+ Name: "Alice Example",
+ Handle: "@@[email protected]",
+ URL: "https://social.example/users/alice",
+ Image: "https://social.example/users/alice/avatar.png",
+ }
+ engagement := func(target string) *activityevents.FediverseEngagementEvent {
+ return &activityevents.FediverseEngagementEvent{
+ Actor: actor,
+ Target: &activityevents.FediverseTarget{URL: target},
+ }
+ }
+ post := &activityevents.FediverseInboundPostEvent{
+ Actor: actor,
+ Content: "<p>Hello <a href=\"https://owncast.example\">@streamer</a></p>",
+ ContentText: "Hello @streamer",
+ URL: "https://social.example/posts/123",
+ PostedAt: "2026-07-10T12:00:00Z",
+ InReplyTo: "https://owncast.example/federation/post/parent",
+ Attachments: []activityevents.FediverseAttachment{{
+ URL: "https://social.example/media/photo.jpg",
+ MediaType: "image/jpeg",
+ Alt: "A photo",
+ }},
+ Language: "en",
+ }
+
+ tests := []struct {
+ name string
+ event dispatcher.Event
+ eventType string
+ json string
+ }{
+ {
+ name: "follow",
+ event: dispatcher.Event{Payload: webhooks.WebhookEvent{
+ Type: models.FediverseEngagementFollow,
+ EventData: &webhooks.WebhookFediverseEngagementFollowEventData{
+ Name: actor.Name,
+ Username: "[email protected]",
+ Image: actor.Image,
+ ServerURL: "https://owncast.example",
+ },
+ }},
+ eventType: "fediverse.follow",
+ json: `{"actor":{"name":"Alice Example","handle":"@[email protected]","image":"https://social.example/users/alice/avatar.png"}}`,
+ },
+ {
+ name: "like",
+ event: dispatcher.Event{Type: models.FediverseEngagementLike, Payload: engagement("https://owncast.example/federation/post/liked")},
+ eventType: "fediverse.like",
+ json: `{"actor":{"name":"Alice Example","handle":"@[email protected]","url":"https://social.example/users/alice","image":"https://social.example/users/alice/avatar.png"},"target":{"url":"https://owncast.example/federation/post/liked"}}`,
+ },
+ {
+ name: "repost",
+ event: dispatcher.Event{Type: models.FediverseEngagementRepost, Payload: engagement("https://owncast.example/federation/post/reposted")},
+ eventType: "fediverse.repost",
+ json: `{"actor":{"name":"Alice Example","handle":"@[email protected]","url":"https://social.example/users/alice","image":"https://social.example/users/alice/avatar.png"},"target":{"url":"https://owncast.example/federation/post/reposted"}}`,
+ },
+ {
+ name: "mention",
+ event: dispatcher.Event{Type: models.FediverseMention, Payload: post},
+ eventType: "fediverse.mention",
+ json: `{"actor":{"name":"Alice Example","handle":"@[email protected]","url":"https://social.example/users/alice","image":"https://social.example/users/alice/avatar.png"},"content":"\u003cp\u003eHello \u003ca href=\"https://owncast.example\"\u003e@streamer\u003c/a\u003e\u003c/p\u003e","contentText":"Hello @streamer","url":"https://social.example/posts/123","postedAt":"2026-07-10T12:00:00Z","inReplyTo":"https://owncast.example/federation/post/parent","attachments":[{"url":"https://social.example/media/photo.jpg","mediaType":"image/jpeg","alt":"A photo"}],"language":"en"}`,
+ },
+ {
+ name: "reply",
+ event: dispatcher.Event{Type: models.FediverseReply, Payload: post},
+ eventType: "fediverse.reply",
+ json: `{"actor":{"name":"Alice Example","handle":"@[email protected]","url":"https://social.example/users/alice","image":"https://social.example/users/alice/avatar.png"},"content":"\u003cp\u003eHello \u003ca href=\"https://owncast.example\"\u003e@streamer\u003c/a\u003e\u003c/p\u003e","contentText":"Hello @streamer","url":"https://social.example/posts/123","postedAt":"2026-07-10T12:00:00Z","inReplyTo":"https://owncast.example/federation/post/parent","attachments":[{"url":"https://social.example/media/photo.jpg","mediaType":"image/jpeg","alt":"A photo"}],"language":"en"}`,
+ },
+ {
+ name: "quote",
+ event: dispatcher.Event{Type: models.FediverseEngagementQuote, Payload: engagement("https://owncast.example/federation/post/quoted")},
+ eventType: "fediverse.quote",
+ json: `{"actor":{"name":"Alice Example","handle":"@[email protected]","url":"https://social.example/users/alice","image":"https://social.example/users/alice/avatar.png"},"target":{"url":"https://owncast.example/federation/post/quoted"}}`,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ out := translatePluginEvent(tt.event)
+ if len(out) != 1 {
+ t.Fatalf("expected 1 event, got %d", len(out))
+ }
+ if out[0].eventType != tt.eventType {
+ t.Fatalf("eventType = %q want %q", out[0].eventType, tt.eventType)
+ }
+ payload, err := json.Marshal(out[0].payload)
+ if err != nil {
+ t.Fatalf("marshal payload: %v", err)
+ }
+ if string(payload) != tt.json {
+ t.Errorf("payload JSON = %s want %s", payload, tt.json)
+ }
+ })
+ }
+}
+
+func TestTranslatePluginEvent_FediverseActivityPassesThroughRawJSON(t *testing.T) {
+ raw := json.RawMessage(`{"type":"Like","actor":"https://social.example/users/alice"}`)
+ out := translatePluginEvent(dispatcher.Event{Type: models.FediverseActivity, Payload: raw})
+ if len(out) != 1 {
+ t.Fatalf("expected 1 event, got %d", len(out))
+ }
+ if out[0].eventType != "fediverse.activity" {
+ t.Fatalf("eventType = %q want %q", out[0].eventType, "fediverse.activity")
+ }
+ payload, err := json.Marshal(out[0].payload)
+ if err != nil {
+ t.Fatalf("marshal payload: %v", err)
+ }
+ if string(payload) != string(raw) {
+ t.Errorf("payload JSON = %s want %s", payload, raw)
+ }
+}
+
+func TestTranslatePluginEvent_FediverseWrongPayloadTypes(t *testing.T) {
+ tests := []dispatcher.Event{
+ {Payload: webhooks.WebhookEvent{Type: models.FediverseEngagementFollow, EventData: struct{}{}}},
+ {Type: models.FediverseEngagementLike, Payload: struct{}{}},
+ {Type: models.FediverseEngagementRepost, Payload: struct{}{}},
+ {Type: models.FediverseMention, Payload: struct{}{}},
+ {Type: models.FediverseReply, Payload: struct{}{}},
+ {Type: models.FediverseEngagementQuote, Payload: struct{}{}},
+ {Type: models.FediverseActivity, Payload: []byte(`{}`)},
+ }
+ for _, event := range tests {
+ if out := translatePluginEvent(event); len(out) != 0 {
+ t.Errorf("%s with payload %T produced %d events", event.Type, event.Payload, len(out))
+ }
+ }
+}
+
func TestTranslateWebhookEvent_SkipsBotAuthoredMessages(t *testing.T) {
// A message a plugin posted (under its bot identity) must not be delivered
// back to plugins, or chat-reacting plugins would echo-loop forever.
diff --git a/services/activitypub/activitypub.go b/services/activitypub/activitypub.go
index 019f725946..41d293905b 100644
--- a/services/activitypub/activitypub.go
+++ b/services/activitypub/activitypub.go
@@ -23,6 +23,7 @@ import (
"github.com/owncast/owncast/services/activitypub/workerpool"
"github.com/owncast/owncast/services/chat"
"github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/services/webhooks"
)
@@ -51,6 +52,7 @@ type Deps struct {
Builder *apmodels.Builder
Signer *crypto.Signer
Resolver *apresolvers.Resolver
+ Events *dispatcher.Dispatcher
Config *config.Config
}
@@ -83,6 +85,7 @@ func New(deps Deps) *Service {
Builder: deps.Builder,
Signer: deps.Signer,
Resolver: deps.Resolver,
+ Events: deps.Events,
})
jobsSvc := jobs.New(jobs.Deps{
diff --git a/services/activitypub/events/fediverseInboundEvent.go b/services/activitypub/events/fediverseInboundEvent.go
new file mode 100644
index 0000000000..9c98f1106a
--- /dev/null
+++ b/services/activitypub/events/fediverseInboundEvent.go
@@ -0,0 +1,39 @@
+package events
+
+// FediverseActor is the remote account responsible for an inbound activity.
+type FediverseActor struct {
+ Name string `json:"name"`
+ Handle string `json:"handle"`
+ URL string `json:"url,omitempty"`
+ Image string `json:"image,omitempty"`
+}
+
+// FediverseTarget identifies the local object acted on by a remote account.
+type FediverseTarget struct {
+ URL string `json:"url"`
+}
+
+// FediverseEngagementEvent is the payload for inbound like, repost, and quote events.
+type FediverseEngagementEvent struct {
+ Actor FediverseActor `json:"actor"`
+ Target *FediverseTarget `json:"target,omitempty"`
+}
+
+// FediverseAttachment is media attached to an inbound post.
+type FediverseAttachment struct {
+ URL string `json:"url"`
+ MediaType string `json:"mediaType"`
+ Alt string `json:"alt,omitempty"`
+}
+
+// FediverseInboundPostEvent is the payload for inbound mention and reply events.
+type FediverseInboundPostEvent struct {
+ Actor FediverseActor `json:"actor"`
+ Content string `json:"content"`
+ ContentText string `json:"contentText"`
+ URL string `json:"url"`
+ PostedAt string `json:"postedAt"`
+ InReplyTo string `json:"inReplyTo,omitempty"`
+ Attachments []FediverseAttachment `json:"attachments,omitempty"`
+ Language string `json:"language,omitempty"`
+}
diff --git a/services/activitypub/inbox/announce.go b/services/activitypub/inbox/announce.go
index 020f11e1ca..8c8c195a77 100644
--- a/services/activitypub/inbox/announce.go
+++ b/services/activitypub/inbox/announce.go
@@ -2,47 +2,23 @@ package inbox
import (
"context"
- "time"
"code.superseriousbusiness.org/activity/streams/vocab"
- "github.com/pkg/errors"
- "github.com/owncast/owncast/services/activitypub/apmodels"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/services/chat/events"
)
func (s *Service) handleAnnounceRequest(c context.Context, activity vocab.ActivityStreamsAnnounce) error {
- objectIRI, err := apmodels.GetIRIStringFromObjectProperty(activity.GetActivityStreamsObject())
- if err != nil {
- return errors.Wrap(err, "announce activity is missing object IRI")
- }
-
- actorIRI, err := apmodels.GetIRIStringFromActorProperty(activity.GetActivityStreamsActor())
- if err != nil {
- return errors.Wrap(err, "announce activity is missing actor IRI")
- }
-
- actorReference := activity.GetActivityStreamsActor()
-
- if hasPreviouslyhandled, err := s.persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementRepost); hasPreviouslyhandled || err != nil {
- return errors.Wrap(err, "inbound activity of share/re-post has already been handled")
- }
-
- // Shares need to match a post we had already sent.
- _, isLiveNotification, timestamp, err := s.persistence.GetObjectByIRI(objectIRI)
- if err != nil {
- return errors.Wrap(err, "Could not find post locally")
- }
-
- // Don't allow old activities to be liked.
- if time.Since(timestamp) > maxAgeForEngagement {
- return errors.New("Activity is too old to be shared")
- }
-
- // Save as an accepted activity.
- if err := s.persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementRepost, time.Now()); err != nil {
- return errors.Wrap(err, "unable to save inbound share/re-post activity")
- }
-
- return s.handleEngagementActivity(events.FediverseEngagementRepost, isLiveNotification, actorReference, events.FediverseEngagementRepost)
+ return s.acceptEngagementRequest(c, activity.GetActivityStreamsObject(), activity.GetActivityStreamsActor(), engagementRequest{
+ objectError: "announce activity is missing object IRI",
+ actorError: "announce activity is missing actor IRI",
+ maxAgeError: "Activity is too old to be shared",
+ resolveActorError: "unable to resolve actor of share/re-post activity",
+ saveError: "unable to save inbound share/re-post activity",
+ internalEventType: models.FediverseEngagementRepost,
+ persistedEvent: events.FediverseEngagementRepost,
+ chatEvent: events.FediverseEngagementRepost,
+ chatAction: events.FediverseEngagementRepost,
+ })
}
diff --git a/services/activitypub/inbox/chat.go b/services/activitypub/inbox/chat.go
index ecc41dcb30..75f2fa4ca5 100644
--- a/services/activitypub/inbox/chat.go
+++ b/services/activitypub/inbox/chat.go
@@ -3,9 +3,10 @@ package inbox
import (
"fmt"
- "code.superseriousbusiness.org/activity/streams/vocab"
"github.com/microcosm-cc/bluemonday"
+ "github.com/owncast/owncast/services/activitypub/apmodels"
+ activityevents "github.com/owncast/owncast/services/activitypub/events"
"github.com/owncast/owncast/services/chat/events"
)
@@ -20,7 +21,16 @@ func sanitizeActorName(displayName, username string) string {
return name
}
-func (s *Service) handleEngagementActivity(eventType events.EventType, isLiveNotification bool, actorReference vocab.ActivityStreamsActorProperty, action string) error {
+func fediverseActorFromResolvedActor(actor apmodels.ActivityPubActor) activityevents.FediverseActor {
+ return activityevents.FediverseActor{
+ Name: sanitizeActorName(actor.Name, actor.Username),
+ Handle: actor.FullUsername,
+ URL: actor.ActorIriString(),
+ Image: actor.ImageString(),
+ }
+}
+
+func (s *Service) handleEngagementActivity(eventType events.EventType, isLiveNotification bool, actor apmodels.ActivityPubActor, action string) error {
// Do nothing if displaying engagement actions has been turned off.
if !s.configRepository.GetFederationShowEngagement() {
return nil
@@ -31,12 +41,6 @@ func (s *Service) handleEngagementActivity(eventType events.EventType, isLiveNot
return nil
}
- // Get actor of the action
- actor, err := s.resolver.GetResolvedActorFromActorProperty(actorReference)
- if err != nil {
- return fmt.Errorf("unable to resolve actor for engagement activity: %w", err)
- }
-
// Send chat message
actorName := sanitizeActorName(actor.Name, actor.Username)
actorIRI := actor.ActorIriString()
diff --git a/services/activitypub/inbox/create.go b/services/activitypub/inbox/create.go
index 97f7580a64..bdd7cf08b4 100644
--- a/services/activitypub/inbox/create.go
+++ b/services/activitypub/inbox/create.go
@@ -2,17 +2,292 @@ package inbox
import (
"context"
+ "database/sql"
+ "net/url"
+ "sort"
+ "time"
"code.superseriousbusiness.org/activity/streams/vocab"
"github.com/pkg/errors"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/services/activitypub/apmodels"
+ "github.com/owncast/owncast/services/activitypub/events"
+ "github.com/owncast/owncast/utils"
)
func (s *Service) handleCreateRequest(c context.Context, activity vocab.ActivityStreamsCreate) error {
- iri, err := apmodels.GetIRIStringFromJSONLDIdProperty(activity.GetJSONLDId())
+ validated, err := validateCreateNote(activity)
+ if err != nil || validated == nil {
+ return err
+ }
+
+ eventType, inReplyTo, relevant, err := s.classifyCreateNote(activity, validated.note)
+ if err != nil || !relevant {
+ return err
+ }
+
+ actor, err := s.resolver.GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())
+ if err != nil {
+ return errors.Wrap(err, "unable to resolve create actor")
+ }
+ if actor.ActorIriString() != validated.actorIRI {
+ return errors.New("resolved create actor does not match activity actor")
+ }
+
+ payload := createPostPayload(validated.note, validated.noteIRI, inReplyTo, actor)
+ claimed, err := s.persistence.ClaimInboundFediverseActivity(validated.createIRI, validated.actorIRI, activity.GetTypeName(), time.Now())
+ if err != nil {
+ return errors.Wrap(err, "unable to claim inbound create activity")
+ }
+ if !claimed {
+ return nil
+ }
+ s.publishFediverseEvent(c, eventType, payload)
+ return nil
+}
+
+type validatedCreate struct {
+ createIRI string
+ actorIRI string
+ noteIRI string
+ note vocab.ActivityStreamsNote
+}
+
+func validateCreateNote(activity vocab.ActivityStreamsCreate) (*validatedCreate, error) {
+ createIRI, err := apmodels.GetIRIStringFromJSONLDIdProperty(activity.GetJSONLDId())
+ if err != nil {
+ return nil, errors.Wrap(err, "create activity is missing IRI")
+ }
+
+ actorIRI, err := activityActorIRI(activity.GetActivityStreamsActor())
+ if err != nil {
+ return nil, errors.Wrap(err, "create activity has invalid actor")
+ }
+
+ object := activity.GetActivityStreamsObject()
+ if object == nil || object.Len() != 1 || object.At(0) == nil || !object.At(0).IsActivityStreamsNote() {
+ return nil, nil
+ }
+ note := object.At(0).GetActivityStreamsNote()
+
+ noteIRI, err := apmodels.GetIRIStringFromJSONLDIdProperty(note.GetJSONLDId())
if err != nil {
- return errors.Wrap(err, "create activity is missing IRI")
+ return nil, errors.Wrap(err, "create note is missing IRI")
+ }
+ if err := validateNoteAttribution(note.GetActivityStreamsAttributedTo(), actorIRI); err != nil {
+ return nil, err
+ }
+
+ return &validatedCreate{
+ createIRI: createIRI,
+ actorIRI: actorIRI,
+ noteIRI: noteIRI,
+ note: note,
+ }, nil
+}
+
+func (s *Service) classifyCreateNote(activity vocab.ActivityStreamsCreate, note vocab.ActivityStreamsNote) (models.EventType, string, bool, error) {
+ inReplyTo := firstInReplyToIRI(note.GetActivityStreamsInReplyTo())
+ if inReplyTo != "" {
+ _, _, _, err := s.persistence.GetNoteByIRI(inReplyTo)
+ if err == nil {
+ return models.FediverseReply, inReplyTo, true, nil
+ }
+ if !errors.Is(err, sql.ErrNoRows) {
+ return "", "", false, errors.Wrap(err, "unable to look up create note parent")
+ }
+ }
+
+ localActor := s.builder.MakeLocalIRIForAccount(s.configRepository.GetFederationUsername())
+ if localActor == nil || !createOrNoteAddresses(activity, note, localActor.String()) {
+ return "", "", false, nil
+ }
+ return models.FediverseMention, inReplyTo, true, nil
+}
+
+func createPostPayload(note vocab.ActivityStreamsNote, noteIRI, inReplyTo string, actor apmodels.ActivityPubActor) *events.FediverseInboundPostEvent {
+ content, language := noteContent(note.GetActivityStreamsContent())
+ postedAt := time.Now().UTC()
+ if published := note.GetActivityStreamsPublished(); published != nil && published.IsXMLSchemaDateTime() {
+ postedAt = published.Get().UTC()
+ }
+
+ postURL := noteIRI
+ if urlProperty := note.GetActivityStreamsUrl(); urlProperty != nil && urlProperty.Len() > 0 {
+ if first := urlProperty.At(0); first != nil && first.IsIRI() && isSafeHTTPURL(first.GetIRI()) {
+ postURL = first.GetIRI().String()
+ }
+ }
+
+ return &events.FediverseInboundPostEvent{
+ Actor: fediverseActorFromResolvedActor(actor),
+ Content: content,
+ ContentText: utils.StripHTML(content),
+ URL: postURL,
+ PostedAt: postedAt.Format(time.RFC3339),
+ InReplyTo: inReplyTo,
+ Attachments: noteAttachments(note.GetActivityStreamsAttachment()),
+ Language: language,
+ }
+}
+
+func activityActorIRI(actor vocab.ActivityStreamsActorProperty) (string, error) {
+ if actor == nil || actor.Len() != 1 || actor.At(0) == nil {
+ return "", errors.New("actor must contain exactly one value")
+ }
+ value := actor.At(0)
+ if value.IsIRI() && value.GetIRI() != nil {
+ return value.GetIRI().String(), nil
+ }
+ if object := value.GetType(); object != nil {
+ return apmodels.GetIRIStringFromJSONLDIdProperty(object.GetJSONLDId())
+ }
+ return "", errors.New("actor is missing IRI")
+}
+
+func validateNoteAttribution(attributedTo vocab.ActivityStreamsAttributedToProperty, actorIRI string) error {
+ if attributedTo == nil || attributedTo.Len() != 1 || attributedTo.At(0) == nil {
+ return errors.New("create note must have exactly one attributedTo")
+ }
+ value := attributedTo.At(0)
+ var attributedToIRI string
+ if value.IsIRI() && value.GetIRI() != nil {
+ attributedToIRI = value.GetIRI().String()
+ } else if object := value.GetType(); object != nil {
+ var err error
+ attributedToIRI, err = apmodels.GetIRIStringFromJSONLDIdProperty(object.GetJSONLDId())
+ if err != nil {
+ return errors.Wrap(err, "create note attributedTo is missing IRI")
+ }
+ }
+ if attributedToIRI == "" || attributedToIRI != actorIRI {
+ return errors.New("create note attributedTo does not match activity actor")
+ }
+ return nil
+}
+
+func firstInReplyToIRI(inReplyTo vocab.ActivityStreamsInReplyToProperty) string {
+ if inReplyTo == nil || inReplyTo.Len() == 0 {
+ return ""
+ }
+ first := inReplyTo.At(0)
+ if first == nil {
+ return ""
+ }
+ if first.IsIRI() && first.GetIRI() != nil {
+ return first.GetIRI().String()
+ }
+ if object := first.GetType(); object != nil {
+ iri, _ := apmodels.GetIRIStringFromJSONLDIdProperty(object.GetJSONLDId())
+ return iri
+ }
+ return ""
+}
+
+func createOrNoteAddresses(activity vocab.ActivityStreamsCreate, note vocab.ActivityStreamsNote, localActorIRI string) bool {
+ return toContainsIRI(activity.GetActivityStreamsTo(), localActorIRI) ||
+ ccContainsIRI(activity.GetActivityStreamsCc(), localActorIRI) ||
+ toContainsIRI(note.GetActivityStreamsTo(), localActorIRI) ||
+ ccContainsIRI(note.GetActivityStreamsCc(), localActorIRI)
+}
+
+func toContainsIRI(property vocab.ActivityStreamsToProperty, target string) bool {
+ if property == nil {
+ return false
+ }
+ for iterator := property.Begin(); iterator != property.End(); iterator = iterator.Next() {
+ if iterator.IsIRI() && iterator.GetIRI() != nil && iterator.GetIRI().String() == target {
+ return true
+ }
+ }
+ return false
+}
+
+func ccContainsIRI(property vocab.ActivityStreamsCcProperty, target string) bool {
+ if property == nil {
+ return false
+ }
+ for iterator := property.Begin(); iterator != property.End(); iterator = iterator.Next() {
+ if iterator.IsIRI() && iterator.GetIRI() != nil && iterator.GetIRI().String() == target {
+ return true
+ }
+ }
+ return false
+}
+
+func noteContent(content vocab.ActivityStreamsContentProperty) (string, string) {
+ if content == nil || content.Len() == 0 {
+ return "", ""
+ }
+ first := content.At(0)
+ if first == nil {
+ return "", ""
+ }
+ if first.IsXMLSchemaString() {
+ return first.GetXMLSchemaString(), ""
+ }
+ if first.IsRDFLangString() {
+ values := first.GetRDFLangString()
+ languages := make([]string, 0, len(values))
+ for language := range values {
+ languages = append(languages, language)
+ }
+ sort.Strings(languages)
+ if len(languages) > 0 {
+ return values[languages[0]], languages[0]
+ }
+ }
+ return "", ""
+}
+
+type attachmentObject interface {
+ GetActivityStreamsUrl() vocab.ActivityStreamsUrlProperty
+ GetActivityStreamsMediaType() vocab.ActivityStreamsMediaTypeProperty
+ GetActivityStreamsName() vocab.ActivityStreamsNameProperty
+}
+
+func noteAttachments(property vocab.ActivityStreamsAttachmentProperty) []events.FediverseAttachment {
+ if property == nil {
+ return nil
+ }
+ var attachments []events.FediverseAttachment
+ for iterator := property.Begin(); iterator != property.End(); iterator = iterator.Next() {
+ var object attachmentObject
+ if iterator.IsActivityStreamsImage() {
+ object = iterator.GetActivityStreamsImage()
+ } else if iterator.IsActivityStreamsDocument() {
+ object = iterator.GetActivityStreamsDocument()
+ } else {
+ continue
+ }
+ if attachment, ok := makeAttachment(object); ok {
+ attachments = append(attachments, attachment)
+ }
+ }
+ return attachments
+}
+
+func isSafeHTTPURL(iri *url.URL) bool {
+ return iri != nil && (iri.Scheme == "http" || iri.Scheme == "https") && iri.Host != ""
+}
+
+func makeAttachment(object attachmentObject) (events.FediverseAttachment, bool) {
+ urlProperty := object.GetActivityStreamsUrl()
+ if urlProperty == nil || urlProperty.Len() == 0 || urlProperty.At(0) == nil || !urlProperty.At(0).IsIRI() {
+ return events.FediverseAttachment{}, false
+ }
+ attachmentIRI := urlProperty.At(0).GetIRI()
+ if !isSafeHTTPURL(attachmentIRI) {
+ return events.FediverseAttachment{}, false
+ }
+
+ attachment := events.FediverseAttachment{URL: attachmentIRI.String()}
+ if mediaType := object.GetActivityStreamsMediaType(); mediaType != nil && mediaType.IsRFCRfc2045() {
+ attachment.MediaType = mediaType.Get()
+ }
+ if name := object.GetActivityStreamsName(); name != nil && name.Len() > 0 && name.At(0) != nil && name.At(0).IsXMLSchemaString() {
+ attachment.Alt = utils.StripHTML(name.At(0).GetXMLSchemaString())
}
- return errors.New("not handling create request of: " + iri)
+ return attachment, true
}
diff --git a/services/activitypub/inbox/create_test.go b/services/activitypub/inbox/create_test.go
new file mode 100644
index 0000000000..64e2c21336
--- /dev/null
+++ b/services/activitypub/inbox/create_test.go
@@ -0,0 +1,418 @@
+package inbox
+
+import (
+ "context"
+ "net/url"
+ "sync"
+ "testing"
+ "time"
+
+ "code.superseriousbusiness.org/activity/streams"
+ "code.superseriousbusiness.org/activity/streams/vocab"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/persistence/configrepository"
+ "github.com/owncast/owncast/services/activitypub/apmodels"
+ "github.com/owncast/owncast/services/activitypub/events"
+ "github.com/owncast/owncast/services/activitypub/persistence"
+ "github.com/owncast/owncast/services/activitypub/resolvers"
+ "github.com/owncast/owncast/services/dispatcher"
+)
+
+type createTestFixture struct {
+ service *Service
+ activity vocab.ActivityStreamsCreate
+ note vocab.ActivityStreamsNote
+ actorIRI *url.URL
+ localActor *url.URL
+ events []dispatcher.Event
+ eventsMu sync.Mutex
+}
+
+func newCreateTestFixture(t *testing.T, suffix string) *createTestFixture {
+ t.Helper()
+
+ configRepository := configrepository.New(testDatastore)
+ builder := apmodels.New(apmodels.Deps{ConfigRepository: configRepository})
+ eventDispatcher := dispatcher.New()
+ fixture := &createTestFixture{
+ actorIRI: mustCreateTestURL(t, "https://remote.example/users/alice"),
+ localActor: builder.MakeLocalIRIForAccount(configRepository.GetFederationUsername()),
+ }
+ eventDispatcher.AddListener(func(_ context.Context, event dispatcher.Event) {
+ fixture.eventsMu.Lock()
+ defer fixture.eventsMu.Unlock()
+ fixture.events = append(fixture.events, event)
+ })
+ fixture.service = New(Deps{
+ Persistence: persistence.New(testDatastore, nil),
+ ConfigRepository: configRepository,
+ Builder: builder,
+ Resolver: resolvers.New(resolvers.Deps{
+ ConfigRepository: configRepository,
+ Builder: builder,
+ }),
+ Events: eventDispatcher,
+ })
+
+ person := streams.NewActivityStreamsPerson()
+ personID := streams.NewJSONLDIdProperty()
+ personID.SetIRI(fixture.actorIRI)
+ person.SetJSONLDId(personID)
+ inbox := streams.NewActivityStreamsInboxProperty()
+ inbox.SetIRI(mustCreateTestURL(t, "https://remote.example/users/alice/inbox"))
+ person.SetActivityStreamsInbox(inbox)
+ name := streams.NewActivityStreamsNameProperty()
+ name.AppendXMLSchemaString("Alice")
+ person.SetActivityStreamsName(name)
+ username := streams.NewActivityStreamsPreferredUsernameProperty()
+ username.SetXMLSchemaString("alice")
+ person.SetActivityStreamsPreferredUsername(username)
+ publicKey := streams.NewW3IDSecurityV1PublicKeyProperty()
+ publicKey.AppendW3IDSecurityV1PublicKey(streams.NewW3IDSecurityV1PublicKey())
+ person.SetW3IDSecurityV1PublicKey(publicKey)
+
+ fixture.activity = streams.NewActivityStreamsCreate()
+ createID := streams.NewJSONLDIdProperty()
+ createID.SetIRI(mustCreateTestURL(t, "https://remote.example/activities/"+suffix))
+ fixture.activity.SetJSONLDId(createID)
+ actor := streams.NewActivityStreamsActorProperty()
+ actor.AppendActivityStreamsPerson(person)
+ fixture.activity.SetActivityStreamsActor(actor)
+
+ fixture.note = streams.NewActivityStreamsNote()
+ noteID := streams.NewJSONLDIdProperty()
+ noteID.SetIRI(mustCreateTestURL(t, "https://remote.example/posts/"+suffix))
+ fixture.note.SetJSONLDId(noteID)
+ attributedTo := streams.NewActivityStreamsAttributedToProperty()
+ attributedTo.AppendIRI(fixture.actorIRI)
+ fixture.note.SetActivityStreamsAttributedTo(attributedTo)
+ object := streams.NewActivityStreamsObjectProperty()
+ object.AppendActivityStreamsNote(fixture.note)
+ fixture.activity.SetActivityStreamsObject(object)
+
+ return fixture
+}
+
+func TestHandleCreateMentionExtractsPost(t *testing.T) {
+ fixture := newCreateTestFixture(t, "mention")
+ cc := streams.NewActivityStreamsCcProperty()
+ cc.AppendIRI(fixture.localActor)
+ fixture.activity.SetActivityStreamsCc(cc)
+
+ content := streams.NewActivityStreamsContentProperty()
+ content.AppendXMLSchemaString("<p>Hello <strong>world</strong></p>")
+ fixture.note.SetActivityStreamsContent(content)
+ postURL := streams.NewActivityStreamsUrlProperty()
+ postURL.AppendIRI(mustCreateTestURL(t, "https://remote.example/@alice/mention"))
+ fixture.note.SetActivityStreamsUrl(postURL)
+ publishedAt := time.Date(2026, time.July, 10, 12, 34, 56, 0, time.FixedZone("offset", 2*60*60))
+ published := streams.NewActivityStreamsPublishedProperty()
+ published.Set(publishedAt)
+ fixture.note.SetActivityStreamsPublished(published)
+
+ attachments := streams.NewActivityStreamsAttachmentProperty()
+ image := streams.NewActivityStreamsImage()
+ imageURL := streams.NewActivityStreamsUrlProperty()
+ imageURL.AppendIRI(mustCreateTestURL(t, "https://cdn.remote.example/image.jpg"))
+ image.SetActivityStreamsUrl(imageURL)
+ imageType := streams.NewActivityStreamsMediaTypeProperty()
+ imageType.Set("image/jpeg")
+ image.SetActivityStreamsMediaType(imageType)
+ imageName := streams.NewActivityStreamsNameProperty()
+ imageName.AppendXMLSchemaString("<b>Alt text</b>")
+ image.SetActivityStreamsName(imageName)
+ attachments.AppendActivityStreamsImage(image)
+ document := streams.NewActivityStreamsDocument()
+ documentURL := streams.NewActivityStreamsUrlProperty()
+ documentURL.AppendIRI(mustCreateTestURL(t, "https://cdn.remote.example/caption.vtt"))
+ document.SetActivityStreamsUrl(documentURL)
+ documentType := streams.NewActivityStreamsMediaTypeProperty()
+ documentType.Set("text/vtt")
+ document.SetActivityStreamsMediaType(documentType)
+ attachments.AppendActivityStreamsDocument(document)
+
+ unsafeDocument := streams.NewActivityStreamsDocument()
+ unsafeURL := streams.NewActivityStreamsUrlProperty()
+ unsafeURL.AppendIRI(mustCreateTestURL(t, "file:///etc/passwd"))
+ unsafeDocument.SetActivityStreamsUrl(unsafeURL)
+ attachments.AppendActivityStreamsDocument(unsafeDocument)
+ fixture.note.SetActivityStreamsAttachment(attachments)
+
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("handle create mention: %v", err)
+ }
+ post := requireCreatePostEvent(t, fixture, models.FediverseMention)
+ if post.Content != "<p>Hello <strong>world</strong></p>" || post.ContentText != "Hello world" {
+ t.Fatalf("unexpected content: HTML %q text %q", post.Content, post.ContentText)
+ }
+ if post.URL != "https://remote.example/@alice/mention" {
+ t.Fatalf("unexpected post URL %q", post.URL)
+ }
+ if post.PostedAt != "2026-07-10T10:34:56Z" {
+ t.Fatalf("unexpected posted time %q", post.PostedAt)
+ }
+ if post.Actor.Handle != "[email protected]" || post.Actor.URL != fixture.actorIRI.String() {
+ t.Fatalf("unexpected actor: %+v", post.Actor)
+ }
+ if len(post.Attachments) != 2 {
+ t.Fatalf("expected safe embedded attachments only, got %+v", post.Attachments)
+ }
+ if got := post.Attachments[0]; got.URL != "https://cdn.remote.example/image.jpg" || got.MediaType != "image/jpeg" || got.Alt != "Alt text" {
+ t.Fatalf("unexpected image attachment: %+v", got)
+ }
+ if got := post.Attachments[1]; got.URL != "https://cdn.remote.example/caption.vtt" || got.MediaType != "text/vtt" {
+ t.Fatalf("unexpected document attachment: %+v", got)
+ }
+}
+
+func TestCreatePostPayloadUsesOnlySafeAbsoluteHTTPURL(t *testing.T) {
+ const noteIRI = "https://remote.example/posts/url-fallback"
+ tests := []struct {
+ name string
+ candidate string
+ want string
+ }{
+ {name: "https", candidate: "https://remote.example/@alice/post", want: "https://remote.example/@alice/post"},
+ {name: "http", candidate: "http://remote.example/@alice/post", want: "http://remote.example/@alice/post"},
+ {name: "file", candidate: "file:///etc/passwd", want: noteIRI},
+ {name: "unsupported scheme", candidate: "ftp://remote.example/post", want: noteIRI},
+ {name: "relative", candidate: "/@alice/post", want: noteIRI},
+ {name: "missing host", candidate: "https:///post", want: noteIRI},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ note := streams.NewActivityStreamsNote()
+ urlProperty := streams.NewActivityStreamsUrlProperty()
+ urlProperty.AppendIRI(mustCreateTestURL(t, tt.candidate))
+ note.SetActivityStreamsUrl(urlProperty)
+
+ payload := createPostPayload(note, noteIRI, "", apmodels.ActivityPubActor{})
+ if payload.URL != tt.want {
+ t.Fatalf("post URL = %q, want %q", payload.URL, tt.want)
+ }
+ })
+ }
+}
+
+func TestHandleCreateLocalReplyTakesPrecedence(t *testing.T) {
+ fixture := newCreateTestFixture(t, "reply")
+ parentIRI := "https://my.cool.site.biz/federation/posts/local-parent"
+ if err := fixture.service.persistence.AddToOutbox(parentIRI, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatalf("save local parent: %v", err)
+ }
+ inReplyTo := streams.NewActivityStreamsInReplyToProperty()
+ inReplyTo.AppendIRI(mustCreateTestURL(t, parentIRI))
+ fixture.note.SetActivityStreamsInReplyTo(inReplyTo)
+
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("handle create reply: %v", err)
+ }
+ post := requireCreatePostEvent(t, fixture, models.FediverseReply)
+ if post.InReplyTo != parentIRI {
+ t.Fatalf("unexpected parent %q", post.InReplyTo)
+ }
+}
+
+func TestHandleCreateUnknownParentIsMention(t *testing.T) {
+ fixture := newCreateTestFixture(t, "unknown-parent")
+ inReplyTo := streams.NewActivityStreamsInReplyToProperty()
+ inReplyTo.AppendIRI(mustCreateTestURL(t, "https://elsewhere.example/posts/unknown"))
+ fixture.note.SetActivityStreamsInReplyTo(inReplyTo)
+ to := streams.NewActivityStreamsToProperty()
+ to.AppendIRI(fixture.localActor)
+ fixture.note.SetActivityStreamsTo(to)
+
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("handle create mention: %v", err)
+ }
+ post := requireCreatePostEvent(t, fixture, models.FediverseMention)
+ if post.InReplyTo != "https://elsewhere.example/posts/unknown" {
+ t.Fatalf("unexpected parent %q", post.InReplyTo)
+ }
+}
+
+func TestHandleCreateUnrelatedAndIRIObjectIgnored(t *testing.T) {
+ fixture := newCreateTestFixture(t, "unrelated")
+ actor := streams.NewActivityStreamsActorProperty()
+ actor.AppendIRI(fixture.actorIRI)
+ fixture.activity.SetActivityStreamsActor(actor)
+ attributedTo := streams.NewActivityStreamsAttributedToProperty()
+ attributedTo.AppendIRI(fixture.actorIRI)
+ fixture.note.SetActivityStreamsAttributedTo(attributedTo)
+
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("unrelated create should be ignored: %v", err)
+ }
+ if len(fixture.events) != 0 {
+ t.Fatalf("unrelated create published %d events", len(fixture.events))
+ }
+
+ object := streams.NewActivityStreamsObjectProperty()
+ object.AppendIRI(mustCreateTestURL(t, "https://remote.example/posts/iri-only"))
+ fixture.activity.SetActivityStreamsObject(object)
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("IRI-only object should be ignored: %v", err)
+ }
+ if len(fixture.events) != 0 {
+ t.Fatalf("IRI-only create published %d events", len(fixture.events))
+ }
+ for _, eventType := range []models.EventType{models.FediverseMention, models.FediverseReply} {
+ handled, err := fixture.service.persistence.HasPreviouslyHandledInboundActivity(
+ "https://remote.example/activities/unrelated",
+ fixture.actorIRI.String(),
+ string(eventType),
+ )
+ if err != nil {
+ t.Fatalf("check ignored activity persistence: %v", err)
+ }
+ if handled {
+ t.Fatalf("ignored create was persisted as %q", eventType)
+ }
+ }
+}
+
+func TestHandleCreateRejectsActorAttributionMismatch(t *testing.T) {
+ fixture := newCreateTestFixture(t, "mismatch")
+ attributedTo := streams.NewActivityStreamsAttributedToProperty()
+ attributedTo.AppendIRI(mustCreateTestURL(t, "https://remote.example/users/mallory"))
+ fixture.note.SetActivityStreamsAttributedTo(attributedTo)
+ to := streams.NewActivityStreamsToProperty()
+ to.AppendIRI(fixture.localActor)
+ fixture.note.SetActivityStreamsTo(to)
+
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err == nil {
+ t.Fatal("expected actor/attributedTo mismatch to be rejected")
+ }
+ if len(fixture.events) != 0 {
+ t.Fatalf("mismatched create published %d events", len(fixture.events))
+ }
+}
+
+func TestHandleCreateDuplicateSuppressed(t *testing.T) {
+ fixture := newCreateTestFixture(t, "duplicate")
+ to := streams.NewActivityStreamsToProperty()
+ to.AppendIRI(fixture.localActor)
+ fixture.note.SetActivityStreamsTo(to)
+
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("first delivery: %v", err)
+ }
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("duplicate delivery: %v", err)
+ }
+ if len(fixture.events) != 1 {
+ t.Fatalf("expected one event after duplicate delivery, got %d", len(fixture.events))
+ }
+}
+
+func TestHandleCreateConcurrentDuplicateSuppressed(t *testing.T) {
+ testDatastore.DB.SetMaxOpenConns(1)
+ fixture := newCreateTestFixture(t, "concurrent-duplicate")
+ to := streams.NewActivityStreamsToProperty()
+ to.AppendIRI(fixture.localActor)
+ fixture.note.SetActivityStreamsTo(to)
+
+ const deliveries = 16
+ start := make(chan struct{})
+ errs := make(chan error, deliveries)
+ var wg sync.WaitGroup
+ wg.Add(deliveries)
+ for range deliveries {
+ go func() {
+ defer wg.Done()
+ <-start
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ errs <- err
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ t.Fatalf("concurrent delivery: %v", err)
+ }
+ if len(fixture.events) != 1 {
+ t.Fatalf("expected one event after concurrent deliveries, got %d", len(fixture.events))
+ }
+}
+
+func TestHandleCreateReplayClassificationChangeSuppressed(t *testing.T) {
+ fixture := newCreateTestFixture(t, "classification-change")
+ parentIRI := "https://my.cool.site.biz/federation/posts/delayed-parent"
+ inReplyTo := streams.NewActivityStreamsInReplyToProperty()
+ inReplyTo.AppendIRI(mustCreateTestURL(t, parentIRI))
+ fixture.note.SetActivityStreamsInReplyTo(inReplyTo)
+ to := streams.NewActivityStreamsToProperty()
+ to.AppendIRI(fixture.localActor)
+ fixture.note.SetActivityStreamsTo(to)
+
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("first delivery: %v", err)
+ }
+ requireCreatePostEvent(t, fixture, models.FediverseMention)
+
+ if err := fixture.service.persistence.AddToOutbox(parentIRI, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatalf("save delayed parent: %v", err)
+ }
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("replayed delivery: %v", err)
+ }
+ if len(fixture.events) != 1 {
+ t.Fatalf("classification-changing replay published an event; total = %d, want 1", len(fixture.events))
+ }
+}
+
+func TestHandleCreatePublishedFallbackAndLanguage(t *testing.T) {
+ fixture := newCreateTestFixture(t, "fallback")
+ to := streams.NewActivityStreamsToProperty()
+ to.AppendIRI(fixture.localActor)
+ fixture.note.SetActivityStreamsTo(to)
+ content := streams.NewActivityStreamsContentProperty()
+ content.AppendRDFLangString(map[string]string{
+ "fr": "<p>Bonjour</p>",
+ "en": "<p>Hello</p>",
+ })
+ fixture.note.SetActivityStreamsContent(content)
+
+ before := time.Now().UTC().Add(-time.Second)
+ if err := fixture.service.handleCreateRequest(context.Background(), fixture.activity); err != nil {
+ t.Fatalf("handle create fallback: %v", err)
+ }
+ after := time.Now().UTC().Add(time.Second)
+ post := requireCreatePostEvent(t, fixture, models.FediverseMention)
+ postedAt, err := time.Parse(time.RFC3339, post.PostedAt)
+ if err != nil || postedAt.Before(before) || postedAt.After(after) {
+ t.Fatalf("postedAt %q is not receipt-time fallback", post.PostedAt)
+ }
+ if post.Language != "en" || post.Content != "<p>Hello</p>" || post.ContentText != "Hello" {
+ t.Fatalf("unexpected deterministic language content: %+v", post)
+ }
+}
+
+func requireCreatePostEvent(t *testing.T, fixture *createTestFixture, eventType models.EventType) *events.FediverseInboundPostEvent {
+ t.Helper()
+ if len(fixture.events) != 1 {
+ t.Fatalf("expected one event, got %d", len(fixture.events))
+ }
+ if fixture.events[0].Type != string(eventType) {
+ t.Fatalf("expected event %q, got %q", eventType, fixture.events[0].Type)
+ }
+ post, ok := fixture.events[0].Payload.(*events.FediverseInboundPostEvent)
+ if !ok {
+ t.Fatalf("unexpected payload type %T", fixture.events[0].Payload)
+ }
+ return post
+}
+
+func mustCreateTestURL(t *testing.T, value string) *url.URL {
+ t.Helper()
+ parsed, err := url.Parse(value)
+ if err != nil {
+ t.Fatalf("parse URL %q: %v", value, err)
+ }
+ return parsed
+}
diff --git a/services/activitypub/inbox/engagement.go b/services/activitypub/inbox/engagement.go
new file mode 100644
index 0000000000..ad8a1e4c7a
--- /dev/null
+++ b/services/activitypub/inbox/engagement.go
@@ -0,0 +1,66 @@
+package inbox
+
+import (
+ "context"
+ "time"
+
+ "code.superseriousbusiness.org/activity/streams/vocab"
+ "github.com/pkg/errors"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/services/activitypub/apmodels"
+ activityevents "github.com/owncast/owncast/services/activitypub/events"
+ "github.com/owncast/owncast/services/chat/events"
+)
+
+type engagementRequest struct {
+ objectError string
+ actorError string
+ maxAgeError string
+ resolveActorError string
+ saveError string
+ internalEventType models.EventType
+ persistedEvent events.EventType
+ chatEvent events.EventType
+ chatAction string
+}
+
+func (s *Service) acceptEngagementRequest(c context.Context, objectProperty vocab.ActivityStreamsObjectProperty, actorProperty vocab.ActivityStreamsActorProperty, request engagementRequest) error {
+ objectIRI, err := apmodels.GetIRIStringFromObjectProperty(objectProperty)
+ if err != nil {
+ return errors.Wrap(err, request.objectError)
+ }
+
+ if actorProperty == nil || actorProperty.Empty() || actorProperty.Len() == 0 || actorProperty.At(0) == nil {
+ return errors.New(request.actorError)
+ }
+
+ _, isLiveNotification, timestamp, err := s.persistence.GetObjectByIRI(objectIRI)
+ if err != nil {
+ return errors.Wrap(err, "Could not find post locally")
+ }
+
+ if time.Since(timestamp) > maxAgeForEngagement {
+ return errors.New(request.maxAgeError)
+ }
+
+ actor, err := s.resolver.GetResolvedActorFromActorProperty(actorProperty)
+ if err != nil {
+ return errors.Wrap(err, request.resolveActorError)
+ }
+ actorIRI := actor.ActorIriString()
+ claimed, err := s.persistence.ClaimInboundFediverseActivity(objectIRI, actorIRI, request.persistedEvent, time.Now())
+ if err != nil {
+ return errors.Wrap(err, request.saveError)
+ }
+ if !claimed {
+ return nil
+ }
+
+ s.publishFediverseEvent(c, request.internalEventType, &activityevents.FediverseEngagementEvent{
+ Actor: fediverseActorFromResolvedActor(actor),
+ Target: &activityevents.FediverseTarget{URL: objectIRI},
+ })
+
+ return s.handleEngagementActivity(request.chatEvent, isLiveNotification, actor, request.chatAction)
+}
diff --git a/services/activitypub/inbox/engagement_events_test.go b/services/activitypub/inbox/engagement_events_test.go
new file mode 100644
index 0000000000..98a8a3ee8d
--- /dev/null
+++ b/services/activitypub/inbox/engagement_events_test.go
@@ -0,0 +1,324 @@
+package inbox
+
+import (
+ "context"
+ "sync"
+ "testing"
+
+ "code.superseriousbusiness.org/activity/streams"
+ "code.superseriousbusiness.org/activity/streams/vocab"
+
+ "github.com/owncast/owncast/config"
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/persistence/configrepository"
+ "github.com/owncast/owncast/services/activitypub/apmodels"
+ apcrypto "github.com/owncast/owncast/services/activitypub/crypto"
+ activityevents "github.com/owncast/owncast/services/activitypub/events"
+ "github.com/owncast/owncast/services/activitypub/persistence"
+ apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"
+ "github.com/owncast/owncast/services/activitypub/workerpool"
+ "github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/dispatcher"
+)
+
+func newEngagementTestService(t *testing.T) (*Service, *persistence.Service, *[]dispatcher.Event) {
+ t.Helper()
+
+ ds, err := datastore.SetupPersistence(":memory:", t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = ds.DB.Close() })
+
+ configRepository := configrepository.New(ds)
+ if err := configRepository.SetServerURL("https://owncast.example"); err != nil {
+ t.Fatal(err)
+ }
+ if err := configRepository.SetChatDisabled(true); err != nil {
+ t.Fatal(err)
+ }
+ if err := configRepository.SetFederationShowEngagement(false); err != nil {
+ t.Fatal(err)
+ }
+ if err := configRepository.SetFederationEnableQuotes(true); err != nil {
+ t.Fatal(err)
+ }
+
+ privateKey, publicKey, err := apcrypto.GenerateKeys()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := configRepository.SetPrivateKey(string(privateKey)); err != nil {
+ t.Fatal(err)
+ }
+ if err := configRepository.SetPublicKey(string(publicKey)); err != nil {
+ t.Fatal(err)
+ }
+
+ signer := apcrypto.New(apcrypto.Deps{ConfigRepository: configRepository})
+ builder := apmodels.New(apmodels.Deps{ConfigRepository: configRepository, Signer: signer})
+ resolver := apresolvers.New(apresolvers.Deps{ConfigRepository: configRepository, Builder: builder, Signer: signer})
+ outbound := workerpool.New(0)
+ outbound.Start()
+ eventDispatcher := dispatcher.New()
+ var publishedMu sync.Mutex
+ published := []dispatcher.Event{}
+ eventDispatcher.AddListener(func(_ context.Context, event dispatcher.Event) {
+ publishedMu.Lock()
+ defer publishedMu.Unlock()
+ published = append(published, event)
+ })
+ persistenceService := persistence.New(ds, nil)
+
+ return New(Deps{
+ Persistence: persistenceService,
+ Workerpool: outbound,
+ ConfigRepository: configRepository,
+ Builder: builder,
+ Signer: signer,
+ Resolver: resolver,
+ Events: eventDispatcher,
+ }), persistenceService, &published
+}
+
+func actorProperty(person vocab.ActivityStreamsPerson) vocab.ActivityStreamsActorProperty {
+ publicKey := streams.NewW3IDSecurityV1PublicKeyProperty()
+ publicKey.AppendW3IDSecurityV1PublicKey(streams.NewW3IDSecurityV1PublicKey())
+ person.SetW3IDSecurityV1PublicKey(publicKey)
+
+ property := streams.NewActivityStreamsActorProperty()
+ property.AppendActivityStreamsPerson(person)
+ return property
+}
+
+func objectProperty(iri string) vocab.ActivityStreamsObjectProperty {
+ property := streams.NewActivityStreamsObjectProperty()
+ property.AppendIRI(mustParseURL(iri))
+ return property
+}
+
+func assertEngagementEvent(t *testing.T, published []dispatcher.Event, eventType models.EventType, target string) {
+ t.Helper()
+ if len(published) != 1 {
+ t.Fatalf("published %d events, want 1", len(published))
+ }
+ if published[0].Type != eventType {
+ t.Fatalf("event type = %q, want %q", published[0].Type, eventType)
+ }
+ payload, ok := published[0].Payload.(*activityevents.FediverseEngagementEvent)
+ if !ok || payload == nil {
+ t.Fatalf("payload type = %T, want *events.FediverseEngagementEvent", published[0].Payload)
+ }
+ if payload.Actor.Name != "Mr Foo" || payload.Actor.Handle != "[email protected]" || payload.Actor.URL != "https://freedom.eagle/user/mrfoo" || payload.Actor.Image != "https://fake.fediverse.server/user/mrfoo/avatar.png" {
+ t.Fatalf("unexpected actor payload: %+v", payload.Actor)
+ }
+ if payload.Target == nil || payload.Target.URL != target {
+ t.Fatalf("target = %+v, want %q", payload.Target, target)
+ }
+}
+
+func TestEngagementPublishesWithChatDisplayDisabledAndSkipsDuplicates(t *testing.T) {
+ tests := []struct {
+ name string
+ eventType models.EventType
+ handle func(*Service, string) error
+ }{
+ {
+ name: "like",
+ eventType: models.FediverseEngagementLike,
+ handle: func(service *Service, target string) error {
+ activity := streams.NewActivityStreamsLike()
+ activity.SetActivityStreamsActor(actorProperty(makeFakePerson()))
+ activity.SetActivityStreamsObject(objectProperty(target))
+ return service.handleLikeRequest(context.Background(), activity)
+ },
+ },
+ {
+ name: "repost",
+ eventType: models.FediverseEngagementRepost,
+ handle: func(service *Service, target string) error {
+ activity := streams.NewActivityStreamsAnnounce()
+ activity.SetActivityStreamsActor(actorProperty(makeFakePerson()))
+ activity.SetActivityStreamsObject(objectProperty(target))
+ return service.handleAnnounceRequest(context.Background(), activity)
+ },
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ service, persistenceService, published := newEngagementTestService(t)
+ target := "https://owncast.example/federation/" + tt.name
+ if err := persistenceService.AddToOutbox(target, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := tt.handle(service, target); err != nil {
+ t.Fatalf("first activity failed: %v", err)
+ }
+ assertEngagementEvent(t, *published, tt.eventType, target)
+
+ _ = tt.handle(service, target)
+ if len(*published) != 1 {
+ t.Fatalf("duplicate published an event; total = %d, want 1", len(*published))
+ }
+ })
+ }
+}
+
+func TestConcurrentEngagementDeliveriesPublishOnce(t *testing.T) {
+ service, persistenceService, published := newEngagementTestService(t)
+ persistenceService.Datastore().DB.SetMaxOpenConns(1)
+ const target = "https://owncast.example/federation/concurrent-like"
+ if err := persistenceService.AddToOutbox(target, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatal(err)
+ }
+
+ activity := streams.NewActivityStreamsLike()
+ activity.SetActivityStreamsActor(actorProperty(makeFakePerson()))
+ activity.SetActivityStreamsObject(objectProperty(target))
+
+ const deliveries = 16
+ start := make(chan struct{})
+ errs := make(chan error, deliveries)
+ var wg sync.WaitGroup
+ wg.Add(deliveries)
+ for range deliveries {
+ go func() {
+ defer wg.Done()
+ <-start
+ if err := service.handleLikeRequest(context.Background(), activity); err != nil {
+ errs <- err
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ t.Fatalf("concurrent delivery: %v", err)
+ }
+ assertEngagementEvent(t, *published, models.FediverseEngagementLike, target)
+}
+
+func quoteRequest(inbox string) vocab.GoToSocialQuoteRequest {
+ person := makeFakePerson()
+ inboxProperty := streams.NewActivityStreamsInboxProperty()
+ inboxProperty.SetIRI(mustParseURL(inbox))
+ person.SetActivityStreamsInbox(inboxProperty)
+
+ activity := streams.NewGoToSocialQuoteRequest()
+ id := streams.NewJSONLDIdProperty()
+ id.SetIRI(mustParseURL("https://remote.example/quote_requests/1"))
+ activity.SetJSONLDId(id)
+ activity.SetActivityStreamsActor(actorProperty(person))
+ activity.SetActivityStreamsObject(objectProperty("https://owncast.example/federation/quoted"))
+ instrument := streams.NewActivityStreamsInstrumentProperty()
+ instrument.AppendIRI(mustParseURL("https://remote.example/posts/quote"))
+ activity.SetActivityStreamsInstrument(instrument)
+ return activity
+}
+
+func TestQuotePublishesOnlyAfterSuccessfulAccept(t *testing.T) {
+ t.Run("success", func(t *testing.T) {
+ service, persistenceService, published := newEngagementTestService(t)
+ const target = "https://owncast.example/federation/quoted"
+ if err := persistenceService.AddToOutbox(target, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := service.handleQuoteRequestInboxRequest(context.Background(), quoteRequest("https://remote.example/inbox")); err != nil {
+ t.Fatal(err)
+ }
+ assertEngagementEvent(t, *published, models.FediverseEngagementQuote, target)
+ })
+
+ t.Run("replay retries accept without republishing", func(t *testing.T) {
+ service, persistenceService, published := newEngagementTestService(t)
+ const target = "https://owncast.example/federation/quoted"
+ if err := persistenceService.AddToOutbox(target, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatal(err)
+ }
+
+ activity := quoteRequest("https://remote.example/inbox")
+ if err := service.handleQuoteRequestInboxRequest(context.Background(), activity); err != nil {
+ t.Fatalf("first delivery: %v", err)
+ }
+ if err := service.handleQuoteRequestInboxRequest(context.Background(), activity); err != nil {
+ t.Fatalf("replayed delivery: %v", err)
+ }
+ if len(*published) != 1 {
+ t.Fatalf("replayed quote published %d events, want 1", len(*published))
+ }
+
+ var outboxItems int
+ if err := persistenceService.Datastore().DB.QueryRow("SELECT COUNT(*) FROM ap_outbox").Scan(&outboxItems); err != nil {
+ t.Fatalf("count outbox items: %v", err)
+ }
+ if outboxItems != 3 {
+ t.Fatalf("outbox has %d items, want target plus two authorization stamps", outboxItems)
+ }
+ })
+
+ t.Run("rejected", func(t *testing.T) {
+ service, _, published := newEngagementTestService(t)
+ if err := service.handleQuoteRequestInboxRequest(context.Background(), quoteRequest("https://remote.example/inbox")); err != nil {
+ t.Fatal(err)
+ }
+ if len(*published) != 0 {
+ t.Fatalf("rejected quote published %d events, want 0", len(*published))
+ }
+ })
+
+ t.Run("accept failed", func(t *testing.T) {
+ service, persistenceService, published := newEngagementTestService(t)
+ const target = "https://owncast.example/federation/quoted"
+ if err := persistenceService.AddToOutbox(target, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := service.handleQuoteRequestInboxRequest(context.Background(), quoteRequest("http://remote.example/inbox")); err == nil {
+ t.Fatal("quote with insecure inbox returned nil error")
+ }
+ if len(*published) != 0 {
+ t.Fatalf("failed quote published %d events, want 0", len(*published))
+ }
+ })
+}
+
+func TestConcurrentQuoteDeliveriesPublishOnce(t *testing.T) {
+ _ = config.GetReleaseString()
+ service, persistenceService, published := newEngagementTestService(t)
+ persistenceService.Datastore().DB.SetMaxOpenConns(1)
+ const target = "https://owncast.example/federation/quoted"
+ if err := persistenceService.AddToOutbox(target, []byte(`{"type":"Note"}`), "Note", false); err != nil {
+ t.Fatal(err)
+ }
+
+ const deliveries = 8
+ activity := quoteRequest("https://remote.example/inbox")
+ start := make(chan struct{})
+ errs := make(chan error, deliveries)
+ var wg sync.WaitGroup
+ wg.Add(deliveries)
+ for range deliveries {
+ go func() {
+ defer wg.Done()
+ <-start
+ if err := service.handleQuoteRequestInboxRequest(context.Background(), activity); err != nil {
+ errs <- err
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ t.Fatalf("concurrent delivery: %v", err)
+ }
+ if len(*published) != 1 {
+ t.Fatalf("concurrent quote deliveries published %d events, want 1", len(*published))
+ }
+}
diff --git a/services/activitypub/inbox/events.go b/services/activitypub/inbox/events.go
new file mode 100644
index 0000000000..2ac0b9c405
--- /dev/null
+++ b/services/activitypub/inbox/events.go
@@ -0,0 +1,16 @@
+package inbox
+
+import (
+ "context"
+
+ "github.com/owncast/owncast/models"
+ "github.com/owncast/owncast/services/dispatcher"
+)
+
+func (s *Service) publishFediverseEvent(ctx context.Context, eventType models.EventType, payload any) {
+ if s.events == nil {
+ return
+ }
+
+ s.events.Publish(ctx, dispatcher.Event{Type: eventType, Payload: payload})
+}
diff --git a/services/activitypub/inbox/follow.go b/services/activitypub/inbox/follow.go
index 8f0a368c7e..7a7dff6b52 100644
--- a/services/activitypub/inbox/follow.go
+++ b/services/activitypub/inbox/follow.go
@@ -56,8 +56,6 @@ func (s *Service) handleFollowInboxRequest(c context.Context, activity vocab.Act
return errors.Wrap(err, "follow activity is missing actor IRI")
}
- actorReference := activity.GetActivityStreamsActor()
-
if approved {
// Only non-featured (fan) follows reach the auto-accept path here;
// featured follows always require manual approval, so live status in
@@ -97,7 +95,7 @@ func (s *Service) handleFollowInboxRequest(c context.Context, activity vocab.Act
// Send action to chat if it has not been previously handled.
if !hasPreviouslyhandled {
- return s.handleEngagementActivity(events.FediverseEngagementFollow, false, actorReference, events.FediverseEngagementFollow)
+ return s.handleEngagementActivity(events.FediverseEngagementFollow, false, followRequest, events.FediverseEngagementFollow)
}
return nil
diff --git a/services/activitypub/inbox/like.go b/services/activitypub/inbox/like.go
index 0a18ed50d6..7834e67144 100644
--- a/services/activitypub/inbox/like.go
+++ b/services/activitypub/inbox/like.go
@@ -2,47 +2,23 @@ package inbox
import (
"context"
- "time"
"code.superseriousbusiness.org/activity/streams/vocab"
- "github.com/pkg/errors"
- "github.com/owncast/owncast/services/activitypub/apmodels"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/services/chat/events"
)
func (s *Service) handleLikeRequest(c context.Context, activity vocab.ActivityStreamsLike) error {
- objectIRI, err := apmodels.GetIRIStringFromObjectProperty(activity.GetActivityStreamsObject())
- if err != nil {
- return errors.Wrap(err, "like activity is missing object IRI")
- }
-
- actorIRI, err := apmodels.GetIRIStringFromActorProperty(activity.GetActivityStreamsActor())
- if err != nil {
- return errors.Wrap(err, "like activity is missing actor IRI")
- }
-
- actorReference := activity.GetActivityStreamsActor()
-
- if hasPreviouslyhandled, err := s.persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementLike); hasPreviouslyhandled || err != nil {
- return errors.Wrap(err, "inbound activity of like has already been handled")
- }
-
- // Likes need to match a post we had already sent.
- _, isLiveNotification, timestamp, err := s.persistence.GetObjectByIRI(objectIRI)
- if err != nil {
- return errors.Wrap(err, "Could not find post locally")
- }
-
- // Don't allow old activities to be liked.
- if time.Since(timestamp) > maxAgeForEngagement {
- return errors.New("Activity is too old to be liked")
- }
-
- // Save as an accepted activity.
- if err := s.persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementLike, time.Now()); err != nil {
- return errors.Wrap(err, "unable to save inbound like activity")
- }
-
- return s.handleEngagementActivity(events.FediverseEngagementLike, isLiveNotification, actorReference, events.FediverseEngagementLike)
+ return s.acceptEngagementRequest(c, activity.GetActivityStreamsObject(), activity.GetActivityStreamsActor(), engagementRequest{
+ objectError: "like activity is missing object IRI",
+ actorError: "like activity is missing actor IRI",
+ maxAgeError: "Activity is too old to be liked",
+ resolveActorError: "unable to resolve actor of like activity",
+ saveError: "unable to save inbound like activity",
+ internalEventType: models.FediverseEngagementLike,
+ persistedEvent: events.FediverseEngagementLike,
+ chatEvent: events.FediverseEngagementLike,
+ chatAction: events.FediverseEngagementLike,
+ })
}
diff --git a/services/activitypub/inbox/quote.go b/services/activitypub/inbox/quote.go
index 19e367a18b..d26f622d29 100644
--- a/services/activitypub/inbox/quote.go
+++ b/services/activitypub/inbox/quote.go
@@ -2,12 +2,15 @@ package inbox
import (
"context"
+ "time"
"code.superseriousbusiness.org/activity/streams/vocab"
"github.com/pkg/errors"
"github.com/teris-io/shortid"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/services/activitypub/apmodels"
+ activityevents "github.com/owncast/owncast/services/activitypub/events"
"github.com/owncast/owncast/services/activitypub/requests"
)
@@ -18,10 +21,16 @@ import (
// stamp. Requests for unknown posts, or any request while federation is
// private, are rejected so the pending quote clears on the remote end.
func (s *Service) handleQuoteRequestInboxRequest(c context.Context, activity vocab.GoToSocialQuoteRequest) error {
+ activityIRI, err := apmodels.GetIRIStringFromJSONLDIdProperty(activity.GetJSONLDId())
+ if err != nil {
+ return errors.Wrap(err, "quote request is missing activity IRI")
+ }
+
actor, err := s.resolver.GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())
if err != nil {
return errors.Wrap(err, "unable to resolve actor of quote request")
}
+ actorIRI := actor.ActorIriString()
// object = the post being quoted, instrument = the quote post itself.
quotedPostIRI, err := apmodels.GetIRIFromObjectProperty(activity.GetActivityStreamsObject())
@@ -60,5 +69,19 @@ func (s *Service) handleQuoteRequestInboxRequest(c context.Context, activity voc
return errors.Wrap(err, "unable to store quote authorization")
}
- return requests.SendQuoteRequestAccept(s.workerpool, actor.Inbox, activity, stampIRI, localAccountName, s.builder, s.signer)
+ if err := requests.SendQuoteRequestAccept(s.workerpool, actor.Inbox, activity, stampIRI, localAccountName, s.builder, s.signer); err != nil {
+ return err
+ }
+ claimed, err := s.persistence.ClaimInboundFediverseActivity(activityIRI, actorIRI, activity.GetTypeName(), time.Now())
+ if err != nil {
+ return errors.Wrap(err, "unable to claim inbound quote request")
+ }
+ if !claimed {
+ return nil
+ }
+ s.publishFediverseEvent(c, models.FediverseEngagementQuote, &activityevents.FediverseEngagementEvent{
+ Actor: fediverseActorFromResolvedActor(actor),
+ Target: &activityevents.FediverseTarget{URL: quotedPostIRI.String()},
+ })
+ return nil
}
diff --git a/services/activitypub/inbox/service.go b/services/activitypub/inbox/service.go
index 4e8bb53724..a7eca2c75b 100644
--- a/services/activitypub/inbox/service.go
+++ b/services/activitypub/inbox/service.go
@@ -18,6 +18,7 @@ import (
apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"
"github.com/owncast/owncast/services/activitypub/workerpool"
"github.com/owncast/owncast/services/chat"
+ "github.com/owncast/owncast/services/dispatcher"
"github.com/owncast/owncast/services/webhooks"
)
@@ -43,6 +44,7 @@ type Service struct {
builder *apmodels.Builder
signer *apcrypto.Signer
resolver *apresolvers.Resolver
+ events *dispatcher.Dispatcher
}
// Deps is the explicit dependency contract for inbox.
@@ -56,6 +58,7 @@ type Deps struct {
Builder *apmodels.Builder
Signer *apcrypto.Signer
Resolver *apresolvers.Resolver
+ Events *dispatcher.Dispatcher
}
// New constructs an idle inbox Service. Call Start to launch the worker
@@ -72,6 +75,7 @@ func New(deps Deps) *Service {
builder: deps.Builder,
signer: deps.Signer,
resolver: deps.Resolver,
+ events: deps.Events,
}
}
diff --git a/services/activitypub/inbox/worker.go b/services/activitypub/inbox/worker.go
index 1e8c912a58..6b3ee346c4 100644
--- a/services/activitypub/inbox/worker.go
+++ b/services/activitypub/inbox/worker.go
@@ -15,6 +15,7 @@ import (
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/services/activitypub/apmodels"
)
@@ -29,26 +30,33 @@ func (s *Service) handle(request apmodels.InboxRequest) {
return
}
- // Bind the activity to its signer. A validly signed request may only carry
- // activities authored by the verified key's owner; otherwise a server could
- // sign with its own key while claiming, in the body, to be a different actor
- // (e.g. forging a featured-stream Offer/Leave/Accept as another server). We
- // compare origins (hostname), the standard fediverse binding, which is
- // robust to id/fragment formatting differences. Fail closed: if no actor
- // IRI can be determined the activity is rejected.
- actorIRI, err := actorIRIFromActivity(request.Body)
+ if !s.handleVerifiedIngress(request.Request.Context(), request.Body, keyOwner) {
+ return
+ }
+
+ if err := s.resolver.Resolve(context.Background(), request.Body, s.handleUpdateRequest, s.handleFollowInboxRequest, s.handleLikeRequest, s.handleAnnounceRequest, s.handleUndoInboxRequest, s.handleCreateRequest, s.handleOfferInboxRequest, s.handleAcceptInboxRequest, s.handleRejectInboxRequest, s.handleLeaveInboxRequest, s.handleQuoteRequestInboxRequest); err != nil {
+ log.Debugln("resolver error:", err)
+ }
+}
+
+func (s *Service) handleVerifiedIngress(ctx context.Context, body []byte, keyOwner *url.URL) bool {
+ actorIRI, err := actorIRIFromActivity(body)
if err != nil {
log.Warnln("rejecting inbound activity: unable to bind actor to signing key:", err)
- return
+ return false
+ }
+ if keyOwner == nil {
+ log.Warnf("rejecting inbound activity: actor %q has no signing key owner", actorIRI)
+ return false
}
if !sameActorOrigin(actorIRI, keyOwner) {
log.Warnf("rejecting inbound activity: actor %q does not match signing key owner %q", actorIRI, keyOwner.String())
- return
+ return false
}
- if err := s.resolver.Resolve(context.Background(), request.Body, s.handleUpdateRequest, s.handleFollowInboxRequest, s.handleLikeRequest, s.handleAnnounceRequest, s.handleUndoInboxRequest, s.handleCreateRequest, s.handleOfferInboxRequest, s.handleAcceptInboxRequest, s.handleRejectInboxRequest, s.handleLeaveInboxRequest, s.handleQuoteRequestInboxRequest); err != nil {
- log.Debugln("resolver error:", err)
- }
+ payload := append(json.RawMessage(nil), body...)
+ s.publishFediverseEvent(ctx, models.FediverseActivity, payload)
+ return true
}
// actorIRIFromActivity extracts the top-level "actor" IRI from a raw inbound
diff --git a/services/activitypub/inbox/worker_test.go b/services/activitypub/inbox/worker_test.go
index 2ab9c1f20d..64ef7e49c6 100644
--- a/services/activitypub/inbox/worker_test.go
+++ b/services/activitypub/inbox/worker_test.go
@@ -1,6 +1,9 @@
package inbox
import (
+ "context"
+ "encoding/json"
+ "net/http/httptest"
"net/url"
"os"
"testing"
@@ -8,11 +11,13 @@ import (
"code.superseriousbusiness.org/activity/streams"
"code.superseriousbusiness.org/activity/streams/vocab"
+ "github.com/owncast/owncast/models"
"github.com/owncast/owncast/persistence/configrepository"
"github.com/owncast/owncast/services/activitypub/apmodels"
"github.com/owncast/owncast/services/activitypub/persistence"
"github.com/owncast/owncast/services/activitypub/persistence/followersrepository"
"github.com/owncast/owncast/services/datastore"
+ "github.com/owncast/owncast/services/dispatcher"
)
func makeFakePerson() vocab.ActivityStreamsPerson {
@@ -124,3 +129,99 @@ func TestBlockedActors(t *testing.T) {
t.Error("Invalid blocking of unblocked actor IRI")
}
}
+
+func TestHandleVerifiedIngress(t *testing.T) {
+ tests := []struct {
+ name string
+ body string
+ keyOwner string
+ wantEvent bool
+ }{
+ {
+ name: "matching actor",
+ body: `{"type":"Like","actor":"https://remote.example/users/alice"}`,
+ keyOwner: "https://remote.example/users/alice#main-key",
+ wantEvent: true,
+ },
+ {
+ name: "unknown activity type",
+ body: `{ "type": "FutureActivity", "actor": "https://remote.example/users/alice", "custom": true }`,
+ keyOwner: "https://remote.example/users/alice#main-key",
+ wantEvent: true,
+ },
+ {
+ name: "mismatched actor",
+ body: `{"type":"Like","actor":"https://forged.example/users/alice"}`,
+ keyOwner: "https://remote.example/users/alice#main-key",
+ },
+ {
+ name: "malformed activity",
+ body: `{"type":"Like","actor":`,
+ keyOwner: "https://remote.example/users/alice#main-key",
+ },
+ {
+ name: "activity without actor",
+ body: `{"type":"Like"}`,
+ keyOwner: "https://remote.example/users/alice#main-key",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ eventDispatcher := dispatcher.New()
+ var published []dispatcher.Event
+ eventDispatcher.AddListener(func(_ context.Context, event dispatcher.Event) {
+ published = append(published, event)
+ })
+ service := New(Deps{Events: eventDispatcher})
+ keyOwner, err := url.Parse(tt.keyOwner)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := []byte(tt.body)
+
+ accepted := service.handleVerifiedIngress(context.Background(), body, keyOwner)
+
+ if accepted != tt.wantEvent {
+ t.Fatalf("accepted = %v, want %v", accepted, tt.wantEvent)
+ }
+ if !tt.wantEvent {
+ if len(published) != 0 {
+ t.Fatalf("published %d events, want 0", len(published))
+ }
+ return
+ }
+ if len(published) != 1 {
+ t.Fatalf("published %d events, want 1", len(published))
+ }
+ if published[0].Type != models.FediverseActivity {
+ t.Fatalf("event type = %q, want %q", published[0].Type, models.FediverseActivity)
+ }
+ payload, ok := published[0].Payload.(json.RawMessage)
+ if !ok {
+ t.Fatalf("payload type = %T, want json.RawMessage", published[0].Payload)
+ }
+ body[0] = '!'
+ if string(payload) != tt.body {
+ t.Fatalf("payload = %q, want exact raw JSON %q", payload, tt.body)
+ }
+ })
+ }
+}
+
+func TestHandleDoesNotPublishUnverifiedRequest(t *testing.T) {
+ eventDispatcher := dispatcher.New()
+ published := 0
+ eventDispatcher.AddListener(func(_ context.Context, _ dispatcher.Event) {
+ published++
+ })
+ service := New(Deps{Events: eventDispatcher})
+ body := []byte(`{"type":"Unknown","actor":"https://remote.example/users/alice"}`)
+ request := httptest.NewRequest("POST", "https://local.example/inbox", nil)
+
+ service.handle(apmodels.InboxRequest{Request: request, Body: body})
+
+ if published != 0 {
+ t.Fatalf("published %d events for an unverified request, want 0", published)
+ }
+}
diff --git a/services/activitypub/persistence/persistence.go b/services/activitypub/persistence/persistence.go
index 7ad2f8e129..5ea67a0980 100644
--- a/services/activitypub/persistence/persistence.go
+++ b/services/activitypub/persistence/persistence.go
@@ -9,6 +9,7 @@ import (
"context"
"database/sql"
"fmt"
+ "sync"
"time"
"code.superseriousbusiness.org/activity/streams"
@@ -24,8 +25,9 @@ import (
// Service owns the ActivityPub persistence operations.
type Service struct {
- datastore *datastore.Datastore
- resolver *apresolvers.Resolver
+ datastore *datastore.Datastore
+ resolver *apresolvers.Resolver
+ inboundActivityClaimMu sync.Mutex
}
// New constructs a persistence Service bound to the given datastore.
@@ -178,3 +180,24 @@ func (s *Service) HasPreviouslyHandledInboundActivity(iri string, actorIRI strin
return exists > 0, nil
}
+
+// ClaimInboundFediverseActivity records an inbound activity unless it was
+// already handled. The mutex makes the count-and-insert pair atomic within
+// this Service.
+func (s *Service) ClaimInboundFediverseActivity(iri string, actorIRI string, eventType string, timestamp time.Time) (bool, error) {
+ s.inboundActivityClaimMu.Lock()
+ defer s.inboundActivityClaimMu.Unlock()
+
+ handled, err := s.HasPreviouslyHandledInboundActivity(iri, actorIRI, eventType)
+ if err != nil {
+ return false, err
+ }
+ if handled {
+ return false, nil
+ }
+ if err := s.SaveInboundFediverseActivity(iri, actorIRI, eventType, timestamp); err != nil {
+ return false, err
+ }
+
+ return true, nil
+}
diff --git a/services/activitypub/persistence/persistence_test.go b/services/activitypub/persistence/persistence_test.go
new file mode 100644
index 0000000000..965dc64754
--- /dev/null
+++ b/services/activitypub/persistence/persistence_test.go
@@ -0,0 +1,61 @@
+package persistence
+
+import (
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestClaimInboundFediverseActivityConcurrent(t *testing.T) {
+ service := New(_datastore, nil)
+ const workers = 32
+
+ start := make(chan struct{})
+ errs := make(chan error, workers)
+ var claimed atomic.Int32
+ var wg sync.WaitGroup
+ wg.Add(workers)
+ for range workers {
+ go func() {
+ defer wg.Done()
+ <-start
+ ok, err := service.ClaimInboundFediverseActivity(
+ "https://remote.example/activities/concurrent-claim",
+ "https://remote.example/users/alice",
+ "Create",
+ time.Now(),
+ )
+ if err != nil {
+ errs <- err
+ return
+ }
+ if ok {
+ claimed.Add(1)
+ }
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(errs)
+
+ for err := range errs {
+ t.Fatalf("claim failed: %v", err)
+ }
+ if got := claimed.Load(); got != 1 {
+ t.Fatalf("successful claims = %d, want 1", got)
+ }
+
+ ok, err := service.ClaimInboundFediverseActivity(
+ "https://remote.example/activities/concurrent-claim",
+ "https://remote.example/users/alice",
+ "Create",
+ time.Now(),
+ )
+ if err != nil {
+ t.Fatalf("retry claim failed: %v", err)
+ }
+ if ok {
+ t.Fatal("retry unexpectedly claimed an already handled activity")
+ }
+}
diff --git a/services/plugins/dispatcher_test.go b/services/plugins/dispatcher_test.go
index 8f73a0290d..09f6aea4fc 100644
--- a/services/plugins/dispatcher_test.go
+++ b/services/plugins/dispatcher_test.go
@@ -19,7 +19,7 @@ func TestReservedEventTypes_CoversCoreEvents(t *testing.T) {
EventStreamStopped, EventStreamTitleChanged, EventSSEConnect,
EventSSEDisconnect, EventTick, EventTimerFire, EventFediverseFollow,
EventFediverseLike, EventFediverseRepost, EventFediverseMention,
- EventFediverseReply,
+ EventFediverseReply, EventFediverseQuote, EventFediverseActivity,
} {
if !reservedEventTypes[e] {
t.Errorf("core event %q must be reserved (plugins must not be able to emit it)", e)
diff --git a/services/plugins/engines/javascript/engine.wasm b/services/plugins/engines/javascript/engine.wasm
index 2be79201eb..27be298e18 100644
Binary files a/services/plugins/engines/javascript/engine.wasm and b/services/plugins/engines/javascript/engine.wasm differ
diff --git a/services/plugins/engines/python/engine.wasm b/services/plugins/engines/python/engine.wasm
index 25d1d6621e..fe6d11baf2 100644
Binary files a/services/plugins/engines/python/engine.wasm and b/services/plugins/engines/python/engine.wasm differ
diff --git a/services/plugins/events.go b/services/plugins/events.go
index 716901014e..f9fd622037 100644
--- a/services/plugins/events.go
+++ b/services/plugins/events.go
@@ -34,14 +34,14 @@ const (
// don't subscribe to or handle this directly.
EventTimerFire = "timer.fire"
- // Fediverse events. Engagement (follow/like/repost) carries only
- // actor + target metadata; mention/reply also carry the post content
- // so plugins can act on what was actually said.
- EventFediverseFollow = "fediverse.follow"
- EventFediverseLike = "fediverse.like"
- EventFediverseRepost = "fediverse.repost"
- EventFediverseMention = "fediverse.mention"
- EventFediverseReply = "fediverse.reply"
+ // Fediverse event names exposed to plugins.
+ EventFediverseFollow = "fediverse.follow"
+ EventFediverseLike = "fediverse.like"
+ EventFediverseRepost = "fediverse.repost"
+ EventFediverseMention = "fediverse.mention"
+ EventFediverseReply = "fediverse.reply"
+ EventFediverseQuote = "fediverse.quote"
+ EventFediverseActivity = "fediverse.activity"
)
// reservedEventTypes are the built-in event types the host originates. A
@@ -66,4 +66,6 @@ var reservedEventTypes = map[string]bool{
EventFediverseRepost: true,
EventFediverseMention: true,
EventFediverseReply: true,
+ EventFediverseQuote: true,
+ EventFediverseActivity: true,
}
diff --git a/services/plugins/hostfns.go b/services/plugins/hostfns.go
index e05fd23d04..dc805fb92c 100644
--- a/services/plugins/hostfns.go
+++ b/services/plugins/hostfns.go
@@ -55,6 +55,7 @@ const (
// nothing on its own; the gate only goes live when an admin enables the
// plugin, and only one auth.gate plugin may be enabled at a time.
PermAuthGate = "auth.gate"
+ PermFediverseInbound = "fediverse.inbound"
PermFediversePost = "fediverse.post"
PermVideoConfigRead = "videoconfig.read"
PermVideoConfigWrite = "videoconfig.write"
diff --git a/services/plugins/manager.go b/services/plugins/manager.go
index 2775be60a0..64dfd9b2d7 100644
--- a/services/plugins/manager.go
+++ b/services/plugins/manager.go
@@ -1533,7 +1533,7 @@ func loadFromBytes(ctx context.Context, env *HostEnv, manifestBytes, artifactByt
if err := manifest.AgreesWith(&runtime); err != nil {
return nil, fail(fmt.Errorf("manifest/runtime mismatch: %w", err))
}
- if err := requireChatFilterPermission(manifest, runtime.Subscriptions); err != nil {
+ if err := requireSubscriptionPermissions(manifest, runtime.Subscriptions); err != nil {
return nil, fail(err)
}
manifest.Subscriptions = runtime.Subscriptions
@@ -1665,11 +1665,9 @@ func buildIdentity(env *HostEnv, manifest *Manifest, assetsFS fs.FS) *pluginIden
return id
}
-// requireChatFilterPermission rejects a runtime registration that
-// subscribes to filterChatMessage without declaring the chat.filter
-// permission. Modifying or dropping every chat message is a meaningful
-// side-effect, so an admin must opt in at install time by granting it.
-func requireChatFilterPermission(manifest *Manifest, subs Subscriptions) error {
+// requireSubscriptionPermissions rejects runtime subscriptions that require
+// permissions the plugin did not declare in its manifest.
+func requireSubscriptionPermissions(manifest *Manifest, subs Subscriptions) error {
if !manifest.hasPermission(PermChatFilter) {
for _, s := range subs.Filter {
if s.Event == EventChatMessageReceived {
@@ -1683,6 +1681,20 @@ func requireChatFilterPermission(manifest *Manifest, subs Subscriptions) error {
}
}
}
+
+ if !manifest.hasPermission(PermFediverseInbound) {
+ for _, s := range subs.Notify {
+ switch s.Event {
+ case EventFediverseFollow, EventFediverseLike, EventFediverseRepost,
+ EventFediverseMention, EventFediverseReply, EventFediverseQuote, EventFediverseActivity:
+ return fmt.Errorf(
+ "plugin subscribes to %s but does not declare the %q permission",
+ s.Event, PermFediverseInbound,
+ )
+ }
+ }
+ }
+
return nil
}
diff --git a/services/plugins/manifest_test.go b/services/plugins/manifest_test.go
index 4381027c3e..7e0260607d 100644
--- a/services/plugins/manifest_test.go
+++ b/services/plugins/manifest_test.go
@@ -906,42 +906,81 @@ func TestParseManifest_Network_NoFetchPermissionAllowsAnyShape(t *testing.T) {
}
}
-func TestRequireChatFilterPermission_RejectsWhenMissing(t *testing.T) {
- // A plugin that subscribes to filterChatMessage at register-time must
- // declare the chat.filter permission in its manifest. The host refuses
- // to load otherwise so the admin can't be surprised by a plugin that
- // silently starts rewriting chat.
- m := &Manifest{DisplayName: "stealth", Permissions: nil}
- subs := Subscriptions{
- Filter: []Subscription{{Event: EventChatMessageReceived, Priority: 100}},
- }
- err := requireChatFilterPermission(m, subs)
- if err == nil {
- t.Fatal("expected error when filterChatMessage is subscribed without chat.filter")
- }
- if !strings.Contains(err.Error(), PermChatFilter) {
- t.Errorf("error should mention %q, got: %v", PermChatFilter, err)
- }
-}
-
-func TestRequireChatFilterPermission_AcceptsWhenDeclared(t *testing.T) {
- m := &Manifest{DisplayName: "honest", Permissions: []string{PermChatFilter}}
- subs := Subscriptions{
- Filter: []Subscription{{Event: EventChatMessageReceived, Priority: 100}},
- }
- if err := requireChatFilterPermission(m, subs); err != nil {
- t.Errorf("declared chat.filter should accept: %v", err)
- }
-}
-
-func TestRequireChatFilterPermission_NoOpWhenNoFilterSubscription(t *testing.T) {
- // A plugin that doesn't subscribe to filterChatMessage at all should
- // pass through, regardless of whether it declares chat.filter.
- m := &Manifest{DisplayName: "passive", Permissions: nil}
- subs := Subscriptions{
- Filter: []Subscription{{Event: "some-other-event", Priority: 100}},
- }
- if err := requireChatFilterPermission(m, subs); err != nil {
- t.Errorf("non-chat filter subscription should not require chat.filter: %v", err)
+func TestRequireSubscriptionPermissions(t *testing.T) {
+ fediverseEvents := []string{
+ EventFediverseFollow,
+ EventFediverseLike,
+ EventFediverseRepost,
+ EventFediverseMention,
+ EventFediverseReply,
+ EventFediverseQuote,
+ EventFediverseActivity,
+ }
+
+ type testCase struct {
+ name string
+ permissions []string
+ subscriptions Subscriptions
+ missingPerm string
+ }
+ tests := []testCase{
+ {
+ name: "chat filter missing permission",
+ subscriptions: Subscriptions{
+ Filter: []Subscription{{Event: EventChatMessageReceived, Priority: 100}},
+ },
+ missingPerm: PermChatFilter,
+ },
+ {
+ name: "chat filter declared permission",
+ permissions: []string{PermChatFilter},
+ subscriptions: Subscriptions{
+ Filter: []Subscription{{Event: EventChatMessageReceived, Priority: 100}},
+ },
+ },
+ {
+ name: "unrelated subscriptions",
+ subscriptions: Subscriptions{
+ Notify: []Subscription{{Event: "some-other-notify-event"}},
+ Filter: []Subscription{{Event: "some-other-filter-event", Priority: 100}},
+ },
+ },
+ }
+ for _, event := range fediverseEvents {
+ tests = append(tests,
+ testCase{
+ name: "missing permission for " + event,
+ subscriptions: Subscriptions{
+ Notify: []Subscription{{Event: event}},
+ },
+ missingPerm: PermFediverseInbound,
+ },
+ testCase{
+ name: "declared permission for " + event,
+ permissions: []string{PermFediverseInbound},
+ subscriptions: Subscriptions{
+ Notify: []Subscription{{Event: event}},
+ },
+ },
+ )
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ manifest := &Manifest{DisplayName: "test", Permissions: tt.permissions}
+ err := requireSubscriptionPermissions(manifest, tt.subscriptions)
+ if tt.missingPerm == "" {
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ return
+ }
+ if err == nil {
+ t.Fatalf("expected error mentioning %q", tt.missingPerm)
+ }
+ if !strings.Contains(err.Error(), tt.missingPerm) {
+ t.Errorf("error should mention %q, got: %v", tt.missingPerm, err)
+ }
+ })
}
}
diff --git a/services/plugins/plugin-contract.json b/services/plugins/plugin-contract.json
index cbea706ec5..50403e4ccf 100644
--- a/services/plugins/plugin-contract.json
+++ b/services/plugins/plugin-contract.json
@@ -6,6 +6,7 @@
"PermChatModerate": "chat.moderate",
"PermChatSend": "chat.send",
"PermEmitEvent": "events.emit",
+ "PermFediverseInbound": "fediverse.inbound",
"PermFediversePost": "fediverse.post",
"PermHttpSSE": "http.sse",
"PermHttpServe": "http.serve",
diff --git a/web/components/admin/plugins/permissionDescriptions.ts b/web/components/admin/plugins/permissionDescriptions.ts
index e20a064ccf..22d46a5e43 100644
--- a/web/components/admin/plugins/permissionDescriptions.ts
+++ b/web/components/admin/plugins/permissionDescriptions.ts
@@ -22,6 +22,7 @@ export const permissionDescriptionKey: Record<string, string> = {
[PluginPermission.NotificationsSend]: Localization.Admin.Plugins.Permissions.notificationsSend,
[PluginPermission.UsersRead]: Localization.Admin.Plugins.Permissions.usersRead,
[PluginPermission.UsersModerate]: Localization.Admin.Plugins.Permissions.usersModerate,
+ [PluginPermission.FediverseInbound]: Localization.Admin.Plugins.Permissions.fediverseInbound,
[PluginPermission.FediversePost]: Localization.Admin.Plugins.Permissions.fediversePost,
[PluginPermission.VideoConfigRead]: Localization.Admin.Plugins.Permissions.videoconfigRead,
[PluginPermission.VideoConfigWrite]: Localization.Admin.Plugins.Permissions.videoconfigWrite,
@@ -51,6 +52,7 @@ export const permissionNameKey: Record<string, string> = {
Localization.Admin.Plugins.PermissionNames.notificationsSend,
[PluginPermission.UsersRead]: Localization.Admin.Plugins.PermissionNames.usersRead,
[PluginPermission.UsersModerate]: Localization.Admin.Plugins.PermissionNames.usersModerate,
+ [PluginPermission.FediverseInbound]: Localization.Admin.Plugins.PermissionNames.fediverseInbound,
[PluginPermission.FediversePost]: Localization.Admin.Plugins.PermissionNames.fediversePost,
[PluginPermission.VideoConfigRead]: Localization.Admin.Plugins.PermissionNames.videoconfigRead,
[PluginPermission.VideoConfigWrite]: Localization.Admin.Plugins.PermissionNames.videoconfigWrite,
diff --git a/web/i18n/en/translation.json b/web/i18n/en/translation.json
index 604bb0f98e..5626619f37 100644
--- a/web/i18n/en/translation.json
+++ b/web/i18n/en/translation.json
@@ -193,6 +193,7 @@
"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",
@@ -216,6 +217,7 @@
"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.",
diff --git a/web/interfaces/plugin.ts b/web/interfaces/plugin.ts
index 9917cdf2fa..e230ac4b93 100644
--- a/web/interfaces/plugin.ts
+++ b/web/interfaces/plugin.ts
@@ -25,6 +25,7 @@ export const PluginPermission = {
VideoConfigRead: 'videoconfig.read',
VideoConfigWrite: 'videoconfig.write',
NotificationsSend: 'notifications.send',
+ FediverseInbound: 'fediverse.inbound',
FediversePost: 'fediverse.post',
UIModify: 'ui.modify',
AuthGate: 'auth.gate',
diff --git a/web/types/localization.ts b/web/types/localization.ts
index 2d0b5f897a..97197e68c5 100644
--- a/web/types/localization.ts
+++ b/web/types/localization.ts
@@ -564,6 +564,7 @@ export const Localization = {
notificationsSend: 'Admin.Plugins.Permissions.notificationsSend',
usersRead: 'Admin.Plugins.Permissions.usersRead',
usersModerate: 'Admin.Plugins.Permissions.usersModerate',
+ fediverseInbound: 'Admin.Plugins.Permissions.fediverseInbound',
fediversePost: 'Admin.Plugins.Permissions.fediversePost',
videoconfigRead: 'Admin.Plugins.Permissions.videoconfigRead',
videoconfigWrite: 'Admin.Plugins.Permissions.videoconfigWrite',
@@ -590,6 +591,7 @@ export const Localization = {
notificationsSend: 'Admin.Plugins.PermissionNames.notificationsSend',
usersRead: 'Admin.Plugins.PermissionNames.usersRead',
usersModerate: 'Admin.Plugins.PermissionNames.usersModerate',
+ fediverseInbound: 'Admin.Plugins.PermissionNames.fediverseInbound',
fediversePost: 'Admin.Plugins.PermissionNames.fediversePost',
videoconfigRead: 'Admin.Plugins.PermissionNames.videoconfigRead',
videoconfigWrite: 'Admin.Plugins.PermissionNames.videoconfigWrite',