emailengine-app 2.84.0 → 2.84.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 (93) hide show
  1. package/.dockerignore +6 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +35 -0
  4. package/Dockerfile +2 -2
  5. package/bin/emailengine.js +15 -0
  6. package/data/google-crawlers.json +1 -1
  7. package/docker-compose.yml +1 -1
  8. package/lib/account/own-account-key.js +42 -0
  9. package/lib/account-assignment.js +1 -33
  10. package/lib/account.js +32 -19
  11. package/lib/add-trackers.js +11 -4
  12. package/lib/api-routes/account-routes.js +67 -14
  13. package/lib/api-routes/gateway-routes.js +9 -3
  14. package/lib/api-routes/message-routes.js +7 -1
  15. package/lib/api-routes/mint-bounds.js +11 -0
  16. package/lib/api-routes/route-helpers.js +125 -3
  17. package/lib/api-routes/submit-routes.js +4 -2
  18. package/lib/auth-token.js +23 -10
  19. package/lib/bounce-detect.js +17 -5
  20. package/lib/consts.js +34 -0
  21. package/lib/create-imap-client.js +41 -2
  22. package/lib/email-client/base-client.js +20 -10
  23. package/lib/email-client/gmail-client.js +21 -7
  24. package/lib/email-client/imap/mailbox.js +10 -4
  25. package/lib/email-client/imap/response-metrics.js +75 -0
  26. package/lib/email-client/imap-client.js +5 -2
  27. package/lib/email-client/message-builder.js +7 -2
  28. package/lib/email-client/outlook/graph-api.js +17 -2
  29. package/lib/email-client/outlook-client.js +6 -3
  30. package/lib/email-client/smtp-pool-manager.js +6 -0
  31. package/lib/encrypt.js +9 -0
  32. package/lib/export.js +3 -1
  33. package/lib/get-raw-email.js +4 -2
  34. package/lib/imap-proxy-auth.js +14 -1
  35. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  36. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  37. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  38. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  39. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  40. package/lib/mcp/listen.js +10 -1
  41. package/lib/oauth/external-account-config.js +3 -1
  42. package/lib/oauth/gmail.js +21 -48
  43. package/lib/oauth/mail-ru.js +5 -38
  44. package/lib/oauth/outlook.js +26 -44
  45. package/lib/pbkdf2-phc.js +18 -1
  46. package/lib/privileged-settings.js +6 -3
  47. package/lib/redis-scan-delete.js +15 -1
  48. package/lib/schemas.js +78 -32
  49. package/lib/settings.js +13 -1
  50. package/lib/smtp-auth.js +23 -0
  51. package/lib/tools.js +245 -56
  52. package/lib/ui-routes/account-routes.js +16 -37
  53. package/lib/ui-routes/admin-config-routes.js +10 -38
  54. package/lib/ui-routes/admin-entities-routes.js +22 -24
  55. package/lib/ui-routes/auth-routes.js +47 -24
  56. package/lib/ui-routes/connection-security-form.js +74 -0
  57. package/lib/ui-routes/form-lists.js +46 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  59. package/lib/ui-routes/oauth-config-routes.js +9 -18
  60. package/lib/ui-routes/sign-in-helpers.js +59 -0
  61. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  62. package/lib/utils/map-concurrent.js +36 -0
  63. package/lib/utils/network.js +28 -0
  64. package/lib/utils/provider-id.js +27 -0
  65. package/lib/utils/require-tls.js +33 -0
  66. package/lib/web-safe-html.js +5 -6
  67. package/lib/webhook-penalty.js +75 -0
  68. package/lib/webhook-routing.js +22 -2
  69. package/package.json +21 -21
  70. package/sbom.json +1 -1
  71. package/server.js +74 -38
  72. package/static/js/ace/ace.js +1 -1
  73. package/static/js/ace/mode-handlebars.js +1 -1
  74. package/static/js/ace/mode-html.js +1 -1
  75. package/static/js/ace/mode-javascript.js +1 -1
  76. package/static/js/ace/mode-markdown.js +1 -1
  77. package/static/js/ace/worker-html.js +1 -1
  78. package/static/js/ace/worker-javascript.js +1 -1
  79. package/static/js/ace/worker-json.js +1 -1
  80. package/static/js/ee-client.js +5 -0
  81. package/static/licenses.html +23 -23
  82. package/translations/messages.pot +66 -66
  83. package/views/account/security.hbs +10 -0
  84. package/views/accounts/account.hbs +11 -11
  85. package/views/accounts/edit.hbs +6 -2
  86. package/views/partials/gateway_form.hbs +3 -1
  87. package/workers/api.js +43 -3
  88. package/workers/webhooks.js +39 -3
  89. package/config/test.toml +0 -46
  90. package/install.sh +0 -428
  91. package/setup-production.sh +0 -215
  92. package/systemd/emailengine.service +0 -97
  93. package/systemd/nginx-proxy.conf +0 -77
package/.dockerignore CHANGED
@@ -26,6 +26,12 @@ scripts
26
26
  systemd
27
27
  manual-test
28
28
 
29
+ # Development and test configuration: config/test.toml carries a prepared API token and binds
30
+ # the API to every interface, and config/development* is the developer's own. The image runs
31
+ # with the production configuration
32
+ config/development*
33
+ config/test.toml
34
+
29
35
  # Local environment, secrets and editor state. keylog.txt is a TLS key log (npm run dev writes one);
30
36
  # it is gitignored, but nothing else would keep it out of the context and the layer cache.
31
37
  .env*
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.84.0"
2
+ ".": "2.84.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.84.2](https://github.com/postalsys/emailengine/compare/v2.84.1...v2.84.2) (2026-10-18)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * bound what hostile message content and mail servers can make a worker do ([02daa27](https://github.com/postalsys/emailengine/commit/02daa27df82680dfa59c572258c88a576d74d2ad))
9
+ * bump @postalsys/email-text-tools to 2.4.24 and @postalsys/ee-client to 1.8.2, embed cid: images only in image attributes ([3d40506](https://github.com/postalsys/emailengine/commit/3d405060828e529156b4df954a3f6b8a5d8e25ae))
10
+ * bump @zone-eu/mailsplit to 5.4.24, mailparser to 3.9.41 and imapflow to 2.5.3 ([3266d8d](https://github.com/postalsys/emailengine/commit/3266d8d2518e37b3c40c947a87d258a68e364497))
11
+ * bump @zone-eu/mailsplit to 5.4.25, mailparser to 3.9.42 and imapflow to 2.5.4 ([76415b0](https://github.com/postalsys/emailengine/commit/76415b0dd58ea202a671e198f6fe9cae9d35d6f0))
12
+ * bump libmime to 5.5.1, libqp to 3.0.1, libbase64 to 1.4.1 and nodemailer to 10.1.7 ([a934ba7](https://github.com/postalsys/emailengine/commit/a934ba79964c2b58abae056adcb0a4544f872eb4))
13
+ * bump node from `ebfe2f9` to `44fce69` ([#676](https://github.com/postalsys/emailengine/issues/676)) ([54a6b87](https://github.com/postalsys/emailengine/commit/54a6b87ad04a9dbad0e91ed20bc179dd11235c48))
14
+ * bump nodemailer to 10.1.5, joi to 18.3.0 and the owned packages that pinned the previous releases ([8faa692](https://github.com/postalsys/emailengine/commit/8faa6926c6d025e77ba17eac027e671782d7b527))
15
+ * bump nodemailer to 10.1.6, smtp-server to 3.20.1 and mailparser to 3.9.45 ([bcf583e](https://github.com/postalsys/emailengine/commit/bcf583e94390c90574733e76ec04f7ac78558402))
16
+ * bump the owned dependencies to the releases of the 2026-10-16 security scan ([2cbd569](https://github.com/postalsys/emailengine/commit/2cbd5691cfed2a9103e021b334c62451228504fe))
17
+ * close the paths a bound or narrowed API token could use to reach other accounts ([c87c861](https://github.com/postalsys/emailengine/commit/c87c8612e41e92bc5abf79c8d3e42978b4d91364))
18
+ * derive a separate signing key per purpose from the service secret ([1fa3368](https://github.com/postalsys/emailengine/commit/1fa336891015dab0b184689412fd02d263dcb6c2))
19
+ * document the TLS options in the API reference and keep the admin modules within their size budgets ([9d96a0c](https://github.com/postalsys/emailengine/commit/9d96a0c5d2f5a17f7a2bbc4beff6869f3be919c1))
20
+ * give admin sessions a lifetime, count only failed sign-ins and ask for the password before enabling TOTP ([d08d3ab](https://github.com/postalsys/emailengine/commit/d08d3ab6c0af99652699b9d007a3e8678f97b115))
21
+ * harden the IMAP proxy and the SMTP listener against unauthenticated clients ([34ebdad](https://github.com/postalsys/emailengine/commit/34ebdad6201ba7ba73d3c20e25bf029782e80beb))
22
+ * keep account ids apart in Redis keys and URLs, and bound licenses, mail merges and stored secrets ([c9d3547](https://github.com/postalsys/emailengine/commit/c9d3547ddf06033022eb8833186efeb00b78847a))
23
+ * keep narrowed tokens off the webhook target, bound slow webhook targets and stop secrets leaking through logs and error payloads ([40ce6cb](https://github.com/postalsys/emailengine/commit/40ce6cbac9b77ea47adf0dc62f9146c5df3842f2))
24
+ * keep STARTTLS opportunistic for an IMAP account that opts out of requiring it ([42cac3a](https://github.com/postalsys/emailengine/commit/42cac3ab1a96cf6e0d6d93389dec06e01cdabc4b))
25
+ * penalise only timed-out webhook targets, log hapi's internal request errors and run the integration tier against cleartext mocks ([4578cc6](https://github.com/postalsys/emailengine/commit/4578cc674215a09b3d98cc28640007c883eec62a))
26
+ * save the webhook and OAuth2 app forms when a list field is not sent ([8157671](https://github.com/postalsys/emailengine/commit/81576712c91ead5374631e16d864bfd6a9856ddc))
27
+ * share the helpers the security fixes duplicated and move each rule to where it covers every caller ([b9ba3ec](https://github.com/postalsys/emailengine/commit/b9ba3ecf44599c861741e50b7f3940eaa54a3c56))
28
+ * treat an unreachable network as a transient connection failure ([b0b4dd5](https://github.com/postalsys/emailengine/commit/b0b4dd5cb56658a8d48f62392bb83a369db265d0))
29
+ * trim the line ends of a text body in linear time when rendering it as html ([d5d30cd](https://github.com/postalsys/emailengine/commit/d5d30cd12bc141c7aeb8d4d2f0f254e550519dd4))
30
+
31
+ ## [2.84.1](https://github.com/postalsys/emailengine/compare/v2.84.0...v2.84.1) (2026-10-15)
32
+
33
+
34
+ ### Bug Fixes
35
+
36
+ * assign accounts again when every IMAP worker restarts after a Redis reconnection ([2200319](https://github.com/postalsys/emailengine/commit/22003191c041f03346031518d3a5a8aec715ba91))
37
+
3
38
  ## [2.84.0](https://github.com/postalsys/emailengine/compare/v2.83.2...v2.84.0) (2026-10-15)
4
39
 
5
40
 
package/Dockerfile CHANGED
@@ -11,7 +11,7 @@
11
11
  # here; the runtime stage below copies out only the finished tree, so npm and its dependencies never
12
12
  # reach the published image. npm accounted for 38 of the 59 HIGH/CRITICAL findings in the old image
13
13
  # (a vendored tar, pacote, sigstore, minimatch) and nothing at runtime ever invokes it.
14
- FROM node:24-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1 AS builder
14
+ FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f AS builder
15
15
 
16
16
  ARG BUILDPLATFORM
17
17
  ARG TARGETPLATFORM
@@ -74,7 +74,7 @@ RUN : "${EE_COMMIT_HASH:?EE_COMMIT_HASH build arg is required, e.g. --build-arg
74
74
  && rm -f update-info.sh
75
75
 
76
76
  # Runtime stage.
77
- FROM node:24-alpine@sha256:ebfe2f90462722a7a4de65e91990e97fe0d401c70e0e762c5b53302f905ec1c1
77
+ FROM node:24-alpine@sha256:44fce696f38ba8c987c4db89954051000bbd05ffd8d8659ba15ed4a8602e937f
78
78
 
79
79
  # `apk upgrade` patches the Alpine packages that the base image itself lags on - at the time of
80
80
  # writing node:24-alpine still carries an openssl below 3.5.8-r0. dumb-init reaps zombies as PID 1.
@@ -6,6 +6,16 @@
6
6
  // lib/db below, off its optional node-gyp decoder. server.js sets the same for a direct start.
7
7
  process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED = 'true';
8
8
 
9
+ // The application root is the working directory, as for server.js: the `config/` directory
10
+ // wild-config loads below (executable `.js` configuration files included, run with the real
11
+ // require) and the `.env` file are resolved against it, and the directory a subcommand happened to
12
+ // be started from is not where this instance's configuration lives
13
+ try {
14
+ process.chdir(require('path').join(__dirname, '..'));
15
+ } catch (err) {
16
+ // ignore - may fail in a packaged binary or a containerized environment
17
+ }
18
+
9
19
  const packageData = require('../package.json');
10
20
  const fs = require('fs');
11
21
  const pathlib = require('path');
@@ -415,6 +425,11 @@ function run() {
415
425
  .then(res => {
416
426
  let returnValue = argv.hash || argv.r ? Buffer.from(res.passwordHash).toString('base64url') : res.password;
417
427
  process.stdout.write(returnValue);
428
+ // The password is stored, and every existing session is ended by the
429
+ // version bump; the login requirement itself is installed by each API
430
+ // worker at startup, so an instance that was running without a password
431
+ // keeps serving the admin pages without one until it is restarted
432
+ process.stderr.write('\nRestart running EmailEngine instances for the new password to take effect\n');
418
433
  return process.exit(0);
419
434
  })
420
435
  .catch(err => {
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-10-14T14:46:03.000000",
2
+ "creationTime": "2026-10-16T14:46:08.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
@@ -106,7 +106,7 @@ services:
106
106
  test: >
107
107
  sh -c "
108
108
  if [ -n \"$$REDIS_PASSWORD\" ]; then
109
- redis-cli --no-auth-warning -a \"$$REDIS_PASSWORD\" ping
109
+ REDISCLI_AUTH=\"$$REDIS_PASSWORD\" redis-cli --no-auth-warning ping
110
110
  else
111
111
  redis-cli ping
112
112
  fi
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ // Which per-account Redis keys belong to one account.
4
+ //
5
+ // The per-account keys are `<prefix>iam:<account>:<suffix>`, and an account id is free text that
6
+ // may contain ":" itself. A glob of `iam:<account>:*` therefore also matches every key of an
7
+ // account whose id begins with this one and a colon (`iam:tenant:*` covers `tenant:x`), so a
8
+ // delete or a flush of one account used to take another tenant's index with it. The suffix is
9
+ // a fixed vocabulary, which is what tells the two apart: the key is this account's only when what
10
+ // follows its id is one of the shapes EmailEngine writes.
11
+
12
+ // `g` (the gateway counters), `announced-in` (the Graph announced set), `h:<hash>` (a mailbox
13
+ // status hash), `l:<hash>` and `n:<hash>` (a mailbox's message list and notifications). The hash
14
+ // is mailboxPathHash(), a base36 number
15
+ const ACCOUNT_KEY_SUFFIX = /^(?:g|announced-in|[hln]:[0-9a-z]+)$/;
16
+
17
+ /**
18
+ * A predicate telling whether a key matched by the account's `iam:<account>:*` glob really
19
+ * belongs to the account, for filtering a scan.
20
+ *
21
+ * @param {String} prefix - REDIS_PREFIX
22
+ * @param {String} account - the account id
23
+ * @returns {Function} key => Boolean
24
+ */
25
+ function ownAccountKeyFilter(prefix, account) {
26
+ let head = `${prefix}iam:${account}:`;
27
+ return key => typeof key === 'string' && key.startsWith(head) && ACCOUNT_KEY_SUFFIX.test(key.slice(head.length));
28
+ }
29
+
30
+ /**
31
+ * Whether one key belongs to the account, see ownAccountKeyFilter().
32
+ *
33
+ * @param {String} prefix - REDIS_PREFIX
34
+ * @param {String} account - the account id
35
+ * @param {String} key - a key the scan returned
36
+ * @returns {Boolean}
37
+ */
38
+ function isOwnAccountKey(prefix, account, key) {
39
+ return ownAccountKeyFilter(prefix, account)(key);
40
+ }
41
+
42
+ module.exports = { isOwnAccountKey, ownAccountKeyFilter, ACCOUNT_KEY_SUFFIX };
@@ -164,37 +164,6 @@ function planRebalance({ workerAssigned, availableWorkers }, targetWorker) {
164
164
  return moves;
165
165
  }
166
166
 
167
- /**
168
- * Runs `fn` over `items` with at most `limit` calls in flight and resolves with the results in
169
- * item order once every call has settled. Rejects with the first failure, like Promise.all, but
170
- * only after the calls already in flight have settled, so a caller never has calls outstanding
171
- * it does not know about
172
- * @param {Array} items
173
- * @param {number} limit - Calls in flight at once
174
- * @param {Function} fn - async (item, index) -> result
175
- * @returns {Promise<Array>}
176
- */
177
- async function mapConcurrent(items, limit, fn) {
178
- const results = new Array(items.length);
179
- let next = 0;
180
- let failure = null;
181
- const runner = async () => {
182
- while (next < items.length && !failure) {
183
- const index = next++;
184
- try {
185
- results[index] = await fn(items[index], index);
186
- } catch (err) {
187
- failure = failure || err;
188
- }
189
- }
190
- };
191
- await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, runner));
192
- if (failure) {
193
- throw failure;
194
- }
195
- return results;
196
- }
197
-
198
167
  module.exports = {
199
168
  pickLeastLoadedWorker,
200
169
  rollbackAssignment,
@@ -202,6 +171,5 @@ module.exports = {
202
171
  requeueFailedAccounts,
203
172
  forgetAccount,
204
173
  shouldRequeueFailedAssignment,
205
- planRebalance,
206
- mapConcurrent
174
+ planRebalance
207
175
  };
package/lib/account.js CHANGED
@@ -21,6 +21,7 @@ const { encrypt, decrypt, decryptField, parseEncryptedData } = require('./encryp
21
21
  const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
22
22
  const settings = require('./settings');
23
23
  const redisScanDelete = require('./redis-scan-delete');
24
+ const { ownAccountKeyFilter } = require('./account/own-account-key');
24
25
  const { extractMultiValues, createTransaction } = require('./redis-operations');
25
26
  const outbox = require('./outbox');
26
27
  const tokens = require('./tokens');
@@ -444,9 +445,10 @@ class Account {
444
445
  *
445
446
  * @param {Object} accountData - The hash as read from Redis
446
447
  * @param {Object} [opts]
447
- * @param {boolean} [opts.skipDecrypt] - Leave every encrypted value as stored. Each stored value
448
- * has its own salt, so a cold decrypt is a synchronous key derivation; a listing that decrypted the
449
- * IMAP/SMTP passwords and OAuth2 tokens of every row blocked the API worker for tens of
448
+ * @param {boolean} [opts.skipDecrypt] - Leave every encrypted value as stored. A value written
449
+ * by another process, or before the salt was per process, carries a salt this process has not
450
+ * derived a key for, so a cold decrypt is a synchronous key derivation; a listing that decrypted
451
+ * the IMAP/SMTP passwords and OAuth2 tokens of every row blocked the API worker for tens of
450
452
  * seconds on a 1000-account page, for fields it never outputs. For callers that read only
451
453
  * the non-secret structure (listings, delegated-row lookups): the credentials and the
452
454
  * ENCRYPTED_ACCOUNT_FIELDS stay ciphertext, and an encrypted custom header list is left out
@@ -1719,7 +1721,7 @@ class Account {
1719
1721
  // should we wait though? might take a lot of time
1720
1722
  // Best effort like the cleanups above: the account record is already gone
1721
1723
  try {
1722
- await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
1724
+ await this.deleteOwnAccountKeys();
1723
1725
  } catch (err) {
1724
1726
  this.logger.error({ msg: 'Failed to delete the log keys of a deleted account', account: this.account, err });
1725
1727
  }
@@ -2245,19 +2247,30 @@ class Account {
2245
2247
  return messageData;
2246
2248
  }
2247
2249
 
2248
- async listSignatures(query) {
2250
+ // Deletes the per-account keys, `iam:<account>:*`. The glob also matches the keys of an
2251
+ // account whose id begins with this one and a colon, so the scan is filtered down to the keys
2252
+ // this account writes
2253
+ async deleteOwnAccountKeys() {
2254
+ await redisScanDelete(
2255
+ this.redis,
2256
+ this.logger,
2257
+ `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`,
2258
+ ownAccountKeyFilter(REDIS_PREFIX, this.account)
2259
+ );
2260
+ }
2261
+
2262
+ // Takes no caller input on purpose. The message is built from the account this object was
2263
+ // constructed for and nothing else: a query object merged over it used to let the caller
2264
+ // replace `cmd` and `account`, which turned a read on one account into any main-thread
2265
+ // command against any account.
2266
+ async listSignatures() {
2249
2267
  await this.loadAccountData(this.account, true);
2250
2268
 
2251
- return await this.call(
2252
- Object.assign(
2253
- {
2254
- cmd: 'listSignatures',
2255
- account: this.account
2256
- },
2257
- query,
2258
- { timeout: this.timeout }
2259
- )
2260
- );
2269
+ return await this.call({
2270
+ cmd: 'listSignatures',
2271
+ account: this.account,
2272
+ timeout: this.timeout
2273
+ });
2261
2274
  }
2262
2275
 
2263
2276
  /**
@@ -2385,7 +2398,7 @@ class Account {
2385
2398
  await pipeline.exec();
2386
2399
 
2387
2400
  // scan and delete keys
2388
- await redisScanDelete(this.redis, this.logger, `${escapeRedisGlob(REDIS_PREFIX)}iam:${escapeRedisGlob(this.account)}:*`);
2401
+ await this.deleteOwnAccountKeys();
2389
2402
 
2390
2403
  return true;
2391
2404
  } finally {
@@ -2565,9 +2578,9 @@ class Account {
2565
2578
  return accountData;
2566
2579
  }
2567
2580
 
2568
- async getActiveAccessTokenData() {
2569
- // throws if account does not exist
2570
- let accountData = await this.loadAccountData(this.account);
2581
+ async getActiveAccessTokenData(accountData) {
2582
+ // throws if account does not exist; a caller that just loaded the account passes it in
2583
+ accountData = accountData || (await this.loadAccountData(this.account));
2571
2584
  if (!accountData.oauth2 || !accountData.oauth2.auth || !accountData.oauth2.auth.user || !accountData.oauth2.provider) {
2572
2585
  let error = Boom.boomify(new Error('Not an OAuth2 account'), { statusCode: 403 });
2573
2586
  error.output.payload.code = 'AccountNotOAuth2';
@@ -4,7 +4,7 @@ const he = require('he');
4
4
 
5
5
  const { rewriteTextNodes } = require('./rewrite-text-nodes');
6
6
 
7
- const { getSignedFormDataSync, getServiceSecret } = require('./tools');
7
+ const { getSignedFormDataSync, getServiceSecret, SIGNING_PURPOSE } = require('./tools');
8
8
 
9
9
  async function addOpenTracker(html, account, messageId, baseUrl) {
10
10
  // add open tracker
@@ -20,7 +20,8 @@ async function addOpenTracker(html, account, messageId, baseUrl) {
20
20
  acc: account,
21
21
  msg: messageId
22
22
  },
23
- true
23
+ true,
24
+ SIGNING_PURPOSE.TRACKING
24
25
  );
25
26
 
26
27
  openTrackUrl.searchParams.append('data', data);
@@ -47,7 +48,12 @@ async function addClickTrackers(html, account, messageId, baseUrl) {
47
48
 
48
49
  const serviceSecret = await getServiceSecret();
49
50
 
50
- html = html.replace(/(<a[^>]* href\s*=[\s"']*)(http[^"'>\s]+)/gi, (match, prefix, url) => {
51
+ // `[^<>]*` rather than `[^>]*` for the attributes before href: an anchor that is never closed
52
+ // used to let the scan run to the end of the document from every `<a` and backtrack over it
53
+ // looking for ` href`, quadratic in the number of anchors (80 KB of `<a ` took most of a
54
+ // second). Stopping at the next `<` costs nothing for well-formed markup, where a tag never
55
+ // contains one
56
+ html = html.replace(/(<a[^<>]* href\s*=[\s"']*)(http[^"'>\s]+)/gi, (match, prefix, url) => {
51
57
  const redirectUrl = new URL('redirect', baseUrl);
52
58
 
53
59
  try {
@@ -79,7 +85,8 @@ async function addClickTrackers(html, account, messageId, baseUrl) {
79
85
  acc: account,
80
86
  msg: messageId
81
87
  },
82
- true
88
+ true,
89
+ SIGNING_PURPOSE.TRACKING
83
90
  );
84
91
 
85
92
  redirectUrl.searchParams.append('data', data);
@@ -11,7 +11,16 @@ const { autodetectImapSettings } = require('../autodetect-imap-settings');
11
11
  const Boom = require('@hapi/boom');
12
12
  const Joi = require('joi');
13
13
  const { failAction, getSignedFormData, getLogs, verifyAccountInfo } = require('../tools');
14
- const { handleError, maskSecrets, assertNoNetworkOverride, MASKED, MASK_NOTE } = require('./route-helpers');
14
+ const {
15
+ handleError,
16
+ maskSecrets,
17
+ assertNoNetworkOverride,
18
+ assertNoIdentityRetarget,
19
+ isRestrictedCredential,
20
+ isBoundCredential,
21
+ MASKED,
22
+ MASK_NOTE
23
+ } = require('./route-helpers');
15
24
 
16
25
  const {
17
26
  settingsSchema,
@@ -255,6 +264,12 @@ async function init(args) {
255
264
  // Validate delegation fields are only used with OAuth2 provider
256
265
  validateDelegationFields(request.payload);
257
266
 
267
+ // A narrowed provisioning token may register accounts, but not one that borrows
268
+ // another account's stored credential. Naming the mailbox of a new account on an
269
+ // application-credentials app is what registering one is, so unlike the update
270
+ // route this one does not ask which app the account is on
271
+ await assertNoIdentityRetarget(request);
272
+
258
273
  let result = await accountObject.create(request.payload);
259
274
  return result;
260
275
  } catch (err) {
@@ -437,6 +452,22 @@ async function init(args) {
437
452
  // Validate delegation fields are only used with OAuth2 provider
438
453
  validateDelegationFields(request.payload);
439
454
 
455
+ // Nor may a bound or narrowed token make this account authenticate as another one:
456
+ // delegation borrows another account's token, and on an application-credentials
457
+ // app the user field alone selects the mailbox. The app is looked up only when the
458
+ // payload names a user and the credential is one the rule applies to.
459
+ await assertNoIdentityRetarget(request, {
460
+ isServiceApp: async () => {
461
+ let provider = request.payload.oauth2.provider;
462
+ if (!provider) {
463
+ let accountData = await accountObject.loadAccountData();
464
+ provider = accountData.oauth2 && accountData.oauth2.provider;
465
+ }
466
+ let app = provider ? await oauth2Apps.get(provider) : null;
467
+ return !!(app && SERVICE_ACCOUNT_PROVIDERS.has(app.provider));
468
+ }
469
+ });
470
+
440
471
  // Credentials in this payload came from an API client, so a credential change here
441
472
  // can mean the account was re-authorized - the only caller allowed to arm the
442
473
  // reconnect gate in update().
@@ -1444,19 +1475,37 @@ async function init(args) {
1444
1475
  });
1445
1476
 
1446
1477
  try {
1447
- const tokenData = await accountObject.getActiveAccessTokenData();
1478
+ // Account data stores the OAuth2 app ID as the provider value; the app is looked
1479
+ // up once here, for the refusal below and the rename after the token is fetched
1480
+ let accountData = await accountObject.loadAccountData();
1481
+ let provider = accountData.oauth2 && accountData.oauth2.provider;
1482
+ let oauth2App = provider ? await oauth2Apps.get(provider) : null;
1483
+
1484
+ // A client-credentials token is the whole tenant's, not this account's: with it
1485
+ // the caller reads every mailbox the application was granted. A credential
1486
+ // admitted to one account, or narrowed below the full API, is therefore refused
1487
+ // it, whatever the setting above says. The admin interface and an unrestricted,
1488
+ // unbound token still get it. Only Graph: a Gmail service account mints its token
1489
+ // per user, with the mailbox as the JWT's subject, so that token is the account's
1490
+ // own and SERVICE_ACCOUNT_PROVIDERS would be the wrong list here
1491
+ if (oauth2App && oauth2App.provider === 'outlookService' && (isBoundCredential(request) || isRestrictedCredential(request))) {
1492
+ let error = Boom.forbidden(
1493
+ 'A token with restricted permissions can not read the access token of an account that authenticates with application credentials'
1494
+ );
1495
+ error.output.payload.code = 'ApplicationCredentialToken';
1496
+ throw error;
1497
+ }
1448
1498
 
1449
- // Account data stores the OAuth2 app ID as the provider value. Resolve it to the
1450
- // provider name and expose the app ID separately. Migrated legacy app IDs equal
1451
- // their provider name, so the lookup is a no-op rename for these.
1452
- if (tokenData.provider) {
1453
- let oauth2App = await oauth2Apps.get(tokenData.provider);
1454
- if (oauth2App) {
1455
- if (oauth2App.id !== oauth2App.provider) {
1456
- tokenData.app = oauth2App.id;
1457
- }
1458
- tokenData.provider = oauth2App.provider;
1499
+ const tokenData = await accountObject.getActiveAccessTokenData(accountData);
1500
+
1501
+ // Resolve the app ID to the provider name and expose the app ID separately.
1502
+ // Migrated legacy app IDs equal their provider name, so the lookup is a no-op
1503
+ // rename for these.
1504
+ if (tokenData.provider && oauth2App) {
1505
+ if (oauth2App.id !== oauth2App.provider) {
1506
+ tokenData.app = oauth2App.id;
1459
1507
  }
1508
+ tokenData.provider = oauth2App.provider;
1460
1509
  }
1461
1510
 
1462
1511
  // Record metric if token was actually refreshed (not cached)
@@ -1545,7 +1594,7 @@ async function init(args) {
1545
1594
  timeout: request.headers['x-ee-timeout']
1546
1595
  });
1547
1596
  try {
1548
- return await accountObject.listSignatures(request.query);
1597
+ return await accountObject.listSignatures();
1549
1598
  } catch (err) {
1550
1599
  handleError(request, err);
1551
1600
  }
@@ -1577,7 +1626,11 @@ async function init(args) {
1577
1626
  failAction,
1578
1627
  params: Joi.object({
1579
1628
  account: accountIdSchema.required()
1580
- })
1629
+ }),
1630
+ // The route takes no query arguments. Declared so that an unexpected one is
1631
+ // refused rather than silently reaching the handler (every /v1 GET route
1632
+ // declares its query, see test/api-routes-table-test.js)
1633
+ query: Joi.object({})
1581
1634
  },
1582
1635
 
1583
1636
  response: {
@@ -6,13 +6,16 @@ const { Gateway } = require('../gateway');
6
6
  const getSecret = require('../get-secret');
7
7
  const { failAction } = require('../tools');
8
8
  const { handleError, maskSecrets, MASKED, MASK_NOTE } = require('./route-helpers');
9
- const { apiResponses, apiBoolean, formBoolean } = require('../schemas');
9
+ const { apiResponses, apiBoolean, formBoolean, requireTlsSchema } = require('../schemas');
10
10
  const { ENUM_DESCRIPTIONS } = require('../enum-descriptions');
11
11
  const { IMPACT } = require('./operation-impact');
12
12
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
13
13
 
14
14
  // Gateways store SMTP delivery errors, not OAuth2 errors, so the error shape differs from the
15
15
  // account-level lastErrorSchema
16
+ // the account schemas' STARTTLS rule, on the form boolean the gateway payloads use
17
+ const gatewayRequireTlsSchema = requireTlsSchema('GatewayRequireTLS', formBoolean());
18
+
16
19
  const gatewayLastErrorSchema = Joi.object({
17
20
  created: Joi.number().integer().example(1623868624153).description('Timestamp of the error as milliseconds from epoch'),
18
21
  status: Joi.string().valid('error').example('error').description('Status of the last delivery attempt'),
@@ -235,6 +238,7 @@ async function init(args) {
235
238
  .example(true)
236
239
  .description('Should connection use TLS. Usually true for port 465')
237
240
  .label('GatewayTlsOptions'),
241
+ requireTLS: gatewayRequireTlsSchema.allow(null),
238
242
 
239
243
  lastError: gatewayLastErrorSchema.allow(null)
240
244
  }).label('GatewayResponse'),
@@ -326,7 +330,8 @@ async function init(args) {
326
330
  .default(false)
327
331
  .example(true)
328
332
  .description('Should connection use TLS. Usually true for port 465')
329
- .label('GatewayCreateTlsOptions')
333
+ .label('GatewayCreateTlsOptions'),
334
+ requireTLS: gatewayRequireTlsSchema
330
335
  }).label('CreateGateway')
331
336
  },
332
337
 
@@ -417,7 +422,8 @@ async function init(args) {
417
422
  .description('Service port number')
418
423
  .label('Port'),
419
424
 
420
- secure: formBoolean().example(true).description('Should connection use TLS. Usually true for port 465').label('GatewayUpdateTlsOptions')
425
+ secure: formBoolean().example(true).description('Should connection use TLS. Usually true for port 465').label('GatewayUpdateTlsOptions'),
426
+ requireTLS: gatewayRequireTlsSchema
421
427
  }).label('UpdateGateway')
422
428
  },
423
429
 
@@ -5,7 +5,8 @@ const { Account } = require('../account');
5
5
  const getSecret = require('../get-secret');
6
6
  const Joi = require('joi');
7
7
  const { failAction } = require('../tools');
8
- const { handleError } = require('./route-helpers');
8
+ const { handleError, assertCredentialAllows } = require('./route-helpers');
9
+ const { ACTION, GROUP } = require('./permission-map');
9
10
  const BEHAVIOR = require('./behavior-notes');
10
11
  const { IMPACT } = require('./operation-impact');
11
12
  const { FIELD_USAGE } = require('../field-usage');
@@ -168,6 +169,11 @@ async function init(args) {
168
169
  });
169
170
 
170
171
  try {
172
+ // The route resolves to read/message, and marking the message seen is a write
173
+ if (request.query.markAsSeen) {
174
+ assertCredentialAllows(request, { action: ACTION.WRITE, group: GROUP.MESSAGE }, 'mark a message as seen');
175
+ }
176
+
171
177
  // detectBounce is not a query option: it is what this route asks of the client, and
172
178
  // the internal fetches (a reply's reference, the sync path) do not pay for it
173
179
  let options = Object.assign({}, request.query, { detectBounce: true });
@@ -66,6 +66,17 @@ function mintWidenings(creator, payload) {
66
66
  const own = creator.restrictions || {};
67
67
  const requested = (payload && payload.restrictions) || {};
68
68
 
69
+ // Scopes are a limit too: a token minted with `api` only must not produce one that also serves
70
+ // the SMTP or IMAP proxy listeners, or every scope the creator was issued with is one request
71
+ // away from gone. A creator with no scope list, or `*`, holds every scope and may hand any out;
72
+ // a payload with no scope list asks for every scope and is refused by a scoped creator.
73
+ if (Array.isArray(creator.scopes) && creator.scopes.length && !creator.scopes.includes('*')) {
74
+ const list = Array.isArray(payload && payload.scopes) ? payload.scopes : [];
75
+ if (!list.length || !list.every(entry => creator.scopes.includes(entry))) {
76
+ reasons.push("scopes must be set to a subset of the creating token's own scopes");
77
+ }
78
+ }
79
+
69
80
  if (Array.isArray(own.addresses) && own.addresses.length) {
70
81
  const list = Array.isArray(requested.addresses) ? requested.addresses : [];
71
82
  if (!list.length || !list.every(entry => entryCovered(entry, own.addresses))) {