emailengine-app 2.79.8 → 2.79.9

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 (133) hide show
  1. package/.github/dependabot.yml +22 -0
  2. package/.github/workflows/test.yml +39 -0
  3. package/.release-please-manifest.json +1 -1
  4. package/CHANGELOG.md +20 -0
  5. package/DOCKER_DEPLOYMENT.md +6 -7
  6. package/Dockerfile +35 -11
  7. package/config/default.toml +2 -1
  8. package/copy-static-files.sh +23 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/lib/account.js +26 -1
  11. package/lib/api-routes/bull-board-routes.js +3 -2
  12. package/lib/api-routes/route-helpers.js +8 -0
  13. package/lib/auth-token.js +73 -2
  14. package/lib/autodetect-imap-settings.js +33 -25
  15. package/lib/consts.js +8 -1
  16. package/lib/egress-fetch.js +133 -0
  17. package/lib/export.js +35 -2
  18. package/lib/handlebars-helpers.js +129 -0
  19. package/lib/imap-proxy-auth.js +41 -21
  20. package/lib/imapproxy/imap-core/README.md +1 -0
  21. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  22. package/lib/imapproxy/imap-server.js +9 -10
  23. package/lib/openapi/index.js +3 -0
  24. package/lib/outbox.js +28 -3
  25. package/lib/rate-limit.js +23 -4
  26. package/lib/schemas.js +10 -3
  27. package/lib/security-headers.js +396 -0
  28. package/lib/sentry.js +36 -4
  29. package/lib/smtp-auth.js +86 -7
  30. package/lib/tools.js +265 -120
  31. package/lib/ui-routes/account-routes.js +4 -3
  32. package/lib/ui-routes/export-routes.js +4 -0
  33. package/lib/ui-routes/mcp-consent-routes.js +7 -0
  34. package/lib/ui-routes/network-config-routes.js +4 -3
  35. package/lib/ui-routes/route-helpers.js +24 -8
  36. package/lib/ui-routes/smtp-test-routes.js +7 -0
  37. package/lib/webhook-egress.js +5 -0
  38. package/package.json +21 -24
  39. package/sbom.json +1 -1
  40. package/server.js +37 -36
  41. package/static/js/ace/css/ace.css +1462 -0
  42. package/static/js/ace/css/kuroir-1.png +0 -0
  43. package/static/js/ace/css/kuroir-2.png +0 -0
  44. package/static/js/ace/css/main-1.png +0 -0
  45. package/static/js/ace/css/main-10.svg +4 -0
  46. package/static/js/ace/css/main-11.svg +5 -0
  47. package/static/js/ace/css/main-12.svg +4 -0
  48. package/static/js/ace/css/main-13.png +0 -0
  49. package/static/js/ace/css/main-14.png +0 -0
  50. package/static/js/ace/css/main-15.png +0 -0
  51. package/static/js/ace/css/main-16.png +0 -0
  52. package/static/js/ace/css/main-17.png +0 -0
  53. package/static/js/ace/css/main-18.png +0 -0
  54. package/static/js/ace/css/main-19.png +0 -0
  55. package/static/js/ace/css/main-2.png +0 -0
  56. package/static/js/ace/css/main-20.png +0 -0
  57. package/static/js/ace/css/main-21.png +0 -0
  58. package/static/js/ace/css/main-22.png +0 -0
  59. package/static/js/ace/css/main-23.png +0 -0
  60. package/static/js/ace/css/main-24.png +0 -0
  61. package/static/js/ace/css/main-25.svg +1 -0
  62. package/static/js/ace/css/main-26.png +0 -0
  63. package/static/js/ace/css/main-3.png +0 -0
  64. package/static/js/ace/css/main-4.png +0 -0
  65. package/static/js/ace/css/main-5.svg +7 -0
  66. package/static/js/ace/css/main-6.svg +9 -0
  67. package/static/js/ace/css/main-7.svg +7 -0
  68. package/static/js/ace/css/main-8.svg +9 -0
  69. package/static/js/ace/css/main-9.svg +6 -0
  70. package/static/js/ace/css/theme/kuroir.css +78 -0
  71. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  72. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  73. package/static/js/ace/css/theme/xcode.css +106 -0
  74. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  75. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  76. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  77. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  78. package/static/js/ace/css/xcode-1.png +0 -0
  79. package/static/js/ace/css/xcode-2.png +0 -0
  80. package/static/js/ee-client.js +256 -102
  81. package/static/js/public.js +7 -0
  82. package/static/js/ui.js +32 -0
  83. package/static/licenses.html +331 -291
  84. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  85. package/translations/messages.pot +203 -157
  86. package/views/accounts/account.hbs +15 -37
  87. package/views/accounts/browse.hbs +3 -1
  88. package/views/accounts/edit.hbs +1 -1
  89. package/views/accounts/register/imap-server.hbs +1 -1
  90. package/views/config/ai.hbs +1 -1
  91. package/views/config/branding.hbs +2 -2
  92. package/views/config/document-store/chat.hbs +1 -1
  93. package/views/config/document-store/index.hbs +1 -1
  94. package/views/config/imap-proxy.hbs +1 -1
  95. package/views/config/license.hbs +1 -1
  96. package/views/config/mcp.hbs +1 -1
  97. package/views/config/network.hbs +14 -16
  98. package/views/config/oauth/app.hbs +2 -2
  99. package/views/config/service.hbs +1 -1
  100. package/views/config/smtp.hbs +1 -1
  101. package/views/config/webhooks.hbs +2 -2
  102. package/views/error.hbs +4 -2
  103. package/views/internals/index.hbs +1 -1
  104. package/views/layout/app.hbs +3 -11
  105. package/views/mcp/authorize.hbs +1 -1
  106. package/views/partials/ace_assets.hbs +13 -0
  107. package/views/partials/add_account_modal.hbs +1 -1
  108. package/views/partials/address_list.hbs +4 -4
  109. package/views/partials/filter_editor_js.hbs +2 -2
  110. package/views/partials/gateway_js.hbs +1 -1
  111. package/views/partials/oauth_form.hbs +1 -1
  112. package/views/partials/public_theme_init.hbs +1 -1
  113. package/views/partials/template_form.hbs +2 -2
  114. package/views/partials/test_send.hbs +7 -4
  115. package/views/partials/theme_init.hbs +1 -1
  116. package/views/partials/ui/details.hbs +2 -2
  117. package/views/partials/webhooks_editor_functions.hbs +1 -1
  118. package/views/reference/redirect.hbs +1 -1
  119. package/views/templates/template.hbs +2 -2
  120. package/views/tokens/new.hbs +1 -1
  121. package/views/unsubscribe.hbs +1 -1
  122. package/views/webhooks/webhook.hbs +2 -2
  123. package/workers/api.js +42 -112
  124. package/workers/export.js +1 -5
  125. package/workers/imap.js +1 -3
  126. package/workers/smtp.js +12 -43
  127. package/workers/submit.js +6 -12
  128. package/workers/webhooks.js +6 -17
  129. package/static/front/EmailEngine_logo_horiz.png +0 -0
  130. package/static/front/EmailEngine_logo_vert.png +0 -0
  131. package/static/front/index.html +0 -57
  132. package/static/front/logo.png +0 -0
  133. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
package/lib/schemas.js CHANGED
@@ -289,7 +289,12 @@ const settingsSchema = {
289
289
 
290
290
  /* ────────────── Proxy ────────────── */
291
291
 
292
- proxyEnabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').description('Route outbound connections through a proxy server'),
292
+ proxyEnabled: Joi.boolean()
293
+ .truthy('Y', 'true', '1', 'on')
294
+ .falsy('N', 'false', 0, '')
295
+ .description(
296
+ 'Route all outbound connections through a proxy server: IMAP and SMTP sessions as well as HTTP/HTTPS requests (Gmail API, Microsoft Graph, OAuth2 token exchange, webhooks, license validation) unless a dedicated HTTP proxy is configured'
297
+ ),
293
298
  proxyUrl: Joi.string()
294
299
  .uri({ scheme: ['http', 'https', 'socks', 'socks4', 'socks4a', 'socks5'], allowRelative: false })
295
300
  .allow('')
@@ -302,12 +307,14 @@ const settingsSchema = {
302
307
  httpProxyEnabled: Joi.boolean()
303
308
  .truthy('Y', 'true', '1', 'on')
304
309
  .falsy('N', 'false', 0, '')
305
- .description('Route outbound HTTP/HTTPS requests (webhooks, OAuth, API calls) through an HTTP proxy'),
310
+ .description(
311
+ 'Route outbound HTTP/HTTPS requests (webhooks, OAuth2 token exchange, Gmail API and Microsoft Graph calls, license validation) through a dedicated proxy instead of the global proxy'
312
+ ),
306
313
  httpProxyUrl: Joi.string()
307
314
  .uri({ scheme: ['http', 'https', 'socks', 'socks4', 'socks4a', 'socks5'], allowRelative: false })
308
315
  .allow('')
309
316
  .example('http://proxy.example.com:8080')
310
- .description('HTTP proxy URL for outbound HTTP/HTTPS requests')
317
+ .description('Dedicated proxy URL for outbound HTTP/HTTPS requests. When not set, HTTP/HTTPS requests use the global proxy')
311
318
  .label('HttpProxyURL'),
312
319
 
313
320
  /* ────────────── SMTP ────────────── */
@@ -0,0 +1,396 @@
1
+ 'use strict';
2
+
3
+ // Response headers every HTTP surface sends. Applied from an onPreResponse extension registered
4
+ // AFTER the error-rendering one in workers/api.js, so the rebuilt error page, a redirect and a
5
+ // rendered view all carry them - a header set only on the success path would be missing from
6
+ // exactly the responses an attacker can provoke.
7
+ //
8
+ // Which headers a response gets is decided by its profile, picked from the request path and the
9
+ // route tags:
10
+ //
11
+ // static - /static and the other inert routes. The common set only: a Content-Security-Policy
12
+ // on a script file governs nothing, except when the file is loaded as a worker,
13
+ // and static/js/evaluation-worker.js runs operator code through `new Function`
14
+ // on purpose, so it must not inherit a policy from here.
15
+ // api - /v1, /mcp, /swagger.json, /metrics: machine-facing JSON that must never be
16
+ // rendered or framed.
17
+ // admin - the authenticated console. The strict, nonce-based policy: only scripts the
18
+ // server rendered with the request's nonce run, so markup that reaches the page
19
+ // (the message browser renders sanitised email HTML, the error logs show inbound
20
+ // headers) cannot bring code with it.
21
+ // bullBoard - /admin/bull-board, third-party markup this code does not render: no nonce, and
22
+ // the Google Fonts stylesheet its shell links.
23
+ // public - everything else: the hosted authentication form, unsubscribe, the OAuth landing
24
+ // page, error pages. Operators inject their own HTML into these pages
25
+ // (templateHtmlHead / templateHeader, a documented feature whose own example is
26
+ // an external stylesheet), so the policy allows inline code and https: sources.
27
+ // They also stay frameable: they are meant to be opened from an operator's own
28
+ // application, and nothing in the contract says they must not be embedded there.
29
+ //
30
+ // The CSP preset additionally follows the layout. A view rendered with the public layout on an
31
+ // admin path - the error page, the branding preview - is that same operator-customisable markup
32
+ // and gets the public preset, while `frame-ancestors` stays with the path, so an admin error
33
+ // page is still not frameable elsewhere.
34
+ //
35
+ // Header names are lowercase because that is how hapi stores them on a response; the wire does
36
+ // not care about the case.
37
+
38
+ const crypto = require('crypto');
39
+ const { BULL_BOARD_BASE_PATH } = require('./consts');
40
+
41
+ const CSP_HEADER = 'content-security-policy';
42
+ const CSP_REPORT_ONLY_HEADER = 'content-security-policy-report-only';
43
+
44
+ // One year, this host only. `includeSubDomains` is not ours to decide: an operator running
45
+ // EmailEngine on a subdomain would be signing up every sibling host. `preload` is a manual
46
+ // submission the operator has to make anyway.
47
+ const HSTS_VALUE = 'max-age=31536000';
48
+
49
+ // The browser features no page of this application asks for. Passkeys
50
+ // (publickey-credentials-*) and the clipboard are deliberately absent from the list.
51
+ const PERMISSIONS_POLICY = 'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()';
52
+
53
+ // How the Content-Security-Policy is delivered. `report-only` keeps the framing protection
54
+ // enforced and moves the rest of the policy to the report-only header, so an operator can see
55
+ // in the browser console what a page would lose without losing it; `off` is the pre-CSP state.
56
+ const CSP_MODES = ['enforce', 'report-only', 'off'];
57
+
58
+ // The layout the operator-customisable pages render with (views/layout/public.hbs)
59
+ const PUBLIC_LAYOUT = 'public';
60
+
61
+ // Route tags of the surfaces no browser page is served from. Shared with the CSRF check in
62
+ // workers/api.js, which skips the same routes: a request that carries no browser session has
63
+ // no crumb to present, and a response nobody renders needs no page policy.
64
+ const MACHINE_TAGS = Object.freeze(['api', 'external', 'static']);
65
+
66
+ // A preset's `nonceDirectives` get the request's nonce appended after any route override, so
67
+ // an override of one of them keeps the nonce and a missing nonce fails closed
68
+ const CSP_PRESETS = Object.freeze({
69
+ admin: Object.freeze({
70
+ nonceDirectives: Object.freeze(['script-src', 'style-src-elem']),
71
+ directives: Object.freeze({
72
+ 'default-src': "'self'",
73
+ 'script-src': "'self'",
74
+ // Stylesheets need the nonce like scripts: nothing first-party appends a <style>
75
+ // element (ACE runs with useStrictCSP and links its sheets, the message browser
76
+ // widget is handed the nonce). Style attributes stay allowed: sanitised email HTML
77
+ // arrives with every rule inlined into them, and a style attribute cannot load or
78
+ // run anything the rest of the policy does not already permit. `style-src` is the
79
+ // fallback for a browser that predates the -elem/-attr split.
80
+ 'style-src': "'self' 'unsafe-inline'",
81
+ 'style-src-elem': "'self'",
82
+ 'style-src-attr': "'unsafe-inline'",
83
+ // data: for the icon masks in the stylesheets, the TOTP QR code and embedded cid images
84
+ 'img-src': "'self' data:",
85
+ 'font-src': "'self'",
86
+ 'connect-src': "'self'",
87
+ // ACE loads its syntax workers through blob: URLs; the webhook function editor loads
88
+ // evaluation-worker.js from /static
89
+ 'worker-src': "'self' blob:",
90
+ 'frame-src': "'none'",
91
+ 'object-src': "'none'",
92
+ 'base-uri': "'none'",
93
+ 'form-action': "'self'"
94
+ })
95
+ }),
96
+
97
+ bullBoard: Object.freeze({
98
+ directives: Object.freeze({
99
+ 'default-src': "'self'",
100
+ 'script-src': "'self'",
101
+ 'style-src': "'self' 'unsafe-inline' https://fonts.googleapis.com",
102
+ 'font-src': "'self' https://fonts.gstatic.com",
103
+ 'img-src': "'self' data:",
104
+ 'connect-src': "'self'",
105
+ 'object-src': "'none'",
106
+ // its shell carries a <base href> for the mount path
107
+ 'base-uri': "'self'",
108
+ 'form-action': "'self'"
109
+ })
110
+ }),
111
+
112
+ api: Object.freeze({
113
+ directives: Object.freeze({
114
+ 'default-src': "'none'"
115
+ })
116
+ }),
117
+
118
+ public: Object.freeze({
119
+ directives: Object.freeze({
120
+ 'default-src': "'self' https: data:",
121
+ 'script-src': "'self' https: 'unsafe-inline'",
122
+ 'style-src': "'self' https: 'unsafe-inline'",
123
+ 'img-src': "'self' https: data: blob:",
124
+ 'font-src': "'self' https: data:",
125
+ 'connect-src': "'self' https:",
126
+ 'object-src': "'none'",
127
+ 'base-uri': "'self'",
128
+ // The hosted form answers its POST with a redirect to the provider's authorization
129
+ // page, and Chrome checks the redirect target of a form submission against form-action
130
+ 'form-action': "'self' https:"
131
+ })
132
+ })
133
+ });
134
+
135
+ // Refuses MIME sniffing everywhere. An attachment or export served as application/octet-stream
136
+ // must not be rendered as HTML because the bytes happen to look like it.
137
+ const COMMON_HEADERS = Object.freeze({
138
+ 'x-content-type-options': 'nosniff',
139
+ // Cross-origin requests carry the origin only. The hosted form and the message browser open
140
+ // with signed tokens in the query string, and browsers that predate this default would send
141
+ // the whole URL to any https target linked from the page
142
+ 'referrer-policy': 'strict-origin-when-cross-origin',
143
+ // Nothing here is meant for Flash or Acrobat cross-domain loading
144
+ 'x-permitted-cross-domain-policies': 'none'
145
+ });
146
+
147
+ const PAGE_HEADERS = Object.freeze(
148
+ Object.assign({}, COMMON_HEADERS, {
149
+ 'permissions-policy': PERMISSIONS_POLICY
150
+ })
151
+ );
152
+
153
+ // The admin session cookie is SameSite=Lax and every form posts a crumb, but neither stops a page
154
+ // from being framed - and a framed admin page carries a valid crumb, so a click inside the frame
155
+ // is a real action. `frame-ancestors` is the standard, X-Frame-Options is for the browsers that
156
+ // only read the legacy header. The cross-origin policies keep another origin from holding a
157
+ // reference to an admin window or embedding an admin response.
158
+ const ADMIN_HEADERS = Object.freeze(
159
+ Object.assign({}, PAGE_HEADERS, {
160
+ 'x-frame-options': 'SAMEORIGIN',
161
+ 'cross-origin-opener-policy': 'same-origin',
162
+ 'cross-origin-resource-policy': 'same-origin'
163
+ })
164
+ );
165
+
166
+ const PROFILES = Object.freeze({
167
+ static: Object.freeze({ headers: COMMON_HEADERS, csp: null, frameAncestors: null, cacheControl: null }),
168
+ api: Object.freeze({
169
+ headers: Object.freeze(Object.assign({}, PAGE_HEADERS, { 'x-frame-options': 'DENY' })),
170
+ csp: 'api',
171
+ frameAncestors: "'none'",
172
+ cacheControl: 'no-store'
173
+ }),
174
+ public: Object.freeze({ headers: PAGE_HEADERS, csp: 'public', frameAncestors: null, cacheControl: null }),
175
+ admin: Object.freeze({ headers: ADMIN_HEADERS, csp: 'admin', frameAncestors: "'self'", cacheControl: 'no-store' }),
176
+ bullBoard: Object.freeze({ headers: ADMIN_HEADERS, csp: 'bullBoard', frameAncestors: "'self'", cacheControl: 'no-store' })
177
+ });
178
+
179
+ /**
180
+ * Tells whether a path belongs to the admin surface.
181
+ *
182
+ * Exact `/admin` plus everything under it. `/admin-something` is not admin, and `/v1/...` is the
183
+ * machine-facing API where a framing header changes nothing. Also what the admin address
184
+ * whitelist in workers/api.js keys on, so the two agree on what "the admin surface" is.
185
+ *
186
+ * @param {string} path - Request path
187
+ * @returns {boolean}
188
+ */
189
+ function isAdminPath(path) {
190
+ return path === '/admin' || (typeof path === 'string' && path.startsWith('/admin/'));
191
+ }
192
+
193
+ /**
194
+ * Tells whether a route serves machines rather than browser pages, by its tags.
195
+ *
196
+ * @param {string[]} [tags] - Route tags
197
+ * @returns {boolean}
198
+ */
199
+ function isMachineRoute(tags = []) {
200
+ return tags.some(tag => MACHINE_TAGS.includes(tag));
201
+ }
202
+
203
+ /**
204
+ * Tells whether the instance declares itself served over https - the same signal that gives the
205
+ * session and CSRF cookies their Secure flag, and the one that decides whether HSTS is sent.
206
+ *
207
+ * @param {string} serviceUrl - The `serviceUrl` setting
208
+ * @returns {boolean}
209
+ */
210
+ function isSecureOrigin(serviceUrl) {
211
+ if (!serviceUrl) {
212
+ return false;
213
+ }
214
+ try {
215
+ return new URL(serviceUrl).protocol === 'https:';
216
+ } catch (err) {
217
+ return false;
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Seeds a request with what the headers need later: the nonce its inline scripts carry and
223
+ * whether HSTS applies. Runs at the top of the onRequest extension, before anything can render
224
+ * a view, so the template and the header agree on the nonce.
225
+ *
226
+ * base64url rather than base64: Handlebars escapes `=` in an attribute, and a test comparing
227
+ * the header against the rendered page should not have to know that.
228
+ *
229
+ * @param {Object} request - Hapi request
230
+ * @param {Object} [options]
231
+ * @param {boolean} [options.secureOrigin] - Whether the instance is served over https
232
+ */
233
+ function attachSecurityContext(request, { secureOrigin = false } = {}) {
234
+ request.app.cspNonce = crypto.randomBytes(16).toString('base64url');
235
+ request.app.secureOrigin = !!secureOrigin;
236
+ }
237
+
238
+ /**
239
+ * Picks the header profile for a request.
240
+ *
241
+ * @param {string} path - Request path
242
+ * @param {string[]} [tags] - Route tags
243
+ * @returns {string} Profile name, a key of PROFILES
244
+ */
245
+ function profileNameFor(path, tags = []) {
246
+ path = typeof path === 'string' ? path : '';
247
+
248
+ if (tags.includes('static') || path.startsWith(`${BULL_BOARD_BASE_PATH}/static/`)) {
249
+ return 'static';
250
+ }
251
+ if (path === BULL_BOARD_BASE_PATH || path.startsWith(`${BULL_BOARD_BASE_PATH}/`)) {
252
+ return 'bullBoard';
253
+ }
254
+ if (isAdminPath(path)) {
255
+ return 'admin';
256
+ }
257
+ // The path prefix covers what no tag can: a mistyped API path lands on the untagged catch-all
258
+ if (path.startsWith('/v1/') || isMachineRoute(tags)) {
259
+ return 'api';
260
+ }
261
+ return 'public';
262
+ }
263
+
264
+ function serializeCsp(directives) {
265
+ return Object.keys(directives)
266
+ .map(name => `${name} ${directives[name]}`)
267
+ .join('; ');
268
+ }
269
+
270
+ /**
271
+ * Resolves the security headers for one response. Pure, so the whole matrix is testable
272
+ * without a server.
273
+ *
274
+ * @param {Object} options
275
+ * @param {string} options.path - Request path
276
+ * @param {string[]} [options.tags] - Route tags
277
+ * @param {string} [options.layout] - Layout the response's view was rendered with, if it is one
278
+ * @param {Object} [options.override] - The route's `plugins.securityHeaders` block: `directives`
279
+ * is merged over the preset, a `null` value removes a directive
280
+ * @param {string} [options.nonce] - Request nonce
281
+ * @param {boolean} [options.secureOrigin] - Whether HSTS applies
282
+ * @param {string} [options.cspMode] - One of CSP_MODES; anything else enforces
283
+ * @returns {{headers: Object, cacheControl: (string|null)}}
284
+ */
285
+ function policyFor({ path, tags = [], layout, override, nonce, secureOrigin = false, cspMode = 'enforce' }) {
286
+ const profile = PROFILES[profileNameFor(path, tags)];
287
+ const headers = Object.assign({}, profile.headers);
288
+
289
+ if (secureOrigin) {
290
+ headers['strict-transport-security'] = HSTS_VALUE;
291
+ }
292
+
293
+ if (profile.csp) {
294
+ const preset = CSP_PRESETS[layout === PUBLIC_LAYOUT ? 'public' : profile.csp];
295
+ const directives = Object.assign({}, preset.directives);
296
+
297
+ const overrides = (override && override.directives) || {};
298
+ for (const directive of Object.keys(overrides)) {
299
+ if (overrides[directive] === null) {
300
+ delete directives[directive];
301
+ } else {
302
+ directives[directive] = overrides[directive];
303
+ }
304
+ }
305
+
306
+ if (nonce) {
307
+ for (const directive of preset.nonceDirectives || []) {
308
+ if (directives[directive]) {
309
+ directives[directive] += ` 'nonce-${nonce}'`;
310
+ }
311
+ }
312
+ }
313
+
314
+ if (profile.frameAncestors) {
315
+ directives['frame-ancestors'] = profile.frameAncestors;
316
+ }
317
+
318
+ const framingOnly = profile.frameAncestors ? `frame-ancestors ${profile.frameAncestors}` : null;
319
+
320
+ if (cspMode === 'off' || cspMode === 'report-only') {
321
+ if (framingOnly) {
322
+ headers[CSP_HEADER] = framingOnly;
323
+ }
324
+ if (cspMode === 'report-only') {
325
+ headers[CSP_REPORT_ONLY_HEADER] = serializeCsp(directives);
326
+ }
327
+ } else {
328
+ headers[CSP_HEADER] = serializeCsp(directives);
329
+ }
330
+ }
331
+
332
+ return { headers, cacheControl: profile.cacheControl };
333
+ }
334
+
335
+ // Boom keeps its headers under the author's casing (`Retry-After`, `WWW-Authenticate`), a
336
+ // regular response lowercases them
337
+ function hasHeader(headers, name) {
338
+ return Object.keys(headers).some(key => key.toLowerCase() === name);
339
+ }
340
+
341
+ /**
342
+ * Builds the hapi onPreResponse extension that stamps the headers onto the outgoing response.
343
+ *
344
+ * Works on both response shapes: a Boom error keeps its headers under `output.headers`, a regular
345
+ * response under `headers`. An earlier extension may already have replaced the original response
346
+ * (the admin error page, the JSON API error), and `request.response` is whatever is current.
347
+ * The profile's own headers are set unconditionally - no handler has a reason to weaken them -
348
+ * while Cache-Control is only filled in where the handler set none, so a stream that asked for
349
+ * `no-cache` (the change feed) or a download keeps what it chose.
350
+ *
351
+ * @param {Object} [options]
352
+ * @param {string} [options.cspMode] - One of CSP_MODES
353
+ * @returns {Function} Extension handler
354
+ */
355
+ function securityHeadersExt({ cspMode = 'enforce' } = {}) {
356
+ return function applySecurityHeaders(request, h) {
357
+ const response = request.response;
358
+ const target = response.isBoom ? response.output.headers : response.headers;
359
+ const settings = (request.route && request.route.settings) || {};
360
+
361
+ // `source.options` is what h.view() was called with; a view rendered through the
362
+ // default layout has no layout option
363
+ const layout = !response.isBoom && response.variety === 'view' && response.source.options ? response.source.options.layout : undefined;
364
+
365
+ const policy = policyFor({
366
+ path: request.path,
367
+ tags: settings.tags || [],
368
+ layout,
369
+ override: settings.plugins && settings.plugins.securityHeaders,
370
+ nonce: request.app.cspNonce,
371
+ secureOrigin: request.app.secureOrigin,
372
+ cspMode
373
+ });
374
+
375
+ Object.assign(target, policy.headers);
376
+
377
+ if (policy.cacheControl && !hasHeader(target, 'cache-control')) {
378
+ target['cache-control'] = policy.cacheControl;
379
+ }
380
+
381
+ return h.continue;
382
+ };
383
+ }
384
+
385
+ module.exports = {
386
+ securityHeadersExt,
387
+ attachSecurityContext,
388
+ policyFor,
389
+ profileNameFor,
390
+ isAdminPath,
391
+ isMachineRoute,
392
+ isSecureOrigin,
393
+ CSP_MODES,
394
+ CSP_HEADER,
395
+ CSP_REPORT_ONLY_HEADER
396
+ };
package/lib/sentry.js CHANGED
@@ -2,8 +2,9 @@
2
2
 
3
3
  const packageData = require('../package.json');
4
4
  const logger = require('./logger');
5
- const { readEnvValue } = require('./tools');
5
+ const { readEnvValue, httpAgent } = require('./tools');
6
6
  const { COMMUNITY_SENTRY_DSN } = require('./consts');
7
+ const { fetch: fetchCmd } = require('undici');
7
8
 
8
9
  const SENTRY_SETTINGS_CHECK_INTERVAL = 60 * 1000;
9
10
 
@@ -11,6 +12,35 @@ let Sentry;
11
12
  let workerName;
12
13
  let activeDsn = false;
13
14
 
15
+ // Sentry's own transport speaks Node http/https and knows only the http_proxy environment
16
+ // variables (HTTP proxies, no SOCKS), so a proxy configured in EmailEngine would not cover error
17
+ // reports. Deliveries go through the shared dispatcher instead, read at send time so a proxy
18
+ // settings change applies to the next event without a restart. Only the two headers Sentry's
19
+ // rate limiting reads are handed back.
20
+ function makeTransport(options) {
21
+ const { createTransport } = require('@sentry/node');
22
+
23
+ return createTransport(options, async request => {
24
+ let res = await fetchCmd(options.url, {
25
+ method: 'POST',
26
+ headers: options.headers,
27
+ body: request.body,
28
+ dispatcher: httpAgent.fetch
29
+ });
30
+
31
+ // the body is never used, but consuming it lets the keep-alive socket be reused
32
+ await res.arrayBuffer();
33
+
34
+ return {
35
+ statusCode: res.status,
36
+ headers: {
37
+ 'x-sentry-rate-limits': res.headers.get('x-sentry-rate-limits'),
38
+ 'retry-after': res.headers.get('retry-after')
39
+ }
40
+ };
41
+ });
42
+ }
43
+
14
44
  function startSentry(dsn) {
15
45
  // require lazily, the SDK loads several hundred modules in every worker thread,
16
46
  // so only pay that cost when error tracking is actually enabled
@@ -21,6 +51,7 @@ function startSentry(dsn) {
21
51
  Sentry.init({
22
52
  dsn,
23
53
  release: packageData.version,
54
+ transport: makeTransport,
24
55
  // Error capture only: skip the OpenTelemetry setup and the default
25
56
  // integrations that patch http/fetch/console on hot paths. Sentry's own
26
57
  // uncaughtException/unhandledRejection integrations are left out on
@@ -130,8 +161,9 @@ function initSentry(worker) {
130
161
  }
131
162
 
132
163
  // Settings changes are detected by polling instead of the {cmd: 'settings'}
133
- // broadcast because that broadcast does not reach all the threads that
134
- // initialize Sentry (smtp, imap-proxy, documents, and the main thread).
164
+ // broadcast: the broadcast only carries the keys one settings form saved, and
165
+ // the main thread, which also initializes Sentry, is its sender rather than a
166
+ // recipient.
135
167
  let checkSettings = async () => {
136
168
  try {
137
169
  await checkSentrySettings();
@@ -144,4 +176,4 @@ function initSentry(worker) {
144
176
  setImmediate(checkSettings);
145
177
  }
146
178
 
147
- module.exports = { initSentry };
179
+ module.exports = { initSentry, makeTransport };
package/lib/smtp-auth.js CHANGED
@@ -9,7 +9,7 @@ const settings = require('./settings');
9
9
  const { redis } = require('./db');
10
10
  const { Account } = require('./account');
11
11
  const getSecret = require('./get-secret');
12
- const { validateAuthToken, REASON_MESSAGES } = require('./auth-token');
12
+ const { validateAuthToken, withAuthFailureBudget, REASON_MESSAGES } = require('./auth-token');
13
13
  const { constantTimeEqual } = require('./tools');
14
14
 
15
15
  /**
@@ -21,11 +21,9 @@ const { constantTimeEqual } = require('./tools');
21
21
  * @returns {Function} async onAuth(auth, session)
22
22
  */
23
23
  function createSmtpAuthHandler({ accountCache, call }) {
24
- return async function onAuth(auth, session) {
25
- if (!session.eeAuthEnabled) {
26
- throw new Error('Authentication not enabled');
27
- }
28
-
24
+ // The credential check proper. Everything it throws is a refusal the client caused, which
25
+ // is what the failure budget in onAuth() counts.
26
+ async function authenticate(auth, session) {
29
27
  let account = auth.username;
30
28
 
31
29
  let smtpPassword = await settings.get('smtpServerPassword');
@@ -65,7 +63,88 @@ function createSmtpAuthHandler({ accountCache, call }) {
65
63
 
66
64
  accountCache.set(session, accountObject);
67
65
  return { user: accountData.account };
66
+ }
67
+
68
+ return async function onAuth(auth, session) {
69
+ if (!session.eeAuthEnabled) {
70
+ throw new Error('Authentication not enabled');
71
+ }
72
+
73
+ return await withAuthFailureBudget(
74
+ { remoteAddress: session.remoteAddress, account: auth.username },
75
+ () => authenticate(auth, session),
76
+ () => {
77
+ let err = new Error(REASON_MESSAGES.limited);
78
+ // A temporary failure, so the client retries later instead of concluding that its
79
+ // credentials are wrong
80
+ err.responseCode = 454;
81
+ return err;
82
+ }
83
+ );
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Builds the resolver that finds the Account a submitted message is sent through.
89
+ *
90
+ * Lives beside the auth handler for the same reason it does: the worker can not be required
91
+ * from a test, and this is the other half of the decision of who may submit through which
92
+ * account. An authenticated session submits through the account it logged in as; a session
93
+ * opened while authentication was off names the account with the X-EE-Account header.
94
+ *
95
+ * @param {Object} deps
96
+ * @param {WeakMap} deps.accountCache - session -> Account cache shared with the auth handler
97
+ * @param {Function} deps.call - RPC function passed to the Account instance
98
+ * @returns {Function} async resolveAccount(session, messageMeta) -> Account
99
+ */
100
+ function createSmtpAccountResolver({ accountCache, call }) {
101
+ return async function resolveAccount(session, messageMeta) {
102
+ let accountObject;
103
+
104
+ if (!session.eeAuthEnabled) {
105
+ // The session decided at connect time that no authentication was required. A client
106
+ // can hold a connection open for as long as it likes, so if the operator has switched
107
+ // authentication on since, the stale decision must not keep admitting submissions.
108
+ if (await settings.get('smtpServerAuthEnabled')) {
109
+ let err = new Error('Authentication required');
110
+ err.responseCode = 530;
111
+ throw err;
112
+ }
113
+ }
114
+
115
+ if (!session.eeAuthEnabled && messageMeta.requestedAccount) {
116
+ // Only a loaded account counts as resolved. Keeping the instance after a failed load
117
+ // let an unknown header value through here, to fail later inside the queueing with
118
+ // an error that never named the reason
119
+ let requested = new Account({ account: messageMeta.requestedAccount, redis, call, secret: await getSecret() });
120
+ try {
121
+ // throws if unknown user
122
+ if (await requested.loadAccountData()) {
123
+ accountObject = requested;
124
+ accountCache.set(session, accountObject);
125
+ logger.debug({ msg: 'Resolved requested account', account: messageMeta.requestedAccount });
126
+ }
127
+ } catch (err) {
128
+ logger.warn({ msg: 'Failed to resolve requested account', account: messageMeta.requestedAccount, err });
129
+ }
130
+ } else {
131
+ accountObject = accountCache.get(session);
132
+ }
133
+
134
+ if (!session.eeAuthEnabled && !messageMeta.requestedAccount && !accountObject) {
135
+ let err = new Error('Sender account ID not provided, can not send mail');
136
+ err.responseCode = 451;
137
+ throw err;
138
+ }
139
+
140
+ if (!accountObject) {
141
+ let err = new Error('Failed to load account');
142
+ err.responseCode = 451;
143
+ throw err;
144
+ }
145
+
146
+ return accountObject;
68
147
  };
69
148
  }
70
149
 
71
- module.exports = { createSmtpAuthHandler };
150
+ module.exports = { createSmtpAuthHandler, createSmtpAccountResolver };