-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathsendMessage.ts
More file actions
297 lines (251 loc) · 7.8 KB
/
sendMessage.ts
File metadata and controls
297 lines (251 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { Apps } from '@rocket.chat/apps';
import { Message } from '@rocket.chat/core-services';
import type { IMessage, IRoom } from '@rocket.chat/core-typings';
import { Messages } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';
import { parseUrlsInMessage } from './parseUrlsInMessage';
import { isRelativeURL } from '../../../../lib/utils/isRelativeURL';
import { isURL } from '../../../../lib/utils/isURL';
import { hasPermissionAsync } from '../../../authorization/server/functions/hasPermission';
import { FileUpload } from '../../../file-upload/server';
import { settings } from '../../../settings/server';
import { afterSaveMessage } from '../lib/afterSaveMessage';
import { notifyOnRoomChangedById, notifyOnMessageChange } from '../lib/notifyListener';
import { validateCustomMessageFields } from '../lib/validateCustomMessageFields';
// TODO: most of the types here are wrong, but I don't want to change them now
/**
* IMPORTANT
*
* This validator prevents malicious href values
* intending to run arbitrary js code in anchor tags.
* You should use it whenever the value you're checking
* is going to be rendered in the href attribute of a
* link.
*/
const validFullURLParam = Match.Where((value) => {
check(value, String);
if (!isURL(value) && !value.startsWith(FileUpload.getPath())) {
throw new Error('Invalid href value provided');
}
if (/^javascript:/i.test(value)) {
throw new Error('Invalid href value provided');
}
return true;
});
const validPartialURLParam = Match.Where((value) => {
check(value, String);
if (!isRelativeURL(value) && !isURL(value) && !value.startsWith(FileUpload.getPath())) {
throw new Error('Invalid href value provided');
}
if (/^javascript:/i.test(value)) {
throw new Error('Invalid href value provided');
}
return true;
});
const objectMaybeIncluding = (types: any) =>
Match.Where((value: any) => {
Object.keys(types).forEach((field) => {
if (value[field] != null) {
try {
check(value[field], types[field]);
} catch (error: any) {
error.path = field;
throw error;
}
}
});
return true;
});
const validateAttachmentsFields = (attachmentField: any) => {
check(
attachmentField,
objectMaybeIncluding({
short: Boolean,
title: String,
value: Match.OneOf(String, Number, Boolean),
}),
);
if (!attachmentField.value || !attachmentField.title) {
throw new Error('Invalid attachment field, title and value is required');
}
};
const validateAttachmentsActions = (attachmentActions: any) => {
check(
attachmentActions,
objectMaybeIncluding({
type: String,
text: String,
url: validFullURLParam,
image_url: validFullURLParam,
is_webview: Boolean,
webview_height_ratio: String,
msg: String,
msg_in_chat_window: Boolean,
}),
);
};
const validateAttachment = (attachment: any) => {
check(
attachment,
objectMaybeIncluding({
color: String,
text: String,
ts: Match.OneOf(String, Number),
thumb_url: validFullURLParam,
button_alignment: String,
actions: [Match.Any],
message_link: validFullURLParam,
collapsed: Boolean,
author_name: String,
author_link: validFullURLParam,
author_icon: validFullURLParam,
title: String,
title_link: validFullURLParam,
title_link_download: Boolean,
image_dimensions: Object,
image_url: validFullURLParam,
image_preview: String,
image_type: String,
image_size: Number,
audio_url: validFullURLParam,
audio_type: String,
audio_size: Number,
video_url: validFullURLParam,
video_type: String,
video_size: Number,
fields: [Match.Any],
}),
);
if (attachment.fields?.length) {
attachment.fields.map(validateAttachmentsFields);
}
if (attachment.actions?.length) {
attachment.actions.map(validateAttachmentsActions);
}
};
const validateBodyAttachments = (attachments: any[]) => attachments.map(validateAttachment);
export const validateMessage = async (message: any, room: any, user: any) => {
check(
message,
objectMaybeIncluding({
_id: String,
msg: String,
text: String,
alias: String,
emoji: String,
tmid: String,
tshow: Boolean,
avatar: validPartialURLParam,
attachments: [Match.Any],
blocks: [Match.Any],
}),
);
if (message.alias || message.avatar) {
const isLiveChatGuest = !message.avatar && user.token && user.token === room.v?.token;
if (!isLiveChatGuest && !(await hasPermissionAsync(user._id, 'message-impersonate', room._id))) {
throw new Error('Not enough permission');
}
}
if (Array.isArray(message.attachments) && message.attachments.length) {
validateBodyAttachments(message.attachments);
}
if (message.customFields) {
validateCustomMessageFields({
customFields: message.customFields,
messageCustomFieldsEnabled: settings.get<boolean>('Message_CustomFields_Enabled'),
messageCustomFields: settings.get<string>('Message_CustomFields'),
});
}
};
export function prepareMessageObject(
message: Partial<IMessage>,
rid: IRoom['_id'],
user: { _id: string; username?: string; name?: string },
): asserts message is IMessage {
if (!message.ts) {
message.ts = new Date();
}
if (message.tshow !== true) {
delete message.tshow;
}
const { _id, username, name } = user;
message.u = {
_id,
username: username as string, // FIXME: this is wrong but I don't want to change it now
name,
};
message.rid = rid;
if (!Match.test(message.msg, String)) {
message.msg = '';
}
if (message.ts == null) {
message.ts = new Date();
}
}
/**
* Validates and sends the message object. This function does not verify the Message_MaxAllowedSize settings.
* Caller of the function should verify the Message_MaxAllowedSize if needed.
* There might be same use cases which needs to override this setting. Example - sending error logs.
*/
export const sendMessage = async function (user: any, message: any, room: any, upsert = false, previewUrls?: string[]) {
if (!user || !message || !room._id) {
return false;
}
await validateMessage(message, room, user);
prepareMessageObject(message, room._id, user);
if (settings.get('Message_Read_Receipt_Enabled')) {
message.unread = true;
}
// For the Rocket.Chat Apps :)
if (Apps.self?.isLoaded()) {
const listenerBridge = Apps.getBridges()?.getListenerBridge();
const prevent = await listenerBridge?.messageEvent('IPreMessageSentPrevent', message);
if (prevent) {
return;
}
const result = await listenerBridge?.messageEvent(
'IPreMessageSentModify',
await listenerBridge?.messageEvent('IPreMessageSentExtend', message),
);
if (typeof result === 'object') {
message = Object.assign(message, result);
// Some app may have inserted malicious/invalid values in the message, let's check it again
await validateMessage(message, room, user);
}
}
parseUrlsInMessage(message, previewUrls);
message = await Message.beforeSave({ message, room, user });
if (!message) {
return;
}
if (message._id && upsert) {
const { _id } = message;
delete message._id;
await Messages.updateOne(
{
_id,
'u._id': message.u._id,
},
{ $set: message },
{ upsert: true },
);
message._id = _id;
} else {
const messageAlreadyExists = message._id && (await Messages.findOneById(message._id, { projection: { _id: 1 } }));
if (messageAlreadyExists) {
return;
}
const { insertedId } = await Messages.insertOne(message);
message._id = insertedId;
}
if (Apps.self?.isLoaded()) {
// If the message has a type (system message), we should notify the listener about it
const messageEvent = message.t ? 'IPostSystemMessageSent' : 'IPostMessageSent';
void Apps.getBridges()?.getListenerBridge().messageEvent(messageEvent, message);
}
// TODO: is there an opportunity to send returned data to notifyOnMessageChange?
await afterSaveMessage(message, room, user);
void notifyOnMessageChange({ id: message._id });
void notifyOnRoomChangedById(message.rid);
return message;
};