emailengine-app 2.81.2 → 2.82.1

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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
package/lib/tools.js CHANGED
@@ -20,6 +20,7 @@ const { createPublicKey, createVerify, randomBytes, createHmac, createHash, timi
20
20
  const logger = require('./logger');
21
21
  const Boom = require('@hapi/boom');
22
22
  const { ImapFlow } = require('imapflow');
23
+ const { createImapClient } = require('./create-imap-client');
23
24
  const nodemailer = require('nodemailer');
24
25
  const { parentPort, workerData } = require('worker_threads');
25
26
  const punycode = require('punycode.js');
@@ -44,7 +45,6 @@ const {
44
45
  FETCH_RETRY_INTERVAL,
45
46
  FETCH_RETRY_EXPONENTIAL,
46
47
  FETCH_RETRY_MAX,
47
- URL_FETCH_RETRY_MAX,
48
48
  MAX_DAYS_STATS,
49
49
  MAILBOX_RESPONSE_FIELDS,
50
50
  MAILBOX_HASH
@@ -68,7 +68,13 @@ const AGENT_OPTS = {
68
68
  };
69
69
 
70
70
  const RETRY_OPTS = {
71
- maxRetries: URL_FETCH_RETRY_MAX,
71
+ // Kept short on purpose: the callers are token endpoint requests (a refresh runs inside the
72
+ // API request that needed the token, with its 10 s RPC budget), license and update checks,
73
+ // and five retries with an uncapped Retry-After could hold one for minutes. The Gmail and
74
+ // Graph provider API requests do not use this dispatcher at all: their retries are decided in
75
+ // lib/email-client/api-retry.js, which knows the method and the provider's throttling answers
76
+ maxRetries: 2,
77
+ maxTimeout: 5000,
72
78
  methods: ['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE', 'POST'],
73
79
  statusCodes: [429], // do not retry 5xx errors
74
80
  // undici does not retry transient DNS failures (EAI_AGAIN) or socket connect
@@ -157,9 +163,6 @@ const HTTP_PROXY_SETTINGS = ['proxyEnabled', 'proxyUrl', 'httpProxyEnabled', 'ht
157
163
  const SOCKS_SCHEMES = new Set(['socks', 'socks4', 'socks4a', 'socks5']);
158
164
  const SOCKS4_PROTOCOLS = new Set(['socks4:', 'socks4a:']);
159
165
 
160
- // Backward-compat aliases (read from httpAgent at call time via getter)
161
- // backward-compat aliases are defined as getters on module.exports below
162
-
163
166
  // Accounts a stale-useAuthServer warning was already logged for, keyed by account:target.
164
167
  // getActiveAccessTokenData() runs once per API request, so an unconditional warn would repeat
165
168
  // the same line for the lifetime of the stale flag.
@@ -201,8 +204,19 @@ function createSocksAgent(proxyUrl, agentOpts) {
201
204
  if (useTls) {
202
205
  let rawSocket = socket;
203
206
  socket = tls.connect(Object.assign({ socket: rawSocket, servername: servername || hostname }, TLS_DEFAULTS));
207
+ // The SOCKS timeout above only covers the proxy negotiation. A proxy (or a target
208
+ // behind it) that accepts the tunnel and then never answers the ClientHello would
209
+ // otherwise hold the request, and whatever awaits it (a token refresh, a Gmail or
210
+ // Graph call), forever.
211
+ let handshakeTimeout = agentOpts.connectTimeout || 30000;
212
+ let timer;
204
213
  try {
205
214
  await new Promise((resolve, reject) => {
215
+ timer = setTimeout(() => {
216
+ let err = new Error(`TLS handshake through the SOCKS proxy timed out after ${handshakeTimeout}ms`);
217
+ err.code = 'ETIMEDOUT';
218
+ reject(err);
219
+ }, handshakeTimeout);
206
220
  socket.once('secureConnect', resolve);
207
221
  socket.once('error', reject);
208
222
  });
@@ -210,6 +224,8 @@ function createSocksAgent(proxyUrl, agentOpts) {
210
224
  socket.destroy();
211
225
  rawSocket.destroy();
212
226
  throw err;
227
+ } finally {
228
+ clearTimeout(timer);
213
229
  }
214
230
  }
215
231
 
@@ -511,6 +527,73 @@ function cidReferenceRegex() {
511
527
  return new RegExp(CID_REFERENCE_SOURCE, 'g');
512
528
  }
513
529
 
530
+ // A data: URL is only built from a content type that is a plain type/subtype token. A value
531
+ // carrying a quote or a space (a provider can relay a sender-supplied header) would otherwise
532
+ // break out of the src attribute of HTML that is served as web safe
533
+ const DATA_URL_CONTENT_TYPE = /^[\w.+-]+\/[\w.+-]+$/;
534
+
535
+ /**
536
+ * Replaces cid: references in HTML with data: URLs for the attachments that have content
537
+ *
538
+ * @param {String} html
539
+ * @param {Function} lookup - called with the content id, returns { contentType, content } (content as base64) or a falsy value
540
+ * @returns {String}
541
+ */
542
+ /**
543
+ * Reads a Retry-After header as seconds. Accepts a fetch Headers object (or anything with get())
544
+ * and a plain header object with keys in any casing, which is how the items of a Graph $batch
545
+ * response carry theirs. The HTTP-date form is converted to the seconds left until it
546
+ *
547
+ * @param {Object} headers - Headers of the response
548
+ * @returns {Number|null} Seconds to wait, 0 or more, or null when the header is absent or unreadable
549
+ */
550
+ function parseRetryAfter(headers) {
551
+ if (!headers) {
552
+ return null;
553
+ }
554
+
555
+ let value = null;
556
+ if (typeof headers.get === 'function') {
557
+ value = headers.get('retry-after');
558
+ } else if (typeof headers === 'object') {
559
+ for (let key of Object.keys(headers)) {
560
+ if (key.toLowerCase() === 'retry-after') {
561
+ value = headers[key];
562
+ break;
563
+ }
564
+ }
565
+ }
566
+
567
+ if (value === null || value === undefined || value === '') {
568
+ return null;
569
+ }
570
+
571
+ value = String(value).trim();
572
+ if (/^\d+(\.\d+)?$/.test(value)) {
573
+ return Number(value);
574
+ }
575
+
576
+ let date = Date.parse(value);
577
+ if (isNaN(date)) {
578
+ return null;
579
+ }
580
+ return Math.max(0, Math.ceil((date - Date.now()) / 1000));
581
+ }
582
+
583
+ function embedCidImages(html, lookup) {
584
+ if (!html) {
585
+ return html;
586
+ }
587
+ return html.replace(cidReferenceRegex(), (fullMatch, cidMatch) => {
588
+ let attachment = lookup(cidMatch);
589
+ if (!attachment || !attachment.content) {
590
+ return fullMatch;
591
+ }
592
+ let contentType = DATA_URL_CONTENT_TYPE.test(attachment.contentType || '') ? attachment.contentType : 'application/octet-stream';
593
+ return `data:${contentType};base64,${attachment.content}`;
594
+ });
595
+ }
596
+
514
597
  // Hands a renewed certificate to every listener without restarting any of them.
515
598
  //
516
599
  // The list of listeners lives here rather than at each call site, because the bug this replaces was
@@ -572,6 +655,8 @@ module.exports = {
572
655
  TLS_MATERIAL_SETTINGS,
573
656
 
574
657
  cidReferenceRegex,
658
+ embedCidImages,
659
+ parseRetryAfter,
575
660
 
576
661
  /**
577
662
  * Establish an admin session: every full session write goes through here
@@ -623,7 +708,7 @@ module.exports = {
623
708
  * notifyTextSize / maxBytes cap is silently ignored on API accounts.
624
709
  * Mutates the passed object; only the "plain" and "html" keys are touched,
625
710
  * so an id reference or a flag riding on the same object is never clipped.
626
- * For byte-exact UTF-8 truncation see truncateToBytes in lib/mcp/tools.js,
711
+ * For byte-exact UTF-8 truncation see capText in lib/mcp/tools.js,
627
712
  * a different contract that is kept separate on purpose.
628
713
  * @param {Object} textContents Object carrying plain and/or html strings
629
714
  * @param {Number} maxBytes Size limit per text type, falsy means no limit
@@ -1331,10 +1416,6 @@ module.exports = {
1331
1416
  return counters;
1332
1417
  },
1333
1418
 
1334
- escapeRegExp(string) {
1335
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
1336
- },
1337
-
1338
1419
  // Escape Redis glob metacharacters (\ * ? [ ]) so a user-controlled identifier interpolated into
1339
1420
  // a SCAN/KEYS MATCH pattern matches literally and cannot widen the match across the key namespace
1340
1421
  // (security review H2). Intended wildcards in the surrounding pattern are added by the caller and
@@ -1386,7 +1467,9 @@ module.exports = {
1386
1467
  }
1387
1468
 
1388
1469
  if (typeof value === 'string') {
1389
- return /^(y|true)/i.test(value);
1470
+ // `on` and `enabled` are what several operators write in env files, and joi and
1471
+ // resolveHttpProxy() already read `on` as true
1472
+ return /^(y|true|on$|enabled$)/i.test(value);
1390
1473
  }
1391
1474
 
1392
1475
  return false; // ????
@@ -1605,7 +1688,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1605
1688
  imapConfig.tls.rejectUnauthorized = false;
1606
1689
  }
1607
1690
 
1608
- let imapClient = new ImapFlow(imapConfig);
1691
+ let imapClient = createImapClient(imapConfig);
1609
1692
 
1610
1693
  let mailboxes = await new Promise((resolve, reject) => {
1611
1694
  imapClient.on('error', err => {
@@ -1830,9 +1913,16 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1830
1913
 
1831
1914
  let passThrough = new PassThrough();
1832
1915
 
1916
+ // An account id may hold any character, but a header value may not: anything above U+00FF
1917
+ // made Node refuse to set the header and the download answered 500. So an ASCII-only
1918
+ // `filename` for old clients plus the RFC 5987 `filename*` carrying the real name.
1919
+ const filename = `logs.${account}.txt`;
1920
+ const asciiFilename = filename.replace(/[^\x20-\x7e]|["\\]/g, '_');
1921
+ const encodedFilename = encodeURIComponent(filename).replace(/['()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase());
1922
+
1833
1923
  passThrough.headers = {
1834
1924
  'content-type': 'text/plain',
1835
- 'content-disposition': `attachment; filename=${JSON.stringify(`logs.${account}.txt`)}`
1925
+ 'content-disposition': `attachment; filename="${asciiFilename}"; filename*=UTF-8''${encodedFilename}`
1836
1926
  };
1837
1927
 
1838
1928
  if (!rows || !Array.isArray(rows) || !rows.length) {
@@ -1932,7 +2022,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1932
2022
  let cmdstat_total = {
1933
2023
  calls: 0,
1934
2024
  usec: 0,
1935
- rejected_calls: 15,
2025
+ rejected_calls: 0,
1936
2026
  failed_calls: 0
1937
2027
  };
1938
2028
 
@@ -2222,7 +2312,16 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2222
2312
  continue;
2223
2313
  }
2224
2314
 
2225
- if (destination[propKey] && sourceVal && typeof destination[propKey] === 'object' && typeof sourceVal === 'object') {
2315
+ // Arrays are values, not records: merging them by index put back the tail of a longer
2316
+ // stored list (an OAuth2 `scope` narrowed by a partial token update kept its old scopes)
2317
+ if (
2318
+ destination[propKey] &&
2319
+ sourceVal &&
2320
+ typeof destination[propKey] === 'object' &&
2321
+ typeof sourceVal === 'object' &&
2322
+ !Array.isArray(destination[propKey]) &&
2323
+ !Array.isArray(sourceVal)
2324
+ ) {
2226
2325
  module.exports.mergeObjects(destination[propKey], sourceVal);
2227
2326
  continue;
2228
2327
  }
@@ -2281,7 +2380,6 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2281
2380
  name: opts.name,
2282
2381
  email: opts.email,
2283
2382
  expectedEmail: opts.expectedEmail,
2284
- syncFrom: (opts.syncFrom && opts.syncFrom.toISOString()) || null,
2285
2383
  notifyFrom: (opts.notifyFrom && opts.notifyFrom.toISOString()) || null,
2286
2384
  subconnections: opts.subconnections && opts.subconnections.length ? opts.subconnections : null,
2287
2385
  redirectUrl: opts.redirectUrl,
@@ -2480,36 +2578,6 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2480
2578
  return hostname;
2481
2579
  },
2482
2580
 
2483
- unpackUIDRangeForSearch(uid) {
2484
- uid = (uid || '').toString();
2485
- let parts = uid
2486
- .split(',')
2487
- .map(u => u.trim())
2488
- .filter(u => u);
2489
-
2490
- let queryEntries = [];
2491
-
2492
- for (let part of parts) {
2493
- if (!isNaN(part) && Number(part)) {
2494
- queryEntries.push(Number(part));
2495
- } else if (part.indexOf(':') >= 0) {
2496
- let entry = {};
2497
- let [a, b] = part.split(':');
2498
- if (!isNaN(a) && Number(a)) {
2499
- entry.gte = Number(a);
2500
- }
2501
- if (!isNaN(b) && Number(b)) {
2502
- entry.lte = Number(b);
2503
- }
2504
- if (Object.keys(entry).length) {
2505
- queryEntries.push(entry);
2506
- }
2507
- }
2508
- }
2509
-
2510
- return queryEntries;
2511
- },
2512
-
2513
2581
  comparePattern(pattern, input) {
2514
2582
  let regex;
2515
2583
  if (regexCache.has(pattern)) {
@@ -2745,13 +2813,6 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2745
2813
  resolveHttpProxy,
2746
2814
  createSocksAgent,
2747
2815
 
2748
- get fetchAgent() {
2749
- return httpAgent.fetch;
2750
- },
2751
- get retryAgent() {
2752
- return httpAgent.retry;
2753
- },
2754
-
2755
2816
  LRUCache,
2756
2817
 
2757
2818
  normalizeHashKeys,
package/lib/totp.js CHANGED
@@ -2,6 +2,11 @@
2
2
 
3
3
  const crypto = require('crypto');
4
4
  const { base32Encode } = require('./base32');
5
+ const qrcode = require('qrcode-generator');
6
+
7
+ // The otpauth URL is percent-encoded ASCII, but the encoder qrcode-generator selects by default
8
+ // keeps one byte per character, so it is switched to UTF-8 once here rather than relied on
9
+ qrcode.stringToBytes = qrcode.stringToBytesFuncs['UTF-8'];
5
10
 
6
11
  // In-house RFC 4226 / RFC 6238 TOTP implementation (SHA-1, 6 digits, 30-second period).
7
12
  // Replaces the unmaintained speakeasy package while staying byte-compatible with seeds it
@@ -64,4 +69,14 @@ function generateTotpUrl(seed, { label, issuer }) {
64
69
  return `otpauth://totp/${encodeURIComponent(label)}?secret=${base32Encode(Buffer.from(seed))}&issuer=${encodeURIComponent(issuer)}`;
65
70
  }
66
71
 
67
- module.exports = { generateTotpSeed, verifyTotp, generateTotpUrl };
72
+ // The enrolment QR code as a GIF data URL for the security page's <img>: error correction level
73
+ // M, 4 px per module inside a 4-module quiet zone, the geometry the qrcode package drew before it
74
+ // was replaced (it pulled a CLI stack in for this one call)
75
+ function generateTotpQrDataUrl(otpauthUrl) {
76
+ let qr = qrcode(0, 'M');
77
+ qr.addData(otpauthUrl);
78
+ qr.make();
79
+ return qr.createDataURL(4, 16);
80
+ }
81
+
82
+ module.exports = { generateTotpSeed, verifyTotp, generateTotpUrl, generateTotpQrDataUrl };
@@ -13,11 +13,13 @@ const Boom = require('@hapi/boom');
13
13
  const settings = require('../settings');
14
14
  const consts = require('../consts');
15
15
  const tokens = require('../tokens');
16
- const { redis, documentsQueue } = require('../db');
16
+ const { redis } = require('../db');
17
17
  const getSecret = require('../get-secret');
18
18
  const capa = require('../capa');
19
19
  const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../account');
20
20
  const { formatGmailWatch } = require('../account/account-state');
21
+ const { SPECIAL_USE_PATH_FIELDS } = require('./special-use-paths');
22
+
21
23
  const { Gateway } = require('../gateway');
22
24
  const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
23
25
  const { atomicIncrement } = require('../redis-operations');
@@ -42,7 +44,8 @@ const {
42
44
  accountIdSchema,
43
45
  defaultAccountTypeSchema,
44
46
  ACCOUNT_DISPLAY_STATES,
45
- signedFormBlobFields: signedBlobFields
47
+ signedFormBlobFields: signedBlobFields,
48
+ formBoolean
46
49
  } = require('../schemas');
47
50
  const {
48
51
  formatAccountData,
@@ -51,7 +54,8 @@ const {
51
54
  adminUrl,
52
55
  accountSuggestions,
53
56
  isClientError,
54
- closedAfterConnectMessage
57
+ closedAfterConnectMessage,
58
+ windowedPageLinks
55
59
  } = require('./route-helpers');
56
60
  const { webhooks: Webhooks } = require('../webhooks');
57
61
  const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
@@ -163,10 +167,12 @@ function init(args) {
163
167
  }
164
168
  }
165
169
  } catch (err) {
166
- // Account has invalid config (e.g., broken delegation)
167
- account.data = {
170
+ // Account has invalid config (e.g., broken delegation). The listing row keeps
171
+ // what it already carries (id, name, email, state) so the row still links to
172
+ // the account and can be deleted; only the error is added.
173
+ account.data = Object.assign({}, account, {
168
174
  delegationError: err.message
169
- };
175
+ });
170
176
  }
171
177
  }
172
178
 
@@ -249,11 +255,7 @@ function init(args) {
249
255
  nextPage,
250
256
  prevPage,
251
257
  firstPage: accounts.page === 0,
252
- pageLinks: new Array(accounts.pages || 1).fill(0).map((z, i) => ({
253
- url: getPagingUrl(i + 1, request.query.state, request.query.query),
254
- title: i + 1,
255
- active: i === accounts.page
256
- })),
258
+ pageLinks: windowedPageLinks(accounts.pages, accounts.page, page => getPagingUrl(page, request.query.state, request.query.query)),
257
259
 
258
260
  stateOptions,
259
261
 
@@ -415,7 +417,7 @@ function init(args) {
415
417
  account: data.account
416
418
  };
417
419
 
418
- for (let key of ['name', 'email', 'syncFrom', 'path']) {
420
+ for (let key of ['name', 'email', 'path']) {
419
421
  if (data[key]) {
420
422
  accountData[key] = data[key];
421
423
  }
@@ -627,16 +629,8 @@ function init(args) {
627
629
  .example(993)
628
630
  .description('Service port number')
629
631
  .label('IMAP port'),
630
- imap_secure: Joi.boolean()
631
- .truthy('Y', 'true', '1', 'on')
632
- .falsy('N', 'false', '0', 0, '')
633
- .default(false)
634
- .example(true)
635
- .description('Should connection use TLS. Usually true for port 993')
636
- .label('IMAP TLS'),
637
- imap_disabled: Joi.boolean()
638
- .truthy('Y', 'true', '1', 'on')
639
- .falsy('N', 'false', '0', 0, '')
632
+ imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993').label('IMAP TLS'),
633
+ imap_disabled: formBoolean()
640
634
  .default(false)
641
635
  .example(true)
642
636
  .description('Disable IMAP if you are using this email account to only send emails.')
@@ -652,13 +646,7 @@ function init(args) {
652
646
  .example(465)
653
647
  .description('Service port number')
654
648
  .label('SMTP port'),
655
- smtp_secure: Joi.boolean()
656
- .truthy('Y', 'true', '1', 'on')
657
- .falsy('N', 'false', '0', 0, '')
658
- .default(false)
659
- .example(true)
660
- .description('Should connection use TLS. Usually true for port 465')
661
- .label('SMTP TLS')
649
+ smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('SMTP TLS')
662
650
  };
663
651
 
664
652
  // The names above, in declaration order, for the checking page's hidden inputs - so the field set
@@ -1274,7 +1262,6 @@ function init(args) {
1274
1262
 
1275
1263
  notifyFrom: data.notifyFrom ? new Date(data.notifyFrom) : new Date(),
1276
1264
 
1277
- syncFrom: data.syncFrom || null,
1278
1265
  path: data.path || null,
1279
1266
 
1280
1267
  imap: {
@@ -1358,7 +1345,7 @@ function init(args) {
1358
1345
  url.searchParams.set('state', result.state);
1359
1346
  httpRedirectUrl = url.href;
1360
1347
  } else {
1361
- httpRedirectUrl = `/admin/accounts/${result.account}`;
1348
+ httpRedirectUrl = adminUrl`/admin/accounts/${result.account}`;
1362
1349
  }
1363
1350
 
1364
1351
  return renderRedirect(request, h, httpRedirectUrl);
@@ -1651,6 +1638,7 @@ function init(args) {
1651
1638
 
1652
1639
  menuAccounts: true,
1653
1640
  account: accountData,
1641
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
1654
1642
  accountAlert,
1655
1643
  accountParked: !!disabledByAuthFailureAt,
1656
1644
  logs: logInfo,
@@ -1676,7 +1664,7 @@ function init(args) {
1676
1664
  account: request.params.account,
1677
1665
  name: accountData.name,
1678
1666
  email: accountData.email,
1679
- redirectUrl: `/admin/accounts/${request.params.account}`,
1667
+ redirectUrl: adminUrl`/admin/accounts/${request.params.account}`,
1680
1668
 
1681
1669
  // Single-use nonce + timestamp so this blob (embedded in the account page and
1682
1670
  // used by the OAuth "Re-authenticate" form) cannot be replayed at the auth:false
@@ -1736,7 +1724,7 @@ function init(args) {
1736
1724
  path: '/admin/accounts/{account}/delete',
1737
1725
  async handler(request, h) {
1738
1726
  try {
1739
- let accountObject = new Account({ redis, account: request.params.account, documentsQueue, call, secret: await getSecret() });
1727
+ let accountObject = new Account({ redis, account: request.params.account, call, secret: await getSecret() });
1740
1728
 
1741
1729
  let { deleted } = await accountObject.delete();
1742
1730
  if (deleted) {
@@ -1958,7 +1946,7 @@ function init(args) {
1958
1946
  }),
1959
1947
 
1960
1948
  payload: Joi.object({
1961
- enabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false)
1949
+ enabled: formBoolean().default(false)
1962
1950
  })
1963
1951
  }
1964
1952
  }
@@ -2156,6 +2144,7 @@ function init(args) {
2156
2144
 
2157
2145
  menuAccounts: true,
2158
2146
  account: request.params.account,
2147
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
2159
2148
  values,
2160
2149
  availablePaths: JSON.stringify(mailboxes.map(entry => entry.path)),
2161
2150
 
@@ -2235,12 +2224,33 @@ function init(args) {
2235
2224
 
2236
2225
  let updateKeys = {};
2237
2226
 
2238
- for (let key of ['host', 'port', 'disabled', 'sentMailPath']) {
2227
+ for (let key of ['host', 'port', 'disabled']) {
2239
2228
  if (`imap_${key}` in request.payload) {
2240
2229
  updateKeys[key] = request.payload[`imap_${key}`];
2241
2230
  }
2242
2231
  }
2243
2232
 
2233
+ // The special-use folder overrides. An empty input means "no override" and has to
2234
+ // be written as null to unset one, while a field the form never showed must not be
2235
+ // written at all: these inputs live inside the IMAP section, which is hidden for an
2236
+ // account whose IMAP the operator switched off. The schema therefore allows the
2237
+ // empty string instead of defaulting to null - a default is inserted by joi for
2238
+ // every key the browser did not send, which made the presence check below always
2239
+ // true, so an unrelated save (a rename, a new webhook URL) wiped every override set
2240
+ // over PUT /v1/account/{account}. Same presence test imap_auth_user relies on.
2241
+ for (const field of SPECIAL_USE_PATH_FIELDS) {
2242
+ const payloadKey = `imap_${field.key}`;
2243
+ if (!(payloadKey in request.payload)) {
2244
+ continue;
2245
+ }
2246
+ const value = request.payload[payloadKey] || null;
2247
+ // Written only when the effective value changes, like the TLS flags below: an
2248
+ // untouched save must not add keys, because any imap diff forces a reconnect
2249
+ if (value !== ((oldData.imap && oldData.imap[field.key]) || null)) {
2250
+ updateKeys[field.key] = value;
2251
+ }
2252
+ }
2253
+
2244
2254
  if ('imap_auth_user' in request.payload) {
2245
2255
  let imapAuth = Object.assign((oldData.imap && oldData.imap.auth) || {}, { user: request.payload.imap_auth_user });
2246
2256
  if (request.payload.imap_auth_pass) {
@@ -2319,6 +2329,7 @@ function init(args) {
2319
2329
 
2320
2330
  menuAccounts: true,
2321
2331
  account: request.params.account,
2332
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
2322
2333
  // re-render the form from the submitted payload (the field names
2323
2334
  // match the template values); without this the form comes back
2324
2335
  // blank and the IMAP/SMTP cards disappear entirely
@@ -2376,6 +2387,7 @@ function init(args) {
2376
2387
 
2377
2388
  menuAccounts: true,
2378
2389
  account: request.params.account,
2390
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
2379
2391
  errors,
2380
2392
  // re-render the form from the (raw, unvalidated) submitted
2381
2393
  // payload so the entered values and the IMAP/SMTP cards
@@ -2413,7 +2425,7 @@ function init(args) {
2413
2425
  proxy: settingsSchema.proxyUrl,
2414
2426
  smtpEhloName: settingsSchema.smtpEhloName,
2415
2427
 
2416
- imap: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
2428
+ imap: formBoolean().default(false),
2417
2429
 
2418
2430
  imap_auth_user: Joi.string().empty('').trim().max(1024),
2419
2431
  imap_auth_pass: Joi.string().empty('').max(1024),
@@ -2424,39 +2436,31 @@ function init(args) {
2424
2436
  .max(64 * 1024)
2425
2437
  .example(993)
2426
2438
  .description('Service port number'),
2427
- imap_secure: Joi.boolean()
2428
- .truthy('Y', 'true', '1', 'on')
2429
- .falsy('N', 'false', 0, '')
2430
- .default(false)
2431
- .example(true)
2432
- .description('Should connection use TLS. Usually true for port 993'),
2433
- imap_tls_ignoreCertErrors: Joi.boolean()
2434
- .truthy('Y', 'true', '1', 'on')
2435
- .falsy('N', 'false', 0, '')
2439
+ imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993'),
2440
+ imap_tls_ignoreCertErrors: formBoolean()
2436
2441
  .default(false)
2437
2442
  .example(false)
2438
2443
  .description('Allow connections to servers with invalid TLS certificates for this account'),
2439
- imap_disableIMAP4rev2: Joi.boolean()
2440
- .truthy('Y', 'true', '1', 'on')
2441
- .falsy('N', 'false', 0, '')
2442
- .default(false)
2443
- .example(false)
2444
- .description('Do not use IMAP4rev2 even if the server supports it'),
2445
- imap_disabled: Joi.boolean()
2446
- .truthy('Y', 'true', '1', 'on')
2447
- .falsy('N', 'false', 0, '')
2444
+ imap_disableIMAP4rev2: formBoolean().default(false).example(false).description('Do not use IMAP4rev2 even if the server supports it'),
2445
+ imap_disabled: formBoolean()
2448
2446
  .default(false)
2449
2447
  .example(true)
2450
2448
  .description('Disable IMAP if you are using this email account to only send emails.'),
2451
2449
 
2452
2450
  imap_resyncDelay: Joi.number().integer().empty(''),
2453
2451
 
2454
- imap_sentMailPath: Joi.string()
2455
- .empty('')
2456
- .default(null)
2457
- .max(1024)
2458
- .example('Sent Mail')
2459
- .description("Upload sent message to this folder. By default the account's Sent Mail folder is used. Leave empty to unset."),
2452
+ // allow('') rather than empty('').default(null): see the write loop above, where the
2453
+ // presence of the key is what says the form showed the field at all
2454
+ ...Object.fromEntries(
2455
+ SPECIAL_USE_PATH_FIELDS.map(field => [
2456
+ `imap_${field.key}`,
2457
+ Joi.string()
2458
+ .allow('', null)
2459
+ .max(1024)
2460
+ .example(field.label)
2461
+ .description(`${field.description} Leave empty to use the folder EmailEngine detects.`)
2462
+ ])
2463
+ ),
2460
2464
 
2461
2465
  webhooks: Joi.string()
2462
2466
  .uri({
@@ -2468,7 +2472,7 @@ function init(args) {
2468
2472
  .example('https://myservice.com/imap/webhooks')
2469
2473
  .description('Account-specific webhook URL'),
2470
2474
 
2471
- smtp: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
2475
+ smtp: formBoolean().default(false),
2472
2476
 
2473
2477
  smtp_auth_user: Joi.string().empty('').trim().max(1024),
2474
2478
  smtp_auth_pass: Joi.string().empty('').max(1024),
@@ -2479,15 +2483,8 @@ function init(args) {
2479
2483
  .max(64 * 1024)
2480
2484
  .example(465)
2481
2485
  .description('Service port number'),
2482
- smtp_secure: Joi.boolean()
2483
- .truthy('Y', 'true', '1', 'on')
2484
- .falsy('N', 'false', 0, '')
2485
- .default(false)
2486
- .example(true)
2487
- .description('Should connection use TLS. Usually true for port 465'),
2488
- smtp_tls_ignoreCertErrors: Joi.boolean()
2489
- .truthy('Y', 'true', '1', 'on')
2490
- .falsy('N', 'false', 0, '')
2486
+ smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465'),
2487
+ smtp_tls_ignoreCertErrors: formBoolean()
2491
2488
  .default(false)
2492
2489
  .example(false)
2493
2490
  .description('Allow connections to servers with invalid TLS certificates for this account'),