emailengine-app 2.76.0 → 2.78.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 (165) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.github/workflows/test.yml +80 -0
  3. package/.ncurc.js +14 -2
  4. package/.release-please-manifest.json +3 -0
  5. package/CHANGELOG.md +54 -0
  6. package/README.md +1 -1
  7. package/bin/emailengine.js +1 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +72 -5
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +75 -26
  12. package/lib/address-strategies.js +18 -0
  13. package/lib/api-reference/code-samples.js +194 -0
  14. package/lib/api-reference/format.js +193 -0
  15. package/lib/api-reference/index.js +222 -0
  16. package/lib/api-reference/model.js +338 -0
  17. package/lib/api-reference/schema-tree.js +366 -0
  18. package/lib/api-routes/account-routes.js +136 -39
  19. package/lib/api-routes/behavior-notes.js +57 -0
  20. package/lib/api-routes/blocklist-routes.js +9 -9
  21. package/lib/api-routes/changes-routes.js +6 -4
  22. package/lib/api-routes/chat-routes.js +3 -3
  23. package/lib/api-routes/delivery-test-routes.js +24 -6
  24. package/lib/api-routes/export-routes.js +14 -12
  25. package/lib/api-routes/gateway-routes.js +11 -11
  26. package/lib/api-routes/license-routes.js +7 -7
  27. package/lib/api-routes/mailbox-routes.js +18 -9
  28. package/lib/api-routes/message-routes.js +55 -35
  29. package/lib/api-routes/oauth2-app-routes.js +22 -16
  30. package/lib/api-routes/outbox-routes.js +7 -7
  31. package/lib/api-routes/pubsub-routes.js +3 -3
  32. package/lib/api-routes/settings-routes.js +10 -9
  33. package/lib/api-routes/stats-routes.js +3 -3
  34. package/lib/api-routes/submit-routes.js +58 -8
  35. package/lib/api-routes/template-routes.js +13 -13
  36. package/lib/api-routes/token-routes.js +15 -10
  37. package/lib/api-routes/webhook-route-routes.js +5 -5
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/autodetect-imap-settings.js +40 -16
  41. package/lib/base32.js +30 -0
  42. package/lib/bounce-detect.js +182 -62
  43. package/lib/consts.js +7 -0
  44. package/lib/egress-filter.js +89 -8
  45. package/lib/email-client/base-client.js +72 -82
  46. package/lib/email-client/gmail-client.js +3 -3
  47. package/lib/email-client/imap/listing-diff.js +3 -3
  48. package/lib/email-client/imap/mailbox.js +5 -69
  49. package/lib/email-client/imap-client.js +3 -2
  50. package/lib/email-client/message-builder.js +13 -13
  51. package/lib/email-client/outlook-client.js +1 -1
  52. package/lib/enum-descriptions.js +130 -0
  53. package/lib/export.js +1 -1
  54. package/lib/gateway.js +1 -1
  55. package/lib/get-raw-email.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  57. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  58. package/lib/imapproxy/imap-server.js +42 -28
  59. package/lib/imapproxy/upstream-client.js +38 -0
  60. package/lib/license-beacon.js +1 -1
  61. package/lib/llm-pre-process.js +1 -1
  62. package/lib/msgpack.js +62 -0
  63. package/lib/oauth/decode-jwt-payload.js +39 -0
  64. package/lib/oauth/outlook-identity.js +61 -0
  65. package/lib/oauth/retry-setup.js +38 -0
  66. package/lib/oauth2-apps.js +10 -4
  67. package/lib/openapi/build-document.js +318 -0
  68. package/lib/openapi/index.js +95 -0
  69. package/lib/openapi/joi-schema.js +523 -0
  70. package/lib/outbox.js +66 -3
  71. package/lib/pre-process.js +1 -1
  72. package/lib/read-env-value.js +37 -0
  73. package/lib/routes-ui.js +5 -1
  74. package/lib/schemas.js +88 -17
  75. package/lib/swagger-options.js +173 -0
  76. package/lib/templates.js +1 -1
  77. package/lib/tokens.js +70 -6
  78. package/lib/tools.js +117 -48
  79. package/lib/totp.js +67 -0
  80. package/lib/ui-routes/account-routes.js +91 -15
  81. package/lib/ui-routes/admin-config-routes.js +2 -7
  82. package/lib/ui-routes/admin-entities-routes.js +3 -0
  83. package/lib/ui-routes/auth-routes.js +6 -24
  84. package/lib/ui-routes/dashboard-routes.js +2 -26
  85. package/lib/ui-routes/reference-routes.js +198 -0
  86. package/lib/ui-routes/route-helpers.js +39 -0
  87. package/lib/utils/is-email.js +34 -0
  88. package/lib/utils/to-camel-case.js +17 -0
  89. package/lib/webhook-egress.js +37 -0
  90. package/lib/webhooks.js +1 -1
  91. package/package.json +27 -31
  92. package/prepare-bundle-deps.sh +28 -0
  93. package/release-please-config.json +11 -0
  94. package/sbom.json +1 -1
  95. package/server.js +11 -3
  96. package/static/css/flyonui.css +1 -1
  97. package/static/css/public.css +3 -0
  98. package/static/css/src/app.tailwind.css +113 -0
  99. package/static/js/app.js +69 -0
  100. package/static/js/ee-client.js +238 -8
  101. package/static/js/reference.js +1021 -0
  102. package/static/js/ui.js +61 -33
  103. package/static/licenses.html +658 -1560
  104. package/translations/README.md +64 -0
  105. package/translations/de.mo +0 -0
  106. package/translations/de.po +164 -120
  107. package/translations/en.po +200 -161
  108. package/translations/et.mo +0 -0
  109. package/translations/et.po +163 -120
  110. package/translations/fr.mo +0 -0
  111. package/translations/fr.po +163 -120
  112. package/translations/ja.mo +0 -0
  113. package/translations/ja.po +163 -120
  114. package/translations/messages.pot +84 -54
  115. package/translations/nl.mo +0 -0
  116. package/translations/nl.po +164 -120
  117. package/translations/pl.mo +0 -0
  118. package/translations/pl.po +163 -120
  119. package/views/account-identity-error.hbs +34 -0
  120. package/views/accounts/edit.hbs +1 -0
  121. package/views/accounts/register/imap.hbs +12 -2
  122. package/views/config/ai.hbs +1 -1
  123. package/views/config/document-store/chat.hbs +5 -5
  124. package/views/config/document-store/index.hbs +2 -2
  125. package/views/config/document-store/pre-processing/index.hbs +1 -1
  126. package/views/config/email-processing.hbs +1 -1
  127. package/views/config/imap-proxy.hbs +1 -1
  128. package/views/config/license.hbs +1 -1
  129. package/views/config/oauth/index.hbs +3 -3
  130. package/views/config/security.hbs +1 -1
  131. package/views/config/smtp.hbs +2 -2
  132. package/views/dashboard.hbs +1 -1
  133. package/views/layout/app.hbs +43 -8
  134. package/views/oauth-scope-error.hbs +1 -1
  135. package/views/partials/oauth_form.hbs +4 -4
  136. package/views/partials/reference/anchor-link.hbs +20 -0
  137. package/views/partials/reference/disclosure.hbs +37 -0
  138. package/views/partials/reference/nav.hbs +120 -0
  139. package/views/partials/reference/operation.hbs +127 -0
  140. package/views/partials/reference/params.hbs +20 -0
  141. package/views/partials/reference/schema-node.hbs +99 -0
  142. package/views/partials/reference/schema.hbs +19 -0
  143. package/views/partials/reference/section-heading.hbs +16 -0
  144. package/views/partials/reference/token-alert.hbs +49 -0
  145. package/views/partials/reference/try-field.hbs +31 -0
  146. package/views/partials/reference/try-it.hbs +78 -0
  147. package/views/partials/side_menu.hbs +1 -1
  148. package/views/partials/ui/badge.hbs +4 -2
  149. package/views/partials/ui/page-header.hbs +1 -1
  150. package/views/partials/ui/search-input.hbs +31 -0
  151. package/views/partials/ui/setting-ref.hbs +1 -1
  152. package/views/partials/ui/stat-card.hbs +4 -2
  153. package/views/partials/ui/tab.hbs +6 -1
  154. package/views/partials/ui/tabs.hbs +2 -2
  155. package/views/reference/index.hbs +76 -0
  156. package/views/reference/redirect.hbs +49 -0
  157. package/views/reference/tag.hbs +28 -0
  158. package/views/reference/token.hbs +49 -0
  159. package/views/tokens/index.hbs +9 -1
  160. package/views/webhooks/index.hbs +3 -3
  161. package/workers/api.js +194 -302
  162. package/workers/imap.js +1 -1
  163. package/workers/submit.js +1 -1
  164. package/workers/webhooks.js +2 -13
  165. package/views/swagger/index.hbs +0 -82
package/lib/tools.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  'use strict';
4
4
 
5
- const msgpack = require('msgpack5')();
5
+ const msgpack = require('./msgpack');
6
6
  const enumMessageFlags = require('./enum-message-flags');
7
7
  const Joi = require('joi');
8
8
  const he = require('he');
@@ -27,6 +27,8 @@ const pathlib = require('path');
27
27
  const { randomUUID: uuid } = require('crypto');
28
28
  const mimeTypes = require('nodemailer/lib/mime-funcs/mime-types');
29
29
  const { v3: murmurhash } = require('murmurhash');
30
+ const { isEmail } = require('./utils/is-email');
31
+ const { toCamelCase } = require('./utils/to-camel-case');
30
32
  const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
31
33
  const {
32
34
  REDIS_PREFIX,
@@ -49,6 +51,8 @@ const { getLocalAddress } = require('./utils/network');
49
51
  const { fetch: fetchCmd, Agent, RetryAgent, ProxyAgent } = require('undici');
50
52
  const tls = require('tls');
51
53
  const { SocksClient } = require('socks');
54
+ const { createWebhookLookup, WEBHOOK_EGRESS_POLICY } = require('./webhook-egress');
55
+ const { readEnvValue } = require('./read-env-value');
52
56
 
53
57
  const AGENT_OPTS = {
54
58
  strictContentLength: false,
@@ -82,19 +86,46 @@ const RETRY_OPTS = {
82
86
  ]
83
87
  };
84
88
 
89
+ // Webhook deliveries are the one outbound path whose destination the operator supplies, so they
90
+ // get a dispatcher that resolves through the egress policy (lib/webhook-egress.js) rather than the
91
+ // shared resolver. It is built here because its lifetime is tied to the other agents': a proxy
92
+ // setting change swaps them all out together.
93
+ function buildWebhookDispatcher(proxied, existing) {
94
+ const lookup = createWebhookLookup();
95
+
96
+ // Behind a proxy the target hostname is resolved by the proxy, not here, so a local lookup can
97
+ // only vet the route to the proxy itself. There is nothing to bind; fall back to the shared
98
+ // dispatcher and leave assertAllowedUrl() as the advisory check it can only be in that setup.
99
+ if (proxied || !lookup) {
100
+ return httpAgent.retry;
101
+ }
102
+
103
+ // Nothing a reload changes can affect a dedicated dispatcher - the policy is fixed at startup
104
+ // and the Agent never references httpAgent.fetch - so reuse it rather than discarding warm
105
+ // sockets. Saving the network settings form reloads on any field, not just a proxy one.
106
+ return existing || new RetryAgent(new Agent(Object.assign({}, AGENT_OPTS, { connect: { lookup } })), RETRY_OPTS);
107
+ }
108
+
85
109
  // Shared mutable object -- consumers import the object reference and access
86
- // .fetch / .retry at call time, so replacing properties here is visible everywhere.
110
+ // .fetch / .retry / .webhook at call time, so replacing properties here is visible everywhere.
87
111
  const httpAgent = {
88
112
  fetch: new Agent(AGENT_OPTS),
89
- retry: null
113
+ retry: null,
114
+ webhook: null
90
115
  };
91
116
  httpAgent.retry = new RetryAgent(httpAgent.fetch, RETRY_OPTS);
117
+ httpAgent.webhook = buildWebhookDispatcher(false, null);
92
118
 
93
119
  // Backward-compat aliases (read from httpAgent at call time via getter)
94
120
  // backward-compat aliases are defined as getters on module.exports below
95
121
 
96
122
  const SOCKS4_PROTOCOLS = new Set(['socks4:', 'socks4a:']);
97
123
 
124
+ // Accounts a stale-useAuthServer warning was already logged for, keyed by account:target.
125
+ // getActiveAccessTokenData() runs once per API request, so an unconditional warn would repeat
126
+ // the same line for the lifetime of the stale flag.
127
+ const AUTH_SERVER_FALLBACK_WARNED = new Set();
128
+
98
129
  function createSocksAgent(proxyUrl, agentOpts) {
99
130
  let parsed = new URL(proxyUrl);
100
131
  let proxyType = SOCKS4_PROTOCOLS.has(parsed.protocol) ? 4 : 5;
@@ -194,6 +225,9 @@ async function _doReloadHttpProxyAgent() {
194
225
  }
195
226
 
196
227
  let oldFetch = httpAgent.fetch;
228
+ // Only a dedicated dispatcher is ours to close; when webhooks share the general one it is
229
+ // closed via oldFetch. Read before anything is swapped, while the comparison still holds.
230
+ let oldWebhook = httpAgent.webhook !== httpAgent.retry ? httpAgent.webhook : null;
197
231
 
198
232
  try {
199
233
  if (enabled && proxyUrl) {
@@ -217,20 +251,27 @@ async function _doReloadHttpProxyAgent() {
217
251
  }
218
252
 
219
253
  httpAgent.retry = new RetryAgent(httpAgent.fetch, RETRY_OPTS);
254
+ httpAgent.webhook = buildWebhookDispatcher(!!(enabled && proxyUrl), oldWebhook);
220
255
 
221
256
  logger.info({
222
257
  msg: 'HTTP proxy agent reloaded',
223
258
  httpProxyEnabled: !!enabled,
224
- httpProxyUrl: enabled && proxyUrl ? proxyUrl : null
259
+ httpProxyUrl: enabled && proxyUrl ? proxyUrl : null,
260
+ webhookEgressPolicy: WEBHOOK_EGRESS_POLICY,
261
+ webhookEgressPinned: httpAgent.webhook !== httpAgent.retry
225
262
  });
226
263
 
227
- if (oldFetch && oldFetch !== httpAgent.fetch) {
228
- try {
229
- await oldFetch.close();
230
- } catch (err) {
231
- // ignore close errors
232
- }
233
- }
264
+ // Closing is graceful, so it waits for whatever is still in flight to drain. Overlap the
265
+ // two rather than making one agent's slow request hold the other's sockets open.
266
+ // Closing a RetryAgent closes the Agent it wraps.
267
+ await Promise.all(
268
+ [
269
+ [oldFetch, httpAgent.fetch],
270
+ [oldWebhook, httpAgent.webhook]
271
+ ]
272
+ .filter(([stale, current]) => stale && stale !== current)
273
+ .map(([stale]) => stale.close().catch(() => false))
274
+ );
234
275
  } catch (err) {
235
276
  logger.error({ msg: 'Failed to create HTTP proxy agent, keeping existing agent', err });
236
277
  }
@@ -278,6 +319,9 @@ function resolveOAuthErrorStatus(responseError, err) {
278
319
  }
279
320
 
280
321
  module.exports = {
322
+ // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
323
+ toCamelCase,
324
+
281
325
  /**
282
326
  * Establish an admin session: every full session write goes through here
283
327
  * so the session always carries a random sid. The message browser binds
@@ -614,6 +658,63 @@ module.exports = {
614
658
  return value;
615
659
  },
616
660
 
661
+ // Whether a `useAuthServer` flag should be honored. The flag was accepted and stored but
662
+ // silently ignored on several code paths for years, so long-lived instances carry it on
663
+ // accounts that were never auth-server backed and sync fine on their stored credentials.
664
+ // Honoring such a stale flag on an instance with no auth server configured can only fail,
665
+ // so when the caller has stored credentials to fall back to, the flag is ignored with a
666
+ // warning instead of parking the account. Call sites use the useAuthServerForOAuth2() /
667
+ // useAuthServerForConnection() wrappers below, which pair the config shape with the right
668
+ // credential predicate.
669
+ async shouldUseAuthServer(hasStoredCredentials, logger, meta) {
670
+ if (!hasStoredCredentials) {
671
+ // Nothing to fall back to - consult the auth server and let resolveCredentials()
672
+ // report the missing configuration.
673
+ return true;
674
+ }
675
+
676
+ if (await settings.get('authServer')) {
677
+ return true;
678
+ }
679
+
680
+ const warnKey = `${meta && meta.account}:${meta && meta.target}`;
681
+ if (!AUTH_SERVER_FALLBACK_WARNED.has(warnKey)) {
682
+ AUTH_SERVER_FALLBACK_WARNED.add(warnKey);
683
+ logger.warn({
684
+ msg: 'Ignoring the useAuthServer flag: no authentication server is configured, using stored credentials instead',
685
+ ...meta
686
+ });
687
+ }
688
+
689
+ return false;
690
+ },
691
+
692
+ // Whether an oauth2 block holds tokens EmailEngine can use on its own: a refresh token to
693
+ // renew from, or an access token that may still be valid. Only the top-level fields count -
694
+ // the renew and cached-token paths never read tokens nested under `auth`.
695
+ hasStoredOAuth2Tokens(oauth2Data) {
696
+ return Boolean(oauth2Data.refreshToken || oauth2Data.accessToken);
697
+ },
698
+
699
+ // Whether an imap/smtp connection config carries complete stored credentials.
700
+ hasStoredServerCredentials(connectionConfig) {
701
+ const auth = connectionConfig.auth;
702
+ return Boolean(auth && auth.user && (auth.pass || auth.accessToken));
703
+ },
704
+
705
+ // Should this oauth2 block be resolved through the external auth server?
706
+ async useAuthServerForOAuth2(oauth2Data, logger, meta) {
707
+ return Boolean(oauth2Data.useAuthServer) && (await module.exports.shouldUseAuthServer(module.exports.hasStoredOAuth2Tokens(oauth2Data), logger, meta));
708
+ },
709
+
710
+ // Should this imap/smtp connection config be resolved through the external auth server?
711
+ async useAuthServerForConnection(connectionConfig, logger, meta) {
712
+ return (
713
+ Boolean(connectionConfig.useAuthServer) &&
714
+ (await module.exports.shouldUseAuthServer(module.exports.hasStoredServerCredentials(connectionConfig), logger, meta))
715
+ );
716
+ },
717
+
617
718
  getWorkerCount(processCount) {
618
719
  if (/^\s*cpus\s*$/i.test(processCount)) {
619
720
  processCount = os.cpus().length;
@@ -1320,26 +1421,9 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1320
1421
  }
1321
1422
  },
1322
1423
 
1323
- isEmail(str) {
1324
- const schema = Joi.object({
1325
- email: Joi.string().email().required()
1326
- });
1327
-
1328
- const { error, value } = schema.validate(
1329
- { email: str },
1330
- {
1331
- abortEarly: false,
1332
- stripUnknown: true,
1333
- convert: true
1334
- }
1335
- );
1336
-
1337
- if (error) {
1338
- return false;
1339
- }
1340
-
1341
- return value.email;
1342
- },
1424
+ // Re-exported from lib/utils/is-email.js so pure modules can use the same check without requiring
1425
+ // this file (and with it settings and Redis). Keep the re-export - callers import it from here.
1426
+ isEmail,
1343
1427
 
1344
1428
  async emitChangeEvent(logger, account, type, key, payload) {
1345
1429
  try {
@@ -1813,6 +1897,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1813
1897
  account: opts.account,
1814
1898
  name: opts.name,
1815
1899
  email: opts.email,
1900
+ expectedEmail: opts.expectedEmail,
1816
1901
  syncFrom: (opts.syncFrom && opts.syncFrom.toISOString()) || null,
1817
1902
  notifyFrom: (opts.notifyFrom && opts.notifyFrom.toISOString()) || null,
1818
1903
  subconnections: opts.subconnections && opts.subconnections.length ? opts.subconnections : null,
@@ -2060,23 +2145,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2060
2145
  .filter(v => v);
2061
2146
  },
2062
2147
 
2063
- readEnvValue(key) {
2064
- if (key in process.env) {
2065
- return process.env[key];
2066
- }
2067
-
2068
- if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
2069
- try {
2070
- // try to load from file
2071
- process.env[key] = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n/g, '\n').trim();
2072
- logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
2073
- } catch (err) {
2074
- logger.fatal({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
2075
- process.env[key] = '';
2076
- }
2077
- return process.env[key];
2078
- }
2079
- },
2148
+ readEnvValue,
2080
2149
 
2081
2150
  convertDataUrisToAttachments(data) {
2082
2151
  if (data.html) {
package/lib/totp.js ADDED
@@ -0,0 +1,67 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { base32Encode } = require('./base32');
5
+
6
+ // In-house RFC 4226 / RFC 6238 TOTP implementation (SHA-1, 6 digits, 30-second period).
7
+ // Replaces the unmaintained speakeasy package while staying byte-compatible with seeds it
8
+ // generated: `totpSeed` is stored as an ASCII string and its raw bytes are the shared secret.
9
+
10
+ const TOTP_STEP_SECONDS = 30;
11
+ const TOTP_DIGITS = 6;
12
+ const TOTP_TOKEN_RE = new RegExp(`^[0-9]{${TOTP_DIGITS}}$`);
13
+
14
+ const SEED_LENGTH = 20;
15
+ const SEED_CHARSET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
16
+
17
+ function hotp(secret, counter) {
18
+ let counterBuf = Buffer.alloc(8);
19
+ counterBuf.writeBigUInt64BE(BigInt(counter));
20
+
21
+ let digest = crypto.createHmac('sha1', secret).update(counterBuf).digest();
22
+
23
+ let offset = digest[digest.length - 1] & 0x0f;
24
+ let code = (digest.readUInt32BE(offset) & 0x7fffffff) % 10 ** TOTP_DIGITS;
25
+
26
+ return code.toString().padStart(TOTP_DIGITS, '0');
27
+ }
28
+
29
+ function generateTotpSeed() {
30
+ let seed = '';
31
+ for (let i = 0; i < SEED_LENGTH; i++) {
32
+ seed += SEED_CHARSET[crypto.randomInt(SEED_CHARSET.length)];
33
+ }
34
+ return seed;
35
+ }
36
+
37
+ function verifyTotp(seed, token, options) {
38
+ let { window = 0, now = Date.now() } = options || {};
39
+
40
+ token = (token || '').toString().trim();
41
+ if (!TOTP_TOKEN_RE.test(token)) {
42
+ return false;
43
+ }
44
+
45
+ let secret = Buffer.from(seed);
46
+ let tokenBuf = Buffer.from(token);
47
+ let counter = Math.floor(now / 1000 / TOTP_STEP_SECONDS);
48
+
49
+ let verified = false;
50
+ for (let delta = -window; delta <= window; delta++) {
51
+ if (counter + delta < 0) {
52
+ continue;
53
+ }
54
+ // no early break - every offset is checked so response timing does not depend on which one matched
55
+ if (crypto.timingSafeEqual(Buffer.from(hotp(secret, counter + delta)), tokenBuf)) {
56
+ verified = true;
57
+ }
58
+ }
59
+
60
+ return verified;
61
+ }
62
+
63
+ function generateTotpUrl(seed, { label, issuer }) {
64
+ return `otpauth://totp/${encodeURIComponent(label)}?secret=${base32Encode(Buffer.from(seed))}&issuer=${encodeURIComponent(issuer)}`;
65
+ }
66
+
67
+ module.exports = { generateTotpSeed, verifyTotp, generateTotpUrl };
@@ -34,8 +34,16 @@ const {
34
34
  readEnvValue,
35
35
  failAction
36
36
  } = require('../tools');
37
- const { settingsSchema, accountIdSchema, defaultAccountTypeSchema, ACCOUNT_DISPLAY_STATES, signedFormBlobFields: signedBlobFields } = require('../schemas');
38
- const { formatAccountData, cachedTemplates, ACCOUNT_STATE_DISPLAY } = require('./route-helpers');
37
+ const {
38
+ settingsSchema,
39
+ accountSchemas,
40
+ accountIdSchema,
41
+ defaultAccountTypeSchema,
42
+ ACCOUNT_DISPLAY_STATES,
43
+ signedFormBlobFields: signedBlobFields
44
+ } = require('../schemas');
45
+ const { formatAccountData, cachedTemplates, identityErrorView, ACCOUNT_STATE_DISPLAY } = require('./route-helpers');
46
+ const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
39
47
 
40
48
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS } = consts;
41
49
 
@@ -358,7 +366,7 @@ function init(args) {
358
366
 
359
367
  accountData.notifyFrom = data.notifyFrom || new Date().toISOString();
360
368
 
361
- for (let key of ['redirectUrl', 'n', 't']) {
369
+ for (let key of ['redirectUrl', 'expectedEmail', 'n', 't']) {
362
370
  if (!accountData._meta) {
363
371
  accountData._meta = {};
364
372
  }
@@ -408,6 +416,8 @@ function init(args) {
408
416
  return h.redirect(authorizeUrl);
409
417
  }
410
418
 
419
+ const expectedEmail = await resolveFormExpectation(data);
420
+
411
421
  return h.view(
412
422
  'accounts/register/imap',
413
423
  {
@@ -416,7 +426,10 @@ function init(args) {
416
426
  data: request.payload.data,
417
427
  sig: request.payload.sig,
418
428
 
419
- email: data.email,
429
+ // A pinned link fixes the address, so prefill from the expectation rather than from the
430
+ // editable hint and mark it read-only. Cosmetic - the endpoints below enforce it.
431
+ email: expectedEmail || data.email,
432
+ emailPinned: !!expectedEmail,
420
433
  name: data.name
421
434
  }
422
435
  },
@@ -656,6 +669,54 @@ function init(args) {
656
669
  return data;
657
670
  };
658
671
 
672
+ // The expectation that applies to a parsed form blob (lib/account/expected-identity.js owns the
673
+ // precedence and the lazy Redis fallback).
674
+ const resolveFormExpectation = data => resolveExpectedIdentity(redis, { account: data.account, blobExpectation: data.expectedEmail });
675
+
676
+ // Expected identity gate for the IMAP arm, mirroring the one the OAuth callback applies in
677
+ // workers/api.js.
678
+ //
679
+ // The evidence here is only the address typed into the form. Working credentials do not prove that
680
+ // the address belongs to the mailbox behind them, so this enforces "the account is registered under
681
+ // the expected address" and nothing stronger - which is exactly what the field documents. Without it
682
+ // the constraint would be trivially sidestepped by choosing the IMAP tab on a form that also offers
683
+ // OAuth2.
684
+ //
685
+ // Returns { expectedEmail, matched } rather than throwing so the caller can name the address that was
686
+ // actually used when it reports the rejection.
687
+ const checkExpectedIdentity = async (data, submittedEmail) => {
688
+ const expectedEmail = await resolveFormExpectation(data);
689
+ return { expectedEmail, matched: !expectedEmail || matchesExpectedIdentity(expectedEmail, [submittedEmail]) };
690
+ };
691
+
692
+ // Stop the flow with a way back rather than a redirect to the calling application: entering the wrong
693
+ // address is correctable, and the hosted form only ever redirects on success. The OAuth arm renders
694
+ // the same view (workers/api.js), differing only in where "try again" points.
695
+ //
696
+ // type=imap keeps the user on the arm they already chose: without it /accounts/new re-asks the
697
+ // provider question and offers OAuth apps they passed over. The signed blob is still unspent (the
698
+ // nonce is claimed only on success), so the link works, and the form it returns to prefills the
699
+ // pinned address read-only.
700
+ const renderIdentityError = (request, h, expectedEmail, actualEmail) =>
701
+ identityErrorView(request, h, {
702
+ expectedEmail,
703
+ actualEmail,
704
+ retryUrl: `/accounts/new?data=${encodeURIComponent(request.payload.data)}&sig=${encodeURIComponent(request.payload.sig)}&type=imap`
705
+ });
706
+
707
+ // have to use HTML redirect, otherwise samesite=strict cookies are not passed on
708
+ const renderRedirect = (request, h, httpRedirectUrl) =>
709
+ h.view(
710
+ 'redirect',
711
+ {
712
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
713
+ httpRedirectUrl
714
+ },
715
+ {
716
+ layout: 'public'
717
+ }
718
+ );
719
+
659
720
  server.route({
660
721
  method: 'POST',
661
722
  path: '/accounts/new/imap',
@@ -663,7 +724,14 @@ function init(args) {
663
724
  async handler(request, h) {
664
725
  // Bound outbound autodiscovery per issued blob (shared cap with the connection tester) so a
665
726
  // leaked signed link cannot drive unlimited outbound probes to arbitrary domains.
666
- await authorizeSignedProbe(request.payload, request.app.gt, request.logger);
727
+ const data = await authorizeSignedProbe(request.payload, request.app.gt, request.logger);
728
+
729
+ // Reject a pinned link early, before autodiscovery runs against the submitted domain, so the
730
+ // user finds out before typing a password. The create endpoint below is the authoritative check.
731
+ const { expectedEmail, matched } = await checkExpectedIdentity(data, request.payload.email);
732
+ if (!matched) {
733
+ return renderIdentityError(request, h, expectedEmail, request.payload.email);
734
+ }
667
735
 
668
736
  let serverSettings;
669
737
  try {
@@ -909,6 +977,13 @@ function init(args) {
909
977
  async handler(request, h) {
910
978
  const data = await parseSignedFormData(redis, request.payload, request.app.gt, { requireNonce: true });
911
979
 
980
+ // Before the nonce claim below, so a rejected attempt does not consume the setup link and the
981
+ // "try again" link on the error page still works.
982
+ const { expectedEmail, matched } = await checkExpectedIdentity(data, request.payload.email);
983
+ if (!matched) {
984
+ return renderIdentityError(request, h, expectedEmail, request.payload.email);
985
+ }
986
+
912
987
  const accountData = {
913
988
  account: data.account || null,
914
989
  name: request.payload.name || data.name,
@@ -946,6 +1021,11 @@ function init(args) {
946
1021
  accountData.subconnections = data.subconnections;
947
1022
  }
948
1023
 
1024
+ if (expectedEmail) {
1025
+ // Pin the account so later setups are checked even from a link that carries no expectation.
1026
+ accountData.expectedEmail = expectedEmail;
1027
+ }
1028
+
949
1029
  const accountObject = new Account({ redis, call, secret: await getSecret() });
950
1030
 
951
1031
  // Claim the single-use nonce BEFORE creating the account so a concurrent double-submit or
@@ -1000,16 +1080,7 @@ function init(args) {
1000
1080
  httpRedirectUrl = `/admin/accounts/${result.account}`;
1001
1081
  }
1002
1082
 
1003
- return h.view(
1004
- 'redirect',
1005
- {
1006
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
1007
- httpRedirectUrl
1008
- },
1009
- {
1010
- layout: 'public'
1011
- }
1012
- );
1083
+ return renderRedirect(request, h, httpRedirectUrl);
1013
1084
  },
1014
1085
  options: {
1015
1086
  auth: false,
@@ -1766,6 +1837,9 @@ function init(args) {
1766
1837
  account: request.params.account,
1767
1838
  name: request.payload.name || '',
1768
1839
  email: request.payload.email,
1840
+ // Empty clears the pin (Account.update hdel's it), which is the only way an operator
1841
+ // can unblock a legitimate mailbox migration on a pinned account.
1842
+ expectedEmail: request.payload.expectedEmail || null,
1769
1843
  proxy: request.payload.proxy,
1770
1844
  smtpEhloName: request.payload.smtpEhloName,
1771
1845
  webhooks: request.payload.webhooks
@@ -1967,6 +2041,8 @@ function init(args) {
1967
2041
  name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
1968
2042
  email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
1969
2043
 
2044
+ expectedEmail: accountSchemas.expectedEmail,
2045
+
1970
2046
  proxy: settingsSchema.proxyUrl,
1971
2047
  smtpEhloName: settingsSchema.smtpEhloName,
1972
2048
 
@@ -22,7 +22,7 @@ const getSecret = require('../get-secret');
22
22
  const timezonesList = require('timezones-list').default;
23
23
  const { redis, submitQueue, notifyQueue, documentsQueue } = require('../db');
24
24
  const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, readEnvList, httpAgent } = require('../tools');
25
- const { assertAllowedUrl, normalizePolicy, POLICY_OFF } = require('../egress-filter');
25
+ const { validateWebhookTarget } = require('../webhook-egress');
26
26
  const { sendWebhookRequest } = require('../webhook-request');
27
27
  const { llmPreProcess } = require('../llm-pre-process');
28
28
  const { documentStoreFeatureEnabled } = require('../document-store');
@@ -55,11 +55,6 @@ const MAX_PAYLOAD_TIMEOUT = getDuration(readEnvValue('EENGINE_MAX_PAYLOAD_TIMEOU
55
55
 
56
56
  const ADMIN_ACCESS_ADDRESSES = readEnvList('EENGINE_ADMIN_ACCESS_ADDRESSES');
57
57
 
58
- // Must match the policy the webhooks worker enforces on real deliveries, including the null that
59
- // tells sendWebhookRequest to keep following redirects when the policy is off
60
- const WEBHOOK_EGRESS_POLICY = normalizePolicy(readEnvValue('EENGINE_WEBHOOK_EGRESS_POLICY'));
61
- const validateWebhookTarget = WEBHOOK_EGRESS_POLICY === POLICY_OFF ? null : target => assertAllowedUrl(target, { policy: WEBHOOK_EGRESS_POLICY });
62
-
63
58
  const IMAP_INDEXERS = [
64
59
  {
65
60
  id: 'full',
@@ -1088,7 +1083,7 @@ return true;`
1088
1083
  }
1089
1084
  }),
1090
1085
  headers,
1091
- dispatcher: httpAgent.retry,
1086
+ dispatcher: httpAgent.webhook,
1092
1087
  validateTarget: validateWebhookTarget
1093
1088
  });
1094
1089
  duration = Date.now() - start;
@@ -2178,6 +2178,9 @@ return payload;`)
2178
2178
  entry.access.timeStr =
2179
2179
  entry.access && entry.access.time && typeof entry.access.time.toISOString === 'function' ? entry.access.time.toISOString() : null;
2180
2180
  entry.idShort = entry.id ? entry.id.slice(0, 8) : '';
2181
+ // Short-lived tokens (the API reference mints one-hour ones) have to be
2182
+ // distinguishable here, otherwise the list implies every token is permanent
2183
+ entry.expiresStr = entry.expires && typeof entry.expires.toISOString === 'function' ? entry.expires.toISOString() : null;
2181
2184
  entry.scopes = entry.scopes
2182
2185
  ? entry.scopes.map((scope, i) => ({
2183
2186
  name: scope === '*' ? 'all scopes' : scope,
@@ -12,8 +12,7 @@ const Joi = require('joi');
12
12
  const crypto = require('crypto');
13
13
  const pbkdf2 = require('@phc/pbkdf2');
14
14
  const QRCode = require('qrcode');
15
- const speakeasy = require('speakeasy');
16
- const base32 = require('base32.js');
15
+ const { generateTotpSeed, verifyTotp, generateTotpUrl } = require('../totp');
17
16
  const {
18
17
  generateRegistrationOptions,
19
18
  verifyRegistrationResponse,
@@ -424,12 +423,7 @@ function init(args) {
424
423
  return h.redirect(`/admin/login`);
425
424
  }
426
425
 
427
- let verified = speakeasy.totp.verify({
428
- secret: base32.encode(Buffer.from(totpSeed)),
429
- encoding: 'base32',
430
- token: request.payload.code,
431
- window: TOTP_WINDOW_SIZE
432
- });
426
+ let verified = verifyTotp(totpSeed, request.payload.code, { window: TOTP_WINDOW_SIZE });
433
427
 
434
428
  if (!verified) {
435
429
  let err = new Error('Failed to verify login');
@@ -569,12 +563,7 @@ function init(args) {
569
563
 
570
564
  let totpSeed = await settings.get('totpSeed');
571
565
  if (!totpSeed) {
572
- let secret = speakeasy.generateSecret({
573
- length: 20,
574
- name: username
575
- });
576
-
577
- totpSeed = secret.ascii;
566
+ totpSeed = generateTotpSeed();
578
567
  await settings.set('totpSeed', totpSeed);
579
568
  }
580
569
 
@@ -582,10 +571,8 @@ function init(args) {
582
571
  // create QR code
583
572
  const serviceUrl = (await settings.get('serviceUrl')) || '';
584
573
 
585
- let otpauth_url = speakeasy.otpauthURL({
586
- secret: totpSeed,
587
- // label is part of URL and speakeasy as of v2.0.0 does not encode special characters
588
- label: encodeURIComponent(serviceUrl.replace(/^https?:\/\/|\/$/g, '')),
574
+ let otpauth_url = generateTotpUrl(totpSeed, {
575
+ label: serviceUrl.replace(/^https?:\/\/|\/$/g, ''),
589
576
  issuer: 'EmailEngine'
590
577
  });
591
578
 
@@ -665,12 +652,7 @@ function init(args) {
665
652
  return h.redirect(`/admin/account/security`);
666
653
  }
667
654
 
668
- let verified = speakeasy.totp.verify({
669
- secret: base32.encode(Buffer.from(totpSeed)),
670
- encoding: 'base32',
671
- token: request.payload.code,
672
- window: TOTP_WINDOW_SIZE
673
- });
655
+ let verified = verifyTotp(totpSeed, request.payload.code, { window: TOTP_WINDOW_SIZE });
674
656
 
675
657
  if (!verified) {
676
658
  await request.flash({ type: 'danger', message: `Invalid verification code` });
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  // Admin UI routes for the dashboard and standalone informational pages: the main
4
- // /admin dashboard (stats counters), the Swagger API reference, the legal page, and the
5
- // upgrade page. Extracted verbatim from lib/routes-ui.js.
4
+ // /admin dashboard (stats counters), the legal page, and the upgrade page. Extracted
5
+ // verbatim from lib/routes-ui.js. The API reference lives in reference-routes.js.
6
6
 
7
7
  const { getStats, getBoolean, readEnvValue } = require('../tools');
8
8
  const settings = require('../settings');
@@ -107,30 +107,6 @@ function init(args) {
107
107
  }
108
108
  });
109
109
 
110
- server.route({
111
- method: 'GET',
112
- path: '/admin/swagger',
113
- async handler(request, h) {
114
- return h.view(
115
- 'swagger/index',
116
- {
117
- pageTitle: 'API Reference',
118
- menuSwagger: true,
119
- injectHtmlHead: `<link rel="stylesheet" type="text/css" href="/admin/swagger/resources/swagger-ui.css" />
120
- <style>
121
- .download-url-wrapper,
122
- .topbar {
123
- display: none !important;
124
- }
125
- </style>`
126
- },
127
- {
128
- layout: 'app'
129
- }
130
- );
131
- }
132
- });
133
-
134
110
  server.route({
135
111
  method: 'GET',
136
112
  path: '/admin/legal',