emailengine-app 2.79.0 → 2.79.2
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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +79 -0
- package/bin/emailengine.js +8 -1
- package/config/default.toml +6 -0
- package/data/google-crawlers.json +1 -1
- package/lib/account.js +137 -19
- package/lib/api-routes/account-routes.js +13 -1
- package/lib/api-routes/index.js +12 -0
- package/lib/api-routes/mailbox-routes.js +6 -0
- package/lib/api-routes/mcp-oauth-routes.js +259 -0
- package/lib/api-routes/mcp-routes.js +172 -0
- package/lib/api-routes/message-routes.js +125 -4
- package/lib/api-routes/outbox-routes.js +7 -0
- package/lib/api-routes/permission-map.js +101 -1
- package/lib/api-routes/route-helpers.js +87 -4
- package/lib/api-routes/route-metadata.js +24 -4
- package/lib/api-routes/settings-routes.js +37 -14
- package/lib/api-routes/submit-routes.js +41 -0
- package/lib/api-routes/template-routes.js +7 -0
- package/lib/api-routes/token-routes.js +292 -122
- package/lib/arf-detect.js +17 -4
- package/lib/bounce-detect.js +28 -17
- package/lib/consts.js +36 -1
- package/lib/db.js +6 -0
- package/lib/email-client/base-client.js +102 -117
- package/lib/email-client/gmail-client.js +91 -29
- package/lib/email-client/imap/mailbox.js +175 -101
- package/lib/email-client/imap-client.js +49 -2
- package/lib/email-client/outlook-client.js +20 -24
- package/lib/enum-descriptions.js +2 -1
- package/lib/field-usage.js +17 -1
- package/lib/lua/h-set-new-mark.lua +36 -0
- package/lib/lua/s-list-accounts.lua +5 -2
- package/lib/mcp/index.js +29 -0
- package/lib/mcp/inject.js +70 -0
- package/lib/mcp/json-schema.js +120 -0
- package/lib/mcp/listen.js +171 -0
- package/lib/mcp/oauth.js +324 -0
- package/lib/mcp/protocol.js +489 -0
- package/lib/mcp/resources.js +139 -0
- package/lib/mcp/tools.js +655 -0
- package/lib/message-port-stream.js +84 -1
- package/lib/oauth2-apps.js +84 -15
- package/lib/openapi/build-document.js +5 -1
- package/lib/openapi/index.js +3 -1
- package/lib/response-stream.js +52 -21
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +26 -5
- package/lib/settings.js +23 -9
- package/lib/token-audit-log.js +32 -9
- package/lib/token-permission-view.js +104 -8
- package/lib/tokens.js +194 -68
- package/lib/tools.js +96 -0
- package/lib/ui-routes/account-routes.js +55 -6
- package/lib/ui-routes/admin-config-routes.js +114 -1
- package/lib/ui-routes/admin-entities-routes.js +103 -19
- package/lib/ui-routes/auth-routes.js +13 -0
- package/lib/ui-routes/mcp-consent-routes.js +330 -0
- package/lib/ui-routes/oauth-config-routes.js +7 -7
- package/lib/ui-routes/route-helpers.js +143 -1
- package/lib/ui-routes/suppression-list-routes.js +14 -9
- package/lib/utils/decode-headers.js +42 -0
- package/lib/utils/header-map.js +48 -0
- package/lib/utils/network.js +9 -1
- package/lib/utils/unsafe-key.js +59 -0
- package/lib/web-safe-html.js +61 -0
- package/lib/webhook-routing.js +6 -2
- package/lib/webhooks.js +31 -8
- package/package.json +9 -8
- package/sbom.json +1 -1
- package/scripts/README.md +25 -0
- package/scripts/build-icon.js +77 -0
- package/server.js +39 -17
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +98 -0
- package/static/emailengine.ico +0 -0
- package/static/js/ui.js +465 -1
- package/static/licenses.html +42 -22
- package/translations/messages.pot +57 -57
- package/views/accounts/account.hbs +8 -8
- package/views/accounts/browse.hbs +1 -1
- package/views/accounts/edit.hbs +2 -2
- package/views/config/mcp.hbs +361 -0
- package/views/config/oauth/index.hbs +7 -0
- package/views/gateways/edit.hbs +1 -1
- package/views/gateways/gateway.hbs +2 -2
- package/views/gateways/index.hbs +7 -7
- package/views/layout/prompt.hbs +62 -0
- package/views/mcp/authorize.hbs +136 -0
- package/views/partials/accounts_table.hbs +7 -7
- package/views/partials/head_assets.hbs +3 -3
- package/views/partials/mcp_access_levels.hbs +13 -0
- package/views/partials/mcp_account_limit.hbs +14 -0
- package/views/partials/mcp_tool_count.hbs +19 -0
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/account-picker.hbs +59 -0
- package/views/partials/ui/code-block.hbs +26 -0
- package/views/partials/ui/menu-item.hbs +5 -0
- package/views/partials/ui/radio.hbs +41 -0
- package/views/partials/ui/tab.hbs +15 -10
- package/views/partials/ui/tabs.hbs +8 -5
- package/views/suppression-lists/list.hbs +1 -1
- package/views/templates/index.hbs +2 -2
- package/views/templates/template.hbs +5 -4
- package/views/tokens/index.hbs +30 -4
- package/views/tokens/new.hbs +517 -239
- package/winconf.js +148 -48
- package/workers/api.js +239 -95
- package/workers/imap.js +65 -72
- package/workers/webhooks.js +21 -1
package/lib/token-audit-log.js
CHANGED
|
@@ -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
|
|
32
|
-
//
|
|
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.
|
|
40
|
-
//
|
|
41
|
-
|
|
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
|
-
|
|
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) ||
|
|
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 };
|
|
@@ -8,12 +8,13 @@
|
|
|
8
8
|
// label here would render as a blank checkbox, and one removed would leave a control that posts a
|
|
9
9
|
// value the API refuses.
|
|
10
10
|
|
|
11
|
-
const { ACTION, GROUP, GRANTABLE_GROUPS, SURFACE_GRANTS } = require('./api-routes/permission-map');
|
|
11
|
+
const { ACTION, GROUP, GRANTABLE_GROUPS, SURFACE_GRANTS, PER_REQUEST_SURFACES } = require('./api-routes/permission-map');
|
|
12
12
|
const tokenPermissions = require('./token-permissions');
|
|
13
13
|
const { ENUM_DESCRIPTIONS } = require('./enum-descriptions');
|
|
14
14
|
|
|
15
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.
|
|
16
|
+
// has to read well - it is not the identifier. The same labels are also lowercased into running
|
|
17
|
+
// prose (see MCP_GRANT_WORDING below), so each one has to work as a sentence fragment too.
|
|
17
18
|
const ACTION_LABELS = {
|
|
18
19
|
[ACTION.READ]: 'Read',
|
|
19
20
|
[ACTION.WRITE]: 'Create and modify',
|
|
@@ -37,6 +38,15 @@ const GROUP_LABELS = {
|
|
|
37
38
|
[GROUP.LOGS]: 'Connection logs'
|
|
38
39
|
};
|
|
39
40
|
|
|
41
|
+
// The one spelling of the slug-to-label lookup. Object.hasOwn rather than a bare lookup: a slug
|
|
42
|
+
// of `constructor` would otherwise render an Object.prototype member.
|
|
43
|
+
const mapLabels = (values, labels) => values.map(value => (Object.hasOwn(labels, value) ? labels[value] : value));
|
|
44
|
+
|
|
45
|
+
// The same vocabulary as a sentence fragment: lowercased and joined as an English list, for
|
|
46
|
+
// prose like the consent screen's grant sentences ("read, create and modify, and send email").
|
|
47
|
+
const GRANT_LIST_FORMAT = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
|
|
48
|
+
const humanGrantList = (values, labels) => GRANT_LIST_FORMAT.format(mapLabels(values, labels).map(word => word.toLowerCase()));
|
|
49
|
+
|
|
40
50
|
// Clusters for the section list. Thirteen rows at identical weight is a scan rather than a choice,
|
|
41
51
|
// and the split is the one a reader already has: the mail itself, the things that act on it, and the
|
|
42
52
|
// things that only watch.
|
|
@@ -88,9 +98,80 @@ const PRESETS = [
|
|
|
88
98
|
const SURFACE_LABELS = {
|
|
89
99
|
smtp: 'send over SMTP',
|
|
90
100
|
'imap-proxy': 'connect through the IMAP proxy',
|
|
91
|
-
metrics: 'read the metrics endpoint'
|
|
101
|
+
metrics: 'read the metrics endpoint',
|
|
102
|
+
mcp: 'call MCP tools'
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// The narrowings behind the MCP access-level choice, offered identically by the OAuth consent
|
|
106
|
+
// page and the admin generator. Derived once at load from the same table the scope enforcement
|
|
107
|
+
// reads, nothing else. Lives here rather than on the pages that post it because this module owns
|
|
108
|
+
// how permission records are presented, and a second derivation had already drifted (all groups
|
|
109
|
+
// instead of the readable ones).
|
|
110
|
+
//
|
|
111
|
+
// Three levels, because that is where consent-screen comprehension and real agent shapes meet:
|
|
112
|
+
// read-only for browsing, "mail agent" for the triage-and-reply agent that must never reach the
|
|
113
|
+
// delete tool, and full for everything the surface exposes. Full is the absence of a permissions
|
|
114
|
+
// record - the mcp scope itself is the bound.
|
|
115
|
+
const MCP_READ_ONLY_PERMISSIONS = {
|
|
116
|
+
actions: [ACTION.READ],
|
|
117
|
+
groups: SURFACE_GRANTS.mcp.filter(grant => grant.action === ACTION.READ).map(grant => grant.group)
|
|
92
118
|
};
|
|
93
119
|
|
|
120
|
+
// The permission record's two axes are independent allowlists, so deriving both from a pair list
|
|
121
|
+
// widens it (read x submit, write x template, ...). Inert here: an mcp-scoped token is usable
|
|
122
|
+
// only through /mcp, where surfaceAdmits() re-checks every request against the exact grant pairs.
|
|
123
|
+
const mailAgentGrants = SURFACE_GRANTS.mcp.filter(grant => grant.action !== ACTION.DESTRUCTIVE);
|
|
124
|
+
const MCP_MAIL_AGENT_PERMISSIONS = {
|
|
125
|
+
actions: [...new Set(mailAgentGrants.map(grant => grant.action))],
|
|
126
|
+
groups: [...new Set(mailAgentGrants.map(grant => grant.group))]
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// What each posted access-level slug mints. The consent route validates against these keys, so a
|
|
130
|
+
// level added here is automatically accepted there - and the fail-safe direction is fixed by the
|
|
131
|
+
// route defaulting to 'read' when no level is posted at all.
|
|
132
|
+
const MCP_ACCESS_LEVELS = {
|
|
133
|
+
read: MCP_READ_ONLY_PERMISSIONS,
|
|
134
|
+
mail: MCP_MAIL_AGENT_PERMISSIONS,
|
|
135
|
+
full: null
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
// How the levels are offered on screen, in the order they are listed. The consent prompt and
|
|
139
|
+
// the admin generator render the same radio group from this table (the mcp_access_levels
|
|
140
|
+
// partial), because two hand-written fieldsets had already drifted on the read-only wording.
|
|
141
|
+
// A level added to MCP_ACCESS_LEVELS needs an entry here to be offered anywhere.
|
|
142
|
+
// What each level's grants mean in plain words, computed once at load and shown wherever a level
|
|
143
|
+
// is approved (today the OAuth consent prompt). Keyed off MCP_ACCESS_LEVELS itself so a level
|
|
144
|
+
// cannot exist without wording; the full level stores null - no permissions record, the mcp
|
|
145
|
+
// scope is the bound - so its wording derives from the surface grant table directly. The mail
|
|
146
|
+
// and full group lists currently come out identical (the destructive grants add no group of
|
|
147
|
+
// their own), but each level derives its own list on purpose - they diverge the moment a
|
|
148
|
+
// destructive-only group joins the surface.
|
|
149
|
+
const MCP_GRANT_WORDING = Object.fromEntries(
|
|
150
|
+
Object.entries(MCP_ACCESS_LEVELS).map(([level, permissions]) => {
|
|
151
|
+
const actions = permissions ? permissions.actions : [...new Set(SURFACE_GRANTS.mcp.map(grant => grant.action))];
|
|
152
|
+
const groups = permissions ? permissions.groups : [...new Set(SURFACE_GRANTS.mcp.map(grant => grant.group))];
|
|
153
|
+
return [level, { actions: humanGrantList(actions, ACTION_LABELS), groups: humanGrantList(groups, GROUP_LABELS) }];
|
|
154
|
+
})
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
const MCP_ACCESS_LEVEL_OPTIONS = [
|
|
158
|
+
{
|
|
159
|
+
value: 'read',
|
|
160
|
+
label: 'Read-only',
|
|
161
|
+
hint: 'Recommended. List, search and read mail - cannot send, delete or change anything.'
|
|
162
|
+
},
|
|
163
|
+
{
|
|
164
|
+
value: 'mail',
|
|
165
|
+
label: 'Mail agent',
|
|
166
|
+
hint: 'Read, organize, draft and send mail - everything except the delete tool.'
|
|
167
|
+
},
|
|
168
|
+
{
|
|
169
|
+
value: 'full',
|
|
170
|
+
label: 'Full access',
|
|
171
|
+
hint: 'Every MCP tool, including deleting messages.'
|
|
172
|
+
}
|
|
173
|
+
];
|
|
174
|
+
|
|
94
175
|
/**
|
|
95
176
|
* View model for the permission controls on the token form.
|
|
96
177
|
*
|
|
@@ -121,11 +202,18 @@ function formModel() {
|
|
|
121
202
|
// it rather than restated in the page script. A hand-copied mirror would let the form keep
|
|
122
203
|
// showing an old warning after the grant list changed, which is exactly the drift
|
|
123
204
|
// lib/auth-token.js exists to prevent.
|
|
205
|
+
//
|
|
206
|
+
// `mode` is the surface's quantifier (see PER_REQUEST_SURFACES): 'all' surfaces are checked
|
|
207
|
+
// once at login and need every listed grant, 'any' surfaces are checked per request and
|
|
208
|
+
// work as long as a single grant pair remains allowed - the page script warns accordingly,
|
|
209
|
+
// which is why the exact (action, group) pairs ride along in `grantList`.
|
|
124
210
|
permissionSurfaces: Object.entries(SURFACE_LABELS).map(([scope, label]) => ({
|
|
125
211
|
scope,
|
|
126
212
|
label,
|
|
213
|
+
mode: PER_REQUEST_SURFACES.has(scope) ? 'any' : 'all',
|
|
127
214
|
actionList: [...new Set(SURFACE_GRANTS[scope].map(grant => grant.action))].join(','),
|
|
128
|
-
groupList: [...new Set(SURFACE_GRANTS[scope].map(grant => grant.group))].join(',')
|
|
215
|
+
groupList: [...new Set(SURFACE_GRANTS[scope].map(grant => grant.group))].join(','),
|
|
216
|
+
grantList: SURFACE_GRANTS[scope].map(grant => `${grant.action}:${grant.group}`).join(',')
|
|
129
217
|
})),
|
|
130
218
|
|
|
131
219
|
// data-actions/data-groups are read by the preset buttons in views/tokens/new.hbs
|
|
@@ -196,9 +284,7 @@ function summarize(permissions) {
|
|
|
196
284
|
// An empty allowlist allows nothing, which is the opposite of the axis being absent
|
|
197
285
|
return 'none';
|
|
198
286
|
}
|
|
199
|
-
|
|
200
|
-
// `constructor` would otherwise render an Object.prototype member
|
|
201
|
-
return values.map(value => (Object.hasOwn(labels, value) ? labels[value] : value)).join(', ');
|
|
287
|
+
return mapLabels(values, labels).join(', ');
|
|
202
288
|
};
|
|
203
289
|
|
|
204
290
|
const actions = label(permissions.actions, ACTION_LABELS);
|
|
@@ -216,4 +302,14 @@ function summarize(permissions) {
|
|
|
216
302
|
};
|
|
217
303
|
}
|
|
218
304
|
|
|
219
|
-
module.exports = {
|
|
305
|
+
module.exports = {
|
|
306
|
+
formModel,
|
|
307
|
+
summarize,
|
|
308
|
+
ACTION_LABELS,
|
|
309
|
+
GROUP_LABELS,
|
|
310
|
+
MCP_READ_ONLY_PERMISSIONS,
|
|
311
|
+
MCP_MAIL_AGENT_PERMISSIONS,
|
|
312
|
+
MCP_ACCESS_LEVELS,
|
|
313
|
+
MCP_ACCESS_LEVEL_OPTIONS,
|
|
314
|
+
MCP_GRANT_WORDING
|
|
315
|
+
};
|
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,
|
|
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);
|
|
@@ -103,6 +113,14 @@ module.exports = {
|
|
|
103
113
|
return false;
|
|
104
114
|
}
|
|
105
115
|
|
|
116
|
+
// The HMAC key is the caller's session id, so a request with no `ee` cookie has nothing to
|
|
117
|
+
// check against. createHmac() throws on an undefined key, which surfaced as a 500 where the
|
|
118
|
+
// honest answer is "not authenticated" - a denial either way, but one that filled the error
|
|
119
|
+
// log and masked real signals.
|
|
120
|
+
if (!sessionId || typeof sessionId !== 'string') {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
|
|
106
124
|
// Now we know it's valid format, proceed with validation
|
|
107
125
|
const tokenBuffer = Buffer.from(hexPart, 'hex');
|
|
108
126
|
const hashedToken = crypto.createHash('sha256').update(tokenBuffer).digest('hex');
|
|
@@ -118,6 +136,13 @@ module.exports = {
|
|
|
118
136
|
throw errGet || errExpire;
|
|
119
137
|
}
|
|
120
138
|
|
|
139
|
+
// An expired or already-deleted token leaves no key, and GET answers null. Splitting that
|
|
140
|
+
// threw, which is the same 500-instead-of-401 shape as the missing session id above - and
|
|
141
|
+
// an expired session token is the ordinary case, not an exceptional one.
|
|
142
|
+
if (typeof storedSignatureValue !== 'string') {
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
|
|
121
146
|
const [storedSignature, storedAccount] = storedSignatureValue.split(':');
|
|
122
147
|
|
|
123
148
|
if (!storedSignature || !constantTimeEqual(storedSignature, expectedSignature)) {
|
|
@@ -228,10 +253,9 @@ module.exports = {
|
|
|
228
253
|
|
|
229
254
|
let res = await req.exec();
|
|
230
255
|
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
}
|
|
256
|
+
let err = extractMultiError(res);
|
|
257
|
+
if (err) {
|
|
258
|
+
throw err;
|
|
235
259
|
}
|
|
236
260
|
|
|
237
261
|
if (!nolog) {
|
|
@@ -339,10 +363,9 @@ module.exports = {
|
|
|
339
363
|
|
|
340
364
|
let res = await req.exec();
|
|
341
365
|
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
}
|
|
366
|
+
let err = extractMultiError(res);
|
|
367
|
+
if (err) {
|
|
368
|
+
throw err;
|
|
346
369
|
}
|
|
347
370
|
|
|
348
371
|
logger.info(Object.assign({}, tokenData, { msg: 'Deleted an access token', remoteAddress: opts.remoteAddress }));
|
|
@@ -350,6 +373,60 @@ module.exports = {
|
|
|
350
373
|
return true;
|
|
351
374
|
},
|
|
352
375
|
|
|
376
|
+
/**
|
|
377
|
+
* Removes every access token bound to an account.
|
|
378
|
+
*
|
|
379
|
+
* Called from Account.delete(). Deleting an account used to unlink only its token index, which
|
|
380
|
+
* left the token records themselves in the global hash - and a record there authenticates
|
|
381
|
+
* regardless of whether the account it names still exists, so the credentials of a deleted
|
|
382
|
+
* account kept working. Since an account ID can be registered again, they would even come back
|
|
383
|
+
* pointed at whoever took the name.
|
|
384
|
+
*
|
|
385
|
+
* Owns the index too, rather than leaving it to the caller: it is the only mapping from an
|
|
386
|
+
* account to its tokens, so it must outlive a failure here - otherwise the records it names are
|
|
387
|
+
* live with nothing left pointing at them.
|
|
388
|
+
*
|
|
389
|
+
* @param {String} account - account ID
|
|
390
|
+
* @returns {Promise<Number>} how many tokens the account index listed
|
|
391
|
+
*/
|
|
392
|
+
async deleteForAccount(account) {
|
|
393
|
+
let hashedTokens = await redis.smembers(`${REDIS_PREFIX}iat:${account}`);
|
|
394
|
+
if (!hashedTokens || !hashedTokens.length) {
|
|
395
|
+
return 0;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// The same three keys delete() removes for a single token, a batch of ids per command.
|
|
399
|
+
//
|
|
400
|
+
// UNLINK for the audit logs: each is a list of up to EENGINE_TOKEN_LOG_ENTRIES entries, and
|
|
401
|
+
// freeing those inline would hold up every other worker - the same reason Account.delete()
|
|
402
|
+
// unlinks throughout. SREM rather than dropping the index outright, so a token minted
|
|
403
|
+
// between the read above and this write keeps its index entry instead of being left in the
|
|
404
|
+
// hash with nothing pointing at it.
|
|
405
|
+
//
|
|
406
|
+
// A transaction, so the commands reach Redis as one block: a connection lost mid-send then
|
|
407
|
+
// revokes nothing and leaves the index to try again from, rather than revoking some.
|
|
408
|
+
let req = redis.multi();
|
|
409
|
+
for (let pos = 0; pos < hashedTokens.length; pos += TOKEN_BATCH_SIZE) {
|
|
410
|
+
let batch = hashedTokens.slice(pos, pos + TOKEN_BATCH_SIZE);
|
|
411
|
+
req = req
|
|
412
|
+
.hdel(`${REDIS_PREFIX}tokens`, ...batch)
|
|
413
|
+
.hdel(`${REDIS_PREFIX}tokens:access`, ...batch)
|
|
414
|
+
.unlink(...batch.map(hashedToken => tokenAuditLog.logKey(hashedToken)))
|
|
415
|
+
.srem(`${REDIS_PREFIX}iat:${account}`, ...batch);
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
let res = await req.exec();
|
|
419
|
+
|
|
420
|
+
let err = extractMultiError(res);
|
|
421
|
+
if (err) {
|
|
422
|
+
throw err;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
logger.info({ msg: 'Deleted the access tokens of an account', account, tokens: hashedTokens.length });
|
|
426
|
+
|
|
427
|
+
return hashedTokens.length;
|
|
428
|
+
},
|
|
429
|
+
|
|
353
430
|
async getRawData(token) {
|
|
354
431
|
if (!/^[0-9a-f]{64}$/i.test(token)) {
|
|
355
432
|
let err = new Error('Invalid token format');
|
|
@@ -408,10 +485,9 @@ module.exports = {
|
|
|
408
485
|
|
|
409
486
|
let res = await req.exec();
|
|
410
487
|
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
}
|
|
488
|
+
let err = extractMultiError(res);
|
|
489
|
+
if (err) {
|
|
490
|
+
throw err;
|
|
415
491
|
}
|
|
416
492
|
|
|
417
493
|
return tokenData;
|
|
@@ -428,11 +504,25 @@ module.exports = {
|
|
|
428
504
|
* @param {Boolean} [opts.all] - every token on the instance, bound or not. Reads the token hash
|
|
429
505
|
* directly rather than walking one index per account: the account is stored on each record, so
|
|
430
506
|
* the union is already there, and enumerating accounts would be a round trip each.
|
|
507
|
+
* @param {String} [opts.scope] - keep only tokens whose scope list names this scope. Literal
|
|
508
|
+
* membership on purpose: a '*' token would also serve the surface, but the filter exists to
|
|
509
|
+
* answer "which tokens were minted for it", and those carry the scope by name.
|
|
431
510
|
*/
|
|
432
511
|
async list(account, page, pageSize, query, opts) {
|
|
433
512
|
page = Math.max(Number(page) || 0, 0);
|
|
434
513
|
pageSize = Math.max(Number(pageSize) || 20, 1);
|
|
435
514
|
|
|
515
|
+
// Normalized here so that "is there a query" and "does this entry match" answer the same
|
|
516
|
+
// question. matchesListQuery() trims before comparing and so matches everything for a
|
|
517
|
+
// whitespace-only query, while the `!query` test below took it for a real one - which put a
|
|
518
|
+
// single space in the search box on the read-everything path with no filter to show for it.
|
|
519
|
+
query = (query || '').toString().trim();
|
|
520
|
+
|
|
521
|
+
const scope = (opts && opts.scope) || null;
|
|
522
|
+
// Either filter forces the read-everything path: the fields they match on live on the
|
|
523
|
+
// record and nowhere else
|
|
524
|
+
const filtered = !!(query || scope);
|
|
525
|
+
|
|
436
526
|
let startPos = page * pageSize;
|
|
437
527
|
|
|
438
528
|
let list;
|
|
@@ -444,7 +534,10 @@ module.exports = {
|
|
|
444
534
|
list = await redis.smembers(`${REDIS_PREFIX}iat`);
|
|
445
535
|
}
|
|
446
536
|
|
|
447
|
-
|
|
537
|
+
// Byte order rather than localeCompare: the ids are hex, where the two agree, and in the
|
|
538
|
+
// `all` listing this is every token on the instance - a locale-aware comparison over a list
|
|
539
|
+
// that size costs more than the read it precedes.
|
|
540
|
+
list = [].concat(list || []).sort((a, b) => (a < b ? 1 : a > b ? -1 : 0));
|
|
448
541
|
|
|
449
542
|
let response = {
|
|
450
543
|
account: account || null,
|
|
@@ -454,9 +547,8 @@ module.exports = {
|
|
|
454
547
|
tokens: []
|
|
455
548
|
};
|
|
456
549
|
|
|
457
|
-
// Without a
|
|
458
|
-
|
|
459
|
-
if (!query) {
|
|
550
|
+
// Without a filter only the visible page's records are read
|
|
551
|
+
if (!filtered) {
|
|
460
552
|
list = list.slice(startPos, startPos + pageSize);
|
|
461
553
|
}
|
|
462
554
|
|
|
@@ -464,65 +556,99 @@ module.exports = {
|
|
|
464
556
|
return response;
|
|
465
557
|
}
|
|
466
558
|
|
|
467
|
-
let
|
|
559
|
+
let entries = [];
|
|
560
|
+
let reaped = 0;
|
|
561
|
+
|
|
562
|
+
// Read in batches, and keep only what the query matches. A search reads every token on the
|
|
563
|
+
// instance: as a single read that was one reply carrying every record, with all of them held
|
|
564
|
+
// decoded until the filter ran at the end. The search is still O(every token) - nothing
|
|
565
|
+
// indexes the fields it matches on - but what is in memory at once is now one batch plus the
|
|
566
|
+
// matches.
|
|
567
|
+
for (let pos = 0; pos < list.length; pos += TOKEN_BATCH_SIZE) {
|
|
568
|
+
let batch = list.slice(pos, pos + TOKEN_BATCH_SIZE);
|
|
569
|
+
let records = await redis.hmgetBuffer(`${REDIS_PREFIX}tokens`, batch);
|
|
570
|
+
|
|
571
|
+
for (let i = 0; i < batch.length; i++) {
|
|
572
|
+
let tokenHash = batch[i];
|
|
573
|
+
let encoded = records && records[i];
|
|
574
|
+
if (!encoded) {
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
468
577
|
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
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 });
|
|
578
|
+
try {
|
|
579
|
+
let tokenData = msgpack.decode(encoded);
|
|
580
|
+
|
|
581
|
+
// An expired token cannot authenticate, so listing it is noise. This
|
|
582
|
+
// is also where a minted-but-never-used token finally gets collected.
|
|
583
|
+
if (tokenData.expires && Date.now() >= tokenData.expires) {
|
|
584
|
+
reapExpiredToken(tokenHash, tokenData.account);
|
|
585
|
+
reaped++;
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
// Before the entry is built: on a scope-filtered read of every record, the
|
|
590
|
+
// date coercion and the copy below would mostly construct throwaways
|
|
591
|
+
if (scope && !(Array.isArray(tokenData.scopes) && tokenData.scopes.includes(scope))) {
|
|
592
|
+
continue;
|
|
507
593
|
}
|
|
594
|
+
|
|
595
|
+
tokenData.created = new Date(tokenData.created);
|
|
596
|
+
if (tokenData.expires) {
|
|
597
|
+
tokenData.expires = new Date(tokenData.expires);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// `account` is absent on the record for an unbound token, so it is filled in
|
|
601
|
+
// explicitly: a listing that mixes bound and unbound tokens should report one
|
|
602
|
+
// shape, not two, and `null` is the answer to "which account" for a token
|
|
603
|
+
// that is not bound to one.
|
|
604
|
+
let entry = Object.assign({ id: tokenHash, account: null }, tokenData);
|
|
605
|
+
|
|
606
|
+
if (query && !matchesListQuery(entry, LIST_QUERY_FIELDS, query)) {
|
|
607
|
+
continue;
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
entries.push(entry);
|
|
611
|
+
} catch (err) {
|
|
612
|
+
logger.error({ msg: 'Failed to process token data', hash: tokenHash, err });
|
|
508
613
|
}
|
|
509
|
-
} else if (lastEntry && entry[1]) {
|
|
510
|
-
lastEntry.access = decodeAccessData(entry[1], tokenHash);
|
|
511
614
|
}
|
|
512
615
|
}
|
|
513
616
|
|
|
514
|
-
if (
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
617
|
+
if (filtered) {
|
|
618
|
+
// The matches are what the caller is paging through, so they are what `total` counts -
|
|
619
|
+
// the same answer filterListPage() gave when it did the filtering here. `pages` follows
|
|
620
|
+
// from the shared derivation below.
|
|
621
|
+
response.total = entries.length;
|
|
622
|
+
entries = entries.slice(startPos, startPos + pageSize);
|
|
623
|
+
} else {
|
|
624
|
+
response.total = Math.max(0, response.total - reaped);
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
// Last-use records for the returned page only. They live in a second hash and nothing
|
|
628
|
+
// filters, sorts or counts on them, so reading one alongside every record above spent a
|
|
629
|
+
// command per token on data that at most one page of tokens would ever show.
|
|
630
|
+
if (entries.length) {
|
|
631
|
+
let accessRecords = await redis.hmgetBuffer(
|
|
632
|
+
`${REDIS_PREFIX}tokens:access`,
|
|
633
|
+
entries.map(entry => entry.id)
|
|
634
|
+
);
|
|
635
|
+
|
|
636
|
+
for (let i = 0; i < entries.length; i++) {
|
|
637
|
+
let encoded = accessRecords && accessRecords[i];
|
|
638
|
+
if (encoded) {
|
|
639
|
+
entries[i].access = decodeAccessData(encoded, entries[i].id);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
518
642
|
}
|
|
519
643
|
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
//
|
|
523
|
-
//
|
|
524
|
-
//
|
|
525
|
-
//
|
|
644
|
+
response.tokens = entries;
|
|
645
|
+
|
|
646
|
+
// Derived last, from whichever total the branches above settled on. A count taken before the
|
|
647
|
+
// loop describes a listing that no longer exists, because the loop reaps expired tokens as
|
|
648
|
+
// it goes - three tokens with the first expired reported `{total: 2, pages: 3}`. Only the
|
|
649
|
+
// records actually read are inspected, so an expired token beyond this call's reach is still
|
|
650
|
+
// counted until a later call gets to it; what this guarantees is that `pages` and `total` in
|
|
651
|
+
// one response are two views of one number.
|
|
526
652
|
response.pages = Math.ceil(response.total / pageSize);
|
|
527
653
|
|
|
528
654
|
return response;
|