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
@@ -2,18 +2,34 @@
2
2
 
3
3
  // Narrowing check for an access token that carries a `permissions` record.
4
4
  //
5
- // Two axes, both subtractive: `actions` says what the token may do, `groups` says what it may
6
- // touch, and the vocabulary for both lives in lib/api-routes/permission-map.js. This function only
7
- // ever SUBTRACTS from what `scopes` and the account binding already allow - there is no value of
8
- // `permissions` that grants anything, so it is safe to run after those checks rather than instead
9
- // of them.
5
+ // Two forms, both subtractive. The two-axis form is the original: `actions` says what the token may
6
+ // do, `groups` says what it may touch, and an operation has to pass both, so the record means the
7
+ // cross product of the two lists. The pair-list form, `grants`, names exact (action, group) pairs
8
+ // instead, for the narrowing the cross product cannot express - read on one section and write on
9
+ // another - and stands alone: a record carrying it beside an axis is refused rather than
10
+ // intersected. The vocabulary for both lives in lib/api-routes/permission-map.js. This function
11
+ // only ever SUBTRACTS from what `scopes` and the account binding already allow - there is no value
12
+ // of `permissions` that grants anything, so it is safe to run after those checks rather than
13
+ // instead of them.
14
+ //
15
+ // An absent `actions` axis means every action. An absent `groups` axis means IMPLICIT_GROUPS - the
16
+ // sections that existed when the two-axis form shipped - and NOT every grantable group: the groups
17
+ // the admin split made grantable have to be named, so a record written before they existed keeps
18
+ // exactly the reach it had.
10
19
  //
11
20
  // Shared by both enforcement points on the same precedent that put lib/auth-token.js in one place:
12
21
  // the api-token strategy in workers/api.js for HTTP, and lib/auth-token.js for the SMTP submission
13
22
  // and IMAP proxy surfaces. A policy change that landed on one and missed the other would be a hole
14
23
  // in whichever surface was forgotten.
15
24
 
16
- const { NEVER_GRANTABLE, ACTION_VALUES, GROUP_VALUES } = require('./api-routes/permission-map');
25
+ const { NEVER_GRANTABLE, ACTION_VALUES, GROUP_VALUES, IMPLICIT_GROUPS, grantKey } = require('./api-routes/permission-map');
26
+
27
+ // One parse per record object. check() runs once per tool for every tools/list and once per
28
+ // MCP-dispatched request, over the same msgpack-decoded record each time, and the pair-list form
29
+ // validates and copies every entry on each parse. Keyed weakly on the record object itself, so a
30
+ // record lives in the cache exactly as long as the token data it came from; primitives (which
31
+ // are always malformed) are not cached and cost nothing to re-read.
32
+ const parsedRecords = new WeakMap();
17
33
 
18
34
  // The axes a record may carry, and the vocabulary each accepts. Anything else is a record this
19
35
  // version does not understand.
@@ -24,6 +40,15 @@ const AXIS_VALUES = {
24
40
 
25
41
  const AXES = Object.keys(AXIS_VALUES);
26
42
 
43
+ // The pair-list form. Listed apart from the axes because it is not one: it replaces both.
44
+ const GRANTS_KEY = 'grants';
45
+ const RECORD_KEYS = AXES.concat(GRANTS_KEY);
46
+
47
+ // The two keys a grant entry carries, and no other. An entry with an extra key is refused the same
48
+ // way a record with an extra axis is: a later version may give the pair a third field, and this
49
+ // one must deny rather than honour the two halves it understands.
50
+ const GRANT_KEYS = ['action', 'group'];
51
+
27
52
  // Why a request was refused. Reported to the caller rather than rendered here, because HTTP, SMTP
28
53
  // and IMAP each say "no" differently.
29
54
  const REASON = {
@@ -40,9 +65,52 @@ const REASON = {
40
65
  RESTRICTED: 'restricted',
41
66
 
42
67
  ACTION: 'action',
43
- GROUP: 'group'
68
+ GROUP: 'group',
69
+
70
+ // No pair in a `grants` list covers the operation. One reason rather than two, because a pair
71
+ // list has no axes to name.
72
+ GRANT: 'grant'
44
73
  };
45
74
 
75
+ /**
76
+ * Reads a `grants` list, or reports that it cannot be read.
77
+ *
78
+ * Every entry is checked the way the axes are: own keys only, exactly the two the pair is made of,
79
+ * and both values in the vocabulary. The entries are copied out rather than kept, so the caller
80
+ * holds plain pairs and not whatever object msgpack decoded.
81
+ *
82
+ * @param {*} value - the record's `grants` field
83
+ * @returns {{pairs: Array, keys: Set}|null} the pairs and their `action:group` keys, or null when
84
+ * the list is not one this version can read
85
+ */
86
+ function parseGrants(value) {
87
+ if (!Array.isArray(value)) {
88
+ return null;
89
+ }
90
+
91
+ const pairs = [];
92
+ const keys = new Set();
93
+ for (const entry of value) {
94
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
95
+ return null;
96
+ }
97
+
98
+ const own = Object.keys(entry);
99
+ if (own.length !== GRANT_KEYS.length || !GRANT_KEYS.every(key => Object.hasOwn(entry, key))) {
100
+ return null;
101
+ }
102
+
103
+ if (!ACTION_VALUES.has(entry.action) || !GROUP_VALUES.has(entry.group)) {
104
+ return null;
105
+ }
106
+
107
+ pairs.push({ action: entry.action, group: entry.group });
108
+ keys.add(grantKey(entry));
109
+ }
110
+
111
+ return { pairs, keys };
112
+ }
113
+
46
114
  /**
47
115
  * Reads a `permissions` record, or reports that it cannot be read.
48
116
  *
@@ -56,33 +124,62 @@ const REASON = {
56
124
  * `permissions` value can reach a record without ever passing route validation.
57
125
  *
58
126
  * @param {*} permissions - the record's `permissions` field
59
- * @returns {{narrowed: Boolean, axes: (Object|null), malformed: Boolean}}
127
+ * @returns {{narrowed: Boolean, actions: (Set|null), groups: (Set|null), grants: (Object|null), malformed: Boolean}}
128
+ * for the two-axis form, `actions` is null when the axis is absent (every action) and
129
+ * `groups` is always resolved (IMPLICIT_GROUPS when absent)
60
130
  */
61
131
  function parsePermissions(permissions) {
62
132
  if (permissions === null || typeof permissions === 'undefined') {
63
- return { narrowed: false, axes: null, malformed: false };
133
+ return { narrowed: false, actions: null, groups: null, grants: null, malformed: false };
64
134
  }
65
135
 
136
+ const malformed = { narrowed: true, actions: null, groups: null, grants: null, malformed: true };
137
+
66
138
  if (typeof permissions !== 'object' || Array.isArray(permissions)) {
67
- return { narrowed: true, axes: null, malformed: true };
139
+ return malformed;
140
+ }
141
+
142
+ let parsed = parsedRecords.get(permissions);
143
+ if (!parsed) {
144
+ parsed = parseRecord(permissions, malformed);
145
+ parsedRecords.set(permissions, parsed);
68
146
  }
147
+ return parsed;
148
+ }
69
149
 
150
+ function parseRecord(permissions, malformed) {
70
151
  const keys = Object.keys(permissions);
71
152
 
72
- // An unknown key is refused rather than ignored. That is what lets a later version add a third
73
- // axis without this one silently disregarding it - an older release denies the request instead
74
- // of honouring a narrowing it cannot apply.
75
- if (keys.some(key => !AXES.includes(key))) {
76
- return { narrowed: true, axes: null, malformed: true };
153
+ // An unknown key is refused rather than ignored. That is what let `grants` be added to a model
154
+ // that already had tokens in the field, and what lets the next key be added the same way: an
155
+ // older release denies the request instead of honouring a narrowing it cannot apply.
156
+ if (keys.some(key => !RECORD_KEYS.includes(key))) {
157
+ return malformed;
77
158
  }
78
159
 
79
160
  // `{}` is ambiguous between "no narrowing" and "grant nothing". The joi schema refuses it so it
80
161
  // never reaches a record through the API, and anything that gets in another way is denied.
81
162
  if (!keys.length) {
82
- return { narrowed: true, axes: null, malformed: true };
163
+ return malformed;
164
+ }
165
+
166
+ if (Object.hasOwn(permissions, GRANTS_KEY)) {
167
+ // The pair list stands alone. Beside an axis it would be two records claiming one token,
168
+ // and neither "intersect them" nor "the list wins" is a reading a reader could predict.
169
+ if (keys.length !== 1) {
170
+ return malformed;
171
+ }
172
+
173
+ const grants = parseGrants(permissions[GRANTS_KEY]);
174
+ if (!grants) {
175
+ return malformed;
176
+ }
177
+
178
+ // An empty list is well-formed and grants nothing, exactly like an empty axis
179
+ return { narrowed: true, actions: null, groups: null, grants, malformed: false };
83
180
  }
84
181
 
85
- const axes = {};
182
+ const axes = { actions: null, groups: null };
86
183
  for (const axis of AXES) {
87
184
  // Object.hasOwn rather than `in`: this record was msgpack-decoded from Redis by a path with
88
185
  // no schema, and `in` walks the prototype chain, so a payload that got something onto the
@@ -93,7 +190,7 @@ function parsePermissions(permissions) {
93
190
 
94
191
  const value = permissions[axis];
95
192
  if (!Array.isArray(value) || value.some(entry => !AXIS_VALUES[axis].has(entry))) {
96
- return { narrowed: true, axes: null, malformed: true };
193
+ return malformed;
97
194
  }
98
195
 
99
196
  // An empty array is well-formed and grants nothing: an allowlist that lists nothing allows
@@ -102,7 +199,16 @@ function parsePermissions(permissions) {
102
199
  axes[axis] = value;
103
200
  }
104
201
 
105
- return { narrowed: true, axes, malformed: false };
202
+ // Resolved once per record, here, so the two readers below share one meaning of an absent
203
+ // axis: every action, and IMPLICIT_GROUPS. Sets, because check() runs per tool on every
204
+ // tools/list.
205
+ return {
206
+ narrowed: true,
207
+ actions: axes.actions && new Set(axes.actions),
208
+ groups: new Set(axes.groups || IMPLICIT_GROUPS),
209
+ grants: null,
210
+ malformed: false
211
+ };
106
212
  }
107
213
 
108
214
  /**
@@ -134,19 +240,27 @@ function check({ tokenData, operation }) {
134
240
  }
135
241
 
136
242
  // Checked before the axes, and independently of them, so no value of `groups` can reach these.
137
- // This is the rule the rest of the model rests on: while it holds, a narrowed token cannot read
138
- // the settings blob, cannot read a stored OAuth2 credential, and cannot mint or revoke a token,
139
- // so it cannot widen itself. Encoded as a deny set rather than as an absence from the grantable
140
- // list so that widening the grantable list can never quietly reopen it.
243
+ // This is the rule the rest of the model rests on: while it holds, a narrowed token cannot mint
244
+ // a token and cannot read a live provider credential, so it cannot widen itself (the settings
245
+ // that would let it are refused per key, see assertNoPrivilegedSettings() in
246
+ // lib/api-routes/route-helpers.js). Encoded as a deny set rather than as an absence from the
247
+ // grantable list so that widening the grantable list can never quietly reopen it.
141
248
  if (NEVER_GRANTABLE.has(group)) {
142
249
  return { allowed: false, reason: REASON.RESTRICTED, required };
143
250
  }
144
251
 
145
- if (parsed.axes.actions && !parsed.axes.actions.includes(action)) {
252
+ if (parsed.grants) {
253
+ if (!parsed.grants.keys.has(grantKey(required))) {
254
+ return { allowed: false, reason: REASON.GRANT, required };
255
+ }
256
+ return { allowed: true, reason: null, required };
257
+ }
258
+
259
+ if (parsed.actions && !parsed.actions.has(action)) {
146
260
  return { allowed: false, reason: REASON.ACTION, required };
147
261
  }
148
262
 
149
- if (parsed.axes.groups && !parsed.axes.groups.includes(group)) {
263
+ if (!parsed.groups.has(group)) {
150
264
  return { allowed: false, reason: REASON.GROUP, required };
151
265
  }
152
266
 
@@ -169,4 +283,40 @@ function inspect(tokenData) {
169
283
  return { narrowed, malformed };
170
284
  }
171
285
 
172
- module.exports = { check, inspect, REASON };
286
+ /**
287
+ * The (action, group) pairs a record allows, whichever form it is written in.
288
+ *
289
+ * The two-axis form expands to its cross product, an absent axis read as parseRecord() resolved
290
+ * it. The pair form is returned as it is. The never-grantable groups are left out either way,
291
+ * because check() refuses them before it reads the record, so a pair naming one is not something
292
+ * the record allows.
293
+ *
294
+ * For consumers that describe a record rather than enforce it: the admin listing summarises a
295
+ * pair-list record through this rather than holding its own reading of the form.
296
+ *
297
+ * @param {*} permissions - the record's `permissions` field
298
+ * @returns {Array<{action: String, group: String}>|null} the pairs, or null when the record narrows
299
+ * nothing or cannot be read (inspect() tells those two apart)
300
+ */
301
+ function effectiveGrants(permissions) {
302
+ const parsed = parsePermissions(permissions);
303
+ if (!parsed.narrowed || parsed.malformed) {
304
+ return null;
305
+ }
306
+
307
+ if (parsed.grants) {
308
+ return parsed.grants.pairs.filter(grant => !NEVER_GRANTABLE.has(grant.group)).map(grant => ({ action: grant.action, group: grant.group }));
309
+ }
310
+
311
+ const grants = [];
312
+ for (const action of parsed.actions || ACTION_VALUES) {
313
+ for (const group of parsed.groups) {
314
+ if (!NEVER_GRANTABLE.has(group)) {
315
+ grants.push({ action, group });
316
+ }
317
+ }
318
+ }
319
+ return grants;
320
+ }
321
+
322
+ module.exports = { check, inspect, effectiveGrants, REASON };
package/lib/tokens.js CHANGED
@@ -504,9 +504,10 @@ module.exports = {
504
504
  * @param {Boolean} [opts.all] - every token on the instance, bound or not. Reads the token hash
505
505
  * directly rather than walking one index per account: the account is stored on each record, so
506
506
  * the union is already there, and enumerating accounts would be a round trip each.
507
- * @param {String} [opts.scope] - keep only tokens whose scope list names this scope. Literal
508
- * membership on purpose: a '*' token would also serve the surface, but the filter exists to
509
- * answer "which tokens were minted for it", and those carry the scope by name.
507
+ * @param {String|Array<String>} [opts.scope] - keep only tokens whose scope list names one of
508
+ * these scopes. Literal membership on purpose: a '*' token would also serve the surface, but
509
+ * the filter exists to answer "which tokens were minted for it", and those carry the scope by
510
+ * name. A list because the MCP pages ask for both MCP scopes at once.
510
511
  */
511
512
  async list(account, page, pageSize, query, opts) {
512
513
  page = Math.max(Number(page) || 0, 0);
@@ -518,10 +519,10 @@ module.exports = {
518
519
  // single space in the search box on the read-everything path with no filter to show for it.
519
520
  query = (query || '').toString().trim();
520
521
 
521
- const scope = (opts && opts.scope) || null;
522
+ const scopes = [].concat((opts && opts.scope) || []).filter(Boolean);
522
523
  // Either filter forces the read-everything path: the fields they match on live on the
523
524
  // record and nowhere else
524
- const filtered = !!(query || scope);
525
+ const filtered = !!(query || scopes.length);
525
526
 
526
527
  let startPos = page * pageSize;
527
528
 
@@ -588,7 +589,7 @@ module.exports = {
588
589
 
589
590
  // Before the entry is built: on a scope-filtered read of every record, the
590
591
  // date coercion and the copy below would mostly construct throwaways
591
- if (scope && !(Array.isArray(tokenData.scopes) && tokenData.scopes.includes(scope))) {
592
+ if (scopes.length && !(Array.isArray(tokenData.scopes) && scopes.some(scope => tokenData.scopes.includes(scope)))) {
592
593
  continue;
593
594
  }
594
595
 
package/lib/tools.js CHANGED
@@ -6,6 +6,7 @@ const msgpack = require('./msgpack');
6
6
  const enumMessageFlags = require('./enum-message-flags');
7
7
  const Joi = require('joi');
8
8
  const packageData = require('../package.json');
9
+ const { TLS_CERTIFICATE_SETTINGS } = require('./tls/listeners');
9
10
  const settings = require('./settings');
10
11
  // Safe to require at load time despite db.js opening Redis clients: settings.js above already
11
12
  // requires it, so db.js is in this file's dependency graph either way. db.js does not require
@@ -33,6 +34,7 @@ const mimeTypes = require('nodemailer/lib/mime-funcs/mime-types');
33
34
  const { v3: murmurhash } = require('murmurhash');
34
35
  const { isEmail } = require('./utils/is-email');
35
36
  const { toCamelCase } = require('./utils/to-camel-case');
37
+ const { normalizePath } = require('./utils/mailbox-path');
36
38
  const { compare: compareVersions, validate: validateVersion } = require('compare-versions');
37
39
  const {
38
40
  REDIS_PREFIX,
@@ -509,28 +511,65 @@ function cidReferenceRegex() {
509
511
  return new RegExp(CID_REFERENCE_SOURCE, 'g');
510
512
  }
511
513
 
512
- // Both the SMTP server and the IMAP proxy read the TLS certificate into their server options once,
513
- // when their worker starts, rather than per handshake, so a newly issued certificate only reaches
514
- // them through a reload. The list lives here rather than at each call site because the bug this
515
- // replaces was exactly that: the renewal path reloaded the SMTP server and forgot the IMAP proxy,
516
- // which then went on offering the expired certificate until something unrelated restarted it.
517
- async function reloadTlsServers(call, logger, context) {
518
- for (let cmd of ['smtpReload', 'imapProxyReload']) {
519
- try {
520
- await call({ cmd });
521
- } catch (err) {
522
- // Caught per command so a server that fails to come back does not cost the other one
523
- // its new certificate, and so the failure is not reported as an acquisition failure.
524
- logger.error(Object.assign({ msg: 'Failed to reload server after certificate change', cmd, err }, context || {}));
525
- }
514
+ // Hands a renewed certificate to every listener without restarting any of them.
515
+ //
516
+ // The list of listeners lives here rather than at each call site, because the bug this replaces was
517
+ // exactly that: the renewal path told the SMTP server and forgot the IMAP proxy, which went on
518
+ // offering the expired certificate until something unrelated restarted it.
519
+ //
520
+ // A restart was how this used to work, and it cut every SMTP submission and every IMAP session in
521
+ // flight for a certificate that was not going to expire for another month. Both mail server
522
+ // libraries build their secure contexts through updateSecureContext() and Node's own https server
523
+ // has setSecureContext(), so a running listener can be given new material between handshakes;
524
+ // connections already established keep the context they negotiated with, which stays valid for as
525
+ // long as they live.
526
+ async function reloadTlsCertificates(call, logger, context) {
527
+ // Sent together rather than one after another: nothing here depends on the order, each command
528
+ // reports its own failure, and the main thread hands them straight to the workers, so awaiting
529
+ // them in sequence only stacked up to three command timeouts in whatever request asked.
530
+ await Promise.all(
531
+ ['apiReloadCertificates', 'smtpReloadCertificates', 'imapProxyReloadCertificates'].map(cmd =>
532
+ call({ cmd }).catch(err => logger.error(Object.assign({ msg: 'Failed to reload certificates', cmd, err }, context || {})))
533
+ )
534
+ );
535
+ }
536
+
537
+ // The settings a listener's certificate is resolved from: which stored sources are admitted
538
+ // (tlsProvisioning), which names are served (tlsHostnames, plus the service URL's own hostname),
539
+ // and which certificate each listener presents by default. Changing any of them changes what a running listener should be offering, and none of
540
+ // that depends on a certificate being ordered - the reconciler returns immediately for every mode
541
+ // but `acme`, and even there it only reloads when an order produced new material. So whoever writes
542
+ // one of these keys hands the result to the listeners, the same way HTTP_PROXY_SETTINGS above is
543
+ // what makes a proxy change reach the dispatchers.
544
+ const TLS_MATERIAL_SETTINGS = ['tlsProvisioning', 'tlsHostnames', 'serviceUrl'].concat(TLS_CERTIFICATE_SETTINGS);
545
+
546
+ /**
547
+ * Reloads the listeners when the settings that were just written change what they serve.
548
+ *
549
+ * @param {Function} call Worker call function
550
+ * @param {Object} logger Worker logger
551
+ * @param {string[]} keys Setting keys that were written
552
+ * @param {Object} [context] Extra fields for the failure log
553
+ * @returns {Promise<boolean>} Whether a reload was sent
554
+ */
555
+ async function maybeReloadTlsCertificates(call, logger, keys, context) {
556
+ if (!keys || !keys.some(key => TLS_MATERIAL_SETTINGS.includes(key))) {
557
+ return false;
526
558
  }
559
+
560
+ await reloadTlsCertificates(call, logger, context);
561
+ return true;
527
562
  }
528
563
 
529
564
  module.exports = {
530
565
  // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
531
566
  toCamelCase,
532
567
 
533
- reloadTlsServers,
568
+ reloadTlsCertificates,
569
+
570
+ maybeReloadTlsCertificates,
571
+
572
+ TLS_MATERIAL_SETTINGS,
534
573
 
535
574
  cidReferenceRegex,
536
575
 
@@ -860,17 +899,9 @@ module.exports = {
860
899
  return hasChanges ? changes : false;
861
900
  },
862
901
 
863
- normalizePath(path, separator) {
864
- if (separator) {
865
- return path.replace(new RegExp(`^INBOX($|${module.exports.escapeRegExp(separator)})`, 'i'), n => n.toUpperCase());
866
- }
867
-
868
- if (/^INBOX$/i.test(path)) {
869
- return 'INBOX';
870
- }
871
-
872
- return path;
873
- },
902
+ // keep the re-export, lib/utils/mailbox-path.js holds it so pure modules can compare folder
903
+ // names without inheriting the Redis connections this module opens
904
+ normalizePath,
874
905
 
875
906
  // Hashed component of a mailbox's per-folder Redis keys: a hash of the normalized path, so an
876
907
  // arbitrarily long (or delimiter-heavy) folder name maps to a compact, stable key.
@@ -936,7 +967,22 @@ module.exports = {
936
967
 
937
968
  let authResponse = await fetchCmd(parsed.toString(), { method: 'GET', headers, dispatcher: httpAgent.retry });
938
969
  if (!authResponse.ok) {
939
- throw new Error(`Invalid response: ${authResponse.status} ${authResponse.statusText}`);
970
+ // The status rides along in a request record, the way the OAuth2 clients attach
971
+ // tokenRequest/oauthRequest, so the callers can tell an authentication server that is
972
+ // having a bad minute (429, 5xx) from one that refused the account. Without it every
973
+ // blip was reported as an authentication failure for every account on the instance -
974
+ // see isTransientCredentialError() in lib/email-client/credential-errors.js.
975
+ //
976
+ // Deliberately NOT err.statusCode: that field is read all the way up as the status of
977
+ // the request EmailEngine is serving (route-helpers handleError, the cross-worker
978
+ // error rebuild in workers/api.js), so the operator's 401 or 404 became EmailEngine's
979
+ // answer to a caller holding a perfectly valid token. The record names the server and
980
+ // nothing else - the query carries the account this asked about, the userinfo the
981
+ // credential it asked with
982
+ let err = new Error(`Invalid response: ${authResponse.status} ${authResponse.statusText}`);
983
+ err.code = 'HTTPRequestError';
984
+ err.authRequest = { status: authResponse.status, url: parsed.origin };
985
+ throw err;
940
986
  }
941
987
 
942
988
  let authData = await authResponse.json();
@@ -17,9 +17,11 @@ const { redis, documentsQueue } = require('../db');
17
17
  const getSecret = require('../get-secret');
18
18
  const capa = require('../capa');
19
19
  const { Account, authFailureDisabledAt, isOperatorDisabled } = require('../account');
20
+ const { formatGmailWatch } = require('../account/account-state');
20
21
  const { Gateway } = require('../gateway');
21
22
  const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
22
23
  const { atomicIncrement } = require('../redis-operations');
24
+ const { OAUTH_REDIRECT_FORM_DIRECTIVES } = require('../security-headers');
23
25
  const { oauth2Apps, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
24
26
  const {
25
27
  getServiceHostname,
@@ -790,7 +792,13 @@ function init(args) {
790
792
 
791
793
  let serverSettings;
792
794
  try {
793
- serverSettings = await autodetectImapSettings(request.payload.email, request.app.gt);
795
+ // The password the user just typed is passed along because hosted Exchange refuses
796
+ // to answer autodiscovery anonymously; it only ever reaches the autodiscovery host
797
+ // named by the address domain's own DNS, and only after that host has asked for it
798
+ serverSettings = await autodetectImapSettings(request.payload.email, request.app.gt, {
799
+ user: request.payload.email,
800
+ pass: request.payload.password
801
+ });
794
802
  } catch (err) {
795
803
  request.logger.debug({ msg: 'Failed to resolve email server settings', email: request.payload.email, err });
796
804
  }
@@ -1410,35 +1418,36 @@ function init(args) {
1410
1418
  accountData.path = null;
1411
1419
  }
1412
1420
 
1413
- let gmailWatch =
1414
- accountData.watchResponse || accountData.watchFailure
1415
- ? {
1416
- lastCheckStr: accountData.lastWatch && accountData.lastWatch.toISOString(),
1417
- expiresStr:
1418
- accountData.watchResponse && accountData.watchResponse.expiration
1419
- ? new Date(Number(accountData.watchResponse.expiration)).toISOString()
1420
- : false
1421
- }
1422
- : false;
1423
-
1424
- if (gmailWatch) {
1425
- gmailWatch.active = gmailWatch.expiresStr && new Date(gmailWatch.expiresStr) > new Date();
1426
- gmailWatch.stateLabel = gmailWatch.active ? 'Active' : 'Expired';
1427
- if (accountData.watchFailure) {
1428
- gmailWatch.error = accountData.watchFailure.err;
1429
- if (!gmailWatch.active) {
1430
- gmailWatch.stateLabel = 'Failed';
1431
- }
1432
-
1433
- if (accountData.watchFailure.req) {
1434
- gmailWatch.request = {
1435
- url: accountData.watchFailure.req.url,
1436
- status: accountData.watchFailure.req.status,
1437
- contentType: accountData.watchFailure.req.contentType,
1438
- response: accountData.watchFailure.req.response
1439
- };
1440
- }
1441
- }
1421
+ // State comes from the same derivation the API reports, so the page and the response
1422
+ // cannot disagree about whether push is working. The reason and the failed request stay
1423
+ // here and out of the API: both are text the provider wrote, and this page is behind an
1424
+ // admin session. NB! a watch that is still armed but whose last renewal failed now
1425
+ // reads Failed rather than Active - it used to show the expiry alone and hide the
1426
+ // failure in a tooltip, which said nothing was wrong right up to the day it lapsed
1427
+ let watchState = formatGmailWatch(accountData);
1428
+ let gmailWatch = watchState
1429
+ ? {
1430
+ lastCheckStr: watchState.lastCheck,
1431
+ expiresStr: watchState.expires || false,
1432
+ active: watchState.state === 'active',
1433
+ stateLabel: { active: 'Active', error: 'Failed', expired: 'Expired' }[watchState.state] || 'Unknown',
1434
+ // The reason and the failed request are read straight off the record here and
1435
+ // deliberately absent from the shared derivation: both carry text the
1436
+ // provider wrote, including the operator's own Pub/Sub topic path, and this
1437
+ // page is behind an admin session while the API field is not
1438
+ error: accountData.watchFailure ? accountData.watchFailure.err || 'Failed to set up Gmail pubsub watch' : false
1439
+ }
1440
+ : false;
1441
+
1442
+ // Not "watchFailure truthy means gmailWatch is": the derivation reports nothing for an
1443
+ // account whose application has no Pub/Sub app, whatever record a previous one left
1444
+ if (gmailWatch && accountData.watchFailure && accountData.watchFailure.req) {
1445
+ gmailWatch.request = {
1446
+ url: accountData.watchFailure.req.url,
1447
+ status: accountData.watchFailure.req.status,
1448
+ contentType: accountData.watchFailure.req.contentType,
1449
+ response: accountData.watchFailure.req.response
1450
+ };
1442
1451
  }
1443
1452
 
1444
1453
  const canReadMail = (accountData.imap || accountData.oauth2) && !(accountData.imap && accountData.imap.disabled) && !DISABLE_MESSAGE_BROWSER;
@@ -1565,6 +1574,10 @@ function init(args) {
1565
1574
  },
1566
1575
 
1567
1576
  options: {
1577
+ // The "Re-authenticate" modal posts to /accounts/new, which answers with a redirect to the
1578
+ // provider's authorization page. Without this the admin preset's `form-action 'self'` blocks
1579
+ // the submission, even though the form posts to this instance
1580
+ plugins: { securityHeaders: { directives: OAUTH_REDIRECT_FORM_DIRECTIVES } },
1568
1581
  validate: {
1569
1582
  options: {
1570
1583
  stripUnknown: true,