emailengine-app 2.79.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 (50) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +39 -0
  3. package/lib/account.js +43 -2
  4. package/lib/api-routes/permission-map.js +4 -0
  5. package/lib/api-routes/route-helpers.js +71 -0
  6. package/lib/api-routes/settings-routes.js +37 -14
  7. package/lib/api-routes/token-routes.js +290 -122
  8. package/lib/arf-detect.js +17 -4
  9. package/lib/bounce-detect.js +28 -17
  10. package/lib/consts.js +6 -0
  11. package/lib/db.js +6 -0
  12. package/lib/email-client/gmail-client.js +4 -7
  13. package/lib/email-client/imap/mailbox.js +35 -35
  14. package/lib/email-client/imap-client.js +49 -2
  15. package/lib/email-client/outlook-client.js +3 -10
  16. package/lib/lua/h-set-new-mark.lua +36 -0
  17. package/lib/message-port-stream.js +84 -1
  18. package/lib/oauth2-apps.js +84 -15
  19. package/lib/openapi/build-document.js +5 -1
  20. package/lib/schemas.js +2 -2
  21. package/lib/settings.js +23 -9
  22. package/lib/token-audit-log.js +32 -9
  23. package/lib/tokens.js +163 -66
  24. package/lib/ui-routes/account-routes.js +13 -6
  25. package/lib/ui-routes/admin-entities-routes.js +52 -17
  26. package/lib/ui-routes/oauth-config-routes.js +7 -7
  27. package/lib/ui-routes/route-helpers.js +28 -1
  28. package/lib/ui-routes/suppression-list-routes.js +14 -9
  29. package/lib/utils/decode-headers.js +42 -0
  30. package/lib/utils/header-map.js +48 -0
  31. package/lib/utils/unsafe-key.js +59 -0
  32. package/lib/webhook-routing.js +6 -2
  33. package/lib/webhooks.js +28 -0
  34. package/package.json +1 -1
  35. package/server.js +39 -17
  36. package/views/accounts/account.hbs +8 -8
  37. package/views/accounts/browse.hbs +1 -1
  38. package/views/accounts/edit.hbs +2 -2
  39. package/views/gateways/edit.hbs +1 -1
  40. package/views/gateways/gateway.hbs +2 -2
  41. package/views/gateways/index.hbs +7 -7
  42. package/views/partials/accounts_table.hbs +7 -7
  43. package/views/suppression-lists/list.hbs +1 -1
  44. package/views/templates/index.hbs +2 -2
  45. package/views/templates/template.hbs +1 -1
  46. package/views/tokens/index.hbs +22 -2
  47. package/views/tokens/new.hbs +10 -3
  48. package/workers/api.js +41 -47
  49. package/workers/imap.js +65 -72
  50. package/workers/webhooks.js +21 -1
@@ -18,6 +18,7 @@
18
18
  // response.schema -> the 200 response body
19
19
  // plugins.openapi.responses -> the documented status codes (see apiResponses in lib/schemas.js)
20
20
  // plugins.openapi.produces -> the media type for routes that do not return JSON
21
+ // plugins.openapi.deprecated -> the route is left out of the document (compatibility aliases)
21
22
  // plugins.openapi['x-*'] -> vendor extensions on the operation, notably x-ee-behavior
22
23
 
23
24
  const { STATUS_CODES } = require('node:http');
@@ -282,7 +283,10 @@ function buildOpenApiDocument(routes, options) {
282
283
 
283
284
  const paths = {};
284
285
 
285
- for (const route of sortRoutes(routes.filter(route => (route.settings.tags || []).includes(API_ROUTE_TAG)))) {
286
+ // Routes marked `plugins.openapi.deprecated` are compatibility aliases: they stay registered
287
+ // (and keep the `api` tag, which also drives the CSRF skip list) but are left out of the
288
+ // published document and the reference page, so nothing steers a new integration onto them
289
+ for (const route of sortRoutes(routes.filter(route => (route.settings.tags || []).includes(API_ROUTE_TAG) && !pluginOptions(route).deprecated))) {
286
290
  const { path, method, operation } = builder.buildOperation(route);
287
291
 
288
292
  if (!paths[path]) {
package/lib/schemas.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const Joi = require('joi');
4
4
  const config = require('@zone-eu/wild-config');
5
5
  const { getByteSize } = require('./tools');
6
- const { COLLAPSE_CLASS } = require('./consts');
6
+ const { COLLAPSE_CLASS, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
7
7
  const { locales } = require('./translations');
8
8
  const { OAUTH_PROVIDERS } = require('./oauth2-apps');
9
9
  const { ACCOUNT_STATES } = require('./account/account-state');
@@ -41,7 +41,7 @@ config.api = config.api || {
41
41
  const DEFAULT_MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024;
42
42
  const MAX_ATTACHMENT_SIZE = getByteSize(process.env.EENGINE_MAX_SIZE || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
43
43
 
44
- const accountIdSchema = Joi.string().empty('').trim().max(256).example('user123').description('Unique identifier for the email account');
44
+ const accountIdSchema = Joi.string().empty('').trim().max(MAX_ACCOUNT_ID_LENGTH).example('user123').description('Unique identifier for the email account');
45
45
 
46
46
  // Suppression list identifier, shared by the Blocklists API and the suppression-list admin UI
47
47
  // so the two surfaces cannot drift on what a valid list ID is
package/lib/settings.js CHANGED
@@ -254,6 +254,19 @@ module.exports = {
254
254
  return (await redis.hsetnx(`${REDIS_PREFIX}settings`, key, value)) === 1;
255
255
  },
256
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
+
257
270
  async setMulti(obj) {
258
271
  const encryptSecret = await getSecret();
259
272
  let docStoreUpdated = false;
@@ -398,17 +411,18 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
398
411
 
399
412
  // Trial installations report errors to the shared community Sentry by default, so issues
400
413
  // 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.
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.
408
423
  try {
409
424
  if (licenseData.trial) {
410
- if (await module.exports.setIfMissing('sentryEnabled', true)) {
411
- await module.exports.set('sentryAutoEnabled', true);
425
+ if (await module.exports.setIfMissingWithMarker('sentryEnabled', true, 'sentryAutoEnabled', true)) {
412
426
  logger.info({ msg: 'Enabled Sentry error reporting for the trial license' });
413
427
  }
414
428
  } else {
@@ -22,29 +22,47 @@ const { redis } = require('./db');
22
22
  const logger = require('./logger');
23
23
  const msgpack = require('./msgpack');
24
24
  const settings = require('./settings');
25
- const { REDIS_PREFIX } = require('./consts');
25
+ const { REDIS_PREFIX, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
26
26
  const { extractMultiError } = require('./redis-operations');
27
27
 
28
28
  // Both overrides below are whole counts that have to be at least 1, and anything else falls back to
29
29
  // the default rather than being clamped towards it - "0" is not a request for the smallest possible
30
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
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
33
  // EXPIRE, so a negative age would drop each entry in the transaction that wrote it.
34
34
  function positiveInt(value, fallback) {
35
35
  const parsed = Math.floor(Number(value));
36
36
  return Number.isFinite(parsed) && parsed >= 1 ? parsed : fallback;
37
37
  }
38
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);
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);
42
46
 
43
47
  // How long a token's log survives its last use, in seconds. Refreshed on every write, so this bounds
44
48
  // how long a log outlives the credential's activity rather than how long each entry lives - which is
45
49
  // the useful bound, because a token nobody has used is a log nobody needs.
46
50
  const LOG_AGE = positiveInt(process.env.EENGINE_TOKEN_LOG_AGE, 7 * 24 * 3600);
47
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
+
48
66
  // The setting is read per request, and the request path already makes several Redis round trips, so
49
67
  // a short in-process cache keeps the steady state at zero extra reads. The window is the longest a
50
68
  // deployment waits for a change to the setting to take effect, per API worker.
@@ -128,7 +146,12 @@ function record(entry) {
128
146
  path: entry.path || null,
129
147
  action: entry.action || null,
130
148
  group: entry.group || null,
131
- account: entry.account || 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,
132
155
  status: entry.status,
133
156
  reason: entry.reason || null
134
157
  };
@@ -161,7 +184,7 @@ async function list(tokenId, opts) {
161
184
  const { page: rawPage, pageSize: rawPageSize } = opts || {};
162
185
 
163
186
  const page = Math.max(Number(rawPage) || 0, 0);
164
- const pageSize = Math.min(Math.max(Number(rawPageSize) || 20, 1), LOG_ENTRIES);
187
+ const pageSize = Math.min(Math.max(Number(rawPageSize) || DEFAULT_LOG_PAGE_SIZE, 1), MAX_PAGE_SIZE);
165
188
 
166
189
  const key = logKey(tokenId);
167
190
  const startPos = page * pageSize;
@@ -205,4 +228,4 @@ function denied(entry, reason) {
205
228
  record(Object.assign({ status: 'denied', reason }, entry));
206
229
  }
207
230
 
208
- module.exports = { record, allowed, denied, list, logKey, resetFlagCache, LOG_ENTRIES };
231
+ module.exports = { record, allowed, denied, list, logKey, resetFlagCache, LOG_ENTRIES, MAX_PAGE_SIZE, DEFAULT_LOG_PAGE_SIZE };
package/lib/tokens.js CHANGED
@@ -5,11 +5,20 @@ const crypto = require('crypto');
5
5
  const msgpack = require('./msgpack');
6
6
  const logger = require('./logger');
7
7
  const { REDIS_PREFIX } = require('./consts');
8
- const { constantTimeEqual, filterListPage } = require('./tools');
8
+ const { constantTimeEqual, matchesListQuery } = require('./tools');
9
+ const { extractMultiError } = require('./redis-operations');
9
10
  const tokenAuditLog = require('./token-audit-log');
10
11
 
11
12
  const SESS_PREFIX = 'sess_';
12
13
 
14
+ // Fields the listing search box matches on, and how many tokens one Redis command covers - a batch
15
+ // of ids per command rather than a command per token, in both the listing reads and the per-account
16
+ // delete. The bound matters twice over: a search over the whole instance would otherwise come back
17
+ // as one reply carrying every record on the server, and an id list spread as call arguments
18
+ // overflows the stack rather than failing cleanly once it is long enough.
19
+ const LIST_QUERY_FIELDS = ['id', 'description', 'account'];
20
+ const TOKEN_BATCH_SIZE = 1000;
21
+
13
22
  /**
14
23
  * The id a token is listed and stored under: the SHA-256 of its raw bytes.
15
24
  *
@@ -64,6 +73,7 @@ function decodeAccessData(encoded, hashedToken) {
64
73
 
65
74
  module.exports = {
66
75
  tokenId,
76
+ TOKEN_BATCH_SIZE,
67
77
 
68
78
  async getSessionToken(sessionId, account, ttl) {
69
79
  const token = crypto.randomBytes(32);
@@ -228,10 +238,9 @@ module.exports = {
228
238
 
229
239
  let res = await req.exec();
230
240
 
231
- for (let entry of res) {
232
- if (entry[0]) {
233
- throw entry[0];
234
- }
241
+ let err = extractMultiError(res);
242
+ if (err) {
243
+ throw err;
235
244
  }
236
245
 
237
246
  if (!nolog) {
@@ -339,10 +348,9 @@ module.exports = {
339
348
 
340
349
  let res = await req.exec();
341
350
 
342
- for (let entry of res) {
343
- if (entry[0]) {
344
- throw entry[0];
345
- }
351
+ let err = extractMultiError(res);
352
+ if (err) {
353
+ throw err;
346
354
  }
347
355
 
348
356
  logger.info(Object.assign({}, tokenData, { msg: 'Deleted an access token', remoteAddress: opts.remoteAddress }));
@@ -350,6 +358,60 @@ module.exports = {
350
358
  return true;
351
359
  },
352
360
 
361
+ /**
362
+ * Removes every access token bound to an account.
363
+ *
364
+ * Called from Account.delete(). Deleting an account used to unlink only its token index, which
365
+ * left the token records themselves in the global hash - and a record there authenticates
366
+ * regardless of whether the account it names still exists, so the credentials of a deleted
367
+ * account kept working. Since an account ID can be registered again, they would even come back
368
+ * pointed at whoever took the name.
369
+ *
370
+ * Owns the index too, rather than leaving it to the caller: it is the only mapping from an
371
+ * account to its tokens, so it must outlive a failure here - otherwise the records it names are
372
+ * live with nothing left pointing at them.
373
+ *
374
+ * @param {String} account - account ID
375
+ * @returns {Promise<Number>} how many tokens the account index listed
376
+ */
377
+ async deleteForAccount(account) {
378
+ let hashedTokens = await redis.smembers(`${REDIS_PREFIX}iat:${account}`);
379
+ if (!hashedTokens || !hashedTokens.length) {
380
+ return 0;
381
+ }
382
+
383
+ // The same three keys delete() removes for a single token, a batch of ids per command.
384
+ //
385
+ // UNLINK for the audit logs: each is a list of up to EENGINE_TOKEN_LOG_ENTRIES entries, and
386
+ // freeing those inline would hold up every other worker - the same reason Account.delete()
387
+ // unlinks throughout. SREM rather than dropping the index outright, so a token minted
388
+ // between the read above and this write keeps its index entry instead of being left in the
389
+ // hash with nothing pointing at it.
390
+ //
391
+ // A transaction, so the commands reach Redis as one block: a connection lost mid-send then
392
+ // revokes nothing and leaves the index to try again from, rather than revoking some.
393
+ let req = redis.multi();
394
+ for (let pos = 0; pos < hashedTokens.length; pos += TOKEN_BATCH_SIZE) {
395
+ let batch = hashedTokens.slice(pos, pos + TOKEN_BATCH_SIZE);
396
+ req = req
397
+ .hdel(`${REDIS_PREFIX}tokens`, ...batch)
398
+ .hdel(`${REDIS_PREFIX}tokens:access`, ...batch)
399
+ .unlink(...batch.map(hashedToken => tokenAuditLog.logKey(hashedToken)))
400
+ .srem(`${REDIS_PREFIX}iat:${account}`, ...batch);
401
+ }
402
+
403
+ let res = await req.exec();
404
+
405
+ let err = extractMultiError(res);
406
+ if (err) {
407
+ throw err;
408
+ }
409
+
410
+ logger.info({ msg: 'Deleted the access tokens of an account', account, tokens: hashedTokens.length });
411
+
412
+ return hashedTokens.length;
413
+ },
414
+
353
415
  async getRawData(token) {
354
416
  if (!/^[0-9a-f]{64}$/i.test(token)) {
355
417
  let err = new Error('Invalid token format');
@@ -408,10 +470,9 @@ module.exports = {
408
470
 
409
471
  let res = await req.exec();
410
472
 
411
- for (let entry of res) {
412
- if (entry[0]) {
413
- throw entry[0];
414
- }
473
+ let err = extractMultiError(res);
474
+ if (err) {
475
+ throw err;
415
476
  }
416
477
 
417
478
  return tokenData;
@@ -433,6 +494,12 @@ module.exports = {
433
494
  page = Math.max(Number(page) || 0, 0);
434
495
  pageSize = Math.max(Number(pageSize) || 20, 1);
435
496
 
497
+ // Normalized here so that "is there a query" and "does this entry match" answer the same
498
+ // question. matchesListQuery() trims before comparing and so matches everything for a
499
+ // whitespace-only query, while the `!query` test below took it for a real one - which put a
500
+ // single space in the search box on the read-everything path with no filter to show for it.
501
+ query = (query || '').toString().trim();
502
+
436
503
  let startPos = page * pageSize;
437
504
 
438
505
  let list;
@@ -444,7 +511,10 @@ module.exports = {
444
511
  list = await redis.smembers(`${REDIS_PREFIX}iat`);
445
512
  }
446
513
 
447
- list = [].concat(list || []).sort((a, b) => -a.localeCompare(b));
514
+ // Byte order rather than localeCompare: the ids are hex, where the two agree, and in the
515
+ // `all` listing this is every token on the instance - a locale-aware comparison over a list
516
+ // that size costs more than the read it precedes.
517
+ list = [].concat(list || []).sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));
448
518
 
449
519
  let response = {
450
520
  account: account || null,
@@ -454,8 +524,8 @@ module.exports = {
454
524
  tokens: []
455
525
  };
456
526
 
457
- // Without a query only the visible page's details are fetched; with a query
458
- // all details are loaded so the filter can run before pagination
527
+ // Without a query only the visible page's records are read; with one every record has to be
528
+ // read, because the fields the filter matches on live on the record and nowhere else.
459
529
  if (!query) {
460
530
  list = list.slice(startPos, startPos + pageSize);
461
531
  }
@@ -464,65 +534,92 @@ module.exports = {
464
534
  return response;
465
535
  }
466
536
 
467
- let req = redis.multi();
537
+ let entries = [];
538
+ let reaped = 0;
539
+
540
+ // Read in batches, and keep only what the query matches. A search reads every token on the
541
+ // instance: as a single read that was one reply carrying every record, with all of them held
542
+ // decoded until the filter ran at the end. The search is still O(every token) - nothing
543
+ // indexes the fields it matches on - but what is in memory at once is now one batch plus the
544
+ // matches.
545
+ for (let pos = 0; pos < list.length; pos += TOKEN_BATCH_SIZE) {
546
+ let batch = list.slice(pos, pos + TOKEN_BATCH_SIZE);
547
+ let records = await redis.hmgetBuffer(`${REDIS_PREFIX}tokens`, batch);
548
+
549
+ for (let i = 0; i < batch.length; i++) {
550
+ let tokenHash = batch[i];
551
+ let encoded = records && records[i];
552
+ if (!encoded) {
553
+ continue;
554
+ }
555
+
556
+ try {
557
+ let tokenData = msgpack.decode(encoded);
468
558
 
469
- for (let tokenHash of list) {
470
- req = req.hgetBuffer(`${REDIS_PREFIX}tokens`, tokenHash);
471
- req = req.hgetBuffer(`${REDIS_PREFIX}tokens:access`, tokenHash);
472
- }
473
-
474
- let detailList = await req.exec();
475
-
476
- let lastEntry = false;
477
- for (let i = 0; i < detailList.length; i++) {
478
- let entry = detailList[i];
479
- // Each token occupies two consecutive multi results (data + access info)
480
- let tokenHash = list[Math.floor(i / 2)];
481
- if (i % 2 === 0) {
482
- lastEntry = false;
483
- if (entry[1]) {
484
- try {
485
- let tokenData = msgpack.decode(entry[1]);
486
-
487
- // An expired token cannot authenticate, so listing it is noise. This
488
- // is also where a minted-but-never-used token finally gets collected.
489
- if (tokenData.expires && Date.now() >= tokenData.expires) {
490
- reapExpiredToken(tokenHash, tokenData.account);
491
- response.total = Math.max(0, response.total - 1);
492
- continue;
493
- }
494
-
495
- tokenData.created = new Date(tokenData.created);
496
- if (tokenData.expires) {
497
- tokenData.expires = new Date(tokenData.expires);
498
- }
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);
504
- response.tokens.push(lastEntry);
505
- } catch (err) {
506
- logger.error({ msg: 'Failed to process token data', hash: tokenHash, err });
559
+ // An expired token cannot authenticate, so listing it is noise. This
560
+ // is also where a minted-but-never-used token finally gets collected.
561
+ if (tokenData.expires && Date.now() >= tokenData.expires) {
562
+ reapExpiredToken(tokenHash, tokenData.account);
563
+ reaped++;
564
+ continue;
507
565
  }
566
+
567
+ tokenData.created = new Date(tokenData.created);
568
+ if (tokenData.expires) {
569
+ tokenData.expires = new Date(tokenData.expires);
570
+ }
571
+
572
+ // `account` is absent on the record for an unbound token, so it is filled in
573
+ // explicitly: a listing that mixes bound and unbound tokens should report one
574
+ // shape, not two, and `null` is the answer to "which account" for a token
575
+ // that is not bound to one.
576
+ let entry = Object.assign({ id: tokenHash, account: null }, tokenData);
577
+
578
+ if (query && !matchesListQuery(entry, LIST_QUERY_FIELDS, query)) {
579
+ continue;
580
+ }
581
+
582
+ entries.push(entry);
583
+ } catch (err) {
584
+ logger.error({ msg: 'Failed to process token data', hash: tokenHash, err });
508
585
  }
509
- } else if (lastEntry && entry[1]) {
510
- lastEntry.access = decodeAccessData(entry[1], tokenHash);
511
586
  }
512
587
  }
513
588
 
514
589
  if (query) {
515
- let paged = filterListPage(response.tokens, ['id', 'description', 'account'], query, startPos, pageSize);
516
- response.tokens = paged.entries;
517
- response.total = paged.total;
590
+ // The matches are what the caller is paging through, so they are what `total` counts -
591
+ // the same answer filterListPage() gave when it did the filtering here.
592
+ response.total = entries.length;
593
+ entries = entries.slice(startPos, startPos + pageSize);
594
+ } else {
595
+ response.total = Math.max(0, response.total - reaped);
596
+ }
597
+
598
+ // Last-use records for the returned page only. They live in a second hash and nothing
599
+ // filters, sorts or counts on them, so reading one alongside every record above spent a
600
+ // command per token on data that at most one page of tokens would ever show.
601
+ if (entries.length) {
602
+ let accessRecords = await redis.hmgetBuffer(
603
+ `${REDIS_PREFIX}tokens:access`,
604
+ entries.map(entry => entry.id)
605
+ );
606
+
607
+ for (let i = 0; i < entries.length; i++) {
608
+ let encoded = accessRecords && accessRecords[i];
609
+ if (encoded) {
610
+ entries[i].access = decodeAccessData(encoded, entries[i].id);
611
+ }
612
+ }
518
613
  }
519
614
 
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.
615
+ response.tokens = entries;
616
+
617
+ // Derived last, from whichever total the branches above settled on. A count taken before the
618
+ // loop describes a listing that no longer exists, because the loop reaps expired tokens as
619
+ // it goes - three tokens with the first expired reported `{total: 2, pages: 3}`. Only the
620
+ // records actually read are inspected, so an expired token beyond this call's reach is still
621
+ // counted until a later call gets to it; what this guarantees is that `pages` and `total` in
622
+ // one response are two views of one number.
526
623
  response.pages = Math.ceil(response.total / pageSize);
527
624
 
528
625
  return response;
@@ -42,9 +42,9 @@ const {
42
42
  ACCOUNT_DISPLAY_STATES,
43
43
  signedFormBlobFields: signedBlobFields
44
44
  } = require('../schemas');
45
- const { formatAccountData, cachedTemplates, identityErrorView, ACCOUNT_STATE_DISPLAY } = require('./route-helpers');
45
+ const { formatAccountData, cachedTemplates, identityErrorView, ACCOUNT_STATE_DISPLAY, adminUrl } = require('./route-helpers');
46
46
  const { webhooks: Webhooks } = require('../webhooks');
47
- const { describeEffectiveRouting } = require('../webhook-routing');
47
+ const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
48
48
  const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
49
49
 
50
50
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS } = consts;
@@ -1368,6 +1368,11 @@ function init(args) {
1368
1368
  Webhooks.list(0, 1000)
1369
1369
  ]);
1370
1370
 
1371
+ // The listing carries route metadata only, but the worker's delivery gate also
1372
+ // requires a filter script, so the card needs the filter-presence markers for the
1373
+ // routes it is about to present as delivering
1374
+ const routeFilterInfo = await Webhooks.getFilterInfo(webhookRoutesList.webhooks.filter(isDeliverableRoute).map(route => route.id));
1375
+
1371
1376
  const webhookRouting = describeEffectiveRouting({
1372
1377
  webhooksEnabled: webhookSettings.webhooksEnabled,
1373
1378
  globalWebhooks: webhookSettings.webhooks,
@@ -1376,7 +1381,9 @@ function init(args) {
1376
1381
  inboxNewOnly: webhookSettings.inboxNewOnly,
1377
1382
  globalCustomHeaders: webhookSettings.webhooksCustomHeaders,
1378
1383
  accountCustomHeaders: accountData.webhooksCustomHeaders,
1379
- routes: webhookRoutesList.webhooks
1384
+ // Non-deliverable routes were not probed; their hasFilter stays undefined, which
1385
+ // describeEffectiveRouting() reads as "unknown" (and filters them out anyway)
1386
+ routes: webhookRoutesList.webhooks.map(route => Object.assign({}, route, { hasFilter: routeFilterInfo.get(route.id) }))
1380
1387
  });
1381
1388
 
1382
1389
  return h.view(
@@ -1478,7 +1485,7 @@ function init(args) {
1478
1485
  } catch (err) {
1479
1486
  await request.flash({ type: 'danger', message: `Couldn't delete account. Try again.` });
1480
1487
  request.logger.error({ msg: 'Failed to delete the account', err, account: request.params.account, remoteAddress: request.app.ip });
1481
- return h.redirect(`/admin/accounts/${request.params.account}`);
1488
+ return h.redirect(adminUrl`/admin/accounts/${request.params.account}`);
1482
1489
  }
1483
1490
  },
1484
1491
  options: {
@@ -1724,7 +1731,7 @@ function init(args) {
1724
1731
  const canReadMail = (accountData.imap || accountData.oauth2) && !(accountData.imap && accountData.imap.disabled) && !DISABLE_MESSAGE_BROWSER;
1725
1732
  if (!canReadMail) {
1726
1733
  await request.flash({ type: 'danger', message: `Mail access is disabled for this account` });
1727
- return h.redirect(`/admin/accounts/${request.params.account}`);
1734
+ return h.redirect(adminUrl`/admin/accounts/${request.params.account}`);
1728
1735
  }
1729
1736
 
1730
1737
  return h.view(
@@ -1955,7 +1962,7 @@ function init(args) {
1955
1962
 
1956
1963
  await accountObject.update(updates);
1957
1964
 
1958
- return h.redirect(`/admin/accounts/${request.params.account}`);
1965
+ return h.redirect(adminUrl`/admin/accounts/${request.params.account}`);
1959
1966
  } catch (err) {
1960
1967
  await request.flash({ type: 'danger', message: `Couldn't save account settings. Try again.` });
1961
1968
  request.logger.error({ msg: 'Failed to update account settings', err, account: request.params.account });