emailengine-app 2.80.0 → 2.81.0

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 (178) hide show
  1. package/.dockerignore +44 -0
  2. package/.github/docker-smoke-test.sh +16 -0
  3. package/.github/workflows/deploy.yml +4 -0
  4. package/.github/workflows/release.yaml +4 -0
  5. package/.github/workflows/test.yml +2 -0
  6. package/.release-please-manifest.json +1 -1
  7. package/CHANGELOG.md +56 -0
  8. package/Dockerfile +17 -9
  9. package/README.md +6 -0
  10. package/data/google-crawlers.json +1 -1
  11. package/docker-compose.yml +7 -1
  12. package/lib/api-routes/account-routes.js +239 -73
  13. package/lib/api-routes/blocklist-routes.js +24 -0
  14. package/lib/api-routes/delivery-test-routes.js +6 -0
  15. package/lib/api-routes/gateway-routes.js +30 -0
  16. package/lib/api-routes/license-routes.js +10 -0
  17. package/lib/api-routes/mcp-oauth-routes.js +3 -3
  18. package/lib/api-routes/mcp-routes.js +39 -21
  19. package/lib/api-routes/oauth2-app-routes.js +38 -1
  20. package/lib/api-routes/outbox-routes.js +6 -0
  21. package/lib/api-routes/permission-map.js +212 -42
  22. package/lib/api-routes/pubsub-routes.js +8 -0
  23. package/lib/api-routes/route-helpers.js +58 -11
  24. package/lib/api-routes/settings-routes.js +50 -4
  25. package/lib/api-routes/stats-routes.js +6 -0
  26. package/lib/api-routes/template-routes.js +21 -0
  27. package/lib/api-routes/token-routes.js +34 -2
  28. package/lib/api-routes/webhook-route-routes.js +13 -0
  29. package/lib/autodetect-imap-settings.js +4 -4
  30. package/lib/email-client/base-client.js +6 -3
  31. package/lib/email-client/credential-errors.js +4 -0
  32. package/lib/email-client/imap/login-failure.js +52 -0
  33. package/lib/email-client/imap/subconnection.js +2 -1
  34. package/lib/email-client/imap-client.js +3 -6
  35. package/lib/enum-descriptions.js +12 -2
  36. package/lib/imapproxy/imap-server.js +1 -1
  37. package/lib/mcp/oauth.js +46 -8
  38. package/lib/mcp/protocol.js +78 -35
  39. package/lib/mcp/tools.js +53 -17
  40. package/lib/privileged-settings.js +147 -0
  41. package/lib/schemas.js +60 -16
  42. package/lib/sentry.js +13 -2
  43. package/lib/settings.js +13 -0
  44. package/lib/tls/catalog.js +428 -0
  45. package/lib/tls/context.js +87 -161
  46. package/lib/tls/listeners.js +62 -0
  47. package/lib/tls/provision.js +1 -1
  48. package/lib/tls/status.js +128 -79
  49. package/lib/tls/store.js +3 -2
  50. package/lib/token-permission-view.js +253 -102
  51. package/lib/token-permissions.js +176 -26
  52. package/lib/tokens.js +7 -6
  53. package/lib/tools.js +5 -3
  54. package/lib/ui-routes/account-routes.js +195 -61
  55. package/lib/ui-routes/admin-config-routes.js +41 -21
  56. package/lib/ui-routes/admin-entities-routes.js +32 -22
  57. package/lib/ui-routes/mcp-consent-routes.js +72 -31
  58. package/lib/ui-routes/tls-config-routes.js +121 -74
  59. package/package.json +16 -16
  60. package/sbom.json +1 -1
  61. package/server.js +7 -1
  62. package/static/css/flyonui.css +1 -1
  63. package/static/css/public.css +41 -0
  64. package/static/css/src/app.tailwind.css +135 -4
  65. package/static/js/public.js +218 -0
  66. package/static/js/ui.js +89 -36
  67. package/static/licenses.html +55 -37
  68. package/translations/README.md +4 -3
  69. package/translations/de.mo +0 -0
  70. package/translations/de.po +296 -185
  71. package/translations/en.po +220 -128
  72. package/translations/es.mo +0 -0
  73. package/translations/es.po +558 -0
  74. package/translations/et.mo +0 -0
  75. package/translations/et.po +288 -181
  76. package/translations/fr.mo +0 -0
  77. package/translations/fr.po +295 -183
  78. package/translations/it.mo +0 -0
  79. package/translations/it.po +558 -0
  80. package/translations/ja.mo +0 -0
  81. package/translations/ja.po +268 -192
  82. package/translations/locales.json +24 -0
  83. package/translations/messages.pot +179 -127
  84. package/translations/nl.mo +0 -0
  85. package/translations/nl.po +288 -175
  86. package/translations/pl.mo +0 -0
  87. package/translations/pl.po +294 -181
  88. package/translations/sv.mo +0 -0
  89. package/translations/sv.po +555 -0
  90. package/translations/tr.mo +0 -0
  91. package/translations/tr.po +555 -0
  92. package/update-info.sh +12 -6
  93. package/views/account/login-redirect.hbs +6 -5
  94. package/views/account/passkeys.hbs +8 -8
  95. package/views/account/security.hbs +2 -2
  96. package/views/accounts/account.hbs +19 -21
  97. package/views/accounts/browse.hbs +1 -1
  98. package/views/accounts/edit.hbs +15 -15
  99. package/views/accounts/index.hbs +3 -3
  100. package/views/accounts/register/imap-server.hbs +27 -173
  101. package/views/accounts/register/validating.hbs +139 -0
  102. package/views/config/ai.hbs +15 -17
  103. package/views/config/branding.hbs +7 -7
  104. package/views/config/document-store/chat.hbs +9 -8
  105. package/views/config/document-store/index.hbs +14 -15
  106. package/views/config/document-store/mappings/index.hbs +5 -6
  107. package/views/config/document-store/mappings/new.hbs +1 -2
  108. package/views/config/document-store/pre-processing/index.hbs +4 -4
  109. package/views/config/email-processing.hbs +6 -6
  110. package/views/config/imap-proxy.hbs +7 -8
  111. package/views/config/license.hbs +9 -9
  112. package/views/config/logging.hbs +5 -7
  113. package/views/config/mcp.hbs +90 -58
  114. package/views/config/network.hbs +4 -4
  115. package/views/config/oauth/app.hbs +12 -12
  116. package/views/config/oauth/index.hbs +6 -6
  117. package/views/config/oauth/subscriptions.hbs +9 -9
  118. package/views/config/security.hbs +5 -7
  119. package/views/config/service.hbs +11 -10
  120. package/views/config/smtp.hbs +9 -12
  121. package/views/config/tls-upload.hbs +3 -3
  122. package/views/config/tls.hbs +281 -182
  123. package/views/config/webhooks.hbs +12 -15
  124. package/views/dashboard.hbs +9 -8
  125. package/views/gateways/edit.hbs +3 -3
  126. package/views/gateways/gateway.hbs +3 -3
  127. package/views/gateways/index.hbs +6 -6
  128. package/views/gateways/new.hbs +3 -3
  129. package/views/internals/index.hbs +15 -13
  130. package/views/layout/app.hbs +6 -6
  131. package/views/layout/login.hbs +32 -19
  132. package/views/layout/main.hbs +2 -2
  133. package/views/layout/prompt.hbs +15 -18
  134. package/views/layout/public.hbs +1 -1
  135. package/views/mcp/authorize.hbs +47 -45
  136. package/views/partials/accounts_table.hbs +5 -5
  137. package/views/partials/ace_assets.hbs +1 -1
  138. package/views/partials/add_account_modal.hbs +4 -4
  139. package/views/partials/address_list.hbs +4 -4
  140. package/views/partials/filter_editor_js.hbs +2 -2
  141. package/views/partials/gateway_form.hbs +5 -5
  142. package/views/partials/gateway_js.hbs +1 -1
  143. package/views/partials/mcp_access_levels.hbs +16 -9
  144. package/views/partials/mcp_account_limit.hbs +2 -2
  145. package/views/partials/mcp_tool_count.hbs +15 -14
  146. package/views/partials/oauth_config_header.hbs +2 -2
  147. package/views/partials/oauth_form.hbs +37 -42
  148. package/views/partials/public_alerts.hbs +1 -1
  149. package/views/partials/public_test_labels.hbs +15 -0
  150. package/views/partials/public_theme_init.hbs +1 -1
  151. package/views/partials/security_header.hbs +2 -2
  152. package/views/partials/template_form.hbs +4 -4
  153. package/views/partials/theme_init.hbs +1 -1
  154. package/views/partials/tls_security_card.hbs +4 -1
  155. package/views/partials/ui/form-field.hbs +6 -1
  156. package/views/partials/ui/setting-ref.hbs +12 -7
  157. package/views/partials/ui/stat-card.hbs +4 -1
  158. package/views/partials/ui/tabs.hbs +3 -7
  159. package/views/partials/webhook_form.hbs +9 -12
  160. package/views/partials/webhooks_editor_functions.hbs +1 -1
  161. package/views/reference/index.hbs +3 -3
  162. package/views/reference/redirect.hbs +1 -1
  163. package/views/reference/tag.hbs +1 -1
  164. package/views/reference/token.hbs +4 -4
  165. package/views/suppression-lists/index.hbs +8 -6
  166. package/views/suppression-lists/list.hbs +13 -8
  167. package/views/templates/edit.hbs +1 -1
  168. package/views/templates/index.hbs +10 -11
  169. package/views/templates/template.hbs +5 -5
  170. package/views/tokens/index.hbs +17 -17
  171. package/views/tokens/new.hbs +190 -93
  172. package/views/unsubscribe.hbs +1 -1
  173. package/views/webhooks/edit.hbs +1 -1
  174. package/views/webhooks/index.hbs +10 -11
  175. package/views/webhooks/new.hbs +1 -1
  176. package/views/webhooks/webhook.hbs +5 -6
  177. package/workers/api.js +9 -8
  178. package/workers/smtp.js +1 -1
@@ -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
@@ -534,13 +535,13 @@ async function reloadTlsCertificates(call, logger, context) {
534
535
  }
535
536
 
536
537
  // The settings a listener's certificate is resolved from: which stored sources are admitted
537
- // (tlsProvisioning), and which names are served (tlsHostnames, plus the service URL's own
538
- // hostname). Changing any of them changes what a running listener should be offering, and none of
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
539
540
  // that depends on a certificate being ordered - the reconciler returns immediately for every mode
540
541
  // but `acme`, and even there it only reloads when an order produced new material. So whoever writes
541
542
  // one of these keys hands the result to the listeners, the same way HTTP_PROXY_SETTINGS above is
542
543
  // what makes a proxy change reach the dispatchers.
543
- const TLS_MATERIAL_SETTINGS = ['tlsProvisioning', 'tlsHostnames', 'serviceUrl'];
544
+ const TLS_MATERIAL_SETTINGS = ['tlsProvisioning', 'tlsHostnames', 'serviceUrl'].concat(TLS_CERTIFICATE_SETTINGS);
544
545
 
545
546
  /**
546
547
  * Reloads the listeners when the settings that were just written change what they serve.
@@ -2285,6 +2286,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2285
2286
  subconnections: opts.subconnections && opts.subconnections.length ? opts.subconnections : null,
2286
2287
  redirectUrl: opts.redirectUrl,
2287
2288
  delegated: opts.delegated,
2289
+ skipServerSettings: opts.skipServerSettings,
2288
2290
  path: opts.path,
2289
2291
  n: opts.n,
2290
2292
  t: opts.t
@@ -661,6 +661,31 @@ function init(args) {
661
661
  .label('SMTP TLS')
662
662
  };
663
663
 
664
+ // The names above, in declaration order, for the checking page's hidden inputs - so the field set
665
+ // it posts is the one this schema declares rather than a second copy written out in the template.
666
+ const connectionFieldNames = Object.keys(connectionFields);
667
+
668
+ // Values validated against the fields above, ignoring everything else the form values carry
669
+ // (the signed blob, the address, the typed password, the app-password hint).
670
+ const connectionFieldsSchema = Joi.object(connectionFields).unknown();
671
+
672
+ // Whether autodiscovery gave the form enough to configure an account without asking the visitor
673
+ // for anything more. Two decisions read it: the settings page auto-runs its connection check on
674
+ // load, and a setup link issued with skipServerSettings skips that page altogether. One answer,
675
+ // because the skip turns a wrong one into an account created from settings nobody looked at.
676
+ //
677
+ // Asked of the schema rather than of a hand-kept list of required names - the shape that has to
678
+ // be kept in sync by hand, and the reason rebuildFormValues above rebuilds from the schema too.
679
+ // So "complete" means exactly "the create endpoint would accept this": a field added or made
680
+ // required there moves both decisions with it, and a discovered value the schema rejects (an
681
+ // address literal where a hostname is required) falls back to the form rather than skipping
682
+ // ahead to a submit that would 400.
683
+ //
684
+ // `_source` is the part no schema can answer. The usernames and passwords are filled in from
685
+ // what the visitor typed whatever autodiscovery found, so without it a domain that resolved to
686
+ // nothing would look complete on the strength of the password alone.
687
+ const hasCompleteServerSettings = values => !!(values && values._source) && !connectionFieldsSchema.validate(values, { convert: true }).error;
688
+
664
689
  // Rebuild safe re-render values from the SAME schema that validated the submission: convert coerces the
665
690
  // tri-state TLS/disabled checkboxes to real booleans (so {{#if values.X}} cannot re-check a box from the
666
691
  // string 'false'), and stripUnknown drops unexpected / prototype keys (and the appPassword_* hint fields)
@@ -726,6 +751,71 @@ function init(args) {
726
751
  return data;
727
752
  };
728
753
 
754
+ // Re-derive the app-password hint for a settings form that is being rendered from posted values
755
+ // rather than from a fresh autodiscovery result, and merge it into those values.
756
+ //
757
+ // serverFormSchema does not carry the appPassword_* fields (they feed unescaped template sinks),
758
+ // so stripUnknown drops them and they cannot be carried in a hidden input - echoing a
759
+ // client-controlled hint into the page was an XSS vector. The hint is therefore rebuilt here from
760
+ // the (trusted) email, out of a static table, never from the submitted payload.
761
+ //
762
+ // Shared by the failAction re-render and by the checking page's hand-off to the settings form, so
763
+ // a form reached either way shows the same "Application Password" label and instructions.
764
+ //
765
+ // Try the static domain table first: it is synchronous, needs no network, and covers the
766
+ // canonical provider domains, so a common-domain render costs no Redis round trips, no DNS, and
767
+ // no probe budget. Never throws - the hint is cosmetic and a failAction must not throw.
768
+ const applyAppPasswordHint = async (values, request, parsedBlob) => {
769
+ if (!values.email) {
770
+ return;
771
+ }
772
+
773
+ let appPassword = getAppPassword(values.email, false, request.app.gt);
774
+
775
+ // Custom-domain fallback (e.g. Google Workspace / M365 on their own domain) needs an MX
776
+ // lookup. failAction runs BEFORE the handler's signature gate, and the lookup drives outbound
777
+ // DNS, so gate it with the SAME machinery as the handler siblings, not a bare signature
778
+ // check: authorizeSignedProbe rejects a signature-only blob (e.g. a leaked tracking/
779
+ // unsubscribe blob) and one past its TTL, and bounds how many lookups one signed link can
780
+ // drive. Without it, any holder of any validly-signed blob could turn this render into an
781
+ // unbounded DNS oracle. On a normal validation-error re-render the nonce is not yet consumed
782
+ // (the create handler claims it only on success), so the hint still shows. values.data /
783
+ // values.sig are the schema-validated copies - rebuildFormValues drops them when malformed
784
+ // (e.g. duplicated fields).
785
+ if (!appPassword && values.data && values.sig) {
786
+ // Consult the per-domain memo BEFORE the probe/DNS work: a repeat re-submit of the same
787
+ // email must not re-run the MX lookup or draw the probe budget again.
788
+ const domain = values.email.split('@').pop().trim().toLowerCase();
789
+ const cached = getCachedAppPasswordHint(domain);
790
+ if (cached) {
791
+ appPassword = cached.value;
792
+ } else {
793
+ try {
794
+ if (parsedBlob) {
795
+ // Already parsed and signature-checked by the caller, so only the cap is left
796
+ // to apply - re-parsing would mean a second serviceSecret read and HMAC check
797
+ await enforceFormProbeLimit(parsedBlob.n, request.app.gt, request.logger);
798
+ } else {
799
+ await authorizeSignedProbe({ data: values.data, sig: values.sig }, request.app.gt, request.logger);
800
+ }
801
+ appPassword = await resolveAppPassword(values.email, request.app.gt);
802
+ // Cache the outcome (including a falsy "no hint" result) so subsequent renders for
803
+ // this domain are free.
804
+ setCachedAppPasswordHint(domain, appPassword);
805
+ } catch (err) {
806
+ // A rejected/expired blob, an exhausted probe cap, or a lookup failure must never
807
+ // break the render. Do NOT cache on failure - an exhausted probe cap or transient
808
+ // DNS error should not poison the hint for the whole TTL.
809
+ request.logger.debug({ msg: 'Failed to resolve app-password hint for form re-render', err });
810
+ }
811
+ }
812
+ }
813
+
814
+ if (appPassword) {
815
+ Object.assign(values, flattenObjectKeys({ appPassword }));
816
+ }
817
+ };
818
+
729
819
  // The expectation that applies to a parsed form blob (lib/account/expected-identity.js owns the
730
820
  // precedence and the lazy Redis fallback).
731
821
  const resolveFormExpectation = data => resolveExpectedIdentity(redis, { account: data.account, blobExpectation: data.expectedEmail });
@@ -820,6 +910,39 @@ function init(args) {
820
910
  values.imap_auth_pass = request.payload.password;
821
911
  values.smtp_auth_pass = request.payload.password;
822
912
 
913
+ // Autodiscovery has already answered the app-password question for this domain, so record
914
+ // it for the renders that cannot compute it from a static table: the failAction re-render
915
+ // and the checking page's hand-off both reach applyAppPasswordHint with nothing but the
916
+ // address, and would otherwise repeat the MX lookup this result came with. Only a positive
917
+ // answer is recorded - a miss here is not authoritative, since the MX-success branch
918
+ // resolves the hint without knowing whether the domain is an Exchange one.
919
+ if (serverSettings && serverSettings.appPassword) {
920
+ setCachedAppPasswordHint(request.payload.email.split('@').pop().trim().toLowerCase(), serverSettings.appPassword);
921
+ }
922
+
923
+ // Nothing is left for the user to fill in: the settings page would auto-verify what is
924
+ // already there and wait for a click. hasCompleteServerSettings() (above, beside
925
+ // connectionFields) is what both that auto-verify and the skip below agree on.
926
+ const settingsComplete = hasCompleteServerSettings(values);
927
+
928
+ if (settingsComplete && data.skipServerSettings) {
929
+ // The setup link asked for the server settings step to be skipped where possible.
930
+ // The page checks the connection and, when it holds, submits the same value set the
931
+ // settings form would have submitted; a failed check hands the user that form after
932
+ // all, so the skip can never end the setup on its own.
933
+ return h.view(
934
+ 'accounts/register/validating',
935
+ {
936
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
937
+ values,
938
+ connectionFieldNames
939
+ },
940
+ {
941
+ layout: 'public'
942
+ }
943
+ );
944
+ }
945
+
823
946
  return h.view(
824
947
  'accounts/register/imap-server',
825
948
  {
@@ -829,17 +952,7 @@ function init(args) {
829
952
  // page says why rather than looking like a form that forgot its defaults
830
953
  autodetectFailed: !serverSettings,
831
954
  autodetectDomain: request.payload.email.split('@').pop(),
832
- autoTest:
833
- values._source &&
834
- values.imap_auth_user &&
835
- values.smtp_auth_user &&
836
- values.imap_auth_pass &&
837
- values.smtp_auth_pass &&
838
- values.imap_host &&
839
- values.smtp_host &&
840
- values.imap_port &&
841
- values.smtp_port &&
842
- true
955
+ autoTest: settingsComplete
843
956
  },
844
957
  {
845
958
  layout: 'public'
@@ -1071,6 +1184,73 @@ function init(args) {
1071
1184
  ...connectionFields
1072
1185
  });
1073
1186
 
1187
+ // Where the checking page sends the user when the connection check did not pass: the ordinary
1188
+ // server settings form, prefilled with everything that was discovered and typed, so the one wrong
1189
+ // field can be corrected. Signature-gated like its siblings because it renders submitted values
1190
+ // back into a page. Rendering it drives no outbound connection of its own, so the gate here is
1191
+ // the signature and the nonce rather than authorizeSignedProbe; the one thing that can still
1192
+ // reach the network is the app-password hint's MX lookup, which draws on the per-nonce probe
1193
+ // budget itself and normally answers from the memo page 1 seeded.
1194
+ server.route({
1195
+ method: 'POST',
1196
+ path: '/accounts/new/imap/settings',
1197
+
1198
+ async handler(request, h) {
1199
+ const data = await parseSignedFormData(redis, request.payload, request.app.gt, { requireNonce: true });
1200
+
1201
+ // Rebuilt from the same schema that validated the submission, exactly as the failAction
1202
+ // re-renders do: coerced tri-state checkboxes, no unknown or prototype keys. The two
1203
+ // passwords are kept rather than dropped - they are what the user typed one step ago and
1204
+ // the form has to come up filled in, the same as it would have been had this page been
1205
+ // rendered directly.
1206
+ const values = rebuildFormValues(serverFormSchema, request.payload);
1207
+ await applyAppPasswordHint(values, request, data);
1208
+
1209
+ return h.view(
1210
+ 'accounts/register/imap-server',
1211
+ {
1212
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
1213
+ values,
1214
+ // The checking page says a connection failed, so the form opens by saying why it
1215
+ // is being asked for rather than looking like a step that appeared from nowhere.
1216
+ // The detail stays on the page the visitor read it on; this is the reminder. The
1217
+ // no-script Continue and the manual escape from a slow check arrive without it,
1218
+ // because no check ran for them and neither must claim one failed.
1219
+ checkFailed: request.query.checkFailed,
1220
+ // The check just failed, so do not repeat it on load: the page opens on the fields
1221
+ // to correct rather than on a spinner about to give the same answer.
1222
+ autoTest: false
1223
+ },
1224
+ {
1225
+ layout: 'public'
1226
+ }
1227
+ );
1228
+ },
1229
+
1230
+ options: {
1231
+ auth: false,
1232
+
1233
+ validate: {
1234
+ options: {
1235
+ stripUnknown: true,
1236
+ abortEarly: false,
1237
+ convert: true
1238
+ },
1239
+
1240
+ failAction,
1241
+
1242
+ // Cosmetic and client-set: it chooses which sentence the page opens with and nothing
1243
+ // else, so it rides the action URL rather than widening a payload schema that carries
1244
+ // two plaintext passwords.
1245
+ query: Joi.object({
1246
+ checkFailed: Joi.boolean().truthy('1').falsy('', '0').default(false)
1247
+ }),
1248
+
1249
+ payload: serverFormSchema
1250
+ }
1251
+ }
1252
+ });
1253
+
1074
1254
  server.route({
1075
1255
  method: 'POST',
1076
1256
  path: '/accounts/new/imap/server',
@@ -1212,56 +1392,10 @@ function init(args) {
1212
1392
  // passwords) - see rebuildFormValues.
1213
1393
  const values = rebuildFormValues(serverFormSchema, request.payload, ['imap_auth_pass', 'smtp_auth_pass']);
1214
1394
 
1215
- // serverFormSchema does not carry the appPassword_* hint fields (they feed unescaped
1216
- // template sinks), so stripUnknown drops them. Re-derive the hint server-side from the
1217
- // (trusted) email so the re-rendered form still shows the app-password label and
1218
- // instructions for Gmail/iCloud/Outlook/etc. The values come from a static table, never
1219
- // from the submitted payload, so they are safe to render.
1220
- //
1221
- // Try the static domain table first: it is synchronous, needs no network, and covers the
1222
- // canonical provider domains, so a common-domain re-render costs no Redis round trips, no
1223
- // DNS, and no probe budget.
1224
- if (values.email) {
1225
- let appPassword = getAppPassword(values.email, false, request.app.gt);
1226
-
1227
- // Custom-domain fallback (e.g. Google Workspace / M365 on their own domain) needs an
1228
- // MX lookup. failAction runs BEFORE the handler's signature gate, and the lookup
1229
- // drives outbound DNS, so gate it with the SAME machinery as the handler siblings, not
1230
- // a bare signature check: authorizeSignedProbe rejects a signature-only blob (e.g. a
1231
- // leaked tracking/unsubscribe blob) and one past its TTL, and bounds how many lookups
1232
- // one signed link can drive. Without it, any holder of any validly-signed blob could
1233
- // turn this re-render into an unbounded DNS oracle. On a normal validation-error
1234
- // re-render the nonce is not yet consumed (the handler claims it only on success), so
1235
- // the hint still shows. values.data/values.sig are the schema-validated copies -
1236
- // rebuildFormValues drops them when malformed (e.g. duplicated fields).
1237
- if (!appPassword && values.data && values.sig) {
1238
- // Consult the per-domain memo BEFORE the probe/DNS work: a repeat re-submit of
1239
- // the same email must not re-run the MX lookup or draw the probe budget again.
1240
- const domain = values.email.split('@').pop().trim().toLowerCase();
1241
- const cached = getCachedAppPasswordHint(domain);
1242
- if (cached) {
1243
- appPassword = cached.value;
1244
- } else {
1245
- try {
1246
- await authorizeSignedProbe({ data: values.data, sig: values.sig }, request.app.gt, request.logger);
1247
- appPassword = await resolveAppPassword(values.email, request.app.gt);
1248
- // Cache the outcome (including a falsy "no hint" result) so subsequent
1249
- // re-renders for this domain are free.
1250
- setCachedAppPasswordHint(domain, appPassword);
1251
- } catch (err) {
1252
- // The hint is cosmetic; a rejected/expired blob, an exhausted probe cap, or a
1253
- // lookup failure must never break the error re-render (failAction must not throw).
1254
- // Do NOT cache on failure - an exhausted probe cap or transient DNS error should
1255
- // not poison the hint for the whole TTL.
1256
- request.logger.debug({ msg: 'Failed to resolve app-password hint for form re-render', err });
1257
- }
1258
- }
1259
- }
1260
-
1261
- if (appPassword) {
1262
- Object.assign(values, flattenObjectKeys({ appPassword }));
1263
- }
1264
- }
1395
+ // The hint fields are not carried by the schema, so rebuild them from the email
1396
+ // (see applyAppPasswordHint) - otherwise a Gmail or iCloud re-render loses the
1397
+ // "Application Password" label and the instructions link.
1398
+ await applyAppPasswordHint(values, request);
1265
1399
 
1266
1400
  return h
1267
1401
  .view(