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.
Files changed (110) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +79 -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 +137 -19
  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 +101 -1
  15. package/lib/api-routes/route-helpers.js +87 -4
  16. package/lib/api-routes/route-metadata.js +24 -4
  17. package/lib/api-routes/settings-routes.js +37 -14
  18. package/lib/api-routes/submit-routes.js +41 -0
  19. package/lib/api-routes/template-routes.js +7 -0
  20. package/lib/api-routes/token-routes.js +292 -122
  21. package/lib/arf-detect.js +17 -4
  22. package/lib/bounce-detect.js +28 -17
  23. package/lib/consts.js +36 -1
  24. package/lib/db.js +6 -0
  25. package/lib/email-client/base-client.js +102 -117
  26. package/lib/email-client/gmail-client.js +91 -29
  27. package/lib/email-client/imap/mailbox.js +175 -101
  28. package/lib/email-client/imap-client.js +49 -2
  29. package/lib/email-client/outlook-client.js +20 -24
  30. package/lib/enum-descriptions.js +2 -1
  31. package/lib/field-usage.js +17 -1
  32. package/lib/lua/h-set-new-mark.lua +36 -0
  33. package/lib/lua/s-list-accounts.lua +5 -2
  34. package/lib/mcp/index.js +29 -0
  35. package/lib/mcp/inject.js +70 -0
  36. package/lib/mcp/json-schema.js +120 -0
  37. package/lib/mcp/listen.js +171 -0
  38. package/lib/mcp/oauth.js +324 -0
  39. package/lib/mcp/protocol.js +489 -0
  40. package/lib/mcp/resources.js +139 -0
  41. package/lib/mcp/tools.js +655 -0
  42. package/lib/message-port-stream.js +84 -1
  43. package/lib/oauth2-apps.js +84 -15
  44. package/lib/openapi/build-document.js +5 -1
  45. package/lib/openapi/index.js +3 -1
  46. package/lib/response-stream.js +52 -21
  47. package/lib/routes-ui.js +4 -0
  48. package/lib/schemas.js +26 -5
  49. package/lib/settings.js +23 -9
  50. package/lib/token-audit-log.js +32 -9
  51. package/lib/token-permission-view.js +104 -8
  52. package/lib/tokens.js +194 -68
  53. package/lib/tools.js +96 -0
  54. package/lib/ui-routes/account-routes.js +55 -6
  55. package/lib/ui-routes/admin-config-routes.js +114 -1
  56. package/lib/ui-routes/admin-entities-routes.js +103 -19
  57. package/lib/ui-routes/auth-routes.js +13 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +330 -0
  59. package/lib/ui-routes/oauth-config-routes.js +7 -7
  60. package/lib/ui-routes/route-helpers.js +143 -1
  61. package/lib/ui-routes/suppression-list-routes.js +14 -9
  62. package/lib/utils/decode-headers.js +42 -0
  63. package/lib/utils/header-map.js +48 -0
  64. package/lib/utils/network.js +9 -1
  65. package/lib/utils/unsafe-key.js +59 -0
  66. package/lib/web-safe-html.js +61 -0
  67. package/lib/webhook-routing.js +6 -2
  68. package/lib/webhooks.js +31 -8
  69. package/package.json +9 -8
  70. package/sbom.json +1 -1
  71. package/scripts/README.md +25 -0
  72. package/scripts/build-icon.js +77 -0
  73. package/server.js +39 -17
  74. package/static/css/flyonui.css +1 -1
  75. package/static/css/src/app.tailwind.css +98 -0
  76. package/static/emailengine.ico +0 -0
  77. package/static/js/ui.js +465 -1
  78. package/static/licenses.html +42 -22
  79. package/translations/messages.pot +57 -57
  80. package/views/accounts/account.hbs +8 -8
  81. package/views/accounts/browse.hbs +1 -1
  82. package/views/accounts/edit.hbs +2 -2
  83. package/views/config/mcp.hbs +361 -0
  84. package/views/config/oauth/index.hbs +7 -0
  85. package/views/gateways/edit.hbs +1 -1
  86. package/views/gateways/gateway.hbs +2 -2
  87. package/views/gateways/index.hbs +7 -7
  88. package/views/layout/prompt.hbs +62 -0
  89. package/views/mcp/authorize.hbs +136 -0
  90. package/views/partials/accounts_table.hbs +7 -7
  91. package/views/partials/head_assets.hbs +3 -3
  92. package/views/partials/mcp_access_levels.hbs +13 -0
  93. package/views/partials/mcp_account_limit.hbs +14 -0
  94. package/views/partials/mcp_tool_count.hbs +19 -0
  95. package/views/partials/side_menu.hbs +1 -0
  96. package/views/partials/ui/account-picker.hbs +59 -0
  97. package/views/partials/ui/code-block.hbs +26 -0
  98. package/views/partials/ui/menu-item.hbs +5 -0
  99. package/views/partials/ui/radio.hbs +41 -0
  100. package/views/partials/ui/tab.hbs +15 -10
  101. package/views/partials/ui/tabs.hbs +8 -5
  102. package/views/suppression-lists/list.hbs +1 -1
  103. package/views/templates/index.hbs +2 -2
  104. package/views/templates/template.hbs +5 -4
  105. package/views/tokens/index.hbs +30 -4
  106. package/views/tokens/new.hbs +517 -239
  107. package/winconf.js +148 -48
  108. package/workers/api.js +239 -95
  109. package/workers/imap.js +65 -72
  110. package/workers/webhooks.js +21 -1
@@ -0,0 +1,330 @@
1
+ 'use strict';
2
+
3
+ // The consent page of the MCP OAuth flow: the one step with a human in it. An MCP client sends
4
+ // the operator's browser here; approving mints a single-use authorization code that the client
5
+ // exchanges for an mcp-scoped access token at POST /mcp/oauth/token.
6
+ //
7
+ // Nothing reachable before the human clicks ever redirects off this origin. RFC 6749 4.1.2.1
8
+ // only forbids redirecting when the client or the redirect_uri cannot be validated, and an
9
+ // earlier revision of this file followed that literally: a validated-but-malformed request
10
+ // (wrong response_type, a code_challenge_method other than S256, a resource naming another
11
+ // server) bounced straight back to the client's address with ?error=. Client registration is
12
+ // open and unauthenticated, so anyone could register their own https redirect_uri and turn that
13
+ // into a no-interaction redirect off the admin origin - an open redirector aimed by whoever
14
+ // composed the link, which is exactly what the rule exists to prevent. Those cases now render
15
+ // the error page instead. The cost is that a misconfigured client gets no callback for them,
16
+ // which is the right trade: a conforming client never sends them, and a developer debugging one
17
+ // reads the reason on screen.
18
+ //
19
+ // Only the two outcomes of a human decision redirect: approval carries the code, Deny carries
20
+ // error=access_denied.
21
+ //
22
+ // Approval requires request.auth.isAuthenticated, exactly like the admin token mint
23
+ // (lib/ui-routes/admin-entities-routes.js): a token is never invalidated once issued, and the
24
+ // session default is applied conditionally, so the gate has to key on the actual request
25
+ // principal rather than the global secured-state.
26
+
27
+ const Boom = require('@hapi/boom');
28
+ const Joi = require('joi');
29
+
30
+ const { redis } = require('../db');
31
+ const { accountExists } = require('../account');
32
+ const { accountPickerSelection, mcpToolGrants } = require('./route-helpers');
33
+ const { failAction } = require('../tools');
34
+ const { accountIdSchema } = require('../schemas');
35
+ const { MCP_ACCESS_LEVELS, MCP_ACCESS_LEVEL_OPTIONS, MCP_GRANT_WORDING } = require('../token-permission-view');
36
+ const { mcpFeatureEnabled } = require('../mcp');
37
+ const { oauthOrigin, getClient, touchClient, createAuthorizationCode, isAcceptableResource } = require('../mcp/oauth');
38
+
39
+ // The OAuth request parameters, carried through the GET render and posted back with the
40
+ // decision. state is a client-side value with no format promises; the size bounds are only
41
+ // there so the consent form cannot be used to store arbitrary blobs in a hidden field.
42
+ const oauthParamsSchema = {
43
+ client_id: Joi.string().hex().length(32).required(),
44
+ redirect_uri: Joi.string().uri().max(2048).required(),
45
+ state: Joi.string().max(4096).allow(''),
46
+ code_challenge: Joi.string()
47
+ .pattern(/^[A-Za-z0-9\-._~]{43,128}$/)
48
+ .required(),
49
+ resource: Joi.string().max(2048).allow('')
50
+ };
51
+
52
+ function redirectHostOf(redirectUri) {
53
+ try {
54
+ return new URL(redirectUri).host || redirectUri;
55
+ } catch (err) {
56
+ return redirectUri;
57
+ }
58
+ }
59
+
60
+ // Sends the browser back to the client. `state` and the RFC 9207 `iss` marker ride along on
61
+ // every authorization response, success and failure alike, so each call site names only what
62
+ // is specific to it.
63
+ function redirectToClient(h, { redirectUri, state, origin }, params) {
64
+ const url = new URL(redirectUri);
65
+ for (const [key, value] of Object.entries(Object.assign({ state, iss: origin }, params))) {
66
+ if (value !== undefined && value !== null && value !== '') {
67
+ url.searchParams.set(key, value);
68
+ }
69
+ }
70
+ return h.redirect(url.href);
71
+ }
72
+
73
+ // Both render paths use the chrome-free `prompt` layout: the operator lands here from an MCP
74
+ // client mid-flow, so the page reads as a consent dialog, not as a place inside the admin app.
75
+ // It is still an admin-surface page (admin session gate, admin IP perimeter, FlyonUI) - only
76
+ // the navigation chrome is gone.
77
+ function renderError(h, message) {
78
+ return h.view(
79
+ 'mcp/authorize',
80
+ {
81
+ pageTitle: 'Authorize MCP client',
82
+ errorMessage: message
83
+ },
84
+ { layout: 'prompt' }
85
+ );
86
+ }
87
+
88
+ async function init(args) {
89
+ const { server } = args;
90
+
91
+ // The one construction of the consent view context, shared by the GET render and the POST
92
+ // re-render, so the two cannot drift on what the page needs.
93
+ async function renderConsent(h, { client, redirectUri, canProvision, values, errors }) {
94
+ // Only resolved for a render that can actually approve, and only when the form carries an
95
+ // account at all: the picker fetches its own suggestions, so a render costs an account
96
+ // lookup exactly when there is a choice on the form to show back
97
+ const selectedAccount = canProvision && values && values.account ? await accountPickerSelection(values.account, server.logger) : null;
98
+
99
+ // Read-only unless the operator picked otherwise; a re-render after a validation error
100
+ // keeps whatever they chose. The template compares this against each option itself
101
+ // (the `equals` helper), so the level is one value rather than three booleans.
102
+ const accessLevel = values && Object.hasOwn(MCP_ACCESS_LEVELS, values.access) ? values.access : 'read';
103
+
104
+ // From the registry the endpoint dispatches through, so the count under the radios cannot
105
+ // describe a tool set that has since changed
106
+ const mcpTools = mcpToolGrants(server, server.logger);
107
+
108
+ return h.view(
109
+ 'mcp/authorize',
110
+ {
111
+ pageTitle: 'Authorize MCP client',
112
+
113
+ clientName: (client && client.client_name) || 'An MCP client',
114
+ redirectHost: redirectHostOf(redirectUri),
115
+
116
+ // What approving actually grants, in plain words, derived once at load from the
117
+ // same tables the enforcement reads - hand-written prose here would drift the
118
+ // first time the tool set changes
119
+ grantWording: MCP_GRANT_WORDING,
120
+
121
+ accessLevel,
122
+ // The radio group itself renders through the shared mcp_access_levels partial
123
+ accessOptions: MCP_ACCESS_LEVEL_OPTIONS,
124
+
125
+ // The tool count under the radios, through the shared mcp_tool_count partial. The
126
+ // grant sentences above it say what a level allows in the permission vocabulary;
127
+ // this says which tools the client ends up holding, which is the thing the person
128
+ // approving is actually being asked about.
129
+ mcpTools,
130
+ mcpAccessPresets: MCP_ACCESS_LEVELS,
131
+
132
+ selectedAccount,
133
+
134
+ // Mirrors the admin token mint: the form warns instead of letting the operator
135
+ // fill everything in and lose it to a 403
136
+ canProvision,
137
+
138
+ values,
139
+ errors
140
+ },
141
+ { layout: 'prompt' }
142
+ );
143
+ }
144
+
145
+ if (!mcpFeatureEnabled) {
146
+ // Same shape as the Document Store UI module: with the deployment gate off, the routes
147
+ // do not exist
148
+ return;
149
+ }
150
+
151
+ server.route({
152
+ method: 'GET',
153
+ path: '/admin/mcp/authorize',
154
+
155
+ async handler(request, h) {
156
+ const origin = await oauthOrigin();
157
+ if (!origin) {
158
+ return renderError(h, 'MCP OAuth sign-in is not enabled on this instance. Enable it under Configuration > MCP.');
159
+ }
160
+
161
+ const client = await getClient(request.query.client_id);
162
+ if (!client) {
163
+ return renderError(h, 'Unknown MCP client. The client registration may have expired - ask the client to register again.');
164
+ }
165
+
166
+ if (!client.redirect_uris.includes(request.query.redirect_uri)) {
167
+ return renderError(h, 'The redirect address of this request is not registered for the client, so the request cannot be trusted.');
168
+ }
169
+
170
+ // Rendered, never redirected: see the note at the top of this file on why a
171
+ // validated redirect_uri is not enough to make an automatic redirect safe here
172
+ if (request.query.response_type !== 'code') {
173
+ return renderError(h, `This client asked for an unsupported response type ("${request.query.response_type}"). Only "code" is supported.`);
174
+ }
175
+
176
+ if (request.query.code_challenge_method && request.query.code_challenge_method !== 'S256') {
177
+ return renderError(h, 'This client asked for an unsupported PKCE method. Only "S256" is supported.');
178
+ }
179
+
180
+ if (!isAcceptableResource(request.query.resource, origin)) {
181
+ return renderError(h, 'This authorization request names a different server as its resource, so it was not meant for this instance.');
182
+ }
183
+
184
+ await touchClient(client.client_id);
185
+
186
+ return renderConsent(h, {
187
+ client,
188
+ redirectUri: request.query.redirect_uri,
189
+ canProvision: request.auth.isAuthenticated,
190
+ values: {
191
+ client_id: client.client_id,
192
+ redirect_uri: request.query.redirect_uri,
193
+ state: request.query.state,
194
+ code_challenge: request.query.code_challenge,
195
+ resource: request.query.resource
196
+ }
197
+ });
198
+ },
199
+
200
+ options: {
201
+ validate: {
202
+ options: {
203
+ stripUnknown: true,
204
+ abortEarly: false,
205
+ convert: true
206
+ },
207
+
208
+ // A malformed authorization request never reaches a redirect, so the failure
209
+ // renders in place
210
+ failAction: (request, h) => renderError(h, 'This MCP authorization link is malformed or incomplete.').takeover(),
211
+
212
+ query: Joi.object(
213
+ Object.assign({}, oauthParamsSchema, {
214
+ response_type: Joi.string().max(64).required(),
215
+ code_challenge_method: Joi.string().max(64),
216
+ scope: Joi.string().max(1024).allow('')
217
+ })
218
+ )
219
+ }
220
+ }
221
+ });
222
+
223
+ server.route({
224
+ method: 'POST',
225
+ path: '/admin/mcp/authorize',
226
+
227
+ async handler(request, h) {
228
+ const origin = await oauthOrigin();
229
+ if (!origin) {
230
+ return renderError(h, 'MCP OAuth sign-in is not enabled on this instance.');
231
+ }
232
+
233
+ const client = await getClient(request.payload.client_id);
234
+ if (!client || !client.redirect_uris.includes(request.payload.redirect_uri)) {
235
+ return renderError(h, 'Unknown MCP client or unregistered redirect address. The registration may have expired while this page was open.');
236
+ }
237
+
238
+ const authRequest = { redirectUri: request.payload.redirect_uri, state: request.payload.state, origin };
239
+
240
+ // Denying is checked before the mint gate, and needs no credential: refusing to hand
241
+ // out a token is not an action that requires the authority to hand one out. With no
242
+ // admin password set the page hides Approve and tells the operator that denying is
243
+ // all they can do, so a 403 on Deny would leave the client waiting for a callback
244
+ // that the only available button could never send.
245
+ if (request.payload.decision !== 'approve') {
246
+ return redirectToClient(h, authRequest, { error: 'access_denied' });
247
+ }
248
+
249
+ // The same rule as the admin token mint, for the same reason: this POST creates a
250
+ // lasting credential, so it needs a real authenticated admin session on THIS request
251
+ if (!request.auth.isAuthenticated) {
252
+ throw Boom.forbidden('Can not authorize an MCP client without an authenticated admin session');
253
+ }
254
+
255
+ // Re-checked here and not only on the GET, because the POST is where the value is
256
+ // written onto the code record and the GET is not what supplied it - a hand-crafted
257
+ // form can name any resource it likes. Redemption refuses a code whose resource does
258
+ // not name this server, so without this the mint succeeds and the exchange fails,
259
+ // which reads to the operator as an approval that did nothing.
260
+ if (!isAcceptableResource(request.payload.resource, origin)) {
261
+ return renderError(h, 'This authorization request names a different server as its resource, so it was not meant for this instance.');
262
+ }
263
+
264
+ const account = request.payload.account || null;
265
+ if (account && !(await accountExists(redis, account))) {
266
+ return renderConsent(h, {
267
+ client,
268
+ redirectUri: request.payload.redirect_uri,
269
+ canProvision: true,
270
+ values: request.payload,
271
+ errors: { account: 'No such account' }
272
+ });
273
+ }
274
+
275
+ // Read-only is the default here exactly as it is on the admin generator, and for a
276
+ // stronger reason: this flow issues credentials to the least controllable clients on
277
+ // the least controllable devices. The radio always posts a value, so the schema
278
+ // default only ever fires for a stale or hand-crafted POST - and defaulting that to
279
+ // 'read' means an omitted field mints the narrowest token, not the widest.
280
+ const access = request.payload.access;
281
+
282
+ const code = await createAuthorizationCode({
283
+ clientId: client.client_id,
284
+ redirectUri: request.payload.redirect_uri,
285
+ codeChallenge: request.payload.code_challenge,
286
+ resource: request.payload.resource || null,
287
+ account,
288
+ permissions: MCP_ACCESS_LEVELS[access],
289
+ description: `MCP: ${client.client_name || redirectHostOf(request.payload.redirect_uri)}${account ? ` (${account})` : ''}`
290
+ });
291
+
292
+ request.logger.info({
293
+ msg: 'Approved an MCP OAuth authorization',
294
+ client: client.client_id,
295
+ clientName: client.client_name,
296
+ account,
297
+ access
298
+ });
299
+
300
+ return redirectToClient(h, authRequest, { code });
301
+ },
302
+
303
+ options: {
304
+ validate: {
305
+ options: {
306
+ stripUnknown: true,
307
+ abortEarly: false,
308
+ convert: true
309
+ },
310
+
311
+ failAction,
312
+
313
+ payload: Joi.object(
314
+ Object.assign({}, oauthParamsSchema, {
315
+ decision: Joi.string().valid('approve', 'deny').required(),
316
+ account: accountIdSchema.allow('').default(null),
317
+ // The keys of MCP_ACCESS_LEVELS, defaulting to the narrowest: a payload
318
+ // that names no level (a stale form, a hand-crafted POST) mints the
319
+ // read-only token, never the wide one
320
+ access: Joi.string()
321
+ .valid(...Object.keys(MCP_ACCESS_LEVELS))
322
+ .default('read')
323
+ })
324
+ )
325
+ }
326
+ }
327
+ });
328
+ }
329
+
330
+ module.exports = init;
@@ -18,7 +18,7 @@ const { Account } = require('../account');
18
18
  const { oauth2Apps, OAUTH_PROVIDERS, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
19
19
  const { verifyOAuth2App } = require('../oauth/verify-app');
20
20
  const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema } = require('../schemas');
21
- const { throwAsBoom } = require('./route-helpers');
21
+ const { throwAsBoom, adminUrl } = require('./route-helpers');
22
22
 
23
23
  const { DEFAULT_PAGE_SIZE } = consts;
24
24
 
@@ -469,7 +469,7 @@ function init(args) {
469
469
  } catch (err) {
470
470
  await request.flash({ type: 'danger', message: `Couldn't delete OAuth2 app. Try again.` });
471
471
  request.logger.error({ msg: 'Failed to delete OAuth2 application', err, app: request.payload.app, remoteAddress: request.app.ip });
472
- return h.redirect(`/admin/config/oauth/app/${request.payload.app}`);
472
+ return h.redirect(adminUrl`/admin/config/oauth/app/${request.payload.app}`);
473
473
  }
474
474
  },
475
475
  options: {
@@ -533,11 +533,11 @@ function init(args) {
533
533
 
534
534
  await request.flash({ type: 'info', message: `Account ${result.state === 'existing' ? 'updated' : 'added'}` });
535
535
 
536
- return h.redirect(`/admin/accounts/${result.account}`);
536
+ return h.redirect(adminUrl`/admin/accounts/${result.account}`);
537
537
  } catch (err) {
538
538
  request.logger.error({ msg: 'Failed to register service account', err, app: appId, remoteAddress: request.app.ip });
539
539
  await request.flash({ type: 'danger', message: `Failed to add account${err.message ? `: ${err.message}` : ''}` });
540
- return h.redirect(`/admin/config/oauth/app/${appId}`);
540
+ return h.redirect(adminUrl`/admin/config/oauth/app/${appId}`);
541
541
  }
542
542
  },
543
543
  options: {
@@ -551,7 +551,7 @@ function init(args) {
551
551
  async failAction(request, h, err) {
552
552
  request.logger.debug({ msg: 'Failed to register service account', err, app: request.params.app });
553
553
  await request.flash({ type: 'danger', message: `Failed to add account. Provide a valid email address.` });
554
- return h.redirect(`/admin/config/oauth/app/${request.params.app}`).takeover();
554
+ return h.redirect(adminUrl`/admin/config/oauth/app/${request.params.app}`).takeover();
555
555
  },
556
556
 
557
557
  params: Joi.object({
@@ -715,7 +715,7 @@ function init(args) {
715
715
  }
716
716
 
717
717
  await request.flash({ type: 'success', message: `OAuth2 app created` });
718
- return h.redirect(`/admin/config/oauth/app/${oauth2App.id}`);
718
+ return h.redirect(adminUrl`/admin/config/oauth/app/${oauth2App.id}`);
719
719
  } catch (err) {
720
720
  await request.flash({ type: 'danger', message: `Couldn't register OAuth2 app. Try again.` });
721
721
  request.logger.error({ msg: 'Failed to register OAuth2 app', err });
@@ -974,7 +974,7 @@ function init(args) {
974
974
  }
975
975
 
976
976
  await request.flash({ type: 'success', message: `OAuth2 app saved` });
977
- return h.redirect(`/admin/config/oauth/app/${oauth2App.id}`);
977
+ return h.redirect(adminUrl`/admin/config/oauth/app/${oauth2App.id}`);
978
978
  } catch (err) {
979
979
  await request.flash({ type: 'danger', message: `Couldn't save OAuth2 app. Try again.` });
980
980
  request.logger.error({ msg: 'Failed to update OAuth2 app', app: request.payload.app, err });
@@ -18,6 +18,8 @@ const psl = require('psl');
18
18
 
19
19
  const settings = require('../settings');
20
20
  const { redis } = require('../db');
21
+ const { toolGrants } = require('../mcp/tools');
22
+ const { Account, accountsExist, accountSummary } = require('../account');
21
23
  const { REDIS_PREFIX, DEFAULT_PAGE_SIZE } = require('../consts');
22
24
  const { oauth2ProviderData } = require('../oauth2-apps');
23
25
  const exampleDocumentsPayloads = require('../payload-examples-documents.json');
@@ -381,6 +383,14 @@ function identityErrorView(request, h, { expectedEmail, actualEmail, retryUrl })
381
383
  // `new URL(path, base)` convention the route modules already use); data is a listing
382
384
  // response carrying zero-based `page` and total `pages`; query is the validated request
383
385
  // query whose `pageSize` is appended to the URLs only when it differs from the default.
386
+ // Tagged template for redirect paths that interpolate an identifier: percent-encodes every
387
+ // interpolated value, so a raw ID cannot break the path or turn into a URL fragment whichever
388
+ // call site forgets. The JS-layer counterpart of the `urlpart` Handlebars helper that closed
389
+ // the same bug class in the templates - use this instead of hand-placing encodeURIComponent.
390
+ function adminUrl(strings, ...values) {
391
+ return strings.reduce((url, part, i) => url + part + (i < values.length ? encodeURIComponent(values[i]) : ''), '');
392
+ }
393
+
384
394
  function buildPagingView(basePath, data, query) {
385
395
  const getPagingUrl = page => {
386
396
  let url = new URL(basePath, 'http://localhost');
@@ -409,8 +419,139 @@ function buildPagingView(basePath, data, query) {
409
419
  };
410
420
  }
411
421
 
422
+ /**
423
+ * Resolves which of the accounts a listing refers to still exist.
424
+ *
425
+ * Rows outlive the account they name: deleting an account leaves its suppression-list entries in
426
+ * place and leaves its access tokens valid. A row naming a dead account must not be rendered as a
427
+ * link to a page that 404s, so the listings ask this before rendering. One probe per distinct
428
+ * account rather than per row, all of them in one round trip, and each is a single HEXISTS - no
429
+ * account load, nothing decrypted.
430
+ *
431
+ * @param {Array} entries - listing rows, each optionally carrying an `account`
432
+ * @returns {Promise<Map<String, Boolean>>} keyed by account ID; rows without one are absent
433
+ */
434
+ async function resolveKnownAccounts(entries) {
435
+ return accountsExist(redis, Array.from(new Set(entries.map(entry => entry.account).filter(Boolean))));
436
+ }
437
+
438
+ // How many accounts one suggestion request answers with. The picker is a search box, not a
439
+ // listing: past a screenful the answer to "I cannot see mine" is to type more of it, and a longer
440
+ // list only makes the response slower to fetch and harder to scan.
441
+ const ACCOUNT_SUGGESTION_LIMIT = 10;
442
+
443
+ /**
444
+ * One account as the account picker renders it.
445
+ *
446
+ * The picker shows the same three things everywhere it appears - who the account belongs to, which
447
+ * address it syncs, and whether it is connected - so the shape is built once here rather than by
448
+ * each page that feeds it. `state` is the badge descriptor the account listings already use, so a
449
+ * suggestion row cannot describe a connection differently from the page it was picked on.
450
+ *
451
+ * @param {Object} entry - an account record, from listAccounts() or accountSummary()
452
+ * @returns {Object} `{ account, name, email, state: { type, name } }`
453
+ */
454
+ function accountPickerEntry(entry) {
455
+ // No lastErrorState is passed on purpose: the picker has room for a state, not for the reason
456
+ // behind it, and that reason is the only thing the label needs translating for
457
+ const badge = accountStateLabel(entry.state, {});
458
+
459
+ return {
460
+ account: entry.account,
461
+ name: entry.name || '',
462
+ email: entry.email || '',
463
+ state: { type: badge.type, name: badge.name }
464
+ };
465
+ }
466
+
467
+ /**
468
+ * Account suggestions for the account picker, shared by every page that carries one.
469
+ *
470
+ * Search rather than a preloaded list: an instance can hold far more accounts than a page could
471
+ * usefully ship, and the id a person is looking for is one they can start typing. A listing
472
+ * failure costs the suggestions and nothing else - the picker still accepts a typed id, and the
473
+ * form that submits it resolves it server-side either way.
474
+ *
475
+ * @param {Function} call - RPC helper for talking to the main thread
476
+ * @param {Object} [opts]
477
+ * @param {String} [opts.query] - search string matched against id, name and address
478
+ * @param {Object} [opts.logger] - request logger for the failure branch
479
+ * @returns {Promise<{accounts: Array, total: Number}>}
480
+ */
481
+ async function accountSuggestions(call, opts) {
482
+ const { query, logger } = opts || {};
483
+
484
+ try {
485
+ const listing = await new Account({ redis, call }).listAccounts(false, query, 0, ACCOUNT_SUGGESTION_LIMIT);
486
+ return {
487
+ accounts: (listing.accounts || []).map(accountPickerEntry),
488
+ total: listing.total || 0
489
+ };
490
+ } catch (err) {
491
+ if (logger) {
492
+ logger.error({ msg: 'Failed to list account suggestions', err });
493
+ }
494
+ return { accounts: [], total: 0 };
495
+ }
496
+ }
497
+
498
+ /**
499
+ * The picker entry for an account a form already holds, or null when it names none.
500
+ *
501
+ * A form re-rendered after a validation error starts with an id rather than with a choice, and so
502
+ * does the token form opened from an account's own token list. Without this the picker would have
503
+ * to show the raw id back as if the person had never picked anything.
504
+ *
505
+ * @param {String} account - Account ID, possibly empty or naming a deleted account
506
+ * @param {Object} [logger] - request logger for the failure branch
507
+ * @returns {Promise<Object|null>}
508
+ */
509
+ async function accountPickerSelection(account, logger) {
510
+ if (!account) {
511
+ return null;
512
+ }
513
+
514
+ try {
515
+ const summary = await accountSummary(redis, account);
516
+ return summary ? accountPickerEntry(summary) : null;
517
+ } catch (err) {
518
+ if (logger) {
519
+ logger.error({ msg: 'Failed to resolve the selected account', account, err });
520
+ }
521
+ return null;
522
+ }
523
+ }
524
+
525
+ /**
526
+ * The MCP tool grants for a page that shows the tool count, or an empty list if the registry
527
+ * cannot be built.
528
+ *
529
+ * The three pages that mint an mcp-scoped token all want this, and all want it the same way: the
530
+ * count is a nicety and the page's real job is not, so a registry failure costs the count and
531
+ * nothing else. Wrapped once here rather than three times, so the pages cannot disagree about
532
+ * that - one of them letting the failure through would take down a token form or a consent
533
+ * decision over a line of text.
534
+ *
535
+ * @param {Object} server - the Hapi server
536
+ * @param {Object} logger - where to report a failure (a request logger, or the server's)
537
+ * @returns {Array} toolGrants() output, or []
538
+ */
539
+ function mcpToolGrants(server, logger) {
540
+ try {
541
+ return toolGrants(server);
542
+ } catch (err) {
543
+ logger.error({ msg: 'Failed to derive the MCP tool catalog', err });
544
+ return [];
545
+ }
546
+ }
547
+
412
548
  module.exports = {
413
549
  jsonErrorPayload,
550
+ mcpToolGrants,
551
+ resolveKnownAccounts,
552
+ accountSuggestions,
553
+ accountPickerEntry,
554
+ accountPickerSelection,
414
555
  identityErrorView,
415
556
  OPEN_AI_MODELS,
416
557
  cachedTemplates,
@@ -424,5 +565,6 @@ module.exports = {
424
565
  throwAsBoom,
425
566
  isClientError,
426
567
  authAwareLevel,
427
- buildPagingView
568
+ buildPagingView,
569
+ adminUrl
428
570
  };
@@ -7,12 +7,10 @@
7
7
  // removing the last address drops the list again (see lib/lua/ee-list-remove.lua).
8
8
 
9
9
  const Joi = require('joi');
10
- const { redis } = require('../db');
11
10
  const { lists } = require('../lists');
12
11
  const settings = require('../settings');
13
- const { accountExists } = require('../account');
14
12
  const { blocklistListIdSchema } = require('../schemas');
15
- const { buildPagingView } = require('./route-helpers');
13
+ const { buildPagingView, resolveKnownAccounts, adminUrl } = require('./route-helpers');
16
14
  const { buildUnsubscribeUrl, getServiceSecret } = require('../tools');
17
15
  const consts = require('../consts');
18
16
 
@@ -77,7 +75,15 @@ function init(args) {
77
75
  try {
78
76
  data = await lists.listContent(listId, request.query.page - 1, request.query.pageSize);
79
77
  } catch (err) {
80
- await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
78
+ // Only a missing list reads as one. Anything else (say, a dropped Redis
79
+ // connection) is a transient failure of an intact list - reporting it as
80
+ // "not found" tells the operator their unsubscribe data is gone when it is not.
81
+ if (err.output && err.output.statusCode === 404) {
82
+ await request.flash({ type: 'danger', message: `Requested suppression list was not found` });
83
+ } else {
84
+ request.logger.error({ msg: 'Failed to load suppression list', listId, err });
85
+ await request.flash({ type: 'danger', message: `Failed to load the suppression list. Try again.` });
86
+ }
81
87
  return h.redirect('/admin/suppression-lists');
82
88
  }
83
89
 
@@ -87,8 +93,7 @@ function init(args) {
87
93
  // account, so entries without one (or whose account is gone) get no link.
88
94
  let [serviceUrl, serviceSecret] = await Promise.all([settings.get('serviceUrl'), getServiceSecret()]);
89
95
 
90
- let uniqueAccounts = Array.from(new Set(data.addresses.map(entry => entry.account).filter(Boolean)));
91
- let knownAccounts = new Map(await Promise.all(uniqueAccounts.map(async account => [account, await accountExists(redis, account)])));
96
+ let knownAccounts = await resolveKnownAccounts(data.addresses);
92
97
 
93
98
  for (let entry of data.addresses) {
94
99
  if (!entry.account || !knownAccounts.get(entry.account)) {
@@ -161,7 +166,7 @@ function init(args) {
161
166
  await request.flash({ type: 'info', message: `${recipient} was already listed; the entry was updated` });
162
167
  }
163
168
 
164
- return h.redirect(`/admin/suppression-lists/list/${listId}`);
169
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
165
170
  } catch (err) {
166
171
  await request.flash({ type: 'danger', message: `Couldn't add the address. Try again.` });
167
172
  request.logger.error({ msg: 'Failed to add suppression list entry', err, listId, remoteAddress: request.app.ip });
@@ -212,11 +217,11 @@ function init(args) {
212
217
  await request.flash({ type: 'info', message: `Removed ${recipient} from the suppression list` });
213
218
  }
214
219
 
215
- return h.redirect(`/admin/suppression-lists/list/${listId}`);
220
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
216
221
  } catch (err) {
217
222
  await request.flash({ type: 'danger', message: `Couldn't remove the address. Try again.` });
218
223
  request.logger.error({ msg: 'Failed to remove suppression list entry', err, listId, remoteAddress: request.app.ip });
219
- return h.redirect(`/admin/suppression-lists/list/${listId}`);
224
+ return h.redirect(adminUrl`/admin/suppression-lists/list/${listId}`);
220
225
  }
221
226
  },
222
227
  options: {
@@ -0,0 +1,42 @@
1
+ 'use strict';
2
+
3
+ const libmime = require('libmime');
4
+ const { UNSAFE_KEYS } = require('./unsafe-key');
5
+
6
+ /**
7
+ * Parses a header block into a map of lowercased header name to array of values.
8
+ *
9
+ * Wraps libmime.decodeHeaders() to drop names that collide with Object.prototype. Header names
10
+ * come from the message, so any sender can use one, and libmime returns them as real own
11
+ * properties. Neither names a real header, so there is nothing to preserve by keeping them:
12
+ *
13
+ * - an own "__proto__" key is the one thing lib/msgpack.js refuses to decode, so a map carrying it
14
+ * encodes into webhook logs and message payloads that can never be read back, and it hands
15
+ * anything that later copies the map with `obj[key] =` or Object.assign a prototype swap
16
+ * - "constructor" is inert on its own, but lib/utils/header-map.js cannot represent it, so keeping
17
+ * it would describe the same message differently depending on the transport that fetched it
18
+ *
19
+ * Dropping them here rather than at each consumer keeps every parsed header block on one
20
+ * contract: lib/email-client/imap/mailbox.js and lib/bounce-detect.js return these maps to callers
21
+ * verbatim, and lib/arf-detect.js copies them key by key into a published report. It is not the
22
+ * last word on either name though - a consumer that rebuilds a key from the name has to check
23
+ * again, see isUnsafeKey() in lib/utils/unsafe-key.js.
24
+ *
25
+ * @param {String|Buffer} headers - Raw header block
26
+ * @returns {Object} Map of lowercased header name to array of values
27
+ */
28
+ function decodeHeaders(headers) {
29
+ let parsed = libmime.decodeHeaders(headers);
30
+
31
+ for (let name of UNSAFE_KEYS) {
32
+ // Probing first is not needed for correctness, deleting a missing key is a no-op, but it is
33
+ // the cheaper no-op and almost every message takes this path
34
+ if (Object.hasOwn(parsed, name)) {
35
+ delete parsed[name];
36
+ }
37
+ }
38
+
39
+ return parsed;
40
+ }
41
+
42
+ module.exports = { decodeHeaders };