emailengine-app 2.82.0 → 2.82.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 (67) hide show
  1. package/.ncurc.js +23 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +51 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/bin/emailengine.js +77 -7
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +35 -10
  8. package/lib/api-routes/account-binding.js +58 -0
  9. package/lib/api-routes/account-routes.js +48 -9
  10. package/lib/api-routes/behavior-notes.js +4 -0
  11. package/lib/api-routes/gateway-routes.js +10 -2
  12. package/lib/api-routes/message-routes.js +10 -3
  13. package/lib/api-routes/outbox-routes.js +1 -1
  14. package/lib/api-routes/settings-routes.js +1 -2
  15. package/lib/api-routes/token-routes.js +1 -1
  16. package/lib/autodetect-imap-settings.js +146 -4
  17. package/lib/consts.js +12 -0
  18. package/lib/db.js +1 -19
  19. package/lib/delivery-error.js +68 -1
  20. package/lib/email-client/base-client.js +6 -13
  21. package/lib/email-client/credential-errors.js +21 -5
  22. package/lib/email-client/gmail-client.js +2 -2
  23. package/lib/email-client/imap-client.js +2 -1
  24. package/lib/email-client/message-builder.js +41 -11
  25. package/lib/email-client/outlook-client.js +263 -84
  26. package/lib/email-client/outlook-fallback-poll.js +30 -0
  27. package/lib/enum-descriptions.js +5 -1
  28. package/lib/export.js +8 -2
  29. package/lib/gateway.js +5 -0
  30. package/lib/get-secret.js +1 -21
  31. package/lib/mcp/tools.js +95 -36
  32. package/lib/oauth/gmail.js +42 -12
  33. package/lib/oauth/mail-ru.js +24 -17
  34. package/lib/oauth/outlook.js +34 -24
  35. package/lib/oauth/scope-checker.js +35 -1
  36. package/lib/oauth/scope-list.js +55 -0
  37. package/lib/oauth/token-fetch.js +47 -0
  38. package/lib/oauth2-apps.js +16 -47
  39. package/lib/outbox.js +2 -7
  40. package/lib/queue-retention.js +4 -2
  41. package/lib/read-env-value.js +33 -2
  42. package/lib/schemas.js +62 -15
  43. package/lib/token-audit-log.js +3 -2
  44. package/lib/tools.js +1 -1
  45. package/lib/ui-routes/account-routes.js +40 -7
  46. package/lib/ui-routes/oauth-config-routes.js +3 -14
  47. package/lib/ui-routes/outlook-subscription-view.js +36 -0
  48. package/lib/ui-routes/route-helpers.js +25 -37
  49. package/lib/ui-routes/special-use-paths.js +33 -0
  50. package/lib/utils/network.js +9 -17
  51. package/package.json +18 -18
  52. package/sbom.json +1 -1
  53. package/server.js +21 -3
  54. package/setup-production.sh +16 -7
  55. package/static/licenses.html +30 -20
  56. package/translations/messages.pot +74 -56
  57. package/views/account-workspace-error.hbs +30 -0
  58. package/views/accounts/account.hbs +14 -6
  59. package/views/accounts/edit.hbs +11 -2
  60. package/views/internals/index.hbs +1 -1
  61. package/views/partials/gmail_api_scopes.hbs +16 -0
  62. package/views/partials/oauth_form.hbs +67 -94
  63. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  64. package/views/partials/scope_info.hbs +14 -23
  65. package/workers/api.js +62 -27
  66. package/workers/imap.js +6 -3
  67. package/workers/submit.js +2 -5
package/.ncurc.js CHANGED
@@ -11,7 +11,26 @@ module.exports = {
11
11
  // is a major we are deliberately soaking. Using 'minor' instead of a blanket reject so these
12
12
  // still receive security/patch updates within the safe major instead of being frozen at one
13
13
  // exact version. Verified against Node 20 (Docker) 2026-06-17.
14
- target: name => (['nanoid', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked', '@sentry/node-core'].includes(name) ? 'minor' : 'latest'),
14
+ //
15
+ // `pino` is capped harder than the rest, at 'patch', because the break arrived in a MINOR and a
16
+ // major cap would not have stopped it. See its entry below.
17
+ target: name =>
18
+ name === 'pino'
19
+ ? 'patch'
20
+ : ['nanoid', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked', '@sentry/node-core', 'he'].includes(name)
21
+ ? 'minor'
22
+ : 'latest',
23
+ // pino - held on 10.3.x. 10.4.0 took PR #2294, which makes lib/caller.js prefer
24
+ // util.getCallSites() over the Error.prepareStackTrace dance. Inside a pkg
25
+ // binary that API aborts the PROCESS, not the call: V8 fails the CHECK in
26
+ // Script::GetPositionInfo() for a script that has no position info in the
27
+ // snapshot, and the binary dies on startup with SIGTRAP (exit 133) before
28
+ // main() does anything. `emailengine --version` is enough to trigger it.
29
+ // Reproduced on node24-macos-arm64 and caught by the linux-x64 binary build
30
+ // job, which exists for exactly this. Nothing in EmailEngine calls the API:
31
+ // pino reaches it whenever a logger is constructed. Lift only once a pino
32
+ // release guards the getCallSites path, or pkg ships position info for
33
+ // snapshotted scripts, and only with a binary built and run to prove it.
15
34
  // nanoid - 4.x dropped the CommonJS require export (ESM-only)
16
35
  // gettext-parser - 8.x is ESM-only
17
36
  // xgettext-template - 6.x is ESM-only (translation build tool)
@@ -21,6 +40,9 @@ module.exports = {
21
40
  // marked - 16.x dropped the CommonJS build (ESM-only, needs require(esm)/Node >=20.19); 15.x is the
22
41
  // last require()-compatible line. 15.0.12 verified on Node 20-24 and in a yao/pkg node24 build.
23
42
  // Permanent while the Node 20 floor above stands.
43
+ // he - 2.x is ESM-only (exports only src/he.mjs) and requires Node >=22; require('he') throws
44
+ // ERR_REQUIRE_ESM on Node 20 before 20.19. 1.2.0 is the last CommonJS release. mailparser,
45
+ // which reaches EmailEngine through the same require, rejects 2.x for the same reason.
24
46
  // @sentry/node-core - held on the 10.x line for the reasons @sentry/node (which it replaced, through its
25
47
  // `light` entry) was held there: @sentry/node 11.x requires Node >=20.19 (the DigitalOcean
26
48
  // images are not guaranteed to be on a 20.x that new), and it depends on
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.82.0"
2
+ ".": "2.82.2"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.82.2](https://github.com/postalsys/emailengine/compare/v2.82.1...v2.82.2) (2026-10-05)
4
+
5
+
6
+ ### Bug Fixes
7
+
8
+ * **outlook:** keep polling an account whose subscription fails but whose mailbox can be read ([a563624](https://github.com/postalsys/emailengine/commit/a563624137b14c66b0c10bf431139656c5da0c7c))
9
+
10
+ ## [2.82.1](https://github.com/postalsys/emailengine/compare/v2.82.0...v2.82.1) (2026-10-05)
11
+
12
+
13
+ ### Bug Fixes
14
+
15
+ * carry the GatewayNotFound code in the 404 response body ([43af659](https://github.com/postalsys/emailengine/commit/43af65915bc6daa77bbf1612860eb40e62ed93ef))
16
+ * check every PTR record when filtering scanner opens and clicks ([ebcd78b](https://github.com/postalsys/emailengine/commit/ebcd78b7957c925b5dc454415f7d9706b17d4a21))
17
+ * classify a wrapped transport failure as the outage it is ([a8d63a8](https://github.com/postalsys/emailengine/commit/a8d63a841fcdb55faa619656bb43d2008c0ce3e2))
18
+ * correct the descriptions and comments that disagreed with the behavior ([dcdc3e9](https://github.com/postalsys/emailengine/commit/dcdc3e9b994ab137afe5769790d8c9cd5a227233))
19
+ * declare the token-request fields the error record actually carries ([23fd0e4](https://github.com/postalsys/emailengine/commit/23fd0e4f8ad2de79bb251cc72eefb2736f1a541e))
20
+ * **deps:** hold pino at 10.3.x, which 10.4.0 made unbundlable ([4c4e7e3](https://github.com/postalsys/emailengine/commit/4c4e7e32bfde6a079bce796a15b2b85f6374c312))
21
+ * **deps:** update @sentry/node-core, pino, eslint and supertest ([9c5b9d5](https://github.com/postalsys/emailengine/commit/9c5b9d51c7a1e8ffd11adecd5181c9b4461bb34c))
22
+ * **deps:** update imapflow, mailparser, nodemailer and smtp-server ([ef14661](https://github.com/postalsys/emailengine/commit/ef1466115acc3dc727e1b46b08fd194dd3f90beb))
23
+ * **deps:** update imapflow, nodemailer, mailparser and the libbase64 chain ([9c8971e](https://github.com/postalsys/emailengine/commit/9c8971e345cfada10f875ca1086ea010b10ada91))
24
+ * describe hasMore the way both backends behave ([8b0bc19](https://github.com/postalsys/emailengine/commit/8b0bc19b32adf8fdb3c5095551ad75417430ba8a))
25
+ * document progress.networkRouting where the outbox entry carries it ([593e390](https://github.com/postalsys/emailengine/commit/593e390e38964e8f57359b421a2d2825a50be1cb))
26
+ * follow an autodiscovery in-response redirect anonymously ([554068e](https://github.com/postalsys/emailengine/commit/554068e322bc7f2daf67ad1841900c420e9d3da1))
27
+ * hold MCP text results to the result cap, newest-first for a log ([d44c648](https://github.com/postalsys/emailengine/commit/d44c64834bf86b36ee0ffe4cdd56da96a8733718))
28
+ * let POST /v1/gateway generate the gateway id ([6901349](https://github.com/postalsys/emailengine/commit/6901349bcfb25fe2c3995a1c0d2a8fe54fd10ba7))
29
+ * let the CLI issue the mcp-manage scope, with explicit grants ([84565d1](https://github.com/postalsys/emailengine/commit/84565d149d7661390c8c75e8a737fa14a628f238))
30
+ * make the export retention and per-message size limits settable ([c6e6930](https://github.com/postalsys/emailengine/commit/c6e6930d6619ae8ceb96a70ac151707db86de7d6))
31
+ * move the nextAttempt retry timing into the module that owns the job phase ([24defb8](https://github.com/postalsys/emailengine/commit/24defb839c725f0f6abdee3bd7f08a395f92aa77))
32
+ * name the token endpoint when a credential request cannot reach it ([a0748bc](https://github.com/postalsys/emailengine/commit/a0748bc61943f107fdaf18d01cf02e9f1b899c8b))
33
+ * offer all five special-use folder overrides on the account form ([d7faa2d](https://github.com/postalsys/emailengine/commit/d7faa2d6a39984fb4ccbf0e41026abcc279aec13))
34
+ * offer the Gmail API base scope to a service-account app ([fc23ea2](https://github.com/postalsys/emailengine/commit/fc23ea2a39142c0cb561d687b4d0be862068a6bc))
35
+ * **outlook:** recover messages whose Graph notification was silently dropped ([f0ea5c1](https://github.com/postalsys/emailengine/commit/f0ea5c19fd6835d23a6665c1431bc3f0a054dde2))
36
+ * perform the autodiscovery steps that name another endpoint ([83a4f6c](https://github.com/postalsys/emailengine/commit/83a4f6cd43ad523062acfed4674a0e8bde194891))
37
+ * print the api.proxy default the server actually applies ([c611661](https://github.com/postalsys/emailengine/commit/c6116611b607dd0e7011e3ed93eefaa45e80c4f4))
38
+ * read EENGINE_WORKERS_EXPORT, which the Workers page already named ([f397492](https://github.com/postalsys/emailengine/commit/f397492cbfd6a05a55b31ce1c1e0518f6a7e7743))
39
+ * read every EENGINE_ variable through the one helper ([b58bfec](https://github.com/postalsys/emailengine/commit/b58bfeccfc18ff39ec841e4e737a4a1299cc499d))
40
+ * record a delivery failure the SMTP error table cannot describe ([01d749f](https://github.com/postalsys/emailengine/commit/01d749f7c3d67d54af0a5abbdfab0f52ec69e233))
41
+ * report a parked IMAP account as an IMAP account ([0be8f56](https://github.com/postalsys/emailengine/commit/0be8f568719143919c2fa67300969a300050a15c))
42
+ * run the Docker Compose command setup-production.sh checked for ([e0e7272](https://github.com/postalsys/emailengine/commit/e0e7272bd481ca5ce6362ee559fdaca04f3730b1))
43
+ * say that a Graph subscription failure is what connectError can mean ([a073622](https://github.com/postalsys/emailengine/commit/a0736226cdb4b7ef59bbb6f1b9221035575280f7))
44
+ * say what happens to the workers when there is no active license ([0b97e05](https://github.com/postalsys/emailengine/commit/0b97e056bda19904b385b8441c5c72eca74d8392))
45
+ * say what makes an OAuth2 app API-based ([d54f8eb](https://github.com/postalsys/emailengine/commit/d54f8eb51ada78844418ee0d09509339f8a2f2ae))
46
+ * say when a file-backed secret resolves differently than it used to ([f4712fa](https://github.com/postalsys/emailengine/commit/f4712fa1b58608a4141f0b3e8c9c7231307db477))
47
+ * stop a failed quota lookup from failing the account it belongs to ([dd45dac](https://github.com/postalsys/emailengine/commit/dd45dac933dbb11f27eb2ad41b6eba2ca2e4985d))
48
+ * stop advertising verify_oauth2_app to an account-bound MCP credential ([441dc3f](https://github.com/postalsys/emailengine/commit/441dc3f00b3290355e49e295795c36b576fe2f04))
49
+ * stop the account form wiping the folder overrides it does not show ([fc3d5eb](https://github.com/postalsys/emailengine/commit/fc3d5eb7ccc74ef3d3a2d01416fce0641828ef1a))
50
+ * strip skipped scopes on every Microsoft cloud, not just the global one ([d74ab26](https://github.com/postalsys/emailengine/commit/d74ab260347424d9cd3b95954ddd09a18a06d513))
51
+ * tighten the MCP account binding, result cap, outbox retry time and CLI scopes ([a54a448](https://github.com/postalsys/emailengine/commit/a54a448294b17eaa84635ffc1ebb6e7f03561b37))
52
+ * verify the hd claim for a Workspace-only OAuth2 application ([5fbb322](https://github.com/postalsys/emailengine/commit/5fbb3228d634f65dab654bd9370d54611e2f0981))
53
+
3
54
  ## [2.82.0](https://github.com/postalsys/emailengine/compare/v2.81.2...v2.82.0) (2026-10-01)
4
55
 
5
56
 
@@ -156,13 +156,11 @@ server {
156
156
  proxy_read_timeout 600;
157
157
  }
158
158
 
159
- # WebSocket support
160
- location /socket.io/ {
161
- proxy_pass http://127.0.0.1:3000/socket.io/;
162
- proxy_http_version 1.1;
163
- proxy_set_header Upgrade $http_upgrade;
164
- proxy_set_header Connection "upgrade";
165
- }
159
+ # No extra location is needed for the live updates. EmailEngine streams account state changes as
160
+ # Server-Sent Events over the ordinary path (/v1/changes and the admin UI's own stream) and sends
161
+ # `X-Accel-Buffering: no` with them, which nginx honours, so the events are not held in a buffer.
162
+ # The read timeout above does apply to them: an idle feed is cut after 600s. A browser EventSource
163
+ # reconnects on its own; a /v1/changes consumer written by hand has to do the same.
166
164
  }
167
165
 
168
166
  server {
@@ -288,8 +286,9 @@ docker-compose logs --tail=50 emailengine
288
286
  #### Rollback if Needed
289
287
 
290
288
  ```bash
291
- # Specify previous version in .env
292
- EMAILENGINE_VERSION=2.40.0
289
+ # Specify previous version in .env. The published image tags carry the `v` prefix the git tags
290
+ # carry (v2.82.0, v2.82, v2, latest), so a bare 2.40.0 resolves to no image at all.
291
+ EMAILENGINE_VERSION=v2.40.0
293
292
  docker-compose up -d --no-deps emailengine
294
293
  ```
295
294
 
@@ -392,9 +391,11 @@ docker-compose logs --tail=100 emailengine
392
391
  #### Performance Issues
393
392
 
394
393
  ```bash
395
- # Enable debug logging temporarily
396
- docker-compose exec emailengine sh -c 'export EENGINE_LOG_LEVEL=debug'
397
- docker-compose restart emailengine
394
+ # Enable debug logging. The level is read from the environment at startup, so it has to be set on
395
+ # the container rather than exported inside it - `exec ... export` sets it in a shell that then
396
+ # exits, and `restart` reuses the container's existing environment either way.
397
+ echo 'EENGINE_LOG_LEVEL=debug' >> .env
398
+ docker-compose up -d --no-deps --force-recreate emailengine
398
399
 
399
400
  # Check slow operations
400
401
  docker-compose exec redis redis-cli -a "$REDIS_PASSWORD" SLOWLOG GET 10
@@ -63,7 +63,13 @@ const COMMANDS = {
63
63
  description: 'Create a new access token',
64
64
  options: [
65
65
  { name: '--description, -d', description: 'Token description', type: 'string' },
66
- { name: '--scope, -s', description: 'Access scope', type: 'string', default: '*' },
66
+ {
67
+ name: '--scope, -s',
68
+ description:
69
+ 'Access scope, repeatable: "*", "api", "metrics", "smtp", "imap-proxy", "mcp-manage" or "mcp". An MCP scope requires an access level after a colon ("mcp-manage:observe", levels observe/operate/administer; "mcp:read", levels read/mail/full), and cannot be combined with the others',
70
+ type: 'string',
71
+ default: '*'
72
+ },
67
73
  { name: '--account, -a', description: 'Limit token to specific account', type: 'string' }
68
74
  ]
69
75
  },
@@ -120,10 +126,13 @@ const GLOBAL_OPTIONS = [
120
126
  group: 'API server'
121
127
  },
122
128
  {
129
+ // The effective default, not the flag's own: server.js seeds the enableApiProxy setting to true
130
+ // when neither --api.proxy nor EENGINE_API_PROXY is given, which is the historical behavior.
131
+ // Printing the option's default told operators the header was ignored unless they opted in.
123
132
  name: '--api.proxy',
124
133
  description: 'Trust X-Forwarded-For from the reverse proxy in front of the API (restrict the peers with EENGINE_API_PROXY_ADDRESSES)',
125
134
  type: 'boolean',
126
- default: false,
135
+ default: true,
127
136
  group: 'API server'
128
137
  },
129
138
  { name: '--api.tls.certPath', description: 'Path to the TLS certificate; setting it serves the API over HTTPS', type: 'string', group: 'API server' },
@@ -513,22 +522,82 @@ function run() {
513
522
  switch (tokensCmd) {
514
523
  case 'issue':
515
524
  {
516
- let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy', 'mcp'];
517
- let scopes = []
525
+ const { MCP_SECTIONS, mcpGrantsFor, mcpLevel } = require('../lib/token-permission-view');
526
+
527
+ // The two MCP scopes, by the name typed on the command line. A token
528
+ // holding one of them always carries the pair list of a named access
529
+ // level, exactly as the admin form and the consent prompt mint it: a
530
+ // credential issued for the tools of today must not grow to include a
531
+ // tool shipped next release. The level is appended to the scope with a
532
+ // colon (`--scope mcp-manage:observe`) and is REQUIRED: there is no
533
+ // consent prompt here to show what a level allows, and the one thing an
534
+ // implicit default must not do is pick the widest one.
535
+ const mcpScopes = new Map(Object.entries(MCP_SECTIONS).map(([key, section]) => [section.scope, { key, section }]));
536
+
537
+ let allowedScopes = ['*', 'api', 'metrics', 'smtp', 'imap-proxy'].concat([...mcpScopes.keys()]);
538
+ let requestedScopes = []
518
539
  .concat(argv.scope || [])
519
540
  .concat(argv.s || [])
520
541
  .map(entry => (entry || '').toString().toLowerCase());
521
542
 
522
- if (!scopes.length) {
523
- scopes = ['*'];
543
+ if (!requestedScopes.length) {
544
+ requestedScopes = ['*'];
524
545
  }
525
546
 
526
- for (let scope of scopes) {
547
+ let scopes = [];
548
+ let mcpChoice = {};
549
+
550
+ for (let entry of requestedScopes) {
551
+ let separator = entry.indexOf(':');
552
+ let scope = separator < 0 ? entry : entry.slice(0, separator);
553
+ let level = separator < 0 ? null : entry.slice(separator + 1);
554
+
527
555
  if (!allowedScopes.includes(scope)) {
528
556
  console.error(`Unknown scope: ${scope}`);
529
557
  console.error(`Allowed scopes: "${allowedScopes.join('", "')}"`);
530
558
  process.exit(1);
531
559
  }
560
+
561
+ if (!mcpScopes.has(scope)) {
562
+ if (level !== null) {
563
+ console.error(`Scope "${scope}" does not take an access level`);
564
+ process.exit(1);
565
+ }
566
+ scopes.push(scope);
567
+ continue;
568
+ }
569
+
570
+ const { key, section } = mcpScopes.get(scope);
571
+ // mcpLevel() is the shared vocabulary, and it answers null both for a
572
+ // name the section does not have and for `none` - which is what makes
573
+ // `--scope mcp:none`, asking for a scope and declining it in the same
574
+ // breath, an error here rather than a token that grants nothing
575
+ if (!mcpLevel(section, level)) {
576
+ const levelNames = section.levels.map(sectionLevel => sectionLevel.value).join('", "');
577
+ console.error(
578
+ level === null
579
+ ? `Scope "${scope}" needs an access level, as "${scope}:<level>"`
580
+ : `Unknown ${scope} access level: ${level}`
581
+ );
582
+ console.error(`Allowed levels: "${levelNames}"`);
583
+ process.exit(1);
584
+ }
585
+ mcpChoice[key] = level;
586
+ }
587
+
588
+ let permissions;
589
+ if (Object.keys(mcpChoice).length) {
590
+ // The admin form hides the level editor as soon as a non-MCP scope is
591
+ // ticked, because one permissions record covers the whole token and a
592
+ // level's pair list would narrow the REST API too. There is no way to
593
+ // type a custom record here, so the combination is refused rather
594
+ // than silently resolved one way or the other.
595
+ if (scopes.length) {
596
+ console.error(`An MCP scope cannot be combined with "${scopes.join('", "')}" on the command line`);
597
+ console.error('Issue separate tokens, or use POST /v1/tokens to set an explicit permissions record');
598
+ process.exit(1);
599
+ }
600
+ ({ scopes, permissions } = mcpGrantsFor(mcpChoice));
532
601
  }
533
602
 
534
603
  let description = (argv.description || argv.d || '').toString();
@@ -541,6 +610,7 @@ function run() {
541
610
  account,
542
611
  description,
543
612
  scopes,
613
+ permissions,
544
614
  nolog: true
545
615
  })
546
616
  .then(token => {
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-09-30T14:46:44.000000",
2
+ "creationTime": "2026-10-02T14:46:13.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -2297,6 +2297,8 @@ class Account {
2297
2297
  await this.call({
2298
2298
  cmd: 'sync',
2299
2299
  account: this.account,
2300
+ // epoch ms, as it is stored with the recovery request
2301
+ since: data.since ? new Date(data.since).getTime() : undefined,
2300
2302
  timeout: this.timeout
2301
2303
  });
2302
2304
  return true;
@@ -2617,9 +2619,19 @@ class Account {
2617
2619
  accountData = await this.loadAccountData(this.account);
2618
2620
  accessToken = accountData.oauth2.accessToken;
2619
2621
  } catch (err) {
2620
- let error = Boom.boomify(err, { statusCode: 403 });
2621
- error.output.payload.code = 'OauthRenewError';
2622
- error.output.payload.authenticationFailed = true;
2622
+ // The same line the authentication-server branch above draws, and for the same reason:
2623
+ // a token endpoint that could not be reached, or that answered 429 or a 5xx, has not
2624
+ // refused the refresh token, so it is the service being unavailable rather than the
2625
+ // credential being rejected. Reporting every renewal failure as 403
2626
+ // authenticationFailed told an API client to re-authorize an account whose credential
2627
+ // is fine, which is what the connection path has avoided since 2.79.
2628
+ const transient = isTransientCredentialError(err);
2629
+
2630
+ let error = Boom.boomify(err, { statusCode: transient ? 503 : 403 });
2631
+ error.output.payload.code = transient ? 'OauthRenewUnavailable' : 'OauthRenewError';
2632
+ if (!transient) {
2633
+ error.output.payload.authenticationFailed = true;
2634
+ }
2623
2635
  if (err.tokenRequest) {
2624
2636
  error.output.payload.tokenRequest = err.tokenRequest;
2625
2637
  }
@@ -2718,11 +2730,15 @@ class Account {
2718
2730
  res
2719
2731
  });
2720
2732
 
2721
- try {
2722
- await this.call({ cmd: 'externalNotify', accounts: [this.account] });
2723
- } catch (err) {
2724
- this.logger.error({ msg: 'Failed to notify about queue changes', account: this.account, err });
2725
- }
2733
+ // Not awaited: the webhook route answers once this returns, and Graph marks an endpoint
2734
+ // slow, and then drops notifications it cannot recover, when more than a few of its
2735
+ // answers take over 3 seconds. The events are already stored, so a worker that is busy or
2736
+ // missing only delays them until its next drain
2737
+ Promise.resolve()
2738
+ .then(() => this.call({ cmd: 'externalNotify', accounts: [this.account] }))
2739
+ .catch(err => {
2740
+ this.logger.error({ msg: 'Failed to notify about queue changes', account: this.account, err });
2741
+ });
2726
2742
  }
2727
2743
 
2728
2744
  async pullQueueEvent() {
@@ -2791,10 +2807,18 @@ class Account {
2791
2807
  * Stores a request to recover missed MS Graph change notifications as a deferred change that
2792
2808
  * is due now, so it survives a worker that is not running, is retried when it fails, and
2793
2809
  * several requests are served by one recovery pass (see OutlookClient.syncMissedMessages())
2810
+ * @param {Object} [opts]
2811
+ * @param {string} [opts.reason='missed'] - What asks for it: 'missed' (the Graph lifecycle
2812
+ * event) or 'manual' (Run sync)
2813
+ * @param {number} [opts.since] - Epoch ms the pass has to look back to, overriding its window
2794
2814
  */
2795
- async queueMissedRecovery() {
2815
+ async queueMissedRecovery({ reason = 'missed', since } = {}) {
2796
2816
  const now = Date.now();
2797
- await this.deferChangeEvent({ type: 'missedRecovery', receivedAt: now }, now);
2817
+ const event = { type: 'missedRecovery', receivedAt: now, reason };
2818
+ if (since) {
2819
+ event.since = since;
2820
+ }
2821
+ await this.deferChangeEvent(event, now);
2798
2822
  }
2799
2823
 
2800
2824
  /**
@@ -2920,6 +2944,7 @@ module.exports = {
2920
2944
  accountSummary,
2921
2945
  authFailureDisabledAt,
2922
2946
  isAuthFailureDisabled,
2947
+ isImapDisabled,
2923
2948
  isOperatorDisabled,
2924
2949
  isAccessTokenInvalidated
2925
2950
  };
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+
3
+ // Which routes an account-bound access token can reach although their path carries no {account}
4
+ // parameter.
5
+ //
6
+ // The api-token strategy checks a bound token's binding against `request.params.account`
7
+ // (workers/api.js), so a route whose path has no such parameter refuses the token with
8
+ // "Unauthorized account" unless it is named here. Three resolutions exist, and the strategy keeps the
9
+ // code for each - this table only says which route gets which:
10
+ //
11
+ // 'query' - the account arrives as a query argument and has to name the token's own account.
12
+ // Omitting it still refuses, so a bound credential cannot enumerate the instance.
13
+ // 'token' - the account is taken from the token rather than from the request, and the handler is
14
+ // held to it through `request.app.enforceAccount`.
15
+ // 'record' - the entity named in the path is checked for membership in the token's account.
16
+ //
17
+ // The MCP tool registry reads the same table to decide which tools are advertised to a bound
18
+ // credential (lib/mcp/tools.js). It used to answer that question from "the route takes an `account`
19
+ // argument", which is a different question: `POST /v1/account`, `POST /v1/authentication/form` and
20
+ // `POST /v1/blocklist/{listId}` all take one in the payload and are refused here, so three tools were
21
+ // offered to a credential whose every call died on the same bare 403, while the template routes that
22
+ // a bound token really can reach were hidden because they name no account at all. One table is what
23
+ // keeps the advertisement and the enforcement from drifting apart again.
24
+ const BOUND_ROUTES = new Map([
25
+ ['get:/v1/templates', 'query'],
26
+ ['get:/v1/tokens', 'query'],
27
+ ['post:/v1/templates/template', 'token'],
28
+ // Matched for every method: the strategy's own case carries no method switch
29
+ ['get:/v1/templates/template/{template}', 'record'],
30
+ ['put:/v1/templates/template/{template}', 'record'],
31
+ ['delete:/v1/templates/template/{template}', 'record']
32
+ ]);
33
+
34
+ /**
35
+ * How a bound token's binding is satisfied on one route, or null when the route has to carry the
36
+ * account in its path.
37
+ *
38
+ * @param {String} method - HTTP method, in any case
39
+ * @param {String} path - the Hapi route path, with its parameter placeholders
40
+ * @returns {String|null} 'query', 'token', 'record', or null
41
+ */
42
+ function boundRouteBinding(method, path) {
43
+ return BOUND_ROUTES.get(`${String(method).toLowerCase()}:${path}`) || null;
44
+ }
45
+
46
+ /**
47
+ * Whether an account-bound token can reach a route at all - either because the path names the
48
+ * account, or because the route is one of the exceptions above.
49
+ *
50
+ * @param {String} method - HTTP method, in any case
51
+ * @param {String} path - the Hapi route path
52
+ * @returns {Boolean}
53
+ */
54
+ function routeAdmitsBoundToken(method, path) {
55
+ return /\{account\}/.test(path) || !!boundRouteBinding(method, path);
56
+ }
57
+
58
+ module.exports = { BOUND_ROUTES, boundRouteBinding, routeAdmitsBoundToken };
@@ -2,7 +2,7 @@
2
2
 
3
3
  const crypto = require('crypto');
4
4
  const { redis } = require('../db');
5
- const { Account, accountExists, authFailureDisabledAt } = require('../account');
5
+ const { Account, accountExists, authFailureDisabledAt, isImapDisabled, isOperatorDisabled } = require('../account');
6
6
  const { formatGmailWatch } = require('../account/account-state');
7
7
  const getSecret = require('../get-secret');
8
8
  const { oauth2Apps, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
@@ -34,7 +34,7 @@ const {
34
34
  apiBoolean
35
35
  } = require('../schemas');
36
36
 
37
- const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE } = require('../consts');
37
+ const { REDIS_PREFIX, MAX_FORM_TTL, NONCE_BYTES, MCP_MAX_PAGE_SIZE, OUTLOOK_SYNC_MAX_LOOKBACK } = require('../consts');
38
38
  const BEHAVIOR = require('./behavior-notes');
39
39
  const { IMPACT } = require('./operation-impact');
40
40
  const { FIELD_USAGE } = require('../field-usage');
@@ -664,7 +664,8 @@ async function init(args) {
664
664
  name: 'sync_account',
665
665
  title: 'Sync account now',
666
666
  description: "Ask the account's worker to run a sync now instead of waiting for the next scheduled one.",
667
- omit: ['sync'],
667
+ // `since` can announce weeks of mail again, an operator decision rather than an agent's
668
+ omit: ['sync', 'since'],
668
669
  force: { sync: true }
669
670
  },
670
671
  openapi: {
@@ -700,7 +701,16 @@ async function init(args) {
700
701
  }),
701
702
 
702
703
  payload: Joi.object({
703
- sync: apiBoolean().default(false).description('Only sync if true')
704
+ sync: apiBoolean().default(false).description('Only sync if true'),
705
+ since: Joi.date()
706
+ .iso()
707
+ .max('now')
708
+ .custom((value, helpers) => (value.getTime() < Date.now() - OUTLOOK_SYNC_MAX_LOOKBACK ? helpers.error('date.lookback') : value))
709
+ .messages({ 'date.lookback': '{{#label}} must be within the last 30 days' })
710
+ .example('2026-10-02T13:00:00.000Z')
711
+ .description(
712
+ 'Outlook (MS Graph) accounts only, ignored for other account types. Look for messages received since this time that were never announced, instead of the usual recovery window of the last few hours. Messages announced before EmailEngine stopped remembering them (about six hours) are announced again with a new messageNew webhook. At most 30 days back.'
713
+ )
704
714
  }).label('RequestSync')
705
715
  },
706
716
 
@@ -1138,11 +1148,19 @@ async function init(args) {
1138
1148
  }
1139
1149
  } else if (accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedAccount) {
1140
1150
  result.type = 'delegated';
1141
- } else if (accountData.imap && !accountData.imap.disabled) {
1151
+ } else if (accountData.imap && !isOperatorDisabled(accountData)) {
1152
+ // A parked account is still an IMAP account, only switched off: imap.disabled is
1153
+ // set by the send-only switch AND by the authentication-failure safety net, so
1154
+ // reading it directly answered "sending", sendOnly true for an account whose mail
1155
+ // a client was about to stop reading. The accounts listing and the admin UI have
1156
+ // asked isOperatorDisabled() since the park shipped - send-only is a
1157
+ // configuration, a park is a fault.
1142
1158
  result.type = 'imap';
1143
1159
  } else {
1144
1160
  result.type = 'sending';
1145
- result.sendOnly = true;
1161
+ // The same answer the listing gives: an account with neither IMAP nor SMTP is a
1162
+ // broken configuration rather than a send-only one
1163
+ result.sendOnly = accountObject.isSendOnlyAccount(accountData);
1146
1164
  }
1147
1165
 
1148
1166
  if ((accountData.imap || (oauth2App && (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap'))) && !result.imapIndexer) {
@@ -1169,8 +1187,25 @@ async function init(args) {
1169
1187
  result.counters = accountData.counters;
1170
1188
  }
1171
1189
 
1172
- if (request.query.quota && !result.sendOnly) {
1173
- result.quota = await accountObject.getQuota();
1190
+ // The quota is the one field of this record that is read off the live connection, and
1191
+ // a connection is not something the stored record can predict: getQuota() loads the
1192
+ // account with requireValid, which refuses every state outside connected, connecting
1193
+ // and syncing, and the IMAP client then checks for a usable socket of its own. So an
1194
+ // account that is merely disconnected, backing off after a connect error, parked or
1195
+ // paused answered 503 for the WHOLE account rather than returning it without a quota,
1196
+ // and so did one carrying no IMAP, SMTP or OAuth2 configuration at all. An optional
1197
+ // field must not be able to fail the response that carries it, which is how the
1198
+ // sibling enrichments above are written too.
1199
+ //
1200
+ // The three skips are kept as a short-circuit: they cost nothing, and they keep a
1201
+ // request that could never answer from making a worker round trip and logging a
1202
+ // warning about it. They are not what makes this safe.
1203
+ if (request.query.quota && !result.sendOnly && result.type !== 'sending' && !isImapDisabled(accountData)) {
1204
+ try {
1205
+ result.quota = await accountObject.getQuota();
1206
+ } catch (err) {
1207
+ request.logger.warn({ msg: 'Failed to read account quota', account: request.params.account, err });
1208
+ }
1174
1209
  }
1175
1210
 
1176
1211
  return result;
@@ -1767,7 +1802,11 @@ async function init(args) {
1767
1802
  name: 'get_account_logs',
1768
1803
  title: 'Get account connection log',
1769
1804
  description:
1770
- 'Read the stored connection log of an account: the raw IMAP or provider API trace, which names folders, message ids and subjects. Use it to find out why an account fails to connect or sync. Only kept while logging is enabled for the account or for the whole instance.'
1805
+ 'Read the stored connection log of an account: the raw IMAP or provider API trace, which names folders, message ids and subjects. Use it to find out why an account fails to connect or sync. Only kept while logging is enabled for the account or for the whole instance. A long log is cut to its most recent entries.',
1806
+ // One JSON entry per line, oldest first, so a log over the result cap has to keep
1807
+ // its END - the first 128KB of a connection log says nothing about why the
1808
+ // account is failing now
1809
+ tail: true
1771
1810
  },
1772
1811
  openapi: {
1773
1812
  'x-ee-behavior': [BEHAVIOR.ACCOUNT_LOG_SCOPE],
@@ -19,6 +19,7 @@
19
19
  // NO_LABEL_SET_ON_GMAIL lib/email-client/gmail-client.js, assertLabelSetSupported throw
20
20
  // GMAIL_DELETE_IS_TRASH lib/email-client/gmail-client.js, deleteMessage
21
21
  // UPLOAD_DRAFTS_ONLY_GRAPH lib/email-client/outlook-client.js, uploadMessage
22
+ // UPLOAD_IGNORES_FLAGS_GMAIL lib/email-client/gmail-client.js, uploadMessage payload
22
23
  // NO_QUOTA_ON_API_ACCOUNTS getQuota on both clients
23
24
  // ACCOUNT_LOG_SCOPE lib/email-client/base-client.js, getLogger; workers/imap.js, getAccountLogger
24
25
 
@@ -49,6 +50,9 @@ module.exports = {
49
50
 
50
51
  UPLOAD_DRAFTS_ONLY_GRAPH: 'For MS Graph accounts only drafts can be uploaded, and the draft flag cannot be changed afterwards.',
51
52
 
53
+ UPLOAD_IGNORES_FLAGS_GMAIL:
54
+ 'For Gmail API accounts the flags and internalDate fields are ignored. The message is inserted with the target label only, and its internal date is taken from the Date header of the message itself.',
55
+
52
56
  NO_LABEL_SET_ON_GMAIL:
53
57
  'For Gmail API accounts the entire label set cannot be replaced in one call. Add and remove labels individually instead of using the set operation.',
54
58
 
@@ -268,7 +268,7 @@ async function init(args) {
268
268
  name: 'create_gateway',
269
269
  title: 'Create SMTP gateway',
270
270
  description:
271
- 'Register an SMTP gateway, a relay server messages can be sent through. Needs an id, a name, the host and the port; a password can be written but never read back.'
271
+ 'Register an SMTP gateway, a relay server messages can be sent through. Needs an id (or null to have one generated), a name, the host and the port; a password can be written but never read back.'
272
272
  },
273
273
  openapi: {
274
274
  responses: apiResponses('Returns the registered gateway.', 400, 401, 403, 429, 500)
@@ -290,7 +290,15 @@ async function init(args) {
290
290
  failAction,
291
291
 
292
292
  payload: Joi.object({
293
- gateway: Joi.string().empty('').trim().max(256).default(null).example('sendgun').description('Gateway ID').label('Gateway ID').required(),
293
+ gateway: Joi.string()
294
+ .empty('')
295
+ .trim()
296
+ .max(256)
297
+ .allow(null)
298
+ .example('sendgun')
299
+ .description('Gateway ID. If set to `null`, a unique ID will be generated automatically')
300
+ .label('Gateway ID')
301
+ .required(),
294
302
 
295
303
  name: Joi.string().empty('').max(256).example('John Smith').description('Account Name').label('Gateway Name').required(),
296
304
 
@@ -306,7 +306,11 @@ async function init(args) {
306
306
  },
307
307
 
308
308
  description: 'Upload message',
309
- notes: ['Upload a message structure, compile it into an EML file and store it into selected mailbox.', BEHAVIOR.UPLOAD_DRAFTS_ONLY_GRAPH],
309
+ notes: [
310
+ 'Upload a message structure, compile it into an EML file and store it into selected mailbox.',
311
+ BEHAVIOR.UPLOAD_DRAFTS_ONLY_GRAPH,
312
+ BEHAVIOR.UPLOAD_IGNORES_FLAGS_GMAIL
313
+ ],
310
314
  tags: ['api', 'Message'],
311
315
 
312
316
  plugins: {
@@ -326,7 +330,7 @@ async function init(args) {
326
330
  keep: ['account', 'path', 'flags', 'reference', 'from', 'to', 'cc', 'bcc', 'subject', 'text', 'html', 'attachments']
327
331
  },
328
332
  openapi: {
329
- 'x-ee-behavior': [BEHAVIOR.UPLOAD_DRAFTS_ONLY_GRAPH],
333
+ 'x-ee-behavior': [BEHAVIOR.UPLOAD_DRAFTS_ONLY_GRAPH, BEHAVIOR.UPLOAD_IGNORES_FLAGS_GMAIL],
330
334
  responses: apiResponses('Returns the uploaded message with the identifiers the provider assigned to it.', 400, 401, 403, 404, 429, 500, 503)
331
335
  }
332
336
  },
@@ -1300,7 +1304,10 @@ async function init(args) {
1300
1304
  .description('Whether the HTML content has been processed into a web-safe version (set when webSafeHtml was requested)'),
1301
1305
  hasMore: Joi.boolean()
1302
1306
  .example(false)
1303
- .description('Is the current text output capped or not. Always false for Gmail API and MS Graph API accounts')
1307
+ .description(
1308
+ 'Whether the returned text was capped by maxBytes. On an IMAP account the cap also decides how much is downloaded; ' +
1309
+ 'on a Gmail API or MS Graph account the provider returns the whole text in one response and the cap decides how much of it is passed on'
1310
+ )
1304
1311
  }).label('TextResponse'),
1305
1312
  failAction: 'log'
1306
1313
  }
@@ -22,7 +22,7 @@ async function init(args) {
22
22
  const listing = await outbox.list(Object.assign({ logger }, request.query));
23
23
 
24
24
  // A queue entry carries the proxy the submission was told to use, and a failed one
25
- // also records the route it took under progress.error.networkRouting
25
+ // also records the route it took under progress.networkRouting
26
26
  for (const entry of listing.messages || []) {
27
27
  maskSecrets(entry);
28
28
  }