Skip to content

Node.js based forum software built for the modern web

fix(activitypub): implement relay follower management and broadcast

Julian Lame2f118479966
diff --git a/src/activitypub/feps.js b/src/activitypub/feps.js
index dbf039ef7a..1af33cbb96 100644
--- a/src/activitypub/feps.js
+++ b/src/activitypub/feps.js
@@ -81,4 +81,7 @@ Feps.announce = async function announce(id, activity) {
relays.forEach((relay) => {
activitypub.analytics.relays.out(relay);
});
+
+ // Broadcast raw activity to relay followers
+ await activitypub.relays.broadcast(activity);
};
diff --git a/src/activitypub/inbox.js b/src/activitypub/inbox.js
index 8b4c28514e..ffe6a5fd57 100644
--- a/src/activitypub/inbox.js
+++ b/src/activitypub/inbox.js
@@ -242,6 +242,7 @@ inbox.update = async (req) => {
const postData = await activitypub.mocks.post(object);
postData.tags = await activitypub.notes._normalizeTags(postData._activitypub.tag, postData.cid);
await posts.edit(postData);
+ await activitypub.feps.announce(object.id, req.body);
const tid = await posts.getPostField(object.id, 'tid');
const { generatedTitle } = await topics.getTopicFields(tid, ['generatedTitle']);
if (generatedTitle && (!postData.title || !postData.title.trim())) {
@@ -699,6 +700,11 @@ inbox.announce = async (req) => {
}
}
}
+
+ // Broadcast to relay followers if we have a pid
+ if (pid) {
+ await activitypub.feps.announce(pid, object);
+ }
};
inbox.follow = async (req) => {
@@ -851,11 +857,24 @@ inbox.undo = async (req) => {
let { type: localType, id } = await helpers.resolveLocalId(object.object);
+ // If object is a Follow activity, check if the target is the instance actor (relay follow)
+ if (!localType && object?.type === 'Follow') {
+ const followTarget = typeof object.object === 'object' ? object.object.id : object.object;
+ if (followTarget === `${nconf.get('url')}/actor`) {
+ localType = 'application';
+ }
+ }
+
activitypub.helpers.log(`[activitypub/inbox/undo] ${type} ${localType && id ? `${localType} ${id}` : object.object} via ${actor}`);
switch (type) {
case 'Follow': {
switch (localType) {
+ case 'application': {
+ await activitypub.relays.removeFollower(actor);
+ break;
+ }
+
case 'user': {
const exists = await user.exists(id);
if (!exists) {
diff --git a/src/activitypub/relays.js b/src/activitypub/relays.js
index afaeaaa05f..af1ee9dc77 100644
--- a/src/activitypub/relays.js
+++ b/src/activitypub/relays.js
@@ -95,11 +95,41 @@ Relays.remove = async (url) => {
]);
};
-Relays.handshake = async (object) => {
+Relays.handshake = async (body) => {
const now = new Date();
- const { type, actor } = object;
+ const { type, actor } = body;
- // Confirm relay was added
+ // Resolve the original Follow activity
+ // If type is 'Follow', the activity is in body.object
+ // If type is 'Accept', the activity is in body.object.object
+ const followActivity = type === 'Follow' ? body.object : body.object?.object;
+
+ if (!followActivity) {
+ throw new Error('[[error:api.400]]');
+ }
+
+ // Check if NodeBB is the target of the follow
+ const target = typeof followActivity === 'object' ? followActivity.id : followActivity;
+ if (target === `${nconf.get('url')}/actor`) {
+ await Relays.addFollower(actor);
+
+ if (type === 'Follow') {
+ await activitypub.send('uid', 0, actor, {
+ '@context': [
+ 'https://www.w3.org/ns/activitystreams',
+ 'https://pleroma.example/schemas/litepub-0.1.jsonld',
+ ],
+ id: `${nconf.get('url')}/actor#activity/accept/${encodeURIComponent(actor)}/${now.getTime()}`,
+ type: 'Accept',
+ to: [actor],
+ published: now.toISOString(),
+ object: followActivity,
+ });
+ }
+ return;
+ }
+
+ // Confirm relay was added (NodeBB is the follower)
const exists = await db.isSortedSetMember('relays:createtime', actor);
if (!exists) {
throw new Error('[[error:api.400]]');
@@ -116,11 +146,30 @@ Relays.handshake = async (object) => {
type: 'Accept',
to: [actor],
published: now.toISOString(),
- object,
+ object: body,
});
} else if (type === 'Accept') {
await db.sortedSetIncrBy('relays:state', 1, actor);
} else {
throw new Error('[[error:api.400]]');
}
-};
\ No newline at end of file
+};
+
+Relays.addFollower = async (actor) => {
+ await db.sortedSetAdd('relays:followers', Date.now(), actor);
+};
+
+Relays.removeFollower = async (actor) => {
+ await db.sortedSetRemove('relays:followers', actor);
+};
+
+Relays.getFollowers = async () => {
+ return db.getSortedSetMembers('relays:followers');
+};
+
+Relays.broadcast = async (payload) => {
+ const followers = await Relays.getFollowers();
+ if (followers.length === 0) return;
+
+ await activitypub.send('uid', 0, followers, payload);
+};
diff --git a/test/activitypub/helpers.js b/test/activitypub/helpers.js
index 25def3ab12..5147b95b61 100644
--- a/test/activitypub/helpers.js
+++ b/test/activitypub/helpers.js
@@ -153,6 +153,31 @@ Helpers.mocks.accept = (actor, object) => {
return { activity };
};
+Helpers.mocks.undo = (override = {}) => {
+ let actor = override.actor;
+ let object = override.object;
+ if (!actor) {
+ ({ id: actor } = Helpers.mocks.person());
+ }
+ if (!object) {
+ ({ id: object } = Helpers.mocks.note());
+ }
+
+ const uuid = utils.generateUUID();
+ const id = `${Helpers.mocks._baseUrl}/undo/${uuid}`;
+
+ const activity = {
+ '@context': 'https://www.w3.org/ns/activitystreams',
+ id,
+ type: 'Undo',
+ to: ['https://www.w3.org/ns/activitystreams#Public'],
+ actor,
+ object,
+ };
+
+ return { activity };
+};
+
Helpers.mocks.like = (override = {}) => {
let actor = override.actor;
let object = override.object;
diff --git a/test/activitypub/inbox.js b/test/activitypub/inbox.js
index cf1a388c4c..934915ee77 100644
--- a/test/activitypub/inbox.js
+++ b/test/activitypub/inbox.js
@@ -1124,5 +1124,108 @@ describe('Inbox', () => {
assert(score > 0);
});
});
+ describe('Relay', () => {
+ const relayActor = 'https://relay.example.com/actor';
+
+ it('should add a follower when the instance actor is followed', async () => {
+ const { activity } = helpers.mocks.follow({
+ actor: relayActor,
+ object: { id: `${nconf.get('url')}/actor` },
+ });
+
+ await activitypub.inbox.follow({ body: activity });
+
+ const isFollower = await db.isSortedSetMember('relays:followers', relayActor);
+ assert.strictEqual(isFollower, true);
+ });
+
+ it('should remove a follower when a Follow activity is undone', async () => {
+ await activitypub.relays.addFollower(relayActor);
+
+ const followActivity = {
+ id: `${nconf.get('url')}/actor#activity/follow/${relayActor}`,
+ type: 'Follow',
+ actor: relayActor,
+ object: `${nconf.get('url')}/actor`,
+ };
+ const { activity: undoActivity } = helpers.mocks.undo({
+ actor: relayActor,
+ object: followActivity,
+ });
+
+ await activitypub.inbox.undo({ body: undoActivity });
+
+ const isFollower = await db.isSortedSetMember('relays:followers', relayActor);
+ assert.strictEqual(isFollower, false);
+ });
+
+ it('should broadcast a public activity received via announce to relay followers', async () => {
+ await activitypub.relays.addFollower(relayActor);
+ await activitypub.relays.add(relayActor);
+
+ const { note, id } = helpers.mocks.note();
+ const { activity: createActivity } = helpers.mocks.create(note);
+ const { activity: announceActivity } = helpers.mocks.announce({
+ actor: relayActor,
+ object: createActivity,
+ });
+
+ // Mock activitypub.send to verify broadcast
+ const originalSend = activitypub.send;
+ const sentTo = [];
+ activitypub.send = async (type, id, targets, payload) => {
+ sentTo.push({ targets, payload });
+ return true;
+ };
+
+ // Mock resolveId so remote note IDs resolve to a local pid
+ const originalResolveId = activitypub.resolveId;
+ activitypub.resolveId = async () => 1;
+
+ // Mock notes.assert to return a valid assertion
+ const originalNotesAssert = activitypub.notes.assert;
+ activitypub.notes.assert = async () => ({ tid: 1 });
+
+ // Mock Notes.announce.add to avoid post/topic lookup errors
+ const originalAnnounceAdd = activitypub.notes.announce.add;
+ activitypub.notes.announce.add = async () => {};
+
+ // Mock posts.getPostField so Feps.announce can resolve tid/cid
+ const originalGetPostField = posts.getPostField;
+ posts.getPostField = async (id, field) => {
+ if (field === 'tid') return 1;
+ if (field === 'cid') return 1;
+ return originalGetPostField(id, field);
+ };
+
+ // Mock topics.getTopicField so Feps.announce can resolve cid
+ const originalGetTopicField = topics.getTopicField;
+ topics.getTopicField = async (id, field) => {
+ if (field === 'cid') return 1;
+ return originalGetTopicField(id, field);
+ };
+
+ // Mock relays.list so Feps.announce has relay targets
+ const originalRelaysList = activitypub.relays.list;
+ activitypub.relays.list = async () => [{ state: 2, url: relayActor }];
+
+ await activitypub.inbox.announce({ body: announceActivity });
+
+ // We expect a broadcast to relay followers
+ // Feps.announce will call activitypub.send
+ assert(sentTo.length > 0);
+ const broadcast = sentTo.find(s => s.targets.includes(relayActor));
+ assert(broadcast, 'Should have broadcast to relay follower');
+
+ activitypub.send = originalSend;
+ activitypub.resolveId = originalResolveId;
+ activitypub.notes.assert = originalNotesAssert;
+ activitypub.notes.announce.add = originalAnnounceAdd;
+ posts.getPostField = originalGetPostField;
+ topics.getTopicField = originalGetTopicField;
+ activitypub.relays.list = originalRelaysList;
+ await db.sortedSetRemove('relays:followers', relayActor);
+ });
+ });
});
});
diff --git a/test/activitypub/relays.js b/test/activitypub/relays.js
new file mode 100644
index 0000000000..2a52b94cf2
--- /dev/null
+++ b/test/activitypub/relays.js
@@ -0,0 +1,67 @@
+'use strict';
+
+const assert = require('assert');
+const activitypub = require('../../src/activitypub');
+const db = require('../../src/database');
+
+describe('ActivityPub Relays', () => {
+ const actor = 'https://example.com/actor';
+
+ afterEach(async () => {
+ await db.sortedSetRemove('relays:followers', actor);
+ });
+
+ it('should add a relay follower', async () => {
+ await activitypub.relays.addFollower(actor);
+ const exists = await db.isSortedSetMember('relays:followers', actor);
+ assert.strictEqual(exists, true);
+ });
+
+ it('should remove a relay follower', async () => {
+ await activitypub.relays.addFollower(actor);
+ await activitypub.relays.removeFollower(actor);
+ const exists = await db.isSortedSetMember('relays:followers', actor);
+ assert.strictEqual(exists, false);
+ });
+
+ it('should get relay followers', async () => {
+ const actor2 = 'https://example2.com/actor';
+ await Promise.all([
+ activitypub.relays.addFollower(actor),
+ activitypub.relays.addFollower(actor2),
+ ]);
+
+ const followers = await activitypub.relays.getFollowers();
+ assert.strictEqual(followers.length, 2);
+ assert.ok(followers.includes(actor));
+ assert.ok(followers.includes(actor2));
+
+ await db.sortedSetRemove('relays:followers', actor2);
+ });
+
+ it('should broadcast to relay followers', async () => {
+ const payload = { type: 'Create', id: '123' };
+ const followers = ['https://f1.com/actor', 'https://f2.com/actor'];
+
+ // Mock activitypub.send
+ const originalSend = activitypub.send;
+ const sentTo = [];
+ activitypub.send = async (type, id, targets, payload) => {
+ sentTo.push({ targets, payload });
+ return true;
+ };
+
+ await Promise.all(followers.map(f => activitypub.relays.addFollower(f)));
+
+ await activitypub.relays.broadcast(payload);
+
+ assert.strictEqual(sentTo.length, 1);
+ assert.deepStrictEqual(sentTo[0].targets, followers);
+ assert.deepStrictEqual(sentTo[0].payload, payload);
+
+ // Cleanup
+ activitypub.send = originalSend;
+ await db.sortedSetRemove('relays:followers', followers[0]);
+ await db.sortedSetRemove('relays:followers', followers[1]);
+ });
+});