emailengine-app 2.84.2 → 2.86.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 (164) hide show
  1. package/.ncurc.js +29 -9
  2. package/.prettierignore +5 -1
  3. package/.prettierrc.js +2 -0
  4. package/.release-please-manifest.json +1 -1
  5. package/CHANGELOG.md +107 -0
  6. package/Dockerfile +20 -1
  7. package/ENVIRONMENT.md +139 -0
  8. package/README.md +2 -2
  9. package/bin/emailengine.js +434 -408
  10. package/config/default.toml +2 -0
  11. package/copy-static-files.sh +41 -14
  12. package/data/google-crawlers.json +1 -1
  13. package/data/public_suffix_list.dat +16563 -0
  14. package/eslint.config.js +81 -99
  15. package/lib/account-assignment.js +19 -0
  16. package/lib/account.js +230 -170
  17. package/lib/api-error-codes.js +49 -0
  18. package/lib/api-reference/format.js +4 -3
  19. package/lib/api-reference/model.js +6 -1
  20. package/lib/api-routes/account-routes.js +255 -38
  21. package/lib/api-routes/blocklist-routes.js +91 -4
  22. package/lib/api-routes/delivery-test-routes.js +27 -4
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +110 -12
  25. package/lib/api-routes/index.js +4 -0
  26. package/lib/api-routes/license-routes.js +2 -2
  27. package/lib/api-routes/mailbox-routes.js +44 -5
  28. package/lib/api-routes/message-routes.js +112 -10
  29. package/lib/api-routes/oauth2-app-routes.js +63 -23
  30. package/lib/api-routes/outbox-routes.js +97 -52
  31. package/lib/api-routes/permission-map.js +67 -7
  32. package/lib/api-routes/scoped-routes.js +74 -0
  33. package/lib/api-routes/settings-routes.js +34 -6
  34. package/lib/api-routes/stats-routes.js +5 -1
  35. package/lib/api-routes/submit-routes.js +337 -309
  36. package/lib/api-routes/template-routes.js +45 -8
  37. package/lib/api-routes/token-routes.js +152 -100
  38. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  39. package/lib/api-routes/webhook-route-routes.js +132 -6
  40. package/lib/bounce-detect.js +397 -205
  41. package/lib/calendar-event.js +81 -1
  42. package/lib/consts.js +38 -45
  43. package/lib/db.js +14 -6
  44. package/lib/delivery-error.js +6 -0
  45. package/lib/deprecations.js +270 -0
  46. package/lib/email-client/base-client.js +137 -184
  47. package/lib/email-client/fallback-poll.js +62 -0
  48. package/lib/email-client/gmail-client.js +60 -22
  49. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  50. package/lib/email-client/imap/adaptive-idle.js +278 -0
  51. package/lib/email-client/imap/connection-errors.js +14 -1
  52. package/lib/email-client/imap/idle-settings.js +31 -5
  53. package/lib/email-client/imap/listing-diff.js +37 -0
  54. package/lib/email-client/imap/mailbox.js +372 -242
  55. package/lib/email-client/imap/subconnection.js +8 -30
  56. package/lib/email-client/imap/sync-operations.js +220 -127
  57. package/lib/email-client/imap-client.js +228 -164
  58. package/lib/email-client/message-builder.js +14 -79
  59. package/lib/email-client/notification-handler.js +1 -2
  60. package/lib/email-client/outlook-client.js +372 -338
  61. package/lib/email-client/smtp-pool-manager.js +16 -13
  62. package/lib/email-client/sync-state-fields.js +19 -0
  63. package/lib/encrypt.js +157 -41
  64. package/lib/enum-descriptions.js +3 -1
  65. package/lib/env-setting-overrides.js +288 -0
  66. package/lib/export-worker.js +751 -0
  67. package/lib/export.js +64 -15
  68. package/lib/gateway.js +19 -4
  69. package/lib/get-raw-email.js +25 -107
  70. package/lib/hapi-request-logger.js +107 -0
  71. package/lib/health.js +75 -0
  72. package/lib/imapproxy/imap-core/README.md +6 -5
  73. package/lib/lock-run.js +119 -0
  74. package/lib/logger-consts.js +48 -0
  75. package/lib/logger.js +1 -1
  76. package/lib/lua/z-head-scores.lua +28 -0
  77. package/lib/mcp/tools.js +37 -8
  78. package/lib/network-errors.js +1 -1
  79. package/lib/node-version.js +24 -0
  80. package/lib/notify-attachments.js +36 -0
  81. package/lib/oauth/outlook-mailbox.js +35 -0
  82. package/lib/oauth/state.js +24 -0
  83. package/lib/oauth2-apps.js +631 -656
  84. package/lib/outbox.js +184 -54
  85. package/lib/parse-message.js +3 -3
  86. package/lib/pbkdf2-phc.js +1 -1
  87. package/lib/privileged-settings.js +2 -2
  88. package/lib/queue-browser/definitions.js +11 -0
  89. package/lib/queue-browser/index.js +68 -19
  90. package/lib/queue-job-actions.js +18 -1
  91. package/lib/queue-retention.js +48 -12
  92. package/lib/queue-stats.js +11 -2
  93. package/lib/read-env-value.js +3 -0
  94. package/lib/redis-memory-warnings.js +99 -0
  95. package/lib/redis-reconnect.js +29 -0
  96. package/lib/request-timing.js +23 -0
  97. package/lib/respawn-backoff.js +35 -0
  98. package/lib/rewrite-text-nodes.js +19 -59
  99. package/lib/schemas.js +164 -40
  100. package/lib/settings.js +6 -2
  101. package/lib/smtp-auth.js +19 -1
  102. package/lib/sso.js +1 -1
  103. package/lib/swagger-options.js +1 -1
  104. package/lib/thread-diagnostics.js +63 -0
  105. package/lib/timezones.js +109 -0
  106. package/lib/tls/provision.js +6 -3
  107. package/lib/token-audit-log.js +19 -20
  108. package/lib/token-permission-view.js +7 -6
  109. package/lib/tools.js +48 -51
  110. package/lib/totp.js +2 -5
  111. package/lib/translations.js +1 -2
  112. package/lib/ui-routes/account-routes.js +475 -454
  113. package/lib/ui-routes/account-setup.js +99 -0
  114. package/lib/ui-routes/admin-config-routes.js +152 -100
  115. package/lib/ui-routes/admin-entities-routes.js +93 -21
  116. package/lib/ui-routes/auth-routes.js +90 -38
  117. package/lib/ui-routes/imap-idle-field.js +1 -1
  118. package/lib/ui-routes/internals-routes.js +5 -0
  119. package/lib/ui-routes/oauth-config-routes.js +124 -82
  120. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  121. package/lib/ui-routes/overridable-fields.js +84 -0
  122. package/lib/ui-routes/queue-routes.js +8 -5
  123. package/lib/ui-routes/route-helpers.js +19 -3
  124. package/lib/ui-routes/settings-page.js +6 -0
  125. package/lib/ui-routes/tls-config-routes.js +58 -15
  126. package/lib/utils/back-off.js +82 -0
  127. package/lib/utils/decode-headers.js +3 -12
  128. package/lib/utils/filter-empty.js +20 -0
  129. package/lib/utils/int-setting.js +48 -0
  130. package/lib/utils/murmurhash3.js +66 -0
  131. package/lib/utils/public-suffix.js +122 -0
  132. package/lib/utils/random-id.js +26 -0
  133. package/lib/utils/tracking-settings.js +35 -0
  134. package/lib/utils/version.js +74 -0
  135. package/lib/web-safe-html.js +18 -105
  136. package/lib/webhook-delivery.js +461 -0
  137. package/lib/webhook-failures.js +132 -0
  138. package/lib/webhook-request.js +29 -1
  139. package/lib/webhook-routing.js +56 -0
  140. package/lib/webhook-test.js +88 -0
  141. package/lib/webhooks.js +93 -45
  142. package/lib/worker-rpc-error.js +2 -1
  143. package/package.json +37 -38
  144. package/sbom.json +7902 -1
  145. package/server.js +784 -518
  146. package/static/js/ace/ace.js +1 -1
  147. package/static/licenses.html +225 -1060
  148. package/translations/messages.pot +62 -63
  149. package/views/config/ai.hbs +1 -1
  150. package/views/config/security.hbs +24 -2
  151. package/views/config/service.hbs +47 -0
  152. package/views/config/webhooks.hbs +36 -0
  153. package/views/internals/index.hbs +8 -0
  154. package/views/partials/queue_retention_note.hbs +12 -8
  155. package/views/partials/ui/env-managed-alert.hbs +16 -7
  156. package/views/partials/webhook_form.hbs +1 -1
  157. package/views/suppression-lists/index.hbs +1 -1
  158. package/workers/api.js +840 -611
  159. package/workers/export.js +17 -632
  160. package/workers/imap.js +13 -0
  161. package/workers/smtp.js +9 -11
  162. package/workers/submit.js +1 -1
  163. package/workers/webhooks.js +18 -448
  164. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -0,0 +1,48 @@
1
+ 'use strict';
2
+
3
+ // The constants lib/logger.js needs, in a module that requires nothing. lib/consts.js reads its
4
+ // own environment variables through lib/read-env-value.js, which logs through lib/logger.js, so a
5
+ // logger that required lib/consts.js was a require cycle, and read-env-value had to defer every
6
+ // log line by a tick to get around it. lib/consts.js re-exports both, so other callers are unchanged.
7
+
8
+ // Transient network error codes that indicate a retry-worthy connection failure
9
+ const TRANSIENT_NETWORK_CODES = new Set([
10
+ 'ENOTFOUND',
11
+ 'EAI_AGAIN',
12
+ 'ETIMEDOUT',
13
+ 'ECONNRESET',
14
+ 'ECONNREFUSED',
15
+ // no route to the host, such as an IPv6 address on a host without IPv6 connectivity
16
+ 'ENETUNREACH',
17
+ 'EHOSTUNREACH',
18
+ 'UND_ERR_SOCKET',
19
+ 'UND_ERR_CONNECT_TIMEOUT',
20
+ 'UND_ERR_HEADERS_TIMEOUT',
21
+ // a response body that stalled mid-transfer
22
+ 'UND_ERR_BODY_TIMEOUT'
23
+ ]);
24
+
25
+ // Applied by lib/logger.js to the root logger, so every worker inherits it. A logged joi
26
+ // ValidationError carries the full submitted payload in `_original` and the offending value in
27
+ // each detail context, and `rawPacket` is a TLS-error field that can carry an unparsed
28
+ // credential frame - without these a failed validation writes plaintext passwords, OAuth2
29
+ // client secrets and access tokens into the log, the per-account log store and Sentry.
30
+ // `req.query.access_token` is here because the api-token scheme accepts the credential as a
31
+ // query argument, and the request logger (lib/hapi-request-logger.js) logs the parsed query
32
+ // object with every request - so a client using that form wrote a live token into this
33
+ // instance's own request log. The serialized `req.url` is the pathname only
34
+ // (pino-std-serializers reports `req.path`), so the credential reaches the log through the
35
+ // query object and nowhere else.
36
+ const REDACTED_LOG_KEYS = [
37
+ 'req.headers.authorization',
38
+ 'req.headers.cookie',
39
+ 'req.query.access_token',
40
+ 'err.rawPacket',
41
+ 'err._original',
42
+ 'err.details[*].context.value',
43
+ // the WHATWG URL parser attaches the string it rejected, and a stored proxy or webhook URL
44
+ // carries its credentials inline
45
+ 'err.input'
46
+ ];
47
+
48
+ module.exports = { REDACTED_LOG_KEYS, TRANSIENT_NETWORK_CODES };
package/lib/logger.js CHANGED
@@ -7,7 +7,7 @@ if (!process.env.EE_ENV_LOADED) {
7
7
 
8
8
  const config = require('@zone-eu/wild-config');
9
9
  const pino = require('pino');
10
- const { REDACTED_LOG_KEYS } = require('./consts');
10
+ const { REDACTED_LOG_KEYS } = require('./logger-consts');
11
11
  const { isTransientNetworkError } = require('./network-errors');
12
12
 
13
13
  config.log = config.log || {
@@ -0,0 +1,28 @@
1
+ --[[
2
+ Script: z-head-scores.lua
3
+ Purpose: Returns the scores of the lowest-scored entries of a sorted set, without the members.
4
+ For a queue scored by UID whose members are full JSON payloads, the UIDs are all a caller wants,
5
+ and ZRANGE WITHSCORES would send every payload along with them
6
+
7
+ KEYS:
8
+ [1] key - Sorted set key
9
+
10
+ ARGV:
11
+ [1] count - How many entries to read from the head of the set
12
+
13
+ Returns:
14
+ Array of scores (as strings), lowest first; empty when the set does not exist
15
+ --]]
16
+
17
+ local count = tonumber(ARGV[1]) or 0;
18
+ if count < 1 then
19
+ return {};
20
+ end;
21
+
22
+ local list = redis.call("ZRANGE", KEYS[1], 0, count - 1, "WITHSCORES");
23
+ local scores = {};
24
+ for i = 2, #list, 2 do
25
+ scores[#scores + 1] = list[i];
26
+ end;
27
+
28
+ return scores;
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
 
@@ -6,7 +6,7 @@
6
6
  //
7
7
  // Dependency-free apart from consts, so lib/logger.js can use it without a require cycle.
8
8
 
9
- const { TRANSIENT_NETWORK_CODES } = require('./consts');
9
+ const { TRANSIENT_NETWORK_CODES } = require('./logger-consts');
10
10
 
11
11
  // How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
12
12
  // error may cite itself - so the walk is bounded rather than trusting it to end.
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // The oldest Node.js release the dependency tree supports, matching `engines.node` in package.json
4
+ // (test/node-version-test.js keeps the two in step). Requires nothing but the dependency-free
5
+ // lib/utils/version.js, because server.js checks it before it requires anything else.
6
+
7
+ const MIN_SUPPORTED_NODE = '20.19.0';
8
+
9
+ const { compareVersions } = require('./utils/version');
10
+
11
+ /**
12
+ * Whether a Node.js version is older than MIN_SUPPORTED_NODE
13
+ * @param {string} version - A version such as process.versions.node ("20.18.1")
14
+ * @returns {boolean} True when the version is older, false for one that can not be read
15
+ */
16
+ function isBelowSupportedNode(version) {
17
+ try {
18
+ return compareVersions(String(version || '').replace(/^v/, ''), MIN_SUPPORTED_NODE) < 0;
19
+ } catch (err) {
20
+ return false;
21
+ }
22
+ }
23
+
24
+ module.exports = { MIN_SUPPORTED_NODE, isBelowSupportedNode };
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ const { mapConcurrent } = require('./utils/map-concurrent');
4
+
5
+ // Attachment downloads a Gmail API or Graph client runs at once for one message
6
+ const API_ATTACHMENT_CONCURRENCY = 4;
7
+
8
+ // Whether an attachment's content belongs in a messageNew payload under the notifyAttachmentSize
9
+ // setting. Both processNew() implementations ask it before downloading an attachment and
10
+ // formatPayload() asks it again for content loaded on other paths, such as inline images the
11
+ // web-safe embed fetched, so what is downloaded and what is kept cannot disagree. An attachment is
12
+ // measured by the encoded size the message structure reports, and only content without one by its
13
+ // decoded size.
14
+ function withinNotifyAttachmentSize(attachment, notifyAttachmentSize) {
15
+ if (!notifyAttachmentSize) {
16
+ return true;
17
+ }
18
+ let size = attachment.encodedSize || (attachment.content ? (attachment.content.length / 4) * 3 : 0);
19
+ return size <= notifyAttachmentSize;
20
+ }
21
+
22
+ /**
23
+ * Loads the content of every attachment the messageNew webhook carries (`notifyAttachments`), the
24
+ * ones over `notifyAttachmentSize` excepted. Shared by the IMAP mailbox and the API clients
25
+ * @param {Object[]} attachments - The message's attachments
26
+ * @param {number} sizeLimit - The notifyAttachmentSize setting
27
+ * @param {Function} load - async (attachment) => void, sets attachment.content (base64) when it can
28
+ * @param {number} [concurrency=1] - Downloads at a time: one for IMAP, where they share the
29
+ * connection, a few for the API clients, where each is an HTTP request of its own
30
+ */
31
+ async function loadNotifyAttachments(attachments, sizeLimit, load, concurrency = 1) {
32
+ const pending = (attachments || []).filter(attachment => withinNotifyAttachmentSize(attachment, sizeLimit) && !attachment.content);
33
+ await mapConcurrent(pending, concurrency, load);
34
+ }
35
+
36
+ module.exports = { withinNotifyAttachmentSize, loadNotifyAttachments, API_ATTACHMENT_CONCURRENCY };
@@ -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 };