emailengine-app 2.75.0 → 2.77.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 (113) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.github/workflows/test.yml +0 -10
  3. package/.ncurc.js +14 -2
  4. package/.release-please-manifest.json +3 -0
  5. package/CHANGELOG.md +38 -0
  6. package/README.md +1 -1
  7. package/config/e2e.toml +1 -1
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +71 -4
  10. package/lib/address-strategies.js +18 -0
  11. package/lib/api-reference/code-samples.js +194 -0
  12. package/lib/api-reference/format.js +179 -0
  13. package/lib/api-reference/index.js +205 -0
  14. package/lib/api-reference/model.js +336 -0
  15. package/lib/api-reference/schema-tree.js +366 -0
  16. package/lib/api-routes/account-routes.js +117 -37
  17. package/lib/api-routes/behavior-notes.js +54 -0
  18. package/lib/api-routes/blocklist-routes.js +9 -9
  19. package/lib/api-routes/changes-routes.js +6 -4
  20. package/lib/api-routes/chat-routes.js +3 -3
  21. package/lib/api-routes/delivery-test-routes.js +24 -6
  22. package/lib/api-routes/export-routes.js +14 -12
  23. package/lib/api-routes/gateway-routes.js +11 -11
  24. package/lib/api-routes/license-routes.js +7 -7
  25. package/lib/api-routes/mailbox-routes.js +18 -9
  26. package/lib/api-routes/message-routes.js +55 -35
  27. package/lib/api-routes/oauth2-app-routes.js +22 -16
  28. package/lib/api-routes/outbox-routes.js +7 -7
  29. package/lib/api-routes/pubsub-routes.js +3 -3
  30. package/lib/api-routes/route-helpers.js +3 -0
  31. package/lib/api-routes/settings-routes.js +10 -9
  32. package/lib/api-routes/stats-routes.js +3 -3
  33. package/lib/api-routes/submit-routes.js +213 -56
  34. package/lib/api-routes/template-routes.js +13 -13
  35. package/lib/api-routes/token-routes.js +15 -10
  36. package/lib/api-routes/webhook-route-routes.js +5 -5
  37. package/lib/consts.js +7 -0
  38. package/lib/email-client/base-client.js +230 -31
  39. package/lib/email-client/gmail/send-request.js +16 -1
  40. package/lib/email-client/gmail-client.js +89 -5
  41. package/lib/email-client/imap-client.js +103 -1
  42. package/lib/email-client/message-builder.js +24 -7
  43. package/lib/email-client/outlook/send-request.js +18 -1
  44. package/lib/email-client/outlook-client.js +79 -4
  45. package/lib/enum-descriptions.js +130 -0
  46. package/lib/imapproxy/imap-server.js +30 -26
  47. package/lib/imapproxy/upstream-client.js +38 -0
  48. package/lib/oauth2-apps.js +9 -3
  49. package/lib/openapi/build-document.js +318 -0
  50. package/lib/openapi/index.js +95 -0
  51. package/lib/openapi/joi-schema.js +523 -0
  52. package/lib/routes-ui.js +5 -1
  53. package/lib/schemas.js +76 -17
  54. package/lib/swagger-options.js +173 -0
  55. package/lib/tokens.js +69 -5
  56. package/lib/ui-routes/admin-entities-routes.js +3 -0
  57. package/lib/ui-routes/dashboard-routes.js +2 -26
  58. package/lib/ui-routes/reference-routes.js +195 -0
  59. package/lib/ui-routes/route-helpers.js +11 -0
  60. package/package.json +19 -26
  61. package/playwright.config.js +1 -1
  62. package/prepare-bundle-deps.sh +28 -0
  63. package/release-please-config.json +11 -0
  64. package/sbom.json +0 -1
  65. package/server.js +22 -2
  66. package/static/css/flyonui.css +1 -1
  67. package/static/css/src/app.tailwind.css +90 -0
  68. package/static/js/ee-client.js +238 -8
  69. package/static/js/reference.js +736 -0
  70. package/static/js/ui.js +61 -33
  71. package/static/licenses.html +16 -16
  72. package/translations/messages.pot +13 -13
  73. package/views/config/ai.hbs +1 -1
  74. package/views/config/document-store/chat.hbs +5 -5
  75. package/views/config/document-store/index.hbs +2 -2
  76. package/views/config/document-store/pre-processing/index.hbs +1 -1
  77. package/views/config/email-processing.hbs +1 -1
  78. package/views/config/imap-proxy.hbs +1 -1
  79. package/views/config/license.hbs +1 -1
  80. package/views/config/oauth/index.hbs +3 -3
  81. package/views/config/security.hbs +1 -1
  82. package/views/config/smtp.hbs +2 -2
  83. package/views/dashboard.hbs +1 -1
  84. package/views/layout/app.hbs +18 -7
  85. package/views/partials/oauth_form.hbs +4 -4
  86. package/views/partials/reference/anchor-link.hbs +20 -0
  87. package/views/partials/reference/disclosure.hbs +37 -0
  88. package/views/partials/reference/nav.hbs +93 -0
  89. package/views/partials/reference/operation.hbs +127 -0
  90. package/views/partials/reference/params.hbs +20 -0
  91. package/views/partials/reference/schema-node.hbs +99 -0
  92. package/views/partials/reference/schema.hbs +19 -0
  93. package/views/partials/reference/section-heading.hbs +16 -0
  94. package/views/partials/reference/token-alert.hbs +24 -0
  95. package/views/partials/reference/try-field.hbs +31 -0
  96. package/views/partials/reference/try-it.hbs +78 -0
  97. package/views/partials/side_menu.hbs +1 -1
  98. package/views/partials/ui/badge.hbs +4 -2
  99. package/views/partials/ui/page-header.hbs +1 -1
  100. package/views/partials/ui/search-input.hbs +31 -0
  101. package/views/partials/ui/setting-ref.hbs +1 -1
  102. package/views/partials/ui/stat-card.hbs +4 -2
  103. package/views/partials/ui/tab.hbs +6 -1
  104. package/views/partials/ui/tabs.hbs +2 -2
  105. package/views/reference/index.hbs +76 -0
  106. package/views/reference/redirect.hbs +49 -0
  107. package/views/reference/tag.hbs +28 -0
  108. package/views/reference/token.hbs +49 -0
  109. package/views/tokens/index.hbs +9 -1
  110. package/views/webhooks/index.hbs +3 -3
  111. package/workers/api.js +37 -215
  112. package/Gruntfile.js +0 -58
  113. 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');
@@ -1622,6 +1643,7 @@ const oauthCreateSchema = {
1622
1643
  .example('gmail')
1623
1644
  .required()
1624
1645
  .description('OAuth2 provider type')
1646
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.oauth2Provider })
1625
1647
  .label('CreateOAuth2Provider'),
1626
1648
 
1627
1649
  enabled: Joi.boolean()
@@ -1804,6 +1826,7 @@ const oauthCreateSchema = {
1804
1826
  })
1805
1827
  .example('global')
1806
1828
  .description('Microsoft Azure cloud environment')
1829
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.azureCloud })
1807
1830
  .label('AzureCloud'),
1808
1831
 
1809
1832
  tenant: Joi.any().alter({
@@ -2092,7 +2115,12 @@ const defaultAccountTypeSchema = Joi.string()
2092
2115
  const outboxEntrySchema = Joi.object({
2093
2116
  queueId: Joi.string().example('1869c5692565f756b33').description('Unique queue entry identifier'),
2094
2117
  account: accountIdSchema.required(),
2095
- source: Joi.string().example('smtp').valid('smtp', 'api', 'test', 'ui').description('How this message entered the queue').label('OutboxSource'),
2118
+ source: Joi.string()
2119
+ .example('smtp')
2120
+ .valid('smtp', 'api', 'test', 'ui')
2121
+ .description('How this message entered the queue')
2122
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.outboxSource })
2123
+ .label('OutboxSource'),
2096
2124
 
2097
2125
  messageId: Joi.string().max(996).example('<test123@example.com>').description('Message-ID header value'),
2098
2126
  envelope: Joi.object({
@@ -2132,6 +2160,7 @@ const outboxEntrySchema = Joi.object({
2132
2160
  .valid('queued', 'processing', 'smtp-starting', 'smtp-completed', 'submitted', 'error')
2133
2161
  .example('queued')
2134
2162
  .description('Current delivery status')
2163
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.outboxStatus })
2135
2164
  .label('OutboxStatus'),
2136
2165
  response: Joi.string().example('250 Message Accepted').description('SMTP server response (when status is "submitted" or "smtp-completed")'),
2137
2166
  messageId: Joi.string().example('<test123@example.com>').description('Message-ID header value of the sent message (when status is "smtp-completed")'),
@@ -2228,6 +2257,14 @@ const headerTimeoutSchema = Joi.number()
2228
2257
  .description('Request timeout in milliseconds (overrides EENGINE_TIMEOUT environment variable)')
2229
2258
  .label('X-EE-Timeout');
2230
2259
 
2260
+ // Headers every API route accepts, applied as a server-wide route default in workers/api.js rather
2261
+ // than being repeated per route. Exported because it also reaches the generated OpenAPI document -
2262
+ // every operation documents this header - so anything reproducing that document has to apply the
2263
+ // same default (test/helpers/build-openapi-spec.js).
2264
+ const apiHeadersSchema = Joi.object({
2265
+ 'x-ee-timeout': headerTimeoutSchema
2266
+ }).unknown();
2267
+
2231
2268
  // Export schemas
2232
2269
  const exportRequestSchema = Joi.object({
2233
2270
  folders: Joi.array()
@@ -2282,7 +2319,12 @@ const exportStatusSchema = Joi.object({
2282
2319
  .example('processing')
2283
2320
  .description('Export status')
2284
2321
  .label('ExportStatusValue'),
2285
- phase: Joi.string().valid('indexing', 'exporting', 'complete').example('indexing').description('Current export phase').label('ExportPhase'),
2322
+ phase: Joi.string()
2323
+ .valid('indexing', 'exporting', 'complete')
2324
+ .example('indexing')
2325
+ .description('Current export phase')
2326
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.exportPhase })
2327
+ .label('ExportPhase'),
2286
2328
  folders: Joi.array().items(Joi.string().label('ExportFolderItem')).description('Folders being exported').label('ExportStatusFolders'),
2287
2329
  startDate: Joi.date().iso().example('2024-01-01T00:00:00Z').description('Export start date filter'),
2288
2330
  endDate: Joi.date().iso().example('2024-12-31T23:59:59Z').description('Export end date filter'),
@@ -2302,6 +2344,7 @@ const exportListEntrySchema = Joi.object({
2302
2344
  .valid('queued', 'processing', 'completed', 'failed', 'cancelled')
2303
2345
  .example('completed')
2304
2346
  .description('Export status')
2347
+ .meta({ enumDescriptions: ENUM_DESCRIPTIONS.exportStatus })
2305
2348
  .label('ExportListStatusValue'),
2306
2349
  created: Joi.date().iso().example('2024-01-15T10:30:00Z').description('When export was created'),
2307
2350
  expiresAt: Joi.date().iso().example('2024-01-16T10:30:00Z').description('When export file expires')
@@ -2322,12 +2365,11 @@ const exportIdSchema = Joi.string()
2322
2365
  .label('ExportId');
2323
2366
 
2324
2367
  // 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.
2368
+ // documentation only - they reach the OpenAPI document through the plugins.openapi.responses
2369
+ // route option and are never used to validate or modify actual responses at runtime.
2328
2370
 
2329
2371
  // 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
2372
+ // in the API reference) paired with a labeled Joi schema for the Boom-style error payload. The
2331
2373
  // optional extra fields document values that EmailEngine adds to the base
2332
2374
  // { statusCode, error, message } payload for that error type.
2333
2375
  const errorResponseEntry = ({ statusCode, statusText, messageExample, label, title, description, fields }) => ({
@@ -2443,10 +2485,10 @@ const errorResponseSchemas = {
2443
2485
  })
2444
2486
  };
2445
2487
 
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.
2488
+ // Builds the value for the plugins.openapi.responses route option from a list of HTTP error
2489
+ // status codes, so that error responses are documented in addition to the 200 response the
2490
+ // generator picks up from the route's response.schema option. This is documentation only and
2491
+ // does not affect request processing in any way.
2450
2492
  function errorResponses(...statusCodes) {
2451
2493
  let responses = {};
2452
2494
  for (let statusCode of statusCodes) {
@@ -2458,6 +2500,19 @@ function errorResponses(...statusCodes) {
2458
2500
  return responses;
2459
2501
  }
2460
2502
 
2503
+ // Builds the full `responses` value for a route: the documented success case plus the
2504
+ // error cases. The generator derives a 200 entry from the route's response.schema but can
2505
+ // only label it "Successful", and for a raw stream or binary body there is no schema to
2506
+ // derive anything from - so the description is stated here. It is documentation only and
2507
+ // never affects request processing.
2508
+ //
2509
+ // `description` should say what the caller gets back, in the style of "Returns the
2510
+ // updated account." Passing it per route rather than putting it on the joi response
2511
+ // schema keeps it operation-specific, since several operations share a response schema.
2512
+ function apiResponses(description, ...statusCodes) {
2513
+ return Object.assign({ 200: { description } }, errorResponses(...statusCodes));
2514
+ }
2515
+
2461
2516
  module.exports = {
2462
2517
  ADDRESS_STRATEGIES,
2463
2518
  ACCOUNT_DISPLAY_STATES,
@@ -2489,6 +2544,9 @@ module.exports = {
2489
2544
  oauthUpdateSchema,
2490
2545
  tokenRestrictionsSchema,
2491
2546
  accountIdSchema,
2547
+ oauth2ProviderSchema,
2548
+ accountTypeSchema,
2549
+ apiHeadersSchema,
2492
2550
  ipSchema,
2493
2551
  tokenIdSchema,
2494
2552
  accountCountersSchema,
@@ -2515,7 +2573,8 @@ module.exports = {
2515
2573
  exportProgressSchema,
2516
2574
  exportIdSchema,
2517
2575
  pubSubErrorSchema,
2518
- errorResponses
2576
+ apiResponses,
2577
+ ENUM_DESCRIPTIONS
2519
2578
  };
2520
2579
 
2521
2580
  /*
@@ -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/tokens.js CHANGED
@@ -9,6 +9,24 @@ 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) {
@@ -2178,6 +2178,9 @@ return payload;`)
2178
2178
  entry.access.timeStr =
2179
2179
  entry.access && entry.access.time && typeof entry.access.time.toISOString === 'function' ? entry.access.time.toISOString() : null;
2180
2180
  entry.idShort = entry.id ? entry.id.slice(0, 8) : '';
2181
+ // Short-lived tokens (the API reference mints one-hour ones) have to be
2182
+ // distinguishable here, otherwise the list implies every token is permanent
2183
+ entry.expiresStr = entry.expires && typeof entry.expires.toISOString === 'function' ? entry.expires.toISOString() : null;
2181
2184
  entry.scopes = entry.scopes
2182
2185
  ? entry.scopes.map((scope, i) => ({
2183
2186
  name: scope === '*' ? 'all scopes' : scope,
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  // Admin UI routes for the dashboard and standalone informational pages: the main
4
- // /admin dashboard (stats counters), the Swagger API reference, the legal page, and the
5
- // upgrade page. Extracted verbatim from lib/routes-ui.js.
4
+ // /admin dashboard (stats counters), the legal page, and the upgrade page. Extracted
5
+ // verbatim from lib/routes-ui.js. The API reference lives in reference-routes.js.
6
6
 
7
7
  const { getStats, getBoolean, readEnvValue } = require('../tools');
8
8
  const settings = require('../settings');
@@ -107,30 +107,6 @@ function init(args) {
107
107
  }
108
108
  });
109
109
 
110
- server.route({
111
- method: 'GET',
112
- path: '/admin/swagger',
113
- async handler(request, h) {
114
- return h.view(
115
- 'swagger/index',
116
- {
117
- pageTitle: 'API Reference',
118
- menuSwagger: true,
119
- injectHtmlHead: `<link rel="stylesheet" type="text/css" href="/admin/swagger/resources/swagger-ui.css" />
120
- <style>
121
- .download-url-wrapper,
122
- .topbar {
123
- display: none !important;
124
- }
125
- </style>`
126
- },
127
- {
128
- layout: 'app'
129
- }
130
- );
131
- }
132
- });
133
-
134
110
  server.route({
135
111
  method: 'GET',
136
112
  path: '/admin/legal',