-
Notifications
You must be signed in to change notification settings - Fork 212
Expand file tree
/
Copy pathapi.js
More file actions
8830 lines (7685 loc) · 333 KB
/
api.js
File metadata and controls
8830 lines (7685 loc) · 333 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
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
// NB! This file is processed by gettext parser and can not use newer syntax like ?.
const { parentPort } = require('worker_threads');
const packageData = require('../package.json');
const config = require('wild-config');
const logger = require('../lib/logger');
const Path = require('path');
const { loadTranslations, gt, joiLocales } = require('../lib/translations');
const util = require('util');
const { webhooks: Webhooks } = require('../lib/webhooks');
const featureFlags = require('../lib/feature-flags');
const Bell = require('@hapi/bell');
const marked = require('marked');
const fs = require('fs');
const eulaText = marked.parse(
fs.readFileSync(Path.join(__dirname, '..', 'LICENSE_EMAILENGINE.txt'), 'utf-8').replace(/\blicenses\.html\b/g, '[licenses.html](/licenses.html)')
);
const {
getByteSize,
getDuration,
getStats,
flash,
failAction,
verifyAccountInfo,
isEmail,
getLogs,
getWorkerCount,
runPrechecks,
matcher,
readEnvValue,
matchIp,
getSignedFormData,
threadStats,
detectAutomatedRequest,
hasEnvValue,
getBoolean,
loadTlsConfig
} = require('../lib/tools');
const Bugsnag = require('@bugsnag/js');
if (readEnvValue('BUGSNAG_API_KEY')) {
Bugsnag.start({
apiKey: readEnvValue('BUGSNAG_API_KEY'),
appVersion: packageData.version,
logger: {
debug(...args) {
logger.debug({ msg: args.shift(), worker: 'api', source: 'bugsnag', args: args.length ? args : undefined });
},
info(...args) {
logger.debug({ msg: args.shift(), worker: 'api', source: 'bugsnag', args: args.length ? args : undefined });
},
warn(...args) {
logger.warn({ msg: args.shift(), worker: 'api', source: 'bugsnag', args: args.length ? args : undefined });
},
error(...args) {
logger.error({ msg: args.shift(), worker: 'api', source: 'bugsnag', args: args.length ? args : undefined });
}
}
});
logger.notifyError = Bugsnag.notify.bind(Bugsnag);
}
const Hapi = require('@hapi/hapi');
const Boom = require('@hapi/boom');
const Cookie = require('@hapi/cookie');
const Crumb = require('@hapi/crumb');
const Joi = require('joi');
const hapiPino = require('hapi-pino');
const Inert = require('@hapi/inert');
const Vision = require('@hapi/vision');
const HapiSwagger = require('hapi-swagger');
const pathlib = require('path');
const crypto = require('crypto');
const { Transform, finished } = require('stream');
const { oauth2Apps, OAUTH_PROVIDERS } = require('../lib/oauth2-apps');
const handlebars = require('handlebars');
const AuthBearer = require('hapi-auth-bearer-token');
const tokens = require('../lib/tokens');
const { autodetectImapSettings } = require('../lib/autodetect-imap-settings');
const Hecks = require('@postalsys/hecks');
const { arenaExpress } = require('../lib/arena-express');
const outbox = require('../lib/outbox');
const { lists } = require('../lib/lists');
const { redis, REDIS_CONF, documentsQueue, notifyQueue, submitQueue } = require('../lib/db');
const { Account } = require('../lib/account');
const { Gateway } = require('../lib/gateway');
const settings = require('../lib/settings');
const getSecret = require('../lib/get-secret');
const { getESClient } = require('../lib/document-store');
const routesUi = require('../lib/routes-ui');
const { encrypt, decrypt } = require('../lib/encrypt');
const { Certs } = require('@postalsys/certs');
const net = require('net');
const consts = require('../lib/consts');
const {
TRACK_OPEN_NOTIFY,
TRACK_CLICK_NOTIFY,
REDIS_PREFIX,
MAX_DAYS_STATS,
RENEW_TLS_AFTER,
BLOCK_TLS_RENEW,
TLS_RENEW_CHECK_INTERVAL,
DEFAULT_CORS_MAX_AGE,
LIST_UNSUBSCRIBE_NOTIFY,
FETCH_TIMEOUT,
DEFAULT_MAX_BODY_SIZE,
DEFAULT_MAX_PAYLOAD_TIMEOUT,
DEFAULT_EENGINE_TIMEOUT,
DEFAULT_MAX_ATTACHMENT_SIZE,
MAX_FORM_TTL,
NONCE_BYTES,
OUTLOOK_EXPIRATION_TIME
} = consts;
const { fetch: fetchCmd, Agent } = require('undici');
const fetchAgent = new Agent({ connect: { timeout: FETCH_TIMEOUT } });
const templateRoutes = require('../lib/api-routes/template-routes');
const chatRoutes = require('../lib/api-routes/chat-routes');
const {
settingsSchema,
addressSchema,
settingsQuerySchema,
imapSchema,
imapUpdateSchema,
smtpSchema,
smtpUpdateSchema,
oauth2Schema,
oauth2UpdateSchema,
messageDetailsSchema,
messageListSchema,
mailboxesSchema,
shortMailboxesSchema,
licenseSchema,
lastErrorSchema,
templateSchemas,
documentStoreSchema,
searchSchema,
messageUpdateSchema,
accountSchemas,
oauthCreateSchema,
tokenRestrictionsSchema,
accountIdSchema,
ipSchema,
accountCountersSchema,
accountPathSchema,
defaultAccountTypeSchema,
fromAddressSchema,
outboxEntrySchema,
googleProjectIdSchema
} = require('../lib/schemas');
const listMessageFolderPathDescription =
'Mailbox folder path. Can use special use labels like "\\Sent". Special value "\\All" is available for Gmail IMAP, Gmail API, MS Graph API accounts.';
const OAuth2ProviderSchema = Joi.string()
.valid(...Object.keys(OAUTH_PROVIDERS))
.required()
.example('gmail')
.description('OAuth2 provider')
.label('OAuth2Provider');
const AccountTypeSchema = Joi.string()
.valid(...['imap'].concat(Object.keys(OAUTH_PROVIDERS)).concat('oauth2'))
.example('outlook')
.description('Account type')
.required();
const FLAG_SORT_ORDER = ['\\Inbox', '\\Flagged', '\\Sent', '\\Drafts', '\\All', '\\Archive', '\\Junk', '\\Trash'];
const { GMAIL_SCOPES } = require('../lib/oauth/gmail');
const { MAIL_RU_SCOPES } = require('../lib/oauth/mail-ru');
const REDACTED_KEYS = ['req.headers.authorization', 'req.headers.cookie', 'err.rawPacket'];
const SMTP_TEST_HOST = 'https://api.nodemailer.com';
config.api = config.api || {
port: 3000,
host: '127.0.0.1',
proxy: false,
tls: false
};
config.service = config.service || {};
const OKTA_OAUTH2_ISSUER = readEnvValue('OKTA_OAUTH2_ISSUER');
const OKTA_OAUTH2_CLIENT_ID = readEnvValue('OKTA_OAUTH2_CLIENT_ID');
const OKTA_OAUTH2_CLIENT_SECRET = readEnvValue('OKTA_OAUTH2_CLIENT_SECRET');
const OKTA_BASE_URL = OKTA_OAUTH2_ISSUER ? new URL(OKTA_OAUTH2_ISSUER).origin : null;
const USE_OKTA_AUTH = !!(OKTA_OAUTH2_ISSUER && OKTA_OAUTH2_CLIENT_ID && OKTA_OAUTH2_CLIENT_SECRET);
const EENGINE_TIMEOUT = getDuration(readEnvValue('EENGINE_TIMEOUT') || config.service.commandTimeout) || DEFAULT_EENGINE_TIMEOUT;
const MAX_ATTACHMENT_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
const API_PORT =
(hasEnvValue('EENGINE_PORT') && Number(readEnvValue('EENGINE_PORT'))) || (hasEnvValue('PORT') && Number(readEnvValue('PORT'))) || config.api.port;
const API_HOST = readEnvValue('EENGINE_HOST') || config.api.host;
// Either an object (TLS enabled) or `false` (TLS disabled)
const API_TLS = hasEnvValue('EENGINE_API_TLS') ? getBoolean(readEnvValue('EENGINE_API_TLS')) && (config.api.tls || {}) : config.api.tls || false;
// Merge TLS settings from config params and environment
loadTlsConfig(API_TLS, 'EENGINE_API_TLS_');
const IMAP_WORKER_COUNT = getWorkerCount(readEnvValue('EENGINE_WORKERS') || (config.workers && config.workers.imap)) || 4;
// Max POST body size for message uploads
// NB! the default for other requests is 1MB
const MAX_BODY_SIZE = getByteSize(readEnvValue('EENGINE_MAX_BODY_SIZE') || config.api.maxBodySize) || DEFAULT_MAX_BODY_SIZE;
// Payload reception timeout in milliseconds for message upload requests
const MAX_PAYLOAD_TIMEOUT = getDuration(readEnvValue('EENGINE_MAX_PAYLOAD_TIMEOUT') || config.api.maxPayloadTimeout) || DEFAULT_MAX_PAYLOAD_TIMEOUT;
// CORS configuration for API requests
// By default, CORS is not enabled
const CORS_ORIGINS = readEnvValue('EENGINE_CORS_ORIGIN') || (config.cors && config.cors.origin);
const CORS_CONFIG = !CORS_ORIGINS
? false
: {
// crux to convert --cors.origin=".." and EENGINE_CORS_ORIGIN="..." into an array of origins
origin: [].concat(
Array.from(
new Set(
[]
.concat(CORS_ORIGINS || [])
.flatMap(origin => origin)
.flatMap(origin => origin && origin.toString().trim().split(/\s+/))
.filter(origin => origin)
)
) || ['*']
),
additionalHeaders: ['X-EE-Timeout'],
additionalExposedHeaders: ['Accept'],
preflightStatusCode: 204,
maxAge:
getDuration(readEnvValue('EENGINE_CORS_MAX_AGE') || (config.cors && config.cors.maxAge), {
seconds: true
}) || DEFAULT_CORS_MAX_AGE,
credentials: true
};
logger.info({
msg: 'API server configuration',
api: {
port: API_PORT,
host: API_HOST,
maxPayloadTimeout: MAX_PAYLOAD_TIMEOUT,
maxBodySize: MAX_BODY_SIZE,
maxSize: MAX_ATTACHMENT_SIZE
},
service: {
commandTimeout: EENGINE_TIMEOUT
},
cors: CORS_CONFIG
});
const TRACKER_IMAGE = Buffer.from('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', 'base64');
let registeredPublishers = new Set();
class ResponseStream extends Transform {
constructor() {
super();
registeredPublishers.add(this);
this.periodicKeepAliveTimer = false;
this.updateTimer();
}
updateTimer() {
clearTimeout(this.periodicKeepAliveTimer);
this.periodicKeepAliveTimer = setTimeout(() => {
this.write(': still here\n\n');
if (this._compressor) {
this._compressor.flush();
}
this.updateTimer();
}, 90 * 1000);
this.periodicKeepAliveTimer.unref();
}
setCompressor(compressor) {
this._compressor = compressor;
}
sendMessage(payload) {
let sendData = JSON.stringify(payload);
this.write('event: message\ndata:' + sendData + '\n\n');
if (this._compressor) {
this._compressor.flush();
}
this.updateTimer();
}
finalize() {
clearTimeout(this.periodicKeepAliveTimer);
registeredPublishers.delete(this);
}
_transform(data, encoding, done) {
this.push(data);
done();
}
_flush(done) {
this.finalize();
done();
}
}
let callQueue = new Map();
let mids = 0;
async function call(message, transferList) {
return new Promise((resolve, reject) => {
let mid = `${Date.now()}:${++mids}`;
let ttl = Math.max(message.timeout || 0, EENGINE_TIMEOUT || 0);
let timer = setTimeout(() => {
let err = new Error('Timeout waiting for command response [T2]');
err.statusCode = 504;
err.code = 'Timeout';
err.ttl = ttl;
reject(err);
}, ttl);
callQueue.set(mid, { resolve, reject, timer });
try {
parentPort.postMessage(
{
cmd: 'call',
mid,
message
},
transferList
);
} catch (err) {
clearTimeout(timer);
callQueue.delete(mid);
return reject(err);
}
});
}
async function checkRateLimit(key, count, allowed, windowSize) {
return await call({ cmd: 'rate-limit', key, count, allowed, windowSize });
}
async function metrics(logger, key, method, ...args) {
try {
parentPort.postMessage({
cmd: 'metrics',
key,
method,
args
});
} catch (err) {
logger.error({ msg: 'Failed to post metrics to parent', err });
}
}
async function notify(cmd, data) {
parentPort.postMessage({
cmd,
data
});
}
async function sendWebhook(account, event, data) {
metrics(logger, 'events', 'inc', {
event
});
let serviceUrl = (await settings.get('serviceUrl')) || null;
let payload = {
serviceUrl,
account,
date: new Date().toISOString()
};
if (event) {
payload.event = event;
}
if (data) {
payload.data = data;
}
await Webhooks.pushToQueue(event, await Webhooks.formatPayload(event, payload));
}
async function onCommand(command) {
switch (command.cmd) {
case 'resource-usage':
return threadStats.usage();
default:
logger.debug({ msg: 'Unhandled command', command });
return 999;
}
}
function publishChangeEvent(data) {
let { account, type, key, payload } = data;
for (let stream of registeredPublishers) {
try {
stream.sendMessage({ account, type, key, payload });
} catch (err) {
logger.error({ msg: 'Failed to publish change event', err, account, type, key, payload });
}
}
}
parentPort.on('message', message => {
if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
let { resolve, reject, timer } = callQueue.get(message.mid);
clearTimeout(timer);
callQueue.delete(message.mid);
if (message.error) {
let err = new Error(message.error);
if (message.code) {
err.code = message.code;
}
if (message.statusCode) {
err.statusCode = message.statusCode;
}
if (message.info) {
err.info = message.info;
}
return reject(err);
} else {
return resolve(message.response);
}
}
if (message && message.cmd === 'call' && message.mid) {
return onCommand(message.message)
.then(response => {
parentPort.postMessage({
cmd: 'resp',
mid: message.mid,
response
});
})
.catch(err => {
parentPort.postMessage({
cmd: 'resp',
mid: message.mid,
error: err.message,
code: err.code,
statusCode: err.statusCode
});
});
}
if (message && message.cmd === 'change') {
publishChangeEvent(message);
}
});
const init = async () => {
await loadTranslations();
gt.setLocale((await settings.get('locale')) || 'en');
handlebars.registerHelper('_', (...args) => {
let params = args.slice(1, args.length - 1);
let translated = gt.gettext(args[0]);
if (params.length) {
translated = util.format(translated, ...params);
}
return new handlebars.SafeString(translated);
});
handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
handlebars.registerHelper('featureFlag', function (flag, options) {
if (featureFlags.enabled(flag)) {
return options.fn(this); // eslint-disable-line no-invalid-this
}
return options.inverse(this); // eslint-disable-line no-invalid-this
});
handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
if (baseVal === compareVal) {
return options.fn(this); // eslint-disable-line no-invalid-this
}
return options.inverse(this); // eslint-disable-line no-invalid-this
});
handlebars.registerHelper('inc', (nr, inc) => Number(nr) + Number(inc));
handlebars.registerHelper('formatInteger', (intVal, locale) => {
if (isNaN(intVal)) {
// ignore non-numbers
return intVal;
}
locale = (locale || 'en_US').replace(/_/g, '-');
let formatter;
try {
formatter = new Intl.NumberFormat(locale, {});
} catch (err) {
formatter = new Intl.NumberFormat('en-US', {});
}
return formatter.format(intVal);
});
const server = Hapi.server({
port: API_PORT,
host: API_HOST,
tls: API_TLS,
state: {
strictHeader: false
},
router: {
stripTrailingSlash: true
},
routes: {
validate: {
options: {
messages: joiLocales,
convert: true
},
headers: Joi.object({
'x-ee-timeout': Joi.number()
.integer()
.min(0)
.max(2 * 3600 * 1000)
.optional()
.description(`Override the \`EENGINE_TIMEOUT\` environment variable for a single API request (in milliseconds)`)
.label('X-EE-Timeout')
}).unknown()
}
}
});
let assertPreconditionResult;
server.decorate('toolkit', 'getESClient', async (...args) => await getESClient(...args));
let getServiceDomain = async () => {
let serviceUrl = await settings.get('serviceUrl');
let hostname = (new URL(serviceUrl).hostname || '').toString().toLowerCase().trim();
if (!hostname || net.isIP(hostname) || ['localhost'].includes(hostname) || /(\.local|\.lan)$/i.test(hostname)) {
return false;
}
return hostname;
};
let certHandler = new Certs({
redis,
namespace: `${REDIS_PREFIX}`,
acme: {
environment: 'emailengine',
directoryUrl: 'https://acme-v02.api.letsencrypt.org/directory'
//directoryUrl: 'https://acme-staging-v02.api.letsencrypt.org/directory',
},
logger: logger.child({ sub: 'acme' }),
encryptFn: async value => {
const encryptSecret = await getSecret();
return encrypt(value, encryptSecret);
},
decryptFn: async value => {
const encryptSecret = await getSecret();
return decrypt(value, encryptSecret);
}
});
server.decorate('toolkit', 'serviceDomain', getServiceDomain);
server.decorate('toolkit', 'certs', certHandler);
server.decorate('toolkit', 'checkRateLimit', checkRateLimit);
server.decorate('toolkit', 'getCertificate', async provision => {
let hostname = await getServiceDomain();
let certificateData;
if (hostname) {
certificateData = await certHandler.getCertificate(hostname, !provision);
}
if (!certificateData) {
certificateData = {
domain: hostname,
status: 'self_signed',
label: { type: 'warning', text: 'Self-signed', title: 'Using a self-signed certificate' }
};
} else if (certificateData.status !== 'valid') {
switch (certificateData.status) {
case 'pending':
certificateData.label = { type: 'info', text: 'Provisioning...', title: 'Currently provisioning a certificate' };
break;
case 'failed':
certificateData.label = {
type: 'danger',
text: 'Failed',
title: (certificateData.lastError && certificateData.lastError.err) || 'Failed to generate a certificate'
};
break;
}
} else if (certificateData.validFrom > new Date()) {
certificateData.label = {
type: 'warning',
text: 'Future certificate',
title: 'Certificate is not yet valid'
};
} else if (certificateData.validTo < new Date()) {
certificateData.label = {
type: 'warning',
text: 'Expired certificate',
title: (certificateData.lastError && certificateData.lastError.err) || 'Certificate has been expired'
};
} else {
certificateData.label = {
type: 'success',
text: 'Valid certificate',
title: certificateData.fingerprint
};
}
return certificateData;
});
server.ext('onPostAuth', async (request, h) => {
let defaultLocale = (await settings.get('locale')) || 'en';
if (defaultLocale && gt.locale !== defaultLocale) {
gt.setLocale(defaultLocale);
}
if (joiLocales[defaultLocale] && request.route.settings.validate.options) {
if (!request.route.settings.validate.options.errors) {
request.route.settings.validate.options.errors = {};
}
request.route.settings.validate.options.errors.language = defaultLocale;
}
return h.continue;
});
server.ext('onRequest', async (request, h) => {
// check if client IP is resolved from X-Forwarded-For or not
let enableApiProxy = (await settings.get('enableApiProxy')) || false;
if (enableApiProxy) {
// check for the IP address from the Forwarded-For header
const xFF = request.headers['x-forwarded-for'];
request.app.ip = xFF ? xFF.split(',')[0] : request.info.remoteAddress;
} else {
// use socket address
request.app.ip = request.info.remoteAddress;
}
// check if access tokens for api requests are required
let disableTokens = await settings.get('disableTokens');
if (disableTokens && !request.url.searchParams.get('access_token') && !request.headers.authorization) {
// make sure that we have a access_token value set in query args
let url = new URL(request.url.href);
url.searchParams.set('access_token', 'preauth');
request.setUrl(`${url.pathname}${url.search}`);
}
// make license info available for the request
request.app.licenseInfo = await call({ cmd: 'license', timeout: request.headers['x-ee-timeout'] });
// flash notifications
request.flash = async message => await flash(redis, request, message);
return h.continue;
});
const swaggerOptions = {
swaggerUI: true,
swaggerUIPath: '/admin/iframe/swagger/',
documentationPage: true,
documentationPath: '/admin/iframe/docs',
expanded: 'list',
sortEndpoints: 'method',
sortTags: 'unsorted',
tryItOutEnabled: true,
templates: Path.join(__dirname, '..', 'views', 'swagger', 'ui'),
grouping: 'tags',
//auth: 'api-token',
info: {
title: 'EmailEngine API',
version: packageData.version,
description: `<strong>Authentication Required:</strong> You must provide an Access Token to use this API. (Generate your Access Token <a href="/admin/tokens" target="_parent">here</a>).
<strong>Note on Request Handling:</strong> Requests made to the same account are processed sequentially and are not executed in parallel. If a previous request is still processing, subsequent requests may be queued. In the event of a prolonged request, queued requests may time out before being executed by EmailEngine.`
},
securityDefinitions: {
bearerAuth: {
type: 'apiKey',
//scheme: 'bearer',
name: 'access_token',
in: 'query'
}
},
security: [{ bearerAuth: [] }],
cors: !!CORS_CONFIG,
cache: {
expiresIn: 7 * 24 * 60 * 60 * 1000
},
tags: [
{
name: 'Account'
},
{
name: 'Mailbox',
description: 'Manage mailbox folders'
},
{
name: 'Message'
},
{
name: 'Submit',
externalDocs: {
description: 'Documentation',
url: 'https://emailengine.app/sending-emails'
}
},
{
name: 'Outbox',
description: 'Manage scheduled and pending emails in the sending queue'
},
{
name: 'Delivery Test',
description: 'Test email deliverability, including SPF, DKIM, and DMARC alignment'
},
{
name: 'Access Tokens'
},
{
name: 'Settings',
description: 'Runtime configuration for EmailEngine'
},
{
name: 'Templates',
description: 'Manage templates for sending emails',
externalDocs: {
description: 'Documentation',
url: 'https://emailengine.app/email-templates'
}
},
{
name: 'Logs'
},
{
name: 'Stats'
},
{
name: 'License'
},
{
name: 'Webhooks'
},
{
name: 'OAuth2 Applications',
externalDocs: {
description: 'Documentation',
url: 'https://emailengine.app/oauth2-configuration'
}
},
{
name: 'SMTP Gateway'
},
{
name: 'Blocklists'
},
{
name: 'Multi Message Actions'
}
]
};
await server.register(AuthBearer);
// Authentication for API calls
server.auth.strategy('api-token', 'bearer-access-token', {
allowQueryToken: true, // optional, false by default
validate: async (request, token /*, h*/) => {
let disableTokens = await settings.get('disableTokens');
if (disableTokens && (!token || token === 'preauth')) {
// tokens checks are disabled, allow all if token is not set
return {
isValid: true,
credentials: {},
artifacts: {}
};
}
let scope = false;
let tags = (request.route && request.route.settings && request.route.settings.tags) || [];
if (tags.includes('api')) {
scope = 'api';
} else {
for (let tag of tags) {
if (/^scope:/.test(tag)) {
scope = tag.substr('scope:'.length);
}
}
}
let tokenData;
try {
tokenData = await tokens.get(token, false, { log: true, remoteAddress: request.app.ip });
} catch (err) {
return {
isValid: false,
credentials: {},
artifacts: { err: err.message }
};
}
if (scope && tokenData.scopes && !tokenData.scopes.includes(scope) && !tokenData.scopes.includes('*')) {
// failed scope validation
logger.error({
msg: 'Trying to use invalid scope for a token',
tokenAccount: tokenData.account,
tokenId: tokenData.id,
requestedScope: scope,
tokenScopes: tokenData.scopes
});
let error = Boom.forbidden('Unauthorized scope');
error.output.payload.requestedScope = scope;
throw error;
}
if (tokenData.account) {
// account token
let accountIdSource;
// allow specific routes that have an account component but not in the URL params section
switch (request.route.path) {
case '/v1/templates':
switch (request.method) {
case 'get':
accountIdSource = request.query && request.query.account;
break;
}
break;
case '/v1/templates/template/{template}': {
let isAccountTemplate =
request.params.template && (await redis.sismember(`${REDIS_PREFIX}tpl:${tokenData.account}:i`, request.params.template));
if (isAccountTemplate) {
accountIdSource = tokenData.account;
}
break;
}
case '/v1/templates/template': {
switch (request.method) {
case 'post':
request.app.enforceAccount = tokenData.account;
accountIdSource = tokenData.account;
break;
}
break;
}
default:
accountIdSource = request.params && request.params.account;
break;
}
if (accountIdSource !== tokenData.account) {
logger.error({
msg: 'Trying to use invalid account for a token',
tokenAccount: tokenData.account,
tokenId: tokenData.id,
account: (request.params && request.params.account) || null
});
let error = Boom.forbidden('Unauthorized account');
throw error;
}
}
if (tokenData.restrictions) {
if (tokenData.restrictions.addresses && !matchIp(request.app.ip, tokenData.restrictions.addresses)) {
logger.error({
msg: 'Trying to use invalid IP for a token',
tokenAccount: tokenData.account,
tokenId: tokenData.id,
account: (request.params && request.params.account) || null,
remoteAddress: request.app.ip,
addressAllowlist: tokenData.restrictions.addresses
});
let error = Boom.forbidden('Unauthorized address');
error.output.payload.remoteAddress = request.app.ip;
throw error;
}
if (
tokenData.restrictions.referrers &&
tokenData.restrictions.referrers.length &&
!matcher(tokenData.restrictions.referrers, request.headers.referer)
) {
logger.error({
msg: 'Trying to use invalid referer for a token',
tokenAccount: tokenData.account,
tokenId: tokenData.id,
account: (request.params && request.params.account) || null,
referer: request.headers.referer,
referrerAllowlist: tokenData.restrictions.referrers
});
let error = Boom.forbidden('Unauthorized referrer');
throw error;
}
if (tokenData.restrictions.rateLimit) {
let rateLimit = await checkRateLimit(
`api:${tokenData.id}`,
1,
tokenData.restrictions.rateLimit.maxRequests,
tokenData.restrictions.rateLimit.timeWindow
);
if (!rateLimit.success) {
logger.error({ msg: 'Rate limited', token: tokenData.id, rateLimit });
let error = Boom.tooManyRequests('Rate limit exceeded');
error.output.payload.ttl = Math.ceil(rateLimit.ttl);
error.output.headers = {
'X-RateLimit-Limit': rateLimit.allowed,
'X-RateLimit-Reset': Math.ceil(rateLimit.ttl)
};
throw error;
} else {
request.app.rateLimitHeaders = {
'X-RateLimit-Limit': rateLimit.allowed,
'X-RateLimit-Reset': Math.ceil(rateLimit.ttl),
'X-RateLimit-Remaining': rateLimit.allowed - rateLimit.count
};
}
}
}
return { isValid: true, credentials: { token }, artifacts: tokenData };
}
});
// needed for auth session and flash messages
await server.register(Cookie);
await server.register(Bell);
let secureCookie = false;
try {
let serviceUrl = await settings.get('serviceUrl');
if (serviceUrl) {
let parsedUrl = new URL(serviceUrl);
secureCookie = parsedUrl.protocol === 'https:';
}
} catch (err) {
// skip
}
// Authentication for admin pages
server.auth.strategy('session', 'cookie', {