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,61 +0,0 @@
1
- 'use strict';
2
-
3
- const { compile } = require('html-to-text');
4
-
5
- const htmlToText = compile({
6
- wordwrap: 1000,
7
- selectors: [
8
- { selector: 'p', options: { leadingLineBreaks: 1, trailingLineBreaks: 1, format: 'inline' } },
9
- { selector: 'pre', options: { leadingLineBreaks: 1, trailingLineBreaks: 1, format: 'inline' } },
10
- //{ selector: 'table.class#id', format: 'skip' },
11
- { selector: 'a', options: { ignoreHref: true, linkBrackets: false } },
12
- { selector: 'img', format: 'skip' },
13
- { selector: 'hr', format: 'skip' },
14
- { selector: 'blockquote', format: 'inline' },
15
- { selector: 'td', format: 'inline' },
16
- { selector: 'tr', format: 'inline' },
17
- { selector: 'h1', options: { uppercase: false } },
18
- { selector: 'h2', options: { uppercase: false } },
19
- { selector: 'h3', options: { uppercase: false } },
20
- { selector: 'h4', options: { uppercase: false } },
21
- { selector: 'h5', options: { uppercase: false } },
22
- { selector: 'h6', options: { uppercase: false } },
23
- { selector: 'table', options: { uppercaseHeaderCells: false } }
24
- ],
25
- hideLinkHrefIfSameAsText: true
26
- });
27
-
28
- function generateTextPreview(textContent, maxLength) {
29
- maxLength = maxLength || 128;
30
- if (!textContent || (!textContent.plain && !textContent.html)) {
31
- return null;
32
- }
33
-
34
- let text;
35
- if (textContent.html) {
36
- text = htmlToText(textContent.html);
37
- } else {
38
- text = textContent.plain;
39
- }
40
-
41
- text = text.replace(/\r?\n/g, ' ').replace(/[\s]+/g, ' ').trim();
42
-
43
- if (text.length <= maxLength) {
44
- return text.replace(/[\u034f\u200c\u00a0]+/g, ' ').trim();
45
- }
46
-
47
- let truncated = text.substring(0, maxLength);
48
-
49
- // Drop the word the cut landed in, unless the chunk is one unbroken run (a long URL or
50
- // token), in which case the hard cut is the only preview there is
51
- let preview = truncated.replace(/([^\s.!?]*)$/, '');
52
- if (!preview.trim()) {
53
- preview = truncated;
54
- }
55
-
56
- return preview.replace(/[\u034f\u200c\u00a0]+/g, ' ').trim();
57
- }
58
-
59
- module.exports = { generateTextPreview };
60
-
61
- //process.stdout.write(generateTextPreview({ html: require('fs').readFileSync(process.argv[2], 'utf-8') }));
@@ -1,129 +0,0 @@
1
- 'use strict';
2
-
3
- let EventEmitter = require('events').EventEmitter;
4
-
5
- // Expects that the folder listing is a Map
6
-
7
- class MemoryNotifier extends EventEmitter {
8
- constructor(options) {
9
- super();
10
- this.folders = options.folders || new Map();
11
-
12
- let logfunc = (...args) => {
13
- let level = args.shift() || 'DEBUG';
14
- let message = args.shift() || '';
15
-
16
- console.log([level].concat(message || '').join(' '), ...args);
17
- };
18
-
19
- this.logger = options.logger || {
20
- info: logfunc.bind(null, 'INFO'),
21
- debug: logfunc.bind(null, 'DEBUG'),
22
- error: logfunc.bind(null, 'ERROR')
23
- };
24
-
25
- this._listeners = new EventEmitter();
26
- this._listeners.setMaxListeners(0);
27
-
28
- EventEmitter.call(this);
29
- }
30
-
31
- /**
32
- * Registers an event handler for mailbox:username events
33
- *
34
- * @param {String} username
35
- * @param {String} mailbox
36
- * @param {Function} handler Function to run once there are new entries in the journal
37
- */
38
- addListener(session, handler) {
39
- this._listeners.addListener(session.user.id.toString(), handler);
40
- }
41
-
42
- /**
43
- * Unregisters an event handler for mailbox:username events
44
- *
45
- * @param {String} username
46
- * @param {String} mailbox
47
- * @param {Function} handler Function to run once there are new entries in the journal
48
- */
49
- removeListener(session, handler) {
50
- this._listeners.removeListener(session.user.id.toString(), handler);
51
- }
52
-
53
- /**
54
- * Stores multiple journal entries to db
55
- *
56
- * @param {String} username
57
- * @param {String} mailbox
58
- * @param {Array|Object} entries An array of entries to be journaled
59
- * @param {Function} callback Runs once the entry is either stored or an error occurred
60
- */
61
- addEntries(mailbox, entries, callback) {
62
- let folder = this.folders.get(mailbox);
63
-
64
- if (!folder) {
65
- return callback(null, new Error('Selected mailbox does not exist'));
66
- }
67
-
68
- if (entries && !Array.isArray(entries)) {
69
- entries = [entries];
70
- } else if (!entries || !entries.length) {
71
- return callback(null, false);
72
- }
73
-
74
- // store entries in the folder object
75
- if (!folder.journal) {
76
- folder.journal = [];
77
- }
78
-
79
- entries.forEach(entry => {
80
- entry.modseq = ++folder.modifyIndex;
81
- folder.journal.push(entry);
82
- });
83
-
84
- setImmediate(callback);
85
- }
86
-
87
- /**
88
- * Sends a notification that there are new updates in the selected mailbox
89
- *
90
- * @param {String} username
91
- * @param {String} mailbox
92
- */
93
- fire(username, payload) {
94
- setImmediate(() => {
95
- this._listeners.emit(username, payload);
96
- });
97
- }
98
-
99
- /**
100
- * Returns all entries from the journal that have higher than provided modification index
101
- *
102
- * @param {String} username
103
- * @param {String} mailbox
104
- * @param {Number} modifyIndex Last known modification id
105
- * @param {Function} callback Returns update entries as an array
106
- */
107
- getUpdates(mailbox, modifyIndex, callback) {
108
- modifyIndex = Number(modifyIndex) || 0;
109
-
110
- if (!this.folders.has(mailbox)) {
111
- return callback(null, 'NONEXISTENT');
112
- }
113
-
114
- let folder = this.folders.get(mailbox);
115
- let minIndex = folder.journal.length;
116
-
117
- for (let i = folder.journal.length - 1; i >= 0; i--) {
118
- if (folder.journal[i].modseq > modifyIndex) {
119
- minIndex = i;
120
- } else {
121
- break;
122
- }
123
- }
124
-
125
- return callback(null, folder.journal.slice(minIndex));
126
- }
127
- }
128
-
129
- module.exports = MemoryNotifier;
@@ -1,32 +0,0 @@
1
- --[[
2
- Script: h-push.lua
3
- Purpose: Appends data to a hash field value (concatenates strings)
4
-
5
- KEYS:
6
- [1] hashKey - The hash key to operate on
7
-
8
- ARGV:
9
- [1] entryKey - The hash field name
10
- [2] buf - The string buffer to append
11
-
12
- Returns:
13
- 2 if field existed and data was appended
14
- 1 if field was newly created with the data
15
- --]]
16
-
17
- local hashKey = KEYS[1];
18
- local entryKey = ARGV[1];
19
-
20
- local buf = ARGV[2];
21
-
22
- if redis.call("HEXISTS", hashKey, entryKey) == 1 then
23
- -- Field exists, append to existing content
24
- local content = redis.call("HGET", hashKey, entryKey);
25
- redis.call("HSET", hashKey, entryKey, content .. buf);
26
- return 2; -- Indicates append operation
27
- else
28
- -- Field doesn't exist, create new
29
- redis.call("HSET", hashKey, entryKey, buf);
30
- return 1; -- Indicates new field creation
31
- end;
32
-
@@ -1,196 +0,0 @@
1
- 'use strict';
2
-
3
- const { redis } = require('./db');
4
- const msgpack = require('./msgpack');
5
- const logger = require('./logger');
6
- const { REDIS_PREFIX } = require('./consts');
7
- const settings = require('./settings');
8
- const { SubScript } = require('./sub-script');
9
-
10
- class PreProcessHandler {
11
- constructor(options) {
12
- this.options = options || {};
13
- this.redis = this.options.redis;
14
-
15
- this.handlerCache = null;
16
- this.handlerCacheV = 0;
17
- }
18
-
19
- getPreProcessLogKey() {
20
- return `${REDIS_PREFIX}dspp:l`;
21
- }
22
-
23
- async getHandler() {
24
- let preProcessData = {
25
- enabled: (await settings.get(`documentStorePreProcessingEnabled`)) || false,
26
- contentFn: await settings.get(`documentStorePreProcessingFn`),
27
- contentMap: await settings.get(`documentStorePreProcessingMap`)
28
- };
29
-
30
- if (!preProcessData.enabled) {
31
- return null;
32
- }
33
-
34
- try {
35
- if (preProcessData.contentFn) {
36
- preProcessData.compiledFn = SubScript.create(`pre-process:filter`, preProcessData.contentFn);
37
- } else {
38
- preProcessData.compiledFn = false;
39
- }
40
- } catch (err) {
41
- await this.storeLog('filter', null, err.stack);
42
-
43
- logger.error({ msg: 'Failed to compile pre-processing script', component: 'pre-process', type: 'filter', err });
44
- preProcessData.compiledFn = null;
45
- preProcessData.compiledMap = null;
46
- }
47
-
48
- if (preProcessData.compiledFn) {
49
- try {
50
- if (preProcessData.contentMap) {
51
- preProcessData.compiledMap = SubScript.create(`pre-process:map`, preProcessData.contentMap);
52
- } else {
53
- preProcessData.contentMap = false;
54
- }
55
- } catch (err) {
56
- await this.storeLog('map', null, err.stack);
57
-
58
- logger.error({ msg: 'Failed to compile pre-processing script', component: 'pre-process', type: 'map', err });
59
- preProcessData.compiledFn = null;
60
- preProcessData.compiledMap = null;
61
- }
62
- }
63
-
64
- if (preProcessData.compiledFn) {
65
- preProcessData.filterFn = async payload => {
66
- try {
67
- return await preProcessData.compiledFn.exec(payload);
68
- } catch (err) {
69
- await this.storeLog('filter', payload, err.stack);
70
- logger.error({ msg: 'Failed to execute pre-processing script', component: 'pre-process', type: 'filter', err });
71
- return null;
72
- }
73
- };
74
- }
75
-
76
- if (preProcessData.compiledMap) {
77
- preProcessData.mapFn = async payload => {
78
- try {
79
- return preProcessData.compiledMap.exec(payload);
80
- } catch (err) {
81
- await this.storeLog('map', payload, err.stack);
82
- logger.error({ msg: 'Failed to execute pre-processing script', component: 'pre-process', type: 'map', err });
83
- return null;
84
- }
85
- };
86
- }
87
-
88
- return preProcessData;
89
- }
90
-
91
- async getPreProcessHandler() {
92
- let v = await this.redis.hget(`${REDIS_PREFIX}settings`, 'documentStoreVersion');
93
- v = Number(v) || 0;
94
- if (v !== this.handlerCacheV) {
95
- // changes detected
96
- this.handlerCache = await this.getHandler();
97
- // mark the cache as current only after a successful rebuild, so a failure above
98
- // leaves it stale and the next call retries
99
- this.handlerCacheV = v;
100
- }
101
- return this.handlerCache;
102
- }
103
-
104
- async storeLog(type, payload, error) {
105
- const maxLogLines = 20;
106
-
107
- let logRow = msgpack.encode({
108
- type,
109
- payload,
110
- error,
111
- created: new Date().toISOString()
112
- });
113
-
114
- try {
115
- await redis.multi().rpush(this.getPreProcessLogKey(), logRow).ltrim(this.getPreProcessLogKey(), -maxLogLines, -1).exec();
116
- } catch (err) {
117
- logger.error({ msg: 'Failed to insert error log entries', component: 'pre-process', err });
118
- }
119
- }
120
-
121
- async getErrorLog() {
122
- let logLines = await redis.lrangeBuffer(this.getPreProcessLogKey(), 0, -1);
123
- if (!Array.isArray(logLines)) {
124
- logLines = [].concat(logLines || []);
125
- }
126
-
127
- let logEntries = [];
128
-
129
- for (let line of logLines) {
130
- try {
131
- let entry = msgpack.decode(line);
132
- logEntries.unshift(entry);
133
- } catch (err) {
134
- logger.error({ msg: 'Failed to decode log line', component: 'pre-process', entry: line && line.toString('base64'), err });
135
- }
136
- }
137
-
138
- return logEntries;
139
- }
140
-
141
- async run(originalPayload) {
142
- // custom webhoom routes
143
- let preProcessHandler = await this.getPreProcessHandler();
144
-
145
- if (!preProcessHandler || !preProcessHandler.enabled) {
146
- return originalPayload;
147
- }
148
-
149
- if (!preProcessHandler.filterFn) {
150
- return false;
151
- }
152
-
153
- let canStore;
154
- let payload = structuredClone(originalPayload);
155
-
156
- try {
157
- canStore = await preProcessHandler.filterFn(payload);
158
- } catch (err) {
159
- await this.storeLog('filter', payload, err.stack);
160
-
161
- logger.error({ msg: 'Failed to execute pre-processing script', component: 'pre-process', type: 'filter', err });
162
- }
163
-
164
- if (canStore) {
165
- if (preProcessHandler.mapFn) {
166
- try {
167
- payload = await preProcessHandler.mapFn(payload);
168
- if (payload) {
169
- if (typeof payload !== 'object') {
170
- throw new Error(`Invalid document type. Must be object, got ${typeof payload}`);
171
- }
172
- // make sure important fields are not touched
173
- for (let key of ['id', 'account', 'path', 'uid', 'specialUse', 'messageId']) {
174
- if (key in originalPayload && originalPayload[key] !== payload[key]) {
175
- payload[key] = originalPayload[key];
176
- }
177
- }
178
- }
179
- } catch (err) {
180
- await this.storeLog('map', payload, err.stack);
181
-
182
- logger.error({ msg: 'Failed to execute pre-processing script', component: 'pre-process', type: 'map', err });
183
- canStore = false;
184
- }
185
- }
186
- }
187
-
188
- if (canStore && payload) {
189
- return payload;
190
- }
191
-
192
- return false;
193
- }
194
- }
195
-
196
- module.exports.preProcess = new PreProcessHandler({ redis });
package/lib/threads.js DELETED
@@ -1,155 +0,0 @@
1
- 'use strict';
2
-
3
- const { randomUUID: uuid } = require('crypto');
4
-
5
- async function getThread(client, index, account, messageData, logger) {
6
- if (messageData.threadId) {
7
- return messageData.threadId;
8
- }
9
-
10
- if (!client) {
11
- return;
12
- }
13
-
14
- let subject = (messageData.subject || '')
15
- .replace(/^([a-z]{1,8}:\s*)*/i, '')
16
- .trim()
17
- .toLowerCase();
18
-
19
- let references = new Set();
20
-
21
- if (messageData.headers) {
22
- []
23
- .concat(messageData.headers['message-id'] || [])
24
- .concat(messageData.headers['in-reply-to'] || [])
25
- .concat(messageData.headers.references || [])
26
- .concat(messageData.headers['thread-index'] || [])
27
- .concat(messageData.relatedMessageId || [])
28
- .flatMap(entry => entry)
29
- .flatMap(entry => entry.split(/\s+/))
30
- .map(entry => entry.trim())
31
- .filter(entry => entry)
32
- .forEach(entry => references.add(entry));
33
- }
34
-
35
- if (!references.size) {
36
- return false;
37
- }
38
-
39
- references = Array.from(references).slice(0, 20);
40
-
41
- let query = {
42
- bool: {
43
- must: [
44
- {
45
- term: {
46
- account
47
- }
48
- },
49
- {
50
- bool: {
51
- should: references.map(ref => ({
52
- term: {
53
- references: ref
54
- }
55
- })),
56
- minimum_should_match: 1
57
- }
58
- }
59
- ]
60
- }
61
- };
62
-
63
- let searchResult;
64
-
65
- const maxThreadRetries = 5;
66
- for (let i = 0; i < 5; i++) {
67
- let failed;
68
- try {
69
- searchResult = await client.search({
70
- index: `${index}.threads`,
71
- query,
72
- size: 1
73
- });
74
-
75
- if (!searchResult.hits.total.value) {
76
- // create new thread
77
- let id = uuid();
78
- let createResult = await client.create({
79
- index: `${index}.threads`,
80
- id,
81
- document: {
82
- account,
83
- subject,
84
- references,
85
- created: new Date().toISOString()
86
- }
87
- });
88
- return (createResult && createResult._id) || false;
89
- }
90
- } catch (err) {
91
- failed = err;
92
- }
93
-
94
- if (!failed) {
95
- // found an existing thread
96
- break;
97
- } else if (i < maxThreadRetries - 1) {
98
- // try again after a small delay
99
- logger.warn({ msg: 'Failed to get thread entry, retrying', retry: i, err: failed });
100
- await new Promise(r => setTimeout(r, 150));
101
- } else {
102
- // too many retries
103
- throw failed;
104
- }
105
- }
106
-
107
- let threadEntry = searchResult.hits.hits[0];
108
- if (!threadEntry || !threadEntry._id) {
109
- return false;
110
- }
111
-
112
- // do not store more than 100 references per thread
113
- if (threadEntry._source.references.length < 128) {
114
- let missingRefs = [];
115
- for (let ref of references) {
116
- if (!threadEntry._source.references.includes(ref)) {
117
- missingRefs.push(ref);
118
- }
119
- }
120
-
121
- if (missingRefs.length) {
122
- // update thread entry
123
- try {
124
- let script = {
125
- lang: 'painless',
126
- source: `
127
- for(ref in params.refs){
128
- if(! ctx._source.references.contains(ref)){
129
- ctx._source.references.add(ref)
130
- }
131
- }`,
132
- params: {
133
- refs: missingRefs
134
- }
135
- };
136
-
137
- await client.update({
138
- index: `${index}.threads`,
139
- id: threadEntry._id,
140
- refresh: true,
141
- script,
142
- upsert: Object.assign(threadEntry._source, {
143
- references: threadEntry._source.references.concat(missingRefs)
144
- })
145
- });
146
- } catch (err) {
147
- logger.warn({ msg: 'Failed to update thread entry', err });
148
- }
149
- }
150
- }
151
-
152
- return threadEntry._id;
153
- }
154
-
155
- module.exports = { getThread };