emailengine-app 2.77.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 (189) hide show
  1. package/.github/workflows/test.yml +80 -0
  2. package/.ncurc.js +23 -13
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +60 -0
  5. package/bin/emailengine.js +1 -1
  6. package/config/e2e.toml +2 -1
  7. package/config/test.toml +2 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +1 -1
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +145 -61
  12. package/lib/api-reference/format.js +105 -4
  13. package/lib/api-reference/index.js +24 -7
  14. package/lib/api-reference/model.js +148 -21
  15. package/lib/api-reference/schema-tree.js +282 -28
  16. package/lib/api-routes/account-routes.js +99 -36
  17. package/lib/api-routes/behavior-notes.js +3 -0
  18. package/lib/api-routes/blocklist-routes.js +21 -47
  19. package/lib/api-routes/chat-routes.js +10 -12
  20. package/lib/api-routes/delivery-test-routes.js +6 -26
  21. package/lib/api-routes/export-routes.js +2 -0
  22. package/lib/api-routes/gateway-routes.js +52 -11
  23. package/lib/api-routes/license-routes.js +2 -0
  24. package/lib/api-routes/mailbox-routes.js +29 -26
  25. package/lib/api-routes/message-routes.js +27 -21
  26. package/lib/api-routes/oauth2-app-routes.js +11 -29
  27. package/lib/api-routes/operation-impact.js +80 -0
  28. package/lib/api-routes/outbox-routes.js +15 -5
  29. package/lib/api-routes/permission-map.js +397 -0
  30. package/lib/api-routes/route-helpers.js +223 -9
  31. package/lib/api-routes/route-metadata.js +28 -0
  32. package/lib/api-routes/settings-routes.js +30 -25
  33. package/lib/api-routes/stats-routes.js +2 -2
  34. package/lib/api-routes/submit-routes.js +53 -31
  35. package/lib/api-routes/template-routes.js +3 -0
  36. package/lib/api-routes/token-routes.js +319 -33
  37. package/lib/api-routes/webhook-route-routes.js +14 -4
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/auth-token.js +80 -8
  41. package/lib/autodetect-imap-settings.js +40 -16
  42. package/lib/base32.js +30 -0
  43. package/lib/bounce-detect.js +182 -62
  44. package/lib/consts.js +10 -0
  45. package/lib/db.js +20 -2
  46. package/lib/delivery-error.js +30 -1
  47. package/lib/egress-filter.js +89 -8
  48. package/lib/email-client/base-client.js +35 -113
  49. package/lib/email-client/gmail-client.js +22 -13
  50. package/lib/email-client/imap/listing-diff.js +3 -3
  51. package/lib/email-client/imap/mailbox.js +28 -93
  52. package/lib/email-client/imap/subconnection.js +10 -7
  53. package/lib/email-client/imap/sync-operations.js +46 -46
  54. package/lib/email-client/imap-client.js +39 -28
  55. package/lib/email-client/message-builder.js +15 -15
  56. package/lib/email-client/notification-handler.js +1 -1
  57. package/lib/email-client/outlook/graph-api.js +10 -4
  58. package/lib/email-client/outlook-client.js +54 -55
  59. package/lib/email-client/smtp-pool-manager.js +1 -1
  60. package/lib/enum-descriptions.js +92 -2
  61. package/lib/export.js +2 -2
  62. package/lib/field-usage.js +133 -0
  63. package/lib/gateway.js +2 -2
  64. package/lib/get-raw-email.js +1 -1
  65. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  66. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  67. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  68. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  69. package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
  70. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  71. package/lib/imapproxy/imap-server.js +40 -10
  72. package/lib/license-beacon.js +5 -10
  73. package/lib/lists.js +49 -1
  74. package/lib/llm-pre-process.js +6 -6
  75. package/lib/logger.js +5 -1
  76. package/lib/metrics-collector.js +2 -2
  77. package/lib/msgpack.js +62 -0
  78. package/lib/oauth/decode-jwt-payload.js +39 -0
  79. package/lib/oauth/gmail.js +9 -12
  80. package/lib/oauth/mail-ru.js +5 -7
  81. package/lib/oauth/outlook-identity.js +61 -0
  82. package/lib/oauth/outlook.js +9 -9
  83. package/lib/oauth/pubsub/google.js +25 -10
  84. package/lib/oauth/retry-setup.js +38 -0
  85. package/lib/oauth/scope-checker.js +1 -1
  86. package/lib/oauth2-apps.js +224 -295
  87. package/lib/openapi/build-document.js +15 -7
  88. package/lib/openapi/joi-schema.js +20 -0
  89. package/lib/outbox.js +145 -14
  90. package/lib/pre-process.js +9 -9
  91. package/lib/queue-stats.js +49 -0
  92. package/lib/read-env-value.js +37 -0
  93. package/lib/reconnection-manager.js +2 -2
  94. package/lib/rewrite-text-nodes.js +4 -3
  95. package/lib/routes-ui.js +4 -0
  96. package/lib/schemas.js +223 -155
  97. package/lib/settings.js +84 -5
  98. package/lib/sub-script.js +2 -1
  99. package/lib/swagger-options.js +2 -1
  100. package/lib/templates.js +5 -5
  101. package/lib/threads.js +2 -2
  102. package/lib/token-audit-log.js +208 -0
  103. package/lib/token-permission-view.js +219 -0
  104. package/lib/token-permissions.js +172 -0
  105. package/lib/tokens.js +100 -16
  106. package/lib/tools.js +259 -85
  107. package/lib/totp.js +67 -0
  108. package/lib/ui-routes/account-routes.js +122 -26
  109. package/lib/ui-routes/admin-config-routes.js +20 -17
  110. package/lib/ui-routes/admin-entities-routes.js +66 -22
  111. package/lib/ui-routes/auth-routes.js +36 -48
  112. package/lib/ui-routes/export-routes.js +10 -4
  113. package/lib/ui-routes/oauth-config-routes.js +5 -5
  114. package/lib/ui-routes/reference-routes.js +11 -8
  115. package/lib/ui-routes/route-helpers.js +79 -2
  116. package/lib/ui-routes/settings-page.js +1 -1
  117. package/lib/ui-routes/smtp-test-routes.js +1 -1
  118. package/lib/ui-routes/suppression-list-routes.js +294 -0
  119. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  120. package/lib/utils/is-email.js +34 -0
  121. package/lib/utils/network.js +2 -2
  122. package/lib/utils/to-camel-case.js +17 -0
  123. package/lib/web-safe-html.js +1 -1
  124. package/lib/webhook-egress.js +37 -0
  125. package/lib/webhook-routing.js +80 -0
  126. package/lib/webhooks.js +21 -15
  127. package/package.json +26 -27
  128. package/sbom.json +1 -0
  129. package/server.js +81 -42
  130. package/static/css/flyonui.css +1 -1
  131. package/static/css/public.css +3 -0
  132. package/static/css/src/app.tailwind.css +159 -9
  133. package/static/js/app.js +69 -0
  134. package/static/js/reference.js +741 -10
  135. package/static/js/ui.js +43 -0
  136. package/static/licenses.html +698 -1590
  137. package/translations/README.md +64 -0
  138. package/translations/de.mo +0 -0
  139. package/translations/de.po +164 -120
  140. package/translations/en.po +200 -161
  141. package/translations/et.mo +0 -0
  142. package/translations/et.po +163 -120
  143. package/translations/fr.mo +0 -0
  144. package/translations/fr.po +163 -120
  145. package/translations/ja.mo +0 -0
  146. package/translations/ja.po +163 -120
  147. package/translations/messages.pot +94 -64
  148. package/translations/nl.mo +0 -0
  149. package/translations/nl.po +164 -120
  150. package/translations/pl.mo +0 -0
  151. package/translations/pl.po +163 -120
  152. package/views/account-identity-error.hbs +34 -0
  153. package/views/accounts/account.hbs +69 -7
  154. package/views/accounts/browse.hbs +18 -35
  155. package/views/accounts/edit.hbs +1 -0
  156. package/views/accounts/register/imap.hbs +12 -2
  157. package/views/config/logging.hbs +6 -0
  158. package/views/config/oauth/app.hbs +0 -2
  159. package/views/config/security.hbs +13 -0
  160. package/views/layout/app.hbs +29 -5
  161. package/views/oauth-scope-error.hbs +1 -1
  162. package/views/partials/oauth_form.hbs +0 -15
  163. package/views/partials/reference/disclosure.hbs +8 -2
  164. package/views/partials/reference/nav.hbs +36 -9
  165. package/views/partials/reference/operation.hbs +48 -14
  166. package/views/partials/reference/params.hbs +17 -1
  167. package/views/partials/reference/schema-node.hbs +112 -54
  168. package/views/partials/reference/schema-tools.hbs +25 -0
  169. package/views/partials/reference/token-alert.hbs +35 -10
  170. package/views/partials/reference/try-it.hbs +84 -11
  171. package/views/partials/side_menu.hbs +1 -0
  172. package/views/partials/ui/checkbox.hbs +2 -2
  173. package/views/partials/ui/tabs.hbs +7 -1
  174. package/views/reference/index.hbs +1 -1
  175. package/views/reference/token.hbs +4 -0
  176. package/views/suppression-lists/index.hbs +85 -0
  177. package/views/suppression-lists/list.hbs +87 -0
  178. package/views/templates/index.hbs +8 -2
  179. package/views/tokens/index.hbs +31 -4
  180. package/views/tokens/new.hbs +324 -2
  181. package/workers/api.js +299 -140
  182. package/workers/documents.js +46 -26
  183. package/workers/export.js +20 -8
  184. package/workers/imap-proxy.js +2 -2
  185. package/workers/imap.js +13 -7
  186. package/workers/smtp.js +13 -7
  187. package/workers/submit.js +41 -31
  188. package/workers/webhooks.js +60 -37
  189. package/lib/feature-flags.js +0 -48
package/lib/account.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  const logger = require('./logger');
4
4
  const Boom = require('@hapi/boom');
5
- const msgpack = require('msgpack5')();
5
+ const msgpack = require('./msgpack');
6
6
  const {
7
7
  normalizePath,
8
8
  formatAccountListingResponse,
@@ -10,6 +10,7 @@ const {
10
10
  mergeObjects,
11
11
  download,
12
12
  resolveCredentials,
13
+ useAuthServerForOAuth2,
13
14
  isEmail,
14
15
  resolveDelegatedAccount,
15
16
  escapeRedisGlob,
@@ -19,11 +20,12 @@ const { MessageChannel } = require('worker_threads');
19
20
  const { MessagePortReadable } = require('./message-port-stream');
20
21
  const { deepStrictEqual, strictEqual } = require('assert');
21
22
  const { encrypt, decrypt } = require('./encrypt');
22
- const { oauth2Apps, LEGACY_KEYS, isApiBasedApp } = require('./oauth2-apps');
23
+ const { oauth2Apps, isApiBasedApp } = require('./oauth2-apps');
23
24
  const settings = require('./settings');
24
25
  const { buildRetentionPolicy } = require('./queue-retention');
25
26
  const { isDocumentStoreEnabled, documentStoreFeatureEnabled } = require('./document-store');
26
27
  const redisScanDelete = require('./redis-scan-delete');
28
+ const outbox = require('./outbox');
27
29
  const { customAlphabet } = require('nanoid');
28
30
  const Lock = require('ioredfour');
29
31
  const { redis } = require('./db');
@@ -299,6 +301,20 @@ class Account {
299
301
  return `${REDIS_PREFIX}iap:${this.account}`;
300
302
  }
301
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
+
302
318
  unserializeAccountData(accountData) {
303
319
  const result = {};
304
320
 
@@ -349,6 +365,13 @@ class Account {
349
365
  }
350
366
  break;
351
367
 
368
+ case 'expectedEmail':
369
+ // '' is the cleared marker written by serializeAccountData - report it as unset.
370
+ if (accountData[key]) {
371
+ result[key] = accountData[key];
372
+ }
373
+ break;
374
+
352
375
  case 'path':
353
376
  if (!accountData[key] || !accountData[key].length) {
354
377
  break;
@@ -362,7 +385,7 @@ class Account {
362
385
  }
363
386
  result[key] = value;
364
387
  } catch (err) {
365
- 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);
366
389
  }
367
390
  } else {
368
391
  // regular string
@@ -382,7 +405,7 @@ class Account {
382
405
  }
383
406
  result[key] = value;
384
407
  } catch (err) {
385
- 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);
386
409
  }
387
410
  break;
388
411
 
@@ -403,7 +426,7 @@ class Account {
403
426
 
404
427
  result[key] = value;
405
428
  } catch (err) {
406
- 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);
407
430
  }
408
431
  break;
409
432
 
@@ -437,7 +460,7 @@ class Account {
437
460
  }
438
461
  }
439
462
  } catch (err) {
440
- 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);
441
464
  }
442
465
  break;
443
466
 
@@ -464,14 +487,14 @@ class Account {
464
487
  result[type].auth[key] = decrypt(result[type].auth[key], this.secret);
465
488
  } catch (err) {
466
489
  // ignore??
467
- 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);
468
491
  }
469
492
  } else if (key in result[type]) {
470
493
  try {
471
494
  result[type][key] = decrypt(result[type][key], this.secret);
472
495
  } catch (err) {
473
496
  // ignore??
474
- 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);
475
498
  }
476
499
  }
477
500
  }
@@ -541,7 +564,7 @@ class Account {
541
564
  try {
542
565
  result[key] = JSON.stringify(accountData[key]);
543
566
  } catch (err) {
544
- 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 });
545
568
  }
546
569
  }
547
570
  break;
@@ -556,7 +579,7 @@ class Account {
556
579
 
557
580
  result[key] = value;
558
581
  } catch (err) {
559
- 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 });
560
583
  }
561
584
 
562
585
  break;
@@ -584,7 +607,7 @@ class Account {
584
607
 
585
608
  result[key] = value;
586
609
  } catch (err) {
587
- 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 });
588
611
  }
589
612
 
590
613
  break;
@@ -603,13 +626,13 @@ class Account {
603
626
  try {
604
627
  connectData.auth[key] = encrypt(connectData.auth[key], this.secret);
605
628
  } catch (err) {
606
- this.logger.error({ msg: 'Failed to encrypt value', err });
629
+ this.logger.error({ msg: 'Failed to encrypt value', key, account: this.account, err });
607
630
  }
608
631
  } else if (key in connectData) {
609
632
  try {
610
633
  connectData[key] = encrypt(connectData[key], this.secret);
611
634
  } catch (err) {
612
- this.logger.error({ msg: 'Failed to encrypt value', err });
635
+ this.logger.error({ msg: 'Failed to encrypt value', key, account: this.account, err });
613
636
  }
614
637
  }
615
638
  }
@@ -627,7 +650,7 @@ class Account {
627
650
 
628
651
  result[key] = JSON.stringify(connectData);
629
652
  } catch (err) {
630
- 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 });
631
654
  }
632
655
  break;
633
656
 
@@ -651,6 +674,17 @@ class Account {
651
674
  }
652
675
  break;
653
676
 
677
+ case 'expectedEmail':
678
+ // Clearable, so it cannot ride the default branch: that drops nulls, and hmset only
679
+ // ever adds keys, which would leave an identity pin settable but never removable.
680
+ // Follows the same convention as `copy` above - null serializes to the empty marker
681
+ // and unserialize treats it as unset - rather than adding a per-field delete to
682
+ // persistUpdate.
683
+ if (typeof accountData[key] === 'string' || accountData[key] === null) {
684
+ result[key] = accountData[key] || '';
685
+ }
686
+ break;
687
+
654
688
  default:
655
689
  if (typeof accountData[key] !== 'undefined' && accountData[key] !== null && typeof accountData[key].toString === 'function') {
656
690
  result[key] = accountData[key].toString();
@@ -779,7 +813,7 @@ class Account {
779
813
  await lock.releaseLock(updateLock);
780
814
  } catch (err) {
781
815
  // The lock expires on its own, so a failed release must not mask the result
782
- 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 });
783
817
  }
784
818
  }
785
819
  }
@@ -840,9 +874,17 @@ class Account {
840
874
  mergeObjects(accountData[subKey], oldAccountData[subKey]);
841
875
  }
842
876
 
843
- let pipeline = this.redis.multi().hmset(this.getAccountKey(), this.serializeAccountData(accountData));
877
+ // An update whose payload serializes to nothing - an empty request, say - must not reach hmset:
878
+ // Redis rejects a write with no field/value pairs outright ("wrong number of arguments"), which
879
+ // surfaced as a 500 on a perfectly valid request.
880
+ const updatedFields = this.serializeAccountData(accountData);
881
+
882
+ let pipeline = this.redis.multi();
883
+ if (Object.keys(updatedFields).length) {
884
+ pipeline = pipeline.hmset(this.getAccountKey(), updatedFields);
885
+ }
844
886
 
845
- if (addProvider && !LEGACY_KEYS.includes(addProvider)) {
887
+ if (addProvider) {
846
888
  pipeline = pipeline.sadd(`${REDIS_PREFIX}oapp:a:${addProvider}`, this.account);
847
889
  if (accountData._oldOAuth2User && accountData._oldOAuth2User.toLowerCase() !== accountData.oauth2.auth?.user?.toLowerCase()) {
848
890
  pipeline = pipeline.hdel(`${REDIS_PREFIX}oapp:h:${addProvider}`, accountData._oldOAuth2User.toLowerCase());
@@ -880,15 +922,13 @@ class Account {
880
922
  }
881
923
  }
882
924
 
883
- let [[err, result]] = await pipeline.exec();
884
- if (err) {
885
- throw err;
886
- }
887
-
888
- if (!result || result !== 'OK') {
889
- let message = 'Something went wrong';
890
- let error = Boom.boomify(new Error(message), { statusCode: 500 });
891
- throw error;
925
+ // Surface the first failing reply. Checked by scanning rather than by reading a fixed index: the
926
+ // hmset is now conditional, so a positional read would silently start asserting against whichever
927
+ // command happened to be queued first.
928
+ for (let [err] of (await pipeline.exec()) || []) {
929
+ if (err) {
930
+ throw err;
931
+ }
892
932
  }
893
933
 
894
934
  return oldAccountData;
@@ -1191,24 +1231,33 @@ class Account {
1191
1231
  const tombstoneTdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyTdy}`;
1192
1232
  const tombstoneYdy = `${REDIS_PREFIX}tomb:${this.account}:${dateKeyYdy}`;
1193
1233
 
1234
+ // UNLINK rather than DEL throughout: none of these need the memory reclaimed synchronously,
1235
+ // and the outbox and the message ID index can hold enough entries that freeing them inline
1236
+ // would block Redis for every other worker.
1237
+ //
1238
+ // The outbox is read and unlinked in the same transaction, because that hash is the only
1239
+ // mapping from an account to the submit queue jobs of the messages it has not delivered
1240
+ // yet, and those jobs outlive the account otherwise. Reading it here means the ID list is
1241
+ // exactly what was unlinked, and costs no extra round trip.
1194
1242
  let pipeline = this.redis
1195
1243
  .multi()
1196
- .del(this.getAccountKey())
1244
+ .hkeys(`${REDIS_PREFIX}iaq:${this.account}`) // queued message IDs, removed from the submit queue below
1245
+ .unlink(this.getAccountKey())
1197
1246
  .srem(`${REDIS_PREFIX}ia:accounts`, this.account)
1198
- .del(this.getMailboxListKey()) // mailbox list
1199
- .del(this.getMailboxHashKey()) // mailbox list for ID references
1200
- .del(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1201
- .del(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1202
- .del(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1203
- .del(`${REDIS_PREFIX}iat:${this.account}`) // access tokens
1204
- .del(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1205
- .del(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1247
+ .unlink(this.getMailboxListKey()) // mailbox list
1248
+ .unlink(this.getMailboxHashKey()) // mailbox list for ID references
1249
+ .unlink(`${REDIS_PREFIX}iar:b:${this.account}`) // bounce list
1250
+ .unlink(`${REDIS_PREFIX}iar:s:${this.account}`) // seen messages list
1251
+ .unlink(`${REDIS_PREFIX}iaq:${this.account}`) // delayed message queue
1252
+ .unlink(`${REDIS_PREFIX}iat:${this.account}`) // access tokens
1253
+ .unlink(`${REDIS_PREFIX}iac:${this.account}`) // cache hash
1254
+ .unlink(`${REDIS_PREFIX}iap:${this.account}`) // external event notification queue
1206
1255
 
1207
- .del(tombstoneTdy)
1208
- .del(tombstoneYdy)
1256
+ .unlink(tombstoneTdy)
1257
+ .unlink(tombstoneYdy)
1209
1258
 
1210
- .del(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
1211
- .del(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
1259
+ .unlink(`${REDIS_PREFIX}tpl:${this.account}:i`) // stored templates index
1260
+ .unlink(`${REDIS_PREFIX}tpl:${this.account}:c`); // stored templates index
1212
1261
 
1213
1262
  if (accountData.oauth2?.provider) {
1214
1263
  pipeline = pipeline.srem(`${REDIS_PREFIX}oapp:a:${accountData.oauth2.provider}`, this.account);
@@ -1219,11 +1268,25 @@ class Account {
1219
1268
 
1220
1269
  let result = await pipeline.exec();
1221
1270
 
1271
+ // Results are positional: [0] is the outbox HKEYS, [1] the account key UNLINK. Both indexes
1272
+ // move if a command is inserted ahead of them.
1273
+ let queuedMessageIds = (result && result[0] && result[0][1]) || [];
1274
+ if (queuedMessageIds.length) {
1275
+ // Best effort: the account is already gone, so a queue that will not cooperate must not
1276
+ // turn a completed deletion into an error.
1277
+ try {
1278
+ let removed = await outbox.removeJobs(queuedMessageIds, { account: this.account, logger: this.logger });
1279
+ this.logger.info({ msg: 'Removed queued messages of a deleted account', account: this.account, queued: queuedMessageIds.length, removed });
1280
+ } catch (err) {
1281
+ this.logger.error({ msg: 'Failed to remove queued messages of a deleted account', account: this.account, err });
1282
+ }
1283
+ }
1284
+
1222
1285
  // scan and delete keys
1223
1286
  // should we wait though? might take a lot of time
1224
1287
  await redisScanDelete(this.redis, this.logger, `${REDIS_PREFIX}iam:${escapeRedisGlob(this.account)}:*`);
1225
1288
 
1226
- if (!result || !result[0] || !result[0][1]) {
1289
+ if (!result || !result[1] || !result[1][1]) {
1227
1290
  return {
1228
1291
  account: this.account,
1229
1292
  deleted: false
@@ -1254,7 +1317,7 @@ class Account {
1254
1317
  }
1255
1318
  });
1256
1319
  } catch (err) {
1257
- 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 });
1258
1321
  }
1259
1322
  }
1260
1323
 
@@ -1429,7 +1492,7 @@ class Account {
1429
1492
  // its own state against this endpoint reads as a deletion.
1430
1493
  let decoded = decodeStoredMailboxEntry(storedListing[path]);
1431
1494
  if (!decoded) {
1432
- 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 });
1433
1496
  continue;
1434
1497
  }
1435
1498
 
@@ -1850,7 +1913,7 @@ class Account {
1850
1913
  messageData.flags.push('\\Seen');
1851
1914
  // do not wait until the update is completed, return immediately
1852
1915
  this.updateMessage(message, { flags: { add: ['\\Seen'] } }).catch(err => {
1853
- 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 });
1854
1917
  });
1855
1918
  }
1856
1919
 
@@ -2330,7 +2393,14 @@ class Account {
2330
2393
 
2331
2394
  this.logger.trace({
2332
2395
  msg: 'Executed ES query',
2333
- 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
+ },
2334
2404
  results: searchResult.hits.total.value
2335
2405
  });
2336
2406
 
@@ -2496,17 +2566,19 @@ class Account {
2496
2566
  try {
2497
2567
  flushLock = await lock.acquireLock(lockKey, 30 * 60 * 1000);
2498
2568
  if (!flushLock.success) {
2499
- 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 });
2500
2571
 
2501
2572
  let error = Boom.boomify(new Error('One flush operation at a time allowed, try again later'), { statusCode: 429 });
2502
2573
  error.output.payload.code = 'LockFail';
2503
2574
  throw error;
2504
2575
  }
2505
2576
  } catch (err) {
2506
- this.logger.error({ msg: 'Failed to get lock', lockKey, err });
2507
2577
  if (Boom.isBoom(err)) {
2578
+ // contention was already logged above
2508
2579
  throw err;
2509
2580
  }
2581
+ this.logger.error({ msg: 'Failed to get flush lock', account: this.account, lockKey, err });
2510
2582
  let error = Boom.boomify(new Error('Failed to get flush lock, try again later'), { statusCode: 500 });
2511
2583
  if (err.code) {
2512
2584
  error.output.payload.code = err.code || 'LockFail';
@@ -2585,7 +2657,7 @@ class Account {
2585
2657
  });
2586
2658
  deletedCount += deleteResult[indexName].deleted || 0;
2587
2659
  } catch (err) {
2588
- logger.error({
2660
+ this.logger.error({
2589
2661
  msg: 'Failed to delete account emails from index',
2590
2662
  action: 'flush',
2591
2663
  code: 'document_delete_account_error',
@@ -2599,10 +2671,11 @@ class Account {
2599
2671
  }
2600
2672
  }
2601
2673
 
2602
- logger.trace({
2674
+ this.logger.trace({
2603
2675
  msg: 'Deleted account emails from index',
2604
2676
  action: 'flush',
2605
2677
  code: 'document_delete_account',
2678
+ account: this.account,
2606
2679
  deletedCount,
2607
2680
  deleteResult
2608
2681
  });
@@ -2644,11 +2717,15 @@ class Account {
2644
2717
  try {
2645
2718
  renewLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
2646
2719
  if (!renewLock.success) {
2647
- 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 });
2648
2722
  throw new Error('Failed to get renewal lock');
2649
2723
  }
2650
2724
  } catch (err) {
2651
- 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
+ }
2652
2729
  let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
2653
2730
  if (err.code) {
2654
2731
  error.output.payload.code = err.code || 'LockFail';
@@ -2669,7 +2746,7 @@ class Account {
2669
2746
  this.logger.info({
2670
2747
  msg: 'OAuth2 access token renewed while locked',
2671
2748
  action: 'ensureAccessToken',
2672
- error: null,
2749
+ account: this.account,
2673
2750
  user: accountData.oauth2.auth.user,
2674
2751
  expires: accountData.oauth2.expires,
2675
2752
  scopes: accountData.oauth2.scope,
@@ -2717,7 +2794,7 @@ class Account {
2717
2794
  this.logger.info({
2718
2795
  msg: 'Renewed OAuth2 access token',
2719
2796
  action: 'ensureAccessToken',
2720
- error: null,
2797
+ account: this.account,
2721
2798
  user: accountData.oauth2.auth.user,
2722
2799
  expires: updates.expires,
2723
2800
  scopes: updates.scope,
@@ -2728,12 +2805,11 @@ class Account {
2728
2805
 
2729
2806
  return accountData;
2730
2807
  } catch (err) {
2731
- this.logger.info({
2808
+ this.logger.warn({
2732
2809
  msg: 'Failed to renew OAuth2 access token',
2733
2810
  action: 'ensureAccessToken',
2734
- error: err,
2735
- response: err.tokenRequest && err.tokenRequest.response,
2736
- flag: err.tokenRequest && err.tokenRequest.flag
2811
+ account: this.account,
2812
+ err
2737
2813
  });
2738
2814
 
2739
2815
  if (err.tokenRequest?.userFlag) {
@@ -2753,7 +2829,7 @@ class Account {
2753
2829
  if (accountData.oauth2) {
2754
2830
  accountData.oauth2.expires = new Date(Date.now() - 24 * 3600 * 1000).toISOString();
2755
2831
  await this.update({ account: accountData.account, oauth2: accountData.oauth2 });
2756
- 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 });
2757
2833
  }
2758
2834
  return accountData;
2759
2835
  }
@@ -2767,7 +2843,7 @@ class Account {
2767
2843
  throw error;
2768
2844
  }
2769
2845
 
2770
- if (accountData.oauth2.useAuthServer) {
2846
+ if (await useAuthServerForOAuth2(accountData.oauth2, this.logger, { account: this.account, target: 'api' })) {
2771
2847
  // resolve credentials
2772
2848
 
2773
2849
  let authData = await resolveCredentials(this.account, 'api');
@@ -2886,17 +2962,18 @@ class Account {
2886
2962
  this.logger.debug({
2887
2963
  msg: 'MS Graph subscription event',
2888
2964
  type: 'event',
2965
+ account: this.account,
2889
2966
  event,
2890
2967
  res
2891
2968
  });
2892
2969
  } catch (err) {
2893
- 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 });
2894
2971
  }
2895
2972
 
2896
2973
  try {
2897
2974
  await this.call({ cmd: 'externalNotify', accounts: [this.account] });
2898
2975
  } catch (err) {
2899
- 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 });
2900
2977
  }
2901
2978
  }
2902
2979
 
@@ -2917,4 +2994,11 @@ class Account {
2917
2994
  }
2918
2995
  }
2919
2996
 
2920
- 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 };
@@ -68,6 +68,18 @@ function slugify(value) {
68
68
  .replace(/^-+|-+$/g, '');
69
69
  }
70
70
 
71
+ // Where a group and an operation live. Four surfaces link to them - the tag directory, the
72
+ // nav's group rows, its per-group lists and the filter index - so the shape of a reference
73
+ // link is stated here rather than composed at each of them. The route itself is registered in
74
+ // lib/ui-routes/reference-routes.js.
75
+ function tagUrl(tagSlug) {
76
+ return `/admin/reference/${tagSlug}`;
77
+ }
78
+
79
+ function operationUrl(tagSlug, operationId) {
80
+ return `${tagUrl(tagSlug)}#${operationId}`;
81
+ }
82
+
71
83
  const METHOD_VARIANTS = {
72
84
  get: 'info',
73
85
  post: 'success',
@@ -96,6 +108,42 @@ function rangeChip(min, max, unit) {
96
108
  return null;
97
109
  }
98
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
+
99
147
  // Short constraint chips shown next to a property. Covers both the standard OpenAPI
100
148
  // keywords and the `x-*` extensions the generator emits for joi rules OpenAPI has no
101
149
  // keyword for (accepted URI schemes, email format, value coercion) - real validation
@@ -113,7 +161,7 @@ function constraintList(schema) {
113
161
 
114
162
  for (const chip of [
115
163
  rangeChip(schema.minimum, schema.maximum, ''),
116
- rangeChip(schema.minLength, schema.maxLength, 'chars'),
164
+ lengthChip(schema.minLength, schema.maxLength),
117
165
  rangeChip(schema.minItems, schema.maxItems, 'items')
118
166
  ]) {
119
167
  if (chip) {
@@ -137,11 +185,13 @@ function constraintList(schema) {
137
185
  }
138
186
  }
139
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.
140
193
  const xConvert = schema['x-convert'];
141
194
  if (xConvert && typeof xConvert === 'object') {
142
- if (xConvert.trim) {
143
- chips.push('trimmed');
144
- }
145
195
  if (xConvert.case === 'lower') {
146
196
  chips.push('lowercased');
147
197
  }
@@ -157,6 +207,54 @@ function constraintList(schema) {
157
207
  return chips;
158
208
  }
159
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
+
160
258
  // JSON rendered for the example panels. Kept here so the pretty-printing is identical
161
259
  // everywhere (page body, code samples, try-it request editor).
162
260
  function stringifyExample(value) {
@@ -173,7 +271,10 @@ function stringifyExample(value) {
173
271
  module.exports = {
174
272
  formatDescription,
175
273
  slugify,
274
+ tagUrl,
275
+ operationUrl,
176
276
  methodVariant,
177
277
  constraintList,
278
+ formatExample,
178
279
  stringifyExample
179
280
  };