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
package/lib/settings.js CHANGED
@@ -11,6 +11,9 @@ const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
11
11
  config.service = config.service || {};
12
12
 
13
13
  const ENCRYPTED_KEYS = [
14
+ // The gmail*/outlook*/mailRu* secrets belong to the retired settings-based OAuth2
15
+ // configuration. They stay listed so oauth2Apps.migrateLegacyApps() can still decrypt
16
+ // stored values through settings.get() before moving them into the app registry.
14
17
  'gmailClientSecret',
15
18
  'outlookClientSecret',
16
19
  'mailRuClientSecret',
@@ -18,7 +21,6 @@ const ENCRYPTED_KEYS = [
18
21
  'smtpServerPassword',
19
22
  'imapProxyServerPassword',
20
23
  'serviceSecret',
21
- 'serviceKey',
22
24
  'gmailServiceKey',
23
25
  'gmailServiceExternalAccount',
24
26
  'documentStorePassword',
@@ -26,6 +28,13 @@ const ENCRYPTED_KEYS = [
26
28
  'totpSeed'
27
29
  ];
28
30
 
31
+ // getValue() runs on an uncached read path - settings.get() is called several times per synced
32
+ // message and once per webhook delivery - and a decrypt/parse failure is permanent rather than
33
+ // transient (a rotated EENGINE_SECRET, a corrupt stored value). Reporting every occurrence would
34
+ // emit a serialized error and stack per message forever, so each key is reported once and rearmed
35
+ // only after it parses successfully again.
36
+ const reportedParseFailures = new Set();
37
+
29
38
  module.exports = {
30
39
  encryptedKeys: ENCRYPTED_KEYS,
31
40
 
@@ -55,11 +64,23 @@ module.exports = {
55
64
  }
56
65
 
57
66
  value = JSON.parse(value);
67
+
68
+ reportedParseFailures.delete(key);
58
69
  } catch (err) {
59
70
  // NB! never log `value` here. By this point a value for an encrypted key has
60
71
  // already been decrypted, so on a parse failure this would write the plaintext
61
72
  // secret (OAuth2 client secrets, the SMTP/IMAP proxy passwords) into the log.
62
- logger.debug({ msg: 'Failed to parse stored setting', key, encrypted: ENCRYPTED_KEYS.includes(key), err });
73
+ // The error object is not safe either: a JSON.parse SyntaxError quotes the head of
74
+ // its input, which for an encrypted key is that same plaintext.
75
+ let encrypted = ENCRYPTED_KEYS.includes(key);
76
+ if (!reportedParseFailures.has(key)) {
77
+ reportedParseFailures.add(key);
78
+ if (encrypted) {
79
+ logger.warn({ msg: 'Failed to parse stored setting', key, encrypted, errorType: err.name });
80
+ } else {
81
+ logger.warn({ msg: 'Failed to parse stored setting', key, encrypted, err });
82
+ }
83
+ }
63
84
  return null;
64
85
  }
65
86
  }
@@ -183,6 +204,13 @@ module.exports = {
183
204
  return 0;
184
205
  }
185
206
 
207
+ // An explicit sentryEnabled write is an operator decision, so it ends the trial-managed
208
+ // state where setLicense() owns the value (the trial default itself is written through
209
+ // setIfMissing(), which skips this rule by design)
210
+ if (key === 'sentryEnabled') {
211
+ await module.exports.clear('sentryAutoEnabled');
212
+ }
213
+
186
214
  const encryptSecret = await getSecret();
187
215
 
188
216
  let formattedValue = module.exports.formatSettingValue(key, value);
@@ -215,9 +243,9 @@ module.exports = {
215
243
  },
216
244
 
217
245
  // Store a value only if the key does not exist yet (atomic HSETNX). Meant for one-shot
218
- // initialization keys (currently the auto-generated serviceSecret) where concurrent minters
219
- // must converge on a single stored value instead of overwriting each other. Skips the
220
- // documentStore/openAi side effects of set() on purpose. Returns true when the value was stored.
246
+ // initialization keys (the auto-generated serviceSecret, the trial default for
247
+ // sentryEnabled) where an existing value must never be overwritten. Skips the side effects
248
+ // of set() on purpose. Returns true when the value was stored.
221
249
  async setIfMissing(key, value) {
222
250
  const encryptSecret = await getSecret();
223
251
 
@@ -226,6 +254,19 @@ module.exports = {
226
254
  return (await redis.hsetnx(`${REDIS_PREFIX}settings`, key, value)) === 1;
227
255
  },
228
256
 
257
+ // Like setIfMissing(), but stamps a marker key in the same atomic Redis step when the value
258
+ // was stored. For seeded defaults whose marker says "the seeder still owns this value":
259
+ // written as two separate commands, a crash between them leaves the seeded value behind with
260
+ // no marker, indistinguishable from an explicit operator choice (see setLicense()).
261
+ async setIfMissingWithMarker(key, value, markerKey, markerValue) {
262
+ const encryptSecret = await getSecret();
263
+
264
+ value = module.exports.encodeSettingValue(key, module.exports.formatSettingValue(key, value), encryptSecret);
265
+ markerValue = module.exports.encodeSettingValue(markerKey, module.exports.formatSettingValue(markerKey, markerValue), encryptSecret);
266
+
267
+ return (await redis.hSetNewMark(`${REDIS_PREFIX}settings`, key, value, markerKey, markerValue)) === 1;
268
+ },
269
+
229
270
  async setMulti(obj) {
230
271
  const encryptSecret = await getSecret();
231
272
  let docStoreUpdated = false;
@@ -253,6 +294,11 @@ module.exports = {
253
294
  }
254
295
  }
255
296
 
297
+ // see set(): an explicit sentryEnabled write ends the trial-managed Sentry state
298
+ if ('sentryEnabled' in obj) {
299
+ await module.exports.clear('sentryAutoEnabled');
300
+ }
301
+
256
302
  return await redis.hmset(`${REDIS_PREFIX}settings`, storeObj);
257
303
  },
258
304
 
@@ -363,6 +409,53 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
363
409
  )
364
410
  .exec();
365
411
 
412
+ // Trial installations report errors to the shared community Sentry by default, so issues
413
+ // with evaluation instances reach the developers. The default is only applied while the
414
+ // operator has never touched the sentryEnabled setting, tracked through the internal
415
+ // sentryAutoEnabled marker; the value and the marker are written in one atomic step
416
+ // (setIfMissingWithMarker), because a value stored without its marker would read as a
417
+ // permanent operator opt-in. Activating a full license or removing the license clears
418
+ // the default again as long as the marker still owns the state, and any explicit
419
+ // operator write to sentryEnabled drops the marker (see set()/setMulti()), making that
420
+ // choice permanent. A SENTRY_DSN environment value pins the Sentry configuration
421
+ // regardless of these settings. License activation must never fail on this convenience,
422
+ // hence the catch-all.
423
+ try {
424
+ if (licenseData.trial) {
425
+ if (await module.exports.setIfMissingWithMarker('sentryEnabled', true, 'sentryAutoEnabled', true)) {
426
+ logger.info({ msg: 'Enabled Sentry error reporting for the trial license' });
427
+ }
428
+ } else {
429
+ await module.exports.clearTrialSentryDefault('license activation');
430
+ }
431
+ } catch (err) {
432
+ logger.error({ msg: 'Failed to apply the trial Sentry default', err });
433
+ }
434
+
435
+ return true;
436
+ },
437
+
438
+ // Undoes the trial Sentry default while the sentryAutoEnabled marker still owns the state;
439
+ // a no-op after any explicit operator choice. Never throws: callers sit on license
440
+ // activation/removal paths that must not fail on this convenience.
441
+ async clearTrialSentryDefault(reason) {
442
+ try {
443
+ if (await module.exports.get('sentryAutoEnabled')) {
444
+ await module.exports.clear('sentryEnabled');
445
+ await module.exports.clear('sentryAutoEnabled');
446
+ logger.info({ msg: 'Disabled the trial default for Sentry error reporting', reason });
447
+ }
448
+ } catch (err) {
449
+ logger.error({ msg: 'Failed to clear the trial Sentry default', reason, err });
450
+ }
451
+ },
452
+
453
+ // Owns the stored license state: the license file itself, the subscription grace marker,
454
+ // and the trial Sentry default that activation may have applied. Used by the explicit
455
+ // remove-license actions and by the grace-period expiry in server.js.
456
+ async removeLicense() {
457
+ await redis.multi().hdel(`${REDIS_PREFIX}settings`, 'license').hdel(`${REDIS_PREFIX}settings`, 'subexp').exec();
458
+ await module.exports.clearTrialSentryDefault('license removal');
366
459
  return true;
367
460
  }
368
461
  };
package/lib/sub-script.js CHANGED
@@ -117,7 +117,8 @@ class SubScript {
117
117
  this.logger.trace({ msg: 'Sub-script executed', duration: Date.now() - start });
118
118
  return result;
119
119
  } catch (err) {
120
- this.logger.error({ msg: 'Sub-script execution failed', duration: Date.now() - start, err });
120
+ // debug breadcrumb only - the callers log the failure with subsystem context
121
+ this.logger.debug({ msg: 'Sub-script execution failed', duration: Date.now() - start, err });
121
122
  throw err;
122
123
  }
123
124
  }
@@ -152,7 +152,8 @@ Full documentation: https://learn.emailengine.app/`
152
152
  },
153
153
  {
154
154
  name: 'Blocklists',
155
- description: 'Manage email address blocklists to prevent sending to specific recipients or domains'
155
+ description:
156
+ 'Manage suppression lists (blocklists) of addresses that must not receive further emails. The same lists are populated by unsubscribe actions and can be managed in the admin UI under Suppression Lists'
156
157
  },
157
158
  {
158
159
  name: 'Multi Message Actions',
package/lib/templates.js CHANGED
@@ -52,12 +52,12 @@ class TemplateHandler {
52
52
 
53
53
  let keys = selectedIds.map(id => `${id}:meta`);
54
54
  let list = await this.redis.hmgetBuffer(this.getTemplatesContentKey(account), keys);
55
- for (let entry of list) {
55
+ for (let [i, entry] of list.entries()) {
56
56
  try {
57
57
  let templateMeta = msgpack.decode(entry);
58
58
  response.templates.push(templateMeta);
59
59
  } catch (err) {
60
- logger.error({ msg: 'Failed to process template', entry: entry && entry.toString('base64'), err });
60
+ logger.error({ msg: 'Failed to process template', template: selectedIds[i], entry: entry && entry.toString('base64'), err });
61
61
  continue;
62
62
  }
63
63
  }
@@ -179,7 +179,7 @@ class TemplateHandler {
179
179
  meta = msgpack.decode(getResult[0]);
180
180
  }
181
181
  } catch (err) {
182
- logger.error({ msg: 'Failed to process template', entry: getResult[0].toString('base64') });
182
+ logger.error({ msg: 'Failed to process template', template: id, entry: getResult[0].toString('base64'), err });
183
183
  }
184
184
 
185
185
  try {
@@ -187,7 +187,7 @@ class TemplateHandler {
187
187
  content = msgpack.decode(getResult[1]);
188
188
  }
189
189
  } catch (err) {
190
- logger.error({ msg: 'Failed to process template', entry: getResult[1].toString('base64') });
190
+ logger.error({ msg: 'Failed to process template', template: id, entry: getResult[1].toString('base64'), err });
191
191
  }
192
192
 
193
193
  return Object.assign(
package/lib/threads.js CHANGED
@@ -96,7 +96,7 @@ async function getThread(client, index, account, messageData, logger) {
96
96
  break;
97
97
  } else if (i < maxThreadRetries - 1) {
98
98
  // try again after a small delay
99
- logger.error({ msg: 'Failed to get thread entry, retrying', retry: i, err: failed });
99
+ logger.warn({ msg: 'Failed to get thread entry, retrying', retry: i, err: failed });
100
100
  await new Promise(r => setTimeout(r, 150));
101
101
  } else {
102
102
  // too many retries
@@ -144,7 +144,7 @@ async function getThread(client, index, account, messageData, logger) {
144
144
  })
145
145
  });
146
146
  } catch (err) {
147
- logger.error({ msg: 'Failed to update thread entry', err });
147
+ logger.warn({ msg: 'Failed to update thread entry', err });
148
148
  }
149
149
  }
150
150
  }
@@ -0,0 +1,231 @@
1
+ 'use strict';
2
+
3
+ // Per-token audit trail: which credential made which request, and whether it was allowed.
4
+ //
5
+ // EmailEngine already logs the token id on every API request line (workers/api.js binds it to the
6
+ // request logger), so the raw material existed - but answering "what has this token been doing" meant
7
+ // grepping the log stream, and `{prefix}tokens:access` keeps only the last use, overwritten each
8
+ // time. This makes the question answerable per credential.
9
+ //
10
+ // Off by default. It adds a write to the hot path of every authenticated request and most instances
11
+ // will never read it, so the compliance case is served by the log being available rather than by
12
+ // every deployment paying for it.
13
+ //
14
+ // A recent-activity view, not a tamper-evident trail. One capped list holds a token's allowed and
15
+ // denied requests together, so a holder that keeps making permitted calls eventually pushes its own
16
+ // refusals off the end. That is deliberate - splitting the two would double the read path to protect
17
+ // a record that is not the authoritative one anyway: both enforcement points write every refusal to
18
+ // the application log as well, and that stream is the one an instance ships off the box. What this
19
+ // module adds is being able to ask the question per credential instead of grepping for a token id.
20
+
21
+ const { redis } = require('./db');
22
+ const logger = require('./logger');
23
+ const msgpack = require('./msgpack');
24
+ const settings = require('./settings');
25
+ const { REDIS_PREFIX, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
26
+ const { extractMultiError } = require('./redis-operations');
27
+
28
+ // Both overrides below are whole counts that have to be at least 1, and anything else falls back to
29
+ // the default rather than being clamped towards it - "0" is not a request for the smallest possible
30
+ // log, it is a value this module has no reading for. Each has its own way of going wrong: the entry
31
+ // cap floors the log route's `pageSize` ceiling, so a value below 1 left `min(1).max(0)` on the
32
+ // query schema and no request could satisfy it, and Redis DELETES a key given a non-positive
33
+ // EXPIRE, so a negative age would drop each entry in the transaction that wrote it.
34
+ function positiveInt(value, fallback) {
35
+ const parsed = Math.floor(Number(value));
36
+ return Number.isFinite(parsed) && parsed >= 1 ? parsed : fallback;
37
+ }
38
+
39
+ // How many entries to keep per token. The cap is a hard trim rather than a target, and it is what
40
+ // bounds the whole feature: every write trims, so total storage is a function of how many tokens are
41
+ // in use rather than of request volume. A full log of typical entries costs roughly 170KB of Redis
42
+ // per token, so a thousand active tokens cost about 170MB - entries carrying a maximum-length
43
+ // account run some three times that. Raise it against those figures, and against the fact that a log
44
+ // of who read whose mail carries the sensitivity of the mail itself.
45
+ const LOG_ENTRIES = positiveInt(process.env.EENGINE_TOKEN_LOG_ENTRIES, 1000);
46
+
47
+ // How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
48
+ // how long a log outlives the credential's activity rather than how long each entry lives - which is
49
+ // the useful bound, because a token nobody has used is a log nobody needs.
50
+ const LOG_AGE = positiveInt(process.env.EENGINE_TOKEN_LOG_AGE, 7 * 24 * 3600);
51
+
52
+ // The largest page the log route will serve. Deliberately not the retention cap: one bounds a single
53
+ // response, the other bounds stored data, and while they were the same constant raising retention
54
+ // also multiplied the work one request could ask for - an LRANGE, a msgpack decode and a joi
55
+ // response validation per entry, on an API worker that is single-threaded by default. Floored by the
56
+ // entry cap so an instance that keeps fewer entries than this cannot be asked for a page it could
57
+ // never fill, which is also what keeps the route's `min(1).max()` satisfiable.
58
+ const MAX_PAGE_SIZE = Math.min(LOG_ENTRIES, 200);
59
+
60
+ // The page size served when a request does not ask for one. Joi does not validate a schema's own
61
+ // default against that schema, so a default above the maximum is handed back for an absent value
62
+ // while the same value sent explicitly is refused - which is what an instance keeping fewer than 20
63
+ // entries used to do to the exact number /swagger.json advertises as the default.
64
+ const DEFAULT_LOG_PAGE_SIZE = Math.min(20, MAX_PAGE_SIZE);
65
+
66
+ // The setting is read per request, and the request path already makes several Redis round trips, so
67
+ // a short in-process cache keeps the steady state at zero extra reads. The window is the longest a
68
+ // deployment waits for a change to the setting to take effect, per API worker.
69
+ const FLAG_CACHE_MS = 10 * 1000;
70
+
71
+ let flagCachedAt = 0;
72
+ let flagValue = false;
73
+
74
+ async function isEnabled() {
75
+ const now = Date.now();
76
+ if (now - flagCachedAt < FLAG_CACHE_MS) {
77
+ return flagValue;
78
+ }
79
+
80
+ try {
81
+ flagValue = !!(await settings.get('tokenAuditLog'));
82
+ } catch (err) {
83
+ // Never let a settings read decide a request. Failing closed here means "do not log", which
84
+ // loses a record rather than refusing a call the token was entitled to make.
85
+ flagValue = false;
86
+ }
87
+ flagCachedAt = now;
88
+
89
+ return flagValue;
90
+ }
91
+
92
+ // Exposed so a test can drop the cache rather than wait it out
93
+ function resetFlagCache() {
94
+ flagCachedAt = 0;
95
+ flagValue = false;
96
+ }
97
+
98
+ function logKey(tokenId) {
99
+ return `${REDIS_PREFIX}tokens:log:${tokenId}`;
100
+ }
101
+
102
+ /**
103
+ * Records one request against a token, if the audit log is enabled.
104
+ *
105
+ * Deliberately not awaited by its callers: the entry is a record OF the request, not part of
106
+ * serving it, so a slow or unavailable Redis must not add latency to a call that already succeeded.
107
+ * The promise handles its own failure for the same reason - an unhandled rejection here would reach
108
+ * the worker's global handler and kill it over a log line.
109
+ *
110
+ * A list rather than a Redis stream: the only reader is "show me this token's recent requests", which
111
+ * a capped list answers directly, and it leaves the cheap last-use lookup in `{prefix}tokens:access`
112
+ * that tokens.list() already reads alone.
113
+ *
114
+ * @param {Object} entry
115
+ * @param {String} entry.tokenId - SHA-256 hash of the token, the same id tokens.list() reports
116
+ * @param {String} [entry.ip] - calling address
117
+ * @param {String} [entry.method] - HTTP method, or the surface name for SMTP and the IMAP proxy
118
+ * @param {String} [entry.path] - request path, or the surface name
119
+ * @param {String} [entry.action] - resolved permission action
120
+ * @param {String} [entry.group] - resolved permission group
121
+ * @param {String} [entry.account] - account the request addressed
122
+ * @param {String} entry.status - 'allowed' or 'denied'
123
+ * @param {String} [entry.reason] - why it was denied
124
+ */
125
+ function record(entry) {
126
+ if (!entry || !entry.tokenId) {
127
+ return;
128
+ }
129
+
130
+ isEnabled()
131
+ .then(async enabled => {
132
+ if (!enabled) {
133
+ return;
134
+ }
135
+
136
+ const key = logKey(entry.tokenId);
137
+
138
+ // The route TEMPLATE, not the resolved URL - `/v1/account/{account}/messages` rather
139
+ // than the request line. That is the deliberate boundary: the resolved URL would carry
140
+ // search terms and message ids out of the query string into a second store with its own
141
+ // retention, and the template plus the account answers what the credential reached.
142
+ const stored = {
143
+ time: Date.now(),
144
+ ip: entry.ip || null,
145
+ method: entry.method || null,
146
+ path: entry.path || null,
147
+ action: entry.action || null,
148
+ group: entry.group || null,
149
+ // The one field here that is unvalidated client input: both enforcement points build
150
+ // their entry before route validation runs, so this is whatever arrived in the path
151
+ // segment or the `?account=` query argument. Truncating to the longest id that could
152
+ // be real bounds an entry the cap above then multiplies by a thousand, and keeps the
153
+ // stored value inside the `accountIdSchema` the log endpoint types it as.
154
+ account: entry.account ? entry.account.slice(0, MAX_ACCOUNT_ID_LENGTH) : null,
155
+ status: entry.status,
156
+ reason: entry.reason || null
157
+ };
158
+
159
+ const results = await redis
160
+ .multi()
161
+ .lpushBuffer(key, msgpack.encode(stored))
162
+ .ltrim(key, 0, LOG_ENTRIES - 1)
163
+ .expire(key, LOG_AGE)
164
+ .exec();
165
+
166
+ const err = extractMultiError(results);
167
+ if (err) {
168
+ throw err;
169
+ }
170
+ })
171
+ .catch(err => logger.error({ msg: 'Failed to record a token audit entry', tokenId: entry.tokenId, err }));
172
+ }
173
+
174
+ /**
175
+ * Reads a token's audit log, newest first.
176
+ *
177
+ * @param {String} tokenId - SHA-256 hash of the token
178
+ * @param {Object} [opts]
179
+ * @param {Number} [opts.page] - zero-based page
180
+ * @param {Number} [opts.pageSize] - entries per page
181
+ * @returns {Promise<Object>} { total, page, pages, entries }
182
+ */
183
+ async function list(tokenId, opts) {
184
+ const { page: rawPage, pageSize: rawPageSize } = opts || {};
185
+
186
+ const page = Math.max(Number(rawPage) || 0, 0);
187
+ const pageSize = Math.min(Math.max(Number(rawPageSize) || DEFAULT_LOG_PAGE_SIZE, 1), MAX_PAGE_SIZE);
188
+
189
+ const key = logKey(tokenId);
190
+ const startPos = page * pageSize;
191
+
192
+ const [total, encoded] = await Promise.all([redis.llen(key), redis.lrangeBuffer(key, startPos, startPos + pageSize - 1)]);
193
+
194
+ const entries = [];
195
+ for (const buf of encoded || []) {
196
+ try {
197
+ const decoded = msgpack.decode(buf);
198
+ decoded.time = decoded.time ? new Date(decoded.time) : null;
199
+ entries.push(decoded);
200
+ } catch (err) {
201
+ // One unreadable entry must not hide the rest of the trail
202
+ logger.error({ msg: 'Failed to decode a token audit entry', tokenId, err });
203
+ }
204
+ }
205
+
206
+ return {
207
+ total,
208
+ page,
209
+ pages: Math.ceil(total / pageSize),
210
+ entries
211
+ };
212
+ }
213
+
214
+ // logKey is exported so lib/tokens.js can drop the log inside the same multi() that removes the
215
+ // token, rather than spelling the key a second time.
216
+ /**
217
+ * Records an accepted request. Thin wrapper so the 'allowed'/'denied' vocabulary lives here rather
218
+ * than being spelled at every call site in the two enforcement points.
219
+ */
220
+ function allowed(entry) {
221
+ record(Object.assign({ status: 'allowed' }, entry));
222
+ }
223
+
224
+ /**
225
+ * Records a refused request, with the reason it was refused.
226
+ */
227
+ function denied(entry, reason) {
228
+ record(Object.assign({ status: 'denied', reason }, entry));
229
+ }
230
+
231
+ module.exports = { record, allowed, denied, list, logKey, resetFlagCache, LOG_ENTRIES, MAX_PAGE_SIZE, DEFAULT_LOG_PAGE_SIZE };