emailengine-app 2.72.1 → 2.72.3
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/CHANGELOG.md +30 -0
- package/Gruntfile.js +4 -1
- package/data/google-crawlers.json +1 -1
- package/lib/account/account-state.js +5 -0
- package/lib/account.js +74 -9
- package/lib/autodetect-imap-settings.js +66 -11
- package/lib/consts.js +7 -0
- package/lib/email-client/gmail-client.js +45 -2
- package/lib/email-client/outlook/graph-api.js +3 -1
- package/lib/email-client/outlook-client.js +34 -6
- package/lib/email-client/smtp-pool-manager.js +2 -1
- package/lib/export.js +3 -2
- package/lib/imap-proxy-auth.js +2 -1
- package/lib/schemas.js +14 -0
- package/lib/settings.js +42 -11
- package/lib/smtp-auth.js +2 -1
- package/lib/sub-script.js +14 -3
- package/lib/tokens.js +2 -1
- package/lib/tools.js +122 -12
- package/lib/ui-routes/account-routes.js +340 -121
- package/lib/ui-routes/admin-config-routes.js +11 -1
- package/lib/ui-routes/unsubscribe-routes.js +69 -49
- package/package.json +25 -22
- package/sbom.json +1 -1
- package/static/js/ee-client.js +198 -140
- package/static/licenses.html +56 -56
- package/translations/messages.pot +98 -88
- package/views/accounts/register/imap-server.hbs +87 -17
- package/views/partials/oauth_form.hbs +4 -4
- package/views/unsubscribe.hbs +8 -17
- package/workers/api.js +124 -53
- package/Fluid-Attacks-Results.csv +0 -1
- package/test-coverage-plan.md +0 -233
package/workers/api.js
CHANGED
|
@@ -34,7 +34,11 @@ const {
|
|
|
34
34
|
getBoolean,
|
|
35
35
|
loadTlsConfig,
|
|
36
36
|
maybeReloadHttpProxyAgent,
|
|
37
|
-
resolveOAuthErrorStatus
|
|
37
|
+
resolveOAuthErrorStatus,
|
|
38
|
+
constantTimeEqual,
|
|
39
|
+
verifyServiceSignature,
|
|
40
|
+
claimFormNonce,
|
|
41
|
+
releaseFormNonce
|
|
38
42
|
} = require('../lib/tools');
|
|
39
43
|
const { matchIp, detectAutomatedRequest } = require('../lib/utils/network');
|
|
40
44
|
|
|
@@ -512,6 +516,11 @@ const init = async () => {
|
|
|
512
516
|
return new handlebars.SafeString(translated);
|
|
513
517
|
});
|
|
514
518
|
|
|
519
|
+
// HTML-escape a value for safe interpolation into an otherwise-unescaped context - e.g. a
|
|
520
|
+
// dynamic `%s` argument to the SafeString-returning `_` helper. Returns a plain string so
|
|
521
|
+
// the surrounding markup stays live while the value itself is entity-escaped.
|
|
522
|
+
handlebars.registerHelper('escapeHtml', value => handlebars.escapeExpression(value));
|
|
523
|
+
|
|
515
524
|
handlebars.registerHelper('isodate', time => new Date(Number(time)).toISOString());
|
|
516
525
|
|
|
517
526
|
handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
|
|
@@ -539,7 +548,12 @@ const init = async () => {
|
|
|
539
548
|
} catch (err) {
|
|
540
549
|
res = util.inspect(payload, false, 4, false);
|
|
541
550
|
}
|
|
542
|
-
return
|
|
551
|
+
// SECURITY: return a plain string (NOT a SafeString) so Handlebars HTML-escapes the
|
|
552
|
+
// output. `payload` can carry attacker-controlled data (e.g. inbound email fields in
|
|
553
|
+
// webhook / pre-processing error logs); wrapping it in a SafeString allowed a stored
|
|
554
|
+
// XSS via a </textarea> breakout in the error-log views (security review H1). In the
|
|
555
|
+
// <textarea> render contexts this is display-identical (the browser decodes entities).
|
|
556
|
+
return res;
|
|
543
557
|
});
|
|
544
558
|
|
|
545
559
|
handlebars.registerHelper('lastVal', (value, separator) => {
|
|
@@ -1596,14 +1610,9 @@ Include your token in requests using one of these methods:
|
|
|
1596
1610
|
path: '/redirect',
|
|
1597
1611
|
async handler(request, h) {
|
|
1598
1612
|
let data = Buffer.from(request.query.data, 'base64url').toString();
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
hmac.update(data);
|
|
1603
|
-
if (hmac.digest('base64url') !== request.query.sig) {
|
|
1604
|
-
let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
|
|
1605
|
-
throw error;
|
|
1606
|
-
}
|
|
1613
|
+
if (!(await verifyServiceSignature(data, request.query.sig))) {
|
|
1614
|
+
let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
|
|
1615
|
+
throw error;
|
|
1607
1616
|
}
|
|
1608
1617
|
|
|
1609
1618
|
data = JSON.parse(data);
|
|
@@ -1651,6 +1660,12 @@ Include your token in requests using one of these methods:
|
|
|
1651
1660
|
failAction,
|
|
1652
1661
|
|
|
1653
1662
|
query: Joi.object({
|
|
1663
|
+
// `sig` is intentionally OPTIONAL on the tracking endpoints (/redirect, /open.gif,
|
|
1664
|
+
// /unsubscribe), unlike the hosted form's signedFormBlobFields which requires it. The
|
|
1665
|
+
// handler calls verifyServiceSignature and fails closed on a missing/bad signature, so a
|
|
1666
|
+
// required-sig schema would only turn that 403 into a Joi 400 - and /unsubscribe must not
|
|
1667
|
+
// 400 a missing-sig one-click request (RFC 8058 wants a benign non-throwing response).
|
|
1668
|
+
// Kept optional deliberately; do not "align" these with the hosted-form fragment.
|
|
1654
1669
|
data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
|
|
1655
1670
|
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true })
|
|
1656
1671
|
})
|
|
@@ -1665,14 +1680,9 @@ Include your token in requests using one of these methods:
|
|
|
1665
1680
|
path: '/open.gif',
|
|
1666
1681
|
async handler(request, h) {
|
|
1667
1682
|
let data = Buffer.from(request.query.data, 'base64url').toString();
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
hmac.update(data);
|
|
1672
|
-
if (hmac.digest('base64url') !== request.query.sig) {
|
|
1673
|
-
let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
|
|
1674
|
-
throw error;
|
|
1675
|
-
}
|
|
1683
|
+
if (!(await verifyServiceSignature(data, request.query.sig))) {
|
|
1684
|
+
let error = Boom.boomify(new Error('Signature validation failed'), { statusCode: 403 });
|
|
1685
|
+
throw error;
|
|
1676
1686
|
}
|
|
1677
1687
|
|
|
1678
1688
|
data = JSON.parse(data);
|
|
@@ -1720,6 +1730,7 @@ Include your token in requests using one of these methods:
|
|
|
1720
1730
|
failAction,
|
|
1721
1731
|
|
|
1722
1732
|
query: Joi.object({
|
|
1733
|
+
// sig intentionally optional - see the note on the /redirect schema above.
|
|
1723
1734
|
data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
|
|
1724
1735
|
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true })
|
|
1725
1736
|
})
|
|
@@ -1733,21 +1744,33 @@ Include your token in requests using one of these methods:
|
|
|
1733
1744
|
method: 'POST',
|
|
1734
1745
|
path: '/unsubscribe',
|
|
1735
1746
|
async handler(request) {
|
|
1736
|
-
//
|
|
1747
|
+
// This unauthenticated RFC 8058 one-click endpoint separates two failure classes:
|
|
1748
|
+
// - Permanent (forged/malformed/incomplete blob, unknown account): retrying cannot help,
|
|
1749
|
+
// so return a benign 2xx string and do not invite a retry.
|
|
1750
|
+
// - Transient (a Redis/getSecret hiccup while recording the suppression): must surface as
|
|
1751
|
+
// a retryable 5xx. An RFC 8058 client treats any 2xx as "unsubscribed" and never retries,
|
|
1752
|
+
// so swallowing a transient failure to 2xx would silently drop the unsubscribe and the
|
|
1753
|
+
// recipient would keep receiving mail. eeListAdd is idempotent (isNew), so a retry is safe.
|
|
1737
1754
|
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1755
|
+
// Joi already enforces base64url on request.query.data, and Buffer.from(<string>, 'base64url')
|
|
1756
|
+
// never throws, so decode inline like the sibling /redirect and /open.gif handlers.
|
|
1757
|
+
let raw = Buffer.from(request.query.data, 'base64url').toString();
|
|
1758
|
+
|
|
1759
|
+
// A false result is a forged/bad signature (permanent -> benign); a THROWN error is a
|
|
1760
|
+
// transient failure reading the service secret and is intentionally left to surface as 5xx.
|
|
1761
|
+
if (!(await verifyServiceSignature(raw, request.query.sig))) {
|
|
1762
|
+
return 'data validation failed';
|
|
1746
1763
|
}
|
|
1747
1764
|
|
|
1748
|
-
|
|
1765
|
+
let data;
|
|
1766
|
+
try {
|
|
1767
|
+
data = JSON.parse(raw);
|
|
1768
|
+
} catch (err) {
|
|
1769
|
+
// Malformed JSON inside a validly-signed blob - permanent.
|
|
1770
|
+
return 'not ok';
|
|
1771
|
+
}
|
|
1749
1772
|
|
|
1750
|
-
if (!data || typeof data !== 'object' || data.act !== 'unsub') {
|
|
1773
|
+
if (!data || typeof data !== 'object' || data.act !== 'unsub' || !data.acc || !data.list || !data.rcpt) {
|
|
1751
1774
|
return 'not ok';
|
|
1752
1775
|
}
|
|
1753
1776
|
|
|
@@ -1763,9 +1786,18 @@ Include your token in requests using one of these methods:
|
|
|
1763
1786
|
// throws if account does not exist
|
|
1764
1787
|
await accountObject.loadAccountData();
|
|
1765
1788
|
} catch (err) {
|
|
1766
|
-
|
|
1789
|
+
// A genuine "account does not exist" is a permanent 404 -> benign 2xx (retrying cannot
|
|
1790
|
+
// help). Any other error (e.g. a transient Redis/decrypt failure) must NOT be swallowed
|
|
1791
|
+
// to a 2xx: an RFC 8058 client treats any 2xx as "unsubscribed" and never retries, so
|
|
1792
|
+
// dropping the unsubscribe would leave the recipient subscribed. Let it surface as 5xx.
|
|
1793
|
+
if (err.output && err.output.statusCode === 404) {
|
|
1794
|
+
return 'unknown account';
|
|
1795
|
+
}
|
|
1796
|
+
throw err;
|
|
1767
1797
|
}
|
|
1768
1798
|
|
|
1799
|
+
// Record the suppression. A transient backend failure here is intentionally NOT swallowed to
|
|
1800
|
+
// a 2xx: it propagates as a 5xx so the client retries rather than dropping the unsubscribe.
|
|
1769
1801
|
let isNew = await redis.eeListAdd(
|
|
1770
1802
|
`${REDIS_PREFIX}lists:unsub:lists`,
|
|
1771
1803
|
`${REDIS_PREFIX}lists:unsub:entries:${data.list}`,
|
|
@@ -1784,13 +1816,19 @@ Include your token in requests using one of these methods:
|
|
|
1784
1816
|
);
|
|
1785
1817
|
|
|
1786
1818
|
if (isNew) {
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1819
|
+
// The suppression is already stored; a webhook delivery hiccup must not fail (and thus
|
|
1820
|
+
// trigger a client retry of) an unsubscribe that already succeeded. Log and move on.
|
|
1821
|
+
try {
|
|
1822
|
+
await sendWebhook(data.acc, LIST_UNSUBSCRIBE_NOTIFY, {
|
|
1823
|
+
recipient: data.rcpt,
|
|
1824
|
+
messageId: data.msg,
|
|
1825
|
+
listId: data.list,
|
|
1826
|
+
remoteAddress: request.app.ip,
|
|
1827
|
+
userAgent: request.headers['user-agent']
|
|
1828
|
+
});
|
|
1829
|
+
} catch (err) {
|
|
1830
|
+
request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', err });
|
|
1831
|
+
}
|
|
1794
1832
|
}
|
|
1795
1833
|
|
|
1796
1834
|
return 'ok';
|
|
@@ -1808,6 +1846,9 @@ Include your token in requests using one of these methods:
|
|
|
1808
1846
|
failAction,
|
|
1809
1847
|
|
|
1810
1848
|
query: Joi.object({
|
|
1849
|
+
// sig intentionally optional - see the note on the /redirect schema above. Especially
|
|
1850
|
+
// here: making sig required would 400 a missing-sig one-click POST, but RFC 8058 wants a
|
|
1851
|
+
// benign non-throwing response (the handler returns 'data validation failed' instead).
|
|
1811
1852
|
data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
|
|
1812
1853
|
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true })
|
|
1813
1854
|
}).label('OneClickUnsubQuery'),
|
|
@@ -1867,14 +1908,16 @@ Include your token in requests using one of these methods:
|
|
|
1867
1908
|
|
|
1868
1909
|
for (let entry of (request.payload && request.payload.value) || []) {
|
|
1869
1910
|
// enumerate and queue all entries
|
|
1870
|
-
|
|
1911
|
+
const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
|
|
1912
|
+
const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
|
|
1913
|
+
if (!subscriptionIdMatch || !clientStateMatch) {
|
|
1871
1914
|
// Security: Log webhook validation failures - could indicate spoofed notifications
|
|
1872
1915
|
request.logger.warn({
|
|
1873
1916
|
msg: 'Webhook validation failed - potential security issue',
|
|
1874
1917
|
securityEvent: 'webhook_validation_failure',
|
|
1875
1918
|
account: request.query.account,
|
|
1876
|
-
subscriptionIdMatch
|
|
1877
|
-
clientStateMatch
|
|
1919
|
+
subscriptionIdMatch,
|
|
1920
|
+
clientStateMatch,
|
|
1878
1921
|
receivedSubscriptionId: entry.subscriptionId,
|
|
1879
1922
|
changeType: entry.changeType,
|
|
1880
1923
|
resource: entry.resource
|
|
@@ -1971,14 +2014,16 @@ Include your token in requests using one of these methods:
|
|
|
1971
2014
|
});
|
|
1972
2015
|
|
|
1973
2016
|
// enumerate and queue all entries
|
|
1974
|
-
|
|
2017
|
+
const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
|
|
2018
|
+
const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
|
|
2019
|
+
if (!subscriptionIdMatch || !clientStateMatch) {
|
|
1975
2020
|
// Security: Log lifecycle webhook validation failures - could indicate spoofed notifications
|
|
1976
2021
|
request.logger.warn({
|
|
1977
2022
|
msg: 'Lifecycle webhook validation failed - potential security issue',
|
|
1978
2023
|
securityEvent: 'lifecycle_webhook_validation_failure',
|
|
1979
2024
|
account: request.query.account,
|
|
1980
|
-
subscriptionIdMatch
|
|
1981
|
-
clientStateMatch
|
|
2025
|
+
subscriptionIdMatch,
|
|
2026
|
+
clientStateMatch,
|
|
1982
2027
|
receivedSubscriptionId: entry.subscriptionId,
|
|
1983
2028
|
lifecycleEvent: entry.lifecycleEvent
|
|
1984
2029
|
});
|
|
@@ -2452,20 +2497,46 @@ Include your token in requests using one of these methods:
|
|
|
2452
2497
|
timeout: request.headers['x-ee-timeout']
|
|
2453
2498
|
});
|
|
2454
2499
|
|
|
2455
|
-
|
|
2456
|
-
|
|
2500
|
+
// Claim the single-use nonce BEFORE create (SET NX), mirroring the IMAP arm in
|
|
2501
|
+
// lib/ui-routes/account-routes.js, so one signed link cannot be double-spent across the two
|
|
2502
|
+
// arms (initiate OAuth -> submit the same blob to /accounts/new/imap/server -> complete this
|
|
2503
|
+
// callback) and a replayed callback cannot create a second account.
|
|
2504
|
+
//
|
|
2505
|
+
// Backward-compat, BY DESIGN: this only engages when accountMeta.n is present. Legacy /
|
|
2506
|
+
// pre-upgrade re-auth blobs carry no nonce (accountMeta.n is undefined), so the claim is
|
|
2507
|
+
// skipped and those links keep working - the OAuth entry (accountFormHandler) intentionally
|
|
2508
|
+
// does NOT require a nonce for exactly that reason.
|
|
2509
|
+
// claimFormNonce/releaseFormNonce (lib/tools.js) are the same primitives the IMAP arm uses, so
|
|
2510
|
+
// the double-spend semantics stay in one place.
|
|
2511
|
+
let nonceClaimed = false;
|
|
2457
2512
|
if (accountMeta.n) {
|
|
2458
|
-
|
|
2459
|
-
const keyName = `${REDIS_PREFIX}account:form:${accountMeta.n}`;
|
|
2513
|
+
let claimed;
|
|
2460
2514
|
try {
|
|
2461
|
-
await redis
|
|
2462
|
-
.multi()
|
|
2463
|
-
.set(keyName, (accountMeta.t || '0').toString())
|
|
2464
|
-
.expire(keyName, Math.floor(MAX_FORM_TTL / 1000))
|
|
2465
|
-
.exec();
|
|
2515
|
+
claimed = await claimFormNonce(redis, accountMeta.n, accountMeta.t);
|
|
2466
2516
|
} catch (err) {
|
|
2467
|
-
|
|
2517
|
+
// A Redis failure is not a consumed nonce - surface a retryable error rather than
|
|
2518
|
+
// misreporting a valid setup URL as invalid.
|
|
2519
|
+
request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
|
|
2520
|
+
throw Boom.boomify(new Error('Temporary error, please try again'), { statusCode: 500 });
|
|
2521
|
+
}
|
|
2522
|
+
if (!claimed) {
|
|
2523
|
+
// The nonce key already exists: this signed URL was already used.
|
|
2524
|
+
throw Boom.boomify(new Error('Invalid or expired account setup URL'), { statusCode: 403 });
|
|
2468
2525
|
}
|
|
2526
|
+
nonceClaimed = true;
|
|
2527
|
+
}
|
|
2528
|
+
|
|
2529
|
+
let result;
|
|
2530
|
+
try {
|
|
2531
|
+
result = await accountObject.create(accountData);
|
|
2532
|
+
} catch (err) {
|
|
2533
|
+
// Release the nonce so the user can retry (same accepted residual as the IMAP arm: if
|
|
2534
|
+
// Redis also fails here the nonce stays consumed for its TTL and a fresh link is needed -
|
|
2535
|
+
// the price of claim-before-create being atomic).
|
|
2536
|
+
if (nonceClaimed) {
|
|
2537
|
+
await releaseFormNonce(redis, accountMeta.n, request.logger);
|
|
2538
|
+
}
|
|
2539
|
+
throw err;
|
|
2469
2540
|
}
|
|
2470
2541
|
|
|
2471
2542
|
let httpRedirectUrl;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
!placeholder
|
package/test-coverage-plan.md
DELETED
|
@@ -1,233 +0,0 @@
|
|
|
1
|
-
# EmailEngine - Feature Map & Prioritized Test Plan
|
|
2
|
-
|
|
3
|
-
Generated 2026-06-16. Read-only audit across five feature areas (email sync engine, REST API, admin UI, background workers/queues, core libraries). No source or tests were modified.
|
|
4
|
-
|
|
5
|
-
Baseline: ~70k LOC source (lib + workers + server.js) vs ~16.1k LOC unit tests, ~1.8k integration, 180 e2e.
|
|
6
|
-
|
|
7
|
-
---
|
|
8
|
-
|
|
9
|
-
## 1. Feature & functionality map
|
|
10
|
-
|
|
11
|
-
EmailEngine is a multi-threaded (Worker Threads), Redis-backed email sync platform exposing a REST API + admin UI.
|
|
12
|
-
|
|
13
|
-
### Email sync engine (lib/email-client/*, workers/imap.js, lib/account*)
|
|
14
|
-
- Three providers behind a shared `BaseClient`: IMAP (ImapFlow + IDLE), Gmail API (Pub/Sub + 10-min poll fallback), Outlook/Graph (subscription webhooks, 3-day renewal).
|
|
15
|
-
- Message ops: list/get/getText/getRawMessage/getAttachment/update/move/delete/upload (+ bulk variants).
|
|
16
|
-
- Mailbox ops: list/create/modify/delete; special-use resolution; provider path encoding (Outlook `/`,`%`; Gmail label<->folder).
|
|
17
|
-
- IMAP sync: `determineSyncStrategy` -> none/partial(condstore|simple)/full; UIDValidity change -> full resync + index reseed; lost-index silent reseed; batched fetch with retry/backoff.
|
|
18
|
-
- Reliability: exponential reconnect/backoff; auth-failure tracking + auto-disable (`setErrorState`); error classification -> account state (authenticationError vs connectError); state machine (account-state.js).
|
|
19
|
-
- Send path: `queueMessage`/`submitMessage` (SMTP + Gmail/Outlook API), idempotency keys, post-delivery Sent-folder upload + Answered/Forwarded flags + gateway stats.
|
|
20
|
-
|
|
21
|
-
### REST API (lib/api-routes/*, ~8.1k LOC, 20 modules)
|
|
22
|
-
- Account + message + mailbox CRUD/ops; submit; outbox; export; gateways; templates; tokens; settings; oauth2-apps; webhook-routes; blocklist; chat (doc-store-gated); delivery-test; license; pubsub; stats; bull-board.
|
|
23
|
-
- Single `api-token` bearer strategy: scope derived from route tags (all REST modules use `api`); account-token binding restricts to own `{account}`; IP/referrer allowlist + per-token rate limit; `disableTokens` open-API bypass.
|
|
24
|
-
|
|
25
|
-
### Admin UI (lib/ui-routes/*, lib/routes-ui.js, workers/api.js; ~128 routes)
|
|
26
|
-
- Auth: session cookie (`ee`), TOTP, passkeys/WebAuthn (intentionally bypasses TOTP), OKTA OAuth2, pbkdf2 password, `passwordVersion` force-logout.
|
|
27
|
-
- CSRF via @hapi/crumb (skip-list: api/metrics/static/external tags).
|
|
28
|
-
- Config screens: webhooks, service, AI, logging/Sentry, license, OAuth apps, network/proxy, SMTP/IMAP-proxy servers, document-store (deprecated, self-gates off).
|
|
29
|
-
- Public (auth:false) flows: add-account wizard (HMAC-signed form), OAuth start/redirect (account creation), unsubscribe.
|
|
30
|
-
|
|
31
|
-
### Background workers & servers (workers/*, server.js, lib/webhooks.js, lib/export.js)
|
|
32
|
-
- Submit worker: BullMQ delivery, retry/backoff classification (`NON_RETRYABLE_CODES`, 5xx-not-503 -> discard).
|
|
33
|
-
- Webhooks worker: BullMQ delivery (10 attempts, HMAC sig), custom routes with sandboxed `fn`/`map` (SubScript/vm).
|
|
34
|
-
- Export worker: phased NDJSON export, gzip + optional AES-256-GCM, recovery, atomic concurrency Lua.
|
|
35
|
-
- SMTP server (MSA) + IMAP proxy: three auth modes each (global password / scoped hex token / header or passthrough).
|
|
36
|
-
- Documents worker: deprecated Elasticsearch indexing, gated off by default.
|
|
37
|
-
- server.js main process: worker spawn/health/restart, account assignment (load-aware round-robin + rendezvous reassignment), RPC with timeout.
|
|
38
|
-
|
|
39
|
-
### Core libraries (lib/*)
|
|
40
|
-
- oauth2-apps.js (OAuth2 app config + token orchestration, 5 providers, WIF, Pub/Sub IAM), oauth/* providers.
|
|
41
|
-
- tokens.js (API + session tokens, hashed storage), encrypt.js (AES-256-GCM), settings.js (encrypted keys).
|
|
42
|
-
- tools.js (binary sync-state serialize/unserialize, license verify, signed-form HMAC, glob matcher, redaction).
|
|
43
|
-
- bounce-detect.js / arf-detect.js (DSN + FBL parsing), add-trackers.js, get-raw-email.js, autodetect-imap-settings.js, rewrite-text-nodes.js, templates.js, redis-operations.js.
|
|
44
|
-
|
|
45
|
-
---
|
|
46
|
-
|
|
47
|
-
## 2. Current coverage assessment
|
|
48
|
-
|
|
49
|
-
Strong (real source imported, good cases):
|
|
50
|
-
- IMAP sync-strategy helpers, lost-index recovery, processChanges, null/event guards, mailbox-listing diff, Outlook folder encoding, label search filters, account-state helpers (email sync).
|
|
51
|
-
- Gmail Pub/Sub manager recovery, WIF external-account signer, OAuth token-request encoding + scope/nonce/error-status, tokens.js, encrypt.js, stream-encrypt, export.js internals + concurrency Lua, IMAP-proxy protocol hardening, redis-operations helpers, bounce/ARF structured (RFC 3464) parsing.
|
|
52
|
-
|
|
53
|
-
Thin or absent:
|
|
54
|
-
- Entire api-routes/ and ui-routes/ handler execution: exercised only via integration smoke (401-without-token + 200-with-`*`-token) and one e2e happy path. No scoped/cross-tenant token tests, no CSRF assertion, no POST mutation handlers, no parameterized routes.
|
|
55
|
-
- Send/submit pipeline, auth auto-disable, reconnect/backoff, Gmail history sync, Outlook subscription lifecycle: only the flaky non-hermetic live integration suite.
|
|
56
|
-
- SubScript sandbox, server.js account assignment/reassignment, SMTP/IMAP-proxy auth layers: zero tests.
|
|
57
|
-
- Large files barely touched: outlook-client.js (4584), gmail-client.js (3079), base-client.js (3279), imap/mailbox.js (3255), workers/api.js (3185), schemas.js (2497), tools.js (2372, ~27% of exports + all binary/crypto/async untested), oauth2-apps.js handler class, autodetect-imap-settings.js (779, 0 tests), get-raw-email.js (552, 0).
|
|
58
|
-
|
|
59
|
-
---
|
|
60
|
-
|
|
61
|
-
## 3. Cross-cutting findings
|
|
62
|
-
|
|
63
|
-
### 3a. "Illusory coverage" - tests that re-implement source instead of importing it
|
|
64
|
-
These pass green even when the shipping code breaks. Highest ROI to fix:
|
|
65
|
-
- `worker-not-available-test.js` - copies the submit discard predicate; omits the `NON_RETRYABLE_CODES` (EAUTH/EOAUTH2/ETLS/...) branch entirely.
|
|
66
|
-
- `autoreply-test.js` - re-defines `isAutoreply`; real `BaseClient.isAutoreply` (base-client.js:2173) untested.
|
|
67
|
-
- `complaint-test.js` - re-implements `mightBeAComplaint`; real wrapper untested (underlying arf-detect IS tested).
|
|
68
|
-
- `email-client-test.js` - defines its own PageCursor + constants; real Gmail `PageCursor` untested.
|
|
69
|
-
- `retry-logic-test.js` - defines its own `calculateBackoffDelay`/`simulateRequestWithRetry`; real Outlook `requestWithRetry` (outlook-client.js:222) untested.
|
|
70
|
-
|
|
71
|
-
### 3b. Auth boundaries asserted only at "401 without any token"
|
|
72
|
-
Scope enforcement, cross-account binding, CSRF, session invalidation, and the admin auth gate are never positively tested with real (scoped / cross-tenant / crumb-less) requests. The test prepared token decodes to `scopes:["*"]`, so every integration/e2e run is a full-root token.
|
|
73
|
-
|
|
74
|
-
### 3c. Latent bugs surfaced during the audit (not tests - fix separately)
|
|
75
|
-
- arf-detect.js:112 - reads `report['source-ip']` but writes `report.arf['source-ip']` (source IP never populated).
|
|
76
|
-
- worker-not-available-test.js silently omits a whole discard branch (see 3a).
|
|
77
|
-
- `mightBeABounce`/`mightBeAComplaint`/`mightBeDSNResponse` are duplicated in both base-client.js (2832-2890) and imap/mailbox.js (3056-3204) - drift risk; consolidate.
|
|
78
|
-
|
|
79
|
-
---
|
|
80
|
-
|
|
81
|
-
## 4. Prioritized test backlog
|
|
82
|
-
|
|
83
|
-
Priority = blast radius x regression likelihood x security sensitivity, weighted by cost-to-implement (cheap high-value first).
|
|
84
|
-
|
|
85
|
-
### P0 - Do first
|
|
86
|
-
|
|
87
|
-
| # | Test | Why | Type |
|
|
88
|
-
|---|------|-----|------|
|
|
89
|
-
| 1 | Fix the 5 "illusory coverage" tests to import real exports (submit discard incl. NON_RETRYABLE_CODES, isAutoreply, mightBeAComplaint, Gmail PageCursor, Outlook requestWithRetry) | False green today; cheapest possible win; unblocks trust in the suite | unit |
|
|
90
|
-
| 2 | SubScript sandbox (lib/sub-script.js) - timeout enforcement, no process/require/global escape, env/scriptEnv injection, payload isolation, compile-error caching | Arbitrary user JS runs in-process on every webhook; zero tests | unit |
|
|
91
|
-
| 3 | tools.serialize / unserialize round-trip - UID+flags+modseq+msgpack, D/N sentinels, BigInt modseq | Corrupts sync state for ALL accounts (dup/dropped messages + webhooks); zero tests; pure/cheap | unit |
|
|
92
|
-
| 4 | API token scope enforcement + cross-account binding (workers/api.js:1106,1121-1170) - smtp/imap-proxy-only token must 403 on /v1/*; account token must 403 on a different account; template special-casing | Core security boundaries, tested only at 401-without-token; provision tokens via lib/tokens.provision() in existing smoke harness | integration |
|
|
93
|
-
| 5 | Admin UI auth gate + CSRF + passwordVersion - boot server WITH admin password: anonymous /admin/* -> 302 login; crumb-less POST -> 403; passwordVersion bump invalidates old cookie | Closes the 3 highest-blast-radius UI gaps at once; a regression making admin world-readable passes all current tests | integration |
|
|
94
|
-
|
|
95
|
-
### P1 - High
|
|
96
|
-
|
|
97
|
-
| # | Test | Why | Type |
|
|
98
|
-
|---|------|-----|------|
|
|
99
|
-
| 6 | Send/submit pipeline + idempotency (base-client.js submitMessage/queueMessageEntry/handleSubmitError, checkIdempotencyKey) - permanent-5xx vs transient, Sent-folder upload, reference flags, gateway stats | Data loss / duplicate sends; only happy-path live coverage | unit + 1 integration error path |
|
|
100
|
-
| 7 | server.js account assignment & reassignment (assignAccounts, rendezvous reassign trigger, call-failure rollback, worker-exit -> unassigned, 10s failsafe, health -> restart) | Highest orchestration blast radius (one routing bug hits all accounts); zero tests | unit (extract) / integration with fake workers |
|
|
101
|
-
| 8 | setErrorState auth-failure auto-disable (base-client.js:383) - error-count, same-error dedupe, MAX_IMAP_AUTH_FAILURE_TIME threshold, disable+close | Safety mechanism vs reconnect storms; untested | unit (mock redis txn + clock) |
|
|
102
|
-
| 9 | SMTP server + IMAP-proxy AUTH layers (workers/smtp.js:112-246, imapproxy/imap-server.js:153-247) - global password, scoped hex token, account==username, IP restriction, API-only rejection | Auth-bypass surface; protocol hardening is tested but auth is not | integration |
|
|
103
|
-
| 10 | Bulk message mutate/delete REST (message-routes.js PUT /messages, /messages/move, /messages/delete?force) | Highest data-loss blast radius among untested endpoints; matches prior Outlook bulk-delete finding | integration |
|
|
104
|
-
| 11 | bounce-detect text-heuristic fallback (~13 vendor matchers: Exim/Postfix/Google/KDDI/Verizon/James/generic 5xx, bounce-detect.js:417-832) | Largest real-world regression surface; regex-fragile (ReDoS-hardened, no regression test) | unit (fixtures) |
|
|
105
|
-
| 12 | OAuth2AppsHandler stateful core (oauth2-apps.js create/update/del encryption, getServiceAccessToken caching/lock:1641, getClient per-provider:1422) + Gmail/Outlook checkForFlags error->flag mapping | Mis-stored/plaintext creds, token stampede, wrong auth flags; only leaf helpers tested today | unit |
|
|
106
|
-
| 13 | Gmail history sync (processHistory/processHistoryEntry, gmail-client.js:2737-3001) + Outlook subscription lifecycle (renewSubscription/ensureSubscription/syncMissedMessages, outlook-client.js:3224-3971) | Core real-time correctness; only flaky live coverage; silent event loss | unit (mock request) |
|
|
107
|
-
| 14 | IMAP reconnect/backoff + error->state classification (imap-client.js reconnect:910, start() catch:1557) | Timing-sensitive; high regression likelihood | unit (fake timers) |
|
|
108
|
-
|
|
109
|
-
### P2 - Medium
|
|
110
|
-
|
|
111
|
-
| # | Test | Why | Type |
|
|
112
|
-
|---|------|-----|------|
|
|
113
|
-
| 15 | bull-board auth (/admin/bull-board/* relies only on default session guard) | Queue job payloads (recipients/message data) leak if guard regresses | integration |
|
|
114
|
-
| 16 | chat / unified-search REST doc-store gating (/v1/chat 404 + /v1/unified/search runtime-404 when feature off) | doc-store-disabled test covers UI only | route-table + integration |
|
|
115
|
-
| 17 | Secret masking on read (GET /v1/account, /v1/oauth2 -> ******) | Assert secrets never round-trip cleartext | integration |
|
|
116
|
-
| 18 | Public account-setup HMAC verification (/accounts/new/imap/server, POST /v1/authentication/form) + signed-form replay/TTL/nonce | Unauth account creation + credential write if sig check regresses | integration + unit |
|
|
117
|
-
| 19 | settings.js secret encrypt/decrypt + POST /v1/settings write broadcast | Silent corruption of stored OAuth secrets/serviceSecret; global blast radius | unit + integration |
|
|
118
|
-
| 20 | Security redaction units: formatPartialSecretKey, add-trackers redirect rewriting (open-redirect via /redirect), get-raw-email X-EE-*/BCC stripping | Header/secret leakage on every outbound message | unit |
|
|
119
|
-
| 21 | UIDVALIDITY-change full-resync branch (mailbox.js onOpen:2102-2127) | Distinct from lost-index reseed; wrong handling re-floods or drops messages | unit |
|
|
120
|
-
| 22 | Export recovery + encryption end-to-end (markInterruptedAsFailed, gzip->encrypt->decryptable artifact, lease extension) | Classifiers tested in isolation; recovery flow not | integration |
|
|
121
|
-
| 23 | Webhook custom-route fn/map filter/transform end-to-end + payload formatting/truncation + route-disable-on-compile-error + HMAC sig value | Handler cache tested; actual filter/transform behavior not | unit/integration |
|
|
122
|
-
| 24 | autodetect-imap-settings.js (779 LOC, 0 tests) - provider table, autoconfig XML substitution, escapeXml autodiscover injection, SRV parsing | Every new-account config; high churn; injection surface | unit (stub dns/undici) |
|
|
123
|
-
| 25 | smtp-pool-manager generatePoolKey (credential isolation) + cleanupIdlePools | Pool-key collision could cross-send via wrong account | unit |
|
|
124
|
-
| 26 | Broad POST mutation + parameterized route execution (token provision/delete, account delete/edit, gateway/oauth/webhook/template CRUD, network config) with a prepared session | ~20 handlers only snapshot-checked, never run | integration / e2e |
|
|
125
|
-
| 27 | gateway CRUD + delivery-stats hincrby + encrypted-pass roundtrip | Holds SMTP creds; only route-name smoke today | unit/integration |
|
|
126
|
-
|
|
127
|
-
### P3 - Lower / opportunistic
|
|
128
|
-
|
|
129
|
-
- message-builder.js + notification-handler.js builders (synchronous, cheap; payload contract).
|
|
130
|
-
- export-routes / outbox / blocklist / template / license HTTP behavior (404 + force semantics + download stream).
|
|
131
|
-
- redis-url parsing, redis-scan-delete batching, reconnection-manager backoff cap, rate-limit bucket math, capa CSV parser, templates CRUD.
|
|
132
|
-
- arf-detect edge branches (and fix the source-ip read/write bug, 3c).
|
|
133
|
-
- OKTA login flow, disableTokens open-API mode, sess_ browse round-trip, requireTotp path-allowlist correctness.
|
|
134
|
-
- mergeObjects prototype-pollution guard, comparePattern/matcher glob+LRU, checkLicense ECDSA verify.
|
|
135
|
-
- Documents/ES enabled path (deprecated, off by default - lowest priority).
|
|
136
|
-
|
|
137
|
-
---
|
|
138
|
-
|
|
139
|
-
## 5. Suggested sequencing
|
|
140
|
-
|
|
141
|
-
1. Land P0 #1 (illusory-coverage fixes) immediately - cheapest, removes false confidence, and #1's submit/autoreply/complaint cases overlap with P1 #6/#11.
|
|
142
|
-
2. P0 #2/#3 (SubScript, serialize) - pure units, high blast radius, no infra needed.
|
|
143
|
-
3. P0 #4/#5 + P2 #15/#16/#17/#26 share one new integration harness: boot the test server with an admin password and provision scoped tokens via lib/tokens.provision(). Build that harness once, then the auth/scope/CSRF/masking/gating tests are incremental.
|
|
144
|
-
4. P1 #6-#14 are the email-engine correctness core; most are unit-testable with mocked redis/transport/request and benefit from extracting pure logic out of the giant client files as you go.
|
|
145
|
-
|
|
146
|
-
---
|
|
147
|
-
|
|
148
|
-
## 6. Implementation status (2026-06-16)
|
|
149
|
-
|
|
150
|
-
Branch `test-coverage-p0-p1`. Each test file was verified to pass individually
|
|
151
|
-
(the full local suite cannot run all files in parallel on a dev machine due to
|
|
152
|
-
process-isolation + Redis connection accumulation; CI runs the unit tier in a
|
|
153
|
-
clean dedicated job). Source changes are additive exports or behavior-preserving
|
|
154
|
-
extractions, verified not to break existing consumers.
|
|
155
|
-
|
|
156
|
-
Done (committed):
|
|
157
|
-
- P0 #1 - illusory-coverage tests now exercise real code (submit discard via new
|
|
158
|
-
lib/delivery-error.js incl. NON_RETRYABLE_CODES; isAutoreply; Mailbox
|
|
159
|
-
mightBeAComplaint + base-client drift; Gmail PageCursor; Outlook
|
|
160
|
-
requestWithRetry incl. transient-network branch).
|
|
161
|
-
- P0 #2 - SubScript sandbox (timeout, context isolation, env, compile cache).
|
|
162
|
-
- P0 #3 - tools.serialize/unserialize round-trip.
|
|
163
|
-
- P0 #4 - API token scope enforcement + cross-account binding (integration).
|
|
164
|
-
- P0 #5 - admin CSRF crumb enforcement (integration). [partial]
|
|
165
|
-
- P1 #8 - setErrorState auth-failure tracking + IMAP auto-disable.
|
|
166
|
-
- P1 #11 - bounce-detect text-heuristic fallback.
|
|
167
|
-
- P1 #12 - Gmail/Outlook checkForFlags/checkForUserFlags error mapping. [partial]
|
|
168
|
-
- P1 #14 - ReconnectionManager backoff/jitter/reset. [partial]
|
|
169
|
-
- P1 #6 - idempotency-key handling (duplicate-submission guard). [partial]
|
|
170
|
-
|
|
171
|
-
Remaining (deferred, with reason):
|
|
172
|
-
- P0 #5 remainder - anonymous /admin/* -> 302 redirect and passwordVersion
|
|
173
|
-
session invalidation need an isolated server WITH an admin password; belongs
|
|
174
|
-
in the Playwright e2e suite (cannot verify locally without Chromium + the
|
|
175
|
-
external trial endpoint). The shared integration server is password-less by
|
|
176
|
-
design, so these must not mutate its global auth state.
|
|
177
|
-
- P1 #6 remainder - full submitMessage pipeline (permanent-vs-transient retry,
|
|
178
|
-
Sent-folder upload, reference flags, gateway stats): large surface in a
|
|
179
|
-
3.3k-line client, heavy transport/Redis mocking.
|
|
180
|
-
- P1 #7 - server.js account assignment/reassignment: highest blast radius but
|
|
181
|
-
the orchestration is entangled with module state; needs logic extraction (a
|
|
182
|
-
refactor of a critical orchestrator) or a fake-worker harness.
|
|
183
|
-
- P1 #9 - SMTP server + IMAP-proxy auth: those servers are not enabled in the
|
|
184
|
-
shared test config; needs a dedicated server boot with them enabled.
|
|
185
|
-
- P1 #10 - bulk message mutate/delete REST: needs a connected mailbox with
|
|
186
|
-
messages; not meaningfully testable against the credential-less test server.
|
|
187
|
-
- P1 #12 remainder - OAuth2AppsHandler CRUD encryption / getServiceAccessToken
|
|
188
|
-
caching / getClient: stateful, needs Redis + secret + provider mocking.
|
|
189
|
-
- P1 #13 - Gmail history sync + Outlook subscription lifecycle: heavy mocking of
|
|
190
|
-
the 3k-4.5k-line client classes.
|
|
191
|
-
- P1 #14 remainder - imap-client reconnect() method + start() error->state
|
|
192
|
-
classification: needs an IMAPClient instance with a mocked ImapFlow + fake
|
|
193
|
-
timers.
|
|
194
|
-
|
|
195
|
-
Guiding constraint: no unverified or fragile tests were committed. The deferred
|
|
196
|
-
items each require infrastructure (extra server, live mailbox, orchestrator
|
|
197
|
-
refactor, or large-class mocking) beyond what a test can assert reliably in this
|
|
198
|
-
environment.
|
|
199
|
-
|
|
200
|
-
## 7. Deferred-item follow-up (2026-06-16, same branch)
|
|
201
|
-
|
|
202
|
-
A second pass converted most of the deferred items into verified tests by
|
|
203
|
-
extracting testable units (leaf workers only - never server.js) and using the
|
|
204
|
-
real handlers against the test Redis:
|
|
205
|
-
|
|
206
|
-
Done (committed):
|
|
207
|
-
- P1 #12 remainder - OAuth2AppsHandler create/get/update/list/del with
|
|
208
|
-
credential encryption at rest (oauth2-apps-crud-test.js).
|
|
209
|
-
- P1 #9 - SMTP auth (extracted lib/smtp-auth.js) and IMAP-proxy auth (extracted
|
|
210
|
-
lib/imap-proxy-auth.js): rejection paths (password/token account/scope/IP) and
|
|
211
|
-
accept paths, plus the IMAP-proxy API-only-account ACCOUNTDISABLED rejection.
|
|
212
|
-
- P1 #14 remainder - IMAPClient.reconnect() guard logic (no double-connect /
|
|
213
|
-
reconnect-storm), via the prototype with start() stubbed.
|
|
214
|
-
- P1 #13 (partial) - Gmail flag/label mapping (flagToLabel/flagsToLabelIds incl.
|
|
215
|
-
inverse \Seen<->UNREAD and set precedence) and Outlook parseExpirationDate.
|
|
216
|
-
- P1 #6 (decision logic) - message-builder send-pipeline deciders
|
|
217
|
-
(SentMailCopyDecider, ProviderMessageIdHandler, SmtpErrorBuilder,
|
|
218
|
-
NetworkRoutingBuilder, NotificationBuilder).
|
|
219
|
-
|
|
220
|
-
Still remaining (genuinely blocked):
|
|
221
|
-
- P1 #7 - server.js account assignment: the assignAccounts loop is entangled
|
|
222
|
-
with module state and per-iteration rollback; a faithful extraction risks
|
|
223
|
-
changing assignment behavior on worker-crash recovery (highest blast radius).
|
|
224
|
-
Not done autonomously - needs a reviewed refactor. The consistency-critical
|
|
225
|
-
half (rendezvous reassignment) is already covered by tools-test.js.
|
|
226
|
-
- P1 #6 remainder - the full submitMessage orchestration (actual SMTP send +
|
|
227
|
-
retry loop) - decision logic is now covered; the glue needs integration/e2e.
|
|
228
|
-
- P1 #13 remainder - Gmail processHistoryEntry / Outlook renew-subscription
|
|
229
|
-
orchestration: multi-step async over 3k-4.5k-line client classes.
|
|
230
|
-
- P0 #5 remainder / P1 #10 - e2e auth-gate + passwordVersion and bulk-message
|
|
231
|
-
REST: need the Playwright e2e instance (isolated server with a password and a
|
|
232
|
-
live mailbox) which depends on Chromium + external endpoints not reliably
|
|
233
|
-
reachable here.
|