snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,98 @@
import { Message } from '@rocket.chat/core-services';
import type { IRoom } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms, Users } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { beforeAddUserToRoom } from '../../hooks/rooms/beforeAddUserToRoom';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { callbacks } from '../../lib/callbacks';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { getSubscriptionAutotranslateDefaultConfig } from '../../lib/getSubscriptionAutotranslateDefaultConfig';
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
import { getDefaultSubscriptionPref } from '../../lib/utils/lib/getDefaultSubscriptionPref';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
addAllUserToRoom(rid: IRoom['_id'], activeUsersOnly?: boolean): Promise<true>;
}
}
export const addAllUserToRoomFn = async (userId: string, rid: IRoom['_id'], activeUsersOnly = false): Promise<true> => {
check(rid, String);
check(activeUsersOnly, Boolean);
if (!(await hasPermissionAsync(userId, 'add-all-to-room'))) {
throw new Meteor.Error(403, 'Access to Method Forbidden', {
method: 'addAllToRoom',
});
}
const userFilter: {
active?: boolean;
} = {};
if (activeUsersOnly === true) {
userFilter.active = true;
}
const users = await Users.find(userFilter).toArray();
if (users.length > settings.get<number>('API_User_Limit')) {
throw new Meteor.Error('error-user-limit-exceeded', 'User Limit Exceeded', {
method: 'addAllToRoom',
});
}
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addAllToRoom',
});
}
await beforeAddUserToRoom(
users.map((u) => u.username!),
room,
);
const now = new Date();
for await (const user of users) {
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (subscription != null) {
continue;
}
await callbacks.run('beforeJoinRoom', user, room);
const autoTranslateConfig = getSubscriptionAutotranslateDefaultConfig(user);
const { insertedId } = await Subscriptions.createWithRoomAndUser(room, user, {
ts: now,
open: true,
alert: true,
unread: 1,
userMentions: 1,
groupMentions: 0,
...autoTranslateConfig,
...getDefaultSubscriptionPref(user),
});
if (insertedId) {
void notifyOnSubscriptionChangedById(insertedId, 'inserted');
}
await Message.saveSystemMessage('uj', rid, user.username || '', user, { ts: now });
await callbacks.run('afterJoinRoom', user, room);
}
return true;
};
Meteor.methods<ServerMethods>({
async addAllUserToRoom(rid, activeUsersOnly = false) {
methodDeprecationLogger.method('addAllUserToRoom', '9.0.0', ['/v1/channels.addAll', '/v1/groups.addAll']);
if (!this.userId) {
throw new Meteor.Error(403, 'Access to Method Forbidden', {
method: 'addAllToRoom',
});
}
return addAllUserToRoomFn(this.userId, rid, activeUsersOnly);
},
});

View File

@@ -0,0 +1,103 @@
import { api, Message, Team } from '@rocket.chat/core-services';
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Users } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
import { syncRoomRolePriorityForUserAndRoom } from '../../lib/roles/syncRoomRolePriority';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
addRoomLeader(rid: IRoom['_id'], userId: IUser['_id']): boolean;
}
}
export const addRoomLeader = async (fromUserId: IUser['_id'], rid: IRoom['_id'], userId: IUser['_id']): Promise<boolean> => {
check(rid, String);
check(userId, String);
if (!(await hasPermissionAsync(fromUserId, 'set-leader', rid))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'addRoomLeader',
});
}
const user = await Users.findOneById(userId);
if (!user?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomLeader',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'addRoomLeader',
});
}
if (subscription.roles && Array.isArray(subscription.roles) === true && subscription.roles.includes('leader') === true) {
throw new Meteor.Error('error-user-already-leader', 'User is already a leader', {
method: 'addRoomLeader',
});
}
const addRoleResponse = await Subscriptions.addRoleById(subscription._id, 'leader');
await syncRoomRolePriorityForUserAndRoom(userId, rid, subscription.roles?.concat(['leader']) || ['leader']);
if (addRoleResponse.modifiedCount) {
void notifyOnSubscriptionChangedById(subscription._id);
}
const fromUser = await Users.findOneById(fromUserId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomLeader',
});
}
await Message.saveSystemMessage('subscription-role-added', rid, user.username, fromUser, { role: 'leader' });
const team = await Team.getOneByMainRoomId(rid);
if (team) {
await Team.addRolesToMember(team._id, userId, ['leader']);
}
if (settings.get<boolean>('UI_DisplayRoles')) {
void api.broadcast('user.roleUpdate', {
type: 'added',
_id: 'leader',
u: {
_id: user._id,
username: user.username,
},
scope: rid,
});
}
return true;
};
Meteor.methods<ServerMethods>({
async addRoomLeader(rid, userId) {
methodDeprecationLogger.method('addRoomLeader', '9.0.0', ['/v1/channels.addLeader', '/v1/groups.addLeader']);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomLeader',
});
}
return addRoomLeader(uid, rid, userId);
},
});

View File

@@ -0,0 +1,125 @@
import { api, Message, Team } from '@rocket.chat/core-services';
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import { isRoomFederated } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms, Users } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { beforeChangeRoomRole } from '../../lib/callbacks/beforeChangeRoomRole';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
import { syncRoomRolePriorityForUserAndRoom } from '../../lib/roles/syncRoomRolePriority';
import { isFederationEnabled, FederationMatrixInvalidConfigurationError } from '../../services/federation/utils';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
addRoomModerator(rid: IRoom['_id'], userId: IUser['_id']): boolean;
}
}
export const addRoomModerator = async (fromUserId: IUser['_id'], rid: IRoom['_id'], userId: IUser['_id']): Promise<boolean> => {
check(rid, String);
check(userId, String);
const room = await Rooms.findOneById(rid, { projection: { t: 1, federated: 1, federation: 1 } });
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addRoomModerator',
});
}
const isFederated = isRoomFederated(room);
if (!(await hasPermissionAsync(fromUserId, 'set-moderator', rid)) && !isFederated) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'addRoomModerator',
});
}
if (isFederated && !isFederationEnabled()) {
throw new FederationMatrixInvalidConfigurationError('unable to change room owners');
}
const user = await Users.findOneById(userId);
if (!user?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomModerator',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'addRoomModerator',
});
}
if (subscription.roles && Array.isArray(subscription.roles) === true && subscription.roles.includes('moderator') === true) {
throw new Meteor.Error('error-user-already-moderator', 'User is already a moderator', {
method: 'addRoomModerator',
});
}
await beforeChangeRoomRole.run({ fromUserId, userId, room, role: 'moderator' });
const addRoleResponse = await Subscriptions.addRoleById(subscription._id, 'moderator');
await syncRoomRolePriorityForUserAndRoom(userId, rid, subscription.roles?.concat(['moderator']) || ['moderator']);
if (addRoleResponse.modifiedCount) {
void notifyOnSubscriptionChangedById(subscription._id);
}
const fromUser = await Users.findOneById(fromUserId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomLeader',
});
}
await Message.saveSystemMessage('subscription-role-added', rid, user.username, fromUser, { role: 'moderator' });
const team = await Team.getOneByMainRoomId(rid);
if (team) {
await Team.addRolesToMember(team._id, userId, ['moderator']);
}
const event = {
type: 'added',
_id: 'moderator',
u: {
_id: user._id,
username: user.username,
name: fromUser.name,
},
scope: rid,
} as const;
if (settings.get<boolean>('UI_DisplayRoles')) {
void api.broadcast('user.roleUpdate', event);
}
void api.broadcast('federation.userRoleChanged', { ...event, givenByUserId: fromUserId });
return true;
};
Meteor.methods<ServerMethods>({
async addRoomModerator(rid, userId) {
methodDeprecationLogger.method('addRoomModerator', '9.0.0', ['/v1/channels.addModerator', '/v1/groups.addModerator']);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomModerator',
});
}
return addRoomModerator(uid, rid, userId);
},
});

View File

@@ -0,0 +1,122 @@
import { api, Message, Team } from '@rocket.chat/core-services';
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import { isRoomFederated } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms, Users } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { beforeChangeRoomRole } from '../../lib/callbacks/beforeChangeRoomRole';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
import { syncRoomRolePriorityForUserAndRoom } from '../../lib/roles/syncRoomRolePriority';
import { isFederationEnabled, FederationMatrixInvalidConfigurationError } from '../../services/federation/utils';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
addRoomOwner(rid: IRoom['_id'], userId: IUser['_id']): boolean;
}
}
export const addRoomOwner = async (fromUserId: IUser['_id'], rid: IRoom['_id'], userId: IUser['_id']): Promise<boolean> => {
check(rid, String);
check(userId, String);
const room = await Rooms.findOneById(rid, { projection: { t: 1, federated: 1, federation: 1 } });
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addRoomOwner',
});
}
const isFederated = isRoomFederated(room);
if (!(await hasPermissionAsync(fromUserId, 'set-owner', rid)) && !isFederated) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'addRoomOwner',
});
}
if (isFederated && !isFederationEnabled()) {
throw new FederationMatrixInvalidConfigurationError('unable to change room owners');
}
const user = await Users.findOneById(userId);
if (!user?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomOwner',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'addRoomOwner',
});
}
if (subscription.roles && Array.isArray(subscription.roles) === true && subscription.roles.includes('owner') === true) {
throw new Meteor.Error('error-user-already-owner', 'User is already an owner', {
method: 'addRoomOwner',
});
}
await beforeChangeRoomRole.run({ fromUserId, userId, room, role: 'owner' });
const addRoleResponse = await Subscriptions.addRoleById(subscription._id, 'owner');
await syncRoomRolePriorityForUserAndRoom(userId, rid, subscription.roles?.concat(['owner']) || ['owner']);
if (addRoleResponse.modifiedCount) {
void notifyOnSubscriptionChangedById(subscription._id);
}
const fromUser = await Users.findOneById(fromUserId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomLeader',
});
}
await Message.saveSystemMessage('subscription-role-added', rid, user.username, fromUser, { role: 'owner' });
const team = await Team.getOneByMainRoomId(rid);
if (team) {
await Team.addRolesToMember(team._id, userId, ['owner']);
}
const event = {
type: 'added',
_id: 'owner',
u: {
_id: user._id,
username: user.username,
name: user.name,
},
scope: rid,
} as const;
if (settings.get('UI_DisplayRoles')) {
void api.broadcast('user.roleUpdate', event);
}
void api.broadcast('federation.userRoleChanged', { ...event, givenByUserId: fromUserId });
return true;
};
Meteor.methods<ServerMethods>({
async addRoomOwner(rid, userId) {
methodDeprecationLogger.method('addRoomOwner', '9.0.0', ['/v1/channels.addOwner', '/v1/groups.addOwner']);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addRoomOwner',
});
}
return addRoomOwner(uid, rid, userId);
},
});

View File

@@ -0,0 +1,29 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Meteor } from 'meteor/meteor';
import { addUsersToRoomMethod } from './addUsersToRoom';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
addUserToRoom(data: { rid: string; username: string }): void;
}
}
Meteor.methods<ServerMethods>({
async addUserToRoom(data) {
methodDeprecationLogger.method('addUserToRoom', '9.0.0', ['/v1/channels.invite', '/v1/groups.invite']);
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addUserToRoom',
});
}
await addUsersToRoomMethod(userId, {
rid: data.rid,
users: [data.username],
});
},
});

View File

@@ -0,0 +1,137 @@
import { api } from '@rocket.chat/core-services';
import { isBannedSubscription, isRoomNativeFederated, type IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Users, Rooms } from '@rocket.chat/models';
import { Match } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { beforeAddUsersToRoom } from '../../lib/callbacks/beforeAddUserToRoom';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { i18n } from '../../lib/i18n';
import { addUserToRoom } from '../../lib/rooms/addUserToRoom';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
addUsersToRoom(data: { rid: string; users: string[] }): boolean;
}
}
export const sanitizeUsername = (username: string) => {
const isFederatedUsername = username.includes('@') && username.includes(':');
if (isFederatedUsername) {
return username;
}
return username.replace(/(^@)|( @)/, '');
};
export const addUsersToRoomMethod = async (userId: string, data: { rid: string; users: string[] }, user?: IUser): Promise<boolean> => {
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addUsersToRoom',
});
}
if (!Match.test(data.rid, String)) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addUsersToRoom',
});
}
// Get user and room details
const room = await Rooms.findOneById(data.rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'addUsersToRoom',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(data.rid, userId, {
projection: { _id: 1 },
});
const userInRoom = subscription != null;
if (room.t === 'd' && !isRoomNativeFederated(room)) {
throw new Meteor.Error('error-cant-invite-for-direct-room', "Can't invite user to direct rooms", {
method: 'addUsersToRoom',
});
}
// Can add to any room you're in, with permission, otherwise need specific room type permission
let canAddUser = false;
if (userInRoom && (await hasPermissionAsync(userId, 'add-user-to-joined-room', room._id))) {
canAddUser = true;
} else if (room.t === 'c' && (await hasPermissionAsync(userId, 'add-user-to-any-c-room'))) {
canAddUser = true;
} else if (room.t === 'p' && (await hasPermissionAsync(userId, 'add-user-to-any-p-room'))) {
canAddUser = true;
}
// Adding wasn't allowed
if (!canAddUser) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'addUsersToRoom',
});
}
// Missing the users to be added
if (!Array.isArray(data.users)) {
throw new Meteor.Error('error-invalid-arguments', 'Invalid arguments', {
method: 'addUsersToRoom',
});
}
await beforeAddUsersToRoom.run({ usernames: data.users, inviter: user }, room);
await Promise.all(
data.users.map(async (username) => {
const sanitizedUsername = sanitizeUsername(username);
const newUser = await Users.findOneByUsernameIgnoringCase(sanitizedUsername);
if (!newUser) {
throw new Meteor.Error('error-user-not-found', 'User not found', {
method: 'addUsersToRoom',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(data.rid, newUser._id);
if (subscription && isBannedSubscription(subscription)) {
throw new Meteor.Error('error-user-is-banned', 'User is banned from this room', {
method: 'addUsersToRoom',
});
}
if (!subscription) {
return addUserToRoom(data.rid, newUser, user);
}
if (!newUser.username) {
return;
}
void api.broadcast('notify.ephemeralMessage', userId, data.rid, {
msg: i18n.t('Username_is_already_in_here', {
interpolation: { escapeValue: false },
username: newUser.username,
lng: user?.language,
}),
});
}),
);
return true;
};
Meteor.methods<ServerMethods>({
async addUsersToRoom(data) {
methodDeprecationLogger.method('addUsersToRoom', '9.0.0', ['/v1/channels.invite', '/v1/groups.invite']);
const uid = Meteor.userId();
// Validate user and room
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'addUsersToRoom',
});
}
return addUsersToRoomMethod(uid, data, ((await Meteor.userAsync()) as IUser | null) ?? undefined);
},
});

View File

@@ -0,0 +1,54 @@
import { isRegisterUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Users, Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { RoomMemberActions } from '../../../definition/IRoomTypeConfig';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { archiveRoom } from '../../lib/rooms/archiveRoom';
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
archiveRoom(rid: string): Promise<void>;
}
}
export const executeArchiveRoom = async (userId: string, rid: string) => {
check(rid, String);
const user = await Users.findOneById(userId, { projection: { username: 1, name: 1 } });
if (!user || !isRegisterUser(user)) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'archiveRoom' });
}
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'archiveRoom' });
}
if (!(await roomCoordinator.getRoomDirectives(room.t).allowMemberAction(room, RoomMemberActions.ARCHIVE, userId))) {
throw new Meteor.Error('error-direct-message-room', `rooms type: ${room.t} can not be archived`, { method: 'archiveRoom' });
}
if (!(await hasPermissionAsync(userId, 'archive-room', room._id))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'archiveRoom' });
}
return archiveRoom(rid, user);
};
Meteor.methods<ServerMethods>({
async archiveRoom(rid) {
methodDeprecationLogger.method('archiveRoom', '9.0.0', '/v1/channels.archive');
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'archiveRoom' });
}
return executeArchiveRoom(userId, rid);
},
});

View File

@@ -0,0 +1,365 @@
import { Team } from '@rocket.chat/core-services';
import type { IUser, AtLeast } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms, Users, Subscriptions } from '@rocket.chat/models';
import { escapeRegExp, isTruthy } from '@rocket.chat/tools';
import mem from 'mem';
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
import { Meteor } from 'meteor/meteor';
import type { FindOptions, SortDirection } from 'mongodb';
import { trim } from '../../../lib/utils/stringUtils';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { settings } from '../../settings';
const sortChannels = (field: string, direction: 'asc' | 'desc'): Record<string, 1 | -1> => {
switch (field) {
case 'createdAt':
return {
ts: direction === 'asc' ? 1 : -1,
};
case 'lastMessage':
return {
'lastMessage.ts': direction === 'asc' ? 1 : -1,
};
default:
return {
[field]: direction === 'asc' ? 1 : -1,
};
}
};
const sortUsers = (field: string, direction: 'asc' | 'desc'): Record<string, SortDirection> => {
switch (field) {
case 'email':
return {
'emails.address': direction === 'asc' ? 1 : -1,
'username': direction === 'asc' ? 1 : -1,
};
default:
return {
[field]: direction === 'asc' ? 1 : -1,
};
}
};
const getChannelsAndGroups = async (
user: AtLeast<IUser, '_id' | '__rooms' | 'roles'>,
canViewAnon: boolean,
searchTerm: string,
sort: Record<string, number>,
pagination: {
skip: number;
limit: number;
},
) => {
if ((!user && !canViewAnon) || (user && !(await hasPermissionAsync(user, 'view-c-room')))) {
return;
}
const teams = await Team.getAllPublicTeams();
const publicTeamIds = teams.map(({ _id }) => _id);
const userTeamsIds = (await Team.listTeamsBySubscriberUserId(user._id, { projection: { teamId: 1 } }))?.map(({ teamId }) => teamId) || [];
const userRooms = user.__rooms ?? [];
const { cursor, totalCount } = Rooms.findPaginatedByNameOrFNameAndRoomIdsIncludingTeamRooms(
searchTerm ? new RegExp(searchTerm, 'i') : null,
[...userTeamsIds, ...publicTeamIds],
userRooms,
{
...pagination,
sort: {
featured: -1,
...sort,
},
projection: {
t: 1,
description: 1,
topic: 1,
name: 1,
fname: 1,
lastMessage: 1,
ts: 1,
archived: 1,
default: 1,
featured: 1,
usersCount: 1,
prid: 1,
teamId: 1,
federated: 1,
},
},
);
const [result, total] = await Promise.all([cursor.toArray(), totalCount]);
const teamIds = result.map(({ teamId }) => teamId).filter(isTruthy);
const teamsMains = await Team.listByIds([...new Set(teamIds)], { projection: { _id: 1, name: 1 } });
const teamsById = new Map(teamsMains.map((team) => [team._id, team]));
const results = result.map((room) => {
if (room.teamId) {
const team = teamsById.get(room.teamId);
if (team) {
return { ...room, belongsTo: team.name };
}
}
return room;
});
return {
total,
results,
};
};
const getChannelsCountForTeam = mem((teamId) => Rooms.countByTeamId(teamId), {
maxAge: 2000,
});
const getTeams = async (
user: AtLeast<IUser, '_id' | '__rooms' | 'roles'>,
searchTerm: string,
sort: Record<string, number>,
pagination: {
skip: number;
limit: number;
},
) => {
if (!user) {
return;
}
const userSubs = await Subscriptions.findByUserId(user._id).toArray();
const ids = userSubs.map((sub) => sub.rid);
const { cursor, totalCount } = Rooms.findPaginatedContainingNameOrFNameInIdsAsTeamMain(
searchTerm ? new RegExp(searchTerm, 'i') : null,
ids,
{
...pagination,
sort: {
featured: -1,
...sort,
},
projection: {
t: 1,
description: 1,
topic: 1,
name: 1,
fname: 1,
lastMessage: 1,
ts: 1,
archived: 1,
default: 1,
featured: 1,
usersCount: 1,
prid: 1,
teamId: 1,
teamMain: 1,
},
},
);
const results = await Promise.all(
(await cursor.toArray()).map(async (room) => ({
...room,
roomsCount: await getChannelsCountForTeam(room.teamId),
})),
);
return {
total: await totalCount,
results,
};
};
const findUsers = async ({
text,
sort,
pagination,
workspace,
viewFullOtherUserInfo,
}: {
text: string;
sort: Record<string, SortDirection>;
pagination: {
skip: number;
limit: number;
};
workspace: string;
viewFullOtherUserInfo: boolean;
}) => {
const searchFields =
workspace === 'all' ? ['username', 'name', 'emails.address'] : settings.get<string>('Accounts_SearchFields').trim().split(',');
const options: FindOptions<IUser> = {
...pagination,
sort,
projection: {
username: 1,
name: 1,
nickname: 1,
bio: 1,
createdAt: 1,
...(viewFullOtherUserInfo && { emails: 1 }),
federation: 1,
avatarETag: 1,
},
};
type FederatedUser =
| IUser
| {
_id?: string;
username?: string;
name?: string;
bio?: string;
nickname?: string;
emails?: string;
federation?: unknown;
isRemote: true;
};
if (workspace === 'all') {
const { cursor, totalCount } = Users.findPaginatedByActiveUsersExcept<FederatedUser>(text, [], options, searchFields);
const [results, total] = await Promise.all([cursor.toArray(), totalCount]);
return {
total,
results,
};
}
if (workspace === 'external') {
const { cursor, totalCount } = Users.findPaginatedByActiveExternalUsersExcept<FederatedUser>(text, [], options, searchFields);
const [results, total] = await Promise.all([cursor.toArray(), totalCount]);
return {
total,
results,
};
}
const { cursor, totalCount } = Users.findPaginatedByActiveLocalUsersExcept<FederatedUser>(text, [], options, searchFields);
const [results, total] = await Promise.all([cursor.toArray(), totalCount]);
return {
total,
results,
};
};
const getUsers = async (
user: AtLeast<IUser, '_id' | '__rooms' | 'roles'> | undefined,
text: string,
workspace: string,
sort: Record<string, SortDirection>,
pagination: {
skip: number;
limit: number;
},
) => {
if (!user || !(await hasPermissionAsync(user, 'view-outside-room')) || !(await hasPermissionAsync(user, 'view-d-room'))) {
return;
}
const viewFullOtherUserInfo = await hasPermissionAsync(user, 'view-full-other-user-info');
const { total, results } = await findUsers({ text, sort, pagination, workspace, viewFullOtherUserInfo });
return {
total,
results,
};
};
type BrowseChannelsParams = {
text?: string;
workspace?: string;
type?: 'channels' | 'users' | 'teams' | string;
sortBy?: 'name' | 'createdAt' | 'usersCount' | 'lastMessage' | 'usernames' | string;
sortDirection?: 'asc' | 'desc';
page?: number;
offset?: number;
limit?: number;
};
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
browseChannels: (params: BrowseChannelsParams) => Promise<unknown>;
}
}
export const browseChannelsMethod = async (
{
text = '',
workspace = '',
type = 'channels',
sortBy = 'name',
sortDirection = 'asc',
page = 0,
offset = 0,
limit = 10,
}: BrowseChannelsParams,
user: AtLeast<IUser, '_id' | '__rooms' | 'roles'> | undefined | null,
) => {
const searchTerm = trim(escapeRegExp(text));
if (
!['channels', 'users', 'teams'].includes(type) ||
!['asc', 'desc'].includes(sortDirection) ||
(!page && page !== 0 && !offset && offset !== 0)
) {
return;
}
const roomParams = ['channels', 'teams'].includes(type) ? ['usernames', 'lastMessage'] : [];
const userParams = type === 'users' ? ['username', 'email', 'bio'] : [];
if (!['name', 'createdAt', 'usersCount', ...roomParams, ...userParams].includes(sortBy)) {
return;
}
const skip = Math.max(0, offset || (page > -1 ? limit * page : 0));
limit = limit > 0 ? limit : 10;
const pagination = {
skip,
limit,
};
const canViewAnonymous = !!settings.get('Accounts_AllowAnonymousRead');
if (!user) {
return;
}
switch (type) {
case 'channels':
return getChannelsAndGroups(user, canViewAnonymous, searchTerm, sortChannels(sortBy, sortDirection), pagination);
case 'teams':
return getTeams(user, searchTerm, sortChannels(sortBy, sortDirection), pagination);
case 'users':
return getUsers(user, text, workspace, sortUsers(sortBy, sortDirection), pagination);
default:
}
};
Meteor.methods<ServerMethods>({
async browseChannels(params: BrowseChannelsParams) {
methodDeprecationLogger.method('browseChannels', '9.0.0', '/v1/directory');
return browseChannelsMethod(params, await Meteor.userAsync());
},
});
DDPRateLimiter.addRule(
{
type: 'method',
name: 'browseChannels',
userId(/* userId*/) {
return true;
},
},
100,
100000,
);

View File

@@ -0,0 +1,117 @@
import type { IRoom } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms, Subscriptions, Users } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import type { FindOptions } from 'mongodb';
import _ from 'underscore';
import { trim } from '../../../lib/utils/stringUtils';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { getUserPreference } from '../../lib/utils/lib/getUserPreference';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
channelsList(filter: string, channelType: string, limit?: number, sort?: string): { channels: IRoom[] };
}
}
Meteor.methods<ServerMethods>({
async channelsList(filter, channelType, limit, sort) {
methodDeprecationLogger.method('channelsList', '9.0.0', '/v1/channels.list');
check(filter, String);
check(channelType, String);
check(limit, Match.Optional(Number));
check(sort, Match.Optional(String));
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'channelsList',
});
}
const options: FindOptions<IRoom> = {
projection: {
name: 1,
t: 1,
},
sort: {
msgs: -1,
},
};
if (_.isNumber(limit)) {
options.limit = limit;
}
if (trim(sort)) {
switch (sort) {
case 'name':
options.sort = {
name: 1,
};
break;
case 'msgs':
options.sort = {
msgs: -1,
};
}
}
let channels: IRoom[] = [];
if (channelType !== 'private') {
if (await hasPermissionAsync(userId, 'view-c-room')) {
if (filter) {
channels = channels.concat(await Rooms.findByTypeAndNameContaining('c', filter, options).toArray());
} else {
channels = channels.concat(await Rooms.findByType('c', options).toArray());
}
} else if (await hasPermissionAsync(userId, 'view-joined-room')) {
const roomIds = (await Subscriptions.findByTypeAndUserId('c', userId, { projection: { rid: 1 } }).toArray()).map((s) => s.rid);
if (filter) {
channels = channels.concat(await Rooms.findByTypeInIdsAndNameContaining('c', roomIds, filter, options).toArray());
} else {
channels = channels.concat(await Rooms.findByTypeInIds('c', roomIds, options).toArray());
}
}
}
if (channelType !== 'public' && (await hasPermissionAsync(userId, 'view-p-room'))) {
const user = await Users.findOne(userId, {
projection: {
'username': 1,
'settings.preferences.sidebarGroupByType': 1,
},
});
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'channelsList',
});
}
const userPref = await getUserPreference(user, 'sidebarGroupByType');
// needs to negate globalPref because userPref represents its opposite
const groupByType = userPref !== undefined ? userPref : settings.get('UI_Group_Channels_By_Type');
if (!groupByType) {
const roomIds = (await Subscriptions.findByTypeAndUserId('p', userId, { projection: { rid: 1 } }).toArray()).map((s) => s.rid);
if (filter) {
channels = channels.concat(await Rooms.findByTypeInIdsAndNameContaining('p', roomIds, filter, options).toArray());
} else {
channels = channels.concat(await Rooms.findByTypeInIds('p', roomIds, options).toArray());
}
}
}
return {
channels,
};
},
});

View File

@@ -0,0 +1,110 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { findRoomByIdOrName } from '../../api/v1/rooms';
import { canAccessRoomAsync } from '../../lib/authorization';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { cleanRoomHistory } from '../../lib/rooms/cleanRoomHistory';
type CleanRoomHistoryParams = {
roomId: string;
latest: Date;
oldest: Date;
inclusive?: boolean;
limit?: number;
excludePinned?: boolean;
ignoreDiscussion?: boolean;
filesOnly?: boolean;
fromUsers?: string[];
ignoreThreads?: boolean;
};
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
cleanRoomHistory(data: CleanRoomHistoryParams): number;
}
}
export const cleanRoomHistoryMethod = async (
userId: string,
{
roomId,
latest,
oldest,
inclusive = true,
limit,
excludePinned = false,
ignoreDiscussion = true,
filesOnly = false,
fromUsers = [],
ignoreThreads,
}: CleanRoomHistoryParams,
): Promise<number> => {
if (!(await hasPermissionAsync(userId, 'clean-channel-history', roomId))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'cleanRoomHistory' });
}
const room = await findRoomByIdOrName({ params: { roomId } });
if (!room || !(await canAccessRoomAsync(room, { _id: userId }))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'cleanRoomHistory' });
}
return cleanRoomHistory({
rid: roomId,
latest,
oldest,
inclusive,
limit,
excludePinned,
ignoreDiscussion,
filesOnly,
fromUsers,
ignoreThreads,
});
};
Meteor.methods<ServerMethods>({
async cleanRoomHistory({
roomId,
latest,
oldest,
inclusive = true,
limit,
excludePinned = false,
ignoreDiscussion = true,
filesOnly = false,
fromUsers = [],
ignoreThreads,
}) {
check(roomId, String);
check(latest, Date);
check(oldest, Date);
check(inclusive, Boolean);
check(limit, Match.Maybe(Number));
check(excludePinned, Match.Maybe(Boolean));
check(filesOnly, Match.Maybe(Boolean));
check(ignoreThreads, Match.Maybe(Boolean));
check(fromUsers, Match.Maybe([String]));
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'cleanRoomHistory' });
}
return cleanRoomHistoryMethod(userId, {
roomId,
latest,
oldest,
inclusive,
limit,
excludePinned,
ignoreDiscussion,
filesOnly,
fromUsers,
ignoreThreads,
});
},
});

View File

@@ -0,0 +1,73 @@
import type { ICreatedRoom, ITeam } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Users, Team } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { createRoom } from '../../lib/rooms/createRoom';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
createChannel(
name: string,
members: string[],
readOnly?: boolean,
customFields?: Record<string, any>,
extraData?: Record<string, any>,
): ICreatedRoom;
}
}
export const createChannelMethod = async (
userId: string,
name: string,
members: string[],
readOnly = false,
customFields?: Record<string, any>,
extraData: Record<string, any> = {},
excludeSelf = false,
) => {
check(name, String);
check(members, Match.Optional([String]));
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'createChannel' });
}
const user = await Users.findOneById(userId, { projection: { services: 0 } });
if (!user?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'createChannel' });
}
if (extraData.teamId) {
const team = await Team.findOneById<Pick<ITeam, '_id' | 'roomId'>>(extraData.teamId, { projection: { roomId: 1 } });
if (!team) {
throw new Meteor.Error('error-team-not-found', 'The "teamId" param provided does not match any team', { method: 'createChannel' });
}
if (!(await hasPermissionAsync(userId, 'create-team-channel', team.roomId))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createChannel' });
}
} else if (!(await hasPermissionAsync(userId, 'create-c'))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createChannel' });
}
return createRoom('c', name, user, members, excludeSelf, readOnly, {
...(customFields && Object.keys(customFields).length && { customFields }),
...extraData,
});
};
Meteor.methods<ServerMethods>({
async createChannel(name, members, readOnly = false, customFields = {}, extraData = {}) {
methodDeprecationLogger.method('createChannel', '9.0.0', '/v1/channels.create');
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'createChannel' });
}
return createChannelMethod(uid, name, members, readOnly, customFields, extraData);
},
});

View File

@@ -0,0 +1,78 @@
import type { ICreatedRoom, IUser, ITeam } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Users, Team } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { createRoom } from '../../lib/rooms/createRoom';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
createPrivateGroup(
name: string,
members: string[],
readOnly?: boolean,
customFields?: Record<string, unknown>,
extraData?: Record<string, unknown>,
): ICreatedRoom;
}
}
export const createPrivateGroupMethod = async (
user: IUser,
name: string,
members: string[],
readOnly = false,
customFields?: Record<string, any>,
extraData: Record<string, any> = {},
excludeSelf = false,
): Promise<
ICreatedRoom & {
rid: string;
}
> => {
check(name, String);
check(members, Match.Optional([String]));
if (extraData.teamId) {
const team = await Team.findOneById<Pick<ITeam, '_id' | 'roomId'>>(extraData.teamId, { projection: { roomId: 1 } });
if (!team) {
throw new Meteor.Error('error-team-not-found', 'The "teamId" param provided does not match any team', {
method: 'createPrivateGroup',
});
}
if (!(await hasPermissionAsync(user, 'create-team-group', team.roomId))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createPrivateGroup' });
}
} else if (!(await hasPermissionAsync(user, 'create-p'))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'createPrivateGroup' });
}
return createRoom('p', name, user, members, excludeSelf, readOnly, {
...(customFields && Object.keys(customFields).length && { customFields }),
...extraData,
});
};
Meteor.methods<ServerMethods>({
async createPrivateGroup(name, members, readOnly = false, customFields = {}, extraData = {}) {
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'createPrivateGroup',
});
}
const user = await Users.findOneById(uid, { projection: { services: 0 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'createPrivateGroup',
});
}
return createPrivateGroupMethod(user, name, members, readOnly, customFields, extraData);
},
});

View File

@@ -0,0 +1,52 @@
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';
import { Meteor } from 'meteor/meteor';
import { canAccessRoomAsync } from '../../lib/authorization';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getRoomById(rid: IRoom['_id']): IRoom;
}
}
Meteor.methods<ServerMethods>({
async getRoomById(rid) {
check(rid, String);
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'getRoomNameById',
});
}
const room = await Rooms.findOneById(rid);
if (room == null) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'getRoomNameById',
});
}
if (!(await canAccessRoomAsync(room, (await Meteor.userAsync()) as IUser))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'getRoomById',
});
}
return room;
},
});
DDPRateLimiter.addRule(
{
type: 'method',
name: 'getRoomById',
userId() {
return true;
},
},
10,
60000,
);

View File

@@ -0,0 +1,44 @@
// DEPRECATE
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { canAccessRoomAsync } from '../../lib/authorization';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getRoomIdByNameOrId(rid: string): string;
}
}
Meteor.methods<ServerMethods>({
async getRoomIdByNameOrId(rid) {
methodDeprecationLogger.method('getRoomIdByNameOrId', '9.0.0', '/v1/rooms.info');
check(rid, String);
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'getRoomIdByNameOrId',
});
}
const room = (await Rooms.findOneById(rid)) || (await Rooms.findOneByName(rid));
if (room == null) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'getRoomIdByNameOrId',
});
}
if (!(await canAccessRoomAsync(room, (await Meteor.userAsync()) ?? undefined))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'getRoomIdByNameOrId',
});
}
return room._id;
},
});

View File

@@ -0,0 +1,38 @@
import { isRoomWithJoinCode } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getRoomJoinCode(rid: string): string | false;
}
}
Meteor.methods<ServerMethods>({
async getRoomJoinCode(rid) {
methodDeprecationLogger.method('getRoomJoinCode', '9.0.0', []);
check(rid, String);
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getJoinCode' });
}
if (!(await hasPermissionAsync(userId, 'view-join-code'))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'getJoinCode' });
}
const room = await Rooms.findById(rid);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return Boolean(room) && (isRoomWithJoinCode(room!) ? room.joinCode : false);
},
});

View File

@@ -0,0 +1,51 @@
import type { IRoom } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getRoomNameById(rid: IRoom['_id']): Promise<string | undefined>;
}
}
Meteor.methods<ServerMethods>({
async getRoomNameById(rid) {
methodDeprecationLogger.method('getRoomNameById', '9.0.0', '/v1/rooms.info');
check(rid, String);
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'getRoomNameById',
});
}
const room = await Rooms.findOneById(rid);
if (room == null) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'getRoomNameById',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, userId, {
projection: { _id: 1 },
});
if (subscription) {
return room.name;
}
if (room.t !== 'c' || (await hasPermissionAsync(userId, 'view-c-room')) !== true) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'getRoomNameById',
});
}
return room.name;
},
});

View File

@@ -0,0 +1,35 @@
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import { Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { canAccessRoomAsync } from '../../lib/authorization';
import type { RoomRoles } from '../../lib/roles/getRoomRoles';
import { getRoomRoles } from '../../lib/roles/getRoomRoles';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getRoomRoles(rid: IRoom['_id']): RoomRoles[];
}
}
export const executeGetRoomRoles = async (rid: IRoom['_id'], fromUser?: IUser | null) => {
check(rid, String);
if (!fromUser && settings.get('Accounts_AllowAnonymousRead') === false) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getRoomRoles' });
}
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'getRoomRoles' });
}
if (fromUser && !(await canAccessRoomAsync(room, fromUser))) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'getRoomRoles' });
}
return getRoomRoles(rid);
};

View File

@@ -0,0 +1,25 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getTotalChannels(): number;
}
}
Meteor.methods<ServerMethods>({
getTotalChannels() {
methodDeprecationLogger.method('getTotalChannels', '9.0.0', '/v1/channels.list');
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'getTotalChannels',
});
}
return Rooms.countDocuments({ t: 'c' });
},
});

View File

@@ -0,0 +1,47 @@
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedByRoomIdAndUserId } from '../../lib/notifyListener';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
hideRoom(rid: string): Promise<number>;
}
}
export const hideRoomMethod = async (userId: string, rid: string): Promise<number> => {
check(rid, String);
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'hideRoom',
});
}
const { modifiedCount } = await Subscriptions.hideByRoomIdAndUserId(rid, userId);
if (modifiedCount) {
void notifyOnSubscriptionChangedByRoomIdAndUserId(rid, userId);
}
return modifiedCount;
};
Meteor.methods<ServerMethods>({
async hideRoom(rid) {
methodDeprecationLogger.method('hideRoom', '9.0.0', '/v1/rooms.hide');
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'hideRoom',
});
}
return hideRoomMethod(uid, rid);
},
});

View File

@@ -0,0 +1,27 @@
import type { IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { addUserToDefaultChannels } from '../../lib/rooms/addUserToDefaultChannels';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
joinDefaultChannels(silenced?: boolean): void;
}
}
Meteor.methods<ServerMethods>({
async joinDefaultChannels(silenced) {
check(silenced, Match.Optional(Boolean));
const user = await Meteor.userAsync();
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'joinDefaultChannels',
});
}
return addUserToDefaultChannels(user as IUser, Boolean(silenced));
},
});

View File

@@ -0,0 +1,34 @@
import { Room } from '@rocket.chat/core-services';
import type { IRoom } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
joinRoom(rid: IRoom['_id'], code?: string): boolean | undefined;
}
}
Meteor.methods<ServerMethods>({
async joinRoom(rid, code) {
methodDeprecationLogger.method('joinRoom', '9.0.0', '/v1/rooms.join');
check(rid, String);
const user = await Meteor.userAsync();
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'joinRoom' });
}
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'joinRoom' });
}
return Room.join({ room, user, ...(code ? { joinCode: code } : {}) });
},
});

View File

@@ -0,0 +1,77 @@
import type { IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Roles, Subscriptions, Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { RoomMemberActions } from '../../../definition/IRoomTypeConfig';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { hasRoleAsync } from '../../lib/authorization/hasRole';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { removeUserFromRoom } from '../../lib/rooms/removeUserFromRoom';
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
leaveRoom(rid: string): Promise<void>;
}
}
export const leaveRoomMethod = async (user: IUser, rid: string): Promise<void> => {
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'leaveRoom' });
}
if (!user || !(await roomCoordinator.getRoomDirectives(room.t).allowMemberAction(room, RoomMemberActions.LEAVE, user._id))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'leaveRoom' });
}
if (
(room.t === 'c' && !(await hasPermissionAsync(user, 'leave-c'))) ||
(room.t === 'p' && !(await hasPermissionAsync(user, 'leave-p')))
) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'leaveRoom' });
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id, {
projection: { _id: 1 },
});
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'You are not in this room', {
method: 'leaveRoom',
});
}
// If user is room owner, check if there are other owners. If there isn't anyone else, warn user to set a new owner.
if (await hasRoleAsync(user._id, 'owner', room._id)) {
const numOwners = await Roles.countUsersInRole('owner', room._id);
if (numOwners === 1) {
throw new Meteor.Error('error-you-are-last-owner', 'You are the last owner. Please set new owner before leaving the room.', {
method: 'leaveRoom',
});
}
}
return removeUserFromRoom(rid, user);
};
Meteor.methods<ServerMethods>({
async leaveRoom(rid) {
methodDeprecationLogger.method('leaveRoom', '9.0.0', ['/v1/channels.leave', '/v1/groups.leave', '/v1/im.leave']);
check(rid, String);
if (!Meteor.userId()) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'leaveRoom' });
}
const user = (await Meteor.userAsync()) as unknown as IUser;
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'leaveRoom' });
}
return leaveRoomMethod(user, rid);
},
});

View File

@@ -0,0 +1,80 @@
import { Message } from '@rocket.chat/core-services';
import type { IRoom } from '@rocket.chat/core-typings';
import { Rooms, Subscriptions, Users } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { RoomMemberActions } from '../../../definition/IRoomTypeConfig';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { callbacks } from '../../lib/callbacks';
import { notifyOnRoomChangedById } from '../../lib/notifyListener';
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
muteUserInRoom(data: { rid: IRoom['_id']; username: string }): boolean;
}
}
export const muteUserInRoom = async (fromId: string, data: { rid: IRoom['_id']; username: string }): Promise<boolean> => {
if (!fromId || !(await hasPermissionAsync(fromId, 'mute-user', data.rid))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'muteUserInRoom',
});
}
const room = await Rooms.findOneById(data.rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'muteUserInRoom',
});
}
if (!(await roomCoordinator.getRoomDirectives(room.t).allowMemberAction(room, RoomMemberActions.MUTE, fromId))) {
throw new Meteor.Error('error-invalid-room-type', `${room.t} is not a valid room type`, {
method: 'muteUserInRoom',
type: room.t,
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUsername(data.rid, data.username, {
projection: { _id: 1 },
});
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'muteUserInRoom',
});
}
const mutedUser = await Users.findOneByUsernameIgnoringCase(data.username);
if (!mutedUser?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user to mute', {
method: 'muteUserInRoom',
});
}
const fromUser = await Users.findOneById(fromId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'muteUserInRoom',
});
}
await callbacks.run('beforeMuteUser', { mutedUser, fromUser }, room);
if (room.ro) {
await Rooms.muteReadOnlyUsernameByRoomId(data.rid, mutedUser.username);
} else {
await Rooms.muteUsernameByRoomId(data.rid, mutedUser.username);
}
await Message.saveSystemMessage('user-muted', data.rid, mutedUser.username, fromUser);
await callbacks.run('afterMuteUser', { mutedUser, fromUser }, room);
void notifyOnRoomChangedById(data.rid);
return true;
};

View File

@@ -0,0 +1,29 @@
import type { IRoom } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { openRoom } from '../../lib/openRoom';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
openRoom(rid: IRoom['_id']): Promise<number>;
}
}
Meteor.methods<ServerMethods>({
async openRoom(rid) {
check(rid, String);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'openRoom',
});
}
return openRoom(uid, rid);
},
});

View File

@@ -0,0 +1,103 @@
import { api, Message, Team } from '@rocket.chat/core-services';
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Users } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
import { syncRoomRolePriorityForUserAndRoom } from '../../lib/roles/syncRoomRolePriority';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
removeRoomLeader(rid: IRoom['_id'], userId: IUser['_id']): boolean;
}
}
export const removeRoomLeader = async (fromUserId: IUser['_id'], rid: IRoom['_id'], userId: IUser['_id']): Promise<boolean> => {
check(rid, String);
check(userId, String);
if (!(await hasPermissionAsync(fromUserId, 'set-leader', rid))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'removeRoomLeader',
});
}
const user = await Users.findOneById(userId);
if (!user?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomLeader',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'removeRoomLeader',
});
}
if (subscription.roles && Array.isArray(subscription.roles) === true && subscription.roles.includes('leader') === false) {
throw new Meteor.Error('error-user-not-leader', 'User is not a leader', {
method: 'removeRoomLeader',
});
}
const removeRoleResponse = await Subscriptions.removeRoleById(subscription._id, 'leader');
await syncRoomRolePriorityForUserAndRoom(userId, rid, subscription.roles?.filter((r) => r !== 'leader') || []);
if (removeRoleResponse.modifiedCount) {
void notifyOnSubscriptionChangedById(subscription._id);
}
const fromUser = await Users.findOneById(fromUserId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomLeader',
});
}
await Message.saveSystemMessage('subscription-role-removed', rid, user.username, fromUser, { role: 'leader' });
const team = await Team.getOneByMainRoomId(rid);
if (team) {
await Team.removeRolesFromMember(team._id, userId, ['leader']);
}
if (settings.get('UI_DisplayRoles')) {
void api.broadcast('user.roleUpdate', {
type: 'removed',
_id: 'leader',
u: {
_id: user._id,
username: user.username,
name: user.name,
},
scope: rid,
});
}
return true;
};
Meteor.methods<ServerMethods>({
async removeRoomLeader(rid, userId) {
methodDeprecationLogger.method('removeRoomLeader', '9.0.0', ['/v1/channels.removeLeader', '/v1/groups.removeLeader']);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomLeader',
});
}
return removeRoomLeader(uid, rid, userId);
},
});

View File

@@ -0,0 +1,116 @@
import { api, Message, Team } from '@rocket.chat/core-services';
import type { IRoom, IUser } from '@rocket.chat/core-typings';
import { isRoomFederated } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms, Users } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { beforeChangeRoomRole } from '../../lib/callbacks/beforeChangeRoomRole';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
import { syncRoomRolePriorityForUserAndRoom } from '../../lib/roles/syncRoomRolePriority';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
removeRoomModerator(rid: IRoom['_id'], userId: IUser['_id']): boolean;
}
}
export const removeRoomModerator = async (fromUserId: IUser['_id'], rid: IRoom['_id'], userId: IUser['_id']): Promise<boolean> => {
check(rid, String);
check(userId, String);
const room = await Rooms.findOneById(rid, { projection: { t: 1, federated: 1, federation: 1 } });
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'removeRoomModerator',
});
}
if (!(await hasPermissionAsync(fromUserId, 'set-moderator', rid)) && !isRoomFederated(room)) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'removeRoomModerator',
});
}
const user = await Users.findOneById(userId);
if (!user?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomModerator',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'removeRoomModerator',
});
}
if (subscription.roles && (!Array.isArray(subscription.roles) || !subscription.roles.includes('moderator'))) {
throw new Meteor.Error('error-user-not-moderator', 'User is not a moderator', {
method: 'removeRoomModerator',
});
}
await beforeChangeRoomRole.run({ fromUserId, userId, room, role: 'user' });
const removeRoleResponse = await Subscriptions.removeRoleById(subscription._id, 'moderator');
await syncRoomRolePriorityForUserAndRoom(userId, rid, subscription.roles?.filter((r) => r !== 'moderator') || []);
if (removeRoleResponse.modifiedCount) {
void notifyOnSubscriptionChangedById(subscription._id);
}
const fromUser = await Users.findOneById(fromUserId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomModerator',
});
}
await Message.saveSystemMessage('subscription-role-removed', rid, user.username, fromUser, { role: 'moderator' });
const team = await Team.getOneByMainRoomId(rid);
if (team) {
await Team.removeRolesFromMember(team._id, userId, ['moderator']);
}
const event = {
type: 'removed',
_id: 'moderator',
u: {
_id: user._id,
username: user.username,
name: user.name,
},
scope: rid,
} as const;
if (settings.get('UI_DisplayRoles')) {
void api.broadcast('user.roleUpdate', event);
}
void api.broadcast('federation.userRoleChanged', { ...event, givenByUserId: fromUserId });
return true;
};
Meteor.methods<ServerMethods>({
async removeRoomModerator(rid, userId) {
methodDeprecationLogger.method('removeRoomModerator', '9.0.0', ['/v1/channels.removeModerator', '/v1/groups.removeModerator']);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomModerator',
});
}
return removeRoomModerator(uid, rid, userId);
},
});

View File

@@ -0,0 +1,121 @@
import { api, Message, Team } from '@rocket.chat/core-services';
import { isRoomFederated } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms, Users, Roles } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { beforeChangeRoomRole } from '../../lib/callbacks/beforeChangeRoomRole';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedById } from '../../lib/notifyListener';
import { syncRoomRolePriorityForUserAndRoom } from '../../lib/roles/syncRoomRolePriority';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
removeRoomOwner(rid: string, userId: string): boolean;
}
}
export const removeRoomOwner = async (fromUserId: string, rid: string, userId: string): Promise<boolean> => {
check(rid, String);
check(userId, String);
const room = await Rooms.findOneById(rid, { projection: { t: 1, federated: 1, federation: 1 } });
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'removeRoomOwner',
});
}
if (!(await hasPermissionAsync(fromUserId, 'set-owner', rid)) && !isRoomFederated(room)) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'removeRoomOwner',
});
}
const user = await Users.findOneById(userId);
if (!user?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomOwner',
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUserId(rid, user._id);
if (!subscription) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'removeRoomOwner',
});
}
if (Array.isArray(subscription.roles) === false || subscription.roles?.includes('owner') === false) {
throw new Meteor.Error('error-user-not-owner', 'User is not an owner', {
method: 'removeRoomOwner',
});
}
const numOwners = await Roles.countUsersInRole('owner', rid);
if (numOwners === 1) {
throw new Meteor.Error('error-remove-last-owner', 'This is the last owner. Please set a new owner before removing this one.', {
method: 'removeRoomOwner',
});
}
await beforeChangeRoomRole.run({ fromUserId, userId, room, role: 'user' });
const removeRoleResponse = await Subscriptions.removeRoleById(subscription._id, 'owner');
await syncRoomRolePriorityForUserAndRoom(userId, rid, subscription.roles?.filter((r) => r !== 'owner') || []);
if (removeRoleResponse.modifiedCount) {
void notifyOnSubscriptionChangedById(subscription._id);
}
const fromUser = await Users.findOneById(fromUserId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomOwner',
});
}
await Message.saveSystemMessage('subscription-role-removed', rid, user.username, fromUser, { role: 'owner' });
const team = await Team.getOneByMainRoomId(rid);
if (team) {
await Team.removeRolesFromMember(team._id, userId, ['owner']);
}
const event = {
type: 'removed',
_id: 'owner',
u: {
_id: user._id,
username: user.username,
name: user.name,
},
scope: rid,
} as const;
if (settings.get('UI_DisplayRoles')) {
void api.broadcast('user.roleUpdate', event);
}
void api.broadcast('federation.userRoleChanged', { ...event, givenByUserId: fromUserId });
return true;
};
Meteor.methods<ServerMethods>({
async removeRoomOwner(rid, userId) {
methodDeprecationLogger.method('removeRoomOwner', '9.0.0', ['/v1/channels.removeOwner', '/v1/groups.removeOwner']);
const uid = Meteor.userId();
if (!uid) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeRoomOwner',
});
}
return removeRoomOwner(uid, rid, userId);
},
});

View File

@@ -0,0 +1,151 @@
import { Apps, AppEvents } from '@rocket.chat/apps';
import { AppsEngineException } from '@rocket.chat/apps-engine/definition/exceptions';
import { Message, Team, Room } from '@rocket.chat/core-services';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions, Rooms, Users, Roles } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { RoomMemberActions } from '../../../definition/IRoomTypeConfig';
import { canAccessRoomAsync } from '../../lib/authorization';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { hasRoleAsync } from '../../lib/authorization/hasRole';
import { callbacks } from '../../lib/callbacks';
import { afterRemoveFromRoomCallback } from '../../lib/callbacks/afterRemoveFromRoomCallback';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnRoomChanged, notifyOnSubscriptionChanged } from '../../lib/notifyListener';
import { removeUserFromRolesAsync } from '../../lib/roles/removeUserFromRoles';
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
import { settings } from '../../settings';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
removeUserFromRoom(data: { rid: string; username: string }): boolean;
}
}
export const removeUserFromRoomMethod = async (fromId: string, data: { rid: string; username: string }): Promise<boolean> => {
if (!(await hasPermissionAsync(fromId, 'remove-user', data.rid))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'removeUserFromRoom',
});
}
const room = await Rooms.findOneById(data.rid);
if (!room || !(await roomCoordinator.getRoomDirectives(room.t).allowMemberAction(room, RoomMemberActions.REMOVE_USER, fromId))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'removeUserFromRoom',
});
}
const fromUser = await Users.findOneById(fromId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeUserFromRoom',
});
}
// did this way so a ctrl-f would find the permission being used
const kickAnyUserPermission = room.t === 'c' ? 'kick-user-from-any-c-room' : 'kick-user-from-any-p-room';
const canKickAnyUser = await hasPermissionAsync(fromId, kickAnyUserPermission);
if (!canKickAnyUser && !(await canAccessRoomAsync(room, fromUser))) {
throw new Meteor.Error('error-room-not-found', 'The required "roomId" or "roomName" param provided does not match any group');
}
const removedUser = await Users.findOneByUsernameIgnoringCase(data.username);
if (!removedUser) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'removeUserFromRoom',
});
}
await Room.beforeUserRemoved(room);
if (!canKickAnyUser) {
const subscription = await Subscriptions.findOneByRoomIdAndUserId(data.rid, removedUser._id, {
projection: { _id: 1 },
});
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'removeUserFromRoom',
});
}
}
if (await hasRoleAsync(removedUser._id, 'owner', room._id)) {
const numOwners = await Roles.countUsersInRole('owner', room._id);
if (numOwners === 1) {
throw new Meteor.Error('error-you-are-last-owner', 'You are the last owner. Please set new owner before leaving the room.', {
method: 'removeUserFromRoom',
});
}
}
try {
await Apps.self?.triggerEvent(AppEvents.IPreRoomUserLeave, room, removedUser, fromUser);
} catch (error: any) {
if (error.name === AppsEngineException.name) {
throw new Meteor.Error('error-app-prevented', error.message);
}
throw error;
}
await callbacks.run('beforeRemoveFromRoom', { removedUser, userWhoRemoved: fromUser }, room);
const deletedSubscription = await Subscriptions.removeByRoomIdAndUserId(data.rid, removedUser._id);
if (deletedSubscription) {
void notifyOnSubscriptionChanged(deletedSubscription, 'removed');
}
if (['c', 'p'].includes(room.t) === true) {
await removeUserFromRolesAsync(removedUser._id, ['moderator', 'owner'], data.rid);
}
await Message.saveSystemMessage('ru', data.rid, removedUser.username || '', fromUser);
if (room.teamId && room.teamMain) {
// if a user is kicked from the main team room, delete the team membership
await Team.removeMember(room.teamId, removedUser._id);
}
if (room.encrypted && settings.get('E2E_Enable')) {
await Rooms.removeUsersFromE2EEQueueByRoomId(room._id, [removedUser._id]);
}
setImmediate(() => {
void afterRemoveFromRoomCallback.run({ removedUser, userWhoRemoved: fromUser }, room);
void notifyOnRoomChanged(room);
});
await Apps.self?.triggerEvent(AppEvents.IPostRoomUserLeave, room, removedUser, fromUser);
return true;
};
Meteor.methods<ServerMethods>({
async removeUserFromRoom(data) {
methodDeprecationLogger.method('removeUserFromRoom', '9.0.0', ['/v1/channels.kick', '/v1/groups.kick']);
check(
data,
Match.ObjectIncluding({
rid: String,
username: String,
}),
);
const fromId = Meteor.userId();
if (!fromId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'removeUserFromRoom',
});
}
return removeUserFromRoomMethod(fromId, data);
},
});

View File

@@ -0,0 +1,568 @@
import { Team } from '@rocket.chat/core-services';
import type { IRoom, IRoomWithRetentionPolicy, IUser, MessageTypesValues, ITeam, RequiredField } from '@rocket.chat/core-typings';
import { TeamType } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Rooms, Users } from '@rocket.chat/models';
import { Match } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { RoomSettingsEnum } from '../../../definition/IRoomTypeConfig';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { isABACManagedRoom } from '../../lib/authorization/isABACManagedRoom';
import { SystemLogger } from '../../lib/logger/system';
import { updateAndNotifyParentRoomWithParentMessage } from '../../lib/messaging/discussions/updateAndNotifyParentRoomWithParentMessage';
import { notifyOnRoomChangedById } from '../../lib/notifyListener';
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
import { setRoomAvatar } from '../../lib/rooms/setRoomAvatar';
import { saveReactWhenReadOnly } from '../../lib/rooms/settings/saveReactWhenReadOnly';
import { saveRoomAnnouncement } from '../../lib/rooms/settings/saveRoomAnnouncement';
import { saveRoomCustomFields } from '../../lib/rooms/settings/saveRoomCustomFields';
import { saveRoomDescription } from '../../lib/rooms/settings/saveRoomDescription';
import { saveRoomEncrypted } from '../../lib/rooms/settings/saveRoomEncrypted';
import { saveRoomName } from '../../lib/rooms/settings/saveRoomName';
import { saveRoomReadOnly } from '../../lib/rooms/settings/saveRoomReadOnly';
import { saveRoomSystemMessages } from '../../lib/rooms/settings/saveRoomSystemMessages';
import { saveRoomTopic } from '../../lib/rooms/settings/saveRoomTopic';
import { saveRoomType } from '../../lib/rooms/settings/saveRoomType';
import { settings } from '../../settings';
type RoomSettings = {
roomAvatar: string;
featured: boolean;
roomName: string | undefined;
roomTopic: string;
roomAnnouncement: string;
roomCustomFields: Record<string, any>;
roomDescription: string;
roomType: IRoom['t'];
readOnly: boolean;
reactWhenReadOnly: boolean;
systemMessages: MessageTypesValues[];
default: boolean;
joinCode: string;
retentionEnabled: boolean;
retentionMaxAge: number;
retentionExcludePinned: boolean;
retentionFilesOnly: boolean;
retentionIgnoreThreads: boolean;
retentionOverrideGlobal: boolean;
encrypted: boolean;
favorite: {
favorite: boolean;
defaultValue: boolean;
};
};
type RoomSettingsValidators = {
[TRoomSetting in keyof RoomSettings]?: (params: {
userId: IUser['_id'];
value: RoomSettings[TRoomSetting];
room: IRoom;
rid: IRoom['_id'];
}) => Promise<void> | void;
};
const hasRetentionPolicy = (room: IRoom & { retention?: any }): room is IRoomWithRetentionPolicy =>
'retention' in room && room.retention !== undefined;
const isAbacManagedTeam = (team: Partial<ITeam> | null, teamRoom: IRoom): boolean => {
return (
team?.type === TeamType.PRIVATE &&
settings.get<boolean>('ABAC_Enabled') &&
Array.isArray(teamRoom?.abacAttributes) &&
teamRoom.abacAttributes.length > 0
);
};
const guardABACManagedField = (room: IRoom, value: string | undefined, current: string | undefined, fieldName: string): void => {
if (!value && !current) {
return;
}
if (value === current) {
return;
}
if (isABACManagedRoom(room)) {
throw new Meteor.Error('error-action-not-allowed', `Editing an ABAC managed room's ${fieldName} is not allowed`, {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
};
const validators: RoomSettingsValidators = {
async default({ userId, room, value }) {
if (!(await hasPermissionAsync(userId, 'view-room-administration'))) {
throw new Meteor.Error('error-action-not-allowed', 'Viewing room administration is not allowed', {
method: 'saveRoomSettings',
action: 'Viewing_room_administration',
});
}
if (isABACManagedRoom(room) && value) {
throw new Meteor.Error('error-action-not-allowed', 'Setting an ABAC managed room as default is not allowed', {
method: 'saveRoomSettings',
action: 'Viewing_room_administration',
});
}
},
async featured({ userId }) {
if (!(await hasPermissionAsync(userId, 'view-room-administration'))) {
throw new Meteor.Error('error-action-not-allowed', 'Viewing room administration is not allowed', {
method: 'saveRoomSettings',
action: 'Viewing_room_administration',
});
}
},
async roomType({ userId, room, value }) {
if (value === room.t) {
return;
}
if (value === 'c' && (!room.teamId || room.teamMain) && !(await hasPermissionAsync(userId, 'create-c'))) {
throw new Meteor.Error('error-action-not-allowed', 'Changing a private group to a public channel is not allowed', {
method: 'saveRoomSettings',
action: 'Change_Room_Type',
});
}
if (value === 'p' && (!room.teamId || room.teamMain) && !(await hasPermissionAsync(userId, 'create-p'))) {
throw new Meteor.Error('error-action-not-allowed', 'Changing a public channel to a private room is not allowed', {
method: 'saveRoomSettings',
action: 'Change_Room_Type',
});
}
if (isABACManagedRoom(room) && value !== 'p') {
throw new Meteor.Error('error-action-not-allowed', 'Changing an ABAC managed private room to public is not allowed', {
method: 'saveRoomSettings',
action: 'Change_Room_Type',
});
}
if (!room.teamId || room.teamMain) {
return;
}
const team = await Team.getInfoById(room.teamId);
if (value === 'c' && !(await hasPermissionAsync(userId, 'create-team-channel', team?.roomId))) {
throw new Meteor.Error('error-action-not-allowed', `Changing a team's private group to a public channel is not allowed`, {
method: 'saveRoomSettings',
action: 'Change_Room_Type',
});
}
if (value === 'p' && !(await hasPermissionAsync(userId, 'create-team-group', team?.roomId))) {
throw new Meteor.Error('error-action-not-allowed', `Changing a team's public channel to a private room is not allowed`, {
method: 'saveRoomSettings',
action: 'Change_Room_Type',
});
}
if (isAbacManagedTeam(team, room) && value !== 'p') {
throw new Meteor.Error('error-action-not-allowed', 'Changing an ABAC managed private team room to public is not allowed', {
method: 'saveRoomSettings',
action: 'Change_Room_Type',
});
}
},
async roomAnnouncement({ room, value }) {
guardABACManagedField(room, value, room.announcement, 'announcement');
},
async roomTopic({ room, value }) {
guardABACManagedField(room, value, room.topic, 'topic');
},
async roomDescription({ room, value }) {
guardABACManagedField(room, value, room.description, 'description');
},
async encrypted({ userId, value, room, rid }) {
if (value !== room.encrypted) {
if (!(await roomCoordinator.getRoomDirectives(room.t).allowRoomSettingChange(room, RoomSettingsEnum.E2E))) {
throw new Meteor.Error('error-action-not-allowed', 'Only groups or direct channels can enable encryption', {
method: 'saveRoomSettings',
action: 'Change_Room_Encrypted',
});
}
if (room.t !== 'd' && !(await hasPermissionAsync(userId, 'toggle-room-e2e-encryption', rid))) {
throw new Meteor.Error('error-action-not-allowed', 'You do not have permission to toggle E2E encryption', {
method: 'saveRoomSettings',
action: 'Change_Room_Encrypted',
});
}
}
},
async retentionEnabled({ userId, value, room, rid }) {
if (
!(await hasPermissionAsync(userId, 'edit-room-retention-policy', rid)) &&
(!hasRetentionPolicy(room) || value !== room.retention.enabled)
) {
throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
},
async retentionMaxAge({ userId, value, room, rid }) {
if (
!(await hasPermissionAsync(userId, 'edit-room-retention-policy', rid)) &&
(!hasRetentionPolicy(room) || value !== room.retention.maxAge)
) {
throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
},
async retentionExcludePinned({ userId, value, room, rid }) {
if (
!(await hasPermissionAsync(userId, 'edit-room-retention-policy', rid)) &&
(!hasRetentionPolicy(room) || value !== room.retention.excludePinned)
) {
throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
},
async retentionFilesOnly({ userId, value, room, rid }) {
if (
!(await hasPermissionAsync(userId, 'edit-room-retention-policy', rid)) &&
(!hasRetentionPolicy(room) || value !== room.retention.filesOnly)
) {
throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
},
async retentionIgnoreThreads({ userId, value, room, rid }) {
if (
!(await hasPermissionAsync(userId, 'edit-room-retention-policy', rid)) &&
(!hasRetentionPolicy(room) || value !== room.retention.ignoreThreads)
) {
throw new Meteor.Error('error-action-not-allowed', 'Editing room retention policy is not allowed', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
},
async roomAvatar({ userId, rid }) {
if (!(await hasPermissionAsync(userId, 'edit-room-avatar', rid))) {
throw new Meteor.Error('error-action-not-allowed', 'Editing a room avatar is not allowed', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
},
};
type RoomSettingsSavers = {
[TRoomSetting in keyof RoomSettings]?: (params: {
userId: IUser['_id'];
user: RequiredField<IUser, 'username' | 'name'>;
value: RoomSettings[TRoomSetting];
room: IRoom;
rid: IRoom['_id'];
}) => void | Promise<void>;
};
const settingSavers: RoomSettingsSavers = {
async roomName({ value, rid, user, room }) {
if (!(await saveRoomName(rid, value, user))) {
return;
}
if (room.teamId && room.teamMain) {
void Team.update(user._id, room.teamId, {
type: room.t === 'c' ? TeamType.PUBLIC : TeamType.PRIVATE,
name: value,
updateRoom: false,
});
}
},
async roomTopic({ value, room, rid, user }) {
if (!value && !room.topic) {
return;
}
if (value !== room.topic) {
await saveRoomTopic(rid, value, user);
}
},
async roomAnnouncement({ value, room, rid, user }) {
if (!value && !room.announcement) {
return;
}
if (value !== room.announcement) {
await saveRoomAnnouncement(rid, value, user);
}
},
async roomCustomFields({ value, room, rid }) {
if (value !== room.customFields) {
await saveRoomCustomFields(rid, value);
}
},
async roomDescription({ value, room, rid, user }) {
if (!value && !room.description) {
return;
}
if (value !== room.description) {
await saveRoomDescription(rid, value, user);
}
},
async roomType({ value, room, rid, user }) {
if (value === room.t) {
return;
}
if (!(await saveRoomType(rid, value, user))) {
return;
}
if (room.teamId && room.teamMain) {
const type = value === 'c' ? TeamType.PUBLIC : TeamType.PRIVATE;
void Team.update(user._id, room.teamId, { type, updateRoom: false });
}
},
async readOnly({ value, room, rid, user }) {
if (value !== room.ro) {
await saveRoomReadOnly(rid, value, user);
}
},
async reactWhenReadOnly({ value, room, rid, user }) {
if (value !== room.reactWhenReadOnly) {
await saveReactWhenReadOnly(rid, value, user);
}
},
async systemMessages({ value, room, rid }) {
if (JSON.stringify(value) !== JSON.stringify(room.sysMes)) {
await saveRoomSystemMessages(rid, value);
if (room?.prid) {
try {
await updateAndNotifyParentRoomWithParentMessage({ ...room, sysMes: value });
} catch (err) {
SystemLogger.error({ msg: 'Failed to propagate discussion metadata', err, rid });
}
}
}
},
async joinCode({ value, rid }) {
await Rooms.setJoinCodeById(rid, String(value));
},
async default({ value, rid }) {
await Rooms.saveDefaultById(rid, value);
},
async featured({ value, rid }) {
await Rooms.saveFeaturedById(rid, value);
},
async retentionEnabled({ value, rid }) {
await Rooms.saveRetentionEnabledById(rid, value);
},
async retentionMaxAge({ value, rid }) {
await Rooms.saveRetentionMaxAgeById(rid, value);
},
async retentionExcludePinned({ value, rid }) {
await Rooms.saveRetentionExcludePinnedById(rid, value);
},
async retentionFilesOnly({ value, rid }) {
await Rooms.saveRetentionFilesOnlyById(rid, value);
},
async retentionIgnoreThreads({ value, rid }) {
await Rooms.saveRetentionIgnoreThreadsById(rid, value);
},
async retentionOverrideGlobal({ value, rid }) {
await Rooms.saveRetentionOverrideGlobalById(rid, value);
},
async encrypted({ value, room, rid, user }) {
await saveRoomEncrypted(rid, value, user, Boolean(room.encrypted) !== Boolean(value));
},
async favorite({ value, rid }) {
await Rooms.saveFavoriteById(rid, value.favorite, value.defaultValue);
},
async roomAvatar({ value, rid, user }) {
await setRoomAvatar(rid, value, user);
},
};
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
saveRoomSettings(rid: IRoom['_id'], settings: Partial<RoomSettings>): Promise<{ result: true; rid: IRoom['_id'] }>;
saveRoomSettings<RoomSettingName extends keyof RoomSettings>(
rid: IRoom['_id'],
setting: RoomSettingName,
value: RoomSettings[RoomSettingName],
): Promise<{ result: true; rid: IRoom['_id'] }>;
}
}
const fields: (keyof RoomSettings)[] = [
'roomAvatar',
'featured',
'roomName',
'roomTopic',
'roomAnnouncement',
'roomCustomFields',
'roomDescription',
'roomType',
'readOnly',
'reactWhenReadOnly',
'systemMessages',
'default',
'joinCode',
'retentionEnabled',
'retentionMaxAge',
'retentionExcludePinned',
'retentionFilesOnly',
'retentionIgnoreThreads',
'retentionOverrideGlobal',
'encrypted',
'favorite',
];
const validate = <TRoomSetting extends keyof RoomSettings>(
setting: TRoomSetting,
params: {
userId: IUser['_id'];
value: RoomSettings[TRoomSetting];
room: IRoom;
rid: IRoom['_id'];
},
) => {
const validator = validators[setting];
return validator?.(params);
};
async function save<TRoomSetting extends keyof RoomSettings>(
setting: TRoomSetting,
params: {
userId: IUser['_id'];
user: RequiredField<IUser, 'username' | 'name'>;
value: RoomSettings[TRoomSetting];
room: IRoom;
rid: IRoom['_id'];
},
) {
const saver = settingSavers[setting];
await saver?.(params);
}
export async function saveRoomSettings(
userId: IUser['_id'],
rid: IRoom['_id'],
settings: Partial<RoomSettings>,
): Promise<{ result: true; rid: IRoom['_id'] }>;
export async function saveRoomSettings<RoomSettingName extends keyof RoomSettings>(
userId: IUser['_id'],
rid: IRoom['_id'],
setting: RoomSettingName,
value: RoomSettings[RoomSettingName],
): Promise<{ result: true; rid: IRoom['_id'] }>;
export async function saveRoomSettings(
userId: IUser['_id'],
rid: IRoom['_id'],
settings: Partial<RoomSettings> | keyof RoomSettings,
value?: RoomSettings[keyof RoomSettings],
): Promise<{ result: true; rid: IRoom['_id'] }> {
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
function: 'RocketChat.saveRoomName',
});
}
if (!Match.test(rid, String)) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'saveRoomSettings',
});
}
if (typeof settings !== 'object') {
settings = {
[settings]: value,
};
}
if (!Object.keys(settings).every((key) => fields.includes(key as keyof typeof settings))) {
throw new Meteor.Error('error-invalid-settings', 'Invalid settings provided', {
method: 'saveRoomSettings',
});
}
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'saveRoomSettings',
});
}
if (!(await hasPermissionAsync(userId, 'edit-room', rid))) {
if (!(Object.keys(settings).includes('encrypted') && room.t === 'd')) {
throw new Meteor.Error('error-action-not-allowed', 'Editing room is not allowed', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
settings = { encrypted: settings.encrypted };
}
if (room.broadcast && (settings.readOnly || settings.reactWhenReadOnly)) {
throw new Meteor.Error('error-action-not-allowed', 'Editing readOnly/reactWhenReadOnly are not allowed for broadcast rooms', {
method: 'saveRoomSettings',
action: 'Editing_room',
});
}
const user = await Users.findOneById(userId, { projection: { username: 1, name: 1 } });
if (!user) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'saveRoomSettings',
});
}
// validations
for (const setting of Object.keys(settings) as (keyof RoomSettings)[]) {
await validate(setting, {
userId,
value: settings[setting],
room,
rid,
});
if (setting === 'retentionOverrideGlobal' && settings.retentionOverrideGlobal === false) {
delete settings.retentionMaxAge;
delete settings.retentionExcludePinned;
delete settings.retentionFilesOnly;
delete settings.retentionIgnoreThreads;
}
}
// saving data
for (const setting of Object.keys(settings) as (keyof RoomSettings)[]) {
await save(setting, {
userId,
user: user as RequiredField<IUser, 'username' | 'name'>,
value: settings[setting],
room,
rid,
});
}
void notifyOnRoomChangedById(rid);
return {
result: true,
rid: room._id,
};
}
Meteor.methods<ServerMethods>({
saveRoomSettings: (...args) => {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
function: 'RocketChat.saveRoomName',
});
}
return saveRoomSettings(userId, ...args);
},
});

View File

@@ -0,0 +1,47 @@
import type { IRoom } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Subscriptions } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { notifyOnSubscriptionChangedByRoomIdAndUserId } from '../../lib/notifyListener';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
toggleFavorite(rid: IRoom['_id'], favorite?: boolean): Promise<number>;
}
}
export const toggleFavoriteMethod = async (userId: string, rid: IRoom['_id'], favorite?: boolean): Promise<number> => {
const userSubscription = await Subscriptions.findOneByRoomIdAndUserId(rid, userId);
if (!userSubscription) {
throw new Meteor.Error('error-invalid-subscription', 'You must be part of a room to favorite it', { method: 'toggleFavorite' });
}
const { modifiedCount } = await Subscriptions.setFavoriteByRoomIdAndUserId(rid, userId, favorite);
if (modifiedCount) {
void notifyOnSubscriptionChangedByRoomIdAndUserId(rid, userId);
}
return modifiedCount;
};
Meteor.methods<ServerMethods>({
async toggleFavorite(rid, favorite) {
methodDeprecationLogger.method('toggleFavorite', '9.0.0', '/v1/rooms.favorite');
check(rid, String);
check(favorite, Match.Optional(Boolean));
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'toggleFavorite',
});
}
return toggleFavoriteMethod(userId, rid, favorite);
},
});

View File

@@ -0,0 +1,50 @@
import { isRegisterUser } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { Users, Rooms } from '@rocket.chat/models';
import { check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { methodDeprecationLogger } from '../../lib/deprecationWarningLogger';
import { unarchiveRoom } from '../../lib/rooms/unarchiveRoom';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
unarchiveRoom(rid: string): Promise<void>;
}
}
export const executeUnarchiveRoom = async (userId: string, rid: string) => {
check(rid, String);
const user = await Users.findOneById(userId, { projection: { username: 1, name: 1 } });
if (!user || !isRegisterUser(user)) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'archiveRoom' });
}
const room = await Rooms.findOneById(rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', { method: 'unarchiveRoom' });
}
if (!(await hasPermissionAsync(userId, 'unarchive-room', room._id))) {
throw new Meteor.Error('error-not-authorized', 'Not authorized', { method: 'unarchiveRoom' });
}
return unarchiveRoom(rid, user);
};
Meteor.methods<ServerMethods>({
async unarchiveRoom(rid) {
methodDeprecationLogger.method('unarchiveRoom', '9.0.0', '/v1/channels.unarchive');
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'unarchiveRoom' });
}
return executeUnarchiveRoom(userId, rid);
},
});

View File

@@ -0,0 +1,81 @@
import { Message } from '@rocket.chat/core-services';
import type { IRoom } from '@rocket.chat/core-typings';
import { Rooms, Subscriptions, Users } from '@rocket.chat/models';
import { Meteor } from 'meteor/meteor';
import { RoomMemberActions } from '../../../definition/IRoomTypeConfig';
import { hasPermissionAsync } from '../../lib/authorization/hasPermission';
import { callbacks } from '../../lib/callbacks';
import { notifyOnRoomChangedById } from '../../lib/notifyListener';
import { roomCoordinator } from '../../lib/rooms/roomCoordinator';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
unmuteUserInRoom(data: { rid: IRoom['_id']; username: string }): boolean;
}
}
export const unmuteUserInRoom = async (fromId: string, data: { rid: IRoom['_id']; username: string }): Promise<boolean> => {
if (!fromId || !(await hasPermissionAsync(fromId, 'mute-user', data.rid))) {
throw new Meteor.Error('error-not-allowed', 'Not allowed', {
method: 'unmuteUserInRoom',
});
}
const room = await Rooms.findOneById(data.rid);
if (!room) {
throw new Meteor.Error('error-invalid-room', 'Invalid room', {
method: 'unmuteUserInRoom',
});
}
if (!(await roomCoordinator.getRoomDirectives(room.t).allowMemberAction(room, RoomMemberActions.MUTE, fromId))) {
throw new Meteor.Error('error-invalid-room-type', `${room.t} is not a valid room type`, {
method: 'unmuteUserInRoom',
type: room.t,
});
}
const subscription = await Subscriptions.findOneByRoomIdAndUsername(data.rid, data.username, {
projection: { _id: 1 },
});
if (!subscription) {
throw new Meteor.Error('error-user-not-in-room', 'User is not in this room', {
method: 'unmuteUserInRoom',
});
}
const unmutedUser = await Users.findOneByUsernameIgnoringCase(data.username);
if (!unmutedUser?.username) {
throw new Meteor.Error('error-invalid-user', 'Invalid user to unmute', {
method: 'unmuteUserInRoom',
});
}
const fromUser = await Users.findOneById(fromId);
if (!fromUser) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', {
method: 'unmuteUserInRoom',
});
}
await callbacks.run('beforeUnmuteUser', { unmutedUser, fromUser }, room);
if (room.ro) {
await Rooms.unmuteReadOnlyUsernameByRoomId(data.rid, unmutedUser.username);
} else {
await Rooms.unmuteMutedUsernameByRoomId(data.rid, unmutedUser.username);
}
await Message.saveSystemMessage('user-unmuted', data.rid, unmutedUser.username, fromUser);
setImmediate(() => {
void callbacks.run('afterUnmuteUser', { unmutedUser, fromUser }, room);
void notifyOnRoomChangedById(data.rid);
});
return true;
};