emailengine-app 2.78.0 → 2.79.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 (155) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +68 -0
  4. package/config/e2e.toml +2 -1
  5. package/config/test.toml +2 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/lib/account.js +112 -36
  8. package/lib/api-reference/format.js +91 -4
  9. package/lib/api-reference/model.js +144 -19
  10. package/lib/api-reference/schema-tree.js +282 -28
  11. package/lib/api-routes/account-routes.js +80 -34
  12. package/lib/api-routes/blocklist-routes.js +21 -47
  13. package/lib/api-routes/chat-routes.js +10 -12
  14. package/lib/api-routes/delivery-test-routes.js +6 -26
  15. package/lib/api-routes/export-routes.js +2 -0
  16. package/lib/api-routes/gateway-routes.js +52 -11
  17. package/lib/api-routes/license-routes.js +2 -0
  18. package/lib/api-routes/mailbox-routes.js +29 -26
  19. package/lib/api-routes/message-routes.js +27 -21
  20. package/lib/api-routes/oauth2-app-routes.js +11 -29
  21. package/lib/api-routes/operation-impact.js +80 -0
  22. package/lib/api-routes/outbox-routes.js +15 -5
  23. package/lib/api-routes/permission-map.js +401 -0
  24. package/lib/api-routes/route-helpers.js +294 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +66 -38
  27. package/lib/api-routes/stats-routes.js +2 -2
  28. package/lib/api-routes/submit-routes.js +53 -31
  29. package/lib/api-routes/template-routes.js +3 -0
  30. package/lib/api-routes/token-routes.js +526 -72
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/arf-detect.js +17 -4
  33. package/lib/auth-token.js +80 -8
  34. package/lib/bounce-detect.js +28 -17
  35. package/lib/consts.js +16 -0
  36. package/lib/db.js +26 -2
  37. package/lib/delivery-error.js +30 -1
  38. package/lib/email-client/base-client.js +27 -41
  39. package/lib/email-client/gmail-client.js +23 -17
  40. package/lib/email-client/imap/mailbox.js +58 -59
  41. package/lib/email-client/imap/subconnection.js +10 -7
  42. package/lib/email-client/imap/sync-operations.js +46 -46
  43. package/lib/email-client/imap-client.js +85 -28
  44. package/lib/email-client/message-builder.js +3 -3
  45. package/lib/email-client/notification-handler.js +1 -1
  46. package/lib/email-client/outlook/graph-api.js +10 -4
  47. package/lib/email-client/outlook-client.js +56 -64
  48. package/lib/email-client/smtp-pool-manager.js +1 -1
  49. package/lib/enum-descriptions.js +92 -2
  50. package/lib/export.js +1 -1
  51. package/lib/field-usage.js +133 -0
  52. package/lib/gateway.js +1 -1
  53. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  54. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  55. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  57. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  58. package/lib/imapproxy/imap-server.js +27 -7
  59. package/lib/license-beacon.js +4 -9
  60. package/lib/lists.js +49 -1
  61. package/lib/llm-pre-process.js +5 -5
  62. package/lib/logger.js +5 -1
  63. package/lib/lua/h-set-new-mark.lua +36 -0
  64. package/lib/message-port-stream.js +84 -1
  65. package/lib/metrics-collector.js +2 -2
  66. package/lib/oauth/gmail.js +9 -12
  67. package/lib/oauth/mail-ru.js +5 -7
  68. package/lib/oauth/outlook.js +9 -9
  69. package/lib/oauth/pubsub/google.js +25 -10
  70. package/lib/oauth/scope-checker.js +1 -1
  71. package/lib/oauth2-apps.js +290 -292
  72. package/lib/openapi/build-document.js +20 -8
  73. package/lib/openapi/joi-schema.js +20 -0
  74. package/lib/outbox.js +85 -17
  75. package/lib/pre-process.js +8 -8
  76. package/lib/queue-stats.js +49 -0
  77. package/lib/read-env-value.js +1 -1
  78. package/lib/reconnection-manager.js +2 -2
  79. package/lib/rewrite-text-nodes.js +4 -3
  80. package/lib/routes-ui.js +4 -0
  81. package/lib/schemas.js +218 -162
  82. package/lib/settings.js +98 -5
  83. package/lib/sub-script.js +2 -1
  84. package/lib/swagger-options.js +2 -1
  85. package/lib/templates.js +4 -4
  86. package/lib/threads.js +2 -2
  87. package/lib/token-audit-log.js +231 -0
  88. package/lib/token-permission-view.js +219 -0
  89. package/lib/token-permissions.js +172 -0
  90. package/lib/tokens.js +247 -66
  91. package/lib/tools.js +142 -37
  92. package/lib/ui-routes/account-routes.js +42 -15
  93. package/lib/ui-routes/admin-config-routes.js +18 -10
  94. package/lib/ui-routes/admin-entities-routes.js +117 -38
  95. package/lib/ui-routes/auth-routes.js +30 -24
  96. package/lib/ui-routes/export-routes.js +10 -4
  97. package/lib/ui-routes/oauth-config-routes.js +12 -12
  98. package/lib/ui-routes/reference-routes.js +3 -3
  99. package/lib/ui-routes/route-helpers.js +78 -2
  100. package/lib/ui-routes/settings-page.js +1 -1
  101. package/lib/ui-routes/smtp-test-routes.js +1 -1
  102. package/lib/ui-routes/suppression-list-routes.js +299 -0
  103. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  104. package/lib/utils/decode-headers.js +42 -0
  105. package/lib/utils/header-map.js +48 -0
  106. package/lib/utils/network.js +2 -2
  107. package/lib/utils/unsafe-key.js +59 -0
  108. package/lib/web-safe-html.js +1 -1
  109. package/lib/webhook-routing.js +84 -0
  110. package/lib/webhooks.js +48 -14
  111. package/package.json +11 -10
  112. package/sbom.json +1 -1
  113. package/server.js +116 -55
  114. package/static/css/flyonui.css +1 -1
  115. package/static/css/src/app.tailwind.css +136 -9
  116. package/static/js/reference.js +456 -10
  117. package/static/js/ui.js +43 -0
  118. package/static/licenses.html +51 -41
  119. package/translations/messages.pot +59 -59
  120. package/views/accounts/account.hbs +75 -13
  121. package/views/accounts/browse.hbs +19 -36
  122. package/views/accounts/edit.hbs +2 -2
  123. package/views/config/logging.hbs +6 -0
  124. package/views/config/oauth/app.hbs +0 -2
  125. package/views/config/security.hbs +13 -0
  126. package/views/gateways/edit.hbs +1 -1
  127. package/views/gateways/gateway.hbs +2 -2
  128. package/views/gateways/index.hbs +7 -7
  129. package/views/partials/accounts_table.hbs +7 -7
  130. package/views/partials/oauth_form.hbs +0 -15
  131. package/views/partials/reference/disclosure.hbs +8 -2
  132. package/views/partials/reference/operation.hbs +47 -13
  133. package/views/partials/reference/params.hbs +17 -1
  134. package/views/partials/reference/schema-node.hbs +110 -52
  135. package/views/partials/reference/schema-tools.hbs +25 -0
  136. package/views/partials/reference/try-it.hbs +84 -11
  137. package/views/partials/side_menu.hbs +1 -0
  138. package/views/partials/ui/checkbox.hbs +2 -2
  139. package/views/partials/ui/tabs.hbs +7 -1
  140. package/views/reference/token.hbs +4 -0
  141. package/views/suppression-lists/index.hbs +85 -0
  142. package/views/suppression-lists/list.hbs +87 -0
  143. package/views/templates/index.hbs +10 -4
  144. package/views/templates/template.hbs +1 -1
  145. package/views/tokens/index.hbs +53 -6
  146. package/views/tokens/new.hbs +334 -5
  147. package/workers/api.js +185 -102
  148. package/workers/documents.js +46 -26
  149. package/workers/export.js +20 -8
  150. package/workers/imap-proxy.js +2 -2
  151. package/workers/imap.js +77 -78
  152. package/workers/smtp.js +13 -7
  153. package/workers/submit.js +40 -30
  154. package/workers/webhooks.js +80 -26
  155. package/lib/feature-flags.js +0 -48
@@ -1,26 +1,36 @@
1
1
  'use strict';
2
2
 
3
3
  const Boom = require('@hapi/boom');
4
+ const { isDeepStrictEqual } = require('node:util');
5
+ const tokenPermissions = require('../token-permissions');
4
6
 
5
7
  // Shared helpers for the extracted API route modules under lib/api-routes/.
6
8
 
7
- // Standard API error handler. Logs the failure, passes Boom errors through unchanged, and converts
8
- // plain errors into a Boom error while preserving the original statusCode and an optional
9
- // machine-readable err.code. This function ALWAYS throws and never returns a value, so callers use it
10
- // as the final statement inside a catch block: `catch (err) { handleError(request, err); }`.
11
- function handleError(request, err) {
9
+ // Derives the failure's HTTP status and logs it under the shared level policy. Kept separate from
10
+ // handleError for the few catch blocks that need a custom response shape but must not fork the
11
+ // logging policy. Unlike handleError this only logs: it RETURNS the derived statusCode instead of
12
+ // throwing, so a caller that uses it must still produce a response of its own.
13
+ function logApiError(request, err) {
12
14
  // Lower-level libraries (e.g. ImapFlow) flag "this server lacks the required capability" with a
13
15
  // machine code but no HTTP status. Surface it as a 422 client error instead of a generic 500 - the
14
16
  // request is well-formed, the account just cannot satisfy it (e.g. label search on non-Gmail IMAP).
15
- let isBoom = Boom.isBoom(err);
16
- let statusCode = isBoom ? err.output.statusCode : err.statusCode || (err.code === 'MissingServerExtension' ? 422 : 500);
17
+ let statusCode = Boom.isBoom(err) ? err.output.statusCode : err.statusCode || (err.code === 'MissingServerExtension' ? 422 : 500);
17
18
 
18
19
  // Log expected client errors (4xx, e.g. a 404 from an existence-check probe) at warn so they do not
19
20
  // flood the error stream, while genuine server faults (5xx) stay at error.
20
21
  let logLevel = statusCode >= 400 && statusCode < 500 ? 'warn' : 'error';
21
22
  request.logger[logLevel]({ msg: 'API request failed', statusCode, err });
23
+ return statusCode;
24
+ }
25
+
26
+ // Standard API error handler. Logs the failure, passes Boom errors through unchanged, and converts
27
+ // plain errors into a Boom error while preserving the original statusCode and an optional
28
+ // machine-readable err.code. This function ALWAYS throws and never returns a value, so callers use it
29
+ // as the final statement inside a catch block: `catch (err) { handleError(request, err); }`.
30
+ function handleError(request, err) {
31
+ let statusCode = logApiError(request, err);
22
32
 
23
- if (isBoom) {
33
+ if (Boom.isBoom(err)) {
24
34
  throw err;
25
35
  }
26
36
  const error = Boom.boomify(err, { statusCode });
@@ -64,4 +74,279 @@ function flattenOAuthAppMeta(app) {
64
74
  }
65
75
  }
66
76
 
67
- module.exports = { handleError, throwNotFound, flattenOAuthAppMeta };
77
+ // What a masked secret reads as in an API response. Same marker the account, gateway and OAuth2-app
78
+ // getters already use for stored passwords, so a client sees one convention.
79
+ const MASKED = '******';
80
+
81
+ // One sentence for every endpoint that returns a masked entity, so the document says what a reader
82
+ // will actually get back. The convention predates this - the gateway getter already documented its
83
+ // masked password - but the wording lived in each route.
84
+ const MASK_NOTE =
85
+ 'Credentials are masked: stored passwords, the credentials in any proxy or webhook URL, and the values of custom webhook headers all read back as "%s". A masked value is not the stored one - leave the field out of an update rather than writing it back, otherwise the mask replaces the credential.'.replace(
86
+ '%s',
87
+ MASKED
88
+ );
89
+
90
+ // Masks the VALUES of a custom-header list, keeping the keys.
91
+ //
92
+ // These carry credentials for someone else's system - the documented example is
93
+ // `Authorization: Bearer <token>` - and they were returned in full by the account and webhook-route
94
+ // getters while the passwords next to them were masked. Reading one back is enough to post forged,
95
+ // correctly authenticated webhooks into the customer's receiver.
96
+ //
97
+ // The keys stay visible because they carry no secret and are what makes the response useful: a
98
+ // reader can see THAT an Authorization header is configured without being handed its value.
99
+ function maskCustomHeaders(headers) {
100
+ if (!Array.isArray(headers)) {
101
+ return headers;
102
+ }
103
+
104
+ // A header with no value has no secret to hide, and masking it would advertise one that is not
105
+ // there - the schema defaults `value` to an empty string, so this is a real stored shape.
106
+ return headers.map(header => (header && typeof header === 'object' && header.value ? Object.assign({}, header, { value: MASKED }) : header));
107
+ }
108
+
109
+ // Masks the credentials in a URL, keeping everything that identifies where it points.
110
+ //
111
+ // Several stored URLs accept inline credentials - `proxyUrl` as `socks5://user:pass@host:1080`, and
112
+ // webhook targets as `https://user:pass@receiver.example.com/hook` - so returning them verbatim
113
+ // published a working credential. Host, port and path stay: they are operational information a
114
+ // client legitimately reads back, and blanking them would break anything that displays the value.
115
+ //
116
+ // Distinct from redactUrlCredentials() in lib/tools.js, which serves the log stream: that one may
117
+ // return a placeholder that is not a URL at all. This one has to come back schema-valid and still
118
+ // identify the destination, because it lands in an API response - which is also why it replaces the
119
+ // credentials in place rather than dropping the userinfo section.
120
+ function maskUrlPassword(url) {
121
+ if (!url || typeof url !== 'string') {
122
+ return url;
123
+ }
124
+
125
+ let parsed;
126
+ try {
127
+ parsed = new URL(url);
128
+ } catch (err) {
129
+ // An unparseable value could itself be the credential that made it unparseable, so it is
130
+ // replaced rather than echoed - the same call lib/tools.js makes for the log stream. Empty
131
+ // rather than a placeholder because every schema here allows it, and a value that cannot be
132
+ // parsed was never a usable destination anyway.
133
+ return '';
134
+ }
135
+
136
+ // Gated on either half: commercial proxies commonly key on a token in the USERNAME with no
137
+ // password at all, and lib/tools.js reads that shape (userId with an empty password).
138
+ if (!parsed.username && !parsed.password) {
139
+ return url;
140
+ }
141
+
142
+ // Each half is masked only where there is one. Rewriting only the password published the
143
+ // username in full, which for the shape above IS the credential - and writing a password into a
144
+ // URL that never had one reports a secret that does not exist, showing the account as more
145
+ // configured than it is.
146
+ if (parsed.username) {
147
+ parsed.username = MASKED;
148
+ }
149
+
150
+ if (parsed.password) {
151
+ parsed.password = MASKED;
152
+ }
153
+
154
+ return parsed.href;
155
+ }
156
+
157
+ // Stored values that are URLs which may embed a password.
158
+ const URL_SECRET_KEYS = ['proxy', 'proxyUrl', 'httpProxyUrl', 'webhooks', 'targetUrl'];
159
+
160
+ // Stored values that are {key, value} header lists whose values are credentials.
161
+ const HEADER_SECRET_KEYS = ['customHeaders', 'webhooksCustomHeaders'];
162
+
163
+ // A failed submission records the route it took, including the proxy it used, and that record is
164
+ // then persisted onto the account, the gateway and the queue entry. So the same proxy URL reappears
165
+ // nested inside a status or error object, one field over from where it was masked.
166
+ function maskNetworkRouting(container) {
167
+ if (!container || typeof container !== 'object') {
168
+ return;
169
+ }
170
+
171
+ if (container.networkRouting && typeof container.networkRouting === 'object' && container.networkRouting.proxy) {
172
+ container.networkRouting.proxy = maskUrlPassword(container.networkRouting.proxy);
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Masks every credential-bearing field of an entity about to be returned from the API.
178
+ *
179
+ * One function rather than a mask call per field per handler, because the leak this closes was
180
+ * exactly the failure mode of doing it per field: `proxy` was masked in the account getter while the
181
+ * same URL came back through `smtpStatus.networkRouting.proxy` in the same response body, and
182
+ * `customHeaders` was masked in the webhook getter while `targetUrl` beside it carried basic auth.
183
+ * With the field set in one place, a newly added handler gets all of them and a newly added secret
184
+ * field reaches every handler at once.
185
+ *
186
+ * Containers are enumerated rather than walked recursively on purpose: an outbox entry carries the
187
+ * submitted message, and a recursive scan would read through mail content to find nothing.
188
+ *
189
+ * Mutates and returns the entity. Safe because every caller passes a per-request object it just
190
+ * deserialized from Redis or built from a queue job, never shared state.
191
+ *
192
+ * @param {Object} entry - the entity about to be serialized into a response
193
+ * @returns {Object} the same object, with credentials masked
194
+ */
195
+ function maskSecrets(entry) {
196
+ if (!entry || typeof entry !== 'object') {
197
+ return entry;
198
+ }
199
+
200
+ for (const key of URL_SECRET_KEYS) {
201
+ if (entry[key]) {
202
+ entry[key] = maskUrlPassword(entry[key]);
203
+ }
204
+ }
205
+
206
+ for (const key of HEADER_SECRET_KEYS) {
207
+ if (entry[key]) {
208
+ entry[key] = maskCustomHeaders(entry[key]);
209
+ }
210
+ }
211
+
212
+ // smtpStatus on an account, lastError on a gateway, progress.error on a queue entry.
213
+ //
214
+ // `lastErrorState` is the account's, and it is a separate entry rather than a rename because the
215
+ // two really are different keys: Account.unserializeAccountData() parses the connection error
216
+ // under `lastErrorState`, and the getter only renames it to `lastError` on the way out, well
217
+ // after this runs. Masking one name and not the other left the account getter publishing the
218
+ // proxy URL of the failed connection while the reviewer read a mask call that looked like it
219
+ // covered it.
220
+ for (const container of ['smtpStatus', 'lastError', 'lastErrorState', 'error', 'progress']) {
221
+ maskNetworkRouting(entry[container]);
222
+ if (entry[container] && typeof entry[container] === 'object') {
223
+ maskNetworkRouting(entry[container].error);
224
+ }
225
+ }
226
+
227
+ return entry;
228
+ }
229
+
230
+ // Compares header lists on the two fields a client round-trips, so an echo check is not thrown
231
+ // off by incidental extra properties on either side
232
+ function normalizedHeaderList(headers) {
233
+ return [].concat(headers || []).map(header => ({ key: (header && header.key) || '', value: (header && header.value) || '' }));
234
+ }
235
+
236
+ /**
237
+ * Whether an incoming value carries the mask maskSecrets() writes into responses where a
238
+ * credential should be.
239
+ *
240
+ * A write-side guard for the masking convention: a masked value passes the joi schemas (it is a
241
+ * well-formed URL / header list), so without this check a read-modify-write client silently
242
+ * replaces the stored credential with the literal mask. Keys outside the two secret lists are
243
+ * never masked on the way out, so they report false.
244
+ *
245
+ * Currently wired into POST /v1/settings only. The account and gateway update routes share the
246
+ * read-side masking but still follow the documented MASK_NOTE contract on writes ("leave the
247
+ * field out of an update rather than writing it back") - closing them the same way is an open
248
+ * follow-up, and needs a shape this helper does not cover yet (the gateway password is a bare
249
+ * masked string, not a URL or header list).
250
+ *
251
+ * @param {String} key - the setting/field name
252
+ * @param {*} value - the incoming value
253
+ * @returns {Boolean} true when the value carries the mask placeholder
254
+ */
255
+ function containsMaskedSecret(key, value) {
256
+ if (URL_SECRET_KEYS.includes(key)) {
257
+ if (!value || typeof value !== 'string') {
258
+ return false;
259
+ }
260
+ let parsed;
261
+ try {
262
+ parsed = new URL(value);
263
+ } catch (err) {
264
+ return false;
265
+ }
266
+ return parsed.username === MASKED || parsed.password === MASKED;
267
+ }
268
+
269
+ if (HEADER_SECRET_KEYS.includes(key)) {
270
+ return Array.isArray(value) && value.some(header => header && typeof header === 'object' && header.value === MASKED);
271
+ }
272
+
273
+ return false;
274
+ }
275
+
276
+ /**
277
+ * Whether an incoming masked value is exactly what a read of the stored value returns - i.e. a
278
+ * read-modify-write client posting back what GET handed it, with this key untouched. Such an echo
279
+ * is not an update at all, so the caller can skip the write instead of refusing it.
280
+ *
281
+ * @param {String} key - the setting/field name
282
+ * @param {*} incoming - the incoming value
283
+ * @param {*} stored - the currently stored value
284
+ * @returns {Boolean} true when the incoming value is the masked echo of the stored one
285
+ */
286
+ function isMaskedRoundTrip(key, incoming, stored) {
287
+ if (URL_SECRET_KEYS.includes(key)) {
288
+ return !!stored && typeof incoming === 'string' && maskUrlPassword(stored) === incoming;
289
+ }
290
+
291
+ if (HEADER_SECRET_KEYS.includes(key)) {
292
+ return Array.isArray(incoming) && isDeepStrictEqual(normalizedHeaderList(maskCustomHeaders(stored)), normalizedHeaderList(incoming));
293
+ }
294
+
295
+ return false;
296
+ }
297
+
298
+ /**
299
+ * Refuses a submission that redirects the connection, when the credential making it is narrowed.
300
+ *
301
+ * `proxy` in a submit payload overrides the account's own route and the instance-wide one
302
+ * (applyProxyConfig in lib/email-client/message-builder.js takes the payload first), and the SMTP
303
+ * session it redirects still carries the account's decrypted username and password. A SOCKS
304
+ * endpoint therefore decides where the connection lands, can answer as the mail server, and - with
305
+ * no STARTTLS advertised and nothing requiring it - collects AUTH in plaintext. So the field turns
306
+ * "may send mail" into "may read the credential that sends the mail".
307
+ *
308
+ * That is the same reasoning that put the gateway writes in the never-grantable `admin` group:
309
+ * reading a stored credential back is masked, sending it somewhere is not. It applies here because
310
+ * `submit` is a grantable group, so the narrowing has to hold the line the route grant cannot.
311
+ *
312
+ * Only for narrowed tokens. An unnarrowed one already reaches PUT /v1/account/{account} and can
313
+ * point the account's own proxy wherever it likes, so refusing it here would cost a documented
314
+ * capability and buy nothing.
315
+ *
316
+ * The refusal is not written to the per-token audit log, deliberately. That trail records what a
317
+ * credential was ADMITTED to attempt - it is written by the auth strategy, before payload validation
318
+ * and the handler, so a 400 or a 404 does not appear in it either, and this is a handler-level
319
+ * refusal of one field. It does reach the application log: handleError() logs the 403 through
320
+ * `request.logger`, which the strategy has already bound the token id to.
321
+ *
322
+ * @param {Object} request - the Hapi request
323
+ */
324
+ function assertNoNetworkOverride(request) {
325
+ if (!request.payload || !request.payload.proxy) {
326
+ return;
327
+ }
328
+
329
+ // Asked of the module that enforces the narrowing rather than by testing `permissions` for
330
+ // truthiness, so `{}` and an unreadable record are read here exactly as they are at the
331
+ // strategy. `artifacts` is the token record the api-token strategy resolved.
332
+ if (!tokenPermissions.inspect(request.auth && request.auth.artifacts).narrowed) {
333
+ return;
334
+ }
335
+
336
+ throw Boom.forbidden('A token with restricted permissions can not override the connection route');
337
+ }
338
+
339
+ module.exports = {
340
+ handleError,
341
+ logApiError,
342
+ throwNotFound,
343
+ flattenOAuthAppMeta,
344
+ maskCustomHeaders,
345
+ maskUrlPassword,
346
+ maskSecrets,
347
+ containsMaskedSecret,
348
+ isMaskedRoundTrip,
349
+ assertNoNetworkOverride,
350
+ MASKED,
351
+ MASK_NOTE
352
+ };
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ // Where a route keeps the metadata that is about its documentation and its permissions rather than
4
+ // about serving the request: `plugins.openapi` in the route definition.
5
+ //
6
+ // Its own module because two readers need it and neither should own it. lib/openapi/build-document.js
7
+ // publishes what it finds there, and ./permission-map.js reads `x-ee-impact` out of it at request
8
+ // time to resolve what a token needs. Keeping the accessor in either would have the other spell the
9
+ // slot out again, and one of them feeds access control: rename the key with two independent readers
10
+ // and the second starts seeing an empty object, which downgrades every declared impact to the method
11
+ // default with nothing failing.
12
+ //
13
+ // It sits under lib/api-routes/ rather than lib/openapi/ so the dependency runs one way. The
14
+ // generator reads route metadata; route modules do not read the generator.
15
+
16
+ const PLUGIN_OPTIONS_KEY = 'openapi';
17
+
18
+ /**
19
+ * The documentation and permission metadata a route declares.
20
+ *
21
+ * @param {Object} route - a `server.table()` entry, or a live `request.route`
22
+ * @returns {Object} the route's `plugins.openapi`, or an empty object when it declares none
23
+ */
24
+ function pluginOptions(route) {
25
+ return (route && route.settings && route.settings.plugins && route.settings.plugins[PLUGIN_OPTIONS_KEY]) || {};
26
+ }
27
+
28
+ module.exports = { pluginOptions };
@@ -1,12 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  const Joi = require('joi');
4
- const { redis, documentsQueue, notifyQueue, submitQueue } = require('../db');
4
+ const { QUEUES_BY_NAME } = require('../db');
5
5
  const settings = require('../settings');
6
6
  const consts = require('../consts');
7
- const { REDIS_PREFIX } = consts;
8
7
  const { failAction } = require('../tools');
9
- const { handleError } = require('./route-helpers');
8
+ const { queueStats } = require('../queue-stats');
9
+ const Boom = require('@hapi/boom');
10
+ const { handleError, maskSecrets, containsMaskedSecret, isMaskedRoundTrip, MASKED } = require('./route-helpers');
10
11
  const { settingsSchema, settingsQuerySchema, apiResponses, ENUM_DESCRIPTIONS } = require('../schemas');
11
12
 
12
13
  // Response variant of the settings schema. Secret values are masked and returned as booleans,
@@ -59,11 +60,20 @@ async function init(args) {
59
60
  values[key] = value;
60
61
  }
61
62
  }
63
+
64
+ // The global equivalents of the credential-bearing account fields. encryptedKeys above
65
+ // covers what is encrypted at rest, which is not the same set: proxyUrl, httpProxyUrl,
66
+ // webhooks and webhooksCustomHeaders are stored in the clear and were returned in full,
67
+ // so this endpoint disclosed exactly what the account getters were masking. It sits in
68
+ // the never-grantable admin group, so no narrowed token reaches it - but leaving the
69
+ // asymmetry here is how the next reader learns the wrong pattern.
70
+ maskSecrets(values);
71
+
62
72
  return values;
63
73
  },
64
74
  options: {
65
75
  description: 'List specific settings',
66
- notes: 'List setting values for specific keys',
76
+ notes: `List setting values for specific keys. Credentials are masked: the credentials in any proxy or webhook URL and the values of custom webhook headers read back as "${MASKED}", and encrypted secrets are returned as booleans. A masked value is not the stored one - POST /v1/settings skips it when it matches the stored value and refuses it otherwise.`,
67
77
  tags: ['api', 'Settings'],
68
78
 
69
79
  plugins: {
@@ -101,25 +111,47 @@ async function init(args) {
101
111
  path: '/v1/settings',
102
112
 
103
113
  async handler(request) {
104
- let updated = [];
105
- for (let key of Object.keys(request.payload)) {
106
- if (key === 'webhooksEnabled' && !request.payload.webhooksEnabled) {
107
- // clear error message (if exists)
108
- await settings.clear('webhookErrorFlag');
109
- }
114
+ let applied = {};
115
+ try {
116
+ for (let key of Object.keys(request.payload)) {
117
+ let value = request.payload[key];
118
+
119
+ // GET /v1/settings masks stored credentials ("******"), and the masked values
120
+ // pass the schemas here - they are well-formed URLs and header lists - so a
121
+ // read-modify-write client would silently replace the stored credential with
122
+ // the literal mask. The unchanged masked echo of the stored value is skipped
123
+ // as "not an update"; a mask anywhere else is refused, because the credential
124
+ // it stands for cannot be reconstructed.
125
+ if (containsMaskedSecret(key, value)) {
126
+ if (isMaskedRoundTrip(key, value, await settings.get(key))) {
127
+ continue;
128
+ }
129
+ throw Boom.badRequest(
130
+ `The value for "${key}" carries the masked placeholder "${MASKED}" instead of a credential. Send the real value, or leave the key out to keep the stored one`
131
+ );
132
+ }
110
133
 
111
- await settings.set(key, request.payload[key]);
112
- updated.push(key);
134
+ if (key === 'webhooksEnabled' && !value) {
135
+ // clear error message (if exists)
136
+ await settings.clear('webhookErrorFlag');
137
+ }
138
+
139
+ await settings.set(key, value);
140
+ applied[key] = value;
141
+ }
142
+ } catch (err) {
143
+ handleError(request, err);
113
144
  }
114
145
 
115
146
  // Broadcast to all workers (including this one); each reloads its HTTP proxy agent via
116
- // the 'settings' message handler, so no inline reload is needed here.
117
- notify('settings', request.payload);
118
- return { updated };
147
+ // the 'settings' message handler, so no inline reload is needed here. Only the keys
148
+ // that were actually written: a skipped masked echo must not trigger reloads either.
149
+ notify('settings', applied);
150
+ return { updated: Object.keys(applied) };
119
151
  },
120
152
  options: {
121
153
  description: 'Set setting values',
122
- notes: 'Set setting values for specific keys',
154
+ notes: `Set setting values for specific keys. Masked credential values ("${MASKED}") read from GET /v1/settings are not accepted: a masked value that matches the stored one is skipped as unchanged, any other value carrying the mask is refused. Send the real credential, or leave the key out to keep the stored value.`,
123
155
  tags: ['api', 'Settings'],
124
156
 
125
157
  plugins: {
@@ -165,30 +197,25 @@ async function init(args) {
165
197
  queue
166
198
  };
167
199
 
168
- const [resActive, resDelayed, resPaused, resWaiting, resMeta] = await redis
169
- .multi()
170
- .llen(`${REDIS_PREFIX}bull:${queue}:active`)
171
- .zcard(`${REDIS_PREFIX}bull:${queue}:delayed`)
172
- .llen(`${REDIS_PREFIX}bull:${queue}:paused`)
173
- .llen(`${REDIS_PREFIX}bull:${queue}:wait`)
174
- .hget(`${REDIS_PREFIX}bull:${queue}:meta`, 'paused')
175
- .exec();
176
-
177
- if (resActive[0] || resDelayed[0] || resPaused[0] || resWaiting[0]) {
178
- // counting failed
200
+ let stats;
201
+ try {
202
+ stats = await queueStats(QUEUES_BY_NAME[queue]);
203
+ } catch (countErr) {
179
204
  let err = new Error('Failed to count queue length');
180
205
  err.statusCode = 500;
206
+ err.cause = countErr;
181
207
  throw err;
182
208
  }
183
209
 
184
210
  values.jobs = {
185
- active: Number(resActive[1]) || 0,
186
- delayed: Number(resDelayed[1]) || 0,
187
- paused: Number(resPaused[1]) || 0,
188
- waiting: Number(resWaiting[1]) || 0
211
+ active: stats.active,
212
+ delayed: stats.delayed,
213
+ // Reported for compatibility only - see the response schema below
214
+ paused: stats.paused,
215
+ waiting: stats.waiting
189
216
  };
190
217
 
191
- values.paused = !!Number(resMeta[1]) || false;
218
+ values.paused = stats.isPaused;
192
219
 
193
220
  return values;
194
221
  } catch (err) {
@@ -246,7 +273,12 @@ async function init(args) {
246
273
  jobs: Joi.object({
247
274
  active: Joi.number().integer().example(123).description('Jobs that are currently being processed'),
248
275
  delayed: Joi.number().integer().example(123).description('Jobs that are processed in the future'),
249
- paused: Joi.number().integer().example(123).description('Jobs that would be processed once queue processing is resumed'),
276
+ paused: Joi.number()
277
+ .integer()
278
+ .example(0)
279
+ .description(
280
+ 'Always 0. BullMQ 6 no longer parks jobs in a separate paused list, so jobs held by a paused queue are counted as waiting. Kept so existing clients still see the key'
281
+ ),
250
282
  waiting: Joi.number()
251
283
  .integer()
252
284
  .example(123)
@@ -267,11 +299,7 @@ async function init(args) {
267
299
  try {
268
300
  let queue = request.params.queue;
269
301
 
270
- let queueObj = {
271
- documents: documentsQueue,
272
- notify: notifyQueue,
273
- submit: submitQueue
274
- }[queue];
302
+ let queueObj = QUEUES_BY_NAME[queue];
275
303
 
276
304
  let values = {
277
305
  queue
@@ -72,14 +72,14 @@ async function init(args) {
72
72
  key: Joi.string().example('maxmemory-policy').description('Warning identifier'),
73
73
  color: Joi.string().example('warning').description('Severity indicator'),
74
74
  title: Joi.string().example('Unsafe Redis eviction policy').description('Warning title'),
75
- details: Joi.array().items(Joi.string()).description('Warning details')
75
+ details: Joi.array().items(Joi.string().example('maxmemory-policy is allkeys-lru')).description('Warning details')
76
76
  })
77
77
  .unknown()
78
78
  .label('RedisWarningEntry')
79
79
  )
80
80
  .description('Warnings about the Redis configuration')
81
81
  .label('RedisWarnings'),
82
- redisPing: Joi.number().description('Redis latency in milliseconds'),
82
+ redisPing: Joi.number().example(1.2).description('Redis latency in milliseconds'),
83
83
  imapflow: Joi.string().example('1.0.188').description('ImapFlow version'),
84
84
  bullmq: Joi.string().example('5.0.0').description('BullMQ version'),
85
85
  arch: Joi.string().example('arm64').description('CPU architecture of the host'),