emailengine-app 2.84.0 → 2.84.2

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 (93) hide show
  1. package/.dockerignore +6 -0
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +35 -0
  4. package/Dockerfile +2 -2
  5. package/bin/emailengine.js +15 -0
  6. package/data/google-crawlers.json +1 -1
  7. package/docker-compose.yml +1 -1
  8. package/lib/account/own-account-key.js +42 -0
  9. package/lib/account-assignment.js +1 -33
  10. package/lib/account.js +32 -19
  11. package/lib/add-trackers.js +11 -4
  12. package/lib/api-routes/account-routes.js +67 -14
  13. package/lib/api-routes/gateway-routes.js +9 -3
  14. package/lib/api-routes/message-routes.js +7 -1
  15. package/lib/api-routes/mint-bounds.js +11 -0
  16. package/lib/api-routes/route-helpers.js +125 -3
  17. package/lib/api-routes/submit-routes.js +4 -2
  18. package/lib/auth-token.js +23 -10
  19. package/lib/bounce-detect.js +17 -5
  20. package/lib/consts.js +34 -0
  21. package/lib/create-imap-client.js +41 -2
  22. package/lib/email-client/base-client.js +20 -10
  23. package/lib/email-client/gmail-client.js +21 -7
  24. package/lib/email-client/imap/mailbox.js +10 -4
  25. package/lib/email-client/imap/response-metrics.js +75 -0
  26. package/lib/email-client/imap-client.js +5 -2
  27. package/lib/email-client/message-builder.js +7 -2
  28. package/lib/email-client/outlook/graph-api.js +17 -2
  29. package/lib/email-client/outlook-client.js +6 -3
  30. package/lib/email-client/smtp-pool-manager.js +6 -0
  31. package/lib/encrypt.js +9 -0
  32. package/lib/export.js +3 -1
  33. package/lib/get-raw-email.js +4 -2
  34. package/lib/imap-proxy-auth.js +14 -1
  35. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +1 -0
  36. package/lib/imapproxy/imap-core/lib/commands/login.js +1 -0
  37. package/lib/imapproxy/imap-core/lib/imap-command.js +86 -43
  38. package/lib/imapproxy/imap-core/lib/imap-stream.js +58 -13
  39. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +3 -1
  40. package/lib/mcp/listen.js +10 -1
  41. package/lib/oauth/external-account-config.js +3 -1
  42. package/lib/oauth/gmail.js +21 -48
  43. package/lib/oauth/mail-ru.js +5 -38
  44. package/lib/oauth/outlook.js +26 -44
  45. package/lib/pbkdf2-phc.js +18 -1
  46. package/lib/privileged-settings.js +6 -3
  47. package/lib/redis-scan-delete.js +15 -1
  48. package/lib/schemas.js +78 -32
  49. package/lib/settings.js +13 -1
  50. package/lib/smtp-auth.js +23 -0
  51. package/lib/tools.js +245 -56
  52. package/lib/ui-routes/account-routes.js +16 -37
  53. package/lib/ui-routes/admin-config-routes.js +10 -38
  54. package/lib/ui-routes/admin-entities-routes.js +22 -24
  55. package/lib/ui-routes/auth-routes.js +47 -24
  56. package/lib/ui-routes/connection-security-form.js +74 -0
  57. package/lib/ui-routes/form-lists.js +46 -0
  58. package/lib/ui-routes/mcp-consent-routes.js +5 -1
  59. package/lib/ui-routes/oauth-config-routes.js +9 -18
  60. package/lib/ui-routes/sign-in-helpers.js +59 -0
  61. package/lib/ui-routes/unsubscribe-routes.js +6 -3
  62. package/lib/utils/map-concurrent.js +36 -0
  63. package/lib/utils/network.js +28 -0
  64. package/lib/utils/provider-id.js +27 -0
  65. package/lib/utils/require-tls.js +33 -0
  66. package/lib/web-safe-html.js +5 -6
  67. package/lib/webhook-penalty.js +75 -0
  68. package/lib/webhook-routing.js +22 -2
  69. package/package.json +21 -21
  70. package/sbom.json +1 -1
  71. package/server.js +74 -38
  72. package/static/js/ace/ace.js +1 -1
  73. package/static/js/ace/mode-handlebars.js +1 -1
  74. package/static/js/ace/mode-html.js +1 -1
  75. package/static/js/ace/mode-javascript.js +1 -1
  76. package/static/js/ace/mode-markdown.js +1 -1
  77. package/static/js/ace/worker-html.js +1 -1
  78. package/static/js/ace/worker-javascript.js +1 -1
  79. package/static/js/ace/worker-json.js +1 -1
  80. package/static/js/ee-client.js +5 -0
  81. package/static/licenses.html +23 -23
  82. package/translations/messages.pot +66 -66
  83. package/views/account/security.hbs +10 -0
  84. package/views/accounts/account.hbs +11 -11
  85. package/views/accounts/edit.hbs +6 -2
  86. package/views/partials/gateway_form.hbs +3 -1
  87. package/workers/api.js +43 -3
  88. package/workers/webhooks.js +39 -3
  89. package/config/test.toml +0 -46
  90. package/install.sh +0 -428
  91. package/setup-production.sh +0 -215
  92. package/systemd/emailengine.service +0 -97
  93. package/systemd/nginx-proxy.conf +0 -77
@@ -53,6 +53,7 @@ const TOOL_BADGES = {
53
53
  const { locales } = require('../translations');
54
54
  const { settingsSchema, formBoolean } = require('../schemas');
55
55
  const { getExampleDocumentsPayloads, mcpToolGrants } = require('./route-helpers');
56
+ const { parseCustomHeaders } = require('./form-lists');
56
57
  const { getOpenAiModels, reasoningEffortOptions, aiPageSchema, aiFieldSchema, aiFieldValues, aiFieldStrings } = require('./ai-options');
57
58
  const { DEFAULT_INSTRUCTIONS, DEFAULT_MODEL, DEFAULT_MAX_TOKENS } = require('@postalsys/email-ai-tools');
58
59
 
@@ -275,24 +276,6 @@ function init(args) {
275
276
  },
276
277
 
277
278
  async applySettings(request) {
278
- let customHeaders = request.payload.customHeaders
279
- .split(/[\r\n]+/)
280
- .map(header => header.trim())
281
- .filter(header => header)
282
- .map(line => {
283
- let sep = line.indexOf(':');
284
- if (sep >= 0) {
285
- return {
286
- key: line.substring(0, sep).trim(),
287
- value: line.substring(sep + 1).trim()
288
- };
289
- }
290
- return {
291
- key: line,
292
- value: ''
293
- };
294
- });
295
-
296
279
  const data = {
297
280
  webhooksEnabled: request.payload.webhooksEnabled,
298
281
  webhooks: request.payload.webhooks,
@@ -312,11 +295,14 @@ function init(args) {
312
295
  notifyHeaders: (request.payload.notifyHeaders || '')
313
296
  .split(/\r?\n/)
314
297
  .map(line => line.toLowerCase().trim())
315
- .filter(line => line),
316
-
317
- webhooksCustomHeaders: customHeaders
298
+ .filter(line => line)
318
299
  };
319
300
 
301
+ // Absent only from a request that did not render the field, keep the stored headers then
302
+ if (typeof request.payload.customHeaders === 'string') {
303
+ data.webhooksCustomHeaders = parseCustomHeaders(request.payload.customHeaders);
304
+ }
305
+
320
306
  if (request.payload.notifyAll) {
321
307
  data.webhookEvents.push('*');
322
308
  }
@@ -861,6 +847,8 @@ function init(args) {
861
847
  try {
862
848
  request.logger.info({ msg: 'Reload models' });
863
849
 
850
+ // without a key in the form the stored key is used, and then the URL has to be the
851
+ // stored one as well; aiRequestOptions() in server.js refuses the other case
864
852
  const { models } = await call({
865
853
  cmd: 'openAiListModels',
866
854
  data: {
@@ -1160,23 +1148,7 @@ function init(args) {
1160
1148
  headers.Authorization = authorization;
1161
1149
  }
1162
1150
 
1163
- let customHeaders = request.payload.customHeaders
1164
- .split(/[\r\n]+/)
1165
- .map(header => header.trim())
1166
- .filter(header => header)
1167
- .map(line => {
1168
- let sep = line.indexOf(':');
1169
- if (sep >= 0) {
1170
- return {
1171
- key: line.substring(0, sep).trim(),
1172
- value: line.substring(sep + 1).trim()
1173
- };
1174
- }
1175
- return {
1176
- key: line,
1177
- value: ''
1178
- };
1179
- });
1151
+ let customHeaders = parseCustomHeaders(request.payload.customHeaders);
1180
1152
 
1181
1153
  customHeaders.forEach(header => {
1182
1154
  headers[header.key] = header.value;
@@ -9,6 +9,7 @@ const { redis } = require('../db');
9
9
  const getSecret = require('../get-secret');
10
10
  const { failAction, verifyAccountInfo, formatPartialSecretKey } = require('../tools');
11
11
  const { templateSchemas, accountIdSchema, tokenPermissionsSchema, formBoolean, mailboxAddressSchema } = require('../schemas');
12
+ const { requireTlsFormField } = require('./connection-security-form');
12
13
  const tokenPermissionView = require('../token-permission-view');
13
14
  const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
14
15
  const { Account, accountExists, accountSummary } = require('../account');
@@ -28,6 +29,7 @@ const {
28
29
  submittedValues,
29
30
  windowedPageLinks
30
31
  } = require('./route-helpers');
32
+ const { parseCustomHeaders } = require('./form-lists');
31
33
  const exampleWebhookPayloads = require('../payload-examples-webhooks.json');
32
34
 
33
35
  const { DEFAULT_PAGE_SIZE } = consts;
@@ -1550,7 +1552,9 @@ return payload;`)
1550
1552
  {
1551
1553
  pageTitle: 'Gateways',
1552
1554
  menuGateways: true,
1553
- wellKnownServices: JSON.stringify(Object.keys(wellKnownServices).map(key => Object.assign({ key }, wellKnownServices[key])))
1555
+ wellKnownServices: JSON.stringify(Object.keys(wellKnownServices).map(key => Object.assign({ key }, wellKnownServices[key]))),
1556
+ // a new gateway requires STARTTLS unless the operator unticks it
1557
+ values: { requireTLS: true }
1554
1558
  },
1555
1559
  {
1556
1560
  layout: 'app'
@@ -1631,7 +1635,8 @@ return payload;`)
1631
1635
  pageTitle: 'Gateways',
1632
1636
  menuGateways: true,
1633
1637
  wellKnownServices: JSON.stringify(Object.keys(wellKnownServices).map(key => Object.assign({ key }, wellKnownServices[key]))),
1634
- values: gatewayData,
1638
+ // STARTTLS is required unless the stored gateway says otherwise
1639
+ values: Object.assign({}, gatewayData, { requireTLS: gatewayData.requireTLS !== false }),
1635
1640
  gatewayData,
1636
1641
  hasSMTPPass
1637
1642
  },
@@ -1672,6 +1677,7 @@ return payload;`)
1672
1677
  host: request.payload.host || null,
1673
1678
  port: request.payload.port || null,
1674
1679
  secure: request.payload.secure || null,
1680
+ requireTLS: request.payload.requireTLS,
1675
1681
  user: request.payload.user || null,
1676
1682
  pass: request.payload.pass || null,
1677
1683
  tls: {}
@@ -1766,7 +1772,8 @@ return payload;`)
1766
1772
  .label('Port')
1767
1773
  .required(),
1768
1774
 
1769
- secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS')
1775
+ secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS'),
1776
+ requireTLS: requireTlsFormField()
1770
1777
  })
1771
1778
  }
1772
1779
  }
@@ -1783,6 +1790,7 @@ return payload;`)
1783
1790
  host: request.payload.host || null,
1784
1791
  port: request.payload.port || null,
1785
1792
  secure: request.payload.secure || null,
1793
+ requireTLS: request.payload.requireTLS,
1786
1794
  user: request.payload.user || null
1787
1795
  };
1788
1796
 
@@ -1892,7 +1900,8 @@ return payload;`)
1892
1900
  .label('Port')
1893
1901
  .required(),
1894
1902
 
1895
- secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS')
1903
+ secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS'),
1904
+ requireTLS: requireTlsFormField()
1896
1905
  })
1897
1906
  }
1898
1907
  }
@@ -1902,14 +1911,17 @@ return payload;`)
1902
1911
  method: 'POST',
1903
1912
  path: '/admin/gateways/test',
1904
1913
  async handler(request) {
1905
- let { gateway, host, port, user, pass, secure } = request.payload;
1914
+ let { gateway, host, port, user, pass, secure, requireTLS } = request.payload;
1906
1915
 
1907
1916
  try {
1908
1917
  if (user && !pass && gateway) {
1909
1918
  let gatewayObject = new Gateway({ gateway, redis, secret: await getSecret() });
1910
1919
  try {
1911
1920
  let gatewayData = await gatewayObject.loadGatewayData();
1912
- if (gatewayData) {
1921
+ // The stored password is only ever sent to the server it was stored for:
1922
+ // the form names any host it likes, and a write-only secret must not be
1923
+ // extractable by pointing the test at one's own server
1924
+ if (gatewayData && gatewayData.host === host && Number(gatewayData.port) === Number(port) && gatewayData.user === user) {
1913
1925
  pass = gatewayData.pass || '';
1914
1926
  }
1915
1927
  } catch (err) {
@@ -1922,6 +1934,7 @@ return payload;`)
1922
1934
  host,
1923
1935
  port,
1924
1936
  secure,
1937
+ requireTLS,
1925
1938
  auth:
1926
1939
  user || pass
1927
1940
  ? {
@@ -2002,7 +2015,8 @@ return payload;`)
2002
2015
  .example(465)
2003
2016
  .description('Service port number')
2004
2017
  .label('Port'),
2005
- secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS')
2018
+ secure: formBoolean().default(false).example(true).description('Should connection use TLS. Usually true for port 465').label('TLS'),
2019
+ requireTLS: requireTlsFormField()
2006
2020
  })
2007
2021
  }
2008
2022
  }
@@ -2496,23 +2510,7 @@ function parseWebhookForm(payload) {
2496
2510
  }
2497
2511
  }
2498
2512
 
2499
- let customHeaders = payload.customHeaders
2500
- .split(/[\r\n]+/)
2501
- .map(header => header.trim())
2502
- .filter(header => header)
2503
- .map(line => {
2504
- let sep = line.indexOf(':');
2505
- if (sep >= 0) {
2506
- return {
2507
- key: line.substring(0, sep).trim(),
2508
- value: line.substring(sep + 1).trim()
2509
- };
2510
- }
2511
- return {
2512
- key: line,
2513
- value: ''
2514
- };
2515
- });
2513
+ let customHeaders = parseCustomHeaders(payload.customHeaders);
2516
2514
 
2517
2515
  return { contentFn: scripts.contentFn, contentMap: scripts.contentMap, customHeaders };
2518
2516
  }
@@ -34,6 +34,8 @@ const passkeys = require('../passkeys');
34
34
  const sso = require('../sso');
35
35
  const { redis } = require('../db');
36
36
  const { windowBudget, reserveAttempts, releaseAttempts, incrementCounter } = require('../rate-limit');
37
+ const { reserveLoginAttempt, upgradePasswordHash } = require('./sign-in-helpers');
38
+ const { budgetAddress } = require('../utils/network');
37
39
 
38
40
  const { LOGIN_PERIOD_TTL, TOTP_WINDOW_SIZE, REDIS_PREFIX } = consts;
39
41
 
@@ -136,22 +138,28 @@ async function verifyAdminPassword(hash, password, logger) {
136
138
  // because the caller is already authenticated as it, and with the login form's per-username
137
139
  // budget. Owns the limiter and the warn logs; the caller decides how to report the failure.
138
140
  //
139
- // @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid' }>}
141
+ // @returns {Promise<{ ok: true } | { ok: false, reason: 'rateLimited' | 'invalid', message: String }>}
140
142
  async function verifyCurrentPassword(request, h, authData, password) {
141
143
  let rateLimit = await h.checkRateLimit(`password:verify:${authData.user || 'admin'}`, 1, 10, 60);
142
144
  if (!rateLimit.success) {
143
145
  request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
144
- return { ok: false, reason: 'rateLimited' };
146
+ return { ok: false, reason: 'rateLimited', message: 'Rate limited, please wait and try again' };
145
147
  }
146
148
 
147
149
  if (!(await verifyAdminPassword(authData.password, password, request.logger))) {
148
150
  request.logger.warn({ msg: 'Invalid current password', remoteAddress: request.app.ip });
149
- return { ok: false, reason: 'invalid' };
151
+ return { ok: false, reason: 'invalid', message: 'Invalid password' };
150
152
  }
151
153
 
152
154
  return { ok: true };
153
155
  }
154
156
 
157
+ // Sends a refused step-down action on the security page back to the page with the reason
158
+ async function refuseSecurityAction(request, h, verified) {
159
+ await request.flash({ type: 'danger', message: verified.message });
160
+ return h.redirect(`/admin/account/security`);
161
+ }
162
+
155
163
  // Counts a failed second-factor code against the password-stage session that submitted it, keyed
156
164
  // on the session's random sid. An exact counter rather than a rate-limit bucket, because the
157
165
  // session is ended on a count, not throttled over a window. Returns the failures so far.
@@ -324,7 +332,7 @@ function init(args) {
324
332
  return h.redirect('/admin/login');
325
333
  }
326
334
  try {
327
- let ipRateLimit = await h.checkRateLimit(`login:ip:${request.app.ip}`, 1, 30, 60);
335
+ let ipRateLimit = await h.checkRateLimit(`login:ip:${budgetAddress(request.app.ip)}`, 1, 30, 60);
328
336
  if (!ipRateLimit.success) {
329
337
  request.logger.warn({ msg: 'Rate limited', ipRateLimit, remoteAddress: request.app.ip });
330
338
  let err = new Error('Rate limited, please wait and try again');
@@ -332,9 +340,10 @@ function init(args) {
332
340
  throw err;
333
341
  }
334
342
 
335
- let rateLimit = await h.checkRateLimit(`login:${request.payload.username}`, 1, 10, 60);
336
- if (!rateLimit.success) {
337
- request.logger.warn({ msg: 'Rate limited', rateLimit, remoteAddress: request.app.ip });
343
+ // The per-account budget counts failures only (see lib/ui-routes/sign-in-helpers.js)
344
+ const attempt = await reserveLoginAttempt(request.payload.username);
345
+ if (!attempt.admitted) {
346
+ request.logger.warn({ msg: 'Rate limited', key: attempt.key, remoteAddress: request.app.ip });
338
347
  let err = new Error('Rate limited, please wait and try again');
339
348
  err.responseText = err.message;
340
349
  throw err;
@@ -362,6 +371,9 @@ function init(args) {
362
371
  throw err;
363
372
  }
364
373
 
374
+ // a hash written with older parameters is replaced now that the password is known
375
+ await upgradePasswordHash(authData, request.payload.password, request.logger);
376
+
365
377
  setAdminSession(request, {
366
378
  user: authData.user,
367
379
  requireTotp: totpEnabled,
@@ -374,6 +386,9 @@ function init(args) {
374
386
  }
375
387
  }
376
388
 
389
+ // accepted, so the attempt reserved above is not a failure
390
+ attempt.release().catch(err => request.logger.warn({ msg: 'Failed to release a login attempt', err }));
391
+
377
392
  request.logger.info({ msg: 'Admin login successful', user: authData.user, method: 'password', remoteAddress: request.app.ip });
378
393
 
379
394
  if (totpEnabled) {
@@ -885,6 +900,18 @@ function init(args) {
885
900
  return h.redirect(`/admin/account/security`);
886
901
  }
887
902
 
903
+ // Switching the second factor on bumps the password version, which ends every
904
+ // other session and leaves only this one signed in. A hijacked session could lock
905
+ // the real admin out that way, so like the step down, the password change and a
906
+ // passkey registration, it asks for the password again
907
+ let authData = await settings.get('authData');
908
+ if (authData && authData.password) {
909
+ let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
910
+ if (!verified.ok) {
911
+ return refuseSecurityAction(request, h, verified);
912
+ }
913
+ }
914
+
888
915
  let verified = verifyTotp(totpSeed, request.payload.code, { window: TOTP_WINDOW_SIZE });
889
916
 
890
917
  if (!verified) {
@@ -894,7 +921,6 @@ function init(args) {
894
921
 
895
922
  await settings.set('totpEnabled', true);
896
923
 
897
- let authData = await settings.get('authData');
898
924
  if (authData) {
899
925
  authData.passwordVersion = Date.now();
900
926
  await settings.set('authData', authData);
@@ -929,7 +955,8 @@ function init(args) {
929
955
 
930
956
  payload: Joi.object({
931
957
  type: Joi.string().valid('totp').description('The type of the two-factor authentication method').required(),
932
- code: Joi.string().min(6).max(6).description('6-digit TOTP code').required()
958
+ code: Joi.string().min(6).max(6).description('6-digit TOTP code').required(),
959
+ password: Joi.string().max(256).empty('').description('The current account password')
933
960
  })
934
961
  }
935
962
  }
@@ -952,11 +979,7 @@ function init(args) {
952
979
  if (authData && authData.password) {
953
980
  let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
954
981
  if (!verified.ok) {
955
- await request.flash({
956
- type: 'danger',
957
- message: verified.reason === 'rateLimited' ? `Rate limited, please wait and try again` : `Invalid password`
958
- });
959
- return h.redirect(`/admin/account/security`);
982
+ return refuseSecurityAction(request, h, verified);
960
983
  }
961
984
  }
962
985
 
@@ -1068,7 +1091,7 @@ function init(args) {
1068
1091
  path: '/admin/account/passkeys/register/options',
1069
1092
  async handler(request, h) {
1070
1093
  try {
1071
- let rateLimit = await h.checkRateLimit(`passkey:register:${request.app.ip}`, 1, 10, 60);
1094
+ let rateLimit = await h.checkRateLimit(`passkey:register:${budgetAddress(request.app.ip)}`, 1, 10, 60);
1072
1095
  if (!rateLimit.success) {
1073
1096
  return h.response({ error: 'Rate limited, please wait and try again' }).code(429);
1074
1097
  }
@@ -1141,7 +1164,7 @@ function init(args) {
1141
1164
  path: '/admin/account/passkeys/register/verify',
1142
1165
  async handler(request, h) {
1143
1166
  try {
1144
- let rateLimit = await h.checkRateLimit(`passkey:register:${request.app.ip}`, 1, 10, 60);
1167
+ let rateLimit = await h.checkRateLimit(`passkey:register:${budgetAddress(request.app.ip)}`, 1, 10, 60);
1145
1168
  if (!rateLimit.success) {
1146
1169
  return h.response({ error: 'Rate limited, please wait and try again' }).code(429);
1147
1170
  }
@@ -1162,9 +1185,11 @@ function init(args) {
1162
1185
  // over the challenge namespacing - a future third way to obtain a registration
1163
1186
  // challenge would otherwise reopen the bypass. Checked before the challenge is
1164
1187
  // consumed, so a mistyped password does not burn the nonce and force the whole
1165
- // ceremony to be repeated.
1166
- if (!(await verifyAdminPassword(authData.password, request.payload.password, request.logger))) {
1167
- return h.response({ error: 'Invalid password' }).code(403);
1188
+ // ceremony to be repeated. Through the same per-account budget as the password
1189
+ // change, so a hijacked session gets no second password-guessing surface here
1190
+ let verified = await verifyCurrentPassword(request, h, authData, request.payload.password);
1191
+ if (!verified.ok) {
1192
+ return h.response({ error: verified.message }).code(verified.reason === 'rateLimited' ? 429 : 403);
1168
1193
  }
1169
1194
 
1170
1195
  let challenge = await passkeys.consumeChallenge(request.payload.challengeId, passkeys.CHALLENGE_REGISTER);
@@ -1299,7 +1324,7 @@ function init(args) {
1299
1324
  return h.response({ error: 'sso_required' }).code(403);
1300
1325
  }
1301
1326
  try {
1302
- let rateLimit = await h.checkRateLimit(`passkey:auth:options:${request.app.ip}`, 1, 10, 60);
1327
+ let rateLimit = await h.checkRateLimit(`passkey:auth:options:${budgetAddress(request.app.ip)}`, 1, 10, 60);
1303
1328
  if (!rateLimit.success) {
1304
1329
  return h.response({ error: 'Rate limited, please wait and try again' }).code(429);
1305
1330
  }
@@ -1362,7 +1387,7 @@ function init(args) {
1362
1387
  return h.response({ error: 'sso_required' }).code(403);
1363
1388
  }
1364
1389
  try {
1365
- let rateLimit = await h.checkRateLimit(`passkey:auth:verify:${request.app.ip}`, 1, 10, 60);
1390
+ let rateLimit = await h.checkRateLimit(`passkey:auth:verify:${budgetAddress(request.app.ip)}`, 1, 10, 60);
1366
1391
  if (!rateLimit.success) {
1367
1392
  return h.response({ error: 'Rate limited, please wait and try again' }).code(429);
1368
1393
  }
@@ -1508,9 +1533,7 @@ function init(args) {
1508
1533
  if (hasExistingPassword) {
1509
1534
  let verified = await verifyCurrentPassword(request, h, authData, request.payload.password0);
1510
1535
  if (!verified.ok) {
1511
- let err = new Error(
1512
- verified.reason === 'rateLimited' ? 'Rate limited, please wait and try again' : 'Failed to verify current password'
1513
- );
1536
+ let err = new Error(verified.message);
1514
1537
  err.details = { password0: err.message };
1515
1538
  throw err;
1516
1539
  }
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+
3
+ // The two connection-security checkboxes of the admin account form, for the IMAP and the SMTP
4
+ // section alike: "Allow invalid certificates" (`tls.rejectUnauthorized`) and "Require STARTTLS"
5
+ // (`requireTLS`, see lib/create-imap-client.js and lib/utils/require-tls.js). The schema,
6
+ // rendering and saving are each written once here, because the two sections used to carry their
7
+ // own copies of the same four comparisons. The gateway forms share the STARTTLS field.
8
+ //
9
+ // A value is written only when the effective state changes: an untouched form save must not add
10
+ // keys to the stored connection object, since any imap diff forces a reconnect.
11
+
12
+ const { formBoolean } = require('../schemas');
13
+
14
+ // required unless the stored object says otherwise
15
+ const storedRequireTls = stored => !(stored && stored.requireTLS === false);
16
+
17
+ /**
18
+ * The "Require STARTTLS" checkbox of a form, unticked when the field is absent.
19
+ *
20
+ * @returns {Object} joi schema
21
+ */
22
+ function requireTlsFormField() {
23
+ return formBoolean().default(false).example(true).description('Require STARTTLS when direct TLS is off').label('RequireTLS');
24
+ }
25
+
26
+ /**
27
+ * The form fields of the two checkboxes for one section.
28
+ *
29
+ * @param {String} prefix - 'imap' or 'smtp', the form field prefix
30
+ * @returns {Object} joi schemas, to spread into the form's payload schema
31
+ */
32
+ function securityFormFields(prefix) {
33
+ return {
34
+ [`${prefix}_requireTLS`]: requireTlsFormField(),
35
+ [`${prefix}_tls_ignoreCertErrors`]: formBoolean()
36
+ .default(false)
37
+ .example(false)
38
+ .description('Allow connections to servers with invalid TLS certificates for this account')
39
+ };
40
+ }
41
+
42
+ /**
43
+ * The form values of the two checkboxes for one section.
44
+ *
45
+ * @param {String} prefix - 'imap' or 'smtp', the form field prefix
46
+ * @param {Object} [stored] - the stored connection object
47
+ * @returns {Object} `<prefix>_tls_ignoreCertErrors` and `<prefix>_requireTLS`
48
+ */
49
+ function securityFormValues(prefix, stored) {
50
+ return {
51
+ [`${prefix}_tls_ignoreCertErrors`]: !!(stored && stored.tls && stored.tls.rejectUnauthorized === false),
52
+ [`${prefix}_requireTLS`]: storedRequireTls(stored)
53
+ };
54
+ }
55
+
56
+ /**
57
+ * Applies the two checkboxes of a submitted form to the update of one section.
58
+ *
59
+ * @param {Object} payload - the validated form payload
60
+ * @param {String} prefix - 'imap' or 'smtp'
61
+ * @param {Object} [stored] - the stored connection object
62
+ * @param {Object} target - the object the section's update keys are collected on
63
+ * @param {Object} tls - the tls object being built for the update (the stored one, or empty)
64
+ */
65
+ function applySecurityForm(payload, prefix, stored, target, tls) {
66
+ if (payload[`${prefix}_tls_ignoreCertErrors`] !== (tls.rejectUnauthorized === false)) {
67
+ tls.rejectUnauthorized = !payload[`${prefix}_tls_ignoreCertErrors`];
68
+ }
69
+ if (payload[`${prefix}_requireTLS`] !== storedRequireTls(stored)) {
70
+ target.requireTLS = payload[`${prefix}_requireTLS`];
71
+ }
72
+ }
73
+
74
+ module.exports = { requireTlsFormField, securityFormFields, securityFormValues, applySecurityForm };
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ // Parsers for the admin form textareas that hold one entry per line. Dependency-free, so any
4
+ // lib/ui-routes module can use them without pulling in route-helpers.js. A missing field parses
5
+ // as an empty list, so a handler updating a stored value checks the field was sent first.
6
+
7
+ /**
8
+ * Parses the "Custom headers" textarea of the webhook forms, one `Name: value` per line, into
9
+ * the `{ key, value }` list the webhooksCustomHeaders setting stores. A line without a colon is
10
+ * a header with an empty value. A missing field parses as no headers.
11
+ *
12
+ * @param {string} [text] - the submitted textarea value
13
+ * @returns {Array<{key: string, value: string}>}
14
+ */
15
+ function parseCustomHeaders(text) {
16
+ return (text || '')
17
+ .split(/[\r\n]+/)
18
+ .map(header => header.trim())
19
+ .filter(header => header)
20
+ .map(line => {
21
+ let sep = line.indexOf(':');
22
+ if (sep >= 0) {
23
+ return {
24
+ key: line.substring(0, sep).trim(),
25
+ value: line.substring(sep + 1).trim()
26
+ };
27
+ }
28
+ return {
29
+ key: line,
30
+ value: ''
31
+ };
32
+ });
33
+ }
34
+
35
+ /**
36
+ * Splits the whitespace separated scope list of the OAuth2 app form. A missing field parses as
37
+ * an empty list.
38
+ *
39
+ * @param {string} [text] - the submitted textarea value
40
+ * @returns {string[]}
41
+ */
42
+ function parseScopeList(text) {
43
+ return (text || '').split(/\s+/).filter(scope => scope);
44
+ }
45
+
46
+ module.exports = { parseCustomHeaders, parseScopeList };
@@ -190,7 +190,8 @@ async function init(args) {
190
190
  return renderError(h, 'This authorization request names a different server as its resource, so it was not meant for this instance.');
191
191
  }
192
192
 
193
- await touchClient(client.client_id);
193
+ // The registration is not refreshed on a render (anyone can open the link, and that
194
+ // let a registration nobody approved outlive the pending-client cap), only on approval
194
195
 
195
196
  // The `scope` parameter is a hint for the starting position of the form, never a
196
197
  // grant: a client asking for `mcp` is asking for mail access, so the mail section
@@ -322,6 +323,9 @@ async function init(args) {
322
323
  });
323
324
  }
324
325
 
326
+ // Approved by an authenticated admin: the registration earns its full lifetime now
327
+ await touchClient(client.client_id);
328
+
325
329
  const code = await createAuthorizationCode({
326
330
  clientId: client.client_id,
327
331
  redirectUri: request.payload.redirect_uri,
@@ -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;
@@ -733,15 +734,8 @@ function init(args) {
733
734
  async handler(request, h) {
734
735
  try {
735
736
  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);
737
+ appData.extraScopes = parseScopeList(appData.extraScopes);
738
+ appData.skipScopes = parseScopeList(appData.skipScopes);
745
739
 
746
740
  if (appData.authority === 'tenant') {
747
741
  appData.authority = appData.tenant;
@@ -904,15 +898,12 @@ function init(args) {
904
898
 
905
899
  try {
906
900
  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);
901
+ // A scope field missing from the request leaves the stored list as it is
902
+ for (let key of ['extraScopes', 'skipScopes']) {
903
+ if (typeof updates[key] === 'string') {
904
+ updates[key] = parseScopeList(updates[key]);
905
+ }
906
+ }
916
907
 
917
908
  if (updates.authority === 'tenant') {
918
909
  updates.authority = updates.tenant;
@@ -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 };