emailengine-app 2.81.2 → 2.82.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -0,0 +1,110 @@
1
+ 'use strict';
2
+
3
+ const { matchIp, parseComparableIp, parseComparableCidr } = require('../utils/network');
4
+
5
+ // POST /v1/tokens is only reachable by a full-privilege root token, so the new token can never
6
+ // hold a wider grant than its creator. The creator's restrictions and lifetime are a different
7
+ // axis, though: a root token limited to one address, one referrer, a rate limit or a one hour
8
+ // lifetime could otherwise mint a successor with none of those and walk out of every limit it
9
+ // was issued with. Rather than silently narrowing what the caller asked for (which would hand
10
+ // back a token that behaves differently from the request), the mint is refused unless the
11
+ // payload repeats each of the creator's limits at least as narrowly.
12
+
13
+ // Parses a single allowlist entry into [address, bits] with the same parsers matchIp() uses, so
14
+ // the containment check unwraps the IPv4-mapped IPv6 form exactly as the strategy does
15
+ function parseEntry(entry) {
16
+ if (/\/\d+$/.test(entry)) {
17
+ return parseComparableCidr(entry);
18
+ }
19
+ const addr = parseComparableIp(entry);
20
+ return [addr, addr.kind() === 'ipv6' ? 128 : 32];
21
+ }
22
+
23
+ // True when every address the entry describes is also allowed by the creator's list
24
+ function entryCovered(entry, allowed) {
25
+ let addr;
26
+ let bits;
27
+ try {
28
+ [addr, bits] = parseEntry(entry);
29
+ } catch (err) {
30
+ return false;
31
+ }
32
+
33
+ // A single address only needs to match; matchIp() already handles the forms the strategy uses
34
+ if (bits === (addr.kind() === 'ipv6' ? 128 : 32)) {
35
+ return matchIp(addr.toString(), allowed);
36
+ }
37
+
38
+ // A range is covered when it sits entirely inside one allowed range: same family, a prefix at
39
+ // least as long, and its network address inside that range
40
+ for (let candidate of allowed) {
41
+ try {
42
+ let [range, rangeBits] = parseEntry(candidate);
43
+ if (range.kind() === addr.kind() && bits >= rangeBits && addr.match(range, rangeBits)) {
44
+ return true;
45
+ }
46
+ } catch (err) {
47
+ // an unparseable allowlist entry covers nothing
48
+ }
49
+ }
50
+ return false;
51
+ }
52
+
53
+ /**
54
+ * Lists the ways a requested token would be less restricted than the token minting it.
55
+ *
56
+ * @param {Object} creator - the minting token's record (request.auth.artifacts)
57
+ * @param {Object} payload - the validated mint payload
58
+ * @returns {string[]} human readable reasons, empty when the new token is at least as narrow
59
+ */
60
+ function mintWidenings(creator, payload) {
61
+ const reasons = [];
62
+ if (!creator || typeof creator !== 'object') {
63
+ return reasons;
64
+ }
65
+
66
+ const own = creator.restrictions || {};
67
+ const requested = (payload && payload.restrictions) || {};
68
+
69
+ if (Array.isArray(own.addresses) && own.addresses.length) {
70
+ const list = Array.isArray(requested.addresses) ? requested.addresses : [];
71
+ if (!list.length || !list.every(entry => entryCovered(entry, own.addresses))) {
72
+ reasons.push("restrictions.addresses must be set to addresses within the creating token's own address allowlist");
73
+ }
74
+ }
75
+
76
+ if (Array.isArray(own.referrers) && own.referrers.length) {
77
+ // Referrer entries are wildcard patterns, and deciding whether one pattern is contained in
78
+ // another is not worth the risk of getting it wrong, so each has to be repeated verbatim
79
+ const list = Array.isArray(requested.referrers) ? requested.referrers : [];
80
+ if (!list.length || !list.every(entry => own.referrers.includes(entry))) {
81
+ reasons.push("restrictions.referrers must be set to a subset of the creating token's own referrer allowlist");
82
+ }
83
+ }
84
+
85
+ if (own.rateLimit && own.rateLimit.maxRequests && own.rateLimit.timeWindow) {
86
+ const limit = requested.rateLimit;
87
+ // Both the burst and the sustained rate have to stay within the creator's limit
88
+ const narrow =
89
+ limit &&
90
+ limit.maxRequests &&
91
+ limit.timeWindow &&
92
+ limit.maxRequests <= own.rateLimit.maxRequests &&
93
+ limit.maxRequests * own.rateLimit.timeWindow <= own.rateLimit.maxRequests * limit.timeWindow;
94
+ if (!narrow) {
95
+ reasons.push("restrictions.rateLimit must be set no higher than the creating token's own rate limit");
96
+ }
97
+ }
98
+
99
+ if (creator.expires) {
100
+ const ownExpires = new Date(creator.expires).getTime();
101
+ const requestedExpires = payload && payload.expires ? new Date(payload.expires).getTime() : NaN;
102
+ if (!Number.isFinite(requestedExpires) || !(requestedExpires <= ownExpires)) {
103
+ reasons.push("expires must be set no later than the creating token's own expiry");
104
+ }
105
+ }
106
+
107
+ return reasons;
108
+ }
109
+
110
+ module.exports = { mintWidenings };
@@ -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
 
@@ -22,7 +22,7 @@ async function init(args) {
22
22
  const listing = await outbox.list(Object.assign({ logger }, request.query));
23
23
 
24
24
  // A queue entry carries the proxy the submission was told to use, and a failed one
25
- // also records the route it took under progress.error.networkRouting
25
+ // also records the route it took under progress.networkRouting
26
26
  for (const entry of listing.messages || []) {
27
27
  maskSecrets(entry);
28
28
  }
@@ -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
@@ -10,7 +10,7 @@ const { tlsSettingChanged } = require('../tls/store');
10
10
  const { queueStats } = require('../queue-stats');
11
11
  const Boom = require('@hapi/boom');
12
12
  const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, assertNoPrivilegedSettings, MASKED } = require('./route-helpers');
13
- const { settingsSchema, settingsQuerySchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
13
+ const { settingsSchema, settingsQuerySchema, isHiddenSetting, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
14
14
 
15
15
  // Response variant of the settings schema. Secret values are masked and returned as booleans,
16
16
  // any setting that has never been set is returned as null, and the virtual eventTypes key is
@@ -41,7 +41,6 @@ settingsOutputSchema.eventTypes = Joi.array()
41
41
  // the privileged keys to a narrowed credential, so the `write/settings` grant means the same thing
42
42
  // on both surfaces; test/settings-privileged-keys-test.js asserts the tool schema and the list
43
43
  // agree.
44
- const isHiddenSetting = key => (settingsSchema[key].describe().metas || []).some(meta => meta && meta.swaggerHidden);
45
44
  const MCP_SETTINGS_KEYS = Object.keys(settingsSchema).filter(key => !settings.privilegedKeys.includes(key) && !isHiddenSetting(key));
46
45
 
47
46
  async function init(args) {
@@ -98,7 +97,7 @@ async function init(args) {
98
97
  },
99
98
  options: {
100
99
  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.`,
100
+ 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
101
  tags: ['api', 'Settings'],
103
102
 
104
103
  plugins: {
@@ -197,6 +196,20 @@ async function init(args) {
197
196
  // restarted the workers. Each command reports its own failure, so this cannot mask
198
197
  // the error being thrown out of the catch.
199
198
  await maybeReloadTlsCertificates(call, request.logger, tlsChanged, { action: 'settings' });
199
+
200
+ // A listener's own settings (enabled, port, host, TLS switch) are read only when
201
+ // the worker starts, so the admin UI asks the main thread to restart the worker
202
+ // that changed. The API route did not, and a write here left the SMTP server or
203
+ // the IMAP proxy running on the old address until something else restarted it.
204
+ for (const { keys, cmd } of Object.values(consts.LISTENER_RELOADS)) {
205
+ if (keys.some(key => key in applied)) {
206
+ try {
207
+ await call({ cmd });
208
+ } catch (err) {
209
+ request.logger.error({ msg: 'Reload request failed', action: cmd, err });
210
+ }
211
+ }
212
+ }
200
213
  }
201
214
 
202
215
  return { updated: Object.keys(applied) };
@@ -312,14 +325,7 @@ async function init(args) {
312
325
  failAction,
313
326
 
314
327
  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')
328
+ queue: Joi.string().empty('').trim().valid('notify', 'submit').required().example('notify').description('Queue ID').label('QueueId')
323
329
  })
324
330
  },
325
331
 
@@ -328,7 +334,7 @@ async function init(args) {
328
334
  queue: Joi.string()
329
335
  .empty('')
330
336
  .trim()
331
- .valid('notify', 'submit', 'documents')
337
+ .valid('notify', 'submit')
332
338
  .required()
333
339
  .example('notify')
334
340
  .description('Queue ID')
@@ -420,14 +426,7 @@ async function init(args) {
420
426
  failAction,
421
427
 
422
428
  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')
429
+ queue: Joi.string().empty('').trim().valid('notify', 'submit').required().example('notify').description('Queue ID').label('QueueIdParam')
431
430
  }),
432
431
 
433
432
  payload: Joi.object({
@@ -440,7 +439,7 @@ async function init(args) {
440
439
  queue: Joi.string()
441
440
  .empty('')
442
441
  .trim()
443
- .valid('notify', 'submit', 'documents')
442
+ .valid('notify', 'submit')
444
443
  .required()
445
444
  .example('notify')
446
445
  .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: {
@@ -370,7 +392,7 @@ async function init(args) {
370
392
  name: 'list_tokens',
371
393
  title: 'List access tokens',
372
394
  description:
373
- 'List the access tokens on this instance, paged: description, scopes, restrictions, the account each is bound to and when it was last used. Token values are never shown. Filter with query, or with account for the tokens bound to one account.',
395
+ "List the access tokens on this instance, paged: description, scopes, restrictions, the account each is bound to and when it was last used. Token values are never shown. Filter with query, or with account for the tokens bound to one account. A credential that is itself bound to an account sees only that account's tokens, not the instance.",
374
396
  bounds: { pageSize: MCP_MAX_PAGE_SIZE }
375
397
  },
376
398
  openapi: {