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.
- package/.ncurc.js +23 -13
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +68 -0
- package/config/e2e.toml +2 -1
- package/config/test.toml +2 -1
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +112 -36
- package/lib/api-reference/format.js +91 -4
- package/lib/api-reference/model.js +144 -19
- package/lib/api-reference/schema-tree.js +282 -28
- package/lib/api-routes/account-routes.js +80 -34
- package/lib/api-routes/blocklist-routes.js +21 -47
- package/lib/api-routes/chat-routes.js +10 -12
- package/lib/api-routes/delivery-test-routes.js +6 -26
- package/lib/api-routes/export-routes.js +2 -0
- package/lib/api-routes/gateway-routes.js +52 -11
- package/lib/api-routes/license-routes.js +2 -0
- package/lib/api-routes/mailbox-routes.js +29 -26
- package/lib/api-routes/message-routes.js +27 -21
- package/lib/api-routes/oauth2-app-routes.js +11 -29
- package/lib/api-routes/operation-impact.js +80 -0
- package/lib/api-routes/outbox-routes.js +15 -5
- package/lib/api-routes/permission-map.js +401 -0
- package/lib/api-routes/route-helpers.js +294 -9
- package/lib/api-routes/route-metadata.js +28 -0
- package/lib/api-routes/settings-routes.js +66 -38
- package/lib/api-routes/stats-routes.js +2 -2
- package/lib/api-routes/submit-routes.js +53 -31
- package/lib/api-routes/template-routes.js +3 -0
- package/lib/api-routes/token-routes.js +526 -72
- package/lib/api-routes/webhook-route-routes.js +14 -4
- package/lib/arf-detect.js +17 -4
- package/lib/auth-token.js +80 -8
- package/lib/bounce-detect.js +28 -17
- package/lib/consts.js +16 -0
- package/lib/db.js +26 -2
- package/lib/delivery-error.js +30 -1
- package/lib/email-client/base-client.js +27 -41
- package/lib/email-client/gmail-client.js +23 -17
- package/lib/email-client/imap/mailbox.js +58 -59
- package/lib/email-client/imap/subconnection.js +10 -7
- package/lib/email-client/imap/sync-operations.js +46 -46
- package/lib/email-client/imap-client.js +85 -28
- package/lib/email-client/message-builder.js +3 -3
- package/lib/email-client/notification-handler.js +1 -1
- package/lib/email-client/outlook/graph-api.js +10 -4
- package/lib/email-client/outlook-client.js +56 -64
- package/lib/email-client/smtp-pool-manager.js +1 -1
- package/lib/enum-descriptions.js +92 -2
- package/lib/export.js +1 -1
- package/lib/field-usage.js +133 -0
- package/lib/gateway.js +1 -1
- package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
- package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
- package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
- package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
- package/lib/imapproxy/imap-core/lib/imap-connection.js +15 -5
- package/lib/imapproxy/imap-server.js +27 -7
- package/lib/license-beacon.js +4 -9
- package/lib/lists.js +49 -1
- package/lib/llm-pre-process.js +5 -5
- package/lib/logger.js +5 -1
- package/lib/lua/h-set-new-mark.lua +36 -0
- package/lib/message-port-stream.js +84 -1
- package/lib/metrics-collector.js +2 -2
- package/lib/oauth/gmail.js +9 -12
- package/lib/oauth/mail-ru.js +5 -7
- package/lib/oauth/outlook.js +9 -9
- package/lib/oauth/pubsub/google.js +25 -10
- package/lib/oauth/scope-checker.js +1 -1
- package/lib/oauth2-apps.js +290 -292
- package/lib/openapi/build-document.js +20 -8
- package/lib/openapi/joi-schema.js +20 -0
- package/lib/outbox.js +85 -17
- package/lib/pre-process.js +8 -8
- package/lib/queue-stats.js +49 -0
- package/lib/read-env-value.js +1 -1
- package/lib/reconnection-manager.js +2 -2
- package/lib/rewrite-text-nodes.js +4 -3
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +218 -162
- package/lib/settings.js +98 -5
- package/lib/sub-script.js +2 -1
- package/lib/swagger-options.js +2 -1
- package/lib/templates.js +4 -4
- package/lib/threads.js +2 -2
- package/lib/token-audit-log.js +231 -0
- package/lib/token-permission-view.js +219 -0
- package/lib/token-permissions.js +172 -0
- package/lib/tokens.js +247 -66
- package/lib/tools.js +142 -37
- package/lib/ui-routes/account-routes.js +42 -15
- package/lib/ui-routes/admin-config-routes.js +18 -10
- package/lib/ui-routes/admin-entities-routes.js +117 -38
- package/lib/ui-routes/auth-routes.js +30 -24
- package/lib/ui-routes/export-routes.js +10 -4
- package/lib/ui-routes/oauth-config-routes.js +12 -12
- package/lib/ui-routes/reference-routes.js +3 -3
- package/lib/ui-routes/route-helpers.js +78 -2
- package/lib/ui-routes/settings-page.js +1 -1
- package/lib/ui-routes/smtp-test-routes.js +1 -1
- package/lib/ui-routes/suppression-list-routes.js +299 -0
- package/lib/ui-routes/unsubscribe-routes.js +19 -29
- package/lib/utils/decode-headers.js +42 -0
- package/lib/utils/header-map.js +48 -0
- package/lib/utils/network.js +2 -2
- package/lib/utils/unsafe-key.js +59 -0
- package/lib/web-safe-html.js +1 -1
- package/lib/webhook-routing.js +84 -0
- package/lib/webhooks.js +48 -14
- package/package.json +11 -10
- package/sbom.json +1 -1
- package/server.js +116 -55
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +136 -9
- package/static/js/reference.js +456 -10
- package/static/js/ui.js +43 -0
- package/static/licenses.html +51 -41
- package/translations/messages.pot +59 -59
- package/views/accounts/account.hbs +75 -13
- package/views/accounts/browse.hbs +19 -36
- package/views/accounts/edit.hbs +2 -2
- package/views/config/logging.hbs +6 -0
- package/views/config/oauth/app.hbs +0 -2
- package/views/config/security.hbs +13 -0
- package/views/gateways/edit.hbs +1 -1
- package/views/gateways/gateway.hbs +2 -2
- package/views/gateways/index.hbs +7 -7
- package/views/partials/accounts_table.hbs +7 -7
- package/views/partials/oauth_form.hbs +0 -15
- package/views/partials/reference/disclosure.hbs +8 -2
- package/views/partials/reference/operation.hbs +47 -13
- package/views/partials/reference/params.hbs +17 -1
- package/views/partials/reference/schema-node.hbs +110 -52
- package/views/partials/reference/schema-tools.hbs +25 -0
- package/views/partials/reference/try-it.hbs +84 -11
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/checkbox.hbs +2 -2
- package/views/partials/ui/tabs.hbs +7 -1
- package/views/reference/token.hbs +4 -0
- package/views/suppression-lists/index.hbs +85 -0
- package/views/suppression-lists/list.hbs +87 -0
- package/views/templates/index.hbs +10 -4
- package/views/templates/template.hbs +1 -1
- package/views/tokens/index.hbs +53 -6
- package/views/tokens/new.hbs +334 -5
- package/workers/api.js +185 -102
- package/workers/documents.js +46 -26
- package/workers/export.js +20 -8
- package/workers/imap-proxy.js +2 -2
- package/workers/imap.js +77 -78
- package/workers/smtp.js +13 -7
- package/workers/submit.js +40 -30
- package/workers/webhooks.js +80 -26
- package/lib/feature-flags.js +0 -48
package/lib/tokens.js
CHANGED
|
@@ -5,10 +5,34 @@ 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,
|
|
8
|
+
const { constantTimeEqual, matchesListQuery } = require('./tools');
|
|
9
|
+
const { extractMultiError } = require('./redis-operations');
|
|
10
|
+
const tokenAuditLog = require('./token-audit-log');
|
|
9
11
|
|
|
10
12
|
const SESS_PREFIX = 'sess_';
|
|
11
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
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The id a token is listed and stored under: the SHA-256 of its raw bytes.
|
|
24
|
+
*
|
|
25
|
+
* Derivable from the token value, which is why provision() does not have to return it - but only if
|
|
26
|
+
* you know the hex string is decoded to bytes before hashing rather than hashed as text. Exported so
|
|
27
|
+
* callers get that right by construction instead of reimplementing it.
|
|
28
|
+
*
|
|
29
|
+
* @param {String} token - the 64-char hex token value
|
|
30
|
+
* @returns {String} SHA-256 hex id
|
|
31
|
+
*/
|
|
32
|
+
function tokenId(token) {
|
|
33
|
+
return crypto.createHash('sha256').update(Buffer.from(token, 'hex')).digest('hex');
|
|
34
|
+
}
|
|
35
|
+
|
|
12
36
|
// Best-effort removal of an expired token record. Fired from both of the places that can
|
|
13
37
|
// notice the expiry - get(), when someone presents the token, and list(), when someone views
|
|
14
38
|
// the token list. Both are needed: a token that is minted and then never used is never
|
|
@@ -27,7 +51,30 @@ function reapExpiredToken(hashedToken, account) {
|
|
|
27
51
|
.catch(err => logger.error({ msg: 'Failed to clean up an expired access token', hash: hashedToken, err }));
|
|
28
52
|
}
|
|
29
53
|
|
|
54
|
+
// Reads one `{prefix}tokens:access` value into the shape both readers publish. Shared because the
|
|
55
|
+
// listing and the single-token getter feed the same joi schema and had already drifted: the listing
|
|
56
|
+
// assigned the decoded object as-is, so a token that had never authenticated came back as `{time:
|
|
57
|
+
// null}` with no `ip` key at all, and the admin view carries a `|| {}` guard for the case where the
|
|
58
|
+
// field is missing entirely. One shape means the getter's promise to match the listing is true.
|
|
59
|
+
function decodeAccessData(encoded, hashedToken) {
|
|
60
|
+
let accessData = {};
|
|
61
|
+
|
|
62
|
+
if (encoded) {
|
|
63
|
+
try {
|
|
64
|
+
accessData = msgpack.decode(encoded);
|
|
65
|
+
} catch (err) {
|
|
66
|
+
// An unreadable last-use entry must not fail the read of the token it belongs to
|
|
67
|
+
logger.error({ msg: 'Failed to process token access data', hash: hashedToken, err });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return { time: accessData.time ? new Date(accessData.time) : null, ip: accessData.ip || null };
|
|
72
|
+
}
|
|
73
|
+
|
|
30
74
|
module.exports = {
|
|
75
|
+
tokenId,
|
|
76
|
+
TOKEN_BATCH_SIZE,
|
|
77
|
+
|
|
31
78
|
async getSessionToken(sessionId, account, ttl) {
|
|
32
79
|
const token = crypto.randomBytes(32);
|
|
33
80
|
const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
|
|
@@ -107,7 +154,7 @@ module.exports = {
|
|
|
107
154
|
* password is a supported configuration), and the CLI needs shell access anyway.
|
|
108
155
|
*
|
|
109
156
|
* Both HTTP callers gate themselves: POST /admin/tokens/new unconditionally, since
|
|
110
|
-
* `server.auth.default('session')` leaves it open while authData is unset; POST /v1/
|
|
157
|
+
* `server.auth.default('session')` leaves it open while authData is unset; POST /v1/tokens only
|
|
111
158
|
* for the `preauth` caller that the `disableTokens` setting lets through without a credential.
|
|
112
159
|
*
|
|
113
160
|
* @param {Object} opts - Token options. May originate from a request payload.
|
|
@@ -115,7 +162,7 @@ module.exports = {
|
|
|
115
162
|
*/
|
|
116
163
|
async provision(opts) {
|
|
117
164
|
opts = opts || {};
|
|
118
|
-
const { account, restrictions, ip, remoteAddress, description, metadata, scopes, nolog, expires } = opts;
|
|
165
|
+
const { account, restrictions, permissions, ip, remoteAddress, description, metadata, scopes, nolog, expires } = opts;
|
|
119
166
|
|
|
120
167
|
const token = crypto.randomBytes(32);
|
|
121
168
|
const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
|
|
@@ -166,6 +213,13 @@ module.exports = {
|
|
|
166
213
|
tokenData.restrictions = restrictions;
|
|
167
214
|
}
|
|
168
215
|
|
|
216
|
+
// Narrowing below the scope. Absent means "not narrowed", which is every token issued
|
|
217
|
+
// before this existed, so the field is only written when it was asked for - see the absent
|
|
218
|
+
// vs empty vs malformed distinction in lib/token-permissions.js.
|
|
219
|
+
if (permissions) {
|
|
220
|
+
tokenData.permissions = permissions;
|
|
221
|
+
}
|
|
222
|
+
|
|
169
223
|
if (metadata) {
|
|
170
224
|
tokenData.metadata = metadata;
|
|
171
225
|
}
|
|
@@ -184,10 +238,9 @@ module.exports = {
|
|
|
184
238
|
|
|
185
239
|
let res = await req.exec();
|
|
186
240
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
}
|
|
241
|
+
let err = extractMultiError(res);
|
|
242
|
+
if (err) {
|
|
243
|
+
throw err;
|
|
191
244
|
}
|
|
192
245
|
|
|
193
246
|
if (!nolog) {
|
|
@@ -206,7 +259,7 @@ module.exports = {
|
|
|
206
259
|
throw err;
|
|
207
260
|
}
|
|
208
261
|
|
|
209
|
-
const hashedToken = hashed ? token :
|
|
262
|
+
const hashedToken = hashed ? token : tokenId(token);
|
|
210
263
|
|
|
211
264
|
let tokenDataEncoded = await redis.hgetBuffer(`${REDIS_PREFIX}tokens`, hashedToken);
|
|
212
265
|
if (!tokenDataEncoded) {
|
|
@@ -242,6 +295,20 @@ module.exports = {
|
|
|
242
295
|
return Object.assign({ id: hashedToken }, tokenData);
|
|
243
296
|
},
|
|
244
297
|
|
|
298
|
+
/**
|
|
299
|
+
* Last-use record for a token, in the shape the listings report it.
|
|
300
|
+
*
|
|
301
|
+
* Kept apart from get(), which every authenticated request runs: the last-use record lives in a
|
|
302
|
+
* second hash and nothing on the auth path reads it, so folding it in would put an extra Redis
|
|
303
|
+
* round trip on every API call to serve one page.
|
|
304
|
+
*
|
|
305
|
+
* @param {String} tokenId - SHA-256 hash of the token, the id the listings report
|
|
306
|
+
* @returns {Promise<{time: (Date|null), ip: (String|null)}>}
|
|
307
|
+
*/
|
|
308
|
+
async getAccess(tokenId) {
|
|
309
|
+
return decodeAccessData(await redis.hgetBuffer(`${REDIS_PREFIX}tokens:access`, tokenId), tokenId);
|
|
310
|
+
},
|
|
311
|
+
|
|
245
312
|
async delete(token, opts) {
|
|
246
313
|
if (!/^[0-9a-f]{64}$/i.test(token)) {
|
|
247
314
|
let err = new Error('Invalid token format');
|
|
@@ -264,7 +331,14 @@ module.exports = {
|
|
|
264
331
|
}
|
|
265
332
|
}
|
|
266
333
|
|
|
267
|
-
|
|
334
|
+
// The audit log goes with the token. It describes a credential that no longer exists, so
|
|
335
|
+
// keeping it would outlive the thing it is a record of - and the key is named after the
|
|
336
|
+
// token id, so nothing would ever collect it.
|
|
337
|
+
let req = redis
|
|
338
|
+
.multi()
|
|
339
|
+
.hdel(`${REDIS_PREFIX}tokens`, tokenData.id)
|
|
340
|
+
.hdel(`${REDIS_PREFIX}tokens:access`, tokenData.id)
|
|
341
|
+
.del(tokenAuditLog.logKey(tokenData.id));
|
|
268
342
|
if (tokenData.account) {
|
|
269
343
|
req = req.srem(`${REDIS_PREFIX}iat:${tokenData.account}`, tokenData.id);
|
|
270
344
|
} else {
|
|
@@ -274,10 +348,9 @@ module.exports = {
|
|
|
274
348
|
|
|
275
349
|
let res = await req.exec();
|
|
276
350
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
}
|
|
351
|
+
let err = extractMultiError(res);
|
|
352
|
+
if (err) {
|
|
353
|
+
throw err;
|
|
281
354
|
}
|
|
282
355
|
|
|
283
356
|
logger.info(Object.assign({}, tokenData, { msg: 'Deleted an access token', remoteAddress: opts.remoteAddress }));
|
|
@@ -285,6 +358,60 @@ module.exports = {
|
|
|
285
358
|
return true;
|
|
286
359
|
},
|
|
287
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
|
+
|
|
288
415
|
async getRawData(token) {
|
|
289
416
|
if (!/^[0-9a-f]{64}$/i.test(token)) {
|
|
290
417
|
let err = new Error('Invalid token format');
|
|
@@ -343,29 +470,51 @@ module.exports = {
|
|
|
343
470
|
|
|
344
471
|
let res = await req.exec();
|
|
345
472
|
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
}
|
|
473
|
+
let err = extractMultiError(res);
|
|
474
|
+
if (err) {
|
|
475
|
+
throw err;
|
|
350
476
|
}
|
|
351
477
|
|
|
352
478
|
return tokenData;
|
|
353
479
|
},
|
|
354
480
|
|
|
355
|
-
|
|
481
|
+
/**
|
|
482
|
+
* Lists tokens.
|
|
483
|
+
*
|
|
484
|
+
* @param {String} [account] - list tokens bound to this account
|
|
485
|
+
* @param {Number} [page] - zero-based page
|
|
486
|
+
* @param {Number} [pageSize] - entries per page
|
|
487
|
+
* @param {String} [query] - filter on id, description or account
|
|
488
|
+
* @param {Object} [opts]
|
|
489
|
+
* @param {Boolean} [opts.all] - every token on the instance, bound or not. Reads the token hash
|
|
490
|
+
* directly rather than walking one index per account: the account is stored on each record, so
|
|
491
|
+
* the union is already there, and enumerating accounts would be a round trip each.
|
|
492
|
+
*/
|
|
493
|
+
async list(account, page, pageSize, query, opts) {
|
|
356
494
|
page = Math.max(Number(page) || 0, 0);
|
|
357
495
|
pageSize = Math.max(Number(pageSize) || 20, 1);
|
|
358
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
|
+
|
|
359
503
|
let startPos = page * pageSize;
|
|
360
504
|
|
|
361
505
|
let list;
|
|
362
|
-
if (
|
|
506
|
+
if (opts && opts.all) {
|
|
507
|
+
list = await redis.hkeys(`${REDIS_PREFIX}tokens`);
|
|
508
|
+
} else if (account) {
|
|
363
509
|
list = await redis.smembers(`${REDIS_PREFIX}iat:${account}`);
|
|
364
510
|
} else {
|
|
365
511
|
list = await redis.smembers(`${REDIS_PREFIX}iat`);
|
|
366
512
|
}
|
|
367
513
|
|
|
368
|
-
|
|
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));
|
|
369
518
|
|
|
370
519
|
let response = {
|
|
371
520
|
account: account || null,
|
|
@@ -375,8 +524,8 @@ module.exports = {
|
|
|
375
524
|
tokens: []
|
|
376
525
|
};
|
|
377
526
|
|
|
378
|
-
// Without a query only the visible page's
|
|
379
|
-
//
|
|
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.
|
|
380
529
|
if (!query) {
|
|
381
530
|
list = list.slice(startPos, startPos + pageSize);
|
|
382
531
|
}
|
|
@@ -385,49 +534,52 @@ module.exports = {
|
|
|
385
534
|
return response;
|
|
386
535
|
}
|
|
387
536
|
|
|
388
|
-
let
|
|
537
|
+
let entries = [];
|
|
538
|
+
let reaped = 0;
|
|
389
539
|
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
let
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
let
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
if (entry[1]) {
|
|
405
|
-
try {
|
|
406
|
-
let tokenData = msgpack.decode(entry[1]);
|
|
407
|
-
|
|
408
|
-
// An expired token cannot authenticate, so listing it is noise. This
|
|
409
|
-
// is also where a minted-but-never-used token finally gets collected.
|
|
410
|
-
if (tokenData.expires && Date.now() >= tokenData.expires) {
|
|
411
|
-
reapExpiredToken(tokenHash, tokenData.account);
|
|
412
|
-
response.total = Math.max(0, response.total - 1);
|
|
413
|
-
continue;
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
tokenData.created = new Date(tokenData.created);
|
|
417
|
-
if (tokenData.expires) {
|
|
418
|
-
tokenData.expires = new Date(tokenData.expires);
|
|
419
|
-
}
|
|
420
|
-
lastEntry = Object.assign({ id: tokenHash }, tokenData);
|
|
421
|
-
response.tokens.push(lastEntry);
|
|
422
|
-
} catch (err) {
|
|
423
|
-
logger.error({ msg: 'Failed to process token data', hash: tokenHash, err });
|
|
424
|
-
}
|
|
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;
|
|
425
554
|
}
|
|
426
|
-
|
|
555
|
+
|
|
427
556
|
try {
|
|
428
|
-
let
|
|
429
|
-
|
|
430
|
-
|
|
557
|
+
let tokenData = msgpack.decode(encoded);
|
|
558
|
+
|
|
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;
|
|
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);
|
|
431
583
|
} catch (err) {
|
|
432
584
|
logger.error({ msg: 'Failed to process token data', hash: tokenHash, err });
|
|
433
585
|
}
|
|
@@ -435,12 +587,41 @@ module.exports = {
|
|
|
435
587
|
}
|
|
436
588
|
|
|
437
589
|
if (query) {
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
response.total =
|
|
441
|
-
|
|
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
|
+
}
|
|
442
613
|
}
|
|
443
614
|
|
|
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.
|
|
623
|
+
response.pages = Math.ceil(response.total / pageSize);
|
|
624
|
+
|
|
444
625
|
return response;
|
|
445
626
|
}
|
|
446
627
|
};
|