emailengine-app 2.84.2 → 2.86.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 +29 -9
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +107 -0
- package/Dockerfile +20 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +2 -2
- package/bin/emailengine.js +434 -408
- package/config/default.toml +2 -0
- package/copy-static-files.sh +41 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16563 -0
- package/eslint.config.js +81 -99
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +230 -170
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/format.js +4 -3
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +255 -38
- package/lib/api-routes/blocklist-routes.js +91 -4
- package/lib/api-routes/delivery-test-routes.js +27 -4
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +110 -12
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +44 -5
- package/lib/api-routes/message-routes.js +112 -10
- package/lib/api-routes/oauth2-app-routes.js +63 -23
- package/lib/api-routes/outbox-routes.js +97 -52
- package/lib/api-routes/permission-map.js +67 -7
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +34 -6
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +337 -309
- package/lib/api-routes/template-routes.js +45 -8
- package/lib/api-routes/token-routes.js +152 -100
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +132 -6
- package/lib/bounce-detect.js +397 -205
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -45
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +137 -184
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +60 -22
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +372 -242
- package/lib/email-client/imap/subconnection.js +8 -30
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +228 -164
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/notification-handler.js +1 -2
- package/lib/email-client/outlook-client.js +372 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/gateway.js +19 -4
- package/lib/get-raw-email.js +25 -107
- package/lib/hapi-request-logger.js +107 -0
- package/lib/health.js +75 -0
- package/lib/imapproxy/imap-core/README.md +6 -5
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/mcp/tools.js +37 -8
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +36 -0
- package/lib/oauth/outlook-mailbox.js +35 -0
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +631 -656
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/pbkdf2-phc.js +1 -1
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +164 -40
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +63 -0
- package/lib/timezones.js +109 -0
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +7 -6
- package/lib/tools.js +48 -51
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +475 -454
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +152 -100
- package/lib/ui-routes/admin-entities-routes.js +93 -21
- package/lib/ui-routes/auth-routes.js +90 -38
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/oauth-config-routes.js +124 -82
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/route-helpers.js +19 -3
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/utils/back-off.js +82 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/murmurhash3.js +66 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/utils/version.js +74 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +56 -0
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +93 -45
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +37 -38
- package/sbom.json +7902 -1
- package/server.js +784 -518
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +225 -1060
- package/translations/messages.pot +62 -63
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +24 -2
- package/views/config/service.hbs +47 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +840 -611
- package/workers/export.js +17 -632
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +18 -448
- package/lib/email-client/outlook-fallback-poll.js +0 -30
package/workers/api.js
CHANGED
|
@@ -8,7 +8,14 @@ const logger = require('../lib/logger');
|
|
|
8
8
|
const Path = require('path');
|
|
9
9
|
const Gettext = require('@postalsys/gettext');
|
|
10
10
|
const { loadTranslations, gt, joiLocales, locales } = require('../lib/translations');
|
|
11
|
-
const {
|
|
11
|
+
const {
|
|
12
|
+
accountStateLabel,
|
|
13
|
+
formatServerState,
|
|
14
|
+
identityErrorView,
|
|
15
|
+
workspaceErrorView,
|
|
16
|
+
renderRedirect,
|
|
17
|
+
isClientError
|
|
18
|
+
} = require('../lib/ui-routes/route-helpers');
|
|
12
19
|
const { boundRouteBinding } = require('../lib/api-routes/account-binding');
|
|
13
20
|
const util = require('util');
|
|
14
21
|
const { webhooks: Webhooks } = require('../lib/webhooks');
|
|
@@ -40,8 +47,6 @@ const {
|
|
|
40
47
|
constantTimeEqual,
|
|
41
48
|
verifyServiceSignature,
|
|
42
49
|
SIGNING_PURPOSE,
|
|
43
|
-
claimFormNonce,
|
|
44
|
-
releaseFormNonce,
|
|
45
50
|
setAdminSession,
|
|
46
51
|
isEndedSession
|
|
47
52
|
} = require('../lib/tools');
|
|
@@ -55,7 +60,7 @@ const Boom = require('@hapi/boom');
|
|
|
55
60
|
const Cookie = require('@hapi/cookie');
|
|
56
61
|
const Crumb = require('@hapi/crumb');
|
|
57
62
|
const Joi = require('joi');
|
|
58
|
-
const
|
|
63
|
+
const requestLogger = require('../lib/hapi-request-logger');
|
|
59
64
|
const Inert = require('@hapi/inert');
|
|
60
65
|
const Vision = require('@hapi/vision');
|
|
61
66
|
const Accept = require('@hapi/accept');
|
|
@@ -67,6 +72,9 @@ const { registeredPublishers, openChangeStream } = require('../lib/response-stre
|
|
|
67
72
|
const { oauth2Apps } = require('../lib/oauth2-apps');
|
|
68
73
|
const { decodeJwtPayload } = require('../lib/oauth/decode-jwt-payload');
|
|
69
74
|
const { resolveOutlookUserInfo } = require('../lib/oauth/outlook-identity');
|
|
75
|
+
const { resolveOutlookMailbox } = require('../lib/oauth/outlook-mailbox');
|
|
76
|
+
const { isValidOAuthState } = require('../lib/oauth/state');
|
|
77
|
+
const { completeAccountSetup } = require('../lib/ui-routes/account-setup');
|
|
70
78
|
const { buildRetrySetup } = require('../lib/oauth/retry-setup');
|
|
71
79
|
const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity } = require('../lib/account/expected-identity');
|
|
72
80
|
|
|
@@ -81,6 +89,7 @@ const { routeGrant, perRequestSurfaceAdmits, sessionTokenAdmits } = require('../
|
|
|
81
89
|
const { mcpOptions } = require('../lib/api-routes/route-metadata');
|
|
82
90
|
|
|
83
91
|
const { redis } = require('../lib/db');
|
|
92
|
+
const { createHealthChecks } = require('../lib/health');
|
|
84
93
|
const { Account } = require('../lib/account');
|
|
85
94
|
const settings = require('../lib/settings');
|
|
86
95
|
|
|
@@ -117,6 +126,9 @@ const {
|
|
|
117
126
|
|
|
118
127
|
const registerApiRoutes = require('../lib/api-routes');
|
|
119
128
|
const { securityHeadersExt, attachSecurityContext, isAdminPath, isMachineRoute, isSecureOrigin, CSP_MODES } = require('../lib/security-headers');
|
|
129
|
+
const { deprecationExt } = require('../lib/deprecations');
|
|
130
|
+
const { errorCodeExt } = require('../lib/api-error-codes');
|
|
131
|
+
const { apiCallDuration } = require('../lib/request-timing');
|
|
120
132
|
const { registerHandlebarsHelpers } = require('../lib/handlebars-helpers');
|
|
121
133
|
|
|
122
134
|
const {
|
|
@@ -229,6 +241,9 @@ const ADMIN_ACCESS_ADDRESSES = readEnvList('EENGINE_ADMIN_ACCESS_ADDRESSES');
|
|
|
229
241
|
// the API proxy setting is on, which is the historical behavior; see resolveClientIp().
|
|
230
242
|
const API_PROXY_ADDRESSES = readEnvList('EENGINE_API_PROXY_ADDRESSES');
|
|
231
243
|
|
|
244
|
+
// How long a shutdown waits for requests in flight, just below the main thread's WORKER_DRAIN_TIMEOUT
|
|
245
|
+
const API_DRAIN_TIMEOUT = 6000;
|
|
246
|
+
|
|
232
247
|
const IMAP_WORKER_COUNT = getWorkerCount(readEnvValue('EENGINE_WORKERS') || (config.workers && config.workers.imap)) || 4;
|
|
233
248
|
|
|
234
249
|
// Max POST body size for message uploads
|
|
@@ -370,7 +385,7 @@ async function sendWebhook(account, event, data) {
|
|
|
370
385
|
payload.data = data;
|
|
371
386
|
}
|
|
372
387
|
|
|
373
|
-
await Webhooks.
|
|
388
|
+
await Webhooks.enqueue(event, payload);
|
|
374
389
|
}
|
|
375
390
|
|
|
376
391
|
async function onCommand(command) {
|
|
@@ -383,12 +398,32 @@ async function onCommand(command) {
|
|
|
383
398
|
// reconciler is a singleton but the HTTPS listeners are not, and a sibling worker that
|
|
384
399
|
// kept its old context would go on serving the certificate that was just replaced.
|
|
385
400
|
return refreshApiTls ? await refreshApiTls() : { updated: false };
|
|
401
|
+
case 'close':
|
|
402
|
+
return await drainApiServer();
|
|
386
403
|
default:
|
|
387
404
|
logger.debug({ msg: 'Unhandled command', command });
|
|
388
405
|
return 999;
|
|
389
406
|
}
|
|
390
407
|
}
|
|
391
408
|
|
|
409
|
+
/**
|
|
410
|
+
* Stops taking new connections and waits for the requests in flight, so a shutdown no longer cuts
|
|
411
|
+
* them. Readiness turns 503 first, which tells a load balancer to stop sending traffic here. The
|
|
412
|
+
* main thread bounds the whole wait with its own drain timeout, this one is just below it.
|
|
413
|
+
*/
|
|
414
|
+
async function drainApiServer() {
|
|
415
|
+
apiDraining = true;
|
|
416
|
+
if (!sessionAuthServer) {
|
|
417
|
+
return true;
|
|
418
|
+
}
|
|
419
|
+
try {
|
|
420
|
+
await sessionAuthServer.stop({ timeout: API_DRAIN_TIMEOUT });
|
|
421
|
+
} catch (err) {
|
|
422
|
+
logger.warn({ msg: 'Failed to stop the API server cleanly', err });
|
|
423
|
+
}
|
|
424
|
+
return true;
|
|
425
|
+
}
|
|
426
|
+
|
|
392
427
|
function publishChangeEvent(data) {
|
|
393
428
|
// Nothing to do (and no reason to compute the badge label) when no SSE client is
|
|
394
429
|
// subscribed - the common case whenever no admin browser has the dashboard open.
|
|
@@ -422,7 +457,8 @@ function publishChangeEvent(data) {
|
|
|
422
457
|
|
|
423
458
|
// The Hapi server, published by init() once the session strategy is registered and the boot-time
|
|
424
459
|
// default has been decided, so the authData branch of the settings dispatcher below cannot set a
|
|
425
|
-
// strategy that does not exist yet or race the boot-time server.auth.default() call
|
|
460
|
+
// strategy that does not exist yet or race the boot-time server.auth.default() call. Also what the
|
|
461
|
+
// shutdown drain stops
|
|
426
462
|
let sessionAuthServer = null;
|
|
427
463
|
|
|
428
464
|
// Installs a renewed certificate on this worker's own HTTPS listener. Published by init() when the
|
|
@@ -497,13 +533,16 @@ parentPort.on('message', message => {
|
|
|
497
533
|
}
|
|
498
534
|
});
|
|
499
535
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
gt.setLocale((await settings.get('locale')) || 'en');
|
|
504
|
-
|
|
505
|
-
registerHandlebarsHelpers(handlebars, { gt });
|
|
536
|
+
// Set by the certificate timer from the startup prechecks (scheduleCertificateReconciler) and read
|
|
537
|
+
// by the onPreResponse extension (registerResponseExtensions)
|
|
538
|
+
let assertPreconditionResult;
|
|
506
539
|
|
|
540
|
+
/**
|
|
541
|
+
* Builds the hapi server, with the API TLS context when the API is served over HTTPS
|
|
542
|
+
* @returns {Promise<Object>} The server, the certificate handler, the API TLS context and the
|
|
543
|
+
* SO_REUSEPORT listener (null unless several API workers share the port)
|
|
544
|
+
*/
|
|
545
|
+
async function createApiServer() {
|
|
507
546
|
// Base Hapi options shared by both the default and SO_REUSEPORT binding paths
|
|
508
547
|
const serverOptions = {
|
|
509
548
|
// hapi's default prints every internal request error to stderr; the request error
|
|
@@ -594,8 +633,10 @@ const init = async () => {
|
|
|
594
633
|
});
|
|
595
634
|
}
|
|
596
635
|
|
|
597
|
-
|
|
636
|
+
return { server, certHandler, apiTlsContext, reusePortListener };
|
|
637
|
+
}
|
|
598
638
|
|
|
639
|
+
function decorateApiToolkit(server, certHandler, apiTlsContext) {
|
|
599
640
|
// A read-only view of the certificate store for routes. Ordering a certificate is the
|
|
600
641
|
// reconciler's job - it owns the state a page follows, the retry pacing and the listener
|
|
601
642
|
// reload - and the difference between reading and ordering is one argument
|
|
@@ -626,7 +667,9 @@ const init = async () => {
|
|
|
626
667
|
enabled: !!API_TLS,
|
|
627
668
|
active: apiTlsContext ? apiTlsContext.active : null
|
|
628
669
|
}));
|
|
670
|
+
}
|
|
629
671
|
|
|
672
|
+
function registerLocaleExtension(server) {
|
|
630
673
|
server.ext('onPreAuth', async (request, h) => {
|
|
631
674
|
const tags = (request.route && request.route.settings && request.route.settings.tags) || [];
|
|
632
675
|
// Skip if it's a static file route
|
|
@@ -701,7 +744,9 @@ const init = async () => {
|
|
|
701
744
|
|
|
702
745
|
return h.continue;
|
|
703
746
|
});
|
|
747
|
+
}
|
|
704
748
|
|
|
749
|
+
function registerRequestContextExtension(server) {
|
|
705
750
|
server.ext('onRequest', async (request, h) => {
|
|
706
751
|
// set default, will be overriden once active language is resolved
|
|
707
752
|
request.app.gt = gt;
|
|
@@ -777,7 +822,9 @@ const init = async () => {
|
|
|
777
822
|
|
|
778
823
|
return h.continue;
|
|
779
824
|
});
|
|
825
|
+
}
|
|
780
826
|
|
|
827
|
+
function buildOpenApiOptions() {
|
|
781
828
|
const openApiOptions = {
|
|
782
829
|
// Spec-shaping options (tag list and order, security scheme, external docs) live in
|
|
783
830
|
// lib/swagger-options.js so the document can be reproduced outside a running server
|
|
@@ -791,6 +838,10 @@ const init = async () => {
|
|
|
791
838
|
cors: !!CORS_CONFIG
|
|
792
839
|
};
|
|
793
840
|
|
|
841
|
+
return openApiOptions;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
function registerApiTokenAuth(server) {
|
|
794
845
|
server.auth.scheme(API_TOKEN_SCHEME, apiTokenScheme);
|
|
795
846
|
|
|
796
847
|
// Authentication for API calls
|
|
@@ -1167,7 +1218,26 @@ const init = async () => {
|
|
|
1167
1218
|
return { isValid: true, credentials: { token }, artifacts: tokenData };
|
|
1168
1219
|
}
|
|
1169
1220
|
});
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
// The version an SSO login stamps into its session, so the checks that end a session later can
|
|
1224
|
+
// compare against it. The password logins in lib/ui-routes/auth-routes.js stamp the same field
|
|
1225
|
+
// from the same place; without it a session is refused on the first request after any version
|
|
1226
|
+
// bump, which is a forced re-login rather than a lockout.
|
|
1227
|
+
//
|
|
1228
|
+
// Read by both strategies that accept a session: the cookie strategy below, and the session
|
|
1229
|
+
// token branch of the api-token strategy above - the two credentials the same cookie carries,
|
|
1230
|
+
// and "log out all sessions" has to end both.
|
|
1231
|
+
const sessionPasswordVersion = async () => {
|
|
1232
|
+
const authData = await settings.get('authData');
|
|
1233
|
+
return (authData && authData.passwordVersion) || 0;
|
|
1234
|
+
};
|
|
1170
1235
|
|
|
1236
|
+
/**
|
|
1237
|
+
* Registers the cookie plugins and the admin session strategy
|
|
1238
|
+
* @returns {Promise<boolean>} Whether the cookies are marked Secure
|
|
1239
|
+
*/
|
|
1240
|
+
async function registerSessionAuth(server) {
|
|
1171
1241
|
// needed for auth session and flash messages
|
|
1172
1242
|
await server.register(Cookie);
|
|
1173
1243
|
await server.register(Bell);
|
|
@@ -1185,20 +1255,6 @@ const init = async () => {
|
|
|
1185
1255
|
isSecure: secureCookie
|
|
1186
1256
|
});
|
|
1187
1257
|
|
|
1188
|
-
// The version an SSO login stamps into its session, so the checks that end a session later can
|
|
1189
|
-
// compare against it. The password logins in lib/ui-routes/auth-routes.js stamp the same field
|
|
1190
|
-
// from the same place; without it a session is refused on the first request after any version
|
|
1191
|
-
// bump, which is a forced re-login rather than a lockout.
|
|
1192
|
-
//
|
|
1193
|
-
// Read by both strategies that accept a session: the cookie strategy below, and the session
|
|
1194
|
-
// token branch of the api-token strategy above - the two credentials the same cookie carries,
|
|
1195
|
-
// and "log out all sessions" has to end both. Declared here rather than above because both
|
|
1196
|
-
// consumers only call it at request time, which is after this whole function has run.
|
|
1197
|
-
const sessionPasswordVersion = async () => {
|
|
1198
|
-
const authData = await settings.get('authData');
|
|
1199
|
-
return (authData && authData.passwordVersion) || 0;
|
|
1200
|
-
};
|
|
1201
|
-
|
|
1202
1258
|
// Authentication for admin pages
|
|
1203
1259
|
server.auth.strategy('session', 'cookie', {
|
|
1204
1260
|
cookie: {
|
|
@@ -1295,27 +1351,31 @@ const init = async () => {
|
|
|
1295
1351
|
}
|
|
1296
1352
|
});
|
|
1297
1353
|
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
// break the registered callback URL) disables the SSO button instead of failing mid-flow.
|
|
1301
|
-
let getServiceRedirectUrl = async () => new URL((await settings.get('serviceUrl')) || `http://${API_HOST}${API_PORT !== 80 ? `:${API_PORT}` : ''}`);
|
|
1302
|
-
let serviceOriginUnchanged = async redirectUrl => (await getServiceRedirectUrl()).origin === redirectUrl.origin;
|
|
1303
|
-
// A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
|
|
1304
|
-
// request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
|
|
1305
|
-
// uses, so the user lands on the login form with a way to try again rather than on the
|
|
1306
|
-
// generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
|
|
1307
|
-
// stops a forced instance from auto-redirecting straight back into the flow.
|
|
1308
|
-
let ssoFailureRedirect = async (request, h, method) => {
|
|
1309
|
-
request.logger.warn({
|
|
1310
|
-
msg: 'SSO login failed',
|
|
1311
|
-
method,
|
|
1312
|
-
reason: (request.auth.error && request.auth.error.message) || 'unknown',
|
|
1313
|
-
remoteAddress: request.app.ip
|
|
1314
|
-
});
|
|
1315
|
-
await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
|
|
1316
|
-
return h.redirect('/admin/login?sso_denied=1');
|
|
1317
|
-
};
|
|
1354
|
+
return secureCookie;
|
|
1355
|
+
}
|
|
1318
1356
|
|
|
1357
|
+
// Shared by the SSO strategies. The redirect URL is captured at strategy registration;
|
|
1358
|
+
// the validators re-read it from settings so an origin change after startup (which would
|
|
1359
|
+
// break the registered callback URL) disables the SSO button instead of failing mid-flow.
|
|
1360
|
+
let getServiceRedirectUrl = async () => new URL((await settings.get('serviceUrl')) || `http://${API_HOST}${API_PORT !== 80 ? `:${API_PORT}` : ''}`);
|
|
1361
|
+
let serviceOriginUnchanged = async redirectUrl => (await getServiceRedirectUrl()).origin === redirectUrl.origin;
|
|
1362
|
+
// A sign-in the IdP denied, or the user cancelled, comes back as an unauthenticated try-mode
|
|
1363
|
+
// request. It gets the same flash-and-redirect the allow-list denial in the OIDC handler
|
|
1364
|
+
// uses, so the user lands on the login form with a way to try again rather than on the
|
|
1365
|
+
// generic error page with bell's raw message. The reason goes to the log only. ?sso_denied=1
|
|
1366
|
+
// stops a forced instance from auto-redirecting straight back into the flow.
|
|
1367
|
+
let ssoFailureRedirect = async (request, h, method) => {
|
|
1368
|
+
request.logger.warn({
|
|
1369
|
+
msg: 'SSO login failed',
|
|
1370
|
+
method,
|
|
1371
|
+
reason: (request.auth.error && request.auth.error.message) || 'unknown',
|
|
1372
|
+
remoteAddress: request.app.ip
|
|
1373
|
+
});
|
|
1374
|
+
await request.flash({ type: 'danger', message: 'Single sign-on failed or was cancelled. Please try again' });
|
|
1375
|
+
return h.redirect('/admin/login?sso_denied=1');
|
|
1376
|
+
};
|
|
1377
|
+
|
|
1378
|
+
async function registerOktaAuth(server, secureCookie) {
|
|
1319
1379
|
if (USE_OKTA_AUTH) {
|
|
1320
1380
|
let redirectUrl = await getServiceRedirectUrl();
|
|
1321
1381
|
|
|
@@ -1370,7 +1430,9 @@ const init = async () => {
|
|
|
1370
1430
|
}
|
|
1371
1431
|
});
|
|
1372
1432
|
}
|
|
1433
|
+
}
|
|
1373
1434
|
|
|
1435
|
+
async function registerOidcAuth(server, secureCookie) {
|
|
1374
1436
|
if (USE_OIDC_AUTH) {
|
|
1375
1437
|
let redirectUrl = await getServiceRedirectUrl();
|
|
1376
1438
|
|
|
@@ -1502,7 +1564,9 @@ const init = async () => {
|
|
|
1502
1564
|
.catch(err => logger.error({ msg: 'OIDC SSO disabled: discovery retry failed', issuer: sso.OIDC_ISSUER, err }));
|
|
1503
1565
|
}
|
|
1504
1566
|
}
|
|
1567
|
+
}
|
|
1505
1568
|
|
|
1569
|
+
async function registerServerPlugins(server) {
|
|
1506
1570
|
if (await settings.isInstanceSecured()) {
|
|
1507
1571
|
server.auth.default('session');
|
|
1508
1572
|
}
|
|
@@ -1512,20 +1576,17 @@ const init = async () => {
|
|
|
1512
1576
|
sessionAuthServer = server;
|
|
1513
1577
|
|
|
1514
1578
|
await server.register({
|
|
1515
|
-
plugin:
|
|
1579
|
+
plugin: requestLogger,
|
|
1516
1580
|
options: {
|
|
1517
|
-
instance: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS }),
|
|
1518
1581
|
// Redact Authorization headers, see https://getpino.io/#/docs/redaction
|
|
1519
|
-
redact: consts.REDACTED_LOG_KEYS
|
|
1582
|
+
logger: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS })
|
|
1520
1583
|
}
|
|
1521
1584
|
});
|
|
1522
1585
|
|
|
1523
1586
|
await server.register([Inert, Vision]);
|
|
1587
|
+
}
|
|
1524
1588
|
|
|
1525
|
-
|
|
1526
|
-
// first request, not at registration time
|
|
1527
|
-
registerOpenApiRoute(server, openApiOptions);
|
|
1528
|
-
|
|
1589
|
+
function registerRequestEvents(server) {
|
|
1529
1590
|
// An exception thrown by a handler, an extension or a response schema with failAction
|
|
1530
1591
|
// 'error' is answered with a bare 500 and reported on the request's error channel. hapi's
|
|
1531
1592
|
// own record of it was an unstructured line on stderr (switched off above), and the API
|
|
@@ -1553,13 +1614,23 @@ const init = async () => {
|
|
|
1553
1614
|
// only log API calls
|
|
1554
1615
|
return;
|
|
1555
1616
|
}
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1617
|
+
// One message per request: the latency rides on the call counter's message and the main
|
|
1618
|
+
// thread observes it there, rather than costing a second postMessage on every request
|
|
1619
|
+
try {
|
|
1620
|
+
parentPort.postMessage({
|
|
1621
|
+
cmd: 'metrics',
|
|
1622
|
+
key: 'apiCall',
|
|
1623
|
+
method: 'inc',
|
|
1624
|
+
args: [{ method: request.method, route: request.route.path, statusCode: request.response && request.response.statusCode }],
|
|
1625
|
+
duration: apiCallDuration(request.info)
|
|
1626
|
+
});
|
|
1627
|
+
} catch (err) {
|
|
1628
|
+
logger.error({ msg: 'Failed to post metrics to parent', err });
|
|
1629
|
+
}
|
|
1561
1630
|
});
|
|
1631
|
+
}
|
|
1562
1632
|
|
|
1633
|
+
function registerStaticPageRoutes(server) {
|
|
1563
1634
|
server.route({
|
|
1564
1635
|
method: 'GET',
|
|
1565
1636
|
path: '/',
|
|
@@ -1680,7 +1751,9 @@ const init = async () => {
|
|
|
1680
1751
|
tags: ['static']
|
|
1681
1752
|
}
|
|
1682
1753
|
});
|
|
1754
|
+
}
|
|
1683
1755
|
|
|
1756
|
+
function registerStaticFilesRoute(server) {
|
|
1684
1757
|
const staticRoot = pathlib.resolve(__dirname, '..', 'static');
|
|
1685
1758
|
const staticRootPrefix = staticRoot + pathlib.sep;
|
|
1686
1759
|
|
|
@@ -1732,34 +1805,70 @@ const init = async () => {
|
|
|
1732
1805
|
: undefined
|
|
1733
1806
|
}
|
|
1734
1807
|
});
|
|
1808
|
+
}
|
|
1809
|
+
|
|
1810
|
+
// Set by the close command: readiness answers 503 from then on while Hapi drains the requests in flight
|
|
1811
|
+
let apiDraining = false;
|
|
1812
|
+
|
|
1813
|
+
const healthChecks = createHealthChecks({
|
|
1814
|
+
call,
|
|
1815
|
+
redis,
|
|
1816
|
+
prefix: REDIS_PREFIX,
|
|
1817
|
+
expectedImapWorkers: IMAP_WORKER_COUNT,
|
|
1818
|
+
isDraining: () => apiDraining
|
|
1819
|
+
});
|
|
1820
|
+
|
|
1821
|
+
/**
|
|
1822
|
+
* Runs a readiness check and turns its failure into a 503 carrying a `code`
|
|
1823
|
+
* @param {Object} request - Hapi request
|
|
1824
|
+
* @returns {Promise<Object>} The check result
|
|
1825
|
+
*/
|
|
1826
|
+
async function answerReadiness(request) {
|
|
1827
|
+
// Same rule as the license lookup: a header value the timer would mangle is ignored
|
|
1828
|
+
const { error: timeoutError, value: timeout } = headerTimeoutSchema.validate(request.headers['x-ee-timeout']);
|
|
1829
|
+
try {
|
|
1830
|
+
return await healthChecks.ready(timeoutError ? undefined : timeout);
|
|
1831
|
+
} catch (err) {
|
|
1832
|
+
if (err.statusCode !== 503) {
|
|
1833
|
+
throw err;
|
|
1834
|
+
}
|
|
1835
|
+
const error = Boom.boomify(err, { statusCode: err.statusCode });
|
|
1836
|
+
error.output.payload.code = err.code;
|
|
1837
|
+
throw error;
|
|
1838
|
+
}
|
|
1839
|
+
}
|
|
1735
1840
|
|
|
1841
|
+
function registerHealthRoute(server) {
|
|
1842
|
+
const options = {
|
|
1843
|
+
auth: false,
|
|
1844
|
+
tags: ['static', 'health']
|
|
1845
|
+
};
|
|
1846
|
+
|
|
1847
|
+
// Kept with its historical meaning (everything needed to serve traffic), for the probes and
|
|
1848
|
+
// smoke tests already pointed at it
|
|
1736
1849
|
server.route({
|
|
1737
1850
|
method: 'GET',
|
|
1738
1851
|
path: '/health',
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
let error = Boom.boomify(new Error('Not all IMAP workers available'), { statusCode: 500 });
|
|
1743
|
-
throw error;
|
|
1744
|
-
}
|
|
1852
|
+
handler: answerReadiness,
|
|
1853
|
+
options: Object.assign({ description: 'Health check' }, options)
|
|
1854
|
+
});
|
|
1745
1855
|
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
}
|
|
1856
|
+
server.route({
|
|
1857
|
+
method: 'GET',
|
|
1858
|
+
path: '/health/ready',
|
|
1859
|
+
handler: answerReadiness,
|
|
1860
|
+
options: Object.assign({ description: 'Readiness check' }, options)
|
|
1861
|
+
});
|
|
1753
1862
|
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
tags: ['static', 'health']
|
|
1760
|
-
}
|
|
1863
|
+
server.route({
|
|
1864
|
+
method: 'GET',
|
|
1865
|
+
path: '/health/live',
|
|
1866
|
+
handler: () => healthChecks.live(),
|
|
1867
|
+
options: Object.assign({ description: 'Liveness check' }, options)
|
|
1761
1868
|
});
|
|
1869
|
+
}
|
|
1762
1870
|
|
|
1871
|
+
function registerRedirectRoute(server) {
|
|
1763
1872
|
server.route({
|
|
1764
1873
|
method: 'GET',
|
|
1765
1874
|
path: '/redirect',
|
|
@@ -1829,7 +1938,9 @@ const init = async () => {
|
|
|
1829
1938
|
auth: false
|
|
1830
1939
|
}
|
|
1831
1940
|
});
|
|
1941
|
+
}
|
|
1832
1942
|
|
|
1943
|
+
function registerOpenTrackingRoute(server) {
|
|
1833
1944
|
server.route({
|
|
1834
1945
|
method: 'GET',
|
|
1835
1946
|
path: '/open.gif',
|
|
@@ -1894,7 +2005,9 @@ const init = async () => {
|
|
|
1894
2005
|
auth: false
|
|
1895
2006
|
}
|
|
1896
2007
|
});
|
|
2008
|
+
}
|
|
1897
2009
|
|
|
2010
|
+
function registerUnsubscribeRoute(server) {
|
|
1898
2011
|
server.route({
|
|
1899
2012
|
method: 'POST',
|
|
1900
2013
|
path: '/unsubscribe',
|
|
@@ -2012,7 +2125,9 @@ const init = async () => {
|
|
|
2012
2125
|
auth: false
|
|
2013
2126
|
}
|
|
2014
2127
|
});
|
|
2128
|
+
}
|
|
2015
2129
|
|
|
2130
|
+
function registerOutlookNotificationRoute(server) {
|
|
2016
2131
|
server.route({
|
|
2017
2132
|
method: 'POST',
|
|
2018
2133
|
path: '/oauth/msg/notification',
|
|
@@ -2115,7 +2230,9 @@ const init = async () => {
|
|
|
2115
2230
|
auth: false
|
|
2116
2231
|
}
|
|
2117
2232
|
});
|
|
2233
|
+
}
|
|
2118
2234
|
|
|
2235
|
+
function registerOutlookLifecycleRoute(server) {
|
|
2119
2236
|
server.route({
|
|
2120
2237
|
method: 'POST',
|
|
2121
2238
|
path: '/oauth/msg/lifecycle',
|
|
@@ -2260,587 +2377,608 @@ const init = async () => {
|
|
|
2260
2377
|
auth: false
|
|
2261
2378
|
}
|
|
2262
2379
|
});
|
|
2380
|
+
}
|
|
2263
2381
|
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
|
|
2281
|
-
|
|
2282
|
-
throw Boom.badRequest(util.format(request.app.gt.gettext('Sign-in with the email provider failed: %s'), request.query.error));
|
|
2283
|
-
}
|
|
2382
|
+
// The OAuth2 callback (GET /oauth). The handler below runs these steps in order; every one that
|
|
2383
|
+
// can end the request either throws or returns the response to send.
|
|
2384
|
+
|
|
2385
|
+
// Refuses a callback that reports a provider error, carries no code or names a malformed state,
|
|
2386
|
+
// before the pending setup is touched
|
|
2387
|
+
function assertOAuthCallbackQuery(request) {
|
|
2388
|
+
// The mailbox owner sees these on the public error page, in the same locale as the
|
|
2389
|
+
// rest of the setup flow. The pending setup is still unspent at this point (its state
|
|
2390
|
+
// entry is claimed only below), so opening the setup link again is a valid retry.
|
|
2391
|
+
if (request.query.error === 'access_denied') {
|
|
2392
|
+
let error = Boom.badRequest(
|
|
2393
|
+
request.app.gt.gettext('The sign-in was cancelled or the requested access was not granted. Open the account setup link again to retry.')
|
|
2394
|
+
);
|
|
2395
|
+
if (request.query.error_description) {
|
|
2396
|
+
error.output.payload.details = [String(request.query.error_description)];
|
|
2397
|
+
}
|
|
2398
|
+
throw error;
|
|
2399
|
+
}
|
|
2284
2400
|
|
|
2285
|
-
|
|
2286
|
-
|
|
2287
|
-
|
|
2401
|
+
if (request.query.error) {
|
|
2402
|
+
throw Boom.badRequest(util.format(request.app.gt.gettext('Sign-in with the email provider failed: %s'), request.query.error));
|
|
2403
|
+
}
|
|
2288
2404
|
|
|
2289
|
-
|
|
2290
|
-
|
|
2291
|
-
|
|
2292
|
-
throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the request state is not valid'));
|
|
2293
|
-
}
|
|
2405
|
+
if (!request.query.code) {
|
|
2406
|
+
throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: no authorization code was received'));
|
|
2407
|
+
}
|
|
2294
2408
|
|
|
2295
|
-
|
|
2296
|
-
|
|
2297
|
-
|
|
2298
|
-
|
|
2299
|
-
);
|
|
2300
|
-
}
|
|
2409
|
+
if (!isValidOAuthState(request.query.state)) {
|
|
2410
|
+
throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the request state is not valid'));
|
|
2411
|
+
}
|
|
2412
|
+
}
|
|
2301
2413
|
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2414
|
+
// Claims the pending setup the state names: the entry is deleted in the same transaction that reads
|
|
2415
|
+
// it, so a setup can be completed only once
|
|
2416
|
+
async function claimOAuthSetup(request) {
|
|
2417
|
+
let [[, accountData]] = await redis.multi().get(`${REDIS_PREFIX}${request.query.state}`).del(`${REDIS_PREFIX}${request.query.state}`).exec();
|
|
2418
|
+
if (!accountData) {
|
|
2419
|
+
throw Boom.badRequest(request.app.gt.gettext('The account setup session has expired or was already used. Open the account setup link again to retry.'));
|
|
2420
|
+
}
|
|
2307
2421
|
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2422
|
+
try {
|
|
2423
|
+
accountData = JSON.parse(accountData);
|
|
2424
|
+
} catch (E) {
|
|
2425
|
+
throw Boom.badRequest(request.app.gt.gettext('Sign-in with the email provider failed: the stored setup session is not valid'));
|
|
2426
|
+
}
|
|
2311
2427
|
|
|
2312
|
-
|
|
2313
|
-
|
|
2428
|
+
if (!accountData.account) {
|
|
2429
|
+
accountData.account = null;
|
|
2430
|
+
}
|
|
2314
2431
|
|
|
2315
|
-
|
|
2432
|
+
return accountData;
|
|
2433
|
+
}
|
|
2316
2434
|
|
|
2317
|
-
|
|
2435
|
+
// Hands the user back to the provider after a failure they can correct themselves, as a fresh
|
|
2436
|
+
// single-use setup. The token-bearing oauth2 object is dropped so the retry starts clean, and
|
|
2437
|
+
// _meta rides along so the redirect URL, the expected identity and the form nonce all survive
|
|
2438
|
+
// it - that nonce is claimed only on success, so it is still unspent here.
|
|
2439
|
+
async function startOAuthRetry(flow, loginHint, prompt) {
|
|
2440
|
+
const { accountData, requestedSetup, provider, accountMeta, oAuth2Client } = flow;
|
|
2318
2441
|
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
// rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
|
|
2322
|
-
// with the authenticated address), `name` gets filled in from the rejected user's profile when
|
|
2323
|
-
// the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
|
|
2324
|
-
// credential, so it must survive while the tokens do not.
|
|
2325
|
-
const requestedSetup = {
|
|
2326
|
-
email: accountData.email,
|
|
2327
|
-
name: accountData.name,
|
|
2328
|
-
delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
|
|
2329
|
-
};
|
|
2442
|
+
const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
|
|
2443
|
+
const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
|
|
2330
2444
|
|
|
2331
|
-
|
|
2332
|
-
if (!oauth2App) {
|
|
2333
|
-
let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
|
|
2334
|
-
throw error;
|
|
2335
|
-
}
|
|
2445
|
+
await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
|
|
2336
2446
|
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2447
|
+
// The address to steer the user towards rides on the authorize URL only - persisting it
|
|
2448
|
+
// would overwrite a shared mailbox with the principal that is signing in to reach it.
|
|
2449
|
+
return oAuth2Client.generateAuthUrl({ state: reAuthState, email: loginHint, prompt });
|
|
2450
|
+
}
|
|
2340
2451
|
|
|
2341
|
-
|
|
2342
|
-
|
|
2343
|
-
h.view(
|
|
2344
|
-
'redirect',
|
|
2345
|
-
{
|
|
2346
|
-
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
2347
|
-
httpRedirectUrl
|
|
2348
|
-
},
|
|
2349
|
-
{
|
|
2350
|
-
layout: 'public'
|
|
2351
|
-
}
|
|
2352
|
-
);
|
|
2452
|
+
async function gmailMissingScopesView(flow, r, grantedScopes) {
|
|
2453
|
+
const { request, h, oAuth2Client, accountData } = flow;
|
|
2353
2454
|
|
|
2354
|
-
|
|
2355
|
-
|
|
2356
|
-
|
|
2357
|
-
// it - that nonce is claimed only on success, so it is still unspent here.
|
|
2358
|
-
const startOAuthRetry = async (loginHint, prompt) => {
|
|
2359
|
-
const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
|
|
2360
|
-
const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
|
|
2455
|
+
// Check if user deselected required scopes in Google's granular consent
|
|
2456
|
+
const requiredFunctionalScopes = oAuth2Client.scopes.filter(s => !OPENID_SCOPES.includes(s));
|
|
2457
|
+
const missingScopes = requiredFunctionalScopes.filter(s => !grantedScopes.includes(s));
|
|
2361
2458
|
|
|
2362
|
-
|
|
2459
|
+
if (missingScopes.length > 0) {
|
|
2460
|
+
request.logger.warn({
|
|
2461
|
+
msg: 'OAuth2 grant missing required scopes',
|
|
2462
|
+
requested: requiredFunctionalScopes,
|
|
2463
|
+
granted: grantedScopes,
|
|
2464
|
+
missing: missingScopes
|
|
2465
|
+
});
|
|
2363
2466
|
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2467
|
+
// Best-effort revocation of the partial token
|
|
2468
|
+
oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
|
|
2469
|
+
request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
|
|
2470
|
+
});
|
|
2368
2471
|
|
|
2369
|
-
|
|
2370
|
-
// satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
|
|
2371
|
-
// fills this in; one that does not leaves it empty, and an empty list fails the check closed.
|
|
2372
|
-
const providerIdentities = [];
|
|
2373
|
-
|
|
2374
|
-
// The Workspace or Cloud organization domain the provider reported, for an application
|
|
2375
|
-
// restricted to Google Workspace accounts. Only the Gmail case fills it in; the
|
|
2376
|
-
// restriction is a Google setting and no other provider has the notion.
|
|
2377
|
-
let workspaceDomain = null;
|
|
2378
|
-
|
|
2379
|
-
// The token to revoke if the setup is rejected after the code was already exchanged, set by
|
|
2380
|
-
// each provider case because the token response is scoped to the switch. Prefer the refresh
|
|
2381
|
-
// token: revoking either invalidates the grant, but the access token may already be expired.
|
|
2382
|
-
let grantToken;
|
|
2383
|
-
|
|
2384
|
-
// `app.provider` is for example "gmail", `provider` is oauth2 app id
|
|
2385
|
-
switch (oauth2App.provider) {
|
|
2386
|
-
case 'gmail': {
|
|
2387
|
-
const r = await oAuth2Client.getToken(request.query.code);
|
|
2388
|
-
if (!r || !r.access_token) {
|
|
2389
|
-
let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
|
|
2390
|
-
throw error;
|
|
2391
|
-
}
|
|
2472
|
+
const retryUrl = await startOAuthRetry(flow, accountData.email);
|
|
2392
2473
|
|
|
2393
|
-
|
|
2474
|
+
const missingScopesList = missingScopes.map(formatScopeDescription);
|
|
2394
2475
|
|
|
2395
|
-
|
|
2476
|
+
return h.view(
|
|
2477
|
+
'oauth-scope-error',
|
|
2478
|
+
{
|
|
2479
|
+
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
2480
|
+
templateLocale: request.app.locale,
|
|
2481
|
+
retryUrl,
|
|
2482
|
+
missingScopesList
|
|
2483
|
+
},
|
|
2484
|
+
{
|
|
2485
|
+
layout: 'public'
|
|
2486
|
+
}
|
|
2487
|
+
);
|
|
2488
|
+
}
|
|
2489
|
+
}
|
|
2396
2490
|
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
const missingScopes = requiredFunctionalScopes.filter(s => !grantedScopes.includes(s));
|
|
2491
|
+
async function resolveGmailUserEmail(flow, r, grantedScopes) {
|
|
2492
|
+
const { request, oAuth2Client } = flow;
|
|
2400
2493
|
|
|
2401
|
-
|
|
2402
|
-
|
|
2403
|
-
|
|
2404
|
-
requested: requiredFunctionalScopes,
|
|
2405
|
-
granted: grantedScopes,
|
|
2406
|
-
missing: missingScopes
|
|
2407
|
-
});
|
|
2494
|
+
let profileRes;
|
|
2495
|
+
let userEmail;
|
|
2496
|
+
let userName;
|
|
2408
2497
|
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2498
|
+
// With OpenID Connect scopes (openid, email, profile), the ID token contains user info
|
|
2499
|
+
// This works for all account types including send-only accounts
|
|
2500
|
+
const idTokenPayload = decodeJwtPayload(r.id_token);
|
|
2501
|
+
if (r.id_token && !idTokenPayload) {
|
|
2502
|
+
request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
|
|
2503
|
+
}
|
|
2504
|
+
if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
|
|
2505
|
+
userEmail = idTokenPayload.email;
|
|
2506
|
+
userName = idTokenPayload.name || null;
|
|
2507
|
+
request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
|
|
2508
|
+
}
|
|
2413
2509
|
|
|
2414
|
-
|
|
2510
|
+
// Back channel, so this is the claim the restriction can actually be enforced on;
|
|
2511
|
+
// the hd argument on the authorization URL only filters the chooser Google shows
|
|
2512
|
+
const workspaceDomain = workspaceDomainOf(idTokenPayload);
|
|
2513
|
+
|
|
2514
|
+
// If ID token didn't provide email, fall back to Gmail API profile endpoint
|
|
2515
|
+
// This should rarely happen since we now request openid/email/profile scopes
|
|
2516
|
+
if (!userEmail) {
|
|
2517
|
+
// Check if we have scopes that allow accessing the profile endpoint
|
|
2518
|
+
const hasProfileScope =
|
|
2519
|
+
grantedScopes.includes('https://mail.google.com/') ||
|
|
2520
|
+
grantedScopes.includes('https://www.googleapis.com/auth/gmail.readonly') ||
|
|
2521
|
+
grantedScopes.includes('https://www.googleapis.com/auth/gmail.modify') ||
|
|
2522
|
+
grantedScopes.includes('https://www.googleapis.com/auth/gmail.metadata');
|
|
2523
|
+
|
|
2524
|
+
if (hasProfileScope) {
|
|
2525
|
+
try {
|
|
2526
|
+
request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
|
|
2527
|
+
profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
|
|
2528
|
+
if (profileRes && profileRes.emailAddress) {
|
|
2529
|
+
userEmail = profileRes.emailAddress;
|
|
2530
|
+
}
|
|
2531
|
+
} catch (err) {
|
|
2532
|
+
request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
|
|
2533
|
+
let response = err.oauthRequest && err.oauthRequest.response;
|
|
2534
|
+
if (response && response.error) {
|
|
2535
|
+
let message;
|
|
2536
|
+
if (/Gmail API has not been used in project/.test(response.error.message)) {
|
|
2537
|
+
message =
|
|
2538
|
+
'Can not perform requests against Gmail API as the project has not been enabled. If you are the admin, check notifications on the dashboard.';
|
|
2539
|
+
} else {
|
|
2540
|
+
message = response.error.message;
|
|
2541
|
+
}
|
|
2415
2542
|
|
|
2416
|
-
|
|
2543
|
+
let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
|
|
2544
|
+
throw error;
|
|
2545
|
+
}
|
|
2546
|
+
throw err;
|
|
2547
|
+
}
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2417
2550
|
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
{
|
|
2421
|
-
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
2422
|
-
templateLocale: request.app.locale,
|
|
2423
|
-
retryUrl,
|
|
2424
|
-
missingScopesList
|
|
2425
|
-
},
|
|
2426
|
-
{
|
|
2427
|
-
layout: 'public'
|
|
2428
|
-
}
|
|
2429
|
-
);
|
|
2430
|
-
}
|
|
2551
|
+
return { profileRes, userEmail, workspaceDomain };
|
|
2552
|
+
}
|
|
2431
2553
|
|
|
2432
|
-
|
|
2433
|
-
|
|
2434
|
-
let userName;
|
|
2554
|
+
async function completeGmailCallback(flow) {
|
|
2555
|
+
const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
|
|
2435
2556
|
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
2441
|
-
}
|
|
2442
|
-
if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
|
|
2443
|
-
userEmail = idTokenPayload.email;
|
|
2444
|
-
userName = idTokenPayload.name || null;
|
|
2445
|
-
request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
|
|
2446
|
-
}
|
|
2557
|
+
const r = await oAuth2Client.getToken(request.query.code);
|
|
2558
|
+
if (!r || !r.access_token) {
|
|
2559
|
+
let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
|
|
2560
|
+
throw error;
|
|
2561
|
+
}
|
|
2447
2562
|
|
|
2448
|
-
|
|
2449
|
-
// the hd argument on the authorization URL only filters the chooser Google shows
|
|
2450
|
-
workspaceDomain = workspaceDomainOf(idTokenPayload);
|
|
2451
|
-
|
|
2452
|
-
// If ID token didn't provide email, fall back to Gmail API profile endpoint
|
|
2453
|
-
// This should rarely happen since we now request openid/email/profile scopes
|
|
2454
|
-
if (!userEmail) {
|
|
2455
|
-
// Check if we have scopes that allow accessing the profile endpoint
|
|
2456
|
-
const hasProfileScope =
|
|
2457
|
-
grantedScopes.includes('https://mail.google.com/') ||
|
|
2458
|
-
grantedScopes.includes('https://www.googleapis.com/auth/gmail.readonly') ||
|
|
2459
|
-
grantedScopes.includes('https://www.googleapis.com/auth/gmail.modify') ||
|
|
2460
|
-
grantedScopes.includes('https://www.googleapis.com/auth/gmail.metadata');
|
|
2461
|
-
|
|
2462
|
-
if (hasProfileScope) {
|
|
2463
|
-
try {
|
|
2464
|
-
request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
|
|
2465
|
-
profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
|
|
2466
|
-
if (profileRes && profileRes.emailAddress) {
|
|
2467
|
-
userEmail = profileRes.emailAddress;
|
|
2468
|
-
}
|
|
2469
|
-
} catch (err) {
|
|
2470
|
-
request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
|
|
2471
|
-
let response = err.oauthRequest && err.oauthRequest.response;
|
|
2472
|
-
if (response && response.error) {
|
|
2473
|
-
let message;
|
|
2474
|
-
if (/Gmail API has not been used in project/.test(response.error.message)) {
|
|
2475
|
-
message =
|
|
2476
|
-
'Can not perform requests against Gmail API as the project has not been enabled. If you are the admin, check notifications on the dashboard.';
|
|
2477
|
-
} else {
|
|
2478
|
-
message = response.error.message;
|
|
2479
|
-
}
|
|
2480
|
-
|
|
2481
|
-
let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
|
|
2482
|
-
throw error;
|
|
2483
|
-
}
|
|
2484
|
-
throw err;
|
|
2485
|
-
}
|
|
2486
|
-
}
|
|
2487
|
-
}
|
|
2563
|
+
const grantedScopes = r.scope ? r.scope.split(/\s+/) : [];
|
|
2488
2564
|
|
|
2489
|
-
|
|
2490
|
-
let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
|
|
2491
|
-
throw error;
|
|
2492
|
-
}
|
|
2565
|
+
request.logger.info({ msg: 'OAuth token received', grantedScopes, hasIdToken: !!r.id_token });
|
|
2493
2566
|
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2567
|
+
const scopeErrorView = await gmailMissingScopesView(flow, r, grantedScopes);
|
|
2568
|
+
if (scopeErrorView) {
|
|
2569
|
+
return { view: scopeErrorView };
|
|
2570
|
+
}
|
|
2498
2571
|
|
|
2499
|
-
|
|
2572
|
+
const { profileRes, userEmail, workspaceDomain } = await resolveGmailUserEmail(flow, r, grantedScopes);
|
|
2500
2573
|
|
|
2501
|
-
|
|
2574
|
+
if (!userEmail) {
|
|
2575
|
+
let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
|
|
2576
|
+
throw error;
|
|
2577
|
+
}
|
|
2502
2578
|
|
|
2503
|
-
|
|
2504
|
-
|
|
2505
|
-
|
|
2506
|
-
provider,
|
|
2507
|
-
accessToken: r.access_token,
|
|
2508
|
-
refreshToken: r.refresh_token,
|
|
2509
|
-
expires: new Date(Date.now() + r.expires_in * 1000),
|
|
2510
|
-
scope: grantedScopes.length ? grantedScopes : defaultScopes,
|
|
2511
|
-
tokenType: r.token_type
|
|
2512
|
-
},
|
|
2513
|
-
{
|
|
2514
|
-
auth: {
|
|
2515
|
-
user: userEmail
|
|
2516
|
-
}
|
|
2517
|
-
}
|
|
2518
|
-
);
|
|
2579
|
+
// Back-channel only: either the id_token from the token endpoint or the Gmail profile
|
|
2580
|
+
// API response, never a value that travelled through the browser.
|
|
2581
|
+
providerIdentities.push(userEmail);
|
|
2519
2582
|
|
|
2520
|
-
|
|
2583
|
+
accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
|
|
2521
2584
|
|
|
2522
|
-
|
|
2523
|
-
break;
|
|
2524
|
-
}
|
|
2585
|
+
const defaultScopes = (oauth2App.baseScopes && GMAIL_SCOPES[oauth2App.baseScopes]) || GMAIL_SCOPES.imap;
|
|
2525
2586
|
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
2529
|
-
|
|
2530
|
-
|
|
2531
|
-
|
|
2587
|
+
accountData.oauth2 = Object.assign(
|
|
2588
|
+
accountData.oauth2 || {},
|
|
2589
|
+
{
|
|
2590
|
+
provider,
|
|
2591
|
+
accessToken: r.access_token,
|
|
2592
|
+
refreshToken: r.refresh_token,
|
|
2593
|
+
expires: new Date(Date.now() + r.expires_in * 1000),
|
|
2594
|
+
scope: grantedScopes.length ? grantedScopes : defaultScopes,
|
|
2595
|
+
tokenType: r.token_type
|
|
2596
|
+
},
|
|
2597
|
+
{
|
|
2598
|
+
auth: {
|
|
2599
|
+
user: userEmail
|
|
2600
|
+
}
|
|
2601
|
+
}
|
|
2602
|
+
);
|
|
2532
2603
|
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
|
|
2536
|
-
// Read account info from the id_token, falling back to the client_info GET argument.
|
|
2537
|
-
// The fallback is needed because previously EmailEngine did not request for the
|
|
2538
|
-
// User.Read scope - but client_info arrives through the browser, so it is a display
|
|
2539
|
-
// fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
|
|
2540
|
-
|
|
2541
|
-
let clientInfo = false;
|
|
2542
|
-
if (request.query.client_info) {
|
|
2543
|
-
try {
|
|
2544
|
-
clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
|
|
2545
|
-
} catch (err) {
|
|
2546
|
-
// Base64-shaped but not JSON. It is an optional display hint, so log and continue
|
|
2547
|
-
// rather than failing the whole setup on a value we do not trust anyway.
|
|
2548
|
-
request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
|
|
2549
|
-
}
|
|
2550
|
-
}
|
|
2604
|
+
accountData.googleHistoryId = profileRes ? Number(profileRes.historyId) || null : null;
|
|
2551
2605
|
|
|
2552
|
-
|
|
2553
|
-
if (r.id_token && !idTokenPayload) {
|
|
2554
|
-
request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
|
|
2555
|
-
}
|
|
2606
|
+
request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userEmail, provider: oauth2App.provider });
|
|
2556
2607
|
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
// Request profile info from API
|
|
2560
|
-
|
|
2561
|
-
let profileRes;
|
|
2562
|
-
try {
|
|
2563
|
-
profileRes = await oAuth2Client.request(r.access_token, `${oAuth2Client.apiBase}/v1.0/me`);
|
|
2564
|
-
} catch (err) {
|
|
2565
|
-
let response = err.oauthRequest && err.oauthRequest.response;
|
|
2566
|
-
if (response && response.error) {
|
|
2567
|
-
let message = response.error.message;
|
|
2568
|
-
let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
|
|
2569
|
-
throw error;
|
|
2570
|
-
}
|
|
2571
|
-
throw err;
|
|
2572
|
-
}
|
|
2608
|
+
return { grantToken: r.refresh_token || r.access_token, workspaceDomain };
|
|
2609
|
+
}
|
|
2573
2610
|
|
|
2574
|
-
|
|
2611
|
+
async function resolveOutlookCallbackUser(flow, r) {
|
|
2612
|
+
const { request, oAuth2Client, oauth2App } = flow;
|
|
2575
2613
|
|
|
2576
|
-
|
|
2577
|
-
msg: 'User profile returned by MS Graph API',
|
|
2578
|
-
user: userInfo.email,
|
|
2579
|
-
provider: oauth2App.provider
|
|
2580
|
-
});
|
|
2581
|
-
}
|
|
2614
|
+
let userInfo;
|
|
2582
2615
|
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
|
|
2616
|
+
if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
|
|
2617
|
+
// Read account info from the id_token, falling back to the client_info GET argument.
|
|
2618
|
+
// The fallback is needed because previously EmailEngine did not request for the
|
|
2619
|
+
// User.Read scope - but client_info arrives through the browser, so it is a display
|
|
2620
|
+
// fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
|
|
2586
2621
|
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2622
|
+
let clientInfo = false;
|
|
2623
|
+
if (request.query.client_info) {
|
|
2624
|
+
try {
|
|
2625
|
+
clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
|
|
2626
|
+
} catch (err) {
|
|
2627
|
+
// Base64-shaped but not JSON. It is an optional display hint, so log and continue
|
|
2628
|
+
// rather than failing the whole setup on a value we do not trust anyway.
|
|
2629
|
+
request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2591
2632
|
|
|
2592
|
-
|
|
2593
|
-
|
|
2594
|
-
|
|
2633
|
+
const idTokenPayload = decodeJwtPayload(r.id_token);
|
|
2634
|
+
if (r.id_token && !idTokenPayload) {
|
|
2635
|
+
request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
|
|
2636
|
+
}
|
|
2595
2637
|
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
// Ensure email is set to the delegated user if not already provided
|
|
2600
|
-
if (!accountData.email) {
|
|
2601
|
-
accountData.email = accountData.oauth2.auth.delegatedUser;
|
|
2602
|
-
}
|
|
2603
|
-
} else if (accountData.delegated && accountData.email && accountData.email !== userInfo.email) {
|
|
2604
|
-
// Legacy: Shared mailbox specified via delegated flag
|
|
2605
|
-
authData.delegatedUser = accountData.email;
|
|
2606
|
-
} else {
|
|
2607
|
-
// Not a delegated account, use the authenticated user's email
|
|
2608
|
-
accountData.email = userInfo.email;
|
|
2609
|
-
}
|
|
2638
|
+
userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
|
|
2639
|
+
} else {
|
|
2640
|
+
// Request profile info from API
|
|
2610
2641
|
|
|
2611
|
-
|
|
2642
|
+
let profileRes;
|
|
2643
|
+
try {
|
|
2644
|
+
profileRes = await oAuth2Client.request(r.access_token, `${oAuth2Client.apiBase}/v1.0/me`);
|
|
2645
|
+
} catch (err) {
|
|
2646
|
+
let response = err.oauthRequest && err.oauthRequest.response;
|
|
2647
|
+
if (response && response.error) {
|
|
2648
|
+
let message = response.error.message;
|
|
2649
|
+
let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
|
|
2650
|
+
throw error;
|
|
2651
|
+
}
|
|
2652
|
+
throw err;
|
|
2653
|
+
}
|
|
2612
2654
|
|
|
2613
|
-
|
|
2614
|
-
accountData.oauth2 || {},
|
|
2615
|
-
{
|
|
2616
|
-
provider,
|
|
2617
|
-
accessToken: r.access_token,
|
|
2618
|
-
refreshToken: r.refresh_token,
|
|
2619
|
-
expires: new Date(Date.now() + r.expires_in * 1000),
|
|
2620
|
-
scope: r.scope ? r.scope.split(/\s+/) : oAuth2Client.scopes,
|
|
2621
|
-
tokenType: r.token_type
|
|
2622
|
-
},
|
|
2623
|
-
{
|
|
2624
|
-
auth: authData
|
|
2625
|
-
}
|
|
2626
|
-
);
|
|
2655
|
+
userInfo = resolveOutlookUserInfo({ profile: profileRes });
|
|
2627
2656
|
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2657
|
+
request.logger.info({
|
|
2658
|
+
msg: 'User profile returned by MS Graph API',
|
|
2659
|
+
user: userInfo.email,
|
|
2660
|
+
provider: oauth2App.provider
|
|
2661
|
+
});
|
|
2662
|
+
}
|
|
2631
2663
|
|
|
2632
|
-
|
|
2633
|
-
|
|
2634
|
-
if (!r || !r.access_token) {
|
|
2635
|
-
let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
|
|
2636
|
-
throw error;
|
|
2637
|
-
}
|
|
2664
|
+
return userInfo;
|
|
2665
|
+
}
|
|
2638
2666
|
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
profileRes = await oAuth2Client.request(r.access_token, 'https://oauth.mail.ru/userinfo');
|
|
2642
|
-
} catch (err) {
|
|
2643
|
-
let response = err.oauthRequest && err.oauthRequest.response;
|
|
2644
|
-
if (response && response.error) {
|
|
2645
|
-
let message = response.error.message;
|
|
2646
|
-
let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
|
|
2647
|
-
throw error;
|
|
2648
|
-
}
|
|
2649
|
-
throw err;
|
|
2650
|
-
}
|
|
2667
|
+
async function completeOutlookCallback(flow) {
|
|
2668
|
+
const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
|
|
2651
2669
|
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2670
|
+
const r = await oAuth2Client.getToken(request.query.code);
|
|
2671
|
+
if (!r || !r.access_token) {
|
|
2672
|
+
let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
|
|
2673
|
+
throw error;
|
|
2674
|
+
}
|
|
2656
2675
|
|
|
2657
|
-
|
|
2658
|
-
providerIdentities.push(profileRes.email);
|
|
2659
|
-
grantToken = r.refresh_token || r.access_token;
|
|
2676
|
+
const userInfo = await resolveOutlookCallbackUser(flow, r);
|
|
2660
2677
|
|
|
2661
|
-
|
|
2662
|
-
|
|
2678
|
+
const authData = {
|
|
2679
|
+
user: userInfo.username || userInfo.email
|
|
2680
|
+
};
|
|
2663
2681
|
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
accessToken: r.access_token,
|
|
2669
|
-
refreshToken: r.refresh_token,
|
|
2670
|
-
expires: new Date(Date.now() + r.expires_in * 1000),
|
|
2671
|
-
scope: r.scope ? r.scope.split(/\s+/) : MAIL_RU_SCOPES,
|
|
2672
|
-
tokenType: r.token_type
|
|
2673
|
-
},
|
|
2674
|
-
{
|
|
2675
|
-
auth: {
|
|
2676
|
-
user: profileRes.email
|
|
2677
|
-
}
|
|
2678
|
-
}
|
|
2679
|
-
);
|
|
2682
|
+
if (!authData.user) {
|
|
2683
|
+
let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
|
|
2684
|
+
throw error;
|
|
2685
|
+
}
|
|
2680
2686
|
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
}
|
|
2687
|
+
// Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
|
|
2688
|
+
providerIdentities.push(...userInfo.verifiedIdentities);
|
|
2684
2689
|
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
2688
|
-
|
|
2690
|
+
// A shared mailbox, named either way, or the signed-in user's own
|
|
2691
|
+
const mailbox = resolveOutlookMailbox(accountData, userInfo);
|
|
2692
|
+
accountData.email = mailbox.email;
|
|
2693
|
+
if (mailbox.delegatedUser) {
|
|
2694
|
+
authData.delegatedUser = mailbox.delegatedUser;
|
|
2695
|
+
}
|
|
2689
2696
|
|
|
2690
|
-
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2697
|
+
accountData.name = accountData.name || userInfo.name || '';
|
|
2698
|
+
|
|
2699
|
+
accountData.oauth2 = Object.assign(
|
|
2700
|
+
accountData.oauth2 || {},
|
|
2701
|
+
{
|
|
2702
|
+
provider,
|
|
2703
|
+
accessToken: r.access_token,
|
|
2704
|
+
refreshToken: r.refresh_token,
|
|
2705
|
+
expires: new Date(Date.now() + r.expires_in * 1000),
|
|
2706
|
+
scope: r.scope ? r.scope.split(/\s+/) : oAuth2Client.scopes,
|
|
2707
|
+
tokenType: r.token_type
|
|
2708
|
+
},
|
|
2709
|
+
{
|
|
2710
|
+
auth: authData
|
|
2711
|
+
}
|
|
2712
|
+
);
|
|
2699
2713
|
|
|
2700
|
-
|
|
2701
|
-
// which filters the account chooser Google shows and nothing else, so a link assembled
|
|
2702
|
-
// without that argument - or a user who switches account inside the chooser - completed the
|
|
2703
|
-
// setup with a consumer account. The hosted-domain claim of the ID token is checked here
|
|
2704
|
-
// instead, and a token that names no domain is refused rather than trusted: for the Gmail
|
|
2705
|
-
// provider the OpenID scopes are always requested (GmailOauth's constructor adds them), so
|
|
2706
|
-
// a missing claim means the account has no Workspace domain, not that the claim was never
|
|
2707
|
-
// asked for.
|
|
2708
|
-
if (oauth2App.googleWorkspaceAccounts && oauth2App.provider === 'gmail' && !workspaceDomain) {
|
|
2709
|
-
request.logger.warn({
|
|
2710
|
-
msg: 'OAuth2 sign-in used a personal account for a Workspace-only application',
|
|
2711
|
-
account: accountData.account,
|
|
2712
|
-
provider: oauth2App.provider
|
|
2713
|
-
});
|
|
2714
|
+
request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: userInfo.email, provider: oauth2App.provider });
|
|
2714
2715
|
|
|
2715
|
-
|
|
2716
|
-
|
|
2717
|
-
if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
|
|
2718
|
-
try {
|
|
2719
|
-
await oAuth2Client.revokeToken(grantToken);
|
|
2720
|
-
} catch (err) {
|
|
2721
|
-
request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after a Workspace check', err });
|
|
2722
|
-
}
|
|
2723
|
-
}
|
|
2716
|
+
return { grantToken: r.refresh_token || r.access_token };
|
|
2717
|
+
}
|
|
2724
2718
|
|
|
2725
|
-
|
|
2726
|
-
|
|
2727
|
-
const retryUrl = await startOAuthRetry(accountData.email, 'select_account consent');
|
|
2719
|
+
async function completeMailRuCallback(flow) {
|
|
2720
|
+
const { request, oAuth2Client, oauth2App, provider, accountData, providerIdentities } = flow;
|
|
2728
2721
|
|
|
2729
|
-
|
|
2730
|
-
|
|
2722
|
+
const r = await oAuth2Client.getToken(request.query.code);
|
|
2723
|
+
if (!r || !r.access_token) {
|
|
2724
|
+
let error = Boom.boomify(new Error(`Oauth failed: did not get token`), { statusCode: 400 });
|
|
2725
|
+
throw error;
|
|
2726
|
+
}
|
|
2731
2727
|
|
|
2732
|
-
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
|
|
2736
|
-
|
|
2737
|
-
|
|
2738
|
-
|
|
2739
|
-
|
|
2740
|
-
|
|
2728
|
+
let profileRes;
|
|
2729
|
+
try {
|
|
2730
|
+
profileRes = await oAuth2Client.request(r.access_token, 'https://oauth.mail.ru/userinfo');
|
|
2731
|
+
} catch (err) {
|
|
2732
|
+
let response = err.oauthRequest && err.oauthRequest.response;
|
|
2733
|
+
if (response && response.error) {
|
|
2734
|
+
let message = response.error.message;
|
|
2735
|
+
let error = Boom.boomify(new Error(message), { statusCode: resolveOAuthErrorStatus(response.error, err) });
|
|
2736
|
+
throw error;
|
|
2737
|
+
}
|
|
2738
|
+
throw err;
|
|
2739
|
+
}
|
|
2741
2740
|
|
|
2742
|
-
|
|
2743
|
-
|
|
2744
|
-
|
|
2745
|
-
|
|
2746
|
-
try {
|
|
2747
|
-
await oAuth2Client.revokeToken(grantToken);
|
|
2748
|
-
} catch (err) {
|
|
2749
|
-
request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
|
|
2750
|
-
}
|
|
2751
|
-
}
|
|
2741
|
+
if (!profileRes || !profileRes || !profileRes.email) {
|
|
2742
|
+
let error = Boom.boomify(new Error(`Oauth failed: failed to retrieve account email address`), { statusCode: 400 });
|
|
2743
|
+
throw error;
|
|
2744
|
+
}
|
|
2752
2745
|
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2746
|
+
// Back-channel only: the Mail.ru userinfo endpoint response.
|
|
2747
|
+
providerIdentities.push(profileRes.email);
|
|
2748
|
+
|
|
2749
|
+
accountData.name = accountData.name || profileRes.name || '';
|
|
2750
|
+
accountData.email = isEmail(profileRes.email) ? profileRes.email : accountData.email;
|
|
2751
|
+
|
|
2752
|
+
accountData.oauth2 = Object.assign(
|
|
2753
|
+
accountData.oauth2 || {},
|
|
2754
|
+
{
|
|
2755
|
+
provider,
|
|
2756
|
+
accessToken: r.access_token,
|
|
2757
|
+
refreshToken: r.refresh_token,
|
|
2758
|
+
expires: new Date(Date.now() + r.expires_in * 1000),
|
|
2759
|
+
scope: r.scope ? r.scope.split(/\s+/) : MAIL_RU_SCOPES,
|
|
2760
|
+
tokenType: r.token_type
|
|
2761
|
+
},
|
|
2762
|
+
{
|
|
2763
|
+
auth: {
|
|
2764
|
+
user: profileRes.email
|
|
2769
2765
|
}
|
|
2766
|
+
}
|
|
2767
|
+
);
|
|
2770
2768
|
|
|
2771
|
-
|
|
2772
|
-
// Pin the account so every later setup is checked, including one driven by a link that
|
|
2773
|
-
// carries no expectation of its own.
|
|
2774
|
-
accountData.expectedEmail = expectedEmail;
|
|
2775
|
-
}
|
|
2769
|
+
request.logger.info({ msg: 'Provisioned OAuth2 tokens', user: profileRes.email, provider: oauth2App.provider });
|
|
2776
2770
|
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
delete accountData.delegated;
|
|
2780
|
-
}
|
|
2771
|
+
return { grantToken: r.refresh_token || r.access_token };
|
|
2772
|
+
}
|
|
2781
2773
|
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2774
|
+
// Exchanges the authorization code with the app's provider type (flow.oauth2App.provider, for example
|
|
2775
|
+
// "gmail") and fills in accountData and providerIdentities from what the provider returned. Resolves
|
|
2776
|
+
// to `{ view }` when the setup has to stop on a page of its own, otherwise to:
|
|
2777
|
+
// grantToken - the token to revoke if the setup is rejected after the exchange. The refresh
|
|
2778
|
+
// token is preferred: revoking either invalidates the grant, but the access token
|
|
2779
|
+
// may already be expired.
|
|
2780
|
+
// workspaceDomain - the Workspace or Cloud organization domain, for an application restricted to
|
|
2781
|
+
// Google Workspace accounts. Only the Gmail provider reports one; the restriction
|
|
2782
|
+
// is a Google setting and no other provider has the notion.
|
|
2783
|
+
async function exchangeOAuthCode(flow) {
|
|
2784
|
+
switch (flow.oauth2App.provider) {
|
|
2785
|
+
case 'gmail':
|
|
2786
|
+
return await completeGmailCallback(flow);
|
|
2787
|
+
|
|
2788
|
+
case 'outlook':
|
|
2789
|
+
return await completeOutlookCallback(flow);
|
|
2790
|
+
|
|
2791
|
+
case 'mailRu':
|
|
2792
|
+
return await completeMailRuCallback(flow);
|
|
2793
|
+
|
|
2794
|
+
default: {
|
|
2795
|
+
throw new Error('Unknown OAuth2 provider');
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
}
|
|
2788
2799
|
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
//
|
|
2794
|
-
// Backward-compat, BY DESIGN: this only engages when accountMeta.n is present. Legacy /
|
|
2795
|
-
// pre-upgrade re-auth blobs carry no nonce (accountMeta.n is undefined), so the claim is
|
|
2796
|
-
// skipped and those links keep working - the OAuth entry (accountFormHandler) intentionally
|
|
2797
|
-
// does NOT require a nonce for exactly that reason.
|
|
2798
|
-
// claimFormNonce/releaseFormNonce (lib/tools.js) are the same primitives the IMAP arm uses, so
|
|
2799
|
-
// the double-spend semantics stay in one place.
|
|
2800
|
-
let nonceClaimed = false;
|
|
2801
|
-
if (accountMeta.n) {
|
|
2802
|
-
let claimed;
|
|
2803
|
-
try {
|
|
2804
|
-
claimed = await claimFormNonce(redis, accountMeta.n, accountMeta.t);
|
|
2805
|
-
} catch (err) {
|
|
2806
|
-
// A Redis failure is not a consumed nonce - surface a retryable error rather than
|
|
2807
|
-
// misreporting a valid setup URL as invalid.
|
|
2808
|
-
request.logger.error({ msg: 'Failed to claim nonce for an account form request', err });
|
|
2809
|
-
throw Boom.boomify(new Error('Temporary error, please try again'), { statusCode: 500 });
|
|
2810
|
-
}
|
|
2811
|
-
if (!claimed) {
|
|
2812
|
-
// The nonce key already exists: this signed URL was already used.
|
|
2813
|
-
throw Boom.boomify(new Error('Invalid or expired account setup URL'), { statusCode: 403 });
|
|
2814
|
-
}
|
|
2815
|
-
nonceClaimed = true;
|
|
2816
|
-
}
|
|
2800
|
+
// The Workspace restriction and the expected identity, both checked after the code exchange.
|
|
2801
|
+
// Answers the error page with a way back when the setup has to be refused
|
|
2802
|
+
async function rejectOAuthIdentity(flow, { grantToken, workspaceDomain }, expectedEmail) {
|
|
2803
|
+
const { request, h, accountData, oauth2App, oAuth2Client, providerIdentities } = flow;
|
|
2817
2804
|
|
|
2818
|
-
|
|
2805
|
+
// The code was already exchanged, so a refused setup leaves us holding a grant we will never
|
|
2806
|
+
// use. Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
|
|
2807
|
+
// GmailOauth implements revokeToken, and a rejected setup must not become a 500.
|
|
2808
|
+
const revokeUnusedGrant = async failureMessage => {
|
|
2809
|
+
if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
|
|
2819
2810
|
try {
|
|
2820
|
-
|
|
2811
|
+
await oAuth2Client.revokeToken(grantToken);
|
|
2821
2812
|
} catch (err) {
|
|
2822
|
-
|
|
2823
|
-
// Redis also fails here the nonce stays consumed for its TTL and a fresh link is needed -
|
|
2824
|
-
// the price of claim-before-create being atomic).
|
|
2825
|
-
if (nonceClaimed) {
|
|
2826
|
-
await releaseFormNonce(redis, accountMeta.n, request.logger);
|
|
2827
|
-
}
|
|
2828
|
-
throw err;
|
|
2813
|
+
request.logger.warn({ msg: failureMessage, err });
|
|
2829
2814
|
}
|
|
2815
|
+
}
|
|
2816
|
+
};
|
|
2830
2817
|
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2818
|
+
// "Accept only Google Workspace accounts" used to be advisory: generateAuthUrl() sets hd=*,
|
|
2819
|
+
// which filters the account chooser Google shows and nothing else, so a link assembled
|
|
2820
|
+
// without that argument - or a user who switches account inside the chooser - completed the
|
|
2821
|
+
// setup with a consumer account. The hosted-domain claim of the ID token is checked here
|
|
2822
|
+
// instead, and a token that names no domain is refused rather than trusted: for the Gmail
|
|
2823
|
+
// provider the OpenID scopes are always requested (GmailOauth's constructor adds them), so
|
|
2824
|
+
// a missing claim means the account has no Workspace domain, not that the claim was never
|
|
2825
|
+
// asked for.
|
|
2826
|
+
if (oauth2App.googleWorkspaceAccounts && oauth2App.provider === 'gmail' && !workspaceDomain) {
|
|
2827
|
+
request.logger.warn({
|
|
2828
|
+
msg: 'OAuth2 sign-in used a personal account for a Workspace-only application',
|
|
2829
|
+
account: accountData.account,
|
|
2830
|
+
provider: oauth2App.provider
|
|
2831
|
+
});
|
|
2841
2832
|
|
|
2842
|
-
|
|
2843
|
-
|
|
2833
|
+
await revokeUnusedGrant('Failed to revoke the OAuth2 grant after a Workspace check');
|
|
2834
|
+
|
|
2835
|
+
// select_account for the same reason as the identity mismatch: they are signed in to the
|
|
2836
|
+
// account that just failed, and without it Google would hand back the same one
|
|
2837
|
+
const retryUrl = await startOAuthRetry(flow, accountData.email, 'select_account consent');
|
|
2838
|
+
|
|
2839
|
+
return workspaceErrorView(request, h, { actualEmail: providerIdentities[0], retryUrl });
|
|
2840
|
+
}
|
|
2841
|
+
|
|
2842
|
+
if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
|
|
2843
|
+
// Neither address is logged: the expectation and the authenticated identity both belong to
|
|
2844
|
+
// the end user, and this line is the one record of a failed attempt. Note the provider
|
|
2845
|
+
// identity was already logged by the provider's "Provisioned OAuth2 tokens" line in exchangeOAuthCode().
|
|
2846
|
+
request.logger.warn({
|
|
2847
|
+
msg: 'OAuth2 identity did not match the expected email address',
|
|
2848
|
+
account: accountData.account,
|
|
2849
|
+
provider: oauth2App.provider
|
|
2850
|
+
});
|
|
2851
|
+
|
|
2852
|
+
await revokeUnusedGrant('Failed to revoke the OAuth2 grant after an identity mismatch');
|
|
2853
|
+
|
|
2854
|
+
// Stop here with a way back rather than redirecting to the calling application: signing in
|
|
2855
|
+
// as the wrong account is a correctable mistake, and the hosted flow only ever redirects on
|
|
2856
|
+
// success. Hint the address they were supposed to use, and force the account picker:
|
|
2857
|
+
// they are already signed in to the one that just failed, so without select_account Google
|
|
2858
|
+
// would hand back the same account and the retry would loop. Microsoft always shows the
|
|
2859
|
+
// picker and Mail.ru ignores the hint, so this only changes Google's behavior.
|
|
2860
|
+
const retryUrl = await startOAuthRetry(flow, expectedEmail, 'select_account consent');
|
|
2861
|
+
|
|
2862
|
+
return identityErrorView(request, h, {
|
|
2863
|
+
expectedEmail,
|
|
2864
|
+
// The primary address the provider reported. Microsoft can return both a mailbox
|
|
2865
|
+
// address and a user principal name, and either would have satisfied the pin, so
|
|
2866
|
+
// naming the first is enough to show which account actually signed in.
|
|
2867
|
+
actualEmail: providerIdentities[0],
|
|
2868
|
+
retryUrl
|
|
2869
|
+
});
|
|
2870
|
+
}
|
|
2871
|
+
}
|
|
2872
|
+
|
|
2873
|
+
async function handleOAuthCallback(request, h) {
|
|
2874
|
+
assertOAuthCallbackQuery(request);
|
|
2875
|
+
|
|
2876
|
+
const accountData = await claimOAuthSetup(request);
|
|
2877
|
+
|
|
2878
|
+
const accountMeta = accountData._meta || {};
|
|
2879
|
+
delete accountData._meta;
|
|
2880
|
+
|
|
2881
|
+
const redirectUrl = accountMeta.redirectUrl;
|
|
2882
|
+
|
|
2883
|
+
const provider = accountData.oauth2.provider;
|
|
2884
|
+
|
|
2885
|
+
// What the caller originally asked for, captured before the provider branches below rewrite
|
|
2886
|
+
// accountData from whoever signed in. A retry has to start from this rather than from the
|
|
2887
|
+
// rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
|
|
2888
|
+
// with the authenticated address), `name` gets filled in from the rejected user's profile when
|
|
2889
|
+
// the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
|
|
2890
|
+
// credential, so it must survive while the tokens do not.
|
|
2891
|
+
const requestedSetup = {
|
|
2892
|
+
email: accountData.email,
|
|
2893
|
+
name: accountData.name,
|
|
2894
|
+
delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
|
|
2895
|
+
};
|
|
2896
|
+
|
|
2897
|
+
const oauth2App = await oauth2Apps.get(provider);
|
|
2898
|
+
if (!oauth2App) {
|
|
2899
|
+
let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
|
|
2900
|
+
throw error;
|
|
2901
|
+
}
|
|
2902
|
+
|
|
2903
|
+
// The code exchange, the profile lookups and any revoke already speak for the account being
|
|
2904
|
+
// set up, so they leave through its route (its own proxy, if the setup named one)
|
|
2905
|
+
const oAuth2Client = await oauth2Apps.getClient(oauth2App.id, { route: await getAccountHttpRoute(redis, accountData) });
|
|
2906
|
+
|
|
2907
|
+
// What the provider steps below read, and the values they fill in
|
|
2908
|
+
const flow = {
|
|
2909
|
+
request,
|
|
2910
|
+
h,
|
|
2911
|
+
accountData,
|
|
2912
|
+
accountMeta,
|
|
2913
|
+
requestedSetup,
|
|
2914
|
+
provider,
|
|
2915
|
+
oauth2App,
|
|
2916
|
+
oAuth2Client,
|
|
2917
|
+
|
|
2918
|
+
// Addresses the provider itself returned over a back channel, the only values allowed to
|
|
2919
|
+
// satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
|
|
2920
|
+
// fills this in; one that does not leaves it empty, and an empty list fails the check closed.
|
|
2921
|
+
providerIdentities: []
|
|
2922
|
+
};
|
|
2923
|
+
|
|
2924
|
+
const exchange = await exchangeOAuthCode(flow);
|
|
2925
|
+
if (exchange.view) {
|
|
2926
|
+
return exchange.view;
|
|
2927
|
+
}
|
|
2928
|
+
|
|
2929
|
+
// Expected identity check. Runs before the nonce claim and before create(), so a rejected
|
|
2930
|
+
// setup neither consumes the signed link nor overwrites the credentials already on the
|
|
2931
|
+
// account. The expectation can come from the signed form blob or from the account itself -
|
|
2932
|
+
// persisting it is what makes the constraint outlive the link that introduced it, and it is
|
|
2933
|
+
// why a later link issued without expectedEmail cannot quietly drop the pin.
|
|
2934
|
+
const expectedEmail = await resolveExpectedIdentity(redis, {
|
|
2935
|
+
account: accountData.account,
|
|
2936
|
+
blobExpectation: pendingSetupExpectation(accountData, accountMeta)
|
|
2937
|
+
});
|
|
2938
|
+
|
|
2939
|
+
const identityView = await rejectOAuthIdentity(flow, exchange, expectedEmail);
|
|
2940
|
+
if (identityView) {
|
|
2941
|
+
return identityView;
|
|
2942
|
+
}
|
|
2943
|
+
|
|
2944
|
+
if (expectedEmail) {
|
|
2945
|
+
// Pin the account so every later setup is checked, including one driven by a link that
|
|
2946
|
+
// carries no expectation of its own.
|
|
2947
|
+
accountData.expectedEmail = expectedEmail;
|
|
2948
|
+
}
|
|
2949
|
+
|
|
2950
|
+
if ('delegated' in accountData) {
|
|
2951
|
+
// remove artefacts
|
|
2952
|
+
delete accountData.delegated;
|
|
2953
|
+
}
|
|
2954
|
+
|
|
2955
|
+
const accountObject = new Account({
|
|
2956
|
+
redis,
|
|
2957
|
+
call,
|
|
2958
|
+
secret: await getSecret(),
|
|
2959
|
+
timeout: request.headers['x-ee-timeout']
|
|
2960
|
+
});
|
|
2961
|
+
|
|
2962
|
+
// The nonce claim spans both arms, so one signed link cannot be spent on each (start OAuth2,
|
|
2963
|
+
// submit the same blob to /accounts/new/imap/server, then complete this callback) and a
|
|
2964
|
+
// replayed callback cannot create a second account. Only a link that carries a nonce is
|
|
2965
|
+
// claimed: re-auth links issued before nonces existed carry none, and the OAuth2 entry
|
|
2966
|
+
// (accountFormHandler) deliberately does not require one so that they keep working.
|
|
2967
|
+
const httpRedirectUrl = await completeAccountSetup(request, {
|
|
2968
|
+
accountObject,
|
|
2969
|
+
accountData,
|
|
2970
|
+
nonce: accountMeta.n ? { n: accountMeta.n, t: accountMeta.t } : null,
|
|
2971
|
+
redirectUrl
|
|
2972
|
+
});
|
|
2973
|
+
|
|
2974
|
+
return renderRedirect(request, h, httpRedirectUrl);
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
function registerOAuthCallbackRoute(server) {
|
|
2978
|
+
server.route({
|
|
2979
|
+
method: 'GET',
|
|
2980
|
+
path: '/oauth',
|
|
2981
|
+
handler: handleOAuthCallback,
|
|
2844
2982
|
options: {
|
|
2845
2983
|
description: 'OAuth2 response endpoint',
|
|
2846
2984
|
|
|
@@ -2886,28 +3024,9 @@ const init = async () => {
|
|
|
2886
3024
|
auth: false
|
|
2887
3025
|
}
|
|
2888
3026
|
});
|
|
3027
|
+
}
|
|
2889
3028
|
|
|
2890
|
-
|
|
2891
|
-
// can be captured without booting this worker - see test/api-routes-table-test.js)
|
|
2892
|
-
await registerApiRoutes({
|
|
2893
|
-
server,
|
|
2894
|
-
call,
|
|
2895
|
-
notify,
|
|
2896
|
-
metrics,
|
|
2897
|
-
CORS_CONFIG,
|
|
2898
|
-
FLAG_SORT_ORDER,
|
|
2899
|
-
SMTP_TEST_HOST,
|
|
2900
|
-
MAX_ATTACHMENT_SIZE,
|
|
2901
|
-
MAX_BODY_SIZE,
|
|
2902
|
-
MAX_PAYLOAD_TIMEOUT,
|
|
2903
|
-
mcpFeatureEnabled,
|
|
2904
|
-
oauth2Schema,
|
|
2905
|
-
imapSchema,
|
|
2906
|
-
smtpSchema,
|
|
2907
|
-
AccountTypeSchema,
|
|
2908
|
-
OAuth2ProviderSchema
|
|
2909
|
-
});
|
|
2910
|
-
|
|
3029
|
+
async function registerCsrfProtection(server, secureCookie) {
|
|
2911
3030
|
// Web UI routes
|
|
2912
3031
|
|
|
2913
3032
|
await server.register({
|
|
@@ -2929,7 +3048,9 @@ const init = async () => {
|
|
|
2929
3048
|
}
|
|
2930
3049
|
}
|
|
2931
3050
|
});
|
|
3051
|
+
}
|
|
2932
3052
|
|
|
3053
|
+
function registerViews(server) {
|
|
2933
3054
|
server.views({
|
|
2934
3055
|
engines: {
|
|
2935
3056
|
hbs: handlebars
|
|
@@ -3185,7 +3306,9 @@ const init = async () => {
|
|
|
3185
3306
|
};
|
|
3186
3307
|
}
|
|
3187
3308
|
});
|
|
3309
|
+
}
|
|
3188
3310
|
|
|
3311
|
+
function registerResponseExtensions(server) {
|
|
3189
3312
|
const preResponse = async (request, h) => {
|
|
3190
3313
|
let response = request.response;
|
|
3191
3314
|
|
|
@@ -3241,8 +3364,8 @@ const init = async () => {
|
|
|
3241
3364
|
const wantsJsonError = routeTags.includes('api') || routeTags.includes('external');
|
|
3242
3365
|
|
|
3243
3366
|
if (request.errorInfo && wantsJsonError) {
|
|
3244
|
-
// JSON response for API requests
|
|
3245
|
-
|
|
3367
|
+
// JSON response for API requests. A 404 thrown without a code already got NotFound
|
|
3368
|
+
// from errorCodeExt(), registered ahead of this handler
|
|
3246
3369
|
let res = h.response(request.errorInfo);
|
|
3247
3370
|
if (error.output.headers) {
|
|
3248
3371
|
for (let key of Object.keys(error.output.headers)) {
|
|
@@ -3267,12 +3390,20 @@ const init = async () => {
|
|
|
3267
3390
|
.code(error.output.statusCode);
|
|
3268
3391
|
};
|
|
3269
3392
|
|
|
3393
|
+
// First: fills in the default code of an error body before preResponse copies it
|
|
3394
|
+
server.ext('onPreResponse', errorCodeExt);
|
|
3270
3395
|
server.ext('onPreResponse', preResponse);
|
|
3271
3396
|
|
|
3272
3397
|
// After preResponse on purpose: it replaces an error response with the rendered error page
|
|
3273
3398
|
// or a JSON body, and the headers have to land on whatever is actually sent
|
|
3274
3399
|
server.ext('onPreResponse', securityHeadersExt({ cspMode: CSP_MODE }));
|
|
3275
3400
|
|
|
3401
|
+
// Deprecation, Sunset and Link on the routes that declare plugins.deprecation, also after
|
|
3402
|
+
// preResponse for the same reason
|
|
3403
|
+
server.ext('onPreResponse', deprecationExt({ logger }));
|
|
3404
|
+
}
|
|
3405
|
+
|
|
3406
|
+
function registerTotpExtension(server) {
|
|
3276
3407
|
server.ext('onPostAuth', async (request, h) => {
|
|
3277
3408
|
if (request.requireTotp) {
|
|
3278
3409
|
// The password step is done and only the second factor is missing, so the session
|
|
@@ -3289,7 +3420,9 @@ const init = async () => {
|
|
|
3289
3420
|
}
|
|
3290
3421
|
return h.continue;
|
|
3291
3422
|
});
|
|
3423
|
+
}
|
|
3292
3424
|
|
|
3425
|
+
function registerChangesRoute(server) {
|
|
3293
3426
|
server.route({
|
|
3294
3427
|
method: 'GET',
|
|
3295
3428
|
path: '/admin/changes',
|
|
@@ -3298,10 +3431,9 @@ const init = async () => {
|
|
|
3298
3431
|
// helper so the two can not drift apart on framing or on stream cleanup.
|
|
3299
3432
|
handler: openChangeStream
|
|
3300
3433
|
});
|
|
3434
|
+
}
|
|
3301
3435
|
|
|
3302
|
-
|
|
3303
|
-
routesUi(server, call);
|
|
3304
|
-
|
|
3436
|
+
function registerMetricsRoute(server) {
|
|
3305
3437
|
server.route({
|
|
3306
3438
|
method: 'GET',
|
|
3307
3439
|
path: '/metrics',
|
|
@@ -3319,7 +3451,9 @@ const init = async () => {
|
|
|
3319
3451
|
}
|
|
3320
3452
|
}
|
|
3321
3453
|
});
|
|
3454
|
+
}
|
|
3322
3455
|
|
|
3456
|
+
function registerNotFoundRoute(server) {
|
|
3323
3457
|
server.route({
|
|
3324
3458
|
method: '*',
|
|
3325
3459
|
path: '/{any*}',
|
|
@@ -3327,7 +3461,9 @@ const init = async () => {
|
|
|
3327
3461
|
throw Boom.notFound(request.app.gt.gettext('Requested page not found')); // 404
|
|
3328
3462
|
}
|
|
3329
3463
|
});
|
|
3464
|
+
}
|
|
3330
3465
|
|
|
3466
|
+
async function startApiListener(server, reusePortListener) {
|
|
3331
3467
|
await server.start();
|
|
3332
3468
|
|
|
3333
3469
|
if (USE_REUSE_PORT) {
|
|
@@ -3358,7 +3494,9 @@ const init = async () => {
|
|
|
3358
3494
|
}
|
|
3359
3495
|
});
|
|
3360
3496
|
}
|
|
3497
|
+
}
|
|
3361
3498
|
|
|
3499
|
+
async function warnUntrustedForwardedFor() {
|
|
3362
3500
|
// An IP allowlist is only as trustworthy as the address it matches against. If the deployment
|
|
3363
3501
|
// takes the client address from X-Forwarded-For but does not say which peers may set it, any
|
|
3364
3502
|
// client that can reach this port can present whatever address the allowlist expects.
|
|
@@ -3382,7 +3520,9 @@ const init = async () => {
|
|
|
3382
3520
|
allowedAddresses: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length ? ADMIN_ACCESS_ADDRESSES : null
|
|
3383
3521
|
});
|
|
3384
3522
|
}
|
|
3523
|
+
}
|
|
3385
3524
|
|
|
3525
|
+
function warmApiReference(server) {
|
|
3386
3526
|
// Warm the swagger.json cache, and with it the /admin/reference render model - which
|
|
3387
3527
|
// reads the same document back and costs ~12ms to build. Doing both here keeps that
|
|
3388
3528
|
// work off the first visitor's request.
|
|
@@ -3395,7 +3535,9 @@ const init = async () => {
|
|
|
3395
3535
|
logger.debug({ msg: 'Failed to build the API reference model', err });
|
|
3396
3536
|
});
|
|
3397
3537
|
});
|
|
3538
|
+
}
|
|
3398
3539
|
|
|
3540
|
+
function scheduleCertificateReconciler(certHandler) {
|
|
3399
3541
|
// Keep the configured hostnames supplied with certificates.
|
|
3400
3542
|
//
|
|
3401
3543
|
// This used to be a renewal timer and nothing else: it read the certificate for the service
|
|
@@ -3427,6 +3569,93 @@ const init = async () => {
|
|
|
3427
3569
|
|
|
3428
3570
|
handler().catch(err => logger.error({ msg: 'Failed to run certificate handler', err }));
|
|
3429
3571
|
}, TLS_RENEW_CHECK_INTERVAL).unref();
|
|
3572
|
+
}
|
|
3573
|
+
|
|
3574
|
+
const init = async () => {
|
|
3575
|
+
await loadTranslations();
|
|
3576
|
+
|
|
3577
|
+
gt.setLocale((await settings.get('locale')) || 'en');
|
|
3578
|
+
|
|
3579
|
+
registerHandlebarsHelpers(handlebars, { gt });
|
|
3580
|
+
|
|
3581
|
+
const { server, certHandler, apiTlsContext, reusePortListener } = await createApiServer();
|
|
3582
|
+
|
|
3583
|
+
decorateApiToolkit(server, certHandler, apiTlsContext);
|
|
3584
|
+
|
|
3585
|
+
registerLocaleExtension(server);
|
|
3586
|
+
registerRequestContextExtension(server);
|
|
3587
|
+
|
|
3588
|
+
const openApiOptions = buildOpenApiOptions();
|
|
3589
|
+
|
|
3590
|
+
registerApiTokenAuth(server);
|
|
3591
|
+
|
|
3592
|
+
const secureCookie = await registerSessionAuth(server);
|
|
3593
|
+
|
|
3594
|
+
await registerOktaAuth(server, secureCookie);
|
|
3595
|
+
await registerOidcAuth(server, secureCookie);
|
|
3596
|
+
|
|
3597
|
+
await registerServerPlugins(server);
|
|
3598
|
+
|
|
3599
|
+
// Position is not load-bearing: the document is generated from the finished route table on the
|
|
3600
|
+
// first request, not at registration time
|
|
3601
|
+
registerOpenApiRoute(server, openApiOptions);
|
|
3602
|
+
|
|
3603
|
+
registerRequestEvents(server);
|
|
3604
|
+
|
|
3605
|
+
registerStaticPageRoutes(server);
|
|
3606
|
+
registerStaticFilesRoute(server);
|
|
3607
|
+
registerHealthRoute(server);
|
|
3608
|
+
registerRedirectRoute(server);
|
|
3609
|
+
registerOpenTrackingRoute(server);
|
|
3610
|
+
registerUnsubscribeRoute(server);
|
|
3611
|
+
registerOutlookNotificationRoute(server);
|
|
3612
|
+
registerOutlookLifecycleRoute(server);
|
|
3613
|
+
registerOAuthCallbackRoute(server);
|
|
3614
|
+
|
|
3615
|
+
// setup every /v1 route module (wiring lives in lib/api-routes/index.js so the route table
|
|
3616
|
+
// can be captured without booting this worker - see test/api-routes-table-test.js)
|
|
3617
|
+
await registerApiRoutes({
|
|
3618
|
+
server,
|
|
3619
|
+
call,
|
|
3620
|
+
notify,
|
|
3621
|
+
metrics,
|
|
3622
|
+
CORS_CONFIG,
|
|
3623
|
+
FLAG_SORT_ORDER,
|
|
3624
|
+
SMTP_TEST_HOST,
|
|
3625
|
+
MAX_ATTACHMENT_SIZE,
|
|
3626
|
+
MAX_BODY_SIZE,
|
|
3627
|
+
MAX_PAYLOAD_TIMEOUT,
|
|
3628
|
+
mcpFeatureEnabled,
|
|
3629
|
+
oauth2Schema,
|
|
3630
|
+
imapSchema,
|
|
3631
|
+
smtpSchema,
|
|
3632
|
+
AccountTypeSchema,
|
|
3633
|
+
OAuth2ProviderSchema
|
|
3634
|
+
});
|
|
3635
|
+
|
|
3636
|
+
await registerCsrfProtection(server, secureCookie);
|
|
3637
|
+
|
|
3638
|
+
registerViews(server);
|
|
3639
|
+
|
|
3640
|
+
registerResponseExtensions(server);
|
|
3641
|
+
|
|
3642
|
+
registerTotpExtension(server);
|
|
3643
|
+
|
|
3644
|
+
registerChangesRoute(server);
|
|
3645
|
+
|
|
3646
|
+
// setup web UI
|
|
3647
|
+
routesUi(server, call);
|
|
3648
|
+
|
|
3649
|
+
registerMetricsRoute(server);
|
|
3650
|
+
registerNotFoundRoute(server);
|
|
3651
|
+
|
|
3652
|
+
await startApiListener(server, reusePortListener);
|
|
3653
|
+
|
|
3654
|
+
await warnUntrustedForwardedFor();
|
|
3655
|
+
|
|
3656
|
+
warmApiReference(server);
|
|
3657
|
+
|
|
3658
|
+
scheduleCertificateReconciler(certHandler);
|
|
3430
3659
|
};
|
|
3431
3660
|
|
|
3432
3661
|
// dynamic imports first, use a wrapper function or eslint parser will crash
|