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
@@ -8,17 +8,26 @@ const tokens = require('../tokens');
8
8
  const { redis } = require('../db');
9
9
  const getSecret = require('../get-secret');
10
10
  const { failAction, verifyAccountInfo, formatPartialSecretKey } = require('../tools');
11
- const { templateSchemas, accountIdSchema, tokenPermissionsSchema } = require('../schemas');
11
+ const { templateSchemas, accountIdSchema, tokenPermissionsSchema, formBoolean } = require('../schemas');
12
12
  const tokenPermissionView = require('../token-permission-view');
13
13
  const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
14
- const { Account, accountExists } = require('../account');
14
+ const { Account, accountExists, accountSummary } = require('../account');
15
15
  const { isMcpEnabled } = require('../mcp');
16
16
  const { Gateway } = require('../gateway');
17
17
  const { templates } = require('../templates');
18
18
  const { webhooks } = require('../webhooks');
19
19
  const consts = require('../consts');
20
20
  const wellKnownServices = require('nodemailer/lib/well-known/services.json');
21
- const { authAwareLevel, isClientError, resolveKnownAccounts, adminUrl, mcpToolGrants, accountPickerEntry, submittedValues } = require('./route-helpers');
21
+ const {
22
+ authAwareLevel,
23
+ isClientError,
24
+ resolveKnownAccounts,
25
+ adminUrl,
26
+ mcpToolGrants,
27
+ accountPickerEntry,
28
+ submittedValues,
29
+ windowedPageLinks
30
+ } = require('./route-helpers');
22
31
  const exampleWebhookPayloads = require('../payload-examples-webhooks.json');
23
32
 
24
33
  const { DEFAULT_PAGE_SIZE } = consts;
@@ -140,11 +149,7 @@ function init(args) {
140
149
  nextPage,
141
150
  prevPage,
142
151
  firstPage: data.page === 0,
143
- pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
144
- url: getPagingUrl(i + 1),
145
- title: i + 1,
146
- active: i === data.page
147
- })),
152
+ pageLinks: windowedPageLinks(data.pages, data.page, getPagingUrl),
148
153
 
149
154
  webhooksEnabled: await settings.get('webhooksEnabled'),
150
155
 
@@ -239,58 +244,11 @@ return payload;`)
239
244
  method: 'POST',
240
245
  path: '/admin/webhooks/new',
241
246
  async handler(request, h) {
242
- let contentFn, contentMap;
243
247
  try {
244
- if (request.payload.contentFnJson === '') {
245
- contentFn = null;
246
- } else {
247
- contentFn = JSON.parse(request.payload.contentFnJson);
248
- if (typeof contentFn !== 'string') {
249
- throw new Error('Invalid Format');
250
- }
251
- }
252
- } catch (err) {
253
- err.details = {
254
- contentFnJson: 'Invalid JSON'
255
- };
256
- throw err;
257
- }
258
-
259
- try {
260
- if (request.payload.contentMapJson === '') {
261
- contentMap = null;
262
- } else {
263
- contentMap = JSON.parse(request.payload.contentMapJson);
264
- if (typeof contentMap !== 'string') {
265
- throw new Error('Invalid Format');
266
- }
267
- }
268
- } catch (err) {
269
- err.details = {
270
- contentMapJson: 'Invalid JSON'
271
- };
272
- throw err;
273
- }
274
-
275
- let customHeaders = request.payload.customHeaders
276
- .split(/[\r\n]+/)
277
- .map(header => header.trim())
278
- .filter(header => header)
279
- .map(line => {
280
- let sep = line.indexOf(':');
281
- if (sep >= 0) {
282
- return {
283
- key: line.substring(0, sep).trim(),
284
- value: line.substring(sep + 1).trim()
285
- };
286
- }
287
- return {
288
- key: line,
289
- value: ''
290
- };
291
- });
248
+ // Parsed inside the try, so a malformed filter or map re-renders the form with the
249
+ // field error instead of escaping as a 500
250
+ let { contentFn, contentMap, customHeaders } = parseWebhookForm(request.payload);
292
251
 
293
- try {
294
252
  let createRequest = await webhooks.create(
295
253
  {
296
254
  name: request.payload.name,
@@ -389,16 +347,12 @@ return payload;`)
389
347
  .default('')
390
348
  .example('https://myservice.com/imap/webhooks')
391
349
  .description('Webhook target URL'),
392
- enabled: Joi.boolean()
393
- .truthy('Y', 'true', '1', 'on')
394
- .falsy('N', 'false', 0, '')
395
- .default(false)
396
- .example(false)
397
- .description('Is the routing enabled'),
350
+ enabled: formBoolean().default(false).example(false).description('Is the routing enabled'),
398
351
  customHeaders: Joi.string()
399
352
  .allow('')
400
353
  .trim()
401
354
  .max(10 * 1024)
355
+ .default('')
402
356
  .description('Custom request headers'),
403
357
  contentFnJson: Joi.string()
404
358
  .max(1024 * 1024)
@@ -553,58 +507,11 @@ return payload;`)
553
507
  method: 'POST',
554
508
  path: '/admin/webhooks/edit',
555
509
  async handler(request, h) {
556
- let contentFn, contentMap;
557
- try {
558
- if (request.payload.contentFnJson === '') {
559
- contentFn = null;
560
- } else {
561
- contentFn = JSON.parse(request.payload.contentFnJson);
562
- if (typeof contentFn !== 'string') {
563
- throw new Error('Invalid Format');
564
- }
565
- }
566
- } catch (err) {
567
- err.details = {
568
- contentFnJson: 'Invalid JSON'
569
- };
570
- throw err;
571
- }
572
-
573
510
  try {
574
- if (request.payload.contentMapJson === '') {
575
- contentMap = null;
576
- } else {
577
- contentMap = JSON.parse(request.payload.contentMapJson);
578
- if (typeof contentMap !== 'string') {
579
- throw new Error('Invalid Format');
580
- }
581
- }
582
- } catch (err) {
583
- err.details = {
584
- contentMapJson: 'Invalid JSON'
585
- };
586
- throw err;
587
- }
588
-
589
- let customHeaders = request.payload.customHeaders
590
- .split(/[\r\n]+/)
591
- .map(header => header.trim())
592
- .filter(header => header)
593
- .map(line => {
594
- let sep = line.indexOf(':');
595
- if (sep >= 0) {
596
- return {
597
- key: line.substring(0, sep).trim(),
598
- value: line.substring(sep + 1).trim()
599
- };
600
- }
601
- return {
602
- key: line,
603
- value: ''
604
- };
605
- });
511
+ // Parsed inside the try, so a malformed filter or map re-renders the form with the
512
+ // field error instead of escaping as a 500
513
+ let { contentFn, contentMap, customHeaders } = parseWebhookForm(request.payload);
606
514
 
607
- try {
608
515
  await webhooks.update(
609
516
  request.payload.webhook,
610
517
  {
@@ -729,16 +636,12 @@ return payload;`)
729
636
  .default('')
730
637
  .example('https://myservice.com/imap/webhooks')
731
638
  .description('Webhook target URL'),
732
- enabled: Joi.boolean()
733
- .truthy('Y', 'true', '1', 'on')
734
- .falsy('N', 'false', 0, '')
735
- .default(false)
736
- .example(false)
737
- .description('Is the routing enabled'),
639
+ enabled: formBoolean().default(false).example(false).description('Is the routing enabled'),
738
640
  customHeaders: Joi.string()
739
641
  .allow('')
740
642
  .trim()
741
643
  .max(10 * 1024)
644
+ .default('')
742
645
  .description('Custom request headers'),
743
646
  contentFnJson: Joi.string()
744
647
  .max(1024 * 1024)
@@ -869,11 +772,7 @@ return payload;`)
869
772
  nextPage,
870
773
  prevPage,
871
774
  firstPage: data.page === 0,
872
- pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
873
- url: getPagingUrl(i + 1),
874
- title: i + 1,
875
- active: i === data.page
876
- })),
775
+ pageLinks: windowedPageLinks(data.pages, data.page, getPagingUrl),
877
776
 
878
777
  templates: data.templates
879
778
  },
@@ -915,11 +814,7 @@ return payload;`)
915
814
  throw error;
916
815
  }
917
816
 
918
- let account;
919
- if (template.account) {
920
- let accountObject = new Account({ redis, account: template.account });
921
- account = await accountObject.loadAccountData();
922
- }
817
+ let account = await loadTemplateAccount(template.account);
923
818
 
924
819
  let accountTemplatesLink = new URL('/admin/templates', 'http://localhost');
925
820
  if (account) {
@@ -980,11 +875,7 @@ return payload;`)
980
875
  throw error;
981
876
  }
982
877
 
983
- let account;
984
- if (template.account) {
985
- let accountObject = new Account({ redis, account: template.account });
986
- account = await accountObject.loadAccountData();
987
- }
878
+ let account = await loadTemplateAccount(template.account);
988
879
 
989
880
  let accountTemplatesLink = new URL('/admin/templates', 'http://localhost');
990
881
  if (account) {
@@ -1081,11 +972,7 @@ return payload;`)
1081
972
  throw error;
1082
973
  }
1083
974
 
1084
- let account;
1085
- if (template.account) {
1086
- let accountObject = new Account({ redis, account: template.account });
1087
- account = await accountObject.loadAccountData();
1088
- }
975
+ let account = await loadTemplateAccount(template.account);
1089
976
 
1090
977
  let accountTemplatesLink = new URL('/admin/templates', 'http://localhost');
1091
978
  if (account) {
@@ -1146,11 +1033,7 @@ return payload;`)
1146
1033
  throw error;
1147
1034
  }
1148
1035
 
1149
- let account;
1150
- if (template.account) {
1151
- let accountObject = new Account({ redis, account: template.account });
1152
- account = await accountObject.loadAccountData();
1153
- }
1036
+ let account = await loadTemplateAccount(template.account);
1154
1037
 
1155
1038
  let accountTemplatesLink = new URL('/admin/templates', 'http://localhost');
1156
1039
  if (account) {
@@ -1214,11 +1097,7 @@ return payload;`)
1214
1097
  method: 'GET',
1215
1098
  path: '/admin/templates/new',
1216
1099
  async handler(request, h) {
1217
- let account;
1218
- if (request.query.account) {
1219
- let accountObject = new Account({ redis, account: request.query.account });
1220
- account = await accountObject.loadAccountData();
1221
- }
1100
+ let account = await loadTemplateAccount(request.query.account);
1222
1101
 
1223
1102
  let accountTemplatesLink = new URL('/admin/templates', 'http://localhost');
1224
1103
  if (account) {
@@ -1282,6 +1161,14 @@ return payload;`)
1282
1161
  method: 'POST',
1283
1162
  path: '/admin/templates/new',
1284
1163
  async handler(request, h) {
1164
+ // The account is a hidden field carried over from an account page, so an unknown ID is
1165
+ // a stale page or a crafted post. Refused up front: a template stored under it could
1166
+ // never be opened again.
1167
+ if (request.payload.account && !(await accountExists(redis, request.payload.account))) {
1168
+ await request.flash({ type: 'danger', message: `No account found with ID "${request.payload.account}"` });
1169
+ return h.redirect('/admin/templates');
1170
+ }
1171
+
1285
1172
  try {
1286
1173
  let createRequest = await templates.create(
1287
1174
  request.payload.account,
@@ -1304,11 +1191,7 @@ return payload;`)
1304
1191
  await request.flash({ type: 'danger', message: `Couldn't create template. Try again.` });
1305
1192
  request.logger.error({ msg: 'Failed to create template', err });
1306
1193
 
1307
- let account;
1308
- if (request.payload.account) {
1309
- let accountObject = new Account({ redis, account: request.payload.account });
1310
- account = await accountObject.loadAccountData();
1311
- }
1194
+ let account = await loadTemplateAccount(request.payload.account);
1312
1195
 
1313
1196
  let accountTemplatesLink = new URL('/admin/templates', 'http://localhost');
1314
1197
  if (account) {
@@ -1361,11 +1244,7 @@ return payload;`)
1361
1244
  await request.flash({ type: 'danger', message: `Couldn't create template. Try again.` });
1362
1245
  request.logger.debug({ msg: 'Failed to create template', err });
1363
1246
 
1364
- let account;
1365
- if (request.payload.account) {
1366
- let accountObject = new Account({ redis, account: request.payload.account });
1367
- account = await accountObject.loadAccountData();
1368
- }
1247
+ let account = await loadTemplateAccount(request.payload.account);
1369
1248
 
1370
1249
  let accountTemplatesLink = new URL('/admin/templates', 'http://localhost');
1371
1250
  if (account) {
@@ -1613,11 +1492,7 @@ return payload;`)
1613
1492
  nextPage,
1614
1493
  prevPage,
1615
1494
  firstPage: gateways.page === 0,
1616
- pageLinks: new Array(gateways.pages || 1).fill(0).map((z, i) => ({
1617
- url: getPagingUrl(i + 1),
1618
- title: i + 1,
1619
- active: i === gateways.page
1620
- })),
1495
+ pageLinks: windowedPageLinks(gateways.pages, gateways.page, getPagingUrl),
1621
1496
 
1622
1497
  gateways: gateways.gateways.map(entry => {
1623
1498
  let label = {};
@@ -1891,13 +1766,7 @@ return payload;`)
1891
1766
  .label('Port')
1892
1767
  .required(),
1893
1768
 
1894
- secure: Joi.boolean()
1895
- .truthy('Y', 'true', '1', 'on')
1896
- .falsy('N', 'false', 0, '')
1897
- .default(false)
1898
- .example(true)
1899
- .description('Should connection use TLS. Usually true for port 465')
1900
- .label('TLS')
1769
+ secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS')
1901
1770
  })
1902
1771
  }
1903
1772
  }
@@ -2023,13 +1892,7 @@ return payload;`)
2023
1892
  .label('Port')
2024
1893
  .required(),
2025
1894
 
2026
- secure: Joi.boolean()
2027
- .truthy('Y', 'true', '1', 'on')
2028
- .falsy('N', 'false', 0, '')
2029
- .default(false)
2030
- .example(true)
2031
- .description('Should connection use TLS. Usually true for port 465')
2032
- .label('TLS')
1895
+ secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS')
2033
1896
  })
2034
1897
  }
2035
1898
  }
@@ -2139,13 +2002,7 @@ return payload;`)
2139
2002
  .example(465)
2140
2003
  .description('Service port number')
2141
2004
  .label('Port'),
2142
- secure: Joi.boolean()
2143
- .truthy('Y', 'true', '1', 'on')
2144
- .falsy('N', 'false', 0, '')
2145
- .default(false)
2146
- .example(true)
2147
- .description('Should connection use TLS. Usually true for port 465')
2148
- .label('TLS')
2005
+ secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS')
2149
2006
  })
2150
2007
  }
2151
2008
  }
@@ -2330,11 +2187,7 @@ return payload;`)
2330
2187
  nextPage,
2331
2188
  prevPage,
2332
2189
  firstPage: data.page === 0,
2333
- pageLinks: new Array(data.pages || 1).fill(0).map((z, i) => ({
2334
- url: getPagingUrl(i + 1, request.query.state, request.query.query),
2335
- title: i + 1,
2336
- active: i === data.page
2337
- })),
2190
+ pageLinks: windowedPageLinks(data.pages, data.page, page => getPagingUrl(page, request.query.state, request.query.query)),
2338
2191
 
2339
2192
  newLink: newLink.pathname + newLink.search
2340
2193
  },
@@ -2607,4 +2460,61 @@ return payload;`)
2607
2460
  });
2608
2461
  }
2609
2462
 
2463
+ // The account a template belongs to, for the template pages. A template can outlive its account
2464
+ // (deleted since, or stored before the create form checked the ID), and a missing account is
2465
+ // then rendered as no account rather than turning the template itself into a 404 nobody can
2466
+ // open or delete.
2467
+ async function loadTemplateAccount(account) {
2468
+ // The pages show the name and address only, so the summary read: one HMGET, nothing decrypted
2469
+ return (await accountSummary(redis, account)) || undefined;
2470
+ }
2471
+
2472
+ // The fields of the webhook route form that are not stored as typed: the filter and map scripts
2473
+ // arrive JSON-encoded from the editor, and the custom headers as "Key: value" lines. Throws with
2474
+ // `details` naming the field for a script that is not a JSON string, so the form re-renders with
2475
+ // that field marked.
2476
+ function parseWebhookForm(payload) {
2477
+ let scripts = {};
2478
+ for (let [field, key] of [
2479
+ ['contentFnJson', 'contentFn'],
2480
+ ['contentMapJson', 'contentMap']
2481
+ ]) {
2482
+ try {
2483
+ if (payload[field] === '') {
2484
+ scripts[key] = null;
2485
+ } else {
2486
+ scripts[key] = JSON.parse(payload[field]);
2487
+ if (typeof scripts[key] !== 'string') {
2488
+ throw new Error('Invalid Format');
2489
+ }
2490
+ }
2491
+ } catch (err) {
2492
+ err.details = {
2493
+ [field]: 'Invalid JSON'
2494
+ };
2495
+ throw err;
2496
+ }
2497
+ }
2498
+
2499
+ let customHeaders = payload.customHeaders
2500
+ .split(/[\r\n]+/)
2501
+ .map(header => header.trim())
2502
+ .filter(header => header)
2503
+ .map(line => {
2504
+ let sep = line.indexOf(':');
2505
+ if (sep >= 0) {
2506
+ return {
2507
+ key: line.substring(0, sep).trim(),
2508
+ value: line.substring(sep + 1).trim()
2509
+ };
2510
+ }
2511
+ return {
2512
+ key: line,
2513
+ value: ''
2514
+ };
2515
+ });
2516
+
2517
+ return { contentFn: scripts.contentFn, contentMap: scripts.contentMap, customHeaders };
2518
+ }
2519
+
2610
2520
  module.exports = init;
@@ -0,0 +1,104 @@
1
+ 'use strict';
2
+
3
+ // The choices the AI configuration page offers: the model list and the reasoning effort levels.
4
+ // Kept apart from the general route helpers because they change with the provider's catalogue,
5
+ // not with the admin UI
6
+
7
+ const Joi = require('joi');
8
+ const settings = require('../settings');
9
+ const { settingsSchema } = require('../schemas');
10
+ const { AI_SETTING_KEYS } = require('../consts');
11
+ const { DEFAULT_MODEL, REASONING_EFFORTS, describeModel } = require('@postalsys/email-ai-tools');
12
+
13
+ // The AI page's fields, derived from the settings schema so the page, its test and the stored
14
+ // settings cannot disagree about a field. The key is handled apart: the form leaves it blank to
15
+ // keep the stored one
16
+ const aiFieldSchema = () => Object.fromEntries(AI_SETTING_KEYS.map(key => [key, settingsSchema[key].default('')]));
17
+ const aiFieldValues = payload => Object.fromEntries(AI_SETTING_KEYS.map(key => [key, payload[key]]));
18
+ // the stored values as the form shows them: strings, empty for unset
19
+ const aiFieldStrings = stored => Object.fromEntries(AI_SETTING_KEYS.map(key => [key, (stored[key] || '').toString()]));
20
+
21
+ // Everything the AI page posts: the switch and the key, the filter script as the page's own text
22
+ // field, and the request options the settings schema describes
23
+ const aiPageSchema = () =>
24
+ Object.assign(
25
+ {
26
+ generateEmailSummary: settingsSchema.generateEmailSummary.default(false),
27
+ openAiAPIKey: settingsSchema.openAiAPIKey.empty(''),
28
+ contentFnJson: Joi.string()
29
+ .max(1024 * 1024)
30
+ .default('')
31
+ .allow('')
32
+ .trim()
33
+ .description('Filter function')
34
+ },
35
+ aiFieldSchema()
36
+ );
37
+
38
+ // Fallback model list, shown until the first successful "Refresh Models" call replaces it with
39
+ // the models actually available on the configured endpoint (stored in the openAiModels
40
+ // setting). Newest first. Checked against OpenAI's catalogue on 2026-10-01
41
+ const OPEN_AI_MODELS = [
42
+ { name: 'GPT-6 Luna', id: 'gpt-6-luna' },
43
+ { name: 'GPT-6 Sol', id: 'gpt-6-sol' },
44
+ { name: 'GPT-6 Astra', id: 'gpt-6-astra' },
45
+ { name: 'GPT-5.6 Luna', id: 'gpt-5.6-luna' },
46
+ { name: 'GPT-5.6 Terra', id: 'gpt-5.6-terra' },
47
+ { name: 'GPT-5.4 Mini', id: 'gpt-5.4-mini' },
48
+ { name: 'GPT-5.4 Nano', id: 'gpt-5.4-nano' },
49
+ { name: 'GPT-5 Mini', id: 'gpt-5-mini' }
50
+ ].map(model => Object.assign(model, describeModel(model.id)));
51
+
52
+ // Labels for the reasoning effort levels that are not just the capitalised value
53
+ const REASONING_EFFORT_LABELS = { '': 'Default', xhigh: 'Extra high', max: 'Maximum' };
54
+
55
+ // The entry that leaves the choice to the library, always first in the picker
56
+ const defaultModelEntry = () => ({
57
+ id: '',
58
+ name: `Default (${DEFAULT_MODEL})`,
59
+ description: 'Follows the built-in default across upgrades',
60
+ recommended: true
61
+ });
62
+
63
+ /**
64
+ * The model list for the page: the stored list from the last refresh, the fallback until then,
65
+ * each entry with a description and a recommended flag for the picker. "Default" comes first,
66
+ * so an instance that never picked a model keeps following the library's default across
67
+ * upgrades; a stored model the list does not carry is added after it, so the person sees what
68
+ * the setting holds rather than an empty box
69
+ *
70
+ * @param {string} selectedModel - The stored model name, empty for the default
71
+ * @returns {Promise<Object[]>} Entries with id, name, description and recommended
72
+ */
73
+ async function getOpenAiModels(selectedModel) {
74
+ const modelList = (await settings.get('openAiModels')) || OPEN_AI_MODELS;
75
+
76
+ const entries = modelList.map(model => {
77
+ // a list stored by an older release carries no description
78
+ const note = typeof model.description === 'string' ? { description: model.description, recommended: !!model.recommended } : describeModel(model.id);
79
+ return { id: model.id, name: model.name || model.id, description: note.description, recommended: note.recommended };
80
+ });
81
+
82
+ if (selectedModel && !entries.find(model => model.id === selectedModel)) {
83
+ entries.unshift({ id: selectedModel, name: selectedModel, description: 'Not in the list this API key can use', recommended: false });
84
+ }
85
+
86
+ return [defaultModelEntry()].concat(entries);
87
+ }
88
+
89
+ /**
90
+ * The reasoning effort select, with the stored level marked. "Default" leaves the choice to the
91
+ * library: "low" for a reasoning model, nothing for any other
92
+ *
93
+ * @param {string} selected - The stored level, empty for the default
94
+ * @returns {Object[]} Entries with value, label and selected
95
+ */
96
+ function reasoningEffortOptions(selected) {
97
+ return ['', ...REASONING_EFFORTS].map(value => ({
98
+ value,
99
+ label: REASONING_EFFORT_LABELS[value] || value.charAt(0).toUpperCase() + value.slice(1),
100
+ selected: value === (selected || '')
101
+ }));
102
+ }
103
+
104
+ module.exports = { getOpenAiModels, reasoningEffortOptions, aiPageSchema, aiFieldSchema, aiFieldValues, aiFieldStrings };