emailengine-app 2.83.2 → 2.84.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 (63) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +20 -0
  3. package/README.md +1 -1
  4. package/SECURITY.md +126 -47
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/api-routes/outbox-routes.js +132 -9
  7. package/lib/api-routes/permission-map.js +11 -1
  8. package/lib/consts.js +0 -4
  9. package/lib/email-client/imap/idle-settings.js +44 -0
  10. package/lib/email-client/imap/mailbox.js +19 -7
  11. package/lib/email-client/imap-client.js +3 -21
  12. package/lib/enum-descriptions.js +7 -0
  13. package/lib/export.js +2 -6
  14. package/lib/field-usage.js +4 -0
  15. package/lib/handlebars-helpers.js +4 -0
  16. package/lib/outbox.js +338 -10
  17. package/lib/queue-browser/definitions.js +132 -0
  18. package/lib/queue-browser/format.js +387 -0
  19. package/lib/queue-browser/index.js +568 -0
  20. package/lib/queue-job-actions.js +75 -0
  21. package/lib/queue-retention.js +53 -1
  22. package/lib/routes-ui.js +5 -0
  23. package/lib/schemas.js +42 -2
  24. package/lib/security-headers.js +2 -24
  25. package/lib/token-permission-view.js +1 -1
  26. package/lib/ui-routes/account-routes.js +6 -0
  27. package/lib/ui-routes/imap-idle-field.js +42 -0
  28. package/lib/ui-routes/queue-routes.js +371 -0
  29. package/lib/utils/status-error.js +21 -0
  30. package/package.json +15 -17
  31. package/prepare-bundle-deps.sh +1 -1
  32. package/sbom.json +1 -1
  33. package/server.js +10 -0
  34. package/static/css/flyonui.css +1 -1
  35. package/static/css/src/app.tailwind.css +2 -0
  36. package/static/js/queues.js +117 -0
  37. package/static/licenses.html +122 -246
  38. package/translations/messages.pot +57 -42
  39. package/views/accounts/account.hbs +31 -0
  40. package/views/accounts/edit.hbs +2 -0
  41. package/views/config/service.hbs +1 -2
  42. package/views/dashboard.hbs +2 -2
  43. package/views/partials/queue_cell_account.hbs +20 -0
  44. package/views/partials/queue_cell_failure.hbs +6 -0
  45. package/views/partials/queue_clean_items.hbs +9 -0
  46. package/views/partials/queue_clean_modal.hbs +9 -0
  47. package/views/partials/queue_entry_actions.hbs +41 -0
  48. package/views/partials/queue_job_actions.hbs +15 -0
  49. package/views/partials/queue_pause_controls.hbs +18 -0
  50. package/views/partials/queue_retention_note.hbs +49 -0
  51. package/views/partials/queue_rows_export.hbs +58 -0
  52. package/views/partials/queue_rows_notify.hbs +73 -0
  53. package/views/partials/queue_rows_submit.hbs +70 -0
  54. package/views/partials/side_menu.hbs +1 -1
  55. package/views/partials/ui/tooltip.hbs +5 -3
  56. package/views/queues/index.hbs +104 -0
  57. package/views/queues/job.hbs +224 -0
  58. package/views/queues/queue.hbs +93 -0
  59. package/views/webhooks/webhook.hbs +3 -0
  60. package/workers/api.js +0 -4
  61. package/workers/submit.js +19 -5
  62. package/workers/webhooks.js +13 -0
  63. package/lib/api-routes/bull-board-routes.js +0 -56
@@ -0,0 +1,387 @@
1
+ 'use strict';
2
+
3
+ // Turns a BullMQ job into what the queue browser shows for it: a webhook delivery, an outgoing
4
+ // message or an export, rather than "job #123 with data {...}". Pure functions over the job's
5
+ // stored fields, so the wording and the failure classification can be tested without Redis.
6
+
7
+ const { nextAttemptOfStoredJob, isPermanentDeliveryError } = require('../delivery-error');
8
+ const { STATES_BY_NAME } = require('./definitions');
9
+
10
+ // Error codes nodemailer and the socket layer use for "could not get a connection at all"
11
+ const CONNECTION_CODES = new Set(['ECONNECTION', 'ETIMEDOUT', 'ESOCKET', 'EDNS', 'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ECONNRESET', 'EPROTOCOL', 'ETLS']);
12
+
13
+ // What each kind of failure is called: the sentence for a detail page and the word or two a
14
+ // listing row has room for. `{status}` is the HTTP or SMTP status the worker recorded.
15
+ const FAILURE_KINDS = {
16
+ auth: { label: 'Authentication failed at the outgoing server', short: 'Auth failed' },
17
+ unreachable: { label: 'Could not reach the outgoing server', short: 'Unreachable' },
18
+ rejected: { label: 'Rejected by the receiving server', short: 'Rejected {status}' },
19
+ refused: { label: 'Temporarily refused by the receiving server', short: 'Refused {status}' },
20
+ timeout: { label: 'The endpoint did not answer in time', short: 'Timed out' },
21
+ redirect: { label: 'The endpoint answered with a redirect', short: 'Redirected' },
22
+ blocked: { label: 'Destination blocked by the egress policy', short: 'Blocked' },
23
+ http: { label: 'The endpoint answered {status}', short: 'HTTP {status}' },
24
+ endpoint: { label: 'Could not reach the endpoint', short: 'Unreachable' },
25
+ failed: { label: 'Delivery failed', short: 'Failed' },
26
+ export: { label: 'Export failed', short: 'Failed' }
27
+ };
28
+
29
+ function isoOrNull(value) {
30
+ const time = Number(value);
31
+ return time ? new Date(time).toISOString() : null;
32
+ }
33
+
34
+ /**
35
+ * Formats a byte count for people: "1.2 MB", "840 B".
36
+ *
37
+ * @param {number} bytes
38
+ * @returns {string}
39
+ */
40
+ function humanSize(bytes) {
41
+ const value = Number(bytes) || 0;
42
+ if (value < 1024) {
43
+ return `${value} B`;
44
+ }
45
+ const units = ['KB', 'MB', 'GB', 'TB'];
46
+ let size = value / 1024;
47
+ let unit = 0;
48
+ while (size >= 1024 && unit < units.length - 1) {
49
+ size /= 1024;
50
+ unit++;
51
+ }
52
+ return `${size < 10 ? size.toFixed(1) : Math.round(size)} ${units[unit]}`;
53
+ }
54
+
55
+ /**
56
+ * The recorded outcome of the last attempt, as the workers store it: `{status: 'error', error:
57
+ * {message, code, statusCode, responseCode}}` on the job's progress field after a failed
58
+ * attempt, and `{status: 'delivered', statusCode, duration}` as the webhook worker's return
59
+ * value after a delivery. Anything else (a plain number, the `{status: 'queued'}` marker)
60
+ * carries no outcome.
61
+ */
62
+ function recordedOutcome(job) {
63
+ for (const value of [job.progress, job.returnvalue]) {
64
+ if (value && typeof value === 'object' && value.status) {
65
+ return value;
66
+ }
67
+ }
68
+ return null;
69
+ }
70
+
71
+ /**
72
+ * Classifies a failure of a submission, from what the submit worker recorded.
73
+ *
74
+ * Whether it is permanent is lib/delivery-error.js's call, made on the same fields the worker
75
+ * decided with (the SMTP reply code before the nodemailer error code); nothing here reads a
76
+ * status as a verdict of its own.
77
+ */
78
+ function submitFailureKind(recorded) {
79
+ const permanent = isPermanentDeliveryError(recorded);
80
+ const responseCode = Number(recorded.responseCode) || null;
81
+ if (recorded.code === 'EAUTH') {
82
+ return { kind: 'auth', permanent };
83
+ }
84
+ if (responseCode) {
85
+ return { kind: permanent ? 'rejected' : 'refused', permanent, status: responseCode };
86
+ }
87
+ if (CONNECTION_CODES.has(recorded.code)) {
88
+ return { kind: 'unreachable', permanent: false };
89
+ }
90
+ return { kind: 'failed', permanent };
91
+ }
92
+
93
+ /**
94
+ * Classifies a failure of a webhook delivery, from what the webhook worker recorded.
95
+ */
96
+ function notifyFailureKind(recorded) {
97
+ const statusCode = Number(recorded.statusCode) || null;
98
+ switch (recorded.code) {
99
+ case 'ETIMEDOUT':
100
+ return { kind: 'timeout', permanent: false };
101
+ case 'EREDIRECTNOTFOLLOWED':
102
+ return { kind: 'redirect', permanent: true, status: statusCode };
103
+ case 'EEGRESSBLOCKED':
104
+ return { kind: 'blocked', permanent: true };
105
+ default:
106
+ if (statusCode) {
107
+ return { kind: 'http', permanent: false, status: statusCode };
108
+ }
109
+ if (CONNECTION_CODES.has(recorded.code)) {
110
+ return { kind: 'endpoint', permanent: false };
111
+ }
112
+ return { kind: 'failed', permanent: false };
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Explains why a job failed, in the terms the worker that ran it uses.
118
+ *
119
+ * Reads the error the worker recorded on the job (its code and status are exact) and falls back
120
+ * to the text of BullMQ's `failedReason`, which is all a job from before the workers recorded
121
+ * anything has. A job whose last attempt failed but that is waiting for its next one is explained
122
+ * the same way, so the delayed list can say what it is retrying from.
123
+ *
124
+ * @param {string} queueName - notify, submit or export
125
+ * @param {Object} job - BullMQ job as stored
126
+ * @returns {Object|null} `{ kind, label, shortLabel, reason, code, statusCode, permanent }`, or
127
+ * null when nothing has failed. `label` is the sentence for the detail page, `shortLabel` the
128
+ * word or two a listing row has room for
129
+ */
130
+ function describeFailure(queueName, job) {
131
+ const outcome = recordedOutcome(job);
132
+ const recorded = outcome && outcome.status === 'error' && outcome.error && typeof outcome.error === 'object' ? outcome.error : {};
133
+ const reason = job.failedReason || recorded.message || null;
134
+ if (!reason) {
135
+ return null;
136
+ }
137
+
138
+ let classified;
139
+ switch (queueName) {
140
+ case 'submit':
141
+ classified = submitFailureKind(recorded);
142
+ break;
143
+ case 'notify':
144
+ classified = notifyFailureKind(recorded);
145
+ break;
146
+ default:
147
+ classified = { kind: 'export', permanent: false };
148
+ }
149
+
150
+ // The workers end a job early with UnrecoverableError when retrying cannot help; BullMQ keeps
151
+ // the class name at the head of the stored stack, which is the one signal an older job has
152
+ const stackHead = Array.isArray(job.stacktrace) && job.stacktrace.length ? String(job.stacktrace[0]).split('\n')[0] : '';
153
+ const permanent = classified.permanent || /^UnrecoverableError\b/.test(stackHead);
154
+
155
+ const wording = FAILURE_KINDS[classified.kind];
156
+ const status = classified.status ? String(classified.status) : '';
157
+ const fill = text => text.replace(' {status}', status ? ` ${status}` : '').replace('{status}', status);
158
+
159
+ return {
160
+ kind: classified.kind,
161
+ label: fill(wording.label),
162
+ shortLabel: fill(wording.short),
163
+ reason: String(reason),
164
+ code: recorded.code || null,
165
+ statusCode: classified.status || Number(recorded.statusCode) || null,
166
+ permanent
167
+ };
168
+ }
169
+
170
+ /**
171
+ * The one timestamp a listing row shows for an entry, with the word that says what it is:
172
+ * when a delayed entry is due, when a running one started, when a finished one finished, and
173
+ * otherwise when it was queued.
174
+ */
175
+ function whenOf(queueDef, state, times) {
176
+ switch (state) {
177
+ case 'delayed':
178
+ return { label: times.isRetryWait ? 'Retry' : 'Scheduled', time: times.dueAt };
179
+ case 'active':
180
+ return { label: 'Started', time: times.processedOn };
181
+ case 'failed':
182
+ return { label: 'Failed', time: times.finishedOn };
183
+ case 'completed':
184
+ return { label: queueDef.name === 'submit' ? 'Sent' : 'Finished', time: times.finishedOn };
185
+ default:
186
+ return { label: 'Queued', time: times.created };
187
+ }
188
+ }
189
+
190
+ /**
191
+ * The fields every row and detail view carries, whatever the queue.
192
+ */
193
+ function formatCommon(queueDef, job, state) {
194
+ const stateInfo = STATES_BY_NAME.get(state) || { name: state, label: state, variant: 'neutral' };
195
+ const attempts = Number(job.opts && job.opts.attempts) || 1;
196
+ const attemptsMade = Number(job.attemptsMade) || 0;
197
+
198
+ const scheduledMs = Number(job.timestamp) + (Number(job.opts && job.opts.delay) || 0);
199
+ const nextAttemptMs = nextAttemptOfStoredJob(job, scheduledMs);
200
+
201
+ const isRetryWait = state === 'delayed' && attemptsMade > 0;
202
+ const times = {
203
+ created: isoOrNull(job.timestamp),
204
+ // A delayed entry is either scheduled (nothing has run yet) or waiting out a backoff
205
+ dueAt: state === 'delayed' ? (attemptsMade ? isoOrNull(nextAttemptMs) : new Date(scheduledMs).toISOString()) : null,
206
+ isRetryWait,
207
+ processedOn: isoOrNull(job.processedOn),
208
+ finishedOn: isoOrNull(job.finishedOn)
209
+ };
210
+
211
+ const outcome = recordedOutcome(job);
212
+
213
+ return Object.assign(
214
+ {
215
+ id: String(job.id),
216
+ queue: queueDef.name,
217
+ url: entryUrl(queueDef.name, job.id),
218
+ state,
219
+ stateInfo,
220
+ account: (job.data && job.data.account) || null,
221
+ scheduled: new Date(scheduledMs).toISOString(),
222
+ attemptsMade,
223
+ attempts,
224
+ // Attempt numbers for people: "attempt 3 of 10" while running, "3 of 10 attempts" after
225
+ attemptsLabel: `${attemptsMade} of ${attempts}`,
226
+ when: whenOf(queueDef, state, times),
227
+ failure: describeFailure(queueDef.name, job),
228
+ // What the worker recorded of the last outcome, beyond the error
229
+ outcome,
230
+ duration: outcome && Number(outcome.duration) ? Number(outcome.duration) : null,
231
+ canPromote: !!queueDef.actions.promote && state === 'delayed',
232
+ canRetry: !!queueDef.actions.retry && state === 'failed',
233
+ canRemove: !!queueDef.actions.remove && state !== 'active'
234
+ },
235
+ times
236
+ );
237
+ }
238
+
239
+ function formatSubmit(queueDef, job, state) {
240
+ const data = job.data || {};
241
+ const envelope = data.envelope || {};
242
+ const to = Array.isArray(envelope.to) ? envelope.to : envelope.to ? [envelope.to] : [];
243
+
244
+ return Object.assign(formatCommon(queueDef, job, state), {
245
+ title: data.subject || '(no subject)',
246
+ subject: data.subject || null,
247
+ messageId: data.messageId || null,
248
+ from: envelope.from || null,
249
+ to,
250
+ toFirst: to[0] || null,
251
+ toMore: to.length > 1 ? to.length - 1 : 0,
252
+ gateway: data.gateway || null,
253
+ source: data.source || null,
254
+ idempotencyKey: data.idempotencyKey || null,
255
+ // 'delayed' names a scheduled send, 'queued' an immediate one; the job name is set once
256
+ isScheduledSend: job.name === 'delayed',
257
+ // Filled in by the Redis-backed listing, which knows whether the content is still stored
258
+ hasContent: null
259
+ });
260
+ }
261
+
262
+ function formatNotify(queueDef, job, state) {
263
+ const data = job.data || {};
264
+ const route = data._route && typeof data._route === 'object' ? data._route : null;
265
+ const payload = data.data && typeof data.data === 'object' ? data.data : {};
266
+
267
+ return Object.assign(formatCommon(queueDef, job, state), {
268
+ title: job.name,
269
+ event: job.name,
270
+ eventId: data.eventId || null,
271
+ date: data.date || null,
272
+ path: data.path || null,
273
+ specialUse: data.specialUse || null,
274
+ routeId: route ? route.id : null,
275
+ // resolved by the Redis-backed listing, which can look the route up
276
+ routeName: null,
277
+ hasMapping: !!(route && route.mapping !== undefined),
278
+ // What the event is about, for the row: a message's subject, an account's new state
279
+ about: payload.subject || payload.messageId || (payload.state ? `state: ${payload.state}` : null),
280
+ messageId: payload.messageId || null
281
+ });
282
+ }
283
+
284
+ function formatExport(queueDef, job, state) {
285
+ const data = job.data || {};
286
+ return Object.assign(formatCommon(queueDef, job, state), {
287
+ title: `Export ${data.exportId || job.id}`,
288
+ exportId: data.exportId || String(job.id)
289
+ });
290
+ }
291
+
292
+ const FORMATTERS = { submit: formatSubmit, notify: formatNotify, export: formatExport };
293
+
294
+ /**
295
+ * The page of one entry in the browser.
296
+ *
297
+ * @param {string} queueName - Queue name
298
+ * @param {string|number} jobId - Job ID
299
+ * @returns {string} Path
300
+ */
301
+ function entryUrl(queueName, jobId) {
302
+ return `/admin/queues/${queueName}/jobs/${encodeURIComponent(jobId)}`;
303
+ }
304
+
305
+ /**
306
+ * Formats a job of a queue for the browser.
307
+ *
308
+ * @param {Object} queueDef - Queue definition from ./definitions
309
+ * @param {Object} job - BullMQ job as stored
310
+ * @param {string} state - The state the job was listed from
311
+ * @returns {Object} Row or detail model
312
+ */
313
+ function formatJob(queueDef, job, state) {
314
+ return (FORMATTERS[queueDef.name] || formatExport)(queueDef, job, state);
315
+ }
316
+
317
+ /**
318
+ * The size of what a webhook delivery posts: the mapped payload when a route mapped it, the
319
+ * event payload otherwise. Measured on the detail page only, because serializing every row's
320
+ * payload (up to notifyTextSize of message text each) just to print a size is not worth it.
321
+ *
322
+ * @param {Object} job - BullMQ job as stored
323
+ * @returns {number} Bytes
324
+ */
325
+ function notifyPayloadSize(job) {
326
+ const data = job.data || {};
327
+ const route = data._route && typeof data._route === 'object' ? data._route : null;
328
+ try {
329
+ return Buffer.byteLength(JSON.stringify(route && route.mapping !== undefined ? route.mapping : data));
330
+ } catch (err) {
331
+ return 0;
332
+ }
333
+ }
334
+
335
+ // The fields a person would search a queue by, per queue
336
+ const SEARCH_FIELDS = {
337
+ submit: (job, data) => {
338
+ const envelope = data.envelope || {};
339
+ return [data.messageId, data.subject, data.gateway, data.idempotencyKey, envelope.from, ...(Array.isArray(envelope.to) ? envelope.to : [envelope.to])];
340
+ },
341
+ notify: (job, data) => {
342
+ const payload = data.data && typeof data.data === 'object' ? data.data : {};
343
+ return [job.name, data._route && data._route.id, data.path, payload.messageId, payload.subject, data.eventId];
344
+ },
345
+ export: (job, data) => [data.exportId]
346
+ };
347
+
348
+ /**
349
+ * Whether a job matches a free-text filter: a substring match over the fields a person would
350
+ * search a queue by. Case-insensitive; an empty filter matches everything.
351
+ *
352
+ * @param {Object} queueDef - Queue definition
353
+ * @param {Object} job - BullMQ job as stored
354
+ * @param {string} query - Filter text, already trimmed
355
+ * @returns {boolean}
356
+ */
357
+ function matchesQuery(queueDef, job, query) {
358
+ const needle = String(query || '').toLowerCase();
359
+ if (!needle) {
360
+ return true;
361
+ }
362
+
363
+ const data = job.data || {};
364
+ const fields = [job.id, data.account, ...(SEARCH_FIELDS[queueDef.name] || SEARCH_FIELDS.export)(job, data)];
365
+
366
+ return fields.some(field => field !== null && field !== undefined && String(field).toLowerCase().includes(needle));
367
+ }
368
+
369
+ /**
370
+ * The raw job, for the collapsed section of the detail page: what a support case asks for, in
371
+ * the shape BullMQ stores it.
372
+ *
373
+ * @param {Object} job - BullMQ job as stored
374
+ * @returns {Object} `{ name, data, opts, progress, returnvalue, stacktrace }`
375
+ */
376
+ function rawJob(job) {
377
+ return {
378
+ name: job.name,
379
+ data: job.data,
380
+ opts: job.opts,
381
+ progress: job.progress && typeof job.progress === 'object' ? job.progress : null,
382
+ returnvalue: job.returnvalue !== null && job.returnvalue !== undefined ? job.returnvalue : null,
383
+ stacktrace: Array.isArray(job.stacktrace) && job.stacktrace.length ? job.stacktrace.join('\n\n') : null
384
+ };
385
+ }
386
+
387
+ module.exports = { formatJob, describeFailure, matchesQuery, rawJob, humanSize, notifyPayloadSize, entryUrl, FAILURE_KINDS };