emailengine-app 2.81.1 → 2.82.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 (208) hide show
  1. package/.ncurc.js +12 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +52 -0
  4. package/Dockerfile +4 -2
  5. package/bin/emailengine.js +28 -18
  6. package/config/default.toml +0 -5
  7. package/config/test.toml +0 -5
  8. package/data/google-crawlers.json +1 -1
  9. package/encrypt.js +70 -42
  10. package/getswagger.sh +0 -4
  11. package/lib/account/account-state.js +2 -110
  12. package/lib/account/bounce-store-sweep.js +63 -0
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +207 -0
  15. package/lib/account.js +374 -878
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-routes.js +18 -29
  19. package/lib/api-routes/blocklist-routes.js +2 -2
  20. package/lib/api-routes/bull-board-routes.js +1 -6
  21. package/lib/api-routes/export-routes.js +2 -22
  22. package/lib/api-routes/gateway-routes.js +5 -14
  23. package/lib/api-routes/index.js +1 -13
  24. package/lib/api-routes/mailbox-routes.js +2 -7
  25. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  26. package/lib/api-routes/mcp-routes.js +7 -7
  27. package/lib/api-routes/message-routes.js +44 -236
  28. package/lib/api-routes/mint-bounds.js +110 -0
  29. package/lib/api-routes/oauth2-app-routes.js +23 -32
  30. package/lib/api-routes/operation-impact.js +1 -1
  31. package/lib/api-routes/outbox-routes.js +2 -2
  32. package/lib/api-routes/permission-map.js +1 -7
  33. package/lib/api-routes/route-helpers.js +11 -5
  34. package/lib/api-routes/settings-routes.js +19 -19
  35. package/lib/api-routes/stats-routes.js +1 -1
  36. package/lib/api-routes/submit-routes.js +17 -18
  37. package/lib/api-routes/template-routes.js +4 -9
  38. package/lib/api-routes/token-routes.js +27 -5
  39. package/lib/api-token-scheme.js +71 -0
  40. package/lib/arf-detect.js +41 -7
  41. package/lib/auth-token.js +44 -24
  42. package/lib/autodetect-imap-settings.js +163 -123
  43. package/lib/bounce-detect.js +25 -16
  44. package/lib/calendar-event.js +78 -0
  45. package/lib/consts.js +51 -5
  46. package/lib/create-imap-client.js +24 -0
  47. package/lib/db.js +76 -17
  48. package/lib/delivery-error.js +2 -1
  49. package/lib/egress-fetch.js +54 -3
  50. package/lib/egress-filter.js +11 -0
  51. package/lib/email-client/api-retry.js +147 -0
  52. package/lib/email-client/base-client.js +628 -615
  53. package/lib/email-client/gmail/gmail-api.js +38 -125
  54. package/lib/email-client/gmail/send-request.js +1 -1
  55. package/lib/email-client/gmail-client.js +170 -84
  56. package/lib/email-client/imap/mailbox.js +244 -535
  57. package/lib/email-client/imap/stale-view.js +109 -0
  58. package/lib/email-client/imap/subconnection.js +46 -9
  59. package/lib/email-client/imap/sync-operations.js +5 -37
  60. package/lib/email-client/imap-client.js +188 -64
  61. package/lib/email-client/message-builder.js +9 -14
  62. package/lib/email-client/notification-handler.js +5 -219
  63. package/lib/email-client/outlook/graph-api.js +147 -126
  64. package/lib/email-client/outlook/send-request.js +10 -4
  65. package/lib/email-client/outlook-client.js +519 -617
  66. package/lib/email-client/smtp-pool-manager.js +3 -2
  67. package/lib/encrypt.js +184 -19
  68. package/lib/enum-descriptions.js +1 -2
  69. package/lib/export.js +144 -41
  70. package/lib/gateway.js +20 -6
  71. package/lib/get-raw-email.js +26 -44
  72. package/lib/handlebars-helpers.js +31 -10
  73. package/lib/imap-proxy-auth.js +13 -29
  74. package/lib/imapproxy/imap-core/README.md +1 -0
  75. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  76. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  77. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  78. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  79. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  80. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  81. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  82. package/lib/imapproxy/imap-server.js +17 -177
  83. package/lib/imapproxy/proxy-handoff.js +235 -0
  84. package/lib/imapproxy/response-error.js +33 -0
  85. package/lib/imapproxy/upstream-client.js +2 -2
  86. package/lib/license-beacon.js +3 -9
  87. package/lib/llm-pre-process.js +182 -43
  88. package/lib/logger.js +1 -1
  89. package/lib/lua/ee-export-queue-add.lua +39 -0
  90. package/lib/lua/ee-get-idempotency.lua +15 -3
  91. package/lib/lua/ee-release-attempts.lua +23 -0
  92. package/lib/lua/ee-reserve-attempts.lua +42 -0
  93. package/lib/lua/h-set-bigger.lua +12 -2
  94. package/lib/lua/s-list-accounts.lua +6 -3
  95. package/lib/mcp/index.js +1 -2
  96. package/lib/mcp/listen.js +221 -18
  97. package/lib/mcp/oauth.js +44 -5
  98. package/lib/mcp/resources.js +8 -2
  99. package/lib/mcp/tools.js +13 -0
  100. package/lib/message-port-stream.js +64 -6
  101. package/lib/msgpack.js +1 -6
  102. package/lib/oauth/external-account-signer.js +16 -13
  103. package/lib/oauth/gmail.js +22 -20
  104. package/lib/oauth/outlook.js +19 -16
  105. package/lib/oauth/pubsub/google.js +38 -2
  106. package/lib/oauth/scope-checker.js +4 -7
  107. package/lib/oauth/verify-app.js +2 -2
  108. package/lib/oauth2-apps.js +139 -44
  109. package/lib/openapi/build-document.js +1 -1
  110. package/lib/openapi/joi-schema.js +78 -9
  111. package/lib/parse-message.js +21 -0
  112. package/lib/payload-examples-webhooks.json +4 -7
  113. package/lib/pbkdf2-phc.js +101 -0
  114. package/lib/privileged-settings.js +0 -14
  115. package/lib/rate-limit.js +54 -15
  116. package/lib/redis-scan-delete.js +56 -29
  117. package/lib/redis-url.js +3 -1
  118. package/lib/respawn-backoff.js +5 -4
  119. package/lib/response-stream.js +25 -4
  120. package/lib/rewrite-text-nodes.js +27 -40
  121. package/lib/routes-ui.js +0 -5
  122. package/lib/schemas.js +129 -262
  123. package/lib/sentry.js +21 -5
  124. package/lib/settings.js +58 -59
  125. package/lib/smtp-auth.js +6 -2
  126. package/lib/smtp-message-processor.js +28 -7
  127. package/lib/sso.js +7 -3
  128. package/lib/stream-encrypt.js +14 -13
  129. package/lib/swagger-options.js +3 -1
  130. package/lib/tls/provision.js +69 -3
  131. package/lib/tls/store.js +14 -1
  132. package/lib/tools.js +113 -52
  133. package/lib/totp.js +16 -1
  134. package/lib/ui-routes/account-routes.js +27 -63
  135. package/lib/ui-routes/admin-config-routes.js +111 -134
  136. package/lib/ui-routes/admin-entities-routes.js +101 -191
  137. package/lib/ui-routes/ai-options.js +104 -0
  138. package/lib/ui-routes/auth-routes.js +98 -18
  139. package/lib/ui-routes/export-routes.js +3 -23
  140. package/lib/ui-routes/internals-routes.js +12 -9
  141. package/lib/ui-routes/network-config-routes.js +8 -18
  142. package/lib/ui-routes/oauth-config-routes.js +80 -214
  143. package/lib/ui-routes/route-helpers.js +40 -44
  144. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  145. package/lib/utils/decode-headers.js +32 -5
  146. package/lib/utils/header-map.js +62 -1
  147. package/lib/utils/network.js +2 -0
  148. package/lib/web-safe-html.js +77 -4
  149. package/lib/webhook-request.js +9 -1
  150. package/lib/webhook-routing.js +27 -1
  151. package/lib/webhooks.js +120 -43
  152. package/lib/worker-rpc-error.js +43 -2
  153. package/list-generate.js +13 -2
  154. package/package.json +38 -46
  155. package/sbom.json +1 -1
  156. package/scripts/refresh-test-tokens.js +42 -14
  157. package/server.js +340 -336
  158. package/static/css/flyonui.css +1 -1
  159. package/static/css/src/app.tailwind.css +7 -8
  160. package/static/js/ee-client.js +145 -70
  161. package/static/js/ui.js +350 -154
  162. package/static/licenses.html +460 -1861
  163. package/translations/messages.pot +99 -99
  164. package/views/accounts/browse.hbs +10 -4
  165. package/views/config/ai.hbs +49 -41
  166. package/views/config/oauth/app.hbs +2 -1
  167. package/views/dashboard.hbs +18 -16
  168. package/views/layout/app.hbs +0 -22
  169. package/views/layout/login.hbs +2 -1
  170. package/views/partials/filter_editor_js.hbs +4 -3
  171. package/views/partials/side_menu.hbs +0 -4
  172. package/views/partials/ui/account-picker.hbs +6 -32
  173. package/views/partials/ui/model-picker.hbs +31 -0
  174. package/views/partials/ui/pagination.hbs +6 -1
  175. package/views/partials/ui/picker.hbs +47 -0
  176. package/views/unsubscribe.hbs +1 -1
  177. package/workers/api.js +33 -23
  178. package/workers/export.js +55 -60
  179. package/workers/imap.js +134 -47
  180. package/workers/submit.js +3 -1
  181. package/workers/webhooks.js +46 -27
  182. package/.githooks/pre-commit +0 -80
  183. package/.github/CODE_OF_CONDUCT.md +0 -76
  184. package/.github/contributing.md +0 -17
  185. package/.github/dependabot.yml +0 -22
  186. package/.github/docker-smoke-test.sh +0 -61
  187. package/.github/workflows/deploy.yml +0 -215
  188. package/.github/workflows/e2e.yml +0 -55
  189. package/.github/workflows/release.yaml +0 -217
  190. package/.github/workflows/test.yml +0 -307
  191. package/lib/api-routes/chat-routes.js +0 -535
  192. package/lib/append-list.js +0 -63
  193. package/lib/document-store.js +0 -75
  194. package/lib/es.js +0 -757
  195. package/lib/generate-text-preview.js +0 -61
  196. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  197. package/lib/lua/h-push.lua +0 -32
  198. package/lib/pre-process.js +0 -196
  199. package/lib/threads.js +0 -155
  200. package/lib/ui-routes/document-store-routes.js +0 -806
  201. package/playwright.config.js +0 -47
  202. package/views/config/document-store/chat.hbs +0 -286
  203. package/views/config/document-store/index.hbs +0 -146
  204. package/views/config/document-store/mappings/index.hbs +0 -108
  205. package/views/config/document-store/mappings/new.hbs +0 -68
  206. package/views/config/document-store/pre-processing/index.hbs +0 -103
  207. package/views/partials/document_store_header.hbs +0 -30
  208. package/workers/documents.js +0 -1128
@@ -1,806 +0,0 @@
1
- 'use strict';
2
-
3
- // Admin UI routes for the Document Store config pages (/admin/config/document-store*).
4
- // Extracted verbatim from lib/routes-ui.js: Elasticsearch-backed document store settings,
5
- // the chat/embeddings model, pre-processing scripts, field mappings, and the connection
6
- // test. The Document Store (Elasticsearch indexing) is a deprecated feature.
7
-
8
- const Joi = require('joi');
9
- const assert = require('assert');
10
- const Boom = require('@hapi/boom');
11
- const { Client: ElasticSearch } = require('@elastic/elasticsearch');
12
-
13
- const settings = require('../settings');
14
- const { redis } = require('../db');
15
- const { REDIS_PREFIX } = require('../consts');
16
- const { failAction } = require('../tools');
17
- const { settingsSchema } = require('../schemas');
18
- const { defaultMappings } = require('../es');
19
- const { getESClient, documentStoreFeatureEnabled } = require('../document-store');
20
- const { getOpenAiModels, OPEN_AI_MODELS, getExampleDocumentsPayloads } = require('./route-helpers');
21
-
22
- const FIELD_TYPES = [
23
- {
24
- type: 'keyword',
25
- name: 'Keyword - for exact matches'
26
- },
27
- {
28
- type: 'text',
29
- name: 'Text - for fulltext search'
30
- },
31
- {
32
- type: 'html',
33
- name: 'HTML - a text field with HTML analyzer (does not index HTML tags)'
34
- },
35
- {
36
- type: 'filename',
37
- name: 'File name - a text field with filename analyzer (ngram)'
38
- },
39
- {
40
- type: 'boolean',
41
- name: 'Boolean'
42
- },
43
- {
44
- type: 'date',
45
- name: 'Date - date and date-time values'
46
- },
47
- {
48
- type: 'long',
49
- name: 'Number, long - from -2^63 to 2^63-1'
50
- },
51
- {
52
- type: 'integer',
53
- name: 'Number, integer - from -2^31 to 2^31-1'
54
- },
55
- {
56
- type: 'short',
57
- name: 'Number, short - from -32,768 to 32,767'
58
- },
59
- {
60
- type: 'byte',
61
- name: 'Number, short - from -128 to 127'
62
- },
63
- {
64
- type: 'double',
65
- name: 'Number, double - a double-precision 64-bit IEEE 754 floating point number'
66
- }
67
- ];
68
-
69
- const defaultMappingsList = Object.keys(defaultMappings)
70
- .map(key => {
71
- let type = defaultMappings[key].type || (defaultMappings[key].properties ? 'object' : 'text');
72
- if (defaultMappings[key].analyzer === 'htmlStripAnalyzer') {
73
- type += ' (HTML)';
74
- }
75
- if (defaultMappings[key].analyzer === 'filenameIndex') {
76
- type += ' (filename)';
77
- }
78
- return {
79
- key,
80
- type,
81
- indexed: defaultMappings[key].index !== false
82
- };
83
- })
84
- .sort((a, b) => a.key.toLowerCase().localeCompare(b.key.toLowerCase()));
85
-
86
- const configDocumentStoreSchema = {
87
- documentStoreEnabled: settingsSchema.documentStoreEnabled.default(false),
88
- documentStoreUrl: settingsSchema.documentStoreUrl.default(''),
89
- documentStoreIndex: settingsSchema.documentStoreIndex.default('emailengine'),
90
- documentStoreAuthEnabled: settingsSchema.documentStoreAuthEnabled.default(false),
91
- documentStoreUsername: settingsSchema.documentStoreUsername.default(''),
92
- documentStorePassword: settingsSchema.documentStorePassword
93
- };
94
-
95
- function init(args) {
96
- const { server } = args;
97
-
98
- // Deprecated Document Store feature: when the gate is off, register no routes so that
99
- // every /admin/config/document-store* page behaves like a regular 404.
100
- if (!documentStoreFeatureEnabled) {
101
- return;
102
- }
103
-
104
- server.route({
105
- method: 'GET',
106
- path: '/admin/config/document-store',
107
- async handler(request, h) {
108
- let documentStoreEnabled = await settings.get('documentStoreEnabled');
109
- let documentStoreUrl = await settings.get('documentStoreUrl');
110
- let documentStoreIndex = (await settings.get('documentStoreIndex')) || 'emailengine';
111
- let documentStoreGenerateEmbeddings = await settings.get('documentStoreGenerateEmbeddings');
112
- let documentStoreAuthEnabled = await settings.get('documentStoreAuthEnabled');
113
- let documentStoreUsername = await settings.get('documentStoreUsername');
114
- let hasDocumentStorePassword = !!(await settings.get('documentStorePassword'));
115
-
116
- return h.view(
117
- 'config/document-store/index',
118
- {
119
- menuConfig: true,
120
- menuConfigDocumentStore: true,
121
- documentStoreSettings: true,
122
-
123
- values: {
124
- documentStoreEnabled,
125
- documentStoreUrl,
126
- documentStoreIndex,
127
- documentStoreAuthEnabled,
128
- documentStoreUsername,
129
- documentStoreGenerateEmbeddings
130
- },
131
-
132
- hasDocumentStorePassword,
133
- hasOpenAiAPIKey: !!(await settings.get('openAiAPIKey'))
134
- },
135
- {
136
- layout: 'app'
137
- }
138
- );
139
- }
140
- });
141
-
142
- server.route({
143
- method: 'POST',
144
- path: '/admin/config/document-store',
145
- async handler(request, h) {
146
- try {
147
- if (!request.payload.documentStoreUrl) {
148
- request.payload.documentStoreEnabled = false;
149
- }
150
-
151
- if (!request.payload.documentStoreUsername) {
152
- request.payload.documentStoreAuthEnabled = false;
153
- // clear password as well if no username set
154
- request.payload.documentStorePassword = '';
155
- }
156
-
157
- for (let key of Object.keys(request.payload)) {
158
- await settings.set(key, request.payload[key]);
159
- }
160
-
161
- await request.flash({ type: 'info', message: `Configuration updated` });
162
-
163
- return h.redirect('/admin/config/document-store');
164
- } catch (err) {
165
- await request.flash({ type: 'danger', message: `Couldn't save settings. Try again.` });
166
- request.logger.error({ msg: 'Failed to update configuration', err });
167
-
168
- let hasDocumentStorePassword = !!(await settings.get('documentStorePassword'));
169
-
170
- return h.view(
171
- 'config/document-store/index',
172
- {
173
- menuConfig: true,
174
- menuConfigDocumentStore: true,
175
- documentStoreSettings: true,
176
-
177
- hasDocumentStorePassword,
178
- hasOpenAiAPIKey: !!(await settings.get('openAiAPIKey'))
179
- },
180
- {
181
- layout: 'app'
182
- }
183
- );
184
- }
185
- },
186
- options: {
187
- validate: {
188
- options: {
189
- stripUnknown: true,
190
- abortEarly: false,
191
- convert: true
192
- },
193
-
194
- async failAction(request, h, err) {
195
- let errors = {};
196
-
197
- if (err.details) {
198
- err.details.forEach(detail => {
199
- if (!errors[detail.path]) {
200
- errors[detail.path] = detail.message;
201
- }
202
- });
203
- }
204
-
205
- await request.flash({ type: 'danger', message: `Couldn't save settings. Try again.` });
206
- request.logger.error({ msg: 'Failed to update configuration', err });
207
-
208
- let hasDocumentStorePassword = !!(await settings.get('documentStorePassword'));
209
-
210
- return h
211
- .view(
212
- 'config/document-store/index',
213
- {
214
- menuConfig: true,
215
- menuConfigDocumentStore: true,
216
- documentStoreSettings: true,
217
-
218
- hasDocumentStorePassword,
219
- hasOpenAiAPIKey: !!(await settings.get('openAiAPIKey')),
220
-
221
- errors
222
- },
223
- {
224
- layout: 'app'
225
- }
226
- )
227
- .takeover();
228
- },
229
-
230
- payload: Joi.object(configDocumentStoreSchema)
231
- }
232
- }
233
- });
234
-
235
- server.route({
236
- method: 'GET',
237
- path: '/admin/config/document-store/chat',
238
- async handler(request, h) {
239
- let documentStoreChatModel = await settings.get('documentStoreChatModel');
240
-
241
- return h.view(
242
- 'config/document-store/chat',
243
- {
244
- menuConfig: true,
245
- menuConfigDocumentStore: true,
246
- documentStoreChat: true,
247
-
248
- documentStoreEnabled: await settings.get('documentStoreEnabled'),
249
- hasOpenAiAPIKey: !!(await settings.get('openAiAPIKey')),
250
- indexInfo: await settings.get('embeddings:index'),
251
-
252
- openAiModels: await getOpenAiModels(OPEN_AI_MODELS, documentStoreChatModel),
253
-
254
- values: {
255
- documentStoreGenerateEmbeddings: (await settings.get(`documentStoreGenerateEmbeddings`)) || false
256
- }
257
- },
258
- {
259
- layout: 'app'
260
- }
261
- );
262
- }
263
- });
264
-
265
- server.route({
266
- method: 'POST',
267
- path: '/admin/config/document-store/chat',
268
- async handler(request, h) {
269
- try {
270
- for (let key of Object.keys(request.payload)) {
271
- await settings.set(key, request.payload[key]);
272
- }
273
-
274
- await request.flash({ type: 'info', message: `Configuration updated` });
275
-
276
- return h.redirect('/admin/config/document-store/chat');
277
- } catch (err) {
278
- await request.flash({ type: 'danger', message: `Couldn't save settings. Try again.` });
279
- request.logger.error({ msg: 'Failed to update configuration', err });
280
-
281
- return h.view(
282
- 'config/document-store/index',
283
- {
284
- menuConfig: true,
285
- menuConfigDocumentStore: true,
286
- documentStoreChat: true,
287
-
288
- documentStoreEnabled: await settings.get('documentStoreEnabled'),
289
- hasOpenAiAPIKey: !!(await settings.get('openAiAPIKey')),
290
- indexInfo: await settings.get('embeddings:index'),
291
-
292
- openAiModels: await getOpenAiModels(OPEN_AI_MODELS, request.payload.documentStoreChatModel)
293
- },
294
- {
295
- layout: 'app'
296
- }
297
- );
298
- }
299
- },
300
- options: {
301
- validate: {
302
- options: {
303
- stripUnknown: true,
304
- abortEarly: false,
305
- convert: true
306
- },
307
-
308
- async failAction(request, h, err) {
309
- let errors = {};
310
-
311
- if (err.details) {
312
- err.details.forEach(detail => {
313
- if (!errors[detail.path]) {
314
- errors[detail.path] = detail.message;
315
- }
316
- });
317
- }
318
-
319
- await request.flash({ type: 'danger', message: `Couldn't save settings. Try again.` });
320
- request.logger.error({ msg: 'Failed to update configuration', err });
321
-
322
- return h
323
- .view(
324
- 'config/document-store/index',
325
- {
326
- menuConfig: true,
327
- menuConfigDocumentStore: true,
328
- documentStoreChat: true,
329
-
330
- documentStoreEnabled: await settings.get('documentStoreEnabled'),
331
- hasOpenAiAPIKey: !!(await settings.get('openAiAPIKey')),
332
- indexInfo: await settings.get('embeddings:index'),
333
-
334
- openAiModels: await getOpenAiModels(OPEN_AI_MODELS, request.payload.documentStoreChatModel),
335
-
336
- errors
337
- },
338
- {
339
- layout: 'app'
340
- }
341
- )
342
- .takeover();
343
- },
344
-
345
- payload: Joi.object({
346
- documentStoreGenerateEmbeddings: settingsSchema.documentStoreGenerateEmbeddings.default(false),
347
- openAiAPIKey: settingsSchema.openAiAPIKey.empty(''),
348
- documentStoreChatModel: settingsSchema.documentStoreChatModel.empty('')
349
- })
350
- }
351
- }
352
- });
353
-
354
- server.route({
355
- method: 'GET',
356
- path: '/admin/config/document-store/pre-processing',
357
- async handler(request, h) {
358
- return h.view(
359
- 'config/document-store/pre-processing/index',
360
- {
361
- menuConfig: true,
362
- menuConfigDocumentStore: true,
363
- documentStorePreProcessing: true,
364
-
365
- values: {
366
- enabled: (await settings.get(`documentStorePreProcessingEnabled`)) || false,
367
-
368
- contentFnJson: JSON.stringify(
369
- (await settings.get(`documentStorePreProcessingFn`)) ||
370
- `// Pass all emails
371
- return true;`
372
- ),
373
- contentMapJson: JSON.stringify(
374
- (await settings.get(`documentStorePreProcessingMap`)) ||
375
- `// By default the output payload is returned unmodified.
376
- return payload;`
377
- )
378
- },
379
-
380
- examplePayloadsJson: JSON.stringify(await getExampleDocumentsPayloads()),
381
- scriptEnvJson: JSON.stringify((await settings.get('scriptEnv')) || '{}')
382
- },
383
- {
384
- layout: 'app'
385
- }
386
- );
387
- }
388
- });
389
-
390
- server.route({
391
- method: 'POST',
392
- path: '/admin/config/document-store/pre-processing',
393
- async handler(request, h) {
394
- let contentFn, contentMap;
395
- try {
396
- if (request.payload.contentFnJson === '') {
397
- contentFn = null;
398
- } else {
399
- contentFn = JSON.parse(request.payload.contentFnJson);
400
- if (typeof contentFn !== 'string') {
401
- throw new Error('Invalid Format');
402
- }
403
- }
404
- } catch (err) {
405
- err.details = {
406
- contentFnJson: 'Invalid JSON'
407
- };
408
- throw err;
409
- }
410
-
411
- try {
412
- if (request.payload.contentMapJson === '') {
413
- contentMap = null;
414
- } else {
415
- contentMap = JSON.parse(request.payload.contentMapJson);
416
- if (typeof contentMap !== 'string') {
417
- throw new Error('Invalid Format');
418
- }
419
- }
420
- } catch (err) {
421
- err.details = {
422
- contentMapJson: 'Invalid JSON'
423
- };
424
- throw err;
425
- }
426
-
427
- try {
428
- await settings.setMulti({
429
- documentStorePreProcessingEnabled: request.payload.enabled,
430
- documentStorePreProcessingFn: contentFn,
431
- documentStorePreProcessingMap: contentMap
432
- });
433
-
434
- await request.flash({ type: 'info', message: `Document Store rules saved` });
435
- return h.redirect(`/admin/config/document-store/pre-processing`);
436
- } catch (err) {
437
- await request.flash({ type: 'danger', message: `Couldn't save Document Store rules. Try again.` });
438
- request.logger.error({ msg: 'Failed to update Document Store pre-processing rules', err });
439
-
440
- return h.view(
441
- 'config/document-store/pre-processing/index',
442
- {
443
- menuConfig: true,
444
- menuConfigDocumentStore: true,
445
- documentStorePreProcessing: true,
446
-
447
- errors: err.details,
448
-
449
- examplePayloadsJson: JSON.stringify(await getExampleDocumentsPayloads()),
450
- scriptEnvJson: JSON.stringify((await settings.get('scriptEnv')) || '{}')
451
- },
452
- {
453
- layout: 'app'
454
- }
455
- );
456
- }
457
- },
458
- options: {
459
- validate: {
460
- options: {
461
- stripUnknown: true,
462
- abortEarly: false,
463
- convert: true
464
- },
465
-
466
- async failAction(request, h, err) {
467
- let errors = {};
468
-
469
- if (err.details) {
470
- err.details.forEach(detail => {
471
- if (!errors[detail.path]) {
472
- errors[detail.path] = detail.message;
473
- }
474
- });
475
- }
476
-
477
- await request.flash({ type: 'danger', message: `Couldn't save Document Store rules. Try again.` });
478
- request.logger.error({ msg: 'Failed to update Document Store pre-processing rules', err });
479
-
480
- return h
481
- .view(
482
- 'config/document-store/pre-processing/index',
483
- {
484
- menuConfig: true,
485
- menuConfigDocumentStore: true,
486
- documentStorePreProcessing: true,
487
-
488
- errors,
489
-
490
- examplePayloadsJson: JSON.stringify(await getExampleDocumentsPayloads()),
491
- scriptEnvJson: JSON.stringify((await settings.get('scriptEnv')) || '{}')
492
- },
493
- {
494
- layout: 'app'
495
- }
496
- )
497
- .takeover();
498
- },
499
-
500
- payload: Joi.object({
501
- enabled: Joi.boolean()
502
- .truthy('Y', 'true', '1', 'on')
503
- .falsy('N', 'false', 0, '')
504
- .default(false)
505
- .example(false)
506
- .description('Is the pre-processing enabled'),
507
- contentFnJson: Joi.string()
508
- .max(1024 * 1024)
509
- .default('')
510
- .allow('')
511
- .trim()
512
- .description('Filter function'),
513
- contentMapJson: Joi.string()
514
- .max(1024 * 1024)
515
- .default('')
516
- .allow('')
517
- .trim()
518
- .description('Map function')
519
- })
520
- }
521
- }
522
- });
523
-
524
- server.route({
525
- method: 'GET',
526
- path: '/admin/config/document-store/mappings',
527
- async handler(request, h) {
528
- let customMappings = (await redis.hgetall(`${REDIS_PREFIX}mappings`)) || {};
529
- const customMappingsList = Object.keys(customMappings)
530
- .map(key => {
531
- let value;
532
- try {
533
- value = JSON.parse(customMappings[key]);
534
- } catch (err) {
535
- return null;
536
- }
537
-
538
- let type = value.type || (value.properties ? 'object' : 'text');
539
- if (value.analyzer === 'htmlStripAnalyzer') {
540
- type += ' (HTML)';
541
- }
542
- if (value.analyzer === 'filenameIndex') {
543
- type += ' (filename)';
544
- }
545
- return {
546
- key,
547
- type,
548
- indexed: value.index !== false
549
- };
550
- })
551
- .sort((a, b) => a.key.toLowerCase().localeCompare(b.key.toLowerCase()));
552
- return h.view(
553
- 'config/document-store/mappings/index',
554
- {
555
- menuConfig: true,
556
- menuConfigDocumentStore: true,
557
- documentStoreMappings: true,
558
-
559
- defaultMappingsList,
560
- customMappingsList
561
- },
562
- {
563
- layout: 'app'
564
- }
565
- );
566
- }
567
- });
568
-
569
- server.route({
570
- method: 'GET',
571
- path: '/admin/config/document-store/mappings/new',
572
- async handler(request, h) {
573
- return h.view(
574
- 'config/document-store/mappings/new',
575
- {
576
- menuConfig: true,
577
- menuConfigDocumentStore: true,
578
- documentStoreMappings: true,
579
-
580
- fieldTypes: FIELD_TYPES.map(entry => ({ type: entry.type, name: entry.name, selected: false })),
581
-
582
- values: {
583
- indexed: true
584
- }
585
- },
586
- {
587
- layout: 'app'
588
- }
589
- );
590
- }
591
- });
592
-
593
- server.route({
594
- method: 'POST',
595
- path: '/admin/config/document-store/mappings/new',
596
- async handler(request, h) {
597
- try {
598
- const { index, client } = await getESClient(request.logger);
599
- if (!client) {
600
- return;
601
- }
602
-
603
- let mappingEntry = {};
604
- switch (request.payload.type) {
605
- case 'html':
606
- mappingEntry[request.payload.field] = {
607
- type: 'text',
608
- analyzer: 'htmlStripAnalyzer',
609
- index: !!request.payload.indexed
610
- };
611
- break;
612
- case 'filename':
613
- mappingEntry[request.payload.field] = {
614
- type: 'text',
615
- analyzer: 'filenameIndex',
616
- search_analyzer: 'filenameSearch',
617
- index: !!request.payload.indexed
618
- };
619
- break;
620
- default: {
621
- mappingEntry[request.payload.field] = {
622
- type: request.payload.type,
623
- index: !!request.payload.indexed
624
- };
625
- }
626
- }
627
-
628
- try {
629
- const updateRes = await client.indices.putMapping({ index, properties: mappingEntry });
630
- assert(updateRes && updateRes.acknowledged);
631
- } catch (err) {
632
- if (err.meta && err.meta.body && err.meta.body.error && err.meta.body.error.reason) {
633
- let error = Boom.boomify(new Error(err.meta.body.error.reason), { statusCode: err.meta.statusCode || 500 });
634
- throw error;
635
- }
636
- throw err;
637
- }
638
-
639
- await redis.hset(`${REDIS_PREFIX}mappings`, request.payload.field, JSON.stringify(mappingEntry[request.payload.field]));
640
-
641
- await request.flash({ type: 'info', message: `Mapping created` });
642
- return h.redirect('/admin/config/document-store/mappings');
643
- } catch (err) {
644
- if (Boom.isBoom(err)) {
645
- await request.flash({ type: 'danger', message: err.message });
646
- } else {
647
- await request.flash({ type: 'danger', message: err.responseText || `Couldn't create mapping. Try again.` });
648
- }
649
- request.logger.error({ msg: 'Failed to create mapping', err });
650
-
651
- return h.view(
652
- 'config/document-store/mappings/new',
653
- {
654
- menuConfig: true,
655
- menuConfigDocumentStore: true,
656
- documentStoreMappings: true,
657
-
658
- fieldTypes: FIELD_TYPES.map(entry => ({ type: entry.type, name: entry.name, selected: request.payload.type === entry.type }))
659
- },
660
- {
661
- layout: 'app'
662
- }
663
- );
664
- }
665
- },
666
- options: {
667
- validate: {
668
- options: {
669
- stripUnknown: true,
670
- abortEarly: false,
671
- convert: true
672
- },
673
-
674
- async failAction(request, h, err) {
675
- let errors = {};
676
-
677
- if (err.details) {
678
- err.details.forEach(detail => {
679
- if (!errors[detail.path]) {
680
- errors[detail.path] = detail.message;
681
- }
682
- });
683
- }
684
-
685
- await request.flash({ type: 'danger', message: `Couldn't create mapping. Try again.` });
686
- request.logger.error({ msg: 'Failed to create mapping', err });
687
-
688
- return h
689
- .view(
690
- 'config/document-store/mappings/new',
691
- {
692
- menuConfig: true,
693
- menuConfigDocumentStore: true,
694
- documentStoreMappings: true,
695
-
696
- fieldTypes: FIELD_TYPES.map(entry => ({ type: entry.type, name: entry.name, selected: request.payload.type === entry.type })),
697
-
698
- errors
699
- },
700
- {
701
- layout: 'app'
702
- }
703
- )
704
- .takeover();
705
- },
706
- payload: Joi.object({
707
- field: Joi.string()
708
- .empty('')
709
- .trim()
710
- .lowercase()
711
- .pattern(/^[-_+]|[\\/*?"<>| ,#:]/, { name: 'allowed elasticsearch field', invert: true })
712
- .invalid(...Object.keys(defaultMappings))
713
- .required()
714
- .label('Field name'),
715
- type: Joi.string()
716
- .empty('')
717
- .trim()
718
- .valid(...FIELD_TYPES.map(entry => entry.type))
719
- .default('text')
720
- .label('Field type'),
721
- indexed: Joi.boolean().truthy('Y', 'true', '1', 'on').falsy('N', 'false', 0, '')
722
- })
723
- }
724
- }
725
- });
726
-
727
- server.route({
728
- method: 'POST',
729
- path: '/admin/config/document-store/test',
730
- async handler(request) {
731
- const { documentStoreUrl, documentStoreAuthEnabled, documentStoreUsername, documentStorePassword } = request.payload;
732
-
733
- let clientConfig = {
734
- node: { url: new URL(documentStoreUrl), tls: { rejectUnauthorized: false } },
735
- auth:
736
- documentStoreAuthEnabled && documentStoreUsername
737
- ? {
738
- username: documentStoreUsername,
739
- password: documentStorePassword || (await settings.get('documentStorePassword'))
740
- }
741
- : false
742
- };
743
-
744
- const client = new ElasticSearch(clientConfig);
745
-
746
- let start = Date.now();
747
- let duration;
748
- try {
749
- let clusterInfo;
750
-
751
- try {
752
- clusterInfo = await client.info();
753
- duration = Date.now() - start;
754
- } catch (err) {
755
- duration = Date.now() - start;
756
- throw err;
757
- }
758
-
759
- if (!clusterInfo || !clusterInfo.name) {
760
- let err = new Error(`Invalid response from server`);
761
- throw err;
762
- }
763
-
764
- return {
765
- success: true,
766
- duration
767
- };
768
- } catch (err) {
769
- request.logger.error({
770
- msg: 'Failed posting request',
771
- documentStoreUrl,
772
- documentStoreAuthEnabled,
773
- documentStoreUsername,
774
- command: 'info',
775
- err
776
- });
777
- return {
778
- success: false,
779
- duration,
780
- error: err.message
781
- };
782
- }
783
- },
784
- options: {
785
- tags: ['test'],
786
- validate: {
787
- options: {
788
- stripUnknown: true,
789
- abortEarly: false,
790
- convert: true
791
- },
792
-
793
- failAction,
794
-
795
- payload: Joi.object({
796
- documentStoreUrl: settingsSchema.documentStoreUrl.required(),
797
- documentStoreAuthEnabled: settingsSchema.documentStoreAuthEnabled.default(false),
798
- documentStoreUsername: settingsSchema.documentStoreUsername.default(''),
799
- documentStorePassword: settingsSchema.documentStorePassword
800
- })
801
- }
802
- }
803
- });
804
- }
805
-
806
- module.exports = init;