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.
- package/.ncurc.js +12 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +52 -0
- package/Dockerfile +4 -2
- package/bin/emailengine.js +28 -18
- package/config/default.toml +0 -5
- package/config/test.toml +0 -5
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +70 -42
- package/getswagger.sh +0 -4
- package/lib/account/account-state.js +2 -110
- package/lib/account/bounce-store-sweep.js +63 -0
- package/lib/account/expected-identity.js +1 -1
- package/lib/account-assignment.js +207 -0
- package/lib/account.js +374 -878
- package/lib/api-reference/index.js +2 -3
- package/lib/api-reference/schema-tree.js +53 -3
- package/lib/api-routes/account-routes.js +18 -29
- package/lib/api-routes/blocklist-routes.js +2 -2
- package/lib/api-routes/bull-board-routes.js +1 -6
- package/lib/api-routes/export-routes.js +2 -22
- package/lib/api-routes/gateway-routes.js +5 -14
- package/lib/api-routes/index.js +1 -13
- package/lib/api-routes/mailbox-routes.js +2 -7
- package/lib/api-routes/mcp-oauth-routes.js +2 -1
- package/lib/api-routes/mcp-routes.js +7 -7
- package/lib/api-routes/message-routes.js +44 -236
- package/lib/api-routes/mint-bounds.js +110 -0
- package/lib/api-routes/oauth2-app-routes.js +23 -32
- package/lib/api-routes/operation-impact.js +1 -1
- package/lib/api-routes/outbox-routes.js +2 -2
- package/lib/api-routes/permission-map.js +1 -7
- package/lib/api-routes/route-helpers.js +11 -5
- package/lib/api-routes/settings-routes.js +19 -19
- package/lib/api-routes/stats-routes.js +1 -1
- package/lib/api-routes/submit-routes.js +17 -18
- package/lib/api-routes/template-routes.js +4 -9
- package/lib/api-routes/token-routes.js +27 -5
- package/lib/api-token-scheme.js +71 -0
- package/lib/arf-detect.js +41 -7
- package/lib/auth-token.js +44 -24
- package/lib/autodetect-imap-settings.js +163 -123
- package/lib/bounce-detect.js +25 -16
- package/lib/calendar-event.js +78 -0
- package/lib/consts.js +51 -5
- package/lib/create-imap-client.js +24 -0
- package/lib/db.js +76 -17
- package/lib/delivery-error.js +2 -1
- package/lib/egress-fetch.js +54 -3
- package/lib/egress-filter.js +11 -0
- package/lib/email-client/api-retry.js +147 -0
- package/lib/email-client/base-client.js +628 -615
- package/lib/email-client/gmail/gmail-api.js +38 -125
- package/lib/email-client/gmail/send-request.js +1 -1
- package/lib/email-client/gmail-client.js +170 -84
- package/lib/email-client/imap/mailbox.js +244 -535
- package/lib/email-client/imap/stale-view.js +109 -0
- package/lib/email-client/imap/subconnection.js +46 -9
- package/lib/email-client/imap/sync-operations.js +5 -37
- package/lib/email-client/imap-client.js +188 -64
- package/lib/email-client/message-builder.js +9 -14
- package/lib/email-client/notification-handler.js +5 -219
- package/lib/email-client/outlook/graph-api.js +147 -126
- package/lib/email-client/outlook/send-request.js +10 -4
- package/lib/email-client/outlook-client.js +519 -617
- package/lib/email-client/smtp-pool-manager.js +3 -2
- package/lib/encrypt.js +184 -19
- package/lib/enum-descriptions.js +1 -2
- package/lib/export.js +144 -41
- package/lib/gateway.js +20 -6
- package/lib/get-raw-email.js +26 -44
- package/lib/handlebars-helpers.js +31 -10
- package/lib/imap-proxy-auth.js +13 -29
- package/lib/imapproxy/imap-core/README.md +1 -0
- package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
- package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
- package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
- package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
- package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
- package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
- package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
- package/lib/imapproxy/imap-server.js +17 -177
- package/lib/imapproxy/proxy-handoff.js +235 -0
- package/lib/imapproxy/response-error.js +33 -0
- package/lib/imapproxy/upstream-client.js +2 -2
- package/lib/license-beacon.js +3 -9
- package/lib/llm-pre-process.js +182 -43
- package/lib/logger.js +1 -1
- package/lib/lua/ee-export-queue-add.lua +39 -0
- package/lib/lua/ee-get-idempotency.lua +15 -3
- package/lib/lua/ee-release-attempts.lua +23 -0
- package/lib/lua/ee-reserve-attempts.lua +42 -0
- package/lib/lua/h-set-bigger.lua +12 -2
- package/lib/lua/s-list-accounts.lua +6 -3
- package/lib/mcp/index.js +1 -2
- package/lib/mcp/listen.js +221 -18
- package/lib/mcp/oauth.js +44 -5
- package/lib/mcp/resources.js +8 -2
- package/lib/mcp/tools.js +13 -0
- package/lib/message-port-stream.js +64 -6
- package/lib/msgpack.js +1 -6
- package/lib/oauth/external-account-signer.js +16 -13
- package/lib/oauth/gmail.js +22 -20
- package/lib/oauth/outlook.js +19 -16
- package/lib/oauth/pubsub/google.js +38 -2
- package/lib/oauth/scope-checker.js +4 -7
- package/lib/oauth/verify-app.js +2 -2
- package/lib/oauth2-apps.js +139 -44
- package/lib/openapi/build-document.js +1 -1
- package/lib/openapi/joi-schema.js +78 -9
- package/lib/parse-message.js +21 -0
- package/lib/payload-examples-webhooks.json +4 -7
- package/lib/pbkdf2-phc.js +101 -0
- package/lib/privileged-settings.js +0 -14
- package/lib/rate-limit.js +54 -15
- package/lib/redis-scan-delete.js +56 -29
- package/lib/redis-url.js +3 -1
- package/lib/respawn-backoff.js +5 -4
- package/lib/response-stream.js +25 -4
- package/lib/rewrite-text-nodes.js +27 -40
- package/lib/routes-ui.js +0 -5
- package/lib/schemas.js +129 -262
- package/lib/sentry.js +21 -5
- package/lib/settings.js +58 -59
- package/lib/smtp-auth.js +6 -2
- package/lib/smtp-message-processor.js +28 -7
- package/lib/sso.js +7 -3
- package/lib/stream-encrypt.js +14 -13
- package/lib/swagger-options.js +3 -1
- package/lib/tls/provision.js +69 -3
- package/lib/tls/store.js +14 -1
- package/lib/tools.js +113 -52
- package/lib/totp.js +16 -1
- package/lib/ui-routes/account-routes.js +27 -63
- package/lib/ui-routes/admin-config-routes.js +111 -134
- package/lib/ui-routes/admin-entities-routes.js +101 -191
- package/lib/ui-routes/ai-options.js +104 -0
- package/lib/ui-routes/auth-routes.js +98 -18
- package/lib/ui-routes/export-routes.js +3 -23
- package/lib/ui-routes/internals-routes.js +12 -9
- package/lib/ui-routes/network-config-routes.js +8 -18
- package/lib/ui-routes/oauth-config-routes.js +80 -214
- package/lib/ui-routes/route-helpers.js +40 -44
- package/lib/ui-routes/unsubscribe-routes.js +2 -2
- package/lib/utils/decode-headers.js +32 -5
- package/lib/utils/header-map.js +62 -1
- package/lib/utils/network.js +2 -0
- package/lib/web-safe-html.js +77 -4
- package/lib/webhook-request.js +9 -1
- package/lib/webhook-routing.js +27 -1
- package/lib/webhooks.js +120 -43
- package/lib/worker-rpc-error.js +43 -2
- package/list-generate.js +13 -2
- package/package.json +38 -46
- package/sbom.json +1 -1
- package/scripts/refresh-test-tokens.js +42 -14
- package/server.js +340 -336
- package/static/css/flyonui.css +1 -1
- package/static/css/src/app.tailwind.css +7 -8
- package/static/js/ee-client.js +145 -70
- package/static/js/ui.js +350 -154
- package/static/licenses.html +460 -1861
- package/translations/messages.pot +99 -99
- package/views/accounts/browse.hbs +10 -4
- package/views/config/ai.hbs +49 -41
- package/views/config/oauth/app.hbs +2 -1
- package/views/dashboard.hbs +18 -16
- package/views/layout/app.hbs +0 -22
- package/views/layout/login.hbs +2 -1
- package/views/partials/filter_editor_js.hbs +4 -3
- package/views/partials/side_menu.hbs +0 -4
- package/views/partials/ui/account-picker.hbs +6 -32
- package/views/partials/ui/model-picker.hbs +31 -0
- package/views/partials/ui/pagination.hbs +6 -1
- package/views/partials/ui/picker.hbs +47 -0
- package/views/unsubscribe.hbs +1 -1
- package/workers/api.js +33 -23
- package/workers/export.js +55 -60
- package/workers/imap.js +134 -47
- package/workers/submit.js +3 -1
- package/workers/webhooks.js +46 -27
- package/.githooks/pre-commit +0 -80
- package/.github/CODE_OF_CONDUCT.md +0 -76
- package/.github/contributing.md +0 -17
- package/.github/dependabot.yml +0 -22
- package/.github/docker-smoke-test.sh +0 -61
- package/.github/workflows/deploy.yml +0 -215
- package/.github/workflows/e2e.yml +0 -55
- package/.github/workflows/release.yaml +0 -217
- package/.github/workflows/test.yml +0 -307
- package/lib/api-routes/chat-routes.js +0 -535
- package/lib/append-list.js +0 -63
- package/lib/document-store.js +0 -75
- package/lib/es.js +0 -757
- package/lib/generate-text-preview.js +0 -61
- package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
- package/lib/lua/h-push.lua +0 -32
- package/lib/pre-process.js +0 -196
- package/lib/threads.js +0 -155
- package/lib/ui-routes/document-store-routes.js +0 -806
- package/playwright.config.js +0 -47
- package/views/config/document-store/chat.hbs +0 -286
- package/views/config/document-store/index.hbs +0 -146
- package/views/config/document-store/mappings/index.hbs +0 -108
- package/views/config/document-store/mappings/new.hbs +0 -68
- package/views/config/document-store/pre-processing/index.hbs +0 -103
- package/views/partials/document_store_header.hbs +0 -30
- package/workers/documents.js +0 -1128
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The IMAP proxy's LOGIN handler and the byte pipe it sets up once the upstream session is ready.
|
|
4
|
+
// Kept out of lib/imapproxy/imap-server.js, which needs a worker-thread parentPort at require time,
|
|
5
|
+
// so the handoff can be tested with stub dependencies.
|
|
6
|
+
|
|
7
|
+
const { PassThrough } = require('stream');
|
|
8
|
+
const { imapHandler } = require('./imap-core/index.js');
|
|
9
|
+
const { isImapResponseError, toImapResponseError } = require('./response-error');
|
|
10
|
+
|
|
11
|
+
class PassThroughLogger extends PassThrough {
|
|
12
|
+
constructor(opts = {}) {
|
|
13
|
+
super();
|
|
14
|
+
this.logger = opts.logger;
|
|
15
|
+
this.src = opts.src;
|
|
16
|
+
this.cid = opts.cid;
|
|
17
|
+
this.imapClient = opts.imapClient;
|
|
18
|
+
this.logRaw = !!opts.logRaw;
|
|
19
|
+
}
|
|
20
|
+
_transform(chunk, encoding, next) {
|
|
21
|
+
if (this.logRaw) {
|
|
22
|
+
this.logger.trace({
|
|
23
|
+
src: this.src,
|
|
24
|
+
msg: 'write to socket',
|
|
25
|
+
data: chunk.toString('base64'),
|
|
26
|
+
compress: !!this.imapClient._deflate,
|
|
27
|
+
secure: !!this.imapClient.secureConnection,
|
|
28
|
+
cid: this.cid
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
this.push(chunk);
|
|
33
|
+
next();
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_flush(next) {
|
|
37
|
+
next();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Builds the imap-core `onAuth` callback of the proxy.
|
|
43
|
+
*
|
|
44
|
+
* @param {Object} deps
|
|
45
|
+
* @param {Function} deps.onAuth Resolves with `{ accountData, imapConfig }` for a login
|
|
46
|
+
* @param {Function} deps.createProxy Opens the authenticated upstream session
|
|
47
|
+
* @param {Object} deps.logger Base logger (a child per proxied session is derived from it)
|
|
48
|
+
* @param {Object} deps.serverLogger Logger for authentication failures
|
|
49
|
+
* @param {Function} deps.metrics Metrics reporter
|
|
50
|
+
* @param {Boolean} [deps.logRaw] Log every proxied chunk
|
|
51
|
+
* @returns {Function} (login, session, callback) handler
|
|
52
|
+
*/
|
|
53
|
+
function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, metrics, logRaw }) {
|
|
54
|
+
// A refusal or a temporary failure the client is told to retry is a warning and reaches the
|
|
55
|
+
// client as the IMAP response it carries; anything else is a proxy fault
|
|
56
|
+
const loginFailure = (err, fields, messages) => {
|
|
57
|
+
if (isImapResponseError(err)) {
|
|
58
|
+
serverLogger.warn(Object.assign({ msg: messages.response }, fields, { err }));
|
|
59
|
+
return toImapResponseError(err);
|
|
60
|
+
}
|
|
61
|
+
serverLogger.error(Object.assign({ msg: messages.fault }, fields, { err }));
|
|
62
|
+
return err;
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// Wires the two legs together once imap-core hands over the client socket
|
|
66
|
+
const attachProxy = ({ session, account, downstream, upstream }) => {
|
|
67
|
+
metrics(logger, 'events', 'inc', {
|
|
68
|
+
event: 'imapProxyConnected'
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
const proxyLogger = logger.child({ property: 'proxy', account, cid: session.id });
|
|
72
|
+
|
|
73
|
+
let upstreamLogger = new PassThroughLogger({
|
|
74
|
+
src: 's',
|
|
75
|
+
cid: session.id,
|
|
76
|
+
imapClient: downstream.imapClient,
|
|
77
|
+
logger: proxyLogger.child({ src: 'S' }),
|
|
78
|
+
logRaw
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
let downstreamLogger = new PassThroughLogger({
|
|
82
|
+
src: 'c',
|
|
83
|
+
cid: session.id,
|
|
84
|
+
imapClient: downstream.imapClient,
|
|
85
|
+
logger: proxyLogger.child({ src: 'C' }),
|
|
86
|
+
logRaw
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// Idempotent teardown for both legs of the proxy. ImapFlow.close() is safe after
|
|
90
|
+
// unbind(): it sends no LOGOUT, clears timers (including autoidle), removes the
|
|
91
|
+
// deflate/writeSocket error forwarders and destroys the upstream socket. Without it the
|
|
92
|
+
// upstream connection and its idle timer would leak (most visibly with COMPRESS enabled).
|
|
93
|
+
let proxyClosed = false;
|
|
94
|
+
const closeProxy = () => {
|
|
95
|
+
if (proxyClosed) {
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
proxyClosed = true;
|
|
99
|
+
|
|
100
|
+
try {
|
|
101
|
+
downstream.imapClient.close();
|
|
102
|
+
} catch (err) {
|
|
103
|
+
proxyLogger.warn({ msg: 'Failed to close upstream connection', err });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
try {
|
|
107
|
+
if (upstream.socket && !upstream.socket.destroyed) {
|
|
108
|
+
upstream.socket.end();
|
|
109
|
+
}
|
|
110
|
+
} catch (err) {
|
|
111
|
+
// ignore
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// Every terminal event from either leg funnels into the idempotent closeProxy(). The
|
|
116
|
+
// helper keeps that wiring declarative; pass a message to log (level defaults to 'warn',
|
|
117
|
+
// use 'info' for graceful closes).
|
|
118
|
+
const teardownOn = (emitter, event, msg, level = 'warn') => {
|
|
119
|
+
emitter.on(event, err => {
|
|
120
|
+
if (msg) {
|
|
121
|
+
let entry = { msg };
|
|
122
|
+
if (err) {
|
|
123
|
+
entry.err = err;
|
|
124
|
+
}
|
|
125
|
+
proxyLogger[level](entry);
|
|
126
|
+
}
|
|
127
|
+
closeProxy();
|
|
128
|
+
});
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
if (upstream.closed || upstream.socket.destroyed) {
|
|
132
|
+
// The client disconnected while LOGIN was waiting for the upstream connection.
|
|
133
|
+
// Nothing would ever close the upstream side, since the client socket's terminal
|
|
134
|
+
// events have already fired.
|
|
135
|
+
upstream.socket.on('error', () => false);
|
|
136
|
+
proxyLogger.info({ msg: 'Client disconnected during login, closing upstream connection' });
|
|
137
|
+
closeProxy();
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
downstream.readSocket.pipe(upstreamLogger).pipe(upstream.socket);
|
|
142
|
+
|
|
143
|
+
if (upstream.head && upstream.head.length) {
|
|
144
|
+
// Commands the client pipelined after LOGIN, read off the socket before the handoff.
|
|
145
|
+
// Written ahead of the pipe so order is kept.
|
|
146
|
+
downstreamLogger.write(upstream.head);
|
|
147
|
+
}
|
|
148
|
+
upstream.socket.pipe(downstreamLogger).pipe(downstream.writeSocket);
|
|
149
|
+
|
|
150
|
+
teardownOn(upstreamLogger, 'error', 'Proxy stream error (to client)');
|
|
151
|
+
teardownOn(downstreamLogger, 'error', 'Proxy stream error (to upstream)');
|
|
152
|
+
teardownOn(upstream.socket, 'error', 'Client socket error');
|
|
153
|
+
teardownOn(upstream.socket, 'end', 'Client connection closed', 'info');
|
|
154
|
+
teardownOn(upstream.socket, 'close');
|
|
155
|
+
teardownOn(downstream.readSocket, 'end', 'Upstream connection closed', 'info');
|
|
156
|
+
|
|
157
|
+
downstream.readSocket.on('error', err => {
|
|
158
|
+
proxyLogger.warn({ msg: 'Upstream read error', err });
|
|
159
|
+
try {
|
|
160
|
+
// best-effort notice to the client before tearing down
|
|
161
|
+
upstream.socket.write('* BYE Upstream connection error\r\n');
|
|
162
|
+
} catch (e) {
|
|
163
|
+
// ignore
|
|
164
|
+
}
|
|
165
|
+
closeProxy();
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// With COMPRESS enabled, readSocket/writeSocket are the inflate/deflate streams, not the
|
|
169
|
+
// raw upstream socket, and unbind() removed ImapFlow's own listeners from that socket. An
|
|
170
|
+
// upstream reset would then emit an 'error' with no listener and crash the worker - guard
|
|
171
|
+
// it explicitly.
|
|
172
|
+
if (downstream.imapClient.socket && downstream.imapClient.socket !== downstream.readSocket) {
|
|
173
|
+
teardownOn(downstream.imapClient.socket, 'error', 'Upstream socket error');
|
|
174
|
+
teardownOn(downstream.imapClient.socket, 'close');
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
proxyLogger.info({ msg: 'Proxy mode enabled' });
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const handleLogin = async (login, session) => {
|
|
181
|
+
let accountData;
|
|
182
|
+
let imapConfig;
|
|
183
|
+
try {
|
|
184
|
+
({ accountData, imapConfig } = await onAuth(login, session));
|
|
185
|
+
if (!imapConfig) {
|
|
186
|
+
throw new Error('IMAP not enabled for account');
|
|
187
|
+
}
|
|
188
|
+
} catch (err) {
|
|
189
|
+
throw loginFailure(
|
|
190
|
+
err,
|
|
191
|
+
{ username: login.username, cid: session.id, remoteAddress: session.remoteAddress },
|
|
192
|
+
{ response: 'Authentication check failed', fault: 'Authentication check failed' }
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// onAuth() resolves with { accountData, imapConfig }; the account id is read off the
|
|
197
|
+
// stored account data (the login name is the same id, kept as a fallback).
|
|
198
|
+
const account = (accountData && accountData.account) || login.username;
|
|
199
|
+
|
|
200
|
+
try {
|
|
201
|
+
const downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
|
|
202
|
+
|
|
203
|
+
session.onProxy = upstream => attachProxy({ session, account, downstream, upstream });
|
|
204
|
+
|
|
205
|
+
if (downstream.imapClient.rawCapabilities) {
|
|
206
|
+
login.connection.send(
|
|
207
|
+
imapHandler.compiler({
|
|
208
|
+
tag: '*',
|
|
209
|
+
command: 'CAPABILITY',
|
|
210
|
+
attributes: downstream.imapClient.rawCapabilities
|
|
211
|
+
})
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
} catch (err) {
|
|
215
|
+
throw loginFailure(err, { account, cid: session.id }, { response: 'Upstream authentication failed', fault: 'Failed to create proxy' });
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
return {
|
|
219
|
+
user: {
|
|
220
|
+
id: 'id.' + login.username,
|
|
221
|
+
username: login.username
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
return function (login, session, callback) {
|
|
227
|
+
// imap-core ignores what the handler returns, so every outcome has to end in the callback
|
|
228
|
+
handleLogin(login, session).then(
|
|
229
|
+
response => callback(null, response),
|
|
230
|
+
err => callback(err)
|
|
231
|
+
);
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
module.exports = { createProxyAuthHandler, PassThroughLogger };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// How the IMAP proxy tells a failure it may answer the client with from an internal fault.
|
|
4
|
+
// Dependency-free on purpose: lib/imapproxy/proxy-handoff.js needs these, and lib/imap-proxy-auth.js,
|
|
5
|
+
// which used to define them, opens the Redis connection at require time. That module re-exports
|
|
6
|
+
// them for the callers that always took them from there.
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Whether an error already names the IMAP response to answer the client with, as opposed to being
|
|
10
|
+
* an internal proxy fault. Both a refusal and a temporary failure carry one.
|
|
11
|
+
*
|
|
12
|
+
* @param {Error} err - The error to check
|
|
13
|
+
* @returns {boolean} True when the error carries an IMAP response
|
|
14
|
+
*/
|
|
15
|
+
function isImapResponseError(err) {
|
|
16
|
+
return !!err && (!!err.authenticationFailed || err.serverResponseCode === 'AUTHENTICATIONFAILED' || err.serverResponseCode === 'UNAVAILABLE');
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Renders a tagged failure as the error the IMAP server answers the client with. imap-core reads
|
|
21
|
+
* the status off `response`, and an error that carries none is answered BAD, which counts against
|
|
22
|
+
* the connection's bad-command budget instead of telling the client what happened.
|
|
23
|
+
*
|
|
24
|
+
* @param {Error} err - The tagged failure
|
|
25
|
+
* @returns {Error} A new error carrying the response line to send
|
|
26
|
+
*/
|
|
27
|
+
function toImapResponseError(err) {
|
|
28
|
+
let error = new Error(`${err.serverResponseCode ? `[${err.serverResponseCode}] ` : ''}${err.responseText || err.message || 'Authentication failed'}`);
|
|
29
|
+
error.response = err.responseStatus || 'NO';
|
|
30
|
+
return error;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
module.exports = { isImapResponseError, toImapResponseError };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
const {
|
|
3
|
+
const { createImapClient } = require('../create-imap-client');
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Creates the upstream ImapFlow client of a proxied session with a permanent 'error' sink.
|
|
@@ -24,7 +24,7 @@ const { ImapFlow } = require('imapflow');
|
|
|
24
24
|
* @returns {ImapFlow} Client with an error sink attached
|
|
25
25
|
*/
|
|
26
26
|
function createUpstreamClient(imapConfig) {
|
|
27
|
-
let imapClient =
|
|
27
|
+
let imapClient = createImapClient(imapConfig);
|
|
28
28
|
|
|
29
29
|
// reads the id off the client so the sink does not keep the config (credentials
|
|
30
30
|
// included) alive through the closure for as long as the connection lives
|
package/lib/license-beacon.js
CHANGED
|
@@ -23,7 +23,6 @@ const { getCounterValues, hasEnvValue, readEnvValue, getBoolean } = require('./t
|
|
|
23
23
|
const { REDIS_PREFIX } = require('./consts');
|
|
24
24
|
const { oauth2Apps } = require('./oauth2-apps');
|
|
25
25
|
const passkeys = require('./passkeys');
|
|
26
|
-
const { documentStoreFeatureEnabled } = require('./document-store');
|
|
27
26
|
|
|
28
27
|
// Beacon schema version. Bump when the meaning of codes changes so the license server can adapt.
|
|
29
28
|
const SCHEMA_VERSION = 1;
|
|
@@ -150,7 +149,6 @@ async function collectBeacon({ redis, logger }) {
|
|
|
150
149
|
'webhooksEnabled',
|
|
151
150
|
'openAiAPIKey',
|
|
152
151
|
'generateEmailSummary',
|
|
153
|
-
'openAiGenerateEmbeddings',
|
|
154
152
|
'openAiAPIUrl',
|
|
155
153
|
'openAiPreProcessingFn',
|
|
156
154
|
'proxyEnabled',
|
|
@@ -161,8 +159,6 @@ async function collectBeacon({ redis, logger }) {
|
|
|
161
159
|
'imapIndexer',
|
|
162
160
|
'totpEnabled',
|
|
163
161
|
'documentStoreEnabled',
|
|
164
|
-
'documentStoreGenerateEmbeddings',
|
|
165
|
-
'documentStorePreProcessingEnabled',
|
|
166
162
|
'gmailEnabled',
|
|
167
163
|
'outlookEnabled',
|
|
168
164
|
'mailRuEnabled',
|
|
@@ -182,7 +178,6 @@ async function collectBeacon({ redis, logger }) {
|
|
|
182
178
|
if (on('webhooksEnabled')) feat.push('webhooks');
|
|
183
179
|
if (nonEmpty(s.openAiAPIKey)) feat.push('ai');
|
|
184
180
|
if (on('generateEmailSummary')) feat.push('ai_sum');
|
|
185
|
-
if (on('openAiGenerateEmbeddings')) feat.push('ai_embed');
|
|
186
181
|
if (nonEmpty(s.openAiAPIUrl)) feat.push('ai_url');
|
|
187
182
|
if (nonEmpty(s.openAiPreProcessingFn)) feat.push('ai_prefn');
|
|
188
183
|
if (on('proxyEnabled')) feat.push('proxy');
|
|
@@ -263,12 +258,11 @@ async function collectBeacon({ redis, logger }) {
|
|
|
263
258
|
diag.use = use.sort();
|
|
264
259
|
});
|
|
265
260
|
|
|
266
|
-
// Deprecation watchlist (presence of legacy/candidate-for-removal features).
|
|
261
|
+
// Deprecation watchlist (presence of legacy/candidate-for-removal features). The Document
|
|
262
|
+
// Store itself is gone since 2.82.0; the setting is still reported so the removal warning
|
|
263
|
+
// an upgraded instance shows can be counted
|
|
267
264
|
const dep = [];
|
|
268
265
|
if (on('documentStoreEnabled')) dep.push('documentStore');
|
|
269
|
-
if (documentStoreFeatureEnabled) dep.push('documentStoreGate');
|
|
270
|
-
if (on('documentStoreGenerateEmbeddings')) dep.push('ds_embed');
|
|
271
|
-
if (on('documentStorePreProcessingEnabled')) dep.push('ds_preproc');
|
|
272
266
|
if (on('trackSentMessages')) dep.push('trackSent');
|
|
273
267
|
await safe(async () => {
|
|
274
268
|
const ids = await redis.smembers(`${REDIS_PREFIX}wh:i`);
|
package/lib/llm-pre-process.js
CHANGED
|
@@ -3,10 +3,107 @@
|
|
|
3
3
|
const { redis } = require('./db');
|
|
4
4
|
const msgpack = require('./msgpack');
|
|
5
5
|
const logger = require('./logger');
|
|
6
|
-
const { REDIS_PREFIX } = require('./consts');
|
|
6
|
+
const { REDIS_PREFIX, AI_REQUEST_TIMEOUT } = require('./consts');
|
|
7
|
+
const { ALLOWED_HEADERS } = require('@postalsys/email-ai-tools');
|
|
7
8
|
const settings = require('./settings');
|
|
8
9
|
const { SubScript } = require('./sub-script');
|
|
9
10
|
|
|
11
|
+
// The last OpenAI failure, shown on the AI configuration page until a summary succeeds again
|
|
12
|
+
const OPENAI_ERROR_KEY = `${REDIS_PREFIX}:openai:error`;
|
|
13
|
+
|
|
14
|
+
// Headers the summary reads: the library's own whitelist, so what is fetched is what the model
|
|
15
|
+
// gets. Both sync paths fetch them for every new message while summaries are on, whatever the
|
|
16
|
+
// notifyHeaders setting asks for, and narrow them back out before the message is published. They
|
|
17
|
+
// are what the risk assessment is about: who the message claims to come from, whether the
|
|
18
|
+
// receiving server could verify that, and what conversation it belongs to
|
|
19
|
+
const SUMMARY_HEADERS = ALLOWED_HEADERS;
|
|
20
|
+
|
|
21
|
+
// What the sync paths fetch for the summary: the headers the model reads, and for a Microsoft
|
|
22
|
+
// mailbox the Received lines, which say whether Microsoft's unnamed authentication header is
|
|
23
|
+
// Microsoft's. Those never reach the model, the library keeps to its whitelist
|
|
24
|
+
const SUMMARY_FETCH_HEADERS = SUMMARY_HEADERS.concat(['received']);
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The headers to fetch for a mailbox while summaries are on
|
|
28
|
+
*
|
|
29
|
+
* @param {string|null} provider - As summaryProvider() names it
|
|
30
|
+
* @returns {string[]}
|
|
31
|
+
*/
|
|
32
|
+
function summaryFetchHeaders(provider) {
|
|
33
|
+
return provider === 'outlook' ? SUMMARY_FETCH_HEADERS : SUMMARY_HEADERS;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Which provider's servers received the mail, as far as the authentication trust rule cares:
|
|
38
|
+
* Google and Microsoft sign their Authentication-Results header in a known way. Told from what
|
|
39
|
+
* the client learned at connect time (the Gmail capability, the host), never from the message
|
|
40
|
+
*
|
|
41
|
+
* @param {Object} client
|
|
42
|
+
* @param {boolean} [client.isGmail] - The IMAP client's Gmail detection, or the API client's type
|
|
43
|
+
* @param {boolean} [client.isOutlook]
|
|
44
|
+
* @param {string} [client.host] - The IMAP host
|
|
45
|
+
* @returns {string|null} 'gmail', 'outlook' or null
|
|
46
|
+
*/
|
|
47
|
+
function summaryProvider({ isGmail, isOutlook, host }) {
|
|
48
|
+
host = (host || '').toLowerCase();
|
|
49
|
+
if (isGmail || /(^|\.)(gmail|googlemail)\.com$/.test(host)) {
|
|
50
|
+
return 'gmail';
|
|
51
|
+
}
|
|
52
|
+
if (isOutlook || /\b(office365|outlook|hotmail)\.(com|us)$/.test(host)) {
|
|
53
|
+
return 'outlook';
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Which Authentication-Results header the summary may trust for a mailbox: the one written by
|
|
60
|
+
* the server that received the message. Google signs its header with its own name and removes
|
|
61
|
+
* any that arrives claiming it. Microsoft writes one without a name, which counts only when the
|
|
62
|
+
* topmost Received line, the one Microsoft itself wrote, names a Microsoft host. No other server
|
|
63
|
+
* is trusted: nothing about a message tells whether its topmost header is the server's or the
|
|
64
|
+
* sender's, and a name a sender can guess (the mailbox's domain, its MX) would let a forged pass
|
|
65
|
+
* through, so the model treats the result as unknown there
|
|
66
|
+
*
|
|
67
|
+
* @param {string|null} provider - As summaryProvider() names it
|
|
68
|
+
* @param {Object} [headers] - The fetched headers, for the Received lines
|
|
69
|
+
* @returns {{trustedAuthservIds: string[], acceptUnnamedAuthentication?: boolean}}
|
|
70
|
+
*/
|
|
71
|
+
function authenticationTrust(provider, headers) {
|
|
72
|
+
if (provider === 'gmail') {
|
|
73
|
+
return { trustedAuthservIds: ['mx.google.com'] };
|
|
74
|
+
}
|
|
75
|
+
if (provider === 'outlook') {
|
|
76
|
+
const topmostReceived = [].concat((headers && headers.received) || [])[0] || '';
|
|
77
|
+
return {
|
|
78
|
+
trustedAuthservIds: ['protection.outlook.com', 'outlook.com'],
|
|
79
|
+
acceptUnnamedAuthentication: /\b[a-z0-9.-]+\.(?:outlook|office365)\.(?:com|us)\b/i.test(topmostReceived)
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
return { trustedAuthservIds: [] };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* The message as the summary library takes it: the decoded subject, sender and date EmailEngine
|
|
87
|
+
* already parsed, every header the sync path fetched (the library keeps the ones it wants), the
|
|
88
|
+
* attachment list without content, and the text parts. One shape for the sync path and for the
|
|
89
|
+
* configuration page's test, so what the page shows is what a webhook gets
|
|
90
|
+
*
|
|
91
|
+
* @param {Object} messageData - Formatted message with its text parts
|
|
92
|
+
* @returns {Object} Input for generateSummary()
|
|
93
|
+
*/
|
|
94
|
+
function buildSummaryInput(messageData) {
|
|
95
|
+
const headers = messageData.headers || {};
|
|
96
|
+
return {
|
|
97
|
+
subject: messageData.subject,
|
|
98
|
+
from: messageData.from,
|
|
99
|
+
date: messageData.date,
|
|
100
|
+
headers: Object.keys(headers).map(key => ({ key, value: [].concat(headers[key] || []) })),
|
|
101
|
+
attachments: [].concat(messageData.attachments || []).map(attachment => ({ filename: attachment.filename, contentType: attachment.contentType })),
|
|
102
|
+
text: messageData.text?.plain,
|
|
103
|
+
html: messageData.text?.html
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
10
107
|
class LLMPreProcessHandler {
|
|
11
108
|
constructor(options) {
|
|
12
109
|
this.options = options || {};
|
|
@@ -21,45 +118,44 @@ class LLMPreProcessHandler {
|
|
|
21
118
|
}
|
|
22
119
|
|
|
23
120
|
async getHandler() {
|
|
24
|
-
|
|
25
|
-
generateEmailSummary
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
};
|
|
121
|
+
const { generateEmailSummary, openAiAPIKey, openAiPreProcessingFn } = await settings.getMulti(
|
|
122
|
+
'generateEmailSummary',
|
|
123
|
+
'openAiAPIKey',
|
|
124
|
+
'openAiPreProcessingFn'
|
|
125
|
+
);
|
|
30
126
|
|
|
31
|
-
if (
|
|
127
|
+
if (!generateEmailSummary || !openAiAPIKey) {
|
|
32
128
|
return null;
|
|
33
129
|
}
|
|
34
130
|
|
|
131
|
+
// No filter script means every message goes. A script that does not compile means the
|
|
132
|
+
// operator's intent is unknown, so nothing goes until it is fixed
|
|
133
|
+
const script = (openAiPreProcessingFn || '').toString().trim();
|
|
134
|
+
if (!script) {
|
|
135
|
+
return { filterFn: null };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
let compiledFn;
|
|
35
139
|
try {
|
|
36
|
-
|
|
37
|
-
preProcessData.compiledFn = SubScript.create(`llm-pre-process:filter`, preProcessData.contentFn);
|
|
38
|
-
} else {
|
|
39
|
-
preProcessData.compiledFn = false;
|
|
40
|
-
}
|
|
140
|
+
compiledFn = SubScript.create(`llm-pre-process:filter`, script);
|
|
41
141
|
} catch (err) {
|
|
42
142
|
await this.storeLog('filter', null, err.stack);
|
|
43
143
|
|
|
44
144
|
logger.error({ msg: 'Failed to compile LLM pre-processing script', component: 'llm-pre-process', type: 'filter', err });
|
|
45
|
-
preProcessData.compiledFn = null;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
if (!preProcessData.compiledFn) {
|
|
49
145
|
return null;
|
|
50
146
|
}
|
|
51
147
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
148
|
+
return {
|
|
149
|
+
filterFn: async payload => {
|
|
150
|
+
try {
|
|
151
|
+
return await compiledFn.exec(payload);
|
|
152
|
+
} catch (err) {
|
|
153
|
+
await this.storeLog('filter', payload, err.stack);
|
|
154
|
+
logger.error({ msg: 'Failed to execute LLM pre-processing script', component: 'llm-pre-process', type: 'filter', err });
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
59
157
|
}
|
|
60
158
|
};
|
|
61
|
-
|
|
62
|
-
return preProcessData;
|
|
63
159
|
}
|
|
64
160
|
|
|
65
161
|
async getPreProcessHandler() {
|
|
@@ -112,33 +208,76 @@ class LLMPreProcessHandler {
|
|
|
112
208
|
return logEntries;
|
|
113
209
|
}
|
|
114
210
|
|
|
115
|
-
|
|
211
|
+
/**
|
|
212
|
+
* Decides whether a message goes to the LLM: summaries have to be on, a key has to be set and
|
|
213
|
+
* the operator's filter script, if there is one, has to accept the message. The script sees a
|
|
214
|
+
* copy, so it cannot change what is announced
|
|
215
|
+
* @param {Object} messageData - The message as the webhook would carry it
|
|
216
|
+
* @returns {Promise<boolean>} True when the message should be summarized
|
|
217
|
+
*/
|
|
218
|
+
async run(messageData) {
|
|
116
219
|
let preProcessHandler = await this.getPreProcessHandler();
|
|
117
|
-
|
|
118
|
-
if (!preProcessHandler || !preProcessHandler.filterFn) {
|
|
220
|
+
if (!preProcessHandler) {
|
|
119
221
|
return false;
|
|
120
222
|
}
|
|
121
223
|
|
|
122
|
-
|
|
123
|
-
|
|
224
|
+
// without a script there is nothing to show a copy to
|
|
225
|
+
if (!preProcessHandler.filterFn) {
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return !!(await preProcessHandler.filterFn(structuredClone(messageData)));
|
|
230
|
+
}
|
|
124
231
|
|
|
232
|
+
/**
|
|
233
|
+
* Asks the main thread for the AI summary of a message and attaches what the model returned
|
|
234
|
+
* to the message in place, as it came. The request usage goes to the log; the main thread
|
|
235
|
+
* counts it in the metrics. A failure is recorded for the AI configuration page and leaves
|
|
236
|
+
* the message unenriched
|
|
237
|
+
* @param {Object} messageData - Formatted message with its text parts, updated in place
|
|
238
|
+
* @param {Object} env - Where the message lives
|
|
239
|
+
* @param {Function} env.call - RPC to the main thread
|
|
240
|
+
* @param {Object} env.redis - The connection's Redis client
|
|
241
|
+
* @param {string} env.account - Account ID
|
|
242
|
+
* @param {string|null} env.provider - As summaryProvider() names it, for the authentication trust rule
|
|
243
|
+
* @param {Object} env.logger - Account-scoped logger
|
|
244
|
+
*/
|
|
245
|
+
async summarize(messageData, { call, redis: client, account, provider, logger: log }) {
|
|
125
246
|
try {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
247
|
+
const { result, usage, signals } = await call({
|
|
248
|
+
cmd: 'generateSummary',
|
|
249
|
+
data: {
|
|
250
|
+
message: buildSummaryInput(messageData),
|
|
251
|
+
trust: authenticationTrust(provider, messageData.headers),
|
|
252
|
+
account
|
|
253
|
+
},
|
|
254
|
+
timeout: AI_REQUEST_TIMEOUT
|
|
255
|
+
});
|
|
129
256
|
|
|
130
|
-
|
|
131
|
-
}
|
|
257
|
+
messageData.summary = result;
|
|
132
258
|
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
generateEmailSummary: preProcessHandler.generateEmailSummary,
|
|
136
|
-
generateEmbeddings: preProcessHandler.generateEmbeddings
|
|
137
|
-
};
|
|
138
|
-
}
|
|
259
|
+
// usage is scalars only: the main thread strips the prompt text the verbose mode adds
|
|
260
|
+
log.info({ msg: 'Generated email summary', id: messageData.id, messageId: messageData.messageId, usage, signals });
|
|
139
261
|
|
|
140
|
-
|
|
262
|
+
await client.del(OPENAI_ERROR_KEY);
|
|
263
|
+
} catch (err) {
|
|
264
|
+
await client.set(
|
|
265
|
+
OPENAI_ERROR_KEY,
|
|
266
|
+
JSON.stringify({
|
|
267
|
+
message: err.message,
|
|
268
|
+
code: err.code,
|
|
269
|
+
statusCode: err.statusCode,
|
|
270
|
+
created: Date.now()
|
|
271
|
+
})
|
|
272
|
+
);
|
|
273
|
+
log.error({ msg: 'Failed to fetch summary from OpenAI', err });
|
|
274
|
+
}
|
|
141
275
|
}
|
|
142
276
|
}
|
|
143
277
|
|
|
144
278
|
module.exports.llmPreProcess = new LLMPreProcessHandler({ redis });
|
|
279
|
+
module.exports.buildSummaryInput = buildSummaryInput;
|
|
280
|
+
module.exports.SUMMARY_HEADERS = SUMMARY_HEADERS;
|
|
281
|
+
module.exports.summaryFetchHeaders = summaryFetchHeaders;
|
|
282
|
+
module.exports.summaryProvider = summaryProvider;
|
|
283
|
+
module.exports.authenticationTrust = authenticationTrust;
|
package/lib/logger.js
CHANGED
|
@@ -26,7 +26,7 @@ function isTransientFetchError(err) {
|
|
|
26
26
|
|
|
27
27
|
let logger = pino({
|
|
28
28
|
// Redaction belongs on the root logger, not on a single worker's child: the imap, smtp,
|
|
29
|
-
// imap-proxy, submit, webhooks
|
|
29
|
+
// imap-proxy, submit, webhooks and export workers all log through this instance,
|
|
30
30
|
// and several of them log joi errors carrying credentials.
|
|
31
31
|
redact: REDACTED_LOG_KEYS,
|
|
32
32
|
formatters: {
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
--[[
|
|
2
|
+
Script: ee-export-queue-add.lua
|
|
3
|
+
Purpose: Queues one message of an export in a single round trip
|
|
4
|
+
|
|
5
|
+
ZADD into the pending set, count the message on the export record only when it was new, and keep
|
|
6
|
+
the set alive as long as the record. A retried folder queues the messages its failed attempt
|
|
7
|
+
already queued: ZADD leaves an existing member alone, and only a new one may count, or
|
|
8
|
+
messagesQueued ends up above exported + skipped and the progress never reaches it. Nothing is
|
|
9
|
+
counted on a record that no longer exists (a deleted export), which HINCRBY would otherwise
|
|
10
|
+
recreate as a hash holding nothing but the counter.
|
|
11
|
+
|
|
12
|
+
KEYS:
|
|
13
|
+
[1] exportKey - The export record hash
|
|
14
|
+
[2] queueKey - The pending-message sorted set
|
|
15
|
+
|
|
16
|
+
ARGV:
|
|
17
|
+
[1] score
|
|
18
|
+
[2] member
|
|
19
|
+
[3] counterField - The record field counting queued messages
|
|
20
|
+
|
|
21
|
+
Returns:
|
|
22
|
+
1 when the member was new, 0 when it was already queued
|
|
23
|
+
--]]
|
|
24
|
+
|
|
25
|
+
local exportKey = KEYS[1]
|
|
26
|
+
local queueKey = KEYS[2]
|
|
27
|
+
|
|
28
|
+
local added = redis.call("ZADD", queueKey, ARGV[1], ARGV[2])
|
|
29
|
+
|
|
30
|
+
local ttl = redis.call("PTTL", exportKey)
|
|
31
|
+
if ttl > 0 then
|
|
32
|
+
redis.call("PEXPIRE", queueKey, ttl)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
if added == 1 and ttl ~= -2 then
|
|
36
|
+
redis.call("HINCRBY", exportKey, ARGV[3], 1)
|
|
37
|
+
end
|
|
38
|
+
|
|
39
|
+
return added
|