emailengine-app 2.82.0 → 2.82.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 (65) hide show
  1. package/.ncurc.js +23 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/bin/emailengine.js +77 -7
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +35 -10
  8. package/lib/api-routes/account-binding.js +58 -0
  9. package/lib/api-routes/account-routes.js +48 -9
  10. package/lib/api-routes/behavior-notes.js +4 -0
  11. package/lib/api-routes/gateway-routes.js +10 -2
  12. package/lib/api-routes/message-routes.js +10 -3
  13. package/lib/api-routes/outbox-routes.js +1 -1
  14. package/lib/api-routes/settings-routes.js +1 -2
  15. package/lib/api-routes/token-routes.js +1 -1
  16. package/lib/autodetect-imap-settings.js +146 -4
  17. package/lib/consts.js +12 -0
  18. package/lib/db.js +1 -19
  19. package/lib/delivery-error.js +68 -1
  20. package/lib/email-client/base-client.js +6 -13
  21. package/lib/email-client/credential-errors.js +21 -5
  22. package/lib/email-client/gmail-client.js +2 -2
  23. package/lib/email-client/imap-client.js +2 -1
  24. package/lib/email-client/message-builder.js +41 -11
  25. package/lib/email-client/outlook-client.js +196 -67
  26. package/lib/enum-descriptions.js +5 -1
  27. package/lib/export.js +8 -2
  28. package/lib/gateway.js +5 -0
  29. package/lib/get-secret.js +1 -21
  30. package/lib/mcp/tools.js +95 -36
  31. package/lib/oauth/gmail.js +42 -12
  32. package/lib/oauth/mail-ru.js +24 -17
  33. package/lib/oauth/outlook.js +34 -24
  34. package/lib/oauth/scope-checker.js +35 -1
  35. package/lib/oauth/scope-list.js +55 -0
  36. package/lib/oauth/token-fetch.js +47 -0
  37. package/lib/oauth2-apps.js +16 -47
  38. package/lib/outbox.js +2 -7
  39. package/lib/queue-retention.js +4 -2
  40. package/lib/read-env-value.js +33 -2
  41. package/lib/schemas.js +62 -15
  42. package/lib/token-audit-log.js +3 -2
  43. package/lib/tools.js +1 -1
  44. package/lib/ui-routes/account-routes.js +40 -7
  45. package/lib/ui-routes/oauth-config-routes.js +3 -14
  46. package/lib/ui-routes/route-helpers.js +23 -23
  47. package/lib/ui-routes/special-use-paths.js +33 -0
  48. package/lib/utils/network.js +9 -17
  49. package/package.json +18 -18
  50. package/sbom.json +1 -1
  51. package/server.js +21 -3
  52. package/setup-production.sh +16 -7
  53. package/static/licenses.html +30 -20
  54. package/translations/messages.pot +74 -56
  55. package/views/account-workspace-error.hbs +30 -0
  56. package/views/accounts/account.hbs +9 -4
  57. package/views/accounts/edit.hbs +11 -2
  58. package/views/internals/index.hbs +1 -1
  59. package/views/partials/gmail_api_scopes.hbs +16 -0
  60. package/views/partials/oauth_form.hbs +67 -94
  61. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  62. package/views/partials/scope_info.hbs +14 -23
  63. package/workers/api.js +62 -27
  64. package/workers/imap.js +6 -3
  65. package/workers/submit.js +2 -5
@@ -44,8 +44,9 @@ function recordTokenMetric(status, provider, statusCode) {
44
44
  }
45
45
 
46
46
  const { OutlookOauth, outlookScopes } = require('./oauth/outlook');
47
- const { GmailOauth, GMAIL_SCOPES, parseExternalAccountConfig } = require('./oauth/gmail');
47
+ const { GmailOauth, GMAIL_SCOPES, GMAIL_PROVIDERS, parseExternalAccountConfig } = require('./oauth/gmail');
48
48
  const { ExternalAccountSigner } = require('./oauth/external-account-signer');
49
+ const { formatExtraScopes } = require('./oauth/scope-list');
49
50
  const crypto = require('crypto');
50
51
  const { MailRuOauth, MAIL_RU_SCOPES } = require('./oauth/mail-ru');
51
52
 
@@ -121,7 +122,13 @@ function oauth2ProviderData(provider, selector) {
121
122
  name: 'OAuth2',
122
123
  provider,
123
124
  caseName,
124
- comment: OAUTH_PROVIDERS[provider] || caseName
125
+ comment: OAUTH_PROVIDERS[provider] || caseName,
126
+ // Whether this provider can reach Gmail over the HTTP API instead of IMAP, which is what
127
+ // `baseScopes: 'api'` selects. True of both Gmail providers: isApiBasedApp() keys on that
128
+ // field and not on the provider, so a service account delegated gmail.modify is as API-based
129
+ // as an interactive app. The form guards the controls that only make sense in that mode - the
130
+ // scope presets, the Pub/Sub service account - on this rather than on one provider name.
131
+ gmailApi: GMAIL_PROVIDERS.has(provider)
125
132
  };
126
133
 
127
134
  switch (provider) {
@@ -220,50 +227,6 @@ function oauth2ProviderData(provider, selector) {
220
227
  return providerData;
221
228
  }
222
229
 
223
- function formatExtraScopes(extraScopes, baseScopes, defaultScopesList, skipScopes, scopePrefix) {
224
- let defaultScopes;
225
-
226
- skipScopes = [].concat(skipScopes || []);
227
-
228
- if (Array.isArray(defaultScopesList)) {
229
- defaultScopes = defaultScopesList;
230
- } else {
231
- defaultScopes = (baseScopes && defaultScopesList[baseScopes]) || defaultScopesList.imap;
232
- }
233
-
234
- if (!extraScopes && !skipScopes.length) {
235
- return defaultScopes;
236
- }
237
-
238
- extraScopes = extraScopes || [];
239
-
240
- let extras = [];
241
- for (let extraScope of extraScopes) {
242
- if (defaultScopes.includes(extraScope) || (scopePrefix && defaultScopes.includes(`${scopePrefix}/${extraScope}`))) {
243
- // skip existing
244
- continue;
245
- }
246
- extras.push(extraScope);
247
- }
248
-
249
- let result = extras.length ? extras.concat(defaultScopes) : defaultScopes;
250
-
251
- if (skipScopes.length) {
252
- result = result.filter(
253
- scope =>
254
- !skipScopes.some(
255
- skipScope =>
256
- scope === skipScope ||
257
- scope === `https://outlook.office.com/${skipScope}` ||
258
- scope === `https://graph.microsoft.com/${skipScope}` ||
259
- scope === `https://www.googleapis.com/auth/${skipScope}`
260
- )
261
- );
262
- }
263
-
264
- return result;
265
- }
266
-
267
230
  class OAuth2AppsHandler {
268
231
  constructor(options) {
269
232
  this.options = options || {};
@@ -1918,7 +1881,13 @@ class OAuth2AppsHandler {
1918
1881
  }
1919
1882
  }
1920
1883
 
1921
- // gmailService uses JWT -> IMAP XOAUTH2, so it is NOT API-based even though it is a service-account provider.
1884
+ // Whether an app's accounts connect through a provider API rather than IMAP.
1885
+ //
1886
+ // Being a service-account provider does not decide it: a gmailService app with the default
1887
+ // `baseScopes: 'imap'` exchanges its JWT for an IMAP XOAUTH2 credential, which is why the provider
1888
+ // name alone is not on this list. `baseScopes: 'api'` is what makes one API-based, for gmailService as
1889
+ // much as for the interactive gmail app - the schema accepts it, verifyGmailService() probes the Gmail
1890
+ // API for exactly that combination, and these accounts get the Gmail API client.
1922
1891
  function isApiBasedApp(app) {
1923
1892
  return app && (app.baseScopes === 'api' || app.provider === 'outlookService');
1924
1893
  }
package/lib/outbox.js CHANGED
@@ -3,6 +3,7 @@
3
3
  const { submitQueue, redis } = require('./db');
4
4
  const { REDIS_PREFIX } = require('../lib/consts');
5
5
  const msgpack = require('./msgpack');
6
+ const { nextAttemptOfStoredJob } = require('./delivery-error');
6
7
 
7
8
  // Job reads and removals are issued in bounded batches. ioredis writes each command as it is
8
9
  // issued, so a batch costs one round trip rather than one per job, while the bound keeps an account
@@ -48,13 +49,7 @@ function decodeQueueEntry(entryBuf) {
48
49
  function formatQueueEntry(job) {
49
50
  let scheduled = job.timestamp + (Number(job.opts.delay) || 0);
50
51
 
51
- let backoffDelay = Number(job.opts.backoff && job.opts.backoff.delay) || 0;
52
- // attemptsMade already includes the failed attempt, so the retry delay is 2^(attemptsMade-1) * base
53
- let nextAttempt = job.attemptsMade ? Math.round(job.processedOn + Math.pow(2, job.attemptsMade - 1) * backoffDelay) : scheduled;
54
-
55
- if (job.opts.attempts <= job.attemptsMade) {
56
- nextAttempt = false;
57
- }
52
+ let nextAttempt = nextAttemptOfStoredJob(job, scheduled);
58
53
 
59
54
  return Object.assign(job.data, {
60
55
  created: new Date(Number(job.data.created || job.timestamp)).toISOString(),
@@ -1,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ const { readEnvValue } = require('./read-env-value');
4
+
3
5
  // Retention policies for BullMQ job entries.
4
6
  //
5
7
  // This module is deliberately dependency-free (no Redis, no settings) so it can be unit tested
@@ -17,8 +19,8 @@ const COMPLETED_JOB_RETENTION_AGE = 24 * 3600;
17
19
  // Both are overridable because the right bound depends on payload size: a `messageNew` webhook
18
20
  // carries up to `notifyTextSize` (2MB by default) of message text, and a receiver that is down
19
21
  // turns every event into a retained entry.
20
- const FAILED_JOB_RETENTION_AGE = Number(process.env.EENGINE_QUEUE_KEEP_FAILED_AGE) || 7 * 24 * 3600;
21
- const FAILED_JOB_RETENTION_COUNT = Number(process.env.EENGINE_QUEUE_KEEP_FAILED) || 500;
22
+ const FAILED_JOB_RETENTION_AGE = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILED_AGE')) || 7 * 24 * 3600;
23
+ const FAILED_JOB_RETENTION_COUNT = Number(readEnvValue('EENGINE_QUEUE_KEEP_FAILED')) || 500;
22
24
 
23
25
  /**
24
26
  * Builds the `removeOnComplete` / `removeOnFail` pair for a queue job.
@@ -7,11 +7,27 @@
7
7
  const Fs = require('fs');
8
8
  const logger = require('./logger');
9
9
 
10
+ // The keys that lib/db.js and lib/get-secret.js used to resolve through private copies of this
11
+ // function. Those copies stripped a single trailing newline and nothing else, so for a file carrying
12
+ // any other surrounding whitespace the value they produced is not the value this helper produces.
13
+ // EENGINE_SECRET is the one that matters: a different secret means every stored credential fails to
14
+ // decrypt, and nothing can repair it automatically, because the old value is the one the data was
15
+ // encrypted with and only the operator knows whether the whitespace belongs to it. So the difference
16
+ // is reported rather than guessed at.
17
+ //
18
+ // The list is closed, not a registry to extend: no other key ever had the old behavior, so warning
19
+ // about one would claim a change that never happened, and no future key can acquire it, because
20
+ // test/read-env-value-guardrail-test.js fails on any module that re-implements the file fallback.
21
+ // It can be deleted outright once upgrading from a release before 2.82.1 is no longer supported.
22
+ const LEGACY_UNTRIMMED_KEYS = new Set(['EENGINE_SECRET', 'EENGINE_REDIS', 'REDIS_URL']);
23
+
10
24
  /**
11
25
  * Reads an environment value, falling back to the contents of the `<KEY>_FILE` variable.
12
26
  *
13
27
  * The file form is how secrets are handed to containerized deployments; the resolved value is
14
- * written back into process.env so the file is read at most once.
28
+ * written back into process.env so the file is read at most once. Surrounding whitespace is trimmed,
29
+ * which is what makes `echo value > file` work, and line endings are normalized so a file written on
30
+ * Windows resolves to the same value as one written anywhere else.
15
31
  *
16
32
  * @param {string} key - Environment variable name
17
33
  * @returns {string|undefined} The value, or undefined when neither form is set
@@ -24,7 +40,22 @@ function readEnvValue(key) {
24
40
  if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
25
41
  try {
26
42
  // try to load from file
27
- process.env[key] = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8').replace(/\r?\n/g, '\n').trim();
43
+ const contents = Fs.readFileSync(process.env[`${key}_FILE`], 'utf-8');
44
+ const value = contents.replace(/\r?\n/g, '\n').trim();
45
+ process.env[key] = value;
46
+
47
+ // What the private copies in lib/db.js and lib/get-secret.js resolved the same file to.
48
+ // Neither the value nor the whitespace around it is logged: the key and the file are what
49
+ // the operator needs to find it, and the value is what the warning exists to protect.
50
+ const legacyValue = contents.replace(/\r?\n$/, '');
51
+ if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
52
+ logger.warn({
53
+ msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
54
+ key,
55
+ file: process.env[`${key}_FILE`]
56
+ });
57
+ }
58
+
28
59
  logger.trace({ msg: 'Loaded environment value from file', key, file: process.env[`${key}_FILE`] });
29
60
  } catch (err) {
30
61
  logger.error({ msg: 'Failed to load environment value from file', key, file: process.env[`${key}_FILE`], err });
package/lib/schemas.js CHANGED
@@ -32,7 +32,7 @@ function formBoolean() {
32
32
  return Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', '0', 0, '');
33
33
  }
34
34
  const config = require('@zone-eu/wild-config');
35
- const { getByteSize } = require('./tools');
35
+ const { getByteSize, readEnvValue } = require('./tools');
36
36
  const { COLLAPSE_CLASS, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
37
37
  const { locales } = require('./translations');
38
38
  const { OAUTH_PROVIDERS } = require('./oauth2-apps');
@@ -69,7 +69,9 @@ config.api = config.api || {
69
69
  };
70
70
 
71
71
  const DEFAULT_MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024;
72
- const MAX_ATTACHMENT_SIZE = getByteSize(process.env.EENGINE_MAX_SIZE || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
72
+ // readEnvValue() rather than process.env, so EENGINE_MAX_SIZE_FILE raises the schema's maximum and not
73
+ // only the listener limit that server.js and workers/api.js resolve the same variable for
74
+ const MAX_ATTACHMENT_SIZE = getByteSize(readEnvValue('EENGINE_MAX_SIZE') || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
73
75
 
74
76
  const accountIdSchema = Joi.string().empty('').trim().max(MAX_ACCOUNT_ID_LENGTH).example('user123').description('Unique identifier for the email account');
75
77
 
@@ -443,7 +445,7 @@ const settingsSchema = {
443
445
  .max(1024)
444
446
  .example('verysecret')
445
447
  .description('Password for SMTP authentication (null = disable authentication)'),
446
- smtpServerTLSEnabled: formBoolean().description('Enable TLS/STARTTLS support for the SMTP server'),
448
+ smtpServerTLSEnabled: formBoolean().description('Serve the SMTP submission server over implicit TLS. STARTTLS is never offered'),
447
449
 
448
450
  /* ────────────── TLS Certificates ────────────── */
449
451
 
@@ -607,7 +609,19 @@ const settingsSchema = {
607
609
 
608
610
  exportMaxMessages: Joi.number().integer().min(1).max(10000000).example(500000).description('Maximum number of messages per export (default: 500000)'),
609
611
 
610
- exportMaxSize: Joi.number().integer().min(1).example(10737418240).description('Maximum export file size in bytes (default: 10GB)')
612
+ exportMaxSize: Joi.number().integer().min(1).example(10737418240).description('Maximum export file size in bytes (default: 10GB)'),
613
+
614
+ exportMaxMessageSize: Joi.number()
615
+ .integer()
616
+ .min(1)
617
+ .example(52428800)
618
+ .description('Maximum size of a single message included in an export, in bytes. Larger messages are skipped (default: 50MB)'),
619
+
620
+ exportMaxAge: Joi.number()
621
+ .integer()
622
+ .min(60000)
623
+ .example(86400000)
624
+ .description('How long a finished export is kept before it is deleted, in milliseconds (default: 24 hours)')
611
625
  };
612
626
 
613
627
  const addressSchema = Joi.object({
@@ -618,7 +632,25 @@ const addressSchema = Joi.object({
618
632
  .label('EmailAddress');
619
633
 
620
634
  // generate a list of boolean values
621
- const settingsQuerySchema = Object.fromEntries(Object.keys(Object.assign({ eventTypes: true }, settingsSchema)).map(key => [key, apiBoolean().default(false)]));
635
+ /**
636
+ * Whether a setting is hidden from the published document, which is how a deprecated key stays
637
+ * accepted without being advertised. The one spelling of the check: lib/api-routes/settings-routes.js
638
+ * reads it too, to decide which settings the MCP tools offer.
639
+ *
640
+ * @param {String} key - a settingsSchema key
641
+ * @returns {Boolean}
642
+ */
643
+ const isHiddenSetting = key => !!settingsSchema[key] && (settingsSchema[key].describe().metas || []).some(meta => meta && meta.swaggerHidden);
644
+
645
+ // The selectors GET /v1/settings takes, one per setting. Built from a fresh apiBoolean(), so the
646
+ // hidden marker on the setting itself did not carry over and the document offered a query argument for
647
+ // every removed feature whose setting is still accepted (documentStoreEnabled and two others).
648
+ const settingsQuerySchema = Object.fromEntries(
649
+ Object.keys(Object.assign({ eventTypes: true }, settingsSchema)).map(key => {
650
+ const selector = apiBoolean().default(false);
651
+ return [key, isHiddenSetting(key) ? selector.meta({ swaggerHidden: true }) : selector];
652
+ })
653
+ );
622
654
 
623
655
  const imapSchema = {
624
656
  auth: Joi.object({
@@ -1311,7 +1343,9 @@ const lastErrorSchema = Joi.object({
1311
1343
  url: Joi.string().example('https://oauth2.googleapis.com/token').description('OAuth2 token endpoint URL').label('OAuthTokenUrl'),
1312
1344
  method: Joi.string().example('post').description('HTTP method used for the token request').label('OAuthTokenMethod'),
1313
1345
  grant: Joi.string()
1314
- .valid('refresh_token', 'authorization_code')
1346
+ // client_credentials is what an Outlook application-permission app requests, and the
1347
+ // enum did not admit it although getClientCredentialsToken() has always recorded it
1348
+ .valid('refresh_token', 'authorization_code', 'client_credentials')
1315
1349
  .example('refresh_token')
1316
1350
  .description('OAuth2 grant type being requested')
1317
1351
  .label('OAuthGrant'),
@@ -1343,6 +1377,16 @@ const lastErrorSchema = Joi.object({
1343
1377
  .example('AAABhaBPHscAAAAH')
1344
1378
  .description('Value of the authorization code or error code related to the failure')
1345
1379
  .label('OAuthTokenErrorCode'),
1380
+ // Set instead of `status` when the request never reached the endpoint, so there is no
1381
+ // response to report (fetchTokenRequest() in lib/oauth/token-fetch.js)
1382
+ error: Joi.string()
1383
+ .example('fetch failed')
1384
+ .description('Transport failure message, set when the token endpoint could not be reached at all')
1385
+ .label('OAuthTokenTransportError'),
1386
+ errorCode: Joi.string()
1387
+ .example('ECONNREFUSED')
1388
+ .description('Transport failure code, set when the token endpoint could not be reached at all')
1389
+ .label('OAuthTokenTransportErrorCode'),
1346
1390
  flag: Joi.object({
1347
1391
  message: Joi.string().example('Please verify the OAuth2 application credentials').description('Description of the application-level problem'),
1348
1392
  code: Joi.string().example('INVALID_CLIENT_SECRET').description('Machine-readable code of the application-level problem'),
@@ -2205,7 +2249,7 @@ const outboxEntrySchema = Joi.object({
2205
2249
  proxy: Joi.string().allow(null).example('socks5://proxy.example.com:1080').description('Proxy URL used for delivery, or null when no proxy is set'),
2206
2250
  localAddress: Joi.string().allow(null).example('198.51.100.24').description('Local IP address used for delivery, or null when not set'),
2207
2251
  idempotencyKey: Joi.string().allow(null).max(1024).example('submit-12345').description('Idempotency key provided when the message was submitted'),
2208
- useStructuredFormat: Joi.boolean().description('Whether delivery errors for this message are reported in a structured format'),
2252
+ useStructuredFormat: Joi.boolean().description('Whether this message is sent to MS Graph as structured JSON instead of raw MIME'),
2209
2253
 
2210
2254
  created: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('When this message was added to the queue'),
2211
2255
  scheduled: Joi.date().iso().example('2021-02-17T13:43:18.860Z').description('Scheduled delivery time'),
@@ -2235,16 +2279,18 @@ const outboxEntrySchema = Joi.object({
2235
2279
  error: Joi.object({
2236
2280
  message: Joi.string().example('Authentication failed').description('Error description'),
2237
2281
  code: Joi.string().example('EAUTH').description('Error code'),
2238
- statusCode: Joi.number().integer().example(502).description('SMTP response code'),
2239
- networkRouting: Joi.object()
2240
- .unknown()
2241
- .allow(null)
2242
- .example({ localAddress: '198.51.100.24', name: 'relay.example.com' })
2243
- .description('Network routing information for the failed delivery attempt')
2244
- .label('OutboxErrorNetworkRouting')
2282
+ statusCode: Joi.number().integer().example(502).description('SMTP response code')
2245
2283
  })
2246
2284
  .label('OutboxListProgressError')
2247
- .description('Error details (when status is "error")')
2285
+ .description('Error details (when status is "error")'),
2286
+ // The submit worker writes this beside `error`, not inside it (workers/submit.js). It was
2287
+ // declared one level deeper here, so a client reading the documented location found nothing
2288
+ networkRouting: Joi.object()
2289
+ .unknown()
2290
+ .allow(null)
2291
+ .example({ localAddress: '198.51.100.24', name: 'relay.example.com' })
2292
+ .description('Network routing information for the failed delivery attempt (when status is "error")')
2293
+ .label('OutboxErrorNetworkRouting')
2248
2294
  }).label('OutboxEntryProgress')
2249
2295
  }).label('OutboxEntry');
2250
2296
 
@@ -2603,6 +2649,7 @@ module.exports = {
2603
2649
  accountSchemas,
2604
2650
  addressSchema,
2605
2651
  settingsQuerySchema,
2652
+ isHiddenSetting,
2606
2653
  imapSchema,
2607
2654
  smtpSchema,
2608
2655
  oauth2Schema,
@@ -24,6 +24,7 @@ const msgpack = require('./msgpack');
24
24
  const settings = require('./settings');
25
25
  const { REDIS_PREFIX, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
26
26
  const { extractMultiError } = require('./redis-operations');
27
+ const { readEnvValue } = require('./read-env-value');
27
28
 
28
29
  // Both overrides below are whole counts that have to be at least 1, and anything else falls back to
29
30
  // the default rather than being clamped towards it - "0" is not a request for the smallest possible
@@ -42,12 +43,12 @@ function positiveInt(value, fallback) {
42
43
  // per token, so a thousand active tokens cost about 170MB - entries carrying a maximum-length
43
44
  // account run some three times that. Raise it against those figures, and against the fact that a log
44
45
  // of who read whose mail carries the sensitivity of the mail itself.
45
- const LOG_ENTRIES = positiveInt(process.env.EENGINE_TOKEN_LOG_ENTRIES, 1000);
46
+ const LOG_ENTRIES = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_ENTRIES'), 1000);
46
47
 
47
48
  // How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
48
49
  // how long a log outlives the credential's activity rather than how long each entry lives - which is
49
50
  // the useful bound, because a token nobody has used is a log nobody needs.
50
- const LOG_AGE = positiveInt(process.env.EENGINE_TOKEN_LOG_AGE, 7 * 24 * 3600);
51
+ const LOG_AGE = positiveInt(readEnvValue('EENGINE_TOKEN_LOG_AGE'), 7 * 24 * 3600);
51
52
 
52
53
  // The largest page the log route will serve. Deliberately not the retention cap: one bounds a single
53
54
  // response, the other bounds stored data, and while they were the same constant raising retention
package/lib/tools.js CHANGED
@@ -708,7 +708,7 @@ module.exports = {
708
708
  * notifyTextSize / maxBytes cap is silently ignored on API accounts.
709
709
  * Mutates the passed object; only the "plain" and "html" keys are touched,
710
710
  * so an id reference or a flag riding on the same object is never clipped.
711
- * For byte-exact UTF-8 truncation see truncateToBytes in lib/mcp/tools.js,
711
+ * For byte-exact UTF-8 truncation see capText in lib/mcp/tools.js,
712
712
  * a different contract that is kept separate on purpose.
713
713
  * @param {Object} textContents Object carrying plain and/or html strings
714
714
  * @param {Number} maxBytes Size limit per text type, falsy means no limit
@@ -18,6 +18,8 @@ const getSecret = require('../get-secret');
18
18
  const capa = require('../capa');
19
19
  const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../account');
20
20
  const { formatGmailWatch } = require('../account/account-state');
21
+ const { SPECIAL_USE_PATH_FIELDS } = require('./special-use-paths');
22
+
21
23
  const { Gateway } = require('../gateway');
22
24
  const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
23
25
  const { atomicIncrement } = require('../redis-operations');
@@ -1636,6 +1638,7 @@ function init(args) {
1636
1638
 
1637
1639
  menuAccounts: true,
1638
1640
  account: accountData,
1641
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
1639
1642
  accountAlert,
1640
1643
  accountParked: !!disabledByAuthFailureAt,
1641
1644
  logs: logInfo,
@@ -2141,6 +2144,7 @@ function init(args) {
2141
2144
 
2142
2145
  menuAccounts: true,
2143
2146
  account: request.params.account,
2147
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
2144
2148
  values,
2145
2149
  availablePaths: JSON.stringify(mailboxes.map(entry => entry.path)),
2146
2150
 
@@ -2220,12 +2224,33 @@ function init(args) {
2220
2224
 
2221
2225
  let updateKeys = {};
2222
2226
 
2223
- for (let key of ['host', 'port', 'disabled', 'sentMailPath']) {
2227
+ for (let key of ['host', 'port', 'disabled']) {
2224
2228
  if (`imap_${key}` in request.payload) {
2225
2229
  updateKeys[key] = request.payload[`imap_${key}`];
2226
2230
  }
2227
2231
  }
2228
2232
 
2233
+ // The special-use folder overrides. An empty input means "no override" and has to
2234
+ // be written as null to unset one, while a field the form never showed must not be
2235
+ // written at all: these inputs live inside the IMAP section, which is hidden for an
2236
+ // account whose IMAP the operator switched off. The schema therefore allows the
2237
+ // empty string instead of defaulting to null - a default is inserted by joi for
2238
+ // every key the browser did not send, which made the presence check below always
2239
+ // true, so an unrelated save (a rename, a new webhook URL) wiped every override set
2240
+ // over PUT /v1/account/{account}. Same presence test imap_auth_user relies on.
2241
+ for (const field of SPECIAL_USE_PATH_FIELDS) {
2242
+ const payloadKey = `imap_${field.key}`;
2243
+ if (!(payloadKey in request.payload)) {
2244
+ continue;
2245
+ }
2246
+ const value = request.payload[payloadKey] || null;
2247
+ // Written only when the effective value changes, like the TLS flags below: an
2248
+ // untouched save must not add keys, because any imap diff forces a reconnect
2249
+ if (value !== ((oldData.imap && oldData.imap[field.key]) || null)) {
2250
+ updateKeys[field.key] = value;
2251
+ }
2252
+ }
2253
+
2229
2254
  if ('imap_auth_user' in request.payload) {
2230
2255
  let imapAuth = Object.assign((oldData.imap && oldData.imap.auth) || {}, { user: request.payload.imap_auth_user });
2231
2256
  if (request.payload.imap_auth_pass) {
@@ -2304,6 +2329,7 @@ function init(args) {
2304
2329
 
2305
2330
  menuAccounts: true,
2306
2331
  account: request.params.account,
2332
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
2307
2333
  // re-render the form from the submitted payload (the field names
2308
2334
  // match the template values); without this the form comes back
2309
2335
  // blank and the IMAP/SMTP cards disappear entirely
@@ -2361,6 +2387,7 @@ function init(args) {
2361
2387
 
2362
2388
  menuAccounts: true,
2363
2389
  account: request.params.account,
2390
+ specialUsePathFields: SPECIAL_USE_PATH_FIELDS,
2364
2391
  errors,
2365
2392
  // re-render the form from the (raw, unvalidated) submitted
2366
2393
  // payload so the entered values and the IMAP/SMTP cards
@@ -2422,12 +2449,18 @@ function init(args) {
2422
2449
 
2423
2450
  imap_resyncDelay: Joi.number().integer().empty(''),
2424
2451
 
2425
- imap_sentMailPath: Joi.string()
2426
- .empty('')
2427
- .default(null)
2428
- .max(1024)
2429
- .example('Sent Mail')
2430
- .description("Upload sent message to this folder. By default the account's Sent Mail folder is used. Leave empty to unset."),
2452
+ // allow('') rather than empty('').default(null): see the write loop above, where the
2453
+ // presence of the key is what says the form showed the field at all
2454
+ ...Object.fromEntries(
2455
+ SPECIAL_USE_PATH_FIELDS.map(field => [
2456
+ `imap_${field.key}`,
2457
+ Joi.string()
2458
+ .allow('', null)
2459
+ .max(1024)
2460
+ .example(field.label)
2461
+ .description(`${field.description} Leave empty to use the folder EmailEngine detects.`)
2462
+ ])
2463
+ ),
2431
2464
 
2432
2465
  webhooks: Joi.string()
2433
2466
  .uri({
@@ -17,6 +17,7 @@ const getSecret = require('../get-secret');
17
17
  const { Account } = require('../account');
18
18
  const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
19
19
  const { verifyOAuth2App } = require('../oauth/verify-app');
20
+ const { isSendOnlyGmailApp } = require('../oauth/scope-checker');
20
21
  const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema, formBoolean } = require('../schemas');
21
22
  const { throwAsBoom, adminUrl, submittedValues, windowedPageLinks } = require('./route-helpers');
22
23
 
@@ -433,20 +434,8 @@ function init(args) {
433
434
  disabledScopes.Gmail_Modify = true;
434
435
  }
435
436
 
436
- // Detect send-only Gmail configuration
437
- let isSendOnlyGmail = false;
438
- if (app.provider === 'gmail' && app.baseScopes === 'api') {
439
- // Build scope list from extraScopes (short form or full URLs)
440
- const scopes = (app.extraScopes || []).map(scope => (scope.startsWith('https://') ? scope : `https://www.googleapis.com/auth/${scope}`));
441
-
442
- // Use Account class helper to check scopes - no need to create full Account instance
443
- const accountHelper = new Account({ redis, secret: await getSecret() });
444
- const { hasSendScope, hasReadScope } = accountHelper.checkAccountScopes('gmail', scopes);
445
-
446
- if (hasSendScope && !hasReadScope) {
447
- isSendOnlyGmail = true;
448
- }
449
- }
437
+ // Covers both Gmail providers: the mode is decided by baseScopes, not by the provider
438
+ let isSendOnlyGmail = isSendOnlyGmailApp(app);
450
439
 
451
440
  if (app.pubSubApp) {
452
441
  let pubSubApp = await oauth2Apps.get(app.pubSubApp);
@@ -350,33 +350,32 @@ function jsonErrorPayload(err) {
350
350
  return { success: false, error: err.code || 'Error', message: err.message };
351
351
  }
352
352
 
353
- // The "wrong account" page, shown when a setup link pinned to one address is completed as another.
354
- // Rendered from both arms of the hosted form - the OAuth2 callback in workers/api.js and the IMAP arm in
355
- // ./account-routes.js - which live in different workers, so the view name, the layout and the refusal
356
- // status are kept here rather than written out twice. Only `retryUrl` is arm-specific: the OAuth arm
357
- // sends the user back to the provider, the IMAP arm back to the form.
358
- //
359
- // 403 rather than the 200 that the sibling views/oauth-scope-error.hbs returns: this is a refused
360
- // request, the surrounding refusals in the same flow already answer 403, and both call sites are plain
361
- // form navigations, so the browser still renders the page.
362
- function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl }) {
353
+ // The refusal pages of the hosted setup flow, where the mailbox owner made a correctable choice and is
354
+ // given a way back (`retryUrl`) rather than being bounced to the calling application. Rendered from both
355
+ // arms of the form - the OAuth2 callback in workers/api.js and the IMAP arm in ./account-routes.js, in
356
+ // different workers - so the view name, the layout and the refusal status are decided here. 403 rather
357
+ // than the 200 that the sibling views/oauth-scope-error.hbs returns: these are refused requests, the
358
+ // surrounding refusals in the same flow already answer 403, and every call site is a plain form
359
+ // navigation, so the browser still renders the page.
360
+ function setupRefusalView(request, h, view, context) {
363
361
  return h
364
- .view(
365
- 'account-identity-error',
366
- {
367
- pageTitleFull: request.app.gt.gettext('Email Account Setup'),
368
- templateLocale: request.app.locale,
369
- expectedEmail,
370
- actualEmail,
371
- retryUrl
372
- },
373
- {
374
- layout: 'public'
375
- }
376
- )
362
+ .view(view, Object.assign({ pageTitleFull: request.app.gt.gettext('Email Account Setup'), templateLocale: request.app.locale }, context), {
363
+ layout: 'public'
364
+ })
377
365
  .code(403);
378
366
  }
379
367
 
368
+ // "Wrong account": a setup link pinned to one address was completed as another. Only `retryUrl` is
369
+ // arm-specific - the OAuth arm sends the user back to the provider, the IMAP arm back to the form.
370
+ function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl }) {
371
+ return setupRefusalView(request, h, 'account-identity-error', { expectedEmail, actualEmail, retryUrl });
372
+ }
373
+
374
+ // "Work account required": the application takes only Workspace accounts and a personal one signed in.
375
+ function workspaceErrorView(request, h, { actualEmail, retryUrl }) {
376
+ return setupRefusalView(request, h, 'account-workspace-error', { actualEmail, retryUrl });
377
+ }
378
+
380
379
  // View-model for the ui/pagination partial: prev/next URLs plus the numbered page links.
381
380
  // basePath is the URL path without a query string (leading slash optional, matching the
382
381
  // `new URL(path, base)` convention the route modules already use); data is a listing
@@ -605,6 +604,7 @@ module.exports = {
605
604
  accountPickerEntry,
606
605
  accountPickerSelection,
607
606
  identityErrorView,
607
+ workspaceErrorView,
608
608
  compiledFragments,
609
609
  closedAfterConnectMessage,
610
610
  accountStateLabel,
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ const { SPECIAL_USE_PATH_TYPES } = require('../consts');
4
+
5
+ // The words the admin UI shows for each special-use folder override. The TYPES are not re-listed
6
+ // here: SPECIAL_USE_PATH_TYPES in lib/consts.js is the contract the IMAP client reads (it turns the
7
+ // list into the specialUseHints it passes to LIST) and the account schemas declare a field per entry,
8
+ // so a type added there reaches the form with it rather than needing a second edit.
9
+ //
10
+ // Split out of ./account-routes.js, which is at its size budget, and because this is page copy rather
11
+ // than routing: the same shape as ./ai-options.js next to it.
12
+ const SPECIAL_USE_PATH_LABELS = {
13
+ sent: { label: 'Sent Mail', description: 'Store copies of sent emails in this folder.' },
14
+ drafts: { label: 'Drafts', description: 'Treat this folder as the Drafts folder.' },
15
+ junk: { label: 'Junk', description: 'Treat this folder as the Junk folder.' },
16
+ trash: { label: 'Trash', description: 'Treat this folder as the Trash folder, where deleted messages are moved.' },
17
+ archive: { label: 'Archive', description: 'Treat this folder as the Archive folder.' }
18
+ };
19
+
20
+ /**
21
+ * The override fields as the edit form and the account page consume them: the account field name, the
22
+ * form input id and the words to show, in the order the two templates render them.
23
+ *
24
+ * `{ type, key, inputId, label, description }` per entry. The form renders one input per entry from
25
+ * `inputId`, its joi schema is generated per entry, and the update loop writes `key` onto the account
26
+ * - so the four of them cannot drift. Only `sentMailPath` was ever offered on the form, which is how
27
+ * the other four came to be settable over PUT /v1/account/{account} alone.
28
+ */
29
+ const SPECIAL_USE_PATH_FIELDS = SPECIAL_USE_PATH_TYPES.map(type =>
30
+ Object.assign({ type, key: `${type}MailPath`, inputId: `imap_${type}MailPath` }, SPECIAL_USE_PATH_LABELS[type])
31
+ );
32
+
33
+ module.exports = { SPECIAL_USE_PATH_FIELDS, SPECIAL_USE_PATH_LABELS };
@@ -177,6 +177,11 @@ function resolveClientIp({ remoteAddress, forwardedFor, enableApiProxy, trustedP
177
177
  return remoteAddress;
178
178
  }
179
179
 
180
+ // Reverse-DNS suffixes of the scanners whose fetches must not count as a real open or click. No `g`
181
+ // flag: RegExp#test() advances lastIndex on a global regex, so a hoisted one would skip every other
182
+ // call - which is exactly how a shared instance of this would start letting scanner traffic through.
183
+ const SCANNER_HOSTNAME_PATTERN = /\bbarracuda\.com$|\bspfbl\.net$/i;
184
+
180
185
  /**
181
186
  * Detects if a request is from an automated scanner (Google, Barracuda, etc.)
182
187
  * @param {string} ip - IP address to check
@@ -213,23 +218,10 @@ async function detectAutomatedRequest(ip) {
213
218
  });
214
219
  }
215
220
 
216
- if (!hostnames || !hostnames.length) {
217
- return false;
218
- }
219
-
220
- const hostname = []
221
- .concat(hostnames || [])
222
- .shift()
223
- .toString()
224
- .trim()
225
- .toLowerCase();
226
-
227
- // Barracuda, spfbl
228
- if (/\bbarracuda\.com$|\bspfbl\.net$/gi.test(hostname)) {
229
- return true;
230
- }
231
-
232
- return false;
221
+ // Every PTR record, not just the first. An address is under no obligation to list the scanner's
222
+ // own name first, and this filter is the only thing keeping scanner fetches out of trackOpen and
223
+ // trackClick - reading one record of several reported them as real opens and clicks.
224
+ return [].concat(hostnames || []).some(entry => SCANNER_HOSTNAME_PATTERN.test(String(entry).trim().toLowerCase()));
233
225
  }
234
226
 
235
227
  /**