emailengine-app 2.89.0 → 2.91.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.
Files changed (120) hide show
  1. package/.ncurc.js +19 -8
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +73 -0
  4. package/Dockerfile +7 -3
  5. package/ENVIRONMENT.md +24 -23
  6. package/README.md +1 -1
  7. package/bin/healthcheck.js +1 -1
  8. package/copy-static-files.sh +0 -8
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +1 -4
  11. package/lib/account/field-codec.js +396 -0
  12. package/lib/account-assignment.js +26 -9
  13. package/lib/account.js +196 -462
  14. package/lib/api-routes/account-routes.js +49 -6
  15. package/lib/api-routes/route-metadata.js +5 -2
  16. package/lib/api-routes/submit-routes.js +15 -2
  17. package/lib/api-token-auth.js +342 -274
  18. package/lib/arf-detect.js +174 -149
  19. package/lib/attachment-size.js +29 -0
  20. package/lib/autodetect-imap-settings.js +482 -296
  21. package/lib/consts.js +5 -5
  22. package/lib/db.js +1 -4
  23. package/lib/email-client/base-client.js +907 -780
  24. package/lib/email-client/gmail-client.js +557 -450
  25. package/lib/email-client/imap/cid-parts.js +61 -0
  26. package/lib/email-client/imap/mailbox.js +376 -422
  27. package/lib/email-client/imap/sync-operations.js +239 -178
  28. package/lib/email-client/imap-client.js +5 -5
  29. package/lib/email-client/message-builder.js +4 -5
  30. package/lib/email-client/new-message-steps.js +168 -2
  31. package/lib/email-client/outlook/graph-message.js +266 -0
  32. package/lib/email-client/outlook/subscription-expiry.js +30 -0
  33. package/lib/email-client/outlook-client.js +652 -808
  34. package/lib/get-raw-email.js +338 -232
  35. package/lib/get-secret.js +1 -4
  36. package/lib/imapproxy/imap-server.js +5 -5
  37. package/lib/license-subscription.js +60 -0
  38. package/lib/load-env.js +48 -0
  39. package/lib/logger-consts.js +37 -1
  40. package/lib/logger.js +1 -4
  41. package/lib/mail-probe.js +157 -0
  42. package/lib/mcp/tools.js +244 -207
  43. package/lib/metric-values.js +76 -0
  44. package/lib/metrics.js +320 -0
  45. package/lib/oauth/gmail.js +39 -120
  46. package/lib/oauth/http-request.js +195 -0
  47. package/lib/oauth/mail-ru.js +33 -60
  48. package/lib/oauth/outlook.js +37 -137
  49. package/lib/oauth/pubsub/google.js +176 -117
  50. package/lib/oauth2-apps.js +440 -463
  51. package/lib/openapi/build-document.js +10 -10
  52. package/lib/read-env-value.js +31 -7
  53. package/lib/redis-backend-warnings.js +70 -0
  54. package/lib/route-descriptors.js +78 -0
  55. package/lib/schemas.js +10 -1
  56. package/lib/sentry-integrations.js +299 -0
  57. package/lib/sentry.js +75 -27
  58. package/lib/sso-routes.js +249 -0
  59. package/lib/sso.js +29 -6
  60. package/lib/tools.js +17 -28
  61. package/lib/ui-routes/account-edit-form.js +198 -0
  62. package/lib/ui-routes/account-page.js +241 -0
  63. package/lib/ui-routes/account-routes.js +46 -349
  64. package/lib/ui-routes/account-setup.js +1 -1
  65. package/lib/ui-routes/auth-routes.js +10 -10
  66. package/lib/ui-routes/provider-signin.js +187 -0
  67. package/lib/ui-routes/route-helpers.js +1 -1
  68. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  69. package/lib/ui-view-context.js +328 -0
  70. package/lib/utils/public-suffix.js +22 -101
  71. package/lib/web-safe-html.js +20 -7
  72. package/lib/worker-metrics.js +82 -0
  73. package/list-generate.js +2 -5
  74. package/package.json +28 -24
  75. package/sbom.json +360 -1030
  76. package/scripts/refresh-test-tokens.js +1 -1
  77. package/server.js +400 -677
  78. package/static/css/flyonui.css +1 -1
  79. package/static/css/public.css +55 -1
  80. package/static/css/src/app.tailwind.css +18 -0
  81. package/static/js/ee-client.js +2619 -645
  82. package/static/js/ui.js +12 -2
  83. package/static/licenses.html +224 -764
  84. package/translations/de.mo +0 -0
  85. package/translations/de.po +429 -390
  86. package/translations/en.mo +0 -0
  87. package/translations/en.po +342 -257
  88. package/translations/es.mo +0 -0
  89. package/translations/es.po +440 -395
  90. package/translations/et.mo +0 -0
  91. package/translations/et.po +425 -375
  92. package/translations/fr.mo +0 -0
  93. package/translations/fr.po +425 -383
  94. package/translations/it.mo +0 -0
  95. package/translations/it.po +441 -394
  96. package/translations/ja.mo +0 -0
  97. package/translations/ja.po +408 -335
  98. package/translations/messages.pot +188 -130
  99. package/translations/nl.mo +0 -0
  100. package/translations/nl.po +419 -382
  101. package/translations/pl.mo +0 -0
  102. package/translations/pl.po +425 -379
  103. package/translations/sv.mo +0 -0
  104. package/translations/sv.po +440 -388
  105. package/translations/tr.mo +0 -0
  106. package/translations/tr.po +441 -387
  107. package/views/account-identity-error.hbs +1 -1
  108. package/views/account-workspace-error.hbs +2 -2
  109. package/views/accounts/browse.hbs +19 -1
  110. package/views/accounts/register/imap-server.hbs +22 -7
  111. package/views/accounts/register/imap.hbs +3 -0
  112. package/views/accounts/register/index.hbs +1 -27
  113. package/views/accounts/register/provider-signin.hbs +58 -0
  114. package/views/oauth-scope-error.hbs +1 -1
  115. package/views/partials/provider_signin_button.hbs +30 -0
  116. package/views/queues/index.hbs +1 -1
  117. package/views/redirect.hbs +1 -1
  118. package/views/unsubscribe.hbs +6 -6
  119. package/workers/api.js +20 -451
  120. package/data/public_suffix_list.dat +0 -16698
@@ -0,0 +1,187 @@
1
+ 'use strict';
2
+
3
+ // The hosted setup form's answer to autodiscovery recognizing a Gmail or Microsoft mailbox on the
4
+ // IMAP path: which OAuth2 applications can sign that mailbox in instead of a password, and the page
5
+ // that offers them.
6
+
7
+ const { oauth2Apps, oauth2ProviderData } = require('../oauth2-apps');
8
+ const { autodetectImapSettings, isConsumerMailbox } = require('../autodetect-imap-settings');
9
+
10
+ // Outlook application authorities that can sign in a personal (Outlook.com) account. A tenant id
11
+ // or `organizations` signs in work accounts only, `consumers` personal ones only.
12
+ const CONSUMER_AUTHORITIES = new Set(['common', 'consumers']);
13
+
14
+ // What autodiscovery found for an address, kept while the sign-in page is open so that choosing
15
+ // "Continue with IMAP" there does not run the whole lookup again. Keyed by the setup link's nonce
16
+ // and the address, so one link's answer never reaches another link. Bounded and short-lived: a
17
+ // cosmetic shortcut, and a miss simply runs the lookup.
18
+ const DISCOVERY_CACHE = new Map();
19
+ const DISCOVERY_CACHE_TTL = 10 * 60 * 1000;
20
+ const DISCOVERY_CACHE_MAX_ENTRIES = 1000;
21
+
22
+ const discoveryKey = (nonce, email) => (nonce ? `${nonce}:${String(email).trim().toLowerCase()}` : null);
23
+
24
+ function rememberDiscovery(key, serverSettings) {
25
+ if (!key) {
26
+ return;
27
+ }
28
+ DISCOVERY_CACHE.delete(key);
29
+ if (DISCOVERY_CACHE.size >= DISCOVERY_CACHE_MAX_ENTRIES) {
30
+ DISCOVERY_CACHE.delete(DISCOVERY_CACHE.keys().next().value);
31
+ }
32
+ DISCOVERY_CACHE.set(key, { serverSettings, expires: Date.now() + DISCOVERY_CACHE_TTL });
33
+ }
34
+
35
+ function recallDiscovery(key) {
36
+ const entry = key && DISCOVERY_CACHE.get(key);
37
+ if (!entry) {
38
+ return null;
39
+ }
40
+ DISCOVERY_CACHE.delete(key);
41
+ return entry.expires > Date.now() ? entry.serverSettings : null;
42
+ }
43
+
44
+ /**
45
+ * Discovers the server settings for the address the visitor typed. A visitor coming back from the
46
+ * sign-in page reuses what was found a moment ago for the same link instead of a second lookup.
47
+ *
48
+ * The password is passed along because hosted Exchange refuses to answer autodiscovery
49
+ * anonymously; it only ever reaches the autodiscovery host named by the address domain's own DNS,
50
+ * and only after that host has asked for it.
51
+ *
52
+ * @param {Object} request - The POST /accounts/new/imap request
53
+ * @param {Object} data - Its parsed signed blob
54
+ * @returns {Promise<Object|undefined>} The autodiscovery result, undefined when nothing was found
55
+ */
56
+ async function discoverServerSettings(request, data) {
57
+ const { email, password, skipSignIn } = request.payload;
58
+ const cached = skipSignIn ? recallDiscovery(discoveryKey(data.n, email)) : null;
59
+ if (cached) {
60
+ return cached;
61
+ }
62
+ try {
63
+ return await autodetectImapSettings(email, request.app.gt, { user: email, pass: password });
64
+ } catch (err) {
65
+ request.logger.debug({ msg: 'Failed to resolve email server settings', email, err });
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Whether an Outlook application can sign in the mailbox. A personal address needs an application
71
+ * open to personal accounts; an organization's address needs one that is not limited to them. An
72
+ * application pinned to one tenant stays in for any organization, since DNS does not say which
73
+ * tenant a domain belongs to.
74
+ */
75
+ function outlookAuthorityFits(app, consumer) {
76
+ const authority = String(app.authority || 'common').toLowerCase();
77
+ return consumer ? CONSUMER_AUTHORITIES.has(authority) : authority !== 'consumers';
78
+ }
79
+
80
+ /**
81
+ * The OAuth2 applications the hosted setup form may show at all, as the provider picker lists them:
82
+ * listed (which is enabled), each with the button data its sign-in button renders from. The sign-in
83
+ * page on the IMAP path narrows this same list, so the two pages cannot disagree about what is
84
+ * offered.
85
+ *
86
+ * @returns {Promise<Object[]>}
87
+ */
88
+ async function listListedApps() {
89
+ return (await oauth2Apps.list(0, 100)).apps
90
+ .filter(app => app.includeInListing)
91
+ .map(app => Object.assign({}, app, { providerData: oauth2ProviderData(app.provider, app.cloud) }));
92
+ }
93
+
94
+ /**
95
+ * The applications to offer for a mailbox autodiscovery identified as `provider`, out of the
96
+ * listed ones (see listListedApps()), in the picker's order: interactive (no Pub/Sub), and for
97
+ * Outlook able to sign in this kind of account.
98
+ *
99
+ * When more than one is offered, each needs a name the visitor can tell apart, so an application
100
+ * without a display title shows its name instead. A single one keeps the picker's look: no title.
101
+ *
102
+ * @param {Object[]} apps - Applications as listListedApps() returns them
103
+ * @param {string} provider - `gmail` or `outlook`, from the autodiscovery result
104
+ * @param {string} email - The address being set up
105
+ * @returns {Object[]} The applications to offer, each with `providerData` and `displayTitle`
106
+ */
107
+ function pickSignInApps(apps, provider, email) {
108
+ const consumer = isConsumerMailbox(email);
109
+ const picked = (apps || []).filter(
110
+ app => app && app.provider === provider && app.baseScopes !== 'pubsub' && (provider !== 'outlook' || outlookAuthorityFits(app, consumer))
111
+ );
112
+
113
+ return picked.map(app => Object.assign({}, app, { displayTitle: app.title || (picked.length > 1 ? app.name : null) }));
114
+ }
115
+
116
+ /**
117
+ * Lists the applications to offer, see pickSignInApps().
118
+ *
119
+ * @returns {Promise<Object[]>}
120
+ */
121
+ async function listSignInApps(provider, email) {
122
+ if (!provider) {
123
+ return [];
124
+ }
125
+ return pickSignInApps(await listListedApps(), provider, email);
126
+ }
127
+
128
+ /**
129
+ * Shown on the IMAP path when autodiscovery recognized a Gmail or Microsoft mailbox and an OAuth2
130
+ * application can sign it in: the visitor picked "Standard IMAP" for a mailbox that signs in better
131
+ * (for Microsoft, only) through the provider.
132
+ *
133
+ * @param {Object} request - The POST /accounts/new/imap request
134
+ * @param {Object} h - Response toolkit
135
+ * @param {Object} [serverSettings] - Autodiscovery result
136
+ * @param {Object} values - The page's form values (name, email, password, data, sig)
137
+ * @param {string} [nonce] - The setup link's nonce, to remember the discovery under
138
+ * @returns {Promise<Object>} `{ response }` to render the page, or `{ apps }` (the applications
139
+ * looked at, possibly none) to go on with the IMAP flow: the visitor chose IMAP already (or the
140
+ * link was minted for it), or no application fits
141
+ */
142
+ async function renderProviderSignIn(request, h, serverSettings, values, nonce) {
143
+ const provider = serverSettings && serverSettings.provider;
144
+ if (!provider || request.payload.skipSignIn) {
145
+ return { apps: null };
146
+ }
147
+
148
+ const apps = await listSignInApps(provider, values.email);
149
+ if (!apps.length) {
150
+ // The operator is the one who can fix this, and nothing else tells them it happens
151
+ request.logger.info({ msg: 'No OAuth2 application can sign in this mailbox, continuing with IMAP', provider, domain: values.email.split('@').pop() });
152
+ return { apps };
153
+ }
154
+
155
+ rememberDiscovery(discoveryKey(nonce, values.email), serverSettings);
156
+
157
+ const response = h.view(
158
+ 'accounts/register/provider-signin',
159
+ {
160
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
161
+ isMicrosoft: provider === 'outlook',
162
+ apps,
163
+ values: { name: values.name, email: values.email, password: values.password, data: values.data, sig: values.sig }
164
+ },
165
+ { layout: 'public' }
166
+ );
167
+ return { response };
168
+ }
169
+
170
+ /**
171
+ * The notice the server settings form opens with for a Microsoft mailbox, which will not accept the
172
+ * password over IMAP. Read off the app-password hint the form already carries for such a mailbox
173
+ * (server-derived, see applyAppPasswordHint), so every render of the form agrees.
174
+ *
175
+ * @param {Object} values - Settings form values
176
+ * @param {Object[]} [knownApps] - Outlook applications already looked up for this request
177
+ * @returns {Promise<Object|null>} `{ noApp }`, or null when the mailbox is not a Microsoft one
178
+ */
179
+ async function microsoftSignInNotice(values, knownApps) {
180
+ if (!values || values.appPassword_provider !== 'Microsoft' || !values.email) {
181
+ return null;
182
+ }
183
+ const apps = knownApps || (await listSignInApps('outlook', values.email).catch(() => []));
184
+ return { noApp: !apps.length };
185
+ }
186
+
187
+ module.exports = { listListedApps, pickSignInApps, listSignInApps, renderProviderSignIn, microsoftSignInNotice, discoverServerSettings };
@@ -123,7 +123,7 @@ function accountStateLabel(state, opts, gt) {
123
123
  if (lastErrorState) {
124
124
  switch (lastErrorState.serverResponseCode) {
125
125
  case 'ETIMEDOUT':
126
- errorMessage = gt.gettext('Connection timed out. This usually occurs if you are behind a firewall or connecting to the wrong port.');
126
+ errorMessage = gt.gettext('Connection timed out. A firewall may be blocking the connection, or the port may be incorrect.');
127
127
  break;
128
128
  case 'ClosedAfterConnectTLS':
129
129
  case 'ClosedAfterConnectText':
@@ -186,7 +186,7 @@ function init(args) {
186
186
  }
187
187
  );
188
188
  } catch (err) {
189
- await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process request. Try again.") });
189
+ await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process your request. Try again.") });
190
190
  // Boom 4xx (bad signature, unknown account) is client-caused traffic on a public
191
191
  // endpoint, not a server failure
192
192
  request.logger[isClientError(err) ? 'debug' : 'error']({ msg: 'Failed to process subscription request', err });
@@ -235,7 +235,7 @@ function init(args) {
235
235
  });
236
236
  }
237
237
 
238
- await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process request. Try again.") });
238
+ await request.flash({ type: 'danger', message: request.app.gt.gettext("Couldn't process your request. Try again.") });
239
239
  request.logger.debug({ msg: 'Failed to process subscription request', err });
240
240
 
241
241
  return h
@@ -0,0 +1,328 @@
1
+ 'use strict';
2
+
3
+ // The view context every server-rendered page receives (the `context` option of server.views() in
4
+ // workers/api.js). Moved out of the API worker, which a test cannot load, so the context and the
5
+ // system alerts it carries are tested directly.
6
+
7
+ const logger = require('./logger');
8
+ const settings = require('./settings');
9
+ const packageData = require('../package.json');
10
+ const { redis } = require('./db');
11
+ const { oauth2Apps } = require('./oauth2-apps');
12
+ const { isSuspended } = require('./license-subscription');
13
+ const { flash, hasEnvValue, readEnvValue, getBoolean } = require('./tools');
14
+ const { LAST_DOCUMENT_STORE_VERSION } = require('./consts');
15
+
16
+ const DAY_MS = 24 * 3600 * 1000;
17
+
18
+ // The settings the context reads on every render
19
+ const CONTEXT_SETTINGS = [
20
+ 'upgrade',
21
+ 'webhookErrorFlag',
22
+ 'webhooksEnabled',
23
+ 'disableTokens',
24
+ 'tract',
25
+ 'templateHeader',
26
+ 'templateHtmlHead',
27
+ 'documentStoreEnabled',
28
+ 'serviceUrl',
29
+ 'language',
30
+ 'locale',
31
+ 'timezone',
32
+ 'pageBrandName',
33
+ 'notificationBaseUrl'
34
+ ];
35
+
36
+ // How a single sign-on session's profile is shown as the signed-in user. SSO users never manage
37
+ // the local password, hence isAdmin: false
38
+ const SSO_AUTH_DISPLAY = {
39
+ okta: profile => ({
40
+ user: profile.username,
41
+ name:
42
+ []
43
+ .concat(profile.firstName || [])
44
+ .concat(profile.lastName || [])
45
+ .join(' ') || profile.username,
46
+ enabled: !!profile.username,
47
+ isAdmin: false
48
+ }),
49
+ oidc: profile => ({
50
+ user: profile.username,
51
+ name: profile.displayName || profile.username,
52
+ enabled: !!profile.username,
53
+ isAdmin: false
54
+ })
55
+ };
56
+
57
+ /**
58
+ * The signed-in user as the page header shows it: the SSO profile for an SSO session, otherwise
59
+ * the local admin account, or a disabled placeholder when no admin password is set.
60
+ *
61
+ * @param {Object} [artifacts] - request.auth.artifacts
62
+ * @returns {Promise<Object>} `{ user, name, enabled, isAdmin }`
63
+ */
64
+ async function resolveAuthDisplay(artifacts) {
65
+ let provider = artifacts && artifacts.provider;
66
+ if (provider && Object.hasOwn(SSO_AUTH_DISPLAY, provider)) {
67
+ return SSO_AUTH_DISPLAY[provider](artifacts.profile || {});
68
+ }
69
+
70
+ let authData = await settings.get('authData');
71
+ if (authData) {
72
+ authData.name = authData.user;
73
+ authData.enabled = true;
74
+ authData.isAdmin = true;
75
+ return authData;
76
+ }
77
+
78
+ return {
79
+ name: 'admin',
80
+ user: 'admin',
81
+ enabled: false,
82
+ isAdmin: true
83
+ };
84
+ }
85
+
86
+ /**
87
+ * The license details shown on the page, with the whole days left until a set expiry.
88
+ *
89
+ * @param {Object} [licenseInfo] - request.app.licenseInfo
90
+ * @param {number} now - current time in milliseconds
91
+ * @returns {Object} a copy of the details, plus `expiresDays` when they carry an expiry
92
+ */
93
+ function licenseDetailsView(licenseInfo, now) {
94
+ let licenseDetails = Object.assign({}, (licenseInfo && licenseInfo.details) || {});
95
+
96
+ if (licenseDetails.expires) {
97
+ let delayMs = new Date(licenseDetails.expires) - now;
98
+ licenseDetails.expiresDays = Math.max(Math.ceil(delayMs / DAY_MS), 0);
99
+ }
100
+
101
+ return licenseDetails;
102
+ }
103
+
104
+ const plural = count => (count !== 1 ? 's' : '');
105
+
106
+ // The banners above every admin page, in display order. Each rule returns an alert, a list of
107
+ // them, or nothing
108
+ const ALERT_RULES = [
109
+ ({ settingsValues }) => {
110
+ let upgradeInfo = settingsValues.upgrade;
111
+ if (upgradeInfo && upgradeInfo.canUpgrade) {
112
+ return {
113
+ url: '/admin/upgrade',
114
+ level: 'info',
115
+ icon: 'icon-[tabler--alert-triangle]',
116
+ message: `An update is available: Emailengine v${upgradeInfo.available}`
117
+ };
118
+ }
119
+ },
120
+
121
+ // The subscription behind the license (lib/license-subscription.js): paused, or a date it pauses on
122
+ ({ licenseInfo }) => {
123
+ if (isSuspended(licenseInfo)) {
124
+ return {
125
+ url: '/admin/config/license',
126
+ level: 'danger',
127
+ icon: 'icon-[tabler--player-pause]',
128
+ message: 'EmailEngine is paused: the subscription behind the license key is not in good standing'
129
+ };
130
+ }
131
+ let licenseSubscription = licenseInfo && licenseInfo.subscription;
132
+ if (licenseSubscription) {
133
+ return {
134
+ url: '/admin/config/license',
135
+ level: 'danger',
136
+ icon: 'icon-[tabler--alert-triangle]',
137
+ message: `Subscription payment overdue: EmailEngine pauses in ${licenseSubscription.days} day${plural(licenseSubscription.days)} unless it is paid`
138
+ };
139
+ }
140
+ },
141
+
142
+ // OAuth2 apps whose token requests are being refused (setFlag() writes the failure
143
+ // into app meta). Shown on every admin page: the accounts on such an app sit
144
+ // disconnected until the operator acts, so the OAuth config page alone is not enough.
145
+ ({ oauthAuthFlags }) =>
146
+ oauthAuthFlags.map(({ app, authFlag }) => ({
147
+ url: authFlag.url || `/admin/config/oauth/app/${encodeURIComponent(app)}`,
148
+ level: 'danger',
149
+ icon: 'icon-[tabler--lock-open]',
150
+ message: authFlag.message
151
+ })),
152
+
153
+ ({ settingsValues }) => {
154
+ let webhookErrorFlag = settingsValues.webhookErrorFlag;
155
+ if (settingsValues.webhooksEnabled && webhookErrorFlag && webhookErrorFlag.message) {
156
+ return {
157
+ url: '/admin/config/webhooks',
158
+ level: 'danger',
159
+ icon: 'icon-[tabler--link]',
160
+ message: 'Webhook delivery is failing'
161
+ };
162
+ }
163
+ },
164
+
165
+ // a paused license is still registered, and the alert above says why it is not active
166
+ ({ licenseInfo }) => {
167
+ if (!licenseInfo || (!licenseInfo.active && !licenseInfo.details)) {
168
+ return {
169
+ url: '/admin/config/license',
170
+ level: 'warning',
171
+ icon: 'icon-[tabler--key]',
172
+ message: 'No license key registered'
173
+ };
174
+ }
175
+ },
176
+
177
+ ({ licenseDetails }) => {
178
+ if (licenseDetails.expires && licenseDetails.expiresDays < 31) {
179
+ return {
180
+ url: '/admin/config/license',
181
+ level: 'warning',
182
+ icon: 'icon-[tabler--key]',
183
+ message: `Your ${licenseDetails.trial ? `trial ` : ''}license key will expire in ${licenseDetails.expiresDays} day${plural(
184
+ licenseDetails.expiresDays
185
+ )}`
186
+ };
187
+ }
188
+ },
189
+
190
+ ({ settingsValues }) => {
191
+ if (settingsValues.disableTokens) {
192
+ return {
193
+ url: '/admin/config/security',
194
+ level: 'warning',
195
+ icon: 'icon-[tabler--key]',
196
+ message: `Access tokens are disabled for API requests`
197
+ };
198
+ }
199
+ },
200
+
201
+ // The Document Store was removed in 2.82.0. The setting that switched it on is read raw off
202
+ // the settings hash (it is no longer in the settings schema), so an instance upgraded with the
203
+ // feature still on is told where it went instead of losing it quietly
204
+ ({ settingsValues }) => {
205
+ if (settingsValues.documentStoreEnabled) {
206
+ return {
207
+ url: '/admin',
208
+ level: 'danger',
209
+ icon: 'icon-[tabler--database]',
210
+ message: `The Document Store has been removed from EmailEngine. Downgrade to v${LAST_DOCUMENT_STORE_VERSION} if you still need it.`
211
+ };
212
+ }
213
+ }
214
+ ];
215
+
216
+ /**
217
+ * The banners shown above every admin page.
218
+ *
219
+ * @param {Object} state
220
+ * @param {Object} state.settingsValues - the CONTEXT_SETTINGS values
221
+ * @param {Object} [state.licenseInfo] - request.app.licenseInfo
222
+ * @param {Object} state.licenseDetails - licenseDetailsView() output
223
+ * @param {Array} state.oauthAuthFlags - `{ app, authFlag }` per OAuth2 app whose token requests fail
224
+ * @param {boolean} state.disableSetupWarnings - keep only the danger level alerts
225
+ * @returns {Array<Object>} `{ url, level, icon, message }` per alert, in display order
226
+ */
227
+ function buildSystemAlerts(state) {
228
+ let systemAlerts = ALERT_RULES.flatMap(rule => [].concat(rule(state) || []));
229
+
230
+ if (state.disableSetupWarnings) {
231
+ // Keep only critical (danger) alerts, suppress info/warning level
232
+ systemAlerts = systemAlerts.filter(alert => alert.level === 'danger');
233
+ }
234
+
235
+ return systemAlerts;
236
+ }
237
+
238
+ /**
239
+ * The view context of a rendered page.
240
+ *
241
+ * @param {Object} request - the hapi request being rendered
242
+ * @returns {Promise<Object>}
243
+ */
244
+ async function buildViewContext(request) {
245
+ // The three reads are independent, and this runs on every admin page render. The
246
+ // OAuth2 auth flags are best-effort - a failure to read them must not take the page
247
+ // down with it.
248
+ const [pendingMessages, settingsValues, oauthAuthFlags] = await Promise.all([
249
+ flash(redis, request),
250
+ settings.getMulti(...CONTEXT_SETTINGS),
251
+ oauth2Apps.listAuthFlags().catch(err => {
252
+ logger.error({ msg: 'Failed to list OAuth2 app auth flags', err });
253
+ return [];
254
+ })
255
+ ]);
256
+
257
+ const {
258
+ tract,
259
+ templateHeader: embeddedTemplateHeader,
260
+ templateHtmlHead: embeddedTemplateHtmlHead,
261
+ documentStoreEnabled: documentStoreRemoved,
262
+ serviceUrl,
263
+ language,
264
+ locale,
265
+ timezone,
266
+ pageBrandName,
267
+ notificationBaseUrl
268
+ } = settingsValues;
269
+
270
+ let authData = await resolveAuthDisplay(request.auth.artifacts);
271
+
272
+ let licenseDetails = licenseDetailsView(request.app.licenseInfo, Date.now());
273
+
274
+ // Check if setup warnings should be disabled (for documentation screenshots, CI, etc.)
275
+ const disableSetupWarnings = hasEnvValue('EENGINE_DISABLE_SETUP_WARNINGS') ? getBoolean(readEnvValue('EENGINE_DISABLE_SETUP_WARNINGS')) : false;
276
+
277
+ let systemAlerts = buildSystemAlerts({
278
+ settingsValues,
279
+ licenseInfo: request.app.licenseInfo,
280
+ licenseDetails,
281
+ oauthAuthFlags,
282
+ disableSetupWarnings
283
+ });
284
+
285
+ // Whether the requester holds a session at all, so a public page (the hosted form's
286
+ // error page, for one) can tell a mailbox owner from an admin without reading
287
+ // authData, which describes the instance rather than the requester
288
+ const isAuthenticated = !!(request.auth && request.auth.isAuthenticated);
289
+
290
+ return {
291
+ // the per-request CSP nonce every inline <script> carries (lib/security-headers.js)
292
+ cspNonce: request.app.cspNonce,
293
+ pageBrandName: pageBrandName || 'EmailEngine',
294
+ values: request.payload || {},
295
+ errors: (request.error && request.error.details) || {},
296
+ pendingMessages,
297
+ licenseInfo: request.app.licenseInfo,
298
+ licenseDetails,
299
+ trialPossible: !tract,
300
+ authData,
301
+ isAuthenticated,
302
+ // The dashboard is an admin destination: a link to it belongs on a page only for
303
+ // a requester who holds an admin session, or on an instance with no admin login
304
+ showDashboardLink: isAuthenticated || !(authData && authData.enabled),
305
+ packageData,
306
+ systemAlerts,
307
+ embeddedTemplateHeader,
308
+ embeddedTemplateHtmlHead,
309
+ currentYear: new Date().getFullYear(),
310
+ documentStoreRemoved,
311
+ lastDocumentStoreVersion: LAST_DOCUMENT_STORE_VERSION,
312
+ updateBrowserInfo: !serviceUrl || !language || !timezone,
313
+
314
+ // Suppress large banner warnings when EENGINE_DISABLE_SETUP_WARNINGS is set
315
+ hideLicenseWarning: disableSetupWarnings,
316
+ disableAuthWarning: disableSetupWarnings,
317
+
318
+ mainServiceUrl: serviceUrl,
319
+ notificationBaseUrl,
320
+
321
+ userLocale: locale,
322
+ userTimezone: timezone,
323
+
324
+ templateLocale: request.app.locale
325
+ };
326
+ }
327
+
328
+ module.exports = { buildViewContext, buildSystemAlerts, resolveAuthDisplay, licenseDetailsView, CONTEXT_SETTINGS };