emailengine-app 2.86.0 → 2.87.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 (74) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +42 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +5 -6
  6. package/README.md +4 -0
  7. package/bin/emailengine.js +2 -4
  8. package/bin/healthcheck.js +20 -0
  9. package/data/google-crawlers.json +1 -1
  10. package/data/public_suffix_list.dat +3 -7
  11. package/lib/account/auth-failure-backfill.js +3 -2
  12. package/lib/account/expected-identity.js +2 -2
  13. package/lib/account.js +101 -39
  14. package/lib/api-listener.js +40 -0
  15. package/lib/api-routes/account-routes.js +14 -7
  16. package/lib/api-routes/submit-routes.js +21 -2
  17. package/lib/api-token-auth.js +406 -0
  18. package/lib/autodetect-imap-settings.js +36 -3
  19. package/lib/consts.js +5 -0
  20. package/lib/email-client/base-client.js +27 -109
  21. package/lib/email-client/gmail-client.js +15 -4
  22. package/lib/email-client/imap/mailbox.js +97 -97
  23. package/lib/email-client/imap/sync-operations.js +13 -6
  24. package/lib/email-client/imap-client.js +28 -7
  25. package/lib/email-client/new-message-steps.js +162 -0
  26. package/lib/email-client/outlook-client.js +10 -2
  27. package/lib/env-setting-overrides.js +6 -2
  28. package/lib/export-worker.js +3 -2
  29. package/lib/export.js +43 -4
  30. package/lib/field-usage.js +1 -1
  31. package/lib/get-boolean.js +38 -0
  32. package/lib/get-raw-email.js +10 -1
  33. package/lib/health-probe.js +71 -0
  34. package/lib/imapproxy/imap-server.js +4 -55
  35. package/lib/net-tos-guard.js +42 -0
  36. package/lib/oauth/gmail.js +54 -29
  37. package/lib/oauth2-apps.js +2 -1
  38. package/lib/otp.js +66 -0
  39. package/lib/read-env-value.js +19 -7
  40. package/lib/redis-keys.js +19 -0
  41. package/lib/redis-operations.js +7 -3
  42. package/lib/schemas.js +62 -2
  43. package/lib/security-headers.js +18 -0
  44. package/lib/session-default.js +50 -0
  45. package/lib/settings.js +2 -1
  46. package/lib/stream-encrypt.js +71 -20
  47. package/lib/sub-script.js +8 -2
  48. package/lib/submit-lock.js +84 -0
  49. package/lib/submit-processor.js +283 -0
  50. package/lib/swagger-options.js +2 -2
  51. package/lib/templates.js +6 -3
  52. package/lib/tls/context.js +2 -16
  53. package/lib/tools.js +8 -30
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/webhooks.js +5 -0
  57. package/lib/worker-rpc-error.js +10 -5
  58. package/lib/worker-rpc.js +138 -0
  59. package/package.json +25 -26
  60. package/sbom.json +660 -1736
  61. package/server.js +6 -5
  62. package/static/css/flyonui.css +2 -2
  63. package/static/js/ee-client.js +650 -196
  64. package/static/licenses.html +280 -1393
  65. package/translations/messages.pot +16 -16
  66. package/views/layout/app.hbs +9 -6
  67. package/views/legal.hbs +8 -0
  68. package/workers/api.js +51 -474
  69. package/workers/export.js +14 -55
  70. package/workers/imap-proxy.js +5 -18
  71. package/workers/imap.js +27 -49
  72. package/workers/smtp.js +7 -69
  73. package/workers/submit.js +21 -279
  74. package/workers/webhooks.js +7 -72
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ // Keeps a failed type-of-service marking from ending the process.
4
+ //
5
+ // undici 7 (held there by the Node 20 floor, see .ncurc.js) calls socket.setTypeOfService() for
6
+ // every request on a Node that has it (24.x), unguarded, as it writes the request (client-h1.js). On macOS
7
+ // the underlying setsockopt() answers EINVAL once the peer has reset the connection, so a peer that
8
+ // went away right after accepting (a server shutting down or restarting) threw an uncaughtException
9
+ // in whichever thread made the request. undici 8 wraps the call itself; marking is best effort
10
+ // there too. EmailEngine never sets a type of service, so nothing is lost by ignoring the failure.
11
+ // Remove this together with the undici 8 upgrade.
12
+
13
+ const net = require('net');
14
+
15
+ /**
16
+ * Wraps setTypeOfService() of a socket prototype so a failure of the call itself is ignored
17
+ * @param {Object} proto - net.Socket.prototype, or a stand-in in tests
18
+ * @returns {boolean} Whether the prototype was wrapped (false without the method, or done before)
19
+ */
20
+ function guardTypeOfService(proto) {
21
+ const original = proto.setTypeOfService;
22
+ if (typeof original !== 'function' || original.tosGuarded) {
23
+ return false;
24
+ }
25
+ const guarded = function setTypeOfService(...args) {
26
+ try {
27
+ return original.apply(this, args);
28
+ } catch (err) {
29
+ if (err && err.syscall === 'setTypeOfService') {
30
+ return this;
31
+ }
32
+ throw err;
33
+ }
34
+ };
35
+ guarded.tosGuarded = true;
36
+ proto.setTypeOfService = guarded;
37
+ return true;
38
+ }
39
+
40
+ guardTypeOfService(net.Socket.prototype);
41
+
42
+ module.exports = { guardTypeOfService };
@@ -877,6 +877,14 @@ class GmailOauth {
877
877
  };
878
878
  }
879
879
 
880
+ /**
881
+ * Asks Google to revoke a grant. Never throws: the outcome is returned for the caller to act on.
882
+ *
883
+ * @param {string} token Refresh or access token of the grant
884
+ * @returns {Promise<{revoked: boolean, status?: number, reason?: string, error?: string}>}
885
+ * `reason` is TokenInvalid when Google no longer knows the token (already revoked or expired),
886
+ * ProviderRefused for any other refusal and RequestFailed when no answer arrived
887
+ */
880
888
  async revokeToken(token) {
881
889
  const fetchOpts = {
882
890
  method: 'post',
@@ -887,41 +895,58 @@ class GmailOauth {
887
895
  body: new URLSearchParams({ token }).toString()
888
896
  };
889
897
 
898
+ let res;
890
899
  try {
891
- let res = await fetchCmd(this.revokeUrl, Object.assign(fetchOpts, { dispatcher: httpAgent.forRoute(this.route).retry }));
892
-
893
- let responseText;
894
- try {
895
- responseText = await res.text();
896
- } catch (err) {
897
- // ignore
898
- }
899
-
900
- if (this.logger) {
901
- this.logger.info({
902
- msg: 'OAuth2 token revocation request',
903
- action: 'oauth2Fetch',
904
- fn: 'revokeToken',
905
- url: this.revokeUrl,
906
- success: !!res.ok,
907
- status: res.status
908
- });
909
- }
910
-
911
- if (!res.ok) {
912
- if (this.logger) {
913
- this.logger.warn({
914
- msg: 'OAuth2 token revocation failed',
915
- status: res.status,
916
- response: responseText
917
- });
918
- }
919
- }
900
+ res = await fetchCmd(this.revokeUrl, Object.assign(fetchOpts, { dispatcher: httpAgent.forRoute(this.route).retry }));
920
901
  } catch (err) {
921
902
  if (this.logger) {
922
903
  this.logger.warn({ msg: 'OAuth2 token revocation error', err });
923
904
  }
905
+ // The low-level code (ECONNREFUSED, UND_ERR_CONNECT_TIMEOUT) says more than fetch's own "fetch failed"
906
+ return { revoked: false, reason: 'RequestFailed', error: err.cause?.code || err.code || err.message };
924
907
  }
908
+
909
+ let responseText;
910
+ try {
911
+ responseText = await res.text();
912
+ } catch (err) {
913
+ // ignore
914
+ }
915
+
916
+ if (this.logger) {
917
+ this.logger.info({
918
+ msg: 'OAuth2 token revocation request',
919
+ action: 'oauth2Fetch',
920
+ fn: 'revokeToken',
921
+ url: this.revokeUrl,
922
+ success: !!res.ok,
923
+ status: res.status
924
+ });
925
+ }
926
+
927
+ if (res.ok) {
928
+ return { revoked: true, status: res.status };
929
+ }
930
+
931
+ if (this.logger) {
932
+ this.logger.warn({
933
+ msg: 'OAuth2 token revocation failed',
934
+ status: res.status,
935
+ response: responseText
936
+ });
937
+ }
938
+
939
+ // Only the OAuth2 error code, never the response body: it is the part a caller can act on
940
+ let error;
941
+ try {
942
+ error = JSON.parse(responseText).error;
943
+ } catch (err) {
944
+ // not a JSON error response
945
+ }
946
+ return Object.assign(
947
+ { revoked: false, status: res.status, reason: error === 'invalid_token' ? 'TokenInvalid' : 'ProviderRefused' },
948
+ typeof error === 'string' ? { error } : {}
949
+ );
925
950
  }
926
951
  }
927
952
 
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('./redis-keys');
3
4
  const { redis } = require('./db');
4
5
  const msgpack = require('./msgpack');
5
6
  const logger = require('./logger');
@@ -643,7 +644,7 @@ class OAuth2AppsHandler {
643
644
  let chunk = accounts.slice(i, i + CHUNK_SIZE);
644
645
  let readReq = this.redis.pipeline();
645
646
  for (let account of chunk) {
646
- readReq = readReq.hget(`${REDIS_PREFIX}iad:${account}`, 'oauth2');
647
+ readReq = readReq.hget(accountDataKey(account), 'oauth2');
647
648
  }
648
649
  let rows = await readReq.exec();
649
650
 
package/lib/otp.js ADDED
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ // One-time passcodes from the OTP-Token header (draft-goto-otp-token), see "One-time passcodes"
4
+ // in CLAUDE.md. mailparser applies the draft's parsing rules; the header itself is not
5
+ // authenticated, so the code is reported together with whether the receiving server vouches for
6
+ // its origin.
7
+
8
+ const { parseOtpToken } = require('mailparser');
9
+ const { parseAuthenticationResults, isTrustedAuthservId } = require('@postalsys/email-ai-tools/lib/authentication.js');
10
+ const { authenticationTrust } = require('./llm-pre-process');
11
+ const { getRegistrableDomain } = require('./utils/public-suffix');
12
+
13
+ // What the fetch paths ask for besides the configured headers when messageNew carries otp: the
14
+ // header itself, and what authenticationTrust() reads (Received for a Microsoft mailbox)
15
+ const OTP_FETCH_HEADERS = ['otp-token', 'authentication-results', 'received'];
16
+
17
+ /**
18
+ * Tells whether the receiving server recorded a passing DKIM signature aligned with the origin:
19
+ * from the same organizational domain, the way DMARC's relaxed alignment compares domains. Only
20
+ * the topmost Authentication-Results header counts, written by a server authenticationTrust() names
21
+ *
22
+ * @param {string} origin - The origin the code is bound to, as parseOtpToken() returns it
23
+ * @param {Object} headers - The message headers, lower-case names to value lists
24
+ * @param {string|null} provider - As summaryProvider() names it
25
+ * @returns {boolean}
26
+ */
27
+ function isAuthenticatedOrigin(origin, headers, provider) {
28
+ const trust = authenticationTrust(provider, headers);
29
+ const parsed = parseAuthenticationResults([].concat(headers['authentication-results'] || [])[0]);
30
+ if (!parsed || !parsed.dkimDomains.length || !isTrustedAuthservId(parsed.authservId, trust.trustedAuthservIds, trust.acceptUnnamedAuthentication)) {
31
+ return false;
32
+ }
33
+
34
+ // an IP address, a loopback name or a public suffix has no organizational domain to match
35
+ const originDomain = getRegistrableDomain(new URL(origin).hostname);
36
+ return !!originDomain && parsed.dkimDomains.some(domain => getRegistrableDomain(domain) === originDomain);
37
+ }
38
+
39
+ /**
40
+ * The one-time passcode of a message, from its OTP-Token header
41
+ *
42
+ * @param {Object} [headers] - The message headers, lower-case names to value lists
43
+ * @param {string|null} provider - As summaryProvider() names it, decides which Authentication-Results header counts
44
+ * @returns {{code: string, origin: string, authenticated: boolean}|undefined}
45
+ */
46
+ function getMessageOtp(headers, provider) {
47
+ const otp = headers && headers['otp-token'] && parseOtpToken([].concat(headers['otp-token']));
48
+ if (!otp) {
49
+ return undefined;
50
+ }
51
+
52
+ return { code: otp.code, origin: otp.origin, authenticated: isAuthenticatedOrigin(otp.origin, headers, provider) };
53
+ }
54
+
55
+ /**
56
+ * Tells whether the notifyHeaders setting asks for the OTP-Token header, the only case the
57
+ * messageNew payload carries the otp field
58
+ *
59
+ * @param {string[]} [notifyHeaders] - The notifyHeaders setting
60
+ * @returns {boolean}
61
+ */
62
+ function notifyHeadersIncludeOtp(notifyHeaders) {
63
+ return [].concat(notifyHeaders || []).some(header => header === '*' || String(header).toLowerCase() === 'otp-token');
64
+ }
65
+
66
+ module.exports = { getMessageOtp, notifyHeadersIncludeOtp, OTP_FETCH_HEADERS };
@@ -6,9 +6,11 @@
6
6
 
7
7
  const Fs = require('fs');
8
8
 
9
- // lib/logger.js takes its constants from lib/logger-consts.js rather than lib/consts.js, which reads
10
- // its own variables through this helper, so the logger can be required here directly
11
- const logger = require('./logger');
9
+ // Loaded on first use: only the <KEY>_FILE branch logs, and a short-lived process that reads plain
10
+ // variables (the Docker health check) should not pay for pino and dotenv. lib/logger.js takes its
11
+ // constants from lib/logger-consts.js rather than lib/consts.js, so there is no cycle either way.
12
+ let logger;
13
+ const getLogger = () => (logger = logger || require('./logger'));
12
14
 
13
15
  // The keys that lib/db.js and lib/get-secret.js used to resolve through private copies of this
14
16
  // function. Those copies stripped a single trailing newline and nothing else, so for a file carrying
@@ -52,20 +54,30 @@ function readEnvValue(key) {
52
54
  // the operator needs to find it, and the value is what the warning exists to protect.
53
55
  const legacyValue = contents.replace(/\r?\n$/, '');
54
56
  if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
55
- logger.warn({
57
+ getLogger().warn({
56
58
  msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
57
59
  key,
58
60
  file: process.env[`${key}_FILE`]
59
61
  });
60
62
  }
61
63
 
62
- logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
64
+ getLogger().trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
63
65
  } catch (err) {
64
- logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
66
+ getLogger().error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
65
67
  process.env[key] = '';
66
68
  }
67
69
  return process.env[key];
68
70
  }
69
71
  }
70
72
 
71
- module.exports = { readEnvValue };
73
+ /**
74
+ * Whether an environment value is set, in either its plain or its `<KEY>_FILE` form.
75
+ *
76
+ * @param {string} key - Environment variable name
77
+ * @returns {boolean}
78
+ */
79
+ function hasEnvValue(key) {
80
+ return key in process.env || `${key}_FILE` in process.env;
81
+ }
82
+
83
+ module.exports = { readEnvValue, hasEnvValue };
@@ -0,0 +1,19 @@
1
+ 'use strict';
2
+
3
+ // Names of the Redis keys that more than one module builds. A key name is a storage contract: a
4
+ // module that spells one differently reads an empty key rather than failing, so a key used across
5
+ // layers (the API, the workers, the main thread) is named here once. test/redis-keys-test.js fails
6
+ // when one of the keys below is spelled out by hand anywhere else.
7
+ //
8
+ // lib/lua/s-list-accounts.lua builds the account data key itself; Lua cannot share this module.
9
+
10
+ const { REDIS_PREFIX } = require('./consts');
11
+
12
+ /**
13
+ * The account data hash: the account record, its connection state and counters
14
+ * @param {String} account - account id
15
+ * @returns {String}
16
+ */
17
+ const accountDataKey = account => `${REDIS_PREFIX}iad:${account}`;
18
+
19
+ module.exports = { accountDataKey };
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const logger = require('./logger');
4
+ const { isTransientRedisError } = require('./utils/redis-errors');
4
5
 
5
6
  /**
6
7
  * Default retry configuration for Redis operations
@@ -31,8 +32,8 @@ function isTransientError(err) {
31
32
  return true;
32
33
  }
33
34
 
34
- // Check for Redis connection errors
35
- if (err.name === 'ReplyError' && /LOADING|BUSY|READONLY|CLUSTERDOWN/.test(err.message)) {
35
+ // Redis replies that clear up on their own
36
+ if (isTransientRedisError(err)) {
36
37
  return true;
37
38
  }
38
39
 
@@ -185,7 +186,10 @@ class RedisTransaction {
185
186
  const results = await multi.exec();
186
187
  const error = extractMultiError(results);
187
188
 
188
- if (error && isTransientError(error) && attempt < maxAttempts) {
189
+ // Only when nothing of it was applied: a transaction runs every command whatever the
190
+ // others answer, so retrying one where some went through would apply those twice
191
+ // (an increment, a push). A refused EXEC (EXECABORT) throws and is retried below
192
+ if (error && isTransientError(error) && results.every(result => Array.isArray(result) && result[0]) && attempt < maxAttempts) {
189
193
  const delay = calculateBackoffDelay(attempt, baseDelay, maxDelay);
190
194
  this.logger.warn({
191
195
  msg: 'Redis transaction encountered transient error, retrying',
package/lib/schemas.js CHANGED
@@ -213,7 +213,9 @@ const settingsSchema = {
213
213
 
214
214
  notifyHeaders: Joi.array()
215
215
  .items(Joi.string().max(256).example('List-ID').label('NotifyHeaderEntry'))
216
- .description('Email headers to include in webhook payloads for additional context')
216
+ .description(
217
+ 'Email headers to include in webhook payloads for additional context. Listing OTP-Token also adds the otp field (the one-time passcode) to messageNew payloads'
218
+ )
217
219
  .label('NotifyHeaders'),
218
220
 
219
221
  /* ────────────── URLs ────────────── */
@@ -698,7 +700,7 @@ const settingsSchema = {
698
700
  imapClientSupportUrl: Joi.string()
699
701
  .allow('')
700
702
  .uri({ scheme: ['http', 'https', 'mailto'], allowRelative: false })
701
- .example('https://github.com/postalsys/emailengine/issues')
703
+ .example('https://emailengine.app/support')
702
704
  .description('Support URL advertised via IMAP ID extension'),
703
705
 
704
706
  /* ────────────── Export ────────────── */
@@ -1299,6 +1301,42 @@ const messageEntrySchema = Joi.object({
1299
1301
  isAutoReply: Joi.boolean().example(false).description('Whether this message appears to be an automatic reply (out of office, vacation responder, etc.)')
1300
1302
  }).label('MessageListEntry');
1301
1303
 
1304
+ // One-time passcode of the OTP-Token header (draft-goto-otp-token). Experimental: the draft is a
1305
+ // work in progress, the field follows it
1306
+ const messageOtpSchema = Joi.object({
1307
+ code: Joi.string().example('123456').description('The passcode'),
1308
+ origin: Joi.string().example('https://example.com').description('The origin the passcode is bound to'),
1309
+ authenticated: Joi.boolean()
1310
+ .example(true)
1311
+ .description(
1312
+ "Whether the receiving server vouches for the origin: its Authentication-Results header records a passing DKIM signature from the origin's organizational domain. Only Gmail and Microsoft 365 mailboxes can report true, for other servers this is always false"
1313
+ )
1314
+ })
1315
+ .description(
1316
+ 'One-time passcode from the OTP-Token header (draft-goto-otp-token), present when the message carries exactly one valid header. Experimental, follows the Internet-Draft. The header is not authenticated by itself, so name the origin to a user only when authenticated is true'
1317
+ )
1318
+ .label('MessageOtp');
1319
+
1320
+ // Optional one-time passcode for the OTP-Token header of an outgoing message
1321
+ const submitOtpSchema = Joi.object({
1322
+ code: Joi.string()
1323
+ .pattern(/^[\x20-\x7e]+$/, 'printable ASCII')
1324
+ .max(256)
1325
+ .required()
1326
+ .example('123456')
1327
+ .description('The passcode, printable ASCII. It should also appear in the message body'),
1328
+ origin: Joi.string()
1329
+ .uri({ scheme: ['https', 'http'], allowRelative: false })
1330
+ .max(2048)
1331
+ .required()
1332
+ .example('https://example.com')
1333
+ .description('The site the passcode is for, https (or http on a loopback host). A full URL is reduced to its origin')
1334
+ })
1335
+ .description(
1336
+ 'Adds an OTP-Token header (draft-goto-otp-token) so that mail clients and browsers can offer the passcode. Experimental, follows the Internet-Draft. Cannot be combined with useStructuredFormat'
1337
+ )
1338
+ .label('SubmitOtp');
1339
+
1302
1340
  const messageDetailsSchema = Joi.object({
1303
1341
  id: Joi.string().example('AAAAAgAACrI').description('EmailEngine message identifier').label('MessageEntryId'),
1304
1342
  uid: Joi.number().integer().example(12345).description('IMAP UID (unique identifier within the mailbox). IMAP accounts only').label('MessageUid'),
@@ -1366,6 +1404,7 @@ const messageDetailsSchema = Joi.object({
1366
1404
  'Whether this message is a bounce (a delivery failure report). Checked for messages in the Inbox only; a delivery or delay notification is not one'
1367
1405
  ),
1368
1406
  relatedMessageId: Joi.string().example('<original@example.com>').description('Message-ID of the message that bounced. Set together with isBounce'),
1407
+ otp: messageOtpSchema,
1369
1408
 
1370
1409
  preview: Joi.string()
1371
1410
  .example('Hello, here is the report you asked for')
@@ -2885,8 +2924,29 @@ function apiResponses(description, ...statusCodes) {
2885
2924
  return Object.assign({ 200: { description } }, errorResponses(...statusCodes));
2886
2925
  }
2887
2926
 
2927
+ // What DELETE /v1/account/{account} reports about revoking the OAuth2 grant, present only when
2928
+ // revoke was requested. Also the `info.revocation` of a revoke=required refusal
2929
+ const accountRevocationSchema = Joi.object({
2930
+ attempted: Joi.boolean().example(true).description('Whether the provider was asked to revoke the grant'),
2931
+ revoked: Joi.boolean().example(true).description('Whether the provider confirmed the revocation'),
2932
+ status: Joi.number().integer().example(200).description('HTTP status of the provider response, when one arrived'),
2933
+ reason: Joi.string()
2934
+ .valid('NotOAuth2', 'NoToken', 'AppNotFound', 'AppError', 'ServiceAccount', 'Unsupported', 'TokenInvalid', 'ProviderRefused', 'RequestFailed')
2935
+ .example('ProviderRefused')
2936
+ .label('AccountRevocationReason')
2937
+ .description(
2938
+ 'Why the grant was not revoked. NotOAuth2: not an OAuth2 account. NoToken: no stored token to revoke with. AppNotFound / AppError: the OAuth2 application is missing or could not be loaded. ServiceAccount: a Workspace service account, which has no per-user grant. Unsupported: the provider offers no revocation endpoint (Microsoft). TokenInvalid: the provider reports the token as already revoked or expired. ProviderRefused: the provider answered with an error. RequestFailed: no answer from the provider'
2939
+ ),
2940
+ error: Joi.string().example('invalid_request').description('OAuth2 error code the provider returned, or the network error code')
2941
+ })
2942
+ .description('Outcome of the OAuth2 grant revocation, included when revoke was requested')
2943
+ .label('AccountRevocation');
2944
+
2888
2945
  module.exports = {
2889
2946
  requireTlsSchema,
2947
+ messageOtpSchema,
2948
+ submitOtpSchema,
2949
+ accountRevocationSchema,
2890
2950
  apiBoolean,
2891
2951
  formBoolean,
2892
2952
  MAX_MESSAGE_ATTACHMENTS,
@@ -195,6 +195,23 @@ function isMachineRoute(tags = []) {
195
195
  return tags.some(tag => MACHINE_TAGS.includes(tag));
196
196
  }
197
197
 
198
+ /**
199
+ * Whether a route's auth setting admits the admin session cookie. An undeclared setting inherits
200
+ * the server default, which is the session strategy once an admin password is set.
201
+ *
202
+ * @param {(Object|Boolean|undefined)} auth - the route's auth setting
203
+ * @returns {boolean}
204
+ */
205
+ function acceptsSession(auth) {
206
+ if (auth === undefined) {
207
+ return true;
208
+ }
209
+ if (!auth || typeof auth !== 'object') {
210
+ return false;
211
+ }
212
+ return auth.strategy === 'session' || (Array.isArray(auth.strategies) && auth.strategies.includes('session'));
213
+ }
214
+
198
215
  /**
199
216
  * Tells whether the instance declares itself served over https - the same signal that gives the
200
217
  * session and CSRF cookies their Secure flag, and the one that decides whether HSTS is sent.
@@ -382,6 +399,7 @@ module.exports = {
382
399
  profileNameFor,
383
400
  isAdminPath,
384
401
  isMachineRoute,
402
+ acceptsSession,
385
403
  isSecureOrigin,
386
404
  CSP_MODES,
387
405
  CSP_HEADER,
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ // Makes an API worker ask for an admin login as soon as an admin password exists.
4
+ //
5
+ // workers/api.js sets the session strategy as the server default at startup when a password is
6
+ // already stored, and the worker that serves the "set password" form sets it in-process and
7
+ // broadcasts the change to the other API workers. The CLI (`emailengine password`) writes the
8
+ // password straight into Redis, with no broadcast, so a running worker kept serving /admin with no
9
+ // login until it was restarted. Checking before authentication closes that gap from the first
10
+ // request that would have got through. Setting the default rebuilds every route's lifecycle, but the
11
+ // request already running keeps the one it started with, which has no authentication step, so that
12
+ // one request is sent back to its own URL (307, which a browser repeats with the same method and
13
+ // body) and runs again with authentication.
14
+
15
+ /**
16
+ * Registers an onPreAuth extension that sets the session strategy as the default once a password is
17
+ * stored. Only a request that would use the default asks Redis, and only until the default is set
18
+ * @param {Object} opts
19
+ * @param {Object} opts.server - hapi server, with the session strategy registered
20
+ * @param {Function} opts.isInstanceSecured - Resolves true once an admin password is set
21
+ * @param {Object} opts.logger
22
+ */
23
+ function requireSessionOnceSecured({ server, isInstanceSecured, logger }) {
24
+ server.ext('onPreAuth', async (request, h) => {
25
+ if (server.auth.settings.default || request.route.settings.auth !== undefined) {
26
+ return h.continue;
27
+ }
28
+ if (!(await isInstanceSecured())) {
29
+ return h.continue;
30
+ }
31
+ // hapi refuses a second default, and a concurrent request may have set it meanwhile
32
+ if (!server.auth.settings.default) {
33
+ server.auth.default('session');
34
+ logger.info({ msg: 'Admin session authentication enabled after a password was set' });
35
+ }
36
+ // Leading slashes collapsed, so a path like //host cannot become a protocol-relative Location
37
+ const location = '/' + request.url.pathname.replace(/^\/+/, '') + request.url.search;
38
+ return h.redirect(location).code(307).takeover();
39
+ });
40
+ }
41
+
42
+ // Route paths a session that has passed the password step but not yet the second factor may reach.
43
+ // Every other route sends such a session to the TOTP prompt (registerTotpExtension() in
44
+ // workers/api.js). The login and TOTP pages have to be here or the prompt could never be answered,
45
+ // the passkey login endpoints because a passkey is a factor of its own, and the catch-all 404 so a
46
+ // mistyped URL does not bounce. test/admin-auth-guardrail-test.js checks every entry against the
47
+ // route table, so a renamed route cannot leave a stale entry that silently drops the exemption.
48
+ const TOTP_EXEMPT_PATHS = Object.freeze(['/{any*}', '/admin/totp', '/admin/login', '/admin/passkey/auth/options', '/admin/passkey/auth/verify']);
49
+
50
+ module.exports = { requireSessionOnceSecured, TOTP_EXEMPT_PATHS };
package/lib/settings.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('./redis-keys');
3
4
  const { redis } = require('./db');
4
5
  const logger = require('./logger');
5
6
  const { encrypt, decryptField } = require('./encrypt');
@@ -365,7 +366,7 @@ module.exports = {
365
366
  }
366
367
 
367
368
  if (account) {
368
- let accountLoggingEnabled = (await redis.hget(`${REDIS_PREFIX}iad:${account}`, 'logs')) === 'true' ? true : false;
369
+ let accountLoggingEnabled = (await redis.hget(accountDataKey(account), 'logs')) === 'true' ? true : false;
369
370
  return {
370
371
  enabled: accountLoggingEnabled,
371
372
  maxLogLines