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
@@ -3,23 +3,22 @@
3
3
  // Admin UI routes for the remaining /admin/config/* pages: webhooks, service URL/branding,
4
4
  // AI (OpenAI) settings, logging, and license. Extracted verbatim from lib/routes-ui.js.
5
5
  // The notificationTypes / configWebhooksSchema / configLoggingSchema consts, the
6
- // getOpenAiError helper, and the getDefaultPrompt helper move with the routes (only these
7
- // config pages use them).
6
+ // getOpenAiError helper moved with the routes (only these config pages use them).
8
7
 
9
8
  const Joi = require('joi');
10
9
  const crypto = require('crypto');
11
10
  const config = require('@zone-eu/wild-config');
12
- const libmime = require('libmime');
13
11
  const os = require('os');
14
12
  const packageData = require('../../package.json');
15
- const { simpleParser } = require('mailparser');
13
+ const { parseMessage } = require('../parse-message');
16
14
  const { fetch: fetchCmd } = require('undici');
17
15
 
18
16
  const settings = require('../settings');
19
17
  const consts = require('../consts');
20
18
  const getSecret = require('../get-secret');
21
19
  const timezonesList = require('timezones-list').default;
22
- const { redis, submitQueue, notifyQueue, documentsQueue } = require('../db');
20
+ const { Queue } = require('bullmq');
21
+ const { redis, submitQueue, notifyQueue, queueConf, logBullErrors } = require('../db');
23
22
  const {
24
23
  getByteSize,
25
24
  formatByteSize,
@@ -33,8 +32,8 @@ const {
33
32
  } = require('../tools');
34
33
  const { validateWebhookTarget } = require('../webhook-egress');
35
34
  const { sendWebhookRequest } = require('../webhook-request');
36
- const { llmPreProcess } = require('../llm-pre-process');
37
- const { documentStoreFeatureEnabled } = require('../document-store');
35
+ const { llmPreProcess, buildSummaryInput, authenticationTrust } = require('../llm-pre-process');
36
+ const { decodeHeaders } = require('../utils/decode-headers');
38
37
  const { mcpFeatureEnabled } = require('../mcp');
39
38
  const { mcpResource } = require('../mcp/oauth');
40
39
  const { getToolRegistry } = require('../mcp/tools');
@@ -52,8 +51,11 @@ const TOOL_BADGES = {
52
51
  [ACTION.WRITE]: { label: 'write', variant: 'info' }
53
52
  };
54
53
  const { locales } = require('../translations');
55
- const { settingsSchema } = require('../schemas');
56
- const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads, mcpToolGrants } = require('./route-helpers');
54
+ const { settingsSchema, formBoolean } = require('../schemas');
55
+ const { getExampleDocumentsPayloads, mcpToolGrants } = require('./route-helpers');
56
+ const { getOpenAiModels, reasoningEffortOptions, aiPageSchema, aiFieldSchema, aiFieldValues, aiFieldStrings } = require('./ai-options');
57
+ const { DEFAULT_INSTRUCTIONS, DEFAULT_MODEL, DEFAULT_MAX_TOKENS } = require('@postalsys/email-ai-tools');
58
+
57
59
  const { registerSettingsPage } = require('./settings-page');
58
60
 
59
61
  const {
@@ -106,7 +108,7 @@ const notificationTypes = Object.keys(consts)
106
108
  }));
107
109
 
108
110
  const configWebhooksSchema = {
109
- webhooksEnabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false).description('Enable Webhooks'),
111
+ webhooksEnabled: formBoolean().default(false).description('Enable Webhooks'),
110
112
  webhooks: Joi.string()
111
113
  .uri({
112
114
  scheme: ['http', 'https'],
@@ -115,11 +117,11 @@ const configWebhooksSchema = {
115
117
  .allow('')
116
118
  .example('https://myservice.com/imap/webhooks')
117
119
  .description('Webhook URL'),
118
- notifyAll: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
119
- headersAll: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
120
+ notifyAll: formBoolean().default(false),
121
+ headersAll: formBoolean().default(false),
120
122
  notifyHeaders: Joi.string().empty('').trim(),
121
- notifyText: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
122
- notifyWebSafeHtml: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
123
+ notifyText: formBoolean().default(false),
124
+ notifyWebSafeHtml: formBoolean().default(false),
123
125
 
124
126
  notifyTextSize: Joi.alternatives().try(
125
127
  Joi.number().empty('').integer().min(0),
@@ -133,10 +135,10 @@ const configWebhooksSchema = {
133
135
  }, 'Byte size conversion')
134
136
  ),
135
137
 
136
- notifyCalendarEvents: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
137
- inboxNewOnly: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
138
+ notifyCalendarEvents: formBoolean().default(false),
139
+ inboxNewOnly: formBoolean().default(false),
138
140
 
139
- notifyAttachments: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false),
141
+ notifyAttachments: formBoolean().default(false),
140
142
  notifyAttachmentSize: Joi.alternatives().try(
141
143
  Joi.number().empty('').integer().min(0),
142
144
  // If it's a string, parse and convert it to bytes
@@ -159,11 +161,11 @@ const configWebhooksSchema = {
159
161
  };
160
162
 
161
163
  for (let type of notificationTypes) {
162
- configWebhooksSchema[`notify_${type.name}`] = Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false);
164
+ configWebhooksSchema[`notify_${type.name}`] = formBoolean().default(false);
163
165
  }
164
166
 
165
167
  const configLoggingSchema = {
166
- all: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false).description('Enable logs for all accounts'),
168
+ all: formBoolean().default(false).description('Enable logs for all accounts'),
167
169
  maxLogLines: Joi.number().integer().empty('').min(0).max(10000000).default(DEFAULT_MAX_LOG_LINES),
168
170
  sentryEnabled: settingsSchema.sentryEnabled.default(false),
169
171
  sentryDsn: settingsSchema.sentryDsn.default('')
@@ -203,11 +205,6 @@ async function getOpenAiError(gt) {
203
205
  function init(args) {
204
206
  const { server, call } = args;
205
207
 
206
- const getDefaultPrompt = async () =>
207
- await call({
208
- cmd: 'openAiDefaultPrompt'
209
- });
210
-
211
208
  registerSettingsPage(server, {
212
209
  path: '/admin/config/webhooks',
213
210
  view: 'config/webhooks',
@@ -273,8 +270,7 @@ function init(args) {
273
270
  Object.assign({}, type, { checked: !!values[`notify_${type.name}`], isMessageNew: type.name === 'messageNew' })
274
271
  ),
275
272
 
276
- webhookErrorFlag: await settings.get('webhookErrorFlag'),
277
- documentStoreEnabled: (documentStoreFeatureEnabled && (await settings.get('documentStoreEnabled'))) || false
273
+ webhookErrorFlag: await settings.get('webhookErrorFlag')
278
274
  };
279
275
  },
280
276
 
@@ -419,12 +415,8 @@ function init(args) {
419
415
  tokenAuditLog: settingsSchema.tokenAuditLog.default(false),
420
416
 
421
417
  // Following options can only be changed via the UI
422
- enableOAuthTokensApi: Joi.boolean()
423
- .truthy('Y', 'true', '1', 'on')
424
- .falsy('N', 'false', 0, '')
425
- .description('If true, then allow using using the OAuth tokens API endpoint')
426
- .default(false),
427
- enableTokens: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').default(false)
418
+ enableOAuthTokensApi: formBoolean().description('If true, then allow using using the OAuth tokens API endpoint').default(false),
419
+ enableTokens: formBoolean().default(false)
428
420
  },
429
421
 
430
422
  async loadValues() {
@@ -712,47 +704,25 @@ function init(args) {
712
704
  view: 'config/ai',
713
705
  pageTitle: 'AI Processing',
714
706
  menuKey: 'menuConfigAi',
715
- schema: {
716
- generateEmailSummary: settingsSchema.generateEmailSummary.default(false),
717
- openAiAPIKey: settingsSchema.openAiAPIKey.empty(''),
718
- openAiModel: settingsSchema.openAiModel.empty(''),
719
-
720
- openAiAPIUrl: settingsSchema.openAiAPIUrl.default(''),
721
-
722
- openAiPrompt: settingsSchema.openAiPrompt.default(''),
723
-
724
- contentFnJson: Joi.string()
725
- .max(1024 * 1024)
726
- .default('')
727
- .allow('')
728
- .trim()
729
- .description('Filter function'),
730
-
731
- openAiTemperature: settingsSchema.openAiTemperature.default(''),
732
- openAiTopP: settingsSchema.openAiTopP.default(''),
733
- openAiMaxTokens: settingsSchema.openAiMaxTokens.default('')
734
- },
707
+ schema: aiPageSchema(),
735
708
 
736
709
  async loadValues() {
737
- const values = {
738
- generateEmailSummary: (await settings.get('generateEmailSummary')) || false,
739
- openAiModel: await settings.get('openAiModel'),
740
- openAiPrompt: ((await settings.get('openAiPrompt')) || '').toString(),
741
- contentFnJson: JSON.stringify(
742
- ((await settings.get(`openAiPreProcessingFn`)) || '').toString() ||
743
- `// Pass all emails
744
- return true;`
745
- ),
746
-
747
- openAiAPIUrl: ((await settings.get('openAiAPIUrl')) || '').toString(),
710
+ const stored = await settings.getMulti('generateEmailSummary', 'openAiPreProcessingFn', ...consts.AI_SETTING_KEYS);
748
711
 
749
- openAiTemperature: ((await settings.get('openAiTemperature')) || '').toString(),
750
- openAiTopP: ((await settings.get('openAiTopP')) || '').toString(),
751
- openAiMaxTokens: ((await settings.get('openAiMaxTokens')) || '').toString()
752
- };
712
+ const values = Object.assign(
713
+ {
714
+ generateEmailSummary: stored.generateEmailSummary || false,
715
+ contentFnJson: JSON.stringify(
716
+ (stored.openAiPreProcessingFn || '').toString() ||
717
+ `// Pass all emails
718
+ return true;`
719
+ )
720
+ },
721
+ aiFieldStrings(stored)
722
+ );
753
723
 
754
724
  if (!values.openAiPrompt.trim()) {
755
- values.openAiPrompt = await getDefaultPrompt();
725
+ values.openAiPrompt = DEFAULT_INSTRUCTIONS;
756
726
  }
757
727
 
758
728
  return values;
@@ -761,18 +731,16 @@ return true;`
761
731
  async viewContext(request, values) {
762
732
  return {
763
733
  errorLog: await getAiErrorLog(),
764
- defaultPromptJson: JSON.stringify({ prompt: await getDefaultPrompt() }),
734
+ defaultPromptJson: JSON.stringify({ prompt: DEFAULT_INSTRUCTIONS }),
735
+ aiDefaults: { model: DEFAULT_MODEL, maxTokens: DEFAULT_MAX_TOKENS },
765
736
 
766
737
  hasOpenAiAPIKey: !!(await settings.get('openAiAPIKey')),
767
738
  openAiError: await getOpenAiError(request.app.gt),
768
- openAiModels: await getOpenAiModels(OPEN_AI_MODELS, values.openAiModel),
739
+ openAiModels: await getOpenAiModels(values.openAiModel),
740
+ reasoningEffortOptions: reasoningEffortOptions(values.openAiReasoningEffort),
769
741
 
770
742
  scriptEnvJson: JSON.stringify((await settings.get('scriptEnv')) || '{}'),
771
- examplePayloadsJson: JSON.stringify(
772
- (await getExampleDocumentsPayloads()).map(entry =>
773
- Object.assign({}, entry, { summary: undefined, riskAssessment: undefined, preview: undefined })
774
- )
775
- )
743
+ examplePayloadsJson: JSON.stringify(await getExampleDocumentsPayloads())
776
744
  };
777
745
  },
778
746
 
@@ -794,20 +762,16 @@ return true;`
794
762
  throw err;
795
763
  }
796
764
 
797
- let data = {
798
- generateEmailSummary: request.payload.generateEmailSummary,
799
- openAiModel: request.payload.openAiModel,
800
- openAiAPIUrl: request.payload.openAiAPIUrl,
801
- openAiPrompt: (request.payload.openAiPrompt || '').toString(),
802
- openAiPreProcessingFn: contentFn,
803
- openAiTemperature: request.payload.openAiTemperature,
804
- openAiTopP: request.payload.openAiTopP,
805
- openAiMaxTokens: request.payload.openAiMaxTokens
806
- };
807
-
808
- let defaultUserPrompt = await getDefaultPrompt();
765
+ const data = Object.assign(
766
+ {
767
+ generateEmailSummary: request.payload.generateEmailSummary,
768
+ openAiPreProcessingFn: contentFn
769
+ },
770
+ aiFieldValues(request.payload)
771
+ );
809
772
 
810
- if (!data.openAiPrompt.trim() || data.openAiPrompt.trim() === defaultUserPrompt.trim()) {
773
+ // the built-in instructions are not stored, so an upgrade that changes them takes effect
774
+ if (!data.openAiPrompt.trim() || data.openAiPrompt.trim() === DEFAULT_INSTRUCTIONS.trim()) {
811
775
  data.openAiPrompt = '';
812
776
  }
813
777
 
@@ -815,7 +779,7 @@ return true;`
815
779
  data.openAiAPIKey = request.payload.openAiAPIKey;
816
780
  }
817
781
 
818
- // per-key set(), not setMulti: writing openAi* keys bumps the
782
+ // per-key set(), not setMulti: writing the handler's keys bumps the
819
783
  // openAiSettingsVersion counter and a truthy generateEmailSummary
820
784
  // force-enables notifyText - side effects that setMulti skips
821
785
  for (let key of Object.keys(data)) {
@@ -831,41 +795,32 @@ return true;`
831
795
  try {
832
796
  request.logger.info({ msg: 'Prompt test' });
833
797
 
834
- const parsed = await simpleParser(Buffer.from(request.payload.emailFile, 'base64'));
798
+ const raw = Buffer.from(request.payload.emailFile, 'base64');
799
+ const parsed = await parseMessage(raw);
800
+
801
+ // the same input the sync path builds, from a message in the shape it has there
802
+ const headers = decodeHeaders(raw);
803
+ const message = buildSummaryInput({
804
+ subject: parsed.subject,
805
+ from: parsed.from?.value?.[0],
806
+ date: parsed.date,
807
+ headers,
808
+ attachments: parsed.attachments,
809
+ text: { plain: parsed.text, html: parsed.html }
810
+ });
835
811
 
836
- const response = {};
837
- response.summary = await call({
812
+ const response = await call({
838
813
  cmd: 'generateSummary',
839
814
  data: {
840
- message: {
841
- headers: parsed.headerLines.map(header => libmime.decodeHeader(header.line)),
842
- attachments: parsed.attachments,
843
- html: parsed.html,
844
- text: parsed.text
845
- },
846
- openAiAPIKey: request.payload.openAiAPIKey,
847
- openAiModel: request.payload.openAiModel,
848
- openAiAPIUrl: request.payload.openAiAPIUrl,
849
- openAiPrompt: request.payload.openAiPrompt,
850
- openAiTemperature: request.payload.openAiTemperature,
851
- openAiTopP: request.payload.openAiTopP,
852
- openAiMaxTokens: request.payload.openAiMaxTokens
815
+ message,
816
+ // a file belongs to no account, so no server's verdict is trusted
817
+ trust: authenticationTrust(null, headers),
818
+ // the form's values as shown, so the test runs with what the page shows
819
+ options: Object.assign({ openAiAPIKey: request.payload.openAiAPIKey }, aiFieldValues(request.payload))
853
820
  },
854
- timeout: 2 * 60 * 1000
821
+ timeout: consts.AI_REQUEST_TIMEOUT
855
822
  });
856
823
 
857
- // crux from olden times
858
- for (let key of Object.keys(response.summary)) {
859
- // remove meta keys from output
860
- if (key.charAt(0) === '_' || response.summary[key] === '') {
861
- delete response.summary[key];
862
- }
863
- if (key === 'riskAssessment') {
864
- response.riskAssessment = response.summary.riskAssessment;
865
- delete response.summary.riskAssessment;
866
- }
867
- }
868
-
869
824
  return { success: true, response };
870
825
  } catch (err) {
871
826
  request.logger.error({ msg: 'Failed to test prompt', err });
@@ -886,16 +841,15 @@ return true;`
886
841
 
887
842
  failAction,
888
843
 
889
- payload: Joi.object({
890
- emailFile: Joi.string().base64({ paddingRequired: false }).required(),
891
- openAiAPIKey: settingsSchema.openAiAPIKey.empty(''),
892
- openAiModel: settingsSchema.openAiModel.empty(''),
893
- openAiAPIUrl: settingsSchema.openAiAPIUrl.default(''),
894
- openAiPrompt: settingsSchema.openAiPrompt.default(''),
895
- openAiTemperature: settingsSchema.openAiTemperature.empty(''),
896
- openAiTopP: settingsSchema.openAiTopP.empty(''),
897
- openAiMaxTokens: settingsSchema.openAiMaxTokens.empty('')
898
- })
844
+ payload: Joi.object(
845
+ Object.assign(
846
+ {
847
+ emailFile: Joi.string().base64({ paddingRequired: false }).required(),
848
+ openAiAPIKey: settingsSchema.openAiAPIKey.empty('')
849
+ },
850
+ aiFieldSchema()
851
+ )
852
+ )
899
853
  }
900
854
  }
901
855
  });
@@ -910,17 +864,20 @@ return true;`
910
864
  const { models } = await call({
911
865
  cmd: 'openAiListModels',
912
866
  data: {
913
- openAiAPIKey: request.payload.openAiAPIKey,
914
- openAiAPIUrl: request.payload.openAiAPIUrl
867
+ options: {
868
+ openAiAPIKey: request.payload.openAiAPIKey,
869
+ openAiAPIUrl: request.payload.openAiAPIUrl
870
+ }
915
871
  },
916
- timeout: 2 * 60 * 1000
872
+ timeout: consts.AI_REQUEST_TIMEOUT
917
873
  });
918
874
 
919
875
  if (models && models.length) {
920
876
  await settings.set('openAiModels', models);
921
877
  }
922
878
 
923
- return { success: true, models };
879
+ // the list as the page first got it, "Default" and the stored model included
880
+ return { success: true, models: await getOpenAiModels(request.payload.openAiModel) };
924
881
  } catch (err) {
925
882
  request.logger.warn({ msg: 'Failed to reload OpenAI models', err });
926
883
  return {
@@ -941,7 +898,8 @@ return true;`
941
898
 
942
899
  payload: Joi.object({
943
900
  openAiAPIKey: settingsSchema.openAiAPIKey.empty(''),
944
- openAiAPIUrl: settingsSchema.openAiAPIUrl.default('')
901
+ openAiAPIUrl: settingsSchema.openAiAPIUrl.default(''),
902
+ openAiModel: settingsSchema.openAiModel.default('')
945
903
  })
946
904
  }
947
905
  }
@@ -998,6 +956,25 @@ return true;`
998
956
  await settings.clear('webhookErrorFlag');
999
957
  break;
1000
958
 
959
+ case 'document-store': {
960
+ // The removal warning (workers/api.js) keys on this setting alone. The other
961
+ // documentStore* values stay in the hash, so a downgrade finds its
962
+ // configuration where it left it. The queued indexing jobs are another
963
+ // matter: they carry message text, nothing trims them any more, and closing
964
+ // the notice is the operator saying they are not going back
965
+ await settings.clear('documentStoreEnabled');
966
+
967
+ const documentsQueue = logBullErrors(new Queue('documents', queueConf), 'queue:documents');
968
+ try {
969
+ await documentsQueue.obliterate({ force: true });
970
+ } catch (err) {
971
+ request.logger.error({ msg: 'Failed to remove the queued Document Store jobs', err });
972
+ } finally {
973
+ await documentsQueue.close();
974
+ }
975
+ break;
976
+ }
977
+
1001
978
  case 'webhook-route':
1002
979
  if (request.payload.entry) {
1003
980
  await redis.hdel(`${REDIS_PREFIX}wh:c`, `${request.payload.entry}:webhookErrorFlag`);
@@ -1031,7 +1008,7 @@ return true;`
1031
1008
  async handler(request) {
1032
1009
  let errors = [];
1033
1010
 
1034
- for (let queue of [submitQueue, notifyQueue, documentsQueue]) {
1011
+ for (let queue of [submitQueue, notifyQueue]) {
1035
1012
  for (let type of ['failed', 'completed']) {
1036
1013
  try {
1037
1014
  await queue.clean(1000, 100000, type);