emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  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-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. 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
@@ -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,7 +13,7 @@ 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');
@@ -42,7 +42,8 @@ const {
42
42
  accountIdSchema,
43
43
  defaultAccountTypeSchema,
44
44
  ACCOUNT_DISPLAY_STATES,
45
- signedFormBlobFields: signedBlobFields
45
+ signedFormBlobFields: signedBlobFields,
46
+ formBoolean
46
47
  } = require('../schemas');
47
48
  const {
48
49
  formatAccountData,
@@ -51,7 +52,8 @@ const {
51
52
  adminUrl,
52
53
  accountSuggestions,
53
54
  isClientError,
54
- closedAfterConnectMessage
55
+ closedAfterConnectMessage,
56
+ windowedPageLinks
55
57
  } = require('./route-helpers');
56
58
  const { webhooks: Webhooks } = require('../webhooks');
57
59
  const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
@@ -163,10 +165,12 @@ function init(args) {
163
165
  }
164
166
  }
165
167
  } catch (err) {
166
- // Account has invalid config (e.g., broken delegation)
167
- account.data = {
168
+ // Account has invalid config (e.g., broken delegation). The listing row keeps
169
+ // what it already carries (id, name, email, state) so the row still links to
170
+ // the account and can be deleted; only the error is added.
171
+ account.data = Object.assign({}, account, {
168
172
  delegationError: err.message
169
- };
173
+ });
170
174
  }
171
175
  }
172
176
 
@@ -249,11 +253,7 @@ function init(args) {
249
253
  nextPage,
250
254
  prevPage,
251
255
  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
- })),
256
+ pageLinks: windowedPageLinks(accounts.pages, accounts.page, page => getPagingUrl(page, request.query.state, request.query.query)),
257
257
 
258
258
  stateOptions,
259
259
 
@@ -415,7 +415,7 @@ function init(args) {
415
415
  account: data.account
416
416
  };
417
417
 
418
- for (let key of ['name', 'email', 'syncFrom', 'path']) {
418
+ for (let key of ['name', 'email', 'path']) {
419
419
  if (data[key]) {
420
420
  accountData[key] = data[key];
421
421
  }
@@ -627,16 +627,8 @@ function init(args) {
627
627
  .example(993)
628
628
  .description('Service port number')
629
629
  .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, '')
630
+ imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993').label('IMAP TLS'),
631
+ imap_disabled: formBoolean()
640
632
  .default(false)
641
633
  .example(true)
642
634
  .description('Disable IMAP if you are using this email account to only send emails.')
@@ -652,13 +644,7 @@ function init(args) {
652
644
  .example(465)
653
645
  .description('Service port number')
654
646
  .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')
647
+ smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('SMTP TLS')
662
648
  };
663
649
 
664
650
  // The names above, in declaration order, for the checking page's hidden inputs - so the field set
@@ -1274,7 +1260,6 @@ function init(args) {
1274
1260
 
1275
1261
  notifyFrom: data.notifyFrom ? new Date(data.notifyFrom) : new Date(),
1276
1262
 
1277
- syncFrom: data.syncFrom || null,
1278
1263
  path: data.path || null,
1279
1264
 
1280
1265
  imap: {
@@ -1358,7 +1343,7 @@ function init(args) {
1358
1343
  url.searchParams.set('state', result.state);
1359
1344
  httpRedirectUrl = url.href;
1360
1345
  } else {
1361
- httpRedirectUrl = `/admin/accounts/${result.account}`;
1346
+ httpRedirectUrl = adminUrl`/admin/accounts/${result.account}`;
1362
1347
  }
1363
1348
 
1364
1349
  return renderRedirect(request, h, httpRedirectUrl);
@@ -1676,7 +1661,7 @@ function init(args) {
1676
1661
  account: request.params.account,
1677
1662
  name: accountData.name,
1678
1663
  email: accountData.email,
1679
- redirectUrl: `/admin/accounts/${request.params.account}`,
1664
+ redirectUrl: adminUrl`/admin/accounts/${request.params.account}`,
1680
1665
 
1681
1666
  // Single-use nonce + timestamp so this blob (embedded in the account page and
1682
1667
  // used by the OAuth "Re-authenticate" form) cannot be replayed at the auth:false
@@ -1736,7 +1721,7 @@ function init(args) {
1736
1721
  path: '/admin/accounts/{account}/delete',
1737
1722
  async handler(request, h) {
1738
1723
  try {
1739
- let accountObject = new Account({ redis, account: request.params.account, documentsQueue, call, secret: await getSecret() });
1724
+ let accountObject = new Account({ redis, account: request.params.account, call, secret: await getSecret() });
1740
1725
 
1741
1726
  let { deleted } = await accountObject.delete();
1742
1727
  if (deleted) {
@@ -1958,7 +1943,7 @@ function init(args) {
1958
1943
  }),
1959
1944
 
1960
1945
  payload: Joi.object({
1961
- enabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false)
1946
+ enabled: formBoolean().default(false)
1962
1947
  })
1963
1948
  }
1964
1949
  }
@@ -2413,7 +2398,7 @@ function init(args) {
2413
2398
  proxy: settingsSchema.proxyUrl,
2414
2399
  smtpEhloName: settingsSchema.smtpEhloName,
2415
2400
 
2416
- imap: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
2401
+ imap: formBoolean().default(false),
2417
2402
 
2418
2403
  imap_auth_user: Joi.string().empty('').trim().max(1024),
2419
2404
  imap_auth_pass: Joi.string().empty('').max(1024),
@@ -2424,27 +2409,13 @@ function init(args) {
2424
2409
  .max(64 * 1024)
2425
2410
  .example(993)
2426
2411
  .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, '')
2412
+ imap_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 993'),
2413
+ imap_tls_ignoreCertErrors: formBoolean()
2436
2414
  .default(false)
2437
2415
  .example(false)
2438
2416
  .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, '')
2417
+ imap_disableIMAP4rev2: formBoolean().default(false).example(false).description('Do not use IMAP4rev2 even if the server supports it'),
2418
+ imap_disabled: formBoolean()
2448
2419
  .default(false)
2449
2420
  .example(true)
2450
2421
  .description('Disable IMAP if you are using this email account to only send emails.'),
@@ -2468,7 +2439,7 @@ function init(args) {
2468
2439
  .example('https://myservice.com/imap/webhooks')
2469
2440
  .description('Account-specific webhook URL'),
2470
2441
 
2471
- smtp: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
2442
+ smtp: formBoolean().default(false),
2472
2443
 
2473
2444
  smtp_auth_user: Joi.string().empty('').trim().max(1024),
2474
2445
  smtp_auth_pass: Joi.string().empty('').max(1024),
@@ -2479,15 +2450,8 @@ function init(args) {
2479
2450
  .max(64 * 1024)
2480
2451
  .example(465)
2481
2452
  .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, '')
2453
+ smtp_secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465'),
2454
+ smtp_tls_ignoreCertErrors: formBoolean()
2491
2455
  .default(false)
2492
2456
  .example(false)
2493
2457
  .description('Allow connections to servers with invalid TLS certificates for this account'),