emailengine-app 2.78.0 → 2.79.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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +70 -35
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. package/lib/feature-flags.js +0 -48
@@ -0,0 +1,294 @@
1
+ 'use strict';
2
+
3
+ // Admin UI for suppression lists (the store behind the Blocklists API and the public
4
+ // unsubscribe flow): /admin/suppression-lists (listing + add/delete) and
5
+ // /admin/suppression-lists/list/{listId} (entries + per-address removal). Lists are
6
+ // registered ad hoc, so adding an address to an unknown list ID creates that list, and
7
+ // removing the last address drops the list again (see lib/lua/ee-list-remove.lua).
8
+
9
+ const Joi = require('joi');
10
+ const { redis } = require('../db');
11
+ const { lists } = require('../lists');
12
+ const settings = require('../settings');
13
+ const { accountExists } = require('../account');
14
+ const { blocklistListIdSchema } = require('../schemas');
15
+ const { buildPagingView } = require('./route-helpers');
16
+ const { buildUnsubscribeUrl, getServiceSecret } = require('../tools');
17
+ const consts = require('../consts');
18
+
19
+ const { DEFAULT_PAGE_SIZE } = consts;
20
+
21
+ const pagingQuerySchema = Joi.object({
22
+ page: Joi.number().integer().min(1).max(1000000).default(1),
23
+ pageSize: Joi.number().integer().min(1).max(250).default(DEFAULT_PAGE_SIZE)
24
+ });
25
+
26
+ function init(args) {
27
+ const { server } = args;
28
+
29
+ server.route({
30
+ method: 'GET',
31
+ path: '/admin/suppression-lists',
32
+ async handler(request, h) {
33
+ let data = await lists.list(request.query.page - 1, request.query.pageSize);
34
+
35
+ return h.view(
36
+ 'suppression-lists/index',
37
+ {
38
+ pageTitle: 'Suppression Lists',
39
+ menuSuppressionLists: true,
40
+
41
+ total: data.total,
42
+
43
+ ...buildPagingView('admin/suppression-lists', data, request.query),
44
+
45
+ suppressionLists: data.blocklists
46
+ },
47
+ {
48
+ layout: 'app'
49
+ }
50
+ );
51
+ },
52
+
53
+ options: {
54
+ validate: {
55
+ options: {
56
+ stripUnknown: true,
57
+ abortEarly: false,
58
+ convert: true
59
+ },
60
+
61
+ async failAction(request, h /*, err*/) {
62
+ return h.redirect('/admin/suppression-lists').takeover();
63
+ },
64
+
65
+ query: pagingQuerySchema
66
+ }
67
+ }
68
+ });
69
+
70
+ server.route({
71
+ method: 'GET',
72
+ path: '/admin/suppression-lists/list/{listId}',
73
+ async handler(request, h) {
74
+ let listId = request.params.listId;
75
+
76
+ let data;
77
+ try {
78
+ data = await lists.listContent(listId, request.query.page - 1, request.query.pageSize);
79
+ } catch (err) {
80
+ await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
81
+ return h.redirect('/admin/suppression-lists');
82
+ }
83
+
84
+ // Link each entry to its public subscription management page - the same signed URL
85
+ // the List-Unsubscribe header carries - so the page can be previewed or the link
86
+ // sent to the recipient for self service re-subscription. The page loads the
87
+ // account, so entries without one (or whose account is gone) get no link.
88
+ let [serviceUrl, serviceSecret] = await Promise.all([settings.get('serviceUrl'), getServiceSecret()]);
89
+
90
+ let uniqueAccounts = Array.from(new Set(data.addresses.map(entry => entry.account).filter(Boolean)));
91
+ let knownAccounts = new Map(await Promise.all(uniqueAccounts.map(async account => [account, await accountExists(redis, account)])));
92
+
93
+ for (let entry of data.addresses) {
94
+ if (!entry.account || !knownAccounts.get(entry.account)) {
95
+ continue;
96
+ }
97
+ entry.unsubscribeUrl = buildUnsubscribeUrl(serviceSecret, serviceUrl, {
98
+ account: entry.account,
99
+ list: listId,
100
+ recipient: entry.recipient
101
+ });
102
+ }
103
+
104
+ return h.view(
105
+ 'suppression-lists/list',
106
+ {
107
+ pageTitle: `Suppression Lists - ${listId}`,
108
+ menuSuppressionLists: true,
109
+
110
+ listId,
111
+ total: data.total,
112
+
113
+ ...buildPagingView(`admin/suppression-lists/list/${listId}`, data, request.query),
114
+
115
+ addresses: data.addresses
116
+ },
117
+ {
118
+ layout: 'app'
119
+ }
120
+ );
121
+ },
122
+
123
+ options: {
124
+ validate: {
125
+ options: {
126
+ stripUnknown: true,
127
+ abortEarly: false,
128
+ convert: true
129
+ },
130
+
131
+ async failAction(request, h /*, err*/) {
132
+ return h.redirect('/admin/suppression-lists').takeover();
133
+ },
134
+
135
+ params: Joi.object({
136
+ listId: blocklistListIdSchema
137
+ }),
138
+
139
+ query: pagingQuerySchema
140
+ }
141
+ }
142
+ });
143
+
144
+ server.route({
145
+ method: 'POST',
146
+ path: '/admin/suppression-lists/add',
147
+ async handler(request, h) {
148
+ let { listId, recipient, reason } = request.payload;
149
+
150
+ try {
151
+ let added = await lists.add(listId, recipient, {
152
+ source: 'admin',
153
+ reason,
154
+ remoteAddress: request.app.ip,
155
+ userAgent: request.headers['user-agent']
156
+ });
157
+
158
+ if (added) {
159
+ await request.flash({ type: 'info', message: `Added ${recipient} to the suppression list` });
160
+ } else {
161
+ await request.flash({ type: 'info', message: `${recipient} was already listed; the entry was updated` });
162
+ }
163
+
164
+ return h.redirect(`/admin/suppression-lists/list/${listId}`);
165
+ } catch (err) {
166
+ await request.flash({ type: 'danger', message: `Couldn't add the address. Try again.` });
167
+ request.logger.error({ msg: 'Failed to add suppression list entry', err, listId, remoteAddress: request.app.ip });
168
+ return h.redirect('/admin/suppression-lists');
169
+ }
170
+ },
171
+ options: {
172
+ validate: {
173
+ options: {
174
+ stripUnknown: true,
175
+ abortEarly: false,
176
+ convert: true
177
+ },
178
+
179
+ async failAction(request, h, err) {
180
+ await request.flash({ type: 'danger', message: `Couldn't add the address. Check the list ID and email address and try again.` });
181
+ request.logger.error({ msg: 'Failed to add suppression list entry', err });
182
+
183
+ return h.redirect('/admin/suppression-lists').takeover();
184
+ },
185
+
186
+ payload: Joi.object({
187
+ listId: blocklistListIdSchema,
188
+ recipient: Joi.string().empty('').email().required().description('Email address to suppress'),
189
+ reason: Joi.string().empty('').max(256).default('block').description('Identifier for the blocking reason')
190
+ })
191
+ }
192
+ }
193
+ });
194
+
195
+ server.route({
196
+ method: 'POST',
197
+ path: '/admin/suppression-lists/list/{listId}/remove',
198
+ async handler(request, h) {
199
+ let listId = request.params.listId;
200
+ let recipient = request.payload.recipient;
201
+
202
+ try {
203
+ let removed = await lists.remove(listId, recipient);
204
+
205
+ if (!removed) {
206
+ await request.flash({ type: 'danger', message: `${recipient} was not found on the list` });
207
+ } else if (!(await lists.exists(listId))) {
208
+ // removing the final address drops the list itself
209
+ await request.flash({ type: 'info', message: `Removed ${recipient}; the now empty list was deleted` });
210
+ return h.redirect('/admin/suppression-lists');
211
+ } else {
212
+ await request.flash({ type: 'info', message: `Removed ${recipient} from the suppression list` });
213
+ }
214
+
215
+ return h.redirect(`/admin/suppression-lists/list/${listId}`);
216
+ } catch (err) {
217
+ await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
218
+ request.logger.error({ msg: 'Failed to remove suppression list entry', err, listId, remoteAddress: request.app.ip });
219
+ return h.redirect(`/admin/suppression-lists/list/${listId}`);
220
+ }
221
+ },
222
+ options: {
223
+ validate: {
224
+ options: {
225
+ stripUnknown: true,
226
+ abortEarly: false,
227
+ convert: true
228
+ },
229
+
230
+ async failAction(request, h, err) {
231
+ await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
232
+ request.logger.error({ msg: 'Failed to remove suppression list entry', err });
233
+
234
+ return h.redirect('/admin/suppression-lists').takeover();
235
+ },
236
+
237
+ params: Joi.object({
238
+ listId: blocklistListIdSchema
239
+ }),
240
+
241
+ payload: Joi.object({
242
+ // entry keys are stored normalized, but accept whatever was displayed
243
+ recipient: Joi.string().max(1024).required().description('Listed address to remove')
244
+ })
245
+ }
246
+ }
247
+ });
248
+
249
+ server.route({
250
+ method: 'POST',
251
+ path: '/admin/suppression-lists/delete',
252
+ async handler(request, h) {
253
+ let listId = request.payload.listId;
254
+
255
+ try {
256
+ let deleted = await lists.deleteList(listId);
257
+
258
+ if (deleted) {
259
+ await request.flash({ type: 'info', message: `Suppression list deleted` });
260
+ } else {
261
+ await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
262
+ }
263
+
264
+ return h.redirect('/admin/suppression-lists');
265
+ } catch (err) {
266
+ await request.flash({ type: 'danger', message: `Couldn't delete the suppression list. Try again.` });
267
+ request.logger.error({ msg: 'Failed to delete suppression list', err, listId, remoteAddress: request.app.ip });
268
+ return h.redirect('/admin/suppression-lists');
269
+ }
270
+ },
271
+ options: {
272
+ validate: {
273
+ options: {
274
+ stripUnknown: true,
275
+ abortEarly: false,
276
+ convert: true
277
+ },
278
+
279
+ async failAction(request, h, err) {
280
+ await request.flash({ type: 'danger', message: `Couldn't delete the suppression list. Try again.` });
281
+ request.logger.error({ msg: 'Failed to delete suppression list', err });
282
+
283
+ return h.redirect('/admin/suppression-lists').takeover();
284
+ },
285
+
286
+ payload: Joi.object({
287
+ listId: blocklistListIdSchema
288
+ })
289
+ }
290
+ }
291
+ });
292
+ }
293
+
294
+ module.exports = init;
@@ -9,8 +9,9 @@ const Joi = require('joi');
9
9
  const Boom = require('@hapi/boom');
10
10
  const { Account } = require('../account');
11
11
  const { redis } = require('../db');
12
- const { REDIS_PREFIX } = require('../consts');
12
+ const { lists } = require('../lists');
13
13
  const { parseSignedFormData } = require('../tools');
14
+ const { isClientError } = require('./route-helpers');
14
15
  const { signedFormBlobFields } = require('../schemas');
15
16
 
16
17
  function init(args) {
@@ -37,7 +38,7 @@ function init(args) {
37
38
  {
38
39
  pageTitleFull: request.app.gt.gettext('Subscription Management'),
39
40
 
40
- unsubscribed: await redis.hexists(`${REDIS_PREFIX}lists:unsub:entries:${data.list}`, data.rcpt),
41
+ unsubscribed: await lists.has(data.list, data.rcpt),
41
42
  values: {
42
43
  listId: data.list,
43
44
  account: data.acc,
@@ -64,7 +65,7 @@ function init(args) {
64
65
  },
65
66
 
66
67
  async failAction(request, h, err) {
67
- request.logger.error({ msg: 'Failed to validate request arguments', err });
68
+ request.logger.debug({ msg: 'Failed to validate request arguments', err });
68
69
  let error = Boom.boomify(new Error(request.app.gt.gettext('Invalid request. Check your input and try again.')), { statusCode: 400 });
69
70
  if (err.code) {
70
71
  error.output.payload.code = err.code;
@@ -121,28 +122,20 @@ function init(args) {
121
122
  }
122
123
  });
123
124
  } catch (err) {
124
- request.logger.error({ msg: `Failed to dispatch ${cmd} event`, account, listId, err });
125
+ request.logger.error({ msg: 'Failed to dispatch list event', event: cmd, account, listId, err });
125
126
  }
126
127
  };
127
128
 
128
129
  switch (request.payload.action) {
129
130
  case 'unsubscribe': {
130
- let isNew = await redis.eeListAdd(
131
- `${REDIS_PREFIX}lists:unsub:lists`,
132
- `${REDIS_PREFIX}lists:unsub:entries:${listId}`,
133
- listId,
134
- email.toLowerCase().trim(),
135
- JSON.stringify({
136
- recipient: email,
137
- account,
138
- source: 'form',
139
- reason: 'unsubscribe',
140
- messageId,
141
- remoteAddress: request.info.remoteAddress,
142
- userAgent: request.headers['user-agent'],
143
- created: new Date().toISOString()
144
- })
145
- );
131
+ let isNew = await lists.add(listId, email, {
132
+ account,
133
+ source: 'form',
134
+ reason: 'unsubscribe',
135
+ messageId,
136
+ remoteAddress: request.info.remoteAddress,
137
+ userAgent: request.headers['user-agent']
138
+ });
146
139
 
147
140
  if (isNew) {
148
141
  await dispatchListEvent('unsubscribe');
@@ -151,12 +144,7 @@ function init(args) {
151
144
  }
152
145
 
153
146
  case 'subscribe': {
154
- let removed = await redis.eeListRemove(
155
- `${REDIS_PREFIX}lists:unsub:lists`,
156
- `${REDIS_PREFIX}lists:unsub:entries:${listId}`,
157
- listId,
158
- email.toLowerCase().trim()
159
- );
147
+ let removed = await lists.remove(listId, email);
160
148
 
161
149
  if (removed) {
162
150
  await dispatchListEvent('subscribe');
@@ -172,7 +160,7 @@ function init(args) {
172
160
  {
173
161
  pageTitleFull: request.app.gt.gettext('Subscription Management'),
174
162
 
175
- unsubscribed: await redis.hexists(`${REDIS_PREFIX}lists:unsub:entries:${listId}`, email),
163
+ unsubscribed: await lists.has(listId, email),
176
164
  values: {
177
165
  listId,
178
166
  account,
@@ -190,7 +178,9 @@ function init(args) {
190
178
  );
191
179
  } catch (err) {
192
180
  await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process request. Try again.") });
193
- request.logger.error({ msg: 'Failed to process subscription request', err });
181
+ // Boom 4xx (bad signature, unknown account) is client-caused traffic on a public
182
+ // endpoint, not a server failure
183
+ request.logger[isClientError(err) ? 'debug' : 'error']({ msg: 'Failed to process subscription request', err });
194
184
 
195
185
  return h.view(
196
186
  'unsubscribe',
@@ -224,7 +214,7 @@ function init(args) {
224
214
  }
225
215
 
226
216
  await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process request. Try again.") });
227
- request.logger.error({ msg: 'Failed to process subscription request', err });
217
+ request.logger.debug({ msg: 'Failed to process subscription request', err });
228
218
 
229
219
  return h
230
220
  .view(
@@ -102,7 +102,7 @@ function matchIp(ip, addresses) {
102
102
  return true;
103
103
  }
104
104
  } catch (err) {
105
- logger.error({ msg: 'Failed to parse IP address', ip, addr, err });
105
+ logger.error({ msg: 'Failed to parse allowlist address', ip, addr, err });
106
106
  }
107
107
  }
108
108
 
@@ -339,7 +339,7 @@ async function getLocalAddress(redis, protocol, account, hint) {
339
339
  addressData.addressSelector = addressSelector;
340
340
  return addressData;
341
341
  } catch (err) {
342
- logger.error({ msg: 'Failed to load address data', localAddress, err });
342
+ logger.warn({ msg: 'Failed to load address data', localAddress, err });
343
343
  addressSelector = 'error';
344
344
  return { address: false, name: hostname, addressSelector };
345
345
  }
@@ -388,7 +388,7 @@ async function messageWebSafeHtml(messageData) {
388
388
  }
389
389
  } catch (err) {
390
390
  // A message that can not be folded is still a message. Render all of it.
391
- logger.error({ msg: 'Failed to mark quoted thread content', err });
391
+ logger.warn({ msg: 'Failed to mark quoted thread content', err });
392
392
  }
393
393
  }
394
394
 
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+
3
+ // Shared webhook routing rules. The notify pipeline (lib/webhooks.js, workers/webhooks.js)
4
+ // and the admin account page's routing card resolve targets and gates through the helpers
5
+ // here, so the debug view cannot drift from what the worker actually does.
6
+
7
+ // Precedence: custom route target, then the per-account webhooks override, then the global
8
+ // webhooks setting. Returns the winning URL and which configuration level provided it.
9
+ function resolveTargetUrl(customRouteTargetUrl, accountWebhooks, globalWebhooks) {
10
+ if (customRouteTargetUrl) {
11
+ return { url: customRouteTargetUrl, source: 'route' };
12
+ }
13
+ if (accountWebhooks) {
14
+ return { url: accountWebhooks, source: 'account' };
15
+ }
16
+ if (globalWebhooks) {
17
+ return { url: globalWebhooks, source: 'global' };
18
+ }
19
+ return { url: null, source: null };
20
+ }
21
+
22
+ // A custom route can only deliver when it is enabled and has a target URL
23
+ function isDeliverableRoute(route) {
24
+ return !!(route && route.enabled && route.targetUrl);
25
+ }
26
+
27
+ // The webhookEvents allowlist applies to the default route only; '*' allows everything
28
+ function eventAllowed(webhookEvents, eventName) {
29
+ let events = [].concat(webhookEvents || []);
30
+ return events.includes('*') || events.includes(eventName);
31
+ }
32
+
33
+ // Assembles a render-ready description of the webhook routing that applies to one account.
34
+ // All inputs are pre-fetched values; this function does not touch Redis or settings.
35
+ function describeEffectiveRouting(opts) {
36
+ opts = opts || {};
37
+
38
+ let events = [].concat(opts.webhookEvents || []);
39
+ let allEvents = events.includes('*');
40
+
41
+ let { url, source } = resolveTargetUrl(null, opts.accountWebhooks, opts.globalWebhooks);
42
+
43
+ let globalHeaders = [].concat(opts.globalCustomHeaders || []).length;
44
+ let accountHeaders = [].concat(opts.accountCustomHeaders || []).length;
45
+
46
+ let customHeadersLabel = null;
47
+ if (globalHeaders && accountHeaders) {
48
+ customHeadersLabel = `${globalHeaders} global, ${accountHeaders} account-specific`;
49
+ } else if (globalHeaders) {
50
+ customHeadersLabel = `${globalHeaders} global`;
51
+ } else if (accountHeaders) {
52
+ customHeadersLabel = `${accountHeaders} account-specific`;
53
+ }
54
+
55
+ return {
56
+ enabled: !!opts.webhooksEnabled,
57
+
58
+ defaultRoute: {
59
+ url,
60
+ source,
61
+ events: allEvents ? [] : events,
62
+ allEvents,
63
+ inboxNewOnly: !!opts.inboxNewOnly,
64
+ customHeadersLabel
65
+ },
66
+
67
+ // Enabled custom routes deliver independently of the default route, each gated by its
68
+ // own filter function instead of the webhookEvents allowlist
69
+ customRoutes: []
70
+ .concat(opts.routes || [])
71
+ .filter(isDeliverableRoute)
72
+ .map(route => ({
73
+ id: route.id,
74
+ name: route.name,
75
+ targetUrl: route.targetUrl
76
+ }))
77
+ };
78
+ }
79
+
80
+ module.exports = { resolveTargetUrl, isDeliverableRoute, eventAllowed, describeEffectiveRouting };
package/lib/webhooks.js CHANGED
@@ -9,6 +9,7 @@ const { SubScript } = require('./sub-script');
9
9
  const settings = require('./settings');
10
10
  const { filterListPage } = require('./tools');
11
11
  const { buildRetentionPolicy } = require('./queue-retention');
12
+ const { isDeliverableRoute } = require('./webhook-routing');
12
13
 
13
14
  class WebhooksHandler {
14
15
  constructor(options) {
@@ -70,7 +71,12 @@ class WebhooksHandler {
70
71
  webhookErrorFlag = JSON.parse(list[i + 2].toString());
71
72
  }
72
73
  } catch (err) {
73
- logger.error({ msg: 'Failed to process webhook error', entry: list[i + 2] && list[i + 2].toString('base64') });
74
+ logger.error({
75
+ msg: 'Failed to parse webhook error flag',
76
+ webhook: selectedIds[i / 3],
77
+ entry: list[i + 2] && list[i + 2].toString('base64'),
78
+ err
79
+ });
74
80
  }
75
81
 
76
82
  try {
@@ -192,7 +198,7 @@ class WebhooksHandler {
192
198
  let entry = msgpack.decode(line);
193
199
  logEntries.unshift(entry);
194
200
  } catch (err) {
195
- logger.error({ msg: 'Failed to retrieve log line', webhook: id, entry: line && line.toString('base64') });
201
+ logger.error({ msg: 'Failed to decode log line', webhook: id, entry: line && line.toString('base64'), err });
196
202
  }
197
203
  }
198
204
 
@@ -212,7 +218,7 @@ class WebhooksHandler {
212
218
  meta = msgpack.decode(getResult[0]);
213
219
  }
214
220
  } catch (err) {
215
- logger.error({ msg: 'Failed to process webhook', entry: getResult[0].toString('base64') });
221
+ logger.error({ msg: 'Failed to process webhook', webhook: id, entry: getResult[0].toString('base64'), err });
216
222
  }
217
223
 
218
224
  return Object.assign({}, meta || {});
@@ -237,7 +243,7 @@ class WebhooksHandler {
237
243
  meta = msgpack.decode(getResult[0]);
238
244
  }
239
245
  } catch (err) {
240
- logger.error({ msg: 'Failed to process webhook', entry: getResult[0].toString('base64') });
246
+ logger.error({ msg: 'Failed to process webhook', webhook: id, entry: getResult[0].toString('base64'), err });
241
247
  }
242
248
 
243
249
  try {
@@ -245,7 +251,7 @@ class WebhooksHandler {
245
251
  content = msgpack.decode(getResult[1]);
246
252
  }
247
253
  } catch (err) {
248
- logger.error({ msg: 'Failed to process webhook', entry: getResult[1].toString('base64') });
254
+ logger.error({ msg: 'Failed to process webhook', webhook: id, entry: getResult[1].toString('base64'), err });
249
255
  }
250
256
 
251
257
  v = Number(getResult[2] && getResult[2].toString()) || 0;
@@ -255,7 +261,7 @@ class WebhooksHandler {
255
261
  webhookErrorFlag = JSON.parse(getResult[3].toString());
256
262
  }
257
263
  } catch (err) {
258
- logger.error({ msg: 'Failed to process webhook', entry: getResult[3].toString('base64') });
264
+ logger.error({ msg: 'Failed to process webhook', webhook: id, entry: getResult[3].toString('base64'), err });
259
265
  }
260
266
 
261
267
  tcount = Number(getResult[4] && getResult[4].toString()) || 0;
@@ -355,7 +361,7 @@ class WebhooksHandler {
355
361
  } catch (err) {
356
362
  await this.storeLog(id, 'filter', null, err.stack);
357
363
 
358
- logger.error({ msg: 'Compilation failed', type: 'filter', webhook: id, err });
364
+ logger.error({ msg: 'Failed to compile webhook script', type: 'filter', webhook: id, err });
359
365
  webhookData.compiledFn = null;
360
366
  webhookData.compiledMap = null;
361
367
  }
@@ -370,7 +376,7 @@ class WebhooksHandler {
370
376
  } catch (err) {
371
377
  await this.storeLog(id, 'map', null, err.stack);
372
378
 
373
- logger.error({ msg: 'Compilation failed', type: 'map', webhook: id, err });
379
+ logger.error({ msg: 'Failed to compile webhook script', type: 'map', webhook: id, err });
374
380
  webhookData.compiledFn = null;
375
381
  webhookData.compiledMap = null;
376
382
  }
@@ -383,7 +389,7 @@ class WebhooksHandler {
383
389
  } catch (err) {
384
390
  await this.storeLog(id, 'filter', payload, err.stack);
385
391
 
386
- logger.error({ msg: 'Exec failed', type: 'filter', webhook: webhookData.id, err });
392
+ logger.error({ msg: 'Failed to execute webhook script', type: 'filter', webhook: webhookData.id, err });
387
393
  return null;
388
394
  }
389
395
  };
@@ -396,7 +402,7 @@ class WebhooksHandler {
396
402
  } catch (err) {
397
403
  await this.storeLog(id, 'map', payload, err.stack);
398
404
 
399
- logger.error({ msg: 'Exec failed', type: 'map', webhook: webhookData.id, err });
405
+ logger.error({ msg: 'Failed to execute webhook script', type: 'map', webhook: webhookData.id, err });
400
406
  return null;
401
407
  }
402
408
  };
@@ -543,7 +549,7 @@ class WebhooksHandler {
543
549
  };
544
550
 
545
551
  for (let route of webhookRoutes) {
546
- if (route.enabled && route.targetUrl && typeof route.filterFn === 'function') {
552
+ if (isDeliverableRoute(route) && typeof route.filterFn === 'function') {
547
553
  let canSend;
548
554
  let payload = structuredClone(originalPayload);
549
555
 
@@ -556,7 +562,7 @@ class WebhooksHandler {
556
562
  } catch (err) {
557
563
  await this.storeLog(route.id, 'filter', payload, err.stack);
558
564
 
559
- logger.error({ msg: 'Exec failed', type: 'filter', webhook: route.id, err });
565
+ logger.error({ msg: 'Failed to execute webhook script', type: 'filter', webhook: route.id, err });
560
566
  }
561
567
 
562
568
  if (canSend) {
@@ -566,7 +572,7 @@ class WebhooksHandler {
566
572
  } catch (err) {
567
573
  await this.storeLog(route.id, 'map', payload, err.stack);
568
574
 
569
- logger.error({ msg: 'Exec failed', type: 'map', webhook: route.id, err });
575
+ logger.error({ msg: 'Failed to execute webhook script', type: 'map', webhook: route.id, err });
570
576
  canSend = false;
571
577
  }
572
578
  }
@@ -599,7 +605,7 @@ class WebhooksHandler {
599
605
  try {
600
606
  await this.redis.hincrby(this.getWebhooksContentKey(), `${route.id}:tcount`, 1);
601
607
  } catch (err) {
602
- logger.error({ msg: 'Failed to increment counter', event, webhook: route.id, err });
608
+ logger.warn({ msg: 'Failed to increment counter', event, webhook: route.id, err });
603
609
  }
604
610
  }
605
611
  }