emailengine-app 2.79.0 → 2.79.1
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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +39 -0
- package/lib/account.js +43 -2
- package/lib/api-routes/permission-map.js +4 -0
- package/lib/api-routes/route-helpers.js +71 -0
- package/lib/api-routes/settings-routes.js +37 -14
- package/lib/api-routes/token-routes.js +290 -122
- package/lib/arf-detect.js +17 -4
- package/lib/bounce-detect.js +28 -17
- package/lib/consts.js +6 -0
- package/lib/db.js +6 -0
- package/lib/email-client/gmail-client.js +4 -7
- package/lib/email-client/imap/mailbox.js +35 -35
- package/lib/email-client/imap-client.js +49 -2
- package/lib/email-client/outlook-client.js +3 -10
- package/lib/lua/h-set-new-mark.lua +36 -0
- package/lib/message-port-stream.js +84 -1
- package/lib/oauth2-apps.js +84 -15
- package/lib/openapi/build-document.js +5 -1
- package/lib/schemas.js +2 -2
- package/lib/settings.js +23 -9
- package/lib/token-audit-log.js +32 -9
- package/lib/tokens.js +163 -66
- package/lib/ui-routes/account-routes.js +13 -6
- package/lib/ui-routes/admin-entities-routes.js +52 -17
- package/lib/ui-routes/oauth-config-routes.js +7 -7
- package/lib/ui-routes/route-helpers.js +28 -1
- package/lib/ui-routes/suppression-list-routes.js +14 -9
- package/lib/utils/decode-headers.js +42 -0
- package/lib/utils/header-map.js +48 -0
- package/lib/utils/unsafe-key.js +59 -0
- package/lib/webhook-routing.js +6 -2
- package/lib/webhooks.js +28 -0
- package/package.json +1 -1
- package/server.js +39 -17
- package/views/accounts/account.hbs +8 -8
- package/views/accounts/browse.hbs +1 -1
- package/views/accounts/edit.hbs +2 -2
- package/views/gateways/edit.hbs +1 -1
- package/views/gateways/gateway.hbs +2 -2
- package/views/gateways/index.hbs +7 -7
- package/views/partials/accounts_table.hbs +7 -7
- package/views/suppression-lists/list.hbs +1 -1
- package/views/templates/index.hbs +2 -2
- package/views/templates/template.hbs +1 -1
- package/views/tokens/index.hbs +22 -2
- package/views/tokens/new.hbs +10 -3
- package/workers/api.js +41 -47
- package/workers/imap.js +65 -72
- package/workers/webhooks.js +21 -1
package/lib/consts.js
CHANGED
|
@@ -207,6 +207,12 @@ module.exports = {
|
|
|
207
207
|
|
|
208
208
|
NONCE_BYTES: 16,
|
|
209
209
|
|
|
210
|
+
// Longest account id EmailEngine accepts. Defined here rather than only on `accountIdSchema`
|
|
211
|
+
// because the token audit log truncates to it while writing, before route validation has had a
|
|
212
|
+
// chance to reject a longer one, and the two have to agree: a log that trimmed at a different
|
|
213
|
+
// length would store a string that names no account while claiming to name one.
|
|
214
|
+
MAX_ACCOUNT_ID_LENGTH: 256,
|
|
215
|
+
|
|
210
216
|
// Class names on the collapse marker web-safe HTML wraps quoted thread history in. Part of the
|
|
211
217
|
// output contract - consumers select on them to style or hide the block - so they are defined
|
|
212
218
|
// once here and referenced by both the generator (lib/web-safe-html.js) and the API docs.
|
package/lib/db.js
CHANGED
|
@@ -133,6 +133,7 @@ const hSetBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-bigg
|
|
|
133
133
|
const hUpdateBiggerScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-update-bigger.lua'), 'utf-8');
|
|
134
134
|
const hSetExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-exists.lua'), 'utf-8');
|
|
135
135
|
const hSetNewScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new.lua'), 'utf-8');
|
|
136
|
+
const hSetNewMarkScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-set-new-mark.lua'), 'utf-8');
|
|
136
137
|
const hIncrbyExistsScript = fs.readFileSync(pathlib.join(__dirname, 'lua/h-incrby-exists.lua'), 'utf-8');
|
|
137
138
|
const eeListAddScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-add.lua'), 'utf-8');
|
|
138
139
|
const eeListRemoveScript = fs.readFileSync(pathlib.join(__dirname, 'lua/ee-list-remove.lua'), 'utf-8');
|
|
@@ -198,6 +199,11 @@ redis.defineCommand('hSetNew', {
|
|
|
198
199
|
lua: hSetNewScript
|
|
199
200
|
});
|
|
200
201
|
|
|
202
|
+
redis.defineCommand('hSetNewMark', {
|
|
203
|
+
numberOfKeys: 1,
|
|
204
|
+
lua: hSetNewMarkScript
|
|
205
|
+
});
|
|
206
|
+
|
|
201
207
|
redis.defineCommand('hIncrbyExists', {
|
|
202
208
|
numberOfKeys: 1,
|
|
203
209
|
lua: hIncrbyExistsScript
|
|
@@ -28,6 +28,7 @@ const settings = require('../settings');
|
|
|
28
28
|
|
|
29
29
|
const { GMAIL_API_BASE, LIST_BATCH_SIZE, request: gmailApiRequest, executeBatchRequests } = require('./gmail/gmail-api');
|
|
30
30
|
const { buildSendRequest, buildDraftSendRequest } = require('./gmail/send-request');
|
|
31
|
+
const { pushHeaderValue } = require('../utils/header-map');
|
|
31
32
|
|
|
32
33
|
const MAX_GMAIL_BATCH_SIZE = 50;
|
|
33
34
|
|
|
@@ -2529,15 +2530,11 @@ class GmailClient extends BaseClient {
|
|
|
2529
2530
|
|
|
2530
2531
|
let envelope = this.getEnvelope(messageData);
|
|
2531
2532
|
|
|
2532
|
-
// Extract all headers
|
|
2533
|
+
// Extract all headers. pushHeaderValue() guards against names that resolve to
|
|
2534
|
+
// Object.prototype members, which would otherwise throw for every fetch of that message
|
|
2533
2535
|
let headers = {};
|
|
2534
2536
|
for (let header of messageData.payload.headers) {
|
|
2535
|
-
|
|
2536
|
-
if (!headers[key]) {
|
|
2537
|
-
headers[key] = [header.value];
|
|
2538
|
-
} else {
|
|
2539
|
-
headers[key].push(header.value);
|
|
2540
|
-
}
|
|
2537
|
+
pushHeaderValue(headers, header.name.toLowerCase(), header.value);
|
|
2541
2538
|
}
|
|
2542
2539
|
|
|
2543
2540
|
const { attachments, textId, encodedTextSize, textContents } = this.getAttachmentList(messageData, { textType });
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { finished } = require('stream');
|
|
3
4
|
const {
|
|
4
5
|
serialize,
|
|
5
6
|
unserialize,
|
|
@@ -16,6 +17,8 @@ const he = require('he');
|
|
|
16
17
|
const libmime = require('libmime');
|
|
17
18
|
const settings = require('../../settings');
|
|
18
19
|
const { bounceDetect, applyDeliveryReport } = require('../../bounce-detect');
|
|
20
|
+
const { decodeHeaders } = require('../../utils/decode-headers');
|
|
21
|
+
const { isUnsafeKey } = require('../../utils/unsafe-key');
|
|
19
22
|
const { arfDetect, camelCaseComplaint } = require('../../arf-detect');
|
|
20
23
|
const appendList = require('../../append-list');
|
|
21
24
|
const { messageWebSafeHtml } = require('../../web-safe-html');
|
|
@@ -758,17 +761,6 @@ class Mailbox {
|
|
|
758
761
|
return lock;
|
|
759
762
|
}
|
|
760
763
|
|
|
761
|
-
/**
|
|
762
|
-
* Marks task as completed and potentially starts idle timer
|
|
763
|
-
* @param {Object} connectionClient - IMAP client that completed the task
|
|
764
|
-
*/
|
|
765
|
-
onTaskCompleted(connectionClient) {
|
|
766
|
-
connectionClient = connectionClient || this.connection.imapClient;
|
|
767
|
-
if (connectionClient === this.connection.imapClient) {
|
|
768
|
-
this.connection.onTaskCompleted();
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
|
|
772
764
|
/**
|
|
773
765
|
* Helper to log IMAP events with proper formatting
|
|
774
766
|
* @param {String} msg - Log message
|
|
@@ -1792,7 +1784,7 @@ class Mailbox {
|
|
|
1792
1784
|
// Normally, these headers are not fetched from the server and only ENVELOPE is used
|
|
1793
1785
|
let parsedAddresses = {};
|
|
1794
1786
|
if (messageData.headers) {
|
|
1795
|
-
headers =
|
|
1787
|
+
headers = decodeHeaders(messageData.headers.toString().trim());
|
|
1796
1788
|
for (let key of ['from', 'to', 'cc', 'bcc']) {
|
|
1797
1789
|
if (headers[key]?.length) {
|
|
1798
1790
|
try {
|
|
@@ -2351,8 +2343,8 @@ class Mailbox {
|
|
|
2351
2343
|
}
|
|
2352
2344
|
|
|
2353
2345
|
// User methods
|
|
2354
|
-
//
|
|
2355
|
-
// Call this.onTaskCompleted() after selected mailbox is processed and lock is released
|
|
2346
|
+
// getMailboxLock() clears connection.completedTimer for the primary connection
|
|
2347
|
+
// Call this.connection.onTaskCompleted(connectionClient) after the selected mailbox is processed and the lock is released
|
|
2356
2348
|
|
|
2357
2349
|
/**
|
|
2358
2350
|
* Fetches text content for a message
|
|
@@ -2395,8 +2387,16 @@ class Mailbox {
|
|
|
2395
2387
|
let text = await download(content);
|
|
2396
2388
|
text = text.toString().replace(/\r?\n/g, '\n');
|
|
2397
2389
|
|
|
2398
|
-
// Group by content type (plain, html, etc)
|
|
2390
|
+
// Group by content type (plain, html, etc). The subtype comes from the message,
|
|
2391
|
+
// so a sender picks it: for "text/__proto__" the `!result[typeKey]` probe below
|
|
2392
|
+
// finds Object.prototype rather than an array, skips the initializer and then
|
|
2393
|
+
// throws on .reduce() - the same shape lib/utils/header-map.js exists to guard.
|
|
2394
|
+
// Neither name is a real MIME subtype, so the part is grouped as plain text
|
|
2395
|
+
// instead of being dropped.
|
|
2399
2396
|
let typeKey = (meta.contentType && meta.contentType.split('/')[1]) || 'plain';
|
|
2397
|
+
if (isUnsafeKey(typeKey)) {
|
|
2398
|
+
typeKey = 'plain';
|
|
2399
|
+
}
|
|
2400
2400
|
if (!result[typeKey]) {
|
|
2401
2401
|
result[typeKey] = [];
|
|
2402
2402
|
}
|
|
@@ -2414,8 +2414,11 @@ class Mailbox {
|
|
|
2414
2414
|
result[typeKey].push(text);
|
|
2415
2415
|
}
|
|
2416
2416
|
} finally {
|
|
2417
|
+
// Paired with the lock: a FETCH that throws still selected a mailbox on this
|
|
2418
|
+
// connection, so it still has to be sent back to the one it is watching.
|
|
2417
2419
|
if (lock) {
|
|
2418
2420
|
lock.release();
|
|
2421
|
+
this.connection.onTaskCompleted(connectionClient);
|
|
2419
2422
|
}
|
|
2420
2423
|
}
|
|
2421
2424
|
|
|
@@ -2426,10 +2429,6 @@ class Mailbox {
|
|
|
2426
2429
|
|
|
2427
2430
|
result.hasMore = hasMore;
|
|
2428
2431
|
|
|
2429
|
-
if (!options.skipLock) {
|
|
2430
|
-
this.onTaskCompleted(connectionClient);
|
|
2431
|
-
}
|
|
2432
|
-
|
|
2433
2432
|
return result;
|
|
2434
2433
|
}
|
|
2435
2434
|
|
|
@@ -2449,7 +2448,6 @@ class Mailbox {
|
|
|
2449
2448
|
let lock = await this.getMailboxLock(connectionClient, { description: `Get attachment: ${message.uid}/${part}` });
|
|
2450
2449
|
|
|
2451
2450
|
let streaming = false;
|
|
2452
|
-
let released = false;
|
|
2453
2451
|
try {
|
|
2454
2452
|
let { meta, content } = await connectionClient.download(message.uid, part, {
|
|
2455
2453
|
uid: true,
|
|
@@ -2457,7 +2455,9 @@ class Mailbox {
|
|
|
2457
2455
|
chunkSize: options.chunkSize
|
|
2458
2456
|
});
|
|
2459
2457
|
|
|
2460
|
-
|
|
2458
|
+
// Both halves are required: meta describes the part, content is what finished() is
|
|
2459
|
+
// handed below, and getText() already guards the same pair
|
|
2460
|
+
if (!meta || !content) {
|
|
2461
2461
|
return false;
|
|
2462
2462
|
}
|
|
2463
2463
|
|
|
@@ -2482,23 +2482,23 @@ class Mailbox {
|
|
|
2482
2482
|
content.contentType = meta.contentType;
|
|
2483
2483
|
content.filename = meta.filename;
|
|
2484
2484
|
content.disposition = meta.disposition;
|
|
2485
|
-
streaming = true;
|
|
2486
2485
|
|
|
2487
|
-
//
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2486
|
+
// The lock is held for the lifetime of the stream, so it can only be given back once the
|
|
2487
|
+
// stream is done - by any route. Enumerating those routes by hand is what let a consumer
|
|
2488
|
+
// that simply destroys the stream hold the lock forever: an abort emits neither 'end' nor
|
|
2489
|
+
// 'error', only 'close'. finished() covers end, error, destroy and premature close by
|
|
2490
|
+
// contract, and fires exactly once, so there is no set of terminal events left to get
|
|
2491
|
+
// wrong. Reporting the task either way is what every other method here does: however the
|
|
2492
|
+
// download ended, the connection has to go back to the mailbox it is watching.
|
|
2493
|
+
finished(content, () => {
|
|
2494
|
+
lock.release();
|
|
2495
|
+
this.connection.onTaskCompleted(connectionClient);
|
|
2493
2496
|
});
|
|
2494
2497
|
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
this.connection.onTaskCompleted(connectionClient);
|
|
2500
|
-
}
|
|
2501
|
-
});
|
|
2498
|
+
// Only once finished() has taken over. Set before the call, a synchronous throw from it
|
|
2499
|
+
// - anything not a stream reaching this far - would leave the finally below believing
|
|
2500
|
+
// the stream owns the lock, and nothing would ever release it.
|
|
2501
|
+
streaming = true;
|
|
2502
2502
|
|
|
2503
2503
|
return content;
|
|
2504
2504
|
} finally {
|
|
@@ -238,11 +238,31 @@ class IMAPClient extends BaseClient {
|
|
|
238
238
|
/**
|
|
239
239
|
* Called when a task is completed - ensures we return to the main mailbox
|
|
240
240
|
* This prevents the connection from staying in a rarely-used mailbox
|
|
241
|
+
*
|
|
242
|
+
* Only the primary connection has a mailbox worth returning to. A task served by a pooled
|
|
243
|
+
* secondary never moved the primary, so scheduling a re-select for it is at best wasted work
|
|
244
|
+
* and at worst pulls the primary out of a mailbox it is still using. getMailboxLock() makes
|
|
245
|
+
* the same distinction when it clears this timer, so the two sides agree.
|
|
246
|
+
*
|
|
247
|
+
* @param {Object} [connectionClient] - IMAP client that completed the task (defaults to the primary)
|
|
241
248
|
*/
|
|
242
|
-
onTaskCompleted() {
|
|
249
|
+
onTaskCompleted(connectionClient) {
|
|
250
|
+
if (connectionClient && connectionClient !== this.imapClient) {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// A download reports its task from a stream callback that can fire long after the account
|
|
255
|
+
// was paused or deleted. close() clears this timer but leaves this.imapClient pointing at
|
|
256
|
+
// the closed client, so without this a late callback arms a fresh one against a connection
|
|
257
|
+
// that is gone - and if a reconnect has since replaced the client, the re-select lands on
|
|
258
|
+
// the new connection mid-walk.
|
|
259
|
+
if (this.isClosing || this.isClosed) {
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
|
|
243
263
|
// check if we need to re-select main mailbox
|
|
264
|
+
clearTimeout(this.completedTimer);
|
|
244
265
|
this.completedTimer = setTimeout(() => {
|
|
245
|
-
clearTimeout(this.completedTimer);
|
|
246
266
|
this.ensureMainMailbox().catch(err => {
|
|
247
267
|
if (CONNECTION_CLOSING_CODES.has(err.code)) {
|
|
248
268
|
this.logger.debug({ msg: 'Select skipped, connection closing', err });
|
|
@@ -2480,6 +2500,12 @@ class IMAPClient extends BaseClient {
|
|
|
2480
2500
|
}
|
|
2481
2501
|
} finally {
|
|
2482
2502
|
lock.release();
|
|
2503
|
+
// mailboxClose() leaves the connection with no mailbox selected, and ImapFlow can
|
|
2504
|
+
// only re-arm IDLE for a mailbox it is in - so on the primary this is what puts the
|
|
2505
|
+
// account back to watching for new mail. The lock here is ImapFlow's own rather
|
|
2506
|
+
// than Mailbox.getMailboxLock(), which is the one that clears completedTimer, so
|
|
2507
|
+
// nothing else on this path would report the task.
|
|
2508
|
+
this.onTaskCompleted(connectionClient);
|
|
2483
2509
|
}
|
|
2484
2510
|
} catch (err) {
|
|
2485
2511
|
this.logger.debug({ msg: 'Mailbox select error', path, err });
|
|
@@ -2601,6 +2627,19 @@ class IMAPClient extends BaseClient {
|
|
|
2601
2627
|
let normalizedPath = [].concat(path || []).join('/');
|
|
2602
2628
|
|
|
2603
2629
|
if (normalizedNewPath !== normalizedPath) {
|
|
2630
|
+
// Acquire lock to prevent concurrent operations on the mailbox. ImapFlow's RENAME
|
|
2631
|
+
// first CLOSEs the mailbox when it is the selected one, which leaves the connection
|
|
2632
|
+
// with no mailbox selected - the same deselection deleteMailbox() goes through - so
|
|
2633
|
+
// the lock/onTaskCompleted pair below is what re-arms IDLE on the primary
|
|
2634
|
+
// connection afterwards. Without it a rename of the watched mailbox left the
|
|
2635
|
+
// account deaf to new mail until the next resync.
|
|
2636
|
+
let lock;
|
|
2637
|
+
try {
|
|
2638
|
+
lock = await connectionClient.getMailboxLock(path, { description: `Rename mailbox ${path}` });
|
|
2639
|
+
} catch (err) {
|
|
2640
|
+
this.logger.debug({ msg: 'Mailbox select error', path, err });
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2604
2643
|
try {
|
|
2605
2644
|
let renameResult = await connectionClient.mailboxRename(path, newPath);
|
|
2606
2645
|
if (renameResult) {
|
|
@@ -2638,6 +2677,14 @@ class IMAPClient extends BaseClient {
|
|
|
2638
2677
|
} else {
|
|
2639
2678
|
throw err;
|
|
2640
2679
|
}
|
|
2680
|
+
} finally {
|
|
2681
|
+
if (lock) {
|
|
2682
|
+
lock.release();
|
|
2683
|
+
}
|
|
2684
|
+
// See deleteMailbox(): the RENAME may have left the connection with no mailbox
|
|
2685
|
+
// selected, and on the primary this is what schedules the re-select that puts
|
|
2686
|
+
// the account back to watching for new mail
|
|
2687
|
+
this.onTaskCompleted(connectionClient);
|
|
2641
2688
|
}
|
|
2642
2689
|
} else {
|
|
2643
2690
|
result.path = normalizedPath;
|
|
@@ -17,6 +17,7 @@ const { detectMimeType, detectExtension } = require('nodemailer/lib/mime-funcs/m
|
|
|
17
17
|
// Import Graph API module for MS Graph API handling
|
|
18
18
|
const graphApi = require('./outlook/graph-api');
|
|
19
19
|
const { buildRawSendMailRequest, buildStructuredSendMailRequest, buildDraftSendRequest } = require('./outlook/send-request');
|
|
20
|
+
const { pushHeaderValue } = require('../utils/header-map');
|
|
20
21
|
|
|
21
22
|
const {
|
|
22
23
|
REDIS_PREFIX,
|
|
@@ -1716,13 +1717,9 @@ class OutlookClient extends BaseClient {
|
|
|
1716
1717
|
name = (name || '').toString().trim().toLowerCase();
|
|
1717
1718
|
|
|
1718
1719
|
value = (value || '').toString().trim();
|
|
1719
|
-
if (!(name
|
|
1720
|
-
headers[name] = [];
|
|
1721
|
-
}
|
|
1722
|
-
if (!Array.isArray(headers[name])) {
|
|
1720
|
+
if (!pushHeaderValue(headers, name, value)) {
|
|
1723
1721
|
continue;
|
|
1724
1722
|
}
|
|
1725
|
-
headers[name].push(value);
|
|
1726
1723
|
|
|
1727
1724
|
// Extract specific headers for easier access
|
|
1728
1725
|
switch (name) {
|
|
@@ -1954,13 +1951,9 @@ class OutlookClient extends BaseClient {
|
|
|
1954
1951
|
let { name, value } = header;
|
|
1955
1952
|
name = (name || '').toString().trim().toLowerCase();
|
|
1956
1953
|
value = (value || '').toString().trim();
|
|
1957
|
-
if (!(name
|
|
1958
|
-
headers[name] = [];
|
|
1959
|
-
}
|
|
1960
|
-
if (!Array.isArray(headers[name])) {
|
|
1954
|
+
if (!pushHeaderValue(headers, name, value)) {
|
|
1961
1955
|
continue;
|
|
1962
1956
|
}
|
|
1963
|
-
headers[name].push(value);
|
|
1964
1957
|
if (name === 'in-reply-to') {
|
|
1965
1958
|
messageData.inReplyTo = value;
|
|
1966
1959
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
--[[
|
|
2
|
+
Script: h-set-new-mark.lua
|
|
3
|
+
Purpose: Sets a hash field value only if the field doesn't already exist, and stamps a second
|
|
4
|
+
marker field in the same atomic step when it does. Used for seeded defaults that a
|
|
5
|
+
marker field declares "still owned by the seeder": writing the two separately leaves a
|
|
6
|
+
crash window where the seeded value exists without its marker and can never be told
|
|
7
|
+
apart from an explicit choice.
|
|
8
|
+
|
|
9
|
+
KEYS:
|
|
10
|
+
[1] hashKey - The hash key to operate on
|
|
11
|
+
|
|
12
|
+
ARGV:
|
|
13
|
+
[1] entryKey - The hash field name
|
|
14
|
+
[2] value - The value to set
|
|
15
|
+
[3] markerKey - The marker field name, written only when the value field was created
|
|
16
|
+
[4] markerValue - The marker value
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
1 if the value field didn't exist and both fields were written
|
|
20
|
+
0 if the value field already exists (no operation, the marker is not touched)
|
|
21
|
+
--]]
|
|
22
|
+
|
|
23
|
+
local hashKey = KEYS[1];
|
|
24
|
+
local entryKey = ARGV[1];
|
|
25
|
+
|
|
26
|
+
local value = ARGV[2];
|
|
27
|
+
local markerKey = ARGV[3];
|
|
28
|
+
local markerValue = ARGV[4];
|
|
29
|
+
|
|
30
|
+
if redis.call("HEXISTS", hashKey, entryKey) == 0 then
|
|
31
|
+
redis.call("HSET", hashKey, entryKey, value);
|
|
32
|
+
redis.call("HSET", hashKey, markerKey, markerValue);
|
|
33
|
+
return 1; -- New field created and marked
|
|
34
|
+
else
|
|
35
|
+
return 0; -- Field already exists, no operation
|
|
36
|
+
end;
|
|
@@ -19,7 +19,24 @@ class MessagePortWritable extends Writable {
|
|
|
19
19
|
this.destroy();
|
|
20
20
|
}
|
|
21
21
|
};
|
|
22
|
+
|
|
23
|
+
// A cancel message only arrives while the consumer is alive to send one. When its thread
|
|
24
|
+
// dies instead, the channel closes without one, and the transfer would otherwise drain the
|
|
25
|
+
// whole source into a port nobody is reading - holding the mailbox lock for the duration.
|
|
26
|
+
//
|
|
27
|
+
// A port that closes with nothing queued behind it reports it only to a listener that was
|
|
28
|
+
// already attached - the event is emitted when the port is started and drained, and a
|
|
29
|
+
// listener added afterwards never sees it. So the producer has to construct this when the
|
|
30
|
+
// port arrives, not once it has content to send: the wait in between is the whole window in
|
|
31
|
+
// which the consumer's thread can die, and for an attachment that is most of the transfer.
|
|
32
|
+
// releaseListeners() is how a producer that ends up with nothing to send gives the port
|
|
33
|
+
// back.
|
|
34
|
+
this.onPortClose = () => {
|
|
35
|
+
this.destroy();
|
|
36
|
+
};
|
|
37
|
+
|
|
22
38
|
this.messagePort.on('message', this.onPortMessage);
|
|
39
|
+
this.messagePort.on('close', this.onPortClose);
|
|
23
40
|
}
|
|
24
41
|
|
|
25
42
|
postToPort(message) {
|
|
@@ -33,12 +50,20 @@ class MessagePortWritable extends Writable {
|
|
|
33
50
|
}
|
|
34
51
|
}
|
|
35
52
|
|
|
53
|
+
// Hands the port back untouched. Used by a producer that took the port but found nothing to
|
|
54
|
+
// send (a 404, say): closing it would reach the consumer as a failed transfer rather than as
|
|
55
|
+
// the error it is about to be handed, and leaving the listeners attached leaks them.
|
|
56
|
+
releaseListeners() {
|
|
57
|
+
this.messagePort.removeListener('message', this.onPortMessage);
|
|
58
|
+
this.messagePort.removeListener('close', this.onPortClose);
|
|
59
|
+
}
|
|
60
|
+
|
|
36
61
|
closePort() {
|
|
37
62
|
if (this.portClosed) {
|
|
38
63
|
return;
|
|
39
64
|
}
|
|
40
65
|
this.portClosed = true;
|
|
41
|
-
this.
|
|
66
|
+
this.releaseListeners();
|
|
42
67
|
try {
|
|
43
68
|
this.messagePort.close();
|
|
44
69
|
} catch (err) {
|
|
@@ -83,6 +108,7 @@ class MessagePortReadable extends Readable {
|
|
|
83
108
|
|
|
84
109
|
this.canRead = false;
|
|
85
110
|
this.portClosed = false;
|
|
111
|
+
this.transferComplete = false;
|
|
86
112
|
|
|
87
113
|
this.readableQueue = [];
|
|
88
114
|
this.onPortMessage = message => {
|
|
@@ -96,6 +122,9 @@ class MessagePortReadable extends Readable {
|
|
|
96
122
|
return;
|
|
97
123
|
}
|
|
98
124
|
if (message.done || message.value) {
|
|
125
|
+
if (message.done) {
|
|
126
|
+
this.transferComplete = true;
|
|
127
|
+
}
|
|
99
128
|
this.readableQueue.push(message);
|
|
100
129
|
|
|
101
130
|
if (this.canRead && this.readableQueue.length === 1) {
|
|
@@ -103,7 +132,18 @@ class MessagePortReadable extends Readable {
|
|
|
103
132
|
}
|
|
104
133
|
}
|
|
105
134
|
};
|
|
135
|
+
|
|
136
|
+
// Queued messages are delivered before 'close', so a channel that closes without
|
|
137
|
+
// { done: true } was cut short - most likely the producing worker died mid-download.
|
|
138
|
+
// Fail the read rather than presenting a truncated body or hanging on it forever.
|
|
139
|
+
this.onPortClose = () => {
|
|
140
|
+
if (!this.transferComplete && !this.destroyed) {
|
|
141
|
+
this.destroy(new Error('Message stream transfer interrupted'));
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
106
145
|
this.messagePort.on('message', this.onPortMessage);
|
|
146
|
+
this.messagePort.on('close', this.onPortClose);
|
|
107
147
|
}
|
|
108
148
|
|
|
109
149
|
_processReading() {
|
|
@@ -132,6 +172,7 @@ class MessagePortReadable extends Readable {
|
|
|
132
172
|
// ignore - the peer may already be closed
|
|
133
173
|
}
|
|
134
174
|
this.messagePort.removeListener('message', this.onPortMessage);
|
|
175
|
+
this.messagePort.removeListener('close', this.onPortClose);
|
|
135
176
|
try {
|
|
136
177
|
this.messagePort.close();
|
|
137
178
|
} catch (closeErr) {
|
|
@@ -153,6 +194,20 @@ class MessagePortReadable extends Readable {
|
|
|
153
194
|
* @param {Object} [logger] - Optional logger used to report transfer failures
|
|
154
195
|
*/
|
|
155
196
|
function pipeToMessagePort(source, writable, logger) {
|
|
197
|
+
// pipeline() throws ERR_STREAM_UNABLE_TO_PIPE *synchronously* when the destination is
|
|
198
|
+
// already destroyed. The callback below never runs in that case, so the throw escapes to
|
|
199
|
+
// the global uncaughtException handler and takes the worker - and every account assigned
|
|
200
|
+
// to it - down with it. An aborted consumer destroys the writable through its
|
|
201
|
+
// { cancel: true } message, and on a slow upstream fetch that can easily land before this
|
|
202
|
+
// helper is entered at all, so it is a routine state rather than an edge case.
|
|
203
|
+
if (writable.destroyed) {
|
|
204
|
+
// Nothing will drain the source now, so release it explicitly - otherwise the upstream
|
|
205
|
+
// download keeps running and the mailbox lock it holds is never given back.
|
|
206
|
+
source.destroy();
|
|
207
|
+
logger?.debug?.({ msg: 'Message stream transfer aborted by consumer before it started' });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
|
|
156
211
|
pipeline(source, writable, err => {
|
|
157
212
|
if (!err || !logger) {
|
|
158
213
|
return;
|
|
@@ -171,6 +226,34 @@ function pipeToMessagePort(source, writable, logger) {
|
|
|
171
226
|
});
|
|
172
227
|
}
|
|
173
228
|
|
|
229
|
+
/**
|
|
230
|
+
* Sends a finished download to the API worker over a destination bound to the transferred port.
|
|
231
|
+
* IMAP resolves a download to a stream and Gmail and Graph to a Buffer; the Buffer is wrapped so
|
|
232
|
+
* both shapes take the same path, leaving pipeToMessagePort() as the single place that has to get
|
|
233
|
+
* an aborted consumer right.
|
|
234
|
+
*
|
|
235
|
+
* Takes the destination rather than the port, because the producer has to build it when the port
|
|
236
|
+
* arrives - see the MessagePortWritable constructor for why. By the time there is content to send,
|
|
237
|
+
* a consumer that gave up has already destroyed it, and pipeToMessagePort() releases the source
|
|
238
|
+
* instead of transferring into a port nobody reads.
|
|
239
|
+
*
|
|
240
|
+
* @param {MessagePortWritable} writable - Destination built when the port arrived
|
|
241
|
+
* @param {Buffer|Readable} source - Payload to transfer
|
|
242
|
+
* @param {Object} [logger] - Optional logger used to report transfer failures
|
|
243
|
+
* @returns {MessagePortWritable} The same destination (used by tests; callers may ignore it)
|
|
244
|
+
*/
|
|
245
|
+
function sendToMessagePort(writable, source, logger) {
|
|
246
|
+
const stream = Buffer.isBuffer(source) ? Readable.from([source], { objectMode: false }) : source;
|
|
247
|
+
|
|
248
|
+
// A { cancel: true } already queued by a consumer that gave up is delivered on the next turn of
|
|
249
|
+
// the event loop. Dispatching from the check phase puts the guard in pipeToMessagePort() after
|
|
250
|
+
// that delivery rather than racing it.
|
|
251
|
+
setImmediate(() => pipeToMessagePort(stream, writable, logger));
|
|
252
|
+
|
|
253
|
+
return writable;
|
|
254
|
+
}
|
|
255
|
+
|
|
174
256
|
module.exports.MessagePortWritable = MessagePortWritable;
|
|
175
257
|
module.exports.MessagePortReadable = MessagePortReadable;
|
|
176
258
|
module.exports.pipeToMessagePort = pipeToMessagePort;
|
|
259
|
+
module.exports.sendToMessagePort = sendToMessagePort;
|
package/lib/oauth2-apps.js
CHANGED
|
@@ -418,9 +418,12 @@ class OAuth2AppsHandler {
|
|
|
418
418
|
// One-time startup migration: converts settings-based OAuth2 configuration ("legacy apps")
|
|
419
419
|
// into regular app-store records. The historical app IDs (gmail, gmailService, outlook,
|
|
420
420
|
// mailRu) are kept, so account references (accountData.oauth2.provider) keep resolving
|
|
421
|
-
// without touching account data. The source settings keys are deleted after
|
|
422
|
-
//
|
|
423
|
-
//
|
|
421
|
+
// without touching account data. The source settings keys are deleted last, after the app
|
|
422
|
+
// records and the account backfill, which is what makes the migration both idempotent and
|
|
423
|
+
// crash-safe: as long as any source key remains, the next startup re-enters and repeats
|
|
424
|
+
// whichever steps are missing (create() is guarded by an existence check and the backfill
|
|
425
|
+
// is an idempotent SADD). A Redis lock guards against parallel instances sharing one
|
|
426
|
+
// Redis. Returns the list of migrated app IDs.
|
|
424
427
|
async migrateLegacyApps() {
|
|
425
428
|
// Full per-app settings key suffixes ever used by the legacy configuration
|
|
426
429
|
const FIELDS = [
|
|
@@ -472,9 +475,33 @@ class OAuth2AppsHandler {
|
|
|
472
475
|
return value.filter(entry => entry);
|
|
473
476
|
};
|
|
474
477
|
|
|
478
|
+
// A stored secret whose decryption failed (a rotated or missing service secret) reads
|
|
479
|
+
// back as null through settings.getMulti(), exactly like an absent key. Deleting the
|
|
480
|
+
// source keys in that state would destroy the only copy of the ciphertext, so probe
|
|
481
|
+
// the raw hash to tell the two apart and leave such an app entirely untouched - the
|
|
482
|
+
// migration retries on the next startup, and restoring the correct service secret
|
|
483
|
+
// makes it whole again.
|
|
484
|
+
const encryptedCandidates = candidateKeys.filter(key => settings.encryptedKeys.includes(key));
|
|
485
|
+
const rawEncryptedValues = await this.redis.hmget(this.getSettingsKey(), encryptedCandidates);
|
|
486
|
+
const undecryptable = new Set(encryptedCandidates.filter((key, i) => rawEncryptedValues[i] !== null && values[key] === null));
|
|
487
|
+
|
|
488
|
+
// Apps whose accounts should be (re-)linked, and apps whose source keys may be dropped
|
|
489
|
+
let backfillable = [];
|
|
490
|
+
let clearable = [];
|
|
491
|
+
|
|
475
492
|
for (let legacyKey of LEGACY_KEYS) {
|
|
476
493
|
const v = field => values[`${legacyKey}${field}`];
|
|
477
494
|
|
|
495
|
+
let failedKeys = FIELDS.map(field => `${legacyKey}${field}`).filter(key => undecryptable.has(key));
|
|
496
|
+
if (failedKeys.length) {
|
|
497
|
+
logger.error({
|
|
498
|
+
msg: 'Skipped legacy OAuth2 app migration: stored credentials could not be decrypted. Restore the original service secret and restart',
|
|
499
|
+
app: legacyKey,
|
|
500
|
+
keys: failedKeys
|
|
501
|
+
});
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
|
|
478
505
|
// Same visibility rule the legacy listing applied: an app existed when it was
|
|
479
506
|
// enabled or had a client configured. Stray keys without either (e.g. only a
|
|
480
507
|
// redirect URL) never surfaced an app and are just cleaned up.
|
|
@@ -548,24 +575,21 @@ class OAuth2AppsHandler {
|
|
|
548
575
|
logger.info({ msg: 'Migrated legacy OAuth2 app to the app registry', app: legacyKey, enabled: entry.enabled });
|
|
549
576
|
}
|
|
550
577
|
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
578
|
+
if (visible) {
|
|
579
|
+
// Whether the record was created now or by an earlier interrupted run: as long
|
|
580
|
+
// as the source keys are still around the backfill below has not been confirmed
|
|
581
|
+
// done, and repeating it is a no-op
|
|
582
|
+
backfillable.push(legacyKey);
|
|
555
583
|
}
|
|
556
|
-
await clearReq.exec();
|
|
557
|
-
}
|
|
558
584
|
|
|
559
|
-
|
|
560
|
-
if (removedOrphans) {
|
|
561
|
-
logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: ORPHAN_KEYS });
|
|
585
|
+
clearable.push(legacyKey);
|
|
562
586
|
}
|
|
563
587
|
|
|
564
588
|
// Backfill the per-app account membership sets that the legacy code never maintained,
|
|
565
589
|
// so account counts and app deletion safety checks see the existing accounts. The
|
|
566
590
|
// per-user binding hash (oapp:h:*) is left to repopulate on the next account update.
|
|
567
|
-
if (
|
|
568
|
-
let
|
|
591
|
+
if (backfillable.length) {
|
|
592
|
+
let backfillableSet = new Set(backfillable);
|
|
569
593
|
let accounts = await this.redis.smembers(`${REDIS_PREFIX}ia:accounts`);
|
|
570
594
|
let backfillReq = this.redis.multi();
|
|
571
595
|
let backfillCount = 0;
|
|
@@ -592,7 +616,7 @@ class OAuth2AppsHandler {
|
|
|
592
616
|
} catch (parseErr) {
|
|
593
617
|
continue;
|
|
594
618
|
}
|
|
595
|
-
if (oauth2Data && oauth2Data.provider &&
|
|
619
|
+
if (oauth2Data && oauth2Data.provider && backfillableSet.has(oauth2Data.provider)) {
|
|
596
620
|
backfillReq = backfillReq.sadd(`${REDIS_PREFIX}oapp:a:${oauth2Data.provider}`, chunk[j]);
|
|
597
621
|
backfillCount++;
|
|
598
622
|
}
|
|
@@ -604,6 +628,16 @@ class OAuth2AppsHandler {
|
|
|
604
628
|
logger.info({ msg: 'Linked existing accounts to migrated OAuth2 apps', accounts: backfillCount });
|
|
605
629
|
}
|
|
606
630
|
}
|
|
631
|
+
|
|
632
|
+
// The copy is complete, drop the source settings keys (no-op when unset)
|
|
633
|
+
if (clearable.length) {
|
|
634
|
+
await this.redis.hdel(this.getSettingsKey(), ...clearable.flatMap(legacyKey => FIELDS.map(field => `${legacyKey}${field}`)));
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
let removedOrphans = await this.redis.hdel(this.getSettingsKey(), ...ORPHAN_KEYS);
|
|
638
|
+
if (removedOrphans) {
|
|
639
|
+
logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: ORPHAN_KEYS });
|
|
640
|
+
}
|
|
607
641
|
} finally {
|
|
608
642
|
await lock.releaseLock(migrateLock);
|
|
609
643
|
}
|
|
@@ -875,6 +909,41 @@ class OAuth2AppsHandler {
|
|
|
875
909
|
}
|
|
876
910
|
}
|
|
877
911
|
|
|
912
|
+
// Auth-failure flags of every registered app, for the site-wide admin alert (see the view
|
|
913
|
+
// context in workers/api.js). Reads only the meta entries - one SMEMBERS plus one HMGET
|
|
914
|
+
// however many apps exist - because it runs on every admin page render.
|
|
915
|
+
async listAuthFlags() {
|
|
916
|
+
// sorted only so the alert order is stable across renders
|
|
917
|
+
let idList = (await this.redis.smembers(this.getIndexKey())).sort();
|
|
918
|
+
if (!idList.length) {
|
|
919
|
+
return [];
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
let metaEntries = await this.redis.hmgetBuffer(
|
|
923
|
+
this.getDataKey(),
|
|
924
|
+
idList.map(id => `${id}:meta`)
|
|
925
|
+
);
|
|
926
|
+
|
|
927
|
+
let flags = [];
|
|
928
|
+
for (let i = 0; i < idList.length; i++) {
|
|
929
|
+
if (!metaEntries[i]) {
|
|
930
|
+
continue;
|
|
931
|
+
}
|
|
932
|
+
let meta;
|
|
933
|
+
try {
|
|
934
|
+
meta = msgpack.decode(metaEntries[i]);
|
|
935
|
+
} catch (err) {
|
|
936
|
+
logger.error({ msg: 'Failed to process app meta', app: idList[i], entryLength: metaEntries[i].length, err });
|
|
937
|
+
continue;
|
|
938
|
+
}
|
|
939
|
+
if (meta && meta.authFlag && meta.authFlag.message) {
|
|
940
|
+
flags.push({ app: idList[i], authFlag: meta.authFlag });
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
return flags;
|
|
945
|
+
}
|
|
946
|
+
|
|
878
947
|
// Note: not atomic (read-modify-write). Concurrent callers use last-write-wins,
|
|
879
948
|
// which is acceptable for self-correcting informational metadata.
|
|
880
949
|
async setMeta(id, meta) {
|