emailengine-app 2.84.1 → 2.85.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 (147) hide show
  1. package/.dockerignore +6 -0
  2. package/.ncurc.js +5 -3
  3. package/.prettierignore +5 -1
  4. package/.prettierrc.js +2 -0
  5. package/.release-please-manifest.json +1 -1
  6. package/CHANGELOG.md +61 -0
  7. package/Dockerfile +8 -2
  8. package/README.md +1 -1
  9. package/bin/emailengine.js +444 -403
  10. package/copy-static-files.sh +39 -14
  11. package/data/google-crawlers.json +1 -1
  12. package/data/public_suffix_list.dat +16562 -0
  13. package/docker-compose.yml +1 -1
  14. package/eslint.config.js +81 -99
  15. package/lib/account/own-account-key.js +42 -0
  16. package/lib/account-assignment.js +1 -33
  17. package/lib/account.js +68 -24
  18. package/lib/add-trackers.js +11 -4
  19. package/lib/api-reference/format.js +4 -3
  20. package/lib/api-routes/account-routes.js +244 -26
  21. package/lib/api-routes/blocklist-routes.js +23 -2
  22. package/lib/api-routes/delivery-test-routes.js +26 -3
  23. package/lib/api-routes/export-routes.js +28 -2
  24. package/lib/api-routes/gateway-routes.js +37 -5
  25. package/lib/api-routes/mailbox-routes.js +41 -2
  26. package/lib/api-routes/message-routes.js +104 -4
  27. package/lib/api-routes/mint-bounds.js +11 -0
  28. package/lib/api-routes/oauth2-app-routes.js +48 -15
  29. package/lib/api-routes/outbox-routes.js +45 -11
  30. package/lib/api-routes/permission-map.js +12 -1
  31. package/lib/api-routes/route-helpers.js +125 -3
  32. package/lib/api-routes/settings-routes.js +23 -2
  33. package/lib/api-routes/submit-routes.js +338 -309
  34. package/lib/api-routes/template-routes.js +38 -2
  35. package/lib/api-routes/token-routes.js +142 -96
  36. package/lib/api-routes/webhook-route-routes.js +13 -2
  37. package/lib/auth-token.js +23 -10
  38. package/lib/bounce-detect.js +414 -210
  39. package/lib/consts.js +39 -4
  40. package/lib/create-imap-client.js +41 -2
  41. package/lib/email-client/base-client.js +30 -41
  42. package/lib/email-client/gmail-client.js +30 -18
  43. package/lib/email-client/imap/mailbox.js +13 -23
  44. package/lib/email-client/imap/response-metrics.js +75 -0
  45. package/lib/email-client/imap/subconnection.js +1 -1
  46. package/lib/email-client/imap-client.js +6 -3
  47. package/lib/email-client/message-builder.js +7 -2
  48. package/lib/email-client/notification-handler.js +1 -2
  49. package/lib/email-client/outlook/graph-api.js +17 -2
  50. package/lib/email-client/outlook-client.js +6 -3
  51. package/lib/email-client/smtp-pool-manager.js +6 -0
  52. package/lib/encrypt.js +9 -0
  53. package/lib/export.js +3 -1
  54. package/lib/gateway.js +2 -3
  55. package/lib/get-raw-email.js +4 -2
  56. package/lib/hapi-request-logger.js +107 -0
  57. package/lib/imap-proxy-auth.js +14 -1
  58. package/lib/imapproxy/imap-core/README.md +6 -5
  59. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  60. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  61. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  62. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  63. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  64. package/lib/mcp/listen.js +10 -1
  65. package/lib/mcp/tools.js +37 -8
  66. package/lib/notify-attachments.js +17 -0
  67. package/lib/oauth/external-account-config.js +3 -1
  68. package/lib/oauth/gmail.js +21 -48
  69. package/lib/oauth/mail-ru.js +5 -38
  70. package/lib/oauth/outlook-mailbox.js +35 -0
  71. package/lib/oauth/outlook.js +26 -44
  72. package/lib/oauth/state.js +24 -0
  73. package/lib/oauth2-apps.js +1 -1
  74. package/lib/pbkdf2-phc.js +19 -2
  75. package/lib/privileged-settings.js +6 -3
  76. package/lib/redis-scan-delete.js +15 -1
  77. package/lib/schemas.js +79 -33
  78. package/lib/settings.js +13 -1
  79. package/lib/smtp-auth.js +23 -0
  80. package/lib/sso.js +1 -1
  81. package/lib/swagger-options.js +1 -1
  82. package/lib/thread-diagnostics.js +46 -0
  83. package/lib/timezones.js +109 -0
  84. package/lib/token-permission-view.js +3 -3
  85. package/lib/tools.js +285 -66
  86. package/lib/totp.js +2 -5
  87. package/lib/translations.js +1 -2
  88. package/lib/ui-routes/account-routes.js +491 -491
  89. package/lib/ui-routes/account-setup.js +99 -0
  90. package/lib/ui-routes/admin-config-routes.js +98 -48
  91. package/lib/ui-routes/admin-entities-routes.js +113 -31
  92. package/lib/ui-routes/auth-routes.js +137 -62
  93. package/lib/ui-routes/connection-security-form.js +74 -0
  94. package/lib/ui-routes/form-lists.js +46 -0
  95. package/lib/ui-routes/internals-routes.js +5 -0
  96. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  97. package/lib/ui-routes/oauth-config-routes.js +133 -100
  98. package/lib/ui-routes/route-helpers.js +19 -3
  99. package/lib/ui-routes/sign-in-helpers.js +59 -0
  100. package/lib/ui-routes/tls-config-routes.js +58 -15
  101. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  102. package/lib/utils/back-off.js +82 -0
  103. package/lib/utils/map-concurrent.js +36 -0
  104. package/lib/utils/murmurhash3.js +66 -0
  105. package/lib/utils/network.js +28 -0
  106. package/lib/utils/provider-id.js +27 -0
  107. package/lib/utils/public-suffix.js +122 -0
  108. package/lib/utils/random-id.js +26 -0
  109. package/lib/utils/require-tls.js +33 -0
  110. package/lib/utils/version.js +74 -0
  111. package/lib/web-safe-html.js +5 -6
  112. package/lib/webhook-penalty.js +75 -0
  113. package/lib/webhook-routing.js +49 -2
  114. package/lib/webhooks.js +41 -6
  115. package/package.json +37 -39
  116. package/sbom.json +7980 -1
  117. package/server.js +659 -455
  118. package/static/js/ace/ace.js +1 -1
  119. package/static/js/ace/mode-handlebars.js +1 -1
  120. package/static/js/ace/mode-html.js +1 -1
  121. package/static/js/ace/mode-javascript.js +1 -1
  122. package/static/js/ace/mode-markdown.js +1 -1
  123. package/static/js/ace/worker-html.js +1 -1
  124. package/static/js/ace/worker-javascript.js +1 -1
  125. package/static/js/ace/worker-json.js +1 -1
  126. package/static/js/ee-client.js +5 -0
  127. package/static/licenses.html +191 -1016
  128. package/translations/messages.pot +70 -71
  129. package/views/account/security.hbs +10 -0
  130. package/views/accounts/account.hbs +11 -11
  131. package/views/accounts/edit.hbs +6 -2
  132. package/views/config/ai.hbs +1 -1
  133. package/views/config/security.hbs +2 -2
  134. package/views/config/service.hbs +3 -0
  135. package/views/internals/index.hbs +8 -0
  136. package/views/partials/gateway_form.hbs +3 -1
  137. package/views/partials/webhook_form.hbs +1 -1
  138. package/views/suppression-lists/index.hbs +1 -1
  139. package/workers/api.js +780 -585
  140. package/workers/export.js +1 -1
  141. package/workers/submit.js +1 -1
  142. package/workers/webhooks.js +54 -34
  143. package/config/test.toml +0 -46
  144. package/install.sh +0 -428
  145. package/setup-production.sh +0 -215
  146. package/systemd/emailengine.service +0 -97
  147. package/systemd/nginx-proxy.conf +0 -77
@@ -21,6 +21,7 @@ const { authMethodContext, gmailServiceAuthRoutes } = require('./gmail-service-a
21
21
  const { isSendOnlyGmailApp } = require('../oauth/scope-checker');
22
22
  const { oauthCreateSchema, oauthUpdateSchema, accountIdSchema, formBoolean } = require('../schemas');
23
23
  const { throwAsBoom, adminUrl, submittedValues, windowedPageLinks } = require('./route-helpers');
24
+ const { parseScopeList } = require('./form-lists');
24
25
  const { baseScopesContext } = require('./oauth-form-context');
25
26
 
26
27
  const { DEFAULT_PAGE_SIZE } = consts;
@@ -51,93 +52,89 @@ const AZURE_CLOUDS = [
51
52
  }
52
53
  ];
53
54
 
54
- function init(args) {
55
- const { server, call } = args;
56
-
57
- gmailServiceAuthRoutes({ server });
58
-
59
- /**
60
- * View context for re-rendering the new or edit OAuth2 app form after a failed save, from the
61
- * submitted fields. One function for the handler's catch and the validation failAction of both
62
- * forms, so the four copies cannot drift again: the secret fields are blanked (the edit page
63
- * never echoes a stored secret, and the API masks them), and on the edit form the
64
- * authentication method stays locked once the app has one.
65
- *
66
- * @param {Object} request - the Hapi request carrying the submitted payload
67
- * @param {Object} [appData] - the stored app when editing, absent when creating
68
- * @param {Object} [errors] - field errors to show
69
- * @returns {Promise<Object>}
70
- */
71
- async function appFormErrorContext(request, appData, errors) {
72
- const payload = request.payload;
73
- const provider = appData ? appData.provider : payload.provider;
74
- const providerData = appData ? oauth2ProviderData(appData.provider, appData.cloud) : oauth2ProviderData(provider);
75
-
76
- const serviceUrl = await settings.get('serviceUrl');
77
- let defaultRedirectUrl = `${serviceUrl}/oauth`;
78
- if (provider === 'outlook') {
79
- defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
80
- }
81
-
82
- const context = {
83
- pageTitle: 'OAuth2 Apps',
84
- menuOauthApps: true,
85
-
86
- [`active${providerData.caseName}`]: true,
87
- providerData,
88
- defaultRedirectUrl,
89
-
90
- pubSubApps: await getPubSubAppsForSelect(payload.pubSubApp),
91
-
92
- ...baseScopesContext(payload.baseScopes),
93
-
94
- azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
95
- entry.selected = payload.cloud === entry.id;
96
- return entry;
97
- }),
98
-
99
- // The submitted fields, not the stored app: without them the new-app form loses its
100
- // provider on a validation error and the next submit is bounced to /admin
101
- values: submittedValues(request, 'clientSecret', 'serviceKey', 'externalAccount'),
102
-
103
- authorityCommon: payload.authority === 'common',
104
- authorityOrganizations: payload.authority === 'organizations',
105
- authorityConsumers: payload.authority === 'consumers',
106
- authorityTenant: payload.authority === 'tenant',
107
-
108
- errors
109
- };
110
-
111
- if (appData) {
112
- Object.assign(context, {
113
- appData,
114
- hasClientSecret: !!appData.clientSecret,
115
- hasServiceKey: !!appData.serviceKey,
116
- hasExternalAccount: !!appData.externalAccount,
117
- ...authMethodContext(appData.authMethod, isAuthMethodLocked(appData))
118
- });
119
- } else {
120
- Object.assign(context, { actionCreate: true, ...authMethodContext(payload.authMethod) });
121
- }
55
+ /**
56
+ * View context for re-rendering the new or edit OAuth2 app form after a failed save, from the
57
+ * submitted fields. One function for the handler's catch and the validation failAction of both
58
+ * forms, so the four copies cannot drift again: the secret fields are blanked (the edit page
59
+ * never echoes a stored secret, and the API masks them), and on the edit form the
60
+ * authentication method stays locked once the app has one.
61
+ *
62
+ * @param {Object} request - the Hapi request carrying the submitted payload
63
+ * @param {Object} [appData] - the stored app when editing, absent when creating
64
+ * @param {Object} [errors] - field errors to show
65
+ * @returns {Promise<Object>}
66
+ */
67
+ async function appFormErrorContext(request, appData, errors) {
68
+ const payload = request.payload;
69
+ const provider = appData ? appData.provider : payload.provider;
70
+ const providerData = appData ? oauth2ProviderData(appData.provider, appData.cloud) : oauth2ProviderData(provider);
71
+
72
+ const serviceUrl = await settings.get('serviceUrl');
73
+ let defaultRedirectUrl = `${serviceUrl}/oauth`;
74
+ if (provider === 'outlook') {
75
+ defaultRedirectUrl = defaultRedirectUrl.replace(/^http:\/\/127\.0\.0\.1\b/i, 'http://localhost');
76
+ }
122
77
 
123
- return context;
78
+ const context = {
79
+ pageTitle: 'OAuth2 Apps',
80
+ menuOauthApps: true,
81
+
82
+ [`active${providerData.caseName}`]: true,
83
+ providerData,
84
+ defaultRedirectUrl,
85
+
86
+ pubSubApps: await getPubSubAppsForSelect(payload.pubSubApp),
87
+
88
+ ...baseScopesContext(payload.baseScopes),
89
+
90
+ azureClouds: structuredClone(AZURE_CLOUDS).map(entry => {
91
+ entry.selected = payload.cloud === entry.id;
92
+ return entry;
93
+ }),
94
+
95
+ // The submitted fields, not the stored app: without them the new-app form loses its
96
+ // provider on a validation error and the next submit is bounced to /admin
97
+ values: submittedValues(request, 'clientSecret', 'serviceKey', 'externalAccount'),
98
+
99
+ authorityCommon: payload.authority === 'common',
100
+ authorityOrganizations: payload.authority === 'organizations',
101
+ authorityConsumers: payload.authority === 'consumers',
102
+ authorityTenant: payload.authority === 'tenant',
103
+
104
+ errors
105
+ };
106
+
107
+ if (appData) {
108
+ Object.assign(context, {
109
+ appData,
110
+ hasClientSecret: !!appData.clientSecret,
111
+ hasServiceKey: !!appData.serviceKey,
112
+ hasExternalAccount: !!appData.externalAccount,
113
+ ...authMethodContext(appData.authMethod, isAuthMethodLocked(appData))
114
+ });
115
+ } else {
116
+ Object.assign(context, { actionCreate: true, ...authMethodContext(payload.authMethod) });
124
117
  }
125
118
 
126
- /**
127
- * Fetch the list of Pub/Sub apps and mark the one matching selectedId as selected.
128
- * Returns the apps array ready for template rendering.
129
- */
130
- async function getPubSubAppsForSelect(selectedId) {
131
- let result = await oauth2Apps.list(0, 1000, { pubsub: true });
132
- let apps = (result && result.apps) || [];
133
- for (let app of apps) {
134
- if (app.id === selectedId) {
135
- app.selected = true;
136
- }
119
+ return context;
120
+ }
121
+
122
+ /**
123
+ * Fetch the list of Pub/Sub apps and mark the one matching selectedId as selected.
124
+ * Returns the apps array ready for template rendering.
125
+ */
126
+ async function getPubSubAppsForSelect(selectedId) {
127
+ let result = await oauth2Apps.list(0, 1000, { pubsub: true });
128
+ let apps = (result && result.apps) || [];
129
+ for (let app of apps) {
130
+ if (app.id === selectedId) {
131
+ app.selected = true;
137
132
  }
138
- return apps;
139
133
  }
134
+ return apps;
135
+ }
140
136
 
137
+ function registerGetConfigOauth(server) {
141
138
  server.route({
142
139
  method: 'GET',
143
140
  path: '/admin/config/oauth',
@@ -239,8 +236,10 @@ function init(args) {
239
236
  }
240
237
  }
241
238
  });
239
+ }
242
240
 
243
- // GET /admin/config/oauth/subscriptions - Gmail Pub/Sub subscriptions list
241
+ // GET /admin/config/oauth/subscriptions - Gmail Pub/Sub subscriptions list
242
+ function registerGetConfigOauthSubscriptions(server) {
244
243
  server.route({
245
244
  method: 'GET',
246
245
  path: '/admin/config/oauth/subscriptions',
@@ -352,7 +351,9 @@ function init(args) {
352
351
  }
353
352
  }
354
353
  });
354
+ }
355
355
 
356
+ function registerPostConfigOauthSubscriptions(server) {
356
357
  server.route({
357
358
  method: 'POST',
358
359
  path: '/admin/config/oauth/subscriptions',
@@ -390,7 +391,9 @@ function init(args) {
390
391
  }
391
392
  }
392
393
  });
394
+ }
393
395
 
396
+ function registerGetConfigOauthApp(server) {
394
397
  server.route({
395
398
  method: 'GET',
396
399
  path: '/admin/config/oauth/app/{app}',
@@ -488,6 +491,10 @@ function init(args) {
488
491
  }
489
492
  }
490
493
  });
494
+ }
495
+
496
+ function registerPostConfigOauthDelete(server, args) {
497
+ const { call } = args;
491
498
 
492
499
  server.route({
493
500
  method: 'POST',
@@ -532,6 +539,10 @@ function init(args) {
532
539
  }
533
540
  }
534
541
  });
542
+ }
543
+
544
+ function registerPostConfigOauthAppAddAccount(server, args) {
545
+ const { call } = args;
535
546
 
536
547
  server.route({
537
548
  method: 'POST',
@@ -605,7 +616,9 @@ function init(args) {
605
616
  }
606
617
  }
607
618
  });
619
+ }
608
620
 
621
+ function registerPostConfigOauthVerify(server) {
609
622
  server.route({
610
623
  method: 'POST',
611
624
  path: '/admin/config/oauth/verify/{app}',
@@ -645,7 +658,9 @@ function init(args) {
645
658
  }
646
659
  }
647
660
  });
661
+ }
648
662
 
663
+ function registerGetConfigOauthNew(server) {
649
664
  server.route({
650
665
  method: 'GET',
651
666
  path: '/admin/config/oauth/new',
@@ -726,6 +741,10 @@ function init(args) {
726
741
  }
727
742
  }
728
743
  });
744
+ }
745
+
746
+ function registerPostConfigOauthNew(server, args) {
747
+ const { call } = args;
729
748
 
730
749
  server.route({
731
750
  method: 'POST',
@@ -733,15 +752,8 @@ function init(args) {
733
752
  async handler(request, h) {
734
753
  try {
735
754
  let appData = Object.assign({}, request.payload);
736
- appData.extraScopes = appData.extraScopes
737
- .split(/\s+/)
738
- .map(scope => scope.trim())
739
- .filter(scope => scope);
740
-
741
- appData.skipScopes = appData.skipScopes
742
- .split(/\s+/)
743
- .map(scope => scope.trim())
744
- .filter(scope => scope);
755
+ appData.extraScopes = parseScopeList(appData.extraScopes);
756
+ appData.skipScopes = parseScopeList(appData.skipScopes);
745
757
 
746
758
  if (appData.authority === 'tenant') {
747
759
  appData.authority = appData.tenant;
@@ -805,7 +817,9 @@ function init(args) {
805
817
  }
806
818
  }
807
819
  });
820
+ }
808
821
 
822
+ function registerGetConfigOauthEdit(server) {
809
823
  server.route({
810
824
  method: 'GET',
811
825
  path: '/admin/config/oauth/edit/{app}',
@@ -891,6 +905,10 @@ function init(args) {
891
905
  }
892
906
  }
893
907
  });
908
+ }
909
+
910
+ function registerPostConfigOauthEdit(server, args) {
911
+ const { call } = args;
894
912
 
895
913
  server.route({
896
914
  method: 'POST',
@@ -904,15 +922,12 @@ function init(args) {
904
922
 
905
923
  try {
906
924
  let updates = Object.assign({}, request.payload);
907
- updates.extraScopes = updates.extraScopes
908
- .split(/\s+/)
909
- .map(scope => scope.trim())
910
- .filter(scope => scope);
911
-
912
- updates.skipScopes = updates.skipScopes
913
- .split(/\s+/)
914
- .map(scope => scope.trim())
915
- .filter(scope => scope);
925
+ // A scope field missing from the request leaves the stored list as it is
926
+ for (let key of ['extraScopes', 'skipScopes']) {
927
+ if (typeof updates[key] === 'string') {
928
+ updates[key] = parseScopeList(updates[key]);
929
+ }
930
+ }
916
931
 
917
932
  if (updates.authority === 'tenant') {
918
933
  updates.authority = updates.tenant;
@@ -975,4 +990,22 @@ function init(args) {
975
990
  });
976
991
  }
977
992
 
993
+ function init(args) {
994
+ const { server } = args;
995
+
996
+ gmailServiceAuthRoutes({ server });
997
+
998
+ registerGetConfigOauth(server);
999
+ registerGetConfigOauthSubscriptions(server);
1000
+ registerPostConfigOauthSubscriptions(server);
1001
+ registerGetConfigOauthApp(server);
1002
+ registerPostConfigOauthDelete(server, args);
1003
+ registerPostConfigOauthAppAddAccount(server, args);
1004
+ registerPostConfigOauthVerify(server);
1005
+ registerGetConfigOauthNew(server);
1006
+ registerPostConfigOauthNew(server, args);
1007
+ registerGetConfigOauthEdit(server);
1008
+ registerPostConfigOauthEdit(server, args);
1009
+ }
1010
+
978
1011
  module.exports = init;
@@ -13,7 +13,7 @@ const Boom = require('@hapi/boom');
13
13
  const util = require('util');
14
14
  const fs = require('fs');
15
15
  const pathlib = require('path');
16
- const psl = require('psl');
16
+ const { getRegistrableDomain } = require('../utils/public-suffix');
17
17
  const handlebars = require('handlebars');
18
18
 
19
19
  const { redis } = require('../db');
@@ -177,11 +177,11 @@ function formatAccountData(account, gt) {
177
177
  } else if (account.imap && !account.imap.disabled) {
178
178
  account.type.icon = 'icon-[tabler--mail]';
179
179
  account.type.name = 'IMAP';
180
- account.type.comment = psl.get(account.imap.host) || account.imap.host;
180
+ account.type.comment = getRegistrableDomain(account.imap.host) || account.imap.host;
181
181
  } else if (account.smtp) {
182
182
  account.type.icon = 'icon-[tabler--send]';
183
183
  account.type.name = 'SMTP';
184
- account.type.comment = psl.get(account.smtp.host) || account.smtp.host;
184
+ account.type.comment = getRegistrableDomain(account.smtp.host) || account.smtp.host;
185
185
  } else if (account.oauth2 && account.oauth2.auth && account.oauth2.auth.delegatedAccount) {
186
186
  account.type.icon = 'icon-[tabler--arrow-right-circle]';
187
187
  account.type.name = gt.gettext('Delegated');
@@ -364,6 +364,21 @@ function workspaceErrorView(request, h, { actualEmail, retryUrl }) {
364
364
  return setupRefusalView(request, h, 'account-workspace-error', { actualEmail, retryUrl });
365
365
  }
366
366
 
367
+ // The page a successful setup ends on, from both arms of the form. An HTML redirect rather than an
368
+ // HTTP one, otherwise samesite=strict cookies are not passed on.
369
+ function renderRedirect(request, h, httpRedirectUrl) {
370
+ return h.view(
371
+ 'redirect',
372
+ {
373
+ pageTitleFull: request.app.gt.gettext('Email Account Setup'),
374
+ httpRedirectUrl
375
+ },
376
+ {
377
+ layout: 'public'
378
+ }
379
+ );
380
+ }
381
+
367
382
  // View-model for the ui/pagination partial: prev/next URLs plus the numbered page links.
368
383
  // basePath is the URL path without a query string (leading slash optional, matching the
369
384
  // `new URL(path, base)` convention the route modules already use); data is a listing
@@ -593,6 +608,7 @@ module.exports = {
593
608
  accountPickerSelection,
594
609
  identityErrorView,
595
610
  workspaceErrorView,
611
+ renderRedirect,
596
612
  compiledFragments,
597
613
  closedAfterConnectMessage,
598
614
  accountStateLabel,
@@ -0,0 +1,59 @@
1
+ 'use strict';
2
+
3
+ // Two steps of the password sign-in that lib/ui-routes/auth-routes.js takes around the credential
4
+ // check: the per-account failure budget, and the upgrade of a password hash written with weaker
5
+ // parameters than hash() uses today.
6
+
7
+ const { windowBudget, reserveAttempts, releaseAttempts } = require('../rate-limit');
8
+ const pbkdf2 = require('../pbkdf2-phc');
9
+ const settings = require('../settings');
10
+
11
+ // Failed password sign-ins one account name may accumulate per minute before further attempts are
12
+ // refused. Failures only: a successful sign-in gives its reservation back
13
+ const LOGIN_FAILURE_BUDGET = 10;
14
+ const LOGIN_FAILURE_WINDOW = 60;
15
+
16
+ /**
17
+ * Reserves one sign-in attempt for an account name.
18
+ *
19
+ * Counted on failure only: the attempt is reserved before the credential check and given back
20
+ * through `release()` once the sign-in succeeded, so ten successful sign-ins a minute do not lock
21
+ * the account and ten wrong passwords do. Keyed under its own namespace, since the username is the
22
+ * attacker's to choose and `ip:<address>` used to land on the per-address counter.
23
+ *
24
+ * @param {String} username - the account name the client is signing in as
25
+ * @returns {Promise<{admitted: Boolean, key: String, release: Function}>}
26
+ */
27
+ async function reserveLoginAttempt(username) {
28
+ const budget = windowBudget(`login:user:${username}`, LOGIN_FAILURE_BUDGET, LOGIN_FAILURE_WINDOW);
29
+ const { admitted } = await reserveAttempts([budget]);
30
+ return {
31
+ admitted,
32
+ key: budget.key,
33
+ // Best effort: a lost release costs this account one attempt of its budget
34
+ release: () => releaseAttempts([budget.key])
35
+ };
36
+ }
37
+
38
+ /**
39
+ * Rewrites the stored password hash with the current parameters when it was written with weaker
40
+ * ones (fewer iterations, SHA-1). Only right after the password was checked against it, which is
41
+ * the one moment the password is known; verify() keeps accepting the old hash otherwise. Not a
42
+ * password change, so the version that ends every other session stays as it is.
43
+ *
44
+ * @param {Object} authData - the stored authData record, updated in place when rewritten
45
+ * @param {String} password - the password that just verified
46
+ * @param {Object} logger
47
+ * @returns {Promise<Boolean>} whether the hash was rewritten
48
+ */
49
+ async function upgradePasswordHash(authData, password, logger) {
50
+ if (!authData || !pbkdf2.needsRehash(authData.password)) {
51
+ return false;
52
+ }
53
+ authData.password = await pbkdf2.hash(password);
54
+ await settings.set('authData', authData);
55
+ logger.info({ msg: 'Admin password hash upgraded to the current parameters', user: authData.user });
56
+ return true;
57
+ }
58
+
59
+ module.exports = { reserveLoginAttempt, upgradePasswordHash, LOGIN_FAILURE_BUDGET };
@@ -110,12 +110,10 @@ async function assertConfiguredHostname(hostname) {
110
110
  return name;
111
111
  }
112
112
 
113
- function init(args) {
114
- const { server, call } = args;
115
-
116
- // The path Let's Encrypt fetches to validate a domain, and the only unauthenticated route on
117
- // this module. It lives here rather than in the routes-ui monolith because it is part of the
118
- // certificate story, and because the preflight probe below shares its token store.
113
+ // The path Let's Encrypt fetches to validate a domain, and the only unauthenticated route on
114
+ // this module. It lives here rather than in the routes-ui monolith because it is part of the
115
+ // certificate story, and because the preflight probe below shares its token store.
116
+ function registerAcmeChallenge(server) {
119
117
  server.route({
120
118
  method: 'GET',
121
119
  path: '/.well-known/acme-challenge/{token}',
@@ -157,6 +155,10 @@ Token: ${JSON.stringify(request.params.token)}`
157
155
  auth: false
158
156
  }
159
157
  });
158
+ }
159
+
160
+ function registerTlsSettingsPage(server, args) {
161
+ const { call } = args;
160
162
 
161
163
  registerSettingsPage(server, {
162
164
  path: TLS_PAGE,
@@ -185,12 +187,16 @@ Token: ${JSON.stringify(request.params.token)}`
185
187
  await maybeReloadTlsCertificates(call, request.logger, changed ? ['tlsProvisioning'] : [], { action: 'settings' });
186
188
  }
187
189
  });
190
+ }
191
+
192
+ // Hostnames are rows of the certificate table, added and removed one at a time. Each write
193
+ // reloads the listeners: they resolve their material against the hostname list, and the
194
+ // self-signed fallback is regenerated when that list no longer matches what it covers. Without
195
+ // the reload a name added here is served the previous certificate until something else restarts
196
+ // the worker, and the page would report a certificate the listener is not using.
197
+ function registerPostConfigTlsHostnames(server, args) {
198
+ const { call } = args;
188
199
 
189
- // Hostnames are rows of the certificate table, added and removed one at a time. Each write
190
- // reloads the listeners: they resolve their material against the hostname list, and the
191
- // self-signed fallback is regenerated when that list no longer matches what it covers. Without
192
- // the reload a name added here is served the previous certificate until something else restarts
193
- // the worker, and the page would report a certificate the listener is not using.
194
200
  server.route({
195
201
  method: 'POST',
196
202
  path: '/admin/config/tls/hostnames',
@@ -235,6 +241,10 @@ Token: ${JSON.stringify(request.params.token)}`
235
241
  }
236
242
  }
237
243
  });
244
+ }
245
+
246
+ function registerPostConfigTlsHostnamesDelete(server, args) {
247
+ const { call } = args;
238
248
 
239
249
  server.route({
240
250
  method: 'POST',
@@ -290,11 +300,15 @@ Token: ${JSON.stringify(request.params.token)}`
290
300
  }
291
301
  }
292
302
  });
303
+ }
304
+
305
+ // Which certificate each listener presents by default. One form for the three listeners,
306
+ // posted with a Save button rather than on change: a wrong default is what a client sees on
307
+ // its next handshake, and three dropdowns that each reload every listener the moment they are
308
+ // touched is three chances to do that by accident.
309
+ function registerPostConfigTlsListeners(server, args) {
310
+ const { call } = args;
293
311
 
294
- // Which certificate each listener presents by default. One form for the three listeners,
295
- // posted with a Save button rather than on change: a wrong default is what a client sees on
296
- // its next handshake, and three dropdowns that each reload every listener the moment they are
297
- // touched is three chances to do that by accident.
298
312
  server.route({
299
313
  method: 'POST',
300
314
  path: '/admin/config/tls/listeners',
@@ -358,7 +372,9 @@ Token: ${JSON.stringify(request.params.token)}`
358
372
  }
359
373
  }
360
374
  });
375
+ }
361
376
 
377
+ function registerGetUploadPage(server) {
362
378
  server.route({
363
379
  method: 'GET',
364
380
  path: UPLOAD_PAGE,
@@ -375,7 +391,9 @@ Token: ${JSON.stringify(request.params.token)}`
375
391
  );
376
392
  }
377
393
  });
394
+ }
378
395
 
396
+ function registerPostConfigTlsRequest(server) {
379
397
  server.route({
380
398
  method: 'POST',
381
399
  path: '/admin/config/tls/request',
@@ -410,7 +428,9 @@ Token: ${JSON.stringify(request.params.token)}`
410
428
  }
411
429
  }
412
430
  });
431
+ }
413
432
 
433
+ function registerPostConfigTlsPreflight(server) {
414
434
  server.route({
415
435
  method: 'POST',
416
436
  path: '/admin/config/tls/preflight',
@@ -434,6 +454,10 @@ Token: ${JSON.stringify(request.params.token)}`
434
454
  }
435
455
  }
436
456
  });
457
+ }
458
+
459
+ function registerPostConfigTlsUpload(server, args) {
460
+ const { call } = args;
437
461
 
438
462
  server.route({
439
463
  method: 'POST',
@@ -488,6 +512,10 @@ Token: ${JSON.stringify(request.params.token)}`
488
512
  }
489
513
  }
490
514
  });
515
+ }
516
+
517
+ function registerPostConfigTlsDelete(server, args) {
518
+ const { call } = args;
491
519
 
492
520
  server.route({
493
521
  method: 'POST',
@@ -549,6 +577,21 @@ Token: ${JSON.stringify(request.params.token)}`
549
577
  });
550
578
  }
551
579
 
580
+ function init(args) {
581
+ const { server } = args;
582
+
583
+ registerAcmeChallenge(server);
584
+ registerTlsSettingsPage(server, args);
585
+ registerPostConfigTlsHostnames(server, args);
586
+ registerPostConfigTlsHostnamesDelete(server, args);
587
+ registerPostConfigTlsListeners(server, args);
588
+ registerGetUploadPage(server);
589
+ registerPostConfigTlsRequest(server);
590
+ registerPostConfigTlsPreflight(server);
591
+ registerPostConfigTlsUpload(server, args);
592
+ registerPostConfigTlsDelete(server, args);
593
+ }
594
+
552
595
  /**
553
596
  * The whole page model: the certificate for every configured name, every certificate the instance
554
597
  * holds, and the listeners with the default each is set to and what each is serving right now.
@@ -10,10 +10,13 @@ const Boom = require('@hapi/boom');
10
10
  const { Account } = require('../account');
11
11
  const { redis } = require('../db');
12
12
  const { lists } = require('../lists');
13
- const { parseSignedFormData } = require('../tools');
13
+ const { parseSignedFormData, SIGNING_PURPOSE } = require('../tools');
14
14
  const { isClientError } = require('./route-helpers');
15
15
  const { signedFormBlobFields } = require('../schemas');
16
16
 
17
+ // the links are signed with the unsubscribe key, see verifyServiceSignature()
18
+ const UNSUBSCRIBE_BLOB = { purpose: SIGNING_PURPOSE.UNSUBSCRIBE };
19
+
17
20
  function init(args) {
18
21
  const { server, call } = args;
19
22
 
@@ -23,7 +26,7 @@ function init(args) {
23
26
  async handler(request, h) {
24
27
  // Verify the HMAC signature over the signed payload before acting on it, and read every
25
28
  // field from the signed data - never from unsigned query input (security review M7).
26
- let data = await parseSignedFormData(redis, { data: request.query.data, sig: request.query.sig }, request.app.gt);
29
+ let data = await parseSignedFormData(redis, { data: request.query.data, sig: request.query.sig }, request.app.gt, UNSUBSCRIBE_BLOB);
27
30
 
28
31
  if (!data || typeof data !== 'object' || data.act !== 'unsub') {
29
32
  // A validly signed blob of another type is the client's problem, not a server
@@ -92,7 +95,7 @@ function init(args) {
92
95
  try {
93
96
  // Verify the signature and read account/list/recipient from the SIGNED payload -
94
97
  // never from client-supplied fields - so subscribe/unsubscribe cannot be forged (M7).
95
- signed = await parseSignedFormData(redis, { data: request.payload.data, sig: request.payload.sig }, request.app.gt);
98
+ signed = await parseSignedFormData(redis, { data: request.payload.data, sig: request.payload.sig }, request.app.gt, UNSUBSCRIBE_BLOB);
96
99
 
97
100
  if (!signed || typeof signed !== 'object' || signed.act !== 'unsub') {
98
101
  signed = null;