emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -122,7 +122,7 @@ function registerGetMessageSource(server, args) {
122
122
  },
123
123
  options: {
124
124
  description: 'Download raw message',
125
- notes: 'Fetches raw message as a stream',
125
+ notes: 'Streams the raw RFC 822 source of the message as the server stores it, headers and MIME parts included.',
126
126
  tags: ['api', 'Message'],
127
127
 
128
128
  auth: {
@@ -132,6 +132,14 @@ function registerGetMessageSource(server, args) {
132
132
  cors: CORS_CONFIG,
133
133
 
134
134
  plugins: {
135
+ mcp: {
136
+ name: 'get_message_source',
137
+ title: 'Get raw message source',
138
+ description:
139
+ 'Download the raw RFC 822 source of one message, headers and MIME parts included, returned inline as a base64 resource. Use get_message for the parsed message; this is for inspecting headers such as authentication results, or forwarding the original. Fails above 1 MB.',
140
+ binary: true,
141
+ resourceUriTemplate: 'emailengine://account/{account}/message/{message}/source'
142
+ },
135
143
  openapi: {
136
144
  produces: ['message/rfc822'],
137
145
  responses: apiResponses('Returns the raw RFC822 message source.', 400, 401, 403, 404, 429, 500, 503)
@@ -390,11 +398,11 @@ function registerUploadMessage(server, args) {
390
398
  .single()
391
399
  .description('List of addresses')
392
400
  .example([{ address: 'recipient@example.com' }])
393
- .label('AddressList'),
401
+ .label('UploadToAddressList'),
394
402
 
395
- cc: Joi.array().items(addressSchema).single().description('List of addresses').label('AddressList'),
403
+ cc: Joi.array().items(addressSchema).single().description('List of addresses').label('UploadAddressList'),
396
404
 
397
- bcc: Joi.array().items(addressSchema).single().description('List of addresses').label('AddressList'),
405
+ bcc: Joi.array().items(addressSchema).single().description('List of addresses').label('UploadAddressList'),
398
406
 
399
407
  subject: Joi.string()
400
408
  .allow('')
@@ -704,7 +712,7 @@ function registerMoveMessage(server, args) {
704
712
  },
705
713
  options: {
706
714
  description: 'Move a message to a specified folder',
707
- notes: 'Moves a message to a target folder',
715
+ notes: 'Moves a message to another folder of the same account. When the server reports it, the response carries the ID the message has in the target folder, which can differ from the one it had.',
708
716
  tags: ['api', 'Message'],
709
717
 
710
718
  plugins: {
@@ -1087,7 +1095,7 @@ function registerListMessages(server, args) {
1087
1095
  },
1088
1096
  options: {
1089
1097
  description: 'List messages in a folder',
1090
- notes: 'Lists messages in a mailbox folder',
1098
+ notes: 'Lists the messages of one folder, newest first, one page at a time. Each entry carries the envelope, flags and labels, not the message body; use the message endpoint for the content.',
1091
1099
  tags: ['api', 'Message'],
1092
1100
 
1093
1101
  plugins: {
@@ -1304,7 +1312,7 @@ function registerGetMessageText(server, args) {
1304
1312
  },
1305
1313
  options: {
1306
1314
  description: 'Retrieve message text',
1307
- notes: 'Retrieves message text',
1315
+ notes: 'Returns the plain text and HTML content of a message by the text ID from the message details, decoded to UTF-8.',
1308
1316
  tags: ['api', 'Message'],
1309
1317
 
1310
1318
  plugins: {
@@ -16,11 +16,13 @@ const {
16
16
  apiResponses,
17
17
  ENUM_DESCRIPTIONS,
18
18
  apiBoolean,
19
- formBoolean
19
+ formBoolean,
20
+ listQuerySchema
20
21
  } = require('../schemas');
21
22
  const { handleError, throwNotFound, flattenOAuthAppMeta, assertNoAttachedIdentity, MASKED } = require('./route-helpers');
22
23
  const { ENCRYPTED_APP_KEYS, MCP_MAX_PAGE_SIZE } = require('../consts');
23
24
  const { IMPACT } = require('./operation-impact');
25
+ const { deprecated } = require('../deprecations');
24
26
 
25
27
  // Stored fields that are returned on OAuth2 application objects in addition to the basic fields
26
28
  const oauth2AppExtraFields = {
@@ -62,7 +64,7 @@ function registerListOAuth2Apps(server, ctx) {
62
64
 
63
65
  async handler(request) {
64
66
  try {
65
- let response = await oauth2Apps.list(request.query.page, request.query.pageSize);
67
+ let response = await oauth2Apps.list(request.query.page, request.query.pageSize, { query: request.query.query });
66
68
 
67
69
  for (let app of response.apps) {
68
70
  for (let secretKey of ENCRYPTED_APP_KEYS) {
@@ -90,7 +92,7 @@ function registerListOAuth2Apps(server, ctx) {
90
92
 
91
93
  options: {
92
94
  description: 'List OAuth2 applications',
93
- notes: 'Lists registered OAuth2 applications',
95
+ notes: 'Lists the stored OAuth2 applications, one page at a time. Client secrets and keys are not included.',
94
96
  tags: ['api', 'OAuth2 Applications'],
95
97
 
96
98
  plugins: {
@@ -129,8 +131,9 @@ function registerListOAuth2Apps(server, ctx) {
129
131
  .example(0)
130
132
  .description('Page number (zero indexed, so use 0 for first page)')
131
133
  .label('PageNumber'),
132
- pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize')
133
- }).label('GatewaysFilter')
134
+ pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize'),
135
+ query: listQuerySchema('ID, name, description, client ID, service account or Pub/Sub names', 'OAuth2AppsListQuery')
136
+ }).label('OAuth2AppsFilter')
134
137
  },
135
138
 
136
139
  response: {
@@ -539,7 +542,11 @@ function registerUpdateOAuth2App(server, ctx) {
539
542
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.azureCloud })
540
543
  .label('AzureCloud'),
541
544
 
542
- tenant: Joi.string().trim().empty('').max(1024).example('f8cdef31-a31e-4b4a-93e4-5f571e91255a').label('Directorytenant'),
545
+ // The admin form's way of naming a directory tenant (authority 'tenant' plus this
546
+ // value). Over the API the tenant ID goes into authority itself
547
+ tenant: deprecated(Joi.string().trim().empty('').max(1024).example('f8cdef31-a31e-4b4a-93e4-5f571e91255a'), 'tenant').label(
548
+ 'Directorytenant'
549
+ ),
543
550
 
544
551
  redirectUrl: Joi.string()
545
552
  .allow('', null, false)
@@ -585,7 +592,7 @@ function registerDeleteOAuth2App(server, ctx) {
585
592
  },
586
593
  options: {
587
594
  description: 'Remove OAuth2 application',
588
- notes: 'Delete OAuth2 application data',
595
+ notes: 'Deletes a stored OAuth2 application. Accounts that authenticate through it can no longer connect.',
589
596
  tags: ['api', 'OAuth2 Applications'],
590
597
 
591
598
  plugins: {
@@ -709,7 +716,7 @@ function registerVerifyOAuth2App(server, ctx) {
709
716
  Joi.object({
710
717
  id: Joi.string().example('signJwt').description('Step identifier'),
711
718
  label: Joi.string().example('Sign assertion (signJwt)').description('Human readable step name'),
712
- status: Joi.string().valid('ok', 'fail', 'skip').example('ok').description('Step outcome'),
719
+ status: Joi.string().valid('ok', 'fail', 'skip').example('ok').description('Step outcome').label('OAuth2VerifyStepStatus'),
713
720
  message: Joi.string().allow(null).example('Assertion signed via IAM signJwt').description('Outcome detail'),
714
721
  hint: Joi.string()
715
722
  .example('Grant roles/iam.serviceAccountTokenCreator to the workload principal')
@@ -1,25 +1,45 @@
1
1
  'use strict';
2
2
 
3
- const Boom = require('@hapi/boom');
4
3
  const Joi = require('joi');
5
4
  const logger = require('../logger');
6
5
  const outbox = require('../outbox');
7
6
  const { failAction } = require('../tools');
8
- const { handleError, maskSecrets, MASK_NOTE } = require('./route-helpers');
9
- const { outboxEntrySchema, apiResponses, apiBoolean } = require('../schemas');
7
+ const { handleError, maskSecrets, MASK_NOTE, throwNotFound } = require('./route-helpers');
8
+
9
+ // What every per-message route answers for an unknown queue ID, and on the account routes for the
10
+ // queue ID of another account's message. The state refusals the outbox module throws (code
11
+ // NotFailed, ContentGone, NotDelayed) carry a 409 of their own
12
+ const QUEUE_ENTRY_NOT_FOUND = 'Requested queue entry was not found';
13
+ const { outboxEntrySchema, accountIdSchema, apiResponses, apiBoolean } = require('../schemas');
14
+ const { routeScopes, routeParams, scopedLabel, mcpFor, pagingQuery } = require('./scoped-routes');
10
15
  const { IMPACT } = require('./operation-impact');
11
16
  const { MCP_MAX_PAGE_SIZE } = require('../consts');
12
17
 
13
- function registerListOutbox(server, ctx) {
18
+ // Every outbox route exists twice, for the instance and for one account (see scoped-routes.js), so
19
+ // a bound credential cannot act on another account's message by its queue ID
20
+ const SCOPES = routeScopes({ instance: '/v1/outbox', account: '/v1/account/{account}/outbox' });
21
+
22
+ const outboxStateSchema = Joi.string()
23
+ .valid(...outbox.JOB_STATES)
24
+ .example('failed')
25
+ .description('List only messages in this state')
26
+ .label('OutboxStateFilter');
27
+
28
+ function registerListOutbox(server, ctx, scope) {
14
29
  const { CORS_CONFIG } = ctx;
15
30
 
31
+ const query = Object.assign(pagingQuery(), { state: outboxStateSchema });
32
+ if (scope.isInstance) {
33
+ query.account = accountIdSchema.description('List only messages queued by this account');
34
+ }
35
+
16
36
  server.route({
17
37
  method: 'GET',
18
- path: '/v1/outbox',
38
+ path: scope.prefix,
19
39
 
20
40
  async handler(request) {
21
41
  try {
22
- const listing = await outbox.list(Object.assign({ logger }, request.query));
42
+ const listing = await outbox.list(Object.assign({ logger }, request.query, request.params.account ? { account: request.params.account } : {}));
23
43
 
24
44
  // A queue entry carries the proxy the submission was told to use, and a failed one
25
45
  // also records the route it took under progress.networkRouting
@@ -34,17 +54,19 @@ function registerListOutbox(server, ctx) {
34
54
  },
35
55
 
36
56
  options: {
37
- description: 'List queued messages',
38
- notes: `Lists messages in the Outbox. ${MASK_NOTE}`,
57
+ description: scope.isInstance ? 'List queued messages' : 'List queued messages of an account',
58
+ notes: scope.isInstance
59
+ ? `Lists messages in the Outbox. With \`account\` set, only the messages that account has queued are listed, the same as the account outbox endpoint. ${MASK_NOTE}`
60
+ : `Lists the messages an account has in the Outbox: scheduled and waiting messages, those being delivered, and failed messages whose content is still stored for a retry. Reachable with an access token bound to the account. ${MASK_NOTE}`,
39
61
  tags: ['api', 'Outbox'],
40
62
 
41
63
  plugins: {
42
- mcp: {
64
+ mcp: mcpFor(scope, {
43
65
  name: 'get_outbox',
44
66
  title: 'List outbox',
45
67
  description: 'List messages queued for delivery, paged, including scheduled sends and their delivery progress.',
46
68
  bounds: { pageSize: MCP_MAX_PAGE_SIZE }
47
- },
69
+ }),
48
70
  openapi: {
49
71
  responses: apiResponses('Returns the messages currently queued for delivery.', 400, 401, 403, 429, 500)
50
72
  }
@@ -64,17 +86,8 @@ function registerListOutbox(server, ctx) {
64
86
  },
65
87
  failAction,
66
88
 
67
- query: Joi.object({
68
- page: Joi.number()
69
- .integer()
70
- .min(0)
71
- .max(1024 * 1024)
72
- .default(0)
73
- .example(0)
74
- .description('Page number (zero indexed, so use 0 for first page)')
75
- .label('PageNumber'),
76
- pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize')
77
- }).label('OutbixListFilter')
89
+ params: routeParams(scope),
90
+ query: Joi.object(query).label(scopedLabel(scope, 'OutboxListFilter'))
78
91
  },
79
92
 
80
93
  response: {
@@ -91,18 +104,18 @@ function registerListOutbox(server, ctx) {
91
104
  });
92
105
  }
93
106
 
94
- function registerGetOutboxEntry(server, ctx) {
95
- const { CORS_CONFIG, outboxEntryParams, notFound } = ctx;
107
+ function registerGetOutboxEntry(server, ctx, scope) {
108
+ const { CORS_CONFIG, queueIdParam } = ctx;
96
109
 
97
110
  server.route({
98
111
  method: 'GET',
99
- path: '/v1/outbox/{queueId}',
112
+ path: `${scope.prefix}/{queueId}`,
100
113
 
101
114
  async handler(request) {
102
115
  try {
103
- let outboxEntry = await outbox.get({ queueId: request.params.queueId, logger });
116
+ let outboxEntry = await outbox.get({ queueId: request.params.queueId, account: request.params.account, logger });
104
117
  if (!outboxEntry) {
105
- throw notFound();
118
+ throwNotFound(QUEUE_ENTRY_NOT_FOUND);
106
119
  }
107
120
  return maskSecrets(outboxEntry);
108
121
  } catch (err) {
@@ -116,12 +129,12 @@ function registerGetOutboxEntry(server, ctx) {
116
129
  tags: ['api', 'Outbox'],
117
130
 
118
131
  plugins: {
119
- mcp: {
132
+ mcp: mcpFor(scope, {
120
133
  name: 'get_queued_message',
121
134
  title: 'Get queued message',
122
135
  description:
123
136
  'Get one message in the sending queue by the queue id that send_message, send_draft or get_outbox returned: its recipients, scheduled time, delivery attempts and the last delivery error.'
124
- },
137
+ }),
125
138
  openapi: {
126
139
  responses: apiResponses('Returns the queued message, including its delivery attempts and last error.', 400, 401, 403, 404, 429, 500)
127
140
  }
@@ -141,7 +154,7 @@ function registerGetOutboxEntry(server, ctx) {
141
154
  },
142
155
  failAction,
143
156
 
144
- params: outboxEntryParams
157
+ params: routeParams(scope, queueIdParam).label(scopedLabel(scope, 'OutboxEntryParams'))
145
158
  },
146
159
 
147
160
  response: {
@@ -152,18 +165,18 @@ function registerGetOutboxEntry(server, ctx) {
152
165
  });
153
166
  }
154
167
 
155
- function registerRetryOutboxEntry(server, ctx) {
156
- const { CORS_CONFIG, outboxEntryParams, notFound } = ctx;
168
+ function registerRetryOutboxEntry(server, ctx, scope) {
169
+ const { CORS_CONFIG, queueIdParam } = ctx;
157
170
 
158
171
  server.route({
159
172
  method: 'POST',
160
- path: '/v1/outbox/{queueId}/retry',
173
+ path: `${scope.prefix}/{queueId}/retry`,
161
174
 
162
175
  async handler(request) {
163
176
  try {
164
- let result = await outbox.retry({ queueId: request.params.queueId, logger });
177
+ let result = await outbox.retry({ queueId: request.params.queueId, account: request.params.account, logger });
165
178
  if (!result) {
166
- throw notFound();
179
+ throwNotFound(QUEUE_ENTRY_NOT_FOUND);
167
180
  }
168
181
  return result;
169
182
  } catch (err) {
@@ -172,16 +185,16 @@ function registerRetryOutboxEntry(server, ctx) {
172
185
  },
173
186
  options: {
174
187
  description: 'Retry a failed message',
175
- notes: 'Puts a message whose delivery failed for good back into the queue with a fresh set of delivery attempts. Only a failed message whose content is still stored can be retried: the content of the most recent failures is kept for this, within the bounds set by EENGINE_QUEUE_KEEP_FAILED_CONTENT and EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE. A message that cannot be retried answers 409 with `code` NotFailed (the message is not in the failed state) or ContentGone (its content is no longer stored).',
188
+ notes: 'Puts a message whose delivery failed for good back into the queue with a fresh set of delivery attempts. Only a failed message whose content is still stored can be retried: the content of the most recent failures is kept for this, within the bounds set by the queueKeepFailedContent and queueKeepFailedContentSize settings (or EENGINE_QUEUE_KEEP_FAILED_CONTENT and EENGINE_QUEUE_KEEP_FAILED_CONTENT_SIZE, which win when set). A message that cannot be retried answers 409 with `code` NotFailed (the message is not in the failed state) or ContentGone (its content is no longer stored).',
176
189
  tags: ['api', 'Outbox'],
177
190
 
178
191
  plugins: {
179
- mcp: {
192
+ mcp: mcpFor(scope, {
180
193
  name: 'retry_queued_message',
181
194
  title: 'Retry failed message',
182
195
  description:
183
196
  'Retry a message whose delivery failed for good, by the queue id from get_outbox. Only a message in the failed state whose content is still stored can be retried; the error says when it cannot. A retried message starts over with a full set of delivery attempts.'
184
- },
197
+ }),
185
198
  openapi: {
186
199
  responses: apiResponses('Returns a retry marker. The message is waiting for a delivery attempt again.', 400, 401, 403, 404, 409, 429, 500)
187
200
  }
@@ -201,7 +214,7 @@ function registerRetryOutboxEntry(server, ctx) {
201
214
  },
202
215
  failAction,
203
216
 
204
- params: outboxEntryParams
217
+ params: routeParams(scope, queueIdParam).label(scopedLabel(scope, 'OutboxEntryParams'))
205
218
  },
206
219
 
207
220
  response: {
@@ -216,18 +229,18 @@ function registerRetryOutboxEntry(server, ctx) {
216
229
  });
217
230
  }
218
231
 
219
- function registerPromoteOutboxEntry(server, ctx) {
220
- const { CORS_CONFIG, outboxEntryParams, notFound } = ctx;
232
+ function registerPromoteOutboxEntry(server, ctx, scope) {
233
+ const { CORS_CONFIG, queueIdParam } = ctx;
221
234
 
222
235
  server.route({
223
236
  method: 'POST',
224
- path: '/v1/outbox/{queueId}/promote',
237
+ path: `${scope.prefix}/{queueId}/promote`,
225
238
 
226
239
  async handler(request) {
227
240
  try {
228
- let result = await outbox.promote({ queueId: request.params.queueId, logger });
241
+ let result = await outbox.promote({ queueId: request.params.queueId, account: request.params.account, logger });
229
242
  if (!result) {
230
- throw notFound();
243
+ throwNotFound(QUEUE_ENTRY_NOT_FOUND);
231
244
  }
232
245
  return result;
233
246
  } catch (err) {
@@ -240,12 +253,12 @@ function registerPromoteOutboxEntry(server, ctx) {
240
253
  tags: ['api', 'Outbox'],
241
254
 
242
255
  plugins: {
243
- mcp: {
256
+ mcp: mcpFor(scope, {
244
257
  name: 'send_queued_message_now',
245
258
  title: 'Send queued message now',
246
259
  description:
247
260
  'Deliver a queued message at the next opportunity instead of waiting for its scheduled time or for the backoff before its next attempt, by the queue id from get_outbox. Only a message in the delayed state can be promoted.'
248
- },
261
+ }),
249
262
  openapi: {
250
263
  responses: apiResponses('Returns a promotion marker. The message is waiting for a delivery attempt.', 400, 401, 403, 404, 409, 429, 500)
251
264
  }
@@ -265,7 +278,7 @@ function registerPromoteOutboxEntry(server, ctx) {
265
278
  },
266
279
  failAction,
267
280
 
268
- params: outboxEntryParams
281
+ params: routeParams(scope, queueIdParam).label(scopedLabel(scope, 'OutboxEntryParams'))
269
282
  },
270
283
 
271
284
  response: {
@@ -280,32 +293,32 @@ function registerPromoteOutboxEntry(server, ctx) {
280
293
  });
281
294
  }
282
295
 
283
- function registerDeleteOutboxEntry(server, ctx) {
284
- const { CORS_CONFIG, outboxEntryParams } = ctx;
296
+ function registerDeleteOutboxEntry(server, ctx, scope) {
297
+ const { CORS_CONFIG, queueIdParam } = ctx;
285
298
 
286
299
  server.route({
287
300
  method: 'DELETE',
288
- path: '/v1/outbox/{queueId}',
301
+ path: `${scope.prefix}/{queueId}`,
289
302
 
290
303
  async handler(request) {
291
304
  try {
292
- return await outbox.del({ queueId: request.params.queueId, logger });
305
+ return await outbox.del({ queueId: request.params.queueId, account: request.params.account, logger });
293
306
  } catch (err) {
294
307
  handleError(request, err);
295
308
  }
296
309
  },
297
310
  options: {
298
311
  description: 'Remove a message',
299
- notes: 'Remove a message from the outbox',
312
+ notes: 'Removes a queued message together with its stored content, so it is not sent. A message whose delivery attempt is running right now is not removed and is reported as locked.',
300
313
  tags: ['api', 'Outbox'],
301
314
 
302
315
  plugins: {
303
- mcp: {
316
+ mcp: mcpFor(scope, {
304
317
  name: 'cancel_queued_message',
305
318
  title: 'Cancel queued message',
306
319
  description:
307
320
  'Cancel a message waiting in the sending queue, by the queue id from get_outbox. A message already handed to the mail server cannot be cancelled.'
308
- },
321
+ }),
309
322
  openapi: {
310
323
  'x-ee-impact': IMPACT.DESTRUCTIVE,
311
324
  responses: apiResponses('Returns a deletion marker. A message already being delivered cannot be removed.', 400, 401, 403, 429, 500)
@@ -326,7 +339,7 @@ function registerDeleteOutboxEntry(server, ctx) {
326
339
  },
327
340
  failAction,
328
341
 
329
- params: outboxEntryParams
342
+ params: routeParams(scope, queueIdParam).label(scopedLabel(scope, 'OutboxEntryParams'))
330
343
  },
331
344
 
332
345
  response: {
@@ -348,21 +361,19 @@ async function init(args) {
348
361
  const { server, CORS_CONFIG } = args;
349
362
 
350
363
  // The queue ID of a message, as every per-message outbox route takes it
351
- const outboxEntryParams = Joi.object({
364
+ const queueIdParam = {
352
365
  queueId: Joi.string().max(100).example('d41f0423195f271f').description('Queue identifier for scheduled email').required()
353
- }).label('OutboxEntryParams');
354
-
355
- // What every per-message route answers for an unknown queue ID. The state refusals the
356
- // outbox module throws (code NotFailed, ContentGone, NotDelayed) carry a 409 of their own
357
- const notFound = () => Boom.boomify(new Error('Requested queue entry was not found'), { statusCode: 404 });
366
+ };
358
367
 
359
- const ctx = { CORS_CONFIG, outboxEntryParams, notFound };
368
+ const ctx = { CORS_CONFIG, queueIdParam };
360
369
 
361
- registerListOutbox(server, ctx);
362
- registerGetOutboxEntry(server, ctx);
363
- registerRetryOutboxEntry(server, ctx);
364
- registerPromoteOutboxEntry(server, ctx);
365
- registerDeleteOutboxEntry(server, ctx);
370
+ for (const scope of SCOPES.all) {
371
+ registerListOutbox(server, ctx, scope);
372
+ registerGetOutboxEntry(server, ctx, scope);
373
+ registerRetryOutboxEntry(server, ctx, scope);
374
+ registerPromoteOutboxEntry(server, ctx, scope);
375
+ registerDeleteOutboxEntry(server, ctx, scope);
376
+ }
366
377
  }
367
378
 
368
379
  module.exports = init;
@@ -126,6 +126,13 @@ const GROUP = {
126
126
  // in ADMIN, because a token that can mint tokens can widen itself.
127
127
  TOKEN: 'token',
128
128
 
129
+ // The webhook deliveries that failed for good: list, retry, remove. Its own group rather than
130
+ // part of `webhook` because a listing names what each failed event was about (the account, the
131
+ // folder, the message) across every account, which no `webhook` grant ever exposed: that group
132
+ // covered reading the route definitions and nothing more. A new group, so it is reachable only
133
+ // by a record that names it, never through IMPLICIT_GROUPS.
134
+ WEBHOOK_DELIVERIES: 'webhook-deliveries',
135
+
129
136
  // Adding accounts and gateways, and reconfiguring them, including where they connect. Its own
130
137
  // group rather than a write on `account` or `gateway` because both records keep their stored
131
138
  // credential across a partial update, so a change to nothing but `host` makes the next
@@ -268,7 +275,12 @@ const SURFACE_GRANTS = {
268
275
  { action: ACTION.WRITE, group: GROUP.OUTBOX },
269
276
  { action: ACTION.DESTRUCTIVE, group: GROUP.OUTBOX },
270
277
  { action: ACTION.READ, group: GROUP.DIAGNOSTICS },
271
- { action: ACTION.READ, group: GROUP.LOGS }
278
+ { action: ACTION.READ, group: GROUP.LOGS },
279
+ // The webhook deliveries that failed for good: listing them is observing the queues, a
280
+ // retry operates them, a removal is a deletion, the same three steps as the outbox above
281
+ { action: ACTION.READ, group: GROUP.WEBHOOK_DELIVERIES },
282
+ { action: ACTION.WRITE, group: GROUP.WEBHOOK_DELIVERIES },
283
+ { action: ACTION.DESTRUCTIVE, group: GROUP.WEBHOOK_DELIVERIES }
272
284
  ]
273
285
  };
274
286
 
@@ -479,7 +491,14 @@ const GROUP_ROUTES = {
479
491
  'GET /v1/outbox/{queueId}',
480
492
  'POST /v1/outbox/{queueId}/retry',
481
493
  'POST /v1/outbox/{queueId}/promote',
482
- 'DELETE /v1/outbox/{queueId}'
494
+ 'DELETE /v1/outbox/{queueId}',
495
+ // The same five for one account, reachable with a token bound to it. Each queue ID has to
496
+ // belong to the account in the path, so they reach a subset of what the five above do
497
+ 'GET /v1/account/{account}/outbox',
498
+ 'GET /v1/account/{account}/outbox/{queueId}',
499
+ 'POST /v1/account/{account}/outbox/{queueId}/retry',
500
+ 'POST /v1/account/{account}/outbox/{queueId}/promote',
501
+ 'DELETE /v1/account/{account}/outbox/{queueId}'
483
502
  ],
484
503
 
485
504
  [GROUP.EXPORT]: [
@@ -499,14 +518,34 @@ const GROUP_ROUTES = {
499
518
  'DELETE /v1/templates/account/{account}'
500
519
  ],
501
520
 
502
- [GROUP.BLOCKLIST]: ['GET /v1/blocklists', 'GET /v1/blocklist/{listId}', 'POST /v1/blocklist/{listId}', 'DELETE /v1/blocklist/{listId}'],
521
+ [GROUP.BLOCKLIST]: [
522
+ 'GET /v1/blocklists',
523
+ 'GET /v1/blocklist/{listId}',
524
+ 'POST /v1/blocklist/{listId}',
525
+ 'DELETE /v1/blocklist/{listId}',
526
+ // The whole list at once, which the entry removal above already reaches one address at a time
527
+ 'DELETE /v1/blocklists/{listId}'
528
+ ],
503
529
 
504
- [GROUP.WEBHOOK]: ['GET /v1/webhookRoutes', 'GET /v1/webhookRoutes/webhookRoute/{webhookRoute}'],
530
+ [GROUP.WEBHOOK]: [
531
+ 'GET /v1/webhookRoutes',
532
+ 'GET /v1/webhookRoutes/webhookRoute/{webhookRoute}',
533
+ // Posts a test event to a configured target. The target is never taken from the request
534
+ // and never echoed back, so it reveals and redirects nothing
535
+ 'POST /v1/webhooks/test'
536
+ ],
505
537
 
506
538
  // Reading a gateway and removing one. The two WRITES are in PROVISIONING below, because they
507
539
  // can redirect where the stored relay credentials are sent - so they are deliberately absent
508
540
  // here rather than listed in both places.
509
- [GROUP.GATEWAY]: ['GET /v1/gateways', 'GET /v1/gateway/{gateway}', 'DELETE /v1/gateway/{gateway}'],
541
+ [GROUP.GATEWAY]: [
542
+ 'GET /v1/gateways',
543
+ 'GET /v1/gateway/{gateway}',
544
+ 'DELETE /v1/gateway/{gateway}',
545
+ // A connection check with the stored settings only, a read: it sends the stored credential
546
+ // to the host it was stored for and nowhere the request could name
547
+ 'POST /v1/gateway/{gateway}/verify'
548
+ ],
510
549
 
511
550
  [GROUP.EVENTS]: ['GET /v1/changes'],
512
551
 
@@ -523,7 +562,7 @@ const GROUP_ROUTES = {
523
562
  'GET /metrics'
524
563
  ],
525
564
 
526
- [GROUP.LOGS]: ['GET /v1/logs/{account}'],
565
+ [GROUP.LOGS]: ['GET /v1/logs/{account}', 'DELETE /v1/logs/{account}'],
527
566
 
528
567
  // The five groups below used to be the admin block. They were split out so an agent that
529
568
  // manages the instance can hold them, and each went to a NEW group rather than into one that
@@ -545,6 +584,16 @@ const GROUP_ROUTES = {
545
584
 
546
585
  [GROUP.LICENSE]: ['GET /v1/license', 'POST /v1/license', 'DELETE /v1/license'],
547
586
 
587
+ [GROUP.WEBHOOK_DELIVERIES]: [
588
+ 'GET /v1/webhooks/failed',
589
+ 'POST /v1/webhooks/failed/{delivery}/retry',
590
+ 'DELETE /v1/webhooks/failed/{delivery}',
591
+ // The same three for one account, reachable with a token bound to it
592
+ 'GET /v1/account/{account}/webhooks/failed',
593
+ 'POST /v1/account/{account}/webhooks/failed/{delivery}/retry',
594
+ 'DELETE /v1/account/{account}/webhooks/failed/{delivery}'
595
+ ],
596
+
548
597
  // Everything about tokens except minting one, which is under ADMIN
549
598
  [GROUP.TOKEN]: [
550
599
  'GET /v1/tokens',
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+
3
+ // Routes that exist twice: once for the whole instance, and once for one account under
4
+ // /v1/account/{account}/... The account form is what an account-bound access token can reach - its
5
+ // path names the account, which is what the api-token strategy checks the binding against - and
6
+ // every ID it is given has to belong to that account. The MCP tools stay on the instance form: the
7
+ // account form does the same thing for a narrower caller. Shared by the outbox and the failed
8
+ // webhook delivery routes, so a third pair does not start from a copy of either.
9
+
10
+ const Joi = require('joi');
11
+ const { accountIdSchema } = require('../schemas');
12
+
13
+ /**
14
+ * @param {Object} prefixes
15
+ * @param {string} prefixes.instance - Path prefix of the instance form
16
+ * @param {string} prefixes.account - Path prefix of the account form, with an {account} parameter
17
+ * @returns {{ instance: Object, account: Object, all: Object[] }} The two scopes
18
+ */
19
+ function routeScopes(prefixes) {
20
+ const instance = { prefix: prefixes.instance, params: {}, mcp: true, isInstance: true, labelPrefix: '' };
21
+ const account = { prefix: prefixes.account, params: { account: accountIdSchema.required() }, mcp: false, isInstance: false, labelPrefix: 'Account' };
22
+ return { instance, account, all: [instance, account] };
23
+ }
24
+
25
+ /**
26
+ * Path parameter schema of a scoped route
27
+ * @param {Object} scope - From routeScopes()
28
+ * @param {Object} [extra] - Parameters of the route itself
29
+ * @returns {Object|undefined} A joi object, or undefined for a route without parameters
30
+ */
31
+ function routeParams(scope, extra) {
32
+ const keys = Object.assign({}, scope.params, extra || {});
33
+ return Object.keys(keys).length ? Joi.object(keys) : undefined;
34
+ }
35
+
36
+ /**
37
+ * A schema label, prefixed with Account on the account form so the two forms name distinct types
38
+ * @param {Object} scope - From routeScopes()
39
+ * @param {string} label - The instance form's label
40
+ * @returns {string}
41
+ */
42
+ function scopedLabel(scope, label) {
43
+ return scope.labelPrefix + label;
44
+ }
45
+
46
+ /**
47
+ * The route's MCP tool block, on the instance form only
48
+ * @param {Object} scope - From routeScopes()
49
+ * @param {Object} definition - The plugins.mcp block
50
+ * @returns {Object|undefined}
51
+ */
52
+ function mcpFor(scope, definition) {
53
+ return scope.mcp ? definition : undefined;
54
+ }
55
+
56
+ /**
57
+ * The page and pageSize query parameters of a paged listing
58
+ * @returns {Object} joi keys
59
+ */
60
+ function pagingQuery() {
61
+ return {
62
+ page: Joi.number()
63
+ .integer()
64
+ .min(0)
65
+ .max(1024 * 1024)
66
+ .default(0)
67
+ .example(0)
68
+ .description('Page number (zero indexed, so use 0 for first page)')
69
+ .label('PageNumber'),
70
+ pageSize: Joi.number().integer().min(1).max(1000).default(20).example(20).description('How many entries per page').label('PageSize')
71
+ };
72
+ }
73
+
74
+ module.exports = { routeScopes, routeParams, scopedLabel, mcpFor, pagingQuery };