emailengine-app 2.87.1 → 2.88.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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +31 -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 +48 -10
- 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/dbsc/index.js +292 -0
- package/lib/dbsc/jwt.js +157 -0
- package/lib/dbsc/protocol.js +132 -0
- package/lib/dbsc/store.js +136 -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 +238 -0
- package/lib/oauth/gmail.js +18 -0
- package/lib/oauth/outlook-identity.js +54 -12
- package/lib/prepared-password.js +38 -0
- package/lib/privileged-settings.js +6 -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/routes-ui.js +4 -1
- package/lib/schemas.js +26 -2
- package/lib/session-default.js +13 -3
- package/lib/settings.js +47 -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 +86 -15
- package/lib/ui-routes/admin-config-routes.js +30 -281
- package/lib/ui-routes/auth-routes.js +17 -64
- package/lib/ui-routes/dbsc-routes.js +43 -0
- package/lib/ui-routes/license-routes.js +326 -0
- package/lib/web-safe-html.js +29 -0
- package/lib/webhook-delivery.js +21 -20
- package/lib/webhook-penalty.js +18 -17
- package/lib/webhooks.js +18 -0
- package/package.json +18 -18
- package/sbom.json +294 -294
- package/scan.js +2 -0
- package/server.js +253 -80
- package/static/css/flyonui.css +2 -2
- package/static/js/ui.js +11 -4
- package/static/licenses.html +27 -27
- package/translations/messages.pot +17 -17
- package/views/config/license.hbs +43 -16
- package/views/config/security.hbs +37 -0
- package/views/partials/side_menu.hbs +1 -1
- package/workers/api.js +128 -109
- package/workers/imap.js +4 -6
|
@@ -381,7 +381,7 @@ class IMAPCommand {
|
|
|
381
381
|
};
|
|
382
382
|
|
|
383
383
|
if (!handler.authenticates) {
|
|
384
|
-
return
|
|
384
|
+
return this.runHandler(handler, complete, next);
|
|
385
385
|
}
|
|
386
386
|
|
|
387
387
|
// One credential check at a time per connection. A client that pipelines several
|
|
@@ -394,9 +394,8 @@ class IMAPCommand {
|
|
|
394
394
|
return complete(null, { response: 'NO', message: 'Authentication already in progress' });
|
|
395
395
|
}
|
|
396
396
|
this.connection._authInFlight = true;
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
this.parsed,
|
|
397
|
+
this.runHandler(
|
|
398
|
+
handler,
|
|
400
399
|
(err, response) => {
|
|
401
400
|
if (err || !response || response.response !== 'OK') {
|
|
402
401
|
this.connection._authInFlight = false;
|
|
@@ -452,6 +451,34 @@ class IMAPCommand {
|
|
|
452
451
|
return callback();
|
|
453
452
|
}
|
|
454
453
|
|
|
454
|
+
// Runs a command handler. A handler that throws synchronously runs on a stream continuation
|
|
455
|
+
// (setImmediate or a literal's 'end'), where nothing above it catches, so the exception would
|
|
456
|
+
// reach the worker's uncaughtException handler and stop the whole proxy. Answer it as a bad
|
|
457
|
+
// command instead, counted like a parser error.
|
|
458
|
+
runHandler(handler, complete, next) {
|
|
459
|
+
try {
|
|
460
|
+
return handler.handler.call(this.connection, this.parsed, complete, next);
|
|
461
|
+
} catch (err) {
|
|
462
|
+
if (handler.authenticates) {
|
|
463
|
+
this.connection._authInFlight = false;
|
|
464
|
+
}
|
|
465
|
+
this.connection.logger.error(
|
|
466
|
+
{
|
|
467
|
+
err,
|
|
468
|
+
tnx: 'command',
|
|
469
|
+
cid: this.connection.id,
|
|
470
|
+
command: this.command
|
|
471
|
+
},
|
|
472
|
+
'Command handler failed'
|
|
473
|
+
);
|
|
474
|
+
this.connection.send(this.tag + ' BAD Invalid arguments');
|
|
475
|
+
if (!this.countBadResponses()) {
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
return next();
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
455
482
|
validateCommand(parsed, handler, callback) {
|
|
456
483
|
let schema = handler.schema || [];
|
|
457
484
|
let maxArgs = schema.length;
|
|
@@ -486,6 +513,19 @@ class IMAPCommand {
|
|
|
486
513
|
return callback(err);
|
|
487
514
|
}
|
|
488
515
|
|
|
516
|
+
// A NIL or a list where a string is declared. Only the leading required arguments are
|
|
517
|
+
// checked: there the position in the schema is the position in the command, while an
|
|
518
|
+
// optional argument further along shifts every argument after it.
|
|
519
|
+
for (let i = 0; i < schema.length && !schema[i].optional; i++) {
|
|
520
|
+
let attr = parsed.attributes[i];
|
|
521
|
+
if (schema[i].type === 'string' && (!attr || Array.isArray(attr))) {
|
|
522
|
+
let err = new Error('Invalid arguments');
|
|
523
|
+
err.responseCode = 400;
|
|
524
|
+
err.code = 'InvalidArguments';
|
|
525
|
+
return callback(err);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
489
529
|
callback();
|
|
490
530
|
}
|
|
491
531
|
|
|
@@ -22,6 +22,7 @@ const { getLocalAddress } = require('../utils/network');
|
|
|
22
22
|
|
|
23
23
|
const { redis } = require('../db');
|
|
24
24
|
const { createImapProxyAuthHandler, classifyCredentialFailure } = require('../imap-proxy-auth');
|
|
25
|
+
const { onRevocation } = require('../revocation-events');
|
|
25
26
|
const settings = require('../settings');
|
|
26
27
|
|
|
27
28
|
const { createCertHandler } = require('../cert-handler');
|
|
@@ -259,7 +260,15 @@ const createServer = function (options = {}) {
|
|
|
259
260
|
logger,
|
|
260
261
|
serverLogger,
|
|
261
262
|
metrics,
|
|
262
|
-
logRaw: EENGINE_LOG_RAW
|
|
263
|
+
logRaw: EENGINE_LOG_RAW,
|
|
264
|
+
recheck: authenticateImapProxy.recheck
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
// A revoked token, a deleted or changed account or a rotated proxy password ends the sessions
|
|
268
|
+
// it opened now rather than at the next periodic re-check
|
|
269
|
+
onRevocation(detail => {
|
|
270
|
+
// A change naming an account re-checks that account's sessions; anything else, all of them
|
|
271
|
+
server.onAuth.recheckSessions({ account: detail.account }).catch(err => logger.error({ msg: 'Proxy session re-check failed', err }));
|
|
263
272
|
});
|
|
264
273
|
|
|
265
274
|
return server;
|
|
@@ -8,6 +8,11 @@ const { PassThrough } = require('stream');
|
|
|
8
8
|
const { imapHandler } = require('./imap-core/index.js');
|
|
9
9
|
const { isImapResponseError, toImapResponseError, faultResponseError } = require('./response-error');
|
|
10
10
|
|
|
11
|
+
// How often an open proxied session re-asks whether its credential still admits it. Revocations
|
|
12
|
+
// announced over lib/revocation-events.js are acted on at once; this catches the rest (an expired
|
|
13
|
+
// token, the auth-failure safety net parking an account).
|
|
14
|
+
const RECHECK_INTERVAL = 60 * 1000;
|
|
15
|
+
|
|
11
16
|
class PassThroughLogger extends PassThrough {
|
|
12
17
|
constructor(opts = {}) {
|
|
13
18
|
super();
|
|
@@ -48,9 +53,77 @@ class PassThroughLogger extends PassThrough {
|
|
|
48
53
|
* @param {Object} deps.serverLogger Logger for authentication failures
|
|
49
54
|
* @param {Function} deps.metrics Metrics reporter
|
|
50
55
|
* @param {Boolean} [deps.logRaw] Log every proxied chunk
|
|
51
|
-
* @
|
|
56
|
+
* @param {Function} [deps.recheck] `(auth, session) => Promise<Boolean>`: whether the credential
|
|
57
|
+
* that opened a session still admits it. false ends the session, a rejection keeps it
|
|
58
|
+
* @param {Number} [deps.recheckInterval] How often open sessions are re-checked
|
|
59
|
+
* @returns {Function} (login, session, callback) handler, with `recheckSessions()` attached to run
|
|
60
|
+
* a re-check pass now (a credential was revoked) and `activeSessions` for inspection
|
|
52
61
|
*/
|
|
53
|
-
function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, metrics, logRaw }) {
|
|
62
|
+
function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, metrics, logRaw, recheck, recheckInterval = RECHECK_INTERVAL }) {
|
|
63
|
+
// Open proxied sessions and what they logged in with, so a revoked credential can end them.
|
|
64
|
+
// One timer serves all of them and runs only while there are any.
|
|
65
|
+
const activeSessions = new Set();
|
|
66
|
+
let recheckTimer = null;
|
|
67
|
+
let recheckInFlight = null;
|
|
68
|
+
|
|
69
|
+
const runRecheckPass = async account => {
|
|
70
|
+
// Sessions of the same credential share one answer, and the credentials are asked at once
|
|
71
|
+
const answers = new Map();
|
|
72
|
+
const pending = [...activeSessions]
|
|
73
|
+
.filter(entry => !account || entry.auth.username === account)
|
|
74
|
+
.map(entry => {
|
|
75
|
+
const key = JSON.stringify([entry.auth.username, entry.auth.password]);
|
|
76
|
+
if (!answers.has(key)) {
|
|
77
|
+
answers.set(
|
|
78
|
+
key,
|
|
79
|
+
recheck(entry.auth, entry.session).catch(err => {
|
|
80
|
+
logger.warn({ msg: 'Could not re-check a proxy session credential', account: entry.auth.username, err });
|
|
81
|
+
return true;
|
|
82
|
+
})
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
return { entry, answer: answers.get(key) };
|
|
86
|
+
});
|
|
87
|
+
for (const { entry, answer } of pending) {
|
|
88
|
+
if (!(await answer) && activeSessions.has(entry)) {
|
|
89
|
+
entry.revoke();
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// Without an account every open session is re-checked, and a call made while such a pass runs
|
|
95
|
+
// joins it. With one, only that account's sessions are (a token or account change names it).
|
|
96
|
+
const recheckSessions = ({ account } = {}) => {
|
|
97
|
+
if (!recheck) {
|
|
98
|
+
return Promise.resolve();
|
|
99
|
+
}
|
|
100
|
+
if (account) {
|
|
101
|
+
return runRecheckPass(account);
|
|
102
|
+
}
|
|
103
|
+
if (!recheckInFlight) {
|
|
104
|
+
recheckInFlight = runRecheckPass().finally(() => {
|
|
105
|
+
recheckInFlight = null;
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
return recheckInFlight;
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const trackSession = entry => {
|
|
112
|
+
activeSessions.add(entry);
|
|
113
|
+
if (recheck && !recheckTimer) {
|
|
114
|
+
recheckTimer = setInterval(() => recheckSessions(), recheckInterval);
|
|
115
|
+
recheckTimer.unref();
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
const untrackSession = entry => {
|
|
120
|
+
activeSessions.delete(entry);
|
|
121
|
+
if (!activeSessions.size && recheckTimer) {
|
|
122
|
+
clearInterval(recheckTimer);
|
|
123
|
+
recheckTimer = null;
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
|
|
54
127
|
// A refusal or a temporary failure the client is told to retry is a warning and reaches the
|
|
55
128
|
// client as the IMAP response it carries; anything else is a proxy fault, logged here and
|
|
56
129
|
// answered with a generic response so its text never reaches the client. Handing the fault
|
|
@@ -66,7 +139,7 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
|
|
|
66
139
|
};
|
|
67
140
|
|
|
68
141
|
// Wires the two legs together once imap-core hands over the client socket
|
|
69
|
-
const attachProxy = ({ session, account, downstream, upstream }) => {
|
|
142
|
+
const attachProxy = ({ session, account, downstream, upstream, auth }) => {
|
|
70
143
|
metrics(logger, 'events', 'inc', {
|
|
71
144
|
event: 'imapProxyConnected'
|
|
72
145
|
});
|
|
@@ -94,11 +167,13 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
|
|
|
94
167
|
// deflate/writeSocket error forwarders and destroys the upstream socket. Without it the
|
|
95
168
|
// upstream connection and its idle timer would leak (most visibly with COMPRESS enabled).
|
|
96
169
|
let proxyClosed = false;
|
|
170
|
+
let tracked = null;
|
|
97
171
|
const closeProxy = () => {
|
|
98
172
|
if (proxyClosed) {
|
|
99
173
|
return;
|
|
100
174
|
}
|
|
101
175
|
proxyClosed = true;
|
|
176
|
+
untrackSession(tracked);
|
|
102
177
|
|
|
103
178
|
try {
|
|
104
179
|
downstream.imapClient.close();
|
|
@@ -177,6 +252,21 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
|
|
|
177
252
|
teardownOn(downstream.imapClient.socket, 'close');
|
|
178
253
|
}
|
|
179
254
|
|
|
255
|
+
tracked = {
|
|
256
|
+
auth,
|
|
257
|
+
session,
|
|
258
|
+
revoke() {
|
|
259
|
+
proxyLogger.info({ msg: 'Closing proxied session, its credential no longer admits it' });
|
|
260
|
+
try {
|
|
261
|
+
upstream.socket.write('* BYE Credentials are no longer valid\r\n');
|
|
262
|
+
} catch (err) {
|
|
263
|
+
// ignore
|
|
264
|
+
}
|
|
265
|
+
closeProxy();
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
trackSession(tracked);
|
|
269
|
+
|
|
180
270
|
proxyLogger.info({ msg: 'Proxy mode enabled' });
|
|
181
271
|
};
|
|
182
272
|
|
|
@@ -204,7 +294,9 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
|
|
|
204
294
|
try {
|
|
205
295
|
downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
|
|
206
296
|
|
|
207
|
-
|
|
297
|
+
// Only what a re-check needs: the login object also holds the connection
|
|
298
|
+
const auth = { username: login.username, password: login.password };
|
|
299
|
+
session.onProxy = upstream => attachProxy({ session, account, downstream, upstream, auth });
|
|
208
300
|
|
|
209
301
|
if (downstream.imapClient.rawCapabilities) {
|
|
210
302
|
login.connection.send(
|
|
@@ -235,13 +327,16 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
|
|
|
235
327
|
};
|
|
236
328
|
};
|
|
237
329
|
|
|
238
|
-
|
|
330
|
+
const handler = function (login, session, callback) {
|
|
239
331
|
// imap-core ignores what the handler returns, so every outcome has to end in the callback
|
|
240
332
|
handleLogin(login, session).then(
|
|
241
333
|
response => callback(null, response),
|
|
242
334
|
err => callback(err)
|
|
243
335
|
);
|
|
244
336
|
};
|
|
337
|
+
handler.recheckSessions = recheckSessions;
|
|
338
|
+
handler.activeSessions = activeSessions;
|
|
339
|
+
return handler;
|
|
245
340
|
}
|
|
246
341
|
|
|
247
342
|
module.exports = { createProxyAuthHandler, PassThroughLogger };
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* What the online subscription check decides, as pure functions: server.js applies the result to
|
|
5
|
+
* Redis and to the workers, and the unit tests pin every rule here.
|
|
6
|
+
*
|
|
7
|
+
* State kept in the settings hash:
|
|
8
|
+
* subexp - the deadline (ms) until which EmailEngine keeps working while the subscription behind
|
|
9
|
+
* its license is not in good standing
|
|
10
|
+
* subsusp - JSON describing a suspension: the deadline has passed and the license server asked to
|
|
11
|
+
* keep the key (keepLicense), so the workers stop but the key stays registered
|
|
12
|
+
*
|
|
13
|
+
* The license server (postalsys.com) decides the deadline and sends it as graceUntil: 7 days after a
|
|
14
|
+
* failed monthly renewal, 28 after a yearly one, none after a cancellation. A server that sends no
|
|
15
|
+
* graceUntil gets the 28 days counted from the first refusal, and without keepLicense the key is
|
|
16
|
+
* removed when they run out, which is how every earlier release behaved.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const HOUR = 60 * 60 * 1000;
|
|
20
|
+
const DAY = 24 * HOUR;
|
|
21
|
+
|
|
22
|
+
// Days of service after the first refusal when the server names no deadline
|
|
23
|
+
const LEGACY_GRACE = 28 * DAY;
|
|
24
|
+
// How often the subscription is checked online: daily, and hourly while it is not in good standing
|
|
25
|
+
const CHECK_INTERVAL = DAY;
|
|
26
|
+
const OVERDUE_CHECK_INTERVAL = HOUR;
|
|
27
|
+
// The furthest a successful answer may postpone the next check
|
|
28
|
+
const MAX_LICENSE_CHECK_DELAY = 30 * DAY;
|
|
29
|
+
// A startup check is skipped when the last successful one is this recent
|
|
30
|
+
const STARTUP_CHECK_FRESHNESS = HOUR;
|
|
31
|
+
|
|
32
|
+
const toTime = value => {
|
|
33
|
+
if (value === null || value === undefined || value === '') {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
// Redis hands back a stored millisecond value as a string of digits
|
|
37
|
+
const time = typeof value === 'number' ? value : /^\d+$/.test(value) ? Number(value) : new Date(value).getTime();
|
|
38
|
+
return Number.isFinite(time) ? time : null;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Parses the stored subsusp value
|
|
43
|
+
* @param {string|null} raw
|
|
44
|
+
* @returns {Object|null} { code, error, since, overdueSince, endedAt } or null
|
|
45
|
+
*/
|
|
46
|
+
function parseSuspension(raw) {
|
|
47
|
+
if (!raw) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
try {
|
|
51
|
+
const parsed = JSON.parse(raw);
|
|
52
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
53
|
+
} catch (err) {
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Is a license one whose validity depends on a subscription, and so is checked online?
|
|
60
|
+
* Trial and other time-limited licenses carry their own expiry, lifetime ones never lapse.
|
|
61
|
+
* @param {Object} details - checkLicense() output
|
|
62
|
+
* @returns {boolean}
|
|
63
|
+
*/
|
|
64
|
+
const isSubscriptionLicense = details => !!details && !details.expires && !details.lt && !details.trial;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* How long to wait between online checks
|
|
68
|
+
* @param {Object} state - { subexp, subsusp } as stored
|
|
69
|
+
* @returns {number} milliseconds
|
|
70
|
+
*/
|
|
71
|
+
const checkInterval = state => (state && (toTime(state.subexp) || state.subsusp) ? OVERDUE_CHECK_INTERVAL : CHECK_INTERVAL);
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* What one answer of the license server changes
|
|
75
|
+
* @param {Object} result
|
|
76
|
+
* @param {boolean} result.ok - the answer was 2xx
|
|
77
|
+
* @param {Object} result.data - its JSON body
|
|
78
|
+
* @param {number} result.now
|
|
79
|
+
* @param {number|null} result.subexp - the stored deadline
|
|
80
|
+
* @returns {Object} { clear, resume, subexp, suspend, removeLicense, nextCheck }: clear drops subexp
|
|
81
|
+
* and subsusp; resume drops subsusp only (the deadline is in the future again); subexp is a deadline
|
|
82
|
+
* to store; suspend is the subsusp record to store; removeLicense is the legacy outcome; nextCheck is
|
|
83
|
+
* when the next online check is due (ms), or null to leave it
|
|
84
|
+
*/
|
|
85
|
+
function decide({ ok, data, now, subexp }) {
|
|
86
|
+
data = data || {};
|
|
87
|
+
|
|
88
|
+
if (ok) {
|
|
89
|
+
const validatedUntil = toTime(data.validatedUntil);
|
|
90
|
+
return {
|
|
91
|
+
clear: true,
|
|
92
|
+
resume: true,
|
|
93
|
+
subexp: null,
|
|
94
|
+
suspend: null,
|
|
95
|
+
removeLicense: false,
|
|
96
|
+
nextCheck: validatedUntil ? Math.min(now + MAX_LICENSE_CHECK_DELAY, validatedUntil) : null
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A refusal without invalidate is not about the subscription (bad input, a server error):
|
|
101
|
+
// nothing changes, EmailEngine never stops over the license server's own trouble
|
|
102
|
+
if (!data.invalidate) {
|
|
103
|
+
return { clear: false, resume: false, subexp: null, suspend: null, removeLicense: false, nextCheck: null };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const stored = toTime(subexp);
|
|
107
|
+
const deadline = toTime(data.graceUntil) || stored || now + LEGACY_GRACE;
|
|
108
|
+
|
|
109
|
+
if (deadline > now) {
|
|
110
|
+
// inside the window: working, even if a stored suspension said otherwise (the server's
|
|
111
|
+
// deadline is the one that counts, and it can move later)
|
|
112
|
+
return { clear: false, resume: true, subexp: deadline, suspend: null, removeLicense: false, nextCheck: now + OVERDUE_CHECK_INTERVAL };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
if (!data.keepLicense) {
|
|
116
|
+
return { clear: false, resume: false, subexp: null, suspend: null, removeLicense: true, nextCheck: null };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
return {
|
|
120
|
+
clear: false,
|
|
121
|
+
resume: false,
|
|
122
|
+
subexp: deadline,
|
|
123
|
+
suspend: {
|
|
124
|
+
code: typeof data.code === 'string' ? data.code.slice(0, 64) : 'SubscriptionInactive',
|
|
125
|
+
error: typeof data.error === 'string' ? data.error.slice(0, 256) : 'Subscription inactive',
|
|
126
|
+
since: new Date(deadline).toISOString(),
|
|
127
|
+
overdueSince: toTime(data.overdueSince) ? new Date(toTime(data.overdueSince)).toISOString() : null,
|
|
128
|
+
endedAt: toTime(data.endedAt) ? new Date(toTime(data.endedAt)).toISOString() : null
|
|
129
|
+
},
|
|
130
|
+
removeLicense: false,
|
|
131
|
+
nextCheck: now + OVERDUE_CHECK_INTERVAL
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* The suspension a stored deadline implies on its own: when it has passed and no suspension is
|
|
137
|
+
* recorded yet (the license server could not be asked, or the deadline ran out while EmailEngine
|
|
138
|
+
* was not running), EmailEngine suspends itself and lets the next answer of the server decide
|
|
139
|
+
* @param {number|string|null} subexp - the stored deadline
|
|
140
|
+
* @param {string|null} subsusp - the stored suspension
|
|
141
|
+
* @param {number} now
|
|
142
|
+
* @returns {Object|null} the suspension record to store, or null
|
|
143
|
+
*/
|
|
144
|
+
function expiredSuspension(subexp, subsusp, now) {
|
|
145
|
+
const deadline = toTime(subexp);
|
|
146
|
+
if (parseSuspension(subsusp) || !deadline || deadline > now) {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
return { code: 'SubscriptionInactive', error: 'Subscription inactive', since: new Date(deadline).toISOString() };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* What a start of EmailEngine does before any worker runs
|
|
154
|
+
* @param {Object} input
|
|
155
|
+
* @param {Object|false} input.details - the loaded license (checkLicense() output), or false
|
|
156
|
+
* @param {number|string|null} input.subexp - the stored deadline
|
|
157
|
+
* @param {string|null} input.subsusp - the stored suspension
|
|
158
|
+
* @param {number|string|null} input.subcheck - when the last online check ran (ms)
|
|
159
|
+
* @param {number} input.now
|
|
160
|
+
* @returns {Object} { suspension, checkNow }: suspension is the record to start suspended with, or
|
|
161
|
+
* null; checkNow asks for an online check right away instead of in 20 minutes
|
|
162
|
+
*/
|
|
163
|
+
function startupPlan({ details, subexp, subsusp, subcheck, now }) {
|
|
164
|
+
if (!isSubscriptionLicense(details)) {
|
|
165
|
+
return { suspension: null, checkNow: false };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const deadline = toTime(subexp);
|
|
169
|
+
const suspension = parseSuspension(subsusp) || expiredSuspension(subexp, subsusp, now);
|
|
170
|
+
|
|
171
|
+
const lastCheck = toTime(subcheck);
|
|
172
|
+
const recentlyChecked = !!lastCheck && now - lastCheck < STARTUP_CHECK_FRESHNESS;
|
|
173
|
+
// a restart loop costs one call an hour, whatever the reason to check
|
|
174
|
+
const checkNow = (!!suspension || !!deadline || details.billing === 'monthly') && !recentlyChecked;
|
|
175
|
+
|
|
176
|
+
return { suspension, checkNow };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Does registering a license keep the stored subscription state? Only when it is the key already
|
|
181
|
+
* registered: registering the same file again (by hand, through the API, or at every start from a
|
|
182
|
+
* license file or EENGINE_PREPARED_LICENSE) must not lift a suspension. A different key starts clean,
|
|
183
|
+
* and the online check that follows registration decides its standing.
|
|
184
|
+
* @param {string|null} storedKey - key of the license currently registered
|
|
185
|
+
* @param {string} newKey - key of the license being registered
|
|
186
|
+
* @returns {boolean}
|
|
187
|
+
*/
|
|
188
|
+
const keepsSubscriptionState = (storedKey, newKey) => !!storedKey && !!newKey && storedKey === newKey;
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* The subscription state as the license page and the API report it
|
|
192
|
+
* @param {Object} input - { subexp, suspension, now }
|
|
193
|
+
* @returns {Object|null} { status, code, error, since, until, days } or null when in good standing;
|
|
194
|
+
* days is how many whole days remain until `until` (0 once it has passed)
|
|
195
|
+
*/
|
|
196
|
+
function subscriptionView({ subexp, suspension, now }) {
|
|
197
|
+
let view = null;
|
|
198
|
+
if (suspension) {
|
|
199
|
+
view = {
|
|
200
|
+
status: 'suspended',
|
|
201
|
+
code: suspension.code || null,
|
|
202
|
+
error: suspension.error || null,
|
|
203
|
+
since: suspension.overdueSince || suspension.endedAt || suspension.since || null,
|
|
204
|
+
until: suspension.since || null
|
|
205
|
+
};
|
|
206
|
+
} else if (toTime(subexp)) {
|
|
207
|
+
const deadline = toTime(subexp);
|
|
208
|
+
view = { status: deadline > now ? 'overdue' : 'suspended', code: null, error: null, since: null, until: new Date(deadline).toISOString() };
|
|
209
|
+
}
|
|
210
|
+
if (view) {
|
|
211
|
+
const until = toTime(view.until);
|
|
212
|
+
view.days = until ? Math.max(Math.ceil((until - now) / DAY), 0) : 0;
|
|
213
|
+
}
|
|
214
|
+
return view;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Is the subscription behind a license reported as suspended?
|
|
219
|
+
* @param {Object} licenseInfo - the `license` command's answer
|
|
220
|
+
* @returns {boolean}
|
|
221
|
+
*/
|
|
222
|
+
const isSuspended = licenseInfo => !!(licenseInfo && licenseInfo.subscription && licenseInfo.subscription.status === 'suspended');
|
|
223
|
+
|
|
224
|
+
module.exports = {
|
|
225
|
+
decide,
|
|
226
|
+
startupPlan,
|
|
227
|
+
expiredSuspension,
|
|
228
|
+
checkInterval,
|
|
229
|
+
subscriptionView,
|
|
230
|
+
isSuspended,
|
|
231
|
+
parseSuspension,
|
|
232
|
+
isSubscriptionLicense,
|
|
233
|
+
keepsSubscriptionState,
|
|
234
|
+
LEGACY_GRACE,
|
|
235
|
+
CHECK_INTERVAL,
|
|
236
|
+
OVERDUE_CHECK_INTERVAL,
|
|
237
|
+
MAX_LICENSE_CHECK_DELAY
|
|
238
|
+
};
|
package/lib/oauth/gmail.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { isEmail } = require('../utils/is-email');
|
|
3
4
|
const packageData = require('../../package.json');
|
|
4
5
|
const {
|
|
5
6
|
formatPartialSecretKey,
|
|
@@ -220,6 +221,22 @@ function workspaceDomainOf(idTokenPayload) {
|
|
|
220
221
|
return hd || null;
|
|
221
222
|
}
|
|
222
223
|
|
|
224
|
+
/**
|
|
225
|
+
* The address an ID token vouches for, or null. Google marks an address it has not confirmed with
|
|
226
|
+
* `email_verified: false` (a Google account registered with a third-party address nobody proved),
|
|
227
|
+
* and such an address is no evidence of who signed in: it used to become the account address and the
|
|
228
|
+
* identity an expectedEmail pin was checked against.
|
|
229
|
+
*
|
|
230
|
+
* @param {Object|null} idTokenPayload - decoded ID token payload (lib/decode-jwt-payload.js)
|
|
231
|
+
* @returns {String|null}
|
|
232
|
+
*/
|
|
233
|
+
function verifiedEmailOf(idTokenPayload) {
|
|
234
|
+
if (!idTokenPayload || idTokenPayload.email_verified === false || !isEmail(idTokenPayload.email)) {
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
return idTokenPayload.email;
|
|
238
|
+
}
|
|
239
|
+
|
|
223
240
|
class GmailOauth {
|
|
224
241
|
constructor(opts) {
|
|
225
242
|
// The network route of the account this client acts for (see getAccountHttpRoute()). Every
|
|
@@ -955,6 +972,7 @@ module.exports.GmailOauth = GmailOauth;
|
|
|
955
972
|
module.exports.checkForFlags = checkForFlags;
|
|
956
973
|
module.exports.checkForUserFlags = checkForUserFlags;
|
|
957
974
|
module.exports.workspaceDomainOf = workspaceDomainOf;
|
|
975
|
+
module.exports.verifiedEmailOf = verifiedEmailOf;
|
|
958
976
|
module.exports.GMAIL_SCOPES = GMAIL_SCOPES;
|
|
959
977
|
module.exports.GMAIL_API_SCOPES = GMAIL_API_SCOPES;
|
|
960
978
|
module.exports.GMAIL_PROVIDERS = GMAIL_PROVIDERS;
|
|
@@ -24,38 +24,80 @@ const { isEmail } = require('../utils/is-email');
|
|
|
24
24
|
// and the user principal name are offered, because either can be the stable identity for a tenant and
|
|
25
25
|
// they routinely differ (user@contoso.com vs user@contoso.onmicrosoft.com).
|
|
26
26
|
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
//
|
|
27
|
+
// The mailbox address (`mail` on the Graph profile, `email` in the id_token) is a directory attribute
|
|
28
|
+
// a tenant administrator can set to any address, in a domain the tenant never proved it owns, and
|
|
29
|
+
// Microsoft returns it unchanged. An address there is only evidence when its domain is one the issuing
|
|
30
|
+
// tenant has verified: the domain of the user principal name (which Entra ID only accepts in a
|
|
31
|
+
// verified domain), a domain the Graph branch read from /v1.0/organization, or an id_token that marks
|
|
32
|
+
// it verified with the `xms_edov` claim. Otherwise anyone administering any tenant could satisfy an
|
|
33
|
+
// expectedEmail pin for an address they do not own. Verified against Entra ID on 2026-11-07.
|
|
34
|
+
//
|
|
35
|
+
// `email` is the first verified identity. It used to fall back to the client_info address, which let
|
|
36
|
+
// the browser choose the account's persisted address and, through `username || email`, its login.
|
|
32
37
|
//
|
|
33
38
|
// `username` is the credential EmailEngine authenticates with (XOAUTH2), so it is verified-only with no
|
|
34
39
|
// clientInfo fallback. The profile's userPrincipalName is taken as-is rather than filtered as an address,
|
|
35
40
|
// matching the previous behavior - a tenant whose UPN is not email-shaped must still be able to log in.
|
|
36
41
|
function resolveOutlookUserInfo(sources) {
|
|
37
|
-
const { clientInfo, idTokenPayload, profile } = sources || {};
|
|
42
|
+
const { clientInfo, idTokenPayload, profile, verifiedDomains } = sources || {};
|
|
38
43
|
|
|
39
44
|
// isEmail already rejects non-strings, so these only normalize a miss to null.
|
|
40
45
|
const asEmail = value => isEmail(value) || null;
|
|
41
46
|
const asString = value => (typeof value === 'string' && value ? value : null);
|
|
47
|
+
const domainOf = address => address.slice(address.lastIndexOf('@') + 1).toLowerCase();
|
|
42
48
|
|
|
43
49
|
const profileUpn = asString(profile && profile.userPrincipalName);
|
|
44
50
|
const idTokenUpn = asEmail(idTokenPayload && idTokenPayload.preferred_username);
|
|
51
|
+
const upnAddresses = [idTokenUpn, asEmail(profileUpn)].filter(Boolean);
|
|
52
|
+
|
|
53
|
+
const trustedDomains = new Set([...upnAddresses.map(domainOf), ...(verifiedDomains || []).map(domain => domain.toLowerCase())]);
|
|
54
|
+
const vouched = address => trustedDomains.has(domainOf(address));
|
|
55
|
+
|
|
56
|
+
const profileMail = asEmail(profile && profile.mail);
|
|
57
|
+
const idTokenEmail = asEmail(idTokenPayload && idTokenPayload.email);
|
|
58
|
+
const mailboxAddresses = [];
|
|
59
|
+
if (profileMail && vouched(profileMail)) {
|
|
60
|
+
mailboxAddresses.push(profileMail);
|
|
61
|
+
}
|
|
62
|
+
if (idTokenEmail && (idTokenPayload.xms_edov === true || vouched(idTokenEmail))) {
|
|
63
|
+
mailboxAddresses.push(idTokenEmail);
|
|
64
|
+
}
|
|
45
65
|
|
|
46
|
-
// One list in preference order does both jobs: membership answers "did the provider
|
|
66
|
+
// One list in preference order does both jobs: membership answers "did the provider vouch for this
|
|
47
67
|
// address", and the first entry is the best address to show. Keeping two orderings in sync by hand
|
|
48
68
|
// would be a silent bug the moment they drifted.
|
|
49
|
-
const verifiedIdentities = [
|
|
50
|
-
...new Set([asEmail(profile && profile.mail), asEmail(idTokenPayload && idTokenPayload.email), idTokenUpn, asEmail(profileUpn)].filter(Boolean))
|
|
51
|
-
];
|
|
69
|
+
const verifiedIdentities = [...new Set([...mailboxAddresses, ...upnAddresses])];
|
|
52
70
|
|
|
53
71
|
return {
|
|
54
72
|
name: asString(idTokenPayload && idTokenPayload.name) || asString(profile && profile.displayName) || asString(clientInfo && clientInfo.name),
|
|
55
|
-
email: verifiedIdentities[0] ||
|
|
73
|
+
email: verifiedIdentities[0] || null,
|
|
56
74
|
username: idTokenUpn || profileUpn,
|
|
57
75
|
verifiedIdentities
|
|
58
76
|
};
|
|
59
77
|
}
|
|
60
78
|
|
|
61
|
-
|
|
79
|
+
/**
|
|
80
|
+
* The domains the signed-in user's tenant has verified, from Graph /v1.0/organization (covered by
|
|
81
|
+
* User.Read). A Graph `mail` value is only identity evidence in one of these or in the domain of the
|
|
82
|
+
* user principal name. An empty list (a personal Microsoft account has no organization, or the request
|
|
83
|
+
* failed) leaves only the user principal name's domain, which narrows what is accepted and never
|
|
84
|
+
* widens it.
|
|
85
|
+
*
|
|
86
|
+
* @param {Object} oAuth2Client - The Outlook OAuth2 client (`request()`, `apiBase`)
|
|
87
|
+
* @param {string} accessToken
|
|
88
|
+
* @param {Object} logger
|
|
89
|
+
* @returns {Promise<string[]>}
|
|
90
|
+
*/
|
|
91
|
+
async function readTenantVerifiedDomains(oAuth2Client, accessToken, logger) {
|
|
92
|
+
try {
|
|
93
|
+
const res = await oAuth2Client.request(accessToken, `${oAuth2Client.apiBase}/v1.0/organization?$select=verifiedDomains`);
|
|
94
|
+
return ((res && res.value) || [])
|
|
95
|
+
.flatMap(org => (Array.isArray(org.verifiedDomains) ? org.verifiedDomains : []).map(domain => domain && domain.name))
|
|
96
|
+
.filter(Boolean);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
logger.warn({ msg: 'Could not read the verified domains of the Microsoft tenant', err });
|
|
99
|
+
return [];
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
module.exports = { resolveOutlookUserInfo, readTenantVerifiedDomains };
|
|
@@ -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 };
|