emailengine-app 2.84.1 → 2.85.0

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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
package/lib/mcp/tools.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // The MCP tool registry and executor.
4
4
  //
5
5
  // Tools are not defined here. A route opts in by carrying a `plugins.mcp` block
6
- // ({ name, title, description, keep?/omit?, force?, bounds?, binary?, tail?, resourceUriTemplate? }),
6
+ // ({ name, title, description, keep?/omit?, force?, bounds?, rename?, binary?, tail?, resourceUriTemplate? }),
7
7
  // and this module derives everything else from what the route already declares: the input schema from
8
8
  // its joi validation schemas, the behavior
9
9
  // annotations from routeGrant() - the same source /swagger.json publishes as x-ee-action and
@@ -55,6 +55,7 @@ const MCP_OPTION_KEYS = new Set([
55
55
  'omit',
56
56
  'force',
57
57
  'bounds',
58
+ 'rename',
58
59
  'binary',
59
60
  'tail',
60
61
  'resourceUriTemplate',
@@ -144,6 +145,29 @@ function buildToolRegistry(routes) {
144
145
  const query = convertSource(validate.query);
145
146
  const payload = convertSource(validate.payload);
146
147
 
148
+ // Tool argument names for route arguments that cannot keep their own. A route may take the
149
+ // same name from two sources - the bulk move reads its source folder from the query and
150
+ // its target from the payload, both as `path` - and one tool argument cannot be both.
151
+ // `{ query: { path: 'source' } }` offers the query `path` as `source` and sends it back
152
+ // under its own name. Every other option (keep, omit, force, bounds) names the tool
153
+ // argument. Path parameters cannot be renamed: the dispatch fills the route template by
154
+ // their names.
155
+ const renames = new Map();
156
+ for (const [sourceName, mapping] of Object.entries(options.rename || {})) {
157
+ const source = { query, payload }[sourceName];
158
+ if (!source) {
159
+ throw new Error(`MCP tool ${options.name}: cannot rename arguments of ${sourceName}, only of query and payload`);
160
+ }
161
+ for (const [key, toolName] of Object.entries(mapping || {})) {
162
+ if (!(key in source.properties)) {
163
+ throw new Error(`MCP tool ${options.name}: renamed argument ${key} is not a ${sourceName} argument of ${route.method} ${route.path}`);
164
+ }
165
+ renames.set(`${sourceName}:${key}`, toolName);
166
+ }
167
+ }
168
+ // Tool argument name -> the name the route takes it under, for the renamed ones only
169
+ const wireNames = new Map();
170
+
147
171
  const properties = {};
148
172
  const required = [];
149
173
  const sources = new Map();
@@ -160,7 +184,11 @@ function buildToolRegistry(routes) {
160
184
  ['query', query],
161
185
  ['payload', payload]
162
186
  ]) {
163
- for (const [key, propertySchema] of Object.entries(source.properties)) {
187
+ for (const [routeKey, propertySchema] of Object.entries(source.properties)) {
188
+ const key = renames.get(`${sourceName}:${routeKey}`) || routeKey;
189
+ if (key !== routeKey) {
190
+ wireNames.set(key, routeKey);
191
+ }
164
192
  if (argSources.has(key)) {
165
193
  // A path parameter and a payload field sharing a name cannot both be a single
166
194
  // tool argument. None of the wrapped routes do this; refuse at build time so
@@ -170,7 +198,7 @@ function buildToolRegistry(routes) {
170
198
  argSources.set(key, sourceName);
171
199
  if (keep ? !keep.has(key) : omit.has(key)) {
172
200
  hidden.add(key);
173
- if (source.required.includes(key)) {
201
+ if (source.required.includes(routeKey)) {
174
202
  // A required argument the tool does not offer has to be supplied by
175
203
  // `force`, or every call dies on the same joi 400 with nothing the model
176
204
  // can do about it
@@ -180,7 +208,7 @@ function buildToolRegistry(routes) {
180
208
  }
181
209
  sources.set(key, sourceName);
182
210
  properties[key] = propertySchema;
183
- if (source.required.includes(key)) {
211
+ if (source.required.includes(routeKey)) {
184
212
  required.push(key);
185
213
  }
186
214
  }
@@ -290,6 +318,7 @@ function buildToolRegistry(routes) {
290
318
  forcedSources,
291
319
  forcedValues,
292
320
  bounds,
321
+ wireNames,
293
322
  // The operation this tool resolves to, for consumers that answer per-credential
294
323
  // questions about the catalog: tools/list uses it to show a permission-narrowed
295
324
  // token only the tools its record can actually call
@@ -386,7 +415,7 @@ function buildPath(template, args, sources) {
386
415
  });
387
416
  }
388
417
 
389
- function buildQuery(args, sources) {
418
+ function buildQuery(args, sources, wireNames) {
390
419
  const query = new URLSearchParams();
391
420
 
392
421
  for (const [key, sourceName] of sources) {
@@ -394,7 +423,7 @@ function buildQuery(args, sources) {
394
423
  continue;
395
424
  }
396
425
  for (const value of [].concat(args[key])) {
397
- query.append(key, String(value));
426
+ query.append(wireNames.get(key) || key, String(value));
398
427
  }
399
428
  }
400
429
 
@@ -527,7 +556,7 @@ async function callTool({ server, tool, args, request }) {
527
556
  let hasPayload = false;
528
557
  for (const [key, sourceName] of effective.sources) {
529
558
  if (sourceName === 'payload' && effective.args[key] !== undefined) {
530
- payload[key] = effective.args[key];
559
+ payload[tool.wireNames.get(key) || key] = effective.args[key];
531
560
  hasPayload = true;
532
561
  }
533
562
  }
@@ -536,7 +565,7 @@ async function callTool({ server, tool, args, request }) {
536
565
  server,
537
566
  request,
538
567
  method: tool.method,
539
- url: buildPath(tool.path, effective.args, effective.sources) + buildQuery(effective.args, effective.sources),
568
+ url: buildPath(tool.path, effective.args, effective.sources) + buildQuery(effective.args, effective.sources, tool.wireNames),
540
569
  payload: hasPayload ? payload : undefined
541
570
  });
542
571
 
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ // Whether an attachment's content belongs in a messageNew payload under the notifyAttachmentSize
4
+ // setting. Both processNew() implementations ask it before downloading an attachment and
5
+ // formatPayload() asks it again for content loaded on other paths, such as inline images the
6
+ // web-safe embed fetched, so what is downloaded and what is kept cannot disagree. An attachment is
7
+ // measured by the encoded size the message structure reports, and only content without one by its
8
+ // decoded size.
9
+ function withinNotifyAttachmentSize(attachment, notifyAttachmentSize) {
10
+ if (!notifyAttachmentSize) {
11
+ return true;
12
+ }
13
+ let size = attachment.encodedSize || (attachment.content ? (attachment.content.length / 4) * 3 : 0);
14
+ return size <= notifyAttachmentSize;
15
+ }
16
+
17
+ module.exports = { withinNotifyAttachmentSize };
@@ -153,7 +153,9 @@ function extractFromFormat(rawText, format) {
153
153
  try {
154
154
  parsed = JSON.parse(rawText);
155
155
  } catch (err) {
156
- throw makeError(`Subject token source did not return valid JSON: ${err.message}`, 'ESubjectTokenRead');
156
+ // Without the parser's message: V8 quotes the offending text in it, and this string reaches
157
+ // the verify report, so it would hand back the first characters of whatever was read
158
+ throw makeError('Subject token source did not return valid JSON', 'ESubjectTokenRead', null, { cause: err });
157
159
  }
158
160
  let field = format.subject_token_field_name;
159
161
  let value = parsed && typeof parsed === 'object' ? parsed[field] : undefined;
@@ -1,7 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  const packageData = require('../../package.json');
4
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
4
+ const {
5
+ formatPartialSecretKey,
6
+ formatSecretHint,
7
+ formatOAuthRequestBody,
8
+ formatOAuthResponse,
9
+ httpAgent,
10
+ formatTokenError,
11
+ parseRetryAfter
12
+ } = require('../tools');
5
13
  const crypto = require('crypto');
6
14
 
7
15
  const { fetch: fetchCmd } = require('undici');
@@ -106,7 +114,8 @@ const checkForFlags = (err, isPrincipal) => {
106
114
  continue;
107
115
  }
108
116
  activationLink = (detail.links.find(link => /Google developers console API activation/.test(link.description) && link.url) || {}).url;
109
- if (activationLink) {
117
+ // rendered as a link in the admin UI, so only an https URL is taken from the response
118
+ if (activationLink && /^https:\/\//i.test(activationLink)) {
110
119
  return {
111
120
  message: 'Please enable the Gmail API in your Google Developer Console to use this feature.',
112
121
  code: 'GMAIL_API_NOT_ENABLED',
@@ -193,43 +202,6 @@ const checkForUserFlags = err => {
193
202
  return false;
194
203
  };
195
204
 
196
- const formatFetchBody = (searchParams, logRaw) => {
197
- let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
198
- let data = Object.fromEntries(entries);
199
-
200
- if (logRaw) {
201
- return data;
202
- }
203
-
204
- for (let key of ['refresh_token', 'client_secret', 'code']) {
205
- if (data[key]) {
206
- data[key] = formatPartialSecretKey(data[key]);
207
- }
208
- }
209
-
210
- if (data.assertion) {
211
- let [payload, signature] = data.assertion.toString().split('.');
212
- data.assertion = [payload, formatPartialSecretKey(signature)].join('.');
213
- }
214
-
215
- return data;
216
- };
217
-
218
- const formatFetchResponse = (responseObj, logRaw) => {
219
- if (!responseObj || typeof responseObj !== 'object') {
220
- return responseObj;
221
- }
222
-
223
- let data = structuredClone(responseObj);
224
- for (let key of ['access_token', 'refresh_token', 'id_token']) {
225
- if (data[key]) {
226
- data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
227
- }
228
- }
229
-
230
- return data;
231
- };
232
-
233
205
  /**
234
206
  * The Google Workspace or Cloud organization domain an ID token belongs to, or null.
235
207
  *
@@ -454,8 +426,8 @@ class GmailOauth {
454
426
  url: requestUrl,
455
427
  success: !!res.ok,
456
428
  status: res.status,
457
- request: formatFetchBody(tokenRequest.body, this.logRaw),
458
- response: formatFetchResponse(responseJson, this.logRaw)
429
+ request: formatOAuthRequestBody(tokenRequest.body),
430
+ response: formatOAuthResponse(responseJson)
459
431
  });
460
432
  }
461
433
 
@@ -481,8 +453,9 @@ class GmailOauth {
481
453
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
482
454
 
483
455
  if (this.clientSecret && EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
484
- // key might have been invalidated or renewed
485
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
456
+ // the key might have been invalidated or renewed. On the error rather than in
457
+ // tokenRequest, which the API error payload and the webhook carry verbatim
458
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
486
459
  }
487
460
 
488
461
  let flag = checkForFlags(err.tokenRequest.response);
@@ -578,8 +551,8 @@ class GmailOauth {
578
551
  url: requestUrl,
579
552
  success: !!res.ok,
580
553
  status: res.status,
581
- request: formatFetchBody(url.searchParams, this.logRaw),
582
- response: formatFetchResponse(responseJson, this.logRaw)
554
+ request: formatOAuthRequestBody(url.searchParams),
555
+ response: formatOAuthResponse(responseJson)
583
556
  });
584
557
  }
585
558
 
@@ -605,8 +578,8 @@ class GmailOauth {
605
578
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
606
579
 
607
580
  if (this.clientSecret && EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
608
- // key might have been invalidated or renewed
609
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
581
+ // the key might have been invalidated or renewed, see getToken()
582
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
610
583
  }
611
584
 
612
585
  let flag = checkForFlags(err.tokenRequest.response, opts.isPrincipal);
@@ -684,7 +657,7 @@ class GmailOauth {
684
657
  fn: 'refreshFromMetadataServer',
685
658
  provider: this.provider,
686
659
  success: true,
687
- response: formatFetchResponse(response, this.logRaw)
660
+ response: formatOAuthResponse(response)
688
661
  });
689
662
  }
690
663
 
@@ -4,7 +4,7 @@ const packageData = require('../../package.json');
4
4
  const { fetch: fetchCmd } = require('undici');
5
5
  const { promoteCauseCode } = require('../network-errors');
6
6
  const { fetchTokenRequest } = require('./token-fetch');
7
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
7
+ const { formatPartialSecretKey, formatOAuthRequestBody, formatOAuthResponse, httpAgent, formatTokenError } = require('../tools');
8
8
 
9
9
  const MAIL_RU_SCOPES = ['userinfo', 'mail.imap'];
10
10
 
@@ -19,38 +19,6 @@ const checkForFlags = err => {
19
19
  return false;
20
20
  };
21
21
 
22
- const formatFetchBody = (searchParams, logRaw) => {
23
- let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
24
- let data = Object.fromEntries(entries);
25
-
26
- if (logRaw) {
27
- return data;
28
- }
29
-
30
- for (let key of ['refresh_token', 'client_secret', 'code']) {
31
- if (data[key]) {
32
- data[key] = formatPartialSecretKey(data[key]);
33
- }
34
- }
35
-
36
- return data;
37
- };
38
-
39
- const formatFetchResponse = (responseObj, logRaw) => {
40
- if (!responseObj || typeof responseObj !== 'object') {
41
- return responseObj;
42
- }
43
-
44
- let data = structuredClone(responseObj);
45
- for (let key of ['access_token', 'refresh_token', 'id_token']) {
46
- if (data[key]) {
47
- data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
48
- }
49
- }
50
-
51
- return data;
52
- };
53
-
54
22
  class MailRuOauth {
55
23
  constructor(opts) {
56
24
  // The network route of the account this client acts for (see getAccountHttpRoute()). Every
@@ -62,7 +30,6 @@ class MailRuOauth {
62
30
  this.clientSecret = opts.clientSecret;
63
31
  this.redirectUrl = opts.redirectUrl;
64
32
 
65
- this.logRaw = opts.logRaw;
66
33
  this.logger = opts.logger;
67
34
 
68
35
  this.provider = 'mailRu';
@@ -148,8 +115,8 @@ class MailRuOauth {
148
115
  url: requestUrl,
149
116
  success: !!res.ok,
150
117
  status: res.status,
151
- request: formatFetchBody(tokenRequest.body, this.logRaw),
152
- response: formatFetchResponse(responseJson, this.logRaw)
118
+ request: formatOAuthRequestBody(tokenRequest.body),
119
+ response: formatOAuthResponse(responseJson)
153
120
  });
154
121
  }
155
122
 
@@ -236,8 +203,8 @@ class MailRuOauth {
236
203
  url: requestUrl,
237
204
  success: !!res.ok,
238
205
  status: res.status,
239
- request: formatFetchBody(url.searchParams, this.logRaw),
240
- response: formatFetchResponse(responseJson, this.logRaw)
206
+ request: formatOAuthRequestBody(url.searchParams),
207
+ response: formatOAuthResponse(responseJson)
241
208
  });
242
209
  }
243
210
 
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ // Decides which mailbox a Microsoft account setup binds once the OAuth2 callback knows who signed
4
+ // in. Three cases, checked in this order:
5
+ //
6
+ // 1. `oauth2.auth.delegatedUser` names a shared mailbox. The signed-in user authenticates and the
7
+ // named mailbox is the one accessed; the account's address defaults to that mailbox when the
8
+ // setup named none.
9
+ // 2. Legacy form: `delegated: true` plus an `email` that differs from the signed-in address. The
10
+ // address is the shared mailbox and it is kept.
11
+ // 3. Anything else is the signed-in user's own mailbox, and the account takes their address.
12
+ //
13
+ // Pure, so the precedence can be tested without driving a whole callback.
14
+
15
+ /**
16
+ * @param {Object} accountData - The pending account (`email`, `delegated`, `oauth2.auth.delegatedUser`)
17
+ * @param {Object} userInfo - The resolved identity of the signed-in user (`email`)
18
+ * @returns {{ email: (string|undefined), delegatedUser: (string|undefined) }} The account address,
19
+ * and the mailbox to access on the signed-in user's behalf when it is not their own
20
+ */
21
+ function resolveOutlookMailbox(accountData, userInfo) {
22
+ const delegatedUser = accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser;
23
+
24
+ if (delegatedUser) {
25
+ return { email: accountData.email || delegatedUser, delegatedUser };
26
+ }
27
+
28
+ if (accountData.delegated && accountData.email && accountData.email !== userInfo.email) {
29
+ return { email: accountData.email, delegatedUser: accountData.email };
30
+ }
31
+
32
+ return { email: userInfo.email, delegatedUser: undefined };
33
+ }
34
+
35
+ module.exports = { resolveOutlookMailbox };
@@ -1,7 +1,15 @@
1
1
  'use strict';
2
2
 
3
3
  const packageData = require('../../package.json');
4
- const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
4
+ const {
5
+ formatPartialSecretKey,
6
+ formatSecretHint,
7
+ formatOAuthRequestBody,
8
+ formatOAuthResponse,
9
+ httpAgent,
10
+ formatTokenError,
11
+ parseRetryAfter
12
+ } = require('../tools');
5
13
 
6
14
  const { fetch: fetchCmd } = require('undici');
7
15
  const { promoteCauseCode } = require('../network-errors');
@@ -128,37 +136,9 @@ const checkForUserFlags = err => {
128
136
  return false;
129
137
  };
130
138
 
131
- const formatFetchBody = (searchParams, logRaw) => {
132
- let entries = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
133
- let data = Object.fromEntries(entries);
134
-
135
- if (logRaw) {
136
- return data;
137
- }
138
-
139
- for (let key of ['refresh_token', 'client_secret', 'code']) {
140
- if (data[key]) {
141
- data[key] = formatPartialSecretKey(data[key]);
142
- }
143
- }
144
-
145
- return data;
146
- };
147
-
148
- const formatFetchResponse = (responseObj, logRaw) => {
149
- if (!responseObj || typeof responseObj !== 'object') {
150
- return responseObj;
151
- }
152
-
153
- let data = structuredClone(responseObj);
154
- for (let key of ['access_token', 'refresh_token', 'id_token']) {
155
- if (data[key]) {
156
- data[key] = logRaw ? data[key] : formatPartialSecretKey(data[key]);
157
- }
158
- }
159
-
160
- return data;
161
- };
139
+ // The secrets are masked whether or not raw logging is on: EENGINE_LOG_RAW is for the protocol
140
+ // traffic, and the application's client secret and the refresh tokens of every account are not
141
+ // something a debug switch should put in the log in full
162
142
 
163
143
  class OutlookOauth {
164
144
  constructor(opts) {
@@ -177,7 +157,6 @@ class OutlookOauth {
177
157
  this.authority = opts.authority;
178
158
  this.redirectUrl = opts.redirectUrl;
179
159
 
180
- this.logRaw = opts.logRaw;
181
160
  this.logger = opts.logger;
182
161
 
183
162
  this.useClientCredentials = !!opts.useClientCredentials;
@@ -307,8 +286,8 @@ class OutlookOauth {
307
286
  url: requestUrl,
308
287
  success: !!res.ok,
309
288
  status: res.status,
310
- request: formatFetchBody(tokenRequest.body, this.logRaw),
311
- response: formatFetchResponse(responseJson, this.logRaw)
289
+ request: formatOAuthRequestBody(tokenRequest.body),
290
+ response: formatOAuthResponse(responseJson)
312
291
  });
313
292
  }
314
293
 
@@ -332,8 +311,9 @@ class OutlookOauth {
332
311
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
333
312
 
334
313
  if (EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
335
- // key might have been invalidated or renewed
336
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
314
+ // the key might have been invalidated or renewed. On the error rather than in
315
+ // tokenRequest, which the API error payload and the webhook carry verbatim
316
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
337
317
  }
338
318
 
339
319
  let flag = checkForFlags(err.tokenRequest.response);
@@ -412,8 +392,8 @@ class OutlookOauth {
412
392
  url: requestUrl,
413
393
  success: !!res.ok,
414
394
  status: res.status,
415
- request: formatFetchBody(url.searchParams, this.logRaw),
416
- response: formatFetchResponse(responseJson, this.logRaw)
395
+ request: formatOAuthRequestBody(url.searchParams),
396
+ response: formatOAuthResponse(responseJson)
417
397
  });
418
398
  }
419
399
 
@@ -436,8 +416,9 @@ class OutlookOauth {
436
416
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
437
417
 
438
418
  if (EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
439
- // key might have been invalidated or renewed
440
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
419
+ // the key might have been invalidated or renewed. On the error rather than in
420
+ // tokenRequest, which the API error payload and the webhook carry verbatim
421
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
441
422
  }
442
423
 
443
424
  let flag = checkForFlags(err.tokenRequest.response);
@@ -507,8 +488,8 @@ class OutlookOauth {
507
488
  url: requestUrl,
508
489
  success: !!res.ok,
509
490
  status: res.status,
510
- request: formatFetchBody(url.searchParams, this.logRaw),
511
- response: formatFetchResponse(responseJson, this.logRaw)
491
+ request: formatOAuthRequestBody(url.searchParams),
492
+ response: formatOAuthResponse(responseJson)
512
493
  });
513
494
  }
514
495
 
@@ -531,7 +512,8 @@ class OutlookOauth {
531
512
  err.tokenRequest.response = responseJson || { error: 'Failed to parse response' };
532
513
 
533
514
  if (EXPOSE_PARTIAL_SECRET_KEY_REGEX.test(err.tokenRequest.response?.error_description)) {
534
- err.tokenRequest.clientSecret = formatPartialSecretKey(this.clientSecret);
515
+ // see getToken()
516
+ err.clientSecretHint = formatSecretHint(this.clientSecret);
535
517
  }
536
518
 
537
519
  let flag = checkForFlags(err.tokenRequest.response);
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // The single-use nonce of a hosted account setup, and the OAuth2 `state` that carries it to the
4
+ // provider and back (`account:add:<nonce>`). A nonce is NONCE_BYTES random bytes, base64url encoded
5
+ // (21-22 characters); base64 (+, / and = padding) is accepted too, for nonces issued before the
6
+ // switch to base64url that may still be cached in a pending setup.
7
+
8
+ const OAUTH_NONCE_PATTERN = /^[A-Za-z0-9_\-+/]{21,22}={0,2}$/;
9
+
10
+ const OAUTH_STATE_PREFIX = 'account:add:';
11
+
12
+ const OAUTH_STATE_PATTERN = new RegExp(`^${OAUTH_STATE_PREFIX}${OAUTH_NONCE_PATTERN.source.slice(1)}`);
13
+
14
+ /**
15
+ * Whether an OAuth2 callback's `state` has the shape EmailEngine issues
16
+ *
17
+ * @param {*} state - The `state` query argument
18
+ * @returns {boolean}
19
+ */
20
+ function isValidOAuthState(state) {
21
+ return OAUTH_STATE_PATTERN.test(state);
22
+ }
23
+
24
+ module.exports = { OAUTH_NONCE_PATTERN, isValidOAuthState };
@@ -229,7 +229,7 @@ function oauth2ProviderData(provider, selector) {
229
229
  providerData.tutorialUrl = 'https://learn.emailengine.app/docs/accounts/microsoft-365/outlook-365';
230
230
  providerData.linkImage = '/static/providers/ms_light.svg';
231
231
  } else {
232
- providerData.tutorialUrl = 'https://learn.emailengine.app/docs/accounts/outlook-client-credentials';
232
+ providerData.tutorialUrl = 'https://learn.emailengine.app/docs/accounts/microsoft-365/outlook-client-credentials';
233
233
  }
234
234
  providerData.imap = {
235
235
  host: imapHost,
package/lib/pbkdf2-phc.js CHANGED
@@ -26,7 +26,7 @@ const MAX_SALT_SIZE = 1024;
26
26
  const PHC_RE = /^\$pbkdf2-([a-z0-9]+)\$i=(0|[1-9][0-9]*)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/;
27
27
 
28
28
  function b64(buf) {
29
- return buf.toString('base64').replace(/=+$/, '');
29
+ return buf.toString('base64').replace(/[=]+$/, '');
30
30
  }
31
31
 
32
32
  function digestKeyLength(digest) {
@@ -98,4 +98,21 @@ async function verify(phcString, password) {
98
98
  return crypto.timingSafeEqual(derived, expected);
99
99
  }
100
100
 
101
- module.exports = { hash, verify };
101
+ /**
102
+ * Whether a stored hash was written with weaker parameters than hash() uses today: an older
103
+ * digest, or fewer iterations. Such a hash keeps verifying (verify() honours whatever the string
104
+ * says), so the only time it can be upgraded is right after the password was checked against it.
105
+ *
106
+ * @param {string} phcString
107
+ * @returns {boolean} true when the hash should be rewritten with the current parameters
108
+ */
109
+ function needsRehash(phcString) {
110
+ let match = typeof phcString === 'string' ? PHC_RE.exec(phcString) : null;
111
+ if (!match) {
112
+ return false;
113
+ }
114
+ let [, digest, iterationsValue] = match;
115
+ return digest !== PDKDF2_DIGEST || Number(iterationsValue) < PDKDF2_ITERATIONS;
116
+ }
117
+
118
+ module.exports = { hash, verify, needsRehash };
@@ -100,9 +100,12 @@ const PRIVILEGED_SETTINGS_GROUPS = [
100
100
  keys: ['openAiAPIKey', 'openAiAPIUrl']
101
101
  },
102
102
  {
103
- // Credential-bearing (the example is an Authorization header)
104
- label: 'custom webhook headers',
105
- keys: ['webhooksCustomHeaders']
103
+ // Credential-bearing (the example is an Authorization header), and the URL they are sent
104
+ // to: a narrowed credential that cannot read the headers could still move the target to
105
+ // its own host and receive them, with every account's event bodies, on the next delivery.
106
+ // Per-account targets stay ordinary; they carry the account's own headers only
107
+ label: 'the webhook target and its custom headers',
108
+ keys: ['webhooks', 'webhooksCustomHeaders']
106
109
  },
107
110
  {
108
111
  // HTML injected into the hosted pages, where end users type mail passwords
@@ -24,7 +24,18 @@ function execBatch(pipeline) {
24
24
  });
25
25
  }
26
26
 
27
- async function redisScanDelete(redis, logger, match) {
27
+ /**
28
+ * Deletes every key matching a glob, in batches.
29
+ *
30
+ * @param {Object} redis - ioredis client
31
+ * @param {Object} logger
32
+ * @param {String} match - SCAN pattern
33
+ * @param {Function} [filter] - key => Boolean; a key the glob matched but the filter refuses is
34
+ * left alone. A glob cannot say where one id ends and the next part of the key begins, the
35
+ * filter can
36
+ * @returns {Promise<Number>} keys removed
37
+ */
38
+ async function redisScanDelete(redis, logger, match, filter) {
28
39
  return new Promise((resolve, reject) => {
29
40
  const stream = redis.scanStream({ match, count: REDIS_BATCH_DELETE_SIZE });
30
41
  let pipeline = redis.pipeline();
@@ -79,6 +90,9 @@ async function redisScanDelete(redis, logger, match) {
79
90
  }
80
91
 
81
92
  for (let ik = 0; ik < resultKeys.length; ik++) {
93
+ if (typeof filter === 'function' && !filter(resultKeys[ik])) {
94
+ continue;
95
+ }
82
96
  batchKeys.push(resultKeys[ik]);
83
97
  pipeline.del(resultKeys[ik]);
84
98
  }