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/workers/api.js CHANGED
@@ -34,7 +34,11 @@ const {
34
34
  getBoolean,
35
35
  loadTlsConfig,
36
36
  maybeReloadHttpProxyAgent,
37
- resolveOAuthErrorStatus
37
+ resolveOAuthErrorStatus,
38
+ constantTimeEqual,
39
+ verifyServiceSignature,
40
+ claimFormNonce,
41
+ releaseFormNonce
38
42
  } = require('../lib/tools');
39
43
  const { matchIp, detectAutomatedRequest } = require('../lib/utils/network');
40
44
 
@@ -512,6 +516,11 @@ const init = async () => {
512
516
  return new handlebars.SafeString(translated);
513
517
  });
514
518
 
519
+ // HTML-escape a value for safe interpolation into an otherwise-unescaped context - e.g. a
520
+ // dynamic `%s` argument to the SafeString-returning `_` helper. Returns a plain string so
521
+ // the surrounding markup stays live while the value itself is entity-escaped.
522
+ handlebars.registerHelper('escapeHtml', value => handlebars.escapeExpression(value));
523
+
515
524
  handlebars.registerHelper('isodate', time => new Date(Number(time)).toISOString());
516
525
 
517
526
  handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
@@ -539,7 +548,12 @@ const init = async () => {
539
548
  } catch (err) {
540
549
  res = util.inspect(payload, false, 4, false);
541
550
  }
542
- return new handlebars.SafeString(res);
551
+ // SECURITY: return a plain string (NOT a SafeString) so Handlebars HTML-escapes the
552
+ // output. `payload` can carry attacker-controlled data (e.g. inbound email fields in
553
+ // webhook / pre-processing error logs); wrapping it in a SafeString allowed a stored
554
+ // XSS via a </textarea> breakout in the error-log views (security review H1). In the
555
+ // <textarea> render contexts this is display-identical (the browser decodes entities).
556
+ return res;
543
557
  });
544
558
 
545
559
  handlebars.registerHelper('lastVal', (value, separator) => {
@@ -1596,14 +1610,9 @@ Include your token in requests using one of these methods:
1596
1610
  path: '/redirect',
1597
1611
  async handler(request, h) {
1598
1612
  let data = Buffer.from(request.query.data, 'base64url').toString();
1599
- let serviceSecret = await settings.get('serviceSecret');
1600
- if (serviceSecret) {
1601
- let hmac = crypto.createHmac('sha256', serviceSecret);
1602
- hmac.update(data);
1603
- if (hmac.digest('base64url') !== request.query.sig) {
1604
- let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1605
- throw error;
1606
- }
1613
+ if (!(await verifyServiceSignature(data, request.query.sig))) {
1614
+ let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1615
+ throw error;
1607
1616
  }
1608
1617
 
1609
1618
  data = JSON.parse(data);
@@ -1651,6 +1660,12 @@ Include your token in requests using one of these methods:
1651
1660
  failAction,
1652
1661
 
1653
1662
  query: Joi.object({
1663
+ // `sig` is intentionally OPTIONAL on the tracking endpoints (/redirect, /open.gif,
1664
+ // /unsubscribe), unlike the hosted form's signedFormBlobFields which requires it. The
1665
+ // handler calls verifyServiceSignature and fails closed on a missing/bad signature, so a
1666
+ // required-sig schema would only turn that 403 into a Joi 400 - and /unsubscribe must not
1667
+ // 400 a missing-sig one-click request (RFC 8058 wants a benign non-throwing response).
1668
+ // Kept optional deliberately; do not "align" these with the hosted-form fragment.
1654
1669
  data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
1655
1670
  sig: Joi.string().base64({ paddingRequired: false, urlSafe: true })
1656
1671
  })
@@ -1665,14 +1680,9 @@ Include your token in requests using one of these methods:
1665
1680
  path: '/open.gif',
1666
1681
  async handler(request, h) {
1667
1682
  let data = Buffer.from(request.query.data, 'base64url').toString();
1668
- let serviceSecret = await settings.get('serviceSecret');
1669
- if (serviceSecret) {
1670
- let hmac = crypto.createHmac('sha256', serviceSecret);
1671
- hmac.update(data);
1672
- if (hmac.digest('base64url') !== request.query.sig) {
1673
- let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1674
- throw error;
1675
- }
1683
+ if (!(await verifyServiceSignature(data, request.query.sig))) {
1684
+ let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
1685
+ throw error;
1676
1686
  }
1677
1687
 
1678
1688
  data = JSON.parse(data);
@@ -1720,6 +1730,7 @@ Include your token in requests using one of these methods:
1720
1730
  failAction,
1721
1731
 
1722
1732
  query: Joi.object({
1733
+ // sig intentionally optional - see the note on the /redirect schema above.
1723
1734
  data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
1724
1735
  sig: Joi.string().base64({ paddingRequired: false, urlSafe: true })
1725
1736
  })
@@ -1733,21 +1744,33 @@ Include your token in requests using one of these methods:
1733
1744
  method: 'POST',
1734
1745
  path: '/unsubscribe',
1735
1746
  async handler(request) {
1736
- // NB! Avoid throwing errors
1747
+ // This unauthenticated RFC 8058 one-click endpoint separates two failure classes:
1748
+ // - Permanent (forged/malformed/incomplete blob, unknown account): retrying cannot help,
1749
+ // so return a benign 2xx string and do not invite a retry.
1750
+ // - Transient (a Redis/getSecret hiccup while recording the suppression): must surface as
1751
+ // a retryable 5xx. An RFC 8058 client treats any 2xx as "unsubscribed" and never retries,
1752
+ // so swallowing a transient failure to 2xx would silently drop the unsubscribe and the
1753
+ // recipient would keep receiving mail. eeListAdd is idempotent (isNew), so a retry is safe.
1737
1754
 
1738
- let data = Buffer.from(request.query.data, 'base64url').toString();
1739
- let serviceSecret = await settings.get('serviceSecret');
1740
- if (serviceSecret) {
1741
- let hmac = crypto.createHmac('sha256', serviceSecret);
1742
- hmac.update(data);
1743
- if (hmac.digest('base64url') !== request.query.sig) {
1744
- return 'data validation failed';
1745
- }
1755
+ // Joi already enforces base64url on request.query.data, and Buffer.from(<string>, 'base64url')
1756
+ // never throws, so decode inline like the sibling /redirect and /open.gif handlers.
1757
+ let raw = Buffer.from(request.query.data, 'base64url').toString();
1758
+
1759
+ // A false result is a forged/bad signature (permanent -> benign); a THROWN error is a
1760
+ // transient failure reading the service secret and is intentionally left to surface as 5xx.
1761
+ if (!(await verifyServiceSignature(raw, request.query.sig))) {
1762
+ return 'data validation failed';
1746
1763
  }
1747
1764
 
1748
- data = JSON.parse(data);
1765
+ let data;
1766
+ try {
1767
+ data = JSON.parse(raw);
1768
+ } catch (err) {
1769
+ // Malformed JSON inside a validly-signed blob - permanent.
1770
+ return 'not ok';
1771
+ }
1749
1772
 
1750
- if (!data || typeof data !== 'object' || data.act !== 'unsub') {
1773
+ if (!data || typeof data !== 'object' || data.act !== 'unsub' || !data.acc || !data.list || !data.rcpt) {
1751
1774
  return 'not ok';
1752
1775
  }
1753
1776
 
@@ -1763,9 +1786,18 @@ Include your token in requests using one of these methods:
1763
1786
  // throws if account does not exist
1764
1787
  await accountObject.loadAccountData();
1765
1788
  } catch (err) {
1766
- return 'unknown account';
1789
+ // A genuine "account does not exist" is a permanent 404 -> benign 2xx (retrying cannot
1790
+ // help). Any other error (e.g. a transient Redis/decrypt failure) must NOT be swallowed
1791
+ // to a 2xx: an RFC 8058 client treats any 2xx as "unsubscribed" and never retries, so
1792
+ // dropping the unsubscribe would leave the recipient subscribed. Let it surface as 5xx.
1793
+ if (err.output && err.output.statusCode === 404) {
1794
+ return 'unknown account';
1795
+ }
1796
+ throw err;
1767
1797
  }
1768
1798
 
1799
+ // Record the suppression. A transient backend failure here is intentionally NOT swallowed to
1800
+ // a 2xx: it propagates as a 5xx so the client retries rather than dropping the unsubscribe.
1769
1801
  let isNew = await redis.eeListAdd(
1770
1802
  `${REDIS_PREFIX}lists:unsub:lists`,
1771
1803
  `${REDIS_PREFIX}lists:unsub:entries:${data.list}`,
@@ -1784,13 +1816,19 @@ Include your token in requests using one of these methods:
1784
1816
  );
1785
1817
 
1786
1818
  if (isNew) {
1787
- await sendWebhook(data.acc, LIST_UNSUBSCRIBE_NOTIFY, {
1788
- recipient: data.rcpt,
1789
- messageId: data.msg,
1790
- listId: data.list,
1791
- remoteAddress: request.app.ip,
1792
- userAgent: request.headers['user-agent']
1793
- });
1819
+ // The suppression is already stored; a webhook delivery hiccup must not fail (and thus
1820
+ // trigger a client retry of) an unsubscribe that already succeeded. Log and move on.
1821
+ try {
1822
+ await sendWebhook(data.acc, LIST_UNSUBSCRIBE_NOTIFY, {
1823
+ recipient: data.rcpt,
1824
+ messageId: data.msg,
1825
+ listId: data.list,
1826
+ remoteAddress: request.app.ip,
1827
+ userAgent: request.headers['user-agent']
1828
+ });
1829
+ } catch (err) {
1830
+ request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', err });
1831
+ }
1794
1832
  }
1795
1833
 
1796
1834
  return 'ok';
@@ -1808,6 +1846,9 @@ Include your token in requests using one of these methods:
1808
1846
  failAction,
1809
1847
 
1810
1848
  query: Joi.object({
1849
+ // sig intentionally optional - see the note on the /redirect schema above. Especially
1850
+ // here: making sig required would 400 a missing-sig one-click POST, but RFC 8058 wants a
1851
+ // benign non-throwing response (the handler returns 'data validation failed' instead).
1811
1852
  data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
1812
1853
  sig: Joi.string().base64({ paddingRequired: false, urlSafe: true })
1813
1854
  }).label('OneClickUnsubQuery'),
@@ -1867,14 +1908,16 @@ Include your token in requests using one of these methods:
1867
1908
 
1868
1909
  for (let entry of (request.payload && request.payload.value) || []) {
1869
1910
  // enumerate and queue all entries
1870
- if (entry.subscriptionId !== outlookSubscription.id || entry.clientState !== outlookSubscription.clientState) {
1911
+ const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
1912
+ const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
1913
+ if (!subscriptionIdMatch || !clientStateMatch) {
1871
1914
  // Security: Log webhook validation failures - could indicate spoofed notifications
1872
1915
  request.logger.warn({
1873
1916
  msg: 'Webhook validation failed - potential security issue',
1874
1917
  securityEvent: 'webhook_validation_failure',
1875
1918
  account: request.query.account,
1876
- subscriptionIdMatch: entry.subscriptionId === outlookSubscription.id,
1877
- clientStateMatch: entry.clientState === outlookSubscription.clientState,
1919
+ subscriptionIdMatch,
1920
+ clientStateMatch,
1878
1921
  receivedSubscriptionId: entry.subscriptionId,
1879
1922
  changeType: entry.changeType,
1880
1923
  resource: entry.resource
@@ -1971,14 +2014,16 @@ Include your token in requests using one of these methods:
1971
2014
  });
1972
2015
 
1973
2016
  // enumerate and queue all entries
1974
- if (entry.subscriptionId !== outlookSubscription.id || entry.clientState !== outlookSubscription.clientState) {
2017
+ const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
2018
+ const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
2019
+ if (!subscriptionIdMatch || !clientStateMatch) {
1975
2020
  // Security: Log lifecycle webhook validation failures - could indicate spoofed notifications
1976
2021
  request.logger.warn({
1977
2022
  msg: 'Lifecycle webhook validation failed - potential security issue',
1978
2023
  securityEvent: 'lifecycle_webhook_validation_failure',
1979
2024
  account: request.query.account,
1980
- subscriptionIdMatch: entry.subscriptionId === outlookSubscription.id,
1981
- clientStateMatch: entry.clientState === outlookSubscription.clientState,
2025
+ subscriptionIdMatch,
2026
+ clientStateMatch,
1982
2027
  receivedSubscriptionId: entry.subscriptionId,
1983
2028
  lifecycleEvent: entry.lifecycleEvent
1984
2029
  });
@@ -2452,20 +2497,46 @@ Include your token in requests using one of these methods:
2452
2497
  timeout: request.headers['x-ee-timeout']
2453
2498
  });
2454
2499
 
2455
- let result = await accountObject.create(accountData);
2456
-
2500
+ // Claim the single-use nonce BEFORE create (SET NX), mirroring the IMAP arm in
2501
+ // lib/ui-routes/account-routes.js, so one signed link cannot be double-spent across the two
2502
+ // arms (initiate OAuth -> submit the same blob to /accounts/new/imap/server -> complete this
2503
+ // callback) and a replayed callback cannot create a second account.
2504
+ //
2505
+ // Backward-compat, BY DESIGN: this only engages when accountMeta.n is present. Legacy /
2506
+ // pre-upgrade re-auth blobs carry no nonce (accountMeta.n is undefined), so the claim is
2507
+ // skipped and those links keep working - the OAuth entry (accountFormHandler) intentionally
2508
+ // does NOT require a nonce for exactly that reason.
2509
+ // claimFormNonce/releaseFormNonce (lib/tools.js) are the same primitives the IMAP arm uses, so
2510
+ // the double-spend semantics stay in one place.
2511
+ let nonceClaimed = false;
2457
2512
  if (accountMeta.n) {
2458
- // store nonce to prevent this URL to be reused
2459
- const keyName = `${REDIS_PREFIX}account:form:${accountMeta.n}`;
2513
+ let claimed;
2460
2514
  try {
2461
- await redis
2462
- .multi()
2463
- .set(keyName, (accountMeta.t || '0').toString())
2464
- .expire(keyName, Math.floor(MAX_FORM_TTL / 1000))
2465
- .exec();
2515
+ claimed = await claimFormNonce(redis, accountMeta.n, accountMeta.t);
2466
2516
  } catch (err) {
2467
- request.logger.error({ msg: 'Failed to set nonce for an account form request', err });
2517
+ // A Redis failure is not a consumed nonce - surface a retryable error rather than
2518
+ // misreporting a valid setup URL as invalid.
2519
+ request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
2520
+ throw Boom.boomify(new Error('Temporary error, please try again'), { statusCode: 500 });
2521
+ }
2522
+ if (!claimed) {
2523
+ // The nonce key already exists: this signed URL was already used.
2524
+ throw Boom.boomify(new Error('Invalid or expired account setup URL'), { statusCode: 403 });
2468
2525
  }
2526
+ nonceClaimed = true;
2527
+ }
2528
+
2529
+ let result;
2530
+ try {
2531
+ result = await accountObject.create(accountData);
2532
+ } catch (err) {
2533
+ // Release the nonce so the user can retry (same accepted residual as the IMAP arm: if
2534
+ // Redis also fails here the nonce stays consumed for its TTL and a fresh link is needed -
2535
+ // the price of claim-before-create being atomic).
2536
+ if (nonceClaimed) {
2537
+ await releaseFormNonce(redis, accountMeta.n, request.logger);
2538
+ }
2539
+ throw err;
2469
2540
  }
2470
2541
 
2471
2542
  let httpRedirectUrl;