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
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const Joi = require('joi');
4
+ const Boom = require('@hapi/boom');
4
5
  const { failAction } = require('../tools');
5
6
  const { oauth2Apps } = require('../oauth2-apps');
6
7
  const { verifyOAuth2App } = require('../oauth/verify-app');
@@ -13,7 +14,9 @@ const {
13
14
  googleTopicNameSchema,
14
15
  googleSubscriptionNameSchema,
15
16
  apiResponses,
16
- ENUM_DESCRIPTIONS
17
+ ENUM_DESCRIPTIONS,
18
+ apiBoolean,
19
+ formBoolean
17
20
  } = require('../schemas');
18
21
  const { handleError, throwNotFound, flattenOAuthAppMeta, MASKED } = require('./route-helpers');
19
22
  const { ENCRYPTED_APP_KEYS, MCP_MAX_PAGE_SIZE } = require('../consts');
@@ -154,19 +157,10 @@ async function init(args) {
154
157
  description: Joi.string().empty('').trim().max(1024).example('App description').description('OAuth2 application description'),
155
158
  title: Joi.string().empty('').trim().max(256).example('App title').description('Title for the application button'),
156
159
  provider: OAuth2ProviderSchema,
157
- enabled: Joi.boolean()
158
- .truthy('Y', 'true', '1', 'on')
159
- .falsy('N', 'false', 0, '')
160
- .example(true)
161
- .description('Is the application enabled')
162
- .label('AppEnabled'),
160
+ enabled: formBoolean().example(true).description('Is the application enabled').label('AppEnabled'),
163
161
  created: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('The time this entry was added'),
164
162
  updated: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('The time this entry was updated'),
165
- includeInListing: Joi.boolean()
166
- .truthy('Y', 'true', '1', 'on')
167
- .falsy('N', 'false', 0, '')
168
- .example(true)
169
- .description('Is the application listed in the hosted authentication form'),
163
+ includeInListing: formBoolean().example(true).description('Is the application listed in the hosted authentication form'),
170
164
 
171
165
  clientId: Joi.string()
172
166
  .example('4f05f488-d858-4f2c-bd12-1039062612fe')
@@ -292,19 +286,10 @@ async function init(args) {
292
286
  description: Joi.string().empty('').trim().max(1024).example('App description').description('OAuth2 application description'),
293
287
  title: Joi.string().empty('').trim().max(256).example('App title').description('Title for the application button'),
294
288
  provider: OAuth2ProviderSchema,
295
- enabled: Joi.boolean()
296
- .truthy('Y', 'true', '1', 'on')
297
- .falsy('N', 'false', 0, '')
298
- .example(true)
299
- .description('Is the application enabled')
300
- .label('AppEnabled'),
289
+ enabled: formBoolean().example(true).description('Is the application enabled').label('AppEnabled'),
301
290
  created: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('The time this entry was added'),
302
291
  updated: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('The time this entry was updated'),
303
- includeInListing: Joi.boolean()
304
- .truthy('Y', 'true', '1', 'on')
305
- .falsy('N', 'false', 0, '')
306
- .example(true)
307
- .description('Is the application listed in the hosted authentication form'),
292
+ includeInListing: formBoolean().example(true).description('Is the application listed in the hosted authentication form'),
308
293
 
309
294
  clientId: Joi.string()
310
295
  .example('4f05f488-d858-4f2c-bd12-1039062612fe')
@@ -402,7 +387,7 @@ async function init(args) {
402
387
  response: {
403
388
  schema: Joi.object({
404
389
  id: Joi.string().max(256).required().example('AAABhaBPHscAAAAH').description('OAuth2 application ID'),
405
- created: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the app created')
390
+ created: apiBoolean().default(true).description('Was the app created')
406
391
  }).label('CreateAppResponse'),
407
392
  failAction: 'log'
408
393
  }
@@ -415,6 +400,16 @@ async function init(args) {
415
400
 
416
401
  async handler(request) {
417
402
  try {
403
+ // The getters return every stored secret as the mask, and the mask is a perfectly
404
+ // valid string for these fields, so a read-modify-write client used to replace the
405
+ // real secret with "******" and break every account on the app
406
+ const echoed = ENCRYPTED_APP_KEYS.filter(key => request.payload[key] === MASKED);
407
+ if (echoed.length) {
408
+ throw Boom.badRequest(
409
+ `The value for ${echoed.map(key => `"${key}"`).join(', ')} is the masked placeholder "${MASKED}" instead of a secret. Send the real value, or leave the field out to keep the stored one`
410
+ );
411
+ }
412
+
418
413
  let result = await oauth2Apps.update(request.params.app, request.payload);
419
414
  return await applyPubSubUpdates(result);
420
415
  } catch (err) {
@@ -423,7 +418,7 @@ async function init(args) {
423
418
  },
424
419
  options: {
425
420
  description: 'Update OAuth2 application',
426
- notes: 'Updates OAuth2 application information',
421
+ notes: `Updates OAuth2 application information. Stored secrets (${ENCRYPTED_APP_KEYS.map(key => `\`${key}\``).join(', ')}) read back as "${MASKED}". A masked value is not the stored one - leave the field out of an update to keep the secret; sending the placeholder back is refused with 400.`,
427
422
  tags: ['api', 'OAuth2 Applications'],
428
423
 
429
424
  plugins: {
@@ -461,7 +456,7 @@ async function init(args) {
461
456
  description: Joi.string().trim().allow('').max(1024).example('My cool app').description('Application description'),
462
457
  title: Joi.string().allow('').trim().max(256).example('App title').description('Title for the application button'),
463
458
 
464
- enabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').example(true).description('Enable this app'),
459
+ enabled: formBoolean().example(true).description('Enable this app'),
465
460
 
466
461
  clientId: Joi.string()
467
462
  .trim()
@@ -618,7 +613,7 @@ async function init(args) {
618
613
  response: {
619
614
  schema: Joi.object({
620
615
  id: Joi.string().max(256).required().example('AAABhaBPHscAAAAH').description('OAuth2 application ID'),
621
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the OAuth2 application deleted'),
616
+ deleted: apiBoolean().default(true).description('Was the OAuth2 application deleted'),
622
617
  accounts: Joi.number().integer().example(12).description('The number of accounts registered with this application')
623
618
  }).label('DeleteAppRequestResponse'),
624
619
  failAction: 'log'
@@ -684,11 +679,7 @@ async function init(args) {
684
679
  .max(256)
685
680
  .example('user@example.com')
686
681
  .description('Mailbox address used to verify domain-wide delegation and live mailbox access'),
687
- testConnection: Joi.boolean()
688
- .truthy('Y', 'true', '1', 'on')
689
- .falsy('N', 'false', 0, '')
690
- .default(true)
691
- .description('Perform the live IMAP/API connection step when an access token is obtained')
682
+ testConnection: formBoolean().default(true).description('Perform the live IMAP/API connection step when an access token is obtained')
692
683
  }).label('VerifyOAuth2AppRequest')
693
684
  },
694
685
 
@@ -13,7 +13,7 @@
13
13
  // Only the exceptions are declared. resolveImpact() derives the default from the HTTP method, so
14
14
  // a plain GET needs nothing and a POST that writes needs nothing. Declare an impact when the
15
15
  // method is a bad proxy for the effect, which is both directions here:
16
- // `POST /v1/unified/search` only reads, and `PUT /v1/account/{account}/messages/delete`
16
+ // `POST /v1/account/{account}/search` only reads, and `PUT /v1/account/{account}/messages/delete`
17
17
  // deletes in bulk.
18
18
  //
19
19
  // The derivation lives here rather than in the one place that reads it today because it is about
@@ -6,7 +6,7 @@ const logger = require('../logger');
6
6
  const outbox = require('../outbox');
7
7
  const { failAction } = require('../tools');
8
8
  const { handleError, maskSecrets, MASK_NOTE } = require('./route-helpers');
9
- const { outboxEntrySchema, apiResponses } = require('../schemas');
9
+ const { outboxEntrySchema, apiResponses, apiBoolean } = require('../schemas');
10
10
  const { IMPACT } = require('./operation-impact');
11
11
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
12
12
 
@@ -195,7 +195,7 @@ async function init(args) {
195
195
 
196
196
  response: {
197
197
  schema: Joi.object({
198
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the message deleted'),
198
+ deleted: apiBoolean().default(true).description('Was the message deleted'),
199
199
  locked: Joi.boolean()
200
200
  .example(true)
201
201
  .description(
@@ -585,13 +585,7 @@ const GROUP_ROUTES = {
585
585
 
586
586
  // Returns a live OAuth2 access token for the account: a mail credential in its own right,
587
587
  // which outlives any narrowing on the token that fetched it
588
- 'GET /v1/account/{account}/oauth-token',
589
-
590
- // The deprecated Document Store. Disabled by default and leaving the releases on
591
- // 2026-10-01, so keeping it out of the grantable vocabulary means the removal does not
592
- // retire a slug a customer had written into a token.
593
- 'POST /v1/chat/{account}',
594
- 'POST /v1/unified/search'
588
+ 'GET /v1/account/{account}/oauth-token'
595
589
  ]
596
590
  };
597
591
 
@@ -155,11 +155,17 @@ function maskUrlPassword(url) {
155
155
  return parsed.href;
156
156
  }
157
157
 
158
- // Stored values that are URLs which may embed a password.
159
- const URL_SECRET_KEYS = ['proxy', 'proxyUrl', 'httpProxyUrl', 'webhooks', 'targetUrl', 'sentryDsn', 'documentStoreUrl'];
160
-
161
- // Stored values that are {key, value} header lists whose values are credentials.
162
- const HEADER_SECRET_KEYS = ['customHeaders', 'webhooksCustomHeaders'];
158
+ // Stored values that are URLs which may embed a password: the credential-bearing settings
159
+ // (lib/settings.js owns that list, so a setting added there is masked here without a second
160
+ // edit; `authServer` joined it because resolveCredentials() in lib/tools.js honours
161
+ // `https://user:pass@host/...` there, and a settings read handed out the basic-auth password of
162
+ // the credential service), plus the fields of the same shape that are not settings: the
163
+ // per-account `proxy` and a webhook route's `targetUrl`.
164
+ const URL_SECRET_KEYS = settings.credentialBearingUrlKeys.concat(['proxy', 'targetUrl']);
165
+
166
+ // Stored values that are {key, value} header lists whose values are credentials: the setting,
167
+ // and a webhook route's own list.
168
+ const HEADER_SECRET_KEYS = settings.credentialBearingHeaderKeys.concat(['customHeaders']);
163
169
 
164
170
  // A failed submission records the route it took, including the proxy it used, and that record is
165
171
  // then persisted onto the account, the gateway and the queue entry. So the same proxy URL reappears
@@ -98,7 +98,7 @@ async function init(args) {
98
98
  },
99
99
  options: {
100
100
  description: 'List specific settings',
101
- notes: `List setting values for specific keys. Credentials are masked: the credentials in any proxy or webhook URL and the values of custom webhook headers read back as "${MASKED}", and encrypted secrets are returned as booleans. A masked value is not the stored one - POST /v1/settings skips it when it matches the stored value and refuses it otherwise.`,
101
+ notes: `List setting values for specific keys. Credentials are masked: the credentials in any proxy, webhook or authentication server URL and the values of custom webhook headers read back as "${MASKED}", and encrypted secrets are returned as booleans. A masked value is not the stored one - POST /v1/settings skips it when it matches the stored value and refuses it otherwise.`,
102
102
  tags: ['api', 'Settings'],
103
103
 
104
104
  plugins: {
@@ -197,6 +197,20 @@ async function init(args) {
197
197
  // restarted the workers. Each command reports its own failure, so this cannot mask
198
198
  // the error being thrown out of the catch.
199
199
  await maybeReloadTlsCertificates(call, request.logger, tlsChanged, { action: 'settings' });
200
+
201
+ // A listener's own settings (enabled, port, host, TLS switch) are read only when
202
+ // the worker starts, so the admin UI asks the main thread to restart the worker
203
+ // that changed. The API route did not, and a write here left the SMTP server or
204
+ // the IMAP proxy running on the old address until something else restarted it.
205
+ for (const { keys, cmd } of Object.values(consts.LISTENER_RELOADS)) {
206
+ if (keys.some(key => key in applied)) {
207
+ try {
208
+ await call({ cmd });
209
+ } catch (err) {
210
+ request.logger.error({ msg: 'Reload request failed', action: cmd, err });
211
+ }
212
+ }
213
+ }
200
214
  }
201
215
 
202
216
  return { updated: Object.keys(applied) };
@@ -312,14 +326,7 @@ async function init(args) {
312
326
  failAction,
313
327
 
314
328
  params: Joi.object({
315
- queue: Joi.string()
316
- .empty('')
317
- .trim()
318
- .valid('notify', 'submit', 'documents')
319
- .required()
320
- .example('notify')
321
- .description('Queue ID')
322
- .label('QueueId')
329
+ queue: Joi.string().empty('').trim().valid('notify', 'submit').required().example('notify').description('Queue ID').label('QueueId')
323
330
  })
324
331
  },
325
332
 
@@ -328,7 +335,7 @@ async function init(args) {
328
335
  queue: Joi.string()
329
336
  .empty('')
330
337
  .trim()
331
- .valid('notify', 'submit', 'documents')
338
+ .valid('notify', 'submit')
332
339
  .required()
333
340
  .example('notify')
334
341
  .description('Queue ID')
@@ -420,14 +427,7 @@ async function init(args) {
420
427
  failAction,
421
428
 
422
429
  params: Joi.object({
423
- queue: Joi.string()
424
- .empty('')
425
- .trim()
426
- .valid('notify', 'submit', 'documents')
427
- .required()
428
- .example('notify')
429
- .description('Queue ID')
430
- .label('QueueIdParam')
430
+ queue: Joi.string().empty('').trim().valid('notify', 'submit').required().example('notify').description('Queue ID').label('QueueIdParam')
431
431
  }),
432
432
 
433
433
  payload: Joi.object({
@@ -440,7 +440,7 @@ async function init(args) {
440
440
  queue: Joi.string()
441
441
  .empty('')
442
442
  .trim()
443
- .valid('notify', 'submit', 'documents')
443
+ .valid('notify', 'submit')
444
444
  .required()
445
445
  .example('notify')
446
446
  .description('Queue ID')
@@ -97,7 +97,7 @@ async function init(args) {
97
97
  bullmq: Joi.string().example('5.0.0').description('BullMQ version'),
98
98
  arch: Joi.string().example('arm64').description('CPU architecture of the host'),
99
99
  build: Joi.object().unknown().description('Build information for the running EmailEngine instance').label('BuildInfo'),
100
- queues: Joi.object().unknown().description('Job counters for the notify, submit, and documents queues').label('QueueStats'),
100
+ queues: Joi.object().unknown().description('Job counters for the notify and submit queues').label('QueueStats'),
101
101
  connections: Joi.object({
102
102
  init: Joi.number().integer().example(2).description('Accounts not yet initialized'),
103
103
  connected: Joi.number().integer().example(8).description('Successfully connected accounts'),
@@ -11,6 +11,7 @@ const { IMPACT } = require('./operation-impact');
11
11
  const { FIELD_USAGE } = require('../field-usage');
12
12
  const {
13
13
  messageReferenceSchema,
14
+ documentStoreSchema,
14
15
  fromAddressSchema,
15
16
  addressSchema,
16
17
  idempotencyKeySchema,
@@ -22,7 +23,9 @@ const {
22
23
  ipSchema,
23
24
  threadIdSchema,
24
25
  apiResponses,
25
- ENUM_DESCRIPTIONS
26
+ ENUM_DESCRIPTIONS,
27
+ MAX_MESSAGE_ATTACHMENTS,
28
+ apiBoolean
26
29
  } = require('../schemas');
27
30
 
28
31
  // Schema fragments shared between the message submit and the draft submit routes. Joi schemas
@@ -34,7 +37,15 @@ const submitHeadersSchema = Joi.object({
34
37
 
35
38
  const sendAtSchema = Joi.date().iso().example('2021-07-08T07:06:34.336Z').description('Send message at specified time');
36
39
 
37
- const deliveryAttemptsSchema = Joi.number().integer().example(10).description('How many delivery attempts to make until message is considered as failed');
40
+ // Bounded like the instance-wide `deliveryAttempts` setting it overrides (which allows 0). The
41
+ // retry backoff is exponential and uncapped, so an arbitrarily large value kept a failing message
42
+ // and its Redis records in the queue indefinitely; a negative one was accepted as well.
43
+ const deliveryAttemptsSchema = Joi.number()
44
+ .integer()
45
+ .min(0)
46
+ .max(100)
47
+ .example(10)
48
+ .description('How many delivery attempts to make until message is considered as failed');
38
49
 
39
50
  const gatewaySchema = Joi.string().max(256).example('example').description('Optional SMTP gateway ID for message routing').label('MessageGateway');
40
51
 
@@ -201,14 +212,8 @@ async function init(args) {
201
212
  }),
202
213
 
203
214
  query: Joi.object({
204
- documentStore: Joi.boolean()
205
- .truthy('Y', 'true', '1')
206
- .falsy('N', 'false', 0)
207
- .default(false)
208
- .description('If enabled then fetch email used as a reference template from the Document Store'),
209
- useStructuredFormat: Joi.boolean()
210
- .truthy('Y', 'true', '1')
211
- .falsy('N', 'false', 0)
215
+ documentStore: documentStoreSchema,
216
+ useStructuredFormat: apiBoolean()
212
217
  .default(false)
213
218
  .description('For MS Graph accounts: send as structured JSON instead of raw MIME')
214
219
  .meta({ usage: FIELD_USAGE.useStructuredFormat })
@@ -361,6 +366,7 @@ async function init(args) {
361
366
  .label('AttachmentReference')
362
367
  }).label('UploadAttachment')
363
368
  )
369
+ .max(MAX_MESSAGE_ATTACHMENTS)
364
370
  .description('List of attachments')
365
371
  .label('UploadAttachmentList'),
366
372
 
@@ -424,9 +430,7 @@ async function init(args) {
424
430
  proxy: proxySchema,
425
431
  localAddress: localAddressSchema,
426
432
 
427
- dryRun: Joi.boolean()
428
- .truthy('Y', 'true', '1')
429
- .falsy('N', 'false', 0)
433
+ dryRun: apiBoolean()
430
434
  .default(false)
431
435
  .description(
432
436
  'If true, then EmailEngine does not send the email and returns an RFC822 formatted email file. Tracking information is not added to the email.'
@@ -474,11 +478,6 @@ async function init(args) {
474
478
  .example('AAAAAQAACnA')
475
479
  .description('Referenced message ID. Not present when only a thread ID was referenced'),
476
480
  threadId: threadIdSchema.description('Referenced thread ID (Gmail API accounts only)').label('SubmitResponseReferenceThreadId'),
477
- documentStore: Joi.boolean()
478
- .example(true)
479
- .description('Was the message data loaded from the Document Store')
480
- .label('ResponseDocumentStore')
481
- .meta({ swaggerHidden: true }),
482
481
  success: Joi.boolean().example(true).description('Was the referenced message processed successfully').label('ResponseReferenceSuccess'),
483
482
  error: Joi.string().example('Referenced message was not found').description('An error message if referenced message processing failed')
484
483
  })
@@ -8,7 +8,7 @@ const Joi = require('joi');
8
8
  const { failAction } = require('../tools');
9
9
  const { handleError, throwNotFound } = require('./route-helpers');
10
10
 
11
- const { templateSchemas, accountIdSchema, apiResponses } = require('../schemas');
11
+ const { templateSchemas, accountIdSchema, apiResponses, apiBoolean } = require('../schemas');
12
12
  const { IMPACT } = require('./operation-impact');
13
13
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
14
14
 
@@ -437,7 +437,7 @@ async function init(args) {
437
437
 
438
438
  response: {
439
439
  schema: Joi.object({
440
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the template deleted'),
440
+ deleted: apiBoolean().default(true).description('Was the template deleted'),
441
441
  account: templateAccountIdSchema,
442
442
  id: Joi.string().max(256).required().example('AAABgS-UcAYAAAABAA').description('Template ID')
443
443
  }).label('DeleteTemplateResponse'),
@@ -505,18 +505,13 @@ async function init(args) {
505
505
  }),
506
506
 
507
507
  query: Joi.object({
508
- force: Joi.boolean()
509
- .truthy('Y', 'true', '1')
510
- .falsy('N', 'false', 0)
511
- .default(false)
512
- .description('Must be true in order to flush templates')
513
- .label('ForceFlush')
508
+ force: apiBoolean().default(false).description('Must be true in order to flush templates').label('ForceFlush')
514
509
  }).label('FlushTemplateQuery')
515
510
  },
516
511
 
517
512
  response: {
518
513
  schema: Joi.object({
519
- flushed: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Were the templates flushed'),
514
+ flushed: apiBoolean().default(true).description('Were the templates flushed'),
520
515
  account: accountIdSchema.required()
521
516
  }).label('FlushTemplatesResponse'),
522
517
  failAction: 'log'
@@ -9,8 +9,18 @@ const tokens = require('../tokens');
9
9
  const tokenAuditLog = require('../token-audit-log');
10
10
  const { failAction } = require('../tools');
11
11
  const { handleError, throwNotFound } = require('./route-helpers');
12
- const { accountIdSchema, tokenRestrictionsSchema, tokenPermissionsSchema, ipSchema, tokenIdSchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
12
+ const {
13
+ accountIdSchema,
14
+ tokenRestrictionsSchema,
15
+ tokenPermissionsSchema,
16
+ ipSchema,
17
+ tokenIdSchema,
18
+ apiResponses,
19
+ ENUM_DESCRIPTIONS,
20
+ apiBoolean
21
+ } = require('../schemas');
13
22
  const { IMPACT } = require('./operation-impact');
23
+ const { mintWidenings } = require('./mint-bounds');
14
24
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
15
25
 
16
26
  const tokenAccessSchema = Joi.object({
@@ -189,7 +199,7 @@ async function init(args) {
189
199
  }).label('DeleteTokenRequest');
190
200
 
191
201
  const deleteTokenResponseSchema = Joi.object({
192
- deleted: Joi.boolean().truthy('Y', 'true', '1').falsy('N', 'false', 0).default(true).description('Was the token deleted')
202
+ deleted: apiBoolean().default(true).description('Was the token deleted')
193
203
  }).label('DeleteTokenRequestResponse');
194
204
 
195
205
  const provisionTokenHandler = async request => {
@@ -221,8 +231,20 @@ async function init(args) {
221
231
  // Safe because this route sits in the never-grantable `admin` group and has no
222
232
  // `{account}` parameter, so an account-bound token is refused by the binding check and
223
233
  // a narrowed one by the group check. The caller is therefore always a full-privilege
224
- // root token, and every token it can mint here is strictly narrower than what it
225
- // already holds.
234
+ // root token, and every token it can mint here holds no wider a grant than it does.
235
+ // Its restrictions and lifetime are checked separately below.
236
+ //
237
+ // A root token limited to an address, a referrer, a rate limit or an expiry must not
238
+ // mint a successor without them, or every limit it was issued with is one request
239
+ // away from gone. Refused rather than inherited, so the token returned always behaves
240
+ // exactly as the payload asked.
241
+ const widenings = mintWidenings(request.auth.artifacts, request.payload);
242
+ if (widenings.length) {
243
+ const error = Boom.forbidden(`The new token would be less restricted than the token creating it: ${widenings.join('; ')}`);
244
+ error.output.payload.code = 'MintWidensRestrictions';
245
+ throw error;
246
+ }
247
+
226
248
  if (request.payload.account) {
227
249
  // throws if account does not exist
228
250
  await accountObject.loadAccountData();
@@ -258,7 +280,7 @@ async function init(args) {
258
280
  // The conditional requirement is stated here because the schema cannot carry it: a flat
259
281
  // `required` array has no way to say "unless `account` is set", and marking `permissions`
260
282
  // required outright would describe the ordinary account-bound mint as invalid.
261
- notes: 'Provisions a new access token. Either bind it to an account, or set `permissions` - an instance-wide token that is not narrowed reaches every account and every endpoint, so the API declines to mint one.',
283
+ notes: 'Provisions a new access token. Either bind it to an account, or set `permissions` - an instance-wide token that is not narrowed reaches every account and every endpoint, so the API declines to mint one. A token can not mint one less restricted than itself: when the calling token has an address allowlist, a referrer allowlist, a rate limit or an expiry, the request has to repeat each of them at least as narrowly (addresses within its allowlist, referrers from its list, a rate no higher, an expiry no later), otherwise it is refused with 403.',
262
284
  tags: ['api', 'Access Tokens'],
263
285
 
264
286
  plugins: {
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ // The hapi authentication scheme behind the `api-token` strategy: `Authorization: Bearer <token>`,
4
+ // or the `access_token` query parameter when the strategy allows it. Replaces hapi-auth-bearer-token
5
+ // (unmaintained since 2020, and the last thing pinning @hapi/hoek 9 into the tree) with exactly the
6
+ // subset EmailEngine used, response for response: test/api-token-scheme-test.js replays the
7
+ // responses recorded from the plugin.
8
+ //
9
+ // The contract with the strategy's validate() is unchanged. It is called as
10
+ // validate(request, token, h) and answers { isValid, credentials, artifacts }; an error it throws
11
+ // is not caught here, so the coded refusals the api-token strategy raises (UnknownToken,
12
+ // ExpiredToken, a permission refusal) reach the client as they always did. A request that carries
13
+ // no bearer token at all is reported as missing authentication, which is what lets a route with
14
+ // `mode: 'optional'` or `'try'` continue without one.
15
+
16
+ const Boom = require('@hapi/boom');
17
+
18
+ const SCHEME_NAME = 'api-token-bearer';
19
+ const TOKEN_TYPE = 'Bearer';
20
+ const ACCESS_TOKEN_NAME = 'access_token';
21
+
22
+ /**
23
+ * Scheme implementation for server.auth.scheme(SCHEME_NAME, apiTokenScheme)
24
+ *
25
+ * @param {object} server - Hapi server (unused, part of the scheme signature)
26
+ * @param {object} options - Strategy options
27
+ * @param {Function} options.validate - Token validation function
28
+ * @param {boolean} [options.allowQueryToken=false] - Also accept the token as `?access_token=`
29
+ */
30
+ function apiTokenScheme(server, options) {
31
+ if (!options || typeof options.validate !== 'function') {
32
+ throw new TypeError('The api-token scheme needs a validate function');
33
+ }
34
+
35
+ const { validate, allowQueryToken = false } = options;
36
+
37
+ return {
38
+ authenticate: async (request, h) => {
39
+ let authorization = request.raw.req.headers.authorization;
40
+
41
+ if (allowQueryToken && !authorization && request.query[ACCESS_TOKEN_NAME]) {
42
+ authorization = `${TOKEN_TYPE} ${request.query[ACCESS_TOKEN_NAME]}`;
43
+ // a credential, not an input the handler or its payload validation should see
44
+ delete request.query[ACCESS_TOKEN_NAME];
45
+ }
46
+
47
+ if (!authorization) {
48
+ throw Boom.unauthorized(null, TOKEN_TYPE);
49
+ }
50
+
51
+ const [tokenType, token] = authorization.split(/\s+/);
52
+ if (!token || tokenType.toLowerCase() !== TOKEN_TYPE.toLowerCase()) {
53
+ throw Boom.unauthorized(null, TOKEN_TYPE);
54
+ }
55
+
56
+ const { isValid, credentials, artifacts } = await validate(request, token, h);
57
+
58
+ if (!isValid) {
59
+ return h.unauthenticated(Boom.unauthorized('Bad token', TOKEN_TYPE), { credentials: credentials || {}, artifacts });
60
+ }
61
+
62
+ if (!credentials || typeof credentials !== 'object') {
63
+ return h.unauthenticated(Boom.badImplementation('Bad token string received for Bearer auth validation'), { credentials: {} });
64
+ }
65
+
66
+ return h.authenticated({ credentials, artifacts });
67
+ }
68
+ };
69
+ }
70
+
71
+ module.exports = { apiTokenScheme, SCHEME_NAME, TOKEN_TYPE, ACCESS_TOKEN_NAME };
package/lib/arf-detect.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const libmime = require('libmime');
4
4
  const addressparser = require('nodemailer/lib/addressparser');
5
5
  const { toCamelCase } = require('./utils/to-camel-case');
6
- const { decodeHeaders } = require('./utils/decode-headers');
6
+ const { decodeHeaders, capHeaderBlock } = require('./utils/decode-headers');
7
7
  const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
8
8
 
9
9
  // The attachment types a complaint is read from: the ARF report itself, and the copy of the
@@ -29,6 +29,31 @@ const ARF_SINGLE = [
29
29
  'incidents'
30
30
  ];
31
31
 
32
+ // A feedback report is a handful of short fields and the original headers a few kilobytes. Both
33
+ // arrive in attachments bounded only by the message size; decodeHeaders() cuts each block to
34
+ // MAX_HEADER_BLOCK_SIZE before it is decoded. No single ARF field is anywhere near this long; a
35
+ // longer one is truncated
36
+ const MAX_FIELD_LENGTH = 2048;
37
+
38
+ function capField(value) {
39
+ return value.length > MAX_FIELD_LENGTH ? value.substring(0, MAX_FIELD_LENGTH) : value;
40
+ }
41
+
42
+ // Strips surrounding whitespace and angle brackets. A single linear pass: the regex this replaces,
43
+ // /^[\s<]*|[>\s]*$/g, retried the trailing alternative from every position of a long whitespace
44
+ // run, which is quadratic.
45
+ function stripAngleBrackets(value) {
46
+ let start = 0;
47
+ let end = value.length;
48
+ while (start < end && (value[start] === '<' || /\s/.test(value[start]))) {
49
+ start++;
50
+ }
51
+ while (end > start && (value[end - 1] === '>' || /\s/.test(value[end - 1]))) {
52
+ end--;
53
+ }
54
+ return value.substring(start, end);
55
+ }
56
+
32
57
  const arfDetect = async messageInfo => {
33
58
  const report = {
34
59
  arf: {},
@@ -42,7 +67,7 @@ const arfDetect = async messageInfo => {
42
67
  case 'message/feedback-report': {
43
68
  // found a feedback report
44
69
 
45
- const contents = decodeHeaders((attachment.content || '').toString());
70
+ const contents = decodeHeaders(attachment.content);
46
71
 
47
72
  Object.keys(contents).forEach(key => {
48
73
  let value = contents[key];
@@ -52,12 +77,14 @@ const arfDetect = async messageInfo => {
52
77
  }
53
78
 
54
79
  if (ARF_SINGLE.includes(key)) {
55
- value = Array.isArray(contents[key]) ? contents[key].join(',') : (contents[key] || '').toString();
80
+ value = capField(Array.isArray(contents[key]) ? contents[key].join(',') : (contents[key] || '').toString());
56
81
  } else if (!Array.isArray(value)) {
57
82
  value = []
58
83
  .concat(value || [])
59
- .map(element => (element || '').toString().trim())
84
+ .map(element => capField((element || '').toString().trim()))
60
85
  .filter(element => element);
86
+ } else {
87
+ value = value.map(element => (typeof element === 'string' ? capField(element) : element));
61
88
  }
62
89
 
63
90
  if (!value || !value.length) {
@@ -66,7 +93,7 @@ const arfDetect = async messageInfo => {
66
93
 
67
94
  switch (key) {
68
95
  case 'original-mail-from':
69
- value = value.replace(/^[\s<]*|[>\s]*$/g, '');
96
+ value = stripAngleBrackets(value);
70
97
  break;
71
98
 
72
99
  case 'arrival-date':
@@ -90,7 +117,7 @@ const arfDetect = async messageInfo => {
90
117
  case 'message/rfc822-headers':
91
118
  case 'text/rfc822-headers':
92
119
  case 'text/rfc822-header': {
93
- let contents = (attachment.content || '').toString();
120
+ let contents = capHeaderBlock(attachment.content);
94
121
  const headerPos = contents.match(/\r?\n\r?\n/);
95
122
 
96
123
  if (headerPos) {