emailengine-app 2.87.2 → 2.89.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.ncurc.js +24 -44
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +37 -0
- package/ENVIRONMENT.md +26 -23
- package/LICENSE_EMAILENGINE.txt +20 -12
- package/app.json +3 -3
- package/bin/emailengine.js +7 -11
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +155 -16
- package/lib/account.js +69 -49
- package/lib/admin-password.js +85 -0
- package/lib/api-routes/license-routes.js +9 -0
- package/lib/api-token-auth.js +21 -5
- package/lib/calendar-event.js +15 -3
- package/lib/consts.js +5 -0
- package/lib/db.js +1 -0
- package/lib/email-client/base-client.js +36 -15
- package/lib/email-client/gmail-client.js +20 -6
- package/lib/email-client/imap/connection-errors.js +30 -1
- package/lib/email-client/imap/session-expiry.js +83 -0
- package/lib/email-client/imap-client.js +12 -2
- package/lib/email-client/smtp-pool-manager.js +66 -8
- package/lib/export.js +147 -22
- package/lib/graph-notifications.js +60 -0
- package/lib/imap-proxy-auth.js +52 -18
- package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
- package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
- package/lib/imapproxy/imap-server.js +10 -1
- package/lib/imapproxy/proxy-handoff.js +100 -5
- package/lib/license-subscription.js +244 -0
- package/lib/node-version.js +99 -12
- package/lib/oauth/gmail.js +18 -0
- package/lib/oauth/outlook-identity.js +54 -12
- package/lib/prepared-password.js +38 -0
- package/lib/queue-browser/index.js +6 -6
- package/lib/queue-job-actions.js +59 -4
- package/lib/read-env-value.js +46 -21
- package/lib/redis-url.js +23 -0
- package/lib/response-stream.js +69 -1
- package/lib/revocation-events.js +79 -0
- package/lib/schemas.js +18 -2
- package/lib/settings.js +50 -24
- package/lib/sso.js +23 -0
- package/lib/submit-penalty.js +24 -0
- package/lib/submit-processor.js +10 -2
- package/lib/tokens.js +6 -0
- package/lib/tools.js +90 -18
- package/lib/ui-routes/admin-config-routes.js +3 -276
- package/lib/ui-routes/auth-routes.js +13 -64
- package/lib/ui-routes/dashboard-routes.js +4 -0
- package/lib/ui-routes/license-routes.js +326 -0
- package/lib/web-safe-html.js +74 -1
- package/lib/webhook-delivery.js +21 -20
- package/lib/webhook-penalty.js +18 -17
- package/lib/webhooks.js +18 -0
- package/list-generate.js +56 -19
- package/package.json +28 -31
- package/sbom.json +373 -964
- package/scan.js +2 -0
- package/server.js +273 -100
- package/static/css/flyonui.css +2 -2
- package/static/js/ui.js +11 -4
- package/static/licenses.html +1108 -504
- package/translations/messages.pot +18 -18
- package/views/config/license.hbs +43 -16
- package/views/dashboard.hbs +9 -0
- package/views/partials/side_menu.hbs +1 -1
- package/views/upgrade.hbs +25 -0
- package/workers/api.js +108 -107
- package/workers/imap.js +4 -6
- package/lib/net-tos-guard.js +0 -42
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Applies EENGINE_PREPARED_PASSWORD at startup. Split out of server.js so it can be tested.
|
|
4
|
+
|
|
5
|
+
const { setAdminPassword } = require('./admin-password');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Stores the prepared admin password hash when it differs from the stored one.
|
|
9
|
+
*
|
|
10
|
+
* Written only when the stored hash differs: passwordVersion is what every admin session and
|
|
11
|
+
* message-browser token is checked against, so rewriting the same hash on each boot would log every
|
|
12
|
+
* operator out at every restart.
|
|
13
|
+
*
|
|
14
|
+
* The replacement itself, passkeys included, is setAdminPassword(); rotating the password through
|
|
15
|
+
* this variable used to end every session and leave the passkeys working.
|
|
16
|
+
*
|
|
17
|
+
* @param {string} preparedPassword - PBKDF2 hash
|
|
18
|
+
* @param {Object} deps
|
|
19
|
+
* @param {Object} deps.settings - settings store (`get()`, `set()`)
|
|
20
|
+
* @param {Object} deps.passkeys - passkey store (`deleteAllCredentials()`)
|
|
21
|
+
* @param {Object} deps.logger
|
|
22
|
+
* @returns {Promise<{ imported: boolean, clearedPasskeys: number }>}
|
|
23
|
+
*/
|
|
24
|
+
async function importPreparedPassword(preparedPassword, { settings, passkeys, logger }) {
|
|
25
|
+
let authData = await settings.get('authData');
|
|
26
|
+
|
|
27
|
+
if (authData && authData.password === preparedPassword) {
|
|
28
|
+
logger.debug({ msg: 'Password already imported' });
|
|
29
|
+
return { imported: false, clearedPasskeys: 0 };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const { clearedPasskeys } = await setAdminPassword(preparedPassword, { settings, passkeys, logger }, authData);
|
|
33
|
+
logger.info({ msg: 'Password imported', clearedPasskeys });
|
|
34
|
+
|
|
35
|
+
return { imported: true, clearedPasskeys };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { importPreparedPassword };
|
|
@@ -22,7 +22,7 @@ const { buildRetentionPolicy } = require('../queue-retention');
|
|
|
22
22
|
const { getFailedJobRetention } = require('../env-setting-overrides');
|
|
23
23
|
const { maskSecrets } = require('../api-routes/route-helpers');
|
|
24
24
|
const { statusError } = require('../utils/status-error');
|
|
25
|
-
const { retryFailedJob, promoteDelayedJob, assertJobState } = require('../queue-job-actions');
|
|
25
|
+
const { retryFailedJob, promoteDelayedJob, assertJobState, loadRealJob } = require('../queue-job-actions');
|
|
26
26
|
const { QUEUES, QUEUES_BY_NAME, STATES, STATES_BY_NAME, STATE_NAMES, SCAN_LIMIT, BATCH_SIZE } = require('./definitions');
|
|
27
27
|
const { formatJob, matchesQuery, rawJob, humanSize, notifyPayloadSize, entryUrl } = require('./format');
|
|
28
28
|
|
|
@@ -42,7 +42,7 @@ function queueObject(queueDef) {
|
|
|
42
42
|
* @returns {Promise<string|null>} BullMQ state, or null when there is no such job
|
|
43
43
|
*/
|
|
44
44
|
async function jobState(queueDef, jobId) {
|
|
45
|
-
const job = await queueObject(queueDef)
|
|
45
|
+
const job = await loadRealJob(queueObject(queueDef), jobId);
|
|
46
46
|
return job ? await job.getState() : null;
|
|
47
47
|
}
|
|
48
48
|
|
|
@@ -50,7 +50,7 @@ async function jobState(queueDef, jobId) {
|
|
|
50
50
|
* Removes a job through BullMQ alone: refused, as `locked`, when a worker is running it.
|
|
51
51
|
*/
|
|
52
52
|
async function removeBullJob(queueDef, jobId, logger) {
|
|
53
|
-
const job = await queueObject(queueDef)
|
|
53
|
+
const job = await loadRealJob(queueObject(queueDef), jobId);
|
|
54
54
|
if (!job) {
|
|
55
55
|
return { removed: false };
|
|
56
56
|
}
|
|
@@ -71,7 +71,7 @@ async function removeBullJob(queueDef, jobId, logger) {
|
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
async function retryBullJob(queueDef, jobId, logger) {
|
|
74
|
-
const job = await queueObject(queueDef)
|
|
74
|
+
const job = await loadRealJob(queueObject(queueDef), jobId);
|
|
75
75
|
if (!job) {
|
|
76
76
|
return false;
|
|
77
77
|
}
|
|
@@ -82,7 +82,7 @@ async function retryBullJob(queueDef, jobId, logger) {
|
|
|
82
82
|
}
|
|
83
83
|
|
|
84
84
|
async function promoteBullJob(queueDef, jobId, logger) {
|
|
85
|
-
const job = await queueObject(queueDef)
|
|
85
|
+
const job = await loadRealJob(queueObject(queueDef), jobId);
|
|
86
86
|
if (!job) {
|
|
87
87
|
return false;
|
|
88
88
|
}
|
|
@@ -502,7 +502,7 @@ async function listJobs(options) {
|
|
|
502
502
|
async function getJob(options) {
|
|
503
503
|
const { queue: queueDef, jobId, logger } = options;
|
|
504
504
|
|
|
505
|
-
const job = await queueObject(queueDef)
|
|
505
|
+
const job = await loadRealJob(queueObject(queueDef), jobId);
|
|
506
506
|
if (!job) {
|
|
507
507
|
return null;
|
|
508
508
|
}
|
package/lib/queue-job-actions.js
CHANGED
|
@@ -5,9 +5,11 @@
|
|
|
5
5
|
// running. The submit queue's own rules (the message content that lives beside the job) are
|
|
6
6
|
// layered on top of these by lib/outbox.js; the webhook queue uses them as they are.
|
|
7
7
|
//
|
|
8
|
-
//
|
|
9
|
-
// through the queue browser.
|
|
8
|
+
// It depends on nothing but BullMQ's DelayedError and the error shape, so lib/outbox.js can use it
|
|
9
|
+
// without a cycle through the queue browser. The penalty helpers at the end are shared by the
|
|
10
|
+
// webhook and submit queues.
|
|
10
11
|
|
|
12
|
+
const { DelayedError } = require('bullmq');
|
|
11
13
|
const { statusError } = require('./utils/status-error');
|
|
12
14
|
|
|
13
15
|
/**
|
|
@@ -82,11 +84,64 @@ async function assertJobState(job, state, noun, verb) {
|
|
|
82
84
|
* @returns {Promise<Object|null>} The job, or null
|
|
83
85
|
*/
|
|
84
86
|
async function getAccountJob(queue, id, account) {
|
|
85
|
-
const job =
|
|
87
|
+
const job = await loadRealJob(queue, id);
|
|
86
88
|
if (!job || (account && (!job.data || job.data.account !== account))) {
|
|
87
89
|
return null;
|
|
88
90
|
}
|
|
89
91
|
return job;
|
|
90
92
|
}
|
|
91
93
|
|
|
92
|
-
|
|
94
|
+
/**
|
|
95
|
+
* Loads a job by an id a caller supplied. BullMQ resolves an id to the hash under the queue prefix,
|
|
96
|
+
* and the queue keeps its own state in hashes beside the jobs: getJob('meta') returned a job made of
|
|
97
|
+
* the queue's metadata, and removing it deleted the pause flag, which released every message an
|
|
98
|
+
* operator had held. A real job always carries a name and a creation time.
|
|
99
|
+
* @param {Object} queue - BullMQ queue
|
|
100
|
+
* @param {string} id - Job ID
|
|
101
|
+
* @returns {Promise<Object|null>} The job, or null
|
|
102
|
+
*/
|
|
103
|
+
async function loadRealJob(queue, id) {
|
|
104
|
+
const job = id ? await queue.getJob(id) : null;
|
|
105
|
+
return job && typeof job.name === 'string' && job.timestamp ? job : null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Moves a job back to the delayed set while a penalty key is set, without spending an attempt: the
|
|
110
|
+
* webhook queue penalises a slow target and the submit queue a stalling account the same way.
|
|
111
|
+
* @param {Object} job - BullMQ job
|
|
112
|
+
* @param {string} token - The worker's lock token
|
|
113
|
+
* @param {Object} redis - ioredis client
|
|
114
|
+
* @param {string} key - Penalty key
|
|
115
|
+
* @param {Function} [onDelay] - Called with the delay before the job is moved
|
|
116
|
+
* @throws {DelayedError} When the job was moved to the delayed set
|
|
117
|
+
*/
|
|
118
|
+
async function delayWhilePenalised(job, token, redis, key, onDelay) {
|
|
119
|
+
const remaining = await redis.pttl(key);
|
|
120
|
+
if (remaining > 0) {
|
|
121
|
+
if (onDelay) {
|
|
122
|
+
onDelay(remaining);
|
|
123
|
+
}
|
|
124
|
+
await job.moveToDelayed(Date.now() + remaining, token);
|
|
125
|
+
throw new DelayedError();
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Sets a penalty key for `ms` milliseconds; a zero penalty sets nothing. A missed penalty costs
|
|
131
|
+
* the queue one more slow attempt and nothing else, so a failed write is not an error.
|
|
132
|
+
* @param {Object} redis - ioredis client
|
|
133
|
+
* @param {string} key - Penalty key
|
|
134
|
+
* @param {number} ms - Penalty length
|
|
135
|
+
*/
|
|
136
|
+
async function setPenalty(redis, key, ms) {
|
|
137
|
+
if (!ms) {
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
await redis.set(key, '1', 'PX', ms);
|
|
142
|
+
} catch (err) {
|
|
143
|
+
// see above
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
module.exports = { retryFailedJob, promoteDelayedJob, assertJobState, getAccountJob, loadRealJob, delayWhilePenalised, setPenalty };
|
package/lib/read-env-value.js
CHANGED
|
@@ -36,6 +36,7 @@ const LEGACY_UNTRIMMED_KEYS = new Set(['EENGINE_SECRET', 'EENGINE_REDIS', 'REDIS
|
|
|
36
36
|
*
|
|
37
37
|
* @param {string} key - Environment variable name
|
|
38
38
|
* @returns {string|undefined} The value, or undefined when neither form is set
|
|
39
|
+
* @throws {Error} code `EnvFileUnreadable` when `<KEY>_FILE` names a file that can not be read
|
|
39
40
|
*/
|
|
40
41
|
function readEnvValue(key) {
|
|
41
42
|
if (key in process.env) {
|
|
@@ -43,30 +44,38 @@ function readEnvValue(key) {
|
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
if (typeof process.env[`${key}_FILE`] === 'string' && process.env[`${key}_FILE`]) {
|
|
47
|
+
const file = process.env[`${key}_FILE`];
|
|
48
|
+
let contents;
|
|
46
49
|
try {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
50
|
+
contents = Fs.readFileSync(file, 'utf-8');
|
|
51
|
+
} catch (err) {
|
|
52
|
+
// Fail closed. This used to resolve to an empty value, which every caller reads as
|
|
53
|
+
// "not configured": a missing admin password hash booted with /admin open, a missing
|
|
54
|
+
// address allow-list with no restriction. A file the operator named and the process
|
|
55
|
+
// can not read is a broken deployment, so it stops the process instead.
|
|
56
|
+
let error = new Error(`Can not read ${key}_FILE (${file}): ${err.message}`);
|
|
57
|
+
error.code = 'EnvFileUnreadable';
|
|
58
|
+
error.key = key;
|
|
59
|
+
throw error;
|
|
60
|
+
}
|
|
51
61
|
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
// the operator needs to find it, and the value is what the warning exists to protect.
|
|
55
|
-
const legacyValue = contents.replace(/\r?\n$/, '');
|
|
56
|
-
if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
|
|
57
|
-
getLogger().warn({
|
|
58
|
-
msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
|
|
59
|
-
key,
|
|
60
|
-
file: process.env[`${key}_FILE`]
|
|
61
|
-
});
|
|
62
|
-
}
|
|
62
|
+
const value = contents.replace(/\r?\n/g, '\n').trim();
|
|
63
|
+
process.env[key] = value;
|
|
63
64
|
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
65
|
+
// What the private copies in lib/db.js and lib/get-secret.js resolved the same file to.
|
|
66
|
+
// Neither the value nor the whitespace around it is logged: the key and the file are what
|
|
67
|
+
// the operator needs to find it, and the value is what the warning exists to protect.
|
|
68
|
+
const legacyValue = contents.replace(/\r?\n$/, '');
|
|
69
|
+
if (LEGACY_UNTRIMMED_KEYS.has(key) && value !== legacyValue) {
|
|
70
|
+
getLogger().warn({
|
|
71
|
+
msg: 'Environment value read from file carries whitespace that is now trimmed, so it resolves differently than in earlier releases. Set the variable itself rather than the file to keep the old value, as one given in the environment is used verbatim.',
|
|
72
|
+
key,
|
|
73
|
+
file
|
|
74
|
+
});
|
|
68
75
|
}
|
|
69
|
-
|
|
76
|
+
|
|
77
|
+
getLogger().trace({ msg: 'Loaded environment value from file', key, file });
|
|
78
|
+
return value;
|
|
70
79
|
}
|
|
71
80
|
}
|
|
72
81
|
|
|
@@ -80,4 +89,20 @@ function hasEnvValue(key) {
|
|
|
80
89
|
return key in process.env || `${key}_FILE` in process.env;
|
|
81
90
|
}
|
|
82
91
|
|
|
83
|
-
|
|
92
|
+
/**
|
|
93
|
+
* Resolves every `EENGINE_*_FILE` (and `REDIS_URL_FILE`) variable now. Called once at the start of
|
|
94
|
+
* the main process, so a file that can not be read stops the boot with its name instead of the
|
|
95
|
+
* first worker thread that reads the value crashing, and then crashing again on every respawn.
|
|
96
|
+
*
|
|
97
|
+
* @throws {Error} code `EnvFileUnreadable` for the first file that can not be read
|
|
98
|
+
*/
|
|
99
|
+
function resolveEnvFiles() {
|
|
100
|
+
for (const name of Object.keys(process.env)) {
|
|
101
|
+
const match = /^(EENGINE_[A-Z0-9_]+|REDIS_URL)_FILE$/.exec(name);
|
|
102
|
+
if (match) {
|
|
103
|
+
readEnvValue(match[1]);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
module.exports = { readEnvValue, hasEnvValue, resolveEnvFiles };
|
package/lib/redis-url.js
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { readEnvValue } = require('./read-env-value');
|
|
4
|
+
const { getBoolean } = require('./get-boolean');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Some managed Redis services (the Heroku Redis add-on among them) present a certificate no CA
|
|
8
|
+
* signed. `EENGINE_REDIS_TLS_REJECT_UNAUTHORIZED=false` relaxes verification for the Redis
|
|
9
|
+
* connection alone. The Heroku manifest used to set NODE_TLS_REJECT_UNAUTHORIZED=0 for that, which
|
|
10
|
+
* switched certificate checks off for every outbound connection of the instance: OAuth2 token
|
|
11
|
+
* refreshes, webhooks, IMAP and SMTP included.
|
|
12
|
+
*
|
|
13
|
+
* @param {Object} conf - ioredis options; changed in place
|
|
14
|
+
* @returns {Object} conf
|
|
15
|
+
*/
|
|
16
|
+
function applyRedisTlsSwitch(conf) {
|
|
17
|
+
const value = readEnvValue('EENGINE_REDIS_TLS_REJECT_UNAUTHORIZED');
|
|
18
|
+
if (conf.tls && typeof value === 'string' && value.trim() && !getBoolean(value)) {
|
|
19
|
+
conf.tls = Object.assign({}, conf.tls, { rejectUnauthorized: false });
|
|
20
|
+
}
|
|
21
|
+
return conf;
|
|
22
|
+
}
|
|
23
|
+
|
|
3
24
|
module.exports = redisConf => {
|
|
4
25
|
let parsedRedisUrl = new URL(redisConf);
|
|
5
26
|
let parsedUrl = {};
|
|
@@ -78,3 +99,5 @@ module.exports = redisConf => {
|
|
|
78
99
|
|
|
79
100
|
return parsedUrl;
|
|
80
101
|
};
|
|
102
|
+
|
|
103
|
+
module.exports.applyRedisTlsSwitch = applyRedisTlsSwitch;
|
package/lib/response-stream.js
CHANGED
|
@@ -174,6 +174,67 @@ function openSseStream(h, options) {
|
|
|
174
174
|
return { stream, response };
|
|
175
175
|
}
|
|
176
176
|
|
|
177
|
+
// How often an open change stream re-asks whether the credential that opened it still admits it.
|
|
178
|
+
// Revocations announced over lib/revocation-events.js are acted on at once; this catches the rest
|
|
179
|
+
// (an expired token, a session ended by a password change).
|
|
180
|
+
const CHANGE_STREAM_RECHECK_INTERVAL = 60 * 1000;
|
|
181
|
+
|
|
182
|
+
let changeStreamRecheckTimer = null;
|
|
183
|
+
let changeStreamRecheckInFlight = null;
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Re-runs the authentication of every open change stream through the strategy that admitted it,
|
|
187
|
+
* against the request that opened it, and closes the streams whose credential is refused now. The
|
|
188
|
+
* feed used to be authorized once, at open, so a revoked or expired token, an ended admin session
|
|
189
|
+
* and an SSO user removed from the allow-list kept receiving every account's change events for as
|
|
190
|
+
* long as the client held the connection. A call made while a pass runs joins it.
|
|
191
|
+
*
|
|
192
|
+
* @returns {Promise<void>}
|
|
193
|
+
*/
|
|
194
|
+
function recheckChangeStreams() {
|
|
195
|
+
if (!changeStreamRecheckInFlight) {
|
|
196
|
+
changeStreamRecheckInFlight = (async () => {
|
|
197
|
+
const streams = [...registeredPublishers].filter(stream => stream.recheckAuth && !stream._finalized);
|
|
198
|
+
if (!streams.length && changeStreamRecheckTimer) {
|
|
199
|
+
// the last change stream is gone; the next one to open starts the timer again
|
|
200
|
+
clearInterval(changeStreamRecheckTimer);
|
|
201
|
+
changeStreamRecheckTimer = null;
|
|
202
|
+
}
|
|
203
|
+
const answers = await Promise.all(streams.map(stream => stream.recheckAuth()));
|
|
204
|
+
streams.forEach((stream, i) => {
|
|
205
|
+
if (!answers[i] && !stream._finalized) {
|
|
206
|
+
stream.finalize();
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
})().finally(() => {
|
|
210
|
+
changeStreamRecheckInFlight = null;
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return changeStreamRecheckInFlight;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Whether the credential behind `request` still passes its route's strategy. A refusal is false:
|
|
218
|
+
* a 401 or 403, or the redirect to the login page the admin session strategy answers a refused
|
|
219
|
+
* session with (thrown by auth.test() as a response, not as an error). Anything else (a Redis
|
|
220
|
+
* fault) says nothing about the credential and keeps the stream.
|
|
221
|
+
*
|
|
222
|
+
* @param {Object} request - The hapi request that opened the stream
|
|
223
|
+
* @returns {Promise<boolean>}
|
|
224
|
+
*/
|
|
225
|
+
async function credentialStillAdmits(request) {
|
|
226
|
+
request.app.authRecheck = true;
|
|
227
|
+
try {
|
|
228
|
+
await request.server.auth.test(request.auth.strategy, request);
|
|
229
|
+
return true;
|
|
230
|
+
} catch (err) {
|
|
231
|
+
const status = (err && ((err.output && err.output.statusCode) || err.statusCode)) || 0;
|
|
232
|
+
return !(status === 401 || status === 403 || (status >= 300 && status < 400));
|
|
233
|
+
} finally {
|
|
234
|
+
request.app.authRecheck = false;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
177
238
|
/**
|
|
178
239
|
* Opens the SSE change feed shared by /admin/changes and /v1/changes.
|
|
179
240
|
*
|
|
@@ -184,7 +245,14 @@ function openSseStream(h, options) {
|
|
|
184
245
|
function openChangeStream(request, h) {
|
|
185
246
|
const { stream, response } = openSseStream(h);
|
|
186
247
|
request.app.stream = stream;
|
|
248
|
+
if (request.auth && request.auth.strategy) {
|
|
249
|
+
stream.recheckAuth = () => credentialStillAdmits(request);
|
|
250
|
+
if (!changeStreamRecheckTimer) {
|
|
251
|
+
changeStreamRecheckTimer = setInterval(recheckChangeStreams, CHANGE_STREAM_RECHECK_INTERVAL);
|
|
252
|
+
changeStreamRecheckTimer.unref();
|
|
253
|
+
}
|
|
254
|
+
}
|
|
187
255
|
return response;
|
|
188
256
|
}
|
|
189
257
|
|
|
190
|
-
module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream, MAX_BUFFERED_BYTES };
|
|
258
|
+
module.exports = { ResponseStream, registeredPublishers, openChangeStream, openSseStream, recheckChangeStreams, MAX_BUFFERED_BYTES };
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Tells long-lived sessions that a credential or account they may depend on has changed, so they
|
|
4
|
+
// re-check it now instead of at their next periodic check. The message names what changed only
|
|
5
|
+
// as a hint: every subscriber re-checks its own sessions against the stored state, so a lost or
|
|
6
|
+
// duplicated message costs at most one periodic interval, never a wrong decision.
|
|
7
|
+
//
|
|
8
|
+
// Redis pub/sub rather than a worker message, because a credential can be revoked from a process
|
|
9
|
+
// that has no worker channel at all (the `emailengine tokens delete` command).
|
|
10
|
+
|
|
11
|
+
const logger = require('./logger');
|
|
12
|
+
const { redis, watchRedisReconnect } = require('./db');
|
|
13
|
+
const { REDIS_PREFIX } = require('./consts');
|
|
14
|
+
|
|
15
|
+
const REVOCATION_CHANNEL = `${REDIS_PREFIX}ee:revocations`;
|
|
16
|
+
|
|
17
|
+
let subscriber = null;
|
|
18
|
+
const handlers = new Set();
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Announces that a credential or account changed in a way that may end open sessions.
|
|
22
|
+
* Never throws: the periodic re-check is the fallback for a message that is not delivered.
|
|
23
|
+
*
|
|
24
|
+
* @param {Object} detail - What changed, e.g. `{ type: 'token' }` or `{ type: 'account', account }`
|
|
25
|
+
* @returns {Promise<void>}
|
|
26
|
+
*/
|
|
27
|
+
async function publishRevocation(detail) {
|
|
28
|
+
try {
|
|
29
|
+
await redis.publish(REVOCATION_CHANNEL, JSON.stringify(detail));
|
|
30
|
+
} catch (err) {
|
|
31
|
+
logger.warn({ msg: 'Failed to announce a credential change', detail, err });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function dispatch(message) {
|
|
36
|
+
let detail = {};
|
|
37
|
+
try {
|
|
38
|
+
detail = JSON.parse(message) || {};
|
|
39
|
+
} catch (err) {
|
|
40
|
+
// a malformed message still means "re-check"
|
|
41
|
+
}
|
|
42
|
+
for (const handler of handlers) {
|
|
43
|
+
try {
|
|
44
|
+
handler(detail);
|
|
45
|
+
} catch (err) {
|
|
46
|
+
logger.error({ msg: 'Credential change handler failed', err });
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Calls `handler(detail)` for every announced change. The subscriber connection is opened on the
|
|
53
|
+
* first registration and shared by every handler in this process.
|
|
54
|
+
*
|
|
55
|
+
* @param {Function} handler
|
|
56
|
+
* @returns {Function} Removes the handler
|
|
57
|
+
*/
|
|
58
|
+
function onRevocation(handler) {
|
|
59
|
+
handlers.add(handler);
|
|
60
|
+
if (!subscriber) {
|
|
61
|
+
subscriber = redis.duplicate();
|
|
62
|
+
subscriber.on('error', err => logger.warn({ msg: 'Credential change subscriber error', err }));
|
|
63
|
+
subscriber.on('message', (channel, message) => dispatch(message));
|
|
64
|
+
// Whatever was published while the connection was down is lost, so every handler
|
|
65
|
+
// re-checks everything once it is back
|
|
66
|
+
watchRedisReconnect(subscriber, () => dispatch('{}'));
|
|
67
|
+
subscriber.subscribe(REVOCATION_CHANNEL).catch(err => logger.error({ msg: 'Failed to subscribe to credential changes', err }));
|
|
68
|
+
}
|
|
69
|
+
return () => {
|
|
70
|
+
handlers.delete(handler);
|
|
71
|
+
if (!handlers.size && subscriber) {
|
|
72
|
+
const closing = subscriber;
|
|
73
|
+
subscriber = null;
|
|
74
|
+
closing.quit().catch(() => closing.disconnect());
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
module.exports = { publishRevocation, onRevocation, REVOCATION_CHANNEL };
|
package/lib/schemas.js
CHANGED
|
@@ -1542,12 +1542,28 @@ const licenseSchema = Joi.object({
|
|
|
1542
1542
|
created: Joi.date().example('2021-10-13T07:47:42.695Z').description('License creation date'),
|
|
1543
1543
|
trial: Joi.boolean().example(false).description('Whether this is a trial license'),
|
|
1544
1544
|
lt: Joi.boolean().example(false).description('Whether this is a lifetime license'),
|
|
1545
|
-
expires: Joi.date().iso().example('2026-01-01T00:00:00.000Z').description('License expiration time, if the license is time-limited')
|
|
1545
|
+
expires: Joi.date().iso().example('2026-01-01T00:00:00.000Z').description('License expiration time, if the license is time-limited'),
|
|
1546
|
+
billing: Joi.string().valid('monthly').example('monthly').description('Set for the license of a monthly plan').label('LicenseBilling')
|
|
1546
1547
|
})
|
|
1547
1548
|
.allow(false)
|
|
1548
1549
|
.description('Details of the registered license. False when no license is registered.')
|
|
1549
1550
|
.label('LicenseDetails'),
|
|
1550
|
-
suspended: Joi.boolean().example(false).description('Whether email operations are suspended due to license issues')
|
|
1551
|
+
suspended: Joi.boolean().example(false).description('Whether email operations are suspended due to license issues'),
|
|
1552
|
+
subscription: Joi.object({
|
|
1553
|
+
status: Joi.string()
|
|
1554
|
+
.valid('overdue', 'suspended')
|
|
1555
|
+
.example('overdue')
|
|
1556
|
+
.description(
|
|
1557
|
+
'overdue: a payment is due and EmailEngine keeps working until `until`; suspended: email processing has stopped until the subscription is in good standing'
|
|
1558
|
+
)
|
|
1559
|
+
.label('LicenseSubscriptionStatus'),
|
|
1560
|
+
code: Joi.string().allow(null).example('PaymentOverdue').description('Reason reported by the license server'),
|
|
1561
|
+
error: Joi.string().allow(null).example('Subscription payment overdue').description('Human-readable reason'),
|
|
1562
|
+
since: Joi.date().iso().allow(null).example('2026-12-01T10:00:00.000Z').description('When the payment became overdue or the subscription ended'),
|
|
1563
|
+
until: Joi.date().iso().allow(null).example('2026-12-08T10:00:00.000Z').description('When EmailEngine pauses, or paused')
|
|
1564
|
+
})
|
|
1565
|
+
.description('Present only while the subscription behind a subscription license is not in good standing')
|
|
1566
|
+
.label('LicenseSubscription')
|
|
1551
1567
|
}).label('LicenseInfo');
|
|
1552
1568
|
|
|
1553
1569
|
const lastErrorSchema = Joi.object({
|
package/lib/settings.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
const { accountDataKey } = require('./redis-keys');
|
|
4
|
+
const { keepsSubscriptionState } = require('./license-subscription');
|
|
4
5
|
const { redis } = require('./db');
|
|
5
6
|
const logger = require('./logger');
|
|
6
7
|
const { encrypt, decryptField } = require('./encrypt');
|
|
@@ -9,6 +10,14 @@ const getSecret = require('./get-secret');
|
|
|
9
10
|
|
|
10
11
|
const { DEFAULT_MAX_LOG_LINES, REDIS_PREFIX } = require('./consts');
|
|
11
12
|
const { PRIVILEGED_SETTINGS_KEYS } = require('./privileged-settings');
|
|
13
|
+
const { publishRevocation } = require('./revocation-events');
|
|
14
|
+
|
|
15
|
+
// A rotated IMAP proxy password ends the sessions the old one opened
|
|
16
|
+
async function announceRevokingChange(keys) {
|
|
17
|
+
if (keys.includes('imapProxyServerPassword')) {
|
|
18
|
+
await publishRevocation({ type: 'setting', key: 'imapProxyServerPassword' });
|
|
19
|
+
}
|
|
20
|
+
}
|
|
12
21
|
|
|
13
22
|
config.service = config.service || {};
|
|
14
23
|
|
|
@@ -296,7 +305,9 @@ module.exports = {
|
|
|
296
305
|
}
|
|
297
306
|
}
|
|
298
307
|
|
|
299
|
-
|
|
308
|
+
let result = await redis.hset(`${REDIS_PREFIX}settings`, key, value);
|
|
309
|
+
await announceRevokingChange([key]);
|
|
310
|
+
return result;
|
|
300
311
|
},
|
|
301
312
|
|
|
302
313
|
// Store a value only if the key does not exist yet (atomic HSETNX). Meant for one-shot
|
|
@@ -342,7 +353,9 @@ module.exports = {
|
|
|
342
353
|
await module.exports.clear('sentryAutoEnabled');
|
|
343
354
|
}
|
|
344
355
|
|
|
345
|
-
|
|
356
|
+
let result = await redis.hmset(`${REDIS_PREFIX}settings`, storeObj);
|
|
357
|
+
await announceRevokingChange(Object.keys(storeObj));
|
|
358
|
+
return result;
|
|
346
359
|
},
|
|
347
360
|
|
|
348
361
|
async clear(...keys) {
|
|
@@ -350,7 +363,9 @@ module.exports = {
|
|
|
350
363
|
if (!keys.length) {
|
|
351
364
|
return 0;
|
|
352
365
|
}
|
|
353
|
-
|
|
366
|
+
let result = await redis.hdel(`${REDIS_PREFIX}settings`, ...keys);
|
|
367
|
+
await announceRevokingChange(keys);
|
|
368
|
+
return result;
|
|
354
369
|
},
|
|
355
370
|
|
|
356
371
|
async getLoggingInfo(account, settingData) {
|
|
@@ -423,28 +438,36 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
|
|
|
423
438
|
throw err;
|
|
424
439
|
}
|
|
425
440
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
441
|
+
// The last registered license (tract): a trial may not be swapped for another trial, and the
|
|
442
|
+
// same key registered again keeps the subscription deadline and any suspension, since otherwise
|
|
443
|
+
// posting the file again, or the restart that re-imports a license file or
|
|
444
|
+
// EENGINE_PREPARED_LICENSE, would lift a suspension (lib/license-subscription.js). An unreadable
|
|
445
|
+
// record counts as no record.
|
|
446
|
+
let storedRecord = await redis.hget(`${REDIS_PREFIX}settings`, 'tract');
|
|
447
|
+
let stored;
|
|
448
|
+
try {
|
|
449
|
+
stored = JSON.parse(storedRecord || 'null');
|
|
450
|
+
} catch (err) {
|
|
451
|
+
stored = null;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
if (licenseData.trial && stored && stored.key !== licenseData.key) {
|
|
455
|
+
let err = new Error('Trial already activated');
|
|
456
|
+
err.code = 'ETrialActive';
|
|
457
|
+
throw err;
|
|
442
458
|
}
|
|
443
459
|
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
460
|
+
let storedKey = stored && typeof stored.key === 'string' ? stored.key : null;
|
|
461
|
+
let keepState = keepsSubscriptionState(storedKey, licenseData.key);
|
|
462
|
+
|
|
463
|
+
let multi = redis.multi().hset(`${REDIS_PREFIX}settings`, 'license', licenseFile);
|
|
464
|
+
if (!keepState) {
|
|
465
|
+
// A different key starts clean, and is checked online soon rather than when the last
|
|
466
|
+
// check of the key it replaces said: subcheck was stamped by that key's checks, and
|
|
467
|
+
// left in place it would hold off the first check of the new one by up to a day
|
|
468
|
+
multi = multi.hdel(`${REDIS_PREFIX}settings`, 'subexp', 'subsusp', 'subcheck');
|
|
469
|
+
}
|
|
470
|
+
await multi
|
|
448
471
|
.hset(
|
|
449
472
|
`${REDIS_PREFIX}settings`,
|
|
450
473
|
'tract',
|
|
@@ -501,7 +524,10 @@ ${Buffer.from(licenseFile, 'base64url').toString('base64')}
|
|
|
501
524
|
// and the trial Sentry default that activation may have applied. Used by the explicit
|
|
502
525
|
// remove-license actions and by the grace-period expiry in server.js.
|
|
503
526
|
async removeLicense() {
|
|
504
|
-
|
|
527
|
+
// The subscription deadline and any suspension stay, tied to the key in `tract`: registering the
|
|
528
|
+
// same key again must find them, or removing and re-adding it would lift a suspension. A
|
|
529
|
+
// different key clears them (setLicense)
|
|
530
|
+
await redis.hdel(`${REDIS_PREFIX}settings`, 'license');
|
|
505
531
|
await module.exports.clearTrialSentryDefault('license removal');
|
|
506
532
|
return true;
|
|
507
533
|
}
|
package/lib/sso.js
CHANGED
|
@@ -384,7 +384,30 @@ function buildOidcBellProvider(discoveryDoc, options) {
|
|
|
384
384
|
};
|
|
385
385
|
}
|
|
386
386
|
|
|
387
|
+
/**
|
|
388
|
+
* Whether the identity provider of an SSO admin session still admits its user: a profile with an id
|
|
389
|
+
* for Okta and OIDC, and for OIDC the email and group allow-lists, re-checked on every request so a
|
|
390
|
+
* change to them (after a restart) takes effect without waiting out the session cookie. Asked by
|
|
391
|
+
* both the session strategy and the message browser's `sess_` token, which rides the same cookie and
|
|
392
|
+
* used to skip the allow-list, so it kept working for a removed user. A local session is admitted.
|
|
393
|
+
*
|
|
394
|
+
* @param {Object} session - The `ee` session cookie
|
|
395
|
+
* @param {Object} allowList - parseAllowList() result
|
|
396
|
+
* @param {Object} allowGroups - parseGroupList() result
|
|
397
|
+
* @returns {boolean}
|
|
398
|
+
*/
|
|
399
|
+
function ssoSessionAdmitted(session, allowList, allowGroups) {
|
|
400
|
+
if (!session || (session.provider !== 'oidc' && session.provider !== 'okta')) {
|
|
401
|
+
return true;
|
|
402
|
+
}
|
|
403
|
+
if (!session.profile || !session.profile.id) {
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
return session.provider !== 'oidc' || isAuthorized(session.profile, allowList, allowGroups);
|
|
407
|
+
}
|
|
408
|
+
|
|
387
409
|
module.exports = {
|
|
410
|
+
ssoSessionAdmitted,
|
|
388
411
|
OIDC_ISSUER,
|
|
389
412
|
OIDC_CLIENT_ID,
|
|
390
413
|
OIDC_CLIENT_SECRET,
|