Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

feat(chat): add a private chat restriction and keep client messages on MUC routes (#17838)

bgrozev775b6faaf859
diff --git a/.gitignore b/.gitignore
index fbbf67635a..c580515e44 100644
--- a/.gitignore
+++ b/.gitignore
@@ -51,7 +51,9 @@ local.properties
# node.js
#
-node_modules/
+# No trailing slash: the pattern must also match a node_modules symlink, which
+# a git worktree gets when it points at the node_modules of the main checkout.
+node_modules
npm-debug.log
yarn-error.log
diff --git a/doc/debian/jitsi-meet-prosody/prosody.cfg.lua-jvb.example b/doc/debian/jitsi-meet-prosody/prosody.cfg.lua-jvb.example
index 571e250c29..53dea3bd17 100644
--- a/doc/debian/jitsi-meet-prosody/prosody.cfg.lua-jvb.example
+++ b/doc/debian/jitsi-meet-prosody/prosody.cfg.lua-jvb.example
@@ -69,6 +69,10 @@ VirtualHost "jitmeet.example.com"
"conference_duration";
"muc_lobby_rooms";
"muc_breakout_rooms";
+ -- Keeps client messages on the routes that the rooms control: a client
+ -- can address a message to a MUC or to a component, not to the JID of
+ -- an account.
+ "filter_direct_messages";
}
c2s_require_encryption = false
lobby_muc = "lobby.jitmeet.example.com"
diff --git a/lang/main.json b/lang/main.json
index e56c4c0406..2b9ce6ba35 100644
--- a/lang/main.json
+++ b/lang/main.json
@@ -1314,6 +1314,7 @@
"participantKnocking": "Participant entered lobby",
"participantLeft": "Participant Left",
"playSounds": "Play sound on",
+ "privateChatWithPermissions": "Disable private chat for non-moderators",
"reactions": "Meeting reactions",
"sameAsSystem": "Same as system ({{label}})",
"selectAudioOutput": "Audio output",
diff --git a/react/features/base/jwt/constants.ts b/react/features/base/jwt/constants.ts
index e87f550f81..edefa2af15 100644
--- a/react/features/base/jwt/constants.ts
+++ b/react/features/base/jwt/constants.ts
@@ -19,6 +19,7 @@ export const MEET_FEATURES: Record<string, ParticipantFeaturesKey> = {
ROOM: 'room',
SCREEN_SHARING: 'screen-sharing',
SEND_GROUPCHAT: 'send-groupchat',
+ SEND_PRIVATE_MESSAGE: 'send-private-message',
LIST_VISITORS: 'list-visitors',
SIP_INBOUND_CALL: 'sip-inbound-call',
SIP_OUTBOUND_CALL: 'sip-outbound-call',
diff --git a/react/features/base/participants/functions.ts b/react/features/base/participants/functions.ts
index 946f0c5773..33f29ff0d8 100644
--- a/react/features/base/participants/functions.ts
+++ b/react/features/base/participants/functions.ts
@@ -1,7 +1,7 @@
import { getGravatarURL } from '@jitsi/js-utils/avatar';
import { IReduxState, IStore } from '../../app/types';
-import { isVisitorChatParticipant } from '../../chat/functions';
+import { isSendPrivateChatDisabled, isVisitorChatParticipant } from '../../chat/functions';
import { isStageFilmstripAvailable } from '../../filmstrip/functions';
import { isAddPeopleEnabled, isDialOutEnabled } from '../../invite/functions';
import { toggleShareDialog } from '../../share-room/actions';
@@ -788,6 +788,13 @@ export function isPrivateChatEnabled(
return false;
}
+ // The moderator restricted private messages for this room and the local
+ // participant does not hold the permission that lifts the restriction. The
+ // server applies the same check, this only keeps the controls out of the UI.
+ if (isSendPrivateChatDisabled(state)) {
+ return false;
+ }
+
// Check if private chat is disabled globally
if (disablePrivateChat === 'all') {
return false;
diff --git a/react/features/base/participants/types.ts b/react/features/base/participants/types.ts
index a40894fc15..b2a8bda369 100644
--- a/react/features/base/participants/types.ts
+++ b/react/features/base/participants/types.ts
@@ -78,6 +78,7 @@ export interface IParticipantFeatures {
'room'?: boolean | string;
'screen-sharing'?: boolean | string;
'send-groupchat'?: boolean | string;
+ 'send-private-message'?: boolean | string;
'sip-inbound-call'?: boolean | string;
'sip-outbound-call'?: boolean | string;
'transcription'?: boolean | string;
diff --git a/react/features/chat/components/native/ChatInputBar.tsx b/react/features/chat/components/native/ChatInputBar.tsx
index 08e0d22bdf..41308cbbb7 100644
--- a/react/features/chat/components/native/ChatInputBar.tsx
+++ b/react/features/chat/components/native/ChatInputBar.tsx
@@ -10,7 +10,7 @@ import { IconSend } from '../../../base/icons/svg';
import IconButton from '../../../base/ui/components/native/IconButton';
import Input from '../../../base/ui/components/native/Input';
import { BUTTON_TYPES } from '../../../base/ui/constants.native';
-import { isSendGroupChatDisabled } from '../../functions';
+import { isSendGroupChatDisabled, isSendPrivateChatDisabled } from '../../functions';
import styles from './styles';
@@ -21,6 +21,11 @@ interface IProps extends WithTranslation {
*/
_isSendGroupChatDisabled: boolean;
+ /**
+ * Whether the local participant is not allowed to send private messages.
+ */
+ _isSendPrivateChatDisabled: boolean;
+
/**
* The id of the message recipient, if any.
*/
@@ -55,6 +60,21 @@ interface IState {
showSend: boolean;
}
+/**
+ * Returns whether the local participant cannot send what this input would send:
+ * a private message when a recipient is selected, a group message if not.
+ *
+ * @param {IProps} props - The props of the component.
+ * @returns {boolean}
+ */
+function _isSendDisabled({
+ _isSendGroupChatDisabled,
+ _isSendPrivateChatDisabled,
+ _privateMessageRecipientId
+}: IProps): boolean {
+ return _privateMessageRecipientId ? _isSendPrivateChatDisabled : _isSendGroupChatDisabled;
+}
+
/**
* Implements the chat input bar with text field and action(s).
*/
@@ -84,7 +104,7 @@ class ChatInputBar extends Component<IProps, IState> {
* @inheritdoc
*/
override render() {
- if (this.props._isSendGroupChatDisabled && !this.props._privateMessageRecipientId) {
+ if (_isSendDisabled(this.props)) {
return (
<View
id = 'no-messages-message'
@@ -159,13 +179,9 @@ class ChatInputBar extends Component<IProps, IState> {
* @returns {void}
*/
_onSubmit() {
- const {
- _isSendGroupChatDisabled,
- _privateMessageRecipientId,
- onSend
- } = this.props;
+ const { onSend } = this.props;
- if (_isSendGroupChatDisabled && !_privateMessageRecipientId) {
+ if (_isSendDisabled(this.props)) {
return;
}
@@ -189,10 +205,10 @@ class ChatInputBar extends Component<IProps, IState> {
function _mapStateToProps(state: IReduxState) {
const { aspectRatio } = state['features/base/responsive-ui'];
const { privateMessageRecipient } = state['features/chat'];
- const isGroupChatDisabled = isSendGroupChatDisabled(state);
return {
- _isSendGroupChatDisabled: isGroupChatDisabled,
+ _isSendGroupChatDisabled: isSendGroupChatDisabled(state),
+ _isSendPrivateChatDisabled: isSendPrivateChatDisabled(state),
_privateMessageRecipientId: privateMessageRecipient?.id,
aspectRatio
};
diff --git a/react/features/chat/components/web/ChatInput.tsx b/react/features/chat/components/web/ChatInput.tsx
index 2ecde32e6b..51f5216fad 100644
--- a/react/features/chat/components/web/ChatInput.tsx
+++ b/react/features/chat/components/web/ChatInput.tsx
@@ -11,7 +11,7 @@ import { IconFaceSmile, IconSend } from '../../../base/icons/svg';
import Button from '../../../base/ui/components/web/Button';
import Input from '../../../base/ui/components/web/Input';
import { CHAR_LIMIT, CHAT_SIZE } from '../../constants';
-import { areSmileysDisabled, isSendGroupChatDisabled } from '../../functions';
+import { areSmileysDisabled, isSendGroupChatDisabled, isSendPrivateChatDisabled } from '../../functions';
import { IMessage } from '../../types';
import SmileysPanel from './SmileysPanel';
@@ -64,6 +64,11 @@ interface IProps extends WithTranslation {
*/
_isSendGroupChatDisabled: boolean;
+ /**
+ * Whether the local participant is not allowed to send private messages.
+ */
+ _isSendPrivateChatDisabled: boolean;
+
/**
* The id of the message recipient, if any.
*/
@@ -111,6 +116,21 @@ interface IState {
showSmileysPanel: boolean;
}
+/**
+ * Returns whether the local participant cannot send what this input would send:
+ * a private message when a recipient is selected, a group message if not.
+ *
+ * @param {IProps} props - The props of the component.
+ * @returns {boolean}
+ */
+function _isSendDisabled({
+ _isSendGroupChatDisabled,
+ _isSendPrivateChatDisabled,
+ _privateMessageRecipientId
+}: IProps): boolean {
+ return _privateMessageRecipientId ? _isSendPrivateChatDisabled : _isSendGroupChatDisabled;
+}
+
/**
* Implements a React Component for drafting and submitting a chat message.
*
@@ -182,7 +202,7 @@ class ChatInput extends Component<IProps, IState> {
*/
override render() {
const classes = withStyles.getClasses(this.props);
- const hideInput = this.props._isSendGroupChatDisabled && !this.props._privateMessageRecipientId;
+ const hideInput = _isSendDisabled(this.props);
if (hideInput) {
return (
@@ -244,13 +264,9 @@ class ChatInput extends Component<IProps, IState> {
* @returns {void}
*/
_onSubmitMessage() {
- const {
- _isSendGroupChatDisabled,
- _privateMessageRecipientId,
- onSend
- } = this.props;
+ const { onSend } = this.props;
- if (_isSendGroupChatDisabled && !_privateMessageRecipientId) {
+ if (_isSendDisabled(this.props)) {
return;
}
@@ -370,12 +386,12 @@ class ChatInput extends Component<IProps, IState> {
*/
const mapStateToProps = (state: IReduxState) => {
const { privateMessageRecipient, width } = state['features/chat'];
- const isGroupChatDisabled = isSendGroupChatDisabled(state);
return {
_areSmileysDisabled: areSmileysDisabled(state),
_privateMessageRecipientId: privateMessageRecipient?.id,
- _isSendGroupChatDisabled: isGroupChatDisabled,
+ _isSendGroupChatDisabled: isSendGroupChatDisabled(state),
+ _isSendPrivateChatDisabled: isSendPrivateChatDisabled(state),
_chatWidth: width.current ?? CHAT_SIZE,
};
};
diff --git a/react/features/chat/functions.ts b/react/features/chat/functions.ts
index 095d9accf4..b3de27b6c9 100644
--- a/react/features/chat/functions.ts
+++ b/react/features/chat/functions.ts
@@ -337,6 +337,38 @@ export function isSendGroupChatDisabled(state: IReduxState): boolean {
return !isJwtFeatureEnabled(state, MEET_FEATURES.SEND_GROUPCHAT, false);
}
+/**
+ * Returns whether the room restricts group chat to the participants that hold
+ * the permission for it.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {boolean}
+ */
+export function isGroupChatRestricted(state: IReduxState): boolean {
+ return Boolean(state['features/chat'].groupChatWithPermissions);
+}
+
+/**
+ * Check if participant is not allowed to send private messages.
+ *
+ * Unlike the group chat check above, this reads the restriction from the room
+ * metadata, which is what a moderator toggles at runtime. The server applies the
+ * same check in mod_filter_messages, and pushes the permissions of a participant
+ * that it promotes to moderator, so this selector follows a promotion.
+ *
+ * @param {IReduxState} state - The redux state.
+ * @returns {boolean} - Returns true if the participant is not allowed to send private messages.
+ */
+export function isSendPrivateChatDisabled(state: IReduxState): boolean {
+ const { privateChatWithPermissions } = state['features/chat'];
+
+ if (!privateChatWithPermissions) {
+ return false;
+ }
+
+ return !isJwtFeatureEnabled(state, MEET_FEATURES.SEND_PRIVATE_MESSAGE, false);
+}
+
/**
* Calculates the maximum width available for the chat panel based on the current window size
* and other UI elements.
diff --git a/react/features/chat/middleware.ts b/react/features/chat/middleware.ts
index 229685e350..e421de0730 100644
--- a/react/features/chat/middleware.ts
+++ b/react/features/chat/middleware.ts
@@ -83,7 +83,9 @@ import {
getFocusedTab,
getUnreadCount,
isChatDisabled,
+ isGroupChatRestricted,
isSendGroupChatDisabled,
+ isSendPrivateChatDisabled,
isVisitorChatParticipant
} from './functions';
import logger from './logger';
@@ -189,6 +191,18 @@ MiddlewareRegistry.register(store => next => action => {
store.dispatch(pushReactions(reactions));
+ // A bridge channel message does not go through the MUC, thus the
+ // server does not apply the chat restrictions of the room to it.
+ // Apply the group chat restriction here, otherwise a reaction shows
+ // in the chat of every participant while chat is restricted. The
+ // permissions of a remote participant are not known locally, thus
+ // this uses the moderator role, which is what the server gives the
+ // permissions to. The reaction itself still plays: on-screen
+ // reactions have their own moderation.
+ if (isGroupChatRestricted(state) && !participant?.isModerator?.()) {
+ break;
+ }
+
_handleReceivedMessage(store, {
participantId: participant.getId(),
message: getReactionMessageFromBuffer(reactions),
@@ -242,6 +256,7 @@ MiddlewareRegistry.register(store => next => action => {
if (
isSendGroupChatDisabled(state)
+ && !isSendPrivateChatDisabled(state)
&& privateMessageRecipient
&& !action.participant
) {
@@ -596,7 +611,12 @@ function _addChatMsgListener(conference: IJitsiConference, store: IStore) {
privateMessage: false
});
- if (isSendGroupChatDisabled(store.getState()) && participantId) {
+ // Group chat is restricted for this participant, so steer the reply
+ // into a private message. Not when private messages are restricted
+ // too: that would move them into a chat they cannot send in either.
+ if (isSendGroupChatDisabled(store.getState())
+ && !isSendPrivateChatDisabled(store.getState())
+ && participantId) {
const participant = getParticipantById(store, participantId);
store.dispatch(setPrivateMessageRecipient(participant));
diff --git a/react/features/chat/reducer.ts b/react/features/chat/reducer.ts
index 1729f1095a..b0821ad2a8 100644
--- a/react/features/chat/reducer.ts
+++ b/react/features/chat/reducer.ts
@@ -33,6 +33,7 @@ import { IMessage, IPendingEditsMap } from './types';
const DEFAULT_STATE = {
groupChatWithPermissions: false,
+ privateChatWithPermissions: false,
isOpen: false,
messageModerationSupported: false,
messages: [],
@@ -69,6 +70,7 @@ export interface IChatState {
messages: IMessage[];
notifyPrivateRecipientsChangedTimestamp?: number;
pendingEdits: IPendingEditsMap;
+ privateChatWithPermissions: boolean;
privateMessageRecipient?: IParticipant | IVisitorChatParticipant;
searchMatchIndex: number;
searchQuery: string;
@@ -364,7 +366,8 @@ ReducerRegistry.register<IChatState>('features/chat', (state = DEFAULT_STATE, ac
if (metadata?.permissions) {
return {
...state,
- groupChatWithPermissions: Boolean(metadata.permissions.groupChatRestricted)
+ groupChatWithPermissions: Boolean(metadata.permissions.groupChatRestricted),
+ privateChatWithPermissions: Boolean(metadata.permissions.privateChatRestricted)
};
}
diff --git a/react/features/settings/actions.web.ts b/react/features/settings/actions.web.ts
index cf87a0deb6..018b4c3d82 100644
--- a/react/features/settings/actions.web.ts
+++ b/react/features/settings/actions.web.ts
@@ -203,14 +203,16 @@ export function submitModeratorTab(newState: any) {
newState.startAudioMuted, newState.startVideoMuted));
}
- if (newState.chatWithPermissionsEnabled !== currentState.chatWithPermissionsEnabled) {
+ if (newState.chatWithPermissionsEnabled !== currentState.chatWithPermissionsEnabled
+ || newState.privateChatWithPermissionsEnabled !== currentState.privateChatWithPermissionsEnabled) {
const { conference } = getState()['features/base/conference'];
const currentPermissions = conference?.getMetadataHandler().getMetadata().permissions || {};
conference?.getMetadataHandler().setMetadata('permissions', {
...currentPermissions,
- groupChatRestricted: newState.chatWithPermissionsEnabled
+ groupChatRestricted: newState.chatWithPermissionsEnabled,
+ privateChatRestricted: newState.privateChatWithPermissionsEnabled
});
}
diff --git a/react/features/settings/components/native/ModeratorSection.tsx b/react/features/settings/components/native/ModeratorSection.tsx
index f8c8e7217d..d66c825472 100644
--- a/react/features/settings/components/native/ModeratorSection.tsx
+++ b/react/features/settings/components/native/ModeratorSection.tsx
@@ -19,6 +19,7 @@ const ModeratorSection = () => {
const {
audioModerationEnabled,
chatWithPermissionsEnabled,
+ privateChatWithPermissionsEnabled,
followMeActive,
followMeEnabled,
followMeRecorderActive,
@@ -64,6 +65,15 @@ const ModeratorSection = () => {
});
}, [ dispatch, conference ]);
+ const onPrivateChatWithPermissionsToggled = useCallback((enabled?: boolean) => {
+ const currentPermissions = conference?.getMetadataHandler().getMetadata().permissions || {};
+
+ conference?.getMetadataHandler().setMetadata('permissions', {
+ ...currentPermissions,
+ privateChatRestricted: enabled
+ });
+ }, [ dispatch, conference ]);
+
const followMeRecorderChecked = followMeRecorderEnabled && !followMeRecorderActive;
const moderationSettings = useMemo(() => {
@@ -103,10 +113,17 @@ const ModeratorSection = () => {
state: chatWithPermissionsEnabled,
onChange: onChatWithPermissionsToggled
},
+ {
+ label: 'settings.privateChatWithPermissions',
+ state: privateChatWithPermissionsEnabled,
+ onChange: onPrivateChatWithPermissionsToggled
+ },
];
if (disableReactionsModeration) {
- moderation.pop();
+ // Remove the reactions entry by name. A pop() here took out whichever
+ // entry came last, which is not the reactions one.
+ return moderation.filter(({ label }) => label !== 'settings.startReactionsMuted');
}
return moderation;
@@ -120,6 +137,10 @@ const ModeratorSection = () => {
onFollowMeToggled,
onFollowMeRecorderToggled,
onStartReactionsMutedToggled,
+ onChatWithPermissionsToggled,
+ onPrivateChatWithPermissionsToggled,
+ chatWithPermissionsEnabled,
+ privateChatWithPermissionsEnabled,
startReactionsMuted ]);
return (
diff --git a/react/features/settings/components/web/ModeratorTab.tsx b/react/features/settings/components/web/ModeratorTab.tsx
index a7152d1f3f..c17094df7f 100644
--- a/react/features/settings/components/web/ModeratorTab.tsx
+++ b/react/features/settings/components/web/ModeratorTab.tsx
@@ -62,6 +62,11 @@ export interface IProps extends AbstractDialogTabProps, WithTranslation {
*/
hideChatWithPermissions: boolean;
+ /**
+ * Whether the user has selected the private chat with permissions feature to be enabled.
+ */
+ privateChatWithPermissionsEnabled: boolean;
+
/**
* Whether the audio-translation room toggle should be shown (i.e. the feature is deployed).
*/
@@ -132,6 +137,7 @@ class ModeratorTab extends AbstractDialogTab<IProps, any> {
this._onFollowMeEnabledChanged = this._onFollowMeEnabledChanged.bind(this);
this._onFollowMeRecorderEnabledChanged = this._onFollowMeRecorderEnabledChanged.bind(this);
this._onChatWithPermissionsChanged = this._onChatWithPermissionsChanged.bind(this);
+ this._onPrivateChatWithPermissionsChanged = this._onPrivateChatWithPermissionsChanged.bind(this);
this._onAudioTranslationEnabledChanged = this._onAudioTranslationEnabledChanged.bind(this);
}
@@ -222,6 +228,17 @@ class ModeratorTab extends AbstractDialogTab<IProps, any> {
super._onChange({ chatWithPermissionsEnabled: checked });
}
+ /**
+ * Callback invoked to select if private chat with permissions should be activated.
+ *
+ * @param {Object} e - The key event to handle.
+ *
+ * @returns {void}
+ */
+ _onPrivateChatWithPermissionsChanged({ target: { checked } }: React.ChangeEvent<HTMLInputElement>) {
+ super._onChange({ privateChatWithPermissionsEnabled: checked });
+ }
+
/**
* Implements React's {@link Component#render()}.
*
@@ -239,6 +256,7 @@ class ModeratorTab extends AbstractDialogTab<IProps, any> {
followMeRecorderActive,
followMeRecorderEnabled,
hideChatWithPermissions,
+ privateChatWithPermissionsEnabled,
showAudioTranslation,
startAudioMuted,
startVideoMuted,
@@ -297,6 +315,13 @@ class ModeratorTab extends AbstractDialogTab<IProps, any> {
label = { t('settings.chatWithPermissions') }
name = 'chat-with-permissions'
onChange = { this._onChatWithPermissionsChanged } /> }
+ { !hideChatWithPermissions
+ && <Checkbox
+ checked = { privateChatWithPermissionsEnabled }
+ className = { classes.checkbox }
+ label = { t('settings.privateChatWithPermissions') }
+ name = 'private-chat-with-permissions'
+ onChange = { this._onPrivateChatWithPermissionsChanged } /> }
{ showAudioTranslation
&& <Checkbox
checked = { audioTranslationEnabled }
diff --git a/react/features/settings/components/web/SettingsDialog.tsx b/react/features/settings/components/web/SettingsDialog.tsx
index 0021dde630..4b3daa6a0d 100644
--- a/react/features/settings/components/web/SettingsDialog.tsx
+++ b/react/features/settings/components/web/SettingsDialog.tsx
@@ -256,6 +256,7 @@ function _mapStateToProps(state: IReduxState, ownProps: any) {
...newProps,
audioTranslationEnabled: tabState?.audioTranslationEnabled,
chatWithPermissionsEnabled: tabState?.chatWithPermissionsEnabled,
+ privateChatWithPermissionsEnabled: tabState?.privateChatWithPermissionsEnabled,
followMeEnabled: tabState?.followMeEnabled,
followMeRecorderEnabled: tabState?.followMeRecorderEnabled,
startAudioMuted: tabState?.startAudioMuted,
diff --git a/react/features/settings/functions.any.ts b/react/features/settings/functions.any.ts
index c08e909aaa..89edcf60e1 100644
--- a/react/features/settings/functions.any.ts
+++ b/react/features/settings/functions.any.ts
@@ -161,7 +161,7 @@ export function getModeratorTabProps(stateful: IStateful) {
startReactionsMuted
} = state['features/base/conference'];
const { followMeEnabled, followMeRecorderEnabled } = state['features/follow-me'];
- const { groupChatWithPermissions } = state['features/chat'];
+ const { groupChatWithPermissions, privateChatWithPermissions } = state['features/chat'];
const {
audioTranslation,
showChatPermissionsModeratorSetting,
@@ -182,6 +182,7 @@ export function getModeratorTabProps(stateful: IStateful) {
showAudioTranslation: Boolean(audioTranslation?.enabled),
videoModerationEnabled: isVideoModerationEnabled,
chatWithPermissionsEnabled: Boolean(groupChatWithPermissions),
+ privateChatWithPermissionsEnabled: Boolean(privateChatWithPermissions),
showModeratorSettings: Boolean(conference && showModeratorSettings),
disableReactionsModeration: Boolean(disableReactionsModeration),
followMeActive: Boolean(conference && followMeActive),
diff --git a/resources/prosody-plugins/mod_filter_direct_messages.lua b/resources/prosody-plugins/mod_filter_direct_messages.lua
new file mode 100644
index 0000000000..01f5b1fb39
--- /dev/null
+++ b/resources/prosody-plugins/mod_filter_direct_messages.lua
@@ -0,0 +1,99 @@
+-- Blocks a message that a client addresses to the JID of an account.
+--
+-- A Jitsi client addresses a message to a MUC (the room JID for group chat, an
+-- occupant JID for a private message) or to one of the Jitsi components. It
+-- never addresses a message to the JID of an account. The MUC applies the
+-- access rules of the room: it refuses a message from a client that is not an
+-- occupant, and mod_filter_messages applies the chat restrictions of the room.
+--
+-- A message that goes to the JID of an account uses none of that. It goes
+-- directly from one client to the other, thus the state of the room has no
+-- effect on it. This module rejects such a message with a <not-allowed/>
+-- error, so that client messages keep to the routes that the rooms control.
+--
+-- Permitted destinations:
+-- * a JID with no node part (a host or a component)
+-- * a local component, which includes each MUC component and the Jitsi
+-- components (metadata, polls, filesharing, ...)
+-- * a host that starts with the MUC prefix, for example
+-- conference.v1.example.com. A participant of the main room replies to a
+-- visitor at the occupant JID of the visitor on the visitor node, which is
+-- a MUC on a different server.
+--
+-- Everything else is rejected.
+--
+-- The check applies to client (c2s) sessions only. It uses pre-message/bare and
+-- pre-message/full, which Prosody fires on the host of the sender, and only for
+-- a client connection. Messages from a component or from a server-to-server
+-- connection do not go through it, thus error replies and the routing that the
+-- visitors module does are not affected.
+--
+-- Load on each VirtualHost that clients connect to, the visitor node included.
+local jid_split = require 'util.jid'.split;
+local st = require 'util.stanza';
+
+local util = module:require 'util';
+local is_admin = util.is_admin;
+
+local hosts = prosody.hosts;
+
+local muc_domain_prefix = module:get_option_string('muc_mapper_domain_prefix', 'conference');
+
+-- Returns true when a client is allowed to address a message to this JID.
+local function is_allowed_destination(to)
+ if not to then
+ -- No destination means the message goes to the account of the sender.
+ return true;
+ end
+
+ local node, host = jid_split(to);
+
+ if not node then
+ -- A host or a component, for example metadata.example.com.
+ return true;
+ end
+
+ if not host then
+ return false;
+ end
+
+ local target_host = hosts[host];
+
+ if target_host and target_host.type == 'component' then
+ -- A local component. Each MUC component is one of these.
+ return true;
+ end
+
+ -- A MUC on another server. A participant of the main room uses this to
+ -- answer a visitor, whose occupant JID is on the visitor node.
+ if host:sub(1, #muc_domain_prefix + 1) == muc_domain_prefix .. '.' then
+ return true;
+ end
+
+ return false;
+end
+
+local function on_message(event)
+ local stanza, session = event.stanza, event.origin;
+
+ if is_allowed_destination(stanza.attr.to) then
+ return;
+ end
+
+ -- jicofo and the other internal clients are admins. They do not send this
+ -- kind of message, but do not change what they can do.
+ if session.full_jid and is_admin(session.full_jid) then
+ return;
+ end
+
+ module:log('debug', 'Blocked message from %s to %s', stanza.attr.from or session.full_jid, stanza.attr.to);
+
+ if stanza.attr.type ~= 'error' then
+ session.send(st.error_reply(stanza, 'cancel', 'not-allowed', 'Messages to this address are not allowed'));
+ end
+
+ return true;
+end
+
+module:hook('pre-message/bare', on_message);
+module:hook('pre-message/full', on_message);
diff --git a/resources/prosody-plugins/mod_filter_messages.lua b/resources/prosody-plugins/mod_filter_messages.lua
index 2c539cdaea..60de0b771a 100644
--- a/resources/prosody-plugins/mod_filter_messages.lua
+++ b/resources/prosody-plugins/mod_filter_messages.lua
@@ -1,29 +1,66 @@
--- Filters MUC group-chat messages when the room operator has restricted chat.
+-- Filters MUC messages when the room operator has restricted chat.
--
--- When room.jitsiMetadata.permissions.groupChatRestricted is true, a sender
--- must have the 'send-groupchat' feature set to true in their JWT context
--- (session.jitsi_meet_context_features) to send a message. Any message that
--- fails this check is rejected with a <not-allowed/> error stanza.
+-- Two independent restrictions live in the room metadata:
+--
+-- permissions.groupChatRestricted — group-chat messages, addressed to the
+-- bare room JID
+-- permissions.privateChatRestricted — private messages, addressed to an
+-- occupant JID (room@muc/nick)
+--
+-- When a restriction is on, a sender must have the matching feature set to true
+-- in their JWT context (session.jitsi_meet_context_features) to send a message.
+-- Any message that fails the check is rejected with a <not-allowed/> error
+-- stanza.
+--
+-- groupChatRestricted → send-groupchat
+-- privateChatRestricted → send-private-message
--
-- Feature evaluation via is_feature_allowed:
--- send-groupchat = true in token features → allowed
--- send-groupchat = false in token features → blocked
+-- feature = true in token features → allowed
+-- feature = false in token features → blocked
-- feature key absent from token features → blocked
-- no token features at all (anonymous) → blocked
--
-- Messages without a <body> (polls, lobby notifications, etc.) are always
--- passed through regardless of the restriction flag.
+-- passed through regardless of the restriction flags.
--
-- Hooks:
--- message/bare — ordinary MUC group-chat messages
--- jitsi-visitor-groupchat-pre-route — visitor messages routed via the
--- visitors component
+-- message/bare — ordinary MUC group-chat messages
+-- jitsi-visitor-groupchat-pre-route — visitor group-chat messages, routed
+-- via the visitors component
+-- muc-private-message — MUC private messages
+-- jitsi-visitor-private-message-pre-route — visitor private messages, routed
+-- via the visitors component
+--
+-- A message that is addressed to the real JID of a participant
+-- (user@domain/resource) does not go to the MUC component, thus no hook here
+-- sees it.
--
-- Load on the MUC component.
local util = module:require 'util';
local get_room_from_jid = util.get_room_from_jid;
+local jid_bare = require 'util.jid'.bare;
local st = require 'util.stanza';
+-- Returns true when the room restricts this kind of message and the sender does
+-- not have the feature that lifts the restriction.
+local function is_blocked(room, session, restriction, feature)
+ return room.jitsiMetadata and room.jitsiMetadata.permissions
+ and room.jitsiMetadata.permissions[restriction]
+ and not is_feature_allowed(feature, session.jitsi_meet_context_features);
+end
+
+-- Sends the rejection for a message that this module filters. The module routes
+-- the reply, thus it also goes to a visitor node over s2s.
+local function reject(stanza, session, text)
+ local reply = st.error_reply(stanza, 'cancel', 'not-allowed', text);
+
+ if session.type == 's2sin' or session.type == 's2sout' then
+ reply.skipMapping = true;
+ end
+ module:send(reply);
+end
+
local function on_message(event)
local stanza = event.stanza;
local body = stanza:get_child('body');
@@ -42,20 +79,65 @@ local function on_message(event)
return;
end
- if room.jitsiMetadata and room.jitsiMetadata.permissions
- and room.jitsiMetadata.permissions.groupChatRestricted
- and not is_feature_allowed('send-groupchat', session.jitsi_meet_context_features) then
+ if is_blocked(room, session, 'groupChatRestricted', 'send-groupchat') then
+ reject(stanza, session, 'Sending group messages not allowed');
+
+ -- let's filter this message
+ return true;
+ end
+end
+
+-- Private messages that a visitor node forwards to a main participant. The
+-- visitors module routes these to the occupant itself, thus muc-private-message
+-- does not fire for them. Returning true filters the message, the same as
+-- jitsi-visitor-groupchat-pre-route does.
+local function on_visitor_private_message(event)
+ local stanza = event.stanza;
+ local body = stanza:get_child('body');
+ local session = event.origin;
+
+ if not body or not session then
+ return;
+ end
+
+ -- The stanza is addressed to an occupant JID (room@muc/nick).
+ local room = get_room_from_jid(jid_bare(stanza.attr.to));
+ if not room then
+ module:log('warn', 'No room found for %s', stanza.attr.to);
+ return;
+ end
+
+ if is_blocked(room, session, 'privateChatRestricted', 'send-private-message') then
+ reject(stanza, session, 'Sending private messages not allowed');
+
+ return true;
+ end
+end
+
+-- The MUC fires this for a private message, after it made sure that the sender
+-- is an occupant of the room and that the recipient is in the room. Returning
+-- false stops the routing. The MUC sends no error of its own in that case, thus
+-- this function sends it.
+local function on_private_message(event)
+ local stanza, session, room = event.stanza, event.origin, event.room;
+ local body = stanza:get_child('body');
+
+ if not body or not session or not room then
+ return;
+ end
- local reply = st.error_reply(stanza, 'cancel', 'not-allowed', 'Sending group messages not allowed');
- if session.type == 's2sin' or session.type == 's2sout' then
- reply.skipMapping = true;
- end
- module:send(reply);
+ if is_blocked(room, session, 'privateChatRestricted', 'send-private-message') then
+ -- The MUC replaced the 'from' of the stanza with the occupant JID of the
+ -- sender before it fired this event, thus the generated reply has that
+ -- as its destination. Send the reply on the session that sent the
+ -- message, the same as the MUC does for its own errors.
+ session.send(st.error_reply(stanza, 'cancel', 'not-allowed', 'Sending private messages not allowed'));
- -- let's filter this message
- return true;
+ return false;
end
end
module:hook('message/bare', on_message); -- room messages
module:hook('jitsi-visitor-groupchat-pre-route', on_message); -- visitors messages
+module:hook('muc-private-message', on_private_message); -- private messages
+module:hook('jitsi-visitor-private-message-pre-route', on_visitor_private_message); -- visitors private messages
diff --git a/resources/prosody-plugins/mod_jitsi_permissions.lua b/resources/prosody-plugins/mod_jitsi_permissions.lua
index 2928af4e35..a4743829db 100644
--- a/resources/prosody-plugins/mod_jitsi_permissions.lua
+++ b/resources/prosody-plugins/mod_jitsi_permissions.lua
@@ -72,6 +72,7 @@ local function load_config()
['outbound-call'] = true;
['create-polls'] = true;
['send-groupchat'] = true;
+ ['send-private-message'] = true;
flip = true;
['live-translation'] = true;
['live-translation-subscribe'] = true;
diff --git a/resources/prosody-plugins/mod_visitors.lua b/resources/prosody-plugins/mod_visitors.lua
index 1b14668490..e2d9888aed 100644
--- a/resources/prosody-plugins/mod_visitors.lua
+++ b/resources/prosody-plugins/mod_visitors.lua
@@ -497,6 +497,14 @@ process_host_module(main_muc_component_config, function(host_module, host)
-- Find the occupant
local occupant = room:get_occupant_by_nick(to);
if occupant then
+ -- This route does not go through the MUC, thus muc-private-message
+ -- does not fire for it. Give the filters a chance to block the
+ -- message, the same as the group-chat route above does.
+ if host_module:fire_event('jitsi-visitor-private-message-pre-route', event) then
+ -- message filtered
+ return true;
+ end
+
-- Add addresses element (XEP-0033) to store original visitor JID for reply functionality
stanza:tag('addresses', { xmlns = 'http://jabber.org/protocol/address' })
:tag('address', { type = 'ofrom', jid = stanza.attr.from }):up()
diff --git a/tests/prosody/docker/cfg/virtualhosts.cfg.lua b/tests/prosody/docker/cfg/virtualhosts.cfg.lua
index e45a06b9d3..c271b06014 100644
--- a/tests/prosody/docker/cfg/virtualhosts.cfg.lua
+++ b/tests/prosody/docker/cfg/virtualhosts.cfg.lua
@@ -43,6 +43,8 @@ VirtualHost "localhost"
-- test-only
"muc_password_check";
"muc_breakout_rooms";
+ -- Rejects a message that a client addresses to the JID of an account.
+ "filter_direct_messages";
}
-- mod_muc_password_check: verify Bearer tokens with the login ASAP key server.
diff --git a/tests/prosody/helpers/xmpp_client.js b/tests/prosody/helpers/xmpp_client.js
index 9cec9c4337..28feda84ac 100644
--- a/tests/prosody/helpers/xmpp_client.js
+++ b/tests/prosody/helpers/xmpp_client.js
@@ -599,6 +599,57 @@ export async function createXmppClient({ host = 'localhost', domain, params, use
);
},
+ /**
+ * Sends a one-to-one <message type='chat'> with a body to an arbitrary
+ * JID. Fire-and-forget: resolves with the stanza id once the stanza is
+ * written.
+ *
+ * Use it for what a Jitsi client never sends, most usefully a message
+ * addressed to the real JID of another client instead of to a MUC.
+ *
+ * @param {string} to Destination JID.
+ * @param {string} [body] Message body text.
+ * @returns {Promise<string>} the stanza id.
+ */
+ async sendDirectChat(to, body) {
+ const id = `dm-${++_counter}`;
+ const children = body === undefined ? [] : [ xml('body', {}, body) ];
+
+ await xmpp.send(
+ xml('message', { to,
+ type: 'chat',
+ id },
+ ...children)
+ );
+
+ return id;
+ },
+
+ /**
+ * Sends a MUC private message to an occupant of the room. Fire-and-forget:
+ * resolves with the stanza id once the stanza is written. The MUC does not
+ * reflect a private message back to the sender, so wait for the message on
+ * the recipient, or for an error reply on the sender.
+ *
+ * @param {string} roomJid e.g. '[email protected]'
+ * @param {string} nick MUC nick of the recipient.
+ * @param {string} [body] message body text; omit to send body-less.
+ * @returns {Promise<string>} the stanza id.
+ */
+ async sendPrivateChat(roomJid, nick, body) {
+ const id = `pm-${++_counter}`;
+ const children = body === undefined ? [] : [ xml('body', {}, body) ];
+
+ await xmpp.send(
+ xml('message', { to: `${roomJid}/${nick}`,
+ type: 'chat',
+ id },
+ ...children)
+ );
+
+ return id;
+ },
+
/**
* Sends a MUC groupchat message to the room. Resolves with the first
* <message> stanza received bearing the same id — either the MUC
diff --git a/tests/prosody/mod_filter_direct_messages_spec.js b/tests/prosody/mod_filter_direct_messages_spec.js
new file mode 100644
index 0000000000..f352bea08b
--- /dev/null
+++ b/tests/prosody/mod_filter_direct_messages_spec.js
@@ -0,0 +1,202 @@
+import assert from 'assert';
+
+import { mintAsapToken } from './helpers/jwt.js';
+import { createXmppClient, joinWithFocus } from './helpers/xmpp_client.js';
+
+const CONFERENCE = 'conference.localhost';
+const METADATA_COMPONENT = 'metadata.localhost';
+const JITMEET_NS = 'http://jitsi.org/jitmeet';
+
+let _counter = 0;
+const nextRoom = () => `filter-direct-${++_counter}@${CONFERENCE}`;
+
+/**
+ * Asserts that no message with this id arrives on the client.
+ *
+ * @param {object} client XMPP client to watch.
+ * @param {string} id Stanza id to wait for.
+ * @param {string} message Assertion message.
+ */
+async function assertNoMessage(client, id, message) {
+ try {
+ await client.waitForMessage(s => s.attrs.id === id, 1000);
+ assert.fail(message);
+ } catch (e) {
+ if (!/Timeout waiting for message/.test(e.message)) {
+ throw e;
+ }
+ }
+}
+
+describe('mod_filter_direct_messages', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ // ── blocked ───────────────────────────────────────────────────────────────
+
+ it('a message to the full JID of another client is rejected', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+
+ clients.push(focus);
+
+ const target = await createXmppClient();
+
+ clients.push(target);
+ await target.joinRoom(r);
+
+ // The sender knows the real JID of the recipient, the way an occupant of
+ // the room does. It is not an occupant itself here, which makes no
+ // difference: this route does not go to the MUC at all.
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+
+ const id = await sender.sendDirectChat(target.jid, 'direct');
+ const reply = await sender.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(reply.attrs.type, 'error', 'the message must be rejected');
+ assert.ok(
+ reply.getChild('error')?.getChild('not-allowed'),
+ 'expected <not-allowed/> error condition'
+ );
+
+ await assertNoMessage(target, id, 'the message must not reach the recipient');
+ });
+
+ it('a message to the bare JID of another client is rejected', async () => {
+ const target = await createXmppClient();
+
+ clients.push(target);
+
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+
+ const bareJid = target.jid.split('/')[0];
+ const id = await sender.sendDirectChat(bareJid, 'direct');
+ const reply = await sender.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(reply.attrs.type, 'error', 'the message must be rejected');
+ assert.ok(
+ reply.getChild('error')?.getChild('not-allowed'),
+ 'expected <not-allowed/> error condition'
+ );
+
+ await assertNoMessage(target, id, 'the message must not reach the recipient');
+ });
+
+ // ── still permitted ───────────────────────────────────────────────────────
+
+ it('a group chat message to the room is delivered', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+
+ clients.push(focus);
+
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ const reply = await sender.sendGroupchat(r, 'hello');
+
+ assert.notEqual(reply.attrs.type, 'error', 'group chat must not be affected');
+ });
+
+ it('a private message to an occupant of the room is delivered', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+
+ clients.push(focus);
+
+ const recipient = await createXmppClient();
+
+ clients.push(recipient);
+ await recipient.joinRoom(r);
+
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ const id = await sender.sendPrivateChat(r, recipient.nick, 'private');
+ const received = await recipient.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(received.getChildText('body'), 'private',
+ 'a MUC private message must not be affected');
+ });
+
+ it('a message to a component is delivered', async () => {
+ const r = nextRoom();
+ const roomName = r.split('@')[0];
+
+ const focus = await joinWithFocus(r);
+
+ clients.push(focus);
+
+ // A moderator, so that the metadata component accepts the update.
+ const token = mintAsapToken({ room: roomName,
+ context: { user: { moderator: true } } });
+ const mod = await createXmppClient({ params: { room: roomName,
+ token } });
+
+ clients.push(mod);
+ await mod.joinRoom(r);
+
+ mod.sendMetadataUpdate(METADATA_COMPONENT, r, 'permissions', { groupChatRestricted: true });
+
+ // The component answers with the broadcast of the new metadata, which
+ // proves that the message reached it.
+ const broadcast = await mod.waitForMessage(s => {
+ const jsonMsg = s.getChild('json-message', JITMEET_NS);
+
+ if (!jsonMsg) {
+ return false;
+ }
+
+ try {
+ return JSON.parse(jsonMsg.getText())?.metadata?.permissions?.groupChatRestricted === true;
+ } catch {
+ return false;
+ }
+ }, 3000);
+
+ assert.ok(broadcast, 'a message to a component must not be affected');
+ });
+
+ it('a message to a MUC on another server is not rejected by this module', async () => {
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+
+ // The shape of the occupant JID of a visitor: a MUC on the visitor node.
+ // There is no server-to-server connection in this environment, so the
+ // message either goes nowhere or comes back with a routing error. Either
+ // way it must not be the rejection of this module.
+ const id = await sender.sendDirectChat(`room@${CONFERENCE.replace('conference.', 'conference.v1.')}/nick`,
+ 'to a visitor');
+
+ try {
+ const reply = await sender.waitForMessage(s => s.attrs.id === id, 1000);
+
+ assert.strictEqual(reply.attrs.type, 'error', 'only an error can come back here');
+ assert.ok(
+ !reply.getChild('error')?.getChild('not-allowed'),
+ 'the error must come from routing, not from this module'
+ );
+ } catch (e) {
+ if (!/Timeout waiting for message/.test(e.message)) {
+ throw e;
+ }
+ }
+ });
+});
diff --git a/tests/prosody/mod_filter_messages_spec.js b/tests/prosody/mod_filter_messages_spec.js
index 2b866d1318..1775dcdf0e 100644
--- a/tests/prosody/mod_filter_messages_spec.js
+++ b/tests/prosody/mod_filter_messages_spec.js
@@ -41,14 +41,16 @@ function connect(roomJid, { contextUser, features } = {}) {
const connectModerator = roomJid => connect(roomJid, { contextUser: { moderator: true } });
/**
- * Sets groupChatRestricted on the room and waits for the metadata broadcast
+ * Sets a chat restriction on the room and waits for the metadata broadcast
* to confirm Prosody has processed the update before returning.
*
* @param {object} mod Moderator XMPP client (occupant of the room).
* @param {string} roomJid Full room JID.
+ * @param {string} [key] Permission to set: 'groupChatRestricted' (default)
+ * or 'privateChatRestricted'.
*/
-async function restrictChat(mod, roomJid) {
- mod.sendMetadataUpdate(METADATA_COMPONENT, roomJid, 'permissions', { groupChatRestricted: true });
+async function restrictChat(mod, roomJid, key = 'groupChatRestricted') {
+ mod.sendMetadataUpdate(METADATA_COMPONENT, roomJid, 'permissions', { [key]: true });
await mod.waitForMessage(s => {
const jsonMsg = s.getChild('json-message', JITMEET_NS);
@@ -58,7 +60,7 @@ async function restrictChat(mod, roomJid) {
try {
const parsed = JSON.parse(jsonMsg.getText());
- return parsed?.metadata?.permissions?.groupChatRestricted === true;
+ return parsed?.metadata?.permissions?.[key] === true;
} catch {
return false;
}
@@ -281,3 +283,208 @@ describe('mod_filter_messages', () => {
'body-less message must pass through even when chat is restricted');
});
});
+
+// ─── privateChatRestricted ────────────────────────────────────────────────────
+//
+// The same module also filters MUC private messages, through the
+// muc-private-message event. muc_max_occupants is 2 in this configuration and
+// focus is the only occupant that is exempt from that limit, so the moderator
+// that sets the restriction is also the recipient in most of these tests.
+
+describe('mod_filter_messages private messages', () => {
+
+ const clients = [];
+
+ afterEach(async () => {
+ await Promise.all(clients.map(c => c.disconnect()));
+ clients.length = 0;
+ });
+
+ // ── unrestricted ──────────────────────────────────────────────────────────
+
+ it('private message is delivered when privateChatRestricted is not set', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+
+ clients.push(focus);
+
+ const recipient = await createXmppClient();
+
+ clients.push(recipient);
+ await recipient.joinRoom(r);
+
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ const id = await sender.sendPrivateChat(r, recipient.nick, 'hello');
+ const received = await recipient.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(received.getChildText('body'), 'hello',
+ 'private message must be delivered when private chat is unrestricted');
+ });
+
+ // ── restricted — blocked ──────────────────────────────────────────────────
+
+ it('anonymous sender is blocked when privateChatRestricted is true', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(focus, mod);
+ await mod.joinRoom(r);
+
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ await restrictChat(mod, r, 'privateChatRestricted');
+
+ const id = await sender.sendPrivateChat(r, mod.nick, 'blocked?');
+ const reply = await sender.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(reply.attrs.type, 'error',
+ 'anonymous sender must be blocked when privateChatRestricted');
+ assert.ok(
+ reply.getChild('error')?.getChild('not-allowed'),
+ 'expected <not-allowed/> error condition'
+ );
+
+ await assert.rejects(
+ () => mod.waitForMessage(s => s.attrs.id === id, 1000),
+ 'the blocked message must not reach the recipient'
+ );
+ });
+
+ it('sender with send-private-message=false is blocked when privateChatRestricted is true', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(focus, mod);
+ await mod.joinRoom(r);
+
+ const sender = await connect(r, { features: { 'send-private-message': false } });
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ await restrictChat(mod, r, 'privateChatRestricted');
+
+ const id = await sender.sendPrivateChat(r, mod.nick, 'blocked?');
+ const reply = await sender.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(reply.attrs.type, 'error',
+ 'sender with send-private-message=false must be blocked');
+ });
+
+ // ── restricted — allowed ──────────────────────────────────────────────────
+
+ it('sender with send-private-message=true is allowed when privateChatRestricted is true', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(focus, mod);
+ await mod.joinRoom(r);
+
+ const sender = await connect(r, { features: { 'send-private-message': true } });
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ await restrictChat(mod, r, 'privateChatRestricted');
+
+ const id = await sender.sendPrivateChat(r, mod.nick, 'allowed!');
+ const received = await mod.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(received.getChildText('body'), 'allowed!',
+ 'sender with send-private-message=true must be allowed');
+ });
+
+ it('moderator with no features in token is allowed when privateChatRestricted is true', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(focus, mod);
+ await mod.joinRoom(r);
+
+ // A moderator without explicit token features gets the default
+ // permissions, which include send-private-message.
+ const sender = await connectModerator(r);
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ await restrictChat(mod, r, 'privateChatRestricted');
+
+ const id = await sender.sendPrivateChat(r, mod.nick, 'allowed!');
+ const received = await mod.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(received.getChildText('body'), 'allowed!',
+ 'moderator must keep private chat when privateChatRestricted');
+ });
+
+ // ── the two restrictions are independent ──────────────────────────────────
+
+ it('groupChatRestricted alone does not block a private message', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(focus, mod);
+ await mod.joinRoom(r);
+
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ await restrictChat(mod, r);
+
+ const blocked = await sender.sendGroupchat(r, 'blocked?');
+
+ assert.strictEqual(blocked.attrs.type, 'error',
+ 'precondition: group chat must be blocked for this sender');
+
+ const id = await sender.sendPrivateChat(r, mod.nick, 'still allowed');
+ const received = await mod.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(received.getChildText('body'), 'still allowed',
+ 'a group chat restriction must not block private messages');
+ });
+
+ // ── body-less message ─────────────────────────────────────────────────────
+
+ it('body-less private message is delivered even when privateChatRestricted is true', async () => {
+ const r = nextRoom();
+
+ const focus = await joinWithFocus(r);
+ const mod = await connectModerator(r);
+
+ clients.push(focus, mod);
+ await mod.joinRoom(r);
+
+ const sender = await createXmppClient();
+
+ clients.push(sender);
+ await sender.joinRoom(r);
+
+ await restrictChat(mod, r, 'privateChatRestricted');
+
+ const id = await sender.sendPrivateChat(r, mod.nick);
+ const received = await mod.waitForMessage(s => s.attrs.id === id, 3000);
+
+ assert.strictEqual(received.attrs.type, 'chat',
+ 'body-less message must pass through even when private chat is restricted');
+ });
+});