emailengine-app 2.78.0 → 2.79.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 (142) hide show
  1. package/.ncurc.js +23 -13
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -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 +70 -35
  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 +397 -0
  24. package/lib/api-routes/route-helpers.js +223 -9
  25. package/lib/api-routes/route-metadata.js +28 -0
  26. package/lib/api-routes/settings-routes.js +30 -25
  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 +319 -33
  31. package/lib/api-routes/webhook-route-routes.js +14 -4
  32. package/lib/auth-token.js +80 -8
  33. package/lib/consts.js +10 -0
  34. package/lib/db.js +20 -2
  35. package/lib/delivery-error.js +30 -1
  36. package/lib/email-client/base-client.js +27 -41
  37. package/lib/email-client/gmail-client.js +19 -10
  38. package/lib/email-client/imap/mailbox.js +23 -24
  39. package/lib/email-client/imap/subconnection.js +10 -7
  40. package/lib/email-client/imap/sync-operations.js +46 -46
  41. package/lib/email-client/imap-client.js +36 -26
  42. package/lib/email-client/message-builder.js +3 -3
  43. package/lib/email-client/notification-handler.js +1 -1
  44. package/lib/email-client/outlook/graph-api.js +10 -4
  45. package/lib/email-client/outlook-client.js +53 -54
  46. package/lib/email-client/smtp-pool-manager.js +1 -1
  47. package/lib/enum-descriptions.js +92 -2
  48. package/lib/export.js +1 -1
  49. package/lib/field-usage.js +133 -0
  50. package/lib/gateway.js +1 -1
  51. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
  52. package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
  53. package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
  54. package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
  55. package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
  56. package/lib/imapproxy/imap-server.js +27 -7
  57. package/lib/license-beacon.js +4 -9
  58. package/lib/lists.js +49 -1
  59. package/lib/llm-pre-process.js +5 -5
  60. package/lib/logger.js +5 -1
  61. package/lib/metrics-collector.js +2 -2
  62. package/lib/oauth/gmail.js +9 -12
  63. package/lib/oauth/mail-ru.js +5 -7
  64. package/lib/oauth/outlook.js +9 -9
  65. package/lib/oauth/pubsub/google.js +25 -10
  66. package/lib/oauth/scope-checker.js +1 -1
  67. package/lib/oauth2-apps.js +223 -294
  68. package/lib/openapi/build-document.js +15 -7
  69. package/lib/openapi/joi-schema.js +20 -0
  70. package/lib/outbox.js +85 -17
  71. package/lib/pre-process.js +8 -8
  72. package/lib/queue-stats.js +49 -0
  73. package/lib/read-env-value.js +1 -1
  74. package/lib/reconnection-manager.js +2 -2
  75. package/lib/rewrite-text-nodes.js +4 -3
  76. package/lib/routes-ui.js +4 -0
  77. package/lib/schemas.js +216 -160
  78. package/lib/settings.js +84 -5
  79. package/lib/sub-script.js +2 -1
  80. package/lib/swagger-options.js +2 -1
  81. package/lib/templates.js +4 -4
  82. package/lib/threads.js +2 -2
  83. package/lib/token-audit-log.js +208 -0
  84. package/lib/token-permission-view.js +219 -0
  85. package/lib/token-permissions.js +172 -0
  86. package/lib/tokens.js +99 -15
  87. package/lib/tools.js +142 -37
  88. package/lib/ui-routes/account-routes.js +31 -11
  89. package/lib/ui-routes/admin-config-routes.js +18 -10
  90. package/lib/ui-routes/admin-entities-routes.js +66 -22
  91. package/lib/ui-routes/auth-routes.js +30 -24
  92. package/lib/ui-routes/export-routes.js +10 -4
  93. package/lib/ui-routes/oauth-config-routes.js +5 -5
  94. package/lib/ui-routes/reference-routes.js +3 -3
  95. package/lib/ui-routes/route-helpers.js +51 -2
  96. package/lib/ui-routes/settings-page.js +1 -1
  97. package/lib/ui-routes/smtp-test-routes.js +1 -1
  98. package/lib/ui-routes/suppression-list-routes.js +294 -0
  99. package/lib/ui-routes/unsubscribe-routes.js +19 -29
  100. package/lib/utils/network.js +2 -2
  101. package/lib/web-safe-html.js +1 -1
  102. package/lib/webhook-routing.js +80 -0
  103. package/lib/webhooks.js +20 -14
  104. package/package.json +11 -10
  105. package/sbom.json +1 -1
  106. package/server.js +80 -41
  107. package/static/css/flyonui.css +1 -1
  108. package/static/css/src/app.tailwind.css +136 -9
  109. package/static/js/reference.js +456 -10
  110. package/static/js/ui.js +43 -0
  111. package/static/licenses.html +51 -41
  112. package/translations/messages.pot +59 -59
  113. package/views/accounts/account.hbs +69 -7
  114. package/views/accounts/browse.hbs +18 -35
  115. package/views/config/logging.hbs +6 -0
  116. package/views/config/oauth/app.hbs +0 -2
  117. package/views/config/security.hbs +13 -0
  118. package/views/partials/oauth_form.hbs +0 -15
  119. package/views/partials/reference/disclosure.hbs +8 -2
  120. package/views/partials/reference/operation.hbs +47 -13
  121. package/views/partials/reference/params.hbs +17 -1
  122. package/views/partials/reference/schema-node.hbs +110 -52
  123. package/views/partials/reference/schema-tools.hbs +25 -0
  124. package/views/partials/reference/try-it.hbs +84 -11
  125. package/views/partials/side_menu.hbs +1 -0
  126. package/views/partials/ui/checkbox.hbs +2 -2
  127. package/views/partials/ui/tabs.hbs +7 -1
  128. package/views/reference/token.hbs +4 -0
  129. package/views/suppression-lists/index.hbs +85 -0
  130. package/views/suppression-lists/list.hbs +87 -0
  131. package/views/templates/index.hbs +8 -2
  132. package/views/tokens/index.hbs +31 -4
  133. package/views/tokens/new.hbs +324 -2
  134. package/workers/api.js +146 -57
  135. package/workers/documents.js +46 -26
  136. package/workers/export.js +20 -8
  137. package/workers/imap-proxy.js +2 -2
  138. package/workers/imap.js +12 -6
  139. package/workers/smtp.js +13 -7
  140. package/workers/submit.js +40 -30
  141. package/workers/webhooks.js +59 -25
  142. package/lib/feature-flags.js +0 -48
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ // Narrowing check for an access token that carries a `permissions` record.
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.
10
+ //
11
+ // Shared by both enforcement points on the same precedent that put lib/auth-token.js in one place:
12
+ // the api-token strategy in workers/api.js for HTTP, and lib/auth-token.js for the SMTP submission
13
+ // and IMAP proxy surfaces. A policy change that landed on one and missed the other would be a hole
14
+ // in whichever surface was forgotten.
15
+
16
+ const { NEVER_GRANTABLE, ACTION_VALUES, GROUP_VALUES } = require('./api-routes/permission-map');
17
+
18
+ // The axes a record may carry, and the vocabulary each accepts. Anything else is a record this
19
+ // version does not understand.
20
+ const AXIS_VALUES = {
21
+ actions: ACTION_VALUES,
22
+ groups: GROUP_VALUES
23
+ };
24
+
25
+ const AXES = Object.keys(AXIS_VALUES);
26
+
27
+ // Why a request was refused. Reported to the caller rather than rendered here, because HTTP, SMTP
28
+ // and IMAP each say "no" differently.
29
+ const REASON = {
30
+ // The route resolved to no action or no group, so this vocabulary does not describe it. Means
31
+ // the route table and permission-map.js have diverged, which test/api-routes-table-test.js
32
+ // exists to prevent.
33
+ UNCLASSIFIED: 'unclassified',
34
+
35
+ // `permissions` is present but not a shape this version can read. Deliberately NOT treated as
36
+ // absent: see the comment on parsePermissions().
37
+ MALFORMED: 'malformed',
38
+
39
+ // A group no `permissions` record may ever name, whatever it says.
40
+ RESTRICTED: 'restricted',
41
+
42
+ ACTION: 'action',
43
+ GROUP: 'group'
44
+ };
45
+
46
+ /**
47
+ * Reads a `permissions` record, or reports that it cannot be read.
48
+ *
49
+ * The distinction between "absent" and "unreadable" is the whole safety of this module, because the
50
+ * two mean opposite things: absent is every token issued before permissions existed and must keep
51
+ * working unnarrowed, while unreadable must grant nothing. Collapsing them would turn a malformed
52
+ * record into a full-privilege token.
53
+ *
54
+ * That is not hypothetical. tokens.setRawData() writes whatever fields its input carries with no
55
+ * joi schema at all, and it is the import path for EENGINE_PREPARED_TOKEN, so an arbitrary
56
+ * `permissions` value can reach a record without ever passing route validation.
57
+ *
58
+ * @param {*} permissions - the record's `permissions` field
59
+ * @returns {{narrowed: Boolean, axes: (Object|null), malformed: Boolean}}
60
+ */
61
+ function parsePermissions(permissions) {
62
+ if (permissions === null || typeof permissions === 'undefined') {
63
+ return { narrowed: false, axes: null, malformed: false };
64
+ }
65
+
66
+ if (typeof permissions !== 'object' || Array.isArray(permissions)) {
67
+ return { narrowed: true, axes: null, malformed: true };
68
+ }
69
+
70
+ const keys = Object.keys(permissions);
71
+
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 };
77
+ }
78
+
79
+ // `{}` is ambiguous between "no narrowing" and "grant nothing". The joi schema refuses it so it
80
+ // never reaches a record through the API, and anything that gets in another way is denied.
81
+ if (!keys.length) {
82
+ return { narrowed: true, axes: null, malformed: true };
83
+ }
84
+
85
+ const axes = {};
86
+ for (const axis of AXES) {
87
+ // Object.hasOwn rather than `in`: this record was msgpack-decoded from Redis by a path with
88
+ // no schema, and `in` walks the prototype chain, so a payload that got something onto the
89
+ // decoded object's prototype could otherwise supply an axis the record does not own.
90
+ if (!Object.hasOwn(permissions, axis)) {
91
+ continue;
92
+ }
93
+
94
+ const value = permissions[axis];
95
+ if (!Array.isArray(value) || value.some(entry => !AXIS_VALUES[axis].has(entry))) {
96
+ return { narrowed: true, axes: null, malformed: true };
97
+ }
98
+
99
+ // An empty array is well-formed and grants nothing: an allowlist that lists nothing allows
100
+ // nothing. That is the opposite of the axis being absent, and it matches how `scopes: []`
101
+ // already behaves.
102
+ axes[axis] = value;
103
+ }
104
+
105
+ return { narrowed: true, axes, malformed: false };
106
+ }
107
+
108
+ /**
109
+ * Is this operation allowed to the token?
110
+ *
111
+ * @param {Object} opts
112
+ * @param {Object} opts.tokenData - the record from tokens.get()
113
+ * @param {Object} opts.operation - { action, group }, resolved by the caller from the route
114
+ * @returns {{allowed: Boolean, reason: (String|null), required: (Object|null)}}
115
+ */
116
+ function check({ tokenData, operation }) {
117
+ const { action = null, group = null } = operation || {};
118
+ const parsed = parsePermissions(tokenData && tokenData.permissions);
119
+
120
+ if (!parsed.narrowed) {
121
+ // No narrowing on this token, so nothing to subtract. Every token issued before this
122
+ // feature shipped takes this path, which is what makes the change additive.
123
+ return { allowed: true, reason: null, required: null };
124
+ }
125
+
126
+ const required = { action, group };
127
+
128
+ if (parsed.malformed) {
129
+ return { allowed: false, reason: REASON.MALFORMED, required };
130
+ }
131
+
132
+ if (!action || !group) {
133
+ return { allowed: false, reason: REASON.UNCLASSIFIED, required };
134
+ }
135
+
136
+ // 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.
141
+ if (NEVER_GRANTABLE.has(group)) {
142
+ return { allowed: false, reason: REASON.RESTRICTED, required };
143
+ }
144
+
145
+ if (parsed.axes.actions && !parsed.axes.actions.includes(action)) {
146
+ return { allowed: false, reason: REASON.ACTION, required };
147
+ }
148
+
149
+ if (parsed.axes.groups && !parsed.axes.groups.includes(group)) {
150
+ return { allowed: false, reason: REASON.GROUP, required };
151
+ }
152
+
153
+ return { allowed: true, reason: null, required };
154
+ }
155
+
156
+ /**
157
+ * What this module makes of a token's `permissions` field, without an operation to check against.
158
+ *
159
+ * Exists so the admin UI can label a record the same way the enforcement reads it. Deriving the
160
+ * shape a second time in the view diverged immediately: `{}`, an unknown axis and an out-of-vocabulary
161
+ * slug are all refusals here, but a view that only looked for a non-object rendered them as working
162
+ * narrow credentials.
163
+ *
164
+ * @param {Object} tokenData - the record from tokens.get()
165
+ * @returns {{narrowed: Boolean, malformed: Boolean}}
166
+ */
167
+ function inspect(tokenData) {
168
+ const { narrowed, malformed } = parsePermissions(tokenData && tokenData.permissions);
169
+ return { narrowed, malformed };
170
+ }
171
+
172
+ module.exports = { check, inspect, REASON };
package/lib/tokens.js CHANGED
@@ -6,9 +6,24 @@ const msgpack = require('./msgpack');
6
6
  const logger = require('./logger');
7
7
  const { REDIS_PREFIX } = require('./consts');
8
8
  const { constantTimeEqual, filterListPage } = require('./tools');
9
+ const tokenAuditLog = require('./token-audit-log');
9
10
 
10
11
  const SESS_PREFIX = 'sess_';
11
12
 
13
+ /**
14
+ * The id a token is listed and stored under: the SHA-256 of its raw bytes.
15
+ *
16
+ * Derivable from the token value, which is why provision() does not have to return it - but only if
17
+ * you know the hex string is decoded to bytes before hashing rather than hashed as text. Exported so
18
+ * callers get that right by construction instead of reimplementing it.
19
+ *
20
+ * @param {String} token - the 64-char hex token value
21
+ * @returns {String} SHA-256 hex id
22
+ */
23
+ function tokenId(token) {
24
+ return crypto.createHash('sha256').update(Buffer.from(token, 'hex')).digest('hex');
25
+ }
26
+
12
27
  // Best-effort removal of an expired token record. Fired from both of the places that can
13
28
  // notice the expiry - get(), when someone presents the token, and list(), when someone views
14
29
  // the token list. Both are needed: a token that is minted and then never used is never
@@ -27,7 +42,29 @@ function reapExpiredToken(hashedToken, account) {
27
42
  .catch(err => logger.error({ msg: 'Failed to clean up an expired access token', hash: hashedToken, err }));
28
43
  }
29
44
 
45
+ // Reads one `{prefix}tokens:access` value into the shape both readers publish. Shared because the
46
+ // listing and the single-token getter feed the same joi schema and had already drifted: the listing
47
+ // assigned the decoded object as-is, so a token that had never authenticated came back as `{time:
48
+ // null}` with no `ip` key at all, and the admin view carries a `|| {}` guard for the case where the
49
+ // field is missing entirely. One shape means the getter's promise to match the listing is true.
50
+ function decodeAccessData(encoded, hashedToken) {
51
+ let accessData = {};
52
+
53
+ if (encoded) {
54
+ try {
55
+ accessData = msgpack.decode(encoded);
56
+ } catch (err) {
57
+ // An unreadable last-use entry must not fail the read of the token it belongs to
58
+ logger.error({ msg: 'Failed to process token access data', hash: hashedToken, err });
59
+ }
60
+ }
61
+
62
+ return { time: accessData.time ? new Date(accessData.time) : null, ip: accessData.ip || null };
63
+ }
64
+
30
65
  module.exports = {
66
+ tokenId,
67
+
31
68
  async getSessionToken(sessionId, account, ttl) {
32
69
  const token = crypto.randomBytes(32);
33
70
  const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
@@ -107,7 +144,7 @@ module.exports = {
107
144
  * password is a supported configuration), and the CLI needs shell access anyway.
108
145
  *
109
146
  * Both HTTP callers gate themselves: POST /admin/tokens/new unconditionally, since
110
- * `server.auth.default('session')` leaves it open while authData is unset; POST /v1/token only
147
+ * `server.auth.default('session')` leaves it open while authData is unset; POST /v1/tokens only
111
148
  * for the `preauth` caller that the `disableTokens` setting lets through without a credential.
112
149
  *
113
150
  * @param {Object} opts - Token options. May originate from a request payload.
@@ -115,7 +152,7 @@ module.exports = {
115
152
  */
116
153
  async provision(opts) {
117
154
  opts = opts || {};
118
- const { account, restrictions, ip, remoteAddress, description, metadata, scopes, nolog, expires } = opts;
155
+ const { account, restrictions, permissions, ip, remoteAddress, description, metadata, scopes, nolog, expires } = opts;
119
156
 
120
157
  const token = crypto.randomBytes(32);
121
158
  const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
@@ -166,6 +203,13 @@ module.exports = {
166
203
  tokenData.restrictions = restrictions;
167
204
  }
168
205
 
206
+ // Narrowing below the scope. Absent means "not narrowed", which is every token issued
207
+ // before this existed, so the field is only written when it was asked for - see the absent
208
+ // vs empty vs malformed distinction in lib/token-permissions.js.
209
+ if (permissions) {
210
+ tokenData.permissions = permissions;
211
+ }
212
+
169
213
  if (metadata) {
170
214
  tokenData.metadata = metadata;
171
215
  }
@@ -206,7 +250,7 @@ module.exports = {
206
250
  throw err;
207
251
  }
208
252
 
209
- const hashedToken = hashed ? token : crypto.createHash('sha256').update(Buffer.from(token, 'hex')).digest('hex');
253
+ const hashedToken = hashed ? token : tokenId(token);
210
254
 
211
255
  let tokenDataEncoded = await redis.hgetBuffer(`${REDIS_PREFIX}tokens`, hashedToken);
212
256
  if (!tokenDataEncoded) {
@@ -242,6 +286,20 @@ module.exports = {
242
286
  return Object.assign({ id: hashedToken }, tokenData);
243
287
  },
244
288
 
289
+ /**
290
+ * Last-use record for a token, in the shape the listings report it.
291
+ *
292
+ * Kept apart from get(), which every authenticated request runs: the last-use record lives in a
293
+ * second hash and nothing on the auth path reads it, so folding it in would put an extra Redis
294
+ * round trip on every API call to serve one page.
295
+ *
296
+ * @param {String} tokenId - SHA-256 hash of the token, the id the listings report
297
+ * @returns {Promise<{time: (Date|null), ip: (String|null)}>}
298
+ */
299
+ async getAccess(tokenId) {
300
+ return decodeAccessData(await redis.hgetBuffer(`${REDIS_PREFIX}tokens:access`, tokenId), tokenId);
301
+ },
302
+
245
303
  async delete(token, opts) {
246
304
  if (!/^[0-9a-f]{64}$/i.test(token)) {
247
305
  let err = new Error('Invalid token format');
@@ -264,7 +322,14 @@ module.exports = {
264
322
  }
265
323
  }
266
324
 
267
- let req = redis.multi().hdel(`${REDIS_PREFIX}tokens`, tokenData.id).hdel(`${REDIS_PREFIX}tokens:access`, tokenData.id);
325
+ // The audit log goes with the token. It describes a credential that no longer exists, so
326
+ // keeping it would outlive the thing it is a record of - and the key is named after the
327
+ // token id, so nothing would ever collect it.
328
+ let req = redis
329
+ .multi()
330
+ .hdel(`${REDIS_PREFIX}tokens`, tokenData.id)
331
+ .hdel(`${REDIS_PREFIX}tokens:access`, tokenData.id)
332
+ .del(tokenAuditLog.logKey(tokenData.id));
268
333
  if (tokenData.account) {
269
334
  req = req.srem(`${REDIS_PREFIX}iat:${tokenData.account}`, tokenData.id);
270
335
  } else {
@@ -352,14 +417,28 @@ module.exports = {
352
417
  return tokenData;
353
418
  },
354
419
 
355
- async list(account, page, pageSize, query) {
420
+ /**
421
+ * Lists tokens.
422
+ *
423
+ * @param {String} [account] - list tokens bound to this account
424
+ * @param {Number} [page] - zero-based page
425
+ * @param {Number} [pageSize] - entries per page
426
+ * @param {String} [query] - filter on id, description or account
427
+ * @param {Object} [opts]
428
+ * @param {Boolean} [opts.all] - every token on the instance, bound or not. Reads the token hash
429
+ * directly rather than walking one index per account: the account is stored on each record, so
430
+ * the union is already there, and enumerating accounts would be a round trip each.
431
+ */
432
+ async list(account, page, pageSize, query, opts) {
356
433
  page = Math.max(Number(page) || 0, 0);
357
434
  pageSize = Math.max(Number(pageSize) || 20, 1);
358
435
 
359
436
  let startPos = page * pageSize;
360
437
 
361
438
  let list;
362
- if (account) {
439
+ if (opts && opts.all) {
440
+ list = await redis.hkeys(`${REDIS_PREFIX}tokens`);
441
+ } else if (account) {
363
442
  list = await redis.smembers(`${REDIS_PREFIX}iat:${account}`);
364
443
  } else {
365
444
  list = await redis.smembers(`${REDIS_PREFIX}iat`);
@@ -417,20 +496,18 @@ module.exports = {
417
496
  if (tokenData.expires) {
418
497
  tokenData.expires = new Date(tokenData.expires);
419
498
  }
420
- lastEntry = Object.assign({ id: tokenHash }, tokenData);
499
+ // `account` is absent on the record for an unbound token, so it is filled in
500
+ // explicitly: a listing that mixes bound and unbound tokens should report one
501
+ // shape, not two, and `null` is the answer to "which account" for a token
502
+ // that is not bound to one.
503
+ lastEntry = Object.assign({ id: tokenHash, account: null }, tokenData);
421
504
  response.tokens.push(lastEntry);
422
505
  } catch (err) {
423
506
  logger.error({ msg: 'Failed to process token data', hash: tokenHash, err });
424
507
  }
425
508
  }
426
509
  } else if (lastEntry && entry[1]) {
427
- try {
428
- let accessData = msgpack.decode(entry[1]);
429
- accessData.time = accessData.time ? new Date(accessData.time) : null;
430
- lastEntry.access = accessData;
431
- } catch (err) {
432
- logger.error({ msg: 'Failed to process token data', hash: tokenHash, err });
433
- }
510
+ lastEntry.access = decodeAccessData(entry[1], tokenHash);
434
511
  }
435
512
  }
436
513
 
@@ -438,9 +515,16 @@ module.exports = {
438
515
  let paged = filterListPage(response.tokens, ['id', 'description', 'account'], query, startPos, pageSize);
439
516
  response.tokens = paged.entries;
440
517
  response.total = paged.total;
441
- response.pages = paged.pages;
442
518
  }
443
519
 
520
+ // Derived last, from whichever total survived. The loop above reaps expired tokens and
521
+ // decrements `total` as it goes, so a count taken before it describes a listing that no
522
+ // longer exists - three tokens with the first expired reported `{total: 2, pages: 3}`. Only
523
+ // the visible page is inspected, so an expired token further along is still counted until a
524
+ // later call reaches it; what this guarantees is that `pages` and `total` in one response
525
+ // are two views of one number. Same formula filterListPage() applies to the filtered set.
526
+ response.pages = Math.ceil(response.total / pageSize);
527
+
444
528
  return response;
445
529
  }
446
530
  };
package/lib/tools.js CHANGED
@@ -8,6 +8,11 @@ const Joi = require('joi');
8
8
  const he = require('he');
9
9
  const packageData = require('../package.json');
10
10
  const settings = require('./settings');
11
+ // Safe to require at load time despite db.js opening Redis clients: settings.js above already
12
+ // requires it, so db.js is in this file's dependency graph either way. db.js does not require
13
+ // tools.js back (it inlines readEnvValue precisely to avoid that), so there is no cycle.
14
+ const { QUEUES_BY_NAME } = require('./db');
15
+ const { queueStats } = require('./queue-stats');
11
16
  const { brotliDecompress } = require('zlib');
12
17
  const util = require('util');
13
18
  const brotliDecompressAsync = util.promisify(brotliDecompress);
@@ -318,6 +323,72 @@ function resolveOAuthErrorStatus(responseError, err) {
318
323
  return typeof fallback === 'number' && fallback >= 400 ? fallback : 500;
319
324
  }
320
325
 
326
+ // Key names whose value must never be rendered into a validation message. Deliberately broad:
327
+ // a false positive only replaces the value with a placeholder in an error message, while a miss
328
+ // writes a credential to the log and returns it to the client.
329
+ const CREDENTIAL_KEY_REGEX = /pass|secret|token|key|seed|credential|signature/i;
330
+
331
+ /**
332
+ * Strips the submitted values out of a joi ValidationError, in place, so it can be logged.
333
+ *
334
+ * A joi error exposes the rejected input in four places: the whole submitted payload in
335
+ * `_original`, the value in every detail context, and - for the `string.pattern` family, the only
336
+ * common rule that renders it - the value inlined into `message` and into the `stack` snapshot
337
+ * taken when the error was constructed. Deleting the first two is not enough, so values belonging
338
+ * to credential-shaped keys are masked in the text as well.
339
+ */
340
+ function redactValidationError(err) {
341
+ if (!err || typeof err !== 'object') {
342
+ return err;
343
+ }
344
+
345
+ delete err._original;
346
+
347
+ let secrets = new Set();
348
+ for (let detail of err.details || []) {
349
+ if (!detail.context) {
350
+ continue;
351
+ }
352
+
353
+ if (typeof detail.context.value === 'string' && detail.context.value) {
354
+ if (CREDENTIAL_KEY_REGEX.test(detail.context.key) || CREDENTIAL_KEY_REGEX.test(detail.context.label)) {
355
+ secrets.add(detail.context.value);
356
+ }
357
+ }
358
+
359
+ delete detail.context.value;
360
+ }
361
+
362
+ if (!secrets.size) {
363
+ return err;
364
+ }
365
+
366
+ let mask = text => {
367
+ for (let secret of secrets) {
368
+ text = text.replaceAll(secret, '(hidden)');
369
+ }
370
+ return text;
371
+ };
372
+
373
+ for (let detail of err.details || []) {
374
+ if (typeof detail.message === 'string') {
375
+ detail.message = mask(detail.message);
376
+ }
377
+ }
378
+
379
+ // `stack` is a plain string snapshot that already embeds the original message, so it has to be
380
+ // masked separately - reassigning `message` does not rewrite it
381
+ if (typeof err.stack === 'string') {
382
+ err.stack = mask(err.stack);
383
+ }
384
+
385
+ if (typeof err.message === 'string') {
386
+ err.message = mask(err.message);
387
+ }
388
+
389
+ return err;
390
+ }
391
+
321
392
  module.exports = {
322
393
  // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
323
394
  toCamelCase,
@@ -652,7 +723,10 @@ module.exports = {
652
723
  });
653
724
 
654
725
  if (error) {
655
- throw error;
726
+ // Every caller logs this error, and two of them (imap-client, message-builder) log it at
727
+ // error level to a logger that persists to the per-account log store and to Sentry. The
728
+ // raw joi error carries the auth server's `pass` and `accessToken` in `_original`.
729
+ throw redactValidationError(error);
656
730
  }
657
731
 
658
732
  return value;
@@ -1140,29 +1214,31 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1140
1214
  }
1141
1215
  },
1142
1216
 
1217
+ redactValidationError,
1218
+
1143
1219
  async failAction(request, h, err) {
1220
+ let error;
1144
1221
  try {
1145
- let details = (err.details || []).map(detail => ({ message: detail.message, key: detail.context.key }));
1222
+ redactValidationError(err);
1146
1223
 
1147
- delete err._original;
1224
+ let details = (err.details || []).map(detail => ({ message: detail.message, key: detail.context.key }));
1148
1225
 
1149
- logger.error({
1226
+ request.logger.debug({
1150
1227
  msg: 'Request failed',
1151
1228
  method: request.method,
1152
1229
  route: request.route.path,
1153
- statusCode: request.response && request.response.statusCode,
1154
1230
  err
1155
1231
  });
1156
1232
 
1157
1233
  let message = request.app.gt.gettext('Invalid input');
1158
- let error = Boom.boomify(new Error(message), { statusCode: 400 });
1234
+ error = Boom.boomify(new Error(message), { statusCode: 400 });
1159
1235
  error.output.payload.fields = details;
1160
-
1161
- throw error;
1162
1236
  } catch (E) {
1163
- request.logger.error({ err: E });
1237
+ request.logger.error({ msg: 'Failed to process a validation failure', err: E });
1164
1238
  throw E;
1165
1239
  }
1240
+
1241
+ throw error;
1166
1242
  },
1167
1243
 
1168
1244
  async verifyAccountInfo(redis, accountData, logger) {
@@ -1264,7 +1340,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1264
1340
  response.mailboxes = mailboxList;
1265
1341
  }
1266
1342
  } catch (err) {
1267
- logger.error({ msg: 'Account verification failed', err });
1343
+ logger.debug({ msg: 'Account verification failed', err });
1268
1344
  response.imap = {
1269
1345
  success: false,
1270
1346
  error: err.message,
@@ -1694,34 +1770,19 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1694
1770
  redisVersion = err.message;
1695
1771
  }
1696
1772
 
1773
+ // Counted concurrently: the queues are independent, so serializing them only adds their
1774
+ // round trips together on a path that renders the admin dashboard. A queue that fails to
1775
+ // count is left out and the rest of the stats response still goes out.
1697
1776
  let queues = {};
1698
- for (let queue of ['notify', 'submit', 'documents']) {
1699
- try {
1700
- const [resActive, resDelayed, resWaiting, resPaused, resMeta] = await redis
1701
- .multi()
1702
- .llen(`${REDIS_PREFIX}bull:${queue}:active`)
1703
- .zcard(`${REDIS_PREFIX}bull:${queue}:delayed`)
1704
- .llen(`${REDIS_PREFIX}bull:${queue}:wait`)
1705
- .llen(`${REDIS_PREFIX}bull:${queue}:paused`)
1706
- .hget(`${REDIS_PREFIX}bull:${queue}:meta`, 'paused')
1707
- .exec();
1708
- if (resActive[0] || resDelayed[0] || resWaiting[0] || resPaused[0] || resMeta[0]) {
1709
- // counting failed, skip this queue but keep the rest of the stats response
1710
- logger.error({ msg: 'Failed to count queue length', queue, active: resActive, delayed: resDelayed, waiting: resWaiting });
1711
- continue;
1777
+ await Promise.all(
1778
+ Object.entries(QUEUES_BY_NAME).map(async ([queue, queueObj]) => {
1779
+ try {
1780
+ queues[queue] = await queueStats(queueObj);
1781
+ } catch (err) {
1782
+ logger.error({ msg: 'Failed to count queue length', queue, err });
1712
1783
  }
1713
- queues[queue] = {
1714
- active: Number(resActive[1]) || 0,
1715
- delayed: Number(resDelayed[1]) || 0,
1716
- waiting: Number(resWaiting[1]) || 0,
1717
- paused: Number(resPaused[1]) || 0,
1718
- isPaused: !!Number(resMeta[1]) || false
1719
- };
1720
- queues[queue].total = queues[queue].active + queues[queue].delayed + queues[queue].waiting + queues[queue].paused;
1721
- } catch (err) {
1722
- logger.error({ msg: 'Failed to count queue length', queue, err });
1723
- }
1724
- }
1784
+ })
1785
+ );
1725
1786
 
1726
1787
  let stats = Object.assign(
1727
1788
  {
@@ -1809,6 +1870,20 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1809
1870
  return secretKey.replace(/^(.{8}).*$/, `$1... (${secretKey.length}B)`);
1810
1871
  },
1811
1872
 
1873
+ // Returns the URL with any embedded basic auth credentials removed, safe for logging. Never
1874
+ // throws: an unparseable value is replaced with a static placeholder rather than echoed back,
1875
+ // because the raw string could itself carry the credentials that made it unparseable.
1876
+ redactUrlCredentials(url) {
1877
+ try {
1878
+ let parsed = new URL(url);
1879
+ parsed.username = '';
1880
+ parsed.password = '';
1881
+ return parsed.toString();
1882
+ } catch {
1883
+ return 'invalid url';
1884
+ }
1885
+ },
1886
+
1812
1887
  validUidValidity(value) {
1813
1888
  if (typeof value === 'bigint') {
1814
1889
  return value > BigInt(0);
@@ -1919,6 +1994,36 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1919
1994
  return { data: data.toString('base64url'), signature };
1920
1995
  },
1921
1996
 
1997
+ // Builds the signed public subscription-management URL for one recipient on one list - the
1998
+ // same URL every outgoing message with a listId embeds as its List-Unsubscribe target, and
1999
+ // the page where a recipient can re-subscribe. Shared by the mailer (lib/email-client/
2000
+ // base-client.js) and the suppression-list admin UI so the two cannot drift. The signed blob
2001
+ // deliberately carries no nonce and no expiry (see parseSignedFormData): the link stays
2002
+ // valid for as long as the service secret does. messageId is optional - admin generated
2003
+ // links have no originating message. Returns an absolute URL when baseUrl is set and a
2004
+ // host-relative one when it is not, so a missing service URL never leaks a placeholder host.
2005
+ buildUnsubscribeUrl(serviceSecret, baseUrl, opts) {
2006
+ let payload = {
2007
+ act: 'unsub',
2008
+ acc: opts.account,
2009
+ list: opts.list,
2010
+ rcpt: opts.recipient
2011
+ };
2012
+ if (opts.messageId) {
2013
+ payload.msg = opts.messageId;
2014
+ }
2015
+
2016
+ let { data: signedData, signature } = module.exports.getSignedFormDataSync(serviceSecret, payload, true);
2017
+
2018
+ let unsubscribeUrlObj = new URL('/unsubscribe', baseUrl || 'http://localhost');
2019
+ unsubscribeUrlObj.searchParams.append('data', signedData);
2020
+ if (signature) {
2021
+ unsubscribeUrlObj.searchParams.append('sig', signature);
2022
+ }
2023
+
2024
+ return baseUrl ? unsubscribeUrlObj.href : unsubscribeUrlObj.pathname + unsubscribeUrlObj.search;
2025
+ },
2026
+
1922
2027
  // Fail-closed HMAC check for service-secret-signed blobs, shared by every verification site.
1923
2028
  // getServiceSecret() generates and persists a secret when missing, so verification is never
1924
2029
  // silently skipped (an empty secret would otherwise accept forged, unsigned data). Returns true
@@ -2206,7 +2311,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2206
2311
  logger.trace({ msg: 'Loaded environment TLS value from file', path, file: ref[path] });
2207
2312
  delete ref[path];
2208
2313
  } catch (err) {
2209
- logger.fatal({ msg: 'Failed to load TLS value from file', path, file: ref[path], err });
2314
+ logger.error({ msg: 'Failed to load TLS value from file', path, file: ref[path], err });
2210
2315
  ref[key] = null;
2211
2316
  }
2212
2317
  }