emailengine-app 2.72.2 → 2.72.3

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.72.3](https://github.com/postalsys/emailengine/compare/v2.72.2...v2.72.3) (2026-07-06)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * bump imapflow to 1.4.4 (dedupe nodemailer/iconv-lite) ([5acc8cd](https://github.com/postalsys/emailengine/commit/5acc8cd99f9179fabb8d8486cf23b0558e4514bf))
9
+ * bump imapflow/mailparser/mailsplit/email-ai-tools (collapse iconv-lite) ([51dcffb](https://github.com/postalsys/emailengine/commit/51dcffb3ff0f22f9b9634d078e58b35aaf7a0312))
10
+ * bump libmime/mailparser/smtp-server/pubface (uniform nodemailer) ([eee89bb](https://github.com/postalsys/emailengine/commit/eee89bb716655519c72fb922849272c1058cbc9a))
11
+ * constant-time MS Graph clientState check and escape unsubscribe email ([3def225](https://github.com/postalsys/emailengine/commit/3def225ab1d598dec4f0b44443ff842295736039))
12
+ * escape Redis glob metacharacters in account-scoped SCAN patterns ([603d9db](https://github.com/postalsys/emailengine/commit/603d9dbce9c4e21b390e10dc7499f2cc5989c875))
13
+ * escape untrusted email fields in message browser to prevent stored XSS ([1159cc1](https://github.com/postalsys/emailengine/commit/1159cc193a98eb972454a5ae61ec01d7df77f06a))
14
+ * gate hosted auth form with a single-use nonce and probe cap, harden serviceSecret ([7ea4ff7](https://github.com/postalsys/emailengine/commit/7ea4ff7e6ca4d9239201f556b24ebd9cf8ab8250))
15
+ * harden hosted authentication form (SSRF gate, fail-closed HMAC, XSS) ([4267df7](https://github.com/postalsys/emailengine/commit/4267df7fd0252aa84ff1d257846126a8f943bf1a))
16
+ * HTML-escape json Handlebars helper to prevent stored XSS in error logs ([af2c153](https://github.com/postalsys/emailengine/commit/af2c153eb4d7de06b2730da6fdeb17bbe868472b))
17
+ * override grunt's transitive js-yaml to 3.15.0 (GHSA-h67p-54hq-rp68) ([024a923](https://github.com/postalsys/emailengine/commit/024a923de3ff2a880e79c7ddbf34bbc058fcbea3))
18
+ * stop logging the MS Graph access token on HTTP 401 ([f2f0300](https://github.com/postalsys/emailengine/commit/f2f03008cbcbaba8b7c2ff9c043ede7930c5c4ef))
19
+ * update dependencies (@postalsys/ee-client 1.3.2, nodemailer 9.0.3, bullmq 5.79.2, @sentry/node 10.63.0, [@bull-board](https://github.com/bull-board) 8.0.2) ([b954f67](https://github.com/postalsys/emailengine/commit/b954f67e1250d8a0029d355a5a8c6fc9d7f00e8e))
20
+ * update dependencies (email-text-tools 2.4.10, email-ai-tools 1.13.10) ([73df05c](https://github.com/postalsys/emailengine/commit/73df05c02db79fc47623ee41e27a315952c289b1))
21
+ * use constant-time comparison for secret and MAC checks ([453caf3](https://github.com/postalsys/emailengine/commit/453caf3ac01e58248a3a7019aa4ec3c2179b3abc))
22
+ * verify HMAC signature on the human-facing unsubscribe routes ([e30be83](https://github.com/postalsys/emailengine/commit/e30be836a71bc7e96baee19e5b019da5b0de40fa))
23
+
3
24
  ## [2.72.2](https://github.com/postalsys/emailengine/compare/v2.72.1...v2.72.2) (2026-06-26)
4
25
 
5
26
 
package/Gruntfile.js CHANGED
@@ -12,7 +12,10 @@ module.exports = function (grunt) {
12
12
  command: "npx eslint 'lib/**/*.js' 'workers/**/*.js' server.js Gruntfile.js"
13
13
  },
14
14
  server: {
15
- command: 'node server.js',
15
+ // Short Gmail fallback-poll interval so gmail-polling-test can exercise the poller
16
+ // quickly. Harmless for push-based Gmail accounts in api-test: notifications keep
17
+ // resetting the timer, and a stray fallback sync is coalesced/idempotent.
18
+ command: 'EENGINE_GMAIL_FALLBACK_POLL_INTERVAL=15000 node server.js',
16
19
  options: {
17
20
  async: true
18
21
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-06-25T14:46:07.000000",
2
+ "creationTime": "2026-06-29T14:45:46.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -11,7 +11,8 @@ const {
11
11
  download,
12
12
  resolveCredentials,
13
13
  isEmail,
14
- resolveDelegatedAccount
14
+ resolveDelegatedAccount,
15
+ escapeRedisGlob
15
16
  } = require('./tools');
16
17
  const crypto = require('crypto');
17
18
  const { MessageChannel } = require('worker_threads');
@@ -1104,7 +1105,7 @@ class Account {
1104
1105
 
1105
1106
  // scan and delete keys
1106
1107
  // should we wait though? might take a lot of time
1107
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${this.account}:*`);
1108
+ await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
1108
1109
 
1109
1110
  if (!result || !result[0] || !result[0][1]) {
1110
1111
  return {
@@ -2469,7 +2470,7 @@ class Account {
2469
2470
  await pipeline.exec();
2470
2471
 
2471
2472
  // scan and delete keys
2472
- await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${this.account}:*`);
2473
+ await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
2473
2474
 
2474
2475
  if (await isDocumentStoreEnabled()) {
2475
2476
  // Flush ElasticSearch index for this account
@@ -24,10 +24,18 @@ const { httpAgent } = require('./tools');
24
24
 
25
25
  const RESOLV_TIMEOUT = 5 * 1000;
26
26
 
27
+ // Shorter cap for the app-password hint MX lookup: it runs on the hosted form's validation-error
28
+ // re-render and only produces a cosmetic label, so it must not stall the page for the full RESOLV_TIMEOUT.
29
+ const APP_PASSWORD_MX_TIMEOUT = 1500;
30
+
27
31
  // use a function instead of const to prevent translations before locale is set
32
+ // The canonical consumer domains are listed alongside the exchange regexes so a plain domain match
33
+ // (getAppPassword with exchange=false) resolves the big providers without any MX lookup - each listed
34
+ // domain's MX points at the same entry the regex would select, so autodetect results do not change.
28
35
  const getAppPasswords = gt => [
29
36
  {
30
37
  trigger: {
38
+ domains: ['gmail.com', 'googlemail.com'],
31
39
  exchange: /\bl\.google\.com$/i
32
40
  },
33
41
  value: {
@@ -39,6 +47,7 @@ const getAppPasswords = gt => [
39
47
 
40
48
  {
41
49
  trigger: {
50
+ domains: ['icloud.com', 'me.com', 'mac.com'],
42
51
  exchange: /\.icloud\.com$/i
43
52
  },
44
53
  value: {
@@ -73,6 +82,7 @@ const getAppPasswords = gt => [
73
82
 
74
83
  {
75
84
  trigger: {
85
+ domains: ['outlook.com', 'hotmail.com', 'live.com'],
76
86
  exchange: /\.outlook\.com$/i
77
87
  },
78
88
  value: {
@@ -87,6 +97,7 @@ const getAppPasswords = gt => [
87
97
 
88
98
  {
89
99
  trigger: {
100
+ domains: ['t-online.de'],
90
101
  exchange: /\.t-online\.de$/i
91
102
  },
92
103
  value: {
@@ -111,6 +122,53 @@ function getAppPassword(email, exchange, gt) {
111
122
  return false;
112
123
  }
113
124
 
125
+ // Resolve the lowest-priority MX exchange for a domain (lowercased). Throws if the domain has no MX
126
+ // record (callers decide whether that is fatal or just "no exchange-based match").
127
+ async function resolveExchange(domain) {
128
+ let srvList = await dns.resolveMx(domain);
129
+ if (!srvList || !srvList.length) {
130
+ throw new Error('No MX record found for domain');
131
+ }
132
+
133
+ const firstItem = srvList.sort((a, b) => a.priority - b.priority).shift();
134
+ return firstItem && firstItem.exchange ? firstItem.exchange.trim().toLowerCase() : undefined;
135
+ }
136
+
137
+ // Resolve only the app-password hint for an email address - a domain match plus, for exchange-based
138
+ // providers (Gmail, iCloud, Outlook, ...), a single MX lookup. Much cheaper than autodetectImapSettings
139
+ // (one DNS query, no HTTP). The hosted form's failAction re-render uses this to restore the
140
+ // app-password label/instructions server-side rather than trusting the submitted (client-controlled)
141
+ // hidden fields, which feed unescaped template sinks. Returns the trusted hint object or false; the
142
+ // returned values are static table constants, so they are safe to render. Never throws.
143
+ async function resolveAppPassword(email, gt) {
144
+ if (!email || typeof email !== 'string' || email.indexOf('@') < 0) {
145
+ return false;
146
+ }
147
+
148
+ // Fast path: a domain-only match (e.g. aol.com) needs no network.
149
+ let hint = getAppPassword(email, false, gt);
150
+ if (hint) {
151
+ return hint;
152
+ }
153
+
154
+ let domain = email.split('@').pop().trim().toLowerCase();
155
+ try {
156
+ domain = punycode.toASCII(domain);
157
+ } catch (err) {
158
+ // ignore - use the raw domain
159
+ }
160
+
161
+ let exchange;
162
+ try {
163
+ exchange = await timedFunction(resolveExchange(domain), APP_PASSWORD_MX_TIMEOUT, 'mx');
164
+ } catch (err) {
165
+ // No MX record / lookup failed / timed out - no exchange-based hint to add.
166
+ return false;
167
+ }
168
+
169
+ return getAppPassword(email, exchange, gt);
170
+ }
171
+
114
172
  async function processAutoconfigFile(email, domain, text, source) {
115
173
  domain = domain || email.split('@').pop().trim().toLowerCase();
116
174
  let user = email.split('@').shift().trim();
@@ -335,17 +393,7 @@ async function resolveUsingMX(email, domain, gt) {
335
393
  }
336
394
 
337
395
  // do not catch potential error as there's nothing to do if we do not find the MX record
338
- let srvList = await dns.resolveMx(domain);
339
- if (!srvList || !srvList.length) {
340
- throw new Error('No MX record found for domain');
341
- }
342
-
343
- let exchange;
344
- const firstItem = srvList.sort((a, b) => a.priority - b.priority).shift();
345
-
346
- if (firstItem && firstItem.exchange) {
347
- exchange = firstItem.exchange.trim().toLowerCase();
348
- }
396
+ let exchange = await resolveExchange(domain);
349
397
 
350
398
  let resolveConfig = async () => {
351
399
  // look for some well known MX servers
@@ -782,4 +830,5 @@ module.exports.autodetectImapSettings = autodetectImapSettings;
782
830
  // network side effects, so they can be exercised directly without mocking DNS or HTTP.
783
831
  module.exports.processAutoconfigFile = processAutoconfigFile;
784
832
  module.exports.getAppPassword = getAppPassword;
833
+ module.exports.resolveAppPassword = resolveAppPassword;
785
834
  module.exports.escapeXml = escapeXml;
package/lib/consts.js CHANGED
@@ -184,6 +184,13 @@ module.exports = {
184
184
  // how long is an authentication form valid
185
185
  MAX_FORM_TTL: 1 * 24 * 3600 * 1000,
186
186
 
187
+ // Max number of outbound-probe requests (email autodiscovery + "Verify connection" tests) allowed per
188
+ // issued form blob. These hosted-form endpoints authorize the caller by signature but do not consume
189
+ // the single-use nonce (a form autodetects/tests several times before submitting), so this shared cap
190
+ // bounds a leaked signed link from being replayed as an unlimited outbound-probe / SSRF oracle.
191
+ // Generous enough not to impede real use.
192
+ MAX_FORM_PROBE_ATTEMPTS: 50,
193
+
187
194
  NONCE_BYTES: 16,
188
195
 
189
196
  // We are using a legacy hash function in caching operations
@@ -72,7 +72,10 @@ function toGmailLabelId(label) {
72
72
  // Timing constants for Gmail Pub/Sub watch
73
73
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h - how often to check if watch needs renewal
74
74
  const MIN_WATCH_TTL = 24 * 3600 * 1000; // 1day - minimum time before renewing watch
75
- const FALLBACK_POLLING_INTERVAL = 10 * 60 * 1000; // 10min - fallback polling if no Pub/Sub notifications
75
+ // 10min default - fallback polling if no Pub/Sub notifications. Overridable via
76
+ // EENGINE_GMAIL_FALLBACK_POLL_INTERVAL (ms) so integration tests can exercise the poller
77
+ // without waiting the full interval.
78
+ const FALLBACK_POLLING_INTERVAL = Number((process.env.EENGINE_GMAIL_FALLBACK_POLL_INTERVAL || '').toString().trim()) || 10 * 60 * 1000;
76
79
 
77
80
  /*
78
81
  Gmail API implementation status:
@@ -126,7 +126,9 @@ async function request(context, url, method, payload, options = {}) {
126
126
 
127
127
  switch (status) {
128
128
  case 401:
129
- context.logger.error({ msg: 'Failed to authenticate API request', account: context.account, accessToken, err });
129
+ // NOTE: never include `accessToken` here - this logger persists to the per-account
130
+ // log store (exposed via the account logs API/UI) and to Sentry (security review M3).
131
+ context.logger.error({ msg: 'Failed to authenticate API request', account: context.account, err });
130
132
  throw err;
131
133
 
132
134
  case 429:
package/lib/export.js CHANGED
@@ -9,6 +9,7 @@ const { redis, exportQueue } = require('./db');
9
9
  const settings = require('./settings');
10
10
  const logger = require('./logger');
11
11
  const getSecret = require('./get-secret');
12
+ const { escapeRedisGlob } = require('./tools');
12
13
 
13
14
  const {
14
15
  REDIS_PREFIX,
@@ -304,7 +305,7 @@ class Export {
304
305
  const page = Number(options.page) || 0;
305
306
  const pageSize = Number(options.pageSize) || 20;
306
307
 
307
- const pattern = `${REDIS_PREFIX}exp:${account}:${EXPORT_ID_PREFIX}*`;
308
+ const pattern = `${REDIS_PREFIX}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
308
309
  const keys = await scanKeys(pattern);
309
310
 
310
311
  const exports = [];
@@ -567,7 +568,7 @@ class Export {
567
568
  if (!file.startsWith(EXPORT_ID_PREFIX)) continue;
568
569
 
569
570
  const exportId = file.split('.')[0];
570
- const pattern = `${REDIS_PREFIX}exp:*:${exportId}`;
571
+ const pattern = `${REDIS_PREFIX}exp:*:${escapeRedisGlob(exportId)}`;
571
572
  const keys = await scanKeys(pattern);
572
573
 
573
574
  if (keys.length === 0) {
@@ -12,6 +12,7 @@ const { Account } = require('./account');
12
12
  const getSecret = require('./get-secret');
13
13
  const { isApiBasedApp } = require('./oauth2-apps');
14
14
  const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
15
+ const { constantTimeEqual } = require('./tools');
15
16
 
16
17
  /**
17
18
  * Builds the IMAP proxy authentication handler.
@@ -25,7 +26,7 @@ function createImapProxyAuthHandler({ call }) {
25
26
  let account = auth.username;
26
27
 
27
28
  let imapPassword = await settings.get('imapProxyServerPassword');
28
- if (!imapPassword || auth.password !== imapPassword) {
29
+ if (!imapPassword || !constantTimeEqual(auth.password, imapPassword)) {
29
30
  // fall back to API token authentication
30
31
  let result = await validateAuthToken({
31
32
  password: auth.password,
package/lib/schemas.js CHANGED
@@ -48,6 +48,19 @@ const ADDRESS_STRATEGIES = [
48
48
 
49
49
  const accountIdSchema = Joi.string().empty('').trim().max(256).example('user123').description('Unique identifier for the email account');
50
50
 
51
+ // The service-secret-signed blob (base64url `data` + its HMAC `sig`) carried by every hosted
52
+ // authentication-form page. Defined once so the security-relevant field definitions cannot drift across
53
+ // the auth:false hosted-form endpoints. Both fields required: every issuer signs unconditionally and every
54
+ // template renders the sig hidden input, so a request without one is always hand-crafted. NB: the tracking
55
+ // endpoints (/redirect, /open.gif, /unsubscribe in workers/api.js) intentionally keep `sig` OPTIONAL at the
56
+ // Joi layer - their handlers fail closed on a missing/bad signature, and /unsubscribe must not turn a
57
+ // missing-sig request into a Joi 400 (RFC 8058 one-click wants a benign non-throwing response) - so they do
58
+ // NOT use this fragment.
59
+ const signedFormBlobFields = {
60
+ data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
61
+ sig: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required()
62
+ };
63
+
51
64
  // All states that the account state field can expose over the API. In addition to the state
52
65
  // machine states, 'disconnected' and 'paused' are client-level display states set by imap-client
53
66
  const ACCOUNT_DISPLAY_STATES = [...Object.values(ACCOUNT_STATES), 'disconnected', 'paused'];
@@ -2466,6 +2479,7 @@ module.exports = {
2466
2479
  responseFromAddressSchema,
2467
2480
  emailIdSchema,
2468
2481
  threadIdSchema,
2482
+ signedFormBlobFields,
2469
2483
  outboxEntrySchema,
2470
2484
  googleProjectIdSchema,
2471
2485
  googleTopicNameSchema,
package/lib/settings.js CHANGED
@@ -142,16 +142,36 @@ module.exports = {
142
142
  return value;
143
143
  },
144
144
 
145
- async set(key, value) {
146
- const encryptSecret = await getSecret();
147
-
148
- let formattedValue = module.exports.formatSettingValue(key, value);
149
- value = JSON.stringify(formattedValue);
145
+ // Serialize an already-formatted setting value the way get()/getValue() expect it back:
146
+ // JSON-encoded, encrypted for ENCRYPTED_KEYS members. Every writer (set, setMulti,
147
+ // setIfMissing) must go through this so the encoding cannot drift between them.
148
+ encodeSettingValue(key, formattedValue, encryptSecret) {
149
+ let value = JSON.stringify(formattedValue);
150
150
 
151
151
  if (encryptSecret && ENCRYPTED_KEYS.includes(key)) {
152
152
  value = encrypt(value, encryptSecret);
153
153
  }
154
154
 
155
+ return value;
156
+ },
157
+
158
+ async set(key, value) {
159
+ // A blank serviceSecret must never be persisted: an empty stored secret breaks HMAC
160
+ // signing/verification for every hosted-form and tracking link, and makes getServiceSecret()
161
+ // silently mint a fresh secret - invalidating every signed link already out in delivered mail.
162
+ // A blank value means "keep the current secret", not "clear it". Enforced here so it covers every
163
+ // writer that reaches set() (the /v1/settings API and the EENGINE_SETTINGS prepared config), not
164
+ // just the admin UI which additionally surfaces a flash. Boot-time minting (server.js) passes a
165
+ // non-empty random value, so it is unaffected.
166
+ if (key === 'serviceSecret' && (typeof value !== 'string' || !value.trim())) {
167
+ return 0;
168
+ }
169
+
170
+ const encryptSecret = await getSecret();
171
+
172
+ let formattedValue = module.exports.formatSettingValue(key, value);
173
+ value = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
174
+
155
175
  if (/^documentStore/.test(key)) {
156
176
  // increase version for documentStore settings
157
177
  try {
@@ -178,19 +198,30 @@ module.exports = {
178
198
  return await redis.hset(`${REDIS_PREFIX}settings`, key, value);
179
199
  },
180
200
 
201
+ // Store a value only if the key does not exist yet (atomic HSETNX). Meant for one-shot
202
+ // initialization keys (currently the auto-generated serviceSecret) where concurrent minters
203
+ // must converge on a single stored value instead of overwriting each other. Skips the
204
+ // documentStore/openAi side effects of set() on purpose. Returns true when the value was stored.
205
+ async setIfMissing(key, value) {
206
+ const encryptSecret = await getSecret();
207
+
208
+ value = module.exports.encodeSettingValue(key, module.exports.formatSettingValue(key, value), encryptSecret);
209
+
210
+ return (await redis.hsetnx(`${REDIS_PREFIX}settings`, key, value)) === 1;
211
+ },
212
+
181
213
  async setMulti(obj) {
182
214
  const encryptSecret = await getSecret();
183
215
  let docStoreUpdated = false;
184
216
  const storeObj = {};
185
217
  for (let key of Object.keys(obj)) {
186
- let formattedValue = module.exports.formatSettingValue(key, obj[key]);
187
- let value = JSON.stringify(formattedValue);
188
-
189
- if (encryptSecret && ENCRYPTED_KEYS.includes(key)) {
190
- value = encrypt(value, encryptSecret);
218
+ // See set(): never persist a blank serviceSecret - a blank value means "keep the current one".
219
+ if (key === 'serviceSecret' && (typeof obj[key] !== 'string' || !obj[key].trim())) {
220
+ continue;
191
221
  }
192
222
 
193
- storeObj[key] = value;
223
+ let formattedValue = module.exports.formatSettingValue(key, obj[key]);
224
+ storeObj[key] = module.exports.encodeSettingValue(key, formattedValue, encryptSecret);
194
225
 
195
226
  if (/^documentStore/.test(key)) {
196
227
  docStoreUpdated = true;
package/lib/smtp-auth.js CHANGED
@@ -10,6 +10,7 @@ const { redis } = require('./db');
10
10
  const { Account } = require('./account');
11
11
  const getSecret = require('./get-secret');
12
12
  const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
13
+ const { constantTimeEqual } = require('./tools');
13
14
 
14
15
  /**
15
16
  * Builds the SMTP server onAuth handler.
@@ -28,7 +29,7 @@ function createSmtpAuthHandler({ accountCache, call }) {
28
29
  let account = auth.username;
29
30
 
30
31
  let smtpPassword = await settings.get('smtpServerPassword');
31
- if (!smtpPassword || auth.password !== smtpPassword) {
32
+ if (!smtpPassword || !constantTimeEqual(auth.password, smtpPassword)) {
32
33
  // fall back to API token authentication
33
34
  let result = await validateAuthToken({
34
35
  password: auth.password,
package/lib/sub-script.js CHANGED
@@ -1,5 +1,13 @@
1
1
  'use strict';
2
2
 
3
+ // SECURITY WARNING: SubScript runs operator-authored fn/map/pre-processing code through
4
+ // Node's `vm` module. `vm` is NOT a security sandbox - code executed here can reach the
5
+ // host realm (e.g. via `someHostValue.constructor.constructor('return process')()`) and
6
+ // therefore runs with full server privileges (process env/secrets, host modules, fs).
7
+ // Only trusted operators may author these scripts; never expose script authoring to
8
+ // untrusted principals. Replacing this with a real isolate (isolated-vm) or out-of-process
9
+ // execution is a tracked follow-up (see security review finding C1).
10
+
3
11
  const crypto = require('crypto');
4
12
  const vm = require('vm');
5
13
  const logger = require('./logger');
@@ -73,9 +81,12 @@ class SubScript {
73
81
  }
74
82
 
75
83
  // Allow callers (and tests) to shorten the execution timeout, but never
76
- // raise it above SUBSCRIPT_RUNTIME_TIMEOUT - the sandbox cap is a hard
77
- // ceiling. A falsy override (including 0, which vm treats as "no limit")
78
- // falls back to the default so the cap can never be disabled.
84
+ // raise it above SUBSCRIPT_RUNTIME_TIMEOUT. A falsy override (including 0,
85
+ // which vm treats as "no limit") falls back to the default so the limit can
86
+ // never be disabled. NOTE: vm's `timeout` only interrupts SYNCHRONOUS
87
+ // execution - it does not bound async work, so a script that awaits (or spins
88
+ // the microtask queue) can still run past this limit. It is a coarse guard,
89
+ // not a hard ceiling (see security review finding M8).
79
90
  let runtimeTimeout = options && options.timeout ? Math.min(options.timeout, SUBSCRIPT_RUNTIME_TIMEOUT) : SUBSCRIPT_RUNTIME_TIMEOUT;
80
91
 
81
92
  let start = Date.now();
package/lib/tokens.js CHANGED
@@ -5,6 +5,7 @@ const crypto = require('crypto');
5
5
  const msgpack = require('msgpack5')();
6
6
  const logger = require('./logger');
7
7
  const { REDIS_PREFIX } = require('./consts');
8
+ const { constantTimeEqual } = require('./tools');
8
9
 
9
10
  const SESS_PREFIX = 'sess_';
10
11
 
@@ -64,7 +65,7 @@ module.exports = {
64
65
 
65
66
  const [storedSignature, storedAccount] = storedSignatureValue.split(':');
66
67
 
67
- if (!storedSignature || storedSignature !== expectedSignature) {
68
+ if (!storedSignature || !constantTimeEqual(storedSignature, expectedSignature)) {
68
69
  // Delete invalid tokens
69
70
  await redis.del(key);
70
71
  return false;
package/lib/tools.js CHANGED
@@ -11,7 +11,7 @@ const settings = require('./settings');
11
11
  const { brotliDecompress } = require('zlib');
12
12
  const util = require('util');
13
13
  const brotliDecompressAsync = util.promisify(brotliDecompress);
14
- const { createPublicKey, createVerify, randomBytes, createHmac } = require('crypto');
14
+ const { createPublicKey, createVerify, randomBytes, createHmac, createHash, timingSafeEqual } = require('crypto');
15
15
  const logger = require('./logger');
16
16
  const Boom = require('@hapi/boom');
17
17
  const { ImapFlow } = require('imapflow');
@@ -812,6 +812,26 @@ module.exports = {
812
812
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
813
813
  },
814
814
 
815
+ // Escape Redis glob metacharacters (\ * ? [ ]) so a user-controlled identifier interpolated into
816
+ // a SCAN/KEYS MATCH pattern matches literally and cannot widen the match across the key namespace
817
+ // (security review H2). Intended wildcards in the surrounding pattern are added by the caller and
818
+ // are not passed through here.
819
+ escapeRedisGlob(value) {
820
+ return String(value === null || value === undefined ? '' : value).replace(/[\\*?[\]]/g, '\\$&');
821
+ },
822
+
823
+ // Constant-time comparison of two secret / MAC strings. Both sides are hashed to a fixed-length
824
+ // digest first so timingSafeEqual never sees unequal lengths (which would throw and would leak
825
+ // length via the exception). Returns false for null/undefined (security review L1).
826
+ constantTimeEqual(a, b) {
827
+ if (a === null || a === undefined || b === null || b === undefined) {
828
+ return false;
829
+ }
830
+ const ha = createHash('sha256').update(String(a)).digest();
831
+ const hb = createHash('sha256').update(String(b)).digest();
832
+ return timingSafeEqual(ha, hb);
833
+ },
834
+
815
835
  getRendezvousScore(key, shardId) {
816
836
  return murmurhash(`${(shardId || '').toString()}\x00${key}`);
817
837
  },
@@ -984,6 +1004,13 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
984
1004
  },
985
1005
 
986
1006
  async verifyAccountInfo(redis, accountData, logger) {
1007
+ // By design this connects to whatever imap/smtp host it is given, with no private/loopback/
1008
+ // reserved-IP filtering: EmailEngine routinely talks to mail servers on any address (incl.
1009
+ // self-hosted boxes on RFC1918 / 127.0.0.1), and it is normally deployed as an isolated
1010
+ // instance with no sensitive internal services to reach. Callers that expose this to
1011
+ // untrusted input gate it upstream (e.g. the hosted form's signed-blob check), and network
1012
+ // isolation - not host filtering here - is the intended SSRF boundary. Do not add an
1013
+ // IP blocklist here without making it opt-in; it would break legitimate local-mail setups.
987
1014
  let response = {};
988
1015
 
989
1016
  let proxyUrl = await settings.get('proxyUrl');
@@ -1679,8 +1706,22 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1679
1706
  async getServiceSecret() {
1680
1707
  let serviceSecret = await settings.get('serviceSecret');
1681
1708
  if (!serviceSecret) {
1709
+ // Mint atomically (HSETNX): unauthenticated tracking/form requests can race to generate
1710
+ // a missing secret, and a plain read-then-write would let the last writer invalidate
1711
+ // whatever the first writer already signed. The loser adopts the winner's secret.
1682
1712
  serviceSecret = randomBytes(16).toString('hex');
1683
- await settings.set('serviceSecret', serviceSecret);
1713
+ let created = await settings.setIfMissing('serviceSecret', serviceSecret);
1714
+ if (!created) {
1715
+ let stored = await settings.get('serviceSecret');
1716
+ if (stored) {
1717
+ serviceSecret = stored;
1718
+ } else {
1719
+ // The field exists but reads back empty/undecryptable (e.g. explicitly blanked
1720
+ // via the settings API): HSETNX cannot heal it, so overwrite - same healing the
1721
+ // previous read-then-write implementation performed.
1722
+ await settings.set('serviceSecret', serviceSecret);
1723
+ }
1724
+ }
1684
1725
  }
1685
1726
  return serviceSecret;
1686
1727
  },
@@ -1732,26 +1773,95 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1732
1773
  return { data: data.toString('base64url'), signature };
1733
1774
  },
1734
1775
 
1735
- async parseSignedFormData(redis, payload, gt) {
1736
- let data = Buffer.from(payload.data, 'base64url').toString();
1737
- let serviceSecret = await settings.get('serviceSecret');
1738
- if (serviceSecret) {
1739
- let hmac = createHmac('sha256', serviceSecret);
1740
- hmac.update(data);
1741
- if (hmac.digest('base64url') !== payload.sig) {
1742
- let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
1743
- throw error;
1776
+ // Fail-closed HMAC check for service-secret-signed blobs, shared by every verification site.
1777
+ // getServiceSecret() generates and persists a secret when missing, so verification is never
1778
+ // silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
1779
+ // only when `sig` matches `data`.
1780
+ //
1781
+ // Reviewed compat note (accepted, do not revert to skip-when-empty): fail-closed means an install
1782
+ // whose stored serviceSecret is currently blank will 403 tracking/unsubscribe links in
1783
+ // already-delivered mail (the old code skipped verification and resolved them, which also accepted
1784
+ // FORGED blobs - the hole this closes). This is documented in the release notes; an operator can
1785
+ // restore the previous secret via the settings API to revive old links. The separate hazard of an
1786
+ // undecryptable-but-present secret being overwritten is PRE-EXISTING (server.js startApplication
1787
+ // re-mints a null-reading secret at boot, before any request), not introduced by this change - so
1788
+ // do not treat it as a regression of this refactor.
1789
+ async verifyServiceSignature(data, sig) {
1790
+ const serviceSecret = await module.exports.getServiceSecret();
1791
+ const hmac = createHmac('sha256', serviceSecret);
1792
+ hmac.update(data);
1793
+ return module.exports.constantTimeEqual(hmac.digest('base64url'), sig);
1794
+ },
1795
+
1796
+ // Redis key for a hosted-form single-use nonce (`n` inside the signed blob). Built in one place so
1797
+ // the sites that must agree on it - the consumed-nonce check below, the IMAP-arm claim
1798
+ // (lib/ui-routes/account-routes.js) and the OAuth callback claim (workers/api.js) - cannot drift.
1799
+ formNonceKey(n) {
1800
+ return `${REDIS_PREFIX}account:form:${n}`;
1801
+ },
1802
+
1803
+ // Atomically claim a hosted-form single-use nonce (SET NX). Returns true when THIS caller won the
1804
+ // claim, false when the key already existed (the signed URL was already used). Throws on a Redis error
1805
+ // - a Redis failure is NOT a consumed nonce, so callers must map it to a retryable 5xx, not a 403.
1806
+ // Shared by the IMAP-arm submit and the OAuth callback so the EX/NX/TTL semantics of the double-spend
1807
+ // guard cannot drift between the two arms; each caller keeps its own Boom 403/500 messages.
1808
+ async claimFormNonce(redis, n, t) {
1809
+ const claimed = await redis.set(module.exports.formNonceKey(n), (t || '0').toString(), 'EX', Math.floor(MAX_FORM_TTL / 1000), 'NX');
1810
+ return !!claimed;
1811
+ },
1812
+
1813
+ // Release a claimed nonce (best-effort) so the caller can let the user retry after a failed create.
1814
+ // Never throws - a lost release just leaves the nonce consumed for its TTL (the accepted residual of
1815
+ // claim-before-create). Pair with claimFormNonce.
1816
+ async releaseFormNonce(redis, n, logger) {
1817
+ const nonceKey = module.exports.formNonceKey(n);
1818
+ try {
1819
+ await redis.del(nonceKey);
1820
+ } catch (err) {
1821
+ if (logger) {
1822
+ logger.error({ msg: 'Failed to release claimed form nonce', nonceKey, err });
1744
1823
  }
1745
1824
  }
1825
+ },
1826
+
1827
+ async parseSignedFormData(redis, payload, gt, opts) {
1828
+ opts = opts || {};
1829
+
1830
+ let data = Buffer.from(payload.data, 'base64url').toString();
1831
+ if (!(await module.exports.verifyServiceSignature(data, payload.sig))) {
1832
+ let error = Boom.boomify(new Error(gt.gettext('Signature validation failed')), { statusCode: 403 });
1833
+ throw error;
1834
+ }
1746
1835
 
1747
1836
  data = JSON.parse(data);
1748
1837
 
1838
+ // Connection-driving / account-creating callers (the IMAP test + server endpoints) require a
1839
+ // single-use nonce so a signed blob cannot be replayed. Blobs issued without n/t (the
1840
+ // unsubscribe and tracking links) are verified by signature only and skip this gate.
1841
+ // NB! this also rejects hosted-form links generated by EmailEngine before v2.39 (those blobs
1842
+ // carry no n/t and never expire) BY DESIGN - a never-expiring signed setup link is exactly
1843
+ // the vulnerability this gate closes. Do not add a legacy bypass; issue a fresh setup link
1844
+ // instead. Warn so support can tell a legacy link from a forgery (the HMAC check above has
1845
+ // already passed at this point).
1846
+ //
1847
+ // Reviewed compat note (kept deliberately, do not "fix"): only the IMAP-arm endpoints pass
1848
+ // requireNonce, so a pre-v2.39 link dead-ends at those POSTs after the user enters credentials -
1849
+ // the accepted cost of closing the replay hole; recovery is re-issuing the link. The OAuth
1850
+ // re-auth path (POST /accounts/new -> accountFormHandler) intentionally does NOT pass
1851
+ // requireNonce, so rolling-upgrade re-auth and legacy OAuth links keep working; that arm's replay
1852
+ // safety is the atomic nonce claim in the OAuth callback (workers/api.js), not this gate.
1853
+ if (opts.requireNonce && (!data.n || !data.t)) {
1854
+ logger.warn({ msg: 'Rejected legacy signed form blob without a nonce (pre-v2.39 setup link)', account: data.account });
1855
+ let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1856
+ throw error;
1857
+ }
1858
+
1749
1859
  if (data.n && data.t) {
1750
1860
  if (data.t < Date.now() - (MAX_FORM_TTL - 60 * 1000)) {
1751
1861
  let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1752
1862
  throw error;
1753
1863
  }
1754
- const nonceSeen = await redis.exists(`${REDIS_PREFIX}account:form:${data.n}`);
1864
+ const nonceSeen = await redis.exists(module.exports.formNonceKey(data.n));
1755
1865
  if (nonceSeen) {
1756
1866
  let error = Boom.boomify(new Error(gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
1757
1867
  throw error;