emailengine-app 2.81.2 → 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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -17,8 +17,9 @@ const getSecret = require('../get-secret');
17
17
  const { Account } = require('../account');
18
18
  const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
19
19
  const { verifyOAuth2App } = require('../oauth/verify-app');
20
- const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema } = require('../schemas');
21
- const { throwAsBoom, adminUrl, submittedValues } = require('./route-helpers');
20
+ const { isSendOnlyGmailApp } = require('../oauth/scope-checker');
21
+ const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema, formBoolean } = require('../schemas');
22
+ const { throwAsBoom, adminUrl, submittedValues, windowedPageLinks } = require('./route-helpers');
22
23
 
23
24
  const { DEFAULT_PAGE_SIZE } = consts;
24
25
 
@@ -62,6 +63,75 @@ function init(args) {
62
63
  };
63
64
  }
64
65
 
66
+ /**
67
+ * View context for re-rendering the new or edit OAuth2 app form after a failed save, from the
68
+ * submitted fields. One function for the handler's catch and the validation failAction of both
69
+ * forms, so the four copies cannot drift again: the secret fields are blanked (the edit page
70
+ * never echoes a stored secret, and the API masks them), and on the edit form the
71
+ * authentication method stays locked once the app has one.
72
+ *
73
+ * @param {Object} request - the Hapi request carrying the submitted payload
74
+ * @param {Object} [appData] - the stored app when editing, absent when creating
75
+ * @param {Object} [errors] - field errors to show
76
+ * @returns {Promise<Object>}
77
+ */
78
+ async function appFormErrorContext(request, appData, errors) {
79
+ const payload = request.payload;
80
+ const provider = appData ? appData.provider : payload.provider;
81
+ const providerData = appData ? oauth2ProviderData(appData.provider, appData.cloud) : oauth2ProviderData(provider);
82
+
83
+ const serviceUrl = await settings.get('serviceUrl');
84
+ let defaultRedirectUrl = `${serviceUrl}/oauth`;
85
+ if (provider === 'outlook') {
86
+ defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
87
+ }
88
+
89
+ const context = {
90
+ pageTitle: 'OAuth2 Apps',
91
+ menuOauthApps: true,
92
+
93
+ [`active${providerData.caseName}`]: true,
94
+ providerData,
95
+ defaultRedirectUrl,
96
+
97
+ pubSubApps: await getPubSubAppsForSelect(payload.pubSubApp),
98
+
99
+ baseScopesApi: payload.baseScopes === 'api',
100
+ baseScopesImap: payload.baseScopes === 'imap' || !payload.baseScopes,
101
+ baseScopesPubsub: payload.baseScopes === 'pubsub',
102
+
103
+ azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
104
+ entry.selected = payload.cloud === entry.id;
105
+ return entry;
106
+ }),
107
+
108
+ // The submitted fields, not the stored app: without them the new-app form loses its
109
+ // provider on a validation error and the next submit is bounced to /admin
110
+ values: submittedValues(request, 'clientSecret', 'serviceKey', 'externalAccount'),
111
+
112
+ authorityCommon: payload.authority === 'common',
113
+ authorityOrganizations: payload.authority === 'organizations',
114
+ authorityConsumers: payload.authority === 'consumers',
115
+ authorityTenant: payload.authority === 'tenant',
116
+
117
+ errors
118
+ };
119
+
120
+ if (appData) {
121
+ Object.assign(context, {
122
+ appData,
123
+ hasClientSecret: !!appData.clientSecret,
124
+ hasServiceKey: !!appData.serviceKey,
125
+ hasExternalAccount: !!appData.externalAccount,
126
+ ...authMethodContext(appData.authMethod, !!appData.serviceKey || !!appData.externalAccount)
127
+ });
128
+ } else {
129
+ Object.assign(context, { actionCreate: true, ...authMethodContext(payload.authMethod) });
130
+ }
131
+
132
+ return context;
133
+ }
134
+
65
135
  /**
66
136
  * Fetch the list of Pub/Sub apps and mark the one matching selectedId as selected.
67
137
  * Returns the apps array ready for template rendering.
@@ -148,11 +218,7 @@ function init(args) {
148
218
  nextPage,
149
219
  prevPage,
150
220
  firstPage: data.page === 0,
151
- pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
152
- url: getPagingUrl(i + 1, request.query.query),
153
- title: i + 1,
154
- active: i === data.page
155
- })),
221
+ pageLinks: windowedPageLinks(data.pages, data.page, page => getPagingUrl(page, request.query.query)),
156
222
 
157
223
  apps: data.apps
158
224
  },
@@ -258,11 +324,7 @@ function init(args) {
258
324
  nextPage,
259
325
  prevPage,
260
326
  firstPage: data.page === 0,
261
- pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
262
- url: getPagingUrl(i + 1),
263
- title: i + 1,
264
- active: i === data.page
265
- })),
327
+ pageLinks: windowedPageLinks(data.pages, data.page, getPagingUrl),
266
328
 
267
329
  apps: data.apps,
268
330
 
@@ -372,20 +434,8 @@ function init(args) {
372
434
  disabledScopes.Gmail_Modify = true;
373
435
  }
374
436
 
375
- // Detect send-only Gmail configuration
376
- let isSendOnlyGmail = false;
377
- if (app.provider === 'gmail' && app.baseScopes === 'api') {
378
- // Build scope list from extraScopes (short form or full URLs)
379
- const scopes = (app.extraScopes || []).map(scope => (scope.startsWith('https://') ? scope : `https://www.googleapis.com/auth/${scope}`));
380
-
381
- // Use Account class helper to check scopes - no need to create full Account instance
382
- const accountHelper = new Account({ redis, secret: await getSecret() });
383
- const { hasSendScope, hasReadScope } = accountHelper.checkAccountScopes('gmail', scopes);
384
-
385
- if (hasSendScope && !hasReadScope) {
386
- isSendOnlyGmail = true;
387
- }
388
- }
437
+ // Covers both Gmail providers: the mode is decided by baseScopes, not by the provider
438
+ let isSendOnlyGmail = isSendOnlyGmailApp(app);
389
439
 
390
440
  if (app.pubSubApp) {
391
441
  let pubSubApp = await oauth2Apps.get(app.pubSubApp);
@@ -601,7 +651,7 @@ function init(args) {
601
651
  payload: Joi.object({
602
652
  crumb: Joi.string().optional(),
603
653
  account: Joi.string().trim().empty('').max(256).optional(),
604
- testConnection: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(true)
654
+ testConnection: formBoolean().default(true)
605
655
  })
606
656
  }
607
657
  }
@@ -720,58 +770,12 @@ function init(args) {
720
770
  await request.flash({ type: 'danger', message: `Couldn't register OAuth2 app. Try again.` });
721
771
  request.logger.error({ msg: 'Failed to register OAuth2 app', err });
722
772
 
723
- let { provider, baseScopes } = request.payload;
773
+ let { provider } = request.payload;
724
774
  if (!provider || !OAUTH_PROVIDERS.hasOwnProperty(provider)) {
725
775
  return h.redirect('/admin');
726
776
  }
727
777
 
728
- let providerData = oauth2ProviderData(provider);
729
-
730
- let serviceUrl = await settings.get('serviceUrl');
731
- let defaultRedirectUrl = `${serviceUrl}/oauth`;
732
- if (provider === 'outlook') {
733
- defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
734
- }
735
-
736
- return h.view(
737
- 'config/oauth/new',
738
- {
739
- pageTitle: 'OAuth2 Apps',
740
- menuOauthApps: true,
741
-
742
- actionCreate: true,
743
-
744
- [`active${providerData.caseName}`]: true,
745
- providerData,
746
- defaultRedirectUrl,
747
-
748
- pubSubApps: await getPubSubAppsForSelect(request.payload.pubSubApp),
749
-
750
- baseScopesApi: baseScopes === 'api',
751
- baseScopesImap: baseScopes === 'imap' || !baseScopes,
752
- baseScopesPubsub: baseScopes === 'pubsub',
753
-
754
- ...authMethodContext(request.payload.authMethod),
755
-
756
- azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
757
- entry.selected = request.payload.cloud === entry.id;
758
- return entry;
759
- }),
760
-
761
- // The submitted fields, not the stored app: without them the new-app form
762
- // loses its provider on a validation error and the next submit is bounced
763
- // to /admin
764
- values: submittedValues(request, 'clientSecret', 'serviceKey'),
765
-
766
- authorityCommon: request.payload.authority === 'common',
767
- authorityOrganizations: request.payload.authority === 'organizations',
768
- authorityConsumers: request.payload.authority === 'consumers',
769
- authorityTenant: request.payload.authority === 'tenant'
770
- },
771
- {
772
- layout: 'app'
773
- }
774
- );
778
+ return h.view('config/oauth/new', await appFormErrorContext(request, null, err.details), { layout: 'app' });
775
779
  }
776
780
  },
777
781
  options: {
@@ -796,59 +800,12 @@ function init(args) {
796
800
  await request.flash({ type: 'danger', message: `Couldn't register OAuth2 app. Try again.` });
797
801
  request.logger.debug({ msg: 'Failed to register OAuth2 app', err });
798
802
 
799
- let { provider, baseScopes } = request.payload;
803
+ let { provider } = request.payload;
800
804
  if (!provider || !OAUTH_PROVIDERS.hasOwnProperty(provider)) {
801
805
  return h.redirect('/admin').takeover();
802
806
  }
803
807
 
804
- let providerData = oauth2ProviderData(provider);
805
-
806
- let serviceUrl = await settings.get('serviceUrl');
807
- let defaultRedirectUrl = `${serviceUrl}/oauth`;
808
- if (provider === 'outlook') {
809
- defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
810
- }
811
-
812
- return h
813
- .view(
814
- 'config/oauth/new',
815
- {
816
- pageTitle: 'OAuth2 Apps',
817
- menuOauthApps: true,
818
-
819
- actionCreate: true,
820
-
821
- [`active${providerData.caseName}`]: true,
822
- providerData,
823
- defaultRedirectUrl,
824
-
825
- pubSubApps: await getPubSubAppsForSelect(request.payload.pubSubApp),
826
-
827
- baseScopesApi: baseScopes === 'api',
828
- baseScopesImap: baseScopes === 'imap' || !baseScopes,
829
- baseScopesPubsub: baseScopes === 'pubsub',
830
-
831
- ...authMethodContext(request.payload.authMethod),
832
-
833
- azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
834
- entry.selected = request.payload.cloud === entry.id;
835
- return entry;
836
- }),
837
-
838
- values: submittedValues(request, 'clientSecret', 'serviceKey'),
839
-
840
- authorityCommon: request.payload.authority === 'common',
841
- authorityOrganizations: request.payload.authority === 'organizations',
842
- authorityConsumers: request.payload.authority === 'consumers',
843
- authorityTenant: request.payload.authority === 'tenant',
844
-
845
- errors
846
- },
847
- {
848
- layout: 'app'
849
- }
850
- )
851
- .takeover();
808
+ return h.view('config/oauth/new', await appFormErrorContext(request, null, errors), { layout: 'app' }).takeover();
852
809
  },
853
810
 
854
811
  payload: Joi.object(oauthCreateSchema).tailor('web')
@@ -986,53 +943,7 @@ function init(args) {
986
943
  await request.flash({ type: 'danger', message: `Couldn't save OAuth2 app. Try again.` });
987
944
  request.logger.error({ msg: 'Failed to update OAuth2 app', app: request.payload.app, err });
988
945
 
989
- let providerData = oauth2ProviderData(appData.provider, appData.cloud);
990
-
991
- let serviceUrl = await settings.get('serviceUrl');
992
- let defaultRedirectUrl = `${serviceUrl}/oauth`;
993
- if (appData.provider === 'outlook') {
994
- defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
995
- }
996
-
997
- return h.view(
998
- 'config/oauth/edit',
999
- {
1000
- pageTitle: 'OAuth2 Apps',
1001
- menuOauthApps: true,
1002
-
1003
- [`active${providerData.caseName}`]: true,
1004
- providerData,
1005
- defaultRedirectUrl,
1006
- appData,
1007
-
1008
- hasClientSecret: !!appData.clientSecret,
1009
- hasServiceKey: !!appData.serviceKey,
1010
- hasExternalAccount: !!appData.externalAccount,
1011
-
1012
- ...authMethodContext(appData.authMethod, !!appData.serviceKey || !!appData.externalAccount),
1013
-
1014
- pubSubApps: await getPubSubAppsForSelect(request.payload.pubSubApp),
1015
-
1016
- baseScopesApi: request.payload.baseScopes === 'api',
1017
- baseScopesImap: request.payload.baseScopes === 'imap' || !request.payload.baseScopes,
1018
- baseScopesPubsub: request.payload.baseScopes === 'pubsub',
1019
-
1020
- azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
1021
- entry.selected = request.payload.cloud === entry.id;
1022
- return entry;
1023
- }),
1024
-
1025
- values: submittedValues(request, 'clientSecret', 'serviceKey'),
1026
-
1027
- authorityCommon: request.payload.authority === 'common',
1028
- authorityOrganizations: request.payload.authority === 'organizations',
1029
- authorityConsumers: request.payload.authority === 'consumers',
1030
- authorityTenant: request.payload.authority === 'tenant'
1031
- },
1032
- {
1033
- layout: 'app'
1034
- }
1035
- );
946
+ return h.view('config/oauth/edit', await appFormErrorContext(request, appData, err.details), { layout: 'app' });
1036
947
  }
1037
948
  },
1038
949
  options: {
@@ -1064,63 +975,7 @@ function init(args) {
1064
975
  await request.flash({ type: 'danger', message: `Couldn't save OAuth2 app. Try again.` });
1065
976
  request.logger.debug({ msg: 'Failed to update OAuth2 app', err });
1066
977
 
1067
- let { provider } = request.payload;
1068
- if (!provider || !OAUTH_PROVIDERS.hasOwnProperty(provider)) {
1069
- return h.redirect('/admin').takeover();
1070
- }
1071
-
1072
- let providerData = oauth2ProviderData(provider);
1073
-
1074
- let serviceUrl = await settings.get('serviceUrl');
1075
- let defaultRedirectUrl = `${serviceUrl}/oauth`;
1076
- if (provider === 'outlook') {
1077
- defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
1078
- }
1079
-
1080
- return h
1081
- .view(
1082
- 'config/oauth/edit',
1083
- {
1084
- pageTitle: 'OAuth2 Apps',
1085
- menuOauthApps: true,
1086
-
1087
- [`active${providerData.caseName}`]: true,
1088
- providerData,
1089
- defaultRedirectUrl,
1090
-
1091
- appData,
1092
-
1093
- hasClientSecret: !!appData.clientSecret,
1094
- hasServiceKey: !!appData.serviceKey,
1095
- hasExternalAccount: !!appData.externalAccount,
1096
-
1097
- ...authMethodContext(request.payload.authMethod),
1098
-
1099
- pubSubApps: await getPubSubAppsForSelect(request.payload.pubSubApp),
1100
-
1101
- baseScopesApi: request.payload.baseScopes === 'api',
1102
- baseScopesImap: request.payload.baseScopes === 'imap' || !request.payload.baseScopes,
1103
- baseScopesPubsub: request.payload.baseScopes === 'pubsub',
1104
-
1105
- azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
1106
- entry.selected = request.payload.cloud === entry.id;
1107
- return entry;
1108
- }),
1109
-
1110
- values: submittedValues(request, 'clientSecret', 'serviceKey'),
1111
-
1112
- authorityCommon: request.payload.authority === 'common',
1113
- authorityOrganizations: request.payload.authority === 'organizations',
1114
- authorityConsumers: request.payload.authority === 'consumers',
1115
- authorityTenant: request.payload.authority === 'tenant',
1116
-
1117
- errors
1118
- },
1119
- {
1120
- layout: 'app'
1121
- }
1122
- )
1123
- .takeover();
978
+ return h.view('config/oauth/edit', await appFormErrorContext(request, appData, errors), { layout: 'app' }).takeover();
1124
979
  },
1125
980
 
1126
981
  payload: Joi.object(oauthUpdateSchema)
@@ -16,7 +16,6 @@ const pathlib = require('path');
16
16
  const psl = require('psl');
17
17
  const handlebars = require('handlebars');
18
18
 
19
- const settings = require('../settings');
20
19
  const { redis } = require('../db');
21
20
  const { toolGrants } = require('../mcp/tools');
22
21
  const { Account, accountsExist, accountSummary, isAuthFailureDisabled, isAccessTokenInvalidated } = require('../account');
@@ -24,26 +23,6 @@ const { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
24
23
  const { oauth2ProviderData } = require('../oauth2-apps');
25
24
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
26
25
 
27
- // Fallback model list, shown until the first successful "Refresh Models" call
28
- // replaces it with the models actually available on the configured endpoint
29
- // (stored in the openAiModels setting)
30
- const OPEN_AI_MODELS = [
31
- {
32
- name: 'GPT-5 Mini',
33
- id: 'gpt-5-mini'
34
- },
35
-
36
- {
37
- name: 'GPT-5',
38
- id: 'gpt-5'
39
- },
40
-
41
- {
42
- name: 'GPT-5 Nano',
43
- id: 'gpt-5-nano'
44
- }
45
- ];
46
-
47
26
  // Partials a page renders again after it has loaded: the delivery-test results and the address
48
27
  // list after an IP rescan. They used to be shipped to the browser as source and compiled there,
49
28
  // which runs `new Function` and would need 'unsafe-eval' in the Content-Security-Policy the
@@ -62,22 +41,6 @@ const compiledFragments = {
62
41
  testSend: handlebars.compile(fs.readFileSync(pathlib.join(__dirname, '..', '..', 'views', 'partials', 'test_send.hbs'), 'utf-8'), FRAGMENT_COMPILE_OPTIONS)
63
42
  };
64
43
 
65
- const getOpenAiModels = async (models, selectedModel) => {
66
- let modelList = (await settings.get('openAiModels')) || structuredClone(models);
67
-
68
- if (selectedModel && !modelList.find(model => model.id === selectedModel)) {
69
- modelList.unshift({
70
- name: selectedModel,
71
- id: selectedModel
72
- });
73
- }
74
-
75
- return modelList.map(model => {
76
- model.selected = model.id === selectedModel;
77
- return model;
78
- });
79
- };
80
-
81
44
  // Ordered display table for account states: the single source for every UI surface
82
45
  // that lists states side by side (the accounts-page filter dropdown, the dashboard
83
46
  // state chips). Unlike accountStateLabel below - which intentionally merges the two
@@ -320,6 +283,7 @@ function formatServerState(state, payload) {
320
283
  }
321
284
  }
322
285
 
286
+ // Example message payloads for the AI pre-processing filter editor, dated now so they read as fresh mail
323
287
  async function getExampleDocumentsPayloads() {
324
288
  let date = new Date().toISOString();
325
289
 
@@ -386,33 +350,32 @@ function jsonErrorPayload(err) {
386
350
  return { success: false, error: err.code || 'Error', message: err.message };
387
351
  }
388
352
 
389
- // The "wrong account" page, shown when a setup link pinned to one address is completed as another.
390
- // Rendered from both arms of the hosted form - the OAuth2 callback in workers/api.js and the IMAP arm in
391
- // ./account-routes.js - which live in different workers, so the view name, the layout and the refusal
392
- // status are kept here rather than written out twice. Only `retryUrl` is arm-specific: the OAuth arm
393
- // sends the user back to the provider, the IMAP arm back to the form.
394
- //
395
- // 403 rather than the 200 that the sibling views/oauth-scope-error.hbs returns: this is a refused
396
- // request, the surrounding refusals in the same flow already answer 403, and both call sites are plain
397
- // form navigations, so the browser still renders the page.
398
- function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl }) {
353
+ // The refusal pages of the hosted setup flow, where the mailbox owner made a correctable choice and is
354
+ // given a way back (`retryUrl`) rather than being bounced to the calling application. Rendered from both
355
+ // arms of the form - the OAuth2 callback in workers/api.js and the IMAP arm in ./account-routes.js, in
356
+ // different workers - so the view name, the layout and the refusal status are decided here. 403 rather
357
+ // than the 200 that the sibling views/oauth-scope-error.hbs returns: these are refused requests, the
358
+ // surrounding refusals in the same flow already answer 403, and every call site is a plain form
359
+ // navigation, so the browser still renders the page.
360
+ function setupRefusalView(request, h, view, context) {
399
361
  return h
400
- .view(
401
- 'account-identity-error',
402
- {
403
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
404
- templateLocale: request.app.locale,
405
- expectedEmail,
406
- actualEmail,
407
- retryUrl
408
- },
409
- {
410
- layout: 'public'
411
- }
412
- )
362
+ .view(view, Object.assign({ pageTitleFull: request.app.gt.gettext('Email Account Setup'), templateLocale: request.app.locale }, context), {
363
+ layout: 'public'
364
+ })
413
365
  .code(403);
414
366
  }
415
367
 
368
+ // "Wrong account": a setup link pinned to one address was completed as another. Only `retryUrl` is
369
+ // arm-specific - the OAuth arm sends the user back to the provider, the IMAP arm back to the form.
370
+ function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl }) {
371
+ return setupRefusalView(request, h, 'account-identity-error', { expectedEmail, actualEmail, retryUrl });
372
+ }
373
+
374
+ // "Work account required": the application takes only Workspace accounts and a personal one signed in.
375
+ function workspaceErrorView(request, h, { actualEmail, retryUrl }) {
376
+ return setupRefusalView(request, h, 'account-workspace-error', { actualEmail, retryUrl });
377
+ }
378
+
416
379
  // View-model for the ui/pagination partial: prev/next URLs plus the numbered page links.
417
380
  // basePath is the URL path without a query string (leading slash optional, matching the
418
381
  // `new URL(path, base)` convention the route modules already use); data is a listing
@@ -446,6 +409,43 @@ function submittedValues(request, ...secretFields) {
446
409
  return values;
447
410
  }
448
411
 
412
+ // Page links shown on either side of the current page, in addition to the first and the last
413
+ const PAGE_LINK_RADIUS = 2;
414
+
415
+ /**
416
+ * The numbered page links of a listing, windowed: the first and last page, and PAGE_LINK_RADIUS
417
+ * pages either side of the current one, with a `gap` entry where pages are left out. A link per
418
+ * page rendered five thousand buttons for an instance with 100k accounts.
419
+ *
420
+ * @param {number} pages - total page count
421
+ * @param {number} page - zero-based current page
422
+ * @param {Function} urlFor - one-based page number to URL
423
+ * @returns {Array<Object>} entries of { url, title, active } or { gap: true }
424
+ */
425
+ function windowedPageLinks(pages, page, urlFor) {
426
+ const total = Math.max(Number(pages) || 0, 1);
427
+ const shown = [...new Set([0, total - 1, ...Array.from({ length: PAGE_LINK_RADIUS * 2 + 1 }, (z, i) => page - PAGE_LINK_RADIUS + i)])]
428
+ .filter(i => i >= 0 && i < total)
429
+ .sort((a, b) => a - b);
430
+
431
+ const pageLink = i => ({ url: urlFor(i + 1), title: i + 1, active: i === page });
432
+
433
+ const links = [];
434
+ let previous = -1;
435
+ for (const i of shown) {
436
+ if (i - previous === 2) {
437
+ // a gap would hide a single page, so show that page instead. It is never the current
438
+ // one: that page is always inside the window, so it is in `shown` itself
439
+ links.push(pageLink(i - 1));
440
+ } else if (i - previous > 2) {
441
+ links.push({ gap: true });
442
+ }
443
+ links.push(pageLink(i));
444
+ previous = i;
445
+ }
446
+ return links;
447
+ }
448
+
449
449
  function buildPagingView(basePath, data, query) {
450
450
  const getPagingUrl = page => {
451
451
  let url = new URL(basePath, 'http://localhost');
@@ -466,11 +466,7 @@ function buildPagingView(basePath, data, query) {
466
466
  nextPage: data.pages > data.page + 1 ? getPagingUrl(data.page + 2) : false,
467
467
  prevPage: data.page > 0 ? getPagingUrl(data.page) : false,
468
468
  firstPage: data.page === 0,
469
- pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
470
- url: getPagingUrl(i + 1),
471
- title: i + 1,
472
- active: i === data.page
473
- }))
469
+ pageLinks: windowedPageLinks(data.pages, data.page, getPagingUrl)
474
470
  };
475
471
  }
476
472
 
@@ -608,9 +604,8 @@ module.exports = {
608
604
  accountPickerEntry,
609
605
  accountPickerSelection,
610
606
  identityErrorView,
611
- OPEN_AI_MODELS,
607
+ workspaceErrorView,
612
608
  compiledFragments,
613
- getOpenAiModels,
614
609
  closedAfterConnectMessage,
615
610
  accountStateLabel,
616
611
  ACCOUNT_STATE_DISPLAY,
@@ -622,6 +617,7 @@ module.exports = {
622
617
  isClientError,
623
618
  authAwareLevel,
624
619
  buildPagingView,
620
+ windowedPageLinks,
625
621
  adminUrl,
626
622
  submittedValues
627
623
  };
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ const { SPECIAL_USE_PATH_TYPES } = require('../consts');
4
+
5
+ // The words the admin UI shows for each special-use folder override. The TYPES are not re-listed
6
+ // here: SPECIAL_USE_PATH_TYPES in lib/consts.js is the contract the IMAP client reads (it turns the
7
+ // list into the specialUseHints it passes to LIST) and the account schemas declare a field per entry,
8
+ // so a type added there reaches the form with it rather than needing a second edit.
9
+ //
10
+ // Split out of ./account-routes.js, which is at its size budget, and because this is page copy rather
11
+ // than routing: the same shape as ./ai-options.js next to it.
12
+ const SPECIAL_USE_PATH_LABELS = {
13
+ sent: { label: 'Sent Mail', description: 'Store copies of sent emails in this folder.' },
14
+ drafts: { label: 'Drafts', description: 'Treat this folder as the Drafts folder.' },
15
+ junk: { label: 'Junk', description: 'Treat this folder as the Junk folder.' },
16
+ trash: { label: 'Trash', description: 'Treat this folder as the Trash folder, where deleted messages are moved.' },
17
+ archive: { label: 'Archive', description: 'Treat this folder as the Archive folder.' }
18
+ };
19
+
20
+ /**
21
+ * The override fields as the edit form and the account page consume them: the account field name, the
22
+ * form input id and the words to show, in the order the two templates render them.
23
+ *
24
+ * `{ type, key, inputId, label, description }` per entry. The form renders one input per entry from
25
+ * `inputId`, its joi schema is generated per entry, and the update loop writes `key` onto the account
26
+ * - so the four of them cannot drift. Only `sentMailPath` was ever offered on the form, which is how
27
+ * the other four came to be settable over PUT /v1/account/{account} alone.
28
+ */
29
+ const SPECIAL_USE_PATH_FIELDS = SPECIAL_USE_PATH_TYPES.map(type =>
30
+ Object.assign({ type, key: `${type}MailPath`, inputId: `imap_${type}MailPath` }, SPECIAL_USE_PATH_LABELS[type])
31
+ );
32
+
33
+ module.exports = { SPECIAL_USE_PATH_FIELDS, SPECIAL_USE_PATH_LABELS };
@@ -123,7 +123,7 @@ function init(args) {
123
123
  recipient: email,
124
124
  messageId,
125
125
  listId,
126
- remoteAddress: request.info.remoteAddress,
126
+ remoteAddress: request.app.ip,
127
127
  userAgent: request.headers['user-agent']
128
128
  }
129
129
  });
@@ -139,7 +139,7 @@ function init(args) {
139
139
  source: 'form',
140
140
  reason: 'unsubscribe',
141
141
  messageId,
142
- remoteAddress: request.info.remoteAddress,
142
+ remoteAddress: request.app.ip,
143
143
  userAgent: request.headers['user-agent']
144
144
  });
145
145