emailengine-app 2.84.1 → 2.85.0

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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
@@ -106,7 +106,7 @@ services:
106
106
  test: >
107
107
  sh -c "
108
108
  if [ -n \"$$REDIS_PASSWORD\" ]; then
109
- redis-cli --no-auth-warning -a \"$$REDIS_PASSWORD\" ping
109
+ REDISCLI_AUTH=\"$$REDIS_PASSWORD\" redis-cli --no-auth-warning ping
110
110
  else
111
111
  redis-cli ping
112
112
  fi
package/eslint.config.js CHANGED
@@ -1,112 +1,94 @@
1
+ 'use strict';
2
+
3
+ // Shared lint baseline for the Postal Systems / Nodemailer packages: eslint:recommended
4
+ // plus the rules of the retired eslint-config-nodemailer, with formatting left to Prettier.
5
+ // Keep this file identical across repos except for the "Repo-specific" block at the end.
6
+
1
7
  const js = require('@eslint/js');
8
+ const prettier = require('eslint-config-prettier');
9
+ const globals = require('globals');
2
10
 
3
11
  module.exports = [
4
12
  {
5
- ignores: ['node_modules/**', 'ee-dist/**', 'static/**']
13
+ ignores: ['node_modules/**', 'coverage/**', 'dist/**', 'ee-dist/**', 'static/**']
6
14
  },
7
15
  js.configs.recommended,
8
16
  {
17
+ files: ['**/*.js', '**/*.cjs'],
9
18
  languageOptions: {
10
- ecmaVersion: 2020,
19
+ ecmaVersion: 2022,
11
20
  sourceType: 'commonjs',
12
- globals: {
13
- // Node.js globals
14
- Buffer: 'readonly',
15
- __dirname: 'readonly',
16
- __filename: 'readonly',
17
- console: 'readonly',
18
- exports: 'writable',
19
- global: 'readonly',
20
- module: 'writable',
21
- process: 'readonly',
22
- require: 'readonly',
23
- BigInt: 'readonly',
24
- setImmediate: 'readonly',
25
- clearImmediate: 'readonly',
26
- setTimeout: 'readonly',
27
- clearTimeout: 'readonly',
28
- setInterval: 'readonly',
29
- clearInterval: 'readonly',
30
- AbortController: 'readonly',
31
- AbortSignal: 'readonly',
32
- URL: 'readonly',
33
- URLSearchParams: 'readonly',
34
- structuredClone: 'readonly',
35
- // Test globals
36
- it: 'readonly',
37
- describe: 'readonly',
38
- before: 'readonly',
39
- after: 'readonly',
40
- beforeEach: 'readonly',
41
- afterEach: 'readonly'
42
- }
21
+ globals: { ...globals.node }
43
22
  },
44
- files: ['**/*.js'],
45
23
  rules: {
46
- // Disable rules that conflict with the project's style
47
- 'no-unused-vars': ['error', { args: 'none', caughtErrors: 'none' }],
48
- 'no-prototype-builtins': 'off',
49
- // Disable all formatting rules (handled by Prettier)
50
- 'array-bracket-spacing': 'off',
51
- 'arrow-parens': 'off',
52
- 'arrow-spacing': 'off',
53
- 'block-spacing': 'off',
54
- 'brace-style': 'off',
55
- 'comma-dangle': 'off',
56
- 'comma-spacing': 'off',
57
- 'comma-style': 'off',
58
- 'computed-property-spacing': 'off',
59
- 'dot-location': 'off',
60
- 'eol-last': 'off',
61
- 'func-call-spacing': 'off',
62
- 'function-call-argument-newline': 'off',
63
- 'function-paren-newline': 'off',
64
- 'generator-star-spacing': 'off',
65
- 'implicit-arrow-linebreak': 'off',
66
- indent: 'off',
67
- 'jsx-quotes': 'off',
68
- 'key-spacing': 'off',
69
- 'keyword-spacing': 'off',
70
- 'linebreak-style': 'off',
71
- 'lines-around-comment': 'off',
72
- 'lines-between-class-members': 'off',
73
- 'max-len': 'off',
74
- 'multiline-ternary': 'off',
75
- 'new-parens': 'off',
76
- 'newline-per-chained-call': 'off',
77
- 'no-extra-parens': 'off',
78
- 'no-mixed-spaces-and-tabs': 'off',
79
- 'no-multi-spaces': 'off',
80
- 'no-multiple-empty-lines': 'off',
81
- 'no-tabs': 'off',
82
- 'no-trailing-spaces': 'off',
83
- 'no-whitespace-before-property': 'off',
84
- 'nonblock-statement-body-position': 'off',
85
- 'object-curly-newline': 'off',
86
- 'object-curly-spacing': 'off',
87
- 'object-property-newline': 'off',
88
- 'one-var-declaration-per-line': 'off',
89
- 'operator-linebreak': 'off',
90
- 'padded-blocks': 'off',
91
- 'padding-line-between-statements': 'off',
92
- 'quote-props': 'off',
93
- quotes: 'off',
94
- 'rest-spread-spacing': 'off',
95
- semi: 'off',
96
- 'semi-spacing': 'off',
97
- 'semi-style': 'off',
98
- 'space-before-blocks': 'off',
99
- 'space-before-function-paren': 'off',
100
- 'space-in-parens': 'off',
101
- 'space-infix-ops': 'off',
102
- 'space-unary-ops': 'off',
103
- 'switch-colon-spacing': 'off',
104
- 'template-curly-spacing': 'off',
105
- 'template-tag-spacing': 'off',
106
- 'unicode-bom': 'off',
107
- 'wrap-iife': 'off',
108
- 'wrap-regex': 'off',
109
- 'yield-star-spacing': 'off'
24
+ 'no-await-in-loop': 'error',
25
+ 'no-div-regex': 'error',
26
+ strict: ['error', 'global'],
27
+ eqeqeq: 'error',
28
+ 'dot-notation': 'error',
29
+ curly: 'error',
30
+ 'no-unused-expressions': ['error', { allowShortCircuit: true }],
31
+ 'no-unused-vars': ['error', { varsIgnorePattern: '^_', argsIgnorePattern: '^_', caughtErrorsIgnorePattern: '^_' }],
32
+ 'handle-callback-err': 'error',
33
+ 'no-new': 'error',
34
+ 'new-cap': 'error',
35
+ 'no-eval': 'error',
36
+ 'no-invalid-this': 'error',
37
+ radix: ['error', 'always'],
38
+ 'no-use-before-define': ['error', 'nofunc'],
39
+ 'callback-return': ['error', ['callback', 'cb', 'done']],
40
+ 'no-redeclare': 'error',
41
+ 'block-scoped-var': 'error',
42
+ 'no-sequences': 'error',
43
+ 'no-throw-literal': 'error',
44
+ 'no-useless-call': 'error',
45
+ 'no-useless-concat': 'error',
46
+ 'no-void': 'error',
47
+ yoda: 'error',
48
+ 'no-var': 'error',
49
+ 'no-bitwise': 'error',
50
+ 'no-lonely-if': 'error',
51
+ 'arrow-body-style': ['error', 'as-needed'],
52
+ 'prefer-arrow-callback': 'error',
53
+ 'object-shorthand': 'error',
54
+ 'prefer-spread': 'error',
55
+ 'no-prototype-builtins': 'off'
56
+ }
57
+ },
58
+ {
59
+ files: ['test/**'],
60
+ languageOptions: {
61
+ globals: { ...globals.node, ...globals.mocha }
110
62
  }
111
- }
63
+ },
64
+ // Repo-specific: overrides go here, each with a one-line reason
65
+ {
66
+ // The vendored imap-core suite (lib/imapproxy/imap-core/test) is mocha-shaped and lives outside test/
67
+ files: ['lib/imapproxy/imap-core/test/**'],
68
+ languageOptions: {
69
+ globals: { ...globals.node, ...globals.mocha }
70
+ }
71
+ },
72
+ {
73
+ rules: {
74
+ // 524 violations: workers and sync loops await sequentially on purpose (ordering, backpressure, rate limits)
75
+ 'no-await-in-loop': 'off',
76
+ // 264 violations: 256 unused catch bindings (optional catch binding would churn 100+ files) and 8 named
77
+ // parameters kept for documented interfaces (base-class stubs, provider overrides, test doubles)
78
+ 'no-unused-vars': ['error', { varsIgnorePattern: '^_', args: 'none', caughtErrors: 'none' }],
79
+ // 48 violations: IMAP/MIME parsers, crypto, flag masks and hashing need bitwise operators
80
+ 'no-bitwise': 'off',
81
+ // 20 violations: closures and hoisted helpers referencing later module-level bindings, fixing means reordering modules
82
+ 'no-use-before-define': 'off',
83
+ // 13 violations: SCREAMING_CASE factory constants, the TLS SNICallback option and node:test's lowercase spec reporter class
84
+ 'new-cap': 'off',
85
+ // 11 violations: Handlebars helpers and test stubs use the call-site this by design
86
+ 'no-invalid-this': 'off',
87
+ // 10 violations: stream transform callbacks followed by other statements, rewriting them risks changing flow
88
+ 'callback-return': 'off',
89
+ // 9 violations, all deliberate x == null / x != null checks that cover both null and undefined
90
+ eqeqeq: ['error', 'always', { null: 'ignore' }]
91
+ }
92
+ },
93
+ prettier
112
94
  ];
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ // Which per-account Redis keys belong to one account.
4
+ //
5
+ // The per-account keys are `<prefix>iam:<account>:<suffix>`, and an account id is free text that
6
+ // may contain ":" itself. A glob of `iam:<account>:*` therefore also matches every key of an
7
+ // account whose id begins with this one and a colon (`iam:tenant:*` covers `tenant:x`), so a
8
+ // delete or a flush of one account used to take another tenant's index with it. The suffix is
9
+ // a fixed vocabulary, which is what tells the two apart: the key is this account's only when what
10
+ // follows its id is one of the shapes EmailEngine writes.
11
+
12
+ // `g` (the gateway counters), `announced-in` (the Graph announced set), `h:<hash>` (a mailbox
13
+ // status hash), `l:<hash>` and `n:<hash>` (a mailbox's message list and notifications). The hash
14
+ // is mailboxPathHash(), a base36 number
15
+ const ACCOUNT_KEY_SUFFIX = /^(?:g|announced-in|[hln]:[0-9a-z]+)$/;
16
+
17
+ /**
18
+ * A predicate telling whether a key matched by the account's `iam:<account>:*` glob really
19
+ * belongs to the account, for filtering a scan.
20
+ *
21
+ * @param {String} prefix - REDIS_PREFIX
22
+ * @param {String} account - the account id
23
+ * @returns {Function} key => Boolean
24
+ */
25
+ function ownAccountKeyFilter(prefix, account) {
26
+ let head = `${prefix}iam:${account}:`;
27
+ return key => typeof key === 'string' && key.startsWith(head) && ACCOUNT_KEY_SUFFIX.test(key.slice(head.length));
28
+ }
29
+
30
+ /**
31
+ * Whether one key belongs to the account, see ownAccountKeyFilter().
32
+ *
33
+ * @param {String} prefix - REDIS_PREFIX
34
+ * @param {String} account - the account id
35
+ * @param {String} key - a key the scan returned
36
+ * @returns {Boolean}
37
+ */
38
+ function isOwnAccountKey(prefix, account, key) {
39
+ return ownAccountKeyFilter(prefix, account)(key);
40
+ }
41
+
42
+ module.exports = { isOwnAccountKey, ownAccountKeyFilter, ACCOUNT_KEY_SUFFIX };
@@ -164,37 +164,6 @@ function planRebalance({ workerAssigned, availableWorkers }, targetWorker) {
164
164
  return moves;
165
165
  }
166
166
 
167
- /**
168
- * Runs `fn` over `items` with at most `limit` calls in flight and resolves with the results in
169
- * item order once every call has settled. Rejects with the first failure, like Promise.all, but
170
- * only after the calls already in flight have settled, so a caller never has calls outstanding
171
- * it does not know about
172
- * @param {Array} items
173
- * @param {number} limit - Calls in flight at once
174
- * @param {Function} fn - async (item, index) -> result
175
- * @returns {Promise<Array>}
176
- */
177
- async function mapConcurrent(items, limit, fn) {
178
- const results = new Array(items.length);
179
- let next = 0;
180
- let failure = null;
181
- const runner = async () => {
182
- while (next < items.length && !failure) {
183
- const index = next++;
184
- try {
185
- results[index] = await fn(items[index], index);
186
- } catch (err) {
187
- failure = failure || err;
188
- }
189
- }
190
- };
191
- await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, runner));
192
- if (failure) {
193
- throw failure;
194
- }
195
- return results;
196
- }
197
-
198
167
  module.exports = {
199
168
  pickLeastLoadedWorker,
200
169
  rollbackAssignment,
@@ -202,6 +171,5 @@ module.exports = {
202
171
  requeueFailedAccounts,
203
172
  forgetAccount,
204
173
  shouldRequeueFailedAssignment,
205
- planRebalance,
206
- mapConcurrent
174
+ planRebalance
207
175
  };
package/lib/account.js CHANGED
@@ -21,13 +21,13 @@ const { encrypt, decrypt, decryptField, parseEncryptedData } = require('./encryp
21
21
  const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
22
22
  const settings = require('./settings');
23
23
  const redisScanDelete = require('./redis-scan-delete');
24
+ const { ownAccountKeyFilter } = require('./account/own-account-key');
24
25
  const { extractMultiValues, createTransaction } = require('./redis-operations');
25
26
  const outbox = require('./outbox');
26
27
  const tokens = require('./tokens');
27
- const { customAlphabet } = require('nanoid');
28
+ const { randomId } = require('./utils/random-id');
28
29
  const Lock = require('ioredfour');
29
30
  const { redis } = require('./db');
30
- const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
31
31
  const { REDIS_PREFIX, AUTH_FAILURE_DISABLED_FIELD, AUTH_FAILURE_DISABLED_LEGACY_DESCRIPTION } = require('./consts');
32
32
  const { webSafeTextResponse, applyWebSafeHtmlOptions } = require('./web-safe-html');
33
33
  const { checkAccountScopes: checkScopes } = require('./oauth/scope-checker');
@@ -444,9 +444,10 @@ class Account {
444
444
  *
445
445
  * @param {Object} accountData - The hash as read from Redis
446
446
  * @param {Object} [opts]
447
- * @param {boolean} [opts.skipDecrypt] - Leave every encrypted value as stored. Each stored value
448
- * has its own salt, so a cold decrypt is a synchronous key derivation; a listing that decrypted the
449
- * IMAP/SMTP passwords and OAuth2 tokens of every row blocked the API worker for tens of
447
+ * @param {boolean} [opts.skipDecrypt] - Leave every encrypted value as stored. A value written
448
+ * by another process, or before the salt was per process, carries a salt this process has not
449
+ * derived a key for, so a cold decrypt is a synchronous key derivation; a listing that decrypted
450
+ * the IMAP/SMTP passwords and OAuth2 tokens of every row blocked the API worker for tens of
450
451
  * seconds on a 1000-account page, for fields it never outputs. For callers that read only
451
452
  * the non-secret structure (listings, delegated-row lookups): the credentials and the
452
453
  * ENCRYPTED_ACCOUNT_FIELDS stay ciphertext, and an encrypted custom header list is left out
@@ -1327,7 +1328,7 @@ class Account {
1327
1328
  let id;
1328
1329
  let retries = 0;
1329
1330
  while (retries++ < 20) {
1330
- id = nanoid();
1331
+ id = randomId();
1331
1332
  let alreadyExists = await this.redis.hexists(`${REDIS_PREFIX}iad:${id}`, 'account');
1332
1333
  if (alreadyExists) {
1333
1334
  id = false;
@@ -1385,7 +1386,7 @@ class Account {
1385
1386
  *
1386
1387
  * @returns {Promise<Boolean>} True when a disable flag was actually lifted
1387
1388
  */
1388
- async clearAuthFailureDisable() {
1389
+ async clearAuthFailureDisable(trigger) {
1389
1390
  const accountKey = this.getAccountKey();
1390
1391
 
1391
1392
  const [disabledAt, imapInfo] = await this.redis.hmget(accountKey, AUTH_FAILURE_DISABLED_FIELD, 'imap');
@@ -1425,7 +1426,39 @@ class Account {
1425
1426
  return false;
1426
1427
  }
1427
1428
 
1428
- this.logger.info({ msg: 'Re-enabled IMAP for account after re-authorization', account: this.account, disabledAt });
1429
+ // `trigger` is 'resume' for the "Resume syncing" action, which retries the stored credentials
1430
+ this.logger.info({
1431
+ msg:
1432
+ trigger === 'resume'
1433
+ ? 'Resumed an account that was switched off after authentication failures'
1434
+ : 'Re-enabled IMAP for account after re-authorization',
1435
+ account: this.account,
1436
+ disabledAt
1437
+ });
1438
+
1439
+ return true;
1440
+ }
1441
+
1442
+ /**
1443
+ * "Resume syncing": turns an account back on after the auth-failure safety net switched it
1444
+ * off, and asks its worker to connect it again. The one implementation behind the admin UI
1445
+ * action and PUT /v1/account/{account}/resume.
1446
+ *
1447
+ * Lifts nothing but the safety net's own disable (see clearAuthFailureDisable), so it cannot
1448
+ * be used to undo an operator's deliberate send-only switch.
1449
+ *
1450
+ * @returns {Promise<Boolean>} True when the account was switched off and has been resumed,
1451
+ * false when there was no such disable to lift
1452
+ */
1453
+ async resumeAfterAuthFailure() {
1454
+ if (!(await this.clearAuthFailureDisable('resume'))) {
1455
+ return false;
1456
+ }
1457
+
1458
+ // The flag is already lifted, so the account is no longer parked whatever the dispatch
1459
+ // does. Losing it only delays the connection until the next periodic reconnect, which is
1460
+ // why notifyWorker() logs a failure rather than throwing it.
1461
+ await this.notifyWorker('reconnect');
1429
1462
 
1430
1463
  return true;
1431
1464
  }
@@ -1719,7 +1752,7 @@ class Account {
1719
1752
  // should we wait though? might take a lot of time
1720
1753
  // Best effort like the cleanups above: the account record is already gone
1721
1754
  try {
1722
- await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
1755
+ await this.deleteOwnAccountKeys();
1723
1756
  } catch (err) {
1724
1757
  this.logger.error({ msg: 'Failed to delete the log keys of a deleted account', account: this.account, err });
1725
1758
  }
@@ -2245,19 +2278,30 @@ class Account {
2245
2278
  return messageData;
2246
2279
  }
2247
2280
 
2248
- async listSignatures(query) {
2281
+ // Deletes the per-account keys, `iam:<account>:*`. The glob also matches the keys of an
2282
+ // account whose id begins with this one and a colon, so the scan is filtered down to the keys
2283
+ // this account writes
2284
+ async deleteOwnAccountKeys() {
2285
+ await redisScanDelete(
2286
+ this.redis,
2287
+ this.logger,
2288
+ `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`,
2289
+ ownAccountKeyFilter(REDIS_PREFIX, this.account)
2290
+ );
2291
+ }
2292
+
2293
+ // Takes no caller input on purpose. The message is built from the account this object was
2294
+ // constructed for and nothing else: a query object merged over it used to let the caller
2295
+ // replace `cmd` and `account`, which turned a read on one account into any main-thread
2296
+ // command against any account.
2297
+ async listSignatures() {
2249
2298
  await this.loadAccountData(this.account, true);
2250
2299
 
2251
- return await this.call(
2252
- Object.assign(
2253
- {
2254
- cmd: 'listSignatures',
2255
- account: this.account
2256
- },
2257
- query,
2258
- { timeout: this.timeout }
2259
- )
2260
- );
2300
+ return await this.call({
2301
+ cmd: 'listSignatures',
2302
+ account: this.account,
2303
+ timeout: this.timeout
2304
+ });
2261
2305
  }
2262
2306
 
2263
2307
  /**
@@ -2385,7 +2429,7 @@ class Account {
2385
2429
  await pipeline.exec();
2386
2430
 
2387
2431
  // scan and delete keys
2388
- await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
2432
+ await this.deleteOwnAccountKeys();
2389
2433
 
2390
2434
  return true;
2391
2435
  } finally {
@@ -2565,9 +2609,9 @@ class Account {
2565
2609
  return accountData;
2566
2610
  }
2567
2611
 
2568
- async getActiveAccessTokenData() {
2569
- // throws if account does not exist
2570
- let accountData = await this.loadAccountData(this.account);
2612
+ async getActiveAccessTokenData(accountData) {
2613
+ // throws if account does not exist; a caller that just loaded the account passes it in
2614
+ accountData = accountData || (await this.loadAccountData(this.account));
2571
2615
  if (!accountData.oauth2 || !accountData.oauth2.auth || !accountData.oauth2.auth.user || !accountData.oauth2.provider) {
2572
2616
  let error = Boom.boomify(new Error('Not an OAuth2 account'), { statusCode: 403 });
2573
2617
  error.output.payload.code = 'AccountNotOAuth2';
@@ -4,7 +4,7 @@ const he = require('he');
4
4
 
5
5
  const { rewriteTextNodes } = require('./rewrite-text-nodes');
6
6
 
7
- const { getSignedFormDataSync, getServiceSecret } = require('./tools');
7
+ const { getSignedFormDataSync, getServiceSecret, SIGNING_PURPOSE } = require('./tools');
8
8
 
9
9
  async function addOpenTracker(html, account, messageId, baseUrl) {
10
10
  // add open tracker
@@ -20,7 +20,8 @@ async function addOpenTracker(html, account, messageId, baseUrl) {
20
20
  acc: account,
21
21
  msg: messageId
22
22
  },
23
- true
23
+ true,
24
+ SIGNING_PURPOSE.TRACKING
24
25
  );
25
26
 
26
27
  openTrackUrl.searchParams.append('data', data);
@@ -47,7 +48,12 @@ async function addClickTrackers(html, account, messageId, baseUrl) {
47
48
 
48
49
  const serviceSecret = await getServiceSecret();
49
50
 
50
- html = html.replace(/(<a[^>]* href\s*=[\s"']*)(http[^"'>\s]+)/gi, (match, prefix, url) => {
51
+ // `[^<>]*` rather than `[^>]*` for the attributes before href: an anchor that is never closed
52
+ // used to let the scan run to the end of the document from every `<a` and backtrack over it
53
+ // looking for ` href`, quadratic in the number of anchors (80 KB of `<a ` took most of a
54
+ // second). Stopping at the next `<` costs nothing for well-formed markup, where a tag never
55
+ // contains one
56
+ html = html.replace(/(<a[^<>]* href\s*=[\s"']*)(http[^"'>\s]+)/gi, (match, prefix, url) => {
51
57
  const redirectUrl = new URL('redirect', baseUrl);
52
58
 
53
59
  try {
@@ -79,7 +85,8 @@ async function addClickTrackers(html, account, messageId, baseUrl) {
79
85
  acc: account,
80
86
  msg: messageId
81
87
  },
82
- true
88
+ true,
89
+ SIGNING_PURPOSE.TRACKING
83
90
  );
84
91
 
85
92
  redirectUrl.searchParams.append('data', data);
@@ -50,9 +50,10 @@ function formatDescription(text) {
50
50
  });
51
51
 
52
52
  // Bare URLs, skipping ones already inside an href="..." emitted above
53
- html = html.replace(/(^|[\s(])(https?:\/\/[^\s<>"')]+)/g, (match, prefix, url) => {
54
- return `${prefix}<a href="${url}" target="_blank" rel="noopener noreferrer" class="link link-primary">${url}</a>`;
55
- });
53
+ html = html.replace(
54
+ /(^|[\s(])(https?:\/\/[^\s<>"')]+)/g,
55
+ (match, prefix, url) => `${prefix}<a href="${url}" target="_blank" rel="noopener noreferrer" class="link link-primary">${url}</a>`
56
+ );
56
57
 
57
58
  return html
58
59
  .split(/\n{2,}/)