Node.js based forum software built for the modern web
feat(flags): support remote flag forwarding for chat messages
Julian Lam8462ac86d248
diff --git a/src/activitypub/out.js b/src/activitypub/out.jsindex d22487ab7b..456e5d326d 100644--- a/src/activitypub/out.js+++ b/src/activitypub/out.js@@ -371,7 +371,7 @@ Out.flag = enabledCheck(async (uid, flag) => {return;}const reportedIds = [flag.targetId];- if (flag.type === 'post' && activitypub.helpers.isUri(flag.targetUid)) {+ if ((flag.type === 'post' || flag.type === 'message') && activitypub.helpers.isUri(flag.targetUid)) {reportedIds.push(flag.targetUid);}const reason = flag.reason ||@@ -572,7 +572,7 @@ Out.undo.flag = enabledCheck(async (uid, flag) => {return;}const reportedIds = [flag.targetId];- if (flag.type === 'post' && activitypub.helpers.isUri(flag.targetUid)) {+ if ((flag.type === 'post' || flag.type === 'message') && activitypub.helpers.isUri(flag.targetUid)) {reportedIds.push(flag.targetUid);}const reason = flag.reason ||diff --git a/src/flags.js b/src/flags.jsindex 80a7586c0b..72330a5231 100644--- a/src/flags.js+++ b/src/flags.js@@ -124,7 +124,7 @@ Flags.get = async function (flagId) {reports,};['flagId', 'targetUid', 'datetime', 'targetId'].forEach((prop) => {- if (flagObj?.[prop]) {+ if (flagObj?.[prop] && utils.isNumber(flagObj[prop])) {flagObj[prop] = parseInt(flagObj[prop], 10);}});@@ -325,7 +325,7 @@ Flags.validate = async function (payload) {throw new Error(`[[error:not-enough-reputation-to-flag, ${meta.config['min:rep:flag']}]]`);}} else if (payload.type === 'message') {- const canView = await messaging.canViewMessage([parseInt(payload.id, 10)], payload.roomId, payload.uid);+ const canView = await messaging.canViewMessage([payload.id], payload.roomId, payload.uid);if (!canView[0]) {throw new Error('[[error:no-privileges]]');}@@ -366,6 +366,10 @@ Flags.getFlagIdByTarget = async function (type, id) {method = user.getUserField;break;+ case 'message':+ method = messaging.getMessageField;+ break;+default:throw new Error('[[error:invalid-data]]');}@@ -481,6 +485,8 @@ Flags.create = async function (type, id, uid, reason, timestamp, forceFlag = fal}} else if (type === 'user') {batched.push(user.setUserField(id, 'flagId', flagId));+ } else if (type === 'message') {+ batched.push(messaging.setMessageField(id, 'flagId', flagId));}// Run all the database calls in one single batched call...@@ -504,6 +510,7 @@ Flags.purge = async function (flagIds) {const flagData = (await db.getObjects(flagIds.map(flagId => `flag:${flagId}`))).filter(Boolean);const postFlags = flagData.filter(flagObj => flagObj.type === 'post');const userFlags = flagData.filter(flagObj => flagObj.type === 'user');+ const messageFlags = flagData.filter(flagObj => flagObj.type === 'message');const assignedFlags = flagData.filter(flagObj => !!flagObj.assignee);const [allReports, cids] = await Promise.all([@@ -529,8 +536,9 @@ Flags.purge = async function (flagIds) {...assignedFlags.map(flagObj => ([`flags:byAssignee:${flagObj.assignee}`, flagObj.flagId])),...userFlags.map(flagObj => ([`flags:byTargetUid:${flagObj.targetUid}`, flagObj.flagId])),]),- db.deleteObjectFields(postFlags.map(flagObj => `post:${flagObj.targetId}`, ['flagId'])),- db.deleteObjectFields(userFlags.map(flagObj => `user:${flagObj.targetId}`, ['flagId'])),+ db.deleteObjectFields(postFlags.map(flagObj => `post:${flagObj.targetId}`), ['flagId']),+ db.deleteObjectFields(userFlags.map(flagObj => `user:${flagObj.targetId}`), ['flagId']),+ db.deleteObjectFields(messageFlags.map(flagObj => `message:${flagObj.targetId}`), ['flagId']),db.deleteAll([...flagIds.map(flagId => `flag:${flagId}`),...flagIds.map(flagId => `flag:${flagId}:notes`),@@ -720,7 +728,7 @@ Flags.getTarget = async function (type, id, uid) {return postData[0];}if (type === 'message') {- const message = await messaging.getMessageData(parseInt(id, 10), uid, await messaging.getRoomIdByMid(id));+ const message = await messaging.getMessageData(id, uid, await messaging.getRoomIdByMid(id));return message && message[0] ? message[0] : {};}throw new Error('[[error:invalid-data]]');@@ -759,7 +767,7 @@ Flags.getTargetUid = async function (type, id) {return 0;}const uid = await messaging.getMessageField(id, 'fromuid');- return uid ? parseInt(uid, 10) : 0;+ return uid || 0;}return id;};diff --git a/test/flags.js b/test/flags.jsindex 8c292878fb..11a3846f97 100644--- a/test/flags.js+++ b/test/flags.js@@ -20,6 +20,9 @@ const Privileges = require('../src/privileges');const plugins = require('../src/plugins');const utils = require('../src/utils');const api = require('../src/api');+const messaging = require('../src/messaging');+const activitypub = require('../src/activitypub');+const apHelpers = require('./activitypub/helpers');describe('Flags', () => {let uid1;@@ -1200,6 +1203,156 @@ describe('Flags', () => {});});+ describe('remote (federated) chat messages', () => {+ let uid1;+ let uid2;+ let actor;+ let mid;+ let roomId;+ let flagId;++ before(async () => {+ Meta.config.activitypubEnabled = 1;+ await Privileges.global.give(['groups:chat', 'groups:chat:privileged'], 'fediverse');++ uid1 = await User.create({ username: utils.generateUUID().slice(0, 10) });+ uid2 = await User.create({ username: utils.generateUUID().slice(0, 10) });+ ({ id: actor } = apHelpers.mocks.person());++ // Remote actor sends a DM to two local users; both become room members+ const { note } = apHelpers.mocks.note({+ attributedTo: actor,+ to: [+ `${nconf.get('url')}/uid/${uid1}`,+ `${nconf.get('url')}/uid/${uid2}`,+ ],+ cc: [],+ });+ const { activity } = apHelpers.mocks.create({+ actor,+ object: note,+ to: [+ `${nconf.get('url')}/uid/${uid1}`,+ `${nconf.get('url')}/uid/${uid2}`,+ ],+ cc: [],+ });++ await activitypub.inbox.create({ body: activity });+ mid = note.id;+ roomId = await messaging.getRoomIdByMid(mid);+ });++ after(async () => {+ await Privileges.global.rescind(['groups:chat', 'groups:chat:privileged'], 'fediverse');+ delete Meta.config.activitypubEnabled;+ });++ it('should store the remote message as a chat message with its ActivityPub URI as mid', async () => {+ assert.ok(activitypub.helpers.isUri(mid));+ assert.strictEqual(await messaging.messageExists(mid), true);+ assert.strictEqual(await messaging.getMessageField(mid, 'fromuid'), actor);+ });++ it('should allow a room member to flag a remote message', async () => {+ const flag = await api.flags.create({ uid: uid1 }, {+ type: 'message',+ id: mid,+ roomId,+ reason: 'spam',+ notifyRemote: true,+ });++ flagId = flag.flagId;+ assert.strictEqual(flag.type, 'message');+ assert.strictEqual(flag.targetId, mid);+ assert.strictEqual(flag.targetUid, actor);+ assert.strictEqual(flag.reports.length, 1);+ assert.strictEqual(flag.reports[0].value, 'spam');+ });++ it('should forward a Flag activity naming the remote message and its author', async () => {+ const flagActivityId = `${nconf.get('url')}/message/${encodeURIComponent(mid)}#activity/flag/${uid1}`;+ const sent = activitypub._sent.get(flagActivityId);+ assert.ok(sent, 'Flag activity was sent');+ assert.strictEqual(sent.payload.type, 'Flag');+ assert.strictEqual(sent.payload.actor, `${nconf.get('url')}/uid/${uid1}`);+ assert.strictEqual(sent.payload.content, 'spam');+ assert.deepStrictEqual(sent.payload.object, [mid, actor]);+ });++ it('should store the flagId on the flagged message', async () => {+ // Coerce both to string since PostgreSQL may return the flagId as a number+ assert.strictEqual(String(await messaging.getMessageField(mid, 'flagId')), String(flagId));+ });++ it('should allow a second reporter to add their report to the existing flag', async () => {+ const flag = await api.flags.create({ uid: uid2 }, {+ type: 'message',+ id: mid,+ roomId,+ reason: 'harassment',+ notifyRemote: true,+ });++ assert.strictEqual(flag.flagId, flagId);+ const reports = await Flags.getReports(flagId);+ assert.strictEqual(reports.length, 2);+ });++ it('should forward a second Flag activity from the new reporter', async () => {+ const flagActivityId = `${nconf.get('url')}/message/${encodeURIComponent(mid)}#activity/flag/${uid2}`;+ const sent = activitypub._sent.get(flagActivityId);+ assert.ok(sent, 'Flag activity was sent');+ assert.strictEqual(sent.payload.content, 'harassment');+ assert.deepStrictEqual(sent.payload.object, [mid, actor]);+ });++ it('should rescind a single report via API and send an Undo Flag', async () => {+ await api.flags.rescind({ uid: uid2 }, { flagId });++ const flag = await Flags.get(flagId);+ const reports = await Flags.getReports(flagId);+ assert.strictEqual(reports.length, 1);+ assert.strictEqual(flag.targetId, mid);+ assert.strictEqual(flag.targetUid, actor);++ const undo = Array.from(activitypub._sent.values()).find(({ payload }) => {+ return payload.type === 'Undo' && payload.object.id.endsWith(`#activity/flag/${uid2}`);+ });+ assert.ok(undo, 'Undo Flag activity was sent');+ assert.strictEqual(undo.payload.object.type, 'Flag');+ assert.deepStrictEqual(undo.payload.object.object, [mid, actor]);+ });++ it('should not allow a user who is not in the room to flag a remote message', async () => {+ const outsider = await User.create({ username: utils.generateUUID().slice(0, 10) });++ await assert.rejects(+ api.flags.create({ uid: outsider }, {+ type: 'message',+ id: mid,+ roomId,+ reason: 'spam',+ }),+ { message: '[[error:no-privileges]]' },+ );+ });++ it('should send an Undo Flag for remaining reports and clean up when purged', async () => {+ await Flags.purge([flagId]);++ assert.strictEqual(await messaging.messageExists(mid), true);+ assert.strictEqual(await messaging.getMessageField(mid, 'flagId'), null);+ assert.strictEqual(await Flags.exists('message', mid, uid1), false);++ const undo = Array.from(activitypub._sent.values()).find(({ payload }) => {+ return payload.type === 'Undo' && payload.object.id.endsWith(`#activity/flag/${uid1}`);+ });+ assert.ok(undo, 'Undo Flag activity was sent');+ assert.deepStrictEqual(undo.payload.object.object, [mid, actor]);+ });+ });});});