emailengine-app 2.78.0 → 2.79.0

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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +70 -35
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. package/lib/feature-flags.js +0 -48
package/.ncurc.js CHANGED
@@ -1,26 +1,36 @@
1
1
  module.exports = {
2
2
  upgrade: true,
3
+ // Node 20 is a hard runtime floor, not a preference. The DigitalOcean one-click images run
4
+ // EmailEngine on Node 20 and ship an upgrade script for EmailEngine but none for Node, so those
5
+ // installs keep self-updating on a runtime that never moves; raising the floor breaks them on
6
+ // their next upgrade. Node 20 being EOL upstream, and CI and the pkg targets being on Node 24,
7
+ // do not lift this. Treat "needs Node >20" as a permanent reject.
8
+ //
3
9
  // Packages capped inside their current major: the next major is ESM-only (this codebase is
4
- // CommonJS and is bundled into a binary with pkg) or it breaks a peer dependency. Using 'minor'
5
- // instead of a blanket reject so these still receive security/patch updates within the safe
6
- // major instead of being frozen at one exact version. Verified against Node 20 (Docker) 2026-06-17.
7
- target: name =>
8
- ['nanoid', 'ical.js', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked', 'bullmq', 'ioredis'].includes(name) ? 'minor' : 'latest',
10
+ // CommonJS and is bundled into a binary with pkg), needs a Node newer than the floor above, or
11
+ // is a major we are deliberately soaking. Using 'minor' instead of a blanket reject so these
12
+ // still receive security/patch updates within the safe major instead of being frozen at one
13
+ // exact version. Verified against Node 20 (Docker) 2026-06-17.
14
+ target: name => (['nanoid', 'ical.js', 'gettext-parser', 'xgettext-template', 'chai', 'undici', 'marked'].includes(name) ? 'minor' : 'latest'),
9
15
  // nanoid - 4.x dropped the CommonJS require export (ESM-only)
10
16
  // ical.js - 2.x is ESM-only
11
17
  // gettext-parser - 8.x is ESM-only
12
18
  // xgettext-template - 6.x is ESM-only (translation build tool)
13
19
  // chai - 5.x is ESM-only (only used by the vendored imap-core tests)
14
- // undici - 8.x requires Node >=22.19 and crashes at require() on Node 20; EmailEngine supports Node 20+
20
+ // undici - 8.x requires Node >=22.19 and crashes at require() on Node 20. Permanent while the
21
+ // Node 20 floor above stands.
15
22
  // marked - 16.x dropped the CommonJS build (ESM-only, needs require(esm)/Node >=20.19); 15.x is the
16
23
  // last require()-compatible line. 15.0.12 verified on Node 20-24 and in a yao/pkg node24 build.
17
- // bullmq - 6.x drops ioredis entirely, and @bull-board/api still peer-requires bullmq ^5.79.2, so the
18
- // install fails outright (ERESOLVE) on the queue browser we mount at /admin/bull-board.
19
- // Lift when bull-board ships bullmq 6 support.
20
- // ioredis - 6.x is held back BY the bullmq cap above, not on its own merits. lib/db.js creates the
21
- // client and hands it to bullmq as `connection` for all four queues, while bullmq 5 pins
22
- // ioredis 5.11.1 as a direct dependency - so bumping ours to 6 would drive bullmq 5's
23
- // internals with a client it was not written against. These two move together.
24
+ // Permanent while the Node 20 floor above stands.
25
+ //
26
+ // bullmq was capped at 5.x until 2026-08-17, when both stated reasons had expired. Now on 6.x, which
27
+ // moves cron-parser off the deprecated 4.9.0 onto 5.x - but not off luxon, which cron-parser depends
28
+ // on in both majors.
29
+ //
30
+ // ioredis was capped at 5.x for the same span, held there BY the bullmq cap (bullmq 5 carried ioredis
31
+ // as a direct dependency; 6.x demoted it to an optional peer, which dissolved the coupling). Now on
32
+ // 6.x, whose one breaking change is that it speaks RESP3 by default - taken as-is, since RESP3 was
33
+ // verified against everything here that could plausibly differ (see the commit that made the move).
24
34
  //
25
35
  // joi used to be capped here because hapi-swagger peer-required 17.x. That dependency is gone
26
36
  // (the OpenAPI document is generated by lib/openapi/ now), so joi may move majors again. A major
@@ -1,3 +1,3 @@
1
1
  {
2
- ".": "2.78.0"
2
+ ".": "2.79.0"
3
3
  }
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.79.0](https://github.com/postalsys/emailengine/compare/v2.78.0...v2.79.0) (2026-08-18)
4
+
5
+
6
+ ### Features
7
+
8
+ * **lists:** add suppression list management to the admin UI ([d684030](https://github.com/postalsys/emailengine/commit/d6840305a3dc0940f248c12e650e068aed866e28))
9
+ * **lists:** link suppression entries to the subscription management page ([b4e1d49](https://github.com/postalsys/emailengine/commit/b4e1d49ff105d95f24462b8ceb0f80b453378cc9))
10
+ * **oauth2:** migrate legacy settings-based OAuth2 apps into the app registry ([4aeb7f5](https://github.com/postalsys/emailengine/commit/4aeb7f5bee45d0ec32ab17d72252bf8d13b57018))
11
+ * **reference:** confirm irreversible Try it requests before running them ([546c32e](https://github.com/postalsys/emailengine/commit/546c32e352a70061ae188c59f54b78933d2bde20))
12
+ * **reference:** edit Try it request bodies in a JSON editor ([dbd38e8](https://github.com/postalsys/emailengine/commit/dbd38e857f16a1ce28c86a32a9105b0e5cb36ca6))
13
+ * **reference:** make large schemas readable in the API reference ([9874821](https://github.com/postalsys/emailengine/commit/9874821288f543d531af757366eced663b738705))
14
+ * **reference:** show an example value and usage guidance for every field ([c974f19](https://github.com/postalsys/emailengine/commit/c974f19e393c6d7519c3599b772a58a898f7c4ce))
15
+ * **reference:** warn in Try it only where running the request has a consequence ([4f53d02](https://github.com/postalsys/emailengine/commit/4f53d02d068f88707419aaffecee6618b2f0bd71))
16
+ * **sentry:** enable error reporting by default for trial licenses ([9c918bc](https://github.com/postalsys/emailengine/commit/9c918bcb9cbb45113c1006db649a6fbf871c6c81))
17
+ * **tokens:** granular access token permissions ([#633](https://github.com/postalsys/emailengine/issues/633)) ([f30bf0a](https://github.com/postalsys/emailengine/commit/f30bf0a838958f64a057afe8f44767a0b3de306a))
18
+ * **webhooks:** show the effective webhook routing on the account page ([0cdbbff](https://github.com/postalsys/emailengine/commit/0cdbbffacfc19ed7af2ef200061edd7e06930b26))
19
+
20
+
21
+ ### Bug Fixes
22
+
23
+ * **deps:** move to ioredis 6 ([da4904a](https://github.com/postalsys/emailengine/commit/da4904aba141f7fffeef2200a726254994ae3f9b))
24
+ * **deps:** override deepmerge-ts to clear GHSA-ggr8-5vv4-36mx ([#635](https://github.com/postalsys/emailengine/issues/635)) ([6d68432](https://github.com/postalsys/emailengine/commit/6d6843217ee5246e150e66307e2c2bae94fbc89b))
25
+ * **deps:** refresh dependencies and dedupe node-html-parser ([5502c04](https://github.com/postalsys/emailengine/commit/5502c0467da52eb2d285c1a057818d6c0eb7694e))
26
+ * **logging:** standardize log levels and keep credentials out of error logs ([a229bdc](https://github.com/postalsys/emailengine/commit/a229bdca3b8662338db889568fa132503c5e89c9))
27
+ * **queues:** move to BullMQ 6 and fix outbox paging ([eba0761](https://github.com/postalsys/emailengine/commit/eba0761f162c2561bab81460b481743e42ab4608))
28
+ * **reference:** count the minted token's expiry down while the page is open ([356dfd0](https://github.com/postalsys/emailengine/commit/356dfd0ac9178bcd2ad007f351c2ded3af0936ce))
29
+ * **ui:** share the confirm dialog helper and stop the reference page scrolling sideways ([994ddec](https://github.com/postalsys/emailengine/commit/994ddec7d42c91c1a7ea5167cfe5ee6df689b4d2))
30
+ * **ui:** stop partial blocks from losing content wrapped in a bare condition ([0887172](https://github.com/postalsys/emailengine/commit/0887172c4fe18d23c8a3bd9f9d26249fc7551a9a))
31
+
3
32
  ## [2.78.0](https://github.com/postalsys/emailengine/compare/v2.77.0...v2.78.0) (2026-08-12)
4
33
 
5
34
 
package/config/e2e.toml CHANGED
@@ -12,7 +12,8 @@
12
12
  settings = '''
13
13
  {
14
14
  "serviceUrl": "https://e2e.emailengine.app/",
15
- "ignoreMailCertErrors": true
15
+ "ignoreMailCertErrors": true,
16
+ "sentryEnabled": false
16
17
  }
17
18
  '''
18
19
 
package/config/test.toml CHANGED
@@ -14,7 +14,8 @@ settings = '''
14
14
  ],
15
15
  "serviceUrl": "http://127.0.0.1:7077",
16
16
  "ignoreMailCertErrors": true,
17
- "serviceSecret": "a cat"
17
+ "serviceSecret": "a cat",
18
+ "sentryEnabled": false
18
19
  }
19
20
  '''
20
21
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "creationTime": "2026-08-11T14:47:00.000000",
2
+ "creationTime": "2026-08-14T14:46:51.000000",
3
3
  "prefixes": [
4
4
  {
5
5
  "ipv6Prefix": "2001:4860:4801:2008::/64"
package/lib/account.js CHANGED
@@ -20,7 +20,7 @@ const { MessageChannel } = require('worker_threads');
20
20
  const { MessagePortReadable } = require('./message-port-stream');
21
21
  const { deepStrictEqual, strictEqual } = require('assert');
22
22
  const { encrypt, decrypt } = require('./encrypt');
23
- const { oauth2Apps, LEGACY_KEYS, isApiBasedApp } = require('./oauth2-apps');
23
+ const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
24
24
  const settings = require('./settings');
25
25
  const { buildRetentionPolicy } = require('./queue-retention');
26
26
  const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
@@ -301,6 +301,20 @@ class Account {
301
301
  return `${REDIS_PREFIX}iap:${this.account}`;
302
302
  }
303
303
 
304
+ // Shared log entry for unserializeAccountData() failures. The raw value is withheld on
305
+ // purpose: imap/smtp/oauth2 payloads may carry cleartext credentials when no EENGINE_SECRET is
306
+ // set, so only its length is logged. `ownerAccount` is the row's own marker when available -
307
+ // listAccounts() unserializes other accounts' rows on an instance whose own account id is false.
308
+ logUnserializeFailure(msg, key, rawValue, ownerAccount, err) {
309
+ this.logger.error({
310
+ msg,
311
+ key,
312
+ valueLength: (rawValue || '').toString().length,
313
+ account: ownerAccount || this.account || undefined,
314
+ err
315
+ });
316
+ }
317
+
304
318
  unserializeAccountData(accountData) {
305
319
  const result = {};
306
320
 
@@ -371,7 +385,7 @@ class Account {
371
385
  }
372
386
  result[key] = value;
373
387
  } catch (err) {
374
- this.logger.error({ msg: 'Failed to parse input from Redis', key, value: accountData[key], err });
388
+ this.logUnserializeFailure('Failed to parse input from Redis', key, accountData[key], accountData.account, err);
375
389
  }
376
390
  } else {
377
391
  // regular string
@@ -391,7 +405,7 @@ class Account {
391
405
  }
392
406
  result[key] = value;
393
407
  } catch (err) {
394
- this.logger.error({ msg: 'Failed to parse input from Redis', key, value: accountData[key], err });
408
+ this.logUnserializeFailure('Failed to parse input from Redis', key, accountData[key], accountData.account, err);
395
409
  }
396
410
  break;
397
411
 
@@ -412,7 +426,7 @@ class Account {
412
426
 
413
427
  result[key] = value;
414
428
  } catch (err) {
415
- this.logger.error({ msg: 'Failed to parse input from Redis', key, value: accountData[key], err });
429
+ this.logUnserializeFailure('Failed to parse input from Redis', key, accountData[key], accountData.account, err);
416
430
  }
417
431
  break;
418
432
 
@@ -446,7 +460,7 @@ class Account {
446
460
  }
447
461
  }
448
462
  } catch (err) {
449
- this.logger.error({ msg: 'Failed to parse input from Redis', key, value: accountData[key], err });
463
+ this.logUnserializeFailure('Failed to parse input from Redis', key, accountData[key], accountData.account, err);
450
464
  }
451
465
  break;
452
466
 
@@ -473,14 +487,14 @@ class Account {
473
487
  result[type].auth[key] = decrypt(result[type].auth[key], this.secret);
474
488
  } catch (err) {
475
489
  // ignore??
476
- this.logger.error({ msg: 'Failed to decrypt value', encrypted: result[type].auth[key], err });
490
+ this.logUnserializeFailure('Failed to decrypt value', key, result[type].auth[key], result.account, err);
477
491
  }
478
492
  } else if (key in result[type]) {
479
493
  try {
480
494
  result[type][key] = decrypt(result[type][key], this.secret);
481
495
  } catch (err) {
482
496
  // ignore??
483
- this.logger.error({ msg: 'Failed to decrypt value', encrypted: result[type][key], err });
497
+ this.logUnserializeFailure('Failed to decrypt value', key, result[type][key], result.account, err);
484
498
  }
485
499
  }
486
500
  }
@@ -550,7 +564,7 @@ class Account {
550
564
  try {
551
565
  result[key] = JSON.stringify(accountData[key]);
552
566
  } catch (err) {
553
- this.logger.error({ msg: 'Failed to stringify input for Redis', key, err });
567
+ this.logger.error({ msg: 'Failed to stringify input for Redis', key, account: this.account, err });
554
568
  }
555
569
  }
556
570
  break;
@@ -565,7 +579,7 @@ class Account {
565
579
 
566
580
  result[key] = value;
567
581
  } catch (err) {
568
- this.logger.error({ msg: 'Failed to stringify input for Redis', key, err });
582
+ this.logger.error({ msg: 'Failed to stringify input for Redis', key, account: this.account, err });
569
583
  }
570
584
 
571
585
  break;
@@ -593,7 +607,7 @@ class Account {
593
607
 
594
608
  result[key] = value;
595
609
  } catch (err) {
596
- this.logger.error({ msg: 'Failed to stringify input for Redis', key, err });
610
+ this.logger.error({ msg: 'Failed to stringify input for Redis', key, account: this.account, err });
597
611
  }
598
612
 
599
613
  break;
@@ -612,13 +626,13 @@ class Account {
612
626
  try {
613
627
  connectData.auth[key] = encrypt(connectData.auth[key], this.secret);
614
628
  } catch (err) {
615
- this.logger.error({ msg: 'Failed to encrypt value', err });
629
+ this.logger.error({ msg: 'Failed to encrypt value', key, account: this.account, err });
616
630
  }
617
631
  } else if (key in connectData) {
618
632
  try {
619
633
  connectData[key] = encrypt(connectData[key], this.secret);
620
634
  } catch (err) {
621
- this.logger.error({ msg: 'Failed to encrypt value', err });
635
+ this.logger.error({ msg: 'Failed to encrypt value', key, account: this.account, err });
622
636
  }
623
637
  }
624
638
  }
@@ -636,7 +650,7 @@ class Account {
636
650
 
637
651
  result[key] = JSON.stringify(connectData);
638
652
  } catch (err) {
639
- this.logger.error({ msg: 'Failed to stringify input for Redis', key, err });
653
+ this.logger.error({ msg: 'Failed to stringify input for Redis', key, account: this.account, err });
640
654
  }
641
655
  break;
642
656
 
@@ -799,7 +813,7 @@ class Account {
799
813
  await lock.releaseLock(updateLock);
800
814
  } catch (err) {
801
815
  // The lock expires on its own, so a failed release must not mask the result
802
- this.logger.error({ msg: 'Failed to release account update lock', account: accountData.account, lockKey, err });
816
+ this.logger.warn({ msg: 'Failed to release account update lock', account: accountData.account, lockKey, err });
803
817
  }
804
818
  }
805
819
  }
@@ -870,7 +884,7 @@ class Account {
870
884
  pipeline = pipeline.hmset(this.getAccountKey(), updatedFields);
871
885
  }
872
886
 
873
- if (addProvider && !LEGACY_KEYS.includes(addProvider)) {
887
+ if (addProvider) {
874
888
  pipeline = pipeline.sadd(`${REDIS_PREFIX}oapp:a:${addProvider}`, this.account);
875
889
  if (accountData._oldOAuth2User && accountData._oldOAuth2User.toLowerCase() !== accountData.oauth2.auth?.user?.toLowerCase()) {
876
890
  pipeline = pipeline.hdel(`${REDIS_PREFIX}oapp:h:${addProvider}`, accountData._oldOAuth2User.toLowerCase());
@@ -1303,7 +1317,7 @@ class Account {
1303
1317
  }
1304
1318
  });
1305
1319
  } catch (err) {
1306
- this.logger.error({ msg: 'Failed to add entry to documents queue', err });
1320
+ this.logger.error({ msg: 'Failed to add entry to documents queue', account: this.account, err });
1307
1321
  }
1308
1322
  }
1309
1323
 
@@ -1478,7 +1492,7 @@ class Account {
1478
1492
  // its own state against this endpoint reads as a deletion.
1479
1493
  let decoded = decodeStoredMailboxEntry(storedListing[path]);
1480
1494
  if (!decoded) {
1481
- this.logger.error({ msg: 'Skipping corrupt stored mailbox listing entry', path, account: this.account });
1495
+ this.logger.warn({ msg: 'Skipping corrupt stored mailbox listing entry', path, account: this.account });
1482
1496
  continue;
1483
1497
  }
1484
1498
 
@@ -1899,7 +1913,7 @@ class Account {
1899
1913
  messageData.flags.push('\\Seen');
1900
1914
  // do not wait until the update is completed, return immediately
1901
1915
  this.updateMessage(message, { flags: { add: ['\\Seen'] } }).catch(err => {
1902
- this.logger.error({ msg: 'Failed to mark message as Seen', message, err });
1916
+ this.logger.error({ msg: 'Failed to mark message as Seen', account: this.account, message, err });
1903
1917
  });
1904
1918
  }
1905
1919
 
@@ -2379,7 +2393,14 @@ class Account {
2379
2393
 
2380
2394
  this.logger.trace({
2381
2395
  msg: 'Executed ES query',
2382
- query: { type: 'search', index, size: pageSize, from: pageSize * page, query: searchQuery, sort: { uid: 'desc' } },
2396
+ query: {
2397
+ type: 'search',
2398
+ index,
2399
+ size: pageSize,
2400
+ from: pageSize * page,
2401
+ query: searchQuery,
2402
+ sort: { [!searchOpts.unified ? 'uid' : 'date']: 'desc' }
2403
+ },
2383
2404
  results: searchResult.hits.total.value
2384
2405
  });
2385
2406
 
@@ -2545,17 +2566,19 @@ class Account {
2545
2566
  try {
2546
2567
  flushLock = await lock.acquireLock(lockKey, 30 * 60 * 1000);
2547
2568
  if (!flushLock.success) {
2548
- this.logger.error({ msg: 'Failed to get lock', lockKey });
2569
+ // contention: another flush already holds the lock
2570
+ this.logger.warn({ msg: 'Failed to get flush lock, another flush is already running', account: this.account, lockKey });
2549
2571
 
2550
2572
  let error = Boom.boomify(new Error('One flush operation at a time allowed, try again later'), { statusCode: 429 });
2551
2573
  error.output.payload.code = 'LockFail';
2552
2574
  throw error;
2553
2575
  }
2554
2576
  } catch (err) {
2555
- this.logger.error({ msg: 'Failed to get lock', lockKey, err });
2556
2577
  if (Boom.isBoom(err)) {
2578
+ // contention was already logged above
2557
2579
  throw err;
2558
2580
  }
2581
+ this.logger.error({ msg: 'Failed to get flush lock', account: this.account, lockKey, err });
2559
2582
  let error = Boom.boomify(new Error('Failed to get flush lock, try again later'), { statusCode: 500 });
2560
2583
  if (err.code) {
2561
2584
  error.output.payload.code = err.code || 'LockFail';
@@ -2634,7 +2657,7 @@ class Account {
2634
2657
  });
2635
2658
  deletedCount += deleteResult[indexName].deleted || 0;
2636
2659
  } catch (err) {
2637
- logger.error({
2660
+ this.logger.error({
2638
2661
  msg: 'Failed to delete account emails from index',
2639
2662
  action: 'flush',
2640
2663
  code: 'document_delete_account_error',
@@ -2648,10 +2671,11 @@ class Account {
2648
2671
  }
2649
2672
  }
2650
2673
 
2651
- logger.trace({
2674
+ this.logger.trace({
2652
2675
  msg: 'Deleted account emails from index',
2653
2676
  action: 'flush',
2654
2677
  code: 'document_delete_account',
2678
+ account: this.account,
2655
2679
  deletedCount,
2656
2680
  deleteResult
2657
2681
  });
@@ -2693,11 +2717,15 @@ class Account {
2693
2717
  try {
2694
2718
  renewLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
2695
2719
  if (!renewLock.success) {
2696
- this.logger.error({ msg: 'Failed to get lock', lockKey });
2720
+ // contention: timed out waiting for the current lock holder
2721
+ this.logger.warn({ msg: 'Failed to get renewal lock, timed out waiting for the current holder', account: this.account, lockKey });
2697
2722
  throw new Error('Failed to get renewal lock');
2698
2723
  }
2699
2724
  } catch (err) {
2700
- this.logger.error({ msg: 'Failed to get lock', lockKey, err });
2725
+ if (!renewLock) {
2726
+ // unexpected lock-layer error; contention was already logged above
2727
+ this.logger.error({ msg: 'Failed to get renewal lock', account: this.account, lockKey, err });
2728
+ }
2701
2729
  let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
2702
2730
  if (err.code) {
2703
2731
  error.output.payload.code = err.code || 'LockFail';
@@ -2718,7 +2746,7 @@ class Account {
2718
2746
  this.logger.info({
2719
2747
  msg: 'OAuth2 access token renewed while locked',
2720
2748
  action: 'ensureAccessToken',
2721
- error: null,
2749
+ account: this.account,
2722
2750
  user: accountData.oauth2.auth.user,
2723
2751
  expires: accountData.oauth2.expires,
2724
2752
  scopes: accountData.oauth2.scope,
@@ -2766,7 +2794,7 @@ class Account {
2766
2794
  this.logger.info({
2767
2795
  msg: 'Renewed OAuth2 access token',
2768
2796
  action: 'ensureAccessToken',
2769
- error: null,
2797
+ account: this.account,
2770
2798
  user: accountData.oauth2.auth.user,
2771
2799
  expires: updates.expires,
2772
2800
  scopes: updates.scope,
@@ -2777,12 +2805,11 @@ class Account {
2777
2805
 
2778
2806
  return accountData;
2779
2807
  } catch (err) {
2780
- this.logger.info({
2808
+ this.logger.warn({
2781
2809
  msg: 'Failed to renew OAuth2 access token',
2782
2810
  action: 'ensureAccessToken',
2783
- error: err,
2784
- response: err.tokenRequest && err.tokenRequest.response,
2785
- flag: err.tokenRequest && err.tokenRequest.flag
2811
+ account: this.account,
2812
+ err
2786
2813
  });
2787
2814
 
2788
2815
  if (err.tokenRequest?.userFlag) {
@@ -2802,7 +2829,7 @@ class Account {
2802
2829
  if (accountData.oauth2) {
2803
2830
  accountData.oauth2.expires = new Date(Date.now() - 24 * 3600 * 1000).toISOString();
2804
2831
  await this.update({ account: accountData.account, oauth2: accountData.oauth2 });
2805
- this.logger.info({ msg: 'Invalidated the OAuth2 access token', expires: accountData.oauth2.expires });
2832
+ this.logger.info({ msg: 'Invalidated the OAuth2 access token', account: this.account, expires: accountData.oauth2.expires });
2806
2833
  }
2807
2834
  return accountData;
2808
2835
  }
@@ -2935,17 +2962,18 @@ class Account {
2935
2962
  this.logger.debug({
2936
2963
  msg: 'MS Graph subscription event',
2937
2964
  type: 'event',
2965
+ account: this.account,
2938
2966
  event,
2939
2967
  res
2940
2968
  });
2941
2969
  } catch (err) {
2942
- this.logger.error({ msg: 'Failed to insert event to account queue', event, err });
2970
+ this.logger.error({ msg: 'Failed to insert event to account queue', account: this.account, event, err });
2943
2971
  }
2944
2972
 
2945
2973
  try {
2946
2974
  await this.call({ cmd: 'externalNotify', accounts: [this.account] });
2947
2975
  } catch (err) {
2948
- logger.error({ msg: 'Failed to notify about queue changes', err });
2976
+ this.logger.error({ msg: 'Failed to notify about queue changes', account: this.account, err });
2949
2977
  }
2950
2978
  }
2951
2979
 
@@ -2966,4 +2994,11 @@ class Account {
2966
2994
  }
2967
2995
  }
2968
2996
 
2969
- module.exports = { Account };
2997
+ // Cheap existence probe that does not load or decrypt account data. The `account` field is
2998
+ // the mandatory marker field of the account hash (the same idiom the notify worker and
2999
+ // genId() rely on), so its presence is the canonical "this account exists" signal.
3000
+ async function accountExists(redis, account) {
3001
+ return (await redis.hexists(`${REDIS_PREFIX}iad:${account}`, 'account')) === 1;
3002
+ }
3003
+
3004
+ module.exports = { Account, accountExists };
@@ -108,6 +108,42 @@ function rangeChip(min, max, unit) {
108
108
  return null;
109
109
  }
110
110
 
111
+ // Length limits at or above this read better as a size than as a character count. `max
112
+ // 5242880 chars` is a number nobody holds; `max 5 MB` is the same fact in a form a reader
113
+ // can act on. Below it the exact count is the more useful answer - a 1024 character limit
114
+ // on a preview line is about the text, not about bytes.
115
+ const SIZE_CHIP_MIN = 8192;
116
+
117
+ // Size label for a character limit, or null when the limit is not a round size. Only exact
118
+ // multiples of 1024 convert: rounding 2560 to "2.5 KB" or, worse, "3 KB" would state a
119
+ // limit the API does not have, and the exact number is the honest answer there.
120
+ function sizeLabel(value) {
121
+ if (typeof value !== 'number' || value < SIZE_CHIP_MIN || value % 1024) {
122
+ return null;
123
+ }
124
+
125
+ const mb = value / (1024 * 1024);
126
+ if (Number.isInteger(mb)) {
127
+ return `${mb} MB`;
128
+ }
129
+
130
+ return `${value / 1024} KB`;
131
+ }
132
+
133
+ // The string-length chip. A limit large enough to be a size is rendered as one, but only
134
+ // when there is no minimum to state alongside it - "1 to 5 MB" would be mixing a character
135
+ // count with a byte size in one phrase. No schema in the current document has both.
136
+ function lengthChip(min, max) {
137
+ if (typeof min !== 'number') {
138
+ const size = sizeLabel(max);
139
+ if (size) {
140
+ return `max ${size}`;
141
+ }
142
+ }
143
+
144
+ return rangeChip(min, max, 'chars');
145
+ }
146
+
111
147
  // Short constraint chips shown next to a property. Covers both the standard OpenAPI
112
148
  // keywords and the `x-*` extensions the generator emits for joi rules OpenAPI has no
113
149
  // keyword for (accepted URI schemes, email format, value coercion) - real validation
@@ -125,7 +161,7 @@ function constraintList(schema) {
125
161
 
126
162
  for (const chip of [
127
163
  rangeChip(schema.minimum, schema.maximum, ''),
128
- rangeChip(schema.minLength, schema.maxLength, 'chars'),
164
+ lengthChip(schema.minLength, schema.maxLength),
129
165
  rangeChip(schema.minItems, schema.maxItems, 'items')
130
166
  ]) {
131
167
  if (chip) {
@@ -149,11 +185,13 @@ function constraintList(schema) {
149
185
  }
150
186
  }
151
187
 
188
+ // `trimmed` is deliberately not a chip. joi trims 162 strings in the document, so it was
189
+ // the most common chip on the page and it never changed what anyone sent: leading
190
+ // whitespace on an account id is not a thing callers do on purpose, and being told it
191
+ // would be removed answered a question nobody had. Case coercion stays, because that one
192
+ // does change the value you get back.
152
193
  const xConvert = schema['x-convert'];
153
194
  if (xConvert && typeof xConvert === 'object') {
154
- if (xConvert.trim) {
155
- chips.push('trimmed');
156
- }
157
195
  if (xConvert.case === 'lower') {
158
196
  chips.push('lowercased');
159
197
  }
@@ -169,6 +207,54 @@ function constraintList(schema) {
169
207
  return chips;
170
208
  }
171
209
 
210
+ // How much of an example value a property row shows before it is cut.
211
+ //
212
+ // The value rides the end of the description rather than taking a line of its own, which
213
+ // only works while it is short enough to share one. The prose column is 34rem, about 86
214
+ // characters; the median example in the document is 15 characters and the 90th percentile
215
+ // is 33, so this cap trips on 67 rows out of 1,056 - base64 blobs, embedded JSON and long
216
+ // URLs, where the opening characters already show the shape. The full value stays reachable
217
+ // through the title attribute, and through data-example for the try-it autocompleter.
218
+ const EXAMPLE_MAX_CHARS = 40;
219
+
220
+ // One example value, formatted for a property row, or null when the value would say nothing.
221
+ //
222
+ // Everything is rendered as JSON, including strings, so the row shows what you would paste
223
+ // rather than prose that happens to sit where prose already is. A cut string is closed off
224
+ // again rather than sliced mid-literal, so the row never shows a dangling quote.
225
+ //
226
+ // A cut value comes back with two more fields, because the two things that want the whole
227
+ // value want it in different forms. `title` is the native tooltip and is the raw value, with
228
+ // no quotes around it. `full` is the JSON form, which is what the try-it autocompleter
229
+ // inserts - handing it `title` instead produced `"raw": TUlNRS1WZXJ...`, an unquoted string
230
+ // in a JSON body. Both are null when nothing was cut, and the row emits neither.
231
+ function formatExample(value) {
232
+ if (typeof value === 'string') {
233
+ // A multi-line example (an HTML body, a PEM key) would break the row it rides on
234
+ const flat = value.replace(/\s+/g, ' ').trim();
235
+ if (!flat) {
236
+ return null;
237
+ }
238
+
239
+ if (flat.length <= EXAMPLE_MAX_CHARS) {
240
+ return { text: JSON.stringify(flat), title: null, full: null };
241
+ }
242
+
243
+ return { text: JSON.stringify(`${flat.slice(0, EXAMPLE_MAX_CHARS)}...`), title: value, full: JSON.stringify(flat) };
244
+ }
245
+
246
+ // Everything else is a number or a flat array of scalars - rowExample() has already
247
+ // rejected the values JSON.stringify has trouble with - so this cuts the rendered form
248
+ // rather than the value, which is why it does not close anything back off.
249
+ const text = JSON.stringify(value);
250
+
251
+ if (text.length <= EXAMPLE_MAX_CHARS) {
252
+ return { text, title: null, full: null };
253
+ }
254
+
255
+ return { text: `${text.slice(0, EXAMPLE_MAX_CHARS)}...`, title: text, full: text };
256
+ }
257
+
172
258
  // JSON rendered for the example panels. Kept here so the pretty-printing is identical
173
259
  // everywhere (page body, code samples, try-it request editor).
174
260
  function stringifyExample(value) {
@@ -189,5 +275,6 @@ module.exports = {
189
275
  operationUrl,
190
276
  methodVariant,
191
277
  constraintList,
278
+ formatExample,
192
279
  stringifyExample
193
280
  };