Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
feat(chat): apply message moderation, editing and retraction on the server (#17763)
Дамян Минков6e91afa2427b
diff --git a/lang/main.json b/lang/main.jsonindex abaee859c9..bb24fd2475 100644--- a/lang/main.json+++ b/lang/main.json@@ -115,6 +115,7 @@}},"chat": {+ "delete": "Delete","deleteMessage": "Delete","deletedMessage": "This message was deleted.","deletedMessageByMe": "You deleted this message.",diff --git a/react/features/base/conference/reducer.ts b/react/features/base/conference/reducer.tsindex 392d3baec1..8445e9de4e 100644--- a/react/features/base/conference/reducer.ts+++ b/react/features/base/conference/reducer.ts@@ -173,6 +173,7 @@ export interface IJitsiConference {sendLobbyMessage: Function;sendLobbyMessageRetraction: Function;sendMessage: Function;+ sendMessageCorrection: Function;sendMessageRetraction: Function;sendPrivateTextMessage: Function;sendReaction: Function;diff --git a/react/features/chat/actionTypes.ts b/react/features/chat/actionTypes.tsindex 35ffea11e4..5b085860f8 100644--- a/react/features/chat/actionTypes.ts+++ b/react/features/chat/actionTypes.ts@@ -64,12 +64,11 @@ export const EDIT_MESSAGE = 'EDIT_MESSAGE';/*** The type of the action which signals to moderate a message- *+ ** {* type: MODERATE_MESSAGE,* messageId: string,- * moderatedBy: string,- * reason: string+ * reason: string* }*/export const MODERATE_MESSAGE = 'MODERATE_MESSAGE';@@ -255,3 +254,14 @@ export const SET_CHAT_IS_RESIZING = 'SET_CHAT_IS_RESIZING';* }*/export const NOTIFY_PRIVATE_RECIPIENTS_CHANGED = 'NOTIFY_PRIVATE_RECIPIENTS_CHANGED';++/**+ * The type of action which sets whether the server handles message moderation+ * and editing for this room.+ *+ * {+ * type: SET_MESSAGE_MODERATION_SUPPORTED,+ * supported: boolean+ * }+ */+export const SET_MESSAGE_MODERATION_SUPPORTED = 'SET_MESSAGE_MODERATION_SUPPORTED';diff --git a/react/features/chat/actions.any.ts b/react/features/chat/actions.any.tsindex 2f08c380a2..249fb32530 100644--- a/react/features/chat/actions.any.ts+++ b/react/features/chat/actions.any.ts@@ -26,6 +26,7 @@ import {SET_FOCUSED_TAB,SET_LOBBY_CHAT_ACTIVE_STATE,SET_LOBBY_CHAT_RECIPIENT,+ SET_MESSAGE_MODERATION_SUPPORTED,SET_PRIVATE_MESSAGE_RECIPIENT} from './actionTypes';import { ChatTabs } from './constants';@@ -490,26 +491,18 @@ export function handleLobbyChatInitialized(participantId: string) {/*** Requests moderation of a chat message.*- * Dispatches the network action so other participants get notified, and- * optimistically marks the message as moderated in the local store too,- * since MESSAGE_MODERATED isn't guaranteed to be echoed back to the sender.+ * The room applies the moderation and echoes it back to everybody, including the+ * sender, so there is nothing to update locally here.** @param {IMessage} message - The message to moderate.* @param {string} reason - Reason to delete message.- * @returns {Function}+ * @returns {Object}*/export function sendMessageModeration(message: IMessage, reason?: string) {- return (dispatch: IStore['dispatch'], getState: IStore['getState']) => {- const state = getState();- const localParticipant = getLocalParticipant(state);-- dispatch({- type: SEND_MESSAGE_MODERATION,- message,- reason- });-- dispatch(moderateMessage(message.messageId, localParticipant?.id, reason));+ return {+ type: SEND_MESSAGE_MODERATION,+ message,+ reason};}@@ -517,15 +510,26 @@ export function sendMessageModeration(message: IMessage, reason?: string) {* Marks a message as moderated.** @param {string} messageId - The moderated message id.- * @param {string} moderatorId - The participant id of the moderator.* @param {string} reason - Optional moderation reason.* @returns {Object}*/-export function moderateMessage(messageId: string, moderatorId?: string, reason?: string) {+export function moderateMessage(messageId: string, reason?: string) {return {type: MODERATE_MESSAGE,messageId,- moderatorId,reason};}++/**+ * Sets whether the room handles message moderation and editing server side.+ *+ * @param {boolean} supported - Whether the room applies message moderation.+ * @returns {Object}+ */+export function setMessageModerationSupported(supported: boolean) {+ return {+ type: SET_MESSAGE_MODERATION_SUPPORTED,+ supported+ };+}diff --git a/react/features/chat/components/web/ChatMessage.tsx b/react/features/chat/components/web/ChatMessage.tsxindex 6273d53af9..6f15c0a800 100644--- a/react/features/chat/components/web/ChatMessage.tsx+++ b/react/features/chat/components/web/ChatMessage.tsx@@ -488,7 +488,6 @@ const ChatMessage = ({isLobbyMessage = { message.lobbyChat }isModerated = { message.isModerated }message = { message }- messageId = { message.messageId }onEditMessage = { handleEditMessage }participantId = { message.participantId } />}</div>@@ -577,7 +576,6 @@ const ChatMessage = ({isLobbyMessage = { message.lobbyChat }isModerated = { message.isModerated }message = { message }- messageId = { message.messageId }onEditMessage = { handleEditMessage }participantId = { message.participantId } />}</div>diff --git a/react/features/chat/components/web/MessageMenu.tsx b/react/features/chat/components/web/MessageMenu.tsxindex 20cc787c64..a037210445 100644--- a/react/features/chat/components/web/MessageMenu.tsx+++ b/react/features/chat/components/web/MessageMenu.tsx@@ -27,7 +27,6 @@ export interface IProps {isLobbyMessage: boolean;isModerated?: boolean;message: IMessage;- messageId: string;onEditMessage?: () => void;participantId: string;}@@ -69,7 +68,7 @@ const useStyles = makeStyles()(theme => {};});-const MessageMenu = ({ canEdit, message, messageId, isFromVisitor, isLobbyMessage, isModerated, enablePrivateChat, displayName, isFileMessage, onEditMessage }: IProps) => {+const MessageMenu = ({ canEdit, message, isFromVisitor, isLobbyMessage, isModerated, enablePrivateChat, displayName, isFileMessage, onEditMessage }: IProps) => {const dispatch = useDispatch();const { classes, cx } = useStyles();const { t } = useTranslation();@@ -80,10 +79,16 @@ const MessageMenu = ({ canEdit, message, messageId, isFromVisitor, isLobbyMessagconst buttonRef = useRef<HTMLDivElement>(null);const isModerator = useSelector(isLocalParticipantModerator);+ const messageModerationSupported = useSelector(+ (state: IReduxState) => state['features/chat'].messageModerationSupported);const participant = useSelector((state: IReduxState) => getParticipantById(state, message.participantId));+ // Editing and deleting are applied by the server, so only offer them where the+ // room says it handles them.+ const canEditMessage = canEdit && messageModerationSupported;+// If no menu items will be shown, don't render the menu button.- if (!enablePrivateChat && isFileMessage && !canEdit) {+ if (!enablePrivateChat && isFileMessage && !canEditMessage) {return null;}@@ -150,9 +155,9 @@ const MessageMenu = ({ canEdit, message, messageId, isFromVisitor, isLobbyMessag}, [ message, handleClose ]);const handleModerateClick = useCallback(() => {- dispatch(sendMessageModeration({ messageId } as IMessage));+ dispatch(sendMessageModeration(message));handleClose();- }, [ dispatch, messageId, handleClose ]);+ }, [ dispatch, message, handleClose ]);const handleEditClick = useCallback(() => {onEditMessage?.();@@ -161,7 +166,7 @@ const MessageMenu = ({ canEdit, message, messageId, isFromVisitor, isLobbyMessagconst popoverContent = (<div className = { classes.menuPanel }>- {canEdit && (+ {canEditMessage && (<divclassName = { classes.menuItem }onClick = { handleEditClick }>@@ -182,15 +187,21 @@ const MessageMenu = ({ canEdit, message, messageId, isFromVisitor, isLobbyMessag{t('Copy')}</div>)}- {isModerator && !isModerated && (- <div- className = { classes.menuItem }- onClick = { handleModerateClick }>- {t('chat.delete')}- </div>- )}+ {isModerator+ && !isModerated+ && messageModerationSupported+ && message.messageType !== MESSAGE_TYPE_LOCAL+ && (+ <div+ className = { classes.menuItem }+ onClick = { handleModerateClick }>+ {t('chat.delete')}+ </div>+ )}{message.messageType === MESSAGE_TYPE_LOCAL&& !message.isDeleted+ && !message.isModerated+ && messageModerationSupported&& (<divclassName = { classes.menuItem }diff --git a/react/features/chat/constants.ts b/react/features/chat/constants.tsindex 62b70f26d6..fb9242e374 100644--- a/react/features/chat/constants.ts+++ b/react/features/chat/constants.ts@@ -77,7 +77,6 @@ export const OPTION_GROUPCHAT = 'groupchat';export const MODERATE_CHAT_MESSAGE = 'MODERATE_CHAT_MESSAGE';-export const EDIT_CHAT_MESSAGE = 'editChat';/*** Maximum number of pending edits are allowed.diff --git a/react/features/chat/middleware.ts b/react/features/chat/middleware.tsindex 90423e36c4..73e220700a 100644--- a/react/features/chat/middleware.ts+++ b/react/features/chat/middleware.ts@@ -20,7 +20,8 @@ import { PARTICIPANT_JOINED, PARTICIPANT_LEFT, PARTICIPANT_UPDATED } from '../baimport {getLocalParticipant,getParticipantById,- getParticipantDisplayName+ getParticipantDisplayName,+ isLocalParticipantModerator} from '../base/participants/functions';import { IParticipant } from '../base/participants/types';import MiddlewareRegistry from '../base/redux/MiddlewareRegistry';@@ -62,13 +63,13 @@ import {notifyPrivateRecipientsChanged,openChat,retractMessage,+ setMessageModerationSupported,setPrivateMessageRecipient} from './actions';import { ChatPrivacyDialog } from './components';import {CHAR_LIMIT,ChatTabs,- EDIT_CHAT_MESSAGE,INCOMING_MSG_SOUND_ID,LOBBY_CHAT_MESSAGE,MESSAGE_TYPE_ERROR,@@ -157,18 +158,17 @@ MiddlewareRegistry.register(store => next => action => {const { participant, data } = action;if (data?.type === MODERATE_CHAT_MESSAGE) {- _onMessageModerated(store, data.messageId, data.moderatedBy, data.reason);- }-- if (data?.type === EDIT_CHAT_MESSAGE && data.messageId && data.message) {- const trimmedMessage = String(data.message).slice(0, CHAR_LIMIT);-- store.dispatch(editMessage({- messageId: data.messageId,- message: trimmedMessage,- editedAt: data.editedAt,- participantId: participant.getId()- }));+ // Moderating a message is a moderator-only operation, and the authoritative+ // source for it is the MESSAGE_MODERATED event from the server (XEP-0425).+ // This endpoint message path only exists so participants can bring late joiners+ // up to date, so honour it just for senders that hold the moderator role, and+ // cap the reason the same way an edit is capped.+ if (participant?.isModerator?.()) {+ _onMessageModerated(+ store,+ data.messageId,+ typeof data.reason === 'string' ? data.reason.slice(0, CHAR_LIMIT) : undefined);+ }break;}@@ -204,11 +204,10 @@ MiddlewareRegistry.register(store => next => action => {case NON_PARTICIPANT_MESSAGE_RECEIVED: {const { participantId, json: data } = action;- if (data?.type === MODERATE_CHAT_MESSAGE) {- _onMessageModerated(store, data.messageId, data.moderatedBy, data.reason);- break;- }-+ // MODERATE_CHAT_MESSAGE is deliberately not handled here: a non participant sender+ // is only identified by a MUC resource, so there is no role to check it against.+ // Moderation arrives from the server (MESSAGE_MODERATED), or from a moderator+ // participant in ENDPOINT_MESSAGE_RECEIVED.if (data?.type === MESSAGE_TYPE_SYSTEM && data.message) {_handleReceivedMessage(store, {displayName: data.displayName ?? i18next.t('chat.systemDisplayName'),@@ -289,14 +288,9 @@ MiddlewareRegistry.register(store => next => action => {m.isModerated);- const editedMessages = state['features/chat'].messages.filter(- (m: IMessage) =>- m.isEdited- && !m.privateMessage- && m.messageType === MESSAGE_TYPE_LOCAL- );-- if (moderatedMessages.length > 0) {+ // Only a moderator's replay is accepted by the receiving side, so don't have+ // every participant emit messages that will be dropped anyway.+ if (moderatedMessages.length > 0 && isLocalParticipantModerator(state)) {const sendWithRetry = (retries: number) => {try {moderatedMessages.forEach(message => {@@ -305,7 +299,6 @@ MiddlewareRegistry.register(store => next => action => {JSON.stringify({type: MODERATE_CHAT_MESSAGE,messageId: message.messageId,- moderatedBy: message.moderatedBy,reason: message.moderationReason}),'json-message'@@ -321,18 +314,6 @@ MiddlewareRegistry.register(store => next => action => {setTimeout(() => sendWithRetry(3), 3000);}- editedMessages.forEach(message => {- conference.sendPrivateTextMessage(- action.participant.id,- JSON.stringify({- type: EDIT_CHAT_MESSAGE,- messageId: message.messageId,- message: message.message,- editedAt: message.editedAt- }),- 'json-message'- );- });}if (_shouldNotifyPrivateRecipientsChanged(store, action)) {@@ -466,21 +447,15 @@ MiddlewareRegistry.register(store => next => action => {) {const trimmedMessage = String(action.message).trim().slice(0, CHAR_LIMIT);- const payload = {- type: EDIT_CHAT_MESSAGE,- messageId: action.messageId,- message: trimmedMessage,- editedAt- };-if (messageToEdit.privateMessage && messageToEdit.recipientId) {- conference.sendPrivateTextMessage(+ conference.sendMessageCorrection(+ action.messageId,+ trimmedMessage,messageToEdit.recipientId,- JSON.stringify(payload),- 'json-message'+ messageToEdit.sentToVisitor);} else {- conference.sendTextMessage(JSON.stringify(payload), 'json-message');+ conference.sendMessageCorrection(action.messageId, trimmedMessage);}store.dispatch(editMessage({@@ -644,25 +619,6 @@ function _addChatMsgListener(conference: IJitsiConference, store: IStore) {JitsiConferenceEvents.PRIVATE_MESSAGE_RECEIVED,(participantId: string, message: string, timestamp: number, messageId: string, displayName?: string,isFromVisitor?: boolean, replyToId?: string) => {- try {- const data = JSON.parse(message);-- if (data?.type === EDIT_CHAT_MESSAGE && data.messageId && data.message) {- const trimmedMessage = String(data.message).slice(0, CHAR_LIMIT);-- store.dispatch(editMessage({- messageId: data.messageId,- message: trimmedMessage,- editedAt: data.editedAt,- participantId- }));-- // Don't treat edit payload as a new chat message.- return;- }- } catch (e) {- // Normal private message.- }_onConferenceMessageReceived(store, {participantId,message,@@ -676,10 +632,27 @@ function _addChatMsgListener(conference: IJitsiConference, store: IStore) {});+ conference.on(+ JitsiConferenceEvents.MESSAGE_CORRECTED,+ (participantId: string, messageId: string, message: string, timestamp?: string) => {+ store.dispatch(editMessage({+ messageId,+ message: String(message).slice(0, CHAR_LIMIT),+ editedAt: timestamp ? new Date(timestamp).getTime() : Date.now(),+ participantId+ }));+ });+conference.on(JitsiConferenceEvents.MESSAGE_MODERATED,- (messageId: string, moderatorId: string, reason?: string) => {- _onMessageModerated(store, messageId, moderatorId, reason);+ (messageId: string, reason?: string) => {+ _onMessageModerated(store, messageId, reason);+ });++ conference.on(+ JitsiConferenceEvents.MESSAGE_MODERATION_SUPPORTED_CHANGED,+ (supported: boolean) => {+ store.dispatch(setMessageModerationSupported(supported));});conference.on(@@ -751,15 +724,14 @@ function _onReactionReceived(store: IStore, { participantId, reactionList, messa}/**- * Handles a moderator message deletion.+ * Handles a moderated message.** @param {Object} store - Redux store.* @param {string} messageId - The id of the message which is being deleted.- * @param {string} moderatorId - The Id of the moderator.* @param {string} reason - The reason for which message is deleted.* @returns {void}*/-function _onMessageModerated(store: IStore, messageId: string, moderatorId: string, reason?: string) {+function _onMessageModerated(store: IStore, messageId: string, reason?: string) {const { messages } = store.getState()['features/chat'];const originalMessage = messages.find(@@ -770,7 +742,7 @@ function _onMessageModerated(store: IStore, messageId: string, moderatorId: strireturn;}- store.dispatch(moderateMessage(messageId, moderatorId, reason));+ store.dispatch(moderateMessage(messageId, reason));}/*diff --git a/react/features/chat/reducer.ts b/react/features/chat/reducer.tsindex 81b09c9f15..1729f1095a 100644--- a/react/features/chat/reducer.ts+++ b/react/features/chat/reducer.ts@@ -23,6 +23,7 @@ import {SET_FOCUSED_TAB,SET_LOBBY_CHAT_ACTIVE_STATE,SET_LOBBY_CHAT_RECIPIENT,+ SET_MESSAGE_MODERATION_SUPPORTED,SET_PRIVATE_MESSAGE_RECIPIENT,SET_USER_CHAT_WIDTH} from './actionTypes';@@ -33,6 +34,7 @@ import { IMessage, IPendingEditsMap } from './types';const DEFAULT_STATE = {groupChatWithPermissions: false,isOpen: false,+ messageModerationSupported: false,messages: [],notifyPrivateRecipientsChangedTimestamp: undefined,pendingEdits: {},@@ -63,6 +65,7 @@ export interface IChatState {id: string;name: string;} | ILocalParticipant;+ messageModerationSupported: boolean;messages: IMessage[];notifyPrivateRecipientsChangedTimestamp?: number;pendingEdits: IPendingEditsMap;@@ -202,9 +205,7 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, acif (m.messageId === newMessage.messageId) {messageExists = true;- // SECURITY: participantId must be present AND match the original- // author. A missing participantId must fail closed, not open.- if (newMessage.participantId && m.participantId !== newMessage.participantId) {+ if (!newMessage.participantId || newMessage.participantId !== m.participantId) {return m;}@@ -250,7 +251,6 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, acreturn {...message,isModerated: true,- moderatedBy: action.moderatorId,moderationReason: action.reason};}@@ -284,6 +284,12 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac};}+ case SET_MESSAGE_MODERATION_SUPPORTED:+ return {+ ...state,+ messageModerationSupported: action.supported+ };+case SET_CHAT_SEARCH_MATCH_INDEX:return {...state,diff --git a/react/features/chat/types.ts b/react/features/chat/types.tsindex 7fa5b5a900..3d7bed123a 100644--- a/react/features/chat/types.ts+++ b/react/features/chat/types.ts@@ -29,7 +29,6 @@ export interface IMessage {message: string;messageId: string;messageType: ChatMessageType;- moderatedBy?: string;moderationReason?: string;participantId: string;privateMessage: boolean;diff --git a/resources/prosody-plugins/mod_fmuc.lua b/resources/prosody-plugins/mod_fmuc.luaindex b71a15cad1..37be716c6b 100644--- a/resources/prosody-plugins/mod_fmuc.lua+++ b/resources/prosody-plugins/mod_fmuc.lua@@ -478,6 +478,27 @@ local function message_handler(event)endend+-- Adds a stanza this node has just routed to its own occupants to the local+-- history. Prosody writes room history from broadcast_message, and routing+-- straight to the occupants bypasses it, so without this the history stays as the+-- main prosody left it when this node connected and a visitor joining later sees+-- nothing that was said since. Fire prosody's own events, so the entry is built,+-- stamped and trimmed exactly as it is in the main room and the modules hooked on+-- them apply here too.+local function add_to_local_history(room, stanza)+ local event = { room = room; stanza = stanza; };++ if not module:fire_event('muc-message-is-historic', event) then+ module:log('debug', 'Not storing %s in %s history', stanza.attr.id, room.jid);++ return;+ end++ module:fire_event('muc-add-history', event);+ module:log('debug', 'Stored %s in %s history, %s entries now',+ stanza.attr.id, room.jid, room._history and #room._history or 0);+end+-- Receives history messages from the main prosody and adds them to the local history-- this happens before the first participant joins and that participant gets the history using the standard flow on joinlocal function history_message_handler(event)@@ -583,6 +604,9 @@ module:hook('muc-occupant-groupchat', function(event)main_message.attr.from = room_jid_match_rewrite(stanza.attr.from);module:send(main_message);end++ add_to_local_history(room, stanza);+stanza.attr.from = from; -- something prosody does internallyreturn true;diff --git a/resources/prosody-plugins/mod_muc_message_moderation.lua b/resources/prosody-plugins/mod_muc_message_moderation.luanew file mode 100644index 0000000000..d8760e9963--- /dev/null+++ b/resources/prosody-plugins/mod_muc_message_moderation.lua@@ -0,0 +1,460 @@+-- Server side handling of chat message moderation (XEP-0425) and message+-- correction (XEP-0308) for Jitsi MUC rooms.+--+-- Both operations used to be synchronised client to client over json messages,+-- and late joiners were brought up to date by every participant replaying the+-- current state to them on join. Handling both here keeps the room history+-- itself correct, so a joining client needs no follow up at all.+--+-- 1. Moderation (XEP-0425). An occupant sends:+--+-- <message type='groupchat'>+-- <apply-to xmlns='urn:xmpp:fasten:0' id='ORIG'>+-- <moderated xmlns='urn:xmpp:message-moderate:1'>+-- <retract xmlns='urn:xmpp:message-retract:1'/>+-- <reason>spam</reason>+-- </moderated>+-- </apply-to>+-- </message>+--+-- The request is honoured only when the sending occupant's MUC role is+-- 'moderator'. The room history entry for ORIG is replaced with a tombstone+-- (body stripped, <moderated by='...'><retracted/></moderated> added) so late+-- joiners never receive the moderated text at all, and the moderation is+-- broadcast from the room JID. The occupant's own request is not relayed, the+-- room emits its own stanza and takes 'by' from the sender's occupant JID.+-- A message that has aged out of the history window is still moderated for+-- everyone in the room, there is just no entry left to turn into a tombstone.+-- 'jitsi-message-moderated' is fired alongside the broadcast so mod_visitors+-- can forward it to the visitor nodes, which the room's own broadcast does+-- not reach.+--+-- 2. Correction (XEP-0308). An occupant sends a new body carrying:+--+-- <replace xmlns='urn:xmpp:message-correct:0' id='ORIG'/>+--+-- The request is honoured only when ORIG was authored by the same occupant+-- and has not been moderated; anything else is dropped and reaches nobody.+-- An honoured correction is relayed untouched: it carries the new body and+-- asks to be stored, so the room archives it and replays it after the message+-- it corrects, and a client joining later applies it the same way one in the+-- room does. Nothing here rewrites the history entry.+--+-- 3. Retraction (XEP-0424). The author retracts their own message with a+-- top level:+--+-- <retract xmlns='urn:xmpp:message-retract:1' id='ORIG'/>+--+-- The request is honoured only when ORIG was authored by the same occupant.+-- The history entry is removed outright rather than tombstoned, so a joining+-- client never receives the message at all, and the retraction is not stored+-- either since there is no longer anything for it to pair with. The retraction+-- stanza itself is what reaches the occupants already in the room.+--+-- The moderation the room broadcasts and the retraction are kept out of history:+-- the first is already reflected in the tombstone, and the second removed the+-- entry it referred to.+--+-- Rooms advertise 'muc#roominfo_messageModerationEnabled' so a client can tell+-- whether the server is here to apply these operations, and offer the moderate+-- and edit actions only when it is.+--+-- Needs to be activated under the muc component where message moderation and+-- editing should be handled. Without it the client hides both actions, as the+-- room stops advertising them.+--+-- Load it on a visitor prosody's muc component too. There it keeps the local+-- history in step for the operations that are not replayed on their own, and+-- advertises the room info field so visitors see the same actions. It does not+-- check anything that reached it from the main prosody, which is where the room+-- the occupants act in lives and where every request is checked. It does check+-- the author of a visitor's own request, since that has not been past the main+-- prosody yet at the point this node routes it.+--+-- Component "conference.meet.jitsi" "muc"+-- modules_enabled = { "muc_message_moderation" }+--+-- Copyright (C) 2026-present 8x8, Inc.++local st = require 'util.stanza';+local id = require 'util.id';+local jid = require 'util.jid';+local datetime = require 'util.datetime';++local ends_with = module:require 'util'.ends_with;++-- only the visitor prosody has a main_domain setting+local main_domain = module:get_option_string('main_domain');+local local_domain = module:get_option_string('muc_mapper_domain_base');++local FASTEN_NS = 'urn:xmpp:fasten:0';+local MODERATE_NS = 'urn:xmpp:message-moderate:1';+local RETRACT_NS = 'urn:xmpp:message-retract:1';+local CORRECT_NS = 'urn:xmpp:message-correct:0';+local HINTS_NS = 'urn:xmpp:hints';++-- Returns the id of the message the stanza asks to moderate and the optional+-- reason, or nil when the stanza is not a moderation request.+function parse_moderation_request(stanza)+ local apply_to = stanza:get_child('apply-to', FASTEN_NS);++ if not apply_to or not apply_to.attr.id then+ return nil;+ end++ local moderated = apply_to:get_child('moderated', MODERATE_NS);++ if not moderated or not moderated:get_child('retract', RETRACT_NS) then+ return nil;+ end++ -- 'by' is only meaningful on a stanza a room has sent, where the server+ -- stamped it. On an occupant's own request it is whatever they typed.+ return apply_to.attr.id, moderated:get_child_text('reason'), moderated.attr.by;+end++-- Returns the id of the message the stanza corrects and the new body, or nil+-- when the stanza is not a correction.+function parse_correction(stanza)+ local replace = stanza:get_child('replace', CORRECT_NS);++ if not replace or not replace.attr.id then+ return nil;+ end++ local body = stanza:get_child_text('body');++ if not body then+ return nil;+ end++ return replace.attr.id, body;+end++-- Returns the id of the message the stanza retracts, or nil when the stanza is+-- not a retraction. A moderation request also carries a <retract/>, but nested+-- inside <apply-to><moderated/>, so it is not matched here.+function parse_retraction(stanza)+ local retract = stanza:get_child('retract', RETRACT_NS);++ if not retract or not retract.attr.id then+ return nil;+ end++ return retract.attr.id;+end++-- Finds the room history entry for a message id. Searches newest first, as+-- edits and moderation overwhelmingly target recent messages.+function find_history_entry(room, message_id)+ local history = room._history;++ if not history or not message_id then+ return nil;+ end++ for i = #history, 1, -1 do+ local entry = history[i];++ if entry.stanza and entry.stanza.attr.id == message_id then+ return entry, i;+ end+ end++ return nil;+end++function is_entry_moderated(entry)+ return entry.stanza:get_child('moderated', MODERATE_NS) ~= nil;+end++-- Replaces a history entry with a XEP-0425 tombstone. The body is dropped so+-- the moderated text is never sent to anyone joining later.+function tombstone_entry(entry, by, reason, stamp)+ local tombstone = st.clone(entry.stanza);++ tombstone:remove_children('body');+ tombstone:remove_children('replace', CORRECT_NS);+ -- never nest two moderation markers if the same message is moderated twice+ tombstone:remove_children('moderated', MODERATE_NS);++ local moderated = st.stanza('moderated', { xmlns = MODERATE_NS, by = by })+ :tag('retracted', { xmlns = RETRACT_NS, stamp = stamp }):up();++ if reason and reason ~= '' then+ moderated:tag('reason'):text(reason):up();+ end++ tombstone:add_child(moderated);+ entry.stanza = tombstone;++ return entry;+end++-- The stanza the room sends to announce a moderation. It carries no body, so a+-- client that does not understand it simply ignores it.+function build_moderation_broadcast(room, target_id, by, reason)+ local moderated = st.stanza('moderated', { xmlns = MODERATE_NS, by = by })+ :tag('retract', { xmlns = RETRACT_NS }):up();++ if reason and reason ~= '' then+ moderated:tag('reason'):text(reason):up();+ end++ local broadcast = st.message({ from = room.jid, type = 'groupchat', id = id.medium() })+ :tag('apply-to', { xmlns = FASTEN_NS, id = target_id });++ broadcast:add_child(moderated);+ broadcast:up();+ broadcast:add_child(st.stanza('no-store', { xmlns = HINTS_NS }));++ return broadcast;+end++-- 'occupant' comes from the hook rather than from stanza.attr.from, which still+-- holds the sender's real jid at this point; the room rewrites it to the+-- occupant nick only after the event has run.+function handle_moderation(origin, room, stanza, occupant, target_id, reason)+ if not occupant or occupant.role ~= 'moderator' then+ module:log('warn', 'Rejected moderation of %s from non-moderator %s', target_id, stanza.attr.from);+ origin.send(st.error_reply(stanza, 'auth', 'forbidden', 'Only moderators can moderate messages'));++ return true;+ end++ local entry = find_history_entry(room, target_id);++ -- The message may have aged out of the room's history window. The moderator's+ -- decision still stands for everyone in the room, there is simply no entry+ -- left to turn into a tombstone.+ if entry then+ tombstone_entry(entry, occupant.nick, reason, datetime.datetime());+ end++ local broadcast = build_moderation_broadcast(room, target_id, occupant.nick, reason);++ room:broadcast_message(broadcast);++ -- broadcast_message only reaches occupants of this room. Visitor nodes are+ -- separate prosodies, and the hook that forwards occupant messages to them+ -- never sees this stanza because the room sent it, so announce it for+ -- mod_visitors to fan out.+ module:fire_event('jitsi-message-moderated', { room = room; stanza = broadcast; });++ -- the room has emitted its own stanza, don't relay the occupant's request+ return true;+end++function handle_correction(origin, room, stanza, occupant, target_id, body)+ local entry = find_history_entry(room, target_id);++ -- With no entry the message has aged out of the room's history window, so+ -- there is nothing to rewrite and no author to check it against. Relay it and+ -- let the receiving clients apply it to their own copy.+ if entry then+ if not occupant or entry.stanza.attr.from ~= occupant.nick then+ module:log('warn', 'Rejected correction of %s from %s, authored by %s',+ target_id, occupant and occupant.nick, entry.stanza.attr.from);+ origin.send(st.error_reply(stanza, 'auth', 'forbidden', 'Only the author can correct a message'));++ return true;+ end++ if is_entry_moderated(entry) then+ module:log('debug', 'Rejected correction of moderated message %s', target_id);+ origin.send(st.error_reply(stanza, 'cancel', 'not-allowed', 'Message has been moderated'));++ return true;+ end+ end++ module:log('debug', 'Relaying correction of %s from %s', target_id, occupant and occupant.nick);++ -- fall through. The correction carries the new body and asks to be stored, so+ -- the room archives it and replays it to anyone joining later, in order after+ -- the message it corrects. Nothing here has to rewrite the entry.+end++-- The author retracting their own message. The history entry is dropped, so the+-- message is simply absent for anyone joining later.+function handle_retraction(origin, room, stanza, occupant, target_id)+ local entry, index = find_history_entry(room, target_id);++ -- With no entry the message has aged out of the room's history window, so+ -- there is nothing to remove and no author to check it against.+ if entry then+ if not occupant or entry.stanza.attr.from ~= occupant.nick then+ module:log('warn', 'Rejected retraction of %s from %s, authored by %s',+ target_id, occupant and occupant.nick, entry.stanza.attr.from);+ origin.send(st.error_reply(stanza, 'auth', 'forbidden', 'Only the author can retract a message'));++ return true;+ end++ table.remove(room._history, index);+ end++ -- The message is gone from history, so a stored retraction has nothing left to+ -- pair with. The client asks for it to be stored, override that.+ stanza:remove_children('store', HINTS_NS);+ stanza:add_child(st.stanza('no-store', { xmlns = HINTS_NS }));++ -- fall through, the retraction the client sent is what reaches the occupants+ -- in the room+end++function handle_groupchat(event)+ local origin, room, stanza, occupant = event.origin, event.room, event.stanza, event.occupant;++ if stanza.attr.type ~= 'groupchat' then+ return;+ end++ local moderate_id, reason = parse_moderation_request(stanza);++ if moderate_id then+ return handle_moderation(origin, room, stanza, occupant, moderate_id, reason);+ end++ local correct_id, body = parse_correction(stanza);++ if correct_id then+ return handle_correction(origin, room, stanza, occupant, correct_id, body);+ end++ local retract_id = parse_retraction(stanza);++ if retract_id then+ return handle_retraction(origin, room, stanza, occupant, retract_id);+ end+end++-- Whether this node may apply an operation to its own history entry. A stanza+-- from an occupant of this node is a visitor's own request that the main prosody+-- has not seen yet, so the author is checked against the entry. Anything else+-- arrived from the main prosody, which has already checked it.+function may_apply_locally(entry, occupant)+ if not occupant or jid.host(occupant.bare_jid) ~= local_domain then+ return true;+ end++ return entry.stanza.attr.from == occupant.nick;+end++-- On a visitor node this module only keeps the local history in step. The room+-- that occupants act in lives on the main prosody, which has already checked the+-- role or the authorship, so nothing is checked again here and no reply is sent.+-- Runs above mod_fmuc's hook and falls through, so fmuc still routes the stanza+-- to the local occupants exactly as before.+function handle_main_groupchat(event)+ local room, stanza, occupant = event.room, event.stanza, event.occupant;++ if stanza.attr.type ~= 'groupchat' then+ return;+ end++ -- Editing and retraction already reach the occupants of this node through the+ -- normal forwarding, so only the local history entry needs bringing in line.+ local retract_id = parse_retraction(stanza);++ if retract_id then+ local entry, index = find_history_entry(room, retract_id);++ if entry and may_apply_locally(entry, occupant) then+ module:log('debug', 'Removing retracted %s from %s history', retract_id, room.jid);+ table.remove(room._history, index);+ end++ return;+ end++ -- A moderation is sent by the main room itself, so it never arrives as an+ -- occupant's stanza and nothing else routes it to the occupants here.+ if occupant then+ return;+ end++ local from_host = jid.host(stanza.attr.from or '');++ if not from_host or not ends_with(from_host, main_domain) then+ if parse_moderation_request(stanza) then+ module:log('debug', 'Ignoring moderation from %s, not under %s', stanza.attr.from, main_domain);+ end++ return;+ end++ local moderate_id, reason, by = parse_moderation_request(stanza);++ if moderate_id then+ local entry = find_history_entry(room, moderate_id);++ if entry then+ tombstone_entry(entry, by, reason, datetime.datetime());+ end++ -- Announce it from this room rather than relaying what arrived. The+ -- forwarded stanza was sent by the main room, which is not an occupant+ -- here, so the from it ends up with depends on how the hop rewrites it.+ -- Building it locally means only the addressing had to survive the hop.+ module:log('debug', 'Announcing moderation of %s on %s', moderate_id, room.jid);++ local broadcast = build_moderation_broadcast(room, moderate_id, by, reason);++ -- Route it to the occupants of this node only. The main prosody's+ -- participants are occupants here as well and it has already told them;+ -- this node has no route to them and would only log a routing error.+ for _, o in room:each_occupant() do+ if jid.host(o.bare_jid) == local_domain then+ room:route_to_occupant(o, broadcast);+ end+ end++ return true;+ end+end++-- Belt and braces next to the no-store hint: moderation broadcasts, corrections+-- and retractions are already reflected in the entry for the original message, or+-- in its removal, so they must not be appended to history as messages of their own.+function skip_history(event)+ local stanza = event.stanza;++ if stanza:get_child('apply-to', FASTEN_NS)+ or stanza:get_child('retract', RETRACT_NS) then+ return true;+ end+end++-- Advertised so clients only offer moderating and editing where the server is+-- here to apply them and keep the room history in step.+local message_moderation_field = {+ name = 'muc#roominfo_messageModerationEnabled';+ type = 'boolean';+ label = 'Whether message moderation and editing are handled by the server.';+ value = 1;+};++function add_room_info(event)+ table.insert(event.form, message_moderation_field);+end++module:hook('muc-add-history', skip_history, 10);+module:hook('muc-disco#info', add_room_info);+module:hook('muc-config-form', add_room_info);++if main_domain then+ -- A visitor node only mirrors what the main prosody applied. The checking+ -- handlers are deliberately not registered here: they compare an author+ -- against the local occupant nick, and on a visitor node the history entry+ -- came from the main prosody's snapshot, so the comparison would refuse a+ -- visitor's own edit rather than apply it.+ --+ -- mod_fmuc handles visitor chat at priority 55 and stops there, so run above+ -- it and fall through once the local history has been brought in line.+ module:hook('muc-occupant-groupchat', handle_main_groupchat, 60);+else+ module:hook('muc-occupant-groupchat', handle_groupchat, 10);+end++module:log('info', 'Loaded MUC message moderation and correction for %s', module.host);diff --git a/resources/prosody-plugins/mod_visitors.lua b/resources/prosody-plugins/mod_visitors.luaindex ed537e3dc9..90608d52eb 100644--- a/resources/prosody-plugins/mod_visitors.lua+++ b/resources/prosody-plugins/mod_visitors.lua@@ -370,6 +370,25 @@ process_host_module(main_muc_component_config, function(host_module, host)module:send(fmuc_msg);endend);+ -- forwards a moderation applied by the room to the vnodes. The hook above only+ -- handles messages sent by an occupant; a moderation is sent by the room itself,+ -- so mod_muc_message_moderation announces it here.+ host_module:hook('jitsi-message-moderated', function(event)+ local room, stanza = event.room, event.stanza;++ if not visitors_nodes[room.jid] or not visitors_nodes[room.jid].nodes then+ return;+ end++ for conference_service in pairs(visitors_nodes[room.jid].nodes) do+ local fmuc_msg = st.clone(stanza);+ fmuc_msg.attr.to = jid.join(jid.node(room.jid), conference_service);+ fmuc_msg.attr.from = room_jid_match_rewrite(room.jid);+ module:log('debug', 'Forwarding moderation to %s', fmuc_msg.attr.to);+ module:send(fmuc_msg);+ end+ end);+-- receiving messages from visitor nodes and forward them to local main participants-- and forward them to the rest of visitor nodeshost_module:hook('muc-occupant-groupchat', function(event)diff --git a/tests/prosody/lua/mod_muc_message_moderation_spec.lua b/tests/prosody/lua/mod_muc_message_moderation_spec.luanew file mode 100644index 0000000000..443d9eeb44--- /dev/null+++ b/tests/prosody/lua/mod_muc_message_moderation_spec.lua@@ -0,0 +1,1416 @@+-- Unit tests for mod_muc_message_moderation.lua+-- Run with busted from resources/prosody-plugins/:+-- busted spec/lua/+--+-- Stubs every Prosody dependency so no Prosody installation is needed. The+-- util.stanza stub is a small but faithful implementation of the builder API the+-- module actually uses, so the assertions below inspect real stanza structure.++-- ---------------------------------------------------------------------------+-- Minimal util.stanza implementation+-- ---------------------------------------------------------------------------++local stanza_mt = {}+stanza_mt.__index = stanza_mt++local st = {}++local function new_stanza(name, attrs)+ return setmetatable({+ name = name,+ attr = attrs or {},+ _children = {},+ last_add = {}+ }, stanza_mt)+end++-- current insertion point: innermost open tag, or the stanza itself+function stanza_mt:_cursor()+ return self.last_add[#self.last_add] or self+end++function stanza_mt:tag(name, attrs)+ local child = new_stanza(name, attrs);++ table.insert(self:_cursor()._children, child);+ table.insert(self.last_add, child);++ return self;+end++function stanza_mt:text(t)+ table.insert(self:_cursor()._children, t);++ return self;+end++function stanza_mt:up()+ table.remove(self.last_add);++ return self;+end++function stanza_mt:add_child(child)+ table.insert(self:_cursor()._children, child);++ return self;+end++local function ns_matches(child, ns)+ return ns == nil or child.attr.xmlns == ns;+end++function stanza_mt:get_child(name, ns)+ for _, child in ipairs(self._children) do+ if type(child) == 'table' and child.name == name and ns_matches(child, ns) then+ return child;+ end+ end++ return nil;+end++function stanza_mt:get_text()+ local out = {};++ for _, child in ipairs(self._children) do+ if type(child) == 'string' then+ table.insert(out, child);+ end+ end++ return table.concat(out);+end++function stanza_mt:get_child_text(name, ns)+ local child = self:get_child(name, ns);++ return child and child:get_text() or nil;+end++function stanza_mt:remove_children(name, ns)+ local kept = {};++ for _, child in ipairs(self._children) do+ local drop = type(child) == 'table' and child.name == name and ns_matches(child, ns);++ if not drop then+ table.insert(kept, child);+ end+ end++ self._children = kept;++ return self;+end++-- counts direct children with a given name, for assertions+function stanza_mt:count_children(name)+ local n = 0;++ for _, child in ipairs(self._children) do+ if type(child) == 'table' and child.name == name then+ n = n + 1;+ end+ end++ return n;+end++function st.stanza(name, attrs)+ return new_stanza(name, attrs);+end++function st.message(attrs)+ return new_stanza('message', attrs);+end++function st.clone(s)+ local copy = new_stanza(s.name, {});++ for k, v in pairs(s.attr) do+ copy.attr[k] = v;+ end++ for _, child in ipairs(s._children) do+ if type(child) == 'string' then+ table.insert(copy._children, child);+ else+ table.insert(copy._children, st.clone(child));+ end+ end++ return copy;+end++function st.error_reply(_stanza, error_type, condition, text)+ return { name = 'error_reply', error_type = error_type, condition = condition, text = text };+end++-- ---------------------------------------------------------------------------+-- Package preloads and global stubs, registered before dofile()+-- ---------------------------------------------------------------------------++local FIXED_STAMP = '2026-08-31T12:00:00Z';++package.preload['util.stanza'] = function() return st end+package.preload['util.id'] = function() return { medium = function() return 'generated-id' end } end+package.preload['util.datetime'] = function() return { datetime = function() return FIXED_STAMP end } end++local hooks = {};+local logs = {};+local fired = {};++local MAIN_DOMAIN = 'main.example.com';+local LOCAL_DOMAIN = 'v16.example.com';+local main_domain_option = MAIN_DOMAIN;++local mock_util = {+ ends_with = function(str, ending)+ return ending == '' or str:sub(-#ending) == ending;+ end+};++_G.module = {+ host = 'conference.example.com',+ log = function(_, level, ...)+ table.insert(logs, { level = level, args = { ... } });+ end,+ hook = function(_, name, fn, priority)+ if not hooks[name] then+ hooks[name] = {};+ end+ table.insert(hooks[name], { fn = fn, priority = priority });+ end,+ fire_event = function(_, name, event)+ table.insert(fired, { name = name, event = event });+ end,+ require = function(_, name)+ if name == 'util' then return mock_util end+ return nil;+ end,+ -- loaded in visitor node role first, so handle_main_groupchat has a+ -- main_domain to compare against; reloaded in main role further down+ get_option_string = function(_, key)+ if key == 'main_domain' then return main_domain_option end+ if key == 'muc_mapper_domain_base' then return LOCAL_DOMAIN end+ return nil;+ end+};++package.preload['util.jid'] = function()+ return {+ host = function(j)+ if not j then return nil end+ local without_resource = j:match('^([^/]+)') or j;+ return without_resource:match('@(.+)$');+ end+ };+end++-- ---------------------------------------------------------------------------+-- Load the module under test+-- ---------------------------------------------------------------------------++local ok, err = pcall(dofile, 'mod_muc_message_moderation.lua');++if not ok then+ describe('mod_muc_message_moderation', function()+ it('skipped — failed to load', function()+ pending(tostring(err):match('([^\n]+)') or tostring(err));+ end)+ end)+ return+end++local parse_moderation_request = assert(_G.parse_moderation_request);+local parse_correction = assert(_G.parse_correction);+local find_history_entry = assert(_G.find_history_entry);+local tombstone_entry = assert(_G.tombstone_entry);+local handle_groupchat = assert(_G.handle_groupchat);+local skip_history = assert(_G.skip_history);+local add_room_info = assert(_G.add_room_info);+local handle_main_groupchat = assert(_G.handle_main_groupchat);++local parse_retraction = assert(_G.parse_retraction);++local FASTEN_NS = 'urn:xmpp:fasten:0';+local MODERATE_NS = 'urn:xmpp:message-moderate:1';+local RETRACT_NS = 'urn:xmpp:message-retract:1';+local CORRECT_NS = 'urn:xmpp:message-correct:0';+local HINTS_NS = 'urn:xmpp:hints';++local ROOM_JID = '[email protected]';++-- Actors carry both identities on purpose. 'jid' is the sender's real jid, which+-- is what stanza.attr.from still holds while these hooks run; 'occupant.nick' is+-- the in-room identity the room stamps on history entries. The module must work+-- off the occupant and never off stanza.attr.from.+local MODERATOR = {+ jid = '[email protected]/device1',+ occupant = { nick = ROOM_JID .. '/moderator-nick', role = 'moderator' }+};+local AUTHOR = {+ jid = '[email protected]/device2',+ occupant = { nick = ROOM_JID .. '/author-nick', role = 'participant' }+};+local OTHER = {+ jid = '[email protected]/device3',+ occupant = { nick = ROOM_JID .. '/other-nick', role = 'participant' }+};++-- ---------------------------------------------------------------------------+-- Fixture builders+-- ---------------------------------------------------------------------------++-- A moderation request as lib-jitsi-meet sends it. payload_by sets 'by' on the+-- request, which the module is expected to ignore in favour of the sender.+local function moderation_request(actor, target_id, reason, payload_by)+ local request = st.message({ from = actor.jid, to = ROOM_JID, type = 'groupchat' })+ :tag('apply-to', { xmlns = FASTEN_NS, id = target_id })+ :tag('moderated', { xmlns = MODERATE_NS, by = payload_by })+ :tag('retract', { xmlns = RETRACT_NS }):up();++ if reason then+ request:tag('reason'):text(reason):up();+ end++ return request;+end++local function correction_request(actor, target_id, body)+ return st.message({ from = actor.jid, to = ROOM_JID, type = 'groupchat' })+ :tag('body'):text(body):up()+ :tag('replace', { xmlns = CORRECT_NS, id = target_id }):up();+end++-- A retraction exactly as sendMessageRetraction builds it, fallback body and+-- 'store' hint included.+local function retraction_request(actor, target_id)+ return st.message({ from = actor.jid, to = ROOM_JID, type = 'groupchat' })+ :tag('retract', { xmlns = RETRACT_NS, id = target_id }):up()+ :tag('fallback', { xmlns = 'urn:xmpp:fallback:0', ['for'] = RETRACT_NS }):up()+ :tag('body'):text('I retracted a previous message, but it is unsupported by your client.'):up()+ :tag('store', { xmlns = HINTS_NS }):up();+end++local function history_message(actor, message_id, body)+ local msg = st.message({ from = actor.occupant.nick, to = '', type = 'groupchat', id = message_id });++ msg:add_child(st.stanza('body'):text(body));++ return { stanza = msg, timestamp = 1000 };+end++-- occupants are only needed by the visitor node path, which routes per occupant+-- instead of broadcasting+local function make_room(history, occupants)+ return {+ jid = ROOM_JID,+ _history = history,+ broadcasts = {},+ routed = {},+ broadcast_message = function(self, stanza)+ table.insert(self.broadcasts, stanza);+ end,+ each_occupant = function(self)+ local i = 0;++ return function()+ i = i + 1;++ if (occupants or {})[i] then+ return i, occupants[i];+ end+ end;+ end,+ route_to_occupant = function(self, occupant, stanza)+ table.insert(self.routed, { occupant = occupant, stanza = stanza });+ end+ };+end++local function make_origin()+ local sent = {};++ return {+ sent = sent,+ send = function(stanza)+ table.insert(sent, stanza);+ end+ };+end++-- ---------------------------------------------------------------------------+-- Tests+-- ---------------------------------------------------------------------------++describe('mod_muc_message_moderation', function()++ describe('registration', function()++ it('hooks muc-occupant-groupchat', function()+ assert.is_table(hooks['muc-occupant-groupchat']);+ end)++ it('hooks muc-add-history', function()+ assert.is_table(hooks['muc-add-history']);+ end)++ it('hooks muc-disco#info', function()+ assert.is_table(hooks['muc-disco#info']);+ end)++ it('hooks muc-config-form', function()+ assert.is_table(hooks['muc-config-form']);+ end)++ it('registers only the visitor node hook, above mod_fmuc', function()+ assert.equal(1, #hooks['muc-occupant-groupchat']);+ assert.equal(60, hooks['muc-occupant-groupchat'][1].priority);+ end)++ it('hooks nothing beyond the groupchat handler on a visitor node', function()+ -- the operations arrive as stanzas, so there is no decoded json event+ -- to listen for on either host any more+ assert.is_nil(hooks['jitsi-endpoint-message-received']);+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('capability advertisement', function()++ local function field_named(form, name)+ for _, field in ipairs(form) do+ if field.name == name then+ return field;+ end+ end++ return nil;+ end++ it('adds the room info field to a disco#info form', function()+ local event = { form = {} };++ add_room_info(event);++ local field = field_named(event.form, 'muc#roominfo_messageModerationEnabled');++ assert.is_table(field);+ assert.equal('boolean', field.type);+ assert.equal(1, field.value);+ end)++ it('adds the room info field to the room config form', function()+ local event = { form = {} };++ hooks['muc-config-form'][1].fn(event);++ assert.is_table(field_named(event.form, 'muc#roominfo_messageModerationEnabled'));+ end)++ it('appends to a form that already has fields', function()+ local event = { form = { { name = 'muc#roominfo_visitorsEnabled', value = 1 } } };++ add_room_info(event);++ assert.equal(2, #event.form);+ assert.is_table(field_named(event.form, 'muc#roominfo_visitorsEnabled'));+ assert.is_table(field_named(event.form, 'muc#roominfo_messageModerationEnabled'));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('parse_moderation_request', function()++ it('returns the target id and reason', function()+ local target, reason = parse_moderation_request(moderation_request(MODERATOR, 'msg-1', 'spam'));++ assert.equal('msg-1', target);+ assert.equal('spam', reason);+ end)++ it('returns the target id with no reason', function()+ local target, reason = parse_moderation_request(moderation_request(MODERATOR, 'msg-1', nil));++ assert.equal('msg-1', target);+ assert.is_nil(reason);+ end)++ it('ignores a plain body message', function()+ local msg = st.message({ from = AUTHOR.jid, type = 'groupchat' }):tag('body'):text('hi'):up();++ assert.is_nil(parse_moderation_request(msg));+ end)++ it('ignores apply-to without an id', function()+ local msg = st.message({ from = MODERATOR.jid, type = 'groupchat' })+ :tag('apply-to', { xmlns = FASTEN_NS })+ :tag('moderated', { xmlns = MODERATE_NS })+ :tag('retract', { xmlns = RETRACT_NS }):up();++ assert.is_nil(parse_moderation_request(msg));+ end)++ it('ignores apply-to without a moderated child', function()+ local msg = st.message({ from = MODERATOR.jid, type = 'groupchat' })+ :tag('apply-to', { xmlns = FASTEN_NS, id = 'msg-1' }):up();++ assert.is_nil(parse_moderation_request(msg));+ end)++ it('ignores moderated without a retract child', function()+ local msg = st.message({ from = MODERATOR.jid, type = 'groupchat' })+ :tag('apply-to', { xmlns = FASTEN_NS, id = 'msg-1' })+ :tag('moderated', { xmlns = MODERATE_NS }):up();++ assert.is_nil(parse_moderation_request(msg));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('parse_correction', function()++ it('returns the target id and the new body', function()+ local target, body = parse_correction(correction_request(AUTHOR, 'msg-1', 'corrected'));++ assert.equal('msg-1', target);+ assert.equal('corrected', body);+ end)++ it('ignores a message with no replace element', function()+ local msg = st.message({ from = AUTHOR.jid, type = 'groupchat' }):tag('body'):text('hi'):up();++ assert.is_nil(parse_correction(msg));+ end)++ it('ignores a replace element with no body', function()+ local msg = st.message({ from = AUTHOR.jid, type = 'groupchat' })+ :tag('replace', { xmlns = CORRECT_NS, id = 'msg-1' }):up();++ assert.is_nil(parse_correction(msg));+ end)++ it('ignores a replace element with no id', function()+ local msg = st.message({ from = AUTHOR.jid, type = 'groupchat' })+ :tag('body'):text('hi'):up()+ :tag('replace', { xmlns = CORRECT_NS }):up();++ assert.is_nil(parse_correction(msg));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('find_history_entry', function()++ it('finds an entry by message id', function()+ local wanted = history_message(AUTHOR, 'msg-2', 'two');+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'one'), wanted });++ local entry, index = find_history_entry(room, 'msg-2');++ assert.equal(wanted, entry);+ assert.equal(2, index);+ end)++ it('returns nil for an unknown id', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'one') });++ assert.is_nil(find_history_entry(room, 'nope'));+ end)++ it('returns nil when the room has no history', function()+ assert.is_nil(find_history_entry(make_room(nil), 'msg-1'));+ end)++ it('returns nil for a nil message id', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'one') });++ assert.is_nil(find_history_entry(room, nil));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('moderation role checks', function()++ it('rejects a request from a participant without the moderator role', function()+ for i = #fired, 1, -1 do fired[i] = nil end++ local entry = history_message(AUTHOR, 'msg-1', 'a message');+ local room = make_room({ entry });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = moderation_request(OTHER, 'msg-1', 'no reason given'),+ occupant = OTHER.occupant+ });++ assert.is_true(handled);+ assert.equal(0, #room.broadcasts);+ assert.equal(0, #fired);+ assert.equal(1, #origin.sent);+ assert.equal('auth', origin.sent[1].error_type);+ assert.equal('forbidden', origin.sent[1].condition);+ -- history is left alone, the body survives+ assert.equal('a message', entry.stanza:get_child_text('body'));+ assert.is_nil(entry.stanza:get_child('moderated', MODERATE_NS));+ end)++ it('rejects a request with no occupant on the event', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'hi') });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = moderation_request(OTHER, 'msg-1', nil),+ occupant = nil+ });++ assert.is_true(handled);+ assert.equal('forbidden', origin.sent[1].condition);+ end)++ it('still moderates a message that has aged out of history', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'hi') });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = moderation_request(MODERATOR, 'aged-out', 'off topic'),+ occupant = MODERATOR.occupant+ });++ assert.is_true(handled);+ assert.equal(0, #origin.sent);+ assert.equal(1, #room.broadcasts);+ assert.equal('aged-out', room.broadcasts[1]:get_child('apply-to', FASTEN_NS).attr.id);+ end)++ it('still checks the role for a message that has aged out of history', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'hi') });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = moderation_request(OTHER, 'aged-out', nil),+ occupant = OTHER.occupant+ });++ assert.is_true(handled);+ assert.equal(0, #room.broadcasts);+ assert.equal('forbidden', origin.sent[1].condition);+ end)++ it('moderates when the room has no history at all', function()+ local room = make_room(nil);+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = moderation_request(MODERATOR, 'msg-1', nil),+ occupant = MODERATOR.occupant+ });++ assert.is_true(handled);+ assert.equal(0, #origin.sent);+ assert.equal(1, #room.broadcasts);+ end)++ it('ignores non-groupchat stanzas', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'hi') });+ local request = moderation_request(MODERATOR, 'msg-1', nil);++ request.attr.type = 'chat';++ assert.is_nil(handle_groupchat({+ origin = make_origin(),+ room = room,+ stanza = request,+ occupant = MODERATOR.occupant+ }));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('moderation by a moderator', function()++ local entry, room, origin;++ before_each(function()+ entry = history_message(AUTHOR, 'msg-1', 'a message');+ room = make_room({ entry });+ origin = make_origin();++ for i = #fired, 1, -1 do fired[i] = nil end++ handle_groupchat({+ origin = origin,+ room = room,+ stanza = moderation_request(MODERATOR, 'msg-1', 'off topic'),+ occupant = MODERATOR.occupant+ });+ end)++ it('sends no error', function()+ assert.equal(0, #origin.sent);+ end)++ it('strips the body from the history entry', function()+ assert.is_nil(entry.stanza:get_child('body'));+ end)++ it('keeps the original id and author on the tombstone', function()+ assert.equal('msg-1', entry.stanza.attr.id);+ assert.equal(AUTHOR.occupant.nick, entry.stanza.attr.from);+ end)++ it('marks the history entry as moderated by the sending occupant', function()+ local moderated = entry.stanza:get_child('moderated', MODERATE_NS);++ assert.is_table(moderated);+ assert.equal(MODERATOR.occupant.nick, moderated.attr.by);+ end)++ it('stamps the retraction in the tombstone', function()+ local moderated = entry.stanza:get_child('moderated', MODERATE_NS);+ local retracted = moderated:get_child('retracted', RETRACT_NS);++ assert.is_table(retracted);+ assert.equal(FIXED_STAMP, retracted.attr.stamp);+ end)++ it('records the reason in the tombstone', function()+ local moderated = entry.stanza:get_child('moderated', MODERATE_NS);++ assert.equal('off topic', moderated:get_child_text('reason'));+ end)++ it('broadcasts the moderation from the room jid', function()+ assert.equal(1, #room.broadcasts);+ assert.equal(ROOM_JID, room.broadcasts[1].attr.from);+ assert.equal('groupchat', room.broadcasts[1].attr.type);+ end)++ it('broadcasts an apply-to referencing the moderated message', function()+ local apply_to = room.broadcasts[1]:get_child('apply-to', FASTEN_NS);++ assert.is_table(apply_to);+ assert.equal('msg-1', apply_to.attr.id);+ assert.is_table(apply_to:get_child('moderated', MODERATE_NS));+ end)++ it('marks the broadcast no-store so it never enters history', function()+ assert.is_table(room.broadcasts[1]:get_child('no-store', HINTS_NS));+ end)++ it('announces the moderation for the visitor nodes', function()+ assert.equal(1, #fired);+ assert.equal('jitsi-message-moderated', fired[1].name);+ assert.equal(room, fired[1].event.room);+ end)++ it('announces the same stanza that was broadcast', function()+ assert.equal(room.broadcasts[1], fired[1].event.stanza);+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('moderation attribution', function()++ it('takes by from the occupant, not from the payload', function()+ local entry = history_message(AUTHOR, 'msg-1', 'hi');+ local room = make_room({ entry });++ handle_groupchat({+ origin = make_origin(),+ room = room,+ stanza = moderation_request(MODERATOR, 'msg-1', nil, ROOM_JID .. '/someone-else'),+ occupant = MODERATOR.occupant+ });++ local moderated = room.broadcasts[1]:get_child('apply-to', FASTEN_NS)+ :get_child('moderated', MODERATE_NS);++ assert.equal(MODERATOR.occupant.nick, moderated.attr.by);+ assert.equal(MODERATOR.occupant.nick, entry.stanza:get_child('moderated', MODERATE_NS).attr.by);+ end)++ it('never uses the sender real jid as by', function()+ local entry = history_message(AUTHOR, 'msg-1', 'hi');+ local room = make_room({ entry });++ handle_groupchat({+ origin = make_origin(),+ room = room,+ stanza = moderation_request(MODERATOR, 'msg-1', nil),+ occupant = MODERATOR.occupant+ });++ local moderated = entry.stanza:get_child('moderated', MODERATE_NS);++ assert.are_not.equal(MODERATOR.jid, moderated.attr.by);+ end)++ it('does not nest a second marker when moderated twice', function()+ local entry = history_message(AUTHOR, 'msg-1', 'hi');+ local room = make_room({ entry });++ for _ = 1, 2 do+ handle_groupchat({+ origin = make_origin(),+ room = room,+ stanza = moderation_request(MODERATOR, 'msg-1', 'again'),+ occupant = MODERATOR.occupant+ });+ end++ assert.equal(1, entry.stanza:count_children('moderated'));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('correction author checks', function()++ it('rejects a correction from someone who is not the author', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = correction_request(OTHER, 'msg-1', 'rewritten by someone else'),+ occupant = OTHER.occupant+ });++ assert.is_true(handled);+ assert.equal('auth', origin.sent[1].error_type);+ assert.equal('forbidden', origin.sent[1].condition);+ assert.equal('original', entry.stanza:get_child_text('body'));+ end)++ it('rejects a correction from a moderator who is not the author', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = correction_request(MODERATOR, 'msg-1', 'rewritten by a moderator'),+ occupant = MODERATOR.occupant+ });++ assert.is_true(handled);+ assert.equal('forbidden', origin.sent[1].condition);+ assert.equal('original', entry.stanza:get_child_text('body'));+ end)++ it('rejects a correction with no occupant on the event', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = correction_request(AUTHOR, 'msg-1', 'whatever'),+ occupant = nil+ });++ assert.is_true(handled);+ assert.equal('forbidden', origin.sent[1].condition);+ assert.equal('original', entry.stanza:get_child_text('body'));+ end)++ it('relays a correction of a message that has aged out of history', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });+ local origin = make_origin();+ local request = correction_request(AUTHOR, 'aged-out', 'corrected');++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = request,+ occupant = AUTHOR.occupant+ });++ assert.is_nil(handled);+ assert.equal(0, #origin.sent);+ assert.equal('original', entry.stanza:get_child_text('body'));+ -- archived like any other correction, there is just no entry here to+ -- have checked it against+ assert.is_nil(request:get_child('no-store', HINTS_NS));+ end)++ it('relays a correction when the room has no history at all', function()+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = make_room(nil),+ stanza = correction_request(AUTHOR, 'msg-1', 'corrected'),+ occupant = AUTHOR.occupant+ });++ assert.is_nil(handled);+ assert.equal(0, #origin.sent);+ end)++ it('rejects a correction of a moderated message', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });++ tombstone_entry(entry, MODERATOR.occupant.nick, 'spam', FIXED_STAMP);++ local origin = make_origin();+ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = correction_request(AUTHOR, 'msg-1', 'putting it back'),+ occupant = AUTHOR.occupant+ });++ assert.is_true(handled);+ assert.equal('not-allowed', origin.sent[1].condition);+ assert.is_nil(entry.stanza:get_child('body'));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('correction by the author', function()++ local entry, room, origin, request, handled;++ before_each(function()+ entry = history_message(AUTHOR, 'msg-1', 'original');+ room = make_room({ entry });+ origin = make_origin();+ request = correction_request(AUTHOR, 'msg-1', 'corrected text');++ handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = request,+ occupant = AUTHOR.occupant+ });+ end)++ it('falls through so the room relays and archives it', function()+ assert.is_nil(handled);+ assert.equal(0, #origin.sent);+ end)++ it('relays the correction untouched', function()+ assert.equal('corrected text', request:get_child_text('body'));+ assert.equal('msg-1', request:get_child('replace', CORRECT_NS).attr.id);+ end)++ it('does not keep it out of history', function()+ -- the room archives it and replays it after the message it corrects+ assert.is_nil(request:get_child('no-store', HINTS_NS));+ end)++ it('leaves the history entry for the original alone', function()+ assert.equal('original', entry.stanza:get_child_text('body'));+ assert.equal(1, entry.stanza:count_children('body'));+ assert.equal('msg-1', entry.stanza.attr.id);+ assert.equal(AUTHOR.occupant.nick, entry.stanza.attr.from);+ end)++ it('honours a second correction the same way', function()+ local second = correction_request(AUTHOR, 'msg-1', 'final text');++ local second_handled = handle_groupchat({+ origin = make_origin(),+ room = room,+ stanza = second,+ occupant = AUTHOR.occupant+ });++ assert.is_nil(second_handled);+ assert.equal('final text', second:get_child_text('body'));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('parse_retraction', function()++ it('returns the target id', function()+ assert.equal('msg-1', parse_retraction(retraction_request(AUTHOR, 'msg-1')));+ end)++ it('ignores a plain body message', function()+ local msg = st.message({ from = AUTHOR.jid, type = 'groupchat' }):tag('body'):text('hi'):up();++ assert.is_nil(parse_retraction(msg));+ end)++ it('ignores a retract with no id', function()+ local msg = st.message({ from = AUTHOR.jid, type = 'groupchat' })+ :tag('retract', { xmlns = RETRACT_NS }):up();++ assert.is_nil(parse_retraction(msg));+ end)++ it('does not match the nested retract of a moderation request', function()+ assert.is_nil(parse_retraction(moderation_request(MODERATOR, 'msg-1', 'spam')));+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('retraction', function()++ it('removes the history entry for the author', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });+ local origin = make_origin();+ local request = retraction_request(AUTHOR, 'msg-1');++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = request,+ occupant = AUTHOR.occupant+ });++ assert.is_nil(handled);+ assert.equal(0, #origin.sent);+ assert.equal(0, #room._history);+ end)++ it('removes only the targeted entry', function()+ local keep_before = history_message(AUTHOR, 'msg-1', 'one');+ local target = history_message(AUTHOR, 'msg-2', 'two');+ local keep_after = history_message(OTHER, 'msg-3', 'three');+ local room = make_room({ keep_before, target, keep_after });++ handle_groupchat({+ origin = make_origin(),+ room = room,+ stanza = retraction_request(AUTHOR, 'msg-2'),+ occupant = AUTHOR.occupant+ });++ assert.equal(2, #room._history);+ assert.equal(keep_before, room._history[1]);+ assert.equal(keep_after, room._history[2]);+ end)++ it('replaces the store hint so the retraction is not archived', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'original') });+ local request = retraction_request(AUTHOR, 'msg-1');++ handle_groupchat({+ origin = make_origin(),+ room = room,+ stanza = request,+ occupant = AUTHOR.occupant+ });++ assert.is_nil(request:get_child('store', HINTS_NS));+ assert.is_table(request:get_child('no-store', HINTS_NS));+ end)++ it('rejects a retraction from someone who is not the author', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = retraction_request(OTHER, 'msg-1'),+ occupant = OTHER.occupant+ });++ assert.is_true(handled);+ assert.equal('auth', origin.sent[1].error_type);+ assert.equal('forbidden', origin.sent[1].condition);+ assert.equal(1, #room._history);+ assert.equal('original', entry.stanza:get_child_text('body'));+ end)++ it('rejects a retraction from a moderator who is not the author', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'original') });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = retraction_request(MODERATOR, 'msg-1'),+ occupant = MODERATOR.occupant+ });++ assert.is_true(handled);+ assert.equal('forbidden', origin.sent[1].condition);+ assert.equal(1, #room._history);+ end)++ it('rejects a retraction with no occupant on the event', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'original') });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = retraction_request(AUTHOR, 'msg-1'),+ occupant = nil+ });++ assert.is_true(handled);+ assert.equal('forbidden', origin.sent[1].condition);+ assert.equal(1, #room._history);+ end)++ it('relays a retraction of a message that has aged out of history', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry });+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = room,+ stanza = retraction_request(AUTHOR, 'aged-out'),+ occupant = AUTHOR.occupant+ });++ assert.is_nil(handled);+ assert.equal(0, #origin.sent);+ assert.equal(1, #room._history);+ end)++ it('relays a retraction when the room has no history at all', function()+ local origin = make_origin();++ local handled = handle_groupchat({+ origin = origin,+ room = make_room(nil),+ stanza = retraction_request(AUTHOR, 'msg-1'),+ occupant = AUTHOR.occupant+ });++ assert.is_nil(handled);+ assert.equal(0, #origin.sent);+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('visitor node history', function()++ local MAIN_ROOM_JID = 'room@conference.' .. MAIN_DOMAIN;++ -- a moderation as mod_visitors forwards it: sent by the main room, so no+ -- local occupant, with 'by' already stamped on the main prosody+ local function forwarded_moderation(target_id, reason, by)+ local stanza = st.message({ from = MAIN_ROOM_JID, to = ROOM_JID, type = 'groupchat' })+ :tag('apply-to', { xmlns = FASTEN_NS, id = target_id })+ :tag('moderated', { xmlns = MODERATE_NS, by = by })+ :tag('retract', { xmlns = RETRACT_NS }):up();++ if reason then+ stanza:tag('reason'):text(reason):up();+ end++ return stanza;+ end++ local function forwarded_retraction(target_id, from)+ return st.message({ from = from or ('author@' .. MAIN_DOMAIN .. '/device'),+ to = ROOM_JID, type = 'groupchat' })+ :tag('retract', { xmlns = RETRACT_NS, id = target_id }):up();+ end++ it('tombstones the local entry for a moderation from main', function()+ local entry = history_message(AUTHOR, 'msg-1', 'a message');+ local room = make_room({ entry });++ local handled = handle_main_groupchat({+ room = room,+ stanza = forwarded_moderation('msg-1', 'off topic', MODERATOR.occupant.nick),+ occupant = nil+ });++ -- handled here, this room announces its own stanza instead+ assert.is_true(handled);+ assert.is_nil(entry.stanza:get_child('body'));++ local moderated = entry.stanza:get_child('moderated', MODERATE_NS);++ assert.is_table(moderated);+ assert.equal('off topic', moderated:get_child_text('reason'));+ end)++ it('keeps the attribution stamped by the main prosody', function()+ local entry = history_message(AUTHOR, 'msg-1', 'a message');+ local room = make_room({ entry });++ handle_main_groupchat({+ room = room,+ stanza = forwarded_moderation('msg-1', nil, MODERATOR.occupant.nick),+ occupant = nil+ });++ assert.equal(MODERATOR.occupant.nick,+ entry.stanza:get_child('moderated', MODERATE_NS).attr.by);+ end)++ it('removes the local entry for a retraction from main', function()+ local room = make_room({+ history_message(AUTHOR, 'msg-1', 'one'),+ history_message(AUTHOR, 'msg-2', 'two')+ });++ local handled = handle_main_groupchat({+ room = room,+ stanza = forwarded_retraction('msg-1'),+ occupant = nil+ });++ assert.is_nil(handled);+ assert.equal(1, #room._history);+ assert.equal('msg-2', room._history[1].stanza.attr.id);+ end)++ it('ignores a stanza from a local occupant', function()+ local entry = history_message(AUTHOR, 'msg-1', 'a message');+ local room = make_room({ entry });++ handle_main_groupchat({+ room = room,+ stanza = forwarded_moderation('msg-1', nil, OTHER.occupant.nick),+ occupant = OTHER.occupant+ });++ assert.equal('a message', entry.stanza:get_child_text('body'));+ end)++ it('ignores a stanza that did not come from the main domain', function()+ local entry = history_message(AUTHOR, 'msg-1', 'a message');+ local room = make_room({ entry });++ local stanza = forwarded_moderation('msg-1', nil, OTHER.occupant.nick);++ stanza.attr.from = '[email protected]';++ handle_main_groupchat({ room = room, stanza = stanza, occupant = nil });++ assert.equal('a message', entry.stanza:get_child_text('body'));+ end)++ it('ignores a non-groupchat stanza', function()+ local entry = history_message(AUTHOR, 'msg-1', 'a message');+ local room = make_room({ entry });+ local stanza = forwarded_moderation('msg-1', nil, MODERATOR.occupant.nick);++ stanza.attr.type = 'chat';++ handle_main_groupchat({ room = room, stanza = stanza, occupant = nil });++ assert.equal('a message', entry.stanza:get_child_text('body'));+ end)++ it('ignores an ordinary message from main', function()+ local entry = history_message(AUTHOR, 'msg-1', 'a message');+ local room = make_room({ entry });+ local stanza = st.message({ from = MAIN_ROOM_JID, to = ROOM_JID, type = 'groupchat' })+ :tag('body'):text('hello'):up();++ assert.is_nil(handle_main_groupchat({ room = room, stanza = stanza, occupant = nil }));+ assert.equal('a message', entry.stanza:get_child_text('body'));+ assert.equal(1, #room._history);+ end)++ local VISITOR = { bare_jid = 'visitor@' .. LOCAL_DOMAIN };+ local MAIN_PARTICIPANT = { bare_jid = 'someone@' .. MAIN_DOMAIN };+ local FOCUS = { bare_jid = '[email protected]' };++ -- an occupant of this node, i.e. a visitor, whose request has not been+ -- past the main prosody at the point this node routes it+ local function local_occupant(nick)+ return { bare_jid = 'visitor@' .. LOCAL_DOMAIN, nick = nick };+ end++ -- an occupant that belongs to the main prosody+ local function main_occupant(nick)+ return { bare_jid = 'someone@' .. MAIN_DOMAIN, nick = nick };+ end++ it('routes the moderation to the occupants of this node', function()+ local room = make_room(+ { history_message(AUTHOR, 'msg-1', 'a message') },+ { VISITOR, MAIN_PARTICIPANT, FOCUS });++ handle_main_groupchat({+ room = room,+ stanza = forwarded_moderation('msg-1', 'off topic', MODERATOR.occupant.nick),+ occupant = nil+ });++ assert.equal(1, #room.routed);+ assert.equal(VISITOR, room.routed[1].occupant);++ local stanza = room.routed[1].stanza;++ -- built locally, so it does not depend on the from the hop produced+ assert.equal(ROOM_JID, stanza.attr.from);++ local moderated = stanza:get_child('apply-to', FASTEN_NS)+ :get_child('moderated', MODERATE_NS);++ assert.equal('msg-1', stanza:get_child('apply-to', FASTEN_NS).attr.id);+ assert.equal('off topic', moderated:get_child_text('reason'));+ assert.is_table(stanza:get_child('no-store', HINTS_NS));+ end)++ it('does not route to occupants belonging to another node', function()+ local room = make_room(+ { history_message(AUTHOR, 'msg-1', 'a message') },+ { MAIN_PARTICIPANT, FOCUS });++ handle_main_groupchat({+ room = room,+ stanza = forwarded_moderation('msg-1', nil, MODERATOR.occupant.nick),+ occupant = nil+ });++ -- the main prosody has already told its own, and this node has no+ -- route to them+ assert.equal(0, #room.routed);+ end)++ it('never broadcasts, which would reach the remote occupants', function()+ local room = make_room(+ { history_message(AUTHOR, 'msg-1', 'a message') },+ { VISITOR, MAIN_PARTICIPANT });++ handle_main_groupchat({+ room = room,+ stanza = forwarded_moderation('msg-1', nil, MODERATOR.occupant.nick),+ occupant = nil+ });++ assert.equal(0, #room.broadcasts);+ end)++ it('removes the entry for a retraction forwarded from main', function()+ local room = make_room({+ history_message(AUTHOR, 'msg-1', 'one'),+ history_message(AUTHOR, 'msg-2', 'two')+ }, { VISITOR });++ handle_main_groupchat({+ room = room,+ stanza = forwarded_retraction('msg-1'),+ occupant = main_occupant(ROOM_JID .. '/someone')+ });++ assert.equal(1, #room._history);+ assert.equal('msg-2', room._history[1].stanza.attr.id);+ end)++ it('leaves a correction to be replayed rather than rewriting history', function()+ local entry = history_message(AUTHOR, 'msg-1', 'original');+ local room = make_room({ entry }, { VISITOR });++ local handled = handle_main_groupchat({+ room = room,+ stanza = correction_request(AUTHOR, 'msg-1', 'corrected'),+ occupant = main_occupant(ROOM_JID .. '/someone')+ });++ -- the correction is archived and replayed by the room, so a joining+ -- client applies it after the message it corrects+ assert.is_nil(handled);+ assert.equal('original', entry.stanza:get_child_text('body'));+ end)++ it('refuses a visitor retraction of a message they did not author', function()+ local room = make_room({ history_message(AUTHOR, 'msg-1', 'original') }, { VISITOR });++ handle_main_groupchat({+ room = room,+ stanza = forwarded_retraction('msg-1'),+ occupant = local_occupant(OTHER.occupant.nick)+ });++ assert.equal(1, #room._history);+ end)++ it('announces it even when the message is not in the local history', function()+ local room = make_room(+ { history_message(AUTHOR, 'msg-1', 'a message') },+ { VISITOR });++ local handled = handle_main_groupchat({+ room = room,+ stanza = forwarded_moderation('aged-out', nil, MODERATOR.occupant.nick),+ occupant = nil+ });++ assert.is_true(handled);+ assert.equal(1, #room.routed);+ end)+ end)++ -- -----------------------------------------------------------------------+ describe('skip_history', function()++ it('skips a moderation broadcast', function()+ local msg = st.message({ from = ROOM_JID, type = 'groupchat' })+ :tag('apply-to', { xmlns = FASTEN_NS, id = 'msg-1' }):up();++ assert.is_true(skip_history({ stanza = msg }));+ end)++ it('stores a correction', function()+ -- it carries the new body and is replayed after the message it corrects+ assert.is_nil(skip_history({ stanza = correction_request(AUTHOR, 'msg-1', 'hi') }));+ end)++ it('skips a retraction', function()+ assert.is_true(skip_history({ stanza = retraction_request(AUTHOR, 'msg-1') }));+ end)++ it('stores an ordinary message', function()+ local msg = st.message({ from = AUTHOR.jid, type = 'groupchat' }):tag('body'):text('hi'):up();++ assert.is_nil(skip_history({ stanza = msg }));+ end)+ end)+ -- -----------------------------------------------------------------------+ -- Declared last: it reloads the module in the main prosody role, which+ -- replaces the globals the blocks above exercise.+ describe('registration on the main prosody', function()++ setup(function()+ hooks = {};+ main_domain_option = nil;+ dofile('mod_muc_message_moderation.lua');+ end)++ it('registers the checking handler', function()+ assert.equal(1, #hooks['muc-occupant-groupchat']);+ assert.equal(10, hooks['muc-occupant-groupchat'][1].priority);+ end)++ it('does not register the visitor node handler', function()+ for _, h in ipairs(hooks['muc-occupant-groupchat']) do+ assert.are_not.equal(60, h.priority);+ end+ end)++ it('advertises the room info field either way', function()+ assert.is_table(hooks['muc-disco#info']);+ assert.is_table(hooks['muc-config-form']);+ end)+ end)+end)