emailengine-app 2.76.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 (102) hide show
  1. package/.github/workflows/release.yaml +24 -19
  2. package/.ncurc.js +14 -2
  3. package/.release-please-manifest.json +3 -0
  4. package/CHANGELOG.md +23 -0
  5. package/README.md +1 -1
  6. package/data/google-crawlers.json +1 -1
  7. package/encrypt.js +71 -4
  8. package/lib/address-strategies.js +18 -0
  9. package/lib/api-reference/code-samples.js +194 -0
  10. package/lib/api-reference/format.js +179 -0
  11. package/lib/api-reference/index.js +205 -0
  12. package/lib/api-reference/model.js +336 -0
  13. package/lib/api-reference/schema-tree.js +366 -0
  14. package/lib/api-routes/account-routes.js +117 -37
  15. package/lib/api-routes/behavior-notes.js +54 -0
  16. package/lib/api-routes/blocklist-routes.js +9 -9
  17. package/lib/api-routes/changes-routes.js +6 -4
  18. package/lib/api-routes/chat-routes.js +3 -3
  19. package/lib/api-routes/delivery-test-routes.js +24 -6
  20. package/lib/api-routes/export-routes.js +14 -12
  21. package/lib/api-routes/gateway-routes.js +11 -11
  22. package/lib/api-routes/license-routes.js +7 -7
  23. package/lib/api-routes/mailbox-routes.js +18 -9
  24. package/lib/api-routes/message-routes.js +55 -35
  25. package/lib/api-routes/oauth2-app-routes.js +22 -16
  26. package/lib/api-routes/outbox-routes.js +7 -7
  27. package/lib/api-routes/pubsub-routes.js +3 -3
  28. package/lib/api-routes/settings-routes.js +10 -9
  29. package/lib/api-routes/stats-routes.js +3 -3
  30. package/lib/api-routes/submit-routes.js +58 -8
  31. package/lib/api-routes/template-routes.js +13 -13
  32. package/lib/api-routes/token-routes.js +15 -10
  33. package/lib/api-routes/webhook-route-routes.js +5 -5
  34. package/lib/consts.js +7 -0
  35. package/lib/email-client/base-client.js +66 -12
  36. package/lib/enum-descriptions.js +130 -0
  37. package/lib/imapproxy/imap-server.js +30 -26
  38. package/lib/imapproxy/upstream-client.js +38 -0
  39. package/lib/oauth2-apps.js +9 -3
  40. package/lib/openapi/build-document.js +318 -0
  41. package/lib/openapi/index.js +95 -0
  42. package/lib/openapi/joi-schema.js +523 -0
  43. package/lib/routes-ui.js +5 -1
  44. package/lib/schemas.js +76 -17
  45. package/lib/swagger-options.js +173 -0
  46. package/lib/tokens.js +69 -5
  47. package/lib/ui-routes/admin-entities-routes.js +3 -0
  48. package/lib/ui-routes/dashboard-routes.js +2 -26
  49. package/lib/ui-routes/reference-routes.js +195 -0
  50. package/lib/ui-routes/route-helpers.js +11 -0
  51. package/package.json +9 -11
  52. package/prepare-bundle-deps.sh +28 -0
  53. package/release-please-config.json +11 -0
  54. package/sbom.json +0 -1
  55. package/server.js +10 -2
  56. package/static/css/flyonui.css +1 -1
  57. package/static/css/src/app.tailwind.css +90 -0
  58. package/static/js/ee-client.js +238 -8
  59. package/static/js/reference.js +736 -0
  60. package/static/js/ui.js +61 -33
  61. package/static/licenses.html +4 -4
  62. package/translations/messages.pot +27 -27
  63. package/views/config/ai.hbs +1 -1
  64. package/views/config/document-store/chat.hbs +5 -5
  65. package/views/config/document-store/index.hbs +2 -2
  66. package/views/config/document-store/pre-processing/index.hbs +1 -1
  67. package/views/config/email-processing.hbs +1 -1
  68. package/views/config/imap-proxy.hbs +1 -1
  69. package/views/config/license.hbs +1 -1
  70. package/views/config/oauth/index.hbs +3 -3
  71. package/views/config/security.hbs +1 -1
  72. package/views/config/smtp.hbs +2 -2
  73. package/views/dashboard.hbs +1 -1
  74. package/views/layout/app.hbs +18 -7
  75. package/views/partials/oauth_form.hbs +4 -4
  76. package/views/partials/reference/anchor-link.hbs +20 -0
  77. package/views/partials/reference/disclosure.hbs +37 -0
  78. package/views/partials/reference/nav.hbs +93 -0
  79. package/views/partials/reference/operation.hbs +127 -0
  80. package/views/partials/reference/params.hbs +20 -0
  81. package/views/partials/reference/schema-node.hbs +99 -0
  82. package/views/partials/reference/schema.hbs +19 -0
  83. package/views/partials/reference/section-heading.hbs +16 -0
  84. package/views/partials/reference/token-alert.hbs +24 -0
  85. package/views/partials/reference/try-field.hbs +31 -0
  86. package/views/partials/reference/try-it.hbs +78 -0
  87. package/views/partials/side_menu.hbs +1 -1
  88. package/views/partials/ui/badge.hbs +4 -2
  89. package/views/partials/ui/page-header.hbs +1 -1
  90. package/views/partials/ui/search-input.hbs +31 -0
  91. package/views/partials/ui/setting-ref.hbs +1 -1
  92. package/views/partials/ui/stat-card.hbs +4 -2
  93. package/views/partials/ui/tab.hbs +6 -1
  94. package/views/partials/ui/tabs.hbs +2 -2
  95. package/views/reference/index.hbs +76 -0
  96. package/views/reference/redirect.hbs +49 -0
  97. package/views/reference/tag.hbs +28 -0
  98. package/views/reference/token.hbs +49 -0
  99. package/views/tokens/index.hbs +9 -1
  100. package/views/webhooks/index.hbs +3 -3
  101. package/workers/api.js +37 -215
  102. package/views/swagger/index.hbs +0 -82
@@ -0,0 +1,318 @@
1
+ 'use strict';
2
+
3
+ // Builds the OpenAPI 3.0 document from the Hapi route table.
4
+ //
5
+ // This is the route-walking half of what hapi-swagger used to do (see lib/openapi/joi-schema.js for
6
+ // the schema half). It is a pure function of the route table plus the document-level options in
7
+ // lib/swagger-options.js, so the same document can be produced inside a test without a listening
8
+ // server - test/fixtures/openapi-golden.json is recorded that way.
9
+ //
10
+ // What each route contributes:
11
+ // description -> summary (the one-line title)
12
+ // notes -> description (paragraphs, joined with <br/><br/>)
13
+ // tags -> tags (minus the internal `api` marker used to select routes)
14
+ // validate.params -> path parameters
15
+ // validate.query -> query parameters
16
+ // validate.headers -> header parameters
17
+ // validate.payload -> requestBody
18
+ // response.schema -> the 200 response body
19
+ // plugins.openapi.responses -> the documented status codes (see apiResponses in lib/schemas.js)
20
+ // plugins.openapi.produces -> the media type for routes that do not return JSON
21
+ // plugins.openapi['x-*'] -> vendor extensions on the operation, notably x-ee-behavior
22
+
23
+ const { STATUS_CODES } = require('node:http');
24
+
25
+ const Joi = require('joi');
26
+
27
+ const { SchemaConverter, deleteEmptyProperties } = require('./joi-schema');
28
+
29
+ // Routes opt into the document by carrying this tag. It is an internal marker rather than a
30
+ // documentation tag, so it is filtered back out of the published tag list.
31
+ const API_ROUTE_TAG = 'api';
32
+
33
+ // Where a route keeps the documentation metadata that its joi schemas cannot express
34
+ const PLUGIN_OPTIONS_KEY = 'openapi';
35
+
36
+ const DEFAULT_MEDIA_TYPE = 'application/json';
37
+
38
+ // Operations of one path are documented in the order a reader expects to meet them
39
+ const METHOD_ORDER = ['get', 'post', 'put', 'patch', 'delete', 'options', 'head'];
40
+
41
+ // hapi-swagger joined a route's `notes` array with this separator, and lib/api-reference/model.js
42
+ // splits the description back on it to separate behavior notes from the operation's own prose.
43
+ const NOTES_SEPARATOR = '<br/><br/>';
44
+
45
+ const OPENAPI_VERSION = '3.0.0';
46
+
47
+ /**
48
+ * Operation id for a route, e.g. GET /v1/account/{account} -> getV1AccountAccount.
49
+ *
50
+ * Generated client libraries turn these into method names, so the algorithm is fixed by
51
+ * compatibility rather than taste: every path segment is stripped of non-word characters and
52
+ * title-cased, then appended to the lowercased method.
53
+ */
54
+ function operationId(method, path) {
55
+ const titleCase = word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
56
+
57
+ return (
58
+ method.toLowerCase() +
59
+ path
60
+ .split('/')
61
+ .map(segment => titleCase(segment.replace(/[^\w\s]/gi, '')))
62
+ .join('')
63
+ );
64
+ }
65
+
66
+ function statusText(code) {
67
+ // "OK" reads oddly as a response description next to "Bad Request", and this is the wording the
68
+ // published document has always used
69
+ return (STATUS_CODES[code] || 'Successful').replace('OK', 'Successful');
70
+ }
71
+
72
+ function pluginOptions(route) {
73
+ return (route.settings.plugins && route.settings.plugins[PLUGIN_OPTIONS_KEY]) || {};
74
+ }
75
+
76
+ // Copies x-* keys onto the target. Anything a route declares under a vendor extension is published
77
+ // verbatim, which is how x-ee-behavior reaches the API reference.
78
+ function assignVendorExtensions(target, source) {
79
+ for (const key of Object.keys(source)) {
80
+ if (key.startsWith('x-') && key.length > 2) {
81
+ target[key] = source[key];
82
+ }
83
+ }
84
+ }
85
+
86
+ class DocumentBuilder {
87
+ constructor() {
88
+ this.converter = new SchemaConverter();
89
+ }
90
+
91
+ /**
92
+ * Turns one Hapi route into an OpenAPI Operation Object.
93
+ *
94
+ * @param {Object} route - an entry from server.table()
95
+ * @returns {Object} { path, method, operation }
96
+ */
97
+ buildOperation(route) {
98
+ const settings = route.settings;
99
+ const options = pluginOptions(route);
100
+ const validate = settings.validate || {};
101
+
102
+ // Non-JSON routes (raw message source, gzip export, event streams) declare the media type
103
+ // their success response carries
104
+ const produces = options.produces || [DEFAULT_MEDIA_TYPE];
105
+
106
+ // Assembled in one literal because the key order is what gets published, and a document that
107
+ // reorders itself between builds is a diff for everyone tracking the hosted copy
108
+ const operation = {
109
+ summary: settings.description,
110
+ operationId: operationId(route.method, route.path),
111
+ description: Array.isArray(settings.notes) ? settings.notes.join(NOTES_SEPARATOR) : settings.notes,
112
+ parameters: [
113
+ ...this.buildParameters(validate.headers, 'header', route.path),
114
+ ...this.buildParameters(validate.params, 'path', route.path),
115
+ ...this.buildParameters(validate.query, 'query', route.path)
116
+ ],
117
+ tags: (settings.tags || []).filter(tag => tag !== API_ROUTE_TAG)
118
+ };
119
+
120
+ if (validate.payload) {
121
+ const schema = this.converter.convert(validate.payload);
122
+ if (schema && Object.keys(schema).length) {
123
+ operation.requestBody = { content: { [DEFAULT_MEDIA_TYPE]: { schema } } };
124
+ }
125
+ }
126
+
127
+ operation.responses = this.buildResponses(options.responses, settings.response && settings.response.schema, produces);
128
+
129
+ assignVendorExtensions(operation, options);
130
+
131
+ return { path: route.path, method: route.method.toLowerCase(), operation: deleteEmptyProperties(operation) };
132
+ }
133
+
134
+ /**
135
+ * Converts one of the request-side joi objects into Parameter Objects.
136
+ *
137
+ * Parameter schemas are inlined rather than referenced: a $ref in a parameter hides the type from
138
+ * a reader scanning the operation, and these schemas are small.
139
+ */
140
+ buildParameters(schema, location, path) {
141
+ if (!schema) {
142
+ return [];
143
+ }
144
+
145
+ const converted = this.converter.convert(schema, { parameterType: location, useDefinitions: false });
146
+ if (!converted || !converted.properties) {
147
+ return [];
148
+ }
149
+
150
+ const required = converted.required || [];
151
+
152
+ return Object.keys(converted.properties).map(name => {
153
+ const propertySchema = converted.properties[name];
154
+
155
+ const parameter = { name, in: location, schema: propertySchema };
156
+
157
+ // Repeated on the parameter itself: tooling shows the parameter-level description, while
158
+ // the schema-level one survives in generated models
159
+ if (propertySchema.description) {
160
+ parameter.description = propertySchema.description;
161
+ }
162
+
163
+ if (propertySchema.type === 'array') {
164
+ parameter.style = 'form';
165
+ parameter.explode = true;
166
+ }
167
+
168
+ // A path parameter is required by definition unless the path itself marks it optional
169
+ if (required.includes(name) || (location === 'path' && path.includes(`{${name}}`))) {
170
+ parameter.required = true;
171
+ }
172
+
173
+ return parameter;
174
+ });
175
+ }
176
+
177
+ /**
178
+ * Builds the Responses Object: the success case discovered from the route's response schema,
179
+ * merged with the status codes the route documents explicitly.
180
+ */
181
+ buildResponses(documented, responseSchema, produces) {
182
+ const responses = {};
183
+
184
+ if (responseSchema) {
185
+ responses[200] = this.buildResponse(200, responseSchema);
186
+ }
187
+
188
+ for (const code of Object.keys(documented || {})) {
189
+ const entry = documented[code];
190
+
191
+ let response;
192
+ if (Joi.isSchema(entry.schema)) {
193
+ response = this.buildResponse(code, entry.schema);
194
+ // The route says what this status means for this operation; the schema's own
195
+ // description is the generic name of the error shape
196
+ response.description = entry.description;
197
+ } else {
198
+ response = Object.assign({}, entry);
199
+ if (!response.description) {
200
+ response.description = statusText(code);
201
+ }
202
+ }
203
+
204
+ responses[code] = Object.assign(responses[code] || {}, response);
205
+ deleteEmptyProperties(responses[code]);
206
+ }
207
+
208
+ // A 2xx with no schema still has a body - a stream, a raw message, an archive - and a
209
+ // response with no content at all reads as "returns nothing"
210
+ if (responses[200] && responses[200].schema === undefined) {
211
+ responses[200].schema = { type: 'string' };
212
+ }
213
+
214
+ return Object.fromEntries(
215
+ Object.entries(responses).map(([code, response]) => {
216
+ const { schema, ...rest } = response;
217
+
218
+ if (!schema) {
219
+ return [code, rest];
220
+ }
221
+
222
+ // `produces` describes what the operation returns when it succeeds. Failures are
223
+ // always the JSON error envelope, whatever the success body is.
224
+ const mediaTypes = Number(code) < 300 ? produces : [DEFAULT_MEDIA_TYPE];
225
+
226
+ return [code, Object.assign(rest, { content: Object.fromEntries(mediaTypes.map(mediaType => [mediaType, { schema }])) })];
227
+ })
228
+ );
229
+ }
230
+
231
+ buildResponse(code, schema) {
232
+ // Described once and passed on, rather than letting convert() describe the same schema again
233
+ const description = this.converter.describe(schema);
234
+
235
+ const response = {
236
+ description: description.flags && description.flags.description,
237
+ schema: this.converter.convert(description)
238
+ };
239
+
240
+ deleteEmptyProperties(response);
241
+
242
+ if (!response.description) {
243
+ response.description = statusText(code);
244
+ }
245
+
246
+ return response;
247
+ }
248
+ }
249
+
250
+ // Hapi's route table comes back grouped by HTTP method in the order each method was first registered
251
+ // anywhere on the server, which makes the emitted order a property of the whole registration sequence
252
+ // rather than of the routes themselves. That is mostly cosmetic, but not entirely: schemas are named
253
+ // from their joi label, and where two different shapes share a label the numeric suffix that
254
+ // separates them (`AddressList1`) follows first-seen order. Sorting here makes the document a
255
+ // function of the route set alone, so the same routes always produce the same document - which is
256
+ // also what lets test/fixtures/openapi-golden.json guard the document the server actually serves.
257
+ function sortRoutes(routes) {
258
+ return [...routes].sort(
259
+ (a, b) => a.path.localeCompare(b.path) || METHOD_ORDER.indexOf(a.method.toLowerCase()) - METHOD_ORDER.indexOf(b.method.toLowerCase())
260
+ );
261
+ }
262
+
263
+ /**
264
+ * Builds the OpenAPI document.
265
+ *
266
+ * @param {Array} routes - the Hapi route table (server.table()), unfiltered
267
+ * @param {Object} options - document-level options, see lib/swagger-options.js
268
+ * @param {Object} options.info - the Info Object; title and version are required
269
+ * @param {Array} [options.servers] - Server Objects; omitted from the document when not given
270
+ * @returns {Object} the OpenAPI document
271
+ */
272
+ function buildOpenApiDocument(routes, options) {
273
+ const builder = new DocumentBuilder();
274
+
275
+ const paths = {};
276
+
277
+ for (const route of sortRoutes(routes.filter(route => (route.settings.tags || []).includes(API_ROUTE_TAG)))) {
278
+ const { path, method, operation } = builder.buildOperation(route);
279
+
280
+ if (!paths[path]) {
281
+ paths[path] = {};
282
+ }
283
+
284
+ paths[path][method] = operation;
285
+ }
286
+
287
+ const document = {
288
+ externalDocs: options.externalDocs,
289
+ security: options.security,
290
+ tags: options.tags || []
291
+ };
292
+
293
+ // Document-level vendor extensions (x-logo and anything added later) sit with the metadata they
294
+ // extend, before the generated sections
295
+ assignVendorExtensions(document, options);
296
+
297
+ // title and version first: they are the two fields OpenAPI requires, and every other info field
298
+ // is prose that follows them
299
+ document.info = Object.assign({ title: 'API documentation', version: '0.0.1' }, options.info);
300
+
301
+ document.openapi = OPENAPI_VERSION;
302
+
303
+ if (options.servers) {
304
+ document.servers = options.servers;
305
+ }
306
+
307
+ document.components = {};
308
+ if (options.securityDefinitions) {
309
+ document.components.securitySchemes = options.securityDefinitions;
310
+ }
311
+ document.components.schemas = builder.converter.definitions;
312
+
313
+ document.paths = paths;
314
+
315
+ return deleteEmptyProperties(document);
316
+ }
317
+
318
+ module.exports = { buildOpenApiDocument, operationId, API_ROUTE_TAG, NOTES_SEPARATOR };
@@ -0,0 +1,95 @@
1
+ 'use strict';
2
+
3
+ // Serves the generated OpenAPI document at /swagger.json.
4
+ //
5
+ // The endpoint is deliberately unauthenticated, as it has been since it was served by hapi-swagger:
6
+ // it is a published product surface (the README points at it, emailengine.dev mirrors it, Postman
7
+ // and code generators consume it), and it describes the shape of the API rather than exposing any
8
+ // instance data. The API reference at /admin/reference reads it back through server.inject(), which
9
+ // also depends on it not requiring a session.
10
+
11
+ const { buildOpenApiDocument, NOTES_SEPARATOR } = require('./build-document');
12
+ const { SCHEMA_REF_PREFIX } = require('./joi-schema');
13
+
14
+ const JSON_PATH = '/swagger.json';
15
+
16
+ // Stands in for the real address while the document body is built, so `servers` already has its
17
+ // place in the key order and the per-request value can be dropped in without rebuilding anything
18
+ const PLACEHOLDER_SERVERS = [{ url: '' }];
19
+
20
+ function firstHeaderValue(request, name) {
21
+ const value = request.headers[name];
22
+ return value ? value.split(',')[0].trim() : undefined;
23
+ }
24
+
25
+ /**
26
+ * The base address to publish as the API's server.
27
+ *
28
+ * Derived from the request rather than from configuration, so an instance reachable under several
29
+ * names describes itself correctly to whoever asked. Forwarded headers win, because behind a reverse
30
+ * proxy they are the only source of the address the client actually used.
31
+ *
32
+ * Those headers are attacker-controlled on a directly reachable port, so two things keep that
33
+ * harmless: the value is computed per request and never cached, so it can only ever appear in the
34
+ * response to the client that sent the header; and it is parsed as a URL, so a malformed header
35
+ * falls back to the request's own address instead of being pasted into the document.
36
+ */
37
+ function serverUrl(request) {
38
+ const forwarded = (firstHeaderValue(request, 'x-forwarded-proto') || '').toLowerCase();
39
+
40
+ // Only the two schemes this server speaks. Without the check the header is not just a scheme but
41
+ // the front of the URL, so `https://elsewhere/#` would compose into an origin of its own.
42
+ const protocol = ['http', 'https'].includes(forwarded) ? forwarded : (request.url.protocol || 'http:').replace(/:$/, '');
43
+ const host = firstHeaderValue(request, 'x-forwarded-host') || request.headers['disguised-host'] || request.info.host;
44
+
45
+ try {
46
+ return new URL(`${protocol}://${host}`).origin;
47
+ } catch (err) {
48
+ return `http://${request.info.host}`;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Registers the OpenAPI document route.
54
+ *
55
+ * Can be registered at any point: the document is built from server.table() on first request, not
56
+ * here, so it sees every route however late it was added, and the builder sorts the table itself so
57
+ * the result does not depend on registration order.
58
+ *
59
+ * @param {Object} server - the Hapi server
60
+ * @param {Object} options - document-level options, see lib/swagger-options.js
61
+ */
62
+ function registerOpenApiRoute(server, options) {
63
+ // Built once and then held for the life of the worker - route definitions cannot change while it
64
+ // is running, so there is nothing to invalidate
65
+ let document;
66
+ let builtAt;
67
+
68
+ const getDocument = () => {
69
+ if (!document) {
70
+ document = buildOpenApiDocument(server.table(), Object.assign({}, options, { servers: PLACEHOLDER_SERVERS }));
71
+ builtAt = new Date();
72
+ }
73
+
74
+ return document;
75
+ };
76
+
77
+ server.route({
78
+ method: 'GET',
79
+ path: JSON_PATH,
80
+ options: {
81
+ auth: false,
82
+ cors: options.cors,
83
+
84
+ handler(request, h) {
85
+ // Shallow copy: `servers` already exists in the built document, so replacing it here
86
+ // keeps its position in the key order and leaves the rest untouched
87
+ const spec = Object.assign({}, getDocument(), { servers: [{ url: serverUrl(request) }] });
88
+
89
+ return h.response(spec).header('last-modified', builtAt.toUTCString());
90
+ }
91
+ }
92
+ });
93
+ }
94
+
95
+ module.exports = { registerOpenApiRoute, buildOpenApiDocument, JSON_PATH, NOTES_SEPARATOR, SCHEMA_REF_PREFIX };