emailengine-app 2.79.7 → 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 (188) 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 +37 -0
  5. package/DOCKER_DEPLOYMENT.md +8 -7
  6. package/Dockerfile +35 -11
  7. package/bin/emailengine.js +29 -13
  8. package/config/default.toml +15 -4
  9. package/copy-static-files.sh +23 -5
  10. package/data/google-crawlers.json +7 -1
  11. package/docker-compose.yml +12 -3
  12. package/install.sh +2 -0
  13. package/lib/account.js +26 -1
  14. package/lib/api-routes/account-routes.js +14 -3
  15. package/lib/api-routes/bull-board-routes.js +3 -2
  16. package/lib/api-routes/mailbox-routes.js +4 -1
  17. package/lib/api-routes/message-routes.js +6 -5
  18. package/lib/api-routes/outbox-routes.js +7 -4
  19. package/lib/api-routes/route-helpers.js +8 -0
  20. package/lib/api-routes/settings-routes.js +34 -25
  21. package/lib/api-routes/stats-routes.js +8 -1
  22. package/lib/api-routes/submit-routes.js +2 -1
  23. package/lib/api-routes/template-routes.js +3 -2
  24. package/lib/auth-token.js +73 -2
  25. package/lib/autodetect-imap-settings.js +33 -25
  26. package/lib/bounce-detect.js +45 -0
  27. package/lib/consts.js +13 -2
  28. package/lib/egress-fetch.js +133 -0
  29. package/lib/egress-filter.js +39 -4
  30. package/lib/email-client/base-client.js +274 -24
  31. package/lib/email-client/gmail/gmail-api.js +15 -7
  32. package/lib/email-client/gmail-client.js +121 -64
  33. package/lib/email-client/imap/mailbox.js +18 -59
  34. package/lib/email-client/imap-client.js +53 -29
  35. package/lib/email-client/notification-handler.js +11 -2
  36. package/lib/email-client/outlook/graph-api.js +106 -90
  37. package/lib/email-client/outlook-client.js +222 -106
  38. package/lib/export.js +35 -2
  39. package/lib/generate-text-preview.js +10 -5
  40. package/lib/handlebars-helpers.js +129 -0
  41. package/lib/headers-rewriter.js +1 -1
  42. package/lib/imap-proxy-auth.js +41 -21
  43. package/lib/imapproxy/imap-core/README.md +1 -0
  44. package/lib/imapproxy/imap-core/lib/tls-options.js +5 -46
  45. package/lib/imapproxy/imap-server.js +9 -10
  46. package/lib/llm-pre-process.js +4 -1
  47. package/lib/mcp/json-schema.js +50 -2
  48. package/lib/openapi/index.js +3 -0
  49. package/lib/outbox.js +50 -8
  50. package/lib/pre-process.js +4 -1
  51. package/lib/rate-limit.js +23 -4
  52. package/lib/rewrite-text-nodes.js +12 -1
  53. package/lib/schemas.js +37 -8
  54. package/lib/security-headers.js +396 -0
  55. package/lib/sentry.js +36 -4
  56. package/lib/settings.js +19 -1
  57. package/lib/smtp-auth.js +86 -7
  58. package/lib/sso.js +13 -3
  59. package/lib/submit-progress.js +29 -0
  60. package/lib/templates.js +11 -0
  61. package/lib/tools.js +361 -173
  62. package/lib/ui-routes/account-routes.js +73 -13
  63. package/lib/ui-routes/admin-config-routes.js +7 -21
  64. package/lib/ui-routes/admin-entities-routes.js +42 -12
  65. package/lib/ui-routes/auth-routes.js +87 -28
  66. package/lib/ui-routes/dashboard-routes.js +1 -1
  67. package/lib/ui-routes/export-routes.js +4 -0
  68. package/lib/ui-routes/internals-routes.js +2 -0
  69. package/lib/ui-routes/mcp-consent-routes.js +12 -2
  70. package/lib/ui-routes/network-config-routes.js +6 -5
  71. package/lib/ui-routes/oauth-config-routes.js +12 -1
  72. package/lib/ui-routes/route-helpers.js +65 -14
  73. package/lib/ui-routes/settings-page.js +10 -0
  74. package/lib/ui-routes/smtp-test-routes.js +7 -0
  75. package/lib/ui-routes/suppression-list-routes.js +16 -5
  76. package/lib/ui-routes/unsubscribe-routes.js +22 -3
  77. package/lib/webhook-egress.js +5 -0
  78. package/lib/webhooks.js +14 -2
  79. package/package.json +23 -26
  80. package/sbom.json +1 -1
  81. package/server.js +100 -71
  82. package/static/css/flyonui.css +1 -1
  83. package/static/js/ace/css/ace.css +1462 -0
  84. package/static/js/ace/css/kuroir-1.png +0 -0
  85. package/static/js/ace/css/kuroir-2.png +0 -0
  86. package/static/js/ace/css/main-1.png +0 -0
  87. package/static/js/ace/css/main-10.svg +4 -0
  88. package/static/js/ace/css/main-11.svg +5 -0
  89. package/static/js/ace/css/main-12.svg +4 -0
  90. package/static/js/ace/css/main-13.png +0 -0
  91. package/static/js/ace/css/main-14.png +0 -0
  92. package/static/js/ace/css/main-15.png +0 -0
  93. package/static/js/ace/css/main-16.png +0 -0
  94. package/static/js/ace/css/main-17.png +0 -0
  95. package/static/js/ace/css/main-18.png +0 -0
  96. package/static/js/ace/css/main-19.png +0 -0
  97. package/static/js/ace/css/main-2.png +0 -0
  98. package/static/js/ace/css/main-20.png +0 -0
  99. package/static/js/ace/css/main-21.png +0 -0
  100. package/static/js/ace/css/main-22.png +0 -0
  101. package/static/js/ace/css/main-23.png +0 -0
  102. package/static/js/ace/css/main-24.png +0 -0
  103. package/static/js/ace/css/main-25.svg +1 -0
  104. package/static/js/ace/css/main-26.png +0 -0
  105. package/static/js/ace/css/main-3.png +0 -0
  106. package/static/js/ace/css/main-4.png +0 -0
  107. package/static/js/ace/css/main-5.svg +7 -0
  108. package/static/js/ace/css/main-6.svg +9 -0
  109. package/static/js/ace/css/main-7.svg +7 -0
  110. package/static/js/ace/css/main-8.svg +9 -0
  111. package/static/js/ace/css/main-9.svg +6 -0
  112. package/static/js/ace/css/theme/kuroir.css +78 -0
  113. package/static/js/ace/css/theme/tomorrow_night.css +128 -0
  114. package/static/js/ace/css/theme/tomorrow_night_eighties.css +128 -0
  115. package/static/js/ace/css/theme/xcode.css +106 -0
  116. package/static/js/ace/css/tomorrow_night-1.png +0 -0
  117. package/static/js/ace/css/tomorrow_night-2.png +0 -0
  118. package/static/js/ace/css/tomorrow_night_eighties-1.png +0 -0
  119. package/static/js/ace/css/tomorrow_night_eighties-2.png +0 -0
  120. package/static/js/ace/css/xcode-1.png +0 -0
  121. package/static/js/ace/css/xcode-2.png +0 -0
  122. package/static/js/ee-client.js +256 -102
  123. package/static/js/public.js +7 -0
  124. package/static/js/ui.js +32 -0
  125. package/static/licenses.html +338 -298
  126. package/static/vendor/simplewebauthn/browser.min.js +2 -2
  127. package/translations/messages.pot +158 -112
  128. package/views/account/passkeys.hbs +8 -0
  129. package/views/account/password.hbs +11 -0
  130. package/views/account/security.hbs +18 -7
  131. package/views/accounts/account.hbs +21 -38
  132. package/views/accounts/browse.hbs +3 -1
  133. package/views/accounts/edit.hbs +1 -1
  134. package/views/accounts/register/imap-server.hbs +11 -3
  135. package/views/config/ai.hbs +3 -1
  136. package/views/config/branding.hbs +4 -2
  137. package/views/config/document-store/chat.hbs +1 -1
  138. package/views/config/document-store/index.hbs +1 -1
  139. package/views/config/email-processing.hbs +2 -0
  140. package/views/config/imap-proxy.hbs +3 -1
  141. package/views/config/license.hbs +1 -1
  142. package/views/config/logging.hbs +3 -1
  143. package/views/config/mcp.hbs +3 -1
  144. package/views/config/network.hbs +16 -16
  145. package/views/config/oauth/app.hbs +4 -4
  146. package/views/config/security.hbs +2 -0
  147. package/views/config/service.hbs +3 -1
  148. package/views/config/smtp.hbs +3 -1
  149. package/views/config/webhooks.hbs +4 -2
  150. package/views/error.hbs +10 -2
  151. package/views/internals/index.hbs +1 -1
  152. package/views/layout/app.hbs +9 -14
  153. package/views/layout/login.hbs +1 -1
  154. package/views/layout/prompt.hbs +1 -1
  155. package/views/layout/public.hbs +1 -1
  156. package/views/legal.hbs +1 -1
  157. package/views/mcp/authorize.hbs +1 -1
  158. package/views/partials/ace_assets.hbs +13 -0
  159. package/views/partials/add_account_modal.hbs +1 -1
  160. package/views/partials/address_list.hbs +4 -4
  161. package/views/partials/filter_editor_js.hbs +3 -3
  162. package/views/partials/gateway_js.hbs +1 -1
  163. package/views/partials/oauth_form.hbs +6 -6
  164. package/views/partials/public_theme_init.hbs +1 -1
  165. package/views/partials/template_form.hbs +2 -2
  166. package/views/partials/test_send.hbs +7 -4
  167. package/views/partials/theme_init.hbs +1 -1
  168. package/views/partials/ui/details.hbs +2 -2
  169. package/views/partials/ui/env-managed-alert.hbs +19 -0
  170. package/views/partials/webhook_form.hbs +1 -1
  171. package/views/partials/webhooks_editor_functions.hbs +1 -1
  172. package/views/reference/redirect.hbs +1 -1
  173. package/views/templates/template.hbs +2 -2
  174. package/views/tokens/new.hbs +1 -1
  175. package/views/unsubscribe.hbs +7 -1
  176. package/views/webhooks/webhook.hbs +2 -2
  177. package/workers/api.js +179 -175
  178. package/workers/export.js +1 -5
  179. package/workers/imap.js +33 -6
  180. package/workers/smtp.js +19 -43
  181. package/workers/submit.js +31 -13
  182. package/workers/webhooks.js +9 -24
  183. package/lib/reconnection-manager.js +0 -106
  184. package/static/front/EmailEngine_logo_horiz.png +0 -0
  185. package/static/front/EmailEngine_logo_vert.png +0 -0
  186. package/static/front/index.html +0 -57
  187. package/static/front/logo.png +0 -0
  188. package/static/vendor/handlebars/handlebars.min-v4.7.9.js +0 -29
package/lib/schemas.js CHANGED
@@ -43,6 +43,11 @@ const MAX_ATTACHMENT_SIZE = getByteSize(process.env.EENGINE_MAX_SIZE || config.a
43
43
 
44
44
  const accountIdSchema = Joi.string().empty('').trim().max(MAX_ACCOUNT_ID_LENGTH).example('user123').description('Unique identifier for the email account');
45
45
 
46
+ // The message id path parameter, shared by every /message/{message} route so they all refuse the
47
+ // same input: EmailEngine ids are base64url, and an id that is not decodes to garbage the client
48
+ // code then fails on, which used to be a 500 on the routes that accepted any string
49
+ const messageIdSchema = Joi.string().base64({ paddingRequired: false, urlSafe: true }).max(256).example('AAAAAQAACnA').description('Message ID');
50
+
46
51
  // Suppression list identifier, shared by the Blocklists API and the suppression-list admin UI
47
52
  // so the two surfaces cannot drift on what a valid list ID is
48
53
  const blocklistListIdSchema = Joi.string()
@@ -284,7 +289,12 @@ const settingsSchema = {
284
289
 
285
290
  /* ────────────── Proxy ────────────── */
286
291
 
287
- 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
+ ),
288
298
  proxyUrl: Joi.string()
289
299
  .uri({ scheme: ['http', 'https', 'socks', 'socks4', 'socks4a', 'socks5'], allowRelative: false })
290
300
  .allow('')
@@ -297,12 +307,14 @@ const settingsSchema = {
297
307
  httpProxyEnabled: Joi.boolean()
298
308
  .truthy('Y', 'true', '1', 'on')
299
309
  .falsy('N', 'false', 0, '')
300
- .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
+ ),
301
313
  httpProxyUrl: Joi.string()
302
314
  .uri({ scheme: ['http', 'https', 'socks', 'socks4', 'socks4a', 'socks5'], allowRelative: false })
303
315
  .allow('')
304
316
  .example('http://proxy.example.com:8080')
305
- .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')
306
318
  .label('HttpProxyURL'),
307
319
 
308
320
  /* ────────────── SMTP ────────────── */
@@ -2351,7 +2363,9 @@ const headerTimeoutSchema = Joi.number()
2351
2363
  .max(2 * 3600 * 1000)
2352
2364
  .optional()
2353
2365
  .example(30000)
2354
- .description('Request timeout in milliseconds (overrides EENGINE_TIMEOUT environment variable)')
2366
+ .description(
2367
+ 'Request timeout in milliseconds. Raises the command timeout above the EENGINE_TIMEOUT default for a long-running request; a value below the default has no effect'
2368
+ )
2355
2369
  .label('X-EE-Timeout');
2356
2370
 
2357
2371
  // Headers every API route accepts, applied as a server-wide route default in workers/api.js rather
@@ -2488,17 +2502,24 @@ const errorResponseSchemas = {
2488
2502
  messageExample: 'Invalid input',
2489
2503
  label: 'ValidationErrorResponse',
2490
2504
  title: 'Validation error',
2491
- description: 'Invalid input - the path parameters, query arguments, or request payload did not pass validation',
2505
+ description:
2506
+ 'Invalid input - the path parameters, query arguments, or request payload did not pass validation. Also returned when the email server refused the request, in which case the response carries a code and the server response instead of a field list',
2492
2507
  fields: {
2493
2508
  fields: Joi.array()
2494
2509
  .items(
2495
2510
  Joi.object({
2496
2511
  message: Joi.string().example('"pageSize" must be less than or equal to 1000').description('Description of the validation failure'),
2497
- key: Joi.string().example('pageSize').description('Name of the input field that failed validation')
2512
+ key: Joi.string().example('pageSize').description('Name of the input field that failed validation'),
2513
+ path: Joi.string()
2514
+ .example('to.0.address')
2515
+ .description('Full path of the input field that failed validation. Same as key for a top-level field, dotted for a nested one')
2498
2516
  }).label('ValidationErrorField')
2499
2517
  )
2500
2518
  .description('List of input fields that failed validation')
2501
- .label('ValidationErrorFields')
2519
+ .label('ValidationErrorFields'),
2520
+ code: Joi.string().example('MailboxNotFound').description('Machine-readable error code, if available'),
2521
+ details: Joi.any().description('Additional error details, if available. The email server response for a refused mailbox operation'),
2522
+ info: Joi.any().description('Additional error details, if available. The email server response for a refused message operation')
2502
2523
  }
2503
2524
  }),
2504
2525
 
@@ -2517,7 +2538,14 @@ const errorResponseSchemas = {
2517
2538
  messageExample: 'Unauthorized scope',
2518
2539
  label: 'AccessDeniedErrorResponse',
2519
2540
  title: 'Access denied error',
2520
- description: 'Access denied - the access token does not grant permission for this operation (token scope, account, or IP address restriction)'
2541
+ description: 'Access denied - the access token does not grant permission for this operation (token scope, account, or IP address restriction)',
2542
+ fields: {
2543
+ requestedScope: Joi.string().example('api').description('The scope the operation needed, when the token does not carry it'),
2544
+ requiredPermission: Joi.string()
2545
+ .example('messages:write')
2546
+ .description('The permission grant the operation needed, when the token permissions do not include it'),
2547
+ remoteAddress: Joi.string().example('203.0.113.1').description('The client IP address, when the token is restricted to other addresses')
2548
+ }
2521
2549
  }),
2522
2550
 
2523
2551
  404: errorResponseEntry({
@@ -2642,6 +2670,7 @@ module.exports = {
2642
2670
  tokenRestrictionsSchema,
2643
2671
  tokenPermissionsSchema,
2644
2672
  accountIdSchema,
2673
+ messageIdSchema,
2645
2674
  blocklistListIdSchema,
2646
2675
  oauth2ProviderSchema,
2647
2676
  accountTypeSchema,
@@ -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/settings.js CHANGED
@@ -10,7 +10,9 @@ const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
10
10
 
11
11
  config.service = config.service || {};
12
12
 
13
- const ENCRYPTED_KEYS = [
13
+ // Values that are secrets in their entirety. Encrypted at rest, and the settings API returns a
14
+ // boolean marker in their place rather than the value.
15
+ const SECRET_KEYS = [
14
16
  // The gmail*/outlook*/mailRu* secrets belong to the retired settings-based OAuth2
15
17
  // configuration. They stay listed so oauth2Apps.migrateLegacyApps() can still decrypt
16
18
  // stored values through settings.get() before moving them into the app registry.
@@ -28,6 +30,16 @@ const ENCRYPTED_KEYS = [
28
30
  'totpSeed'
29
31
  ];
30
32
 
33
+ // Values that carry a secret without being one: URLs that may embed `user:pass@` credentials
34
+ // (a SOCKS or HTTP proxy, a webhook target, a Sentry DSN with its key) and the custom webhook
35
+ // headers, whose example is an Authorization bearer. Encrypted at rest like the secrets, but the
36
+ // API reads them back with only the credential part masked (route-helpers maskSecrets()), so they
37
+ // are not in the list it turns into booleans. Encryption applies to the JSON encoding, so the
38
+ // header list being an array rather than a string makes no difference.
39
+ const CREDENTIAL_BEARING_KEYS = ['webhooks', 'webhooksCustomHeaders', 'proxyUrl', 'httpProxyUrl', 'sentryDsn'];
40
+
41
+ const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
42
+
31
43
  // getValue() runs on an uncached read path - settings.get() is called several times per synced
32
44
  // message and once per webhook delivery - and a decrypt/parse failure is permanent rather than
33
45
  // transient (a rotated EENGINE_SECRET, a corrupt stored value). Reporting every occurrence would
@@ -36,8 +48,14 @@ const ENCRYPTED_KEYS = [
36
48
  const reportedParseFailures = new Set();
37
49
 
38
50
  module.exports = {
51
+ // Everything encrypted at rest: what `emailengine encrypt` re-encrypts on a secret rotation
39
52
  encryptedKeys: ENCRYPTED_KEYS,
40
53
 
54
+ // The subset the settings API returns as a boolean marker (lib/api-routes/settings-routes.js).
55
+ // The credential-bearing URLs are encrypted too but are returned with just the credentials
56
+ // masked, so a consumer that hides values has to read this list, not encryptedKeys.
57
+ secretKeys: SECRET_KEYS,
58
+
41
59
  /**
42
60
  * Whether admin authentication is configured for this instance.
43
61
  *