1- import { api } from '@rocket.chat/core-services' ;
1+ import { api , FederationMatrix } from '@rocket.chat/core-services' ;
22import type { IUser , SlashCommandCallbackParams } from '@rocket.chat/core-typings' ;
3- import { Subscriptions , Users } from '@rocket.chat/models' ;
3+ import { validateFederatedUsername } from '@rocket.chat/federation-matrix' ;
4+ import { Subscriptions , Users , Rooms } from '@rocket.chat/models' ;
45import { Meteor } from 'meteor/meteor' ;
56
67import { i18n } from '../../../server/lib/i18n' ;
8+ import { FederationActions } from '../../../server/services/room/hooks/BeforeFederationActions' ;
79import { addUsersToRoomMethod , sanitizeUsername } from '../../lib/server/methods/addUsersToRoom' ;
810import { settings } from '../../settings/server' ;
911import { slashCommands } from '../../utils/server/slashCommand' ;
@@ -15,13 +17,42 @@ import { slashCommands } from '../../utils/server/slashCommand';
1517slashCommands . add ( {
1618 command : 'invite' ,
1719 callback : async ( { params, message, userId } : SlashCommandCallbackParams < 'invite' > ) : Promise < void > => {
18- const usernames = params
20+ let usernames = params
1921 . split ( / [ \s , ] / )
2022 . map ( ( username ) => sanitizeUsername ( username ) )
2123 . filter ( ( a ) => a !== '' ) ;
2224 if ( usernames . length === 0 ) {
2325 return ;
2426 }
27+
28+ // Get room information for federation check
29+ const room = await Rooms . findOneById ( message . rid ) ;
30+ if ( ! room ) {
31+ void api . broadcast ( 'notify.ephemeralMessage' , userId , message . rid , {
32+ msg : i18n . t ( 'error-invalid-room' , { lng : settings . get ( 'Language' ) || 'en' } ) ,
33+ } ) ;
34+ return ;
35+ }
36+
37+ // Ensure federated users exist locally before looking them up
38+ const federatedUsernames = usernames . filter ( ( u ) => validateFederatedUsername ( u ) ) as string [ ] ;
39+ if ( federatedUsernames . length > 0 ) {
40+ if ( FederationActions . shouldPerformFederationAction ( room ) ) {
41+ await FederationMatrix . ensureFederatedUsersExistLocally ( federatedUsernames ) ;
42+ } else {
43+ void api . broadcast ( 'notify.ephemeralMessage' , userId , message . rid , {
44+ msg : i18n . t ( 'You_cannot_add_external_users_to_non_federated_room' , { lng : settings . get ( 'Language' ) || 'en' } ) ,
45+ } ) ;
46+ // These federated users shouldn't be invited and we already broadcasted the error message
47+ usernames = usernames . filter ( ( username ) => {
48+ return ! federatedUsernames . includes ( username ) ;
49+ } ) ;
50+ if ( usernames . length === 0 ) {
51+ return ;
52+ }
53+ }
54+ }
55+
2556 const users = await Users . findByUsernames ( usernames ) . toArray ( ) ;
2657 if ( users . length === 0 ) {
2758 void api . broadcast ( 'notify.ephemeralMessage' , userId , message . rid , {
0 commit comments