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
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
 
@@ -253,6 +281,11 @@ module.exports = {
253
281
  }
254
282
  }
255
283
 
284
+ // see set(): an explicit sentryEnabled write ends the trial-managed Sentry state
285
+ if ('sentryEnabled' in obj) {
286
+ await module.exports.clear('sentryAutoEnabled');
287
+ }
288
+
256
289
  return await redis.hmset(`${REDIS_PREFIX}settings`, storeObj);
257
290
  },
258
291
 
@@ -363,6 +396,52 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
363
396
  )
364
397
  .exec();
365
398
 
399
+ // Trial installations report errors to the shared community Sentry by default, so issues
400
+ // with evaluation instances reach the developers. The default is only applied while the
401
+ // operator has never touched the sentryEnabled setting (atomic through setIfMissing),
402
+ // tracked through the internal sentryAutoEnabled marker: activating a full license or
403
+ // removing the license clears the default again as long as the marker still owns the
404
+ // state, and any explicit operator write to sentryEnabled drops the marker (see
405
+ // set()/setMulti()), making that choice permanent. A SENTRY_DSN environment value pins
406
+ // the Sentry configuration regardless of these settings. License activation must never
407
+ // fail on this convenience, hence the catch-all.
408
+ try {
409
+ if (licenseData.trial) {
410
+ if (await module.exports.setIfMissing('sentryEnabled', true)) {
411
+ await module.exports.set('sentryAutoEnabled', true);
412
+ logger.info({ msg: 'Enabled Sentry error reporting for the trial license' });
413
+ }
414
+ } else {
415
+ await module.exports.clearTrialSentryDefault('license activation');
416
+ }
417
+ } catch (err) {
418
+ logger.error({ msg: 'Failed to apply the trial Sentry default', err });
419
+ }
420
+
421
+ return true;
422
+ },
423
+
424
+ // Undoes the trial Sentry default while the sentryAutoEnabled marker still owns the state;
425
+ // a no-op after any explicit operator choice. Never throws: callers sit on license
426
+ // activation/removal paths that must not fail on this convenience.
427
+ async clearTrialSentryDefault(reason) {
428
+ try {
429
+ if (await module.exports.get('sentryAutoEnabled')) {
430
+ await module.exports.clear('sentryEnabled');
431
+ await module.exports.clear('sentryAutoEnabled');
432
+ logger.info({ msg: 'Disabled the trial default for Sentry error reporting', reason });
433
+ }
434
+ } catch (err) {
435
+ logger.error({ msg: 'Failed to clear the trial Sentry default', reason, err });
436
+ }
437
+ },
438
+
439
+ // Owns the stored license state: the license file itself, the subscription grace marker,
440
+ // and the trial Sentry default that activation may have applied. Used by the explicit
441
+ // remove-license actions and by the grace-period expiry in server.js.
442
+ async removeLicense() {
443
+ await redis.multi().hdel(`${REDIS_PREFIX}settings`, 'license').hdel(`${REDIS_PREFIX}settings`, 'subexp').exec();
444
+ await module.exports.clearTrialSentryDefault('license removal');
366
445
  return true;
367
446
  }
368
447
  };
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,208 @@
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 } = 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 is also the upper bound of the log route's `pageSize`, so a value below 1 left `min(1).max(0)`
32
+ // on the 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. A log of who read whose mail carries the sensitivity of the
40
+ // mail itself, so the default is low and the cap is a hard trim rather than a target.
41
+ const LOG_ENTRIES = positiveInt(process.env.EENGINE_TOKEN_LOG_ENTRIES, 200);
42
+
43
+ // How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
44
+ // how long a log outlives the credential's activity rather than how long each entry lives - which is
45
+ // the useful bound, because a token nobody has used is a log nobody needs.
46
+ const LOG_AGE = positiveInt(process.env.EENGINE_TOKEN_LOG_AGE, 7 * 24 * 3600);
47
+
48
+ // The setting is read per request, and the request path already makes several Redis round trips, so
49
+ // a short in-process cache keeps the steady state at zero extra reads. The window is the longest a
50
+ // deployment waits for a change to the setting to take effect, per API worker.
51
+ const FLAG_CACHE_MS = 10 * 1000;
52
+
53
+ let flagCachedAt = 0;
54
+ let flagValue = false;
55
+
56
+ async function isEnabled() {
57
+ const now = Date.now();
58
+ if (now - flagCachedAt < FLAG_CACHE_MS) {
59
+ return flagValue;
60
+ }
61
+
62
+ try {
63
+ flagValue = !!(await settings.get('tokenAuditLog'));
64
+ } catch (err) {
65
+ // Never let a settings read decide a request. Failing closed here means "do not log", which
66
+ // loses a record rather than refusing a call the token was entitled to make.
67
+ flagValue = false;
68
+ }
69
+ flagCachedAt = now;
70
+
71
+ return flagValue;
72
+ }
73
+
74
+ // Exposed so a test can drop the cache rather than wait it out
75
+ function resetFlagCache() {
76
+ flagCachedAt = 0;
77
+ flagValue = false;
78
+ }
79
+
80
+ function logKey(tokenId) {
81
+ return `${REDIS_PREFIX}tokens:log:${tokenId}`;
82
+ }
83
+
84
+ /**
85
+ * Records one request against a token, if the audit log is enabled.
86
+ *
87
+ * Deliberately not awaited by its callers: the entry is a record OF the request, not part of
88
+ * serving it, so a slow or unavailable Redis must not add latency to a call that already succeeded.
89
+ * The promise handles its own failure for the same reason - an unhandled rejection here would reach
90
+ * the worker's global handler and kill it over a log line.
91
+ *
92
+ * A list rather than a Redis stream: the only reader is "show me this token's recent requests", which
93
+ * a capped list answers directly, and it leaves the cheap last-use lookup in `{prefix}tokens:access`
94
+ * that tokens.list() already reads alone.
95
+ *
96
+ * @param {Object} entry
97
+ * @param {String} entry.tokenId - SHA-256 hash of the token, the same id tokens.list() reports
98
+ * @param {String} [entry.ip] - calling address
99
+ * @param {String} [entry.method] - HTTP method, or the surface name for SMTP and the IMAP proxy
100
+ * @param {String} [entry.path] - request path, or the surface name
101
+ * @param {String} [entry.action] - resolved permission action
102
+ * @param {String} [entry.group] - resolved permission group
103
+ * @param {String} [entry.account] - account the request addressed
104
+ * @param {String} entry.status - 'allowed' or 'denied'
105
+ * @param {String} [entry.reason] - why it was denied
106
+ */
107
+ function record(entry) {
108
+ if (!entry || !entry.tokenId) {
109
+ return;
110
+ }
111
+
112
+ isEnabled()
113
+ .then(async enabled => {
114
+ if (!enabled) {
115
+ return;
116
+ }
117
+
118
+ const key = logKey(entry.tokenId);
119
+
120
+ // The route TEMPLATE, not the resolved URL - `/v1/account/{account}/messages` rather
121
+ // than the request line. That is the deliberate boundary: the resolved URL would carry
122
+ // search terms and message ids out of the query string into a second store with its own
123
+ // retention, and the template plus the account answers what the credential reached.
124
+ const stored = {
125
+ time: Date.now(),
126
+ ip: entry.ip || null,
127
+ method: entry.method || null,
128
+ path: entry.path || null,
129
+ action: entry.action || null,
130
+ group: entry.group || null,
131
+ account: entry.account || null,
132
+ status: entry.status,
133
+ reason: entry.reason || null
134
+ };
135
+
136
+ const results = await redis
137
+ .multi()
138
+ .lpushBuffer(key, msgpack.encode(stored))
139
+ .ltrim(key, 0, LOG_ENTRIES - 1)
140
+ .expire(key, LOG_AGE)
141
+ .exec();
142
+
143
+ const err = extractMultiError(results);
144
+ if (err) {
145
+ throw err;
146
+ }
147
+ })
148
+ .catch(err => logger.error({ msg: 'Failed to record a token audit entry', tokenId: entry.tokenId, err }));
149
+ }
150
+
151
+ /**
152
+ * Reads a token's audit log, newest first.
153
+ *
154
+ * @param {String} tokenId - SHA-256 hash of the token
155
+ * @param {Object} [opts]
156
+ * @param {Number} [opts.page] - zero-based page
157
+ * @param {Number} [opts.pageSize] - entries per page
158
+ * @returns {Promise<Object>} { total, page, pages, entries }
159
+ */
160
+ async function list(tokenId, opts) {
161
+ const { page: rawPage, pageSize: rawPageSize } = opts || {};
162
+
163
+ const page = Math.max(Number(rawPage) || 0, 0);
164
+ const pageSize = Math.min(Math.max(Number(rawPageSize) || 20, 1), LOG_ENTRIES);
165
+
166
+ const key = logKey(tokenId);
167
+ const startPos = page * pageSize;
168
+
169
+ const [total, encoded] = await Promise.all([redis.llen(key), redis.lrangeBuffer(key, startPos, startPos + pageSize - 1)]);
170
+
171
+ const entries = [];
172
+ for (const buf of encoded || []) {
173
+ try {
174
+ const decoded = msgpack.decode(buf);
175
+ decoded.time = decoded.time ? new Date(decoded.time) : null;
176
+ entries.push(decoded);
177
+ } catch (err) {
178
+ // One unreadable entry must not hide the rest of the trail
179
+ logger.error({ msg: 'Failed to decode a token audit entry', tokenId, err });
180
+ }
181
+ }
182
+
183
+ return {
184
+ total,
185
+ page,
186
+ pages: Math.ceil(total / pageSize),
187
+ entries
188
+ };
189
+ }
190
+
191
+ // logKey is exported so lib/tokens.js can drop the log inside the same multi() that removes the
192
+ // token, rather than spelling the key a second time.
193
+ /**
194
+ * Records an accepted request. Thin wrapper so the 'allowed'/'denied' vocabulary lives here rather
195
+ * than being spelled at every call site in the two enforcement points.
196
+ */
197
+ function allowed(entry) {
198
+ record(Object.assign({ status: 'allowed' }, entry));
199
+ }
200
+
201
+ /**
202
+ * Records a refused request, with the reason it was refused.
203
+ */
204
+ function denied(entry, reason) {
205
+ record(Object.assign({ status: 'denied', reason }, entry));
206
+ }
207
+
208
+ module.exports = { record, allowed, denied, list, logKey, resetFlagCache, LOG_ENTRIES };
@@ -0,0 +1,219 @@
1
+ 'use strict';
2
+
3
+ // Presentation of the token permission vocabulary for the admin UI: the checkbox rows on the token
4
+ // form, the presets above them, and the one-line summary on the token list.
5
+ //
6
+ // Its own module because two views need the same labels, and because the labels have to be derived
7
+ // from lib/api-routes/permission-map.js rather than typed again - a group added there without a
8
+ // label here would render as a blank checkbox, and one removed would leave a control that posts a
9
+ // value the API refuses.
10
+
11
+ const { ACTION, GROUP, GRANTABLE_GROUPS, SURFACE_GRANTS } = require('./api-routes/permission-map');
12
+ const tokenPermissions = require('./token-permissions');
13
+ const { ENUM_DESCRIPTIONS } = require('./enum-descriptions');
14
+
15
+ // Sentence-case labels for the checkbox rows. The slug itself is shown beside each one, so this only
16
+ // has to read well - it is not the identifier.
17
+ const ACTION_LABELS = {
18
+ [ACTION.READ]: 'Read',
19
+ [ACTION.WRITE]: 'Create and modify',
20
+ [ACTION.SEND]: 'Send email',
21
+ [ACTION.DESTRUCTIVE]: 'Delete'
22
+ };
23
+
24
+ const GROUP_LABELS = {
25
+ [GROUP.ACCOUNT]: 'Accounts',
26
+ [GROUP.MAILBOX]: 'Folders',
27
+ [GROUP.MESSAGE]: 'Messages',
28
+ [GROUP.SUBMIT]: 'Sending',
29
+ [GROUP.OUTBOX]: 'Sending queue',
30
+ [GROUP.EXPORT]: 'Bulk export',
31
+ [GROUP.TEMPLATE]: 'Templates',
32
+ [GROUP.BLOCKLIST]: 'Suppression lists',
33
+ [GROUP.WEBHOOK]: 'Webhook routes',
34
+ [GROUP.GATEWAY]: 'SMTP gateways',
35
+ [GROUP.EVENTS]: 'Change stream',
36
+ [GROUP.DIAGNOSTICS]: 'Statistics and status',
37
+ [GROUP.LOGS]: 'Connection logs'
38
+ };
39
+
40
+ // Clusters for the section list. Thirteen rows at identical weight is a scan rather than a choice,
41
+ // and the split is the one a reader already has: the mail itself, the things that act on it, and the
42
+ // things that only watch.
43
+ const GROUP_CLUSTERS = [
44
+ { label: 'Mail', groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.SUBMIT, GROUP.OUTBOX, GROUP.EXPORT] },
45
+ { label: 'Configuration', groups: [GROUP.TEMPLATE, GROUP.BLOCKLIST, GROUP.WEBHOOK, GROUP.GATEWAY] },
46
+ { label: 'Monitoring', groups: [GROUP.EVENTS, GROUP.DIAGNOSTICS, GROUP.LOGS] }
47
+ ];
48
+
49
+ // Starting points, because a fourteen-row matrix is not how anyone begins. Each is a real shape
50
+ // somebody asks for rather than an illustration of the axes.
51
+ const PRESETS = [
52
+ {
53
+ label: 'Read only',
54
+ title: 'Read messages, folders and accounts. Cannot change or send anything',
55
+ actions: [ACTION.READ],
56
+ groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.OUTBOX, GROUP.DIAGNOSTICS]
57
+ },
58
+ {
59
+ // Not "never delete it". Filing mail is the same operation as deleting it here - the delete
60
+ // endpoint moves the message to Trash, which this preset allows the token to do directly -
61
+ // so the honest claim is about the endpoints, not the outcome. See the note on
62
+ // ACTION.DESTRUCTIVE in lib/api-routes/permission-map.js.
63
+ label: 'Mail agent',
64
+ title: 'Read, file and send mail, without reaching the delete endpoints',
65
+ actions: [ACTION.READ, ACTION.WRITE, ACTION.SEND],
66
+ groups: [GROUP.ACCOUNT, GROUP.MAILBOX, GROUP.MESSAGE, GROUP.SUBMIT, GROUP.OUTBOX]
67
+ },
68
+ {
69
+ // Deliberately not described as "no access to stored messages": a submit payload may carry
70
+ // `reference: {message, action: 'forward'}`, which reads a stored message and delivers it, so
71
+ // sending implies read-through of a message the holder can name. The grant is route-level and
72
+ // does not inspect the payload, so the claim would have been false.
73
+ label: 'Send only',
74
+ title: 'Submit mail and watch the sending queue',
75
+ actions: [ACTION.READ, ACTION.SEND],
76
+ groups: [GROUP.SUBMIT, GROUP.OUTBOX]
77
+ },
78
+ {
79
+ label: 'Everything allowed',
80
+ title: 'Every action on every section that can be granted. Still cannot reach credentials or settings',
81
+ actions: Object.values(ACTION),
82
+ groups: GRANTABLE_GROUPS
83
+ }
84
+ ];
85
+
86
+ // How each non-API scope reads in a sentence. The grants themselves come from SURFACE_GRANTS, which
87
+ // is what the enforcement reads, so this cannot describe rules that have since changed.
88
+ const SURFACE_LABELS = {
89
+ smtp: 'send over SMTP',
90
+ 'imap-proxy': 'connect through the IMAP proxy',
91
+ metrics: 'read the metrics endpoint'
92
+ };
93
+
94
+ /**
95
+ * View model for the permission controls on the token form.
96
+ *
97
+ * @returns {Object} { permissionActions, permissionGroups, permissionPresets }
98
+ */
99
+ function formModel() {
100
+ return {
101
+ permissionActions: Object.values(ACTION).map(value => ({
102
+ value,
103
+ inputId: `permissionAction_${value}`,
104
+ label: ACTION_LABELS[value] || value,
105
+ description: ENUM_DESCRIPTIONS.tokenAction[value] || ''
106
+ })),
107
+
108
+ // Clustered rather than flat. Asserted against GRANTABLE_GROUPS in the tests, so a group
109
+ // added without a cluster cannot silently vanish from the form.
110
+ permissionGroupClusters: GROUP_CLUSTERS.map(cluster => ({
111
+ label: cluster.label,
112
+ groups: cluster.groups.map(value => ({
113
+ value,
114
+ inputId: `permissionGroup_${value}`,
115
+ label: GROUP_LABELS[value] || value,
116
+ description: ENUM_DESCRIPTIONS.tokenGroup[value] || ''
117
+ }))
118
+ })),
119
+
120
+ // What each non-API scope needs before it can be used, derived from the tables that enforce
121
+ // it rather than restated in the page script. A hand-copied mirror would let the form keep
122
+ // showing an old warning after the grant list changed, which is exactly the drift
123
+ // lib/auth-token.js exists to prevent.
124
+ permissionSurfaces: Object.entries(SURFACE_LABELS).map(([scope, label]) => ({
125
+ scope,
126
+ label,
127
+ actionList: [...new Set(SURFACE_GRANTS[scope].map(grant => grant.action))].join(','),
128
+ groupList: [...new Set(SURFACE_GRANTS[scope].map(grant => grant.group))].join(',')
129
+ })),
130
+
131
+ // data-actions/data-groups are read by the preset buttons in views/tokens/new.hbs
132
+ permissionPresets: PRESETS.map(preset => ({
133
+ label: preset.label,
134
+ title: preset.title,
135
+ actionList: preset.actions.join(','),
136
+ groupList: preset.groups.join(',')
137
+ }))
138
+ };
139
+ }
140
+
141
+ // Phrases the two axes as something a person reads rather than as two labelled fields. An axis that
142
+ // is absent is not a restriction, so it is left out of the sentence entirely - saying "all sections"
143
+ // would imply a grant the record does not make.
144
+ //
145
+ // An axis that names everything is collapsed rather than enumerated. Spelling out all thirteen
146
+ // sections produced a line long enough to push the table sideways, and it read as a detailed
147
+ // restriction when it is the opposite: the interesting fact about such a token is what it still
148
+ // cannot reach.
149
+ function sentenceFor(actions, groups, coversAllActions, coversAllGroups) {
150
+ // An empty allowlist allows nothing, so the token authenticates and then refuses everything.
151
+ // "Can none only" said the record; this says what it means.
152
+ if (actions === 'none' || groups === 'none') {
153
+ return 'Allows nothing - this token cannot make any request';
154
+ }
155
+ const verb = coversAllActions ? 'Full access' : actions && `Can ${actions.toLowerCase()}`;
156
+ const where = coversAllGroups ? 'every section' : groups;
157
+
158
+ if (verb && where) {
159
+ return coversAllActions && coversAllGroups ? 'Full access, except settings, credentials and tokens' : `${verb} in ${where}`;
160
+ }
161
+ if (verb) {
162
+ return coversAllActions ? 'Full access' : `${verb} only`;
163
+ }
164
+ if (where) {
165
+ return coversAllGroups ? 'Every section' : `Limited to ${where}`;
166
+ }
167
+ return 'Restricted';
168
+ }
169
+
170
+ /**
171
+ * One-line description of what a stored `permissions` record allows, for the token list.
172
+ *
173
+ * @param {*} permissions - the record's `permissions` field
174
+ * @returns {Object|null} { actions, groups, unreadable } or null when the token is not narrowed
175
+ */
176
+ function summarize(permissions) {
177
+ // Asked of the module that enforces it rather than re-derived here. `{}`, an unknown axis and a
178
+ // slug outside the vocabulary are all refusals, so a view that only looked for a non-object
179
+ // would render them as working narrow credentials - which is the opposite of the truth, since
180
+ // every request such a token makes is denied.
181
+ const verdict = tokenPermissions.inspect({ permissions });
182
+
183
+ if (!verdict.narrowed) {
184
+ return null;
185
+ }
186
+
187
+ if (verdict.malformed) {
188
+ return { actions: null, groups: null, unreadable: true };
189
+ }
190
+
191
+ const label = (values, labels) => {
192
+ if (!Array.isArray(values)) {
193
+ return null;
194
+ }
195
+ if (!values.length) {
196
+ // An empty allowlist allows nothing, which is the opposite of the axis being absent
197
+ return 'none';
198
+ }
199
+ // Object.hasOwn rather than a bare lookup, for the same reason the parse uses it: a slug of
200
+ // `constructor` would otherwise render an Object.prototype member
201
+ return values.map(value => (Object.hasOwn(labels, value) ? labels[value] : value)).join(', ');
202
+ };
203
+
204
+ const actions = label(permissions.actions, ACTION_LABELS);
205
+ const groups = label(permissions.groups, GROUP_LABELS);
206
+
207
+ const covers = (values, whole) => Array.isArray(values) && values.length === whole.length && whole.every(entry => values.includes(entry));
208
+
209
+ return {
210
+ actions,
211
+ groups,
212
+ // One line a person can read, rather than two labelled fragments. "Can: Read / In: Messages"
213
+ // is the record read out loud; this is what the record means.
214
+ sentence: sentenceFor(actions, groups, covers(permissions.actions, Object.values(ACTION)), covers(permissions.groups, GRANTABLE_GROUPS)),
215
+ unreadable: false
216
+ };
217
+ }
218
+
219
+ module.exports = { formModel, summarize, ACTION_LABELS, GROUP_LABELS };