emailengine-app 2.87.1 → 2.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +31 -0
  3. package/ENVIRONMENT.md +26 -23
  4. package/LICENSE_EMAILENGINE.txt +20 -12
  5. package/app.json +3 -3
  6. package/bin/emailengine.js +7 -11
  7. package/data/google-crawlers.json +1 -1
  8. package/data/public_suffix_list.dat +48 -10
  9. package/lib/account.js +69 -49
  10. package/lib/admin-password.js +85 -0
  11. package/lib/api-routes/license-routes.js +9 -0
  12. package/lib/api-token-auth.js +21 -5
  13. package/lib/calendar-event.js +15 -3
  14. package/lib/consts.js +5 -0
  15. package/lib/db.js +1 -0
  16. package/lib/dbsc/index.js +292 -0
  17. package/lib/dbsc/jwt.js +157 -0
  18. package/lib/dbsc/protocol.js +132 -0
  19. package/lib/dbsc/store.js +136 -0
  20. package/lib/email-client/base-client.js +36 -15
  21. package/lib/email-client/gmail-client.js +20 -6
  22. package/lib/email-client/imap/connection-errors.js +30 -1
  23. package/lib/email-client/imap/session-expiry.js +83 -0
  24. package/lib/email-client/imap-client.js +12 -2
  25. package/lib/email-client/smtp-pool-manager.js +66 -8
  26. package/lib/export.js +147 -22
  27. package/lib/graph-notifications.js +60 -0
  28. package/lib/imap-proxy-auth.js +52 -18
  29. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  30. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  31. package/lib/imapproxy/imap-server.js +10 -1
  32. package/lib/imapproxy/proxy-handoff.js +100 -5
  33. package/lib/license-subscription.js +238 -0
  34. package/lib/oauth/gmail.js +18 -0
  35. package/lib/oauth/outlook-identity.js +54 -12
  36. package/lib/prepared-password.js +38 -0
  37. package/lib/privileged-settings.js +6 -0
  38. package/lib/queue-browser/index.js +6 -6
  39. package/lib/queue-job-actions.js +59 -4
  40. package/lib/read-env-value.js +46 -21
  41. package/lib/redis-url.js +23 -0
  42. package/lib/response-stream.js +69 -1
  43. package/lib/revocation-events.js +79 -0
  44. package/lib/routes-ui.js +4 -1
  45. package/lib/schemas.js +26 -2
  46. package/lib/session-default.js +13 -3
  47. package/lib/settings.js +47 -24
  48. package/lib/sso.js +23 -0
  49. package/lib/submit-penalty.js +24 -0
  50. package/lib/submit-processor.js +10 -2
  51. package/lib/tokens.js +6 -0
  52. package/lib/tools.js +86 -15
  53. package/lib/ui-routes/admin-config-routes.js +30 -281
  54. package/lib/ui-routes/auth-routes.js +17 -64
  55. package/lib/ui-routes/dbsc-routes.js +43 -0
  56. package/lib/ui-routes/license-routes.js +326 -0
  57. package/lib/web-safe-html.js +29 -0
  58. package/lib/webhook-delivery.js +21 -20
  59. package/lib/webhook-penalty.js +18 -17
  60. package/lib/webhooks.js +18 -0
  61. package/package.json +18 -18
  62. package/sbom.json +294 -294
  63. package/scan.js +2 -0
  64. package/server.js +253 -80
  65. package/static/css/flyonui.css +2 -2
  66. package/static/js/ui.js +11 -4
  67. package/static/licenses.html +27 -27
  68. package/translations/messages.pot +17 -17
  69. package/views/config/license.hbs +43 -16
  70. package/views/config/security.hbs +37 -0
  71. package/views/partials/side_menu.hbs +1 -1
  72. package/workers/api.js +128 -109
  73. package/workers/imap.js +4 -6
package/lib/sso.js CHANGED
@@ -384,7 +384,30 @@ function buildOidcBellProvider(discoveryDoc, options) {
384
384
  };
385
385
  }
386
386
 
387
+ /**
388
+ * Whether the identity provider of an SSO admin session still admits its user: a profile with an id
389
+ * for Okta and OIDC, and for OIDC the email and group allow-lists, re-checked on every request so a
390
+ * change to them (after a restart) takes effect without waiting out the session cookie. Asked by
391
+ * both the session strategy and the message browser's `sess_` token, which rides the same cookie and
392
+ * used to skip the allow-list, so it kept working for a removed user. A local session is admitted.
393
+ *
394
+ * @param {Object} session - The `ee` session cookie
395
+ * @param {Object} allowList - parseAllowList() result
396
+ * @param {Object} allowGroups - parseGroupList() result
397
+ * @returns {boolean}
398
+ */
399
+ function ssoSessionAdmitted(session, allowList, allowGroups) {
400
+ if (!session || (session.provider !== 'oidc' && session.provider !== 'okta')) {
401
+ return true;
402
+ }
403
+ if (!session.profile || !session.profile.id) {
404
+ return false;
405
+ }
406
+ return session.provider !== 'oidc' || isAuthorized(session.profile, allowList, allowGroups);
407
+ }
408
+
387
409
  module.exports = {
410
+ ssoSessionAdmitted,
388
411
  OIDC_ISSUER,
389
412
  OIDC_CLIENT_ID,
390
413
  OIDC_CLIENT_SECRET,
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+
3
+ // A delivery penalty per account, for the submit queue. The queue is shared by every account and
4
+ // runs one delivery at a time by default, so an account whose SMTP server holds each delivery until
5
+ // the deadline used to hold the whole queue: a few such messages delayed every other account's mail
6
+ // by the full deadline each. An account whose delivery ran into the deadline is penalised: for a
7
+ // while its next messages are moved back to the delayed set instead of being attempted, with their
8
+ // attempt count unchanged, and the queue spends its time on accounts whose servers answer. Mirrors
9
+ // lib/webhook-penalty.js.
10
+
11
+ const { REDIS_PREFIX } = require('./consts');
12
+
13
+ // How long an account is penalised after a delivery ran into the deadline
14
+ const SUBMIT_PENALTY_MS = 10 * 60 * 1000;
15
+
16
+ /**
17
+ * @param {string} account - Account id
18
+ * @returns {string} The Redis key of the account's penalty
19
+ */
20
+ function submitPenaltyKey(account) {
21
+ return `${REDIS_PREFIX}submit:penalty:${account}`;
22
+ }
23
+
24
+ module.exports = { submitPenaltyKey, SUBMIT_PENALTY_MS };
@@ -14,6 +14,8 @@
14
14
  // completes keeps its marker until the marker expires.
15
15
 
16
16
  const { UnrecoverableError } = require('bullmq');
17
+ const { delayWhilePenalised } = require('./queue-job-actions');
18
+ const { submitPenaltyKey } = require('./submit-penalty');
17
19
 
18
20
  const { decodeQueueEntry, outboxKey } = require('./outbox');
19
21
  const { shouldDiscardJob, willBeFinalAttempt, nextAttemptWhileProcessing } = require('./delivery-error');
@@ -37,10 +39,10 @@ function normalizeQueueId(job) {
37
39
  * @param {Object} deps.logger
38
40
  * @param {Object} deps.submitQueue - the BullMQ queue the jobs belong to, read back for a job's stored progress
39
41
  * @param {Function} deps.getAccount - async (accountId) => object with submitMessage(queueEntry)
40
- * @returns {Function} async (job) => processes one queued message
42
+ * @returns {Function} async (job, token) => processes one queued message
41
43
  */
42
44
  function createSubmitProcessor({ redis, logger, submitQueue, getAccount }) {
43
- return async job => {
45
+ return async (job, token) => {
44
46
  normalizeQueueId(job);
45
47
 
46
48
  // A job re-run after a stall (heartbeat kill, crash, a shutdown drain that could not cover
@@ -93,6 +95,12 @@ function createSubmitProcessor({ redis, logger, submitQueue, getAccount }) {
93
95
  return;
94
96
  }
95
97
 
98
+ // An account whose last delivery ran into the deadline waits, so its server does not hold
99
+ // the queue every other account shares; see lib/submit-penalty.js
100
+ await delayWhilePenalised(job, token, redis, submitPenaltyKey(job.data.account), delay =>
101
+ logger.info({ msg: 'Account is penalised for a stalled delivery, delaying message', account: job.data.account, job: job.id, delay })
102
+ );
103
+
96
104
  let accountObject = await getAccount(job.data.account);
97
105
 
98
106
  logger.trace({
package/lib/tokens.js CHANGED
@@ -8,6 +8,7 @@ const { REDIS_PREFIX } = require('./consts');
8
8
  const { constantTimeEqual, matchesListQuery } = require('./tools');
9
9
  const { extractMultiError } = require('./redis-operations');
10
10
  const tokenAuditLog = require('./token-audit-log');
11
+ const { publishRevocation } = require('./revocation-events');
11
12
 
12
13
  const SESS_PREFIX = 'sess_';
13
14
 
@@ -370,6 +371,9 @@ module.exports = {
370
371
 
371
372
  logger.info(Object.assign({}, tokenData, { msg: 'Deleted an access token', remoteAddress: opts.remoteAddress }));
372
373
 
374
+ // Sessions this token opened end now
375
+ await publishRevocation({ type: 'token', account: tokenData.account || null });
376
+
373
377
  return true;
374
378
  },
375
379
 
@@ -424,6 +428,8 @@ module.exports = {
424
428
 
425
429
  logger.info({ msg: 'Deleted the access tokens of an account', account, tokens: hashedTokens.length });
426
430
 
431
+ await publishRevocation({ type: 'token', account });
432
+
427
433
  return hashedTokens.length;
428
434
  },
429
435
 
package/lib/tools.js CHANGED
@@ -679,6 +679,12 @@ function attributeValueRegex(names) {
679
679
  // link, and rewriting a cid: link into one would hand the sender exactly what was refused
680
680
  const CID_EMBED_ATTRIBUTE = attributeValueRegex(['src', 'srcset', 'background']);
681
681
 
682
+ // How many bytes of data: URLs an HTML string may gain from repeated references to an image it
683
+ // already embedded. The first reference to every image is always embedded; past this budget a
684
+ // repeated one keeps its cid: link. Without it each reference became a full copy, so a few hundred
685
+ // bytes of HTML naming one inline image many times grew into a payload of many megabytes.
686
+ const CID_REPEAT_EMBED_BUDGET = 2 * 1024 * 1024;
687
+
682
688
  /**
683
689
  * Replaces the cid: references in the image attributes of an HTML string with data: URLs for the
684
690
  * attachments that have content
@@ -692,6 +698,8 @@ function embedCidImages(html, lookup) {
692
698
  return html;
693
699
  }
694
700
  let references = cidReferenceRegex();
701
+ let embeddedOnce = new Set();
702
+ let repeatBudget = CID_REPEAT_EMBED_BUDGET;
695
703
  return html.replace(CID_EMBED_ATTRIBUTE, (attribute, prefix, value) => {
696
704
  if (!value.includes('cid:')) {
697
705
  return attribute;
@@ -702,6 +710,15 @@ function embedCidImages(html, lookup) {
702
710
  return reference;
703
711
  }
704
712
  let contentType = DATA_URL_CONTENT_TYPE.test(attachment.contentType || '') ? attachment.contentType : 'application/octet-stream';
713
+ if (embeddedOnce.has(cid)) {
714
+ // measured before it is built: `data:` and `;base64,` are 13 characters
715
+ let length = 13 + contentType.length + attachment.content.length;
716
+ if (length > repeatBudget) {
717
+ return reference;
718
+ }
719
+ repeatBudget -= length;
720
+ }
721
+ embeddedOnce.add(cid);
705
722
  return `data:${contentType};base64,${attachment.content}`;
706
723
  });
707
724
  return prefix + embedded;
@@ -758,6 +775,36 @@ async function maybeReloadTlsCertificates(call, logger, keys, context) {
758
775
  return true;
759
776
  }
760
777
 
778
+ // The public keys license files are verified against. runPrechecks() below carries the same three,
779
+ // encoded; a key added to one list has to be added to the other, or a license that passes here fails
780
+ // the API worker's precheck and every API route answers with an error (test/license-keys-test.js
781
+ // checks that the two lists agree).
782
+ const LICENSE_VERIFY_KEYS = [
783
+ // main-key-1
784
+ {
785
+ key: createPublicKey(`-----BEGIN PUBLIC KEY-----
786
+ MFIwEAYHKoZIzj0CAQYFK4EEAAMDPgAEAaBbeChuyKlNp0MFi4nnRelWA6H/JHWr
787
+ ZdCXj2+HK4j0W0yzPN8VX0P7ox+1YgXNegBNchjVuu6xWSKE
788
+ -----END PUBLIC KEY-----`)
789
+ },
790
+ // trial-key-1
791
+ {
792
+ key: createPublicKey(`-----BEGIN PUBLIC KEY-----
793
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
794
+ 8ZRXhDSmZQgW92fmNTsPs3tB6fQ3eAqO4JECE5Y2sI2EX/+Gm8JcErRhDg==
795
+ -----END PUBLIC KEY-----
796
+ `)
797
+ },
798
+ // monthly-key-1: licenses of monthly plans
799
+ {
800
+ key: createPublicKey(`-----BEGIN PUBLIC KEY-----
801
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoic2BVgaR9H5nYwuq/6shU6e5st/
802
+ n8v8h1HPSe15WQKtxrojHQvw0fV3SnE1eAn8kZCndxRljsNEWgMsurkU5Q==
803
+ -----END PUBLIC KEY-----`),
804
+ billing: 'monthly'
805
+ }
806
+ ];
807
+
761
808
  module.exports = {
762
809
  // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
763
810
  toCamelCase,
@@ -1594,20 +1641,18 @@ module.exports = {
1594
1641
  getBoolean,
1595
1642
 
1596
1643
  async checkLicense(license) {
1597
- let verifyKeys = [
1598
- // main-key-1
1599
- `-----BEGIN PUBLIC KEY-----
1600
- MFIwEAYHKoZIzj0CAQYFK4EEAAMDPgAEAaBbeChuyKlNp0MFi4nnRelWA6H/JHWr
1601
- ZdCXj2+HK4j0W0yzPN8VX0P7ox+1YgXNegBNchjVuu6xWSKE
1602
- -----END PUBLIC KEY-----`,
1603
- // trial-key-1
1604
- `-----BEGIN PUBLIC KEY-----
1605
- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1606
- 8ZRXhDSmZQgW92fmNTsPs3tB6fQ3eAqO4JECE5Y2sI2EX/+Gm8JcErRhDg==
1607
- -----END PUBLIC KEY-----
1608
- `
1609
- ].map(key => createPublicKey(key));
1644
+ return await module.exports.decodeLicense(license, LICENSE_VERIFY_KEYS);
1645
+ },
1610
1646
 
1647
+ /**
1648
+ * Verifies and decodes a license file against a list of public keys. checkLicense() is the one
1649
+ * production caller and passes the keys EmailEngine trusts; nothing configurable can add one.
1650
+ * @param {string|Buffer} license - the license file or its base64url body
1651
+ * @param {Array<Object>} verifyKeys - [{ key, billing? }], key a public KeyObject or PEM
1652
+ * @returns {Promise<Object>} the license details; `billing: 'monthly'` when a monthly-plan key
1653
+ * signed it
1654
+ */
1655
+ async decodeLicense(license, verifyKeys) {
1611
1656
  let encodedLicense;
1612
1657
  if (!/\n/.test(license.toString().trim())) {
1613
1658
  encodedLicense = Buffer.from(license.toString().trim(), 'base64url');
@@ -1635,7 +1680,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1635
1680
  const verify = createVerify('SHA256');
1636
1681
  verify.write(licenseRaw);
1637
1682
  verify.end();
1638
- const isSigned = verify.verify(verifyKey, signature);
1683
+ const isSigned = verify.verify(verifyKey.key, signature);
1639
1684
  if (isSigned) {
1640
1685
  signedBy = verifyKey;
1641
1686
  break;
@@ -1662,6 +1707,12 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1662
1707
  trial: rawLicenseData.t
1663
1708
  };
1664
1709
 
1710
+ // Licenses of monthly plans are signed with their own key, which only releases that enforce
1711
+ // the monthly payment window trust; the online check runs at startup for these
1712
+ if (signedBy.billing) {
1713
+ licenseData.billing = signedBy.billing;
1714
+ }
1715
+
1665
1716
  if (rawLicenseData.l) {
1666
1717
  licenseData.lt = true;
1667
1718
  }
@@ -1951,9 +2002,25 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1951
2002
 
1952
2003
  async runPrechecks(redis) {
1953
2004
  let keyName = Buffer.from([108, 105, 99, 101, 110, 115, 101]).toString();
1954
- let content = (await redis.hget(`${REDIS_PREFIX}settings`, keyName)) || '';
2005
+ let [storedContent, suspended] = await redis.hmget(`${REDIS_PREFIX}settings`, keyName, Buffer.from('73756273757370', 'hex').toString());
2006
+ let content = storedContent || '';
1955
2007
  let assertedBy;
1956
2008
 
2009
+ // A license kept through a suspension (lib/license-subscription.js) answers API requests the
2010
+ // way a missing license does, until the subscription is in good standing again. Checked first: a
2011
+ // suspension is only ever recorded for a registered license
2012
+ if (suspended && content) {
2013
+ let err = new Error(
2014
+ Buffer.from(
2015
+ '456d61696c456e67696e65206973207061757365643a2074686520737562736372697074696f6e20626568696e6420697473206c6963656e7365206b6579206973206e6f7420696e20676f6f64207374616e64696e67',
2016
+ 'hex'
2017
+ ).toString()
2018
+ );
2019
+ err.code = Buffer.from('45537562736372697074696f6e53757370656e646564', 'hex').toString();
2020
+ err.statusCode = 403;
2021
+ throw err;
2022
+ }
2023
+
1957
2024
  if (content) {
1958
2025
  let rootList = [
1959
2026
  Buffer.from(
@@ -1963,6 +2030,10 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1963
2030
  Buffer.from(
1964
2031
  '2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d466b77457759484b6f5a497a6a3043415159494b6f5a497a6a30444151634451674145563351556959737031336e4439737544312f5a6b45586e754d6f53670a385a52586844536d5a5167573932666d4e54735073337442366651336541714f344a45434535593273493245582f2b476d384a634572526844673d3d0a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a',
1965
2032
  'hex'
2033
+ ).toString(),
2034
+ Buffer.from(
2035
+ '2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d466b77457759484b6f5a497a6a3043415159494b6f5a497a6a304441516344516741456f69633242566761523948356e597775712f3673685536653573742f0a6e387638683148505365313557514b7478726f6a4851767730665633536e453165416e386b5a436e6478526c6a734e4557674d7375726b5535513d3d0a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d',
2036
+ 'hex'
1966
2037
  ).toString()
1967
2038
  ].map(key => createPublicKey(key));
1968
2039
 
@@ -7,10 +7,7 @@
7
7
 
8
8
  const Joi = require('joi');
9
9
  const config = require('@zone-eu/wild-config');
10
- const os = require('os');
11
- const packageData = require('../../package.json');
12
10
  const { parseMessage } = require('../parse-message');
13
- const { fetch: fetchCmd } = require('undici');
14
11
 
15
12
  const settings = require('../settings');
16
13
  const consts = require('../consts');
@@ -18,10 +15,12 @@ const getSecret = require('../get-secret');
18
15
  const { timezoneOptions } = require('../timezones');
19
16
  const { Queue } = require('bullmq');
20
17
  const { redis, submitQueue, notifyQueue, queueConf, logBullErrors } = require('../db');
21
- const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, readEnvList, httpAgent, maybeReloadTlsCertificates } = require('../tools');
18
+ const { getByteSize, formatByteSize, getDuration, failAction, readEnvValue, readEnvList, maybeReloadTlsCertificates } = require('../tools');
22
19
  const { sendTestWebhook, testEventBody } = require('../webhook-test');
20
+ const licenseRoutes = require('./license-routes');
23
21
  const { llmPreProcess, buildSummaryInput, authenticationTrust } = require('../llm-pre-process');
24
22
  const { decodeHeaders } = require('../utils/decode-headers');
23
+ const { isSecureOrigin } = require('../security-headers');
25
24
  const { mcpFeatureEnabled } = require('../mcp');
26
25
  const { mcpResource } = require('../mcp/oauth');
27
26
  const { getToolRegistry } = require('../mcp/tools');
@@ -63,8 +62,6 @@ const {
63
62
  DEFAULT_OUTLOOK_EXPORT_BATCH_SIZE
64
63
  } = consts;
65
64
 
66
- const LICENSE_HOST = 'https://postalsys.com';
67
-
68
65
  config.api = config.api || {
69
66
  port: 3000,
70
67
  host: '127.0.0.1',
@@ -426,6 +423,15 @@ function registerConfigServicePage(server, args) {
426
423
  });
427
424
  }
428
425
 
426
+ // What the Security page says about device-bound sessions: whether the setting can take effect on
427
+ // this instance (an https Service URL, which browsers require), and whether the browser looking at
428
+ // the page is bound right now, which is the one way an operator can see it working
429
+ async function dbscStatus(request) {
430
+ const dbsc = request.server.app.dbsc;
431
+ const [serviceUrl, currentBound] = await Promise.all([settings.get('serviceUrl'), !!dbsc && dbsc.isBound(request)]);
432
+ return { active: isSecureOrigin(serviceUrl), currentBound };
433
+ }
434
+
429
435
  function registerConfigSecurityPage(server) {
430
436
  registerSettingsPage(server, {
431
437
  path: '/admin/config/security',
@@ -436,6 +442,7 @@ function registerConfigSecurityPage(server) {
436
442
  serviceSecret: settingsSchema.serviceSecret,
437
443
  ignoreMailCertErrors: settingsSchema.ignoreMailCertErrors.default(false),
438
444
  tokenAuditLog: settingsSchema.tokenAuditLog.default(false),
445
+ dbscEnabled: settingsSchema.dbscEnabled.default(false),
439
446
  tokenLogEntries: settingsSchema.tokenLogEntries.allow(null).default(null),
440
447
  // days on the form, seconds in the setting
441
448
  tokenLogAge: Joi.number().empty('').positive().precision(2).allow(null).default(null),
@@ -446,7 +453,14 @@ function registerConfigSecurityPage(server) {
446
453
  },
447
454
 
448
455
  async loadValues() {
449
- const storedValues = await settings.getMulti('serviceSecret', 'disableTokens', 'enableOAuthTokensApi', 'ignoreMailCertErrors', 'tokenAuditLog');
456
+ const storedValues = await settings.getMulti(
457
+ 'serviceSecret',
458
+ 'disableTokens',
459
+ 'enableOAuthTokensApi',
460
+ 'ignoreMailCertErrors',
461
+ 'tokenAuditLog',
462
+ 'dbscEnabled'
463
+ );
450
464
 
451
465
  return {
452
466
  ...(await overridableFormValues('tokenLogEntries', 'tokenLogAge')),
@@ -454,14 +468,17 @@ function registerConfigSecurityPage(server) {
454
468
  enableTokens: !storedValues.disableTokens,
455
469
  enableOAuthTokensApi: storedValues.enableOAuthTokensApi || false,
456
470
  ignoreMailCertErrors: storedValues.ignoreMailCertErrors || false,
457
- tokenAuditLog: storedValues.tokenAuditLog || false
471
+ tokenAuditLog: storedValues.tokenAuditLog || false,
472
+ dbscEnabled: storedValues.dbscEnabled || false
458
473
  };
459
474
  },
460
475
 
461
- async viewContext() {
476
+ async viewContext(request) {
477
+ const [encryption, dbsc] = await Promise.all([getSecret(), dbscStatus(request)]);
462
478
  return {
463
- encryption: await getSecret(),
464
- adminAccessLimit: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length
479
+ encryption,
480
+ adminAccessLimit: ADMIN_ACCESS_ADDRESSES && ADMIN_ACCESS_ADDRESSES.length,
481
+ dbsc
465
482
  };
466
483
  },
467
484
 
@@ -471,6 +488,7 @@ function registerConfigSecurityPage(server) {
471
488
  enableOAuthTokensApi: request.payload.enableOAuthTokensApi,
472
489
  ignoreMailCertErrors: request.payload.ignoreMailCertErrors,
473
490
  tokenAuditLog: request.payload.tokenAuditLog,
491
+ dbscEnabled: request.payload.dbscEnabled,
474
492
  ...overridableSettingsFromForm(request.payload, 'tokenLogEntries', 'tokenLogAge')
475
493
  };
476
494
 
@@ -1261,272 +1279,6 @@ function registerPostConfigWebhooksTest(server) {
1261
1279
 
1262
1280
  // Webhook, template, gateway, and token routes are in admin-entities-routes.js
1263
1281
 
1264
- function registerGetConfigLicense(server, args) {
1265
- const { call } = args;
1266
-
1267
- server.route({
1268
- method: 'GET',
1269
- path: '/admin/config/license',
1270
- async handler(request, h) {
1271
- await call({ cmd: 'checkLicense' });
1272
-
1273
- let subexp = await settings.get('subexp');
1274
- let expiresDays;
1275
- if (subexp && !(request.app.licenseInfo && request.app.licenseInfo.details && request.app.licenseInfo.details.lt)) {
1276
- let delayMs = new Date(subexp) - Date.now();
1277
- expiresDays = Math.max(Math.ceil(delayMs / (24 * 3600 * 1000)), 0);
1278
- }
1279
-
1280
- return h.view(
1281
- 'config/license',
1282
- {
1283
- pageTitle: 'License',
1284
- menuLicense: true,
1285
- hideLicenseWarning: true,
1286
-
1287
- subexp,
1288
- expiresDays,
1289
-
1290
- showLicenseText:
1291
- !request.app.licenseInfo ||
1292
- !request.app.licenseInfo.active ||
1293
- (request.app.licenseInfo.details && request.app.licenseInfo.details.trial)
1294
- },
1295
- {
1296
- layout: 'app'
1297
- }
1298
- );
1299
- }
1300
- });
1301
- }
1302
-
1303
- function registerPostConfigLicense(server, args) {
1304
- const { call } = args;
1305
-
1306
- server.route({
1307
- method: 'POST',
1308
- path: '/admin/config/license',
1309
- async handler(request, h) {
1310
- try {
1311
- // update license
1312
- const licenseInfo = await call({ cmd: 'updateLicense', license: request.payload.license });
1313
- if (!licenseInfo) {
1314
- let err = new Error('Failed to update license. Check license file contents.');
1315
- err.statusCode = 403;
1316
- err.details = { license: err.message };
1317
- throw err;
1318
- }
1319
-
1320
- if (licenseInfo.active) {
1321
- await request.flash({ type: 'info', message: `License activated` });
1322
- }
1323
-
1324
- return h.redirect('/admin/config/license');
1325
- } catch (err) {
1326
- await request.flash({ type: 'danger', message: `Couldn't register license. Check the key and try again.` });
1327
- request.logger.warn({ msg: 'Failed to register license key', err });
1328
-
1329
- return h.view(
1330
- 'config/license',
1331
- {
1332
- pageTitle: 'License',
1333
- menuLicense: true,
1334
- hideLicenseWarning: true,
1335
-
1336
- errors: err.details,
1337
- showLicenseText:
1338
- (err.details && !!err.details.license) ||
1339
- !request.app.licenseInfo ||
1340
- !request.app.licenseInfo.active ||
1341
- (request.app.licenseInfo.details && request.app.licenseInfo.details.trial)
1342
- },
1343
- {
1344
- layout: 'app'
1345
- }
1346
- );
1347
- }
1348
- },
1349
- options: {
1350
- validate: {
1351
- options: {
1352
- stripUnknown: true,
1353
- abortEarly: false,
1354
- convert: true
1355
- },
1356
-
1357
- async failAction(request, h, err) {
1358
- let errors = {};
1359
-
1360
- if (err.details) {
1361
- err.details.forEach(detail => {
1362
- if (!errors[detail.path]) {
1363
- errors[detail.path] = detail.message;
1364
- }
1365
- });
1366
- }
1367
-
1368
- await request.flash({ type: 'danger', message: `Couldn't register license. Check the key and try again.` });
1369
- request.logger.warn({ msg: 'Failed to register license key', err });
1370
-
1371
- return h
1372
- .view(
1373
- 'config/license',
1374
- {
1375
- pageTitle: 'License',
1376
- menuLicense: true,
1377
- hideLicenseWarning: true,
1378
-
1379
- errors,
1380
-
1381
- showLicenseText:
1382
- (errors && !!errors.license) ||
1383
- !request.app.licenseInfo ||
1384
- !request.app.licenseInfo.active ||
1385
- (request.app.licenseInfo.details && request.app.licenseInfo.details.trial)
1386
- },
1387
- {
1388
- layout: 'app'
1389
- }
1390
- )
1391
- .takeover();
1392
- },
1393
-
1394
- payload: Joi.object({
1395
- license: Joi.string()
1396
- .max(10 * 1024)
1397
- .required()
1398
- .example('-----BEGIN LICENSE-----\r\n...')
1399
- .description('License file')
1400
- }).label('RegisterLicense')
1401
- }
1402
- }
1403
- });
1404
- }
1405
-
1406
- function registerPostConfigLicenseDelete(server, args) {
1407
- const { call } = args;
1408
-
1409
- server.route({
1410
- method: 'POST',
1411
- path: '/admin/config/license/delete',
1412
- async handler(request, h) {
1413
- try {
1414
- const licenseInfo = await call({ cmd: 'removeLicense' });
1415
- if (!licenseInfo) {
1416
- let err = new Error('Failed to clear license info');
1417
- err.statusCode = 403;
1418
- throw err;
1419
- } else {
1420
- await request.flash({ type: 'info', message: `License removed` });
1421
- }
1422
-
1423
- return h.redirect('/admin/config/license');
1424
- } catch (err) {
1425
- await request.flash({ type: 'danger', message: `Couldn't remove license. Try again.` });
1426
- request.logger.error({ msg: 'Failed to unregister license key', err, remoteAddress: request.app.ip });
1427
- return h.redirect('/admin/config/license');
1428
- }
1429
- },
1430
- options: {
1431
- validate: {
1432
- options: {
1433
- stripUnknown: true,
1434
- abortEarly: false,
1435
- convert: true
1436
- },
1437
-
1438
- async failAction(request, h, err) {
1439
- await request.flash({ type: 'danger', message: `Couldn't remove license. Try again.` });
1440
- request.logger.error({ msg: 'Failed to unregister license key', err });
1441
-
1442
- return h.redirect('/admin/config/license').takeover();
1443
- },
1444
-
1445
- payload: Joi.object({})
1446
- }
1447
- }
1448
- });
1449
- }
1450
-
1451
- function registerPostConfigLicenseTrial(server, args) {
1452
- const { call } = args;
1453
-
1454
- server.route({
1455
- method: 'POST',
1456
- path: '/admin/config/license/trial',
1457
- async handler(request) {
1458
- try {
1459
- // provision new trial license
1460
-
1461
- let headers = {
1462
- 'Content-Type': 'application/json',
1463
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
1464
- };
1465
-
1466
- let res = await fetchCmd(`${LICENSE_HOST}/licenses/trial`, {
1467
- method: 'post',
1468
- body: JSON.stringify({
1469
- version: packageData.version,
1470
- app: '@postalsys/emailengine-app',
1471
- hostname: os.hostname() || 'localhost',
1472
- url: (await settings.get('serviceUrl')) || ''
1473
- }),
1474
- headers,
1475
- dispatcher: httpAgent.retry
1476
- });
1477
-
1478
- if (!res.ok) {
1479
- let err = new Error(res.statusText || `Invalid response: ${res.status} ${res.statusText}`);
1480
- err.statusCode = res.status;
1481
-
1482
- try {
1483
- err.response = await res.json();
1484
- } catch (err) {
1485
- // ignore
1486
- }
1487
-
1488
- throw err;
1489
- }
1490
-
1491
- const data = await res.json();
1492
-
1493
- let licenseFile = `-----BEGIN LICENSE-----
1494
- ${Buffer.from(data.content, 'base64url').toString('base64')}
1495
- -----END LICENSE-----`;
1496
-
1497
- const licenseInfo = await call({ cmd: 'updateLicense', license: licenseFile });
1498
- if (!licenseInfo) {
1499
- let err = new Error('Failed to update license. Check license file contents.');
1500
- err.statusCode = 403;
1501
- err.details = { license: err.message };
1502
- throw err;
1503
- }
1504
-
1505
- if (licenseInfo.active) {
1506
- await request.flash({ type: 'info', message: `Trial activated` });
1507
- return { success: true, message: `Trial activated` };
1508
- }
1509
-
1510
- throw new Error('Failed to activate provisioned trial license');
1511
- } catch (err) {
1512
- request.logger.error({ msg: 'Failed to provision a trial license key', err, remoteAddress: request.app.ip });
1513
- return { success: false, error: (err.response && err.response.error) || err.message };
1514
- }
1515
- },
1516
- options: {
1517
- validate: {
1518
- options: {
1519
- stripUnknown: true,
1520
- abortEarly: false,
1521
- convert: true
1522
- },
1523
-
1524
- failAction
1525
- }
1526
- }
1527
- });
1528
- }
1529
-
1530
1282
  function init(args) {
1531
1283
  const { server } = args;
1532
1284
 
@@ -1545,10 +1297,7 @@ function init(args) {
1545
1297
  registerConfigLoggingPage(server);
1546
1298
  registerPostConfigLoggingReconnect(server, args);
1547
1299
  registerPostConfigWebhooksTest(server);
1548
- registerGetConfigLicense(server, args);
1549
- registerPostConfigLicense(server, args);
1550
- registerPostConfigLicenseDelete(server, args);
1551
- registerPostConfigLicenseTrial(server, args);
1300
+ licenseRoutes(server, args);
1552
1301
  }
1553
1302
 
1554
1303
  module.exports = init;