emailengine-app 2.81.2 → 2.82.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 (204) hide show
  1. package/.ncurc.js +12 -11
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +27 -0
  4. package/Dockerfile +2 -0
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/expected-identity.js +1 -1
  13. package/lib/account-assignment.js +138 -1
  14. package/lib/account.js +254 -859
  15. package/lib/api-reference/index.js +2 -3
  16. package/lib/api-reference/schema-tree.js +53 -3
  17. package/lib/api-routes/account-routes.js +18 -29
  18. package/lib/api-routes/blocklist-routes.js +2 -2
  19. package/lib/api-routes/bull-board-routes.js +1 -6
  20. package/lib/api-routes/export-routes.js +2 -22
  21. package/lib/api-routes/gateway-routes.js +5 -14
  22. package/lib/api-routes/index.js +1 -13
  23. package/lib/api-routes/mailbox-routes.js +2 -7
  24. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  25. package/lib/api-routes/mcp-routes.js +7 -7
  26. package/lib/api-routes/message-routes.js +40 -235
  27. package/lib/api-routes/mint-bounds.js +110 -0
  28. package/lib/api-routes/oauth2-app-routes.js +23 -32
  29. package/lib/api-routes/operation-impact.js +1 -1
  30. package/lib/api-routes/outbox-routes.js +2 -2
  31. package/lib/api-routes/permission-map.js +1 -7
  32. package/lib/api-routes/route-helpers.js +11 -5
  33. package/lib/api-routes/settings-routes.js +19 -19
  34. package/lib/api-routes/stats-routes.js +1 -1
  35. package/lib/api-routes/submit-routes.js +17 -18
  36. package/lib/api-routes/template-routes.js +4 -9
  37. package/lib/api-routes/token-routes.js +27 -5
  38. package/lib/api-token-scheme.js +71 -0
  39. package/lib/arf-detect.js +33 -6
  40. package/lib/auth-token.js +44 -24
  41. package/lib/autodetect-imap-settings.js +163 -123
  42. package/lib/bounce-detect.js +25 -16
  43. package/lib/calendar-event.js +78 -0
  44. package/lib/consts.js +42 -5
  45. package/lib/create-imap-client.js +24 -0
  46. package/lib/db.js +76 -11
  47. package/lib/delivery-error.js +2 -1
  48. package/lib/egress-fetch.js +54 -3
  49. package/lib/egress-filter.js +11 -0
  50. package/lib/email-client/api-retry.js +147 -0
  51. package/lib/email-client/base-client.js +377 -523
  52. package/lib/email-client/gmail/gmail-api.js +38 -125
  53. package/lib/email-client/gmail/send-request.js +1 -1
  54. package/lib/email-client/gmail-client.js +76 -50
  55. package/lib/email-client/imap/mailbox.js +158 -324
  56. package/lib/email-client/imap/stale-view.js +109 -0
  57. package/lib/email-client/imap/subconnection.js +46 -9
  58. package/lib/email-client/imap/sync-operations.js +5 -37
  59. package/lib/email-client/imap-client.js +188 -64
  60. package/lib/email-client/message-builder.js +9 -14
  61. package/lib/email-client/notification-handler.js +5 -219
  62. package/lib/email-client/outlook/graph-api.js +147 -126
  63. package/lib/email-client/outlook/send-request.js +10 -4
  64. package/lib/email-client/outlook-client.js +194 -397
  65. package/lib/email-client/smtp-pool-manager.js +3 -2
  66. package/lib/encrypt.js +184 -19
  67. package/lib/enum-descriptions.js +1 -2
  68. package/lib/export.js +133 -39
  69. package/lib/gateway.js +20 -6
  70. package/lib/get-raw-email.js +26 -44
  71. package/lib/handlebars-helpers.js +31 -10
  72. package/lib/imap-proxy-auth.js +13 -29
  73. package/lib/imapproxy/imap-core/README.md +1 -0
  74. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  75. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  76. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  77. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  78. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  79. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  80. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  81. package/lib/imapproxy/imap-server.js +17 -177
  82. package/lib/imapproxy/proxy-handoff.js +235 -0
  83. package/lib/imapproxy/response-error.js +33 -0
  84. package/lib/imapproxy/upstream-client.js +2 -2
  85. package/lib/license-beacon.js +3 -9
  86. package/lib/llm-pre-process.js +182 -43
  87. package/lib/logger.js +1 -1
  88. package/lib/lua/ee-export-queue-add.lua +39 -0
  89. package/lib/lua/ee-get-idempotency.lua +15 -3
  90. package/lib/lua/ee-release-attempts.lua +23 -0
  91. package/lib/lua/ee-reserve-attempts.lua +42 -0
  92. package/lib/lua/h-set-bigger.lua +12 -2
  93. package/lib/lua/s-list-accounts.lua +6 -3
  94. package/lib/mcp/index.js +1 -2
  95. package/lib/mcp/listen.js +221 -18
  96. package/lib/mcp/oauth.js +44 -5
  97. package/lib/mcp/resources.js +8 -2
  98. package/lib/mcp/tools.js +13 -0
  99. package/lib/message-port-stream.js +64 -6
  100. package/lib/oauth/external-account-signer.js +16 -13
  101. package/lib/oauth/gmail.js +22 -20
  102. package/lib/oauth/outlook.js +19 -16
  103. package/lib/oauth/pubsub/google.js +38 -2
  104. package/lib/oauth/scope-checker.js +4 -7
  105. package/lib/oauth/verify-app.js +2 -2
  106. package/lib/oauth2-apps.js +139 -44
  107. package/lib/openapi/build-document.js +1 -1
  108. package/lib/openapi/joi-schema.js +78 -9
  109. package/lib/parse-message.js +21 -0
  110. package/lib/payload-examples-webhooks.json +4 -7
  111. package/lib/pbkdf2-phc.js +101 -0
  112. package/lib/privileged-settings.js +0 -14
  113. package/lib/rate-limit.js +54 -15
  114. package/lib/redis-scan-delete.js +56 -29
  115. package/lib/redis-url.js +3 -1
  116. package/lib/respawn-backoff.js +5 -4
  117. package/lib/response-stream.js +25 -4
  118. package/lib/rewrite-text-nodes.js +27 -40
  119. package/lib/routes-ui.js +0 -5
  120. package/lib/schemas.js +122 -242
  121. package/lib/sentry.js +21 -5
  122. package/lib/settings.js +58 -59
  123. package/lib/smtp-auth.js +6 -2
  124. package/lib/smtp-message-processor.js +28 -7
  125. package/lib/sso.js +7 -3
  126. package/lib/stream-encrypt.js +14 -13
  127. package/lib/swagger-options.js +3 -1
  128. package/lib/tls/provision.js +69 -3
  129. package/lib/tls/store.js +14 -1
  130. package/lib/tools.js +113 -52
  131. package/lib/totp.js +16 -1
  132. package/lib/ui-routes/account-routes.js +27 -63
  133. package/lib/ui-routes/admin-config-routes.js +111 -134
  134. package/lib/ui-routes/admin-entities-routes.js +101 -191
  135. package/lib/ui-routes/ai-options.js +104 -0
  136. package/lib/ui-routes/auth-routes.js +98 -18
  137. package/lib/ui-routes/export-routes.js +3 -23
  138. package/lib/ui-routes/internals-routes.js +12 -9
  139. package/lib/ui-routes/network-config-routes.js +8 -18
  140. package/lib/ui-routes/oauth-config-routes.js +80 -214
  141. package/lib/ui-routes/route-helpers.js +40 -44
  142. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  143. package/lib/utils/decode-headers.js +32 -5
  144. package/lib/utils/header-map.js +62 -1
  145. package/lib/utils/network.js +2 -0
  146. package/lib/web-safe-html.js +77 -4
  147. package/lib/webhook-request.js +9 -1
  148. package/lib/webhook-routing.js +27 -1
  149. package/lib/webhooks.js +120 -43
  150. package/lib/worker-rpc-error.js +43 -2
  151. package/list-generate.js +13 -2
  152. package/package.json +33 -41
  153. package/sbom.json +1 -1
  154. package/scripts/refresh-test-tokens.js +42 -14
  155. package/server.js +317 -289
  156. package/static/css/flyonui.css +1 -1
  157. package/static/css/src/app.tailwind.css +7 -8
  158. package/static/js/ee-client.js +145 -70
  159. package/static/js/ui.js +350 -154
  160. package/static/licenses.html +434 -1835
  161. package/translations/messages.pot +97 -97
  162. package/views/accounts/browse.hbs +10 -4
  163. package/views/config/ai.hbs +49 -41
  164. package/views/config/oauth/app.hbs +2 -1
  165. package/views/dashboard.hbs +18 -16
  166. package/views/layout/app.hbs +0 -22
  167. package/views/layout/login.hbs +2 -1
  168. package/views/partials/filter_editor_js.hbs +4 -3
  169. package/views/partials/side_menu.hbs +0 -4
  170. package/views/partials/ui/account-picker.hbs +6 -32
  171. package/views/partials/ui/model-picker.hbs +31 -0
  172. package/views/partials/ui/pagination.hbs +6 -1
  173. package/views/partials/ui/picker.hbs +47 -0
  174. package/views/unsubscribe.hbs +1 -1
  175. package/workers/api.js +20 -20
  176. package/workers/export.js +55 -60
  177. package/workers/imap.js +126 -46
  178. package/workers/submit.js +3 -1
  179. package/workers/webhooks.js +46 -27
  180. package/.githooks/pre-commit +0 -80
  181. package/.github/CODE_OF_CONDUCT.md +0 -76
  182. package/.github/contributing.md +0 -17
  183. package/.github/dependabot.yml +0 -22
  184. package/.github/docker-smoke-test.sh +0 -61
  185. package/.github/workflows/deploy.yml +0 -215
  186. package/.github/workflows/e2e.yml +0 -55
  187. package/.github/workflows/release.yaml +0 -217
  188. package/.github/workflows/test.yml +0 -307
  189. package/lib/api-routes/chat-routes.js +0 -535
  190. package/lib/document-store.js +0 -75
  191. package/lib/es.js +0 -757
  192. package/lib/generate-text-preview.js +0 -61
  193. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  194. package/lib/pre-process.js +0 -196
  195. package/lib/threads.js +0 -155
  196. package/lib/ui-routes/document-store-routes.js +0 -806
  197. package/playwright.config.js +0 -47
  198. package/views/config/document-store/chat.hbs +0 -286
  199. package/views/config/document-store/index.hbs +0 -146
  200. package/views/config/document-store/mappings/index.hbs +0 -108
  201. package/views/config/document-store/mappings/new.hbs +0 -68
  202. package/views/config/document-store/pre-processing/index.hbs +0 -103
  203. package/views/partials/document_store_header.hbs +0 -30
  204. package/workers/documents.js +0 -1128
@@ -17,8 +17,8 @@ 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 { oauthCreateSchema, oauthUpdateSchema, accountIdSchema, formBoolean } = require('../schemas');
21
+ const { throwAsBoom, adminUrl, submittedValues, windowedPageLinks } = require('./route-helpers');
22
22
 
23
23
  const { DEFAULT_PAGE_SIZE } = consts;
24
24
 
@@ -62,6 +62,75 @@ function init(args) {
62
62
  };
63
63
  }
64
64
 
65
+ /**
66
+ * View context for re-rendering the new or edit OAuth2 app form after a failed save, from the
67
+ * submitted fields. One function for the handler's catch and the validation failAction of both
68
+ * forms, so the four copies cannot drift again: the secret fields are blanked (the edit page
69
+ * never echoes a stored secret, and the API masks them), and on the edit form the
70
+ * authentication method stays locked once the app has one.
71
+ *
72
+ * @param {Object} request - the Hapi request carrying the submitted payload
73
+ * @param {Object} [appData] - the stored app when editing, absent when creating
74
+ * @param {Object} [errors] - field errors to show
75
+ * @returns {Promise<Object>}
76
+ */
77
+ async function appFormErrorContext(request, appData, errors) {
78
+ const payload = request.payload;
79
+ const provider = appData ? appData.provider : payload.provider;
80
+ const providerData = appData ? oauth2ProviderData(appData.provider, appData.cloud) : oauth2ProviderData(provider);
81
+
82
+ const serviceUrl = await settings.get('serviceUrl');
83
+ let defaultRedirectUrl = `${serviceUrl}/oauth`;
84
+ if (provider === 'outlook') {
85
+ defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
86
+ }
87
+
88
+ const context = {
89
+ pageTitle: 'OAuth2 Apps',
90
+ menuOauthApps: true,
91
+
92
+ [`active${providerData.caseName}`]: true,
93
+ providerData,
94
+ defaultRedirectUrl,
95
+
96
+ pubSubApps: await getPubSubAppsForSelect(payload.pubSubApp),
97
+
98
+ baseScopesApi: payload.baseScopes === 'api',
99
+ baseScopesImap: payload.baseScopes === 'imap' || !payload.baseScopes,
100
+ baseScopesPubsub: payload.baseScopes === 'pubsub',
101
+
102
+ azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
103
+ entry.selected = payload.cloud === entry.id;
104
+ return entry;
105
+ }),
106
+
107
+ // The submitted fields, not the stored app: without them the new-app form loses its
108
+ // provider on a validation error and the next submit is bounced to /admin
109
+ values: submittedValues(request, 'clientSecret', 'serviceKey', 'externalAccount'),
110
+
111
+ authorityCommon: payload.authority === 'common',
112
+ authorityOrganizations: payload.authority === 'organizations',
113
+ authorityConsumers: payload.authority === 'consumers',
114
+ authorityTenant: payload.authority === 'tenant',
115
+
116
+ errors
117
+ };
118
+
119
+ if (appData) {
120
+ Object.assign(context, {
121
+ appData,
122
+ hasClientSecret: !!appData.clientSecret,
123
+ hasServiceKey: !!appData.serviceKey,
124
+ hasExternalAccount: !!appData.externalAccount,
125
+ ...authMethodContext(appData.authMethod, !!appData.serviceKey || !!appData.externalAccount)
126
+ });
127
+ } else {
128
+ Object.assign(context, { actionCreate: true, ...authMethodContext(payload.authMethod) });
129
+ }
130
+
131
+ return context;
132
+ }
133
+
65
134
  /**
66
135
  * Fetch the list of Pub/Sub apps and mark the one matching selectedId as selected.
67
136
  * Returns the apps array ready for template rendering.
@@ -148,11 +217,7 @@ function init(args) {
148
217
  nextPage,
149
218
  prevPage,
150
219
  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
- })),
220
+ pageLinks: windowedPageLinks(data.pages, data.page, page => getPagingUrl(page, request.query.query)),
156
221
 
157
222
  apps: data.apps
158
223
  },
@@ -258,11 +323,7 @@ function init(args) {
258
323
  nextPage,
259
324
  prevPage,
260
325
  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
- })),
326
+ pageLinks: windowedPageLinks(data.pages, data.page, getPagingUrl),
266
327
 
267
328
  apps: data.apps,
268
329
 
@@ -601,7 +662,7 @@ function init(args) {
601
662
  payload: Joi.object({
602
663
  crumb: Joi.string().optional(),
603
664
  account: Joi.string().trim().empty('').max(256).optional(),
604
- testConnection: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(true)
665
+ testConnection: formBoolean().default(true)
605
666
  })
606
667
  }
607
668
  }
@@ -720,58 +781,12 @@ function init(args) {
720
781
  await request.flash({ type: 'danger', message: `Couldn't register OAuth2 app. Try again.` });
721
782
  request.logger.error({ msg: 'Failed to register OAuth2 app', err });
722
783
 
723
- let { provider, baseScopes } = request.payload;
784
+ let { provider } = request.payload;
724
785
  if (!provider || !OAUTH_PROVIDERS.hasOwnProperty(provider)) {
725
786
  return h.redirect('/admin');
726
787
  }
727
788
 
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
- );
789
+ return h.view('config/oauth/new', await appFormErrorContext(request, null, err.details), { layout: 'app' });
775
790
  }
776
791
  },
777
792
  options: {
@@ -796,59 +811,12 @@ function init(args) {
796
811
  await request.flash({ type: 'danger', message: `Couldn't register OAuth2 app. Try again.` });
797
812
  request.logger.debug({ msg: 'Failed to register OAuth2 app', err });
798
813
 
799
- let { provider, baseScopes } = request.payload;
814
+ let { provider } = request.payload;
800
815
  if (!provider || !OAUTH_PROVIDERS.hasOwnProperty(provider)) {
801
816
  return h.redirect('/admin').takeover();
802
817
  }
803
818
 
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();
819
+ return h.view('config/oauth/new', await appFormErrorContext(request, null, errors), { layout: 'app' }).takeover();
852
820
  },
853
821
 
854
822
  payload: Joi.object(oauthCreateSchema).tailor('web')
@@ -986,53 +954,7 @@ function init(args) {
986
954
  await request.flash({ type: 'danger', message: `Couldn't save OAuth2 app. Try again.` });
987
955
  request.logger.error({ msg: 'Failed to update OAuth2 app', app: request.payload.app, err });
988
956
 
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
- );
957
+ return h.view('config/oauth/edit', await appFormErrorContext(request, appData, err.details), { layout: 'app' });
1036
958
  }
1037
959
  },
1038
960
  options: {
@@ -1064,63 +986,7 @@ function init(args) {
1064
986
  await request.flash({ type: 'danger', message: `Couldn't save OAuth2 app. Try again.` });
1065
987
  request.logger.debug({ msg: 'Failed to update OAuth2 app', err });
1066
988
 
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();
989
+ return h.view('config/oauth/edit', await appFormErrorContext(request, appData, errors), { layout: 'app' }).takeover();
1124
990
  },
1125
991
 
1126
992
  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
 
@@ -446,6 +410,43 @@ function submittedValues(request, ...secretFields) {
446
410
  return values;
447
411
  }
448
412
 
413
+ // Page links shown on either side of the current page, in addition to the first and the last
414
+ const PAGE_LINK_RADIUS = 2;
415
+
416
+ /**
417
+ * The numbered page links of a listing, windowed: the first and last page, and PAGE_LINK_RADIUS
418
+ * pages either side of the current one, with a `gap` entry where pages are left out. A link per
419
+ * page rendered five thousand buttons for an instance with 100k accounts.
420
+ *
421
+ * @param {number} pages - total page count
422
+ * @param {number} page - zero-based current page
423
+ * @param {Function} urlFor - one-based page number to URL
424
+ * @returns {Array<Object>} entries of { url, title, active } or { gap: true }
425
+ */
426
+ function windowedPageLinks(pages, page, urlFor) {
427
+ const total = Math.max(Number(pages) || 0, 1);
428
+ const shown = [...new Set([0, total - 1, ...Array.from({ length: PAGE_LINK_RADIUS * 2 + 1 }, (z, i) => page - PAGE_LINK_RADIUS + i)])]
429
+ .filter(i => i >= 0 && i < total)
430
+ .sort((a, b) => a - b);
431
+
432
+ const pageLink = i => ({ url: urlFor(i + 1), title: i + 1, active: i === page });
433
+
434
+ const links = [];
435
+ let previous = -1;
436
+ for (const i of shown) {
437
+ if (i - previous === 2) {
438
+ // a gap would hide a single page, so show that page instead. It is never the current
439
+ // one: that page is always inside the window, so it is in `shown` itself
440
+ links.push(pageLink(i - 1));
441
+ } else if (i - previous > 2) {
442
+ links.push({ gap: true });
443
+ }
444
+ links.push(pageLink(i));
445
+ previous = i;
446
+ }
447
+ return links;
448
+ }
449
+
449
450
  function buildPagingView(basePath, data, query) {
450
451
  const getPagingUrl = page => {
451
452
  let url = new URL(basePath, 'http://localhost');
@@ -466,11 +467,7 @@ function buildPagingView(basePath, data, query) {
466
467
  nextPage: data.pages > data.page + 1 ? getPagingUrl(data.page + 2) : false,
467
468
  prevPage: data.page > 0 ? getPagingUrl(data.page) : false,
468
469
  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
- }))
470
+ pageLinks: windowedPageLinks(data.pages, data.page, getPagingUrl)
474
471
  };
475
472
  }
476
473
 
@@ -608,9 +605,7 @@ module.exports = {
608
605
  accountPickerEntry,
609
606
  accountPickerSelection,
610
607
  identityErrorView,
611
- OPEN_AI_MODELS,
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
  };
@@ -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
 
@@ -3,12 +3,39 @@
3
3
  const libmime = require('libmime');
4
4
  const { UNSAFE_KEYS } = require('./unsafe-key');
5
5
 
6
+ // Largest header block handed to libmime. Its line unfolding used to be quadratic in the line
7
+ // count, and the bounce and complaint detectors decode blocks taken from attachments any sender
8
+ // controls, so the cut is made here rather than at each caller. No real header block comes
9
+ // anywhere near this
10
+ const MAX_HEADER_BLOCK_SIZE = 64 * 1024;
11
+
12
+ /**
13
+ * Returns a header block as a string, cut to MAX_HEADER_BLOCK_SIZE.
14
+ *
15
+ * decodeHeaders() applies this itself; it is exported for the callers that run their own
16
+ * line-based preprocessing over a block before decoding it, so that work is bounded the same way.
17
+ *
18
+ * @param {string|Buffer} content - Raw header block
19
+ * @returns {string}
20
+ */
21
+ function capHeaderBlock(content) {
22
+ if (!content) {
23
+ return '';
24
+ }
25
+ if (Buffer.isBuffer(content)) {
26
+ return content.subarray(0, MAX_HEADER_BLOCK_SIZE).toString();
27
+ }
28
+ content = content.toString();
29
+ return content.length > MAX_HEADER_BLOCK_SIZE ? content.substring(0, MAX_HEADER_BLOCK_SIZE) : content;
30
+ }
31
+
6
32
  /**
7
33
  * Parses a header block into a map of lowercased header name to array of values.
8
34
  *
9
- * Wraps libmime.decodeHeaders() to drop names that collide with Object.prototype. Header names
10
- * come from the message, so any sender can use one, and libmime returns them as real own
11
- * properties. Neither names a real header, so there is nothing to preserve by keeping them:
35
+ * Wraps libmime.decodeHeaders() to cut the block to MAX_HEADER_BLOCK_SIZE and to drop names that
36
+ * collide with Object.prototype. Header names come from the message, so any sender can use one,
37
+ * and libmime returns them as real own properties. Neither names a real header, so there is
38
+ * nothing to preserve by keeping them:
12
39
  *
13
40
  * - an own "__proto__" key is the one thing lib/msgpack.js refuses to decode, so a map carrying it
14
41
  * encodes into webhook logs and message payloads that can never be read back, and it hands
@@ -26,7 +53,7 @@ const { UNSAFE_KEYS } = require('./unsafe-key');
26
53
  * @returns {Object} Map of lowercased header name to array of values
27
54
  */
28
55
  function decodeHeaders(headers) {
29
- let parsed = libmime.decodeHeaders(headers);
56
+ let parsed = libmime.decodeHeaders(capHeaderBlock(headers));
30
57
 
31
58
  for (let name of UNSAFE_KEYS) {
32
59
  // Probing first is not needed for correctness, deleting a missing key is a no-op, but it is
@@ -39,4 +66,4 @@ function decodeHeaders(headers) {
39
66
  return parsed;
40
67
  }
41
68
 
42
- module.exports = { decodeHeaders };
69
+ module.exports = { decodeHeaders, capHeaderBlock, MAX_HEADER_BLOCK_SIZE };
@@ -45,4 +45,65 @@ function pushHeaderValue(headers, key, value) {
45
45
  return true;
46
46
  }
47
47
 
48
- module.exports = { pushHeaderValue };
48
+ // Headers the notification path needs for its own processing, whatever the notifyHeaders
49
+ // setting asks for: auto-reply detection, threading, the multipart/report check behind bounce
50
+ // and complaint detection, and the address fields as a fallback for an ENVELOPE that carries no
51
+ // usable address (Lark Mail omits them, and any server can mis-parse a malformed header into a
52
+ // display name with no address). They travel with the one header section the path already
53
+ // requests and are narrowed back out before the message is published
54
+ const NOTIFICATION_HEADERS = [
55
+ 'x-autoreply',
56
+ 'x-autorespond',
57
+ 'auto-submitted',
58
+ 'precedence',
59
+ 'in-reply-to',
60
+ 'references',
61
+ 'content-type',
62
+ 'from',
63
+ 'to',
64
+ 'cc',
65
+ 'bcc'
66
+ ];
67
+
68
+ /**
69
+ * Builds the header field list for a notification fetch: what the operator asked for, what the
70
+ * path needs for itself, and whatever else the caller has a use for this time (the AI summary's
71
+ * headers while summaries are on)
72
+ *
73
+ * @param {String[]|Boolean} configuredHeaders - Headers the notifyHeaders setting asks for
74
+ * @param {String[]} [extraHeaders] - Headers the caller wants fetched as well
75
+ * @returns {String[]} Header names to request from the server
76
+ */
77
+ function notificationHeaderFields(configuredHeaders, extraHeaders) {
78
+ const fetchHeaders = new Set(Array.isArray(configuredHeaders) ? configuredHeaders : []);
79
+
80
+ for (const key of NOTIFICATION_HEADERS.concat(extraHeaders || [])) {
81
+ fetchHeaders.add(key);
82
+ }
83
+
84
+ return Array.from(fetchHeaders);
85
+ }
86
+
87
+ /**
88
+ * Narrows a message's fetched headers to what the caller asked for, once every internal use of
89
+ * the extra ones is over. A list keeps those names, false drops the block, and anything else
90
+ * (every header was asked for) leaves it alone
91
+ *
92
+ * @param {Object} message - Message whose headers were fetched with notificationHeaderFields()
93
+ * @param {String[]|Boolean|undefined} requestedHeaders - What the caller asked for
94
+ */
95
+ function narrowHeaders(message, requestedHeaders) {
96
+ if (Array.isArray(requestedHeaders)) {
97
+ const narrowed = {};
98
+ for (const key of Object.keys(message.headers || {})) {
99
+ if (requestedHeaders.includes(key)) {
100
+ narrowed[key] = message.headers[key];
101
+ }
102
+ }
103
+ message.headers = narrowed;
104
+ } else if (requestedHeaders === false) {
105
+ delete message.headers;
106
+ }
107
+ }
108
+
109
+ module.exports = { pushHeaderValue, notificationHeaderFields, narrowHeaders, NOTIFICATION_HEADERS };
@@ -357,6 +357,8 @@ module.exports = {
357
357
  resolvePublicInterfaces,
358
358
  updatePublicInterfaces,
359
359
  getLocalAddress,
360
+ parseComparableIp,
361
+ parseComparableCidr,
360
362
  matchIp,
361
363
  resolveClientIp,
362
364
  detectAutomatedRequest,