emailengine-app 2.87.2 → 2.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/.ncurc.js +24 -44
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +37 -0
  4. package/ENVIRONMENT.md +26 -23
  5. package/LICENSE_EMAILENGINE.txt +20 -12
  6. package/app.json +3 -3
  7. package/bin/emailengine.js +7 -11
  8. package/data/google-crawlers.json +1 -1
  9. package/data/public_suffix_list.dat +155 -16
  10. package/lib/account.js +69 -49
  11. package/lib/admin-password.js +85 -0
  12. package/lib/api-routes/license-routes.js +9 -0
  13. package/lib/api-token-auth.js +21 -5
  14. package/lib/calendar-event.js +15 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/db.js +1 -0
  17. package/lib/email-client/base-client.js +36 -15
  18. package/lib/email-client/gmail-client.js +20 -6
  19. package/lib/email-client/imap/connection-errors.js +30 -1
  20. package/lib/email-client/imap/session-expiry.js +83 -0
  21. package/lib/email-client/imap-client.js +12 -2
  22. package/lib/email-client/smtp-pool-manager.js +66 -8
  23. package/lib/export.js +147 -22
  24. package/lib/graph-notifications.js +60 -0
  25. package/lib/imap-proxy-auth.js +52 -18
  26. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  27. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  28. package/lib/imapproxy/imap-server.js +10 -1
  29. package/lib/imapproxy/proxy-handoff.js +100 -5
  30. package/lib/license-subscription.js +244 -0
  31. package/lib/node-version.js +99 -12
  32. package/lib/oauth/gmail.js +18 -0
  33. package/lib/oauth/outlook-identity.js +54 -12
  34. package/lib/prepared-password.js +38 -0
  35. package/lib/queue-browser/index.js +6 -6
  36. package/lib/queue-job-actions.js +59 -4
  37. package/lib/read-env-value.js +46 -21
  38. package/lib/redis-url.js +23 -0
  39. package/lib/response-stream.js +69 -1
  40. package/lib/revocation-events.js +79 -0
  41. package/lib/schemas.js +18 -2
  42. package/lib/settings.js +50 -24
  43. package/lib/sso.js +23 -0
  44. package/lib/submit-penalty.js +24 -0
  45. package/lib/submit-processor.js +10 -2
  46. package/lib/tokens.js +6 -0
  47. package/lib/tools.js +90 -18
  48. package/lib/ui-routes/admin-config-routes.js +3 -276
  49. package/lib/ui-routes/auth-routes.js +13 -64
  50. package/lib/ui-routes/dashboard-routes.js +4 -0
  51. package/lib/ui-routes/license-routes.js +326 -0
  52. package/lib/web-safe-html.js +74 -1
  53. package/lib/webhook-delivery.js +21 -20
  54. package/lib/webhook-penalty.js +18 -17
  55. package/lib/webhooks.js +18 -0
  56. package/list-generate.js +56 -19
  57. package/package.json +28 -31
  58. package/sbom.json +373 -964
  59. package/scan.js +2 -0
  60. package/server.js +273 -100
  61. package/static/css/flyonui.css +2 -2
  62. package/static/js/ui.js +11 -4
  63. package/static/licenses.html +1108 -504
  64. package/translations/messages.pot +18 -18
  65. package/views/config/license.hbs +43 -16
  66. package/views/dashboard.hbs +9 -0
  67. package/views/partials/side_menu.hbs +1 -1
  68. package/views/upgrade.hbs +25 -0
  69. package/workers/api.js +108 -107
  70. package/workers/imap.js +4 -6
  71. package/lib/net-tos-guard.js +0 -42
@@ -8,6 +8,11 @@ const { PassThrough } = require('stream');
8
8
  const { imapHandler } = require('./imap-core/index.js');
9
9
  const { isImapResponseError, toImapResponseError, faultResponseError } = require('./response-error');
10
10
 
11
+ // How often an open proxied session re-asks whether its credential still admits it. Revocations
12
+ // announced over lib/revocation-events.js are acted on at once; this catches the rest (an expired
13
+ // token, the auth-failure safety net parking an account).
14
+ const RECHECK_INTERVAL = 60 * 1000;
15
+
11
16
  class PassThroughLogger extends PassThrough {
12
17
  constructor(opts = {}) {
13
18
  super();
@@ -48,9 +53,77 @@ class PassThroughLogger extends PassThrough {
48
53
  * @param {Object} deps.serverLogger Logger for authentication failures
49
54
  * @param {Function} deps.metrics Metrics reporter
50
55
  * @param {Boolean} [deps.logRaw] Log every proxied chunk
51
- * @returns {Function} (login, session, callback) handler
56
+ * @param {Function} [deps.recheck] `(auth, session) => Promise<Boolean>`: whether the credential
57
+ * that opened a session still admits it. false ends the session, a rejection keeps it
58
+ * @param {Number} [deps.recheckInterval] How often open sessions are re-checked
59
+ * @returns {Function} (login, session, callback) handler, with `recheckSessions()` attached to run
60
+ * a re-check pass now (a credential was revoked) and `activeSessions` for inspection
52
61
  */
53
- function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, metrics, logRaw }) {
62
+ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, metrics, logRaw, recheck, recheckInterval = RECHECK_INTERVAL }) {
63
+ // Open proxied sessions and what they logged in with, so a revoked credential can end them.
64
+ // One timer serves all of them and runs only while there are any.
65
+ const activeSessions = new Set();
66
+ let recheckTimer = null;
67
+ let recheckInFlight = null;
68
+
69
+ const runRecheckPass = async account => {
70
+ // Sessions of the same credential share one answer, and the credentials are asked at once
71
+ const answers = new Map();
72
+ const pending = [...activeSessions]
73
+ .filter(entry => !account || entry.auth.username === account)
74
+ .map(entry => {
75
+ const key = JSON.stringify([entry.auth.username, entry.auth.password]);
76
+ if (!answers.has(key)) {
77
+ answers.set(
78
+ key,
79
+ recheck(entry.auth, entry.session).catch(err => {
80
+ logger.warn({ msg: 'Could not re-check a proxy session credential', account: entry.auth.username, err });
81
+ return true;
82
+ })
83
+ );
84
+ }
85
+ return { entry, answer: answers.get(key) };
86
+ });
87
+ for (const { entry, answer } of pending) {
88
+ if (!(await answer) && activeSessions.has(entry)) {
89
+ entry.revoke();
90
+ }
91
+ }
92
+ };
93
+
94
+ // Without an account every open session is re-checked, and a call made while such a pass runs
95
+ // joins it. With one, only that account's sessions are (a token or account change names it).
96
+ const recheckSessions = ({ account } = {}) => {
97
+ if (!recheck) {
98
+ return Promise.resolve();
99
+ }
100
+ if (account) {
101
+ return runRecheckPass(account);
102
+ }
103
+ if (!recheckInFlight) {
104
+ recheckInFlight = runRecheckPass().finally(() => {
105
+ recheckInFlight = null;
106
+ });
107
+ }
108
+ return recheckInFlight;
109
+ };
110
+
111
+ const trackSession = entry => {
112
+ activeSessions.add(entry);
113
+ if (recheck && !recheckTimer) {
114
+ recheckTimer = setInterval(() => recheckSessions(), recheckInterval);
115
+ recheckTimer.unref();
116
+ }
117
+ };
118
+
119
+ const untrackSession = entry => {
120
+ activeSessions.delete(entry);
121
+ if (!activeSessions.size && recheckTimer) {
122
+ clearInterval(recheckTimer);
123
+ recheckTimer = null;
124
+ }
125
+ };
126
+
54
127
  // A refusal or a temporary failure the client is told to retry is a warning and reaches the
55
128
  // client as the IMAP response it carries; anything else is a proxy fault, logged here and
56
129
  // answered with a generic response so its text never reaches the client. Handing the fault
@@ -66,7 +139,7 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
66
139
  };
67
140
 
68
141
  // Wires the two legs together once imap-core hands over the client socket
69
- const attachProxy = ({ session, account, downstream, upstream }) => {
142
+ const attachProxy = ({ session, account, downstream, upstream, auth }) => {
70
143
  metrics(logger, 'events', 'inc', {
71
144
  event: 'imapProxyConnected'
72
145
  });
@@ -94,11 +167,13 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
94
167
  // deflate/writeSocket error forwarders and destroys the upstream socket. Without it the
95
168
  // upstream connection and its idle timer would leak (most visibly with COMPRESS enabled).
96
169
  let proxyClosed = false;
170
+ let tracked = null;
97
171
  const closeProxy = () => {
98
172
  if (proxyClosed) {
99
173
  return;
100
174
  }
101
175
  proxyClosed = true;
176
+ untrackSession(tracked);
102
177
 
103
178
  try {
104
179
  downstream.imapClient.close();
@@ -177,6 +252,21 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
177
252
  teardownOn(downstream.imapClient.socket, 'close');
178
253
  }
179
254
 
255
+ tracked = {
256
+ auth,
257
+ session,
258
+ revoke() {
259
+ proxyLogger.info({ msg: 'Closing proxied session, its credential no longer admits it' });
260
+ try {
261
+ upstream.socket.write('* BYE Credentials are no longer valid\r\n');
262
+ } catch (err) {
263
+ // ignore
264
+ }
265
+ closeProxy();
266
+ }
267
+ };
268
+ trackSession(tracked);
269
+
180
270
  proxyLogger.info({ msg: 'Proxy mode enabled' });
181
271
  };
182
272
 
@@ -204,7 +294,9 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
204
294
  try {
205
295
  downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
206
296
 
207
- session.onProxy = upstream => attachProxy({ session, account, downstream, upstream });
297
+ // Only what a re-check needs: the login object also holds the connection
298
+ const auth = { username: login.username, password: login.password };
299
+ session.onProxy = upstream => attachProxy({ session, account, downstream, upstream, auth });
208
300
 
209
301
  if (downstream.imapClient.rawCapabilities) {
210
302
  login.connection.send(
@@ -235,13 +327,16 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
235
327
  };
236
328
  };
237
329
 
238
- return function (login, session, callback) {
330
+ const handler = function (login, session, callback) {
239
331
  // imap-core ignores what the handler returns, so every outcome has to end in the callback
240
332
  handleLogin(login, session).then(
241
333
  response => callback(null, response),
242
334
  err => callback(err)
243
335
  );
244
336
  };
337
+ handler.recheckSessions = recheckSessions;
338
+ handler.activeSessions = activeSessions;
339
+ return handler;
245
340
  }
246
341
 
247
342
  module.exports = { createProxyAuthHandler, PassThroughLogger };
@@ -0,0 +1,244 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * What the online subscription check decides, as pure functions: server.js applies the result to
5
+ * Redis and to the workers, and the unit tests pin every rule here.
6
+ *
7
+ * State kept in the settings hash:
8
+ * subexp - the deadline (ms) until which EmailEngine keeps working while the subscription behind
9
+ * its license is not in good standing
10
+ * subsusp - JSON describing a suspension: the deadline has passed and the license server asked to
11
+ * keep the key (keepLicense), so the workers stop but the key stays registered
12
+ *
13
+ * The license server (postalsys.com) decides the deadline and sends it as graceUntil: 7 days after a
14
+ * failed monthly renewal, 28 after a yearly one, none after a cancellation. A server that sends no
15
+ * graceUntil gets the 28 days counted from the first refusal, and without keepLicense the key is
16
+ * removed when they run out, which is how every earlier release behaved.
17
+ */
18
+
19
+ const HOUR = 60 * 60 * 1000;
20
+ const DAY = 24 * HOUR;
21
+
22
+ // Days of service after the first refusal when the server names no deadline
23
+ const LEGACY_GRACE = 28 * DAY;
24
+ // How often the subscription is checked online: daily, and hourly while it is not in good standing
25
+ const CHECK_INTERVAL = DAY;
26
+ const OVERDUE_CHECK_INTERVAL = HOUR;
27
+ // The furthest a successful answer may postpone the next check
28
+ const MAX_LICENSE_CHECK_DELAY = 30 * DAY;
29
+ // A startup check is skipped when the last successful one is this recent
30
+ const STARTUP_CHECK_FRESHNESS = HOUR;
31
+
32
+ const toTime = value => {
33
+ if (value === null || value === undefined || value === '') {
34
+ return null;
35
+ }
36
+ // Redis hands back a stored millisecond value as a string of digits
37
+ const time = typeof value === 'number' ? value : /^\d+$/.test(value) ? Number(value) : new Date(value).getTime();
38
+ return Number.isFinite(time) ? time : null;
39
+ };
40
+
41
+ /**
42
+ * Parses the stored subsusp value
43
+ * @param {string|null} raw
44
+ * @returns {Object|null} { code, error, since, overdueSince, endedAt } or null
45
+ */
46
+ function parseSuspension(raw) {
47
+ if (!raw) {
48
+ return null;
49
+ }
50
+ try {
51
+ const parsed = JSON.parse(raw);
52
+ return parsed && typeof parsed === 'object' ? parsed : null;
53
+ } catch (err) {
54
+ return null;
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Is a license one whose validity depends on a subscription, and so is checked online?
60
+ * Trial and other time-limited licenses carry their own expiry, lifetime ones never lapse.
61
+ * @param {Object} details - checkLicense() output
62
+ * @returns {boolean}
63
+ */
64
+ const isSubscriptionLicense = details => !!details && !details.expires && !details.lt && !details.trial;
65
+
66
+ /**
67
+ * How long to wait between online checks
68
+ * @param {Object} state - { subexp, subsusp } as stored
69
+ * @returns {number} milliseconds
70
+ */
71
+ const checkInterval = state => (state && (toTime(state.subexp) || state.subsusp) ? OVERDUE_CHECK_INTERVAL : CHECK_INTERVAL);
72
+
73
+ /**
74
+ * What one answer of the license server changes
75
+ * @param {Object} result
76
+ * @param {boolean} result.ok - the answer was 2xx
77
+ * @param {Object} result.data - its JSON body
78
+ * @param {number} result.now
79
+ * @param {number|null} result.subexp - the stored deadline
80
+ * @returns {Object} { clear, resume, subexp, suspend, removeLicense, nextCheck }: clear drops subexp
81
+ * and subsusp; resume drops subsusp only (the deadline is in the future again); subexp is a deadline
82
+ * to store; suspend is the subsusp record to store; removeLicense is the legacy outcome; nextCheck is
83
+ * when the next online check is due (ms), or null to leave it
84
+ */
85
+ // A server-provided time as an ISO string, or null when it does not parse
86
+ const isoOrNull = value => {
87
+ const time = toTime(value);
88
+ return time ? new Date(time).toISOString() : null;
89
+ };
90
+
91
+ // What decide() returns when nothing changes; each branch states only what differs
92
+ const NO_CHANGE = Object.freeze({ clear: false, resume: false, subexp: null, suspend: null, removeLicense: false, nextCheck: null });
93
+
94
+ function decide({ ok, data, now, subexp }) {
95
+ data = data || {};
96
+
97
+ if (ok) {
98
+ const validatedUntil = toTime(data.validatedUntil);
99
+ return {
100
+ ...NO_CHANGE,
101
+ clear: true,
102
+ resume: true,
103
+ nextCheck: validatedUntil ? Math.min(now + MAX_LICENSE_CHECK_DELAY, validatedUntil) : null
104
+ };
105
+ }
106
+
107
+ // A refusal without invalidate is not about the subscription (bad input, a server error):
108
+ // nothing changes, EmailEngine never stops over the license server's own trouble
109
+ if (!data.invalidate) {
110
+ return { ...NO_CHANGE };
111
+ }
112
+
113
+ const stored = toTime(subexp);
114
+ const deadline = toTime(data.graceUntil) || stored || now + LEGACY_GRACE;
115
+
116
+ if (deadline > now) {
117
+ // inside the window: working, even if a stored suspension said otherwise (the server's
118
+ // deadline is the one that counts, and it can move later)
119
+ return { ...NO_CHANGE, resume: true, subexp: deadline, nextCheck: now + OVERDUE_CHECK_INTERVAL };
120
+ }
121
+
122
+ if (!data.keepLicense) {
123
+ return { ...NO_CHANGE, removeLicense: true };
124
+ }
125
+
126
+ return {
127
+ ...NO_CHANGE,
128
+ subexp: deadline,
129
+ suspend: {
130
+ code: typeof data.code === 'string' ? data.code.slice(0, 64) : 'SubscriptionInactive',
131
+ error: typeof data.error === 'string' ? data.error.slice(0, 256) : 'Subscription inactive',
132
+ since: new Date(deadline).toISOString(),
133
+ overdueSince: isoOrNull(data.overdueSince),
134
+ endedAt: isoOrNull(data.endedAt)
135
+ },
136
+ nextCheck: now + OVERDUE_CHECK_INTERVAL
137
+ };
138
+ }
139
+
140
+ /**
141
+ * The suspension a stored deadline implies on its own: when it has passed and no suspension is
142
+ * recorded yet (the license server could not be asked, or the deadline ran out while EmailEngine
143
+ * was not running), EmailEngine suspends itself and lets the next answer of the server decide
144
+ * @param {number|string|null} subexp - the stored deadline
145
+ * @param {string|null} subsusp - the stored suspension
146
+ * @param {number} now
147
+ * @returns {Object|null} the suspension record to store, or null
148
+ */
149
+ function expiredSuspension(subexp, subsusp, now) {
150
+ const deadline = toTime(subexp);
151
+ if (parseSuspension(subsusp) || !deadline || deadline > now) {
152
+ return null;
153
+ }
154
+ return { code: 'SubscriptionInactive', error: 'Subscription inactive', since: new Date(deadline).toISOString() };
155
+ }
156
+
157
+ /**
158
+ * What a start of EmailEngine does before any worker runs
159
+ * @param {Object} input
160
+ * @param {Object|false} input.details - the loaded license (checkLicense() output), or false
161
+ * @param {number|string|null} input.subexp - the stored deadline
162
+ * @param {string|null} input.subsusp - the stored suspension
163
+ * @param {number|string|null} input.subcheck - when the last online check ran (ms)
164
+ * @param {number} input.now
165
+ * @returns {Object} { suspension, checkNow }: suspension is the record to start suspended with, or
166
+ * null; checkNow asks for an online check right away instead of in 20 minutes
167
+ */
168
+ function startupPlan({ details, subexp, subsusp, subcheck, now }) {
169
+ if (!isSubscriptionLicense(details)) {
170
+ return { suspension: null, checkNow: false };
171
+ }
172
+
173
+ const deadline = toTime(subexp);
174
+ const suspension = parseSuspension(subsusp) || expiredSuspension(subexp, subsusp, now);
175
+
176
+ const lastCheck = toTime(subcheck);
177
+ const recentlyChecked = !!lastCheck && now - lastCheck < STARTUP_CHECK_FRESHNESS;
178
+ // a restart loop costs one call an hour, whatever the reason to check
179
+ const checkNow = (!!suspension || !!deadline || details.billing === 'monthly') && !recentlyChecked;
180
+
181
+ return { suspension, checkNow };
182
+ }
183
+
184
+ /**
185
+ * Does registering a license keep the stored subscription state? Only when it is the key already
186
+ * registered: registering the same file again (by hand, through the API, or at every start from a
187
+ * license file or EENGINE_PREPARED_LICENSE) must not lift a suspension. A different key starts clean,
188
+ * and the online check that follows registration decides its standing.
189
+ * @param {string|null} storedKey - key of the license currently registered
190
+ * @param {string} newKey - key of the license being registered
191
+ * @returns {boolean}
192
+ */
193
+ const keepsSubscriptionState = (storedKey, newKey) => !!storedKey && !!newKey && storedKey === newKey;
194
+
195
+ /**
196
+ * The subscription state as the license page and the API report it
197
+ * @param {Object} input - { subexp, suspension, now }
198
+ * @returns {Object|null} { status, code, error, since, until, days } or null when in good standing;
199
+ * days is how many whole days remain until `until` (0 once it has passed)
200
+ */
201
+ function subscriptionView({ subexp, suspension, now }) {
202
+ let view = null;
203
+ if (suspension) {
204
+ view = {
205
+ status: 'suspended',
206
+ code: suspension.code || null,
207
+ error: suspension.error || null,
208
+ since: suspension.overdueSince || suspension.endedAt || suspension.since || null,
209
+ until: suspension.since || null
210
+ };
211
+ } else if (toTime(subexp)) {
212
+ const deadline = toTime(subexp);
213
+ view = { status: deadline > now ? 'overdue' : 'suspended', code: null, error: null, since: null, until: new Date(deadline).toISOString() };
214
+ }
215
+ if (view) {
216
+ const until = toTime(view.until);
217
+ view.days = until ? Math.max(Math.ceil((until - now) / DAY), 0) : 0;
218
+ }
219
+ return view;
220
+ }
221
+
222
+ /**
223
+ * Is the subscription behind a license reported as suspended?
224
+ * @param {Object} licenseInfo - the `license` command's answer
225
+ * @returns {boolean}
226
+ */
227
+ const isSuspended = licenseInfo => !!(licenseInfo && licenseInfo.subscription && licenseInfo.subscription.status === 'suspended');
228
+
229
+ module.exports = {
230
+ decide,
231
+ startupPlan,
232
+ expiredSuspension,
233
+ checkInterval,
234
+ subscriptionView,
235
+ isSuspended,
236
+ parseSuspension,
237
+ isSubscriptionLicense,
238
+ keepsSubscriptionState,
239
+ toTime,
240
+ LEGACY_GRACE,
241
+ CHECK_INTERVAL,
242
+ OVERDUE_CHECK_INTERVAL,
243
+ MAX_LICENSE_CHECK_DELAY
244
+ };
@@ -1,24 +1,111 @@
1
1
  'use strict';
2
2
 
3
- // The oldest Node.js release the dependency tree supports, matching `engines.node` in package.json
4
- // (test/node-version-test.js keeps the two in step). Requires nothing but the dependency-free
5
- // lib/utils/version.js, because server.js checks it before it requires anything else.
6
-
7
- const MIN_SUPPORTED_NODE = '20.19.0';
3
+ // Which Node.js releases EmailEngine runs on. Requires nothing but the dependency-free
4
+ // lib/utils/version.js, because server.js asks before it requires anything else.
5
+ //
6
+ // Two thresholds, because the dependency tree has two:
7
+ //
8
+ // - MIN_NODE is the oldest release EmailEngine can start on at all. undici 8, which the main
9
+ // thread and every worker load at startup, throws when it is loaded on anything older than
10
+ // 22.19 (it calls a zlib API Node 20 does not have), so below it server.js exits with a message
11
+ // instead of letting the first worker die on a TypeError.
12
+ // - SUPPORTED_RANGES is what package.json `engines.node` declares, the range the bundled jsdom
13
+ // (inside @postalsys/email-text-tools) declares. A release between the two starts and runs, and
14
+ // the dashboard says it is outside the supported range. test/node-version-test.js keeps the
15
+ // ranges equal to the engines field.
8
16
 
9
17
  const { compareVersions } = require('./utils/version');
10
18
 
19
+ const MIN_NODE = '22.19.0';
20
+
21
+ // [major, minimum within that major], the last entry also admits every later major
22
+ const SUPPORTED_RANGES = [
23
+ [22, '22.22.2'],
24
+ [24, '24.15.0'],
25
+ [26, '26.0.0']
26
+ ];
27
+
28
+ // The engines.node form of SUPPORTED_RANGES
29
+ const SUPPORTED_RANGE_TEXT = SUPPORTED_RANGES.map(([, min], i) => (i === SUPPORTED_RANGES.length - 1 ? `>=${min}` : `^${min}`)).join(' || ');
30
+
31
+ // What an operator reads when the version is not supported
32
+ // ("22.x from 22.22.2, 24.x from 24.15.0, or 26 and newer")
33
+ const SUPPORTED_RANGE_LABEL = SUPPORTED_RANGES.map(([major, min], i) =>
34
+ i === SUPPORTED_RANGES.length - 1 ? `or ${major} and newer` : `${major}.x from ${min}`
35
+ ).join(', ');
36
+
37
+ function normalize(version) {
38
+ return String(version || '').replace(/^v/, '');
39
+ }
40
+
41
+ function inSupportedRange(version) {
42
+ const major = Number(version.split('.')[0]);
43
+ const last = SUPPORTED_RANGES[SUPPORTED_RANGES.length - 1];
44
+ if (major >= last[0]) {
45
+ return compareVersions(version, last[1]) >= 0;
46
+ }
47
+ const range = SUPPORTED_RANGES.find(([rangeMajor]) => rangeMajor === major);
48
+ return !!range && compareVersions(version, range[1]) >= 0;
49
+ }
50
+
11
51
  /**
12
- * Whether a Node.js version is older than MIN_SUPPORTED_NODE
13
- * @param {string} version - A version such as process.versions.node ("20.18.1")
14
- * @returns {boolean} True when the version is older, false for one that can not be read
52
+ * How well EmailEngine supports a Node.js version
53
+ * @param {string} version - A version such as process.versions.node ("22.19.0")
54
+ * @returns {'unsupported'|'outside-range'|'ok'} 'unsupported' below MIN_NODE, 'outside-range' for
55
+ * a release that runs but is not in SUPPORTED_RANGES, 'ok' otherwise. A version that can not be
56
+ * read is 'ok': nothing is gained by refusing to start over a string we do not understand
15
57
  */
16
- function isBelowSupportedNode(version) {
58
+ function nodeSupport(version) {
59
+ const normalized = normalize(version);
17
60
  try {
18
- return compareVersions(String(version || '').replace(/^v/, ''), MIN_SUPPORTED_NODE) < 0;
61
+ if (compareVersions(normalized, MIN_NODE) < 0) {
62
+ return 'unsupported';
63
+ }
64
+ return inSupportedRange(normalized) ? 'ok' : 'outside-range';
19
65
  } catch (err) {
20
- return false;
66
+ return 'ok';
21
67
  }
22
68
  }
23
69
 
24
- module.exports = { MIN_SUPPORTED_NODE, isBelowSupportedNode };
70
+ // What an operator on a Debian or Ubuntu server with Node.js from NodeSource (the DigitalOcean one-click
71
+ // image included) runs to move to a supported release. The startup error and /admin/upgrade show it
72
+ const NODESOURCE_UPGRADE_COMMANDS = [
73
+ 'curl -fsSL https://deb.nodesource.com/setup_24.x | sudo bash -',
74
+ 'sudo apt-get install -y nodejs',
75
+ 'sudo systemctl restart emailengine'
76
+ ];
77
+
78
+ /**
79
+ * The commands an operator runs to move to a supported Node.js release, for the startup error
80
+ * @returns {string}
81
+ */
82
+ function nodeUpgradeHint() {
83
+ return [
84
+ 'To upgrade Node.js on a Debian or Ubuntu server that installed it from NodeSource (this includes the',
85
+ 'DigitalOcean one-click image), run:',
86
+ '',
87
+ ...NODESOURCE_UPGRADE_COMMANDS.map(command => ` ${command}`),
88
+ '',
89
+ 'The EmailEngine binaries and the Docker image carry their own Node.js and are not affected.'
90
+ ].join('\n');
91
+ }
92
+
93
+ /**
94
+ * What the admin UI shows about the Node.js release it runs on
95
+ * @param {string} version - A version such as process.versions.node
96
+ * @param {boolean} [packaged] - A pkg binary, which carries its own Node.js: there is nothing for
97
+ * its operator to upgrade but EmailEngine, so it is never flagged
98
+ * @returns {{version: string, supported: string, upgradeCommands: string[], packaged: boolean, outsideRange: boolean}}
99
+ */
100
+ function nodeRuntimeView(version, packaged) {
101
+ return {
102
+ version: normalize(version),
103
+ supported: SUPPORTED_RANGE_LABEL,
104
+ upgradeCommands: NODESOURCE_UPGRADE_COMMANDS,
105
+ packaged: !!packaged,
106
+ // 'unsupported' never renders: the process would not have started
107
+ outsideRange: !packaged && nodeSupport(version) !== 'ok'
108
+ };
109
+ }
110
+
111
+ module.exports = { nodeRuntimeView, MIN_NODE, SUPPORTED_RANGE_TEXT, SUPPORTED_RANGE_LABEL, nodeSupport, nodeUpgradeHint };
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const { isEmail } = require('../utils/is-email');
3
4
  const packageData = require('../../package.json');
4
5
  const {
5
6
  formatPartialSecretKey,
@@ -220,6 +221,22 @@ function workspaceDomainOf(idTokenPayload) {
220
221
  return hd || null;
221
222
  }
222
223
 
224
+ /**
225
+ * The address an ID token vouches for, or null. Google marks an address it has not confirmed with
226
+ * `email_verified: false` (a Google account registered with a third-party address nobody proved),
227
+ * and such an address is no evidence of who signed in: it used to become the account address and the
228
+ * identity an expectedEmail pin was checked against.
229
+ *
230
+ * @param {Object|null} idTokenPayload - decoded ID token payload (lib/decode-jwt-payload.js)
231
+ * @returns {String|null}
232
+ */
233
+ function verifiedEmailOf(idTokenPayload) {
234
+ if (!idTokenPayload || idTokenPayload.email_verified === false || !isEmail(idTokenPayload.email)) {
235
+ return null;
236
+ }
237
+ return idTokenPayload.email;
238
+ }
239
+
223
240
  class GmailOauth {
224
241
  constructor(opts) {
225
242
  // The network route of the account this client acts for (see getAccountHttpRoute()). Every
@@ -955,6 +972,7 @@ module.exports.GmailOauth = GmailOauth;
955
972
  module.exports.checkForFlags = checkForFlags;
956
973
  module.exports.checkForUserFlags = checkForUserFlags;
957
974
  module.exports.workspaceDomainOf = workspaceDomainOf;
975
+ module.exports.verifiedEmailOf = verifiedEmailOf;
958
976
  module.exports.GMAIL_SCOPES = GMAIL_SCOPES;
959
977
  module.exports.GMAIL_API_SCOPES = GMAIL_API_SCOPES;
960
978
  module.exports.GMAIL_PROVIDERS = GMAIL_PROVIDERS;
@@ -24,38 +24,80 @@ const { isEmail } = require('../utils/is-email');
24
24
  // and the user principal name are offered, because either can be the stable identity for a tenant and
25
25
  // they routinely differ (user@contoso.com vs user@contoso.onmicrosoft.com).
26
26
  //
27
- // `email` prefers a verified value and falls back to clientInfo only when no back-channel source produced
28
- // one. That fallback exists for OAuth2 apps predating the User.Read scope; it is rarely reached now, since
29
- // the id_token carries preferred_username whenever `openid profile` is granted. The precedence matters
30
- // beyond the identity check: accountData.email is persisted, shown in the admin UI, and used as the
31
- // default From address, so a spoofable value winning there is a bug in its own right.
27
+ // The mailbox address (`mail` on the Graph profile, `email` in the id_token) is a directory attribute
28
+ // a tenant administrator can set to any address, in a domain the tenant never proved it owns, and
29
+ // Microsoft returns it unchanged. An address there is only evidence when its domain is one the issuing
30
+ // tenant has verified: the domain of the user principal name (which Entra ID only accepts in a
31
+ // verified domain), a domain the Graph branch read from /v1.0/organization, or an id_token that marks
32
+ // it verified with the `xms_edov` claim. Otherwise anyone administering any tenant could satisfy an
33
+ // expectedEmail pin for an address they do not own. Verified against Entra ID on 2026-11-07.
34
+ //
35
+ // `email` is the first verified identity. It used to fall back to the client_info address, which let
36
+ // the browser choose the account's persisted address and, through `username || email`, its login.
32
37
  //
33
38
  // `username` is the credential EmailEngine authenticates with (XOAUTH2), so it is verified-only with no
34
39
  // clientInfo fallback. The profile's userPrincipalName is taken as-is rather than filtered as an address,
35
40
  // matching the previous behavior - a tenant whose UPN is not email-shaped must still be able to log in.
36
41
  function resolveOutlookUserInfo(sources) {
37
- const { clientInfo, idTokenPayload, profile } = sources || {};
42
+ const { clientInfo, idTokenPayload, profile, verifiedDomains } = sources || {};
38
43
 
39
44
  // isEmail already rejects non-strings, so these only normalize a miss to null.
40
45
  const asEmail = value => isEmail(value) || null;
41
46
  const asString = value => (typeof value === 'string' && value ? value : null);
47
+ const domainOf = address => address.slice(address.lastIndexOf('@') + 1).toLowerCase();
42
48
 
43
49
  const profileUpn = asString(profile && profile.userPrincipalName);
44
50
  const idTokenUpn = asEmail(idTokenPayload && idTokenPayload.preferred_username);
51
+ const upnAddresses = [idTokenUpn, asEmail(profileUpn)].filter(Boolean);
52
+
53
+ const trustedDomains = new Set([...upnAddresses.map(domainOf), ...(verifiedDomains || []).map(domain => domain.toLowerCase())]);
54
+ const vouched = address => trustedDomains.has(domainOf(address));
55
+
56
+ const profileMail = asEmail(profile && profile.mail);
57
+ const idTokenEmail = asEmail(idTokenPayload && idTokenPayload.email);
58
+ const mailboxAddresses = [];
59
+ if (profileMail && vouched(profileMail)) {
60
+ mailboxAddresses.push(profileMail);
61
+ }
62
+ if (idTokenEmail && (idTokenPayload.xms_edov === true || vouched(idTokenEmail))) {
63
+ mailboxAddresses.push(idTokenEmail);
64
+ }
45
65
 
46
- // One list in preference order does both jobs: membership answers "did the provider return this
66
+ // One list in preference order does both jobs: membership answers "did the provider vouch for this
47
67
  // address", and the first entry is the best address to show. Keeping two orderings in sync by hand
48
68
  // would be a silent bug the moment they drifted.
49
- const verifiedIdentities = [
50
- ...new Set([asEmail(profile && profile.mail), asEmail(idTokenPayload && idTokenPayload.email), idTokenUpn, asEmail(profileUpn)].filter(Boolean))
51
- ];
69
+ const verifiedIdentities = [...new Set([...mailboxAddresses, ...upnAddresses])];
52
70
 
53
71
  return {
54
72
  name: asString(idTokenPayload && idTokenPayload.name) || asString(profile && profile.displayName) || asString(clientInfo && clientInfo.name),
55
- email: verifiedIdentities[0] || asEmail(clientInfo && clientInfo.preferred_username),
73
+ email: verifiedIdentities[0] || null,
56
74
  username: idTokenUpn || profileUpn,
57
75
  verifiedIdentities
58
76
  };
59
77
  }
60
78
 
61
- module.exports = { resolveOutlookUserInfo };
79
+ /**
80
+ * The domains the signed-in user's tenant has verified, from Graph /v1.0/organization (covered by
81
+ * User.Read). A Graph `mail` value is only identity evidence in one of these or in the domain of the
82
+ * user principal name. An empty list (a personal Microsoft account has no organization, or the request
83
+ * failed) leaves only the user principal name's domain, which narrows what is accepted and never
84
+ * widens it.
85
+ *
86
+ * @param {Object} oAuth2Client - The Outlook OAuth2 client (`request()`, `apiBase`)
87
+ * @param {string} accessToken
88
+ * @param {Object} logger
89
+ * @returns {Promise<string[]>}
90
+ */
91
+ async function readTenantVerifiedDomains(oAuth2Client, accessToken, logger) {
92
+ try {
93
+ const res = await oAuth2Client.request(accessToken, `${oAuth2Client.apiBase}/v1.0/organization?$select=verifiedDomains`);
94
+ return ((res && res.value) || [])
95
+ .flatMap(org => (Array.isArray(org.verifiedDomains) ? org.verifiedDomains : []).map(domain => domain && domain.name))
96
+ .filter(Boolean);
97
+ } catch (err) {
98
+ logger.warn({ msg: 'Could not read the verified domains of the Microsoft tenant', err });
99
+ return [];
100
+ }
101
+ }
102
+
103
+ module.exports = { resolveOutlookUserInfo, readTenantVerifiedDomains };