emailengine-app 2.84.2 → 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 (86) hide show
  1. package/.ncurc.js +5 -3
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +33 -0
  6. package/Dockerfile +6 -0
  7. package/README.md +1 -1
  8. package/bin/emailengine.js +434 -408
  9. package/copy-static-files.sh +39 -14
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +16562 -0
  12. package/eslint.config.js +81 -99
  13. package/lib/account.js +36 -5
  14. package/lib/api-reference/format.js +4 -3
  15. package/lib/api-routes/account-routes.js +177 -12
  16. package/lib/api-routes/blocklist-routes.js +23 -2
  17. package/lib/api-routes/delivery-test-routes.js +26 -3
  18. package/lib/api-routes/export-routes.js +28 -2
  19. package/lib/api-routes/gateway-routes.js +28 -2
  20. package/lib/api-routes/mailbox-routes.js +41 -2
  21. package/lib/api-routes/message-routes.js +97 -3
  22. package/lib/api-routes/oauth2-app-routes.js +48 -15
  23. package/lib/api-routes/outbox-routes.js +45 -11
  24. package/lib/api-routes/permission-map.js +12 -1
  25. package/lib/api-routes/settings-routes.js +23 -2
  26. package/lib/api-routes/submit-routes.js +336 -309
  27. package/lib/api-routes/template-routes.js +38 -2
  28. package/lib/api-routes/token-routes.js +142 -96
  29. package/lib/api-routes/webhook-route-routes.js +13 -2
  30. package/lib/bounce-detect.js +397 -205
  31. package/lib/consts.js +5 -4
  32. package/lib/email-client/base-client.js +10 -31
  33. package/lib/email-client/gmail-client.js +9 -11
  34. package/lib/email-client/imap/mailbox.js +3 -19
  35. package/lib/email-client/imap/subconnection.js +1 -1
  36. package/lib/email-client/imap-client.js +1 -1
  37. package/lib/email-client/notification-handler.js +1 -2
  38. package/lib/gateway.js +2 -3
  39. package/lib/hapi-request-logger.js +107 -0
  40. package/lib/imapproxy/imap-core/README.md +6 -5
  41. package/lib/mcp/tools.js +37 -8
  42. package/lib/notify-attachments.js +17 -0
  43. package/lib/oauth/outlook-mailbox.js +35 -0
  44. package/lib/oauth/state.js +24 -0
  45. package/lib/oauth2-apps.js +1 -1
  46. package/lib/pbkdf2-phc.js +1 -1
  47. package/lib/schemas.js +1 -1
  48. package/lib/sso.js +1 -1
  49. package/lib/swagger-options.js +1 -1
  50. package/lib/thread-diagnostics.js +46 -0
  51. package/lib/timezones.js +109 -0
  52. package/lib/token-permission-view.js +3 -3
  53. package/lib/tools.js +40 -10
  54. package/lib/totp.js +2 -5
  55. package/lib/translations.js +1 -2
  56. package/lib/ui-routes/account-routes.js +475 -454
  57. package/lib/ui-routes/account-setup.js +99 -0
  58. package/lib/ui-routes/admin-config-routes.js +88 -10
  59. package/lib/ui-routes/admin-entities-routes.js +91 -7
  60. package/lib/ui-routes/auth-routes.js +90 -38
  61. package/lib/ui-routes/internals-routes.js +5 -0
  62. package/lib/ui-routes/oauth-config-routes.js +124 -82
  63. package/lib/ui-routes/route-helpers.js +19 -3
  64. package/lib/ui-routes/tls-config-routes.js +58 -15
  65. package/lib/utils/back-off.js +82 -0
  66. package/lib/utils/murmurhash3.js +66 -0
  67. package/lib/utils/public-suffix.js +122 -0
  68. package/lib/utils/random-id.js +26 -0
  69. package/lib/utils/version.js +74 -0
  70. package/lib/webhook-routing.js +27 -0
  71. package/lib/webhooks.js +41 -6
  72. package/package.json +27 -29
  73. package/sbom.json +7980 -1
  74. package/server.js +634 -441
  75. package/static/licenses.html +181 -1006
  76. package/translations/messages.pot +62 -63
  77. package/views/config/ai.hbs +1 -1
  78. package/views/config/security.hbs +2 -2
  79. package/views/config/service.hbs +3 -0
  80. package/views/internals/index.hbs +8 -0
  81. package/views/partials/webhook_form.hbs +1 -1
  82. package/views/suppression-lists/index.hbs +1 -1
  83. package/workers/api.js +738 -583
  84. package/workers/export.js +1 -1
  85. package/workers/submit.js +1 -1
  86. package/workers/webhooks.js +16 -32
package/lib/consts.js CHANGED
@@ -472,10 +472,11 @@ module.exports = {
472
472
  // credential frame - without these a failed validation writes plaintext passwords, OAuth2
473
473
  // client secrets and access tokens into the log, the per-account log store and Sentry.
474
474
  // `req.query.access_token` is here because the api-token scheme accepts the credential as a
475
- // query argument, and hapi-pino logs the parsed query object with every request - so a client
476
- // using that form wrote a live token into this instance's own request log. The serialized
477
- // `req.url` is the pathname only (pino-std-serializers reports `req.path`), so the credential
478
- // reaches the log through the query object and nowhere else.
475
+ // query argument, and the request logger (lib/hapi-request-logger.js) logs the parsed query
476
+ // object with every request - so a client using that form wrote a live token into this
477
+ // instance's own request log. The serialized `req.url` is the pathname only
478
+ // (pino-std-serializers reports `req.path`), so the credential reaches the log through the
479
+ // query object and nowhere else.
479
480
  REDACTED_LOG_KEYS: [
480
481
  'req.headers.authorization',
481
482
  'req.headers.cookie',
@@ -58,6 +58,7 @@ const {
58
58
  collectCidReferences,
59
59
  embedCidImages
60
60
  } = require('../tools');
61
+ const { withinNotifyAttachmentSize } = require('../notify-attachments');
61
62
 
62
63
  // Import application constants
63
64
  const {
@@ -1925,8 +1926,8 @@ class BaseClient {
1925
1926
 
1926
1927
  try {
1927
1928
  referencedMessage = await retryOnTransientError(
1928
- async () => {
1929
- return await this.getMessage(
1929
+ async () =>
1930
+ await this.getMessage(
1930
1931
  data.reference.message,
1931
1932
  {
1932
1933
  fields: !extendedData
@@ -1940,8 +1941,7 @@ class BaseClient {
1940
1941
  textType: extendedData ? '*' : false
1941
1942
  },
1942
1943
  connectionOptions
1943
- );
1944
- },
1944
+ ),
1945
1945
  {
1946
1946
  maxAttempts: 3,
1947
1947
  baseDelay: 1000,
@@ -2320,8 +2320,8 @@ class BaseClient {
2320
2320
 
2321
2321
  try {
2322
2322
  referencedMessage = await retryOnTransientError(
2323
- async () => {
2324
- return await this.getMessage(
2323
+ async () =>
2324
+ await this.getMessage(
2325
2325
  data.reference.message,
2326
2326
  {
2327
2327
  fields: !extendedData
@@ -2335,8 +2335,7 @@ class BaseClient {
2335
2335
  textType: extendedData ? '*' : false
2336
2336
  },
2337
2337
  connectionOptions
2338
- );
2339
- },
2338
+ ),
2340
2339
  {
2341
2340
  maxAttempts: 3,
2342
2341
  baseDelay: 1000,
@@ -3136,7 +3135,7 @@ class BaseClient {
3136
3135
  let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
3137
3136
  if (notifyAttachments && messageData.attachments?.length) {
3138
3137
  for (let attachment of messageData.attachments || []) {
3139
- if (notifyAttachmentSize && attachment.encodedSize && attachment.encodedSize > notifyAttachmentSize) {
3138
+ if (!withinNotifyAttachmentSize(attachment, notifyAttachmentSize)) {
3140
3139
  // skip large attachments
3141
3140
  continue;
3142
3141
  }
@@ -3150,26 +3149,6 @@ class BaseClient {
3150
3149
  }
3151
3150
  }
3152
3151
 
3153
- // Fetch inline attachments referenced in HTML
3154
- if (messageData.attachments && messageData.attachments.length && messageData.text && messageData.text.html) {
3155
- // fetch inline attachments
3156
- let cidReferences = collectCidReferences(messageData.text.html);
3157
- for (let attachment of messageData.attachments) {
3158
- if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
3159
- // skip large attachments
3160
- continue;
3161
- }
3162
-
3163
- if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
3164
- try {
3165
- attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
3166
- } catch (err) {
3167
- this.logger.error({ msg: 'Failed to load attachment content', attachment, err });
3168
- }
3169
- }
3170
- }
3171
- }
3172
-
3173
3152
  // Fetch and process calendar events if needed
3174
3153
  let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
3175
3154
  if (notifyCalendarEvents && messageData.attachments && messageData.attachments.length) {
@@ -3288,8 +3267,8 @@ class BaseClient {
3288
3267
  for (let attachment of messageData.attachments) {
3289
3268
  let contentId = attachment.contentId && attachment.contentId.replace(/^<|>$/g, '');
3290
3269
  if (contentId && cidReferences.has(contentId)) {
3291
- // An attachment the earlier inline pass already loaded is embedded as is; the
3292
- // same size cap applies to anything downloaded here
3270
+ // An attachment notifyAttachments already loaded is embedded as is; anything
3271
+ // downloaded here is capped at the inline image size
3293
3272
  if (!attachment.content && !(attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
3294
3273
  try {
3295
3274
  attachment.content = (await this.getAttachment(attachment.id))?.data?.toString('base64');
@@ -422,18 +422,16 @@ class GmailClient extends BaseClient {
422
422
  })
423
423
  };
424
424
  }
425
- } else {
425
+ } else if (profileRes.emailAddress && accountData.oauth2.auth?.user !== profileRes.emailAddress) {
426
426
  // Extract email from profile for full access accounts
427
- if (profileRes.emailAddress && accountData.oauth2.auth?.user !== profileRes.emailAddress) {
428
- updates._oldOAuth2User = accountData.oauth2.auth?.user; // needed for cleanups
429
- updates.oauth2 = {
430
- partial: true,
431
- auth: Object.assign(accountData.oauth2.auth || {}, {
432
- // update username
433
- user: profileRes.emailAddress
434
- })
435
- };
436
- }
427
+ updates._oldOAuth2User = accountData.oauth2.auth?.user; // needed for cleanups
428
+ updates.oauth2 = {
429
+ partial: true,
430
+ auth: Object.assign(accountData.oauth2.auth || {}, {
431
+ // update username
432
+ user: profileRes.emailAddress
433
+ })
434
+ };
437
435
  }
438
436
 
439
437
  // Detect and store user locale (only for full access accounts)
@@ -16,6 +16,7 @@ const {
16
16
  embedCidImages
17
17
  } = require('../../tools');
18
18
  const { samePath } = require('../../utils/mailbox-path');
19
+ const { withinNotifyAttachmentSize } = require('../../notify-attachments');
19
20
  const { connectionNotAvailableError } = require('./connection-errors');
20
21
  const msgpack = require('../../msgpack');
21
22
  const he = require('he');
@@ -1505,7 +1506,7 @@ class Mailbox {
1505
1506
  let notifyAttachmentSize = await settings.get('notifyAttachmentSize');
1506
1507
  if (notifyAttachments && messageInfo.attachments?.length) {
1507
1508
  for (let attachment of messageInfo.attachments || []) {
1508
- if (notifyAttachmentSize && attachment.encodedSize && attachment.encodedSize > notifyAttachmentSize) {
1509
+ if (!withinNotifyAttachmentSize(attachment, notifyAttachmentSize)) {
1509
1510
  // skip large attachments
1510
1511
  continue;
1511
1512
  }
@@ -1515,23 +1516,6 @@ class Mailbox {
1515
1516
  }
1516
1517
  }
1517
1518
 
1518
- // Fetch inline attachments referenced in HTML
1519
- if (messageInfo.attachments?.length && messageInfo.text?.html) {
1520
- // fetch inline attachments
1521
- let cidReferences = collectCidReferences(messageInfo.text.html);
1522
- for (let attachment of messageInfo.attachments || []) {
1523
- if (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE) {
1524
- // skip large attachments
1525
- continue;
1526
- }
1527
-
1528
- // Check if attachment is referenced by Content-ID in HTML
1529
- if (!attachment.content && attachment.contentId && cidReferences.has(attachment.contentId.replace(/^<|>$/g, ''))) {
1530
- await this.loadAttachmentContent(messageInfo, attachment, options);
1531
- }
1532
- }
1533
- }
1534
-
1535
1519
  // Fetch and process calendar events if needed
1536
1520
  let notifyCalendarEvents = await settings.get('notifyCalendarEvents');
1537
1521
  if (notifyCalendarEvents && messageInfo.attachments && messageInfo.attachments.length) {
@@ -1660,7 +1644,7 @@ class Mailbox {
1660
1644
  });
1661
1645
 
1662
1646
  if (attachment.content || (attachment.encodedSize && attachment.encodedSize > MAX_INLINE_ATTACHMENT_SIZE)) {
1663
- // already downloaded in a previous step, or skipped there as too large to inline
1647
+ // already loaded by notifyAttachments, or too large to inline
1664
1648
  continue;
1665
1649
  }
1666
1650
 
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { createImapClient } = require('../../create-imap-client');
4
- const { backOff } = require('exponential-backoff');
4
+ const { backOff } = require('../../utils/back-off');
5
5
  const { ReconnectBackoff } = require('../reconnect-backoff');
6
6
  const { detachImapClient } = require('./detach-client');
7
7
  const { connectionUnavailableError } = require('./connection-errors');
@@ -5,7 +5,7 @@ const { createImapClient } = require('../create-imap-client');
5
5
  const { Mailbox } = require('./imap/mailbox');
6
6
  const logger = require('../logger');
7
7
  const packageData = require('../../package.json');
8
- const { backOff } = require('exponential-backoff');
8
+ const { backOff } = require('../utils/back-off');
9
9
  const msgpack = require('../msgpack');
10
10
 
11
11
  const { oauth2ProviderData } = require('../oauth2-apps');
@@ -97,8 +97,7 @@ class NotificationHandler {
97
97
  // Build notification payload
98
98
  const payload = this.buildPayload(mailbox, event, data, serviceUrl);
99
99
 
100
- const notifyPayload = await Webhooks.formatPayload(event, payload);
101
- await Webhooks.pushToQueue(event, notifyPayload);
100
+ await Webhooks.enqueue(event, payload);
102
101
  }
103
102
  }
104
103
 
package/lib/gateway.js CHANGED
@@ -5,8 +5,7 @@ const Boom = require('@hapi/boom');
5
5
  const { REDIS_PREFIX } = require('./consts');
6
6
  const logger = require('./logger');
7
7
  const { encrypt, decrypt } = require('./encrypt');
8
- const { customAlphabet } = require('nanoid');
9
- const nanoid = customAlphabet('0123456789abcdefghijklmnopqrstuvwxyz', 16);
8
+ const { randomId } = require('./utils/random-id');
10
9
  const { mergeObjects, filterListPage } = require('./tools');
11
10
 
12
11
  class Gateway {
@@ -87,7 +86,7 @@ class Gateway {
87
86
  let id;
88
87
  let retries = 0;
89
88
  while (retries++ < 20) {
90
- id = nanoid();
89
+ id = randomId();
91
90
  let alreadyExists = await this.redis.hexists(`${REDIS_PREFIX}gateway:${id}`, 'gateway');
92
91
  if (alreadyExists) {
93
92
  id = false;
@@ -0,0 +1,107 @@
1
+ 'use strict';
2
+
3
+ // Request logging for the API server, in place of the hapi-pino plugin (which pulled a second pino
4
+ // major into the tree). It writes the same records hapi-pino did, because operators parse them:
5
+ //
6
+ // - every request gets `request.logger`, a child bound to the serialized request (`req`)
7
+ // - "[response] <method> <path> <status> (<ms>ms)" at info with `res` and `responseTime` when a
8
+ // response is sent, "-" in place of the status when the client went away first
9
+ // - a request error event at error level with `err` and `tags`, its message as the line
10
+ // - server.log() and request.log() events with `tags` and `data`, at the most severe level named
11
+ // among the tags (info when none is)
12
+ // - "server started" / "server stopped" carrying server.info
13
+ //
14
+ // The server is decorated with `server.logger`.
15
+
16
+ const { stdSerializers } = require('pino');
17
+
18
+ const LEVEL_TAGS = new Set(['trace', 'debug', 'info', 'warn', 'error', 'fatal']);
19
+
20
+ const SERIALIZERS = {
21
+ req: stdSerializers.wrapRequestSerializer(stdSerializers.req),
22
+ res: stdSerializers.wrapResponseSerializer(stdSerializers.res),
23
+ err: stdSerializers.err
24
+ };
25
+
26
+ function logEvent(logger, event) {
27
+ const tags = event.tags || [];
28
+
29
+ let level = 'info';
30
+ let highest = 0;
31
+ for (const tag of tags) {
32
+ if (LEVEL_TAGS.has(tag) && logger.levels.values[tag] > highest) {
33
+ highest = logger.levels.values[tag];
34
+ level = tag;
35
+ }
36
+ }
37
+
38
+ logger[level]({ tags, data: event.data });
39
+ }
40
+
41
+ function getRequestLogger(logger, request) {
42
+ if (!request.logger) {
43
+ request.logger = logger.child({ req: request });
44
+ }
45
+ return request.logger;
46
+ }
47
+
48
+ module.exports = {
49
+ name: 'request-logger',
50
+
51
+ /**
52
+ * @param {Object} server Hapi server
53
+ * @param {Object} options
54
+ * @param {Object} options.logger Pino logger to write through
55
+ */
56
+ register(server, options) {
57
+ // Serializers the logger already carries win, the way hapi-pino merged them
58
+ const logger = options.logger.child({}, { serializers: SERIALIZERS });
59
+
60
+ server.decorate('server', 'logger', logger);
61
+
62
+ server.ext('onRequest', (request, h) => {
63
+ request.logger = logger.child({ req: request });
64
+ return h.continue;
65
+ });
66
+
67
+ server.events.on('log', event => {
68
+ if (event.error) {
69
+ logger.error({ err: event.error, tags: event.tags });
70
+ } else {
71
+ logEvent(logger, event);
72
+ }
73
+ });
74
+
75
+ server.events.on('request', (request, event, tags) => {
76
+ // hapi's internal channel is noise apart from a malformed Accept-Encoding header
77
+ if (event.channel === 'internal' && !tags['accept-encoding']) {
78
+ return;
79
+ }
80
+
81
+ if (event.error) {
82
+ getRequestLogger(logger, request).error({ tags: event.tags, err: event.error }, event.error.message);
83
+ } else if (event.channel === 'app') {
84
+ logEvent(getRequestLogger(logger, request), event);
85
+ }
86
+ });
87
+
88
+ server.events.on('response', request => {
89
+ const { info, raw } = request;
90
+ const responseTime = (info.completed !== undefined ? info.completed : info.responded) - info.received;
91
+ const status = raw.res.headersSent ? raw.res.statusCode : '-';
92
+
93
+ getRequestLogger(logger, request).info(
94
+ { res: raw.res, responseTime },
95
+ `[response] ${request.method} ${request.path} ${status} (${responseTime}ms)`
96
+ );
97
+ });
98
+
99
+ server.ext('onPostStart', async () => {
100
+ logger.info(server.info, 'server started');
101
+ });
102
+
103
+ server.ext('onPostStop', async () => {
104
+ logger.info(server.info, 'server stopped');
105
+ });
106
+ }
107
+ };
@@ -47,8 +47,9 @@ The `test/` directory is upstream's mocha suite. It is written for mocha, which
47
47
  dependency here, and had never been executed after the import.
48
48
 
49
49
  The hermetic specs now run as part of the normal unit tier through
50
- `test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect and requires
51
- them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
50
+ `test/imap-core-vendored-test.js`, which installs the mocha globals the specs expect, routes their
51
+ `require('chai')` to a node:assert-backed stand-in (`test/helpers/chai-stand-in.js`, covering only
52
+ the chains these files use; chai itself is not a dependency), and requires them. **Do not edit the files under `test/` to make them run** - keeping them byte-identical to
52
53
  upstream is what makes the patch list above reviewable. Adapt them from the EmailEngine side
53
54
  instead.
54
55
 
@@ -59,12 +60,12 @@ Wired up and running:
59
60
  - `imap-compile-stream-test.js`
60
61
  - `imap-indexer-test.js` (upstream has its `#rebuild` block commented out)
61
62
  - `tools-test.js`
63
+ - `search-test.js` (unit tests for the SEARCH query parser and matcher)
62
64
 
63
- Not wired up, because they drive a live server via `test-server.js` and need MongoDB plus a
64
- WildDuck REST API that does not exist in this repository:
65
+ Not wired up, because it drives a live WildDuck server and needs MongoDB plus a WildDuck REST API
66
+ (`prepare.sh` loads its fixtures through both) that do not exist in this repository:
65
67
 
66
68
  - `protocol-test.js`
67
- - `search-test.js`
68
69
 
69
70
  That is a real coverage gap: `protocol-test.js` is the suite that exercises the connection and
70
71
  command state machines, which is where most of the local patches above landed. The connection
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 };
@@ -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 };
@@ -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) {
package/lib/schemas.js CHANGED
@@ -1803,7 +1803,7 @@ const oauthCreateSchema = {
1803
1803
  then: Joi.required(),
1804
1804
  otherwise: Joi.optional().valid(false, null)
1805
1805
  })
1806
- .example('boT7Q~dUljnfFdVuqpC11g8nGMjO8kpRAv-ZB')
1806
+ .example('example-client-secret')
1807
1807
  .description('OAuth2 client secret from the provider'),
1808
1808
 
1809
1809
  baseScopes: Joi.string()
package/lib/sso.js CHANGED
@@ -35,7 +35,7 @@
35
35
  // dotted path (e.g. "realm_access.roles") for IdPs that nest it.
36
36
 
37
37
  const { fetch: fetchCmd } = require('undici');
38
- const { backOff } = require('exponential-backoff');
38
+ const { backOff } = require('./utils/back-off');
39
39
  const { readEnvValue, httpAgent, getBoolean } = require('./tools');
40
40
  const packageData = require('../package.json');
41
41
 
@@ -145,7 +145,7 @@ Full documentation: https://learn.emailengine.app/`
145
145
  description: 'Configure OAuth2 applications for Gmail, Outlook, and other providers. Manage client credentials and authentication flows',
146
146
  externalDocs: {
147
147
  description: 'OAuth2 Configuration Guide',
148
- url: 'https://learn.emailengine.app/docs/configuration/oauth2-configuration'
148
+ url: 'https://learn.emailengine.app/docs/accounts/oauth2-setup'
149
149
  }
150
150
  },
151
151
  {