emailengine-app 2.87.2 → 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 (64) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +23 -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/email-client/base-client.js +36 -15
  17. package/lib/email-client/gmail-client.js +20 -6
  18. package/lib/email-client/imap/connection-errors.js +30 -1
  19. package/lib/email-client/imap/session-expiry.js +83 -0
  20. package/lib/email-client/imap-client.js +12 -2
  21. package/lib/email-client/smtp-pool-manager.js +66 -8
  22. package/lib/export.js +147 -22
  23. package/lib/graph-notifications.js +60 -0
  24. package/lib/imap-proxy-auth.js +52 -18
  25. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  26. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  27. package/lib/imapproxy/imap-server.js +10 -1
  28. package/lib/imapproxy/proxy-handoff.js +100 -5
  29. package/lib/license-subscription.js +238 -0
  30. package/lib/oauth/gmail.js +18 -0
  31. package/lib/oauth/outlook-identity.js +54 -12
  32. package/lib/prepared-password.js +38 -0
  33. package/lib/queue-browser/index.js +6 -6
  34. package/lib/queue-job-actions.js +59 -4
  35. package/lib/read-env-value.js +46 -21
  36. package/lib/redis-url.js +23 -0
  37. package/lib/response-stream.js +69 -1
  38. package/lib/revocation-events.js +79 -0
  39. package/lib/schemas.js +18 -2
  40. package/lib/settings.js +47 -24
  41. package/lib/sso.js +23 -0
  42. package/lib/submit-penalty.js +24 -0
  43. package/lib/submit-processor.js +10 -2
  44. package/lib/tokens.js +6 -0
  45. package/lib/tools.js +86 -15
  46. package/lib/ui-routes/admin-config-routes.js +3 -276
  47. package/lib/ui-routes/auth-routes.js +13 -64
  48. package/lib/ui-routes/license-routes.js +326 -0
  49. package/lib/web-safe-html.js +29 -0
  50. package/lib/webhook-delivery.js +21 -20
  51. package/lib/webhook-penalty.js +18 -17
  52. package/lib/webhooks.js +18 -0
  53. package/package.json +18 -18
  54. package/sbom.json +294 -294
  55. package/scan.js +2 -0
  56. package/server.js +253 -80
  57. package/static/css/flyonui.css +2 -2
  58. package/static/js/ui.js +11 -4
  59. package/static/licenses.html +27 -27
  60. package/translations/messages.pot +17 -17
  61. package/views/config/license.hbs +43 -16
  62. package/views/partials/side_menu.hbs +1 -1
  63. package/workers/api.js +108 -107
  64. package/workers/imap.js +4 -6
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,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;
@@ -13,6 +13,7 @@ const { formBoolean } = require('../schemas');
13
13
  const crypto = require('crypto');
14
14
  const { parentPort } = require('worker_threads');
15
15
  const pbkdf2 = require('../pbkdf2-phc');
16
+ const { verifyAdminPassword, verifyCurrentPassword, setAdminPassword } = require('../admin-password');
16
17
  const { generateTotpSeed, verifyTotp, generateTotpUrl, generateTotpQrDataUrl } = require('../totp');
17
18
  const {
18
19
  generateRegistrationOptions,
@@ -115,46 +116,6 @@ function passkeyTimestamp(value) {
115
116
  return date && !isNaN(date.getTime()) ? date.toISOString() : null;
116
117
  }
117
118
 
118
- // Single place that knows how a failed password check is interpreted: an absent password and a
119
- // verify() that throws (which happens only on a malformed stored hash, never on a wrong password)
120
- // are both failures, never a pass. Sign-in, the password change and both passkey registration
121
- // steps all come through here, so a change to how the account password is checked - a KDF swap,
122
- // a dummy verify to flatten timing - lands in one place.
123
- async function verifyAdminPassword(hash, password, logger) {
124
- if (!password) {
125
- return false;
126
- }
127
- try {
128
- return await pbkdf2.verify(hash, password);
129
- } catch (err) {
130
- logger.error({ msg: 'Failed to verify password hash', err });
131
- return false;
132
- }
133
- }
134
-
135
- // The current-password check behind the security page's step-down actions (the password change
136
- // and switching the second factor off). A live session alone is not supposed to reveal the
137
- // password, and unthrottled the field let a hijacked session guess it at full speed, so the
138
- // check is rate limited the way the login form is: keyed on the account rather than the address
139
- // because the caller is already authenticated as it, and with the login form's per-username
140
- // budget. Owns the limiter and the warn logs; the caller decides how to report the failure.
141
- //
142
- // @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid', message: String }>}
143
- async function verifyCurrentPassword(request, h, authData, password) {
144
- let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
145
- if (!rateLimit.success) {
146
- request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
147
- return { ok: false, reason: 'rateLimited', message: 'Rate limited, please wait and try again' };
148
- }
149
-
150
- if (!(await verifyAdminPassword(authData.password, password, request.logger))) {
151
- request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
152
- return { ok: false, reason: 'invalid', message: 'Invalid password' };
153
- }
154
-
155
- return { ok: true };
156
- }
157
-
158
119
  // Sends a refused step-down action on the security page back to the page with the reason
159
120
  async function refuseSecurityAction(request, h, verified) {
160
121
  await request.flash({ type: 'danger', message: verified.message });
@@ -1136,9 +1097,12 @@ function registerPostAccountPasskeysRegisterOptions(server) {
1136
1097
  }
1137
1098
 
1138
1099
  // Last, because it is the expensive check: the request is refused for a missing
1139
- // Service URL or a full list without paying for a PBKDF2 verification first
1140
- if (!(await verifyAdminPassword(authData.password, request.payload.password, request.logger))) {
1141
- return h.response({ error: 'Invalid password' }).code(403);
1100
+ // Service URL or a full list without paying for a PBKDF2 verification first.
1101
+ // Through the per-account budget the other step-down checks use: the per-address
1102
+ // limit above alone let a hijacked session guess the password from many addresses
1103
+ let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
1104
+ if (!verified.ok) {
1105
+ return h.response({ error: verified.message }).code(verified.statusCode);
1142
1106
  }
1143
1107
 
1144
1108
  let options = await generateRegistrationOptions({
@@ -1213,7 +1177,7 @@ function registerPostAccountPasskeysRegisterVerify(server) {
1213
1177
  // change, so a hijacked session gets no second password-guessing surface here
1214
1178
  let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
1215
1179
  if (!verified.ok) {
1216
- return h.response({ error: verified.message }).code(verified.reason === 'rateLimited' ? 429 : 403);
1180
+ return h.response({ error: verified.message }).code(verified.statusCode);
1217
1181
  }
1218
1182
 
1219
1183
  let challenge = await passkeys.consumeChallenge(request.payload.challengeId, passkeys.CHALLENGE_REGISTER);
@@ -1573,26 +1537,11 @@ function registerPostAccountPassword(server) {
1573
1537
  }
1574
1538
  }
1575
1539
 
1576
- const passwordHash = await pbkdf2.hash(request.payload.password);
1577
-
1578
- authData = authData || {};
1579
- authData.user = authData.user || 'admin';
1580
- authData.password = passwordHash;
1581
- authData.passwordVersion = Date.now();
1582
-
1583
- await settings.set('authData', authData);
1584
-
1585
- // Every passkey goes with the old password: registering one takes the password,
1586
- // so a passkey that outlived a password change could be one registered by whoever
1587
- // had the old password. The form warns about this while passkeys exist, and the
1588
- // flash below says how many went.
1589
- let clearedPasskeys = 0;
1590
- try {
1591
- clearedPasskeys = await passkeys.deleteAllCredentials(authData.user || 'admin');
1592
- request.logger.info({ msg: 'All passkeys cleared after password change', user: authData.user || 'admin', cleared: clearedPasskeys });
1593
- } catch (passkeyErr) {
1594
- request.logger.error({ msg: 'Failed to clear passkeys after password change', err: passkeyErr });
1595
- }
1540
+ // Every passkey goes with the old password (see setAdminPassword()). The form
1541
+ // warns about this while passkeys exist, and the flash below says how many went.
1542
+ const changed = await setAdminPassword(await pbkdf2.hash(request.payload.password), { settings, passkeys, logger: request.logger }, authData);
1543
+ authData = changed.authData;
1544
+ const clearedPasskeys = changed.clearedPasskeys;
1596
1545
 
1597
1546
  if (!server.auth.settings.default) {
1598
1547
  server.auth.default('session');