emailengine-app 2.87.0 → 2.87.2

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 (71) hide show
  1. package/.ncurc.js +2 -4
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +3 -4
  5. package/bin/emailengine.js +2 -4
  6. package/bin/healthcheck.js +20 -0
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +3 -7
  9. package/lib/account/auth-failure-backfill.js +3 -2
  10. package/lib/account/expected-identity.js +2 -2
  11. package/lib/account.js +9 -8
  12. package/lib/api-listener.js +40 -0
  13. package/lib/api-token-auth.js +406 -0
  14. package/lib/autodetect-imap-settings.js +36 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +23 -107
  21. package/lib/email-client/gmail-client.js +7 -4
  22. package/lib/email-client/imap/mailbox.js +89 -96
  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 +4 -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/get-boolean.js +38 -0
  31. package/lib/health-probe.js +71 -0
  32. package/lib/imapproxy/imap-server.js +4 -55
  33. package/lib/net-tos-guard.js +42 -0
  34. package/lib/oauth2-apps.js +2 -1
  35. package/lib/privileged-settings.js +6 -0
  36. package/lib/read-env-value.js +19 -7
  37. package/lib/redis-keys.js +19 -0
  38. package/lib/redis-operations.js +7 -3
  39. package/lib/routes-ui.js +4 -1
  40. package/lib/schemas.js +8 -0
  41. package/lib/security-headers.js +18 -0
  42. package/lib/session-default.js +60 -0
  43. package/lib/settings.js +2 -1
  44. package/lib/stream-encrypt.js +71 -20
  45. package/lib/sub-script.js +8 -2
  46. package/lib/submit-lock.js +84 -0
  47. package/lib/submit-processor.js +283 -0
  48. package/lib/templates.js +6 -3
  49. package/lib/tls/context.js +2 -16
  50. package/lib/tools.js +8 -30
  51. package/lib/ui-routes/admin-config-routes.js +27 -5
  52. package/lib/ui-routes/auth-routes.js +4 -0
  53. package/lib/ui-routes/dbsc-routes.js +43 -0
  54. package/lib/utils/redis-errors.js +44 -0
  55. package/lib/webhook-delivery.js +3 -4
  56. package/lib/worker-rpc-error.js +10 -5
  57. package/lib/worker-rpc.js +138 -0
  58. package/package.json +17 -19
  59. package/sbom.json +370 -1446
  60. package/server.js +6 -5
  61. package/static/css/flyonui.css +2 -2
  62. package/static/licenses.html +253 -1366
  63. package/translations/messages.pot +16 -16
  64. package/views/config/security.hbs +37 -0
  65. package/workers/api.js +61 -467
  66. package/workers/export.js +14 -55
  67. package/workers/imap-proxy.js +5 -18
  68. package/workers/imap.js +27 -49
  69. package/workers/smtp.js +7 -69
  70. package/workers/submit.js +21 -279
  71. package/workers/webhooks.js +7 -72
package/lib/export.js CHANGED
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { accountDataKey } = require('./redis-keys');
3
4
  const os = require('os');
4
5
  const crypto = require('crypto');
5
6
  const fs = require('fs');
@@ -381,9 +382,45 @@ function calculateScore(timestamp, folder, messageId, uid) {
381
382
  return baseSeconds * 1000000 + tiebreaker;
382
383
  }
383
384
 
385
+ // BullMQ states of a job that is still going to run, or is running (markInterruptedAsFailed())
386
+ const LIVE_JOB_STATES = new Set(['waiting', 'delayed', 'prioritized', 'waiting-children', 'active']);
387
+
388
+ // Recovery runs in every export worker as it starts, so an export whose job is still live belongs
389
+ // to BullMQ rather than to recovery: a waiting job is picked up by a worker, an active one is
390
+ // either running in a sibling worker or held by the lock of a worker that died, which lapses after
391
+ // the export worker's lockDuration so BullMQ's stalled check runs it again. Export.startProcessing()
392
+ // rebuilds an export from the start on every run, so a crash ends the same way however long the
393
+ // restart took. Only an export whose job is gone or finished is failed here.
394
+ //
395
+ // The removal is still the last word before anything is deleted, because a job read as finished or
396
+ // gone a moment ago is the only thing standing between recovery and a live export: BullMQ refuses,
397
+ // in the same script that would remove it, a job whose lock is held, so a removal that succeeded
398
+ // means no worker can run the job any more. A refused removal, or any other failure, keeps the
399
+ // export rather than deleting it on a guess.
400
+ async function removeAbandonedJob(job, account, exportId) {
401
+ try {
402
+ await job.remove();
403
+ } catch (err) {
404
+ logger.info({ msg: 'Kept an interrupted export, its job could not be removed', account, exportId, err });
405
+ return false;
406
+ }
407
+ logger.info({ msg: 'Removed interrupted export job from queue', account, exportId });
408
+ return true;
409
+ }
410
+
411
+ // Whether startup recovery should leave an export to the queue. A cancelled export is never left:
412
+ // running its job would reset the status to processing and undo the cancellation, so its job is
413
+ // removed (unless a worker holds it, and that worker sees the cancellation itself)
414
+ async function isLeftToQueue(job, status) {
415
+ if (!job || status === 'cancelled') {
416
+ return false;
417
+ }
418
+ return LIVE_JOB_STATES.has(await job.getState().catch(() => null));
419
+ }
420
+
384
421
  class Export {
385
422
  static async create(account, options) {
386
- const accountData = await redis.hgetall(`${REDIS_PREFIX}iad:${account}`);
423
+ const accountData = await redis.hgetall(accountDataKey(account));
387
424
  if (!accountData || !accountData.account) {
388
425
  throw createError('Account not found', 'AccountNotFound', 404);
389
426
  }
@@ -802,9 +839,11 @@ class Export {
802
839
 
803
840
  if (data && (data.status === 'processing' || data.status === 'queued' || data.status === 'cancelled')) {
804
841
  const job = await exportQueue.getJob(exportId).catch(() => null);
805
- if (job) {
806
- await job.remove().catch(() => {});
807
- logger.info({ msg: 'Removed interrupted export job from queue', account, exportId });
842
+ if (await isLeftToQueue(job, data.status)) {
843
+ continue;
844
+ }
845
+ if (job && !(await removeAbandonedJob(job, account, exportId))) {
846
+ continue;
808
847
  }
809
848
 
810
849
  await Export.fail(account, exportId, 'Export interrupted by application restart');
@@ -0,0 +1,38 @@
1
+ 'use strict';
2
+
3
+ // Split out of lib/tools.js so leaf modules (lib/api-listener.js) can read a switch without loading
4
+ // it. Still re-exported from lib/tools.js, which is where most callers reach it.
5
+
6
+ /**
7
+ * Reads a configuration switch the way every EmailEngine setting reads one.
8
+ *
9
+ * @param {*} value - A boolean, a number, or a string such as "true", "yes", "on", "enabled" or "1"
10
+ * @returns {boolean}
11
+ */
12
+ function getBoolean(value) {
13
+ if (typeof value === 'boolean') {
14
+ return value;
15
+ }
16
+
17
+ if (typeof value === 'string') {
18
+ value = value.trim();
19
+ }
20
+
21
+ if (typeof value === 'string' && !isNaN(value) && /^[0-9]+$/.test(value)) {
22
+ value = Number(value);
23
+ }
24
+
25
+ if (typeof value === 'number') {
26
+ return !!value;
27
+ }
28
+
29
+ if (typeof value === 'string') {
30
+ // `on` and `enabled` are what several operators write in env files, and joi and
31
+ // resolveHttpProxy() already read `on` as true
32
+ return /^(y|true|on$|enabled$)/i.test(value);
33
+ }
34
+
35
+ return false;
36
+ }
37
+
38
+ module.exports = { getBoolean };
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ // The Docker image's HEALTHCHECK, run by bin/healthcheck.js. The image's first health check was a
4
+ // BusyBox wget against http://127.0.0.1:${EENGINE_PORT}, which failed every time on an instance
5
+ // serving the API over HTTPS: the probe reached a TLS socket with a plain request, Swarm marked
6
+ // the task unhealthy, sent it no traffic and replaced it every few minutes. The probe therefore
7
+ // asks lib/api-listener.js, the same resolver the API listener is built from.
8
+
9
+ const http = require('http');
10
+ const https = require('https');
11
+ const { apiPort, apiHost, apiTlsConfig } = require('./api-listener');
12
+
13
+ const PROBE_TIMEOUT = 5000;
14
+ const PROBE_PATH = '/health/live';
15
+
16
+ // A listener bound to every address answers on loopback; a specific address is probed directly
17
+ const WILDCARD_HOSTS = new Set(['', '0.0.0.0', '::']);
18
+
19
+ /**
20
+ * Where the API listener of this instance can be reached from inside its own container.
21
+ *
22
+ * @param {Object} api - The `[api]` section of the configuration
23
+ * @returns {{ protocol: string, host: string, port: number }}
24
+ */
25
+ function probeTarget(api) {
26
+ const host = (apiHost(api) || '')
27
+ .toString()
28
+ .trim()
29
+ .replace(/^\[(.*)\]$/, '$1');
30
+
31
+ return {
32
+ protocol: apiTlsConfig(api) ? 'https' : 'http',
33
+ host: WILDCARD_HOSTS.has(host) ? '127.0.0.1' : host,
34
+ port: Number(apiPort(api))
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Asks the liveness endpoint once.
40
+ *
41
+ * @param {{ protocol: string, host: string, port: number }} target
42
+ * @param {Object} [opts]
43
+ * @param {number} [opts.timeout] - Milliseconds before the probe gives up
44
+ * @returns {Promise<{ ok: boolean, statusCode?: number, error?: string }>}
45
+ */
46
+ function probe(target, { timeout = PROBE_TIMEOUT } = {}) {
47
+ const client = target.protocol === 'https' ? https : http;
48
+
49
+ return new Promise(resolve => {
50
+ const req = client.get(
51
+ {
52
+ host: target.host,
53
+ port: target.port,
54
+ path: PROBE_PATH,
55
+ timeout,
56
+ // The probe only asks whether this process answers. The certificate is whatever the
57
+ // operator serves for a public name (or the self-signed fallback), never one issued
58
+ // for the loopback address, and judging it is not the liveness check's business.
59
+ rejectUnauthorized: false
60
+ },
61
+ res => {
62
+ res.resume();
63
+ resolve({ ok: res.statusCode === 200, statusCode: res.statusCode });
64
+ }
65
+ );
66
+ req.on('timeout', () => req.destroy(new Error(`No response in ${timeout}ms`)));
67
+ req.on('error', err => resolve({ ok: false, error: err.message }));
68
+ });
69
+ }
70
+
71
+ module.exports = { probeTarget, probe, PROBE_PATH };
@@ -49,65 +49,14 @@ const IMAP_PROXY_MAX_CLIENTS = Number(readEnvValue('EENGINE_IMAPPROXY_MAX_CLIENT
49
49
 
50
50
  const { TLS_DEFAULTS } = require('../consts');
51
51
 
52
- let callQueue = new Map();
53
- let mids = 0;
54
-
55
- async function call(message, transferList) {
56
- return new Promise((resolve, reject) => {
57
- let mid = `${Date.now()}:${++mids}`;
58
-
59
- let ttl = Math.max(message.timeout || 0, EENGINE_TIMEOUT || 0);
60
- let timer = setTimeout(() => {
61
- let err = new Error('Timeout waiting for command response [T4]');
62
- err.statusCode = 504;
63
- err.code = 'Timeout';
64
- err.ttl = ttl;
65
- callQueue.delete(mid);
66
- reject(err);
67
- }, ttl);
68
-
69
- callQueue.set(mid, { resolve, reject, timer });
70
-
71
- try {
72
- parentPort.postMessage(
73
- {
74
- cmd: 'call',
75
- mid,
76
- message
77
- },
78
- transferList
79
- );
80
- } catch (err) {
81
- clearTimeout(timer);
82
- callQueue.delete(mid);
83
- return reject(err);
84
- }
85
- });
86
- }
52
+ const { createRpcClient } = require('../worker-rpc');
53
+ const rpc = createRpcClient({ port: parentPort, defaultTimeout: EENGINE_TIMEOUT, timeoutTag: 'T4' });
54
+ const call = rpc.call;
87
55
 
88
56
  // Resolve pending call() promises when the main thread answers. Without this any
89
57
  // RPC issued from this worker (via the `call` passed into Account) would never settle
90
58
  // and would reject on timeout. Mirrors the handlers in workers/imap.js and smtp.js.
91
- parentPort.on('message', message => {
92
- if (message && message.cmd === 'resp' && message.mid && callQueue.has(message.mid)) {
93
- let { resolve, reject, timer } = callQueue.get(message.mid);
94
- clearTimeout(timer);
95
- callQueue.delete(message.mid);
96
-
97
- if (message.error) {
98
- let err = new Error(message.error);
99
- if (message.code) {
100
- err.code = message.code;
101
- }
102
- if (message.statusCode) {
103
- err.statusCode = message.statusCode;
104
- }
105
- return reject(err);
106
- }
107
-
108
- return resolve(message.response);
109
- }
110
- });
59
+ parentPort.on('message', rpc.handleResponse);
111
60
 
112
61
  async function metrics(logger, key, method, ...args) {
113
62
  try {
@@ -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 };
@@ -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
 
@@ -118,6 +118,12 @@ const PRIVILEGED_SETTINGS_GROUPS = [
118
118
  label: 'the MCP and audit switches',
119
119
  keys: ['mcpEnabled', 'mcpOAuthEnabled', 'tokenAuditLog', 'tokenLogEntries', 'tokenLogAge']
120
120
  },
121
+ {
122
+ // Whether the admin session must prove it is still on the device that signed in. A
123
+ // narrowed credential switching it off would make a copied admin cookie usable again
124
+ label: 'admin session binding',
125
+ keys: ['dbscEnabled']
126
+ },
121
127
  {
122
128
  // The error reporting target
123
129
  label: 'error reporting',
@@ -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/routes-ui.js CHANGED
@@ -16,6 +16,7 @@ const accountRoutes = require('./ui-routes/account-routes');
16
16
  const mcpConsentRoutes = require('./ui-routes/mcp-consent-routes');
17
17
  const tlsConfigRoutes = require('./ui-routes/tls-config-routes');
18
18
  const queueRoutes = require('./ui-routes/queue-routes');
19
+ const dbscRoutes = require('./ui-routes/dbsc-routes');
19
20
 
20
21
  function applyRoutes(server, call) {
21
22
  // Initialize admin entity routes (webhooks, templates, gateways, tokens)
@@ -52,8 +53,10 @@ function applyRoutes(server, call) {
52
53
  // TLS certificates: the configuration page, and the ACME challenge route the CA calls
53
54
  tlsConfigRoutes({ server, call });
54
55
 
55
- // Admin auth and user-profile routes (login, logout, TOTP, passkeys, password)
56
+ // Admin auth and user-profile routes (login, logout, TOTP, passkeys, password), and the
57
+ // device-bound session endpoints the browser calls (registration, refresh)
56
58
  authRoutes({ server });
59
+ dbscRoutes({ server });
57
60
 
58
61
  // OAuth2 application config routes
59
62
  oauthConfigRoutes({ server, call });
package/lib/schemas.js CHANGED
@@ -351,6 +351,14 @@ const settingsSchema = {
351
351
  .description('External authentication service URL for retrieving mailbox credentials dynamically')
352
352
  .label('AuthServer'),
353
353
 
354
+ // Off by default: browser support is still limited, the protocol is a draft standard, and a
355
+ // bound session that cannot renew its credential is signed out (lib/dbsc)
356
+ dbscEnabled: formBoolean()
357
+ .example(false)
358
+ .description(
359
+ "Bind admin sessions to a key kept in the signed-in device's security hardware (Device Bound Session Credentials), in browsers that support it, so a copied session cookie stops working within minutes. Requires an https serviceUrl. Disabled by default"
360
+ ),
361
+
354
362
  // Off by default: it adds a write to the hot path of every authenticated request, and most
355
363
  // instances will never read the result
356
364
  tokenAuditLog: formBoolean()
@@ -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,60 @@
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. The device-bound session refresh is here because the browser
47
+ // ignores a redirect there, and a session that has not passed its second factor has no binding
48
+ // for it to renew anyway (lib/dbsc answers that itself). test/admin-auth-guardrail-test.js checks
49
+ // every entry against the route table, so a renamed route cannot leave a stale entry that silently
50
+ // drops the exemption.
51
+ const TOTP_EXEMPT_PATHS = Object.freeze([
52
+ '/{any*}',
53
+ '/admin/totp',
54
+ '/admin/login',
55
+ '/admin/passkey/auth/options',
56
+ '/admin/passkey/auth/verify',
57
+ '/admin/dbsc/refresh'
58
+ ]);
59
+
60
+ 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