emailengine-app 2.87.0 → 2.87.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +3 -4
  5. package/bin/emailengine.js +2 -4
  6. package/bin/healthcheck.js +20 -0
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +3 -7
  9. package/lib/account/auth-failure-backfill.js +3 -2
  10. package/lib/account/expected-identity.js +2 -2
  11. package/lib/account.js +9 -8
  12. package/lib/api-listener.js +40 -0
  13. package/lib/api-token-auth.js +406 -0
  14. package/lib/autodetect-imap-settings.js +36 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +23 -107
  21. package/lib/email-client/gmail-client.js +7 -4
  22. package/lib/email-client/imap/mailbox.js +89 -96
  23. package/lib/email-client/imap/sync-operations.js +13 -6
  24. package/lib/email-client/imap-client.js +28 -7
  25. package/lib/email-client/new-message-steps.js +162 -0
  26. package/lib/email-client/outlook-client.js +4 -2
  27. package/lib/env-setting-overrides.js +6 -2
  28. package/lib/export-worker.js +3 -2
  29. package/lib/export.js +43 -4
  30. package/lib/get-boolean.js +38 -0
  31. package/lib/health-probe.js +71 -0
  32. package/lib/imapproxy/imap-server.js +4 -55
  33. package/lib/net-tos-guard.js +42 -0
  34. package/lib/oauth2-apps.js +2 -1
  35. package/lib/privileged-settings.js +6 -0
  36. package/lib/read-env-value.js +19 -7
  37. package/lib/redis-keys.js +19 -0
  38. package/lib/redis-operations.js +7 -3
  39. package/lib/routes-ui.js +4 -1
  40. package/lib/schemas.js +8 -0
  41. package/lib/security-headers.js +18 -0
  42. package/lib/session-default.js +60 -0
  43. package/lib/settings.js +2 -1
  44. package/lib/stream-encrypt.js +71 -20
  45. package/lib/sub-script.js +8 -2
  46. package/lib/submit-lock.js +84 -0
  47. package/lib/submit-processor.js +283 -0
  48. package/lib/templates.js +6 -3
  49. package/lib/tls/context.js +2 -16
  50. package/lib/tools.js +8 -30
  51. package/lib/ui-routes/admin-config-routes.js +27 -5
  52. package/lib/ui-routes/auth-routes.js +4 -0
  53. package/lib/ui-routes/dbsc-routes.js +43 -0
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/worker-rpc-error.js +10 -5
  57. package/lib/worker-rpc.js +138 -0
  58. package/package.json +17 -19
  59. package/sbom.json +370 -1446
  60. package/server.js +6 -5
  61. package/static/css/flyonui.css +2 -2
  62. package/static/licenses.html +253 -1366
  63. package/translations/messages.pot +16 -16
  64. package/views/config/security.hbs +37 -0
  65. package/workers/api.js +61 -467
  66. package/workers/export.js +14 -55
  67. package/workers/imap-proxy.js +5 -18
  68. package/workers/imap.js +27 -49
  69. package/workers/smtp.js +7 -69
  70. package/workers/submit.js +21 -279
  71. package/workers/webhooks.js +7 -72
@@ -0,0 +1,136 @@
1
+ 'use strict';
2
+
3
+ // What the server remembers about device-bound admin sessions, in Redis so every API worker sees
4
+ // the same state:
5
+ //
6
+ // dbsc:b:{sid} the binding: the session key the browser registered (JSON), for as long as the
7
+ // admin session itself can live. Its existence is what makes the session bound,
8
+ // and it is never deleted, not on a refusal and not on logout (which marks it
9
+ // `ended`): a session cookie whose binding was removed would read as unbound and
10
+ // be accepted on its own again
11
+ // dbsc:c:{value} a challenge, single use and short-lived, naming the sid and step it was minted
12
+ // for, so a proof signed over one session's challenge cannot serve another
13
+ // dbsc:o:{sid} an offer throttle, so a browser that cannot bind (or will not) is asked about
14
+ // once a minute rather than on every page
15
+ // dbsc:f:{sid} failed refresh proofs, so a browser stuck on a bad key is told to stop rather
16
+ // than retried for ever (the spec puts no bound on its 403 loop)
17
+
18
+ const crypto = require('crypto');
19
+
20
+ const { REDIS_PREFIX } = require('../consts');
21
+ const { incrementCounter } = require('../rate-limit');
22
+
23
+ const CHALLENGE_TTL = 120;
24
+ const OFFER_INTERVAL = 60;
25
+ const FAILURE_WINDOW = 300;
26
+ const MAX_REFRESH_FAILURES = 3;
27
+
28
+ const bindingKey = sid => `${REDIS_PREFIX}dbsc:b:${sid}`;
29
+ const challengeKey = challenge => `${REDIS_PREFIX}dbsc:c:${challenge}`;
30
+ const offerKey = sid => `${REDIS_PREFIX}dbsc:o:${sid}`;
31
+ const failureKey = sid => `${REDIS_PREFIX}dbsc:f:${sid}`;
32
+
33
+ /**
34
+ * @param {Object} redis - ioredis client
35
+ */
36
+ function createDbscStore(redis) {
37
+ return {
38
+ /**
39
+ * Claims the right to offer registration to a session, at most once per OFFER_INTERVAL
40
+ * @param {string} sid
41
+ * @returns {Promise<boolean>}
42
+ */
43
+ async claimOffer(sid) {
44
+ return (await redis.set(offerKey(sid), '1', 'EX', OFFER_INTERVAL, 'NX')) === 'OK';
45
+ },
46
+
47
+ /**
48
+ * @param {string} sid
49
+ * @param {'register'|'refresh'} purpose
50
+ * @returns {Promise<string>} a new challenge
51
+ */
52
+ async mintChallenge(sid, purpose) {
53
+ const challenge = crypto.randomBytes(24).toString('base64url');
54
+ await redis.set(challengeKey(challenge), JSON.stringify({ sid, purpose }), 'EX', CHALLENGE_TTL);
55
+ return challenge;
56
+ },
57
+
58
+ /**
59
+ * Spends a challenge. Answers true only for one minted for this session and step
60
+ * @param {string} challenge
61
+ * @param {string} sid
62
+ * @param {'register'|'refresh'} purpose
63
+ * @returns {Promise<boolean>}
64
+ */
65
+ async consumeChallenge(challenge, sid, purpose) {
66
+ const stored = await redis.getdel(challengeKey(challenge));
67
+ if (!stored) {
68
+ return false;
69
+ }
70
+ try {
71
+ const parsed = JSON.parse(stored);
72
+ return parsed.sid === sid && parsed.purpose === purpose;
73
+ } catch (err) {
74
+ return false;
75
+ }
76
+ },
77
+
78
+ /**
79
+ * Stores a session's key unless the session already has one: a session is bound once, so a
80
+ * stolen session cookie cannot be re-bound to a key of the thief's
81
+ * @param {string} sid
82
+ * @param {Object} binding - { id, alg, jwk }
83
+ * @param {number} ttlSeconds - the admin session's remaining life
84
+ * @returns {Promise<boolean>} false when the session was already bound
85
+ */
86
+ async bind(sid, binding, ttlSeconds) {
87
+ const value = JSON.stringify(Object.assign({}, binding, { created: Date.now() }));
88
+ return (await redis.set(bindingKey(sid), value, 'EX', Math.max(1, Math.ceil(ttlSeconds)), 'NX')) === 'OK';
89
+ },
90
+
91
+ /**
92
+ * @param {string} sid
93
+ * @returns {Promise<Object|null>}
94
+ */
95
+ async getBinding(sid) {
96
+ const stored = await redis.get(bindingKey(sid));
97
+ if (!stored) {
98
+ return null;
99
+ }
100
+ try {
101
+ return JSON.parse(stored);
102
+ } catch (err) {
103
+ return null;
104
+ }
105
+ },
106
+
107
+ /**
108
+ * Ends a binding with its session (logout) by marking it, never by deleting it: the key is
109
+ * what keeps a copied session cookie refused, so it stays for the session's remaining life
110
+ * and no key can be bound to that session again
111
+ * @param {string} sid
112
+ */
113
+ async endBinding(sid) {
114
+ const binding = await this.getBinding(sid);
115
+ if (binding && !binding.ended) {
116
+ await redis.set(bindingKey(sid), JSON.stringify(Object.assign(binding, { ended: Date.now() })), 'XX', 'KEEPTTL');
117
+ }
118
+ await redis.del(offerKey(sid), failureKey(sid));
119
+ },
120
+
121
+ /**
122
+ * Counts a failed refresh proof
123
+ * @param {string} sid
124
+ * @returns {Promise<boolean>} true while the session may still be asked again
125
+ */
126
+ async recordRefreshFailure(sid) {
127
+ return (await incrementCounter(failureKey(sid), 1, FAILURE_WINDOW)) <= MAX_REFRESH_FAILURES;
128
+ },
129
+
130
+ async clearRefreshFailures(sid) {
131
+ await redis.del(failureKey(sid));
132
+ }
133
+ };
134
+ }
135
+
136
+ module.exports = { createDbscStore, MAX_REFRESH_FAILURES, bindingKey, offerKey, failureKey };
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('../redis-keys');
3
4
  const { threadId: workerThreadId } = require('worker_threads');
4
5
  const crypto = require('crypto');
5
6
  const logger = require('../logger');
@@ -16,10 +17,20 @@ const { addTrackers } = require('../add-trackers');
16
17
  const { getRawEmail } = require('../get-raw-email');
17
18
  const { getTemplate } = require('@postalsys/templates');
18
19
  const { deepEqual } = require('assert');
19
- const { arfDetect, camelCaseComplaint, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
20
+ const { arfDetect, FEEDBACK_REPORT_TYPE, ORIGINAL_MESSAGE_TYPES, COMPLAINT_ATTACHMENT_TYPES } = require('../arf-detect');
21
+ const {
22
+ isFailedDelivery,
23
+ classifyBounce,
24
+ bounceNotification,
25
+ complaintNotification,
26
+ embedInlineImages,
27
+ markWebSafe,
28
+ notifyNewMessage
29
+ } = require('./new-message-steps');
20
30
  const { createTransaction } = require('../redis-operations');
21
31
  const { ACCOUNT_STATES } = require('../account/account-state');
22
32
  const { credentialErrorStatus, isTransientCredentialError, resolveAuthServerCredentials } = require('./credential-errors');
33
+ const { isTransientRedisError } = require('../utils/redis-errors');
23
34
  const { parseMessage } = require('../parse-message');
24
35
  const libmime = require('libmime');
25
36
  const { bounceDetect, applyDeliveryReport, PARSER_OPTIONS: DSN_PARSER_OPTIONS } = require('../bounce-detect');
@@ -55,8 +66,7 @@ const {
55
66
  emitChangeEvent,
56
67
  getDateBuckets,
57
68
  useAuthServerForOAuth2,
58
- collectCidReferences,
59
- embedCidImages
69
+ collectCidReferences
60
70
  } = require('../tools');
61
71
  const { loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY } = require('../notify-attachments');
62
72
  const { TRACKING_SETTINGS, needsTrackingSettings, resolveTracking } = require('../utils/tracking-settings');
@@ -67,12 +77,9 @@ const {
67
77
  AUTH_SUCCESS_NOTIFY,
68
78
  ACCOUNT_INITIALIZED_NOTIFY,
69
79
  REDIS_PREFIX,
70
- MESSAGE_NEW_NOTIFY,
71
- EMAIL_BOUNCE_NOTIFY,
72
80
  DEFAULT_DELIVERY_ATTEMPTS,
73
81
  MIME_BOUNDARY_PREFIX,
74
82
  DEFAULT_DOWNLOAD_CHUNK_SIZE,
75
- EMAIL_COMPLAINT_NOTIFY,
76
83
  MAX_INLINE_ATTACHMENT_SIZE,
77
84
  MAIL_MERGE_CONCURRENCY,
78
85
  DEFAULT_MAX_IMAP_AUTH_FAILURE_TIME,
@@ -229,17 +236,6 @@ function buildReferences(referencedMessage) {
229
236
  return references;
230
237
  }
231
238
 
232
- /**
233
- * Whether a parsed bounce reports a failed delivery. A DSN also reports delivered, delayed,
234
- * relayed and expanded recipients, and none of those is a bounce to store or to fire emailBounce
235
- * for; a delayed DSN that landed in Junk used to reach the bounce path with its action set
236
- * @param {Object} bounce - Result of bounceDetect()
237
- * @returns {boolean}
238
- */
239
- function isFailedDelivery(bounce) {
240
- return !!bounce && typeof bounce.action === 'string' && bounce.action.trim().toLowerCase() === 'failed' && !!bounce.recipient && !!bounce.messageId;
241
- }
242
-
243
239
  // Finds the attachments of a referenced message whose content id the given HTML links to
244
240
  function findReferencedCidAttachments(html, attachments) {
245
241
  let cidAttachments = [];
@@ -577,7 +573,9 @@ class BaseClient {
577
573
  const messageIds = event.type === 'created' ? [typeof event.message === 'string' ? event.message : event.message?.id] : undefined;
578
574
  const logEntry = { account: this.account, eventType: event.type, messageIds, attempt: nextAttempt.attempt, err };
579
575
 
580
- if (delay && isTransientCredentialError(err)) {
576
+ // A step Redis refused for now (OOM, LOADING, a failover) is deferred like a failure of the
577
+ // service, since the deferral itself may still get past it
578
+ if (delay && (isTransientCredentialError(err) || isTransientRedisError(err))) {
581
579
  const dueTime = Date.now() + delay;
582
580
  // The change being retried right now is already stored as this attempt (its lease),
583
581
  // so moving that entry is the deferral
@@ -758,7 +756,7 @@ class BaseClient {
758
756
  // Redis key generators for different data types
759
757
 
760
758
  getAccountKey() {
761
- return `${REDIS_PREFIX}iad:${this.account}`;
759
+ return accountDataKey(this.account);
762
760
  }
763
761
 
764
762
  getMailboxListKey() {
@@ -3052,19 +3050,7 @@ class BaseClient {
3052
3050
  // Parse ARF report
3053
3051
  const report = await arfDetect(messageData);
3054
3052
 
3055
- if (report && report.arf && report.arf['original-rcpt-to'] && report.arf['original-rcpt-to'].length) {
3056
- // can send report
3057
- let complaint = camelCaseComplaint(report);
3058
-
3059
- complaintNotifyInfo = Object.assign({ complaintMessage: messageData.id }, complaint);
3060
-
3061
- messageData.isComplaint = true;
3062
-
3063
- // Link to original message
3064
- if (complaint.headers && complaint.headers.messageId) {
3065
- messageData.relatedMessageId = complaint.headers.messageId;
3066
- }
3067
- }
3053
+ complaintNotifyInfo = complaintNotification(report, messageData);
3068
3054
  } catch (err) {
3069
3055
  this.logger.error({
3070
3056
  msg: 'Failed to process ARF',
@@ -3108,43 +3094,8 @@ class BaseClient {
3108
3094
  if (content) {
3109
3095
  let bounce = await bounceDetect(content);
3110
3096
 
3111
- if (bounce?.response?.message) {
3112
- try {
3113
- let bounceType = await this.call({
3114
- cmd: 'bounceClassify',
3115
- data: {
3116
- message: bounce?.response?.message
3117
- },
3118
- timeout: 2 * 60 * 1000
3119
- });
3120
- if (bounceType?.label) {
3121
- bounce.response.category = bounceType.label;
3122
- }
3123
- if (bounceType?.action) {
3124
- bounce.response.recommendedAction = bounceType.action;
3125
- }
3126
- if (bounceType?.blocklist) {
3127
- bounce.response.blocklist = bounceType.blocklist;
3128
- }
3129
- if (bounceType?.retryAfter) {
3130
- bounce.response.retryAfter = bounceType.retryAfter;
3131
- }
3132
- } catch (err) {
3133
- // ignore, just do not include this information
3134
- this.logger.warn({
3135
- msg: 'Failed to classify bounce response',
3136
- bounceResponse: bounce?.response?.message,
3137
- err
3138
- });
3139
- }
3140
- }
3141
-
3142
- if (isFailedDelivery(bounce)) {
3143
- bounceNotifyInfo = Object.assign({ bounceMessage: messageData.id }, bounce);
3144
-
3145
- messageData.isBounce = true;
3146
- messageData.relatedMessageId = bounce.messageId;
3147
- }
3097
+ await classifyBounce(bounce, this.call, this.logger);
3098
+ bounceNotifyInfo = bounceNotification(bounce, messageData);
3148
3099
 
3149
3100
  this.logger.debug({
3150
3101
  msg: 'Detected bounce message',
@@ -3236,25 +3187,10 @@ class BaseClient {
3236
3187
  }
3237
3188
  }
3238
3189
 
3239
- // Replace CID references with data URIs. The web safe copy is what webhooks deliver
3240
- // in place of the HTML, so it gets the same treatment
3241
- if (attachmentList.size) {
3242
- const embedImages = html =>
3243
- embedCidImages(html, contentId => {
3244
- let { attachment, content } = attachmentList.get(contentId) || {};
3245
- return content && { contentType: attachment.contentType, content };
3246
- });
3247
-
3248
- messageData.text.html = embedImages(messageData.text.html);
3249
- if (messageData.text._generatedHtml) {
3250
- messageData.text._generatedHtml = embedImages(messageData.text._generatedHtml);
3251
- }
3252
- }
3190
+ embedInlineImages(messageData.text, attachmentList);
3253
3191
  }
3254
3192
 
3255
- if (messageData.text._generatedHtml) {
3256
- messageData.text.webSafe = true;
3257
- }
3193
+ markWebSafe(messageData.text);
3258
3194
  }
3259
3195
 
3260
3196
  // Narrow the headers to what the caller asked for. This runs last: the checks and the AI
@@ -3272,26 +3208,7 @@ class BaseClient {
3272
3208
  messageData.path = undefined;
3273
3209
  }
3274
3210
 
3275
- // Send new message notification
3276
- await this.notify(
3277
- {
3278
- path,
3279
- specialUse
3280
- },
3281
- MESSAGE_NEW_NOTIFY,
3282
- messageData
3283
- );
3284
-
3285
- // Send additional notifications for bounces and complaints
3286
- if (bounceNotifyInfo) {
3287
- // send bounce notification _after_ bounce email notification
3288
- await this.notify(false, EMAIL_BOUNCE_NOTIFY, bounceNotifyInfo);
3289
- }
3290
-
3291
- if (complaintNotifyInfo) {
3292
- // send complaint notification _after_ complaint email notification
3293
- await this.notify(false, EMAIL_COMPLAINT_NOTIFY, complaintNotifyInfo);
3294
- }
3211
+ await notifyNewMessage(this.notify.bind(this), { path, specialUse }, messageData, { bounceNotifyInfo, complaintNotifyInfo });
3295
3212
  }
3296
3213
 
3297
3214
  /**
@@ -3909,7 +3826,6 @@ module.exports = {
3909
3826
  metricsMeta: postMetrics,
3910
3827
  applyReferenceRecipients,
3911
3828
  buildReferences,
3912
- isFailedDelivery,
3913
3829
  markRejectedAccessToken,
3914
3830
  renewRejectedAccessToken
3915
3831
  };
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('../redis-keys');
4
+ const { isOwnSent } = require('./new-message-steps');
3
5
  const { Account } = require('../account');
4
6
  const { oauth2Apps } = require('../oauth2-apps');
5
7
  const { checkAccountScopes, isSendOnlyByScopes } = require('../oauth/scope-checker');
@@ -2029,7 +2031,7 @@ class GmailClient extends BaseClient {
2029
2031
  // PRIVATE METHODS
2030
2032
 
2031
2033
  getAccountKey() {
2032
- return `${REDIS_PREFIX}iad:${this.account}`;
2034
+ return accountDataKey(this.account);
2033
2035
  }
2034
2036
 
2035
2037
  async getAccount() {
@@ -3431,9 +3433,6 @@ class GmailClient extends BaseClient {
3431
3433
  return;
3432
3434
  }
3433
3435
 
3434
- // All new emails are "new" as message movement between folders is reported as label changes
3435
- messageData.seemsLikeNew = true;
3436
-
3437
3436
  if (eventEntry.category) {
3438
3437
  messageData.category = eventEntry.category;
3439
3438
  }
@@ -3446,6 +3445,10 @@ class GmailClient extends BaseClient {
3446
3445
  }
3447
3446
  }
3448
3447
 
3448
+ // Moving a message between folders is a label change in Gmail and never reaches this path,
3449
+ // so there is no seen-before check here. What is not new is mail the account sent itself
3450
+ messageData.seemsLikeNew = !isOwnSent(messageData);
3451
+
3449
3452
  return messageData;
3450
3453
  }
3451
3454