emailengine-app 2.77.0 → 2.79.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/.github/workflows/test.yml +80 -0
- package/.ncurc.js +23 -13
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +60 -0
- package/bin/emailengine.js +1 -1
- package/config/e2e.toml +2 -1
- package/config/test.toml +2 -1
- package/data/google-crawlers.json +1 -1
- package/encrypt.js +1 -1
- package/lib/account/expected-identity.js +88 -0
- package/lib/account.js +145 -61
- package/lib/api-reference/format.js +105 -4
- package/lib/api-reference/index.js +24 -7
- package/lib/api-reference/model.js +148 -21
- package/lib/api-reference/schema-tree.js +282 -28
- package/lib/api-routes/account-routes.js +99 -36
- package/lib/api-routes/behavior-notes.js +3 -0
- package/lib/api-routes/blocklist-routes.js +21 -47
- package/lib/api-routes/chat-routes.js +10 -12
- package/lib/api-routes/delivery-test-routes.js +6 -26
- package/lib/api-routes/export-routes.js +2 -0
- package/lib/api-routes/gateway-routes.js +52 -11
- package/lib/api-routes/license-routes.js +2 -0
- package/lib/api-routes/mailbox-routes.js +29 -26
- package/lib/api-routes/message-routes.js +27 -21
- package/lib/api-routes/oauth2-app-routes.js +11 -29
- package/lib/api-routes/operation-impact.js +80 -0
- package/lib/api-routes/outbox-routes.js +15 -5
- package/lib/api-routes/permission-map.js +397 -0
- package/lib/api-routes/route-helpers.js +223 -9
- package/lib/api-routes/route-metadata.js +28 -0
- package/lib/api-routes/settings-routes.js +30 -25
- package/lib/api-routes/stats-routes.js +2 -2
- package/lib/api-routes/submit-routes.js +53 -31
- package/lib/api-routes/template-routes.js +3 -0
- package/lib/api-routes/token-routes.js +319 -33
- package/lib/api-routes/webhook-route-routes.js +14 -4
- package/lib/append-list.js +3 -14
- package/lib/arf-detect.js +23 -1
- package/lib/auth-token.js +80 -8
- package/lib/autodetect-imap-settings.js +40 -16
- package/lib/base32.js +30 -0
- package/lib/bounce-detect.js +182 -62
- package/lib/consts.js +10 -0
- package/lib/db.js +20 -2
- package/lib/delivery-error.js +30 -1
- package/lib/egress-filter.js +89 -8
- package/lib/email-client/base-client.js +35 -113
- package/lib/email-client/gmail-client.js +22 -13
- package/lib/email-client/imap/listing-diff.js +3 -3
- package/lib/email-client/imap/mailbox.js +28 -93
- package/lib/email-client/imap/subconnection.js +10 -7
- package/lib/email-client/imap/sync-operations.js +46 -46
- package/lib/email-client/imap-client.js +39 -28
- package/lib/email-client/message-builder.js +15 -15
- package/lib/email-client/notification-handler.js +1 -1
- package/lib/email-client/outlook/graph-api.js +10 -4
- package/lib/email-client/outlook-client.js +54 -55
- package/lib/email-client/smtp-pool-manager.js +1 -1
- package/lib/enum-descriptions.js +92 -2
- package/lib/export.js +2 -2
- package/lib/field-usage.js +133 -0
- package/lib/gateway.js +2 -2
- package/lib/get-raw-email.js +1 -1
- package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +3 -3
- package/lib/imapproxy/imap-core/lib/commands/id.js +2 -13
- package/lib/imapproxy/imap-core/lib/commands/starttls.js +1 -1
- package/lib/imapproxy/imap-core/lib/imap-command.js +21 -5
- package/lib/imapproxy/imap-core/lib/imap-connection.js +17 -7
- package/lib/imapproxy/imap-core/lib/imap-server.js +2 -2
- package/lib/imapproxy/imap-server.js +40 -10
- package/lib/license-beacon.js +5 -10
- package/lib/lists.js +49 -1
- package/lib/llm-pre-process.js +6 -6
- package/lib/logger.js +5 -1
- package/lib/metrics-collector.js +2 -2
- package/lib/msgpack.js +62 -0
- package/lib/oauth/decode-jwt-payload.js +39 -0
- package/lib/oauth/gmail.js +9 -12
- package/lib/oauth/mail-ru.js +5 -7
- package/lib/oauth/outlook-identity.js +61 -0
- package/lib/oauth/outlook.js +9 -9
- package/lib/oauth/pubsub/google.js +25 -10
- package/lib/oauth/retry-setup.js +38 -0
- package/lib/oauth/scope-checker.js +1 -1
- package/lib/oauth2-apps.js +224 -295
- package/lib/openapi/build-document.js +15 -7
- package/lib/openapi/joi-schema.js +20 -0
- package/lib/outbox.js +145 -14
- package/lib/pre-process.js +9 -9
- package/lib/queue-stats.js +49 -0
- package/lib/read-env-value.js +37 -0
- package/lib/reconnection-manager.js +2 -2
- package/lib/rewrite-text-nodes.js +4 -3
- package/lib/routes-ui.js +4 -0
- package/lib/schemas.js +223 -155
- package/lib/settings.js +84 -5
- package/lib/sub-script.js +2 -1
- package/lib/swagger-options.js +2 -1
- package/lib/templates.js +5 -5
- package/lib/threads.js +2 -2
- package/lib/token-audit-log.js +208 -0
- package/lib/token-permission-view.js +219 -0
- package/lib/token-permissions.js +172 -0
- package/lib/tokens.js +100 -16
- package/lib/tools.js +259 -85
- package/lib/totp.js +67 -0
- package/lib/ui-routes/account-routes.js +122 -26
- package/lib/ui-routes/admin-config-routes.js +20 -17
- package/lib/ui-routes/admin-entities-routes.js +66 -22
- package/lib/ui-routes/auth-routes.js +36 -48
- package/lib/ui-routes/export-routes.js +10 -4
- package/lib/ui-routes/oauth-config-routes.js +5 -5
- package/lib/ui-routes/reference-routes.js +11 -8
- package/lib/ui-routes/route-helpers.js +79 -2
- package/lib/ui-routes/settings-page.js +1 -1
- package/lib/ui-routes/smtp-test-routes.js +1 -1
- package/lib/ui-routes/suppression-list-routes.js +294 -0
- package/lib/ui-routes/unsubscribe-routes.js +19 -29
- package/lib/utils/is-email.js +34 -0
- package/lib/utils/network.js +2 -2
- package/lib/utils/to-camel-case.js +17 -0
- package/lib/web-safe-html.js +1 -1
- package/lib/webhook-egress.js +37 -0
- package/lib/webhook-routing.js +80 -0
- package/lib/webhooks.js +21 -15
- package/package.json +26 -27
- package/sbom.json +1 -0
- package/server.js +81 -42
- package/static/css/flyonui.css +1 -1
- package/static/css/public.css +3 -0
- package/static/css/src/app.tailwind.css +159 -9
- package/static/js/app.js +69 -0
- package/static/js/reference.js +741 -10
- package/static/js/ui.js +43 -0
- package/static/licenses.html +698 -1590
- package/translations/README.md +64 -0
- package/translations/de.mo +0 -0
- package/translations/de.po +164 -120
- package/translations/en.po +200 -161
- package/translations/et.mo +0 -0
- package/translations/et.po +163 -120
- package/translations/fr.mo +0 -0
- package/translations/fr.po +163 -120
- package/translations/ja.mo +0 -0
- package/translations/ja.po +163 -120
- package/translations/messages.pot +94 -64
- package/translations/nl.mo +0 -0
- package/translations/nl.po +164 -120
- package/translations/pl.mo +0 -0
- package/translations/pl.po +163 -120
- package/views/account-identity-error.hbs +34 -0
- package/views/accounts/account.hbs +69 -7
- package/views/accounts/browse.hbs +18 -35
- package/views/accounts/edit.hbs +1 -0
- package/views/accounts/register/imap.hbs +12 -2
- package/views/config/logging.hbs +6 -0
- package/views/config/oauth/app.hbs +0 -2
- package/views/config/security.hbs +13 -0
- package/views/layout/app.hbs +29 -5
- package/views/oauth-scope-error.hbs +1 -1
- package/views/partials/oauth_form.hbs +0 -15
- package/views/partials/reference/disclosure.hbs +8 -2
- package/views/partials/reference/nav.hbs +36 -9
- package/views/partials/reference/operation.hbs +48 -14
- package/views/partials/reference/params.hbs +17 -1
- package/views/partials/reference/schema-node.hbs +112 -54
- package/views/partials/reference/schema-tools.hbs +25 -0
- package/views/partials/reference/token-alert.hbs +35 -10
- package/views/partials/reference/try-it.hbs +84 -11
- package/views/partials/side_menu.hbs +1 -0
- package/views/partials/ui/checkbox.hbs +2 -2
- package/views/partials/ui/tabs.hbs +7 -1
- package/views/reference/index.hbs +1 -1
- package/views/reference/token.hbs +4 -0
- package/views/suppression-lists/index.hbs +85 -0
- package/views/suppression-lists/list.hbs +87 -0
- package/views/templates/index.hbs +8 -2
- package/views/tokens/index.hbs +31 -4
- package/views/tokens/new.hbs +324 -2
- package/workers/api.js +299 -140
- package/workers/documents.js +46 -26
- package/workers/export.js +20 -8
- package/workers/imap-proxy.js +2 -2
- package/workers/imap.js +13 -7
- package/workers/smtp.js +13 -7
- package/workers/submit.js +41 -31
- package/workers/webhooks.js +60 -37
- package/lib/feature-flags.js +0 -48
package/workers/api.js
CHANGED
|
@@ -8,10 +8,10 @@ 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 { accountStateLabel, formatServerState } = require('../lib/ui-routes/route-helpers');
|
|
11
|
+
const { accountStateLabel, formatServerState, identityErrorView, isClientError } = require('../lib/ui-routes/route-helpers');
|
|
12
12
|
const util = require('util');
|
|
13
13
|
const { webhooks: Webhooks } = require('../lib/webhooks');
|
|
14
|
-
const
|
|
14
|
+
const { lists } = require('../lib/lists');
|
|
15
15
|
const Bell = require('@hapi/bell');
|
|
16
16
|
const marked = require('marked');
|
|
17
17
|
|
|
@@ -63,10 +63,17 @@ const pathlib = require('path');
|
|
|
63
63
|
const crypto = require('crypto');
|
|
64
64
|
const { registeredPublishers, openChangeStream } = require('../lib/response-stream');
|
|
65
65
|
const { oauth2Apps } = require('../lib/oauth2-apps');
|
|
66
|
+
const { decodeJwtPayload } = require('../lib/oauth/decode-jwt-payload');
|
|
67
|
+
const { resolveOutlookUserInfo } = require('../lib/oauth/outlook-identity');
|
|
68
|
+
const { buildRetrySetup } = require('../lib/oauth/retry-setup');
|
|
69
|
+
const { matchesExpectedIdentity, pendingSetupExpectation, resolveExpectedIdentity } = require('../lib/account/expected-identity');
|
|
66
70
|
|
|
67
71
|
const handlebars = require('handlebars');
|
|
68
72
|
const AuthBearer = require('hapi-auth-bearer-token');
|
|
69
73
|
const tokens = require('../lib/tokens');
|
|
74
|
+
const tokenPermissions = require('../lib/token-permissions');
|
|
75
|
+
const tokenAuditLog = require('../lib/token-audit-log');
|
|
76
|
+
const { routeGrant } = require('../lib/api-routes/permission-map');
|
|
70
77
|
|
|
71
78
|
const { redis, documentsQueue } = require('../lib/db');
|
|
72
79
|
const { Account } = require('../lib/account');
|
|
@@ -147,7 +154,11 @@ function formatScopeDescription(scope) {
|
|
|
147
154
|
return shortName.replace(/\./g, ' ').replace(/\b\w/g, c => c.toUpperCase());
|
|
148
155
|
}
|
|
149
156
|
|
|
150
|
-
|
|
157
|
+
// The two MS Graph subscription routes are unauthenticated and deliberately carry no payload
|
|
158
|
+
// schema: they must answer 202 to anything, because a 400 would make Graph tear the subscription
|
|
159
|
+
// down, and the validation handshake posts an empty body. So the payload is arbitrary JSON and
|
|
160
|
+
// every read of it has to be defensive.
|
|
161
|
+
const graphNotificationEntries = payload => (Array.isArray(payload && payload.value) ? payload.value.filter(entry => entry && typeof entry === 'object') : []);
|
|
151
162
|
|
|
152
163
|
const SMTP_TEST_HOST = 'https://api.nodemailer.com';
|
|
153
164
|
|
|
@@ -377,7 +388,7 @@ function publishChangeEvent(data) {
|
|
|
377
388
|
try {
|
|
378
389
|
stream.sendMessage({ account, type, key, payload, stateLabel });
|
|
379
390
|
} catch (err) {
|
|
380
|
-
logger.
|
|
391
|
+
logger.warn({ msg: 'Failed to publish change event', err, account, type, key, payload });
|
|
381
392
|
}
|
|
382
393
|
}
|
|
383
394
|
}
|
|
@@ -481,13 +492,6 @@ const init = async () => {
|
|
|
481
492
|
|
|
482
493
|
handlebars.registerHelper('ngettext', (msgid, plural, count) => util.format(gt.ngettext(msgid, plural, count), count));
|
|
483
494
|
|
|
484
|
-
handlebars.registerHelper('featureFlag', function (flag, options) {
|
|
485
|
-
if (featureFlags.enabled(flag)) {
|
|
486
|
-
return options.fn(this);
|
|
487
|
-
}
|
|
488
|
-
return options.inverse(this);
|
|
489
|
-
});
|
|
490
|
-
|
|
491
495
|
handlebars.registerHelper('equals', function (compareVal, baseVal, options) {
|
|
492
496
|
if (baseVal === compareVal) {
|
|
493
497
|
return options.fn(this);
|
|
@@ -908,9 +912,39 @@ const init = async () => {
|
|
|
908
912
|
request.logger.setBindings({ tokenId: tokenData.id, tokenAccount: tokenData.account || null });
|
|
909
913
|
}
|
|
910
914
|
|
|
915
|
+
const grant = routeGrant(request.route);
|
|
916
|
+
|
|
917
|
+
// This strategy runs before route validation, so `request.query` is whatever the client
|
|
918
|
+
// sent: a repeated `?account=` arrives as an array. Only a string can name an account,
|
|
919
|
+
// and this value is persisted into the audit log, so anything else is not one.
|
|
920
|
+
const queryAccount = request.query && typeof request.query.account === 'string' ? request.query.account : null;
|
|
921
|
+
|
|
922
|
+
// Shared by every audit entry below, so an allow and a deny describe the same request.
|
|
923
|
+
// Built before the first check that can refuse: a rejection is the strongest signal of
|
|
924
|
+
// credential misuse there is, and a trail that only held the calls that succeeded would
|
|
925
|
+
// be silent about exactly the ones worth looking at.
|
|
926
|
+
const auditEntry = {
|
|
927
|
+
tokenId: tokenData.id,
|
|
928
|
+
ip: request.app.ip,
|
|
929
|
+
method: request.route.method,
|
|
930
|
+
path: request.route.path,
|
|
931
|
+
action: grant.action,
|
|
932
|
+
group: grant.group,
|
|
933
|
+
// The account the REQUEST addressed, which is not always the one in the path: the
|
|
934
|
+
// routes that take it as a query argument are the ones a bound token gets refused
|
|
935
|
+
// on, and falling straight through to the token's own account recorded a
|
|
936
|
+
// cross-account attempt against the account it was entitled to reach - the opposite
|
|
937
|
+
// of what the entry exists to show. The token's account is still the answer for the
|
|
938
|
+
// routes that name no account at all.
|
|
939
|
+
//
|
|
940
|
+
// The refusals below log this field rather than re-deriving it, so the application
|
|
941
|
+
// log and the audit row cannot disagree about which account a denial concerned.
|
|
942
|
+
account: (request.params && request.params.account) || queryAccount || tokenData.account || null
|
|
943
|
+
};
|
|
944
|
+
|
|
911
945
|
if (scope && tokenData.scopes && !tokenData.scopes.includes(scope) && !tokenData.scopes.includes('*')) {
|
|
912
946
|
// failed scope validation
|
|
913
|
-
logger.
|
|
947
|
+
logger.warn({
|
|
914
948
|
msg: 'Trying to use invalid scope for a token',
|
|
915
949
|
tokenAccount: tokenData.account,
|
|
916
950
|
tokenId: tokenData.id,
|
|
@@ -918,11 +952,43 @@ const init = async () => {
|
|
|
918
952
|
tokenScopes: tokenData.scopes
|
|
919
953
|
});
|
|
920
954
|
|
|
955
|
+
tokenAuditLog.denied(auditEntry, 'scope');
|
|
956
|
+
|
|
921
957
|
let error = Boom.forbidden('Unauthorized scope');
|
|
922
958
|
error.output.payload.requestedScope = scope;
|
|
923
959
|
throw error;
|
|
924
960
|
}
|
|
925
961
|
|
|
962
|
+
// Narrowing below the scope. Runs after the scope check and before the account binding,
|
|
963
|
+
// so the order is: token resolved, scope, permissions, account, restrictions.
|
|
964
|
+
//
|
|
965
|
+
// Before the account switch on purpose - that switch reads the account from the query or
|
|
966
|
+
// from a Redis membership check for the three /v1/templates special cases, and none of
|
|
967
|
+
// that should happen for a request the permissions already refuse.
|
|
968
|
+
//
|
|
969
|
+
// Only subtracts: a token with no `permissions` field takes the allowed path, which is
|
|
970
|
+
// every token issued before this shipped.
|
|
971
|
+
const permissionCheck = tokenPermissions.check({ tokenData, operation: grant });
|
|
972
|
+
if (!permissionCheck.allowed) {
|
|
973
|
+
logger.warn({
|
|
974
|
+
msg: 'Token permissions do not allow this operation',
|
|
975
|
+
tokenAccount: tokenData.account,
|
|
976
|
+
tokenId: tokenData.id,
|
|
977
|
+
account: auditEntry.account,
|
|
978
|
+
reason: permissionCheck.reason,
|
|
979
|
+
required: permissionCheck.required
|
|
980
|
+
});
|
|
981
|
+
|
|
982
|
+
let error = Boom.forbidden('Unauthorized permission');
|
|
983
|
+
// Mirrors how the scope failure above attaches requestedScope: an agent that gets a
|
|
984
|
+
// 403 needs to know WHICH grant it lacked, not just that it lacked one.
|
|
985
|
+
// A refused call is the interesting record, so it is logged before the throw
|
|
986
|
+
tokenAuditLog.denied(auditEntry, permissionCheck.reason);
|
|
987
|
+
|
|
988
|
+
error.output.payload.requiredPermission = permissionCheck.required;
|
|
989
|
+
throw error;
|
|
990
|
+
}
|
|
991
|
+
|
|
926
992
|
if (tokenData.account) {
|
|
927
993
|
// account token
|
|
928
994
|
|
|
@@ -930,10 +996,19 @@ const init = async () => {
|
|
|
930
996
|
|
|
931
997
|
// allow specific routes that have an account component but not in the URL params section
|
|
932
998
|
switch (request.route.path) {
|
|
999
|
+
// The two listings that take the account as a query argument. `/v1/tokens` is
|
|
1000
|
+
// here because it replaced GET /v1/tokens/account/{account}, which carried the
|
|
1001
|
+
// account in the path and so reached a bound token's own tokens through the
|
|
1002
|
+
// default branch below - the replacement had nothing reading the argument, so
|
|
1003
|
+
// the capability disappeared with no alias and no error a caller could act on.
|
|
1004
|
+
// Both stay under the same rule as everything else: the argument has to name the
|
|
1005
|
+
// token's own account, and omitting it still refuses, because a bound credential
|
|
1006
|
+
// must not enumerate the instance.
|
|
933
1007
|
case '/v1/templates':
|
|
1008
|
+
case '/v1/tokens':
|
|
934
1009
|
switch (request.method) {
|
|
935
1010
|
case 'get':
|
|
936
|
-
accountIdSource =
|
|
1011
|
+
accountIdSource = queryAccount;
|
|
937
1012
|
break;
|
|
938
1013
|
}
|
|
939
1014
|
break;
|
|
@@ -963,13 +1038,15 @@ const init = async () => {
|
|
|
963
1038
|
}
|
|
964
1039
|
|
|
965
1040
|
if (accountIdSource !== tokenData.account) {
|
|
966
|
-
logger.
|
|
1041
|
+
logger.warn({
|
|
967
1042
|
msg: 'Trying to use invalid account for a token',
|
|
968
1043
|
tokenAccount: tokenData.account,
|
|
969
1044
|
tokenId: tokenData.id,
|
|
970
|
-
account:
|
|
1045
|
+
account: auditEntry.account
|
|
971
1046
|
});
|
|
972
1047
|
|
|
1048
|
+
tokenAuditLog.denied(auditEntry, 'account');
|
|
1049
|
+
|
|
973
1050
|
let error = Boom.forbidden('Unauthorized account');
|
|
974
1051
|
throw error;
|
|
975
1052
|
}
|
|
@@ -977,15 +1054,17 @@ const init = async () => {
|
|
|
977
1054
|
|
|
978
1055
|
if (tokenData.restrictions) {
|
|
979
1056
|
if (tokenData.restrictions.addresses && !matchIp(request.app.ip, tokenData.restrictions.addresses)) {
|
|
980
|
-
logger.
|
|
1057
|
+
logger.warn({
|
|
981
1058
|
msg: 'Trying to use invalid IP for a token',
|
|
982
1059
|
tokenAccount: tokenData.account,
|
|
983
1060
|
tokenId: tokenData.id,
|
|
984
|
-
account:
|
|
1061
|
+
account: auditEntry.account,
|
|
985
1062
|
remoteAddress: request.app.ip,
|
|
986
1063
|
addressAllowlist: tokenData.restrictions.addresses
|
|
987
1064
|
});
|
|
988
1065
|
|
|
1066
|
+
tokenAuditLog.denied(auditEntry, 'address');
|
|
1067
|
+
|
|
989
1068
|
let error = Boom.forbidden('Unauthorized address');
|
|
990
1069
|
error.output.payload.remoteAddress = request.app.ip;
|
|
991
1070
|
throw error;
|
|
@@ -996,15 +1075,17 @@ const init = async () => {
|
|
|
996
1075
|
tokenData.restrictions.referrers.length &&
|
|
997
1076
|
!matcher(tokenData.restrictions.referrers, request.headers.referer)
|
|
998
1077
|
) {
|
|
999
|
-
logger.
|
|
1078
|
+
logger.warn({
|
|
1000
1079
|
msg: 'Trying to use invalid referer for a token',
|
|
1001
1080
|
tokenAccount: tokenData.account,
|
|
1002
1081
|
tokenId: tokenData.id,
|
|
1003
|
-
account:
|
|
1082
|
+
account: auditEntry.account,
|
|
1004
1083
|
referer: request.headers.referer,
|
|
1005
1084
|
referrerAllowlist: tokenData.restrictions.referrers
|
|
1006
1085
|
});
|
|
1007
1086
|
|
|
1087
|
+
tokenAuditLog.denied(auditEntry, 'referrer');
|
|
1088
|
+
|
|
1008
1089
|
let error = Boom.forbidden('Unauthorized referrer');
|
|
1009
1090
|
throw error;
|
|
1010
1091
|
}
|
|
@@ -1018,7 +1099,9 @@ const init = async () => {
|
|
|
1018
1099
|
);
|
|
1019
1100
|
|
|
1020
1101
|
if (!rateLimit.success) {
|
|
1021
|
-
logger.
|
|
1102
|
+
logger.warn({ msg: 'Rate limited', token: tokenData.id, rateLimit });
|
|
1103
|
+
tokenAuditLog.denied(auditEntry, 'rateLimit');
|
|
1104
|
+
|
|
1022
1105
|
let error = Boom.tooManyRequests('Rate limit exceeded');
|
|
1023
1106
|
error.output.payload.ttl = Math.ceil(rateLimit.ttl);
|
|
1024
1107
|
error.output.headers = {
|
|
@@ -1036,6 +1119,13 @@ const init = async () => {
|
|
|
1036
1119
|
}
|
|
1037
1120
|
}
|
|
1038
1121
|
|
|
1122
|
+
// The one point every accepted token request passes. "allowed" means the credential was
|
|
1123
|
+
// accepted, not that the request succeeded: this runs in the auth strategy, before
|
|
1124
|
+
// payload validation and the handler, so a call recorded here can still end in a 400 or
|
|
1125
|
+
// a 404. That is the right boundary for a credential trail - it answers what the token
|
|
1126
|
+
// was permitted to attempt.
|
|
1127
|
+
tokenAuditLog.allowed(auditEntry);
|
|
1128
|
+
|
|
1039
1129
|
return { isValid: true, credentials: { token }, artifacts: tokenData };
|
|
1040
1130
|
}
|
|
1041
1131
|
});
|
|
@@ -1306,9 +1396,9 @@ const init = async () => {
|
|
|
1306
1396
|
await server.register({
|
|
1307
1397
|
plugin: hapiPino,
|
|
1308
1398
|
options: {
|
|
1309
|
-
instance: logger.child({ component: 'api' }, { redact:
|
|
1399
|
+
instance: logger.child({ component: 'api' }, { redact: consts.REDACTED_LOG_KEYS }),
|
|
1310
1400
|
// Redact Authorization headers, see https://getpino.io/#/docs/redaction
|
|
1311
|
-
redact:
|
|
1401
|
+
redact: consts.REDACTED_LOG_KEYS
|
|
1312
1402
|
}
|
|
1313
1403
|
});
|
|
1314
1404
|
|
|
@@ -1547,7 +1637,7 @@ const init = async () => {
|
|
|
1547
1637
|
userAgent: request.headers['user-agent']
|
|
1548
1638
|
});
|
|
1549
1639
|
} else {
|
|
1550
|
-
request.logger.
|
|
1640
|
+
request.logger.debug({
|
|
1551
1641
|
msg: 'Detected automated request',
|
|
1552
1642
|
account: data.acc,
|
|
1553
1643
|
event: TRACK_CLICK_NOTIFY,
|
|
@@ -1611,7 +1701,7 @@ const init = async () => {
|
|
|
1611
1701
|
userAgent: request.headers['user-agent']
|
|
1612
1702
|
});
|
|
1613
1703
|
} else {
|
|
1614
|
-
request.logger.
|
|
1704
|
+
request.logger.debug({
|
|
1615
1705
|
msg: 'Detected automated request',
|
|
1616
1706
|
account: data.acc,
|
|
1617
1707
|
event: TRACK_OPEN_NOTIFY,
|
|
@@ -1711,22 +1801,14 @@ const init = async () => {
|
|
|
1711
1801
|
|
|
1712
1802
|
// Record the suppression. A transient backend failure here is intentionally NOT swallowed to
|
|
1713
1803
|
// a 2xx: it propagates as a 5xx so the client retries rather than dropping the unsubscribe.
|
|
1714
|
-
let isNew = await
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
data.
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
source: 'one-click',
|
|
1723
|
-
reason: 'unsubscribe',
|
|
1724
|
-
messageId: data.msg,
|
|
1725
|
-
remoteAddress: request.app.ip,
|
|
1726
|
-
userAgent: request.headers['user-agent'],
|
|
1727
|
-
created: new Date().toISOString()
|
|
1728
|
-
})
|
|
1729
|
-
);
|
|
1804
|
+
let isNew = await lists.add(data.list, data.rcpt, {
|
|
1805
|
+
account: data.acc,
|
|
1806
|
+
source: 'one-click',
|
|
1807
|
+
reason: 'unsubscribe',
|
|
1808
|
+
messageId: data.msg,
|
|
1809
|
+
remoteAddress: request.app.ip,
|
|
1810
|
+
userAgent: request.headers['user-agent']
|
|
1811
|
+
});
|
|
1730
1812
|
|
|
1731
1813
|
if (isNew) {
|
|
1732
1814
|
// The suppression is already stored; a webhook delivery hiccup must not fail (and thus
|
|
@@ -1740,7 +1822,7 @@ const init = async () => {
|
|
|
1740
1822
|
userAgent: request.headers['user-agent']
|
|
1741
1823
|
});
|
|
1742
1824
|
} catch (err) {
|
|
1743
|
-
request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', err });
|
|
1825
|
+
request.logger.error({ msg: 'Failed to send one-click unsubscribe webhook', account: data.acc, listId: data.list, err });
|
|
1744
1826
|
}
|
|
1745
1827
|
}
|
|
1746
1828
|
|
|
@@ -1812,14 +1894,20 @@ const init = async () => {
|
|
|
1812
1894
|
throw err;
|
|
1813
1895
|
}
|
|
1814
1896
|
|
|
1897
|
+
const notificationEntries = graphNotificationEntries(request.payload);
|
|
1898
|
+
|
|
1815
1899
|
if (!accountData.outlookSubscription) {
|
|
1816
|
-
request.logger.
|
|
1900
|
+
request.logger.warn({
|
|
1901
|
+
msg: 'Subscription not found for account',
|
|
1902
|
+
account: request.query.account,
|
|
1903
|
+
subscriptionIds: notificationEntries.map(entry => entry.subscriptionId)
|
|
1904
|
+
});
|
|
1817
1905
|
return h.response(Buffer.alloc(0)).code(202);
|
|
1818
1906
|
}
|
|
1819
1907
|
|
|
1820
1908
|
const outlookSubscription = accountData.outlookSubscription;
|
|
1821
1909
|
|
|
1822
|
-
for (let entry of
|
|
1910
|
+
for (let entry of notificationEntries) {
|
|
1823
1911
|
// enumerate and queue all entries
|
|
1824
1912
|
const subscriptionIdMatch = entry.subscriptionId === outlookSubscription.id;
|
|
1825
1913
|
const clientStateMatch = constantTimeEqual(entry.clientState, outlookSubscription.clientState);
|
|
@@ -1906,8 +1994,14 @@ const init = async () => {
|
|
|
1906
1994
|
throw err;
|
|
1907
1995
|
}
|
|
1908
1996
|
|
|
1997
|
+
const lifecycleEntries = graphNotificationEntries(request.payload);
|
|
1998
|
+
|
|
1909
1999
|
if (!accountData.outlookSubscription) {
|
|
1910
|
-
request.logger.
|
|
2000
|
+
request.logger.warn({
|
|
2001
|
+
msg: 'Subscription not found for account',
|
|
2002
|
+
account: request.query.account,
|
|
2003
|
+
subscriptionIds: lifecycleEntries.map(entry => entry.subscriptionId)
|
|
2004
|
+
});
|
|
1911
2005
|
return h.response(Buffer.alloc(0)).code(202);
|
|
1912
2006
|
}
|
|
1913
2007
|
|
|
@@ -1917,7 +2011,7 @@ const init = async () => {
|
|
|
1917
2011
|
// concurrent handlers racing (e.g., two subscriptionRemoved entries)
|
|
1918
2012
|
const seenLifecycleEvents = new Set();
|
|
1919
2013
|
|
|
1920
|
-
for (let entry of
|
|
2014
|
+
for (let entry of lifecycleEntries) {
|
|
1921
2015
|
request.logger.debug({
|
|
1922
2016
|
msg: 'MS Graph subscription event',
|
|
1923
2017
|
type: 'lifecycle',
|
|
@@ -2056,6 +2150,18 @@ const init = async () => {
|
|
|
2056
2150
|
|
|
2057
2151
|
const provider = accountData.oauth2.provider;
|
|
2058
2152
|
|
|
2153
|
+
// What the caller originally asked for, captured before the provider branches below rewrite
|
|
2154
|
+
// accountData from whoever signed in. A retry has to start from this rather than from the
|
|
2155
|
+
// rejected attempt: `email` may name a shared mailbox to bind (and is otherwise overwritten
|
|
2156
|
+
// with the authenticated address), `name` gets filled in from the rejected user's profile when
|
|
2157
|
+
// the caller supplied none, and `oauth2.auth.delegatedUser` names the mailbox rather than a
|
|
2158
|
+
// credential, so it must survive while the tokens do not.
|
|
2159
|
+
const requestedSetup = {
|
|
2160
|
+
email: accountData.email,
|
|
2161
|
+
name: accountData.name,
|
|
2162
|
+
delegatedUser: accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser
|
|
2163
|
+
};
|
|
2164
|
+
|
|
2059
2165
|
const oauth2App = await oauth2Apps.get(provider);
|
|
2060
2166
|
if (!oauth2App) {
|
|
2061
2167
|
let error = Boom.boomify(new Error('Missing or disabled OAuth2 app'), { statusCode: 404 });
|
|
@@ -2064,6 +2170,44 @@ const init = async () => {
|
|
|
2064
2170
|
|
|
2065
2171
|
const oAuth2Client = await oauth2Apps.getClient(oauth2App.id);
|
|
2066
2172
|
|
|
2173
|
+
// have to use HTML redirect, otherwise samesite=strict cookies are not passed on
|
|
2174
|
+
const renderRedirect = httpRedirectUrl =>
|
|
2175
|
+
h.view(
|
|
2176
|
+
'redirect',
|
|
2177
|
+
{
|
|
2178
|
+
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
2179
|
+
httpRedirectUrl
|
|
2180
|
+
},
|
|
2181
|
+
{
|
|
2182
|
+
layout: 'public'
|
|
2183
|
+
}
|
|
2184
|
+
);
|
|
2185
|
+
|
|
2186
|
+
// Hands the user back to the provider after a failure they can correct themselves, as a fresh
|
|
2187
|
+
// single-use setup. The token-bearing oauth2 object is dropped so the retry starts clean, and
|
|
2188
|
+
// _meta rides along so the redirect URL, the expected identity and the form nonce all survive
|
|
2189
|
+
// it - that nonce is claimed only on success, so it is still unspent here.
|
|
2190
|
+
const startOAuthRetry = async (loginHint, prompt) => {
|
|
2191
|
+
const reAuthState = `account:add:${crypto.randomBytes(NONCE_BYTES).toString('base64url')}`;
|
|
2192
|
+
const reAuthAccountData = buildRetrySetup(accountData, requestedSetup, provider, accountMeta);
|
|
2193
|
+
|
|
2194
|
+
await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
|
|
2195
|
+
|
|
2196
|
+
// The address to steer the user towards rides on the authorize URL only - persisting it
|
|
2197
|
+
// would overwrite a shared mailbox with the principal that is signing in to reach it.
|
|
2198
|
+
return oAuth2Client.generateAuthUrl({ state: reAuthState, email: loginHint, prompt });
|
|
2199
|
+
};
|
|
2200
|
+
|
|
2201
|
+
// Addresses the provider itself returned over a back channel, the only values allowed to
|
|
2202
|
+
// satisfy an expected identity (see lib/account/expected-identity.js). Every provider case
|
|
2203
|
+
// fills this in; one that does not leaves it empty, and an empty list fails the check closed.
|
|
2204
|
+
const providerIdentities = [];
|
|
2205
|
+
|
|
2206
|
+
// The token to revoke if the setup is rejected after the code was already exchanged, set by
|
|
2207
|
+
// each provider case because the token response is scoped to the switch. Prefer the refresh
|
|
2208
|
+
// token: revoking either invalidates the grant, but the access token may already be expired.
|
|
2209
|
+
let grantToken;
|
|
2210
|
+
|
|
2067
2211
|
// `app.provider` is for example "gmail", `provider` is oauth2 app id
|
|
2068
2212
|
switch (oauth2App.provider) {
|
|
2069
2213
|
case 'gmail': {
|
|
@@ -2091,22 +2235,10 @@ const init = async () => {
|
|
|
2091
2235
|
|
|
2092
2236
|
// Best-effort revocation of the partial token
|
|
2093
2237
|
oAuth2Client.revokeToken(r.refresh_token || r.access_token).catch(err => {
|
|
2094
|
-
request.logger.
|
|
2238
|
+
request.logger.warn({ msg: 'Failed to revoke partial OAuth2 token', err });
|
|
2095
2239
|
});
|
|
2096
2240
|
|
|
2097
|
-
const
|
|
2098
|
-
const reAuthState = `account:add:${reAuthNonce}`;
|
|
2099
|
-
const reAuthAccountData = Object.assign({}, accountData, {
|
|
2100
|
-
oauth2: { provider },
|
|
2101
|
-
_meta: accountMeta
|
|
2102
|
-
});
|
|
2103
|
-
|
|
2104
|
-
await redis.set(`${REDIS_PREFIX}${reAuthState}`, JSON.stringify(reAuthAccountData), 'EX', Math.floor(MAX_FORM_TTL / 1000));
|
|
2105
|
-
|
|
2106
|
-
const reAuthUrl = oAuth2Client.generateAuthUrl({
|
|
2107
|
-
state: reAuthState,
|
|
2108
|
-
email: accountData.email
|
|
2109
|
-
});
|
|
2241
|
+
const retryUrl = await startOAuthRetry(accountData.email);
|
|
2110
2242
|
|
|
2111
2243
|
const missingScopesList = missingScopes.map(formatScopeDescription);
|
|
2112
2244
|
|
|
@@ -2115,7 +2247,7 @@ const init = async () => {
|
|
|
2115
2247
|
{
|
|
2116
2248
|
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
2117
2249
|
templateLocale: request.app.locale,
|
|
2118
|
-
|
|
2250
|
+
retryUrl,
|
|
2119
2251
|
missingScopesList
|
|
2120
2252
|
},
|
|
2121
2253
|
{
|
|
@@ -2130,20 +2262,14 @@ const init = async () => {
|
|
|
2130
2262
|
|
|
2131
2263
|
// With OpenID Connect scopes (openid, email, profile), the ID token contains user info
|
|
2132
2264
|
// This works for all account types including send-only accounts
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
|
|
2142
|
-
}
|
|
2143
|
-
} catch (err) {
|
|
2144
|
-
request.logger.error({ msg: 'Failed to decode Gmail ID token', err });
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2265
|
+
const idTokenPayload = decodeJwtPayload(r.id_token);
|
|
2266
|
+
if (r.id_token && !idTokenPayload) {
|
|
2267
|
+
request.logger.warn({ msg: 'Failed to decode Gmail ID token' });
|
|
2268
|
+
}
|
|
2269
|
+
if (idTokenPayload && typeof idTokenPayload.email === 'string' && isEmail(idTokenPayload.email)) {
|
|
2270
|
+
userEmail = idTokenPayload.email;
|
|
2271
|
+
userName = idTokenPayload.name || null;
|
|
2272
|
+
request.logger.info({ msg: 'Extracted user info from ID token', userEmail, userName });
|
|
2147
2273
|
}
|
|
2148
2274
|
|
|
2149
2275
|
// If ID token didn't provide email, fall back to Gmail API profile endpoint
|
|
@@ -2158,13 +2284,13 @@ const init = async () => {
|
|
|
2158
2284
|
|
|
2159
2285
|
if (hasProfileScope) {
|
|
2160
2286
|
try {
|
|
2161
|
-
request.logger.
|
|
2287
|
+
request.logger.debug({ msg: 'Attempting Gmail profile endpoint as fallback' });
|
|
2162
2288
|
profileRes = await oAuth2Client.request(r.access_token, 'https://gmail.googleapis.com/gmail/v1/users/me/profile');
|
|
2163
2289
|
if (profileRes && profileRes.emailAddress) {
|
|
2164
2290
|
userEmail = profileRes.emailAddress;
|
|
2165
2291
|
}
|
|
2166
2292
|
} catch (err) {
|
|
2167
|
-
request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err
|
|
2293
|
+
request.logger.error({ msg: 'Failed to fetch user info from Gmail API', err });
|
|
2168
2294
|
let response = err.oauthRequest && err.oauthRequest.response;
|
|
2169
2295
|
if (response && response.error) {
|
|
2170
2296
|
let message;
|
|
@@ -2188,6 +2314,11 @@ const init = async () => {
|
|
|
2188
2314
|
throw error;
|
|
2189
2315
|
}
|
|
2190
2316
|
|
|
2317
|
+
// Back-channel only: either the id_token from the token endpoint or the Gmail profile
|
|
2318
|
+
// API response, never a value that travelled through the browser.
|
|
2319
|
+
providerIdentities.push(userEmail);
|
|
2320
|
+
grantToken = r.refresh_token || r.access_token;
|
|
2321
|
+
|
|
2191
2322
|
accountData.email = isEmail(userEmail) ? userEmail : accountData.email;
|
|
2192
2323
|
|
|
2193
2324
|
const defaultScopes = (oauth2App.baseScopes && GMAIL_SCOPES[oauth2App.baseScopes]) || GMAIL_SCOPES.imap;
|
|
@@ -2222,43 +2353,31 @@ const init = async () => {
|
|
|
2222
2353
|
throw error;
|
|
2223
2354
|
}
|
|
2224
2355
|
|
|
2225
|
-
let userInfo
|
|
2356
|
+
let userInfo;
|
|
2226
2357
|
|
|
2227
2358
|
if (!oauth2App.baseScopes || oauth2App.baseScopes === 'imap') {
|
|
2228
|
-
// Read account info from GET
|
|
2229
|
-
//
|
|
2230
|
-
|
|
2231
|
-
|
|
2359
|
+
// Read account info from the id_token, falling back to the client_info GET argument.
|
|
2360
|
+
// The fallback is needed because previously EmailEngine did not request for the
|
|
2361
|
+
// User.Read scope - but client_info arrives through the browser, so it is a display
|
|
2362
|
+
// fallback only and never counts as identity evidence. See lib/oauth/outlook-identity.js.
|
|
2232
2363
|
|
|
2233
|
-
|
|
2234
|
-
|
|
2364
|
+
let clientInfo = false;
|
|
2365
|
+
if (request.query.client_info) {
|
|
2366
|
+
try {
|
|
2367
|
+
clientInfo = JSON.parse(Buffer.from(request.query.client_info, 'base64url').toString());
|
|
2368
|
+
} catch (err) {
|
|
2369
|
+
// Base64-shaped but not JSON. It is an optional display hint, so log and continue
|
|
2370
|
+
// rather than failing the whole setup on a value we do not trust anyway.
|
|
2371
|
+
request.logger.warn({ msg: 'Failed to decode Outlook client_info argument', err });
|
|
2372
|
+
}
|
|
2235
2373
|
}
|
|
2236
2374
|
|
|
2237
|
-
|
|
2238
|
-
|
|
2375
|
+
const idTokenPayload = decodeJwtPayload(r.id_token);
|
|
2376
|
+
if (r.id_token && !idTokenPayload) {
|
|
2377
|
+
request.logger.warn({ msg: 'Failed to decode Outlook ID token' });
|
|
2239
2378
|
}
|
|
2240
2379
|
|
|
2241
|
-
|
|
2242
|
-
let [, encodedValue] = r.id_token.split('.');
|
|
2243
|
-
if (encodedValue) {
|
|
2244
|
-
try {
|
|
2245
|
-
let decodedValue = JSON.parse(Buffer.from(encodedValue, 'base64url').toString());
|
|
2246
|
-
if (decodedValue && typeof decodedValue.name === 'string') {
|
|
2247
|
-
userInfo.name = decodedValue.name;
|
|
2248
|
-
}
|
|
2249
|
-
|
|
2250
|
-
if (decodedValue && typeof decodedValue.email === 'string' && isEmail(decodedValue.email)) {
|
|
2251
|
-
userInfo.email = decodedValue.email;
|
|
2252
|
-
}
|
|
2253
|
-
|
|
2254
|
-
if (decodedValue && typeof decodedValue.preferred_username === 'string' && isEmail(decodedValue.preferred_username)) {
|
|
2255
|
-
userInfo.username = decodedValue.preferred_username;
|
|
2256
|
-
}
|
|
2257
|
-
} catch (err) {
|
|
2258
|
-
request.logger.error({ msg: 'Failed to decode JWT payload', err, encodedValue });
|
|
2259
|
-
}
|
|
2260
|
-
}
|
|
2261
|
-
}
|
|
2380
|
+
userInfo = resolveOutlookUserInfo({ clientInfo, idTokenPayload });
|
|
2262
2381
|
} else {
|
|
2263
2382
|
// Request profile info from API
|
|
2264
2383
|
|
|
@@ -2275,28 +2394,13 @@ const init = async () => {
|
|
|
2275
2394
|
throw err;
|
|
2276
2395
|
}
|
|
2277
2396
|
|
|
2397
|
+
userInfo = resolveOutlookUserInfo({ profile: profileRes });
|
|
2398
|
+
|
|
2278
2399
|
request.logger.info({
|
|
2279
2400
|
msg: 'User profile returned by MS Graph API',
|
|
2280
2401
|
user: userInfo.email,
|
|
2281
|
-
provider: oauth2App.provider
|
|
2282
|
-
profile: profileRes
|
|
2402
|
+
provider: oauth2App.provider
|
|
2283
2403
|
});
|
|
2284
|
-
|
|
2285
|
-
if (profileRes.displayName) {
|
|
2286
|
-
userInfo.name = profileRes.displayName;
|
|
2287
|
-
}
|
|
2288
|
-
|
|
2289
|
-
if (profileRes.mail) {
|
|
2290
|
-
userInfo.email = profileRes.mail;
|
|
2291
|
-
}
|
|
2292
|
-
|
|
2293
|
-
if (profileRes.userPrincipalName) {
|
|
2294
|
-
userInfo.username = profileRes.userPrincipalName;
|
|
2295
|
-
}
|
|
2296
|
-
}
|
|
2297
|
-
|
|
2298
|
-
if (!userInfo.email && userInfo.username && isEmail(userInfo.username)) {
|
|
2299
|
-
userInfo.email = userInfo.username;
|
|
2300
2404
|
}
|
|
2301
2405
|
|
|
2302
2406
|
const authData = {
|
|
@@ -2308,6 +2412,10 @@ const init = async () => {
|
|
|
2308
2412
|
throw error;
|
|
2309
2413
|
}
|
|
2310
2414
|
|
|
2415
|
+
// Only the back-channel addresses, so a forged client_info cannot satisfy an expectation.
|
|
2416
|
+
providerIdentities.push(...userInfo.verifiedIdentities);
|
|
2417
|
+
grantToken = r.refresh_token || r.access_token;
|
|
2418
|
+
|
|
2311
2419
|
if (accountData.oauth2 && accountData.oauth2.auth && accountData.oauth2.auth.delegatedUser) {
|
|
2312
2420
|
// Delegated user (shared mailbox) specified in oauth2.auth.delegatedUser
|
|
2313
2421
|
authData.delegatedUser = accountData.oauth2.auth.delegatedUser;
|
|
@@ -2369,6 +2477,10 @@ const init = async () => {
|
|
|
2369
2477
|
throw error;
|
|
2370
2478
|
}
|
|
2371
2479
|
|
|
2480
|
+
// Back-channel only: the Mail.ru userinfo endpoint response.
|
|
2481
|
+
providerIdentities.push(profileRes.email);
|
|
2482
|
+
grantToken = r.refresh_token || r.access_token;
|
|
2483
|
+
|
|
2372
2484
|
accountData.name = accountData.name || profileRes.name || '';
|
|
2373
2485
|
accountData.email = isEmail(profileRes.email) ? profileRes.email : accountData.email;
|
|
2374
2486
|
|
|
@@ -2398,6 +2510,61 @@ const init = async () => {
|
|
|
2398
2510
|
}
|
|
2399
2511
|
}
|
|
2400
2512
|
|
|
2513
|
+
// Expected identity check. Runs before the nonce claim and before create(), so a rejected
|
|
2514
|
+
// setup neither consumes the signed link nor overwrites the credentials already on the
|
|
2515
|
+
// account. The expectation can come from the signed form blob or from the account itself -
|
|
2516
|
+
// persisting it is what makes the constraint outlive the link that introduced it, and it is
|
|
2517
|
+
// why a later link issued without expectedEmail cannot quietly drop the pin.
|
|
2518
|
+
const expectedEmail = await resolveExpectedIdentity(redis, {
|
|
2519
|
+
account: accountData.account,
|
|
2520
|
+
blobExpectation: pendingSetupExpectation(accountData, accountMeta)
|
|
2521
|
+
});
|
|
2522
|
+
|
|
2523
|
+
if (expectedEmail && !matchesExpectedIdentity(expectedEmail, providerIdentities)) {
|
|
2524
|
+
// Neither address is logged: the expectation and the authenticated identity both belong to
|
|
2525
|
+
// the end user, and this line is the one record of a failed attempt. Note the provider
|
|
2526
|
+
// identity was already logged by the "Provisioned OAuth2 tokens" line above.
|
|
2527
|
+
request.logger.warn({
|
|
2528
|
+
msg: 'OAuth2 identity did not match the expected email address',
|
|
2529
|
+
account: accountData.account,
|
|
2530
|
+
provider: oauth2App.provider
|
|
2531
|
+
});
|
|
2532
|
+
|
|
2533
|
+
// The code was already exchanged, so we are holding a refresh token we will never use.
|
|
2534
|
+
// Best effort, and the same duck-typing guard Account.delete({ revoke }) uses: only
|
|
2535
|
+
// GmailOauth implements revokeToken, and a rejected setup must not become a 500.
|
|
2536
|
+
if (grantToken && typeof oAuth2Client.revokeToken === 'function') {
|
|
2537
|
+
try {
|
|
2538
|
+
await oAuth2Client.revokeToken(grantToken);
|
|
2539
|
+
} catch (err) {
|
|
2540
|
+
request.logger.warn({ msg: 'Failed to revoke the OAuth2 grant after an identity mismatch', err });
|
|
2541
|
+
}
|
|
2542
|
+
}
|
|
2543
|
+
|
|
2544
|
+
// Stop here with a way back rather than redirecting to the calling application: signing in
|
|
2545
|
+
// as the wrong account is a correctable mistake, and the hosted flow only ever redirects on
|
|
2546
|
+
// success. Hint the address they were supposed to use, and force the account picker:
|
|
2547
|
+
// they are already signed in to the one that just failed, so without select_account Google
|
|
2548
|
+
// would hand back the same account and the retry would loop. Microsoft always shows the
|
|
2549
|
+
// picker and Mail.ru ignores the hint, so this only changes Google's behavior.
|
|
2550
|
+
const retryUrl = await startOAuthRetry(expectedEmail, 'select_account consent');
|
|
2551
|
+
|
|
2552
|
+
return identityErrorView(request, h, {
|
|
2553
|
+
expectedEmail,
|
|
2554
|
+
// The primary address the provider reported. Microsoft can return both a mailbox
|
|
2555
|
+
// address and a user principal name, and either would have satisfied the pin, so
|
|
2556
|
+
// naming the first is enough to show which account actually signed in.
|
|
2557
|
+
actualEmail: providerIdentities[0],
|
|
2558
|
+
retryUrl
|
|
2559
|
+
});
|
|
2560
|
+
}
|
|
2561
|
+
|
|
2562
|
+
if (expectedEmail) {
|
|
2563
|
+
// Pin the account so every later setup is checked, including one driven by a link that
|
|
2564
|
+
// carries no expectation of its own.
|
|
2565
|
+
accountData.expectedEmail = expectedEmail;
|
|
2566
|
+
}
|
|
2567
|
+
|
|
2401
2568
|
if ('delegated' in accountData) {
|
|
2402
2569
|
// remove artefacts
|
|
2403
2570
|
delete accountData.delegated;
|
|
@@ -2463,17 +2630,7 @@ const init = async () => {
|
|
|
2463
2630
|
httpRedirectUrl = `/admin/accounts/${result.account}`;
|
|
2464
2631
|
}
|
|
2465
2632
|
|
|
2466
|
-
|
|
2467
|
-
return h.view(
|
|
2468
|
-
'redirect',
|
|
2469
|
-
{
|
|
2470
|
-
pageTitleFull: request.app.gt.gettext('Email Account Setup'),
|
|
2471
|
-
httpRedirectUrl
|
|
2472
|
-
},
|
|
2473
|
-
{
|
|
2474
|
-
layout: 'public'
|
|
2475
|
-
}
|
|
2476
|
-
);
|
|
2633
|
+
return renderRedirect(httpRedirectUrl);
|
|
2477
2634
|
},
|
|
2478
2635
|
options: {
|
|
2479
2636
|
description: 'OAuth2 response endpoint',
|
|
@@ -2504,7 +2661,9 @@ const init = async () => {
|
|
|
2504
2661
|
.description('OAuth2 scopes'),
|
|
2505
2662
|
client_info: Joi.string()
|
|
2506
2663
|
.empty('')
|
|
2507
|
-
.
|
|
2664
|
+
// A few hundred bytes of JSON in practice. Bounded tightly because this is an
|
|
2665
|
+
// unauthenticated route and the value is JSON.parse-d.
|
|
2666
|
+
.max(4 * 1024)
|
|
2508
2667
|
.base64({ urlSafe: true, paddingRequired: false })
|
|
2509
2668
|
.description('Outlook client info'),
|
|
2510
2669
|
error: Joi.string()
|
|
@@ -2878,7 +3037,7 @@ const init = async () => {
|
|
|
2878
3037
|
return h.response(request.errorInfo).code(request.errorInfo.statusCode || 500);
|
|
2879
3038
|
}
|
|
2880
3039
|
|
|
2881
|
-
logger
|
|
3040
|
+
logger[isClientError(error) ? 'debug' : 'error']({ msg: 'Web request failed', path: request.path, method: request.method, err: error });
|
|
2882
3041
|
|
|
2883
3042
|
return h
|
|
2884
3043
|
.view('error', ctx, {
|
|
@@ -3026,7 +3185,7 @@ const init = async () => {
|
|
|
3026
3185
|
await certHandler.acquireCert(serviceDomain);
|
|
3027
3186
|
await call({ cmd: 'smtpReload' });
|
|
3028
3187
|
} catch (err) {
|
|
3029
|
-
logger.error({ err });
|
|
3188
|
+
logger.error({ msg: 'Failed to acquire TLS certificate', serviceDomain, err });
|
|
3030
3189
|
} finally {
|
|
3031
3190
|
try {
|
|
3032
3191
|
await certHandler.setCertificateData(serviceDomain, { lastCheck: new Date() });
|
|
@@ -3044,7 +3203,7 @@ const init = async () => {
|
|
|
3044
3203
|
// dynamic imports first, use a wrapper function or eslint parser will crash
|
|
3045
3204
|
init()
|
|
3046
3205
|
.then(() => {
|
|
3047
|
-
logger.
|
|
3206
|
+
logger.info({
|
|
3048
3207
|
msg: 'Started API server thread',
|
|
3049
3208
|
port: API_PORT,
|
|
3050
3209
|
host: API_HOST,
|
|
@@ -3065,6 +3224,6 @@ init()
|
|
|
3065
3224
|
}, 10 * 1000).unref();
|
|
3066
3225
|
})
|
|
3067
3226
|
.catch(err => {
|
|
3068
|
-
logger.
|
|
3227
|
+
logger.fatal({ msg: 'Failed to initialize API', err });
|
|
3069
3228
|
logger.flush(() => process.exit(3));
|
|
3070
3229
|
});
|