Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { ReadReceipt } from '@rocket.chat/core-typings';
import type { IReadReceiptWithUser } from '@rocket.chat/core-typings';
import { Box } from '@rocket.chat/fuselage';
import { UserAvatar } from '@rocket.chat/ui-avatar';
import { useUserDisplayName } from '@rocket.chat/ui-client';
import type { ReactElement } from 'react';

import { useFormatDateAndTime } from '../../../../hooks/useFormatDateAndTime';

const ReadReceiptRow = ({ user, ts }: ReadReceipt): ReactElement => {
const ReadReceiptRow = ({ user, ts }: IReadReceiptWithUser): ReactElement => {
const displayName = useUserDisplayName(user || {});
const formatDateAndTime = useFormatDateAndTime({ withSeconds: true });

Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/definition/IRoomTypeConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type {
RoomType,
IUser,
IMessage,
ReadReceipt,
IReadReceipt,
ValueOf,
AtLeast,
ISubscription,
Expand Down Expand Up @@ -106,7 +106,7 @@ export interface IRoomTypeServerDirectives {
) => Promise<{ title: string | undefined; text: string; name: string | undefined }>;
getMsgSender: (message: IMessage) => Promise<IUser | null>;
includeInRoomSearch: () => boolean;
getReadReceiptsExtraData: (message: IMessage) => Partial<ReadReceipt>;
getReadReceiptsExtraData: (message: IMessage) => Partial<IReadReceipt>;
includeInDashboard: () => boolean;
roomFind?: (rid: string) => Promise<IRoom | undefined> | Promise<IOmnichannelRoom | null> | IRoom | undefined;
}
4 changes: 2 additions & 2 deletions apps/meteor/ee/server/api/chat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { IMessage, ReadReceipt } from '@rocket.chat/core-typings';
import type { IMessage, IReadReceiptWithUser } from '@rocket.chat/core-typings';
import { License } from '@rocket.chat/license';
import { Meteor } from 'meteor/meteor';

Expand All @@ -14,7 +14,7 @@ declare module '@rocket.chat/rest-typings' {
interface Endpoints {
'/v1/chat.getMessageReadReceipts': {
GET: (params: GetMessageReadReceiptsProps) => {
receipts: ReadReceipt[];
receipts: IReadReceiptWithUser[];
};
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { api } from '@rocket.chat/core-services';
import type { IMessage, IRoom, IReadReceipt, IReadReceiptWithUser } from '@rocket.chat/core-typings';
import { LivechatVisitors, ReadReceipts, Messages, Rooms, Subscriptions, Users } from '@rocket.chat/models';
import { Random } from '@rocket.chat/random';

Expand All @@ -8,21 +9,21 @@ import { SystemLogger } from '../../../../server/lib/logger/system';
import { roomCoordinator } from '../../../../server/lib/rooms/roomCoordinator';

// debounced function by roomId, so multiple calls within 2 seconds to same roomId runs only once
const list = {};
const debounceByRoomId = function (fn) {
return function (roomId, ...args) {
clearTimeout(list[roomId]);
list[roomId] = setTimeout(() => {
fn.call(this, roomId, ...args);
delete list[roomId];
const list: Record<string, NodeJS.Timeout> = {};
const debounceByRoomId = function (fn: (room: IRoom) => Promise<void>) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to your changes, but this debounce here may cause some inconsistencies regarding which messages are flagged as read or not when new messages keep coming in after the first debounced call.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pierre-lehnen-rc why do you think that? BTW the debounce was not receiving the expected data anyways

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't look at the whole process to see how it works and whether this is an actual problem or not, but:

Messages.setVisibleMessagesAsRead will update all unread messages in a room at the time it is executed, which due to the debounce will be at least 2 seconds after the call to 'subscriptions.read'. During this 2 second window, new messages may have been added to the collection - those new messages will also be flagged as read by the process that was scheduled before they were sent.

return function (this: unknown, room: IRoom) {
clearTimeout(list[room._id]);
list[room._id] = setTimeout(() => {
void fn.call(this, room);
delete list[room._id];
}, 2000);
};
};

const updateMessages = debounceByRoomId(async ({ _id, lm }) => {
const updateMessages = debounceByRoomId(async ({ _id, lm }: IRoom) => {
// @TODO maybe store firstSubscription in room object so we don't need to call the above update method
const firstSubscription = await Subscriptions.getMinimumLastSeenByRoomId(_id);
if (!firstSubscription || !firstSubscription.ls) {
if (!firstSubscription?.ls) {
return;
}

Expand All @@ -31,31 +32,37 @@ const updateMessages = debounceByRoomId(async ({ _id, lm }) => {
void api.broadcast('notify.messagesRead', { rid: _id, until: firstSubscription.ls });
}

if (lm <= firstSubscription.ls) {
if (lm && lm <= firstSubscription.ls) {
await Rooms.setLastMessageAsRead(_id);
void notifyOnRoomChangedById(_id);
}
});

export const ReadReceipt = {
async markMessagesAsRead(roomId, userId, userLastSeen) {
class ReadReceiptClass {
async markMessagesAsRead(roomId: string, userId: string, userLastSeen: Date) {
if (!settings.get('Message_Read_Receipt_Enabled')) {
return;
}

const room = await Rooms.findOneById(roomId, { projection: { lm: 1 } });

// if users last seen is greater than room's last message, it means the user already have this room marked as read
if (!room || userLastSeen > room.lm) {
if (!room || (room.lm && userLastSeen > room.lm)) {
return;
}

this.storeReadReceipts(await Messages.findVisibleUnreadMessagesByRoomAndDate(roomId, userLastSeen).toArray(), roomId, userId);
void this.storeReadReceipts(
() => {
return Messages.findVisibleUnreadMessagesByRoomAndDate(roomId, userLastSeen).toArray();
},
roomId,
userId,
);

await updateMessages(room);
},
updateMessages(room);
}

async markMessageAsReadBySender(message, { _id: roomId, t }, userId) {
async markMessageAsReadBySender(message: IMessage, { _id: roomId, t }: { _id: string; t: string }, userId: string) {
if (!settings.get('Message_Read_Receipt_Enabled')) {
return;
}
Expand All @@ -76,28 +83,46 @@ export const ReadReceipt = {
}

const extraData = roomCoordinator.getRoomDirectives(t).getReadReceiptsExtraData(message);
this.storeReadReceipts([message], roomId, userId, extraData);
},
void this.storeReadReceipts(
() => {
return Promise.resolve([message]);
},
roomId,
userId,
extraData,
);
}

async storeThreadMessagesReadReceipts(tmid, userId, userLastSeen) {
async storeThreadMessagesReadReceipts(tmid: string, userId: string, userLastSeen: Date) {
if (!settings.get('Message_Read_Receipt_Enabled')) {
return;
}

const message = await Messages.findOneById(tmid, { projection: { tlm: 1, rid: 1 } });

// if users last seen is greater than thread's last message, it means the user has already marked this thread as read
if (!message || userLastSeen > message.tlm) {
if (!message || (message.tlm && userLastSeen > message.tlm)) {
return;
}

this.storeReadReceipts(await Messages.findUnreadThreadMessagesByDate(tmid, userId, userLastSeen).toArray(), message.rid, userId);
},
void this.storeReadReceipts(
() => {
return Messages.findUnreadThreadMessagesByDate(message.rid, tmid, userId, userLastSeen).toArray();
},
message.rid,
userId,
);
}

async storeReadReceipts(messages, roomId, userId, extraData = {}) {
private async storeReadReceipts(
getMessages: () => Promise<Pick<IMessage, '_id' | 't' | 'pinned' | 'drid' | 'tmid'>[]>,
Comment thread
rodrigok marked this conversation as resolved.
roomId: string,
userId: string,
extraData: Partial<IReadReceipt> = {},
) {
Comment on lines +117 to +122

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Constrain extraData to prevent core field override.

extraData is typed as Partial<IReadReceipt>, allowing callers to override critical fields like _id, roomId, userId, messageId, and ts at Line 135. This could lead to data corruption or inconsistencies.

Based on the codebase usage (Line 85 passes data from getReadReceiptsExtraData), only the token field should be allowed in extraData.

Apply this diff to restrict extraData to safe fields:

 	private async storeReadReceipts(
 		getMessages: () => Promise<Pick<IMessage, '_id' | 't' | 'pinned' | 'drid' | 'tmid'>[]>,
 		roomId: string,
 		userId: string,
-		extraData: Partial<IReadReceipt> = {},
+		extraData: Pick<IReadReceipt, 'token'> | Record<string, never> = {},
 	) {

Or more permissively, exclude core fields:

-		extraData: Partial<IReadReceipt> = {},
+		extraData: Omit<Partial<IReadReceipt>, '_id' | 'roomId' | 'userId' | 'messageId' | 'ts'> = {},

Also applies to: 135-135

🤖 Prompt for AI Agents
In apps/meteor/ee/server/lib/message-read-receipt/ReadReceipt.ts around lines
117 to 122 (and also affecting line 135), extraData is currently typed as
Partial<IReadReceipt> which allows callers to override core fields (_id, roomId,
userId, messageId, ts) and can corrupt data; change the type to only allow safe
fields (e.g., { token?: string }) or use Omit<IReadReceipt, '_id' | 'roomId' |
'userId' | 'messageId' | 'ts'> so callers cannot supply or override those core
fields, and update any related call sites if necessary to satisfy the new
narrower type.

if (settings.get('Message_Read_Receipt_Store_Users')) {
const ts = new Date();
const receipts = messages.map((message) => ({
const receipts = (await getMessages()).map((message) => ({
_id: Random.id(),
roomId,
userId,
Expand All @@ -120,18 +145,20 @@ export const ReadReceipt = {
SystemLogger.error({ msg: 'Error inserting read receipts per user', err });
}
}
},
}

async getReceipts(message) {
async getReceipts(message: Pick<IMessage, '_id'>): Promise<IReadReceiptWithUser[]> {
const receipts = await ReadReceipts.findByMessageId(message._id).toArray();

return Promise.all(
receipts.map(async (receipt) => ({
...receipt,
user: receipt.token
user: (receipt.token
? await LivechatVisitors.getVisitorByToken(receipt.token, { projection: { username: 1, name: 1 } })
: await Users.findOneById(receipt.userId, { projection: { username: 1, name: 1 } }),
: await Users.findOneById(receipt.userId, { projection: { username: 1, name: 1, token: 1 } })) as IReadReceiptWithUser['user'],
})),
);
},
};
}
}

export const ReadReceipt = new ReadReceiptClass();
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export class MessageReadsService extends ServiceClassInternal implements IMessag

const firstRead = await MessageReads.getMinimumLastSeenByThreadId(tmid);
if (firstRead?.ls) {
const result = await Messages.setThreadMessagesAsRead(tmid, firstRead.ls);
const result = await Messages.setThreadMessagesAsRead(threadMessage.rid, tmid, firstRead.ls);
if (result.modifiedCount > 0) {
void api.broadcast('notify.messagesRead', { rid: threadMessage.rid, tmid, until: firstRead.ls });
}
Expand Down
6 changes: 3 additions & 3 deletions apps/meteor/ee/server/methods/getReadReceipts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ReadReceipt as ReadReceiptType, IMessage } from '@rocket.chat/core-typings';
import type { IReadReceiptWithUser, IMessage } from '@rocket.chat/core-typings';
import type { ServerMethods } from '@rocket.chat/ddp-client';
import { License } from '@rocket.chat/license';
import { Messages } from '@rocket.chat/models';
Expand All @@ -11,11 +11,11 @@ import { ReadReceipt } from '../lib/message-read-receipt/ReadReceipt';
declare module '@rocket.chat/ddp-client' {
// eslint-disable-next-line @typescript-eslint/naming-convention
interface ServerMethods {
getReadReceipts(options: { messageId: IMessage['_id'] }): ReadReceiptType[];
getReadReceipts(options: { messageId: IMessage['_id'] }): IReadReceiptWithUser[];
}
}

export const getReadReceiptsFunction = async function (messageId: IMessage['_id'], userId: string): Promise<ReadReceiptType[]> {
export const getReadReceiptsFunction = async function (messageId: IMessage['_id'], userId: string): Promise<IReadReceiptWithUser[]> {
if (!License.hasModule('message-read-receipt')) {
throw new Meteor.Error('error-action-not-allowed', 'This is an enterprise feature', { method: 'getReadReceipts' });
}
Expand Down
15 changes: 7 additions & 8 deletions apps/meteor/ee/server/models/raw/ReadReceipts.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import type { IUser, IMessage, ReadReceipt, RocketChatRecordDeleted } from '@rocket.chat/core-typings';
import type { IUser, IMessage, IReadReceipt, RocketChatRecordDeleted } from '@rocket.chat/core-typings';
import type { IReadReceiptsModel } from '@rocket.chat/model-typings';
import { BaseRaw } from '@rocket.chat/models';
import type { Collection, FindCursor, Db, IndexDescription, DeleteResult, Filter, UpdateResult, Document } from 'mongodb';

import { otrSystemMessages } from '../../../../app/otr/lib/constants';

export class ReadReceiptsRaw extends BaseRaw<ReadReceipt> implements IReadReceiptsModel {
constructor(db: Db, trash?: Collection<RocketChatRecordDeleted<ReadReceipt>>) {
export class ReadReceiptsRaw extends BaseRaw<IReadReceipt> implements IReadReceiptsModel {
constructor(db: Db, trash?: Collection<RocketChatRecordDeleted<IReadReceipt>>) {
super(db, 'read_receipts', trash);
}

protected modelIndexes(): IndexDescription[] {
return [{ key: { roomId: 1, userId: 1, messageId: 1 }, unique: true }, { key: { messageId: 1 } }, { key: { userId: 1 } }];
}

findByMessageId(messageId: string): FindCursor<ReadReceipt> {
findByMessageId(messageId: string): FindCursor<IReadReceipt> {
return this.find({ messageId });
}

Expand All @@ -39,7 +39,7 @@ export class ReadReceiptsRaw extends BaseRaw<ReadReceipt> implements IReadReceip
}

removeOTRReceiptsUntilDate(roomId: string, until: Date): Promise<DeleteResult> {
const query = {
return this.col.deleteMany({
roomId,
t: {
$in: [
Expand All @@ -50,8 +50,7 @@ export class ReadReceiptsRaw extends BaseRaw<ReadReceipt> implements IReadReceip
],
},
ts: { $lte: until },
};
return this.col.deleteMany(query);
});
}

async removeByIdPinnedTimestampLimitAndUsers(
Expand All @@ -62,7 +61,7 @@ export class ReadReceiptsRaw extends BaseRaw<ReadReceipt> implements IReadReceip
users: IUser['_id'][],
ignoreThreads: boolean,
): Promise<DeleteResult> {
const query: Filter<ReadReceipt> = {
const query: Filter<IReadReceipt> = {
roomId,
ts,
};
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/server/lib/rooms/roomCoordinator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { getUserDisplayName } from '@rocket.chat/core-typings';
import type { IRoom, RoomType, IUser, IMessage, ReadReceipt, ValueOf, AtLeast } from '@rocket.chat/core-typings';
import type { IRoom, RoomType, IUser, IMessage, IReadReceipt, ValueOf, AtLeast } from '@rocket.chat/core-typings';
import { Users } from '@rocket.chat/models';

import { settings } from '../../../app/settings/server';
Expand Down Expand Up @@ -56,7 +56,7 @@ class RoomCoordinatorServer extends RoomCoordinator {
includeInRoomSearch(): boolean {
return false;
},
getReadReceiptsExtraData(_message: IMessage): Partial<ReadReceipt> {
getReadReceiptsExtraData(_message: IMessage): Partial<IReadReceipt> {
return {};
},
includeInDashboard(): boolean {
Expand Down
20 changes: 20 additions & 0 deletions packages/core-typings/src/IReadReceipt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import type { IMessage } from './IMessage/IMessage';
import type { IRoom } from './IRoom';
import type { IUser } from './IUser';

export type IReadReceipt = {
token?: string;
messageId: IMessage['_id'];
roomId: IRoom['_id'];
ts: Date;
t?: IMessage['t'];
pinned?: IMessage['pinned'];
drid?: IMessage['drid'];
tmid?: IMessage['tmid'];
userId: IUser['_id'];
_id: string;
};

export type IReadReceiptWithUser = IReadReceipt & {
user?: Pick<IUser, '_id' | 'name' | 'username'> | undefined;
};
13 changes: 0 additions & 13 deletions packages/core-typings/src/ReadReceipt.ts

This file was deleted.

2 changes: 1 addition & 1 deletion packages/core-typings/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export * from './IAvatar';
export * from './ICustomUserStatus';
export * from './IEmailMessageHistory';

export * from './ReadReceipt';
export * from './IReadReceipt';
export * from './MessageReads';
export * from './IUpload';
export * from './IOEmbedCache';
Expand Down
3 changes: 2 additions & 1 deletion packages/model-typings/src/models/IMessagesModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,10 +274,11 @@ export interface IMessagesModel extends IBaseModel<IMessage> {
setVisibleMessagesAsRead(rid: string, until: Date): Promise<UpdateResult | Document>;
getMessageByFileIdAndUsername(fileID: string, userId: string): Promise<IMessage | null>;
getMessageByFileId(fileID: string): Promise<IMessage | null>;
setThreadMessagesAsRead(tmid: string, until: Date): Promise<UpdateResult | Document>;
setThreadMessagesAsRead(rid: string, tmid: string, until: Date): Promise<UpdateResult | Document>;
updateRepliesByThreadId(tmid: string, replies: string[], ts: Date): Promise<UpdateResult>;
refreshDiscussionMetadata(room: Pick<IRoom, '_id' | 'msgs' | 'lm'>): Promise<null | WithId<IMessage>>;
findUnreadThreadMessagesByDate(
rid: string,
tmid: string,
userId: string,
after: Date,
Expand Down
6 changes: 3 additions & 3 deletions packages/model-typings/src/models/IReadReceiptsModel.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import type { ReadReceipt, IUser, IMessage } from '@rocket.chat/core-typings';
import type { IReadReceipt, IUser, IMessage } from '@rocket.chat/core-typings';
import type { FindCursor, DeleteResult, UpdateResult, Document, Filter } from 'mongodb';

import type { IBaseModel } from './IBaseModel';

export interface IReadReceiptsModel extends IBaseModel<ReadReceipt> {
findByMessageId(messageId: string): FindCursor<ReadReceipt>;
export interface IReadReceiptsModel extends IBaseModel<IReadReceipt> {
findByMessageId(messageId: string): FindCursor<IReadReceipt>;
removeByUserId(userId: string): Promise<DeleteResult>;
removeByRoomId(roomId: string): Promise<DeleteResult>;
removeByRoomIds(roomIds: string[]): Promise<DeleteResult>;
Expand Down
Loading
Loading