emailengine-app 2.76.0 → 2.78.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 (165) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.github/workflows/test.yml +80 -0
  3. package/.ncurc.js +14 -2
  4. package/.release-please-manifest.json +3 -0
  5. package/CHANGELOG.md +54 -0
  6. package/README.md +1 -1
  7. package/bin/emailengine.js +1 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +72 -5
  10. package/lib/account/expected-identity.js +88 -0
  11. package/lib/account.js +75 -26
  12. package/lib/address-strategies.js +18 -0
  13. package/lib/api-reference/code-samples.js +194 -0
  14. package/lib/api-reference/format.js +193 -0
  15. package/lib/api-reference/index.js +222 -0
  16. package/lib/api-reference/model.js +338 -0
  17. package/lib/api-reference/schema-tree.js +366 -0
  18. package/lib/api-routes/account-routes.js +136 -39
  19. package/lib/api-routes/behavior-notes.js +57 -0
  20. package/lib/api-routes/blocklist-routes.js +9 -9
  21. package/lib/api-routes/changes-routes.js +6 -4
  22. package/lib/api-routes/chat-routes.js +3 -3
  23. package/lib/api-routes/delivery-test-routes.js +24 -6
  24. package/lib/api-routes/export-routes.js +14 -12
  25. package/lib/api-routes/gateway-routes.js +11 -11
  26. package/lib/api-routes/license-routes.js +7 -7
  27. package/lib/api-routes/mailbox-routes.js +18 -9
  28. package/lib/api-routes/message-routes.js +55 -35
  29. package/lib/api-routes/oauth2-app-routes.js +22 -16
  30. package/lib/api-routes/outbox-routes.js +7 -7
  31. package/lib/api-routes/pubsub-routes.js +3 -3
  32. package/lib/api-routes/settings-routes.js +10 -9
  33. package/lib/api-routes/stats-routes.js +3 -3
  34. package/lib/api-routes/submit-routes.js +58 -8
  35. package/lib/api-routes/template-routes.js +13 -13
  36. package/lib/api-routes/token-routes.js +15 -10
  37. package/lib/api-routes/webhook-route-routes.js +5 -5
  38. package/lib/append-list.js +3 -14
  39. package/lib/arf-detect.js +23 -1
  40. package/lib/autodetect-imap-settings.js +40 -16
  41. package/lib/base32.js +30 -0
  42. package/lib/bounce-detect.js +182 -62
  43. package/lib/consts.js +7 -0
  44. package/lib/egress-filter.js +89 -8
  45. package/lib/email-client/base-client.js +72 -82
  46. package/lib/email-client/gmail-client.js +3 -3
  47. package/lib/email-client/imap/listing-diff.js +3 -3
  48. package/lib/email-client/imap/mailbox.js +5 -69
  49. package/lib/email-client/imap-client.js +3 -2
  50. package/lib/email-client/message-builder.js +13 -13
  51. package/lib/email-client/outlook-client.js +1 -1
  52. package/lib/enum-descriptions.js +130 -0
  53. package/lib/export.js +1 -1
  54. package/lib/gateway.js +1 -1
  55. package/lib/get-raw-email.js +1 -1
  56. package/lib/imapproxy/imap-core/lib/imap-connection.js +2 -2
  57. package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
  58. package/lib/imapproxy/imap-server.js +42 -28
  59. package/lib/imapproxy/upstream-client.js +38 -0
  60. package/lib/license-beacon.js +1 -1
  61. package/lib/llm-pre-process.js +1 -1
  62. package/lib/msgpack.js +62 -0
  63. package/lib/oauth/decode-jwt-payload.js +39 -0
  64. package/lib/oauth/outlook-identity.js +61 -0
  65. package/lib/oauth/retry-setup.js +38 -0
  66. package/lib/oauth2-apps.js +10 -4
  67. package/lib/openapi/build-document.js +318 -0
  68. package/lib/openapi/index.js +95 -0
  69. package/lib/openapi/joi-schema.js +523 -0
  70. package/lib/outbox.js +66 -3
  71. package/lib/pre-process.js +1 -1
  72. package/lib/read-env-value.js +37 -0
  73. package/lib/routes-ui.js +5 -1
  74. package/lib/schemas.js +88 -17
  75. package/lib/swagger-options.js +173 -0
  76. package/lib/templates.js +1 -1
  77. package/lib/tokens.js +70 -6
  78. package/lib/tools.js +117 -48
  79. package/lib/totp.js +67 -0
  80. package/lib/ui-routes/account-routes.js +91 -15
  81. package/lib/ui-routes/admin-config-routes.js +2 -7
  82. package/lib/ui-routes/admin-entities-routes.js +3 -0
  83. package/lib/ui-routes/auth-routes.js +6 -24
  84. package/lib/ui-routes/dashboard-routes.js +2 -26
  85. package/lib/ui-routes/reference-routes.js +198 -0
  86. package/lib/ui-routes/route-helpers.js +39 -0
  87. package/lib/utils/is-email.js +34 -0
  88. package/lib/utils/to-camel-case.js +17 -0
  89. package/lib/webhook-egress.js +37 -0
  90. package/lib/webhooks.js +1 -1
  91. package/package.json +27 -31
  92. package/prepare-bundle-deps.sh +28 -0
  93. package/release-please-config.json +11 -0
  94. package/sbom.json +1 -1
  95. package/server.js +11 -3
  96. package/static/css/flyonui.css +1 -1
  97. package/static/css/public.css +3 -0
  98. package/static/css/src/app.tailwind.css +113 -0
  99. package/static/js/app.js +69 -0
  100. package/static/js/ee-client.js +238 -8
  101. package/static/js/reference.js +1021 -0
  102. package/static/js/ui.js +61 -33
  103. package/static/licenses.html +658 -1560
  104. package/translations/README.md +64 -0
  105. package/translations/de.mo +0 -0
  106. package/translations/de.po +164 -120
  107. package/translations/en.po +200 -161
  108. package/translations/et.mo +0 -0
  109. package/translations/et.po +163 -120
  110. package/translations/fr.mo +0 -0
  111. package/translations/fr.po +163 -120
  112. package/translations/ja.mo +0 -0
  113. package/translations/ja.po +163 -120
  114. package/translations/messages.pot +84 -54
  115. package/translations/nl.mo +0 -0
  116. package/translations/nl.po +164 -120
  117. package/translations/pl.mo +0 -0
  118. package/translations/pl.po +163 -120
  119. package/views/account-identity-error.hbs +34 -0
  120. package/views/accounts/edit.hbs +1 -0
  121. package/views/accounts/register/imap.hbs +12 -2
  122. package/views/config/ai.hbs +1 -1
  123. package/views/config/document-store/chat.hbs +5 -5
  124. package/views/config/document-store/index.hbs +2 -2
  125. package/views/config/document-store/pre-processing/index.hbs +1 -1
  126. package/views/config/email-processing.hbs +1 -1
  127. package/views/config/imap-proxy.hbs +1 -1
  128. package/views/config/license.hbs +1 -1
  129. package/views/config/oauth/index.hbs +3 -3
  130. package/views/config/security.hbs +1 -1
  131. package/views/config/smtp.hbs +2 -2
  132. package/views/dashboard.hbs +1 -1
  133. package/views/layout/app.hbs +43 -8
  134. package/views/oauth-scope-error.hbs +1 -1
  135. package/views/partials/oauth_form.hbs +4 -4
  136. package/views/partials/reference/anchor-link.hbs +20 -0
  137. package/views/partials/reference/disclosure.hbs +37 -0
  138. package/views/partials/reference/nav.hbs +120 -0
  139. package/views/partials/reference/operation.hbs +127 -0
  140. package/views/partials/reference/params.hbs +20 -0
  141. package/views/partials/reference/schema-node.hbs +99 -0
  142. package/views/partials/reference/schema.hbs +19 -0
  143. package/views/partials/reference/section-heading.hbs +16 -0
  144. package/views/partials/reference/token-alert.hbs +49 -0
  145. package/views/partials/reference/try-field.hbs +31 -0
  146. package/views/partials/reference/try-it.hbs +78 -0
  147. package/views/partials/side_menu.hbs +1 -1
  148. package/views/partials/ui/badge.hbs +4 -2
  149. package/views/partials/ui/page-header.hbs +1 -1
  150. package/views/partials/ui/search-input.hbs +31 -0
  151. package/views/partials/ui/setting-ref.hbs +1 -1
  152. package/views/partials/ui/stat-card.hbs +4 -2
  153. package/views/partials/ui/tab.hbs +6 -1
  154. package/views/partials/ui/tabs.hbs +2 -2
  155. package/views/reference/index.hbs +76 -0
  156. package/views/reference/redirect.hbs +49 -0
  157. package/views/reference/tag.hbs +28 -0
  158. package/views/reference/token.hbs +49 -0
  159. package/views/tokens/index.hbs +9 -1
  160. package/views/webhooks/index.hbs +3 -3
  161. package/workers/api.js +194 -302
  162. package/workers/imap.js +1 -1
  163. package/workers/submit.js +1 -1
  164. package/workers/webhooks.js +2 -13
  165. package/views/swagger/index.hbs +0 -82
package/lib/schemas.js CHANGED
@@ -41,12 +41,6 @@ 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 ADDRESS_STRATEGIES = [
45
- { key: 'default', title: 'Default' },
46
- { key: 'dedicated', title: 'Dedicated' },
47
- { key: 'random', title: 'Random' }
48
- ];
49
-
50
44
  const accountIdSchema = Joi.string().empty('').trim().max(256).example('user123').description('Unique identifier for the email account');
51
45
 
52
46
  // The service-secret-signed blob (base64url `data` + its HMAC `sig`) carried by every hosted
@@ -66,6 +60,28 @@ const signedFormBlobFields = {
66
60
  // machine states, 'disconnected' and 'paused' are client-level display states set by imap-client
67
61
  const ACCOUNT_DISPLAY_STATES = [...Object.values(ACCOUNT_STATES), 'disconnected', 'paused'];
68
62
 
63
+ const { ADDRESS_STRATEGIES } = require('./address-strategies');
64
+ const { ENUM_DESCRIPTIONS } = require('./enum-descriptions');
65
+
66
+ // Account identity as the API describes it. These live here rather than next to the routes that use
67
+ // them because they are derived from the OAuth2 provider list, and a copy in a test fixture would
68
+ // document a different set of providers than the server accepts.
69
+ const oauth2ProviderSchema = Joi.string()
70
+ .valid(...Object.keys(OAUTH_PROVIDERS))
71
+ .required()
72
+ .example('gmail')
73
+ .description('OAuth2 provider')
74
+ .label('OAuth2Provider');
75
+
76
+ const accountTypeSchema = Joi.string()
77
+ .valid(...['imap'].concat(Object.keys(OAUTH_PROVIDERS)).concat(['oauth2', 'delegated', 'sending', 'invalid']))
78
+ .example('outlook')
79
+ .description(
80
+ 'Account type: "imap" for IMAP accounts, an OAuth2 provider name for OAuth2 accounts, "oauth2" when the OAuth2 application is missing, "delegated" for delegated accounts, "sending" for send-only accounts, "invalid" when delegation cannot be resolved'
81
+ )
82
+ .required()
83
+ .label('AccountType');
84
+
69
85
  // Allowed configuration keys
70
86
  const settingsSchema = {
71
87
  /* ────────────── Webhooks ────────────── */
@@ -446,12 +462,14 @@ const settingsSchema = {
446
462
  .empty('')
447
463
  .valid(...ADDRESS_STRATEGIES.map(entry => entry.key))
448
464
  .description('IP address selection strategy for outbound IMAP connections when multiple local addresses are available')
465
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.addressStrategy })
449
466
  .label('ImapStrategy'),
450
467
 
451
468
  smtpStrategy: Joi.string()
452
469
  .empty('')
453
470
  .valid(...ADDRESS_STRATEGIES.map(entry => entry.key))
454
471
  .description('IP address selection strategy for outbound SMTP connections when multiple local addresses are available')
472
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.addressStrategy })
455
473
  .label('SmtpStrategy'),
456
474
 
457
475
  localAddresses: Joi.array()
@@ -1020,12 +1038,14 @@ const messageSpecialUseSchema = Joi.string()
1020
1038
  .example('\\Sent')
1021
1039
  .valid('\\Drafts', '\\Junk', '\\Sent', '\\Trash', '\\Inbox')
1022
1040
  .description('Special folder type where this message is stored')
1041
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.mailboxSpecialUse })
1023
1042
  .label('MessageSpecialUse');
1024
1043
 
1025
1044
  const messageCategorySchema = Joi.string()
1026
1045
  .example('primary')
1027
1046
  .valid('primary', 'social', 'promotions', 'updates', 'forums')
1028
1047
  .description('Gmail inbox tab/category of the message (Gmail API accounts only)')
1048
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.messageCategory })
1029
1049
  .label('MessageCategory');
1030
1050
 
1031
1051
  const bounceListSchema = Joi.array()
@@ -1163,6 +1183,7 @@ const messageDetailsSchema = Joi.object({
1163
1183
  .example('\\Sent')
1164
1184
  .valid('\\All', '\\Archive', '\\Drafts', '\\Flagged', '\\Junk', '\\Sent', '\\Trash', '\\Inbox')
1165
1185
  .description('Special folder type of the mailbox containing this message (IMAP accounts only)')
1186
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.mailboxSpecialUse })
1166
1187
  .label('MailboxSpecialUse'),
1167
1188
  messageSpecialUse: messageSpecialUseSchema
1168
1189
  }).label('MessageDetails');
@@ -1542,6 +1563,13 @@ const messageUpdateSchema = Joi.object({
1542
1563
  }
1543
1564
  });
1544
1565
 
1566
+ // The update variant below is derived from this one, so the two cannot drift apart in the published API
1567
+ // document - only the "how to clear it" sentence differs.
1568
+ const EXPECTED_EMAIL_DESCRIPTION =
1569
+ 'Pins the account to an email address. A hosted authentication form setup is rejected unless the identity it authenticates matches this address. For OAuth2 the address is compared against what the provider returns, never against caller-supplied hints, so for a shared or delegated mailbox this must be the authenticating principal rather than the mailbox address. For IMAP it is compared against the address entered on the form, which the credentials do not prove ownership of. Once set, the constraint stays on the account and applies to later reauthentication as well.';
1570
+
1571
+ const expectedEmailSchema = Joi.string().empty('').email().example('user@example.com').description(EXPECTED_EMAIL_DESCRIPTION);
1572
+
1545
1573
  const accountSchemas = {
1546
1574
  syncFrom: Joi.date()
1547
1575
  .iso()
@@ -1565,6 +1593,11 @@ const accountSchemas = {
1565
1593
  )
1566
1594
  .label('SubconnectionPaths'),
1567
1595
 
1596
+ expectedEmail: expectedEmailSchema,
1597
+
1598
+ // Same field on the update endpoint, where null clears the constraint.
1599
+ expectedEmailUpdate: expectedEmailSchema.allow(null).description(`${EXPECTED_EMAIL_DESCRIPTION} Set to \`null\` to remove the constraint.`),
1600
+
1568
1601
  imapIndexer: Joi.string()
1569
1602
  .empty('')
1570
1603
  .trim()
@@ -1622,6 +1655,7 @@ const oauthCreateSchema = {
1622
1655
  .example('gmail')
1623
1656
  .required()
1624
1657
  .description('OAuth2 provider type')
1658
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.oauth2Provider })
1625
1659
  .label('CreateOAuth2Provider'),
1626
1660
 
1627
1661
  enabled: Joi.boolean()
@@ -1804,6 +1838,7 @@ const oauthCreateSchema = {
1804
1838
  })
1805
1839
  .example('global')
1806
1840
  .description('Microsoft Azure cloud environment')
1841
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.azureCloud })
1807
1842
  .label('AzureCloud'),
1808
1843
 
1809
1844
  tenant: Joi.any().alter({
@@ -2092,7 +2127,12 @@ const defaultAccountTypeSchema = Joi.string()
2092
2127
  const outboxEntrySchema = Joi.object({
2093
2128
  queueId: Joi.string().example('1869c5692565f756b33').description('Unique queue entry identifier'),
2094
2129
  account: accountIdSchema.required(),
2095
- source: Joi.string().example('smtp').valid('smtp', 'api', 'test', 'ui').description('How this message entered the queue').label('OutboxSource'),
2130
+ source: Joi.string()
2131
+ .example('smtp')
2132
+ .valid('smtp', 'api', 'test', 'ui')
2133
+ .description('How this message entered the queue')
2134
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.outboxSource })
2135
+ .label('OutboxSource'),
2096
2136
 
2097
2137
  messageId: Joi.string().max(996).example('<test123@example.com>').description('Message-ID header value'),
2098
2138
  envelope: Joi.object({
@@ -2132,6 +2172,7 @@ const outboxEntrySchema = Joi.object({
2132
2172
  .valid('queued', 'processing', 'smtp-starting', 'smtp-completed', 'submitted', 'error')
2133
2173
  .example('queued')
2134
2174
  .description('Current delivery status')
2175
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.outboxStatus })
2135
2176
  .label('OutboxStatus'),
2136
2177
  response: Joi.string().example('250 Message Accepted').description('SMTP server response (when status is "submitted" or "smtp-completed")'),
2137
2178
  messageId: Joi.string().example('<test123@example.com>').description('Message-ID header value of the sent message (when status is "smtp-completed")'),
@@ -2228,6 +2269,14 @@ const headerTimeoutSchema = Joi.number()
2228
2269
  .description('Request timeout in milliseconds (overrides EENGINE_TIMEOUT environment variable)')
2229
2270
  .label('X-EE-Timeout');
2230
2271
 
2272
+ // Headers every API route accepts, applied as a server-wide route default in workers/api.js rather
2273
+ // than being repeated per route. Exported because it also reaches the generated OpenAPI document -
2274
+ // every operation documents this header - so anything reproducing that document has to apply the
2275
+ // same default (test/helpers/build-openapi-spec.js).
2276
+ const apiHeadersSchema = Joi.object({
2277
+ 'x-ee-timeout': headerTimeoutSchema
2278
+ }).unknown();
2279
+
2231
2280
  // Export schemas
2232
2281
  const exportRequestSchema = Joi.object({
2233
2282
  folders: Joi.array()
@@ -2282,7 +2331,12 @@ const exportStatusSchema = Joi.object({
2282
2331
  .example('processing')
2283
2332
  .description('Export status')
2284
2333
  .label('ExportStatusValue'),
2285
- phase: Joi.string().valid('indexing', 'exporting', 'complete').example('indexing').description('Current export phase').label('ExportPhase'),
2334
+ phase: Joi.string()
2335
+ .valid('indexing', 'exporting', 'complete')
2336
+ .example('indexing')
2337
+ .description('Current export phase')
2338
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.exportPhase })
2339
+ .label('ExportPhase'),
2286
2340
  folders: Joi.array().items(Joi.string().label('ExportFolderItem')).description('Folders being exported').label('ExportStatusFolders'),
2287
2341
  startDate: Joi.date().iso().example('2024-01-01T00:00:00Z').description('Export start date filter'),
2288
2342
  endDate: Joi.date().iso().example('2024-12-31T23:59:59Z').description('Export end date filter'),
@@ -2302,6 +2356,7 @@ const exportListEntrySchema = Joi.object({
2302
2356
  .valid('queued', 'processing', 'completed', 'failed', 'cancelled')
2303
2357
  .example('completed')
2304
2358
  .description('Export status')
2359
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.exportStatus })
2305
2360
  .label('ExportListStatusValue'),
2306
2361
  created: Joi.date().iso().example('2024-01-15T10:30:00Z').description('When export was created'),
2307
2362
  expiresAt: Joi.date().iso().example('2024-01-16T10:30:00Z').description('When export file expires')
@@ -2322,12 +2377,11 @@ const exportIdSchema = Joi.string()
2322
2377
  .label('ExportId');
2323
2378
 
2324
2379
  // Boom-style error payloads returned by failed API requests. These schemas are used for API
2325
- // documentation only - they are rendered as error response examples in Swagger UI through the
2326
- // plugins['hapi-swagger'].responses route option and are never used to validate or modify
2327
- // actual responses at runtime.
2380
+ // documentation only - they reach the OpenAPI document through the plugins.openapi.responses
2381
+ // route option and are never used to validate or modify actual responses at runtime.
2328
2382
 
2329
2383
  // Builds one documented error response: a response description (shown next to the status code
2330
- // in Swagger UI) paired with a labeled Joi schema for the Boom-style error payload. The
2384
+ // in the API reference) paired with a labeled Joi schema for the Boom-style error payload. The
2331
2385
  // optional extra fields document values that EmailEngine adds to the base
2332
2386
  // { statusCode, error, message } payload for that error type.
2333
2387
  const errorResponseEntry = ({ statusCode, statusText, messageExample, label, title, description, fields }) => ({
@@ -2443,10 +2497,10 @@ const errorResponseSchemas = {
2443
2497
  })
2444
2498
  };
2445
2499
 
2446
- // Builds the value for the plugins['hapi-swagger'].responses route option from a list of HTTP
2447
- // error status codes, so that error responses are rendered in Swagger UI in addition to the
2448
- // 200 response that hapi-swagger picks up from the route's response.schema option. This is
2449
- // documentation only and does not affect request processing in any way.
2500
+ // Builds the value for the plugins.openapi.responses route option from a list of HTTP error
2501
+ // status codes, so that error responses are documented in addition to the 200 response the
2502
+ // generator picks up from the route's response.schema option. This is documentation only and
2503
+ // does not affect request processing in any way.
2450
2504
  function errorResponses(...statusCodes) {
2451
2505
  let responses = {};
2452
2506
  for (let statusCode of statusCodes) {
@@ -2458,6 +2512,19 @@ function errorResponses(...statusCodes) {
2458
2512
  return responses;
2459
2513
  }
2460
2514
 
2515
+ // Builds the full `responses` value for a route: the documented success case plus the
2516
+ // error cases. The generator derives a 200 entry from the route's response.schema but can
2517
+ // only label it "Successful", and for a raw stream or binary body there is no schema to
2518
+ // derive anything from - so the description is stated here. It is documentation only and
2519
+ // never affects request processing.
2520
+ //
2521
+ // `description` should say what the caller gets back, in the style of "Returns the
2522
+ // updated account." Passing it per route rather than putting it on the joi response
2523
+ // schema keeps it operation-specific, since several operations share a response schema.
2524
+ function apiResponses(description, ...statusCodes) {
2525
+ return Object.assign({ 200: { description } }, errorResponses(...statusCodes));
2526
+ }
2527
+
2461
2528
  module.exports = {
2462
2529
  ADDRESS_STRATEGIES,
2463
2530
  ACCOUNT_DISPLAY_STATES,
@@ -2489,6 +2556,9 @@ module.exports = {
2489
2556
  oauthUpdateSchema,
2490
2557
  tokenRestrictionsSchema,
2491
2558
  accountIdSchema,
2559
+ oauth2ProviderSchema,
2560
+ accountTypeSchema,
2561
+ apiHeadersSchema,
2492
2562
  ipSchema,
2493
2563
  tokenIdSchema,
2494
2564
  accountCountersSchema,
@@ -2515,7 +2585,8 @@ module.exports = {
2515
2585
  exportProgressSchema,
2516
2586
  exportIdSchema,
2517
2587
  pubSubErrorSchema,
2518
- errorResponses
2588
+ apiResponses,
2589
+ ENUM_DESCRIPTIONS
2519
2590
  };
2520
2591
 
2521
2592
  /*
@@ -0,0 +1,173 @@
1
+ 'use strict';
2
+
3
+ // Everything that describes the API document itself: the tag list and its order, the security
4
+ // scheme, external docs, the logo. The generator that consumes them lives in lib/openapi/.
5
+ //
6
+ // Kept separate from workers/api.js so the generated document can be reproduced outside a
7
+ // running server - test/helpers/build-openapi-spec.js registers the real route table and
8
+ // these options to build the same spec in-process. A copy in the test would silently drift,
9
+ // and `tags` is not cosmetic: it drives the tag ORDER and descriptions that the API
10
+ // reference navigation is built from (lib/api-reference/model.js).
11
+ //
12
+ // The remaining options (cors, info) stay in workers/api.js, where the values they depend on
13
+ // live.
14
+
15
+ module.exports = {
16
+ // Everything about the document that does not change between installs. workers/api.js
17
+ // merges in the one field that does - `version`, which it reads from package.json - so
18
+ // this stays reproducible outside a running server and the tests can see all of it.
19
+ //
20
+ // The description has two renderers: every consumer of /swagger.json, and the admin
21
+ // reference landing page, which shows it in place of prose of its own so those facts have
22
+ // one source (lib/api-reference/model.js -> views/reference/index.hbs).
23
+ //
24
+ // That second renderer makes the FORMAT load-bearing. Paragraphs, `code spans` and
25
+ // absolute links only - no headings, no lists, no raw HTML. formatDescription() in
26
+ // lib/api-reference/format.js escapes first and adds back a closed tag set, so anything
27
+ // outside that subset shows up as visible literal text. Links have to be absolute too:
28
+ // the document is served from emailengine.dev and read by code generators, where an
29
+ // /admin path points at nothing. The page carries its own buttons to the admin pages.
30
+ info: {
31
+ title: 'EmailEngine API',
32
+
33
+ contact: {
34
+ name: 'EmailEngine Support',
35
+ url: 'https://learn.emailengine.app/docs/support',
36
+ email: 'support@emailengine.app'
37
+ },
38
+
39
+ license: {
40
+ name: 'EmailEngine License',
41
+ url: 'https://emailengine.dev/LICENSE_EMAILENGINE.txt'
42
+ },
43
+
44
+ description: `EmailEngine provides a RESTful API for managing email accounts, sending messages, and processing email data across multiple providers.
45
+
46
+ Every request needs an access token, passed either as an \`Authorization: Bearer <token>\` header or an \`?access_token=\` query argument. Tokens are issued and revoked on the Access Tokens page of the EmailEngine admin interface.
47
+
48
+ Requests against the same email account are processed sequentially to keep its state consistent, so simultaneous calls for one account queue up behind each other. Long-running operations can be given more room with the \`x-ee-timeout\` header, in milliseconds.
49
+
50
+ Every failure returns the same JSON envelope: a numeric \`statusCode\`, a short \`error\` label and a human-readable \`message\`. Each endpoint therefore documents only which status codes it can return and what they mean.
51
+
52
+ Full documentation: https://learn.emailengine.app/`
53
+ },
54
+
55
+ externalDocs: {
56
+ description: 'EmailEngine Documentation',
57
+ url: 'https://learn.emailengine.app/'
58
+ },
59
+
60
+ securityDefinitions: {
61
+ bearerAuth: {
62
+ type: 'http',
63
+ scheme: 'bearer',
64
+ bearerFormat: 'JWT',
65
+ description: 'Enter your access token'
66
+ }
67
+ },
68
+
69
+ security: [{ bearerAuth: [] }],
70
+
71
+ tags: [
72
+ {
73
+ name: 'Account',
74
+ description: 'Manage email accounts, including IMAP/SMTP configuration, OAuth2 authentication, and account health monitoring'
75
+ },
76
+ {
77
+ name: 'Mailbox',
78
+ description: 'List, create, modify, and manage mailbox folders. Retrieve folder statistics and special-use designations'
79
+ },
80
+ {
81
+ name: 'Message',
82
+ description: 'Search, retrieve, update, and delete email messages. Manage flags, labels, and message content'
83
+ },
84
+ {
85
+ name: 'Submit',
86
+ description:
87
+ 'Send emails with attachments, reply to threads, forward messages, and upload to folders. Supports both immediate and scheduled sending',
88
+ externalDocs: {
89
+ description: 'Sending Emails Documentation',
90
+ url: 'https://learn.emailengine.app/docs/sending'
91
+ }
92
+ },
93
+ {
94
+ name: 'Outbox',
95
+ description: 'Monitor and manage the email sending queue. View pending messages, retry failed deliveries, and track sending progress'
96
+ },
97
+ {
98
+ name: 'Delivery Test',
99
+ description: 'Test email deliverability and authentication. Verify SPF, DKIM signatures, DMARC alignment, and analyze potential delivery issues'
100
+ },
101
+ {
102
+ name: 'Access Tokens',
103
+ description: 'Create and manage API access tokens with customizable permissions, IP restrictions, and rate limits'
104
+ },
105
+ {
106
+ name: 'Settings',
107
+ description: 'Configure EmailEngine runtime settings including webhooks, tracking, AI features, and email processing options'
108
+ },
109
+ {
110
+ name: 'Templates',
111
+ description: 'Create and manage reusable email templates with variable substitution, HTML/text content, and attachments',
112
+ externalDocs: {
113
+ description: 'Email Templates Documentation',
114
+ url: 'https://learn.emailengine.app/docs/sending/templates'
115
+ }
116
+ },
117
+ {
118
+ name: 'Logs',
119
+ description: 'Access system and account-level logs for debugging, monitoring, and audit purposes'
120
+ },
121
+ {
122
+ name: 'Stats',
123
+ description: 'Retrieve usage statistics, performance metrics, and account activity data',
124
+ externalDocs: {
125
+ description: 'Monitoring and Analytics',
126
+ url: 'https://learn.emailengine.app/docs/advanced/monitoring'
127
+ }
128
+ },
129
+ {
130
+ name: 'License',
131
+ description: 'Manage EmailEngine licensing, view license status, and handle license-related operations'
132
+ },
133
+ {
134
+ name: 'Webhooks',
135
+ description: 'Configure webhook endpoints, manage event subscriptions, and monitor webhook delivery status',
136
+ externalDocs: {
137
+ description: 'Webhooks Guide',
138
+ url: 'https://learn.emailengine.app/docs/webhooks/overview'
139
+ }
140
+ },
141
+ {
142
+ name: 'OAuth2 Applications',
143
+ description: 'Configure OAuth2 applications for Gmail, Outlook, and other providers. Manage client credentials and authentication flows',
144
+ externalDocs: {
145
+ description: 'OAuth2 Configuration Guide',
146
+ url: 'https://learn.emailengine.app/docs/configuration/oauth2-configuration'
147
+ }
148
+ },
149
+ {
150
+ name: 'SMTP Gateway',
151
+ description: 'Configure and manage the built-in SMTP server for receiving emails and integrating with external systems'
152
+ },
153
+ {
154
+ name: 'Blocklists',
155
+ description: 'Manage email address blocklists to prevent sending to specific recipients or domains'
156
+ },
157
+ {
158
+ name: 'Multi Message Actions',
159
+ description: 'Perform bulk operations on multiple messages simultaneously, such as marking as read, moving, or deleting'
160
+ },
161
+ {
162
+ name: 'Export (Beta)',
163
+ description:
164
+ 'Bulk export messages from email accounts. This feature is in beta and the API may change in future releases. Export files are encrypted at rest when a service secret is configured.'
165
+ }
166
+ ],
167
+
168
+ // Custom vendor extensions for additional metadata
169
+ 'x-logo': {
170
+ url: 'https://emailengine.dev/static/logo.png',
171
+ altText: 'EmailEngine Logo'
172
+ }
173
+ };
package/lib/templates.js CHANGED
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const { redis } = require('./db');
4
- const msgpack = require('msgpack5')();
4
+ const msgpack = require('./msgpack');
5
5
  const logger = require('./logger');
6
6
  const { REDIS_PREFIX } = require('./consts');
7
7
  const { filterListPage } = require('./tools');
package/lib/tokens.js CHANGED
@@ -2,13 +2,31 @@
2
2
 
3
3
  const { redis } = require('./db');
4
4
  const crypto = require('crypto');
5
- const msgpack = require('msgpack5')();
5
+ const msgpack = require('./msgpack');
6
6
  const logger = require('./logger');
7
7
  const { REDIS_PREFIX } = require('./consts');
8
8
  const { constantTimeEqual, filterListPage } = require('./tools');
9
9
 
10
10
  const SESS_PREFIX = 'sess_';
11
11
 
12
+ // Best-effort removal of an expired token record. Fired from both of the places that can
13
+ // notice the expiry - get(), when someone presents the token, and list(), when someone views
14
+ // the token list. Both are needed: a token that is minted and then never used is never
15
+ // resolved through get(), so before list() also reaped, such a record sat in Redis forever
16
+ // even though it could no longer authenticate.
17
+ //
18
+ // Done with raw commands rather than through delete(), which resolves the token through
19
+ // get() and would recurse back into the expiry check.
20
+ function reapExpiredToken(hashedToken, account) {
21
+ redis
22
+ .multi()
23
+ .hdel(`${REDIS_PREFIX}tokens`, hashedToken)
24
+ .hdel(`${REDIS_PREFIX}tokens:access`, hashedToken)
25
+ .srem(account ? `${REDIS_PREFIX}iat:${account}` : `${REDIS_PREFIX}iat`, hashedToken)
26
+ .exec()
27
+ .catch(err => logger.error({ msg: 'Failed to clean up an expired access token', hash: hashedToken, err }));
28
+ }
29
+
12
30
  module.exports = {
13
31
  async getSessionToken(sessionId, account, ttl) {
14
32
  const token = crypto.randomBytes(32);
@@ -97,7 +115,7 @@ module.exports = {
97
115
  */
98
116
  async provision(opts) {
99
117
  opts = opts || {};
100
- const { account, restrictions, ip, remoteAddress, description, metadata, scopes, nolog } = opts;
118
+ const { account, restrictions, ip, remoteAddress, description, metadata, scopes, nolog, expires } = opts;
101
119
 
102
120
  const token = crypto.randomBytes(32);
103
121
  const hashedToken = crypto.createHash('sha256').update(token).digest('hex');
@@ -108,6 +126,22 @@ module.exports = {
108
126
  created: now.getTime()
109
127
  };
110
128
 
129
+ // Optional lifetime. Tokens live in a Redis hash, whose fields cannot carry their
130
+ // own TTL, so expiry is stored on the record and enforced in get() below - which
131
+ // is the single validation point for every token consumer.
132
+ if (expires) {
133
+ const expiresAt = expires instanceof Date ? expires.getTime() : Number(expires);
134
+ // Reject rather than coerce: Number('soon') is NaN, and NaN is falsy at the
135
+ // check in get(), so a malformed value would silently mean "never expires" -
136
+ // fail-open on the one field that limits a credential's lifetime.
137
+ if (!Number.isFinite(expiresAt)) {
138
+ let err = new Error('Invalid token expiry');
139
+ err.code = 'InvalidExpiry';
140
+ throw err;
141
+ }
142
+ tokenData.expires = expiresAt;
143
+ }
144
+
111
145
  if (account) {
112
146
  tokenData.account = account;
113
147
  }
@@ -183,6 +217,20 @@ module.exports = {
183
217
 
184
218
  let tokenData = msgpack.decode(tokenDataEncoded);
185
219
 
220
+ // Expiry check. This is the only place tokens are validated (lib/auth-token.js for
221
+ // SMTP/IMAP-proxy auth and the api-token strategy in workers/api.js are the two
222
+ // callers), so an expired token stops working everywhere at once.
223
+ //
224
+ // `allowExpired` exists for delete(), which resolves a token through this function:
225
+ // without it an expired token could never be removed, only accumulate.
226
+ if (tokenData.expires && Date.now() >= tokenData.expires && !opts.allowExpired) {
227
+ reapExpiredToken(hashedToken, tokenData.account);
228
+
229
+ let err = new Error('Expired token');
230
+ err.code = 'ExpiredToken';
231
+ throw err;
232
+ }
233
+
186
234
  if (opts.log) {
187
235
  // log access time
188
236
  let accessData = { time: Date.now(), ip: opts.remoteAddress || null };
@@ -205,10 +253,12 @@ module.exports = {
205
253
 
206
254
  let tokenData;
207
255
  try {
208
- tokenData = await module.exports.get(token, true);
256
+ // allowExpired: an expired token must still be removable and inspectable,
257
+ // otherwise it could only accumulate
258
+ tokenData = await module.exports.get(token, true, { allowExpired: true });
209
259
  } catch (err) {
210
260
  try {
211
- tokenData = await module.exports.get(token);
261
+ tokenData = await module.exports.get(token, false, { allowExpired: true });
212
262
  } catch (err) {
213
263
  return false;
214
264
  }
@@ -244,10 +294,12 @@ module.exports = {
244
294
 
245
295
  let tokenData;
246
296
  try {
247
- tokenData = await module.exports.get(token, true);
297
+ // allowExpired: an expired token must still be removable and inspectable,
298
+ // otherwise it could only accumulate
299
+ tokenData = await module.exports.get(token, true, { allowExpired: true });
248
300
  } catch (err) {
249
301
  try {
250
- tokenData = await module.exports.get(token);
302
+ tokenData = await module.exports.get(token, false, { allowExpired: true });
251
303
  } catch (err) {
252
304
  return false;
253
305
  }
@@ -352,7 +404,19 @@ module.exports = {
352
404
  if (entry[1]) {
353
405
  try {
354
406
  let tokenData = msgpack.decode(entry[1]);
407
+
408
+ // An expired token cannot authenticate, so listing it is noise. This
409
+ // is also where a minted-but-never-used token finally gets collected.
410
+ if (tokenData.expires && Date.now() >= tokenData.expires) {
411
+ reapExpiredToken(tokenHash, tokenData.account);
412
+ response.total = Math.max(0, response.total - 1);
413
+ continue;
414
+ }
415
+
355
416
  tokenData.created = new Date(tokenData.created);
417
+ if (tokenData.expires) {
418
+ tokenData.expires = new Date(tokenData.expires);
419
+ }
356
420
  lastEntry = Object.assign({ id: tokenHash }, tokenData);
357
421
  response.tokens.push(lastEntry);
358
422
  } catch (err) {