-
-
Notifications
You must be signed in to change notification settings - Fork 273
/
Copy pathsubmit.js
798 lines (715 loc) · 42.2 KB
/
submit.js
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
'use strict';
const config = require('wild-config');
const log = require('npmlog');
const libmime = require('libmime');
const util = require('util');
const MailComposer = require('nodemailer/lib/mail-composer');
const { htmlToText } = require('html-to-text');
const Joi = require('joi');
const ObjectId = require('mongodb').ObjectId;
const tools = require('../tools');
const Maildropper = require('../maildropper');
const roles = require('../roles');
const Transform = require('stream').Transform;
const { sessSchema, sessIPSchema, booleanSchema, metaDataSchema } = require('../schemas');
const { preprocessAttachments } = require('../data-url');
const { userId, mailboxId } = require('../schemas/request/general-schemas');
const { AddressOptionalName, AddressOptionalNameArray, Header, ReferenceWithoutAttachments } = require('../schemas/request/messages-schemas');
const { successRes } = require('../schemas/response/general-schemas');
class StreamCollect extends Transform {
constructor() {
super();
this.chunks = [];
this.chunklen = 0;
}
_transform(chunk, encoding, done) {
this.chunks.push(chunk);
this.chunklen += chunk.length;
this.push(chunk);
done();
}
}
module.exports = (db, server, messageHandler, userHandler, settingsHandler) => {
let maildrop = new Maildropper({
db,
zone: config.sender.zone,
collection: config.sender.collection,
gfs: config.sender.gfs,
loopSecret: config.sender.loopSecret
});
function submitMessage(options, callback) {
let user = options.user;
db.users.collection('users').findOne(
{ _id: user },
{
projection: {
username: true,
name: true,
address: true,
quota: true,
storageUsed: true,
recipients: true,
encryptMessages: true,
pubKey: true,
disabled: true,
suspended: true,
fromWhitelist: true,
mtaRelay: true
}
},
(err, userData) => {
if (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
return callback(err);
}
if (!userData) {
err = new Error('This user does not exist');
err.responseCode = 404;
err.code = 'UserNotFound';
return callback();
}
if (userData.disabled || userData.suspended) {
err = new Error('User account is disabled');
err.responseCode = 403;
err.code = 'UserDisabled';
return callback(err);
}
settingsHandler
.getMulti(['const:max:storage', 'const:max:recipients', 'const:max:forwards'])
.then(settings => {
let overQuota = Number(userData.quota || settings['const:max:storage']) - userData.storageUsed <= 0;
let maxRecipients = userData.recipients || config.maxRecipients || settings['const:max:recipients'];
let getReferencedMessage = done => {
if (!options.reference) {
return done(null, false);
}
let query = {};
if (typeof options.reference === 'object') {
query.mailbox = options.reference.mailbox;
query.uid = options.reference.id;
} else {
return done(null, false);
}
query.user = user;
let getMessage = next => {
let updateable = ['reply', 'replyAll', 'forward'];
if (!options.reference || !updateable.includes(options.reference.action)) {
return db.database.collection('messages').findOne(
query,
{
projection: {
'mimeTree.parsedHeader': true,
thread: true
}
},
next
);
}
let $addToSet = {};
switch (options.reference.action) {
case 'reply':
case 'replyAll':
$addToSet.flags = '\\Answered';
break;
case 'forward':
$addToSet.flags = { $each: ['\\Answered', '$Forwarded'] };
break;
}
db.database.collection('messages').findOneAndUpdate(
query,
{
$addToSet
},
{
returnDocument: 'after',
projection: {
'mimeTree.parsedHeader': true,
uid: true,
flags: true,
thread: true
}
},
(err, r) => {
if (err) {
return next(err);
}
let messageData = r && r.value;
if (!messageData) {
return next(null, false);
}
let notifyEntries = [
{
command: 'FETCH',
uid: messageData.uid,
flags: messageData.flags,
message: messageData._id,
unseenChange: false
}
];
return messageHandler.notifier.addEntries(options.reference.mailbox, notifyEntries, () => {
messageHandler.notifier.fire(user);
return next(null, messageData);
});
}
);
};
getMessage((err, messageData) => {
if (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
return callback(err);
}
let headers = (messageData && messageData.mimeTree && messageData.mimeTree.parsedHeader) || {};
let subject = headers.subject || '';
try {
subject = libmime.decodeWords(subject).trim();
} catch (E) {
// failed to parse value
}
if (!/^\w+: /.test(subject)) {
subject = ((options.reference.action === 'forward' ? 'Fwd' : 'Re') + ': ' + subject).trim();
}
let sender = headers['reply-to'] || headers.from || headers.sender;
let replyTo = [];
let replyCc = [];
let uniqueRecipients = new Set();
let checkAddress = (target, addr) => {
let address = tools.normalizeAddress(addr.address);
if (address !== userData.address && !uniqueRecipients.has(address)) {
uniqueRecipients.add(address);
if (addr.name) {
try {
addr.name = libmime.decodeWords(addr.name).trim();
} catch (E) {
// failed to parse value
}
}
target.push(addr);
}
};
if (sender && sender.address) {
checkAddress(replyTo, sender);
}
if (options.reference.action === 'replyAll') {
[].concat(headers.to || []).forEach(addr => {
let walk = addr => {
if (addr.address) {
checkAddress(replyTo, addr);
} else if (addr.group) {
addr.group.forEach(walk);
}
};
walk(addr);
});
[].concat(headers.cc || []).forEach(addr => {
let walk = addr => {
if (addr.address) {
checkAddress(replyCc, addr);
} else if (addr.group) {
addr.group.forEach(walk);
}
};
walk(addr);
});
}
let messageId = (headers['message-id'] || '').trim();
let references = (headers.references || '')
.trim()
.replace(/\s+/g, ' ')
.split(' ')
.filter(mid => mid);
if (messageId && !references.includes(messageId)) {
references.unshift(messageId);
}
if (references.length > 50) {
references = references.slice(0, 50);
}
let referenceData = {
replyTo,
replyCc,
subject,
thread: messageData.thread,
inReplyTo: messageId,
references: references.join(' ')
};
return done(null, referenceData);
});
};
getReferencedMessage((err, referenceData) => {
if (err) {
return callback(err);
}
let envelope = options.envelope;
if (!envelope) {
envelope = {
from: options.from,
to: []
};
}
if (!envelope.from) {
if (options.from) {
envelope.from = options.from;
} else {
options.from = envelope.from = {
name: userData.name || '',
address: userData.address
};
}
}
options.from = options.from || envelope.from;
let validateFromAddress = (address, next) => {
if (options.uploadOnly) {
// message is not sent, so we do not care if address is valid or not
return next(null, address);
}
if (!address || address === userData.address) {
// using default address, ok
return next(null, userData.address);
}
if (userData.fromWhitelist && userData.fromWhitelist.length) {
if (
userData.fromWhitelist.some(addr => {
if (addr === address) {
return true;
}
if (addr.charAt(0) === '*' && address.indexOf(addr.substr(1)) >= 0) {
return true;
}
if (addr.charAt(addr.length - 1) === '*' && address.indexOf(addr.substr(0, addr.length - 1)) === 0) {
return true;
}
return false;
})
) {
// whitelisted address
return next(null, address);
}
}
userHandler.get(address, false, (err, resolvedUser) => {
if (err) {
return next(err);
}
if (!resolvedUser || resolvedUser._id.toString() !== userData._id.toString()) {
return next(null, userData.address);
}
return next(null, address);
});
};
// make sure that envelope address is allowed for current user
validateFromAddress(tools.normalizeAddress(envelope.from.address), (err, address) => {
if (err) {
return callback(err);
}
envelope.from.address = address;
// make sure that message header address is allowed for current user
validateFromAddress(tools.normalizeAddress(options.from.address), (err, address) => {
if (err) {
return callback(err);
}
options.from.address = address;
if (!envelope.to.length) {
envelope.to = envelope.to
.concat(options.to || [])
.concat(options.cc || [])
.concat(options.bcc || []);
if (!envelope.to.length && referenceData && ['reply', 'replyAll'].includes(options.reference.action)) {
envelope.to = envelope.to.concat(referenceData.replyTo || []).concat(referenceData.replyCc || []);
options.to = referenceData.replyTo;
options.cc = referenceData.replyCc;
}
}
let extraHeaders = [];
if (referenceData) {
if (['reply', 'replyAll'].includes(options.reference.action) && referenceData.inReplyTo) {
extraHeaders.push({ key: 'In-Reply-To', value: referenceData.inReplyTo });
}
if (referenceData.references) {
extraHeaders.push({ key: 'References', value: referenceData.references });
}
}
let now = new Date();
let sendTime = options.sendTime;
if (!sendTime || sendTime < now) {
sendTime = now;
}
let data = {
envelope,
from: options.from,
date: sendTime,
to: options.to || [],
cc: options.cc || [],
bcc: options.bcc || [],
subject: options.subject || (referenceData && referenceData.subject) || '',
text: options.text || '',
html: options.html || '',
headers: extraHeaders.concat(options.headers || []),
attachments: options.attachments || [],
disableFileAccess: true,
disableUrlAccess: true
};
// ensure plaintext content if html is provided
if (data.html && !data.text) {
try {
// might explode on long or strange strings
data.text = htmlToText(data.html);
} catch (E) {
// ignore
}
}
let compiler = new MailComposer(data);
let compiled = compiler.compile();
let collector = new StreamCollect();
let compiledEnvelope = compiled.getEnvelope();
let messageId = new ObjectId();
let addToDeliveryQueue = next => {
if (!compiledEnvelope.to || !compiledEnvelope.to.length || options.uploadOnly) {
// no delivery, just build the message
collector.on('data', () => false); //drain
collector.on('end', () => {
next(null, false);
});
collector.once('error', err => {
next(err);
});
let stream = compiled.createReadStream();
stream.once('error', err => collector.emit('error', err));
stream.pipe(collector);
return;
}
messageHandler.counters.ttlcounter(
'wdr:' + userData._id.toString(),
compiledEnvelope.to.length,
maxRecipients,
false,
(err, result) => {
if (err) {
err.responseCode = 500;
err.code = 'InternalDatabaseError';
return callback(err);
}
let success = result.success;
let sent = result.value;
let ttl = result.ttl;
let ttlHuman = false;
if (ttl) {
if (ttl < 60) {
ttlHuman = ttl + ' seconds';
} else if (ttl < 3600) {
ttlHuman = Math.round(ttl / 60) + ' minutes';
} else {
ttlHuman = Math.round(ttl / 3600) + ' hours';
}
}
if (!success) {
log.info('API', 'RCPTDENY denied sent=%s allowed=%s expires=%ss.', sent, maxRecipients, ttl);
let err = new Error(
'You reached a daily sending limit for your account' + (ttl ? '. Limit expires in ' + ttlHuman : '')
);
err.responseCode = 403;
err.code = 'RateLimitedError';
return setImmediate(() => callback(err));
}
// push message to outbound queue
let message = maildrop.push(
{
user: userData._id,
userEmail: userData.address,
parentId: messageId,
reason: 'submit',
from: compiledEnvelope.from,
to: compiledEnvelope.to,
sendTime,
origin: options.ip,
runPlugins: true,
mtaRelay: userData.mtaRelay || false
},
(err, ...args) => {
if (err || !args[0]) {
if (err) {
if (!err.code && err.name === 'SMTPReject') {
err.code = 'MessageRejected';
}
err.code = err.code || 'ERRCOMPOSE';
}
err.responseCode = 500;
return callback(err, ...args);
}
let outbound = args[0].id;
return next(null, outbound);
}
);
if (message) {
let stream = compiled.createReadStream();
stream.once('error', err => message.emit('error', err));
stream.pipe(collector).pipe(message);
}
}
);
};
addToDeliveryQueue((err, outbound) => {
if (err) {
// ignore
}
if (overQuota) {
log.info('API', 'STOREFAIL user=%s error=%s', user, 'Over quota');
return callback(null, {
id: false,
mailbox: false,
queueId: outbound,
overQuota: true
});
}
// Checks if the message needs to be encrypted before storing it
messageHandler.encryptMessage(
userData.encryptMessages ? userData.pubKey : false,
{ chunks: collector.chunks, chunklen: collector.chunklen },
(err, encrypted) => {
let raw = false;
if (!err && encrypted) {
// message was encrypted, so use the result instead of raw
raw = encrypted;
}
let meta = {
source: 'API',
from: compiledEnvelope.from,
to: compiledEnvelope.to,
origin: options.ip,
sess: options.sess,
time: new Date()
};
if (options.meta) {
Object.keys(options.meta || {}).forEach(key => {
if (!(key in meta)) {
meta[key] = options.meta[key];
}
});
}
let messageOptions = {
user: userData._id,
[options.mailbox ? 'mailbox' : 'specialUse']: options.mailbox
? new ObjectId(options.mailbox)
: options.isDraft
? '\\Drafts'
: '\\Sent',
outbound,
meta,
date: false,
flags: ['\\Seen'].concat(options.isDraft ? '\\Draft' : [])
};
if (raw) {
messageOptions.raw = raw;
} else {
messageOptions.raw = Buffer.concat(collector.chunks, collector.chunklen);
}
messageHandler.add(messageOptions, (err, success, info) => {
if (err) {
log.error('API', 'SUBMITFAIL user=%s error=%s', user, err.message);
err.responseCode = 500;
err.code = 'InternalDatabaseError';
return callback(err);
} else if (!info) {
log.info('API', 'SUBMITSKIP user=%s message=already exists', user);
return callback(null, false);
}
let done = () =>
callback(null, {
id: info.uid,
mailbox: info.mailbox,
queueId: outbound
});
if (options.draft) {
return db.database.collection('messages').findOne(
{
mailbox: new ObjectId(options.draft.mailbox),
uid: options.draft.id
},
(err, messageData) => {
if (err || !messageData || messageData.user.toString() !== user.toString()) {
return done();
}
messageHandler.del(
{
user,
mailbox: new ObjectId(options.draft.mailbox),
messageData,
archive: !messageData.flags.includes('\\Draft')
},
done
);
}
);
}
done();
});
}
);
});
});
});
});
})
.catch(err => callback(err));
}
);
}
const submitMessageWrapper = util.promisify(submitMessage);
server.post(
{
name: 'submitMessage',
path: '/users/:user/submit',
tags: ['Submission'],
summary: 'Submit a Message for Delivery',
description: 'Use this method to send emails from a user account',
validationObjs: {
requestBody: {
mailbox: Joi.string().hex().lowercase().length(24).description('ID of the Mailbox'),
from: AddressOptionalName.description('Address for the From: header'),
replyTo: AddressOptionalName.description('Address for the Reply-To: header'),
to: Joi.array()
.items(
Joi.object({
name: Joi.string().empty('').max(255).description('Name of the sender'),
address: Joi.string().email({ tlds: false }).failover('').required().description('Address of the sender')
}).$_setFlag('objectName', 'AddressOptionalName')
)
.description('Addresses for the To: header'),
cc: AddressOptionalNameArray.description('Addresses for the Cc: header'),
bcc: AddressOptionalNameArray.description('Addresses for the Bcc: header'),
headers: Joi.array()
.items(Header)
.description(
'Custom headers for the message. If reference message is set then In-Reply-To and References headers are set automatically'
),
subject: Joi.string()
.empty('')
.max(2 * 1024)
.description('Message subject. If not then resolved from Reference message'),
text: Joi.string()
.empty('')
.max(1024 * 1024)
.description('Plaintext message'),
html: Joi.string()
.empty('')
.max(1024 * 1024)
.description('HTML formatted message'),
attachments: Joi.array()
.items(
Joi.object({
filename: Joi.string().empty('').max(255).description('Attachment filename'),
contentType: Joi.string().empty('').max(255).description('MIME type for the attachment file'),
encoding: Joi.string().empty('').default('base64').description('Encoding to use to store the attachments'),
contentTransferEncoding: Joi.string().empty('').description('Transfer encoding'),
contentDisposition: Joi.string().empty('').trim().lowercase().valid('inline', 'attachment').description('Content Disposition'),
content: Joi.string().required().description('Base64 encoded attachment content'),
cid: Joi.string()
.empty('')
.max(255)
.description('Content-ID value if you want to reference to this attachment from HTML formatted message')
})
)
.description('Attachments for the message'),
meta: metaDataSchema.label('metaData').description('Optional metadata, must be an object or JSON formatted string'),
sess: sessSchema,
ip: sessIPSchema,
reference: ReferenceWithoutAttachments.description(
'Optional referenced email. If uploaded message is a reply draft and relevant fields are not provided then these are resolved from the message to be replied to'
),
// if true then treat this message as a draft
isDraft: booleanSchema.default(false).description('Is the message a draft or not'),
// if set then this message is based on a draft that should be deleted after processing
draft: Joi.object()
.keys({
mailbox: mailboxId,
id: Joi.number().required().description('Message ID')
})
.description('Draft message to base this one on'),
sendTime: Joi.date().description('Send time'),
uploadOnly: booleanSchema.default(false).description('If true only uploads the message but does not send it'),
envelope: Joi.object()
.keys({
from: AddressOptionalName.description('Address for the From: header'),
to: Joi.array().items(
Joi.object()
.keys({
name: Joi.string().empty('').max(255).description('Name of the sender'),
address: Joi.string().email({ tlds: false }).required().description('Address of the sender')
})
.description('Addresses for the To: header')
)
})
.description('Optional envelope')
},
queryParams: {},
pathParams: {
user: userId
},
response: {
200: {
description: 'Success',
model: Joi.object({
success: successRes,
message: Joi.object({
mailbox: Joi.string().required().description('Mailbox ID the message was stored to'),
id: Joi.number().description('Message ID in the Mailbox').required(),
queueId: Joi.string().required().description('Queue ID in MTA')
})
.required()
.description('Information about submitted Message')
.$_setFlag('objectName', 'MessageWithQueueId')
}).$_setFlag('objectName', 'SubmitMessageResponse')
}
}
}
},
tools.responseWrapper(async (req, res) => {
res.charSet('utf-8');
const { pathParams, requestBody, queryParams } = req.route.spec.validationObjs;
const schema = Joi.object({
...pathParams,
...requestBody,
...queryParams
});
// extract embedded attachments from HTML
preprocessAttachments(req.params);
const result = schema.validate(req.params, {
abortEarly: false,
convert: true,
allowUnknown: true
});
if (result.error) {
res.status(400);
return res.json({
error: result.error.message,
code: 'InputValidationError',
details: tools.validationErrors(result)
});
}
// permissions check
if (req.user && req.user === result.value.user) {
req.validate(roles.can(req.role).createOwn('messages'));
} else {
req.validate(roles.can(req.role).createAny('messages'));
}
result.value.user = new ObjectId(result.value.user);
if (result.value.reference && result.value.reference.mailbox) {
result.value.reference.mailbox = new ObjectId(result.value.reference.mailbox);
}
let info;
try {
info = await submitMessageWrapper(result.value);
} catch (err) {
log.error('API', 'SUBMIT error=%s', err.message);
res.status(500); // TODO: use response code specific status
return res.json({
error: err.message,
code: err.code
});
}
return res.json({
success: true,
message: info
});
})
);
};