emailengine-app 2.89.0 → 2.91.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 (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -16,7 +16,8 @@ const {
16
16
  readEnvValue,
17
17
  emitChangeEvent,
18
18
  loadTlsConfig,
19
- assertTlsCredentials
19
+ assertTlsCredentials,
20
+ getMailProxyUrl
20
21
  } = require('../tools');
21
22
  const { getLocalAddress } = require('../utils/network');
22
23
 
@@ -159,10 +160,9 @@ async function onAuth(auth, session) {
159
160
  if (accountData.proxy) {
160
161
  imapConfig.proxy = accountData.proxy;
161
162
  } else {
162
- let proxyUrl = await settings.get('proxyUrl');
163
- let proxyEnabled = await settings.get('proxyEnabled');
164
- if (proxyEnabled && proxyUrl && !imapConfig.proxy) {
165
- imapConfig.proxy = proxyUrl;
163
+ let mailProxyUrl = await getMailProxyUrl();
164
+ if (mailProxyUrl && !imapConfig.proxy) {
165
+ imapConfig.proxy = mailProxyUrl;
166
166
  }
167
167
  }
168
168
 
@@ -16,6 +16,8 @@
16
16
  * removed when they run out, which is how every earlier release behaved.
17
17
  */
18
18
 
19
+ const { compareVersions, parseVersion } = require('./utils/version');
20
+
19
21
  const HOUR = 60 * 60 * 1000;
20
22
  const DAY = 24 * HOUR;
21
23
 
@@ -154,6 +156,61 @@ function expiredSuspension(subexp, subsusp, now) {
154
156
  return { code: 'SubscriptionInactive', error: 'Subscription inactive', since: new Date(deadline).toISOString() };
155
157
  }
156
158
 
159
+ /**
160
+ * Whether the record of the last successful validation no longer covers this instance, so the
161
+ * scheduled online check is allowed to run. It is covered while the version that validated (kv,
162
+ * hex) is this release or a later one and the record's own expiry (ks, hex ms) has not passed;
163
+ * an unreadable or missing record means checking again, which also rewrites it
164
+ * @param {Object} input
165
+ * @param {string|null} input.kv - the stored validated version
166
+ * @param {string|null} input.ks - the stored record expiry
167
+ * @param {string} input.version - the running version
168
+ * @param {number} input.now
169
+ * @returns {boolean}
170
+ */
171
+ function needsVersionRecheck({ kv, ks, version, now }) {
172
+ if (!ks || typeof ks !== 'string' || new Date(parseInt(ks, 16)) < now) {
173
+ return true;
174
+ }
175
+ let validatedVersion = kv && typeof kv === 'string' ? Buffer.from(kv, 'hex').toString() : null;
176
+ return !(parseVersion(validatedVersion) && compareVersions(version, validatedVersion) <= 0);
177
+ }
178
+
179
+ /**
180
+ * Which license the periodic check concerns, and whether a passed deadline suspends it before
181
+ * the license server is asked
182
+ * @param {Object} licenseInfo - the running license state (`active`, `suspension`, `details`)
183
+ * @param {Object} input
184
+ * @param {number|string|null} input.subexp - the stored deadline
185
+ * @param {string|null} input.subsusp - the stored suspension
186
+ * @param {number} input.now
187
+ * @returns {{subscriptionLicense: boolean, localSuspension: (Object|null)}} subscriptionLicense says
188
+ * the online check applies (a suspended license is still registered and still checked, which is
189
+ * how it resumes); localSuspension is the suspension record to apply now, or null
190
+ */
191
+ function subscriptionCheckState(licenseInfo, { subexp, subsusp, now }) {
192
+ let subscriptionLicense = (licenseInfo.active || !!licenseInfo.suspension) && isSubscriptionLicense(licenseInfo.details);
193
+ let localSuspension = subscriptionLicense && !licenseInfo.suspension ? expiredSuspension(subexp, subsusp, now) : null;
194
+ return { subscriptionLicense, localSuspension };
195
+ }
196
+
197
+ /**
198
+ * What a license check does to the licensed workers
199
+ * @param {boolean} licenseActive
200
+ * @param {number} suspendedTypes - how many worker types are suspended now
201
+ * @returns {'suspend'|'resume'|null} suspend every licensed worker type, respawn the suspended
202
+ * ones, or leave them as they are
203
+ */
204
+ function workerSuspensionChange(licenseActive, suspendedTypes) {
205
+ if (!licenseActive && !suspendedTypes) {
206
+ return 'suspend';
207
+ }
208
+ if (licenseActive && suspendedTypes) {
209
+ return 'resume';
210
+ }
211
+ return null;
212
+ }
213
+
157
214
  /**
158
215
  * What a start of EmailEngine does before any worker runs
159
216
  * @param {Object} input
@@ -230,6 +287,9 @@ module.exports = {
230
287
  decide,
231
288
  startupPlan,
232
289
  expiredSuspension,
290
+ needsVersionRecheck,
291
+ subscriptionCheckState,
292
+ workerSuspensionChange,
233
293
  checkInterval,
234
294
  subscriptionView,
235
295
  isSuspended,
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ // Loads `.env` from the working directory into process.env with Node's own parser
4
+ // (process.loadEnvFile, Node 21.7+), which replaced the dotenv package. Variables that are
5
+ // already set are never overwritten, the same as dotenv did.
6
+ //
7
+ // Dependency-free on purpose: server.js loads it before it checks the Node.js version, so it has
8
+ // to load on any release. On a release without process.loadEnvFile it does nothing, and the
9
+ // version check that follows tells the operator to upgrade.
10
+
11
+ /**
12
+ * Loads an env file, if there is one.
13
+ *
14
+ * A missing file is the normal case and is silent. A file that exists but cannot be read is
15
+ * reported on stderr and otherwise ignored, as dotenv ignored it: the instance then starts with
16
+ * the environment it was given rather than not at all.
17
+ *
18
+ * @param {string} [path='.env'] Resolved against the working directory
19
+ * @returns {boolean} Whether a file was loaded
20
+ */
21
+ function loadEnvFile(path = '.env') {
22
+ if (typeof process.loadEnvFile !== 'function') {
23
+ return false;
24
+ }
25
+ try {
26
+ process.loadEnvFile(path);
27
+ return true;
28
+ } catch (err) {
29
+ if (err.code !== 'ENOENT') {
30
+ process.stderr.write(`Could not load ${path}: ${err.message}\n`);
31
+ }
32
+ return false;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Loads `.env` once per process, however many modules ask. A worker thread starts with a copy of
38
+ * the main thread's process.env, marker included, so it does not load the file again; the tests set
39
+ * the marker themselves to keep a developer's own .env out of a child process.
40
+ */
41
+ function loadEnvOnce() {
42
+ if (!process.env.EE_ENV_LOADED) {
43
+ loadEnvFile();
44
+ process.env.EE_ENV_LOADED = 'true';
45
+ }
46
+ }
47
+
48
+ module.exports = { loadEnvFile, loadEnvOnce };
@@ -45,4 +45,40 @@ const REDACTED_LOG_KEYS = [
45
45
  'err.input'
46
46
  ];
47
47
 
48
- module.exports = { REDACTED_LOG_KEYS, TRANSIENT_NETWORK_CODES };
48
+ // An RFC 9110 field name (token). Anything else, such as an entry written as "Name: value", is
49
+ // refused rather than turned into a redaction path that never matches.
50
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9a-z-]+$/;
51
+
52
+ /**
53
+ * Turns the EENGINE_LOG_REDACT_HEADERS value into redaction paths for the request headers it lists.
54
+ * Node lowercases incoming header names, so the names are matched lowercase.
55
+ *
56
+ * @param {string} [value] - Comma-separated header names
57
+ * @returns {string[]} pino redaction paths, one per distinct name
58
+ * @throws {Error} code `EnvValueInvalid` for an entry that is not a header name. The message names
59
+ * the position of the entry, never its text: an entry written as "Name: value" carries the very
60
+ * secret the variable exists to keep out of the log.
61
+ */
62
+ function parseRedactHeaders(value) {
63
+ const names = new Set();
64
+ const entries = (value || '').split(',').map(entry => entry.trim().toLowerCase());
65
+ entries.forEach((name, i) => {
66
+ if (!name) {
67
+ return;
68
+ }
69
+ if (!HEADER_NAME.test(name)) {
70
+ const error = new Error(`EENGINE_LOG_REDACT_HEADERS: entry ${i + 1} is not a valid header name`);
71
+ error.code = 'EnvValueInvalid';
72
+ throw error;
73
+ }
74
+ names.add(name);
75
+ });
76
+ return [...names].map(name => `req.headers["${name}"]`);
77
+ }
78
+
79
+ // Read from process.env directly, not through readEnvValue(), because that helper logs through
80
+ // lib/logger.js, which loads this module. The main process resolves the _FILE form into
81
+ // process.env before anything loads the logger (see resolveEnvFiles()), and worker threads inherit it.
82
+ REDACTED_LOG_KEYS.push(...parseRedactHeaders(process.env.EENGINE_LOG_REDACT_HEADERS));
83
+
84
+ module.exports = { REDACTED_LOG_KEYS, TRANSIENT_NETWORK_CODES, parseRedactHeaders };
package/lib/logger.js CHANGED
@@ -1,9 +1,6 @@
1
1
  'use strict';
2
2
 
3
- if (!process.env.EE_ENV_LOADED) {
4
- require('dotenv').config({ quiet: true });
5
- process.env.EE_ENV_LOADED = 'true';
6
- }
3
+ require('./load-env').loadEnvOnce();
7
4
 
8
5
  const config = require('@zone-eu/wild-config');
9
6
  const pino = require('pino');
@@ -0,0 +1,157 @@
1
+ 'use strict';
2
+
3
+ // Checks whether a host runs a mail server, for the last autodiscovery stage: a domain that
4
+ // publishes nothing about its mail is often served by its MX host or an `imap.`/`smtp.` name, and
5
+ // the only way to tell is to connect and see what answers.
6
+ //
7
+ // The probe sends nothing but a TLS ClientHello and reads the first line the server volunteers. It
8
+ // never logs in and never writes to the stream, so a host that is not a mail server sees an
9
+ // ordinary TLS connection that closes.
10
+
11
+ const dns = require('dns').promises;
12
+ const tls = require('tls');
13
+ const { proxyConnection, detachEarlyErrorHandler } = require('imapflow/lib/proxy-connection.js');
14
+ const { assertAllowedUrl, createEgressLookup } = require('./egress-filter');
15
+ const { WEBHOOK_EGRESS_POLICY } = require('./webhook-egress');
16
+ const logger = require('./logger');
17
+
18
+ // Budget of one probe: name lookup, proxy negotiation, handshake and the greeting line. Short
19
+ // enough that the IMAP and the SMTP round of the fallback stage both fit its time budget.
20
+ const PROBE_TIMEOUT = 2 * 1000;
21
+
22
+ // A greeting is one line; a server that sends more than this without a newline is not one
23
+ const MAX_GREETING = 512;
24
+
25
+ // Keyed by port: 993 is IMAP over implicit TLS, 465 is SMTP submission over implicit TLS
26
+ const PROTOCOLS = {
27
+ 993: { greeting: /^\* (?:OK|PREAUTH)\b/i, silentIsEnough: false },
28
+ // SMTP servers commonly hold the greeting back for several seconds to catch clients that talk
29
+ // first, longer than this probe waits. A completed handshake with a certificate valid for the
30
+ // name is then the answer on the submission port, where nothing but a mail server listens.
31
+ 465: { greeting: /^220[ -]/, silentIsEnough: true }
32
+ };
33
+
34
+ const probeLogger = logger.child({ component: 'mail-probe' });
35
+
36
+ const resolveAll = hostname => dns.lookup(hostname, { all: true });
37
+
38
+ /**
39
+ * Opens the TLS connection and checks the certificate against the probed name.
40
+ *
41
+ * The probe's destinations come from the address domain's DNS, which a caller controls, so the
42
+ * autodiscovery egress policy applies. Directly, the policy-bound lookup is also the one the socket
43
+ * connects with, so the addresses vetted are the addresses connected to. Behind a proxy the proxy
44
+ * resolves the name again, so only the up-front check applies - the same rules, and the same
45
+ * limitation, as the HTTP lookups of autodiscovery.
46
+ */
47
+ async function openTls(host, port, ctx) {
48
+ const policy = ctx.egressPolicy || WEBHOOK_EGRESS_POLICY;
49
+ const resolve = ctx.resolve || resolveAll;
50
+ const tlsOptions = Object.assign({ servername: host }, ctx.tlsOptions || {});
51
+ // Tests point the well-known ports at local servers; production never sets this
52
+ const connectPort = (ctx.ports && ctx.ports[port]) || port;
53
+
54
+ // Up front on both paths: a candidate can be an address literal (an MX or CNAME record may name
55
+ // `127.0.0.1` outright), and net.connect skips the lookup below for a literal
56
+ await assertAllowedUrl(`https://${host}:${connectPort}/`, { policy, resolve });
57
+
58
+ if (!ctx.proxyUrl) {
59
+ return tls.connect(Object.assign({ host, port: connectPort, lookup: createEgressLookup(policy, { resolve }) }, tlsOptions));
60
+ }
61
+
62
+ const socket = await proxyConnection(probeLogger, ctx.proxyUrl, host, connectPort, { connectionTimeout: ctx.timeout || PROBE_TIMEOUT });
63
+ if (!socket) {
64
+ throw new Error('Unsupported proxy protocol');
65
+ }
66
+ const secure = tls.connect(Object.assign({ socket }, tlsOptions));
67
+ // The TLS socket owns the raw one from here, and the error handler in readGreeting() covers both
68
+ detachEarlyErrorHandler(socket);
69
+ return secure;
70
+ }
71
+
72
+ /**
73
+ * Waits for the server's first line on an open TLS socket, and closes it either way.
74
+ *
75
+ * @returns {Promise<boolean>} Whether the line is the protocol's greeting
76
+ */
77
+ function readGreeting(socket, protocol, timeout, signal) {
78
+ return new Promise(resolve => {
79
+ let settled = false;
80
+ let received = '';
81
+ let handshake = false;
82
+
83
+ const finish = result => {
84
+ if (settled) {
85
+ return;
86
+ }
87
+ settled = true;
88
+ clearTimeout(timer);
89
+ if (signal) {
90
+ signal.removeEventListener('abort', onAbort);
91
+ }
92
+ socket.destroy();
93
+ resolve(result);
94
+ };
95
+ const onAbort = () => finish(false);
96
+
97
+ // A wall-clock limit rather than the socket's idle timeout, which a server trickling a byte
98
+ // at a time would keep resetting
99
+ const timer = setTimeout(() => finish(handshake && protocol.silentIsEnough), timeout);
100
+ timer.unref();
101
+
102
+ // A blocked address, a refused connection and a certificate that does not cover the name
103
+ // all land here
104
+ socket.on('error', () => finish(false));
105
+ socket.on('close', () => finish(false));
106
+
107
+ if (signal) {
108
+ if (signal.aborted) {
109
+ return finish(false);
110
+ }
111
+ signal.addEventListener('abort', onAbort, { once: true });
112
+ }
113
+
114
+ socket.on('secureConnect', () => {
115
+ handshake = true;
116
+ });
117
+ socket.setEncoding('utf-8');
118
+ socket.on('data', chunk => {
119
+ received += chunk;
120
+ if (received.includes('\n') || received.length > MAX_GREETING) {
121
+ finish(protocol.greeting.test(received));
122
+ }
123
+ });
124
+ });
125
+ }
126
+
127
+ /**
128
+ * Connects to a host over implicit TLS and checks the first line the server sends.
129
+ *
130
+ * @param {string} host - Name to probe
131
+ * @param {number} port - 993 for IMAP, 465 for SMTP
132
+ * @param {Object} [ctx] - `{ signal, proxyUrl }`, plus for tests `resolve` (a `dns.lookup`
133
+ * stand-in answering `[{ address, family }]`), `egressPolicy`, `tlsOptions` (merged into the TLS
134
+ * connect options), `ports` (993/465 mapped to other ports) and `timeout`
135
+ * @returns {Promise<boolean>} Whether a mail server of that protocol answered for the name
136
+ */
137
+ async function probeMailServer(host, port, ctx) {
138
+ ctx = ctx || {};
139
+ const protocol = PROTOCOLS[port];
140
+ if (!protocol) {
141
+ throw new Error(`No probe for port ${port}`);
142
+ }
143
+ if (ctx.signal && ctx.signal.aborted) {
144
+ return false;
145
+ }
146
+
147
+ let socket;
148
+ try {
149
+ socket = await openTls(host, port, ctx);
150
+ } catch (err) {
151
+ return false;
152
+ }
153
+
154
+ return await readGreeting(socket, protocol, ctx.timeout || PROBE_TIMEOUT, ctx.signal);
155
+ }
156
+
157
+ module.exports = { probeMailServer };