emailengine-app 2.79.1 → 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.
Files changed (81) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +40 -0
  3. package/bin/emailengine.js +8 -1
  4. package/config/default.toml +6 -0
  5. package/data/google-crawlers.json +1 -1
  6. package/lib/account.js +95 -18
  7. package/lib/api-routes/account-routes.js +13 -1
  8. package/lib/api-routes/index.js +12 -0
  9. package/lib/api-routes/mailbox-routes.js +6 -0
  10. package/lib/api-routes/mcp-oauth-routes.js +259 -0
  11. package/lib/api-routes/mcp-routes.js +172 -0
  12. package/lib/api-routes/message-routes.js +125 -4
  13. package/lib/api-routes/outbox-routes.js +7 -0
  14. package/lib/api-routes/permission-map.js +97 -1
  15. package/lib/api-routes/route-helpers.js +16 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/submit-routes.js +41 -0
  18. package/lib/api-routes/template-routes.js +7 -0
  19. package/lib/api-routes/token-routes.js +4 -2
  20. package/lib/consts.js +30 -1
  21. package/lib/email-client/base-client.js +102 -117
  22. package/lib/email-client/gmail-client.js +87 -22
  23. package/lib/email-client/imap/mailbox.js +140 -66
  24. package/lib/email-client/outlook-client.js +17 -14
  25. package/lib/enum-descriptions.js +2 -1
  26. package/lib/field-usage.js +17 -1
  27. package/lib/lua/s-list-accounts.lua +5 -2
  28. package/lib/mcp/index.js +29 -0
  29. package/lib/mcp/inject.js +70 -0
  30. package/lib/mcp/json-schema.js +120 -0
  31. package/lib/mcp/listen.js +171 -0
  32. package/lib/mcp/oauth.js +324 -0
  33. package/lib/mcp/protocol.js +489 -0
  34. package/lib/mcp/resources.js +139 -0
  35. package/lib/mcp/tools.js +655 -0
  36. package/lib/openapi/index.js +3 -1
  37. package/lib/response-stream.js +52 -21
  38. package/lib/routes-ui.js +4 -0
  39. package/lib/schemas.js +24 -3
  40. package/lib/token-permission-view.js +104 -8
  41. package/lib/tokens.js +34 -5
  42. package/lib/tools.js +96 -0
  43. package/lib/ui-routes/account-routes.js +43 -1
  44. package/lib/ui-routes/admin-config-routes.js +114 -1
  45. package/lib/ui-routes/admin-entities-routes.js +54 -5
  46. package/lib/ui-routes/auth-routes.js +13 -0
  47. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  48. package/lib/ui-routes/route-helpers.js +116 -1
  49. package/lib/utils/network.js +9 -1
  50. package/lib/web-safe-html.js +61 -0
  51. package/lib/webhooks.js +3 -8
  52. package/package.json +9 -8
  53. package/sbom.json +1 -1
  54. package/scripts/README.md +25 -0
  55. package/scripts/build-icon.js +77 -0
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +98 -0
  58. package/static/emailengine.ico +0 -0
  59. package/static/js/ui.js +465 -1
  60. package/static/licenses.html +42 -22
  61. package/translations/messages.pot +57 -57
  62. package/views/config/mcp.hbs +361 -0
  63. package/views/config/oauth/index.hbs +7 -0
  64. package/views/layout/prompt.hbs +62 -0
  65. package/views/mcp/authorize.hbs +136 -0
  66. package/views/partials/head_assets.hbs +3 -3
  67. package/views/partials/mcp_access_levels.hbs +13 -0
  68. package/views/partials/mcp_account_limit.hbs +14 -0
  69. package/views/partials/mcp_tool_count.hbs +19 -0
  70. package/views/partials/side_menu.hbs +1 -0
  71. package/views/partials/ui/account-picker.hbs +59 -0
  72. package/views/partials/ui/code-block.hbs +26 -0
  73. package/views/partials/ui/menu-item.hbs +5 -0
  74. package/views/partials/ui/radio.hbs +41 -0
  75. package/views/partials/ui/tab.hbs +15 -10
  76. package/views/partials/ui/tabs.hbs +8 -5
  77. package/views/templates/template.hbs +4 -3
  78. package/views/tokens/index.hbs +8 -2
  79. package/views/tokens/new.hbs +514 -243
  80. package/winconf.js +148 -48
  81. package/workers/api.js +198 -48
@@ -23,9 +23,17 @@ const registeredPublishers = new Set();
23
23
  const KEEP_ALIVE_INTERVAL = 90 * 1000;
24
24
 
25
25
  class ResponseStream extends Transform {
26
- constructor() {
26
+ /**
27
+ * @param {Object} [options]
28
+ * @param {Set} [options.registry] - the live-stream set this stream registers itself in.
29
+ * Defaults to the shared change-feed set that publishChangeEvent() fans out to; the
30
+ * MCP listen streams (lib/mcp/listen.js) pass their own set so the two feeds cannot
31
+ * receive each other's frames.
32
+ */
33
+ constructor(options) {
27
34
  super();
28
- registeredPublishers.add(this);
35
+ this.registry = (options && options.registry) || registeredPublishers;
36
+ this.registry.add(this);
29
37
  this.periodicKeepAliveTimer = false;
30
38
  this.updateTimer();
31
39
 
@@ -78,7 +86,7 @@ class ResponseStream extends Transform {
78
86
  this._finalized = true;
79
87
 
80
88
  clearTimeout(this.periodicKeepAliveTimer);
81
- registeredPublishers.delete(this);
89
+ this.registry.delete(this);
82
90
 
83
91
  if (!this.destroyed) {
84
92
  this.destroy();
@@ -103,36 +111,59 @@ class ResponseStream extends Transform {
103
111
  }
104
112
 
105
113
  /**
106
- * Opens an SSE change feed on a Hapi request.
114
+ * Opens an SSE response on a Hapi toolkit: the stream, its cleanup, the deferred greeting, and
115
+ * the response headers, in one place for every feed.
107
116
  *
108
- * Both feeds - the admin UI one (/admin/changes) and the API one (/v1/changes) - are the same
109
- * stream with the same framing, so the wiring lives here next to the stream it wires up rather
110
- * than being written out twice. The parts that matter and are easy to get subtly different:
111
- * finalize() has to run when the response is finished (a dropped tab must not keep its stream in
112
- * registeredPublishers), the greeting has to be deferred so it is written after the response
113
- * headers, and X-Accel-Buffering: no is what keeps an intermediate proxy from holding events
114
- * back until the connection closes.
117
+ * All three consumers - the admin change feed, /v1/changes, and the MCP subscriptions/listen
118
+ * stream (lib/mcp/listen.js) - share this wiring because the parts that matter are easy to get
119
+ * subtly different: finalize() has to run when the response is finished (a dropped client must
120
+ * not keep its stream in the registry), the greeting and anything else written on open have to
121
+ * be deferred so they land after the response headers, and X-Accel-Buffering: no is what keeps
122
+ * an intermediate proxy from holding events back until the connection closes.
115
123
  *
116
- * @param {Object} request - Hapi request; the stream is parked on request.app.stream
117
124
  * @param {Object} h - Hapi response toolkit
118
- * @returns {Object} Hapi response
125
+ * @param {Object} [options]
126
+ * @param {Set} [options.registry] - passed to the ResponseStream constructor
127
+ * @param {Function} [options.onOpen] - called with the stream after the greeting is written
128
+ * @returns {{stream: ResponseStream, response: Object}}
119
129
  */
120
- function openChangeStream(request, h) {
121
- request.app.stream = new ResponseStream();
122
- finished(request.app.stream, err => request.app.stream.finalize(err));
130
+ function openSseStream(h, options) {
131
+ const stream = new ResponseStream({ registry: options && options.registry });
132
+
133
+ finished(stream, err => stream.finalize(err));
134
+
123
135
  setImmediate(() => {
124
136
  try {
125
- request.app.stream.write(`: EmailEngine v${packageData.version}\n\n`);
137
+ stream.write(`: EmailEngine v${packageData.version}\n\n`);
138
+ if (options && options.onOpen) {
139
+ options.onOpen(stream);
140
+ }
126
141
  } catch (err) {
127
- // ignore
142
+ // the stream is already gone; finished() above cleans up
128
143
  }
129
144
  });
130
- return h
131
- .response(request.app.stream)
145
+
146
+ const response = h
147
+ .response(stream)
132
148
  .header('X-Accel-Buffering', 'no')
133
149
  .header('Connection', 'keep-alive')
134
150
  .header('Cache-Control', 'no-cache')
135
151
  .type('text/event-stream');
152
+
153
+ return { stream, response };
154
+ }
155
+
156
+ /**
157
+ * Opens the SSE change feed shared by /admin/changes and /v1/changes.
158
+ *
159
+ * @param {Object} request - Hapi request; the stream is parked on request.app.stream
160
+ * @param {Object} h - Hapi response toolkit
161
+ * @returns {Object} Hapi response
162
+ */
163
+ function openChangeStream(request, h) {
164
+ const { stream, response } = openSseStream(h);
165
+ request.app.stream = stream;
166
+ return response;
136
167
  }
137
168
 
138
- module.exports = { ResponseStream, registeredPublishers, openChangeStream };
169
+ module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream };
package/lib/routes-ui.js CHANGED
@@ -14,6 +14,7 @@ const authRoutes = require('./ui-routes/auth-routes');
14
14
  const oauthConfigRoutes = require('./ui-routes/oauth-config-routes');
15
15
  const adminConfigRoutes = require('./ui-routes/admin-config-routes');
16
16
  const accountRoutes = require('./ui-routes/account-routes');
17
+ const mcpConsentRoutes = require('./ui-routes/mcp-consent-routes');
17
18
 
18
19
  function applyRoutes(server, call) {
19
20
  // Initialize admin entity routes (webhooks, templates, gateways, tokens)
@@ -59,6 +60,9 @@ function applyRoutes(server, call) {
59
60
  // Account management routes (listing, add-account wizard, per-account view/edit/logs/browse)
60
61
  accountRoutes({ server, call });
61
62
 
63
+ // MCP OAuth consent page (self-gates on the MCP feature flag, like the Document Store module)
64
+ mcpConsentRoutes({ server, call });
65
+
62
66
  server.route({
63
67
  method: 'GET',
64
68
  path: '/.well-known/acme-challenge/{token}',
package/lib/schemas.js CHANGED
@@ -330,6 +330,24 @@ const settingsSchema = {
330
330
  .falsy('N', 'false', 0, '')
331
331
  .description('Include parsed calendar event data in webhook payloads'),
332
332
 
333
+ /* ────────────── MCP ────────────── */
334
+
335
+ mcpEnabled: Joi.boolean()
336
+ .truthy('Y', 'true', '1', 'on')
337
+ .falsy('N', 'false', 0, '')
338
+ .example(false)
339
+ .description(
340
+ 'Enable the MCP (Model Context Protocol) endpoint at /mcp, which lets AI agents work with the connected email accounts using access tokens. Disabled by default'
341
+ ),
342
+
343
+ mcpOAuthEnabled: Joi.boolean()
344
+ .truthy('Y', 'true', '1', 'on')
345
+ .falsy('N', 'false', 0, '')
346
+ .example(false)
347
+ .description(
348
+ 'Enable the built-in OAuth2 authorization server for the MCP endpoint, used by MCP clients that cannot be configured with a static access token. Requires mcpEnabled and a configured serviceUrl. Disabled by default'
349
+ ),
350
+
333
351
  /* ────────────── Document Store (Deprecated) ────────────── */
334
352
 
335
353
  documentStoreEnabled: Joi.boolean()
@@ -2267,14 +2285,14 @@ const messageReferenceSchema = Joi.object({
2267
2285
  .truthy('Y', 'true', '1')
2268
2286
  .falsy('N', 'false', 0)
2269
2287
  .default(false)
2270
- .description('Include the original message as quoted text in the response')
2288
+ .description('Quote the referenced message under the new text, the way an email client does. Without it only the new text is sent')
2271
2289
  .label('InlineReply'),
2272
2290
 
2273
2291
  forwardAttachments: Joi.boolean()
2274
2292
  .truthy('Y', 'true', '1')
2275
2293
  .falsy('N', 'false', 0)
2276
2294
  .default(false)
2277
- .description('Include original attachments when forwarding')
2295
+ .description('Carry the attachments of the referenced message over to the forwarded copy. Only valid when action is "forward"')
2278
2296
  .when('action', {
2279
2297
  is: 'forward',
2280
2298
  then: Joi.optional(),
@@ -2299,7 +2317,10 @@ const messageReferenceSchema = Joi.object({
2299
2317
  documentStore: documentStoreSchema.default(false).meta({ swaggerHidden: true })
2300
2318
  })
2301
2319
  .or('message', 'threadId')
2302
- .description('Configuration for replying to or forwarding an existing message')
2320
+ .description(
2321
+ 'Reply to or forward a stored message. EmailEngine fills in the subject, the recipients and the In-Reply-To/References headers from the ' +
2322
+ 'referenced message, and flags it as answered or forwarded once the new message is sent, so only the new content has to be supplied'
2323
+ )
2303
2324
  .label('MessageReference');
2304
2325
 
2305
2326
  const idempotencyKeySchema = Joi.string()
@@ -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
- // Object.hasOwn rather than a bare lookup, for the same reason the parse uses it: a slug of
200
- // `constructor` would otherwise render an Object.prototype member
201
- return values.map(value => (Object.hasOwn(labels, value) ? labels[value] : value)).join(', ');
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 = { formModel, summarize, ACTION_LABELS, GROUP_LABELS };
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
@@ -113,6 +113,14 @@ module.exports = {
113
113
  return false;
114
114
  }
115
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
+
116
124
  // Now we know it's valid format, proceed with validation
117
125
  const tokenBuffer = Buffer.from(hexPart, 'hex');
118
126
  const hashedToken = crypto.createHash('sha256').update(tokenBuffer).digest('hex');
@@ -128,6 +136,13 @@ module.exports = {
128
136
  throw errGet || errExpire;
129
137
  }
130
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
+
131
146
  const [storedSignature, storedAccount] = storedSignatureValue.split(':');
132
147
 
133
148
  if (!storedSignature || !constantTimeEqual(storedSignature, expectedSignature)) {
@@ -489,6 +504,9 @@ module.exports = {
489
504
  * @param {Boolean} [opts.all] - every token on the instance, bound or not. Reads the token hash
490
505
  * directly rather than walking one index per account: the account is stored on each record, so
491
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.
492
510
  */
493
511
  async list(account, page, pageSize, query, opts) {
494
512
  page = Math.max(Number(page) || 0, 0);
@@ -500,6 +518,11 @@ module.exports = {
500
518
  // single space in the search box on the read-everything path with no filter to show for it.
501
519
  query = (query || '').toString().trim();
502
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
+
503
526
  let startPos = page * pageSize;
504
527
 
505
528
  let list;
@@ -524,9 +547,8 @@ module.exports = {
524
547
  tokens: []
525
548
  };
526
549
 
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.
529
- if (!query) {
550
+ // Without a filter only the visible page's records are read
551
+ if (!filtered) {
530
552
  list = list.slice(startPos, startPos + pageSize);
531
553
  }
532
554
 
@@ -564,6 +586,12 @@ module.exports = {
564
586
  continue;
565
587
  }
566
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;
593
+ }
594
+
567
595
  tokenData.created = new Date(tokenData.created);
568
596
  if (tokenData.expires) {
569
597
  tokenData.expires = new Date(tokenData.expires);
@@ -586,9 +614,10 @@ module.exports = {
586
614
  }
587
615
  }
588
616
 
589
- if (query) {
617
+ if (filtered) {
590
618
  // 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.
619
+ // the same answer filterListPage() gave when it did the filtering here. `pages` follows
620
+ // from the shared derivation below.
592
621
  response.total = entries.length;
593
622
  entries = entries.slice(startPos, startPos + pageSize);
594
623
  } else {
package/lib/tools.js CHANGED
@@ -389,10 +389,23 @@ function redactValidationError(err) {
389
389
  return err;
390
390
  }
391
391
 
392
+ // Shared token grammar for cid: references in HTML. Collection
393
+ // (collectCidReferences) and every cid: to data URI replace step must tokenize
394
+ // identically, otherwise the attachments fetched drift from the references
395
+ // replaced and inline images silently disappear. Exposed as a factory rather
396
+ // than one regex instance so no lastIndex state can leak between callers.
397
+ const CID_REFERENCE_SOURCE = String.raw`\bcid:([^"'\s>]+)`;
398
+
399
+ function cidReferenceRegex() {
400
+ return new RegExp(CID_REFERENCE_SOURCE, 'g');
401
+ }
402
+
392
403
  module.exports = {
393
404
  // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
394
405
  toCamelCase,
395
406
 
407
+ cidReferenceRegex,
408
+
396
409
  /**
397
410
  * Establish an admin session: every full session write goes through here
398
411
  * so the session always carries a random sid. The message browser binds
@@ -409,6 +422,89 @@ module.exports = {
409
422
  request.cookieAuth.set(Object.assign({}, sessionData, { sid: randomBytes(32).toString('hex') }));
410
423
  },
411
424
 
425
+ /**
426
+ * Whether a session cookie has been ended by a later "log out all sessions"
427
+ * or password change.
428
+ *
429
+ * The read side of the `passwordVersion` setAdminSession() stamps, and the
430
+ * one spelling of the comparison, because the same cookie carries two
431
+ * credentials and both have to end together: the admin session itself, and
432
+ * the browse page's `sess_` API token, which is HMAC'd to the cookie's sid
433
+ * and slides its own TTL on every use. They authenticate through different
434
+ * Hapi strategies in workers/api.js, so a rule written out twice is a rule
435
+ * one of them can be left out of - which is how the token outlived the
436
+ * click for a while.
437
+ *
438
+ * A zero or absent current version never ends a session: it means no local
439
+ * password exists (an unsecured instance), or nobody has ever bumped it,
440
+ * and a session stamped before the field existed must not be force-expired.
441
+ *
442
+ * @param {Number} currentPasswordVersion authData.passwordVersion, or 0
443
+ * @param {Object} session decoded session cookie
444
+ * @returns {Boolean} true when the session is over
445
+ */
446
+ isEndedSession(currentPasswordVersion, session) {
447
+ return !!currentPasswordVersion && currentPasswordVersion !== (session && session.passwordVersion);
448
+ },
449
+
450
+ /**
451
+ * Caps the decoded plain and html values of a text object at maxBytes,
452
+ * mirroring the IMAP getText() semantics: the limit applies per text type
453
+ * to the decoded string. The API clients (Gmail, MS Graph) receive the full
454
+ * text from the provider in one response, so unlike IMAP the limit cannot
455
+ * reduce what is downloaded, only what is passed on - without it a
456
+ * notifyTextSize / maxBytes cap is silently ignored on API accounts.
457
+ * Mutates the passed object; only the "plain" and "html" keys are touched,
458
+ * so an id reference or a flag riding on the same object is never clipped.
459
+ * For byte-exact UTF-8 truncation see truncateToBytes in lib/mcp/tools.js,
460
+ * a different contract that is kept separate on purpose.
461
+ * @param {Object} textContents Object carrying plain and/or html strings
462
+ * @param {Number} maxBytes Size limit per text type, falsy means no limit
463
+ * @returns {Boolean} true if any value was truncated
464
+ */
465
+ truncateTextContents(textContents, maxBytes) {
466
+ let hasMore = false;
467
+ if (maxBytes && textContents) {
468
+ for (let key of ['plain', 'html']) {
469
+ if (typeof textContents[key] === 'string' && textContents[key].length > maxBytes) {
470
+ textContents[key] = textContents[key].substr(0, maxBytes);
471
+ hasMore = true;
472
+ }
473
+ }
474
+ }
475
+ return hasMore;
476
+ },
477
+
478
+ /**
479
+ * Collects the content ids referenced through "cid:" links in an HTML string.
480
+ * Returned ids carry no "cid:" prefix or angle brackets. Use this with a Set
481
+ * lookup per attachment instead of scanning the full HTML once per attachment:
482
+ * the repeated synchronous scans cost attachment count times body size, which
483
+ * on a crafted message blocks the worker event loop past the heartbeat
484
+ * restart timeout. Tokenizes with the same grammar as the cid: replace steps
485
+ * (cidReferenceRegex), so a content id that is only a prefix of a referenced
486
+ * id, or that appears outside a cid: link, does not match. Each token is
487
+ * additionally added truncated at a closing parenthesis: the replace grammar
488
+ * does not stop at ")" and so never embeds CSS url(cid:...) references, but
489
+ * the attachment content they point at should still be fetched.
490
+ * @param {String} html HTML content to scan
491
+ * @returns {Set<String>} Content ids referenced in the HTML
492
+ */
493
+ collectCidReferences(html) {
494
+ let cids = new Set();
495
+ if (typeof html === 'string') {
496
+ for (let match of html.matchAll(cidReferenceRegex())) {
497
+ let cid = match[1];
498
+ cids.add(cid);
499
+ let parenPos = cid.indexOf(')');
500
+ if (parenPos > 0) {
501
+ cids.add(cid.substring(0, parenPos));
502
+ }
503
+ }
504
+ }
505
+ return cids;
506
+ },
507
+
412
508
  /**
413
509
  * Helper function to set specific bit in a buffer
414
510
  * @param {Buffer} buffer Buffer to edit
@@ -42,7 +42,7 @@ const {
42
42
  ACCOUNT_DISPLAY_STATES,
43
43
  signedFormBlobFields: signedBlobFields
44
44
  } = require('../schemas');
45
- const { formatAccountData, cachedTemplates, identityErrorView, ACCOUNT_STATE_DISPLAY, adminUrl } = require('./route-helpers');
45
+ const { formatAccountData, cachedTemplates, identityErrorView, ACCOUNT_STATE_DISPLAY, adminUrl, accountSuggestions } = require('./route-helpers');
46
46
  const { webhooks: Webhooks } = require('../webhooks');
47
47
  const { describeEffectiveRouting, isDeliverableRoute } = require('../webhook-routing');
48
48
  const { matchesExpectedIdentity, resolveExpectedIdentity } = require('../account/expected-identity');
@@ -280,6 +280,48 @@ function init(args) {
280
280
  }
281
281
  });
282
282
 
283
+ // The data behind the account picker (views/partials/ui/account-picker.hbs), which every admin
284
+ // form that binds something to one account renders. A search endpoint rather than a list
285
+ // shipped with the page: an instance can hold far more accounts than a page could usefully
286
+ // carry, and the whole point of the control is that a person types part of what they are
287
+ // looking for.
288
+ //
289
+ // No auth options of its own: it inherits the admin surface's session default, exactly like the
290
+ // listing it is a narrower view of, and it exposes nothing that listing does not.
291
+ server.route({
292
+ method: 'GET',
293
+ path: '/admin/accounts/suggestions',
294
+
295
+ async handler(request) {
296
+ const { accounts, total } = await accountSuggestions(call, { query: request.query.query, logger: request.logger });
297
+
298
+ return {
299
+ accounts,
300
+ // What the box could not show, so the picker can say "keep typing" rather than
301
+ // letting a capped list read as the whole instance. The total itself is not
302
+ // returned: nothing renders it, and it would only be a third number to keep
303
+ // consistent with the other two.
304
+ more: Math.max(total - accounts.length, 0)
305
+ };
306
+ },
307
+
308
+ options: {
309
+ validate: {
310
+ options: {
311
+ stripUnknown: true,
312
+ abortEarly: false,
313
+ convert: true
314
+ },
315
+
316
+ failAction,
317
+
318
+ query: Joi.object({
319
+ query: Joi.string().trim().empty('').max(256).description('Search string matched against account id, name and address')
320
+ })
321
+ }
322
+ }
323
+ });
324
+
283
325
  server.route({
284
326
  method: 'POST',
285
327
  path: '/admin/accounts/new',