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
package/lib/mcp/tools.js CHANGED
@@ -15,7 +15,7 @@
15
15
  // account binding, IP restrictions, rate limits and the token audit log all apply exactly as they
16
16
  // do over REST. This module never touches Redis and never bypasses a handler.
17
17
 
18
- const { routeGrant, ACTION } = require('../api-routes/permission-map');
18
+ const { routeGrant, surfaceAdmits, surfaceBoundAdmits, PER_REQUEST_SURFACES, ACTION } = require('../api-routes/permission-map');
19
19
  const tokenPermissions = require('../token-permissions');
20
20
  const { mcpOptions } = require('../api-routes/route-metadata');
21
21
  const { joiToJsonSchema } = require('./json-schema');
@@ -40,7 +40,7 @@ const TRUNCATION_NOTICE = size => `\n\n[Result truncated by EmailEngine: the ful
40
40
 
41
41
  // Every key a plugins.mcp block may carry. The one place the block's shape is written down, so a
42
42
  // misspelling is a build failure rather than a knob that quietly does nothing.
43
- const MCP_OPTION_KEYS = new Set(['name', 'title', 'description', 'keep', 'omit', 'force', 'bounds', 'binary', 'resourceUriTemplate', 'endpoint']);
43
+ const MCP_OPTION_KEYS = new Set(['name', 'title', 'description', 'keep', 'omit', 'force', 'bounds', 'binary', 'resourceUriTemplate', 'endpoint', 'openWorld']);
44
44
 
45
45
  // One registry per Hapi server, built on first use and held for the life of the worker - route
46
46
  // definitions cannot change while it runs, and the build walks every joi schema of every wrapped
@@ -241,9 +241,10 @@ function buildToolRegistry(routes) {
241
241
  title: options.title,
242
242
  readOnlyHint: grant.action === ACTION.READ,
243
243
  destructiveHint: grant.action === ACTION.DESTRUCTIVE,
244
- // Sending mail reaches arbitrary external recipients; everything else stays inside
245
- // the connected mailboxes
246
- openWorldHint: grant.action === ACTION.SEND
244
+ // Sending mail reaches arbitrary external recipients. A tool whose grant does not
245
+ // imply that but whose purpose is reaching a host outside the instance - the
246
+ // autodiscovery lookup, the connection tests - declares `openWorld` itself.
247
+ openWorldHint: grant.action === ACTION.SEND || !!options.openWorld
247
248
  };
248
249
 
249
250
  const inputSchema = {
@@ -273,6 +274,10 @@ function buildToolRegistry(routes) {
273
274
  // questions about the catalog: tools/list uses it to show a permission-narrowed
274
275
  // token only the tools its record can actually call
275
276
  grant,
277
+ // The per-request scopes whose table covers that operation, in the order the scopes
278
+ // are declared: the other half of what tools/list filters on, and what the admin
279
+ // pages group and count by
280
+ surfaces: [...PER_REQUEST_SURFACES].filter(scope => surfaceAdmits(scope, grant)),
276
281
  binary: !!options.binary,
277
282
  resourceUriTemplate: options.resourceUriTemplate
278
283
  });
@@ -280,7 +285,15 @@ function buildToolRegistry(routes) {
280
285
 
281
286
  const tools = [...byName.values()].map(entry => entry.definition).sort((a, b) => a.name.localeCompare(b.name, 'en'));
282
287
 
283
- return { tools, byName };
288
+ // The catalog reduced to what the admin pages count and group by, in tools/list order. Built
289
+ // here with the registry rather than on each read: the registry is immutable for the life of
290
+ // the worker and three admin pages plus the MCP door read this.
291
+ const grants = tools.map(tool => {
292
+ const entry = byName.get(tool.name);
293
+ return Object.assign({ name: tool.name, accountScoped: entry.sources.has('account'), surfaces: entry.surfaces }, entry.grant);
294
+ });
295
+
296
+ return { tools, byName, grants };
284
297
  }
285
298
 
286
299
  /**
@@ -553,6 +566,11 @@ function toolVisibleTo(entry, { tokenData, boundAccount }) {
553
566
  if (boundAccount && !entry.sources.has('account')) {
554
567
  return false;
555
568
  }
569
+ // The scope bound first: a credential holding only the mail scope is not offered the
570
+ // management tools however wide its permissions record, and the other way round
571
+ if (!surfaceBoundAdmits(tokenData, entry.grant)) {
572
+ return false;
573
+ }
556
574
  return tokenPermissions.check({ tokenData, operation: entry.grant }).allowed;
557
575
  }
558
576
 
@@ -625,27 +643,45 @@ function listToolsFor(server, { tokenData, boundAccount }) {
625
643
  * which is what the two permission axes alone cannot tell a reader. Kept here rather than having
626
644
  * callers walk `byName`, so the dispatch table stays this module's business.
627
645
  *
628
- * `accountScoped` is what the binding half of toolVisibleTo() reads, carried along because the
629
- * admin pages have to apply the same two filters in a browser, where neither this module nor the
630
- * permission checker can be called. test/mcp-tools-test.js asserts that the two-allowlist model
631
- * those pages use agrees with toolVisibleTo() over the whole catalog, so the prediction cannot
632
- * drift away from the rule it predicts.
646
+ * `accountScoped` and `surfaces` are what the binding and scope halves of toolVisibleTo() read,
647
+ * carried along because the admin pages have to apply the same filters in a browser, where
648
+ * neither this module nor the permission checker can be called. test/mcp-tools-test.js asserts
649
+ * that the model those pages use agrees with toolVisibleTo() over the whole catalog, so the
650
+ * prediction cannot drift away from the rule it predicts.
633
651
  *
634
652
  * @param {Object} server - the Hapi server
635
- * @returns {Array<{name: String, action: String, group: String, accountScoped: Boolean}>}
653
+ * @returns {Array<{name: String, action: String, group: String, accountScoped: Boolean, surfaces: Array<String>}>}
636
654
  */
637
655
  function toolGrants(server) {
638
- const { tools, byName } = getToolRegistry(server);
639
- return tools.map(tool => {
640
- const entry = byName.get(tool.name);
641
- return Object.assign({ name: tool.name, accountScoped: entry.sources.has('account') }, entry.grant);
642
- });
656
+ return getToolRegistry(server).grants;
657
+ }
658
+
659
+ /**
660
+ * The per-request scopes a catalog actually exercises: a scope is held when a tool only that
661
+ * scope's table covers is in the catalog. The tools both tables cover (the account reads) say
662
+ * nothing about either. What the instructions are written from, so a narrowed record that
663
+ * empties a scope out is described accurately.
664
+ *
665
+ * @param {Object} server - the Hapi server
666
+ * @param {Array} catalog - tool definitions, as listToolsFor() returns them
667
+ * @returns {Array<String>} scopes, in declaration order
668
+ */
669
+ function catalogSurfaces(server, catalog) {
670
+ const names = new Set(catalog.map(tool => tool.name));
671
+ const held = new Set();
672
+ for (const entry of getToolRegistry(server).grants) {
673
+ if (entry.surfaces.length === 1 && names.has(entry.name)) {
674
+ held.add(entry.surfaces[0]);
675
+ }
676
+ }
677
+ return [...PER_REQUEST_SURFACES].filter(scope => held.has(scope));
643
678
  }
644
679
 
645
680
  module.exports = {
646
681
  buildToolRegistry,
647
682
  getToolRegistry,
648
683
  toolGrants,
684
+ catalogSurfaces,
649
685
  toolVisibleTo,
650
686
  toolDefinitionFor,
651
687
  listToolsFor,
@@ -0,0 +1,147 @@
1
+ 'use strict';
2
+
3
+ // The settings a narrowed credential may never read or write: what assertNoPrivilegedSettings()
4
+ // in lib/api-routes/route-helpers.js refuses on GET and POST /v1/settings, and what the two MCP
5
+ // settings tools leave out of their schemas (MCP_SETTINGS_KEYS in lib/api-routes/settings-routes.js).
6
+ // `read/settings` and `write/settings` are grantable permissions, and the settings blob is the one
7
+ // endpoint whose fields span every trust level, so these are the keys that would make a settings
8
+ // editor more than a settings editor.
9
+ //
10
+ // Grouped by the reason each cluster is on the list, and each group carries the words every
11
+ // description of the rule uses for it: the settings tools, the `settings` permission group in the
12
+ // OpenAPI document and the token form all render PRIVILEGED_SETTINGS_SUMMARY, so a key added here
13
+ // is described everywhere at once rather than in copies that drift.
14
+ //
15
+ // A leaf module on purpose: lib/enum-descriptions.js is pure prose loaded by lib/schemas.js, and
16
+ // lib/settings.js opens Redis, so the list has to live below both. The TLS listener table is the
17
+ // one import, dependency-free for the same reason (lib/tls/listeners.js).
18
+
19
+ const { TLS_CERTIFICATE_SETTINGS } = require('./tls/listeners');
20
+
21
+ const PRIVILEGED_SETTINGS_GROUPS = [
22
+ {
23
+ // Operator code run inside the instance, and the environment it sees
24
+ label: 'operator scripts',
25
+ keys: ['openAiPreProcessingFn', 'scriptEnv']
26
+ },
27
+ {
28
+ // Signs hosted authentication links and unsubscribe links
29
+ label: 'the link signing secret',
30
+ keys: ['serviceSecret']
31
+ },
32
+ {
33
+ // Where account credentials are fetched from
34
+ label: 'the authentication server',
35
+ keys: ['authServer']
36
+ },
37
+ {
38
+ // Trust of X-Forwarded-For, which the admin address perimeter is checked against, and the
39
+ // outbound address list
40
+ label: 'proxy trust and local addresses',
41
+ keys: ['enableApiProxy', 'localAddresses']
42
+ },
43
+ {
44
+ // Every IMAP, SMTP and HTTP connection, credentials included, goes through these
45
+ label: 'proxies',
46
+ keys: ['proxyEnabled', 'proxyUrl', 'httpProxyEnabled', 'httpProxyUrl']
47
+ },
48
+ {
49
+ // The built-in listeners: what they are, where they bind, whether they demand a credential
50
+ // and whether they speak TLS. The SMTP submission server's authentication switch is the
51
+ // sharpest of these - with it off, the server takes the sending account from a client
52
+ // header, so a settings grant would turn into unauthenticated sending as any account - but a
53
+ // narrowed credential must not move a listener onto a public interface or downgrade it to
54
+ // cleartext either, however delayed the restart that applies it.
55
+ label: 'the built-in listeners',
56
+ keys: [
57
+ 'smtpServerEnabled',
58
+ 'smtpServerHost',
59
+ 'smtpServerPort',
60
+ 'smtpServerAuthEnabled',
61
+ 'smtpServerPassword',
62
+ 'smtpServerProxy',
63
+ 'smtpServerTLSEnabled',
64
+ 'imapProxyServerEnabled',
65
+ 'imapProxyServerHost',
66
+ 'imapProxyServerPort',
67
+ 'imapProxyServerPassword',
68
+ 'imapProxyServerProxy',
69
+ 'imapProxyServerTLSEnabled'
70
+ ]
71
+ },
72
+ {
73
+ // Which stored certificate each listener presents, the API's included, and the mode that
74
+ // decides which certificates may be served at all: switched to self-signed, every listener
75
+ // presents the unverifiable certificate, which is a downgrade for every client that checks
76
+ // and an opening for the ones told not to. The hostname list places orders with the CA.
77
+ label: 'TLS certificates and provisioning',
78
+ keys: [...TLS_CERTIFICATE_SETTINGS, 'tlsProvisioning', 'tlsHostnames']
79
+ },
80
+ {
81
+ // The origin everything else is anchored to: the first hostname certificates are ordered
82
+ // for, the issuer and resource the MCP OAuth discovery documents name, where the hosted
83
+ // setup links point (the form where end users type mail passwords), and the signal that
84
+ // marks the cookies Secure. A settings editor that could move it would re-anchor all of
85
+ // that at once. notificationBaseUrl, the documented override, stays ordinary: it only names
86
+ // where Microsoft Graph delivers its change notifications, which carry no content.
87
+ label: 'the service URL',
88
+ keys: ['serviceUrl']
89
+ },
90
+ {
91
+ // Switches certificate checking off for every IMAP and SMTP connection the instance makes,
92
+ // which is the on-path reader's way to the account credentials
93
+ label: 'mail certificate checking',
94
+ keys: ['ignoreMailCertErrors']
95
+ },
96
+ {
97
+ // The AI key, and the base URL it is sent to: a narrowed credential that could point the
98
+ // latter at its own host would receive the former as a bearer header on the next request
99
+ label: 'the AI key and endpoint',
100
+ keys: ['openAiAPIKey', 'openAiAPIUrl']
101
+ },
102
+ {
103
+ // Credential-bearing (the example is an Authorization header)
104
+ label: 'custom webhook headers',
105
+ keys: ['webhooksCustomHeaders']
106
+ },
107
+ {
108
+ // HTML injected into the hosted pages, where end users type mail passwords
109
+ label: 'hosted page markup',
110
+ keys: ['templateHeader', 'templateHtmlHead']
111
+ },
112
+ {
113
+ // A credential must not change the door it came through, enable credential issuance, or
114
+ // switch off its own audit trail
115
+ label: 'the MCP and audit switches',
116
+ keys: ['mcpEnabled', 'mcpOAuthEnabled', 'tokenAuditLog']
117
+ },
118
+ {
119
+ // The deprecated Document Store's endpoint and credentials
120
+ label: 'the Document Store',
121
+ keys: [
122
+ 'documentStoreEnabled',
123
+ 'documentStoreUrl',
124
+ 'documentStoreIndex',
125
+ 'documentStoreAuthEnabled',
126
+ 'documentStoreUsername',
127
+ 'documentStorePassword',
128
+ 'documentStoreGenerateEmbeddings',
129
+ 'documentStorePreProcessingEnabled'
130
+ ]
131
+ },
132
+ {
133
+ // The error reporting target
134
+ label: 'error reporting',
135
+ keys: ['sentryEnabled', 'sentryDsn']
136
+ }
137
+ ];
138
+
139
+ const PRIVILEGED_SETTINGS_KEYS = PRIVILEGED_SETTINGS_GROUPS.flatMap(group => group.keys);
140
+
141
+ // The groups as one phrase, "operator scripts, the link signing secret, ..., and error reporting",
142
+ // for every description that says what a narrowed credential is refused
143
+ const PRIVILEGED_SETTINGS_SUMMARY = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' }).format(
144
+ PRIVILEGED_SETTINGS_GROUPS.map(group => group.label)
145
+ );
146
+
147
+ module.exports = { PRIVILEGED_SETTINGS_GROUPS, PRIVILEGED_SETTINGS_KEYS, PRIVILEGED_SETTINGS_SUMMARY };
package/lib/routes-ui.js CHANGED
@@ -15,6 +15,7 @@ const oauthConfigRoutes = require('./ui-routes/oauth-config-routes');
15
15
  const adminConfigRoutes = require('./ui-routes/admin-config-routes');
16
16
  const accountRoutes = require('./ui-routes/account-routes');
17
17
  const mcpConsentRoutes = require('./ui-routes/mcp-consent-routes');
18
+ const tlsConfigRoutes = require('./ui-routes/tls-config-routes');
18
19
 
19
20
  function applyRoutes(server, call) {
20
21
  // Initialize admin entity routes (webhooks, templates, gateways, tokens)
@@ -44,6 +45,9 @@ function applyRoutes(server, call) {
44
45
  // Network, SMTP server, IMAP proxy, and browser config routes
45
46
  networkConfigRoutes({ server, call });
46
47
 
48
+ // TLS certificates: the configuration page, and the ACME challenge route the CA calls
49
+ tlsConfigRoutes({ server, call });
50
+
47
51
  // Document Store (Elasticsearch) config routes (deprecated feature; the module self-gates
48
52
  // and registers no routes unless the Document Store feature is enabled)
49
53
  documentStoreRoutes({ server });
@@ -62,40 +66,6 @@ function applyRoutes(server, call) {
62
66
 
63
67
  // MCP OAuth consent page (self-gates on the MCP feature flag, like the Document Store module)
64
68
  mcpConsentRoutes({ server, call });
65
-
66
- server.route({
67
- method: 'GET',
68
- path: '/.well-known/acme-challenge/{token}',
69
- async handler(request, h) {
70
- let domain = (request.headers.host || '').toString().replace(/:.*$/g, '').trim().toLowerCase();
71
-
72
- let challenge;
73
- try {
74
- challenge = await h.certs.routeHandler(domain, request.params.token);
75
- if (!challenge) {
76
- throw new Error('Challenge not found for the provided token and domain');
77
- }
78
- } catch (err) {
79
- return h
80
- .response(
81
- `Request failed: ${err.message}
82
- Domain: ${JSON.stringify(domain)}
83
- Token: ${JSON.stringify(request.params.token)}`
84
- )
85
- .type('text/plain')
86
- .code(err.statusCode || 500);
87
- }
88
-
89
- const response = h.response('success');
90
- response.type('text/plain');
91
-
92
- return challenge;
93
- },
94
-
95
- options: {
96
- auth: false
97
- }
98
- });
99
69
  }
100
70
 
101
71
  module.exports = (...args) => {
package/lib/schemas.js CHANGED
@@ -1,5 +1,21 @@
1
1
  'use strict';
2
2
 
3
+ const net = require('net');
4
+ const { LISTENERS: TLS_LISTENERS, CERTIFICATE_ID_PATTERN: TLS_CERTIFICATE_ID_PATTERN } = require('./tls/listeners');
5
+
6
+ // The certificate a listener presents by default, as a setting per listener (lib/tls/listeners.js
7
+ // names the keys, lib/tls/catalog.js decides from the value)
8
+ const tlsCertificateChoice = listener =>
9
+ Joi.string()
10
+ .empty('')
11
+ .allow(null)
12
+ .pattern(TLS_CERTIFICATE_ID_PATTERN)
13
+ .max(262)
14
+ .example('auto')
15
+ .description(
16
+ `The certificate the ${listener.name} presents by default (to a client that names no host, and for every name the certificate covers). "auto" lets EmailEngine decide: the material from ${listener.envPrefix}* when it is set, otherwise the certificate for the Service URL hostname. Otherwise an id from the TLS Certificates page: "manual", "self-signed", "acme:<hostname>", or "env:api" / "env:smtp" / "env:imapProxy". A name the default does not cover is still served its own certificate`
17
+ )
18
+ .label('TlsCertificateChoice');
3
19
  const Joi = require('joi');
4
20
  const config = require('@zone-eu/wild-config');
5
21
  const { getByteSize } = require('./tools');
@@ -76,7 +92,7 @@ const ACCOUNT_DISPLAY_STATES = [...Object.values(ACCOUNT_STATES), 'disconnected'
76
92
 
77
93
  const { ADDRESS_STRATEGIES } = require('./address-strategies');
78
94
  const { ENUM_DESCRIPTIONS } = require('./enum-descriptions');
79
- const { ACTION, GRANTABLE_GROUPS } = require('./api-routes/permission-map');
95
+ const { ACTION, GRANTABLE_GROUPS, IMPLICIT_GROUPS } = require('./api-routes/permission-map');
80
96
  const { FIELD_USAGE } = require('./field-usage');
81
97
 
82
98
  // Account identity as the API describes it. These live here rather than next to the routes that use
@@ -483,6 +499,39 @@ const settingsSchema = {
483
499
  .falsy('N', 'false', 0, '')
484
500
  .description('Enable TLS/STARTTLS support for the SMTP server'),
485
501
 
502
+ /* ────────────── TLS Certificates ────────────── */
503
+
504
+ tlsProvisioning: Joi.string()
505
+ .empty('')
506
+ .valid('acme', 'manual', 'self-signed')
507
+ .example('acme')
508
+ .description(
509
+ 'Where the TLS certificate for the built-in listeners comes from: "acme" orders one from Let\'s Encrypt, "manual" uses the certificate uploaded through the admin UI, "self-signed" stops trying to get a real one'
510
+ )
511
+ .label('TlsProvisioning'),
512
+
513
+ tlsHostnames: Joi.array()
514
+ .items(
515
+ Joi.string()
516
+ .max(255)
517
+ .lowercase()
518
+ .pattern(/^[a-z0-9._:-]+$/i)
519
+ // The colon is for a bare IPv6 literal. A host:port pasted out of a mail client's
520
+ // settings is not a name a certificate can be issued for, and it used to be stored
521
+ // as one: a permanently failing order, and a reachability check made against the
522
+ // IMAPS port in plain HTTP.
523
+ .custom((value, helpers) => (value.includes(':') && net.isIP(value) !== 6 ? helpers.message('{{#label}} must not include a port') : value))
524
+ .example('smtp.example.com')
525
+ .label('TlsHostnameEntry')
526
+ )
527
+ .single()
528
+ .description(
529
+ 'Additional hostnames to hold certificates for, beyond the Service URL hostname. Each one is ordered separately and served over SNI, so a mail client connecting to smtp.example.com is offered a certificate for that name'
530
+ )
531
+ .label('TlsHostnames'),
532
+
533
+ ...Object.fromEntries(TLS_LISTENERS.map(listener => [listener.settingKey, tlsCertificateChoice(listener)])),
534
+
486
535
  /* ────────────── IMAP Proxy ────────────── */
487
536
 
488
537
  imapProxyServerEnabled: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '').description('Enable the IMAP proxy server'),
@@ -2138,14 +2187,22 @@ const tokenRestrictionsSchema = Joi.object({
2138
2187
  // than accepting one and denying every request it makes. The request-time deny in
2139
2188
  // lib/token-permissions.js stays regardless - it has to, because tokens.setRawData() writes a record
2140
2189
  // with no schema at all.
2190
+ // One instance of each value schema, referenced from both the axis lists and the pair entries: the
2191
+ // OpenAPI generator names components after labels, and two schema objects carrying the same label
2192
+ // come out numbered.
2193
+ const tokenActionSchema = Joi.string()
2194
+ .valid(...Object.values(ACTION))
2195
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenAction })
2196
+ .label('TokenAction');
2197
+
2198
+ const tokenGroupSchema = Joi.string()
2199
+ .valid(...GRANTABLE_GROUPS)
2200
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenGroup })
2201
+ .label('TokenGroup');
2202
+
2141
2203
  const tokenPermissionsSchema = Joi.object({
2142
2204
  actions: Joi.array()
2143
- .items(
2144
- Joi.string()
2145
- .valid(...Object.values(ACTION))
2146
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenAction })
2147
- .label('TokenAction')
2148
- )
2205
+ .items(tokenActionSchema)
2149
2206
  .single()
2150
2207
  .min(1)
2151
2208
  .example(['read', 'write'])
@@ -2153,25 +2210,44 @@ const tokenPermissionsSchema = Joi.object({
2153
2210
  .label('TokenActions'),
2154
2211
 
2155
2212
  groups: Joi.array()
2156
- .items(
2157
- Joi.string()
2158
- .valid(...GRANTABLE_GROUPS)
2159
- .meta({ enumDescriptions: ENUM_DESCRIPTIONS.tokenGroup })
2160
- .label('TokenGroup')
2161
- )
2213
+ .items(tokenGroupSchema)
2162
2214
  .single()
2163
2215
  .min(1)
2164
2216
  .example(['message', 'mailbox'])
2165
- .description('Which parts of the API this token may reach. Omit to allow all of them')
2166
- .label('TokenGroups')
2217
+ .description(
2218
+ `Which parts of the API this token may reach. Omitted, the token reaches every section except the instance sections (${GRANTABLE_GROUPS.filter(
2219
+ group => !IMPLICIT_GROUPS.includes(group)
2220
+ )
2221
+ .map(group => `\`${group}\``)
2222
+ .join(', ')}), which have to be named`
2223
+ )
2224
+ .label('TokenGroups'),
2225
+
2226
+ grants: Joi.array()
2227
+ .items(
2228
+ Joi.object({
2229
+ action: tokenActionSchema.required(),
2230
+ group: tokenGroupSchema.required()
2231
+ }).label('TokenGrant')
2232
+ )
2233
+ .min(1)
2234
+ .example([
2235
+ { action: 'read', group: 'message' },
2236
+ { action: 'write', group: 'template' }
2237
+ ])
2238
+ .description(
2239
+ 'Exact (action, group) pairs this token may perform, for a narrowing the two axes cannot express, such as reading one section while changing another. Stands alone: a record that sets `grants` may not set `actions` or `groups`'
2240
+ )
2241
+ .label('TokenGrants')
2167
2242
  })
2243
+ .without('grants', ['actions', 'groups'])
2168
2244
  .min(1)
2169
2245
  .empty(Joi.valid('', false))
2170
2246
  .allow(null)
2171
2247
  .example({ actions: ['read'], groups: ['message', 'mailbox'] })
2172
2248
  .label('TokenPermissions')
2173
2249
  .description(
2174
- 'Restricts a token below its scope. Each axis is an allowlist that only narrows, and both apply together, so an operation must match the actions AND the groups. Endpoints that hand out credentials or change instance configuration can never be reached by a token that sets this field, whatever it lists'
2250
+ 'Restricts a token below its scope. Written either as two axes, `actions` and `groups`, which are allowlists that apply together so an operation must match both, or as `grants`, a list of exact (action, group) pairs. Endpoints that hand out credentials can never be reached by a token that sets this field, whatever it lists'
2175
2251
  );
2176
2252
 
2177
2253
  const ipSchema = Joi.string()
@@ -132,6 +132,20 @@ const CSP_PRESETS = Object.freeze({
132
132
  })
133
133
  });
134
134
 
135
+ // What an admin page has to declare when it carries a form whose POST is answered with a redirect
136
+ // to an OAuth provider's authorization page. Chrome checks a form submission's redirect target
137
+ // against form-action, so `'self'` blocks the submission even though the form posts to this very
138
+ // instance. The hosted setup form gets the same relaxation from the public preset - an admin page
139
+ // renders the same form and has to ask for it, which is what the account page's "Re-authenticate"
140
+ // button needs.
141
+ //
142
+ // `https:` rather than the five authorization origins the providers actually use today
143
+ // (accounts.google.com, oauth.mail.ru and the three Entra clouds in lib/oauth/outlook.js). Listing
144
+ // them would be accurate right now and would silently reintroduce this very bug the day a provider
145
+ // or a Microsoft cloud is added - as a CSP refusal in the browser console, which is how it was
146
+ // found the first time. It is also the value every public page already carries.
147
+ const OAUTH_REDIRECT_FORM_DIRECTIVES = Object.freeze({ 'form-action': "'self' https:" });
148
+
135
149
  // Refuses MIME sniffing everywhere. An attachment or export served as application/octet-stream
136
150
  // must not be rendered as HTML because the bytes happen to look like it.
137
151
  const COMMON_HEADERS = Object.freeze({
@@ -384,6 +398,7 @@ function securityHeadersExt({ cspMode = 'enforce' } = {}) {
384
398
 
385
399
  module.exports = {
386
400
  securityHeadersExt,
401
+ OAUTH_REDIRECT_FORM_DIRECTIVES,
387
402
  attachSecurityContext,
388
403
  policyFor,
389
404
  profileNameFor,
package/lib/settings.js CHANGED
@@ -7,6 +7,7 @@ const config = require('@zone-eu/wild-config');
7
7
  const getSecret = require('./get-secret');
8
8
 
9
9
  const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
10
+ const { PRIVILEGED_SETTINGS_KEYS } = require('./privileged-settings');
10
11
 
11
12
  config.service = config.service || {};
12
13
 
@@ -40,6 +41,15 @@ const CREDENTIAL_BEARING_KEYS = ['webhooks', 'webhooksCustomHeaders', 'proxyUrl'
40
41
 
41
42
  const ENCRYPTED_KEYS = SECRET_KEYS.concat(CREDENTIAL_BEARING_KEYS);
42
43
 
44
+ // Settings a narrowed access token may not read or write, whatever its record grants. `write/settings` is
45
+ // a grantable permission, and most of the settings blob is what it says: webhook targets,
46
+ // notification shaping, sync strategy, listener ports. These keys are different in kind - each one
47
+ // would make the holder more than a settings editor - so assertNoPrivilegedSettings() in
48
+ // lib/api-routes/route-helpers.js refuses them to a restricted credential, and the MCP settings
49
+ // tool never offers them. An unnarrowed API token is unaffected, as it is for `proxy`.
50
+ //
51
+ // Listed beside SECRET_KEYS because the three lists are read together: a key that is a secret is
52
+ // privileged, but the privileged list is wider than the secrets.
43
53
  // getValue() runs on an uncached read path - settings.get() is called several times per synced
44
54
  // message and once per webhook delivery - and a decrypt/parse failure is permanent rather than
45
55
  // transient (a rotated EENGINE_SECRET, a corrupt stored value). Reporting every occurrence would
@@ -56,6 +66,9 @@ module.exports = {
56
66
  // masked, so a consumer that hides values has to read this list, not encryptedKeys.
57
67
  secretKeys: SECRET_KEYS,
58
68
 
69
+ // What a narrowed token may never read or write, see lib/privileged-settings.js
70
+ privilegedKeys: PRIVILEGED_SETTINGS_KEYS,
71
+
59
72
  /**
60
73
  * Whether admin authentication is configured for this instance.
61
74
  *