emailengine-app 2.89.0 → 2.90.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 (72) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +44 -0
  4. package/Dockerfile +5 -1
  5. package/bin/healthcheck.js +1 -1
  6. package/copy-static-files.sh +0 -8
  7. package/data/google-crawlers.json +1 -1
  8. package/encrypt.js +1 -4
  9. package/lib/account/field-codec.js +396 -0
  10. package/lib/account.js +158 -453
  11. package/lib/api-routes/account-routes.js +42 -6
  12. package/lib/api-routes/route-metadata.js +5 -2
  13. package/lib/api-routes/submit-routes.js +15 -2
  14. package/lib/api-token-auth.js +342 -274
  15. package/lib/arf-detect.js +174 -149
  16. package/lib/attachment-size.js +29 -0
  17. package/lib/autodetect-imap-settings.js +83 -234
  18. package/lib/consts.js +1 -5
  19. package/lib/db.js +1 -4
  20. package/lib/email-client/base-client.js +907 -780
  21. package/lib/email-client/gmail-client.js +557 -450
  22. package/lib/email-client/imap/cid-parts.js +61 -0
  23. package/lib/email-client/imap/mailbox.js +376 -422
  24. package/lib/email-client/imap/sync-operations.js +239 -178
  25. package/lib/email-client/new-message-steps.js +168 -2
  26. package/lib/email-client/outlook/graph-message.js +266 -0
  27. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  28. package/lib/email-client/outlook-client.js +652 -808
  29. package/lib/get-raw-email.js +338 -232
  30. package/lib/get-secret.js +1 -4
  31. package/lib/license-subscription.js +60 -0
  32. package/lib/load-env.js +48 -0
  33. package/lib/logger.js +1 -4
  34. package/lib/mcp/tools.js +244 -207
  35. package/lib/metric-values.js +76 -0
  36. package/lib/metrics.js +320 -0
  37. package/lib/oauth/gmail.js +39 -120
  38. package/lib/oauth/http-request.js +195 -0
  39. package/lib/oauth/mail-ru.js +24 -58
  40. package/lib/oauth/outlook.js +37 -137
  41. package/lib/oauth/pubsub/google.js +176 -117
  42. package/lib/oauth2-apps.js +440 -463
  43. package/lib/openapi/build-document.js +10 -10
  44. package/lib/read-env-value.js +1 -1
  45. package/lib/route-descriptors.js +78 -0
  46. package/lib/schemas.js +10 -1
  47. package/lib/sentry-integrations.js +299 -0
  48. package/lib/sentry.js +75 -27
  49. package/lib/sso-routes.js +249 -0
  50. package/lib/sso.js +29 -6
  51. package/lib/ui-routes/account-edit-form.js +198 -0
  52. package/lib/ui-routes/account-page.js +241 -0
  53. package/lib/ui-routes/account-routes.js +12 -318
  54. package/lib/ui-routes/auth-routes.js +10 -10
  55. package/lib/ui-view-context.js +328 -0
  56. package/lib/utils/public-suffix.js +22 -101
  57. package/lib/web-safe-html.js +20 -7
  58. package/lib/worker-metrics.js +82 -0
  59. package/list-generate.js +2 -5
  60. package/package.json +23 -19
  61. package/sbom.json +267 -908
  62. package/scripts/refresh-test-tokens.js +1 -1
  63. package/server.js +320 -676
  64. package/static/css/flyonui.css +1 -1
  65. package/static/css/src/app.tailwind.css +18 -0
  66. package/static/js/ee-client.js +2619 -645
  67. package/static/js/ui.js +12 -2
  68. package/static/licenses.html +219 -737
  69. package/translations/messages.pot +64 -53
  70. package/views/accounts/browse.hbs +19 -1
  71. package/workers/api.js +20 -451
  72. package/data/public_suffix_list.dat +0 -16698
@@ -15,12 +15,12 @@ const { parentPort } = require('worker_threads');
15
15
  const pbkdf2 = require('../pbkdf2-phc');
16
16
  const { verifyAdminPassword, verifyCurrentPassword, setAdminPassword } = require('../admin-password');
17
17
  const { generateTotpSeed, verifyTotp, generateTotpUrl, generateTotpQrDataUrl } = require('../totp');
18
- const {
19
- generateRegistrationOptions,
20
- verifyRegistrationResponse,
21
- generateAuthenticationOptions,
22
- verifyAuthenticationResponse
23
- } = require('@simplewebauthn/server');
18
+ // Loaded on the first passkey request rather than with the admin UI: the library and its X.509 and
19
+ // ASN.1 dependencies are about 4.6 MB of heap and 70 ms of startup in the API worker, and they add
20
+ // tslib's helpers to globalThis and reflect-metadata's methods to Reflect, all for a feature many
21
+ // instances never use. A literal require(), so pkg still bundles it.
22
+ let webauthnModule;
23
+ const webauthn = () => (webauthnModule = webauthnModule || require('@simplewebauthn/server'));
24
24
 
25
25
  // The public key algorithms a passkey may be registered with: ES256 and RS256, which every
26
26
  // authenticator offers. The library's own list starts with EdDSA, and an Ed25519 passkey fails at
@@ -1105,7 +1105,7 @@ function registerPostAccountPasskeysRegisterOptions(server) {
1105
1105
  return h.response({ error: verified.message }).code(verified.statusCode);
1106
1106
  }
1107
1107
 
1108
- let options = await generateRegistrationOptions({
1108
+ let options = await webauthn().generateRegistrationOptions({
1109
1109
  rpName: 'EmailEngine',
1110
1110
  rpID: rpId,
1111
1111
  userName: user,
@@ -1185,7 +1185,7 @@ function registerPostAccountPasskeysRegisterVerify(server) {
1185
1185
  return h.response({ error: 'Challenge expired or invalid. Please try again.' }).code(400);
1186
1186
  }
1187
1187
 
1188
- let verification = await verifyRegistrationResponse({
1188
+ let verification = await webauthn().verifyRegistrationResponse({
1189
1189
  response: request.payload.credential,
1190
1190
  expectedChallenge: challenge,
1191
1191
  expectedOrigin: origin,
@@ -1331,7 +1331,7 @@ function registerPostPasskeyAuthOptions(server) {
1331
1331
  return h.response({ error: 'no_passkeys' }).code(400);
1332
1332
  }
1333
1333
 
1334
- let options = await generateAuthenticationOptions({
1334
+ let options = await webauthn().generateAuthenticationOptions({
1335
1335
  rpID: rpId,
1336
1336
  allowCredentials: allCredentials.map(c => ({
1337
1337
  id: c.id,
@@ -1405,7 +1405,7 @@ function registerPostPasskeyAuthVerify(server) {
1405
1405
  return h.response({ success: false, error: 'Authentication failed' }).code(400);
1406
1406
  }
1407
1407
 
1408
- let verification = await verifyAuthenticationResponse({
1408
+ let verification = await webauthn().verifyAuthenticationResponse({
1409
1409
  response: request.payload.credential,
1410
1410
  expectedChallenge: challenge,
1411
1411
  expectedOrigin: origin,
@@ -0,0 +1,328 @@
1
+ 'use strict';
2
+
3
+ // The view context every server-rendered page receives (the `context` option of server.views() in
4
+ // workers/api.js). Moved out of the API worker, which a test cannot load, so the context and the
5
+ // system alerts it carries are tested directly.
6
+
7
+ const logger = require('./logger');
8
+ const settings = require('./settings');
9
+ const packageData = require('../package.json');
10
+ const { redis } = require('./db');
11
+ const { oauth2Apps } = require('./oauth2-apps');
12
+ const { isSuspended } = require('./license-subscription');
13
+ const { flash, hasEnvValue, readEnvValue, getBoolean } = require('./tools');
14
+ const { LAST_DOCUMENT_STORE_VERSION } = require('./consts');
15
+
16
+ const DAY_MS = 24 * 3600 * 1000;
17
+
18
+ // The settings the context reads on every render
19
+ const CONTEXT_SETTINGS = [
20
+ 'upgrade',
21
+ 'webhookErrorFlag',
22
+ 'webhooksEnabled',
23
+ 'disableTokens',
24
+ 'tract',
25
+ 'templateHeader',
26
+ 'templateHtmlHead',
27
+ 'documentStoreEnabled',
28
+ 'serviceUrl',
29
+ 'language',
30
+ 'locale',
31
+ 'timezone',
32
+ 'pageBrandName',
33
+ 'notificationBaseUrl'
34
+ ];
35
+
36
+ // How a single sign-on session's profile is shown as the signed-in user. SSO users never manage
37
+ // the local password, hence isAdmin: false
38
+ const SSO_AUTH_DISPLAY = {
39
+ okta: profile => ({
40
+ user: profile.username,
41
+ name:
42
+ []
43
+ .concat(profile.firstName || [])
44
+ .concat(profile.lastName || [])
45
+ .join(' ') || profile.username,
46
+ enabled: !!profile.username,
47
+ isAdmin: false
48
+ }),
49
+ oidc: profile => ({
50
+ user: profile.username,
51
+ name: profile.displayName || profile.username,
52
+ enabled: !!profile.username,
53
+ isAdmin: false
54
+ })
55
+ };
56
+
57
+ /**
58
+ * The signed-in user as the page header shows it: the SSO profile for an SSO session, otherwise
59
+ * the local admin account, or a disabled placeholder when no admin password is set.
60
+ *
61
+ * @param {Object} [artifacts] - request.auth.artifacts
62
+ * @returns {Promise<Object>} `{ user, name, enabled, isAdmin }`
63
+ */
64
+ async function resolveAuthDisplay(artifacts) {
65
+ let provider = artifacts && artifacts.provider;
66
+ if (provider && Object.hasOwn(SSO_AUTH_DISPLAY, provider)) {
67
+ return SSO_AUTH_DISPLAY[provider](artifacts.profile || {});
68
+ }
69
+
70
+ let authData = await settings.get('authData');
71
+ if (authData) {
72
+ authData.name = authData.user;
73
+ authData.enabled = true;
74
+ authData.isAdmin = true;
75
+ return authData;
76
+ }
77
+
78
+ return {
79
+ name: 'admin',
80
+ user: 'admin',
81
+ enabled: false,
82
+ isAdmin: true
83
+ };
84
+ }
85
+
86
+ /**
87
+ * The license details shown on the page, with the whole days left until a set expiry.
88
+ *
89
+ * @param {Object} [licenseInfo] - request.app.licenseInfo
90
+ * @param {number} now - current time in milliseconds
91
+ * @returns {Object} a copy of the details, plus `expiresDays` when they carry an expiry
92
+ */
93
+ function licenseDetailsView(licenseInfo, now) {
94
+ let licenseDetails = Object.assign({}, (licenseInfo && licenseInfo.details) || {});
95
+
96
+ if (licenseDetails.expires) {
97
+ let delayMs = new Date(licenseDetails.expires) - now;
98
+ licenseDetails.expiresDays = Math.max(Math.ceil(delayMs / DAY_MS), 0);
99
+ }
100
+
101
+ return licenseDetails;
102
+ }
103
+
104
+ const plural = count => (count !== 1 ? 's' : '');
105
+
106
+ // The banners above every admin page, in display order. Each rule returns an alert, a list of
107
+ // them, or nothing
108
+ const ALERT_RULES = [
109
+ ({ settingsValues }) => {
110
+ let upgradeInfo = settingsValues.upgrade;
111
+ if (upgradeInfo && upgradeInfo.canUpgrade) {
112
+ return {
113
+ url: '/admin/upgrade',
114
+ level: 'info',
115
+ icon: 'icon-[tabler--alert-triangle]',
116
+ message: `An update is available: Emailengine v${upgradeInfo.available}`
117
+ };
118
+ }
119
+ },
120
+
121
+ // The subscription behind the license (lib/license-subscription.js): paused, or a date it pauses on
122
+ ({ licenseInfo }) => {
123
+ if (isSuspended(licenseInfo)) {
124
+ return {
125
+ url: '/admin/config/license',
126
+ level: 'danger',
127
+ icon: 'icon-[tabler--player-pause]',
128
+ message: 'EmailEngine is paused: the subscription behind the license key is not in good standing'
129
+ };
130
+ }
131
+ let licenseSubscription = licenseInfo && licenseInfo.subscription;
132
+ if (licenseSubscription) {
133
+ return {
134
+ url: '/admin/config/license',
135
+ level: 'danger',
136
+ icon: 'icon-[tabler--alert-triangle]',
137
+ message: `Subscription payment overdue: EmailEngine pauses in ${licenseSubscription.days} day${plural(licenseSubscription.days)} unless it is paid`
138
+ };
139
+ }
140
+ },
141
+
142
+ // OAuth2 apps whose token requests are being refused (setFlag() writes the failure
143
+ // into app meta). Shown on every admin page: the accounts on such an app sit
144
+ // disconnected until the operator acts, so the OAuth config page alone is not enough.
145
+ ({ oauthAuthFlags }) =>
146
+ oauthAuthFlags.map(({ app, authFlag }) => ({
147
+ url: authFlag.url || `/admin/config/oauth/app/${encodeURIComponent(app)}`,
148
+ level: 'danger',
149
+ icon: 'icon-[tabler--lock-open]',
150
+ message: authFlag.message
151
+ })),
152
+
153
+ ({ settingsValues }) => {
154
+ let webhookErrorFlag = settingsValues.webhookErrorFlag;
155
+ if (settingsValues.webhooksEnabled && webhookErrorFlag && webhookErrorFlag.message) {
156
+ return {
157
+ url: '/admin/config/webhooks',
158
+ level: 'danger',
159
+ icon: 'icon-[tabler--link]',
160
+ message: 'Webhook delivery is failing'
161
+ };
162
+ }
163
+ },
164
+
165
+ // a paused license is still registered, and the alert above says why it is not active
166
+ ({ licenseInfo }) => {
167
+ if (!licenseInfo || (!licenseInfo.active && !licenseInfo.details)) {
168
+ return {
169
+ url: '/admin/config/license',
170
+ level: 'warning',
171
+ icon: 'icon-[tabler--key]',
172
+ message: 'No license key registered'
173
+ };
174
+ }
175
+ },
176
+
177
+ ({ licenseDetails }) => {
178
+ if (licenseDetails.expires && licenseDetails.expiresDays < 31) {
179
+ return {
180
+ url: '/admin/config/license',
181
+ level: 'warning',
182
+ icon: 'icon-[tabler--key]',
183
+ message: `Your ${licenseDetails.trial ? `trial ` : ''}license key will expire in ${licenseDetails.expiresDays} day${plural(
184
+ licenseDetails.expiresDays
185
+ )}`
186
+ };
187
+ }
188
+ },
189
+
190
+ ({ settingsValues }) => {
191
+ if (settingsValues.disableTokens) {
192
+ return {
193
+ url: '/admin/config/security',
194
+ level: 'warning',
195
+ icon: 'icon-[tabler--key]',
196
+ message: `Access tokens are disabled for API requests`
197
+ };
198
+ }
199
+ },
200
+
201
+ // The Document Store was removed in 2.82.0. The setting that switched it on is read raw off
202
+ // the settings hash (it is no longer in the settings schema), so an instance upgraded with the
203
+ // feature still on is told where it went instead of losing it quietly
204
+ ({ settingsValues }) => {
205
+ if (settingsValues.documentStoreEnabled) {
206
+ return {
207
+ url: '/admin',
208
+ level: 'danger',
209
+ icon: 'icon-[tabler--database]',
210
+ message: `The Document Store has been removed from EmailEngine. Downgrade to v${LAST_DOCUMENT_STORE_VERSION} if you still need it.`
211
+ };
212
+ }
213
+ }
214
+ ];
215
+
216
+ /**
217
+ * The banners shown above every admin page.
218
+ *
219
+ * @param {Object} state
220
+ * @param {Object} state.settingsValues - the CONTEXT_SETTINGS values
221
+ * @param {Object} [state.licenseInfo] - request.app.licenseInfo
222
+ * @param {Object} state.licenseDetails - licenseDetailsView() output
223
+ * @param {Array} state.oauthAuthFlags - `{ app, authFlag }` per OAuth2 app whose token requests fail
224
+ * @param {boolean} state.disableSetupWarnings - keep only the danger level alerts
225
+ * @returns {Array<Object>} `{ url, level, icon, message }` per alert, in display order
226
+ */
227
+ function buildSystemAlerts(state) {
228
+ let systemAlerts = ALERT_RULES.flatMap(rule => [].concat(rule(state) || []));
229
+
230
+ if (state.disableSetupWarnings) {
231
+ // Keep only critical (danger) alerts, suppress info/warning level
232
+ systemAlerts = systemAlerts.filter(alert => alert.level === 'danger');
233
+ }
234
+
235
+ return systemAlerts;
236
+ }
237
+
238
+ /**
239
+ * The view context of a rendered page.
240
+ *
241
+ * @param {Object} request - the hapi request being rendered
242
+ * @returns {Promise<Object>}
243
+ */
244
+ async function buildViewContext(request) {
245
+ // The three reads are independent, and this runs on every admin page render. The
246
+ // OAuth2 auth flags are best-effort - a failure to read them must not take the page
247
+ // down with it.
248
+ const [pendingMessages, settingsValues, oauthAuthFlags] = await Promise.all([
249
+ flash(redis, request),
250
+ settings.getMulti(...CONTEXT_SETTINGS),
251
+ oauth2Apps.listAuthFlags().catch(err => {
252
+ logger.error({ msg: 'Failed to list OAuth2 app auth flags', err });
253
+ return [];
254
+ })
255
+ ]);
256
+
257
+ const {
258
+ tract,
259
+ templateHeader: embeddedTemplateHeader,
260
+ templateHtmlHead: embeddedTemplateHtmlHead,
261
+ documentStoreEnabled: documentStoreRemoved,
262
+ serviceUrl,
263
+ language,
264
+ locale,
265
+ timezone,
266
+ pageBrandName,
267
+ notificationBaseUrl
268
+ } = settingsValues;
269
+
270
+ let authData = await resolveAuthDisplay(request.auth.artifacts);
271
+
272
+ let licenseDetails = licenseDetailsView(request.app.licenseInfo, Date.now());
273
+
274
+ // Check if setup warnings should be disabled (for documentation screenshots, CI, etc.)
275
+ const disableSetupWarnings = hasEnvValue('EENGINE_DISABLE_SETUP_WARNINGS') ? getBoolean(readEnvValue('EENGINE_DISABLE_SETUP_WARNINGS')) : false;
276
+
277
+ let systemAlerts = buildSystemAlerts({
278
+ settingsValues,
279
+ licenseInfo: request.app.licenseInfo,
280
+ licenseDetails,
281
+ oauthAuthFlags,
282
+ disableSetupWarnings
283
+ });
284
+
285
+ // Whether the requester holds a session at all, so a public page (the hosted form's
286
+ // error page, for one) can tell a mailbox owner from an admin without reading
287
+ // authData, which describes the instance rather than the requester
288
+ const isAuthenticated = !!(request.auth && request.auth.isAuthenticated);
289
+
290
+ return {
291
+ // the per-request CSP nonce every inline <script> carries (lib/security-headers.js)
292
+ cspNonce: request.app.cspNonce,
293
+ pageBrandName: pageBrandName || 'EmailEngine',
294
+ values: request.payload || {},
295
+ errors: (request.error && request.error.details) || {},
296
+ pendingMessages,
297
+ licenseInfo: request.app.licenseInfo,
298
+ licenseDetails,
299
+ trialPossible: !tract,
300
+ authData,
301
+ isAuthenticated,
302
+ // The dashboard is an admin destination: a link to it belongs on a page only for
303
+ // a requester who holds an admin session, or on an instance with no admin login
304
+ showDashboardLink: isAuthenticated || !(authData && authData.enabled),
305
+ packageData,
306
+ systemAlerts,
307
+ embeddedTemplateHeader,
308
+ embeddedTemplateHtmlHead,
309
+ currentYear: new Date().getFullYear(),
310
+ documentStoreRemoved,
311
+ lastDocumentStoreVersion: LAST_DOCUMENT_STORE_VERSION,
312
+ updateBrowserInfo: !serviceUrl || !language || !timezone,
313
+
314
+ // Suppress large banner warnings when EENGINE_DISABLE_SETUP_WARNINGS is set
315
+ hideLicenseWarning: disableSetupWarnings,
316
+ disableAuthWarning: disableSetupWarnings,
317
+
318
+ mainServiceUrl: serviceUrl,
319
+ notificationBaseUrl,
320
+
321
+ userLocale: locale,
322
+ userTimezone: timezone,
323
+
324
+ templateLocale: request.app.locale
325
+ };
326
+ }
327
+
328
+ module.exports = { buildViewContext, buildSystemAlerts, resolveAuthDisplay, licenseDetailsView, CONTEXT_SETTINGS };
@@ -1,122 +1,43 @@
1
1
  'use strict';
2
2
 
3
- // Registrable-domain lookup against the Public Suffix List (https://publicsuffix.org/list/), in
4
- // place of the psl package, whose bundled copy of the list had not been refreshed since its last
5
- // release. The list itself lives in data/public_suffix_list.dat and is refreshed by
6
- // copy-static-files.sh on every `npm run update`.
3
+ // Registrable-domain lookup against the Public Suffix List (https://publicsuffix.org/list/), through
4
+ // tldts, which compiles the list in and releases with every change to it. @postalsys/email-ai-tools
5
+ // already loads the same tldts for its own lookups. Until 2026-11 EmailEngine parsed its own copy of
6
+ // the list (data/public_suffix_list.dat, refreshed by copy-static-files.sh); over all 31 678 names
7
+ // derived from that list's rules, this answers the same.
7
8
  //
8
- // The matching follows the list's own algorithm (https://github.com/publicsuffix/list/wiki/Format):
9
- // an exception rule wins outright, otherwise the matching rule with the most labels does, and a
10
- // name no rule covers falls back to the implicit "*" rule (its last label is the suffix). Both the
11
- // ICANN and the private section are used, as psl did.
9
+ // Both the ICANN and the private section count (allowPrivateDomains), as they always did here.
12
10
 
13
- const fs = require('fs');
14
- const pathlib = require('path');
15
- const net = require('net');
16
- const { domainToASCII } = require('url');
11
+ const { getDomain } = require('tldts');
17
12
 
18
- const LIST_PATH = pathlib.join(__dirname, '..', '..', 'data', 'public_suffix_list.dat');
19
-
20
- /**
21
- * @param {string} text The list in its published format
22
- * @returns {{ exact: Set<string>, wildcard: Set<string>, exception: Set<string> }} Rules in ASCII
23
- * (punycode) form; `wildcard` holds the parent of each "*." rule, which `exact` holds as well
24
- */
25
- function parseList(text) {
26
- const rules = { exact: new Set(), wildcard: new Set(), exception: new Set() };
27
-
28
- for (let line of text.split('\n')) {
29
- // a rule is the first whitespace-delimited token of a line that is not a comment
30
- line = line.trim().split(/\s/)[0];
31
- if (!line || line.startsWith('//')) {
32
- continue;
33
- }
34
-
35
- let set = rules.exact;
36
- if (line.startsWith('!')) {
37
- set = rules.exception;
38
- line = line.slice(1);
39
- } else if (line.startsWith('*.')) {
40
- set = rules.wildcard;
41
- line = line.slice(2);
42
- }
43
-
44
- const rule = domainToASCII(line) || line.toLowerCase();
45
- set.add(rule);
46
-
47
- // The parent of a wildcard rule counts as a public suffix of its own, as it does in psl and
48
- // libpsl: "*.kawasaki.jp" makes "kawasaki.jp" no more registrable than "foo.kawasaki.jp"
49
- if (set === rules.wildcard) {
50
- rules.exact.add(rule);
51
- }
52
- }
53
-
54
- return rules;
55
- }
56
-
57
- let defaultRules = null;
13
+ // Full stops other scripts use, which URL host parsing folds into "."
14
+ const FULL_STOPS = /[\u3002\uff0e\uff61]/g;
58
15
 
59
16
  /**
60
17
  * Returns the registrable domain of a host name: the public suffix plus one label, e.g.
61
18
  * "example.co.uk" for "imap.mail.example.co.uk".
62
19
  *
63
20
  * @param {string} host
64
- * @param {Object} [rules] Parsed rules, the bundled list when omitted
65
- * @returns {string|null} The registrable domain in the spelling of the input (lower-cased), or null
66
- * for an IP address, an invalid name, or a name that is itself a public suffix
21
+ * @returns {string|null} The registrable domain in the spelling of the input (lower-cased, an IDN
22
+ * stays in Unicode), or null for an IP address, an invalid name, or a name that is itself a
23
+ * public suffix
67
24
  */
68
- function getRegistrableDomain(host, rules) {
25
+ function getRegistrableDomain(host) {
69
26
  if (typeof host !== 'string') {
70
27
  return null;
71
28
  }
72
29
 
73
- host = host.trim().toLowerCase().replace(/\.$/, '');
74
- if (!host || net.isIP(host.replace(/^\[|\]$/g, ''))) {
75
- return null;
76
- }
77
-
78
- const ascii = domainToASCII(host);
79
- if (!ascii) {
80
- return null;
81
- }
82
-
83
- const labels = ascii.split('.');
84
- if (labels.some(label => !label)) {
85
- return null;
86
- }
87
-
88
- if (!rules) {
89
- defaultRules = defaultRules || parseList(fs.readFileSync(LIST_PATH, 'utf-8'));
90
- rules = defaultRules;
91
- }
92
-
93
- // number of labels in the public suffix
94
- let suffixLength = 0;
95
-
96
- for (let i = 0; i < labels.length && !suffixLength; i++) {
97
- // an exception marks its own name as registrable: the suffix is one label shorter
98
- if (rules.exception.has(labels.slice(i).join('.'))) {
99
- suffixLength = labels.length - i - 1;
100
- }
101
- }
102
-
103
- for (let i = 0; i < labels.length && !suffixLength; i++) {
104
- if (rules.exact.has(labels.slice(i).join('.')) || (i + 1 < labels.length && rules.wildcard.has(labels.slice(i + 1).join('.')))) {
105
- suffixLength = labels.length - i;
106
- }
107
- }
108
-
109
- suffixLength = suffixLength || 1;
110
-
111
- if (labels.length <= suffixLength) {
30
+ // tldts handles case, surrounding whitespace, a trailing dot and IP addresses itself, but reads
31
+ // an ideographic full stop as part of a label and skips an empty one
32
+ host = host.trim().replace(FULL_STOPS, '.').replace(/\.$/, '');
33
+ if (!host || host.split('.').some(label => !label)) {
112
34
  return null;
113
35
  }
114
36
 
115
- // Answer in the caller's spelling (an IDN stays in Unicode) when the label counts line up, which
116
- // they do unless the input used an ideographic full stop that domainToASCII folded into a dot
117
- const original = host.split('.');
118
- const source = original.length === labels.length ? original : labels;
119
- return source.slice(-(suffixLength + 1)).join('.');
37
+ // validateHostname is off because the callers pass names they did not choose (DKIM domains,
38
+ // configured server hosts), and a label with an underscore or a leading hyphen still has a
39
+ // registrable domain
40
+ return getDomain(host, { allowPrivateDomains: true, validateHostname: false }) || null;
120
41
  }
121
42
 
122
- module.exports = { getRegistrableDomain, parseList, LIST_PATH };
43
+ module.exports = { getRegistrableDomain };
@@ -58,12 +58,20 @@ const MAX_ANALYZE_CHARS = 256 * 1024;
58
58
  // EENGINE_DISABLE_THREAD_COLLAPSE, which wins when set (lib/env-setting-overrides.js). Read per
59
59
  // message through that module's short cache, so a change applies without a restart.
60
60
 
61
- // Base styles for messages that only have a plain text body. mimeHtml() applies the same block
62
- // whenever it converts text to HTML itself; once a collapse marker is involved the conversion happens
63
- // here instead, so the styling has to travel with it, or a plain text reply would lose its quote
64
- // colouring the moment it became collapsible. juice inlines the block and the sanitizer drops the tag.
65
- // Taken from the package rather than kept as a copy, which had already drifted from it.
66
- const PLAINTEXT_STYLE_BLOCK = textTools.INLINE_STYLE_BLOCK;
61
+ // Base styles for messages that only have a plain text body: the quote colouring of the package's
62
+ // block, without its fixed font. Web-safe HTML is embedded in a host page, where a hard-coded
63
+ // 12px sans-serif made a plain text message the one thing on the page in another font and size;
64
+ // without the rule the message takes the host's. The conversion happens here rather than in
65
+ // mimeHtml(), which would apply the whole block. juice inlines the block and the sanitizer drops the
66
+ // tag. Derived from the package rather than kept as a copy, which had already drifted from it.
67
+ const FIXED_FONT_RULE = /body, td, th, p\s*\{[^}]*\}/;
68
+ const PLAINTEXT_STYLE_BLOCK = textTools.INLINE_STYLE_BLOCK.replace(FIXED_FONT_RULE, '');
69
+
70
+ // A text body as the HTML mimeHtml() is given, styled with the block above
71
+ function plainTextHtml(text) {
72
+ let html = textTools.textToHtml(text);
73
+ return html ? PLAINTEXT_STYLE_BLOCK + html : '';
74
+ }
67
75
 
68
76
  // Table internals can not host a wrapper element. A <details> opened between table cells is
69
77
  // foster-parented out of the table by the HTML parser, which would leave the content behind and
@@ -247,6 +255,7 @@ function collapseText(text, offset) {
247
255
  return null;
248
256
  }
249
257
 
258
+ // the block goes first even when the head converts to nothing, so the folded quotes keep their colours
250
259
  return (
251
260
  PLAINTEXT_STYLE_BLOCK +
252
261
  textTools.textToHtml(text.slice(0, offset)) +
@@ -431,7 +440,10 @@ async function messageWebSafeHtml(messageData) {
431
440
  messageData = Object.assign({}, messageData, { text: Object.assign({}, messageData.text, { html }) });
432
441
  }
433
442
 
434
- let source = { html, text: messageData.text.plain };
443
+ // A text body is converted here, so it gets the style block without the fixed font. The text
444
+ // stays beside it for mimeHtml()'s fallback on input it refuses to process.
445
+ let text = messageData.text.plain;
446
+ let source = { html: html || !text ? html : plainTextHtml(text), text };
435
447
 
436
448
  const { disableThreadCollapse } = await getOverridableSettings('disableThreadCollapse');
437
449
  if (!disableThreadCollapse) {
@@ -512,6 +524,7 @@ function applyWebSafeHtmlOptions(options) {
512
524
 
513
525
  module.exports = {
514
526
  WEB_SAFE_HTML_MAX_INPUT,
527
+ PLAINTEXT_STYLE_BLOCK,
515
528
  createMimeHtmlLoader,
516
529
  messageWebSafeHtml,
517
530
  webSafeTextResponse,
@@ -0,0 +1,82 @@
1
+ 'use strict';
2
+
3
+ // Which dashboard counters a worker's `metrics` message bumps. The message handler lives in
4
+ // server.js, which cannot be loaded by a test (it starts the whole application on require), so
5
+ // the decision is kept here, pure, and test/worker-metrics-test.js covers it.
6
+
7
+ const { MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, CONNECT_ERROR_NOTIFY } = require('./consts');
8
+
9
+ // The events that also count towards the instance-wide stats, not only the account's own
10
+ const COUNTED_EVENTS = new Set([MESSAGE_NEW_NOTIFY, MESSAGE_DELETED_NOTIFY, CONNECT_ERROR_NOTIFY]);
11
+
12
+ /**
13
+ * Resolves the counters a `metrics` message from a worker updates.
14
+ *
15
+ * @param {Object} message - the worker message (`key`, `args`, `meta`)
16
+ * @returns {{account: (String|undefined), statUpdateKey: (String|false), accountUpdateKey: (String|false)}}
17
+ * `statUpdateKey` names the instance-wide stats counter, `accountUpdateKey` the per-account one;
18
+ * false when there is none
19
+ */
20
+ function resolveMetricKeys(message) {
21
+ let statUpdateKey = false;
22
+ let accountUpdateKey = false;
23
+
24
+ let { account } = message.meta || {};
25
+
26
+ switch (message.key) {
27
+ case 'webhooks': {
28
+ let { status } = message.args[0] || {};
29
+ statUpdateKey = `${message.key}:${status}`;
30
+ break;
31
+ }
32
+
33
+ case 'events': {
34
+ let { event } = message.args[0] || {};
35
+ if (account) {
36
+ accountUpdateKey = `${message.key}:${event}`;
37
+ }
38
+
39
+ // Track specific events
40
+ if (COUNTED_EVENTS.has(event)) {
41
+ statUpdateKey = `${message.key}:${event}`;
42
+ }
43
+ break;
44
+ }
45
+
46
+ case 'apiCall': {
47
+ let { statusCode } = message.args[0] || {};
48
+ let success = statusCode >= 200 && statusCode < 300;
49
+ statUpdateKey = `${message.key}:${success ? 'success' : 'fail'}`;
50
+ break;
51
+ }
52
+
53
+ case 'queuesProcessed': {
54
+ let { queue, status } = message.args[0] || {};
55
+ if (['submit'].includes(queue)) {
56
+ statUpdateKey = `${queue}:${status === 'completed' ? 'success' : 'fail'}`;
57
+ }
58
+ break;
59
+ }
60
+ }
61
+
62
+ return { account, statUpdateKey, accountUpdateKey };
63
+ }
64
+
65
+ /**
66
+ * The Redis hash buckets a stats counter is written to: one hash per UTC day, one field per
67
+ * UTC minute.
68
+ *
69
+ * @param {Date} now
70
+ * @returns {{dateStr: String, timeStr: String}} `YYYYMMDD` and `YYYYMMDDHHmm`
71
+ */
72
+ function statBuckets(now) {
73
+ let iso = now.toISOString();
74
+ return {
75
+ // daily bucket
76
+ dateStr: iso.substr(0, 10).replace(/[^0-9]+/g, ''),
77
+ // minute bucket
78
+ timeStr: iso.substr(0, 16).replace(/[^0-9]+/g, '')
79
+ };
80
+ }
81
+
82
+ module.exports = { resolveMetricKeys, statBuckets };