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
@@ -19,7 +19,24 @@ class MessagePortWritable extends Writable {
19
19
  this.destroy();
20
20
  }
21
21
  };
22
+
23
+ // A cancel message only arrives while the consumer is alive to send one. When its thread
24
+ // dies instead, the channel closes without one, and the transfer would otherwise drain the
25
+ // whole source into a port nobody is reading - holding the mailbox lock for the duration.
26
+ //
27
+ // A port that closes with nothing queued behind it reports it only to a listener that was
28
+ // already attached - the event is emitted when the port is started and drained, and a
29
+ // listener added afterwards never sees it. So the producer has to construct this when the
30
+ // port arrives, not once it has content to send: the wait in between is the whole window in
31
+ // which the consumer's thread can die, and for an attachment that is most of the transfer.
32
+ // releaseListeners() is how a producer that ends up with nothing to send gives the port
33
+ // back.
34
+ this.onPortClose = () => {
35
+ this.destroy();
36
+ };
37
+
22
38
  this.messagePort.on('message', this.onPortMessage);
39
+ this.messagePort.on('close', this.onPortClose);
23
40
  }
24
41
 
25
42
  postToPort(message) {
@@ -33,12 +50,20 @@ class MessagePortWritable extends Writable {
33
50
  }
34
51
  }
35
52
 
53
+ // Hands the port back untouched. Used by a producer that took the port but found nothing to
54
+ // send (a 404, say): closing it would reach the consumer as a failed transfer rather than as
55
+ // the error it is about to be handed, and leaving the listeners attached leaks them.
56
+ releaseListeners() {
57
+ this.messagePort.removeListener('message', this.onPortMessage);
58
+ this.messagePort.removeListener('close', this.onPortClose);
59
+ }
60
+
36
61
  closePort() {
37
62
  if (this.portClosed) {
38
63
  return;
39
64
  }
40
65
  this.portClosed = true;
41
- this.messagePort.removeListener('message', this.onPortMessage);
66
+ this.releaseListeners();
42
67
  try {
43
68
  this.messagePort.close();
44
69
  } catch (err) {
@@ -83,6 +108,7 @@ class MessagePortReadable extends Readable {
83
108
 
84
109
  this.canRead = false;
85
110
  this.portClosed = false;
111
+ this.transferComplete = false;
86
112
 
87
113
  this.readableQueue = [];
88
114
  this.onPortMessage = message => {
@@ -96,6 +122,9 @@ class MessagePortReadable extends Readable {
96
122
  return;
97
123
  }
98
124
  if (message.done || message.value) {
125
+ if (message.done) {
126
+ this.transferComplete = true;
127
+ }
99
128
  this.readableQueue.push(message);
100
129
 
101
130
  if (this.canRead && this.readableQueue.length === 1) {
@@ -103,7 +132,18 @@ class MessagePortReadable extends Readable {
103
132
  }
104
133
  }
105
134
  };
135
+
136
+ // Queued messages are delivered before 'close', so a channel that closes without
137
+ // { done: true } was cut short - most likely the producing worker died mid-download.
138
+ // Fail the read rather than presenting a truncated body or hanging on it forever.
139
+ this.onPortClose = () => {
140
+ if (!this.transferComplete && !this.destroyed) {
141
+ this.destroy(new Error('Message stream transfer interrupted'));
142
+ }
143
+ };
144
+
106
145
  this.messagePort.on('message', this.onPortMessage);
146
+ this.messagePort.on('close', this.onPortClose);
107
147
  }
108
148
 
109
149
  _processReading() {
@@ -132,6 +172,7 @@ class MessagePortReadable extends Readable {
132
172
  // ignore - the peer may already be closed
133
173
  }
134
174
  this.messagePort.removeListener('message', this.onPortMessage);
175
+ this.messagePort.removeListener('close', this.onPortClose);
135
176
  try {
136
177
  this.messagePort.close();
137
178
  } catch (closeErr) {
@@ -153,6 +194,20 @@ class MessagePortReadable extends Readable {
153
194
  * @param {Object} [logger] - Optional logger used to report transfer failures
154
195
  */
155
196
  function pipeToMessagePort(source, writable, logger) {
197
+ // pipeline() throws ERR_STREAM_UNABLE_TO_PIPE *synchronously* when the destination is
198
+ // already destroyed. The callback below never runs in that case, so the throw escapes to
199
+ // the global uncaughtException handler and takes the worker - and every account assigned
200
+ // to it - down with it. An aborted consumer destroys the writable through its
201
+ // { cancel: true } message, and on a slow upstream fetch that can easily land before this
202
+ // helper is entered at all, so it is a routine state rather than an edge case.
203
+ if (writable.destroyed) {
204
+ // Nothing will drain the source now, so release it explicitly - otherwise the upstream
205
+ // download keeps running and the mailbox lock it holds is never given back.
206
+ source.destroy();
207
+ logger?.debug?.({ msg: 'Message stream transfer aborted by consumer before it started' });
208
+ return;
209
+ }
210
+
156
211
  pipeline(source, writable, err => {
157
212
  if (!err || !logger) {
158
213
  return;
@@ -171,6 +226,34 @@ function pipeToMessagePort(source, writable, logger) {
171
226
  });
172
227
  }
173
228
 
229
+ /**
230
+ * Sends a finished download to the API worker over a destination bound to the transferred port.
231
+ * IMAP resolves a download to a stream and Gmail and Graph to a Buffer; the Buffer is wrapped so
232
+ * both shapes take the same path, leaving pipeToMessagePort() as the single place that has to get
233
+ * an aborted consumer right.
234
+ *
235
+ * Takes the destination rather than the port, because the producer has to build it when the port
236
+ * arrives - see the MessagePortWritable constructor for why. By the time there is content to send,
237
+ * a consumer that gave up has already destroyed it, and pipeToMessagePort() releases the source
238
+ * instead of transferring into a port nobody reads.
239
+ *
240
+ * @param {MessagePortWritable} writable - Destination built when the port arrived
241
+ * @param {Buffer|Readable} source - Payload to transfer
242
+ * @param {Object} [logger] - Optional logger used to report transfer failures
243
+ * @returns {MessagePortWritable} The same destination (used by tests; callers may ignore it)
244
+ */
245
+ function sendToMessagePort(writable, source, logger) {
246
+ const stream = Buffer.isBuffer(source) ? Readable.from([source], { objectMode: false }) : source;
247
+
248
+ // A { cancel: true } already queued by a consumer that gave up is delivered on the next turn of
249
+ // the event loop. Dispatching from the check phase puts the guard in pipeToMessagePort() after
250
+ // that delivery rather than racing it.
251
+ setImmediate(() => pipeToMessagePort(stream, writable, logger));
252
+
253
+ return writable;
254
+ }
255
+
174
256
  module.exports.MessagePortWritable = MessagePortWritable;
175
257
  module.exports.MessagePortReadable = MessagePortReadable;
176
258
  module.exports.pipeToMessagePort = pipeToMessagePort;
259
+ module.exports.sendToMessagePort = sendToMessagePort;
@@ -418,9 +418,12 @@ class OAuth2AppsHandler {
418
418
  // One-time startup migration: converts settings-based OAuth2 configuration ("legacy apps")
419
419
  // into regular app-store records. The historical app IDs (gmail, gmailService, outlook,
420
420
  // mailRu) are kept, so account references (accountData.oauth2.provider) keep resolving
421
- // without touching account data. The source settings keys are deleted after a successful
422
- // copy, which is what makes the migration idempotent; a Redis lock guards against parallel
423
- // instances sharing one Redis. Returns the list of migrated app IDs.
421
+ // without touching account data. The source settings keys are deleted last, after the app
422
+ // records and the account backfill, which is what makes the migration both idempotent and
423
+ // crash-safe: as long as any source key remains, the next startup re-enters and repeats
424
+ // whichever steps are missing (create() is guarded by an existence check and the backfill
425
+ // is an idempotent SADD). A Redis lock guards against parallel instances sharing one
426
+ // Redis. Returns the list of migrated app IDs.
424
427
  async migrateLegacyApps() {
425
428
  // Full per-app settings key suffixes ever used by the legacy configuration
426
429
  const FIELDS = [
@@ -472,9 +475,33 @@ class OAuth2AppsHandler {
472
475
  return value.filter(entry => entry);
473
476
  };
474
477
 
478
+ // A stored secret whose decryption failed (a rotated or missing service secret) reads
479
+ // back as null through settings.getMulti(), exactly like an absent key. Deleting the
480
+ // source keys in that state would destroy the only copy of the ciphertext, so probe
481
+ // the raw hash to tell the two apart and leave such an app entirely untouched - the
482
+ // migration retries on the next startup, and restoring the correct service secret
483
+ // makes it whole again.
484
+ const encryptedCandidates = candidateKeys.filter(key => settings.encryptedKeys.includes(key));
485
+ const rawEncryptedValues = await this.redis.hmget(this.getSettingsKey(), encryptedCandidates);
486
+ const undecryptable = new Set(encryptedCandidates.filter((key, i) => rawEncryptedValues[i] !== null && values[key] === null));
487
+
488
+ // Apps whose accounts should be (re-)linked, and apps whose source keys may be dropped
489
+ let backfillable = [];
490
+ let clearable = [];
491
+
475
492
  for (let legacyKey of LEGACY_KEYS) {
476
493
  const v = field => values[`${legacyKey}${field}`];
477
494
 
495
+ let failedKeys = FIELDS.map(field => `${legacyKey}${field}`).filter(key => undecryptable.has(key));
496
+ if (failedKeys.length) {
497
+ logger.error({
498
+ msg: 'Skipped legacy OAuth2 app migration: stored credentials could not be decrypted. Restore the original service secret and restart',
499
+ app: legacyKey,
500
+ keys: failedKeys
501
+ });
502
+ continue;
503
+ }
504
+
478
505
  // Same visibility rule the legacy listing applied: an app existed when it was
479
506
  // enabled or had a client configured. Stray keys without either (e.g. only a
480
507
  // redirect URL) never surfaced an app and are just cleaned up.
@@ -548,24 +575,21 @@ class OAuth2AppsHandler {
548
575
  logger.info({ msg: 'Migrated legacy OAuth2 app to the app registry', app: legacyKey, enabled: entry.enabled });
549
576
  }
550
577
 
551
- // the copy (or cleanup) is complete, drop the source settings keys (no-op when unset)
552
- let clearReq = this.redis.multi();
553
- for (let field of FIELDS) {
554
- clearReq = clearReq.hdel(this.getSettingsKey(), `${legacyKey}${field}`);
578
+ if (visible) {
579
+ // Whether the record was created now or by an earlier interrupted run: as long
580
+ // as the source keys are still around the backfill below has not been confirmed
581
+ // done, and repeating it is a no-op
582
+ backfillable.push(legacyKey);
555
583
  }
556
- await clearReq.exec();
557
- }
558
584
 
559
- let removedOrphans = await this.redis.hdel(this.getSettingsKey(), ...ORPHAN_KEYS);
560
- if (removedOrphans) {
561
- logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: ORPHAN_KEYS });
585
+ clearable.push(legacyKey);
562
586
  }
563
587
 
564
588
  // Backfill the per-app account membership sets that the legacy code never maintained,
565
589
  // so account counts and app deletion safety checks see the existing accounts. The
566
590
  // per-user binding hash (oapp:h:*) is left to repopulate on the next account update.
567
- if (migrated.length) {
568
- let migratedSet = new Set(migrated);
591
+ if (backfillable.length) {
592
+ let backfillableSet = new Set(backfillable);
569
593
  let accounts = await this.redis.smembers(`${REDIS_PREFIX}ia:accounts`);
570
594
  let backfillReq = this.redis.multi();
571
595
  let backfillCount = 0;
@@ -592,7 +616,7 @@ class OAuth2AppsHandler {
592
616
  } catch (parseErr) {
593
617
  continue;
594
618
  }
595
- if (oauth2Data && oauth2Data.provider && migratedSet.has(oauth2Data.provider)) {
619
+ if (oauth2Data && oauth2Data.provider && backfillableSet.has(oauth2Data.provider)) {
596
620
  backfillReq = backfillReq.sadd(`${REDIS_PREFIX}oapp:a:${oauth2Data.provider}`, chunk[j]);
597
621
  backfillCount++;
598
622
  }
@@ -604,6 +628,16 @@ class OAuth2AppsHandler {
604
628
  logger.info({ msg: 'Linked existing accounts to migrated OAuth2 apps', accounts: backfillCount });
605
629
  }
606
630
  }
631
+
632
+ // The copy is complete, drop the source settings keys (no-op when unset)
633
+ if (clearable.length) {
634
+ await this.redis.hdel(this.getSettingsKey(), ...clearable.flatMap(legacyKey => FIELDS.map(field => `${legacyKey}${field}`)));
635
+ }
636
+
637
+ let removedOrphans = await this.redis.hdel(this.getSettingsKey(), ...ORPHAN_KEYS);
638
+ if (removedOrphans) {
639
+ logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: ORPHAN_KEYS });
640
+ }
607
641
  } finally {
608
642
  await lock.releaseLock(migrateLock);
609
643
  }
@@ -875,6 +909,41 @@ class OAuth2AppsHandler {
875
909
  }
876
910
  }
877
911
 
912
+ // Auth-failure flags of every registered app, for the site-wide admin alert (see the view
913
+ // context in workers/api.js). Reads only the meta entries - one SMEMBERS plus one HMGET
914
+ // however many apps exist - because it runs on every admin page render.
915
+ async listAuthFlags() {
916
+ // sorted only so the alert order is stable across renders
917
+ let idList = (await this.redis.smembers(this.getIndexKey())).sort();
918
+ if (!idList.length) {
919
+ return [];
920
+ }
921
+
922
+ let metaEntries = await this.redis.hmgetBuffer(
923
+ this.getDataKey(),
924
+ idList.map(id => `${id}:meta`)
925
+ );
926
+
927
+ let flags = [];
928
+ for (let i = 0; i < idList.length; i++) {
929
+ if (!metaEntries[i]) {
930
+ continue;
931
+ }
932
+ let meta;
933
+ try {
934
+ meta = msgpack.decode(metaEntries[i]);
935
+ } catch (err) {
936
+ logger.error({ msg: 'Failed to process app meta', app: idList[i], entryLength: metaEntries[i].length, err });
937
+ continue;
938
+ }
939
+ if (meta && meta.authFlag && meta.authFlag.message) {
940
+ flags.push({ app: idList[i], authFlag: meta.authFlag });
941
+ }
942
+ }
943
+
944
+ return flags;
945
+ }
946
+
878
947
  // Note: not atomic (read-modify-write). Concurrent callers use last-write-wins,
879
948
  // which is acceptable for self-correcting informational metadata.
880
949
  async setMeta(id, meta) {
@@ -18,6 +18,7 @@
18
18
  // response.schema -> the 200 response body
19
19
  // plugins.openapi.responses -> the documented status codes (see apiResponses in lib/schemas.js)
20
20
  // plugins.openapi.produces -> the media type for routes that do not return JSON
21
+ // plugins.openapi.deprecated -> the route is left out of the document (compatibility aliases)
21
22
  // plugins.openapi['x-*'] -> vendor extensions on the operation, notably x-ee-behavior
22
23
 
23
24
  const { STATUS_CODES } = require('node:http');
@@ -282,7 +283,10 @@ function buildOpenApiDocument(routes, options) {
282
283
 
283
284
  const paths = {};
284
285
 
285
- for (const route of sortRoutes(routes.filter(route => (route.settings.tags || []).includes(API_ROUTE_TAG)))) {
286
+ // Routes marked `plugins.openapi.deprecated` are compatibility aliases: they stay registered
287
+ // (and keep the `api` tag, which also drives the CSRF skip list) but are left out of the
288
+ // published document and the reference page, so nothing steers a new integration onto them
289
+ for (const route of sortRoutes(routes.filter(route => (route.settings.tags || []).includes(API_ROUTE_TAG) && !pluginOptions(route).deprecated))) {
286
290
  const { path, method, operation } = builder.buildOperation(route);
287
291
 
288
292
  if (!paths[path]) {
@@ -92,4 +92,6 @@ function registerOpenApiRoute(server, options) {
92
92
  });
93
93
  }
94
94
 
95
- module.exports = { registerOpenApiRoute, buildOpenApiDocument, JSON_PATH, NOTES_SEPARATOR, SCHEMA_REF_PREFIX };
95
+ // serverUrl is shared with the MCP config page, which needs the same "address the client
96
+ // actually used" answer for its connection snippets when no serviceUrl is configured
97
+ module.exports = { registerOpenApiRoute, buildOpenApiDocument, serverUrl, JSON_PATH, NOTES_SEPARATOR, SCHEMA_REF_PREFIX };
@@ -23,9 +23,17 @@ const registeredPublishers = new Set();
23
23
  const KEEP_ALIVE_INTERVAL = 90 * 1000;
24
24
 
25
25
  class ResponseStream extends Transform {
26
- constructor() {
26
+ /**
27
+ * @param {Object} [options]
28
+ * @param {Set} [options.registry] - the live-stream set this stream registers itself in.
29
+ * Defaults to the shared change-feed set that publishChangeEvent() fans out to; the
30
+ * MCP listen streams (lib/mcp/listen.js) pass their own set so the two feeds cannot
31
+ * receive each other's frames.
32
+ */
33
+ constructor(options) {
27
34
  super();
28
- registeredPublishers.add(this);
35
+ this.registry = (options && options.registry) || registeredPublishers;
36
+ this.registry.add(this);
29
37
  this.periodicKeepAliveTimer = false;
30
38
  this.updateTimer();
31
39
 
@@ -78,7 +86,7 @@ class ResponseStream extends Transform {
78
86
  this._finalized = true;
79
87
 
80
88
  clearTimeout(this.periodicKeepAliveTimer);
81
- registeredPublishers.delete(this);
89
+ this.registry.delete(this);
82
90
 
83
91
  if (!this.destroyed) {
84
92
  this.destroy();
@@ -103,36 +111,59 @@ class ResponseStream extends Transform {
103
111
  }
104
112
 
105
113
  /**
106
- * Opens an SSE change feed on a Hapi request.
114
+ * Opens an SSE response on a Hapi toolkit: the stream, its cleanup, the deferred greeting, and
115
+ * the response headers, in one place for every feed.
107
116
  *
108
- * Both feeds - the admin UI one (/admin/changes) and the API one (/v1/changes) - are the same
109
- * stream with the same framing, so the wiring lives here next to the stream it wires up rather
110
- * than being written out twice. The parts that matter and are easy to get subtly different:
111
- * finalize() has to run when the response is finished (a dropped tab must not keep its stream in
112
- * registeredPublishers), the greeting has to be deferred so it is written after the response
113
- * headers, and X-Accel-Buffering: no is what keeps an intermediate proxy from holding events
114
- * back until the connection closes.
117
+ * All three consumers - the admin change feed, /v1/changes, and the MCP subscriptions/listen
118
+ * stream (lib/mcp/listen.js) - share this wiring because the parts that matter are easy to get
119
+ * subtly different: finalize() has to run when the response is finished (a dropped client must
120
+ * not keep its stream in the registry), the greeting and anything else written on open have to
121
+ * be deferred so they land after the response headers, and X-Accel-Buffering: no is what keeps
122
+ * an intermediate proxy from holding events back until the connection closes.
115
123
  *
116
- * @param {Object} request - Hapi request; the stream is parked on request.app.stream
117
124
  * @param {Object} h - Hapi response toolkit
118
- * @returns {Object} Hapi response
125
+ * @param {Object} [options]
126
+ * @param {Set} [options.registry] - passed to the ResponseStream constructor
127
+ * @param {Function} [options.onOpen] - called with the stream after the greeting is written
128
+ * @returns {{stream: ResponseStream, response: Object}}
119
129
  */
120
- function openChangeStream(request, h) {
121
- request.app.stream = new ResponseStream();
122
- finished(request.app.stream, err => request.app.stream.finalize(err));
130
+ function openSseStream(h, options) {
131
+ const stream = new ResponseStream({ registry: options && options.registry });
132
+
133
+ finished(stream, err => stream.finalize(err));
134
+
123
135
  setImmediate(() => {
124
136
  try {
125
- request.app.stream.write(`: EmailEngine v${packageData.version}\n\n`);
137
+ stream.write(`: EmailEngine v${packageData.version}\n\n`);
138
+ if (options && options.onOpen) {
139
+ options.onOpen(stream);
140
+ }
126
141
  } catch (err) {
127
- // ignore
142
+ // the stream is already gone; finished() above cleans up
128
143
  }
129
144
  });
130
- return h
131
- .response(request.app.stream)
145
+
146
+ const response = h
147
+ .response(stream)
132
148
  .header('X-Accel-Buffering', 'no')
133
149
  .header('Connection', 'keep-alive')
134
150
  .header('Cache-Control', 'no-cache')
135
151
  .type('text/event-stream');
152
+
153
+ return { stream, response };
154
+ }
155
+
156
+ /**
157
+ * Opens the SSE change feed shared by /admin/changes and /v1/changes.
158
+ *
159
+ * @param {Object} request - Hapi request; the stream is parked on request.app.stream
160
+ * @param {Object} h - Hapi response toolkit
161
+ * @returns {Object} Hapi response
162
+ */
163
+ function openChangeStream(request, h) {
164
+ const { stream, response } = openSseStream(h);
165
+ request.app.stream = stream;
166
+ return response;
136
167
  }
137
168
 
138
- module.exports = { ResponseStream, registeredPublishers, openChangeStream };
169
+ module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream };
package/lib/routes-ui.js CHANGED
@@ -14,6 +14,7 @@ const authRoutes = require('./ui-routes/auth-routes');
14
14
  const oauthConfigRoutes = require('./ui-routes/oauth-config-routes');
15
15
  const adminConfigRoutes = require('./ui-routes/admin-config-routes');
16
16
  const accountRoutes = require('./ui-routes/account-routes');
17
+ const mcpConsentRoutes = require('./ui-routes/mcp-consent-routes');
17
18
 
18
19
  function applyRoutes(server, call) {
19
20
  // Initialize admin entity routes (webhooks, templates, gateways, tokens)
@@ -59,6 +60,9 @@ function applyRoutes(server, call) {
59
60
  // Account management routes (listing, add-account wizard, per-account view/edit/logs/browse)
60
61
  accountRoutes({ server, call });
61
62
 
63
+ // MCP OAuth consent page (self-gates on the MCP feature flag, like the Document Store module)
64
+ mcpConsentRoutes({ server, call });
65
+
62
66
  server.route({
63
67
  method: 'GET',
64
68
  path: '/.well-known/acme-challenge/{token}',
package/lib/schemas.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const Joi = require('joi');
4
4
  const config = require('@zone-eu/wild-config');
5
5
  const { getByteSize } = require('./tools');
6
- const { COLLAPSE_CLASS } = require('./consts');
6
+ const { COLLAPSE_CLASS, MAX_ACCOUNT_ID_LENGTH } = require('./consts');
7
7
  const { locales } = require('./translations');
8
8
  const { OAUTH_PROVIDERS } = require('./oauth2-apps');
9
9
  const { ACCOUNT_STATES } = require('./account/account-state');
@@ -41,7 +41,7 @@ config.api = config.api || {
41
41
  const DEFAULT_MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024;
42
42
  const MAX_ATTACHMENT_SIZE = getByteSize(process.env.EENGINE_MAX_SIZE || config.api.maxSize) || DEFAULT_MAX_ATTACHMENT_SIZE;
43
43
 
44
- const accountIdSchema = Joi.string().empty('').trim().max(256).example('user123').description('Unique identifier for the email account');
44
+ const accountIdSchema = Joi.string().empty('').trim().max(MAX_ACCOUNT_ID_LENGTH).example('user123').description('Unique identifier for the email account');
45
45
 
46
46
  // Suppression list identifier, shared by the Blocklists API and the suppression-list admin UI
47
47
  // so the two surfaces cannot drift on what a valid list ID is
@@ -330,6 +330,24 @@ const settingsSchema = {
330
330
  .falsy('N', 'false', 0, '')
331
331
  .description('Include parsed calendar event data in webhook payloads'),
332
332
 
333
+ /* ────────────── MCP ────────────── */
334
+
335
+ mcpEnabled: Joi.boolean()
336
+ .truthy('Y', 'true', '1', 'on')
337
+ .falsy('N', 'false', 0, '')
338
+ .example(false)
339
+ .description(
340
+ 'Enable the MCP (Model Context Protocol) endpoint at /mcp, which lets AI agents work with the connected email accounts using access tokens. Disabled by default'
341
+ ),
342
+
343
+ mcpOAuthEnabled: Joi.boolean()
344
+ .truthy('Y', 'true', '1', 'on')
345
+ .falsy('N', 'false', 0, '')
346
+ .example(false)
347
+ .description(
348
+ 'Enable the built-in OAuth2 authorization server for the MCP endpoint, used by MCP clients that cannot be configured with a static access token. Requires mcpEnabled and a configured serviceUrl. Disabled by default'
349
+ ),
350
+
333
351
  /* ────────────── Document Store (Deprecated) ────────────── */
334
352
 
335
353
  documentStoreEnabled: Joi.boolean()
@@ -2267,14 +2285,14 @@ const messageReferenceSchema = Joi.object({
2267
2285
  .truthy('Y', 'true', '1')
2268
2286
  .falsy('N', 'false', 0)
2269
2287
  .default(false)
2270
- .description('Include the original message as quoted text in the response')
2288
+ .description('Quote the referenced message under the new text, the way an email client does. Without it only the new text is sent')
2271
2289
  .label('InlineReply'),
2272
2290
 
2273
2291
  forwardAttachments: Joi.boolean()
2274
2292
  .truthy('Y', 'true', '1')
2275
2293
  .falsy('N', 'false', 0)
2276
2294
  .default(false)
2277
- .description('Include original attachments when forwarding')
2295
+ .description('Carry the attachments of the referenced message over to the forwarded copy. Only valid when action is "forward"')
2278
2296
  .when('action', {
2279
2297
  is: 'forward',
2280
2298
  then: Joi.optional(),
@@ -2299,7 +2317,10 @@ const messageReferenceSchema = Joi.object({
2299
2317
  documentStore: documentStoreSchema.default(false).meta({ swaggerHidden: true })
2300
2318
  })
2301
2319
  .or('message', 'threadId')
2302
- .description('Configuration for replying to or forwarding an existing message')
2320
+ .description(
2321
+ 'Reply to or forward a stored message. EmailEngine fills in the subject, the recipients and the In-Reply-To/References headers from the ' +
2322
+ 'referenced message, and flags it as answered or forwarded once the new message is sent, so only the new content has to be supplied'
2323
+ )
2303
2324
  .label('MessageReference');
2304
2325
 
2305
2326
  const idempotencyKeySchema = Joi.string()
package/lib/settings.js CHANGED
@@ -254,6 +254,19 @@ module.exports = {
254
254
  return (await redis.hsetnx(`${REDIS_PREFIX}settings`, key, value)) === 1;
255
255
  },
256
256
 
257
+ // Like setIfMissing(), but stamps a marker key in the same atomic Redis step when the value
258
+ // was stored. For seeded defaults whose marker says "the seeder still owns this value":
259
+ // written as two separate commands, a crash between them leaves the seeded value behind with
260
+ // no marker, indistinguishable from an explicit operator choice (see setLicense()).
261
+ async setIfMissingWithMarker(key, value, markerKey, markerValue) {
262
+ const encryptSecret = await getSecret();
263
+
264
+ value = module.exports.encodeSettingValue(key, module.exports.formatSettingValue(key, value), encryptSecret);
265
+ markerValue = module.exports.encodeSettingValue(markerKey, module.exports.formatSettingValue(markerKey, markerValue), encryptSecret);
266
+
267
+ return (await redis.hSetNewMark(`${REDIS_PREFIX}settings`, key, value, markerKey, markerValue)) === 1;
268
+ },
269
+
257
270
  async setMulti(obj) {
258
271
  const encryptSecret = await getSecret();
259
272
  let docStoreUpdated = false;
@@ -398,17 +411,18 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
398
411
 
399
412
  // Trial installations report errors to the shared community Sentry by default, so issues
400
413
  // with evaluation instances reach the developers. The default is only applied while the
401
- // operator has never touched the sentryEnabled setting (atomic through setIfMissing),
402
- // tracked through the internal sentryAutoEnabled marker: activating a full license or
403
- // removing the license clears the default again as long as the marker still owns the
404
- // state, and any explicit operator write to sentryEnabled drops the marker (see
405
- // set()/setMulti()), making that choice permanent. A SENTRY_DSN environment value pins
406
- // the Sentry configuration regardless of these settings. License activation must never
407
- // fail on this convenience, hence the catch-all.
414
+ // operator has never touched the sentryEnabled setting, tracked through the internal
415
+ // sentryAutoEnabled marker; the value and the marker are written in one atomic step
416
+ // (setIfMissingWithMarker), because a value stored without its marker would read as a
417
+ // permanent operator opt-in. Activating a full license or removing the license clears
418
+ // the default again as long as the marker still owns the state, and any explicit
419
+ // operator write to sentryEnabled drops the marker (see set()/setMulti()), making that
420
+ // choice permanent. A SENTRY_DSN environment value pins the Sentry configuration
421
+ // regardless of these settings. License activation must never fail on this convenience,
422
+ // hence the catch-all.
408
423
  try {
409
424
  if (licenseData.trial) {
410
- if (await module.exports.setIfMissing('sentryEnabled', true)) {
411
- await module.exports.set('sentryAutoEnabled', true);
425
+ if (await module.exports.setIfMissingWithMarker('sentryEnabled', true, 'sentryAutoEnabled', true)) {
412
426
  logger.info({ msg: 'Enabled Sentry error reporting for the trial license' });
413
427
  }
414
428
  } else {