emailengine-app 2.81.1 → 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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  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/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  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-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -3,7 +3,6 @@
3
3
  const { redis } = require('../db');
4
4
  const { Account } = require('../account');
5
5
  const getSecret = require('../get-secret');
6
- const settings = require('../settings');
7
6
  const Joi = require('joi');
8
7
  const { failAction } = require('../tools');
9
8
  const { handleError } = require('./route-helpers');
@@ -42,9 +41,7 @@ const {
42
41
  messageIdSchema,
43
42
  messageDetailsSchema,
44
43
  messageListSchema,
45
- messageEntrySchema,
46
44
  documentStoreSchema,
47
- documentStoreQuerySchema,
48
45
  searchSchema,
49
46
  messageUpdateSchema,
50
47
  addressSchema,
@@ -53,7 +50,9 @@ const {
53
50
  emailIdSchema,
54
51
  threadIdSchema,
55
52
  apiResponses,
56
- ENUM_DESCRIPTIONS
53
+ ENUM_DESCRIPTIONS,
54
+ MAX_MESSAGE_ATTACHMENTS,
55
+ apiBoolean
57
56
  } = require('../schemas');
58
57
 
59
58
  const listMessageFolderPathDescription =
@@ -69,6 +68,18 @@ const UPDATE_OP_ENTRY_EXAMPLE = {
69
68
 
70
69
  // Response field for a flag or label update operation. IMAP accounts return a boolean (whether
71
70
  // the operation succeeded), API-based accounts echo the requested values as an array.
71
+ // The `failed` member of a bulk response: the messages the server refused after retries. The
72
+ // labels are public type names in the OpenAPI document, so the prefix is the operation's.
73
+ const bulkFailedSchema = prefix =>
74
+ Joi.object({
75
+ emailIds: Joi.array()
76
+ .items(emailIdSchema)
77
+ .description('List of emailId values the server refused after retries (MS Graph API accounts only)')
78
+ .label(`${prefix}FailedEmailIds`)
79
+ })
80
+ .label(`${prefix}Failed`)
81
+ .description('Present when some messages could not be processed (MS Graph API accounts only)');
82
+
72
83
  const updateOpResultSchema = (op, noun, entryLabel, example, label) =>
73
84
  Joi.alternatives()
74
85
  .try(Joi.boolean(), Joi.array().items(Joi.string().label(entryLabel).example(UPDATE_OP_ENTRY_EXAMPLE[noun])))
@@ -85,7 +96,7 @@ const idMapSchema = Joi.array()
85
96
  .label('IdMapArray');
86
97
 
87
98
  async function init(args) {
88
- const { server, call, CORS_CONFIG, MAX_ATTACHMENT_SIZE, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT, documentStoreFeatureEnabled } = args;
99
+ const { server, call, CORS_CONFIG, MAX_ATTACHMENT_SIZE, MAX_BODY_SIZE, MAX_PAYLOAD_TIMEOUT } = args;
89
100
 
90
101
  // GET /v1/account/{account}/message/{message}/source - Download raw message
91
102
  server.route({
@@ -147,18 +158,20 @@ async function init(args) {
147
158
  method: 'GET',
148
159
  path: '/v1/account/{account}/message/{message}',
149
160
 
150
- async handler(request, h) {
161
+ async handler(request) {
151
162
  let accountObject = new Account({
152
163
  redis,
153
164
  account: request.params.account,
154
165
  call,
155
166
  secret: await getSecret(),
156
- esClient: await h.getESClient(request.logger),
157
167
  timeout: request.headers['x-ee-timeout']
158
168
  });
159
169
 
160
170
  try {
161
- return await accountObject.getMessage(request.params.message, request.query);
171
+ // detectBounce is not a query option: it is what this route asks of the client, and
172
+ // the internal fetches (a reply's reference, the sync path) do not pay for it
173
+ let options = Object.assign({}, request.query, { detectBounce: true });
174
+ return await accountObject.getMessage(request.params.message, options);
162
175
  } catch (err) {
163
176
  handleError(request, err);
164
177
  }
@@ -228,9 +241,7 @@ async function init(args) {
228
241
  .description('Which text content to return, use * for all. By default text content is not returned.')
229
242
  .label('MessageTextType'),
230
243
 
231
- webSafeHtml: Joi.boolean()
232
- .truthy('Y', 'true', '1')
233
- .falsy('N', 'false', 0)
244
+ webSafeHtml: apiBoolean()
234
245
  .default(false)
235
246
  .description('Shorthand option to fetch and preprocess HTML and inline images')
236
247
  .meta({ usage: FIELD_USAGE.webSafeHtml })
@@ -240,28 +251,19 @@ async function init(args) {
240
251
  // for" from an explicit false, because an explicit false is what overrides
241
252
  // the webSafeHtml shorthand. It resolves the tri-state to a boolean, so no
242
253
  // consumer downstream sees the undefined.
243
- embedAttachedImages: Joi.boolean()
244
- .truthy('Y', 'true', '1')
245
- .falsy('N', 'false', 0)
254
+ embedAttachedImages: apiBoolean()
246
255
  .description('If true, then fetches attached images and embeds these in the HTML as data URIs. Not set means false')
247
256
  .meta({ usage: FIELD_USAGE.embedAttachedImages })
248
257
  .label('EmbedImages'),
249
258
 
250
- preProcessHtml: Joi.boolean()
251
- .truthy('Y', 'true', '1')
252
- .falsy('N', 'false', 0)
253
- .default(false)
254
- .description('If true, then pre-processes HTML for compatibility')
255
- .label('PreProcess'),
259
+ preProcessHtml: apiBoolean().default(false).description('If true, then pre-processes HTML for compatibility').label('PreProcess'),
256
260
 
257
- markAsSeen: Joi.boolean()
258
- .truthy('Y', 'true', '1')
259
- .falsy('N', 'false', 0)
261
+ markAsSeen: apiBoolean()
260
262
  .default(false)
261
263
  .description('If true, then marks unseen email as seen while returning the message')
262
264
  .label('MarkAsSeen'),
263
265
 
264
- documentStore: documentStoreSchema.default(false)
266
+ documentStore: documentStoreSchema
265
267
  }),
266
268
 
267
269
  params: Joi.object({
@@ -421,6 +423,7 @@ async function init(args) {
421
423
  .label('MsgUploadReference')
422
424
  }).label('UploadAttachment')
423
425
  )
426
+ .max(MAX_MESSAGE_ATTACHMENTS)
424
427
  .description('List of attachments')
425
428
  .label('UploadAttachmentList'),
426
429
 
@@ -459,7 +462,6 @@ async function init(args) {
459
462
  .description('Referenced message ID. Not present when only a thread ID was referenced'),
460
463
  threadId: threadIdSchema.description('Referenced thread ID (Gmail API accounts only)').label('ResponseReferenceThreadId'),
461
464
  success: Joi.boolean().example(true).description('Was the referenced message processed').label('ResponseReferenceSuccess'),
462
- documentStore: documentStoreSchema.default(false),
463
465
  error: Joi.string().example('Referenced message was not found').description('An error message if referenced message processing failed')
464
466
  })
465
467
  .description('Reference info if referencing was requested')
@@ -627,6 +629,7 @@ async function init(args) {
627
629
  delete: updateOpResultSchema('delete', 'labels', 'BulkLabelEntry', ['Label3'], 'BulkLabelDeleteResult'),
628
630
  set: updateOpResultSchema('set', 'labels', 'BulkLabelEntry', ['Label1'], 'BulkLabelSetResult')
629
631
  }).label('BulkLabelUpdateResponse'),
632
+ failed: bulkFailedSchema('BulkUpdate'),
630
633
  emailIds: Joi.array()
631
634
  .items(emailIdSchema)
632
635
  .description('List of updated email IDs (Gmail API and MS Graph API accounts only)')
@@ -791,7 +794,8 @@ async function init(args) {
791
794
  .description(
792
795
  'An optional list of emailId values, if the server supports unique email IDs (Gmail API and MS Graph API accounts only). Null when no messages matched the search (Gmail API)'
793
796
  )
794
- .label('MovedEmailIdsArray')
797
+ .label('MovedEmailIdsArray'),
798
+ failed: bulkFailedSchema('BulkMove')
795
799
  }).label('MessagesMoveResponse'),
796
800
  failAction: 'log'
797
801
  }
@@ -851,9 +855,7 @@ async function init(args) {
851
855
  failAction,
852
856
 
853
857
  query: Joi.object({
854
- force: Joi.boolean()
855
- .truthy('Y', 'true', '1')
856
- .falsy('N', 'false', 0)
858
+ force: apiBoolean()
857
859
  .default(false)
858
860
  .description('Delete message even if not in Trash. Not supported for Gmail API accounts.')
859
861
  .label('ForceDelete')
@@ -942,9 +944,7 @@ async function init(args) {
942
944
 
943
945
  query: Joi.object({
944
946
  path: Joi.string().empty('').required().example('INBOX').description(listMessageFolderPathDescription),
945
- force: Joi.boolean()
946
- .truthy('Y', 'true', '1')
947
- .falsy('N', 'false', 0)
947
+ force: apiBoolean()
948
948
  .default(false)
949
949
  .description('Delete messages even if not in Trash. Not supported for Gmail API accounts (messages are always moved to Trash)')
950
950
  .label('ForceDelete')
@@ -983,7 +983,8 @@ async function init(args) {
983
983
  .label('DeletedEmailIdsArray')
984
984
  })
985
985
  .label('MessagesDeleted')
986
- .description('Value is present if messages were deleted permanently (MS Graph API accounts only)')
986
+ .description('Value is present if messages were deleted permanently (MS Graph API accounts only)'),
987
+ failed: bulkFailedSchema('BulkDelete')
987
988
  }).label('MessagesDeleteResponse'),
988
989
  failAction: 'log'
989
990
  }
@@ -995,13 +996,12 @@ async function init(args) {
995
996
  method: 'GET',
996
997
  path: '/v1/account/{account}/messages',
997
998
 
998
- async handler(request, h) {
999
+ async handler(request) {
999
1000
  let accountObject = new Account({
1000
1001
  redis,
1001
1002
  account: request.params.account,
1002
1003
  call,
1003
1004
  secret: await getSecret(),
1004
- esClient: await h.getESClient(request.logger),
1005
1005
  timeout: request.headers['x-ee-timeout']
1006
1006
  });
1007
1007
 
@@ -1067,7 +1067,7 @@ async function init(args) {
1067
1067
  .label('PageNumber'),
1068
1068
 
1069
1069
  pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize'),
1070
- documentStore: documentStoreSchema.default(false)
1070
+ documentStore: documentStoreSchema
1071
1071
  }).label('MessageQuery')
1072
1072
  },
1073
1073
 
@@ -1083,38 +1083,15 @@ async function init(args) {
1083
1083
  method: 'POST',
1084
1084
  path: '/v1/account/{account}/search',
1085
1085
 
1086
- async handler(request, h) {
1086
+ async handler(request) {
1087
1087
  let accountObject = new Account({
1088
1088
  redis,
1089
1089
  account: request.params.account,
1090
1090
  call,
1091
1091
  secret: await getSecret(),
1092
- esClient: await h.getESClient(request.logger),
1093
1092
  timeout: request.headers['x-ee-timeout']
1094
1093
  });
1095
1094
 
1096
- let extraValidationErrors = [];
1097
-
1098
- if (request.query.documentStore) {
1099
- for (let key of ['seq', 'modseq']) {
1100
- if (request.payload.search && key in request.payload.search) {
1101
- extraValidationErrors.push({ message: 'Not available when using Document Store', context: { key } });
1102
- }
1103
- }
1104
- } else {
1105
- for (let key of ['documentQuery']) {
1106
- if (key in request.payload) {
1107
- extraValidationErrors.push({ message: 'Requires Document Store to be enabled', context: { key } });
1108
- }
1109
- }
1110
- }
1111
-
1112
- if (extraValidationErrors.length) {
1113
- let error = new Error('Input validation failed');
1114
- error.details = extraValidationErrors;
1115
- return failAction(request, h, error);
1116
- }
1117
-
1118
1095
  try {
1119
1096
  return await accountObject.searchMessages(Object.assign(request.query, request.payload));
1120
1097
  } catch (err) {
@@ -1159,15 +1136,7 @@ async function init(args) {
1159
1136
  }),
1160
1137
 
1161
1138
  query: Joi.object({
1162
- path: Joi.string()
1163
- .when('documentStore', {
1164
- is: true,
1165
- then: Joi.optional(),
1166
- otherwise: Joi.required()
1167
- })
1168
- .example('INBOX')
1169
- .description(listMessageFolderPathDescription)
1170
- .label('Path'),
1139
+ path: Joi.string().required().example('INBOX').description(listMessageFolderPathDescription).label('Path'),
1171
1140
 
1172
1141
  cursor: Joi.string()
1173
1142
  .trim()
@@ -1188,36 +1157,17 @@ async function init(args) {
1188
1157
 
1189
1158
  pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page'),
1190
1159
 
1191
- useOutlookSearch: Joi.boolean()
1192
- .truthy('Y', 'true', '1')
1193
- .falsy('N', 'false', 0)
1160
+ useOutlookSearch: apiBoolean()
1194
1161
  .description('MS Graph only. Use the $search parameter for search queries instead of $filter')
1195
1162
  .meta({ usage: FIELD_USAGE.useOutlookSearch })
1196
1163
  .label('useOutlookSearch')
1197
1164
  .optional(),
1198
1165
 
1199
- documentStore: documentStoreSchema.default(false).meta({ swaggerHidden: true }),
1200
- exposeQuery: Joi.boolean()
1201
- .truthy('Y', 'true', '1')
1202
- .falsy('N', 'false', 0)
1203
- .description('If enabled then includes the combined query (as the documentStoreQuery field) in the response for debugging')
1204
- .label('exposeQuery')
1205
- .when('documentStore', {
1206
- is: true,
1207
- then: Joi.optional(),
1208
- otherwise: Joi.forbidden()
1209
- })
1210
- .meta({ swaggerHidden: true })
1166
+ documentStore: documentStoreSchema
1211
1167
  }),
1212
1168
 
1213
1169
  payload: Joi.object({
1214
- search: searchSchema,
1215
- documentQuery: Joi.object()
1216
- .min(1)
1217
- .description('Document Store query. Only allowed with `documentStore`.')
1218
- .label('DocumentQuery')
1219
- .unknown()
1220
- .meta({ swaggerHidden: true })
1170
+ search: searchSchema
1221
1171
  })
1222
1172
  .label('MessageSearchPayload')
1223
1173
  .example({
@@ -1250,157 +1200,17 @@ async function init(args) {
1250
1200
  }
1251
1201
  });
1252
1202
 
1253
- // POST /v1/unified/search - Unified search for messages
1254
- // Deprecated Document Store feature: only register this endpoint when the feature is enabled,
1255
- // otherwise it behaves like a regular 404.
1256
- if (documentStoreFeatureEnabled) {
1257
- server.route({
1258
- method: 'POST',
1259
- path: '/v1/unified/search',
1260
-
1261
- async handler(request, h) {
1262
- let accountObject = new Account({
1263
- redis,
1264
- call,
1265
- secret: await getSecret(),
1266
- esClient: await h.getESClient(request.logger),
1267
- timeout: request.headers['x-ee-timeout']
1268
- });
1269
-
1270
- let extraValidationErrors = [];
1271
-
1272
- for (let key of ['seq', 'modseq']) {
1273
- if (request.payload.search && key in request.payload.search) {
1274
- extraValidationErrors.push({ message: 'Not available when using Document Store', context: { key } });
1275
- }
1276
- }
1277
-
1278
- if (extraValidationErrors.length) {
1279
- let error = new Error('Input validation failed');
1280
- error.details = extraValidationErrors;
1281
- return failAction(request, h, error);
1282
- }
1283
-
1284
- let documentStoreEnabled = await settings.get('documentStoreEnabled');
1285
- if (!documentStoreEnabled) {
1286
- let error = new Error('Document store not enabled');
1287
- error.details = extraValidationErrors;
1288
- return failAction(request, h, error);
1289
- }
1290
-
1291
- try {
1292
- return await accountObject.searchMessages(Object.assign({ documentStore: true }, request.query, request.payload), { unified: true });
1293
- } catch (err) {
1294
- handleError(request, err);
1295
- }
1296
- },
1297
- options: {
1298
- description: 'Unified search for messages',
1299
- notes: 'Filter messages from the Document Store for multiple accounts or paths. Document Store must be enabled for the unified search to work.',
1300
- tags: ['api', 'Deprecated endpoints (Document Store)'],
1301
-
1302
- plugins: {
1303
- openapi: {
1304
- 'x-ee-impact': IMPACT.READONLY,
1305
- responses: apiResponses('Returns matching messages across all indexed accounts.', 400, 401, 403, 429, 500)
1306
- }
1307
- },
1308
-
1309
- auth: {
1310
- strategy: 'api-token',
1311
- mode: 'required'
1312
- },
1313
- cors: CORS_CONFIG,
1314
-
1315
- validate: {
1316
- options: {
1317
- stripUnknown: false,
1318
- abortEarly: false,
1319
- convert: true
1320
- },
1321
- failAction,
1322
-
1323
- query: Joi.object({
1324
- page: Joi.number()
1325
- .integer()
1326
- .min(0)
1327
- .max(1024 * 1024)
1328
- .default(0)
1329
- .example(0)
1330
- .description('Page number (zero indexed, so use 0 for first page)'),
1331
- pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page'),
1332
- exposeQuery: Joi.boolean()
1333
- .truthy('Y', 'true', '1')
1334
- .falsy('N', 'false', 0)
1335
- .description('If enabled then includes the combined query (as the documentStoreQuery field) in the response for debugging')
1336
- .label('exposeQuery')
1337
- .optional()
1338
- .meta({ swaggerHidden: true })
1339
- }),
1340
-
1341
- payload: Joi.object({
1342
- accounts: Joi.array()
1343
- .items(Joi.string().empty('').trim().max(256).example('example'))
1344
- .single()
1345
- .description('Optional list of account ID values')
1346
- .label('UnifiedSearchAccounts'),
1347
- paths: Joi.array()
1348
- .items(Joi.string().optional().example('INBOX'))
1349
- .single()
1350
- .description('Optional list of mailbox folder paths or specialUse flags')
1351
- .label('UnifiedSearchPaths'),
1352
- search: searchSchema,
1353
- documentQuery: Joi.object().min(1).description('Document Store query').label('DocumentQuery').unknown().meta({ swaggerHidden: true })
1354
- }).label('UnifiedSearchQuery')
1355
- },
1356
-
1357
- response: {
1358
- schema: Joi.object({
1359
- total: Joi.number()
1360
- .integer()
1361
- .example(120)
1362
- .description('Total number of matching messages (capped at 10000 by the Document Store)')
1363
- .label('UnifiedTotalNumber'),
1364
- page: Joi.number().integer().example(0).description('Current page number (zero-based)').label('UnifiedPageNumber'),
1365
- pages: Joi.number().integer().example(24).description('Total number of pages available').label('UnifiedPagesNumber'),
1366
- accounts: Joi.array()
1367
- .items(Joi.string().example('example'))
1368
- .description('Account filter used for the search, if provided')
1369
- .label('UnifiedSearchAccountsEcho'),
1370
- paths: Joi.array()
1371
- .items(Joi.string().example('INBOX'))
1372
- .description('Path filter used for the search, if provided')
1373
- .label('UnifiedSearchPathsEcho'),
1374
- messages: Joi.array()
1375
- .items(
1376
- messageEntrySchema
1377
- .keys({
1378
- account: accountIdSchema.description('Account ID this message belongs to')
1379
- })
1380
- .unknown()
1381
- .label('UnifiedMessageListEntry')
1382
- )
1383
- .label('UnifiedPageMessages'),
1384
- documentStoreQuery: documentStoreQuerySchema
1385
- }).label('UnifiedSearchResponse'),
1386
- failAction: 'log'
1387
- }
1388
- }
1389
- });
1390
- }
1391
-
1392
1203
  // GET /v1/account/{account}/text/{text} - Retrieve message text
1393
1204
  server.route({
1394
1205
  method: 'GET',
1395
1206
  path: '/v1/account/{account}/text/{text}',
1396
1207
 
1397
- async handler(request, h) {
1208
+ async handler(request) {
1398
1209
  let accountObject = new Account({
1399
1210
  redis,
1400
1211
  account: request.params.account,
1401
1212
  call,
1402
1213
  secret: await getSecret(),
1403
- esClient: await h.getESClient(request.logger),
1404
1214
  timeout: request.headers['x-ee-timeout']
1405
1215
  });
1406
1216
 
@@ -1461,15 +1271,13 @@ async function init(args) {
1461
1271
  .description('Which text content to return, use * for all. By default all contents are returned.')
1462
1272
  .label('TextSearchTextType'),
1463
1273
 
1464
- webSafeHtml: Joi.boolean()
1465
- .truthy('Y', 'true', '1')
1466
- .falsy('N', 'false', 0)
1274
+ webSafeHtml: apiBoolean()
1467
1275
  .default(false)
1468
1276
  .description('If true, then returns a single sanitized HTML rendering of the body instead of the raw text parts')
1469
1277
  .meta({ usage: FIELD_USAGE.webSafeText })
1470
1278
  .label('WebSafeText'),
1471
1279
 
1472
- documentStore: documentStoreSchema.default(false)
1280
+ documentStore: documentStoreSchema
1473
1281
  }),
1474
1282
 
1475
1283
  params: Joi.object({
@@ -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 };