emailengine-app 2.87.2 → 2.89.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 (71) hide show
  1. package/.ncurc.js +24 -44
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +37 -0
  4. package/ENVIRONMENT.md +26 -23
  5. package/LICENSE_EMAILENGINE.txt +20 -12
  6. package/app.json +3 -3
  7. package/bin/emailengine.js +7 -11
  8. package/data/google-crawlers.json +1 -1
  9. package/data/public_suffix_list.dat +155 -16
  10. package/lib/account.js +69 -49
  11. package/lib/admin-password.js +85 -0
  12. package/lib/api-routes/license-routes.js +9 -0
  13. package/lib/api-token-auth.js +21 -5
  14. package/lib/calendar-event.js +15 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/db.js +1 -0
  17. package/lib/email-client/base-client.js +36 -15
  18. package/lib/email-client/gmail-client.js +20 -6
  19. package/lib/email-client/imap/connection-errors.js +30 -1
  20. package/lib/email-client/imap/session-expiry.js +83 -0
  21. package/lib/email-client/imap-client.js +12 -2
  22. package/lib/email-client/smtp-pool-manager.js +66 -8
  23. package/lib/export.js +147 -22
  24. package/lib/graph-notifications.js +60 -0
  25. package/lib/imap-proxy-auth.js +52 -18
  26. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  27. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  28. package/lib/imapproxy/imap-server.js +10 -1
  29. package/lib/imapproxy/proxy-handoff.js +100 -5
  30. package/lib/license-subscription.js +244 -0
  31. package/lib/node-version.js +99 -12
  32. package/lib/oauth/gmail.js +18 -0
  33. package/lib/oauth/outlook-identity.js +54 -12
  34. package/lib/prepared-password.js +38 -0
  35. package/lib/queue-browser/index.js +6 -6
  36. package/lib/queue-job-actions.js +59 -4
  37. package/lib/read-env-value.js +46 -21
  38. package/lib/redis-url.js +23 -0
  39. package/lib/response-stream.js +69 -1
  40. package/lib/revocation-events.js +79 -0
  41. package/lib/schemas.js +18 -2
  42. package/lib/settings.js +50 -24
  43. package/lib/sso.js +23 -0
  44. package/lib/submit-penalty.js +24 -0
  45. package/lib/submit-processor.js +10 -2
  46. package/lib/tokens.js +6 -0
  47. package/lib/tools.js +90 -18
  48. package/lib/ui-routes/admin-config-routes.js +3 -276
  49. package/lib/ui-routes/auth-routes.js +13 -64
  50. package/lib/ui-routes/dashboard-routes.js +4 -0
  51. package/lib/ui-routes/license-routes.js +326 -0
  52. package/lib/web-safe-html.js +74 -1
  53. package/lib/webhook-delivery.js +21 -20
  54. package/lib/webhook-penalty.js +18 -17
  55. package/lib/webhooks.js +18 -0
  56. package/list-generate.js +56 -19
  57. package/package.json +28 -31
  58. package/sbom.json +373 -964
  59. package/scan.js +2 -0
  60. package/server.js +273 -100
  61. package/static/css/flyonui.css +2 -2
  62. package/static/js/ui.js +11 -4
  63. package/static/licenses.html +1108 -504
  64. package/translations/messages.pot +18 -18
  65. package/views/config/license.hbs +43 -16
  66. package/views/dashboard.hbs +9 -0
  67. package/views/partials/side_menu.hbs +1 -1
  68. package/views/upgrade.hbs +25 -0
  69. package/workers/api.js +108 -107
  70. package/workers/imap.js +4 -6
  71. package/lib/net-tos-guard.js +0 -42
@@ -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
@@ -2,8 +2,6 @@
2
2
 
3
3
  'use strict';
4
4
 
5
- // Before anything that makes an HTTP request, see the module
6
- require('./net-tos-guard');
7
5
  const { accountDataKey } = require('./redis-keys');
8
6
  const { filterEmptyObjectValues } = require('./utils/filter-empty');
9
7
 
@@ -275,7 +273,10 @@ function buildFetchDispatcher(proxyUrl, extraOpts) {
275
273
  if (SOCKS_SCHEMES.has(scheme)) {
276
274
  return createSocksAgent(proxyUrl, AGENT_OPTS);
277
275
  }
278
- return new ProxyAgent(Object.assign({}, AGENT_OPTS, { uri: proxyUrl }));
276
+ // proxyTunnel: undici 8 forwards a plain http:// request to the proxy in absolute form instead
277
+ // of tunnelling it, which is what undici 7 did and what proxies set up for EmailEngine have seen
278
+ // for every request since. A proxy that only allows CONNECT would refuse the forwarded form
279
+ return new ProxyAgent(Object.assign({}, AGENT_OPTS, { uri: proxyUrl, proxyTunnel: true }));
279
280
  }
280
281
 
281
282
  // Swaps the shared dispatchers over to `proxyUrl` (null for direct connections). The new fetch
@@ -679,6 +680,12 @@ function attributeValueRegex(names) {
679
680
  // link, and rewriting a cid: link into one would hand the sender exactly what was refused
680
681
  const CID_EMBED_ATTRIBUTE = attributeValueRegex(['src', 'srcset', 'background']);
681
682
 
683
+ // How many bytes of data: URLs an HTML string may gain from repeated references to an image it
684
+ // already embedded. The first reference to every image is always embedded; past this budget a
685
+ // repeated one keeps its cid: link. Without it each reference became a full copy, so a few hundred
686
+ // bytes of HTML naming one inline image many times grew into a payload of many megabytes.
687
+ const CID_REPEAT_EMBED_BUDGET = 2 * 1024 * 1024;
688
+
682
689
  /**
683
690
  * Replaces the cid: references in the image attributes of an HTML string with data: URLs for the
684
691
  * attachments that have content
@@ -692,6 +699,8 @@ function embedCidImages(html, lookup) {
692
699
  return html;
693
700
  }
694
701
  let references = cidReferenceRegex();
702
+ let embeddedOnce = new Set();
703
+ let repeatBudget = CID_REPEAT_EMBED_BUDGET;
695
704
  return html.replace(CID_EMBED_ATTRIBUTE, (attribute, prefix, value) => {
696
705
  if (!value.includes('cid:')) {
697
706
  return attribute;
@@ -702,6 +711,15 @@ function embedCidImages(html, lookup) {
702
711
  return reference;
703
712
  }
704
713
  let contentType = DATA_URL_CONTENT_TYPE.test(attachment.contentType || '') ? attachment.contentType : 'application/octet-stream';
714
+ if (embeddedOnce.has(cid)) {
715
+ // measured before it is built: `data:` and `;base64,` are 13 characters
716
+ let length = 13 + contentType.length + attachment.content.length;
717
+ if (length > repeatBudget) {
718
+ return reference;
719
+ }
720
+ repeatBudget -= length;
721
+ }
722
+ embeddedOnce.add(cid);
705
723
  return `data:${contentType};base64,${attachment.content}`;
706
724
  });
707
725
  return prefix + embedded;
@@ -758,6 +776,36 @@ async function maybeReloadTlsCertificates(call, logger, keys, context) {
758
776
  return true;
759
777
  }
760
778
 
779
+ // The public keys license files are verified against. runPrechecks() below carries the same three,
780
+ // encoded; a key added to one list has to be added to the other, or a license that passes here fails
781
+ // the API worker's precheck and every API route answers with an error (test/license-subscription-test.js
782
+ // checks that the two lists agree).
783
+ const LICENSE_VERIFY_KEYS = [
784
+ // main-key-1
785
+ {
786
+ key: createPublicKey(`-----BEGIN PUBLIC KEY-----
787
+ MFIwEAYHKoZIzj0CAQYFK4EEAAMDPgAEAaBbeChuyKlNp0MFi4nnRelWA6H/JHWr
788
+ ZdCXj2+HK4j0W0yzPN8VX0P7ox+1YgXNegBNchjVuu6xWSKE
789
+ -----END PUBLIC KEY-----`)
790
+ },
791
+ // trial-key-1
792
+ {
793
+ key: createPublicKey(`-----BEGIN PUBLIC KEY-----
794
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
795
+ 8ZRXhDSmZQgW92fmNTsPs3tB6fQ3eAqO4JECE5Y2sI2EX/+Gm8JcErRhDg==
796
+ -----END PUBLIC KEY-----
797
+ `)
798
+ },
799
+ // monthly-key-1: licenses of monthly plans
800
+ {
801
+ key: createPublicKey(`-----BEGIN PUBLIC KEY-----
802
+ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoic2BVgaR9H5nYwuq/6shU6e5st/
803
+ n8v8h1HPSe15WQKtxrojHQvw0fV3SnE1eAn8kZCndxRljsNEWgMsurkU5Q==
804
+ -----END PUBLIC KEY-----`),
805
+ billing: 'monthly'
806
+ }
807
+ ];
808
+
761
809
  module.exports = {
762
810
  // keep the re-export, lib/utils/to-camel-case.js holds it so pure modules can use it too
763
811
  toCamelCase,
@@ -1594,20 +1642,18 @@ module.exports = {
1594
1642
  getBoolean,
1595
1643
 
1596
1644
  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));
1645
+ return await module.exports.decodeLicense(license, LICENSE_VERIFY_KEYS);
1646
+ },
1610
1647
 
1648
+ /**
1649
+ * Verifies and decodes a license file against a list of public keys. checkLicense() is the one
1650
+ * production caller and passes the keys EmailEngine trusts; nothing configurable can add one.
1651
+ * @param {string|Buffer} license - the license file or its base64url body
1652
+ * @param {Array<Object>} verifyKeys - [{ key, billing? }], key a public KeyObject or PEM
1653
+ * @returns {Promise<Object>} the license details; `billing: 'monthly'` when a monthly-plan key
1654
+ * signed it
1655
+ */
1656
+ async decodeLicense(license, verifyKeys) {
1611
1657
  let encodedLicense;
1612
1658
  if (!/\n/.test(license.toString().trim())) {
1613
1659
  encodedLicense = Buffer.from(license.toString().trim(), 'base64url');
@@ -1635,7 +1681,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1635
1681
  const verify = createVerify('SHA256');
1636
1682
  verify.write(licenseRaw);
1637
1683
  verify.end();
1638
- const isSigned = verify.verify(verifyKey, signature);
1684
+ const isSigned = verify.verify(verifyKey.key, signature);
1639
1685
  if (isSigned) {
1640
1686
  signedBy = verifyKey;
1641
1687
  break;
@@ -1662,6 +1708,12 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1662
1708
  trial: rawLicenseData.t
1663
1709
  };
1664
1710
 
1711
+ // Licenses of monthly plans are signed with their own key, which only releases that enforce
1712
+ // the monthly payment window trust; the online check runs at startup for these
1713
+ if (signedBy.billing) {
1714
+ licenseData.billing = signedBy.billing;
1715
+ }
1716
+
1665
1717
  if (rawLicenseData.l) {
1666
1718
  licenseData.lt = true;
1667
1719
  }
@@ -1951,9 +2003,25 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1951
2003
 
1952
2004
  async runPrechecks(redis) {
1953
2005
  let keyName = Buffer.from([108, 105, 99, 101, 110, 115, 101]).toString();
1954
- let content = (await redis.hget(`${REDIS_PREFIX}settings`, keyName)) || '';
2006
+ let [storedContent, suspended] = await redis.hmget(`${REDIS_PREFIX}settings`, keyName, Buffer.from('73756273757370', 'hex').toString());
2007
+ let content = storedContent || '';
1955
2008
  let assertedBy;
1956
2009
 
2010
+ // A license kept through a suspension (lib/license-subscription.js) answers API requests the
2011
+ // way a missing license does, until the subscription is in good standing again. Checked first: a
2012
+ // suspension is only ever recorded for a registered license
2013
+ if (suspended && content) {
2014
+ let err = new Error(
2015
+ Buffer.from(
2016
+ '456d61696c456e67696e65206973207061757365643a2074686520737562736372697074696f6e20626568696e6420697473206c6963656e7365206b6579206973206e6f7420696e20676f6f64207374616e64696e67',
2017
+ 'hex'
2018
+ ).toString()
2019
+ );
2020
+ err.code = Buffer.from('45537562736372697074696f6e53757370656e646564', 'hex').toString();
2021
+ err.statusCode = 403;
2022
+ throw err;
2023
+ }
2024
+
1957
2025
  if (content) {
1958
2026
  let rootList = [
1959
2027
  Buffer.from(
@@ -1963,6 +2031,10 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
1963
2031
  Buffer.from(
1964
2032
  '2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d466b77457759484b6f5a497a6a3043415159494b6f5a497a6a30444151634451674145563351556959737031336e4439737544312f5a6b45586e754d6f53670a385a52586844536d5a5167573932666d4e54735073337442366651336541714f344a45434535593273493245582f2b476d384a634572526844673d3d0a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d0a',
1965
2033
  'hex'
2034
+ ).toString(),
2035
+ Buffer.from(
2036
+ '2d2d2d2d2d424547494e205055424c4943204b45592d2d2d2d2d0a4d466b77457759484b6f5a497a6a3043415159494b6f5a497a6a304441516344516741456f69633242566761523948356e597775712f3673685536653573742f0a6e387638683148505365313557514b7478726f6a4851767730665633536e453165416e386b5a436e6478526c6a734e4557674d7375726b5535513d3d0a2d2d2d2d2d454e44205055424c4943204b45592d2d2d2d2d',
2037
+ 'hex'
1966
2038
  ).toString()
1967
2039
  ].map(key => createPublicKey(key));
1968
2040
 
@@ -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,8 +15,9 @@ 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');
25
23
  const { isSecureOrigin } = require('../security-headers');
@@ -64,8 +62,6 @@ const {
64
62
  DEFAULT_OUTLOOK_EXPORT_BATCH_SIZE
65
63
  } = consts;
66
64
 
67
- const LICENSE_HOST = 'https://postalsys.com';
68
-
69
65
  config.api = config.api || {
70
66
  port: 3000,
71
67
  host: '127.0.0.1',
@@ -1283,272 +1279,6 @@ function registerPostConfigWebhooksTest(server) {
1283
1279
 
1284
1280
  // Webhook, template, gateway, and token routes are in admin-entities-routes.js
1285
1281
 
1286
- function registerGetConfigLicense(server, args) {
1287
- const { call } = args;
1288
-
1289
- server.route({
1290
- method: 'GET',
1291
- path: '/admin/config/license',
1292
- async handler(request, h) {
1293
- await call({ cmd: 'checkLicense' });
1294
-
1295
- let subexp = await settings.get('subexp');
1296
- let expiresDays;
1297
- if (subexp && !(request.app.licenseInfo && request.app.licenseInfo.details && request.app.licenseInfo.details.lt)) {
1298
- let delayMs = new Date(subexp) - Date.now();
1299
- expiresDays = Math.max(Math.ceil(delayMs / (24 * 3600 * 1000)), 0);
1300
- }
1301
-
1302
- return h.view(
1303
- 'config/license',
1304
- {
1305
- pageTitle: 'License',
1306
- menuLicense: true,
1307
- hideLicenseWarning: true,
1308
-
1309
- subexp,
1310
- expiresDays,
1311
-
1312
- showLicenseText:
1313
- !request.app.licenseInfo ||
1314
- !request.app.licenseInfo.active ||
1315
- (request.app.licenseInfo.details && request.app.licenseInfo.details.trial)
1316
- },
1317
- {
1318
- layout: 'app'
1319
- }
1320
- );
1321
- }
1322
- });
1323
- }
1324
-
1325
- function registerPostConfigLicense(server, args) {
1326
- const { call } = args;
1327
-
1328
- server.route({
1329
- method: 'POST',
1330
- path: '/admin/config/license',
1331
- async handler(request, h) {
1332
- try {
1333
- // update license
1334
- const licenseInfo = await call({ cmd: 'updateLicense', license: request.payload.license });
1335
- if (!licenseInfo) {
1336
- let err = new Error('Failed to update license. Check license file contents.');
1337
- err.statusCode = 403;
1338
- err.details = { license: err.message };
1339
- throw err;
1340
- }
1341
-
1342
- if (licenseInfo.active) {
1343
- await request.flash({ type: 'info', message: `License activated` });
1344
- }
1345
-
1346
- return h.redirect('/admin/config/license');
1347
- } catch (err) {
1348
- await request.flash({ type: 'danger', message: `Couldn't register license. Check the key and try again.` });
1349
- request.logger.warn({ msg: 'Failed to register license key', err });
1350
-
1351
- return h.view(
1352
- 'config/license',
1353
- {
1354
- pageTitle: 'License',
1355
- menuLicense: true,
1356
- hideLicenseWarning: true,
1357
-
1358
- errors: err.details,
1359
- showLicenseText:
1360
- (err.details && !!err.details.license) ||
1361
- !request.app.licenseInfo ||
1362
- !request.app.licenseInfo.active ||
1363
- (request.app.licenseInfo.details && request.app.licenseInfo.details.trial)
1364
- },
1365
- {
1366
- layout: 'app'
1367
- }
1368
- );
1369
- }
1370
- },
1371
- options: {
1372
- validate: {
1373
- options: {
1374
- stripUnknown: true,
1375
- abortEarly: false,
1376
- convert: true
1377
- },
1378
-
1379
- async failAction(request, h, err) {
1380
- let errors = {};
1381
-
1382
- if (err.details) {
1383
- err.details.forEach(detail => {
1384
- if (!errors[detail.path]) {
1385
- errors[detail.path] = detail.message;
1386
- }
1387
- });
1388
- }
1389
-
1390
- await request.flash({ type: 'danger', message: `Couldn't register license. Check the key and try again.` });
1391
- request.logger.warn({ msg: 'Failed to register license key', err });
1392
-
1393
- return h
1394
- .view(
1395
- 'config/license',
1396
- {
1397
- pageTitle: 'License',
1398
- menuLicense: true,
1399
- hideLicenseWarning: true,
1400
-
1401
- errors,
1402
-
1403
- showLicenseText:
1404
- (errors && !!errors.license) ||
1405
- !request.app.licenseInfo ||
1406
- !request.app.licenseInfo.active ||
1407
- (request.app.licenseInfo.details && request.app.licenseInfo.details.trial)
1408
- },
1409
- {
1410
- layout: 'app'
1411
- }
1412
- )
1413
- .takeover();
1414
- },
1415
-
1416
- payload: Joi.object({
1417
- license: Joi.string()
1418
- .max(10 * 1024)
1419
- .required()
1420
- .example('-----BEGIN LICENSE-----\r\n...')
1421
- .description('License file')
1422
- }).label('RegisterLicense')
1423
- }
1424
- }
1425
- });
1426
- }
1427
-
1428
- function registerPostConfigLicenseDelete(server, args) {
1429
- const { call } = args;
1430
-
1431
- server.route({
1432
- method: 'POST',
1433
- path: '/admin/config/license/delete',
1434
- async handler(request, h) {
1435
- try {
1436
- const licenseInfo = await call({ cmd: 'removeLicense' });
1437
- if (!licenseInfo) {
1438
- let err = new Error('Failed to clear license info');
1439
- err.statusCode = 403;
1440
- throw err;
1441
- } else {
1442
- await request.flash({ type: 'info', message: `License removed` });
1443
- }
1444
-
1445
- return h.redirect('/admin/config/license');
1446
- } catch (err) {
1447
- await request.flash({ type: 'danger', message: `Couldn't remove license. Try again.` });
1448
- request.logger.error({ msg: 'Failed to unregister license key', err, remoteAddress: request.app.ip });
1449
- return h.redirect('/admin/config/license');
1450
- }
1451
- },
1452
- options: {
1453
- validate: {
1454
- options: {
1455
- stripUnknown: true,
1456
- abortEarly: false,
1457
- convert: true
1458
- },
1459
-
1460
- async failAction(request, h, err) {
1461
- await request.flash({ type: 'danger', message: `Couldn't remove license. Try again.` });
1462
- request.logger.error({ msg: 'Failed to unregister license key', err });
1463
-
1464
- return h.redirect('/admin/config/license').takeover();
1465
- },
1466
-
1467
- payload: Joi.object({})
1468
- }
1469
- }
1470
- });
1471
- }
1472
-
1473
- function registerPostConfigLicenseTrial(server, args) {
1474
- const { call } = args;
1475
-
1476
- server.route({
1477
- method: 'POST',
1478
- path: '/admin/config/license/trial',
1479
- async handler(request) {
1480
- try {
1481
- // provision new trial license
1482
-
1483
- let headers = {
1484
- 'Content-Type': 'application/json',
1485
- 'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
1486
- };
1487
-
1488
- let res = await fetchCmd(`${LICENSE_HOST}/licenses/trial`, {
1489
- method: 'post',
1490
- body: JSON.stringify({
1491
- version: packageData.version,
1492
- app: '@postalsys/emailengine-app',
1493
- hostname: os.hostname() || 'localhost',
1494
- url: (await settings.get('serviceUrl')) || ''
1495
- }),
1496
- headers,
1497
- dispatcher: httpAgent.retry
1498
- });
1499
-
1500
- if (!res.ok) {
1501
- let err = new Error(res.statusText || `Invalid response: ${res.status} ${res.statusText}`);
1502
- err.statusCode = res.status;
1503
-
1504
- try {
1505
- err.response = await res.json();
1506
- } catch (err) {
1507
- // ignore
1508
- }
1509
-
1510
- throw err;
1511
- }
1512
-
1513
- const data = await res.json();
1514
-
1515
- let licenseFile = `-----BEGIN LICENSE-----
1516
- ${Buffer.from(data.content, 'base64url').toString('base64')}
1517
- -----END LICENSE-----`;
1518
-
1519
- const licenseInfo = await call({ cmd: 'updateLicense', license: licenseFile });
1520
- if (!licenseInfo) {
1521
- let err = new Error('Failed to update license. Check license file contents.');
1522
- err.statusCode = 403;
1523
- err.details = { license: err.message };
1524
- throw err;
1525
- }
1526
-
1527
- if (licenseInfo.active) {
1528
- await request.flash({ type: 'info', message: `Trial activated` });
1529
- return { success: true, message: `Trial activated` };
1530
- }
1531
-
1532
- throw new Error('Failed to activate provisioned trial license');
1533
- } catch (err) {
1534
- request.logger.error({ msg: 'Failed to provision a trial license key', err, remoteAddress: request.app.ip });
1535
- return { success: false, error: (err.response && err.response.error) || err.message };
1536
- }
1537
- },
1538
- options: {
1539
- validate: {
1540
- options: {
1541
- stripUnknown: true,
1542
- abortEarly: false,
1543
- convert: true
1544
- },
1545
-
1546
- failAction
1547
- }
1548
- }
1549
- });
1550
- }
1551
-
1552
1282
  function init(args) {
1553
1283
  const { server } = args;
1554
1284
 
@@ -1567,10 +1297,7 @@ function init(args) {
1567
1297
  registerConfigLoggingPage(server);
1568
1298
  registerPostConfigLoggingReconnect(server, args);
1569
1299
  registerPostConfigWebhooksTest(server);
1570
- registerGetConfigLicense(server, args);
1571
- registerPostConfigLicense(server, args);
1572
- registerPostConfigLicenseDelete(server, args);
1573
- registerPostConfigLicenseTrial(server, args);
1300
+ licenseRoutes(server, args);
1574
1301
  }
1575
1302
 
1576
1303
  module.exports = init;