emailengine-app 2.79.9 → 2.80.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +73 -0
  3. package/README.md +6 -0
  4. package/config/default.toml +5 -1
  5. package/data/google-crawlers.json +1 -1
  6. package/encrypt.js +43 -0
  7. package/lib/account/account-state.js +62 -0
  8. package/lib/account.js +34 -2
  9. package/lib/api-routes/account-routes.js +101 -1
  10. package/lib/api-routes/blocklist-routes.js +24 -0
  11. package/lib/api-routes/delivery-test-routes.js +6 -0
  12. package/lib/api-routes/gateway-routes.js +30 -0
  13. package/lib/api-routes/index.js +1 -1
  14. package/lib/api-routes/license-routes.js +10 -0
  15. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  16. package/lib/api-routes/mcp-routes.js +39 -21
  17. package/lib/api-routes/oauth2-app-routes.js +38 -1
  18. package/lib/api-routes/outbox-routes.js +6 -0
  19. package/lib/api-routes/permission-map.js +208 -43
  20. package/lib/api-routes/pubsub-routes.js +8 -0
  21. package/lib/api-routes/route-helpers.js +58 -11
  22. package/lib/api-routes/settings-routes.js +67 -6
  23. package/lib/api-routes/stats-routes.js +6 -0
  24. package/lib/api-routes/template-routes.js +21 -0
  25. package/lib/api-routes/token-routes.js +34 -2
  26. package/lib/api-routes/webhook-route-routes.js +13 -0
  27. package/lib/autodetect-imap-settings.js +349 -47
  28. package/lib/cert-handler.js +62 -0
  29. package/lib/consts.js +50 -6
  30. package/lib/db.js +12 -0
  31. package/lib/egress-fetch.js +21 -9
  32. package/lib/email-client/base-client.js +238 -67
  33. package/lib/email-client/credential-errors.js +122 -0
  34. package/lib/email-client/gmail/gmail-api.js +2 -1
  35. package/lib/email-client/gmail-client.js +70 -64
  36. package/lib/email-client/imap/connection-errors.js +52 -0
  37. package/lib/email-client/imap/listing-diff.js +47 -6
  38. package/lib/email-client/imap/login-failure.js +52 -0
  39. package/lib/email-client/imap/mailbox.js +457 -379
  40. package/lib/email-client/imap/subconnection.js +17 -12
  41. package/lib/email-client/imap/sync-operations.js +46 -59
  42. package/lib/email-client/imap-client.js +139 -101
  43. package/lib/email-client/message-builder.js +11 -11
  44. package/lib/email-client/outlook/graph-api.js +2 -1
  45. package/lib/email-client/outlook-client.js +219 -106
  46. package/lib/enum-descriptions.js +12 -2
  47. package/lib/imap-proxy-auth.js +58 -3
  48. package/lib/imapproxy/imap-server.js +53 -62
  49. package/lib/lua/h-del-if-equals.lua +39 -0
  50. package/lib/lua/h-set-if-equals.lua +39 -0
  51. package/lib/mcp/oauth.js +46 -8
  52. package/lib/mcp/protocol.js +78 -35
  53. package/lib/mcp/tools.js +53 -17
  54. package/lib/privileged-settings.js +147 -0
  55. package/lib/routes-ui.js +4 -34
  56. package/lib/schemas.js +92 -16
  57. package/lib/security-headers.js +15 -0
  58. package/lib/settings.js +13 -0
  59. package/lib/tls/catalog.js +428 -0
  60. package/lib/tls/context.js +302 -0
  61. package/lib/tls/der.js +223 -0
  62. package/lib/tls/listeners.js +62 -0
  63. package/lib/tls/provision.js +555 -0
  64. package/lib/tls/self-signed.js +282 -0
  65. package/lib/tls/status.js +480 -0
  66. package/lib/tls/store.js +667 -0
  67. package/lib/token-permission-view.js +252 -102
  68. package/lib/token-permissions.js +176 -26
  69. package/lib/tokens.js +7 -6
  70. package/lib/tools.js +73 -27
  71. package/lib/ui-routes/account-routes.js +43 -30
  72. package/lib/ui-routes/admin-config-routes.js +63 -22
  73. package/lib/ui-routes/admin-entities-routes.js +23 -13
  74. package/lib/ui-routes/auth-routes.js +16 -1
  75. package/lib/ui-routes/internals-routes.js +3 -5
  76. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  77. package/lib/ui-routes/network-config-routes.js +54 -45
  78. package/lib/ui-routes/tls-config-routes.js +628 -0
  79. package/lib/utils/mailbox-path.js +51 -0
  80. package/lib/utils/severity.js +31 -0
  81. package/package.json +12 -12
  82. package/sbom.json +1 -1
  83. package/server.js +23 -1
  84. package/static/css/flyonui.css +1 -1
  85. package/static/css/src/app.tailwind.css +11 -0
  86. package/static/js/app.js +34 -0
  87. package/static/js/public.js +6 -2
  88. package/static/js/ui.js +97 -61
  89. package/static/licenses.html +341 -1252
  90. package/translations/messages.pot +62 -56
  91. package/views/account/login-redirect.hbs +22 -0
  92. package/views/account/passkeys.hbs +2 -2
  93. package/views/accounts/account.hbs +2 -2
  94. package/views/accounts/browse.hbs +1 -1
  95. package/views/accounts/edit.hbs +1 -1
  96. package/views/accounts/register/imap-server.hbs +1 -1
  97. package/views/config/ai.hbs +1 -1
  98. package/views/config/branding.hbs +2 -2
  99. package/views/config/document-store/chat.hbs +1 -1
  100. package/views/config/document-store/index.hbs +1 -1
  101. package/views/config/imap-proxy.hbs +1 -4
  102. package/views/config/license.hbs +1 -1
  103. package/views/config/mcp.hbs +88 -52
  104. package/views/config/network.hbs +1 -1
  105. package/views/config/oauth/app.hbs +2 -2
  106. package/views/config/service.hbs +1 -1
  107. package/views/config/smtp.hbs +1 -4
  108. package/views/config/tls-upload.hbs +81 -0
  109. package/views/config/tls.hbs +593 -0
  110. package/views/config/webhooks.hbs +2 -2
  111. package/views/internals/index.hbs +1 -1
  112. package/views/layout/app.hbs +6 -6
  113. package/views/layout/login.hbs +5 -5
  114. package/views/layout/main.hbs +2 -2
  115. package/views/layout/prompt.hbs +3 -3
  116. package/views/layout/public.hbs +1 -1
  117. package/views/mcp/authorize.hbs +47 -45
  118. package/views/partials/ace_assets.hbs +1 -1
  119. package/views/partials/add_account_modal.hbs +1 -1
  120. package/views/partials/filter_editor_js.hbs +2 -2
  121. package/views/partials/gateway_js.hbs +1 -1
  122. package/views/partials/mcp_access_levels.hbs +16 -9
  123. package/views/partials/mcp_tool_count.hbs +15 -14
  124. package/views/partials/oauth_form.hbs +1 -1
  125. package/views/partials/public_theme_init.hbs +1 -1
  126. package/views/partials/side_menu.hbs +1 -0
  127. package/views/partials/template_form.hbs +1 -1
  128. package/views/partials/theme_init.hbs +1 -1
  129. package/views/partials/tls_security_card.hbs +25 -53
  130. package/views/partials/ui/alert-banner.hbs +3 -2
  131. package/views/partials/ui/badge.hbs +6 -2
  132. package/views/partials/ui/btn.hbs +5 -2
  133. package/views/partials/webhooks_editor_functions.hbs +1 -1
  134. package/views/reference/index.hbs +1 -1
  135. package/views/reference/redirect.hbs +1 -1
  136. package/views/reference/tag.hbs +1 -1
  137. package/views/reference/token.hbs +1 -1
  138. package/views/templates/template.hbs +1 -1
  139. package/views/tokens/new.hbs +175 -74
  140. package/views/unsubscribe.hbs +1 -1
  141. package/views/webhooks/webhook.hbs +1 -1
  142. package/workers/api.js +102 -142
  143. package/workers/imap-proxy.js +4 -1
  144. package/workers/smtp.js +51 -44
  145. package/views/partials/tls_security_js.hbs +0 -64
  146. package/views/partials/tls_security_modal.hbs +0 -22
@@ -0,0 +1,282 @@
1
+ 'use strict';
2
+
3
+ // Builds the self-signed certificate a TLS listener falls back to.
4
+ //
5
+ // EmailEngine used to promise this and not do it: the admin UI showed a "Self-signed" badge and
6
+ // said one would be used, while nothing anywhere generated one. What actually happened once the
7
+ // built-in key pairs were removed from smtp-server and imap-core (they shipped in every copy of
8
+ // those libraries, so a listener "secured" by one was readable by anyone) is that a TLS listener
9
+ // with no certificate refused to start, and the worker crash-looped. The promise is kept here
10
+ // instead of withdrawn, because the alternative to a warning badge is an outage.
11
+ //
12
+ // This certificate is generated on the instance, is unique to it, and its key is encrypted at rest
13
+ // like every other secret. That is the whole difference from the shipped key pairs, and it is the
14
+ // difference that matters: nobody else has this key. It is still self-signed, so a client either
15
+ // pins the fingerprint the admin UI shows or accepts an unverified certificate. Nothing here
16
+ // claims otherwise.
17
+
18
+ const crypto = require('crypto');
19
+ const net = require('net');
20
+ const punycode = require('punycode.js');
21
+ const { promisify } = require('util');
22
+
23
+ const generateKeyPair = promisify(crypto.generateKeyPair);
24
+
25
+ const {
26
+ sequence,
27
+ set,
28
+ octetString,
29
+ bitString,
30
+ boolean,
31
+ nullValue,
32
+ utf8String,
33
+ explicit,
34
+ implicit,
35
+ integer,
36
+ oid,
37
+ time,
38
+ namedBits,
39
+ ipToBuffer,
40
+ readTlv
41
+ } = require('./der');
42
+
43
+ // RFC 5280 object identifiers, named so the structure below reads like the specification.
44
+ const OID_COMMON_NAME = '2.5.4.3';
45
+ const OID_ORGANIZATION = '2.5.4.10';
46
+ const OID_SHA256_WITH_RSA = '1.2.840.113549.1.1.11';
47
+ const OID_ECDSA_WITH_SHA256 = '1.2.840.10045.4.3.2';
48
+ const OID_EXT_SUBJECT_ALT_NAME = '2.5.29.17';
49
+ const OID_EXT_BASIC_CONSTRAINTS = '2.5.29.19';
50
+ const OID_EXT_KEY_USAGE = '2.5.29.15';
51
+ const OID_EXT_EXT_KEY_USAGE = '2.5.29.37';
52
+ const OID_EXT_SUBJECT_KEY_ID = '2.5.29.14';
53
+ const OID_KP_SERVER_AUTH = '1.3.6.1.5.5.7.3.1';
54
+
55
+ // KeyUsage bit positions.
56
+ const KEY_USAGE_DIGITAL_SIGNATURE = 0;
57
+ const KEY_USAGE_KEY_ENCIPHERMENT = 2;
58
+
59
+ // A year, less than the 398 days the CA/Browser Forum allows a public certificate to live. The
60
+ // value only matters to whoever pinned the fingerprint: a shorter life means more re-pinning, a
61
+ // longer one means a listener that quietly stops working years from now.
62
+ const DEFAULT_VALIDITY_DAYS = 365;
63
+
64
+ // Clock skew allowance. A certificate that is not valid yet fails a handshake exactly like an
65
+ // expired one, and the machine that generates this is often the one with the wrong clock.
66
+ const BACKDATE_MS = 60 * 60 * 1000;
67
+
68
+ const ORGANIZATION = 'EmailEngine self-signed';
69
+
70
+ /**
71
+ * Certificate name with a single Common Name attribute, plus a fixed organization so the origin of
72
+ * the certificate is legible in any inspection tool.
73
+ *
74
+ * The Common Name is vestigial for verification (no TLS client may match on it any more), but an
75
+ * empty subject renders as blank in every UI, so it carries the primary hostname. Its upper bound
76
+ * is 64 characters, which a long hostname can exceed; the name that is actually matched lives in
77
+ * the subjectAltName extension, so truncating here loses nothing.
78
+ *
79
+ * @param {string} commonName Primary hostname
80
+ * @returns {Buffer} Encoded Name
81
+ */
82
+ function encodeName(commonName) {
83
+ return sequence([
84
+ set([sequence([oid(OID_ORGANIZATION), utf8String(ORGANIZATION)])]),
85
+ set([sequence([oid(OID_COMMON_NAME), utf8String(commonName.slice(0, 64))])])
86
+ ]);
87
+ }
88
+
89
+ /**
90
+ * The A-label form of a hostname, which is what goes on the wire. Unchanged for an all-ASCII name.
91
+ *
92
+ * @param {string} hostname Name, possibly internationalized
93
+ * @returns {string} ASCII-compatible encoding
94
+ */
95
+ function toAsciiHostname(hostname) {
96
+ try {
97
+ return punycode.toASCII(hostname);
98
+ } catch (err) {
99
+ return hostname;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * subjectAltName, the extension a TLS client actually matches the hostname against.
105
+ *
106
+ * @param {string[]} hostnames Names and IP addresses to cover
107
+ * @returns {Buffer} Encoded GeneralNames
108
+ */
109
+ function encodeSubjectAltName(hostnames) {
110
+ const entries = [];
111
+
112
+ for (const hostname of hostnames) {
113
+ if (net.isIP(hostname)) {
114
+ const address = ipToBuffer(hostname);
115
+ if (address) {
116
+ entries.push(implicit(7, address));
117
+ }
118
+ continue;
119
+ }
120
+
121
+ // A dNSName is an IA5String, so an internationalized name has to go in as its A-label.
122
+ // Writing the Unicode bytes produces a certificate that parses and matches nothing.
123
+ entries.push(implicit(2, Buffer.from(toAsciiHostname(hostname), 'latin1')));
124
+ }
125
+
126
+ return sequence(entries);
127
+ }
128
+
129
+ /**
130
+ * One Extension of the extensions list.
131
+ *
132
+ * @param {string} extnId Extension OID
133
+ * @param {boolean} critical Whether a client that does not understand it must reject the certificate
134
+ * @param {Buffer} value The extension's own DER
135
+ * @returns {Buffer} Encoded Extension
136
+ */
137
+ function extension(extnId, critical, value) {
138
+ const parts = [oid(extnId)];
139
+ if (critical) {
140
+ parts.push(boolean(true));
141
+ }
142
+ parts.push(octetString(value));
143
+ return sequence(parts);
144
+ }
145
+
146
+ /**
147
+ * The public key bits out of a SubjectPublicKeyInfo, which is what a subject key identifier is the
148
+ * SHA-1 of. SPKI is `SEQUENCE { AlgorithmIdentifier, BIT STRING }`, so this steps over the first
149
+ * element and drops the BIT STRING's unused-bit count.
150
+ *
151
+ * @param {Buffer} spki DER SubjectPublicKeyInfo
152
+ * @returns {Buffer} The public key bit string contents
153
+ */
154
+ function publicKeyBits(spki) {
155
+ const outer = readTlv(spki);
156
+ const algorithm = readTlv(spki, outer.contentStart);
157
+ const keyBits = readTlv(spki, algorithm.end);
158
+ return spki.subarray(keyBits.contentStart + 1, keyBits.end);
159
+ }
160
+
161
+ function toPem(der, label) {
162
+ const body = der.toString('base64').replace(/.{1,64}/g, line => `${line}\n`);
163
+ return `-----BEGIN ${label}-----\n${body}-----END ${label}-----\n`;
164
+ }
165
+
166
+ /**
167
+ * Generates the private key the certificate is signed with.
168
+ *
169
+ * RSA by default, matching the choice @postalsys/certs makes for ACME keys and for the same reason:
170
+ * this key terminates TLS for IMAP and SMTP clients as well as browsers, and RSA is the safer
171
+ * assumption there. Nothing downstream depends on the two being byte-identical - both are read back
172
+ * with crypto.createPrivateKey().
173
+ *
174
+ * @param {string} keyType 'rsa' (default) or 'ec'
175
+ * @returns {Promise<string>} PEM private key
176
+ */
177
+ async function generatePrivateKey(keyType) {
178
+ if (keyType === 'ec') {
179
+ const { privateKey } = await generateKeyPair('ec', {
180
+ namedCurve: 'prime256v1',
181
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
182
+ privateKeyEncoding: { type: 'sec1', format: 'pem' }
183
+ });
184
+ return privateKey;
185
+ }
186
+
187
+ const { privateKey } = await generateKeyPair('rsa', {
188
+ modulusLength: 2048,
189
+ publicExponent: 65537,
190
+ publicKeyEncoding: { type: 'spki', format: 'pem' },
191
+ privateKeyEncoding: { type: 'pkcs1', format: 'pem' }
192
+ });
193
+
194
+ return privateKey;
195
+ }
196
+
197
+ /**
198
+ * Mints a self-signed server certificate.
199
+ *
200
+ * Deliberately a leaf and not a certificate authority: `basicConstraints` says CA:FALSE and there
201
+ * is no keyCertSign. `openssl req -x509` defaults the other way, which makes a certificate that can
202
+ * be dropped into a trust store more readily, but it also mints a certificate that is allowed to
203
+ * sign others - and this key sits on a mail server, not in a safe. Whoever wants to trust it pins
204
+ * the fingerprint.
205
+ *
206
+ * @param {Object} opts
207
+ * @param {string[]} opts.hostnames Names and IP addresses the certificate covers; the first is the subject
208
+ * @param {string} [opts.keyType] 'rsa' (default) or 'ec'
209
+ * @param {number} [opts.validityDays] Lifetime in days
210
+ * @param {string} [opts.privateKey] Reuse an existing PEM key instead of generating one
211
+ * @param {Date} [opts.now] Clock, for tests
212
+ * @returns {Promise<Object>} `{ cert, privateKey, fingerprint, serialNumber, altNames, validFrom, validTo }`
213
+ */
214
+ async function createSelfSignedCertificate(opts) {
215
+ const options = opts || {};
216
+
217
+ const hostnames = []
218
+ .concat(options.hostnames || [])
219
+ .map(hostname => (hostname || '').toString().trim().toLowerCase())
220
+ .filter(hostname => hostname);
221
+
222
+ if (!hostnames.length) {
223
+ throw new Error('Can not generate a certificate without a hostname');
224
+ }
225
+
226
+ const keyType = options.keyType === 'ec' ? 'ec' : 'rsa';
227
+ const privateKeyPem = options.privateKey || (await generatePrivateKey(keyType));
228
+ const privateKey = crypto.createPrivateKey(privateKeyPem);
229
+ const spki = crypto.createPublicKey(privateKey).export({ type: 'spki', format: 'der' });
230
+
231
+ const now = options.now || new Date();
232
+ const validFrom = new Date(now.getTime() - BACKDATE_MS);
233
+ const validTo = new Date(now.getTime() + (options.validityDays || DEFAULT_VALIDITY_DAYS) * 24 * 3600 * 1000);
234
+
235
+ const signatureAlgorithm = keyType === 'ec' ? sequence([oid(OID_ECDSA_WITH_SHA256)]) : sequence([oid(OID_SHA256_WITH_RSA), nullValue()]);
236
+
237
+ // An EC key signs; it never encrypts a key exchange, so keyEncipherment would be a usage the
238
+ // certificate cannot honour.
239
+ const keyUsageBits = keyType === 'ec' ? [KEY_USAGE_DIGITAL_SIGNATURE] : [KEY_USAGE_DIGITAL_SIGNATURE, KEY_USAGE_KEY_ENCIPHERMENT];
240
+
241
+ const name = encodeName(net.isIP(hostnames[0]) ? hostnames[0] : toAsciiHostname(hostnames[0]));
242
+
243
+ const tbsCertificate = sequence([
244
+ // [0] EXPLICIT version, 2 meaning v3. Extensions do not exist before v3.
245
+ explicit(0, integer(2)),
246
+ integer(crypto.randomBytes(16)),
247
+ signatureAlgorithm,
248
+ name,
249
+ sequence([time(validFrom), time(validTo)]),
250
+ name,
251
+ spki,
252
+ explicit(
253
+ 3,
254
+ sequence([
255
+ extension(OID_EXT_BASIC_CONSTRAINTS, true, sequence([])),
256
+ extension(OID_EXT_KEY_USAGE, true, namedBits(keyUsageBits)),
257
+ extension(OID_EXT_EXT_KEY_USAGE, false, sequence([oid(OID_KP_SERVER_AUTH)])),
258
+ extension(OID_EXT_SUBJECT_ALT_NAME, false, encodeSubjectAltName(hostnames)),
259
+ extension(OID_EXT_SUBJECT_KEY_ID, false, octetString(crypto.createHash('sha1').update(publicKeyBits(spki)).digest()))
260
+ ])
261
+ )
262
+ ]);
263
+
264
+ const signature = crypto.sign('sha256', tbsCertificate, privateKey);
265
+ const der = sequence([tbsCertificate, signatureAlgorithm, bitString(signature)]);
266
+
267
+ const cert = toPem(der, 'CERTIFICATE');
268
+ const x509 = new crypto.X509Certificate(cert);
269
+
270
+ return {
271
+ cert,
272
+ privateKey: privateKeyPem,
273
+ keyType,
274
+ serialNumber: x509.serialNumber,
275
+ fingerprint: x509.fingerprint,
276
+ altNames: hostnames,
277
+ validFrom: new Date(x509.validFrom),
278
+ validTo: new Date(x509.validTo)
279
+ };
280
+ }
281
+
282
+ module.exports = { createSelfSignedCertificate, toAsciiHostname };