emailengine-app 2.82.0 → 2.82.1

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 (65) hide show
  1. package/.ncurc.js +23 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -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 +196 -67
  26. package/lib/enum-descriptions.js +5 -1
  27. package/lib/export.js +8 -2
  28. package/lib/gateway.js +5 -0
  29. package/lib/get-secret.js +1 -21
  30. package/lib/mcp/tools.js +95 -36
  31. package/lib/oauth/gmail.js +42 -12
  32. package/lib/oauth/mail-ru.js +24 -17
  33. package/lib/oauth/outlook.js +34 -24
  34. package/lib/oauth/scope-checker.js +35 -1
  35. package/lib/oauth/scope-list.js +55 -0
  36. package/lib/oauth/token-fetch.js +47 -0
  37. package/lib/oauth2-apps.js +16 -47
  38. package/lib/outbox.js +2 -7
  39. package/lib/queue-retention.js +4 -2
  40. package/lib/read-env-value.js +33 -2
  41. package/lib/schemas.js +62 -15
  42. package/lib/token-audit-log.js +3 -2
  43. package/lib/tools.js +1 -1
  44. package/lib/ui-routes/account-routes.js +40 -7
  45. package/lib/ui-routes/oauth-config-routes.js +3 -14
  46. package/lib/ui-routes/route-helpers.js +23 -23
  47. package/lib/ui-routes/special-use-paths.js +33 -0
  48. package/lib/utils/network.js +9 -17
  49. package/package.json +18 -18
  50. package/sbom.json +1 -1
  51. package/server.js +21 -3
  52. package/setup-production.sh +16 -7
  53. package/static/licenses.html +30 -20
  54. package/translations/messages.pot +74 -56
  55. package/views/account-workspace-error.hbs +30 -0
  56. package/views/accounts/account.hbs +9 -4
  57. package/views/accounts/edit.hbs +11 -2
  58. package/views/internals/index.hbs +1 -1
  59. package/views/partials/gmail_api_scopes.hbs +16 -0
  60. package/views/partials/oauth_form.hbs +67 -94
  61. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  62. package/views/partials/scope_info.hbs +14 -23
  63. package/workers/api.js +62 -27
  64. package/workers/imap.js +6 -3
  65. package/workers/submit.js +2 -5
@@ -140,7 +140,7 @@
140
140
  <p class="mb-4">EmailEngine spreads its work across worker threads - account sync, the API and web server, webhook
141
141
  delivery, message submission, and exports. Their counts are set at startup with environment variables such as
142
142
  <code>EENGINE_WORKERS</code> (account sync), <code>EENGINE_WORKERS_API</code>, <code>EENGINE_WORKERS_WEBHOOKS</code>,
143
- and <code>EENGINE_WORKERS_SUBMIT</code>.</p>
143
+ <code>EENGINE_WORKERS_SUBMIT</code> and <code>EENGINE_WORKERS_EXPORT</code>.</p>
144
144
  <p class="mb-4">Most worker types can be scaled to several threads with those variables. The HTTP and API server is
145
145
  the exception: running more than one API worker requires <code>SO_REUSEPORT</code>, which is available only on
146
146
  Linux with Node.js 23.1 or newer. On macOS, Windows, or older Node.js versions EmailEngine falls back to a
@@ -0,0 +1,16 @@
1
+ {{!-- The Gmail API scopes an app in `baseScopes: api` mode requests, as list items. Shared by the
2
+ interactive `gmail` block and the `gmailService` one: what an app asks Google for follows from its own
3
+ scope selection, not from whether a person or a service account presents it. A service-account app
4
+ listing gmail.modify here while it had deliberately skipped it is the bug this partial exists to stop
5
+ coming back. --}}
6
+
7
+ {{#unless disabledScopes.Gmail_Modify}}
8
+ <li><code>"https://www.googleapis.com/auth/gmail.modify"</code></li>
9
+ {{else}}
10
+ {{#if isSendOnlyGmail}}
11
+ <li><code>"https://www.googleapis.com/auth/gmail.send"</code></li>
12
+ {{else}}
13
+ <li><code>"https://www.googleapis.com/auth/gmail.readonly"</code></li>
14
+ <li><code>"https://www.googleapis.com/auth/gmail.labels"</code></li>
15
+ {{/if}}
16
+ {{/unless}}
@@ -81,9 +81,9 @@ Read about setting up {{providerData.comment}} from <a href="{{providerData.tuto
81
81
  {{#if activeGmail}}
82
82
  <div>
83
83
  {{> ui/checkbox id="googleWorkspaceAccounts" name="googleWorkspaceAccounts"
84
- label="Show only Google Workspace accounts on the OAuth2 login page"
84
+ label="Accept only Google Workspace accounts"
85
85
  checked=values.googleWorkspaceAccounts error=errors.googleWorkspaceAccounts
86
- hint="When enabled, only Google Workspace accounts will be available on the Gmail OAuth2 login screen."}}
86
+ hint="Shows only Google Workspace accounts on the Gmail sign-in screen, and refuses the setup if a personal account signs in anyway."}}
87
87
  </div>
88
88
  {{/if}}
89
89
 
@@ -441,6 +441,20 @@ Read about setting up {{providerData.comment}} from <a href="{{providerData.tuto
441
441
  <td>Regular email protocols</td>
442
442
  <td><code>"https://mail.google.com/"</code> consent screen scope</td>
443
443
 
444
+ </tr>
445
+ <tr>
446
+ <td>
447
+ <div class="flex items-center gap-2">
448
+ <input class="radio radio-sm base-scopes-radio" type="radio" name="baseScopes"
449
+ id="baseScopesAPI" value="api" {{#if baseScopesApi}}checked{{/if}}>
450
+ <label class="label-text p-0" for="baseScopesAPI">
451
+ Gmail API {{> ui/badge label="beta" variant="neutral"}}
452
+ </label>
453
+ </div>
454
+ </td>
455
+ <td>Gmail HTTP API, through domain-wide delegation</td>
456
+ <td><code>"/auth/gmail.modify"</code> delegated scope</td>
457
+
444
458
  </tr>
445
459
  <tr>
446
460
  <td>
@@ -469,6 +483,17 @@ Read about setting up {{providerData.comment}} from <a href="{{providerData.tuto
469
483
  </tr>
470
484
  {{/if}}
471
485
 
486
+ {{#if baseScopesApi}}
487
+ <tr>
488
+ <td>
489
+ <strong>Gmail API</strong> {{> ui/badge label="beta" variant="neutral"}}
490
+ </td>
491
+ <td>Gmail HTTP API, through domain-wide delegation</td>
492
+ <td><code>"/auth/gmail.modify"</code> delegated scope</td>
493
+
494
+ </tr>
495
+ {{/if}}
496
+
472
497
  {{#if baseScopesPubsub}}
473
498
  <tr>
474
499
  <td>
@@ -486,8 +511,10 @@ Read about setting up {{providerData.comment}} from <a href="{{providerData.tuto
486
511
  </table>
487
512
  </div>
488
513
 
489
- <div id="select-pubsub-app"
490
- class="card-footer border-base-content/10 border-t px-6 py-4{{#unless baseScopesPubsub}} hidden{{/unless}}">
514
+ {{> oauth_pubsub_app_select}}
515
+
516
+ <div class="card-footer border-base-content/10 border-t px-6 py-4{{#unless baseScopesPubsub}} hidden{{/unless}}"
517
+ data-base-scopes="pubsub">
491
518
 
492
519
  {{#if actionCreate}}
493
520
 
@@ -624,40 +651,7 @@ Read about setting up {{providerData.comment}} from <a href="{{providerData.tuto
624
651
  </table>
625
652
  </div>
626
653
 
627
- <div id="select-pubsub-app"
628
- class="card-footer border-base-content/10 border-t px-6 py-4{{#unless baseScopesApi}} hidden{{/unless}}">
629
-
630
- <p class="mb-2">
631
- For faster webhook notifications, select a Gmail service account with the Pub/Sub Admin role.
632
- EmailEngine uses it to set up Google Cloud Pub/Sub for accounts managed by this app.
633
- </p>
634
-
635
- <p class="mb-2">
636
- <strong>Note:</strong> This is optional but recommended. With a Pub/Sub service account, EmailEngine
637
- receives changes in near real time. Without one, it falls back to polling each account about every 10
638
- minutes, so webhooks for new, updated, or deleted emails (and bounce detection) still fire, just with up
639
- to a 10-minute delay. Send-only accounts don't require this.
640
- </p>
641
-
642
- <label class="label-text" for="pubSubApp">Select service account to manage webhooks (optional). The service
643
- account must be for the same Google Cloud Project.</label>
644
- <select class="select w-full{{#if errors.pubSubApp}} is-invalid{{/if}}" id="pubSubApp"
645
- name="pubSubApp" {{#unless baseScopesApi}}disabled{{/unless}}>
646
-
647
- <option value="">Select the service account for your project</option>
648
-
649
- {{#each pubSubApps}}
650
- <option value="{{id}}" data-project="{{googleProjectId}}" {{#if selected}}selected{{/if}} {{#unless
651
- baseScopesApi}}disabled{{/unless}}>{{name}}{{#if
652
- description}} -
653
- {{description}}{{/if}} [{{googleProjectId}}]</option>
654
- {{/each}}
655
-
656
- </select>
657
- {{#if errors.pubSubApp}}
658
- <span class="helper-text text-error">{{errors.pubSubApp}}</span>
659
- {{/if}}
660
- </div>
654
+ {{> oauth_pubsub_app_select}}
661
655
 
662
656
  </div>
663
657
  {{/if}}
@@ -744,8 +738,8 @@ Read about setting up {{providerData.comment}} from <a href="{{providerData.tuto
744
738
  </table>
745
739
  </div>
746
740
 
747
- <div id="select-pubsub-app"
748
- class="card-footer border-base-content/10 border-t px-6 py-4{{#unless baseScopesApi}} hidden{{/unless}}">
741
+ <div class="card-footer border-base-content/10 border-t px-6 py-4{{#unless baseScopesApi}} hidden{{/unless}}"
742
+ data-base-scopes="api">
749
743
 
750
744
  <p class="mb-2">Microsoft Graph delivers change notifications to EmailEngine at these two endpoints:</p>
751
745
 
@@ -815,7 +809,9 @@ Read about setting up {{providerData.comment}} from <a href="{{providerData.tuto
815
809
 
816
810
  {{/if}}
817
811
 
818
- {{#if activeGmail}}
812
+ {{!-- Guarded on providerData.gmailApi, not on one provider: a service account in Gmail API mode takes
813
+ the same delegated scopes an interactive app takes, so the presets apply to it too. --}}
814
+ {{#if providerData.gmailApi}}
819
815
  <div class="card bg-base-100 shadow-md mb-6{{#unless baseScopesApi}} hidden{{/unless}}" id="account-type-card-gmail">
820
816
  <div class="card-header">
821
817
  <h6 class="card-title text-primary">Scope presets</h6>
@@ -911,7 +907,7 @@ open=values.extraScopes}}
911
907
  <p class="mb-4">Request additional OAuth2 scopes, for example when your application uses the provider access tokens
912
908
  for services beyond email.</p>
913
909
 
914
- {{#if activeGmail}}
910
+ {{#if providerData.gmailApi}}
915
911
  <div class="alert alert-soft alert-info mb-4 block">
916
912
  <p>When adding new scopes, ensure that related APIs are
917
913
  enabled for your OAuth2 app (look for <em>Enabled APIs & services</em> in <a
@@ -921,15 +917,6 @@ open=values.extraScopes}}
921
917
  </div>
922
918
  {{/if}}
923
919
 
924
- {{#if activeGmailService}}
925
- <div class="alert alert-soft alert-info mb-4"><span>When adding new scopes, ensure that related APIs are
926
- enabled for your OAuth2 app (look for <em>Enabled APIs & services</em> in <a
927
- href="https://console.cloud.google.com/apis/dashboard" target="_blank" rel="noopener noreferrer"
928
- referrerpolicy="no-referrer" class="link link-animated">Google Cloud Console</a>)
929
- before registering accounts with these permissions. Otherwise, token generation will fail.</span>
930
- </div>
931
- {{/if}}
932
-
933
920
  {{#if activeOutlook}}
934
921
  <div class="alert alert-soft alert-info mb-4"><span>
935
922
 
@@ -986,57 +973,43 @@ open=values.skipScopes}}
986
973
  const pubSubAppElm = document.getElementById('pubSubApp');
987
974
 
988
975
  /**
989
- * Checks and updates the visibility of scope-related UI elements based on selected base scopes radio button.
990
- * Handles both API and Pub/Sub scope selections, showing/hiding relevant configuration sections.
976
+ * Shows the configuration sections that belong to the selected base scope.
977
+ *
978
+ * Each toggled section declares the value that reveals it with `data-base-scopes`, rather than
979
+ * being looked up by element id: a service-account app offers both `api` and `pubsub` and so
980
+ * carries two of them in one block, which two hardcoded id lookups could not express - they
981
+ * both reached for the same element and fought over it.
991
982
  */
992
983
  function checkScopesRadio() {
993
- let baseScopesAPIElm = document.getElementById('baseScopesAPI');
994
- let baseScopesPubsubElm = document.getElementById('baseScopesPubsub');
995
- let selectPubsubAppElm = document.getElementById('select-pubsub-app');
996
- let accountTypeCardGmail = document.getElementById('account-type-card-gmail');
997
- let accountTypeCardOutlook = document.getElementById('account-type-card-outlook');
998
-
999
- if (baseScopesAPIElm && selectPubsubAppElm) {
1000
- if (baseScopesAPIElm.checked) {
1001
- selectPubsubAppElm.classList.remove('hidden');
1002
- if (pubSubAppElm) {
1003
- pubSubAppElm.disabled = false;
1004
- }
1005
- } else {
1006
- selectPubsubAppElm.classList.add('hidden');
1007
- if (pubSubAppElm) {
1008
- pubSubAppElm.disabled = true;
1009
- }
1010
- }
984
+ let selected = document.querySelector('.base-scopes-radio:checked');
985
+ if (!selected) {
986
+ // A stored app's page renders its base scope as a static row and carries no radios at
987
+ // all, so the server already decided what is visible. Toggling against "nothing
988
+ // selected" would hide every section, including the Pub/Sub topic names and the
989
+ // Microsoft notification endpoints that page exists to show.
990
+ return;
1011
991
  }
1012
992
 
1013
- if (baseScopesPubsubElm && selectPubsubAppElm) {
1014
- if (baseScopesPubsubElm.checked) {
1015
- selectPubsubAppElm.classList.remove('hidden');
1016
- } else {
1017
- selectPubsubAppElm.classList.add('hidden');
993
+ let shownElm = null;
994
+ document.querySelectorAll('[data-base-scopes]').forEach(sectionElm => {
995
+ let shown = sectionElm.dataset.baseScopes === selected.value;
996
+ sectionElm.classList.toggle('hidden', !shown);
997
+ if (shown) {
998
+ shownElm = sectionElm;
1018
999
  }
1019
- }
1000
+ });
1020
1001
 
1021
- // Show/hide account type card based on API mode selection
1022
- if (baseScopesAPIElm) {
1023
- if (baseScopesAPIElm.checked) {
1024
- if (accountTypeCardGmail) {
1025
- accountTypeCardGmail.classList.remove('hidden');
1026
- }
1027
- if (accountTypeCardOutlook) {
1028
- accountTypeCardOutlook.classList.remove('hidden');
1029
- }
1030
- } else {
1031
- if (accountTypeCardGmail) {
1032
- accountTypeCardGmail.classList.add('hidden');
1033
- }
1034
- if (accountTypeCardOutlook) {
1035
- accountTypeCardOutlook.classList.add('hidden');
1036
- }
1037
- }
1002
+ if (pubSubAppElm) {
1003
+ // A disabled control is left out of the submitted form, which is how a hidden Pub/Sub
1004
+ // selection stays out of the payload instead of riding along. Only the select is touched
1005
+ // here - which options are selectable belongs to filterPubSubApps() alone.
1006
+ pubSubAppElm.disabled = !shownElm || !shownElm.contains(pubSubAppElm);
1038
1007
  }
1039
1008
 
1009
+ // The account type card describes what an API-based app can do with an account
1010
+ document.querySelectorAll('#account-type-card-gmail, #account-type-card-outlook').forEach(cardElm => {
1011
+ cardElm.classList.toggle('hidden', selected.value !== 'api');
1012
+ });
1040
1013
  }
1041
1014
 
1042
1015
  document.querySelectorAll('.base-scopes-radio').forEach(radioElm => {
@@ -0,0 +1,43 @@
1
+ {{!-- The Pub/Sub service account an API-based Gmail app uses to arm watches, shared by the
2
+ interactive `gmail` block and the `gmailService` one: both reach Gmail over the HTTP API, so both want
3
+ the same control, and the server-side `pubSubApp` field was never provider-specific.
4
+
5
+ `data-base-scopes="api"` is what reveals it - see checkScopesRadio() at the bottom of oauth_form.hbs. --}}
6
+
7
+ <div class="card-footer border-base-content/10 border-t px-6 py-4{{#unless baseScopesApi}} hidden{{/unless}}"
8
+ data-base-scopes="api">
9
+
10
+ <p class="mb-2">
11
+ For faster webhook notifications, select a Gmail service account with the Pub/Sub Admin role.
12
+ EmailEngine uses it to set up Google Cloud Pub/Sub for accounts managed by this app.
13
+ </p>
14
+
15
+ <p class="mb-2">
16
+ <strong>Note:</strong> This is optional but recommended. With a Pub/Sub service account, EmailEngine
17
+ receives changes in near real time. Without one, it falls back to polling each account about every 10
18
+ minutes, so webhooks for new, updated, or deleted emails (and bounce detection) still fire, just with up
19
+ to a 10-minute delay. Send-only accounts don't require this.
20
+ </p>
21
+
22
+ <label class="label-text" for="pubSubApp">Select service account to manage webhooks (optional). The service
23
+ account must be for the same Google Cloud Project.</label>
24
+ <select class="select w-full{{#if errors.pubSubApp}} is-invalid{{/if}}" id="pubSubApp"
25
+ name="pubSubApp" {{#unless baseScopesApi}}disabled{{/unless}}>
26
+
27
+ <option value="">Select the service account for your project</option>
28
+
29
+ {{!-- Nothing disables an option here: the select carries that for the whole control, and
30
+ filterPubSubApps() in oauth_form.hbs owns the per-option state so the two cannot fight. An
31
+ {{#unless baseScopesApi}} inside this {{#each}} resolved against the ITEM rather than the page,
32
+ so it shipped `disabled` on every option in every mode. --}}
33
+ {{#each pubSubApps}}
34
+ <option value="{{id}}" data-project="{{googleProjectId}}" {{#if selected}}selected{{/if}}>{{name}}{{#if
35
+ description}} -
36
+ {{description}}{{/if}} [{{googleProjectId}}]</option>
37
+ {{/each}}
38
+
39
+ </select>
40
+ {{#if errors.pubSubApp}}
41
+ <span class="helper-text text-error">{{errors.pubSubApp}}</span>
42
+ {{/if}}
43
+ </div>
@@ -11,18 +11,7 @@
11
11
  {{/if}}
12
12
 
13
13
  {{#if baseScopesApi}}
14
-
15
- {{#unless disabledScopes.Gmail_Modify}}
16
- <li><code>"https://www.googleapis.com/auth/gmail.modify"</code></li>
17
- {{else}}
18
- {{#if isSendOnlyGmail}}
19
- <li><code>"https://www.googleapis.com/auth/gmail.send"</code></li>
20
- {{else}}
21
- <li><code>"https://www.googleapis.com/auth/gmail.readonly"</code></li>
22
- <li><code>"https://www.googleapis.com/auth/gmail.labels"</code></li>
23
- {{/if}}
24
- {{/unless}}
25
-
14
+ {{> gmail_api_scopes}}
26
15
  {{/if}}
27
16
 
28
17
  {{#if baseScopesPubsub}}
@@ -31,15 +20,6 @@
31
20
 
32
21
  </ul>
33
22
 
34
- {{#if isSendOnlyGmail}}
35
- <div class="alert alert-soft alert-warning mt-4 block">
36
- <strong>Send-only account limitation:</strong> Messages sent through this app cannot be tracked by EmailEngine.
37
- The Gmail API modifies the Message-ID header when sending emails, and without read permissions,
38
- EmailEngine cannot resolve the new Message-ID assigned by Gmail. Delivery status and bounce
39
- notifications may not be accurately associated with the sent message.
40
- </div>
41
- {{/if}}
42
-
43
23
  <div>Read about setting up the OAuth2 project in Google Cloud from
44
24
 
45
25
  {{#if baseScopesImap}}
@@ -68,9 +48,9 @@
68
48
  {{/if}}
69
49
 
70
50
  {{#if baseScopesApi}}
71
- <div>Your OAuth2 project <strong>must</strong> have the following scopes enabled:</div>
51
+ <div>The service account's domain-wide delegation <strong>must</strong> list the following scopes:</div>
72
52
  <ul class="list-disc ps-6 my-2">
73
- <li><code>"https://www.googleapis.com/auth/gmail.modify"</code></li>
53
+ {{> gmail_api_scopes}}
74
54
  </ul>
75
55
  {{/if}}
76
56
 
@@ -142,3 +122,14 @@
142
122
  available for your <a href="https://oauth.mail.ru/app/" target="_blank" rel="noopener noreferrer"
143
123
  referrerpolicy="no-referrer" class="link link-animated">OAuth2 apps</a> by default.</div>
144
124
  {{/if}}
125
+
126
+ {{!-- A send-only app is only ever an API-based Gmail app, whichever of the two providers it is, so this
127
+ needs no provider guard - see isSendOnlyGmailApp() in lib/oauth/scope-checker.js. --}}
128
+ {{#if isSendOnlyGmail}}
129
+ <div class="alert alert-soft alert-warning mt-4 block">
130
+ <strong>Send-only account limitation:</strong> Messages sent through this app cannot be tracked by EmailEngine.
131
+ The Gmail API modifies the Message-ID header when sending emails, and without read permissions,
132
+ EmailEngine cannot resolve the new Message-ID assigned by Gmail. Delivery status and bounce
133
+ notifications may not be accurately associated with the sent message.
134
+ </div>
135
+ {{/if}}
package/workers/api.js CHANGED
@@ -8,7 +8,8 @@ const logger = require('../lib/logger');
8
8
  const Path = require('path');
9
9
  const Gettext = require('@postalsys/gettext');
10
10
  const { loadTranslations, gt, joiLocales, locales } = require('../lib/translations');
11
- const { accountStateLabel, formatServerState, identityErrorView, isClientError } = require('../lib/ui-routes/route-helpers');
11
+ const { accountStateLabel, formatServerState, identityErrorView, workspaceErrorView, isClientError } = require('../lib/ui-routes/route-helpers');
12
+ const { boundRouteBinding } = require('../lib/api-routes/account-binding');
12
13
  const util = require('util');
13
14
  const { webhooks: Webhooks } = require('../lib/webhooks');
14
15
  const { lists } = require('../lib/lists');
@@ -133,7 +134,7 @@ const SUPPORTED_LOCALES = locales.map(locale => locale.locale);
133
134
 
134
135
  const FLAG_SORT_ORDER = ['\\Inbox', '\\Flagged', '\\Sent', '\\Drafts', '\\All', '\\Archive', '\\Junk', '\\Trash'];
135
136
 
136
- const { GMAIL_SCOPES, OPENID_SCOPES } = require('../lib/oauth/gmail');
137
+ const { GMAIL_SCOPES, OPENID_SCOPES, workspaceDomainOf } = require('../lib/oauth/gmail');
137
138
  const { MAIL_RU_SCOPES } = require('../lib/oauth/mail-ru');
138
139
 
139
140
  const GMAIL_SCOPE_DESCRIPTIONS = {
@@ -1007,25 +1008,23 @@ const init = async () => {
1007
1008
 
1008
1009
  let accountIdSource;
1009
1010
 
1010
- // allow specific routes that have an account component but not in the URL params section
1011
- switch (request.route.path) {
1012
- // The two listings that take the account as a query argument. `/v1/tokens` is
1013
- // here because it replaced GET /v1/tokens/account/{account}, which carried the
1014
- // account in the path and so reached a bound token's own tokens through the
1015
- // default branch below - as its deprecated alias registration still does.
1016
- // Both stay under the same rule as everything else: the argument has to name the
1017
- // token's own account, and omitting it still refuses, because a bound credential
1018
- // must not enumerate the instance.
1019
- case '/v1/templates':
1020
- case '/v1/tokens':
1021
- switch (request.method) {
1022
- case 'get':
1023
- accountIdSource = queryAccount;
1024
- break;
1025
- }
1011
+ // Routes that carry an account component somewhere other than their URL params, named
1012
+ // by lib/api-routes/account-binding.js. The table is shared with the MCP tool registry,
1013
+ // which has to advertise exactly the tools a bound credential can actually call; the
1014
+ // resolution of each kind stays here, where the request is.
1015
+ switch (boundRouteBinding(request.method, request.route.path)) {
1016
+ case 'query':
1017
+ // `/v1/tokens` is in the table because it replaced
1018
+ // GET /v1/tokens/account/{account}, which carried the account in the path and so
1019
+ // reached a bound token's own tokens through the default branch below - as its
1020
+ // deprecated alias registration still does. Both stay under the same rule as
1021
+ // everything else: the argument has to name the token's own account, and
1022
+ // omitting it still refuses, because a bound credential must not enumerate the
1023
+ // instance.
1024
+ accountIdSource = queryAccount;
1026
1025
  break;
1027
1026
 
1028
- case '/v1/templates/template/{template}': {
1027
+ case 'record': {
1029
1028
  let isAccountTemplate =
1030
1029
  request.params.template && (await redis.sismember(`${REDIS_PREFIX}tpl:${tokenData.account}:i`, request.params.template));
1031
1030
  if (isAccountTemplate) {
@@ -1034,15 +1033,10 @@ const init = async () => {
1034
1033
  break;
1035
1034
  }
1036
1035
 
1037
- case '/v1/templates/template': {
1038
- switch (request.method) {
1039
- case 'post':
1040
- request.app.enforceAccount = tokenData.account;
1041
- accountIdSource = tokenData.account;
1042
- break;
1043
- }
1036
+ case 'token':
1037
+ request.app.enforceAccount = tokenData.account;
1038
+ accountIdSource = tokenData.account;
1044
1039
  break;
1045
- }
1046
1040
 
1047
1041
  default:
1048
1042
  accountIdSource = request.params && request.params.account;
@@ -2336,6 +2330,11 @@ const init = async () => {
2336
2330
  // fills this in; one that does not leaves it empty, and an empty list fails the check closed.
2337
2331
  const providerIdentities = [];
2338
2332
 
2333
+ // The Workspace or Cloud organization domain the provider reported, for an application
2334
+ // restricted to Google Workspace accounts. Only the Gmail case fills it in; the
2335
+ // restriction is a Google setting and no other provider has the notion.
2336
+ let workspaceDomain = null;
2337
+
2339
2338
  // The token to revoke if the setup is rejected after the code was already exchanged, set by
2340
2339
  // each provider case because the token response is scoped to the switch. Prefer the refresh
2341
2340
  // token: revoking either invalidates the grant, but the access token may already be expired.
@@ -2405,6 +2404,10 @@ const init = async () => {
2405
2404
  request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
2406
2405
  }
2407
2406
 
2407
+ // Back channel, so this is the claim the restriction can actually be enforced on;
2408
+ // the hd argument on the authorization URL only filters the chooser Google shows
2409
+ workspaceDomain = workspaceDomainOf(idTokenPayload);
2410
+
2408
2411
  // If ID token didn't provide email, fall back to Gmail API profile endpoint
2409
2412
  // This should rarely happen since we now request openid/email/profile scopes
2410
2413
  if (!userEmail) {
@@ -2653,6 +2656,38 @@ const init = async () => {
2653
2656
  blobExpectation: pendingSetupExpectation(accountData, accountMeta)
2654
2657
  });
2655
2658
 
2659
+ // "Accept only Google Workspace accounts" used to be advisory: generateAuthUrl() sets hd=*,
2660
+ // which filters the account chooser Google shows and nothing else, so a link assembled
2661
+ // without that argument - or a user who switches account inside the chooser - completed the
2662
+ // setup with a consumer account. The hosted-domain claim of the ID token is checked here
2663
+ // instead, and a token that names no domain is refused rather than trusted: for the Gmail
2664
+ // provider the OpenID scopes are always requested (GmailOauth's constructor adds them), so
2665
+ // a missing claim means the account has no Workspace domain, not that the claim was never
2666
+ // asked for.
2667
+ if (oauth2App.googleWorkspaceAccounts && oauth2App.provider === 'gmail' && !workspaceDomain) {
2668
+ request.logger.warn({
2669
+ msg: 'OAuth2 sign-in used a personal account for a Workspace-only application',
2670
+ account: accountData.account,
2671
+ provider: oauth2App.provider
2672
+ });
2673
+
2674
+ // The code was already exchanged, so we are holding a grant we will never use. Best
2675
+ // effort, and the same duck-typing guard as the identity mismatch below.
2676
+ if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
2677
+ try {
2678
+ await oAuth2Client.revokeToken(grantToken);
2679
+ } catch (err) {
2680
+ request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after a Workspace check', err });
2681
+ }
2682
+ }
2683
+
2684
+ // select_account for the same reason as the identity mismatch: they are signed in to the
2685
+ // account that just failed, and without it Google would hand back the same one
2686
+ const retryUrl = await startOAuthRetry(accountData.email, 'select_account consent');
2687
+
2688
+ return workspaceErrorView(request, h, { actualEmail: providerIdentities[0], retryUrl });
2689
+ }
2690
+
2656
2691
  if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
2657
2692
  // Neither address is logged: the expectation and the authenticated identity both belong to
2658
2693
  // the end user, and this line is the one record of a failed attempt. Note the provider
package/workers/imap.js CHANGED
@@ -446,7 +446,7 @@ class ConnectionHandler {
446
446
  }
447
447
  }
448
448
 
449
- async syncConnection(account) {
449
+ async syncConnection(account, opts = {}) {
450
450
  logger.info({ msg: 'Account sync requested', account });
451
451
  if (this.accounts.has(account)) {
452
452
  let accountObject = this.accounts.get(account);
@@ -458,7 +458,8 @@ class ConnectionHandler {
458
458
  msg: 'Account sync requested'
459
459
  });
460
460
 
461
- await accountObject.connection.syncMailboxes();
461
+ // only the Graph client reads the options, the others sync their own way
462
+ await accountObject.connection.syncMailboxes(opts);
462
463
 
463
464
  return true;
464
465
  }
@@ -994,10 +995,12 @@ class ConnectionHandler {
994
995
  await this.closeConnections();
995
996
  return true;
996
997
 
998
+ case 'sync':
999
+ return await this.syncConnection(message.account, { since: message.since });
1000
+
997
1001
  case 'delete':
998
1002
  case 'unassign':
999
1003
  case 'update':
1000
- case 'sync':
1001
1004
  case 'pause':
1002
1005
  case 'resume':
1003
1006
  case 'reconnect':
package/workers/submit.js CHANGED
@@ -42,7 +42,7 @@ const SUBMIT_QC = (readEnvValue('EENGINE_SUBMIT_QC') && Number(readEnvValue('EEN
42
42
 
43
43
  const SUBMIT_DELAY = getDuration(readEnvValue('EENGINE_SUBMIT_DELAY') || config.submitDelay) || null;
44
44
 
45
- const { shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt } = require('../lib/delivery-error');
45
+ const { shouldDiscardJob, willBeFinalAttempt, isFinalFailedAttempt, nextAttemptWhileProcessing } = require('../lib/delivery-error');
46
46
  const { isAlreadySent } = require('../lib/submit-progress');
47
47
  const { packRpcError, unpackRpcError } = require('../lib/worker-rpc-error');
48
48
 
@@ -216,10 +216,7 @@ const submitWorker = new Worker(
216
216
  // ignore
217
217
  }
218
218
 
219
- let backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
220
- // job.attemptsMade is not yet incremented for the ongoing attempt, so the
221
- // next retry (if this attempt fails) is delayed by 2^attemptsMade * base
222
- let nextAttempt = !willBeFinalAttempt(job) ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade) * backoffDelay) : false;
219
+ let nextAttempt = nextAttemptWhileProcessing(job);
223
220
 
224
221
  queueEntry.job = {
225
222
  id: job.id,