emailengine-app 2.79.6 → 2.79.8

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 (109) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +32 -0
  3. package/DOCKER_DEPLOYMENT.md +2 -0
  4. package/bin/emailengine.js +29 -13
  5. package/config/default.toml +13 -3
  6. package/data/google-crawlers.json +7 -1
  7. package/docker-compose.yml +12 -3
  8. package/install.sh +2 -0
  9. package/lib/api-routes/account-routes.js +14 -3
  10. package/lib/api-routes/mailbox-routes.js +4 -1
  11. package/lib/api-routes/message-routes.js +6 -5
  12. package/lib/api-routes/outbox-routes.js +7 -4
  13. package/lib/api-routes/settings-routes.js +34 -25
  14. package/lib/api-routes/stats-routes.js +8 -1
  15. package/lib/api-routes/submit-routes.js +2 -1
  16. package/lib/api-routes/template-routes.js +3 -2
  17. package/lib/bounce-detect.js +45 -0
  18. package/lib/consts.js +9 -3
  19. package/lib/egress-filter.js +39 -4
  20. package/lib/email-client/base-client.js +274 -24
  21. package/lib/email-client/gmail/gmail-api.js +15 -7
  22. package/lib/email-client/gmail-client.js +121 -64
  23. package/lib/email-client/imap/mailbox.js +18 -59
  24. package/lib/email-client/imap-client.js +53 -29
  25. package/lib/email-client/notification-handler.js +11 -2
  26. package/lib/email-client/outlook/graph-api.js +106 -90
  27. package/lib/email-client/outlook-client.js +222 -106
  28. package/lib/generate-text-preview.js +10 -5
  29. package/lib/headers-rewriter.js +1 -1
  30. package/lib/llm-pre-process.js +4 -1
  31. package/lib/mcp/json-schema.js +50 -2
  32. package/lib/outbox.js +22 -5
  33. package/lib/passkeys.js +39 -7
  34. package/lib/pre-process.js +4 -1
  35. package/lib/rewrite-text-nodes.js +12 -1
  36. package/lib/schemas.js +27 -5
  37. package/lib/settings.js +19 -1
  38. package/lib/sso.js +60 -7
  39. package/lib/submit-progress.js +29 -0
  40. package/lib/templates.js +11 -0
  41. package/lib/tools.js +115 -53
  42. package/lib/ui-routes/account-routes.js +79 -12
  43. package/lib/ui-routes/admin-config-routes.js +7 -21
  44. package/lib/ui-routes/admin-entities-routes.js +42 -12
  45. package/lib/ui-routes/auth-routes.js +242 -87
  46. package/lib/ui-routes/dashboard-routes.js +1 -1
  47. package/lib/ui-routes/internals-routes.js +2 -0
  48. package/lib/ui-routes/mcp-consent-routes.js +5 -2
  49. package/lib/ui-routes/network-config-routes.js +12 -3
  50. package/lib/ui-routes/oauth-config-routes.js +12 -1
  51. package/lib/ui-routes/route-helpers.js +41 -6
  52. package/lib/ui-routes/settings-page.js +10 -0
  53. package/lib/ui-routes/suppression-list-routes.js +16 -5
  54. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  55. package/lib/webhooks.js +14 -2
  56. package/package.json +17 -17
  57. package/sbom.json +1 -1
  58. package/server.js +63 -35
  59. package/static/css/flyonui.css +1 -1
  60. package/static/css/src/app.tailwind.css +55 -0
  61. package/static/js/app.js +4 -35
  62. package/static/js/passkey-register.js +50 -1
  63. package/static/js/public.js +128 -0
  64. package/static/js/ui.js +183 -6
  65. package/static/licenses.html +371 -770
  66. package/translations/messages.pot +66 -66
  67. package/views/account/passkeys.hbs +141 -0
  68. package/views/account/password.hbs +11 -0
  69. package/views/account/security.hbs +318 -326
  70. package/views/accounts/account.hbs +90 -115
  71. package/views/accounts/register/imap-server.hbs +18 -12
  72. package/views/config/ai.hbs +2 -0
  73. package/views/config/branding.hbs +2 -0
  74. package/views/config/document-store/index.hbs +6 -6
  75. package/views/config/email-processing.hbs +2 -0
  76. package/views/config/imap-proxy.hbs +2 -0
  77. package/views/config/license.hbs +4 -1
  78. package/views/config/logging.hbs +3 -1
  79. package/views/config/mcp.hbs +2 -0
  80. package/views/config/network.hbs +2 -0
  81. package/views/config/oauth/app.hbs +3 -3
  82. package/views/config/oauth/edit.hbs +1 -1
  83. package/views/config/oauth/new.hbs +1 -1
  84. package/views/config/security.hbs +2 -0
  85. package/views/config/service.hbs +2 -0
  86. package/views/config/smtp.hbs +2 -0
  87. package/views/config/webhooks.hbs +9 -6
  88. package/views/error.hbs +6 -0
  89. package/views/layout/app.hbs +6 -3
  90. package/views/layout/login.hbs +1 -1
  91. package/views/layout/prompt.hbs +1 -1
  92. package/views/layout/public.hbs +1 -1
  93. package/views/legal.hbs +1 -1
  94. package/views/partials/filter_editor_js.hbs +1 -1
  95. package/views/partials/gateway_js.hbs +7 -6
  96. package/views/partials/oauth_form.hbs +5 -5
  97. package/views/partials/ui/btn.hbs +8 -2
  98. package/views/partials/ui/confirm-modal.hbs +2 -3
  99. package/views/partials/ui/empty-state.hbs +25 -0
  100. package/views/partials/ui/env-managed-alert.hbs +19 -0
  101. package/views/partials/webhook_form.hbs +1 -1
  102. package/views/partials/webhooks_editor_functions.hbs +5 -5
  103. package/views/unsubscribe.hbs +6 -0
  104. package/workers/api.js +193 -81
  105. package/workers/imap.js +32 -3
  106. package/workers/smtp.js +7 -0
  107. package/workers/submit.js +25 -1
  108. package/workers/webhooks.js +13 -17
  109. package/lib/reconnection-manager.js +0 -106
@@ -19,10 +19,58 @@
19
19
  // one field every client shows.
20
20
  //
21
21
  // Everything else the converter emits (properties, required, enum, anyOf, minimum/maxLength and
22
- // friends) is already valid 2020-12.
22
+ // friends) is already valid 2020-12, with one exception: the converter folds joi `.valid()` and
23
+ // `.allow()` into a single `enum`, so `.allow(false)` beside a string or object type arrives as
24
+ // `enum: [false]`. OpenAPI readers treat that as documentation, but in JSON Schema `enum` is
25
+ // exclusive - `{type: "object", enum: [false]}` is a schema nothing satisfies, so a validating
26
+ // client refuses every valid call and a model reading it is told the only accepted value is
27
+ // `false`. splitSentinels() moves such members out into `const` branches beside the schema proper.
23
28
 
24
29
  const { SchemaConverter } = require('../openapi/joi-schema');
25
30
 
31
+ // Keywords that describe a schema rather than constrain it. They stay on the outer node when a
32
+ // schema is split into anyOf branches, so every client still finds them in the usual place.
33
+ const ANNOTATION_KEYS = new Set(['title', 'description', 'examples', 'default', 'deprecated']);
34
+
35
+ function isInstanceOfType(value, types) {
36
+ const valueType = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
37
+ return types.some(type => type === valueType || (type === 'integer' && valueType === 'number' && Number.isInteger(value)));
38
+ }
39
+
40
+ // An enum member that cannot be an instance of the declared type is a joi `.allow()` sentinel
41
+ // (`false` clearing a block on an update, `false`/`null` for "not set"), not part of the value
42
+ // domain. It leaves the enum and becomes a `const` branch. What remains was a real `.valid()`
43
+ // list and stays as the enum; when only `null` remains (`.allow(false, null)` on a plain string)
44
+ // the type array already admits it and the enum goes.
45
+ function splitSentinels(schema) {
46
+ if (!Array.isArray(schema.enum) || !schema.type) {
47
+ return schema;
48
+ }
49
+
50
+ const types = [].concat(schema.type);
51
+ const sentinels = schema.enum.filter(value => !isInstanceOfType(value, types));
52
+ if (!sentinels.length) {
53
+ return schema;
54
+ }
55
+
56
+ const result = {};
57
+ const branch = {};
58
+ for (const [key, value] of Object.entries(schema)) {
59
+ (ANNOTATION_KEYS.has(key) ? result : branch)[key] = value;
60
+ }
61
+
62
+ const values = schema.enum.filter(value => isInstanceOfType(value, types));
63
+ if (values.some(value => value !== null)) {
64
+ branch.enum = values;
65
+ } else {
66
+ delete branch.enum;
67
+ }
68
+
69
+ result.anyOf = [branch].concat(sentinels.map(value => ({ const: value })));
70
+
71
+ return result;
72
+ }
73
+
26
74
  function toJsonSchema(node) {
27
75
  if (Array.isArray(node)) {
28
76
  return node.map(entry => toJsonSchema(entry));
@@ -98,7 +146,7 @@ function toJsonSchema(node) {
98
146
  }
99
147
  }
100
148
 
101
- return result;
149
+ return splitSentinels(result);
102
150
  }
103
151
 
104
152
  /**
package/lib/outbox.js CHANGED
@@ -133,18 +133,35 @@ async function list(options) {
133
133
  };
134
134
  }
135
135
 
136
+ // Resolves to { deleted } - with `locked: true` when the message could not be removed because a
137
+ // submit worker is delivering it right now. That is the one refusal a caller can act on (retry
138
+ // once the attempt is over), so it is reported rather than folded into a plain false; a failure to
139
+ // remove for any other reason is thrown.
136
140
  async function del(options) {
137
141
  options = options || {};
138
142
 
139
143
  let logger = options.logger;
140
144
 
141
145
  if (!options.queueId) {
142
- return false;
146
+ return { deleted: false };
143
147
  }
144
148
 
145
149
  let job = await submitQueue.getJob(options.queueId);
146
150
  if (!job) {
147
- return false;
151
+ return { deleted: false };
152
+ }
153
+
154
+ // BullMQ refuses to remove a job a worker holds the lock on, and for the submit queue that is
155
+ // a message in the middle of a delivery attempt. Checked before touching the content: the
156
+ // attempt in flight still needs it, and removing it here would not stop the attempt anyway.
157
+ if (await job.isActive()) {
158
+ logger.info({
159
+ msg: 'Queued message is being delivered, not removed',
160
+ account: job.data.account,
161
+ queueId: job.data.queueId,
162
+ messageId: job.data.messageId
163
+ });
164
+ return { deleted: false, locked: true };
148
165
  }
149
166
 
150
167
  // Delete message content
@@ -158,13 +175,13 @@ async function del(options) {
158
175
  // Delete job entry
159
176
  try {
160
177
  await job.remove();
161
- logger.info({ msg: 'Removed queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId });
162
- return true;
163
178
  } catch (err) {
164
179
  logger.error({ msg: 'Failed to remove queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId, err });
180
+ throw err;
165
181
  }
166
182
 
167
- return false;
183
+ logger.info({ msg: 'Removed queue entry', account: job.data.account, queueId: job.data.queueId, messageId: job.data.messageId });
184
+ return { deleted: true };
168
185
  }
169
186
 
170
187
  async function get(options) {
package/lib/passkeys.js CHANGED
@@ -7,6 +7,29 @@ const { REDIS_PREFIX, WEBAUTHN_CHALLENGE_TTL } = require('./consts');
7
7
 
8
8
  const KEY_PREFIX = `${REDIS_PREFIX}webauthn:`;
9
9
 
10
+ // A WebAuthn challenge is a bare nonce, and nothing in the signed response the authenticator
11
+ // returns says which ceremony the server minted it for - that binding is the server's job.
12
+ // Registration is gated behind a password confirmation and sign-in deliberately is not, so while
13
+ // both ceremonies drew from one keyspace a nonce minted by the unauthenticated sign-in endpoint
14
+ // could be spent completing a registration, skipping the gate entirely. The purpose is part of the
15
+ // key, so each ceremony can only consume what it minted.
16
+ const CHALLENGE_REGISTER = 'register';
17
+ const CHALLENGE_AUTH = 'auth';
18
+ const CHALLENGE_PURPOSES = new Set([CHALLENGE_REGISTER, CHALLENGE_AUTH]);
19
+
20
+ function assertPurpose(purpose) {
21
+ if (!CHALLENGE_PURPOSES.has(purpose)) {
22
+ // Every caller passes one of the exported constants, so this is a programming error and
23
+ // must not degrade into an unnamespaced key that would restore the bypass
24
+ throw new Error(`Unknown WebAuthn challenge purpose: ${purpose}`);
25
+ }
26
+ }
27
+
28
+ function challengeKey(challengeId, purpose) {
29
+ assertPurpose(purpose);
30
+ return `${KEY_PREFIX}challenge:${purpose}:${challengeId}`;
31
+ }
32
+
10
33
  // Passkey data does not require encryption at rest. Unlike TOTP seeds or OAuth
11
34
  // client secrets (which are shared secrets), passkeys use public-key cryptography.
12
35
  // Only the public key is stored here -- the private key never leaves the
@@ -90,6 +113,9 @@ function credentialKeys(id, user) {
90
113
  }
91
114
 
92
115
  module.exports = {
116
+ CHALLENGE_REGISTER,
117
+ CHALLENGE_AUTH,
118
+
93
119
  async getRpConfig() {
94
120
  let serviceUrl = await settings.get('serviceUrl');
95
121
  if (!serviceUrl) {
@@ -99,18 +125,20 @@ module.exports = {
99
125
  return { rpId: url.hostname, origin: url.origin };
100
126
  },
101
127
 
102
- async storeChallenge(challenge) {
128
+ async storeChallenge(challenge, purpose) {
103
129
  let challengeId = crypto.randomBytes(32).toString('hex');
104
- await redis.set(`${KEY_PREFIX}challenge:${challengeId}`, challenge, 'EX', WEBAUTHN_CHALLENGE_TTL);
130
+ await redis.set(challengeKey(challengeId, purpose), challenge, 'EX', WEBAUTHN_CHALLENGE_TTL);
105
131
  return challengeId;
106
132
  },
107
133
 
108
- async consumeChallenge(challengeId) {
134
+ async consumeChallenge(challengeId, purpose) {
135
+ // Before the id check, so a caller that forgot the purpose trips the guardrail whatever
136
+ // it passed as an id rather than getting a plausible null back
137
+ assertPurpose(purpose);
109
138
  if (!challengeId || typeof challengeId !== 'string') {
110
139
  return null;
111
140
  }
112
- let key = `${KEY_PREFIX}challenge:${challengeId}`;
113
- let challenge = await redis.getdel(key);
141
+ let challenge = await redis.getdel(challengeKey(challengeId, purpose));
114
142
  return challenge || null;
115
143
  },
116
144
 
@@ -142,8 +170,12 @@ module.exports = {
142
170
  return hydrateCredential(data);
143
171
  },
144
172
 
145
- async updateCounter(credentialId, newCounter) {
146
- await redis.hset(`${KEY_PREFIX}cred:${credentialId}`, 'counter', String(newCounter));
173
+ // Called after a verified assertion, so it stamps the sign-in time alongside the
174
+ // signature counter. The stamp is what the security page shows as "Last used";
175
+ // credentials registered before it existed carry no field and render as unknown
176
+ // rather than as never used.
177
+ async recordAuthentication(credentialId, newCounter) {
178
+ await redis.hset(`${KEY_PREFIX}cred:${credentialId}`, 'counter', String(newCounter), 'lastUsedAt', new Date().toISOString());
147
179
  },
148
180
 
149
181
  async listCredentials(user) {
@@ -93,7 +93,10 @@ class PreProcessHandler {
93
93
  v = Number(v) || 0;
94
94
  if (v !== this.handlerCacheV) {
95
95
  // changes detected
96
- this.handlerCache = this.getHandler();
96
+ this.handlerCache = await this.getHandler();
97
+ // mark the cache as current only after a successful rebuild, so a failure above
98
+ // leaves it stale and the next call retries
99
+ this.handlerCacheV = v;
97
100
  }
98
101
  return this.handlerCache;
99
102
  }
@@ -76,6 +76,9 @@ function rewriteTextNodes(source, options) {
76
76
 
77
77
  const splitter = new Splitter();
78
78
  const joiner = new Joiner();
79
+ // The tail of the pipe chain. Every failure inside the chain is routed to its 'error'
80
+ // handler below, which rejects the returned promise.
81
+ const newlines = new LeWindows();
79
82
 
80
83
  // create a Rewriter for text/html
81
84
  let rewriter = new Rewriter(node => {
@@ -122,6 +125,15 @@ function rewriteTextNodes(source, options) {
122
125
  }
123
126
  }
124
127
 
128
+ // Nothing else listens for errors on the node decoder, so without this a decoder
129
+ // failure would be an uncaughtException that takes the worker with it. None of the
130
+ // decoders used here has a failure path today, so this is a guard against the next
131
+ // dependency update giving one of them one, not a fix for a reachable case. Routed
132
+ // to the tail so it rejects the same way any other pipeline failure does.
133
+ decoder.on('error', err => {
134
+ newlines.emit('error', err);
135
+ });
136
+
125
137
  decoder.on('readable', () => {
126
138
  let chunk;
127
139
  while ((chunk = decoder.read()) !== null) {
@@ -173,7 +185,6 @@ function rewriteTextNodes(source, options) {
173
185
  });
174
186
 
175
187
  // set up pipe chain
176
- let newlines = new LeWindows();
177
188
  splitter.pipe(rewriter).pipe(joiner).pipe(newlines);
178
189
 
179
190
  joiner.on('error', err => {
package/lib/schemas.js CHANGED
@@ -43,6 +43,11 @@ const MAX_ATTACHMENT_SIZE = getByteSize(process.env.EENGINE_MAX_SIZE || config.a
43
43
 
44
44
  const accountIdSchema = Joi.string().empty('').trim().max(MAX_ACCOUNT_ID_LENGTH).example('user123').description('Unique identifier for the email account');
45
45
 
46
+ // The message id path parameter, shared by every /message/{message} route so they all refuse the
47
+ // same input: EmailEngine ids are base64url, and an id that is not decodes to garbage the client
48
+ // code then fails on, which used to be a 500 on the routes that accepted any string
49
+ const messageIdSchema = Joi.string().base64({ paddingRequired: false, urlSafe: true }).max(256).example('AAAAAQAACnA').description('Message ID');
50
+
46
51
  // Suppression list identifier, shared by the Blocklists API and the suppression-list admin UI
47
52
  // so the two surfaces cannot drift on what a valid list ID is
48
53
  const blocklistListIdSchema = Joi.string()
@@ -2351,7 +2356,9 @@ const headerTimeoutSchema = Joi.number()
2351
2356
  .max(2 * 3600 * 1000)
2352
2357
  .optional()
2353
2358
  .example(30000)
2354
- .description('Request timeout in milliseconds (overrides EENGINE_TIMEOUT environment variable)')
2359
+ .description(
2360
+ 'Request timeout in milliseconds. Raises the command timeout above the EENGINE_TIMEOUT default for a long-running request; a value below the default has no effect'
2361
+ )
2355
2362
  .label('X-EE-Timeout');
2356
2363
 
2357
2364
  // Headers every API route accepts, applied as a server-wide route default in workers/api.js rather
@@ -2488,17 +2495,24 @@ const errorResponseSchemas = {
2488
2495
  messageExample: 'Invalid input',
2489
2496
  label: 'ValidationErrorResponse',
2490
2497
  title: 'Validation error',
2491
- description: 'Invalid input - the path parameters, query arguments, or request payload did not pass validation',
2498
+ description:
2499
+ 'Invalid input - the path parameters, query arguments, or request payload did not pass validation. Also returned when the email server refused the request, in which case the response carries a code and the server response instead of a field list',
2492
2500
  fields: {
2493
2501
  fields: Joi.array()
2494
2502
  .items(
2495
2503
  Joi.object({
2496
2504
  message: Joi.string().example('"pageSize" must be less than or equal to 1000').description('Description of the validation failure'),
2497
- key: Joi.string().example('pageSize').description('Name of the input field that failed validation')
2505
+ key: Joi.string().example('pageSize').description('Name of the input field that failed validation'),
2506
+ path: Joi.string()
2507
+ .example('to.0.address')
2508
+ .description('Full path of the input field that failed validation. Same as key for a top-level field, dotted for a nested one')
2498
2509
  }).label('ValidationErrorField')
2499
2510
  )
2500
2511
  .description('List of input fields that failed validation')
2501
- .label('ValidationErrorFields')
2512
+ .label('ValidationErrorFields'),
2513
+ code: Joi.string().example('MailboxNotFound').description('Machine-readable error code, if available'),
2514
+ details: Joi.any().description('Additional error details, if available. The email server response for a refused mailbox operation'),
2515
+ info: Joi.any().description('Additional error details, if available. The email server response for a refused message operation')
2502
2516
  }
2503
2517
  }),
2504
2518
 
@@ -2517,7 +2531,14 @@ const errorResponseSchemas = {
2517
2531
  messageExample: 'Unauthorized scope',
2518
2532
  label: 'AccessDeniedErrorResponse',
2519
2533
  title: 'Access denied error',
2520
- description: 'Access denied - the access token does not grant permission for this operation (token scope, account, or IP address restriction)'
2534
+ description: 'Access denied - the access token does not grant permission for this operation (token scope, account, or IP address restriction)',
2535
+ fields: {
2536
+ requestedScope: Joi.string().example('api').description('The scope the operation needed, when the token does not carry it'),
2537
+ requiredPermission: Joi.string()
2538
+ .example('messages:write')
2539
+ .description('The permission grant the operation needed, when the token permissions do not include it'),
2540
+ remoteAddress: Joi.string().example('203.0.113.1').description('The client IP address, when the token is restricted to other addresses')
2541
+ }
2521
2542
  }),
2522
2543
 
2523
2544
  404: errorResponseEntry({
@@ -2642,6 +2663,7 @@ module.exports = {
2642
2663
  tokenRestrictionsSchema,
2643
2664
  tokenPermissionsSchema,
2644
2665
  accountIdSchema,
2666
+ messageIdSchema,
2645
2667
  blocklistListIdSchema,
2646
2668
  oauth2ProviderSchema,
2647
2669
  accountTypeSchema,
package/lib/settings.js CHANGED
@@ -10,7 +10,9 @@ const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
10
10
 
11
11
  config.service = config.service || {};
12
12
 
13
- const ENCRYPTED_KEYS = [
13
+ // Values that are secrets in their entirety. Encrypted at rest, and the settings API returns a
14
+ // boolean marker in their place rather than the value.
15
+ const SECRET_KEYS = [
14
16
  // The gmail*/outlook*/mailRu* secrets belong to the retired settings-based OAuth2
15
17
  // configuration. They stay listed so oauth2Apps.migrateLegacyApps() can still decrypt
16
18
  // stored values through settings.get() before moving them into the app registry.
@@ -28,6 +30,16 @@ const ENCRYPTED_KEYS = [
28
30
  'totpSeed'
29
31
  ];
30
32
 
33
+ // Values that carry a secret without being one: URLs that may embed `user:pass@` credentials
34
+ // (a SOCKS or HTTP proxy, a webhook target, a Sentry DSN with its key) and the custom webhook
35
+ // headers, whose example is an Authorization bearer. Encrypted at rest like the secrets, but the
36
+ // API reads them back with only the credential part masked (route-helpers maskSecrets()), so they
37
+ // are not in the list it turns into booleans. Encryption applies to the JSON encoding, so the
38
+ // header list being an array rather than a string makes no difference.
39
+ const CREDENTIAL_BEARING_KEYS = ['webhooks', 'webhooksCustomHeaders', 'proxyUrl', 'httpProxyUrl', 'sentryDsn'];
40
+
41
+ const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
42
+
31
43
  // getValue() runs on an uncached read path - settings.get() is called several times per synced
32
44
  // message and once per webhook delivery - and a decrypt/parse failure is permanent rather than
33
45
  // transient (a rotated EENGINE_SECRET, a corrupt stored value). Reporting every occurrence would
@@ -36,8 +48,14 @@ const ENCRYPTED_KEYS = [
36
48
  const reportedParseFailures = new Set();
37
49
 
38
50
  module.exports = {
51
+ // Everything encrypted at rest: what `emailengine encrypt` re-encrypts on a secret rotation
39
52
  encryptedKeys: ENCRYPTED_KEYS,
40
53
 
54
+ // The subset the settings API returns as a boolean marker (lib/api-routes/settings-routes.js).
55
+ // The credential-bearing URLs are encrypted too but are returned with just the credentials
56
+ // masked, so a consumer that hides values has to read this list, not encryptedKeys.
57
+ secretKeys: SECRET_KEYS,
58
+
41
59
  /**
42
60
  * Whether admin authentication is configured for this instance.
43
61
  *
package/lib/sso.js CHANGED
@@ -35,6 +35,7 @@
35
35
  // dotted path (e.g. "realm_access.roles") for IdPs that nest it.
36
36
 
37
37
  const { fetch: fetchCmd } = require('undici');
38
+ const { backOff } = require('exponential-backoff');
38
39
  const { readEnvValue, httpAgent, getBoolean } = require('./tools');
39
40
  const packageData = require('../package.json');
40
41
 
@@ -67,6 +68,13 @@ const USE_OIDC_AUTH = !!(OIDC_ISSUER && OIDC_CLIENT_ID && OIDC_CLIENT_SECRET);
67
68
 
68
69
  const DISCOVERY_TIMEOUT = 10 * 1000;
69
70
 
71
+ // Backoff bounds for retryDiscovery(). Quick at first, because the common failure is
72
+ // an IdP that is merely slower to boot than we are (a shared host restarting both at
73
+ // once, where the IdP can be a minute behind), then doubling to one probe every five
74
+ // minutes so a genuine multi-hour outage costs almost nothing.
75
+ const DISCOVERY_RETRY_MIN = 5 * 1000;
76
+ const DISCOVERY_RETRY_MAX = 5 * 60 * 1000;
77
+
70
78
  // `openid` is what makes the request an OIDC request; `profile` and `email`
71
79
  // populate the userinfo claims mapped by mapUserinfoProfile().
72
80
  const DEFAULT_SCOPES = ['openid', 'profile', 'email'];
@@ -91,14 +99,24 @@ function parseScopes(scopeStr) {
91
99
  }
92
100
 
93
101
  // Parse OIDC_ALLOWED_USERS into a normalized list of allow-list entries. Entries
94
- // starting with "@" are treated as domain matches, everything else as an exact
95
- // email match. Matching is case-insensitive.
102
+ // containing "@" are exact email matches, unless the "@" comes first, which makes
103
+ // the entry a domain match. An entry with no "@" at all cannot be an email, so it
104
+ // is read as a domain too: as an exact-email rule it could never match, and a bare
105
+ // "example.com" would have locked every user out with a generic "not authorized".
106
+ // Matching is case-insensitive.
96
107
  function parseAllowList(str) {
97
108
  return (str || '')
98
109
  .split(',')
99
110
  .map(entry => entry.trim().toLowerCase())
100
111
  .filter(entry => entry)
101
- .map(entry => (entry.charAt(0) === '@' ? { type: 'domain', value: entry.slice(1) } : { type: 'email', value: entry }));
112
+ .map(entry => {
113
+ const at = entry.indexOf('@');
114
+ if (at > 0) {
115
+ return { type: 'email', value: entry };
116
+ }
117
+ return { type: 'domain', value: at === 0 ? entry.slice(1) : entry };
118
+ })
119
+ .filter(entry => entry.value);
102
120
  }
103
121
 
104
122
  // Normalize a single group name: coerce to string, trim, and strip leading slashes
@@ -259,10 +277,13 @@ function mapUserinfoProfile(userinfo, groupsClaim) {
259
277
  };
260
278
  }
261
279
 
262
- // Fetch and validate the discovery document for the configured issuer. Uses the
280
+ // Fetch and validate the discovery document for the configured issuer. Defaults to the
263
281
  // shared RetryAgent (transient DNS/socket retries) with a hard timeout so a
264
- // slow/unreachable IdP cannot stall API-worker startup indefinitely.
265
- async function fetchOidcDiscovery() {
282
+ // slow/unreachable IdP cannot stall API-worker startup indefinitely. Callers that
283
+ // retry on their own schedule pass a plain dispatcher instead - see retryDiscovery().
284
+ async function fetchOidcDiscovery(options) {
285
+ options = options || {};
286
+
266
287
  let url = getDiscoveryUrl(OIDC_ISSUER);
267
288
 
268
289
  let res = await fetchCmd(url, {
@@ -271,7 +292,7 @@ async function fetchOidcDiscovery() {
271
292
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`,
272
293
  Accept: 'application/json'
273
294
  },
274
- dispatcher: httpAgent.retry,
295
+ dispatcher: options.dispatcher || httpAgent.retry,
275
296
  signal: AbortSignal.timeout(DISCOVERY_TIMEOUT)
276
297
  });
277
298
 
@@ -283,6 +304,37 @@ async function fetchOidcDiscovery() {
283
304
  return validateDiscoveryDocument(doc, OIDC_ISSUER);
284
305
  }
285
306
 
307
+ // Keep probing the discovery endpoint until it answers, resolving with the document.
308
+ // Callers use this after a failed startup fetch: discovery is what the bell strategy is
309
+ // built from, so a failure that is never retried leaves SSO switched off for the
310
+ // lifetime of the process - silently, and on a forced instance that looks like the
311
+ // admin panel reverting to password login on its own.
312
+ //
313
+ // Two deliberate departures from a plain fetch-with-retry. It waits before the first
314
+ // attempt, because this continues a fetch that has just failed rather than starting a
315
+ // fresh one. And each probe uses the plain dispatcher instead of the retrying one
316
+ // fetchOidcDiscovery() defaults to: this loop is itself the retry layer, and undici's
317
+ // ladder underneath it would turn every "cheap probe" into five connect attempts
318
+ // holding a socket for the whole 10s timeout.
319
+ async function retryDiscovery(options) {
320
+ options = options || {};
321
+
322
+ let fetchDiscovery = options.fetchDiscovery || (() => fetchOidcDiscovery({ dispatcher: httpAgent.fetch }));
323
+
324
+ return backOff(fetchDiscovery, {
325
+ delayFirstAttempt: true,
326
+ startingDelay: options.minDelay || DISCOVERY_RETRY_MIN,
327
+ maxDelay: options.maxDelay || DISCOVERY_RETRY_MAX,
328
+ numOfAttempts: Infinity,
329
+ retry: (err, attempt) => {
330
+ if (options.onError) {
331
+ options.onError(err, attempt);
332
+ }
333
+ return true;
334
+ }
335
+ });
336
+ }
337
+
286
338
  // Build an OIDC RP-initiated logout URL against the IdP's end_session_endpoint.
287
339
  // id_token_hint is included when available so the IdP skips its logout-confirmation
288
340
  // prompt; client_id + post_logout_redirect_uri (the latter must be registered at the
@@ -350,6 +402,7 @@ module.exports = {
350
402
  validateDiscoveryDocument,
351
403
  mapUserinfoProfile,
352
404
  fetchOidcDiscovery,
405
+ retryDiscovery,
353
406
  buildLogoutUrl,
354
407
  buildOidcBellProvider
355
408
  };
@@ -0,0 +1,29 @@
1
+ 'use strict';
2
+
3
+ // Progress states a submit job reaches only once the message has been accepted. The email client
4
+ // writes 'smtp-completed' right after the MTA's 250 (or the provider API's accept), and the submit
5
+ // worker writes 'submitted' once the post-send bookkeeping is through as well. Everything a job
6
+ // does after either state is bookkeeping (Sent-folder copy, draft cleanup, flag updates, gateway
7
+ // stats), so a job that is running again in one of these states must not send the message again.
8
+ //
9
+ // Split out of workers/submit.js because the worker boots a BullMQ consumer on require, which
10
+ // keeps the decision itself out of reach of a unit test.
11
+ const SENT_PROGRESS_STATES = new Set(['smtp-completed', 'submitted']);
12
+
13
+ /**
14
+ * Tells whether a submit job's stored progress says the message was already accepted.
15
+ *
16
+ * BullMQ hands a re-run job the progress its previous run stored, so this is what a stalled job
17
+ * (heartbeat kill, crash, a shutdown drain that could not cover a long SMTP transaction) looks
18
+ * like when it comes back. A retry after a real delivery failure never carries one of these states:
19
+ * the failure path writes 'error' before it throws, and a run cut short before the 250 leaves
20
+ * 'processing' or 'smtp-starting' behind.
21
+ *
22
+ * @param {*} progress - job.progress as BullMQ hydrates it (an object, or 0 when never set)
23
+ * @returns {boolean} True when the message was already sent
24
+ */
25
+ function isAlreadySent(progress) {
26
+ return !!(progress && typeof progress === 'object' && SENT_PROGRESS_STATES.has(progress.status));
27
+ }
28
+
29
+ module.exports = { isAlreadySent, SENT_PROGRESS_STATES };
package/lib/templates.js CHANGED
@@ -84,8 +84,19 @@ class TemplateHandler {
84
84
  return id;
85
85
  }
86
86
 
87
+ // The inverse of generateId(): an 8-byte timestamp, a 4-byte counter, then the account id.
88
+ // Anything shorter than the fixed 12-byte header cannot be an id this module issued, and the
89
+ // routes accept any string up to 256 characters, so a malformed id is refused as "not found"
90
+ // here rather than failing on the header read.
87
91
  unpackId(id) {
88
92
  let idBuf = Buffer.from(id, 'base64');
93
+ if (idBuf.length < 4 + 8) {
94
+ let err = new Error('Document was not found');
95
+ err.code = 'NotFound';
96
+ err.statusCode = 404;
97
+ throw err;
98
+ }
99
+
89
100
  return {
90
101
  counter: idBuf.readUInt32BE(8),
91
102
  created: new Date(Number(idBuf.readBigUInt64BE(0))).toISOString(),