emailengine-app 2.78.0 → 2.79.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +68 -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 +112 -36
  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 +401 -0
  24. package/lib/api-routes/route-helpers.js +294 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +66 -38
  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 +526 -72
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/arf-detect.js +17 -4
  33. package/lib/auth-token.js +80 -8
  34. package/lib/bounce-detect.js +28 -17
  35. package/lib/consts.js +16 -0
  36. package/lib/db.js +26 -2
  37. package/lib/delivery-error.js +30 -1
  38. package/lib/email-client/base-client.js +27 -41
  39. package/lib/email-client/gmail-client.js +23 -17
  40. package/lib/email-client/imap/mailbox.js +58 -59
  41. package/lib/email-client/imap/subconnection.js +10 -7
  42. package/lib/email-client/imap/sync-operations.js +46 -46
  43. package/lib/email-client/imap-client.js +85 -28
  44. package/lib/email-client/message-builder.js +3 -3
  45. package/lib/email-client/notification-handler.js +1 -1
  46. package/lib/email-client/outlook/graph-api.js +10 -4
  47. package/lib/email-client/outlook-client.js +56 -64
  48. package/lib/email-client/smtp-pool-manager.js +1 -1
  49. package/lib/enum-descriptions.js +92 -2
  50. package/lib/export.js +1 -1
  51. package/lib/field-usage.js +133 -0
  52. package/lib/gateway.js +1 -1
  53. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  54. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  55. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  57. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  58. package/lib/imapproxy/imap-server.js +27 -7
  59. package/lib/license-beacon.js +4 -9
  60. package/lib/lists.js +49 -1
  61. package/lib/llm-pre-process.js +5 -5
  62. package/lib/logger.js +5 -1
  63. package/lib/lua/h-set-new-mark.lua +36 -0
  64. package/lib/message-port-stream.js +84 -1
  65. package/lib/metrics-collector.js +2 -2
  66. package/lib/oauth/gmail.js +9 -12
  67. package/lib/oauth/mail-ru.js +5 -7
  68. package/lib/oauth/outlook.js +9 -9
  69. package/lib/oauth/pubsub/google.js +25 -10
  70. package/lib/oauth/scope-checker.js +1 -1
  71. package/lib/oauth2-apps.js +290 -292
  72. package/lib/openapi/build-document.js +20 -8
  73. package/lib/openapi/joi-schema.js +20 -0
  74. package/lib/outbox.js +85 -17
  75. package/lib/pre-process.js +8 -8
  76. package/lib/queue-stats.js +49 -0
  77. package/lib/read-env-value.js +1 -1
  78. package/lib/reconnection-manager.js +2 -2
  79. package/lib/rewrite-text-nodes.js +4 -3
  80. package/lib/routes-ui.js +4 -0
  81. package/lib/schemas.js +218 -162
  82. package/lib/settings.js +98 -5
  83. package/lib/sub-script.js +2 -1
  84. package/lib/swagger-options.js +2 -1
  85. package/lib/templates.js +4 -4
  86. package/lib/threads.js +2 -2
  87. package/lib/token-audit-log.js +231 -0
  88. package/lib/token-permission-view.js +219 -0
  89. package/lib/token-permissions.js +172 -0
  90. package/lib/tokens.js +247 -66
  91. package/lib/tools.js +142 -37
  92. package/lib/ui-routes/account-routes.js +42 -15
  93. package/lib/ui-routes/admin-config-routes.js +18 -10
  94. package/lib/ui-routes/admin-entities-routes.js +117 -38
  95. package/lib/ui-routes/auth-routes.js +30 -24
  96. package/lib/ui-routes/export-routes.js +10 -4
  97. package/lib/ui-routes/oauth-config-routes.js +12 -12
  98. package/lib/ui-routes/reference-routes.js +3 -3
  99. package/lib/ui-routes/route-helpers.js +78 -2
  100. package/lib/ui-routes/settings-page.js +1 -1
  101. package/lib/ui-routes/smtp-test-routes.js +1 -1
  102. package/lib/ui-routes/suppression-list-routes.js +299 -0
  103. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  104. package/lib/utils/decode-headers.js +42 -0
  105. package/lib/utils/header-map.js +48 -0
  106. package/lib/utils/network.js +2 -2
  107. package/lib/utils/unsafe-key.js +59 -0
  108. package/lib/web-safe-html.js +1 -1
  109. package/lib/webhook-routing.js +84 -0
  110. package/lib/webhooks.js +48 -14
  111. package/package.json +11 -10
  112. package/sbom.json +1 -1
  113. package/server.js +116 -55
  114. package/static/css/flyonui.css +1 -1
  115. package/static/css/src/app.tailwind.css +136 -9
  116. package/static/js/reference.js +456 -10
  117. package/static/js/ui.js +43 -0
  118. package/static/licenses.html +51 -41
  119. package/translations/messages.pot +59 -59
  120. package/views/accounts/account.hbs +75 -13
  121. package/views/accounts/browse.hbs +19 -36
  122. package/views/accounts/edit.hbs +2 -2
  123. package/views/config/logging.hbs +6 -0
  124. package/views/config/oauth/app.hbs +0 -2
  125. package/views/config/security.hbs +13 -0
  126. package/views/gateways/edit.hbs +1 -1
  127. package/views/gateways/gateway.hbs +2 -2
  128. package/views/gateways/index.hbs +7 -7
  129. package/views/partials/accounts_table.hbs +7 -7
  130. package/views/partials/oauth_form.hbs +0 -15
  131. package/views/partials/reference/disclosure.hbs +8 -2
  132. package/views/partials/reference/operation.hbs +47 -13
  133. package/views/partials/reference/params.hbs +17 -1
  134. package/views/partials/reference/schema-node.hbs +110 -52
  135. package/views/partials/reference/schema-tools.hbs +25 -0
  136. package/views/partials/reference/try-it.hbs +84 -11
  137. package/views/partials/side_menu.hbs +1 -0
  138. package/views/partials/ui/checkbox.hbs +2 -2
  139. package/views/partials/ui/tabs.hbs +7 -1
  140. package/views/reference/token.hbs +4 -0
  141. package/views/suppression-lists/index.hbs +85 -0
  142. package/views/suppression-lists/list.hbs +87 -0
  143. package/views/templates/index.hbs +10 -4
  144. package/views/templates/template.hbs +1 -1
  145. package/views/tokens/index.hbs +53 -6
  146. package/views/tokens/new.hbs +334 -5
  147. package/workers/api.js +185 -102
  148. package/workers/documents.js +46 -26
  149. package/workers/export.js +20 -8
  150. package/workers/imap-proxy.js +2 -2
  151. package/workers/imap.js +77 -78
  152. package/workers/smtp.js +13 -7
  153. package/workers/submit.js +40 -30
  154. package/workers/webhooks.js +80 -26
  155. package/lib/feature-flags.js +0 -48
@@ -17,7 +17,6 @@ module.exports = {
17
17
  let serverId = {};
18
18
  let serverIdList = [];
19
19
  let key = false;
20
- let maxKeyLen = 0;
21
20
 
22
21
  if (this._server.options.id && typeof this._server.options.id === 'object') {
23
22
  Object.keys(this._server.options.id).forEach(key => {
@@ -37,7 +36,6 @@ module.exports = {
37
36
  } else {
38
37
  if (allowedKeys.indexOf(key) >= 0) {
39
38
  clientId[key] = (val.value || '').toString();
40
- maxKeyLen = Math.max(maxKeyLen, key.length);
41
39
  }
42
40
  key = false;
43
41
  }
@@ -46,7 +44,8 @@ module.exports = {
46
44
  this._server.logger.info(
47
45
  {
48
46
  tnx: 'id',
49
- cid: this.id
47
+ cid: this.id,
48
+ clientId
50
49
  },
51
50
  'Client identification data received'
52
51
  );
@@ -62,16 +61,6 @@ module.exports = {
62
61
  .sort((a, b) => allowedKeys.indexOf(a) - allowedKeys.indexOf(b))
63
62
  .forEach(key => {
64
63
  logdata[`_client_id_${key}`] = clientId[key];
65
- this._server.logger.info(
66
- {
67
- tnx: 'id',
68
- cid: this.id
69
- },
70
- '%s%s: %s',
71
- key,
72
- new Array(maxKeyLen - key.length + 1).join(' '),
73
- clientId[key]
74
- );
75
64
  });
76
65
 
77
66
  this._server.loggelf(logdata);
@@ -104,7 +104,7 @@ function upgrade(connection) {
104
104
  user: connection.session && connection.session.user && connection.session.user.username,
105
105
  cipher: cipher && cipher.name
106
106
  },
107
- 'Connection upgraded to TLS using ',
107
+ 'Connection upgraded to TLS using %s',
108
108
  (cipher && cipher.name) || 'N/A'
109
109
  );
110
110
 
@@ -122,7 +122,7 @@ class IMAPCommand {
122
122
  cid: this.connection.id,
123
123
  src: 'C'
124
124
  },
125
- this.payload
125
+ this.loggablePayload()
126
126
  );
127
127
 
128
128
  this.payload = ''; // reset payload
@@ -180,7 +180,7 @@ class IMAPCommand {
180
180
  cid: this.connection.id,
181
181
  src: 'C'
182
182
  },
183
- this.payload || ''
183
+ this.loggablePayload()
184
184
  );
185
185
  if (!this.countBadResponses()) {
186
186
  // stop processing
@@ -197,8 +197,7 @@ class IMAPCommand {
197
197
  cid: this.connection.id,
198
198
  src: 'C'
199
199
  },
200
- '<%s bytes of data>',
201
- (this.payload && this.payload.length) || 0
200
+ this.loggablePayload()
202
201
  );
203
202
  return this.connection._nextHandler(this.payload, next);
204
203
  }
@@ -213,7 +212,7 @@ class IMAPCommand {
213
212
  cid: this.connection.id,
214
213
  src: 'C'
215
214
  },
216
- this.payload
215
+ this.loggablePayload()
217
216
  );
218
217
  this.connection.send(this.tag + ' BAD ' + E.message);
219
218
  if (!this.countBadResponses()) {
@@ -318,6 +317,23 @@ class IMAPCommand {
318
317
  });
319
318
  }
320
319
 
320
+ // LOGIN and AUTHENTICATE payloads carry credentials and must never be logged raw.
321
+ // Also scans the payload itself for malformed lines (e.g. a missing tag) where the
322
+ // credential-bearing command name was not parsed into this.command.
323
+ loggablePayload() {
324
+ // A continuation frame is not a command, so neither the parsed command name nor the payload
325
+ // text identifies it - during AUTHENTICATE it is the bare base64 SASL blob. Nothing about
326
+ // it is safe to render, so report the size only, the same way the accepted path does.
327
+ if (typeof this.connection._nextHandler === 'function') {
328
+ return `<${(this.payload && this.payload.length) || 0} bytes of data>`;
329
+ }
330
+
331
+ if (/^(AUTHENTICATE|LOGIN)/i.test(this.command || '') || /^\s*(?:\S+\s+)?(AUTHENTICATE|LOGIN)\b/i.test(this.payload || '')) {
332
+ return [this.tag, this.command, '(* payload hidden *)'].filter(v => v).join(' ');
333
+ }
334
+ return this.payload || '';
335
+ }
336
+
321
337
  sendNotifications(handler, callback) {
322
338
  if (this.connection.state !== 'Selected' || !!handler.disableNotifications) {
323
339
  // nothing to advertise if not in Selected state
@@ -103,7 +103,7 @@ class IMAPConnection extends EventEmitter {
103
103
  this._closed = false;
104
104
 
105
105
  this.logger = {};
106
- ['info', 'debug', 'error'].forEach(level => {
106
+ ['info', 'debug', 'warn', 'error'].forEach(level => {
107
107
  this.logger[level] = (...args) => {
108
108
  if (!this.ignore) {
109
109
  this._server.logger[level](...args);
@@ -173,7 +173,7 @@ class IMAPConnection extends EventEmitter {
173
173
  this.session.clientHostname = this.clientHostname = clientHostname || '[' + this.remoteAddress + ']';
174
174
 
175
175
  if (greetingSent && clientHostname) {
176
- this.logger.info(
176
+ this.logger.debug(
177
177
  {
178
178
  tnx: 'connect',
179
179
  cid: this.id
@@ -267,7 +267,7 @@ class IMAPConnection extends EventEmitter {
267
267
  this[!this.compression ? '_socket' : '_deflate'].write(payload + '\r\n', 'binary', (...args) => {
268
268
  if (args[0]) {
269
269
  // write error
270
- this.logger.error(
270
+ this.logger.warn(
271
271
  {
272
272
  tnx: 'send',
273
273
  cid: this.id,
@@ -284,7 +284,7 @@ class IMAPConnection extends EventEmitter {
284
284
  });
285
285
  } catch (err) {
286
286
  // write error
287
- this.logger.error(
287
+ this.logger.warn(
288
288
  {
289
289
  tnx: 'send',
290
290
  cid: this.id,
@@ -510,6 +510,8 @@ class IMAPConnection extends EventEmitter {
510
510
  return;
511
511
  }
512
512
 
513
+ let logLevel = 'error';
514
+
513
515
  if (err && /SSL[23]*_GET_CLIENT_HELLO|ssl[23]*_read_bytes|ssl_bytes_to_cipher_list/i.test(err.message)) {
514
516
  let message = err.message;
515
517
  err.message = 'Failed to establish TLS session';
@@ -521,6 +523,8 @@ class IMAPConnection extends EventEmitter {
521
523
  message,
522
524
  remoteAddress: this.remoteAddress
523
525
  };
526
+ // TLS handshake garbage from the client, not a server fault
527
+ logLevel = 'warn';
524
528
  }
525
529
 
526
530
  if (!err || !err.message) {
@@ -530,15 +534,21 @@ class IMAPConnection extends EventEmitter {
530
534
  err.meta = {
531
535
  remoteAddress: this.remoteAddress
532
536
  };
537
+ // Client-caused, same classification the server-level handler gives a SocketError. That
538
+ // handler never sees this one: `processed` below makes it return early, so the level has
539
+ // to be lowered here or every scanner and load-balancer probe lands in the error stream.
540
+ logLevel = 'warn';
533
541
  }
534
542
 
535
- this.logger.error(
543
+ this.logger[logLevel](
536
544
  {
537
545
  err,
538
546
  cid: this.id
539
547
  },
540
548
  err.message
541
549
  );
550
+ // mark as logged so server-level listeners do not log a duplicate entry
551
+ err.processed = true;
542
552
  this.emit('error', err);
543
553
  }
544
554
 
@@ -317,7 +317,23 @@ const createServer = function (options = {}) {
317
317
  let server = new IMAPServer(options);
318
318
 
319
319
  server.on('error', err => {
320
- serverLogger.error({ msg: 'Server error', err });
320
+ if (err && err.processed) {
321
+ // already logged by the connection that raised it
322
+ return;
323
+ }
324
+ let entry = { msg: 'Server error', err };
325
+ if (err && err.meta && err.meta.remoteAddress) {
326
+ entry.remoteAddress = err.meta.remoteAddress;
327
+ }
328
+ if (err && err.report === false) {
329
+ // e.g. a scanner closing the socket while initiating TLS
330
+ serverLogger.debug(entry);
331
+ } else if (err && (err.code === 'TLSError' || err.code === 'SocketError')) {
332
+ // client-caused connection or TLS handshake failure
333
+ serverLogger.warn(entry);
334
+ } else {
335
+ serverLogger.error(entry);
336
+ }
321
337
  });
322
338
 
323
339
  server.onAuth = function (login, session, callback) {
@@ -366,7 +382,7 @@ const createServer = function (options = {}) {
366
382
  try {
367
383
  downstream.imapClient.close();
368
384
  } catch (err) {
369
- proxyLogger.error({ msg: 'Failed to close upstream connection', err });
385
+ proxyLogger.warn({ msg: 'Failed to close upstream connection', err });
370
386
  }
371
387
 
372
388
  try {
@@ -380,8 +396,8 @@ const createServer = function (options = {}) {
380
396
 
381
397
  // Every terminal event from either leg funnels into the idempotent
382
398
  // closeProxy(). The helper keeps that wiring declarative; pass a message
383
- // to log (level defaults to 'error', use 'info' for graceful closes).
384
- const teardownOn = (emitter, event, msg, level = 'error') => {
399
+ // to log (level defaults to 'warn', use 'info' for graceful closes).
400
+ const teardownOn = (emitter, event, msg, level = 'warn') => {
385
401
  emitter.on(event, err => {
386
402
  if (msg) {
387
403
  let entry = { msg };
@@ -405,7 +421,7 @@ const createServer = function (options = {}) {
405
421
  teardownOn(downstream.readSocket, 'end', 'Upstream connection closed', 'info');
406
422
 
407
423
  downstream.readSocket.on('error', err => {
408
- proxyLogger.error({ msg: 'Upstream read error', err });
424
+ proxyLogger.warn({ msg: 'Upstream read error', err });
409
425
  try {
410
426
  // best-effort notice to the client before tearing down
411
427
  upstream.socket.write('* BYE Upstream connection error\r\n');
@@ -446,26 +462,30 @@ const createServer = function (options = {}) {
446
462
  })
447
463
  .catch(err => {
448
464
  if (err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED') {
465
+ serverLogger.warn({ msg: 'Upstream authentication failed', account, cid: session.id, err });
449
466
  let error = new Error(
450
467
  `${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
451
468
  );
452
469
  error.response = err.responseStatus || 'NO';
453
470
  return callback(error);
454
471
  } else {
455
- serverLogger.error({ msg: 'Failed to create proxy', err });
472
+ serverLogger.error({ msg: 'Failed to create proxy', account, cid: session.id, err });
456
473
  return callback(err);
457
474
  }
458
475
  });
459
476
  })
460
477
  .catch(err => {
461
- serverLogger.error({ msg: 'Authentication check failed', username: login.username, err });
478
+ let entry = { msg: 'Authentication check failed', username: login.username, cid: session.id, remoteAddress: session.remoteAddress, err };
462
479
  if (err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED') {
480
+ // routine failed client login, not a proxy fault
481
+ serverLogger.warn(entry);
463
482
  let error = new Error(
464
483
  `${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`
465
484
  );
466
485
  error.response = err.responseStatus || 'NO';
467
486
  return callback(error);
468
487
  }
488
+ serverLogger.error(entry);
469
489
  return callback(err);
470
490
  });
471
491
  };
@@ -23,7 +23,6 @@ const { getCounterValues, hasEnvValue, readEnvValue, getBoolean } = require('./t
23
23
  const { REDIS_PREFIX } = require('./consts');
24
24
  const { oauth2Apps } = require('./oauth2-apps');
25
25
  const passkeys = require('./passkeys');
26
- const featureFlags = require('./feature-flags');
27
26
  const { documentStoreFeatureEnabled } = require('./document-store');
28
27
 
29
28
  // Beacon schema version. Bump when the meaning of codes changes so the license server can adapt.
@@ -131,7 +130,7 @@ async function collectBeacon({ redis, logger }) {
131
130
  return await fn();
132
131
  } catch (err) {
133
132
  if (logger) {
134
- logger.error({ msg: 'Beacon field collection failed', err });
133
+ logger.debug({ msg: 'Beacon field collection failed', err });
135
134
  }
136
135
  return undefined;
137
136
  }
@@ -270,7 +269,6 @@ async function collectBeacon({ redis, logger }) {
270
269
  if (documentStoreFeatureEnabled) dep.push('documentStoreGate');
271
270
  if (on('documentStoreGenerateEmbeddings')) dep.push('ds_embed');
272
271
  if (on('documentStorePreProcessingEnabled')) dep.push('ds_preproc');
273
- if (on('gmailEnabled') || on('outlookEnabled') || on('mailRuEnabled')) dep.push('legacyOauth');
274
272
  if (on('trackSentMessages')) dep.push('trackSent');
275
273
  await safe(async () => {
276
274
  const ids = await redis.smembers(`${REDIS_PREFIX}wh:i`);
@@ -297,9 +295,6 @@ async function collectBeacon({ redis, logger }) {
297
295
  });
298
296
  diag.dep = dep.sort();
299
297
 
300
- // Enabled EENGINE_FEATURE_* flags (already sorted).
301
- diag.flags = (await safe(() => featureFlags.listEnabled())) || [];
302
-
303
298
  // Runtime context.
304
299
  diag.dist = installChannel();
305
300
  diag.node = process.versions.node;
@@ -310,7 +305,7 @@ async function collectBeacon({ redis, logger }) {
310
305
  return { fh, diag };
311
306
  } catch (err) {
312
307
  if (logger) {
313
- logger.error({ msg: 'Beacon collection failed', err });
308
+ logger.warn({ msg: 'Beacon collection failed', err });
314
309
  }
315
310
  return null;
316
311
  }
@@ -334,7 +329,7 @@ async function attachBeacon(body, { redis, logger, now }) {
334
329
  }
335
330
  } catch (err) {
336
331
  if (logger) {
337
- logger.error({ msg: 'License beacon collection failed', err });
332
+ logger.warn({ msg: 'License beacon collection failed', err });
338
333
  }
339
334
  }
340
335
  }
@@ -355,7 +350,7 @@ async function persistBeaconMarkers({ redis, logger, body, now, needFull }) {
355
350
  }
356
351
  } catch (err) {
357
352
  if (logger) {
358
- logger.error({ msg: 'Failed to persist license beacon markers', err });
353
+ logger.warn({ msg: 'Failed to persist license beacon markers', err });
359
354
  }
360
355
  }
361
356
  }
package/lib/lists.js CHANGED
@@ -19,6 +19,54 @@ class ListHandler {
19
19
  return `${REDIS_PREFIX}lists:unsub:entries:${listId}`;
20
20
  }
21
21
 
22
+ normalizeRecipient(recipient) {
23
+ return (recipient || '').toString().toLowerCase().trim();
24
+ }
25
+
26
+ // does the list itself exist
27
+ async exists(listId) {
28
+ return (await this.redis.hexists(this.getListsIndexKey(), listId)) === 1;
29
+ }
30
+
31
+ // is the recipient suppressed on this list
32
+ async has(listId, recipient) {
33
+ return (await this.redis.hexists(this.getListsContentKey(listId), this.normalizeRecipient(recipient))) === 1;
34
+ }
35
+
36
+ // Adds a suppression record. The entry key is the normalized recipient address; the stored
37
+ // record echoes the recipient and is stamped with a created time unless the caller provides
38
+ // one. Returns 1 when the address was newly added, 0 when it was already listed (eeListAdd
39
+ // keeps the list counter in sync atomically).
40
+ async add(listId, recipient, meta) {
41
+ let record = Object.assign({ recipient }, meta || {});
42
+ if (!record.created) {
43
+ record.created = new Date().toISOString();
44
+ }
45
+ return await this.redis.eeListAdd(
46
+ this.getListsIndexKey(),
47
+ this.getListsContentKey(listId),
48
+ listId,
49
+ this.normalizeRecipient(recipient),
50
+ JSON.stringify(record)
51
+ );
52
+ }
53
+
54
+ // Returns 1 when the address was removed, 0 when it was not listed
55
+ async remove(listId, recipient) {
56
+ return await this.redis.eeListRemove(this.getListsIndexKey(), this.getListsContentKey(listId), listId, this.normalizeRecipient(recipient));
57
+ }
58
+
59
+ // Drops a whole list with all of its entries. Returns true when the list existed.
60
+ async deleteList(listId) {
61
+ let result = await this.redis.multi().hdel(this.getListsIndexKey(), listId).del(this.getListsContentKey(listId)).exec();
62
+ for (let [err] of result) {
63
+ if (err) {
64
+ throw err;
65
+ }
66
+ }
67
+ return !!result[0][1];
68
+ }
69
+
22
70
  async list(page, pageSize) {
23
71
  page = Math.max(Number(page) || 0, 0);
24
72
  pageSize = Math.max(Number(pageSize) || 20, 1);
@@ -45,7 +93,7 @@ class ListHandler {
45
93
  }
46
94
 
47
95
  async listContent(listId, page, pageSize) {
48
- let exists = await redis.hexists(this.getListsIndexKey(), listId);
96
+ let exists = await this.exists(listId);
49
97
  if (!exists) {
50
98
  let message = 'Requested blocklist was not found';
51
99
  let error = Boom.boomify(new Error(message), { statusCode: 404 });
@@ -41,7 +41,7 @@ class LLMPreProcessHandler {
41
41
  } catch (err) {
42
42
  await this.storeLog('filter', null, err.stack);
43
43
 
44
- logger.error({ msg: 'Compilation failed', type: 'filter', err });
44
+ logger.error({ msg: 'Failed to compile LLM pre-processing script', component: 'llm-pre-process', type: 'filter', err });
45
45
  preProcessData.compiledFn = null;
46
46
  }
47
47
 
@@ -54,7 +54,7 @@ class LLMPreProcessHandler {
54
54
  return await preProcessData.compiledFn.exec(payload);
55
55
  } catch (err) {
56
56
  await this.storeLog('filter', payload, err.stack);
57
- logger.error({ msg: 'Exec failed', type: 'filter', err });
57
+ logger.error({ msg: 'Failed to execute LLM pre-processing script', component: 'llm-pre-process', type: 'filter', err });
58
58
  return null;
59
59
  }
60
60
  };
@@ -85,7 +85,7 @@ class LLMPreProcessHandler {
85
85
  try {
86
86
  await redis.multi().rpush(this.getPreProcessLogKey(), logRow).ltrim(this.getPreProcessLogKey(), -maxLogLines, -1).exec();
87
87
  } catch (err) {
88
- logger.error({ msg: 'Failed to insert error log entries', err });
88
+ logger.error({ msg: 'Failed to insert error log entries', component: 'llm-pre-process', err });
89
89
  }
90
90
  }
91
91
 
@@ -102,7 +102,7 @@ class LLMPreProcessHandler {
102
102
  let entry = msgpack.decode(line);
103
103
  logEntries.unshift(entry);
104
104
  } catch (err) {
105
- logger.error({ msg: 'Failed to retrieve log line', entry: line && line.toString('base64') });
105
+ logger.error({ msg: 'Failed to decode log line', component: 'llm-pre-process', entry: line && line.toString('base64'), err });
106
106
  }
107
107
  }
108
108
 
@@ -124,7 +124,7 @@ class LLMPreProcessHandler {
124
124
  } catch (err) {
125
125
  await this.storeLog('filter', payload, err.stack);
126
126
 
127
- logger.error({ msg: 'Exec failed', type: 'filter', err });
127
+ logger.error({ msg: 'Failed to execute LLM pre-processing script', component: 'llm-pre-process', type: 'filter', err });
128
128
  }
129
129
 
130
130
  if (canUse && payload) {
package/lib/logger.js CHANGED
@@ -7,7 +7,7 @@ if (!process.env.EE_ENV_LOADED) {
7
7
 
8
8
  const config = require('@zone-eu/wild-config');
9
9
  const pino = require('pino');
10
- const { TRANSIENT_NETWORK_CODES } = require('./consts');
10
+ const { TRANSIENT_NETWORK_CODES, REDACTED_LOG_KEYS } = require('./consts');
11
11
 
12
12
  config.log = config.log || {
13
13
  level: 'trace'
@@ -25,6 +25,10 @@ function isTransientFetchError(err) {
25
25
  }
26
26
 
27
27
  let logger = pino({
28
+ // Redaction belongs on the root logger, not on a single worker's child: the imap, smtp,
29
+ // imap-proxy, submit, webhooks, export and documents workers all log through this instance,
30
+ // and several of them log joi errors carrying credentials.
31
+ redact: REDACTED_LOG_KEYS,
28
32
  formatters: {
29
33
  log(object) {
30
34
  if (object.err && ['TypeError', 'RangeError'].includes(object.err.name) && !isTransientFetchError(object.err)) {
@@ -0,0 +1,36 @@
1
+ --[[
2
+ Script: h-set-new-mark.lua
3
+ Purpose: Sets a hash field value only if the field doesn't already exist, and stamps a second
4
+ marker field in the same atomic step when it does. Used for seeded defaults that a
5
+ marker field declares "still owned by the seeder": writing the two separately leaves a
6
+ crash window where the seeded value exists without its marker and can never be told
7
+ apart from an explicit choice.
8
+
9
+ KEYS:
10
+ [1] hashKey - The hash key to operate on
11
+
12
+ ARGV:
13
+ [1] entryKey - The hash field name
14
+ [2] value - The value to set
15
+ [3] markerKey - The marker field name, written only when the value field was created
16
+ [4] markerValue - The marker value
17
+
18
+ Returns:
19
+ 1 if the value field didn't exist and both fields were written
20
+ 0 if the value field already exists (no operation, the marker is not touched)
21
+ --]]
22
+
23
+ local hashKey = KEYS[1];
24
+ local entryKey = ARGV[1];
25
+
26
+ local value = ARGV[2];
27
+ local markerKey = ARGV[3];
28
+ local markerValue = ARGV[4];
29
+
30
+ if redis.call("HEXISTS", hashKey, entryKey) == 0 then
31
+ redis.call("HSET", hashKey, entryKey, value);
32
+ redis.call("HSET", hashKey, markerKey, markerValue);
33
+ return 1; -- New field created and marked
34
+ else
35
+ return 0; -- Field already exists, no operation
36
+ end;
@@ -19,7 +19,24 @@ class MessagePortWritable extends Writable {
19
19
  this.destroy();
20
20
  }
21
21
  };
22
+
23
+ // A cancel message only arrives while the consumer is alive to send one. When its thread
24
+ // dies instead, the channel closes without one, and the transfer would otherwise drain the
25
+ // whole source into a port nobody is reading - holding the mailbox lock for the duration.
26
+ //
27
+ // A port that closes with nothing queued behind it reports it only to a listener that was
28
+ // already attached - the event is emitted when the port is started and drained, and a
29
+ // listener added afterwards never sees it. So the producer has to construct this when the
30
+ // port arrives, not once it has content to send: the wait in between is the whole window in
31
+ // which the consumer's thread can die, and for an attachment that is most of the transfer.
32
+ // releaseListeners() is how a producer that ends up with nothing to send gives the port
33
+ // back.
34
+ this.onPortClose = () => {
35
+ this.destroy();
36
+ };
37
+
22
38
  this.messagePort.on('message', this.onPortMessage);
39
+ this.messagePort.on('close', this.onPortClose);
23
40
  }
24
41
 
25
42
  postToPort(message) {
@@ -33,12 +50,20 @@ class MessagePortWritable extends Writable {
33
50
  }
34
51
  }
35
52
 
53
+ // Hands the port back untouched. Used by a producer that took the port but found nothing to
54
+ // send (a 404, say): closing it would reach the consumer as a failed transfer rather than as
55
+ // the error it is about to be handed, and leaving the listeners attached leaks them.
56
+ releaseListeners() {
57
+ this.messagePort.removeListener('message', this.onPortMessage);
58
+ this.messagePort.removeListener('close', this.onPortClose);
59
+ }
60
+
36
61
  closePort() {
37
62
  if (this.portClosed) {
38
63
  return;
39
64
  }
40
65
  this.portClosed = true;
41
- this.messagePort.removeListener('message', this.onPortMessage);
66
+ this.releaseListeners();
42
67
  try {
43
68
  this.messagePort.close();
44
69
  } catch (err) {
@@ -83,6 +108,7 @@ class MessagePortReadable extends Readable {
83
108
 
84
109
  this.canRead = false;
85
110
  this.portClosed = false;
111
+ this.transferComplete = false;
86
112
 
87
113
  this.readableQueue = [];
88
114
  this.onPortMessage = message => {
@@ -96,6 +122,9 @@ class MessagePortReadable extends Readable {
96
122
  return;
97
123
  }
98
124
  if (message.done || message.value) {
125
+ if (message.done) {
126
+ this.transferComplete = true;
127
+ }
99
128
  this.readableQueue.push(message);
100
129
 
101
130
  if (this.canRead && this.readableQueue.length === 1) {
@@ -103,7 +132,18 @@ class MessagePortReadable extends Readable {
103
132
  }
104
133
  }
105
134
  };
135
+
136
+ // Queued messages are delivered before 'close', so a channel that closes without
137
+ // { done: true } was cut short - most likely the producing worker died mid-download.
138
+ // Fail the read rather than presenting a truncated body or hanging on it forever.
139
+ this.onPortClose = () => {
140
+ if (!this.transferComplete && !this.destroyed) {
141
+ this.destroy(new Error('Message stream transfer interrupted'));
142
+ }
143
+ };
144
+
106
145
  this.messagePort.on('message', this.onPortMessage);
146
+ this.messagePort.on('close', this.onPortClose);
107
147
  }
108
148
 
109
149
  _processReading() {
@@ -132,6 +172,7 @@ class MessagePortReadable extends Readable {
132
172
  // ignore - the peer may already be closed
133
173
  }
134
174
  this.messagePort.removeListener('message', this.onPortMessage);
175
+ this.messagePort.removeListener('close', this.onPortClose);
135
176
  try {
136
177
  this.messagePort.close();
137
178
  } catch (closeErr) {
@@ -153,6 +194,20 @@ class MessagePortReadable extends Readable {
153
194
  * @param {Object} [logger] - Optional logger used to report transfer failures
154
195
  */
155
196
  function pipeToMessagePort(source, writable, logger) {
197
+ // pipeline() throws ERR_STREAM_UNABLE_TO_PIPE *synchronously* when the destination is
198
+ // already destroyed. The callback below never runs in that case, so the throw escapes to
199
+ // the global uncaughtException handler and takes the worker - and every account assigned
200
+ // to it - down with it. An aborted consumer destroys the writable through its
201
+ // { cancel: true } message, and on a slow upstream fetch that can easily land before this
202
+ // helper is entered at all, so it is a routine state rather than an edge case.
203
+ if (writable.destroyed) {
204
+ // Nothing will drain the source now, so release it explicitly - otherwise the upstream
205
+ // download keeps running and the mailbox lock it holds is never given back.
206
+ source.destroy();
207
+ logger?.debug?.({ msg: 'Message stream transfer aborted by consumer before it started' });
208
+ return;
209
+ }
210
+
156
211
  pipeline(source, writable, err => {
157
212
  if (!err || !logger) {
158
213
  return;
@@ -171,6 +226,34 @@ function pipeToMessagePort(source, writable, logger) {
171
226
  });
172
227
  }
173
228
 
229
+ /**
230
+ * Sends a finished download to the API worker over a destination bound to the transferred port.
231
+ * IMAP resolves a download to a stream and Gmail and Graph to a Buffer; the Buffer is wrapped so
232
+ * both shapes take the same path, leaving pipeToMessagePort() as the single place that has to get
233
+ * an aborted consumer right.
234
+ *
235
+ * Takes the destination rather than the port, because the producer has to build it when the port
236
+ * arrives - see the MessagePortWritable constructor for why. By the time there is content to send,
237
+ * a consumer that gave up has already destroyed it, and pipeToMessagePort() releases the source
238
+ * instead of transferring into a port nobody reads.
239
+ *
240
+ * @param {MessagePortWritable} writable - Destination built when the port arrived
241
+ * @param {Buffer|Readable} source - Payload to transfer
242
+ * @param {Object} [logger] - Optional logger used to report transfer failures
243
+ * @returns {MessagePortWritable} The same destination (used by tests; callers may ignore it)
244
+ */
245
+ function sendToMessagePort(writable, source, logger) {
246
+ const stream = Buffer.isBuffer(source) ? Readable.from([source], { objectMode: false }) : source;
247
+
248
+ // A { cancel: true } already queued by a consumer that gave up is delivered on the next turn of
249
+ // the event loop. Dispatching from the check phase puts the guard in pipeToMessagePort() after
250
+ // that delivery rather than racing it.
251
+ setImmediate(() => pipeToMessagePort(stream, writable, logger));
252
+
253
+ return writable;
254
+ }
255
+
174
256
  module.exports.MessagePortWritable = MessagePortWritable;
175
257
  module.exports.MessagePortReadable = MessagePortReadable;
176
258
  module.exports.pipeToMessagePort = pipeToMessagePort;
259
+ module.exports.sendToMessagePort = sendToMessagePort;
@@ -51,9 +51,9 @@ class MetricsCollector {
51
51
  if (this.collectorTimer) {
52
52
  clearTimeout(this.collectorTimer);
53
53
  this.collectorTimer = null;
54
+ this.logger.info({ msg: 'Stopped background metrics collector' });
54
55
  }
55
56
  this.isCollecting = false;
56
- this.logger.info({ msg: 'Stopped background metrics collector' });
57
57
  }
58
58
 
59
59
  /**
@@ -175,7 +175,7 @@ class MetricsCollector {
175
175
  const cacheAge = this.lastCollectionTime ? Date.now() - this.lastCollectionTime : null;
176
176
  this.logger.debug({
177
177
  msg: 'Returning cached metrics',
178
- workers: this.cachedThreadsInfo.length,
178
+ threads: this.cachedThreadsInfo.length,
179
179
  cacheAge
180
180
  });
181
181
  return this.cachedThreadsInfo;