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
|
@@ -18,12 +18,15 @@ const getSecret = require('../get-secret');
|
|
|
18
18
|
const capa = require('../capa');
|
|
19
19
|
const { Account } = require('../account');
|
|
20
20
|
const { Gateway } = require('../gateway');
|
|
21
|
-
const { autodetectImapSettings } = require('../autodetect-imap-settings');
|
|
21
|
+
const { autodetectImapSettings, resolveAppPassword, getAppPassword } = require('../autodetect-imap-settings');
|
|
22
|
+
const { atomicIncrement } = require('../redis-operations');
|
|
22
23
|
const { oauth2Apps, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
|
|
23
24
|
const {
|
|
24
25
|
getServiceHostname,
|
|
25
26
|
getSignedFormData,
|
|
26
27
|
parseSignedFormData,
|
|
28
|
+
claimFormNonce,
|
|
29
|
+
releaseFormNonce,
|
|
27
30
|
getLogs,
|
|
28
31
|
verifyAccountInfo,
|
|
29
32
|
flattenObjectKeys,
|
|
@@ -31,13 +34,53 @@ const {
|
|
|
31
34
|
readEnvValue,
|
|
32
35
|
failAction
|
|
33
36
|
} = require('../tools');
|
|
34
|
-
const { settingsSchema, accountIdSchema, defaultAccountTypeSchema, ACCOUNT_DISPLAY_STATES } = require('../schemas');
|
|
37
|
+
const { settingsSchema, accountIdSchema, defaultAccountTypeSchema, ACCOUNT_DISPLAY_STATES, signedFormBlobFields: signedBlobFields } = require('../schemas');
|
|
35
38
|
const { formatAccountData, cachedTemplates } = require('./route-helpers');
|
|
36
39
|
|
|
37
|
-
const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, DEFAULT_MAX_LOG_LINES } = consts;
|
|
40
|
+
const { REDIS_PREFIX, DEFAULT_PAGE_SIZE, NONCE_BYTES, MAX_FORM_TTL, MAX_FORM_PROBE_ATTEMPTS, DEFAULT_MAX_LOG_LINES } = consts;
|
|
38
41
|
|
|
39
42
|
const DISABLE_MESSAGE_BROWSER = getBoolean(readEnvValue('EENGINE_DISABLE_MESSAGE_BROWSER'));
|
|
40
43
|
|
|
44
|
+
// Per-API-worker, in-process memo for the custom-domain app-password hint resolved on the page-2
|
|
45
|
+
// failAction re-render. The hint is cosmetic (a provider label/instructions from a static table), but
|
|
46
|
+
// resolving it for a custom domain costs a signed-probe authorization (Redis + HMAC, drawing the shared
|
|
47
|
+
// per-nonce probe budget) plus a DNS MX lookup that blocks the error page up to APP_PASSWORD_MX_TIMEOUT.
|
|
48
|
+
// A struggling user re-submits the same email repeatedly, so cache the resolved hint (including a
|
|
49
|
+
// negative result) by lowercased domain to avoid repeating that work and burning the probe budget on
|
|
50
|
+
// cosmetics. Values are static-table constants, so a cached hit is byte-identical to a fresh resolve.
|
|
51
|
+
const APP_PASSWORD_HINT_CACHE = new Map();
|
|
52
|
+
const APP_PASSWORD_HINT_TTL = 10 * 60 * 1000;
|
|
53
|
+
// Bound the memo so a long-lived API worker cannot accumulate one entry per distinct custom domain
|
|
54
|
+
// forever. Writes are already gated behind a signed probe + the per-nonce cap, so cardinality tracks
|
|
55
|
+
// legitimate setup-link issuance, but this caps the worst case. FIFO eviction (Map preserves insertion
|
|
56
|
+
// order) is fine for a cosmetic hint cache.
|
|
57
|
+
const APP_PASSWORD_HINT_MAX_ENTRIES = 1000;
|
|
58
|
+
|
|
59
|
+
function getCachedAppPasswordHint(domain) {
|
|
60
|
+
const entry = APP_PASSWORD_HINT_CACHE.get(domain);
|
|
61
|
+
if (!entry) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
if (entry.expires > Date.now()) {
|
|
65
|
+
return entry;
|
|
66
|
+
}
|
|
67
|
+
APP_PASSWORD_HINT_CACHE.delete(domain);
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function setCachedAppPasswordHint(domain, value) {
|
|
72
|
+
// delete-then-set keeps insertion order meaningful (a refreshed domain becomes newest) and avoids
|
|
73
|
+
// over-evicting when we are only updating an existing entry.
|
|
74
|
+
APP_PASSWORD_HINT_CACHE.delete(domain);
|
|
75
|
+
if (APP_PASSWORD_HINT_CACHE.size >= APP_PASSWORD_HINT_MAX_ENTRIES) {
|
|
76
|
+
const oldest = APP_PASSWORD_HINT_CACHE.keys().next().value;
|
|
77
|
+
if (oldest !== undefined) {
|
|
78
|
+
APP_PASSWORD_HINT_CACHE.delete(oldest);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
APP_PASSWORD_HINT_CACHE.set(domain, { value, expires: Date.now() + APP_PASSWORD_HINT_TTL });
|
|
82
|
+
}
|
|
83
|
+
|
|
41
84
|
async function getMailboxListing(accountObject) {
|
|
42
85
|
let mailboxes = [
|
|
43
86
|
{
|
|
@@ -327,6 +370,12 @@ function init(args) {
|
|
|
327
370
|
});
|
|
328
371
|
|
|
329
372
|
async function accountFormHandler(request, h) {
|
|
373
|
+
// Intentionally parsed WITHOUT requireNonce (unlike the IMAP-arm endpoints). This OAuth entry must
|
|
374
|
+
// keep accepting legacy / pre-upgrade re-auth blobs that carry no n/t - requiring a nonce here
|
|
375
|
+
// would 403 the account page's "Re-authenticate" button across a rolling upgrade and break
|
|
376
|
+
// still-circulating pre-v2.39 OAuth setup links. Replay safety is enforced downstream instead: the
|
|
377
|
+
// OAuth callback (workers/api.js) claims the form nonce atomically (SET NX before create) when one
|
|
378
|
+
// is present. Do NOT add requireNonce here without re-checking that compat impact.
|
|
330
379
|
const data = await parseSignedFormData(redis, request.payload, request.app.gt);
|
|
331
380
|
|
|
332
381
|
const oauth2App = await oauth2Apps.get(request.payload.type);
|
|
@@ -414,6 +463,12 @@ function init(args) {
|
|
|
414
463
|
);
|
|
415
464
|
}
|
|
416
465
|
|
|
466
|
+
// signedBlobFields (the base64url data + HMAC sig carried by every hosted-form page) is imported from
|
|
467
|
+
// lib/schemas.js as signedFormBlobFields and spread into each schema below, so the security-relevant
|
|
468
|
+
// field definitions cannot drift across the auth:false endpoints (or from the sibling unsubscribe-routes
|
|
469
|
+
// copy). Both fields are required: every issuer signs unconditionally and every template renders the sig
|
|
470
|
+
// hidden input, so a request without one is always hand-crafted.
|
|
471
|
+
|
|
417
472
|
server.route({
|
|
418
473
|
method: 'GET',
|
|
419
474
|
path: '/accounts/new',
|
|
@@ -467,8 +522,7 @@ function init(args) {
|
|
|
467
522
|
},
|
|
468
523
|
|
|
469
524
|
query: Joi.object({
|
|
470
|
-
|
|
471
|
-
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true }),
|
|
525
|
+
...signedBlobFields,
|
|
472
526
|
type: defaultAccountTypeSchema
|
|
473
527
|
})
|
|
474
528
|
}
|
|
@@ -500,8 +554,7 @@ function init(args) {
|
|
|
500
554
|
},
|
|
501
555
|
|
|
502
556
|
payload: Joi.object({
|
|
503
|
-
|
|
504
|
-
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true }),
|
|
557
|
+
...signedBlobFields,
|
|
505
558
|
type: Joi.string()
|
|
506
559
|
.empty('')
|
|
507
560
|
.allow(false)
|
|
@@ -515,12 +568,139 @@ function init(args) {
|
|
|
515
568
|
}
|
|
516
569
|
});
|
|
517
570
|
|
|
571
|
+
// Shared by this route's payload validation and its failAction re-render (same rationale as
|
|
572
|
+
// serverFormSchema below), so the re-rendered first page is built from the same schema that validated
|
|
573
|
+
// the submission rather than echoing the raw payload.
|
|
574
|
+
const firstPageSchema = Joi.object({
|
|
575
|
+
...signedBlobFields,
|
|
576
|
+
name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
|
|
577
|
+
email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
|
|
578
|
+
password: Joi.string().max(1024).min(1).required().example('secret').label('Password').description('Your account password')
|
|
579
|
+
});
|
|
580
|
+
|
|
581
|
+
// Shared IMAP/SMTP connection fields for the hosted form's /imap/test and /imap/server routes, so the
|
|
582
|
+
// two payload schemas (and their failAction re-renders) are built from one definition and cannot drift.
|
|
583
|
+
// The tri-state booleans list '0' as falsy (a string a non-browser client may submit symmetric with the
|
|
584
|
+
// truthy '1'); without it '0' would fail coercion and re-render a checkbox as checked.
|
|
585
|
+
const connectionFields = {
|
|
586
|
+
imap_auth_user: Joi.string().empty('').trim().max(1024).required(),
|
|
587
|
+
imap_auth_pass: Joi.string().empty('').max(1024).required(),
|
|
588
|
+
imap_host: Joi.string().hostname().required().example('imap.gmail.com').description('Hostname to connect to').label('IMAP host'),
|
|
589
|
+
imap_port: Joi.number()
|
|
590
|
+
.integer()
|
|
591
|
+
.min(1)
|
|
592
|
+
.max(64 * 1024)
|
|
593
|
+
.required()
|
|
594
|
+
.example(993)
|
|
595
|
+
.description('Service port number')
|
|
596
|
+
.label('IMAP port'),
|
|
597
|
+
imap_secure: Joi.boolean()
|
|
598
|
+
.truthy('Y', 'true', '1', 'on')
|
|
599
|
+
.falsy('N', 'false', '0', 0, '')
|
|
600
|
+
.default(false)
|
|
601
|
+
.example(true)
|
|
602
|
+
.description('Should connection use TLS. Usually true for port 993')
|
|
603
|
+
.label('IMAP TLS'),
|
|
604
|
+
imap_disabled: Joi.boolean()
|
|
605
|
+
.truthy('Y', 'true', '1', 'on')
|
|
606
|
+
.falsy('N', 'false', '0', 0, '')
|
|
607
|
+
.default(false)
|
|
608
|
+
.example(true)
|
|
609
|
+
.description('Disable IMAP if you are using this email account to only send emails.')
|
|
610
|
+
.label('IMAP disabled'),
|
|
611
|
+
smtp_auth_user: Joi.string().empty('').trim().max(1024).required(),
|
|
612
|
+
smtp_auth_pass: Joi.string().empty('').max(1024).required(),
|
|
613
|
+
smtp_host: Joi.string().hostname().required().example('smtp.gmail.com').description('Hostname to connect to').label('SMTP host'),
|
|
614
|
+
smtp_port: Joi.number()
|
|
615
|
+
.integer()
|
|
616
|
+
.min(1)
|
|
617
|
+
.max(64 * 1024)
|
|
618
|
+
.required()
|
|
619
|
+
.example(465)
|
|
620
|
+
.description('Service port number')
|
|
621
|
+
.label('SMTP port'),
|
|
622
|
+
smtp_secure: Joi.boolean()
|
|
623
|
+
.truthy('Y', 'true', '1', 'on')
|
|
624
|
+
.falsy('N', 'false', '0', 0, '')
|
|
625
|
+
.default(false)
|
|
626
|
+
.example(true)
|
|
627
|
+
.description('Should connection use TLS. Usually true for port 465')
|
|
628
|
+
.label('SMTP TLS')
|
|
629
|
+
};
|
|
630
|
+
|
|
631
|
+
// Rebuild safe re-render values from the SAME schema that validated the submission: convert coerces the
|
|
632
|
+
// tri-state TLS/disabled checkboxes to real booleans (so {{#if values.X}} cannot re-check a box from the
|
|
633
|
+
// string 'false'), and stripUnknown drops unexpected / prototype keys (and the appPassword_* hint fields)
|
|
634
|
+
// before they can reach the unescaped template sinks. Keys that FAILED validation are dropped too: Joi
|
|
635
|
+
// keeps the raw submitted value for a failed coercion (e.g. the string 'no' for a tri-state boolean, or
|
|
636
|
+
// an array from duplicated form fields), and rendering that raw value would re-check a cleared checkbox
|
|
637
|
+
// or corrupt the hidden data/sig inputs - a failed key re-renders empty instead. The named secret fields
|
|
638
|
+
// are then dropped so a plaintext credential is never echoed back into the HTML. `value` is null when
|
|
639
|
+
// request.payload is null (a bodyless POST), so fall back to {} before mutating.
|
|
640
|
+
const rebuildFormValues = (schema, payload, secretFields) => {
|
|
641
|
+
const { value, error } = schema.validate(payload, { convert: true, stripUnknown: true, abortEarly: false });
|
|
642
|
+
const values = value || {};
|
|
643
|
+
if (error && error.details) {
|
|
644
|
+
for (let detail of error.details) {
|
|
645
|
+
if (detail.path && detail.path.length) {
|
|
646
|
+
delete values[detail.path[0]];
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
for (let field of secretFields || []) {
|
|
651
|
+
delete values[field];
|
|
652
|
+
}
|
|
653
|
+
return values;
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
// Bound the number of outbound-probe requests per issued form blob, shared by the auth:false endpoints
|
|
657
|
+
// that drive outbound network from an attacker-controllable host/domain: POST /accounts/new/imap
|
|
658
|
+
// (email autodiscovery) and POST /accounts/new/imap/test (connection test). Both authorize by signature
|
|
659
|
+
// but do not consume the single-use nonce, so without this a leaked signed link is an unlimited
|
|
660
|
+
// SSRF/port-scan oracle. One shared counter per nonce means pivoting between the two endpoints cannot
|
|
661
|
+
// reset the cap. Fail open on a Redis error - the cap is defense-in-depth, not correctness.
|
|
662
|
+
const enforceFormProbeLimit = async (nonce, gt, logger) => {
|
|
663
|
+
let count = 0;
|
|
664
|
+
try {
|
|
665
|
+
const counted = await atomicIncrement(redis, `${REDIS_PREFIX}account:form:probe:${nonce}`, 1, Math.floor(MAX_FORM_TTL / 1000));
|
|
666
|
+
if (counted.success) {
|
|
667
|
+
count = counted.value;
|
|
668
|
+
}
|
|
669
|
+
} catch (err) {
|
|
670
|
+
logger.error({ msg: 'Failed to count outbound form probes', err });
|
|
671
|
+
}
|
|
672
|
+
if (count > MAX_FORM_PROBE_ATTEMPTS) {
|
|
673
|
+
// The cap is keyed on the nonce inside the signed blob, so reloading the same link keeps the
|
|
674
|
+
// same nonce and stays capped - the caller needs a freshly issued setup link.
|
|
675
|
+
//
|
|
676
|
+
// Reviewed, accepted (do not "fix" by removing the cap): for an API-issued link the end user
|
|
677
|
+
// cannot self-recover once exhausted and must go back to the integrator for a fresh link. This
|
|
678
|
+
// is bounded by the link's <=24h TTL, the account-creating submit itself does not draw from the
|
|
679
|
+
// budget, and the app-password hint memo (APP_PASSWORD_HINT_CACHE) keeps error re-renders from
|
|
680
|
+
// burning it on cosmetics. If this ever bites real users, tune MAX_FORM_PROBE_ATTEMPTS or scope
|
|
681
|
+
// the budget per-endpoint rather than dropping the SSRF/port-scan defense.
|
|
682
|
+
throw Boom.boomify(new Error(gt.gettext('Too many attempts for this setup link. Request a new setup link to continue.')), { statusCode: 429 });
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
// The authorization gate for every outbound-probe-driving call in this file: a valid signed blob
|
|
687
|
+
// WITH a nonce (requireNonce guarantees data.n) plus the shared per-nonce probe cap. Keep the two
|
|
688
|
+
// paired through this helper - a probe site that checks the signature but skips the cap silently
|
|
689
|
+
// reopens the unbounded-probe hole. Throws Boom 403/429; returns the parsed blob.
|
|
690
|
+
const authorizeSignedProbe = async (payload, gt, logger) => {
|
|
691
|
+
const data = await parseSignedFormData(redis, payload, gt, { requireNonce: true });
|
|
692
|
+
await enforceFormProbeLimit(data.n, gt, logger);
|
|
693
|
+
return data;
|
|
694
|
+
};
|
|
695
|
+
|
|
518
696
|
server.route({
|
|
519
697
|
method: 'POST',
|
|
520
698
|
path: '/accounts/new/imap',
|
|
521
699
|
|
|
522
700
|
async handler(request, h) {
|
|
523
|
-
|
|
701
|
+
// Bound outbound autodiscovery per issued blob (shared cap with the connection tester) so a
|
|
702
|
+
// leaked signed link cannot drive unlimited outbound probes to arbitrary domains.
|
|
703
|
+
await authorizeSignedProbe(request.payload, request.app.gt, request.logger);
|
|
524
704
|
|
|
525
705
|
let serverSettings;
|
|
526
706
|
try {
|
|
@@ -592,12 +772,19 @@ function init(args) {
|
|
|
592
772
|
await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't set up account. Try again.") });
|
|
593
773
|
request.logger.error({ msg: 'Failed to process account', err });
|
|
594
774
|
|
|
775
|
+
// Repopulate the form (crucially the signed data/sig blob) from what was submitted;
|
|
776
|
+
// without it the hidden inputs render empty and the corrected re-submit fails the
|
|
777
|
+
// required `data` check, leaving the user stuck. rebuildFormValues rebuilds from the same
|
|
778
|
+
// schema that validated the submission and drops the plaintext password.
|
|
779
|
+
const values = rebuildFormValues(firstPageSchema, request.payload, ['password']);
|
|
780
|
+
|
|
595
781
|
return h
|
|
596
782
|
.view(
|
|
597
783
|
'accounts/register/imap',
|
|
598
784
|
{
|
|
599
785
|
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
600
|
-
errors
|
|
786
|
+
errors,
|
|
787
|
+
values
|
|
601
788
|
},
|
|
602
789
|
{
|
|
603
790
|
layout: 'public'
|
|
@@ -606,13 +793,7 @@ function init(args) {
|
|
|
606
793
|
.takeover();
|
|
607
794
|
},
|
|
608
795
|
|
|
609
|
-
payload:
|
|
610
|
-
data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
|
|
611
|
-
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true }),
|
|
612
|
-
name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
|
|
613
|
-
email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
|
|
614
|
-
password: Joi.string().max(1024).min(1).required().example('secret').label('Password').description('Your account password')
|
|
615
|
-
})
|
|
796
|
+
payload: firstPageSchema
|
|
616
797
|
}
|
|
617
798
|
}
|
|
618
799
|
});
|
|
@@ -622,6 +803,25 @@ function init(args) {
|
|
|
622
803
|
path: '/accounts/new/imap/test',
|
|
623
804
|
async handler(request) {
|
|
624
805
|
try {
|
|
806
|
+
// Require a valid signed form blob (throws Boom 403 on failure). Without this an
|
|
807
|
+
// unauthenticated caller could drive outbound IMAP/SMTP connections to arbitrary
|
|
808
|
+
// hosts (SSRF / internal port scan / credential relay); the hosted form always
|
|
809
|
+
// submits the signed data/sig it was issued.
|
|
810
|
+
//
|
|
811
|
+
// NB: this is an AUTHORIZATION gate, not egress filtering. A caller holding a valid
|
|
812
|
+
// signed link can still point imap_host/smtp_host at an internal address, because
|
|
813
|
+
// verifyAccountInfo connects to whatever host it is given (see the matching note there).
|
|
814
|
+
// That residual is accepted by design: EmailEngine is normally deployed as an isolated
|
|
815
|
+
// instance with no local mail servers to reach, so blocking private/loopback IPs would
|
|
816
|
+
// break the legitimate "connect to my own mail server" flow far more often than it would
|
|
817
|
+
// stop a real probe. If you run EmailEngine next to sensitive internal services, isolate
|
|
818
|
+
// it at the network layer rather than expecting this gate to filter egress.
|
|
819
|
+
//
|
|
820
|
+
// The gate authorizes the caller but does not consume the single-use nonce: the form
|
|
821
|
+
// legitimately tests a connection several times before submitting, so the shared
|
|
822
|
+
// per-nonce probe cap (inside authorizeSignedProbe) bounds replays instead.
|
|
823
|
+
await authorizeSignedProbe(request.payload, request.app.gt, request.logger);
|
|
824
|
+
|
|
625
825
|
let verifyResult = await verifyAccountInfo(
|
|
626
826
|
redis,
|
|
627
827
|
{
|
|
@@ -721,59 +921,30 @@ function init(args) {
|
|
|
721
921
|
failAction,
|
|
722
922
|
|
|
723
923
|
payload: Joi.object({
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
imap_host: Joi.string().hostname().required().example('imap.gmail.com').description('Hostname to connect to').label('IMAP host'),
|
|
727
|
-
imap_port: Joi.number()
|
|
728
|
-
.integer()
|
|
729
|
-
.min(1)
|
|
730
|
-
.max(64 * 1024)
|
|
731
|
-
.required()
|
|
732
|
-
.example(993)
|
|
733
|
-
.description('Service port number')
|
|
734
|
-
.label('IMAP port'),
|
|
735
|
-
imap_secure: Joi.boolean()
|
|
736
|
-
.truthy('Y', 'true', '1', 'on')
|
|
737
|
-
.falsy('N', 'false', 0, '')
|
|
738
|
-
.default(false)
|
|
739
|
-
.example(true)
|
|
740
|
-
.description('Should connection use TLS. Usually true for port 993'),
|
|
741
|
-
imap_disabled: Joi.boolean()
|
|
742
|
-
.truthy('Y', 'true', '1', 'on')
|
|
743
|
-
.falsy('N', 'false', 0, '')
|
|
744
|
-
.default(false)
|
|
745
|
-
.example(true)
|
|
746
|
-
.description('Disable IMAP if you are using this email account to only send emails.'),
|
|
747
|
-
|
|
748
|
-
smtp_auth_user: Joi.string().empty('').trim().max(1024).required(),
|
|
749
|
-
smtp_auth_pass: Joi.string().empty('').max(1024).required(),
|
|
750
|
-
smtp_host: Joi.string().hostname().required().example('smtp.gmail.com').description('Hostname to connect to'),
|
|
751
|
-
smtp_port: Joi.number()
|
|
752
|
-
.integer()
|
|
753
|
-
.min(1)
|
|
754
|
-
.max(64 * 1024)
|
|
755
|
-
.required()
|
|
756
|
-
.example(465)
|
|
757
|
-
.description('Service port number')
|
|
758
|
-
.label('SMTP host'),
|
|
759
|
-
smtp_secure: Joi.boolean()
|
|
760
|
-
.truthy('Y', 'true', '1', 'on')
|
|
761
|
-
.falsy('N', 'false', 0, '')
|
|
762
|
-
.default(false)
|
|
763
|
-
.example(true)
|
|
764
|
-
.description('Should connection use TLS. Usually true for port 465')
|
|
765
|
-
.label('SMTP port')
|
|
924
|
+
...signedBlobFields,
|
|
925
|
+
...connectionFields
|
|
766
926
|
})
|
|
767
927
|
}
|
|
768
928
|
}
|
|
769
929
|
});
|
|
770
930
|
|
|
931
|
+
// Shared by this route's payload validation and its failAction re-render, so the re-rendered form
|
|
932
|
+
// is built from the same schema that validated the submission and cannot drift from it (unlike the
|
|
933
|
+
// earlier hand-maintained truthy Set, which had to be kept in sync by hand).
|
|
934
|
+
const serverFormSchema = Joi.object({
|
|
935
|
+
...signedBlobFields,
|
|
936
|
+
name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
|
|
937
|
+
tz: Joi.string().empty('').max(100).example('Europe/Tallinn').description('Optional timezone for autogenerated date strings'),
|
|
938
|
+
email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
|
|
939
|
+
...connectionFields
|
|
940
|
+
});
|
|
941
|
+
|
|
771
942
|
server.route({
|
|
772
943
|
method: 'POST',
|
|
773
944
|
path: '/accounts/new/imap/server',
|
|
774
945
|
|
|
775
946
|
async handler(request, h) {
|
|
776
|
-
const data = await parseSignedFormData(redis, request.payload, request.app.gt);
|
|
947
|
+
const data = await parseSignedFormData(redis, request.payload, request.app.gt, { requireNonce: true });
|
|
777
948
|
|
|
778
949
|
const accountData = {
|
|
779
950
|
account: data.account || null,
|
|
@@ -813,20 +984,46 @@ function init(args) {
|
|
|
813
984
|
}
|
|
814
985
|
|
|
815
986
|
const accountObject = new Account({ redis, call, secret: await getSecret() });
|
|
816
|
-
const result = await accountObject.create(accountData);
|
|
817
987
|
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
988
|
+
// Claim the single-use nonce BEFORE creating the account so a concurrent double-submit or
|
|
989
|
+
// a replayed URL cannot create duplicate accounts (SET NX is atomic). parseSignedFormData
|
|
990
|
+
// already rejects a nonce that was fully consumed by an earlier successful submit.
|
|
991
|
+
// requireNonce:true above guarantees data.n and data.t are present.
|
|
992
|
+
// claimFormNonce/releaseFormNonce (lib/tools.js) encapsulate the SET NX + release so the IMAP
|
|
993
|
+
// arm and the OAuth callback (workers/api.js) share one copy of the double-spend semantics.
|
|
994
|
+
let claimed;
|
|
995
|
+
try {
|
|
996
|
+
claimed = await claimFormNonce(redis, data.n, data.t);
|
|
997
|
+
} catch (err) {
|
|
998
|
+
// A Redis failure here is not a consumed nonce. Report it as a retryable server error
|
|
999
|
+
// instead of misdiagnosing a valid setup URL as invalid or expired.
|
|
1000
|
+
request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
|
|
1001
|
+
throw Boom.boomify(new Error(request.app.gt.gettext('Temporary error, please try again')), { statusCode: 500 });
|
|
1002
|
+
}
|
|
1003
|
+
if (!claimed) {
|
|
1004
|
+
// SET NX returned null: the nonce key already exists, so this URL was already used.
|
|
1005
|
+
//
|
|
1006
|
+
// Reviewed, accepted (do not "fix" server-side): the LOSING side of a legitimate concurrent
|
|
1007
|
+
// double-submit lands here and sees this 403 even though the winning request created the
|
|
1008
|
+
// account. The client-side formSubmitting latch (views/accounts/register/imap-server.hbs) is
|
|
1009
|
+
// the primary guard; the residual is a no-JS double-click, and even then this is strictly
|
|
1010
|
+
// better than the pre-hardening behavior (two duplicate accounts). A nicer UX (store the
|
|
1011
|
+
// created account id under the nonce key and redirect the loser to success) is a possible
|
|
1012
|
+
// future enhancement, not a bug.
|
|
1013
|
+
throw Boom.boomify(new Error(request.app.gt.gettext('Invalid or expired account setup URL')), { statusCode: 403 });
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
let result;
|
|
1017
|
+
try {
|
|
1018
|
+
result = await accountObject.create(accountData);
|
|
1019
|
+
} catch (err) {
|
|
1020
|
+
// Release the nonce so the user can fix the form and retry. Accepted residual: if
|
|
1021
|
+
// Redis fails here too (it likely failed create() as well), the nonce stays consumed
|
|
1022
|
+
// for its remaining TTL and the user needs a freshly issued link - the claim-BEFORE-
|
|
1023
|
+
// create ordering is what makes the double-submit dedupe atomic, and this narrow
|
|
1024
|
+
// crash window is the price of that.
|
|
1025
|
+
await releaseFormNonce(redis, data.n, request.logger);
|
|
1026
|
+
throw err;
|
|
830
1027
|
}
|
|
831
1028
|
|
|
832
1029
|
let httpRedirectUrl;
|
|
@@ -875,12 +1072,69 @@ function init(args) {
|
|
|
875
1072
|
await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't set up account. Try again.") });
|
|
876
1073
|
request.logger.error({ msg: 'Failed to process account', err });
|
|
877
1074
|
|
|
1075
|
+
// Rebuild the re-render values from the SAME schema that just validated the submission
|
|
1076
|
+
// (coerces the tri-state checkboxes, strips unknown/prototype keys, drops both plaintext
|
|
1077
|
+
// passwords) - see rebuildFormValues.
|
|
1078
|
+
const values = rebuildFormValues(serverFormSchema, request.payload, ['imap_auth_pass', 'smtp_auth_pass']);
|
|
1079
|
+
|
|
1080
|
+
// serverFormSchema does not carry the appPassword_* hint fields (they feed unescaped
|
|
1081
|
+
// template sinks), so stripUnknown drops them. Re-derive the hint server-side from the
|
|
1082
|
+
// (trusted) email so the re-rendered form still shows the app-password label and
|
|
1083
|
+
// instructions for Gmail/iCloud/Outlook/etc. The values come from a static table, never
|
|
1084
|
+
// from the submitted payload, so they are safe to render.
|
|
1085
|
+
//
|
|
1086
|
+
// Try the static domain table first: it is synchronous, needs no network, and covers the
|
|
1087
|
+
// canonical provider domains, so a common-domain re-render costs no Redis round trips, no
|
|
1088
|
+
// DNS, and no probe budget.
|
|
1089
|
+
if (values.email) {
|
|
1090
|
+
let appPassword = getAppPassword(values.email, false, request.app.gt);
|
|
1091
|
+
|
|
1092
|
+
// Custom-domain fallback (e.g. Google Workspace / M365 on their own domain) needs an
|
|
1093
|
+
// MX lookup. failAction runs BEFORE the handler's signature gate, and the lookup
|
|
1094
|
+
// drives outbound DNS, so gate it with the SAME machinery as the handler siblings, not
|
|
1095
|
+
// a bare signature check: authorizeSignedProbe rejects a signature-only blob (e.g. a
|
|
1096
|
+
// leaked tracking/unsubscribe blob) and one past its TTL, and bounds how many lookups
|
|
1097
|
+
// one signed link can drive. Without it, any holder of any validly-signed blob could
|
|
1098
|
+
// turn this re-render into an unbounded DNS oracle. On a normal validation-error
|
|
1099
|
+
// re-render the nonce is not yet consumed (the handler claims it only on success), so
|
|
1100
|
+
// the hint still shows. values.data/values.sig are the schema-validated copies -
|
|
1101
|
+
// rebuildFormValues drops them when malformed (e.g. duplicated fields).
|
|
1102
|
+
if (!appPassword && values.data && values.sig) {
|
|
1103
|
+
// Consult the per-domain memo BEFORE the probe/DNS work: a repeat re-submit of
|
|
1104
|
+
// the same email must not re-run the MX lookup or draw the probe budget again.
|
|
1105
|
+
const domain = values.email.split('@').pop().trim().toLowerCase();
|
|
1106
|
+
const cached = getCachedAppPasswordHint(domain);
|
|
1107
|
+
if (cached) {
|
|
1108
|
+
appPassword = cached.value;
|
|
1109
|
+
} else {
|
|
1110
|
+
try {
|
|
1111
|
+
await authorizeSignedProbe({ data: values.data, sig: values.sig }, request.app.gt, request.logger);
|
|
1112
|
+
appPassword = await resolveAppPassword(values.email, request.app.gt);
|
|
1113
|
+
// Cache the outcome (including a falsy "no hint" result) so subsequent
|
|
1114
|
+
// re-renders for this domain are free.
|
|
1115
|
+
setCachedAppPasswordHint(domain, appPassword);
|
|
1116
|
+
} catch (err) {
|
|
1117
|
+
// The hint is cosmetic; a rejected/expired blob, an exhausted probe cap, or a
|
|
1118
|
+
// lookup failure must never break the error re-render (failAction must not throw).
|
|
1119
|
+
// Do NOT cache on failure - an exhausted probe cap or transient DNS error should
|
|
1120
|
+
// not poison the hint for the whole TTL.
|
|
1121
|
+
request.logger.error({ msg: 'Failed to resolve app-password hint for form re-render', err });
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
if (appPassword) {
|
|
1127
|
+
Object.assign(values, flattenObjectKeys({ appPassword }));
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
|
|
878
1131
|
return h
|
|
879
1132
|
.view(
|
|
880
1133
|
'accounts/register/imap-server',
|
|
881
1134
|
{
|
|
882
1135
|
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
883
|
-
errors
|
|
1136
|
+
errors,
|
|
1137
|
+
values
|
|
884
1138
|
},
|
|
885
1139
|
{
|
|
886
1140
|
layout: 'public'
|
|
@@ -889,53 +1143,7 @@ function init(args) {
|
|
|
889
1143
|
.takeover();
|
|
890
1144
|
},
|
|
891
1145
|
|
|
892
|
-
payload:
|
|
893
|
-
data: Joi.string().base64({ paddingRequired: false, urlSafe: true }).required(),
|
|
894
|
-
sig: Joi.string().base64({ paddingRequired: false, urlSafe: true }),
|
|
895
|
-
name: Joi.string().empty('').max(256).example('John Smith').description('Account Name'),
|
|
896
|
-
tz: Joi.string().empty('').max(100).example('Europe/Tallinn').description('Optional timezone for autogenerated date strings'),
|
|
897
|
-
email: Joi.string().email().required().example('user@example.com').label('Email').description('Your account email'),
|
|
898
|
-
imap_auth_user: Joi.string().empty('').trim().max(1024).required(),
|
|
899
|
-
imap_auth_pass: Joi.string().empty('').max(1024).required(),
|
|
900
|
-
imap_host: Joi.string().hostname().required().example('imap.gmail.com').description('Hostname to connect to'),
|
|
901
|
-
imap_port: Joi.number()
|
|
902
|
-
.integer()
|
|
903
|
-
.min(1)
|
|
904
|
-
.max(64 * 1024)
|
|
905
|
-
.required()
|
|
906
|
-
.example(993)
|
|
907
|
-
.description('Service port number'),
|
|
908
|
-
imap_secure: Joi.boolean()
|
|
909
|
-
.truthy('Y', 'true', '1', 'on')
|
|
910
|
-
.falsy('N', 'false', 0, '')
|
|
911
|
-
.default(false)
|
|
912
|
-
.example(true)
|
|
913
|
-
.description('Should connection use TLS. Usually true for port 993'),
|
|
914
|
-
|
|
915
|
-
imap_disabled: Joi.boolean()
|
|
916
|
-
.truthy('Y', 'true', '1', 'on')
|
|
917
|
-
.falsy('N', 'false', 0, '')
|
|
918
|
-
.default(false)
|
|
919
|
-
.example(true)
|
|
920
|
-
.description('Disable IMAP if you are using this email account to only send emails.'),
|
|
921
|
-
|
|
922
|
-
smtp_auth_user: Joi.string().empty('').trim().max(1024).required(),
|
|
923
|
-
smtp_auth_pass: Joi.string().empty('').max(1024).required(),
|
|
924
|
-
smtp_host: Joi.string().hostname().required().example('smtp.gmail.com').description('Hostname to connect to'),
|
|
925
|
-
smtp_port: Joi.number()
|
|
926
|
-
.integer()
|
|
927
|
-
.min(1)
|
|
928
|
-
.max(64 * 1024)
|
|
929
|
-
.required()
|
|
930
|
-
.example(465)
|
|
931
|
-
.description('Service port number'),
|
|
932
|
-
smtp_secure: Joi.boolean()
|
|
933
|
-
.truthy('Y', 'true', '1', 'on')
|
|
934
|
-
.falsy('N', 'false', 0, '')
|
|
935
|
-
.default(false)
|
|
936
|
-
.example(true)
|
|
937
|
-
.description('Should connection use TLS. Usually true for port 465')
|
|
938
|
-
})
|
|
1146
|
+
payload: serverFormSchema
|
|
939
1147
|
}
|
|
940
1148
|
}
|
|
941
1149
|
});
|
|
@@ -1131,7 +1339,18 @@ function init(args) {
|
|
|
1131
1339
|
account: request.params.account,
|
|
1132
1340
|
name: accountData.name,
|
|
1133
1341
|
email: accountData.email,
|
|
1134
|
-
redirectUrl: `/admin/accounts/${request.params.account}
|
|
1342
|
+
redirectUrl: `/admin/accounts/${request.params.account}`,
|
|
1343
|
+
|
|
1344
|
+
// Single-use nonce + timestamp so this blob (embedded in the account page and
|
|
1345
|
+
// used by the OAuth "Re-authenticate" form) cannot be replayed at the auth:false
|
|
1346
|
+
// /accounts/new/imap/{test,server} endpoints if it leaks. Mirrors the new-account
|
|
1347
|
+
// issuer above. Accepted consequences, BY DESIGN: the blob expires after
|
|
1348
|
+
// MAX_FORM_TTL (24h), and it is consumed by the next successful re-auth (the OAuth
|
|
1349
|
+
// callback and the IMAP form submit both claim account:form:{n}), so a stale tab or
|
|
1350
|
+
// a back-button copy of this page gets a 403 on Re-authenticate until the page is
|
|
1351
|
+
// reloaded - reloading re-mints a fresh blob.
|
|
1352
|
+
n: crypto.randomBytes(NONCE_BYTES).toString('base64url'),
|
|
1353
|
+
t: Date.now()
|
|
1135
1354
|
}),
|
|
1136
1355
|
|
|
1137
1356
|
showAdvanced: accountData.proxy || accountData.webhooks,
|
|
@@ -455,7 +455,6 @@ function init(args) {
|
|
|
455
455
|
async handler(request, h) {
|
|
456
456
|
try {
|
|
457
457
|
let data = {
|
|
458
|
-
serviceSecret: request.payload.serviceSecret,
|
|
459
458
|
queueKeep: request.payload.queueKeep,
|
|
460
459
|
pageBrandName: request.payload.pageBrandName,
|
|
461
460
|
templateHeader: request.payload.templateHeader,
|
|
@@ -479,6 +478,17 @@ function init(args) {
|
|
|
479
478
|
data.serviceUrl = url.origin;
|
|
480
479
|
}
|
|
481
480
|
|
|
481
|
+
// Only overwrite the service secret when a non-empty value is provided: an empty
|
|
482
|
+
// stored secret would break HMAC signing/verification for every hosted-form/tracking
|
|
483
|
+
// link, so a blank field means "keep the current secret", never "clear it". Tell the
|
|
484
|
+
// admin the field was ignored - silently dropping it would make the success flash
|
|
485
|
+
// read as if a clear-to-rotate took effect.
|
|
486
|
+
if (request.payload.serviceSecret) {
|
|
487
|
+
data.serviceSecret = request.payload.serviceSecret;
|
|
488
|
+
} else if (await settings.get('serviceSecret')) {
|
|
489
|
+
await request.flash({ type: 'warning', message: `Service secret was left unchanged - type a new value to rotate it` });
|
|
490
|
+
}
|
|
491
|
+
|
|
482
492
|
for (let key of Object.keys(data)) {
|
|
483
493
|
await settings.set(key, data[key]);
|
|
484
494
|
}
|