emailengine-app 2.81.2 → 2.82.1

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 (226) hide show
  1. package/.ncurc.js +33 -10
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +71 -0
  4. package/DOCKER_DEPLOYMENT.md +13 -12
  5. package/Dockerfile +2 -0
  6. package/bin/emailengine.js +105 -25
  7. package/config/default.toml +0 -5
  8. package/config/test.toml +0 -5
  9. package/data/google-crawlers.json +1 -1
  10. package/encrypt.js +70 -42
  11. package/getswagger.sh +0 -4
  12. package/lib/account/account-state.js +2 -110
  13. package/lib/account/expected-identity.js +1 -1
  14. package/lib/account-assignment.js +138 -1
  15. package/lib/account.js +289 -869
  16. package/lib/api-reference/index.js +2 -3
  17. package/lib/api-reference/schema-tree.js +53 -3
  18. package/lib/api-routes/account-binding.js +58 -0
  19. package/lib/api-routes/account-routes.js +65 -37
  20. package/lib/api-routes/behavior-notes.js +4 -0
  21. package/lib/api-routes/blocklist-routes.js +2 -2
  22. package/lib/api-routes/bull-board-routes.js +1 -6
  23. package/lib/api-routes/export-routes.js +2 -22
  24. package/lib/api-routes/gateway-routes.js +15 -16
  25. package/lib/api-routes/index.js +1 -13
  26. package/lib/api-routes/mailbox-routes.js +2 -7
  27. package/lib/api-routes/mcp-oauth-routes.js +2 -1
  28. package/lib/api-routes/mcp-routes.js +7 -7
  29. package/lib/api-routes/message-routes.js +50 -238
  30. package/lib/api-routes/mint-bounds.js +110 -0
  31. package/lib/api-routes/oauth2-app-routes.js +23 -32
  32. package/lib/api-routes/operation-impact.js +1 -1
  33. package/lib/api-routes/outbox-routes.js +3 -3
  34. package/lib/api-routes/permission-map.js +1 -7
  35. package/lib/api-routes/route-helpers.js +11 -5
  36. package/lib/api-routes/settings-routes.js +20 -21
  37. package/lib/api-routes/stats-routes.js +1 -1
  38. package/lib/api-routes/submit-routes.js +17 -18
  39. package/lib/api-routes/template-routes.js +4 -9
  40. package/lib/api-routes/token-routes.js +28 -6
  41. package/lib/api-token-scheme.js +71 -0
  42. package/lib/arf-detect.js +33 -6
  43. package/lib/auth-token.js +44 -24
  44. package/lib/autodetect-imap-settings.js +305 -123
  45. package/lib/bounce-detect.js +25 -16
  46. package/lib/calendar-event.js +78 -0
  47. package/lib/consts.js +54 -5
  48. package/lib/create-imap-client.js +24 -0
  49. package/lib/db.js +77 -30
  50. package/lib/delivery-error.js +70 -2
  51. package/lib/egress-fetch.js +54 -3
  52. package/lib/egress-filter.js +11 -0
  53. package/lib/email-client/api-retry.js +147 -0
  54. package/lib/email-client/base-client.js +383 -536
  55. package/lib/email-client/credential-errors.js +21 -5
  56. package/lib/email-client/gmail/gmail-api.js +38 -125
  57. package/lib/email-client/gmail/send-request.js +1 -1
  58. package/lib/email-client/gmail-client.js +77 -51
  59. package/lib/email-client/imap/mailbox.js +158 -324
  60. package/lib/email-client/imap/stale-view.js +109 -0
  61. package/lib/email-client/imap/subconnection.js +46 -9
  62. package/lib/email-client/imap/sync-operations.js +5 -37
  63. package/lib/email-client/imap-client.js +190 -65
  64. package/lib/email-client/message-builder.js +50 -25
  65. package/lib/email-client/notification-handler.js +5 -219
  66. package/lib/email-client/outlook/graph-api.js +147 -126
  67. package/lib/email-client/outlook/send-request.js +10 -4
  68. package/lib/email-client/outlook-client.js +389 -463
  69. package/lib/email-client/smtp-pool-manager.js +3 -2
  70. package/lib/encrypt.js +184 -19
  71. package/lib/enum-descriptions.js +6 -3
  72. package/lib/export.js +141 -41
  73. package/lib/gateway.js +25 -6
  74. package/lib/get-raw-email.js +26 -44
  75. package/lib/get-secret.js +1 -21
  76. package/lib/handlebars-helpers.js +31 -10
  77. package/lib/imap-proxy-auth.js +13 -29
  78. package/lib/imapproxy/imap-core/README.md +1 -0
  79. package/lib/imapproxy/imap-core/lib/handler/imap-parser.js +12 -0
  80. package/lib/imapproxy/imap-core/lib/imap-command.js +74 -10
  81. package/lib/imapproxy/imap-core/lib/imap-connection.js +9 -1
  82. package/lib/imapproxy/imap-core/lib/imap-server.js +112 -26
  83. package/lib/imapproxy/imap-core/lib/imap-stream.js +41 -1
  84. package/lib/imapproxy/imap-core/lib/imap-tools.js +10 -2
  85. package/lib/imapproxy/imap-core/lib/indexer/indexer.js +4 -2
  86. package/lib/imapproxy/imap-server.js +17 -177
  87. package/lib/imapproxy/proxy-handoff.js +235 -0
  88. package/lib/imapproxy/response-error.js +33 -0
  89. package/lib/imapproxy/upstream-client.js +2 -2
  90. package/lib/license-beacon.js +3 -9
  91. package/lib/llm-pre-process.js +182 -43
  92. package/lib/logger.js +1 -1
  93. package/lib/lua/ee-export-queue-add.lua +39 -0
  94. package/lib/lua/ee-get-idempotency.lua +15 -3
  95. package/lib/lua/ee-release-attempts.lua +23 -0
  96. package/lib/lua/ee-reserve-attempts.lua +42 -0
  97. package/lib/lua/h-set-bigger.lua +12 -2
  98. package/lib/lua/s-list-accounts.lua +6 -3
  99. package/lib/mcp/index.js +1 -2
  100. package/lib/mcp/listen.js +221 -18
  101. package/lib/mcp/oauth.js +44 -5
  102. package/lib/mcp/resources.js +8 -2
  103. package/lib/mcp/tools.js +108 -36
  104. package/lib/message-port-stream.js +64 -6
  105. package/lib/oauth/external-account-signer.js +16 -13
  106. package/lib/oauth/gmail.js +64 -32
  107. package/lib/oauth/mail-ru.js +24 -17
  108. package/lib/oauth/outlook.js +53 -40
  109. package/lib/oauth/pubsub/google.js +38 -2
  110. package/lib/oauth/scope-checker.js +39 -8
  111. package/lib/oauth/scope-list.js +55 -0
  112. package/lib/oauth/token-fetch.js +47 -0
  113. package/lib/oauth/verify-app.js +2 -2
  114. package/lib/oauth2-apps.js +154 -90
  115. package/lib/openapi/build-document.js +1 -1
  116. package/lib/openapi/joi-schema.js +78 -9
  117. package/lib/outbox.js +2 -7
  118. package/lib/parse-message.js +21 -0
  119. package/lib/payload-examples-webhooks.json +4 -7
  120. package/lib/pbkdf2-phc.js +101 -0
  121. package/lib/privileged-settings.js +0 -14
  122. package/lib/queue-retention.js +4 -2
  123. package/lib/rate-limit.js +54 -15
  124. package/lib/read-env-value.js +33 -2
  125. package/lib/redis-scan-delete.js +56 -29
  126. package/lib/redis-url.js +3 -1
  127. package/lib/respawn-backoff.js +5 -4
  128. package/lib/response-stream.js +25 -4
  129. package/lib/rewrite-text-nodes.js +27 -40
  130. package/lib/routes-ui.js +0 -5
  131. package/lib/schemas.js +180 -253
  132. package/lib/sentry.js +21 -5
  133. package/lib/settings.js +58 -59
  134. package/lib/smtp-auth.js +6 -2
  135. package/lib/smtp-message-processor.js +28 -7
  136. package/lib/sso.js +7 -3
  137. package/lib/stream-encrypt.js +14 -13
  138. package/lib/swagger-options.js +3 -1
  139. package/lib/tls/provision.js +69 -3
  140. package/lib/tls/store.js +14 -1
  141. package/lib/token-audit-log.js +3 -2
  142. package/lib/tools.js +114 -53
  143. package/lib/totp.js +16 -1
  144. package/lib/ui-routes/account-routes.js +67 -70
  145. package/lib/ui-routes/admin-config-routes.js +111 -134
  146. package/lib/ui-routes/admin-entities-routes.js +101 -191
  147. package/lib/ui-routes/ai-options.js +104 -0
  148. package/lib/ui-routes/auth-routes.js +98 -18
  149. package/lib/ui-routes/export-routes.js +3 -23
  150. package/lib/ui-routes/internals-routes.js +12 -9
  151. package/lib/ui-routes/network-config-routes.js +8 -18
  152. package/lib/ui-routes/oauth-config-routes.js +83 -228
  153. package/lib/ui-routes/route-helpers.js +63 -67
  154. package/lib/ui-routes/special-use-paths.js +33 -0
  155. package/lib/ui-routes/unsubscribe-routes.js +2 -2
  156. package/lib/utils/decode-headers.js +32 -5
  157. package/lib/utils/header-map.js +62 -1
  158. package/lib/utils/network.js +11 -17
  159. package/lib/web-safe-html.js +77 -4
  160. package/lib/webhook-request.js +9 -1
  161. package/lib/webhook-routing.js +27 -1
  162. package/lib/webhooks.js +120 -43
  163. package/lib/worker-rpc-error.js +43 -2
  164. package/list-generate.js +13 -2
  165. package/package.json +38 -46
  166. package/sbom.json +1 -1
  167. package/scripts/refresh-test-tokens.js +42 -14
  168. package/server.js +338 -292
  169. package/setup-production.sh +16 -7
  170. package/static/css/flyonui.css +1 -1
  171. package/static/css/src/app.tailwind.css +7 -8
  172. package/static/js/ee-client.js +145 -70
  173. package/static/js/ui.js +350 -154
  174. package/static/licenses.html +349 -1740
  175. package/translations/messages.pot +129 -111
  176. package/views/account-workspace-error.hbs +30 -0
  177. package/views/accounts/account.hbs +9 -4
  178. package/views/accounts/browse.hbs +10 -4
  179. package/views/accounts/edit.hbs +11 -2
  180. package/views/config/ai.hbs +49 -41
  181. package/views/config/oauth/app.hbs +2 -1
  182. package/views/dashboard.hbs +18 -16
  183. package/views/internals/index.hbs +1 -1
  184. package/views/layout/app.hbs +0 -22
  185. package/views/layout/login.hbs +2 -1
  186. package/views/partials/filter_editor_js.hbs +4 -3
  187. package/views/partials/gmail_api_scopes.hbs +16 -0
  188. package/views/partials/oauth_form.hbs +67 -94
  189. package/views/partials/oauth_pubsub_app_select.hbs +43 -0
  190. package/views/partials/scope_info.hbs +14 -23
  191. package/views/partials/side_menu.hbs +0 -4
  192. package/views/partials/ui/account-picker.hbs +6 -32
  193. package/views/partials/ui/model-picker.hbs +31 -0
  194. package/views/partials/ui/pagination.hbs +6 -1
  195. package/views/partials/ui/picker.hbs +47 -0
  196. package/views/unsubscribe.hbs +1 -1
  197. package/workers/api.js +82 -47
  198. package/workers/export.js +55 -60
  199. package/workers/imap.js +132 -49
  200. package/workers/submit.js +5 -6
  201. package/workers/webhooks.js +46 -27
  202. package/.githooks/pre-commit +0 -80
  203. package/.github/CODE_OF_CONDUCT.md +0 -76
  204. package/.github/contributing.md +0 -17
  205. package/.github/dependabot.yml +0 -22
  206. package/.github/docker-smoke-test.sh +0 -61
  207. package/.github/workflows/deploy.yml +0 -215
  208. package/.github/workflows/e2e.yml +0 -55
  209. package/.github/workflows/release.yaml +0 -217
  210. package/.github/workflows/test.yml +0 -307
  211. package/lib/api-routes/chat-routes.js +0 -535
  212. package/lib/document-store.js +0 -75
  213. package/lib/es.js +0 -757
  214. package/lib/generate-text-preview.js +0 -61
  215. package/lib/imapproxy/imap-core/memory-notifier.js +0 -129
  216. package/lib/pre-process.js +0 -196
  217. package/lib/threads.js +0 -155
  218. package/lib/ui-routes/document-store-routes.js +0 -806
  219. package/playwright.config.js +0 -47
  220. package/views/config/document-store/chat.hbs +0 -286
  221. package/views/config/document-store/index.hbs +0 -146
  222. package/views/config/document-store/mappings/index.hbs +0 -108
  223. package/views/config/document-store/mappings/new.hbs +0 -68
  224. package/views/config/document-store/pre-processing/index.hbs +0 -103
  225. package/views/partials/document_store_header.hbs +0 -30
  226. package/workers/documents.js +0 -1128
@@ -0,0 +1,71 @@
1
+ 'use strict';
2
+
3
+ // The hapi authentication scheme behind the `api-token` strategy: `Authorization: Bearer <token>`,
4
+ // or the `access_token` query parameter when the strategy allows it. Replaces hapi-auth-bearer-token
5
+ // (unmaintained since 2020, and the last thing pinning @hapi/hoek 9 into the tree) with exactly the
6
+ // subset EmailEngine used, response for response: test/api-token-scheme-test.js replays the
7
+ // responses recorded from the plugin.
8
+ //
9
+ // The contract with the strategy's validate() is unchanged. It is called as
10
+ // validate(request, token, h) and answers { isValid, credentials, artifacts }; an error it throws
11
+ // is not caught here, so the coded refusals the api-token strategy raises (UnknownToken,
12
+ // ExpiredToken, a permission refusal) reach the client as they always did. A request that carries
13
+ // no bearer token at all is reported as missing authentication, which is what lets a route with
14
+ // `mode: 'optional'` or `'try'` continue without one.
15
+
16
+ const Boom = require('@hapi/boom');
17
+
18
+ const SCHEME_NAME = 'api-token-bearer';
19
+ const TOKEN_TYPE = 'Bearer';
20
+ const ACCESS_TOKEN_NAME = 'access_token';
21
+
22
+ /**
23
+ * Scheme implementation for server.auth.scheme(SCHEME_NAME, apiTokenScheme)
24
+ *
25
+ * @param {object} server - Hapi server (unused, part of the scheme signature)
26
+ * @param {object} options - Strategy options
27
+ * @param {Function} options.validate - Token validation function
28
+ * @param {boolean} [options.allowQueryToken=false] - Also accept the token as `?access_token=`
29
+ */
30
+ function apiTokenScheme(server, options) {
31
+ if (!options || typeof options.validate !== 'function') {
32
+ throw new TypeError('The api-token scheme needs a validate function');
33
+ }
34
+
35
+ const { validate, allowQueryToken = false } = options;
36
+
37
+ return {
38
+ authenticate: async (request, h) => {
39
+ let authorization = request.raw.req.headers.authorization;
40
+
41
+ if (allowQueryToken && !authorization && request.query[ACCESS_TOKEN_NAME]) {
42
+ authorization = `${TOKEN_TYPE} ${request.query[ACCESS_TOKEN_NAME]}`;
43
+ // a credential, not an input the handler or its payload validation should see
44
+ delete request.query[ACCESS_TOKEN_NAME];
45
+ }
46
+
47
+ if (!authorization) {
48
+ throw Boom.unauthorized(null, TOKEN_TYPE);
49
+ }
50
+
51
+ const [tokenType, token] = authorization.split(/\s+/);
52
+ if (!token || tokenType.toLowerCase() !== TOKEN_TYPE.toLowerCase()) {
53
+ throw Boom.unauthorized(null, TOKEN_TYPE);
54
+ }
55
+
56
+ const { isValid, credentials, artifacts } = await validate(request, token, h);
57
+
58
+ if (!isValid) {
59
+ return h.unauthenticated(Boom.unauthorized('Bad token', TOKEN_TYPE), { credentials: credentials || {}, artifacts });
60
+ }
61
+
62
+ if (!credentials || typeof credentials !== 'object') {
63
+ return h.unauthenticated(Boom.badImplementation('Bad token string received for Bearer auth validation'), { credentials: {} });
64
+ }
65
+
66
+ return h.authenticated({ credentials, artifacts });
67
+ }
68
+ };
69
+ }
70
+
71
+ module.exports = { apiTokenScheme, SCHEME_NAME, TOKEN_TYPE, ACCESS_TOKEN_NAME };
package/lib/arf-detect.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const libmime = require('libmime');
4
4
  const addressparser = require('nodemailer/lib/addressparser');
5
5
  const { toCamelCase } = require('./utils/to-camel-case');
6
- const { decodeHeaders } = require('./utils/decode-headers');
6
+ const { decodeHeaders, capHeaderBlock } = require('./utils/decode-headers');
7
7
  const { isUnsafeTransformedKey } = require('./utils/unsafe-key');
8
8
 
9
9
  // The attachment types a complaint is read from: the ARF report itself, and the copy of the
@@ -29,6 +29,31 @@ const ARF_SINGLE = [
29
29
  'incidents'
30
30
  ];
31
31
 
32
+ // A feedback report is a handful of short fields and the original headers a few kilobytes. Both
33
+ // arrive in attachments bounded only by the message size; decodeHeaders() cuts each block to
34
+ // MAX_HEADER_BLOCK_SIZE before it is decoded. No single ARF field is anywhere near this long; a
35
+ // longer one is truncated
36
+ const MAX_FIELD_LENGTH = 2048;
37
+
38
+ function capField(value) {
39
+ return value.length > MAX_FIELD_LENGTH ? value.substring(0, MAX_FIELD_LENGTH) : value;
40
+ }
41
+
42
+ // Strips surrounding whitespace and angle brackets. A single linear pass: the regex this replaces,
43
+ // /^[\s<]*|[>\s]*$/g, retried the trailing alternative from every position of a long whitespace
44
+ // run, which is quadratic.
45
+ function stripAngleBrackets(value) {
46
+ let start = 0;
47
+ let end = value.length;
48
+ while (start < end && (value[start] === '<' || /\s/.test(value[start]))) {
49
+ start++;
50
+ }
51
+ while (end > start && (value[end - 1] === '>' || /\s/.test(value[end - 1]))) {
52
+ end--;
53
+ }
54
+ return value.substring(start, end);
55
+ }
56
+
32
57
  const arfDetect = async messageInfo => {
33
58
  const report = {
34
59
  arf: {},
@@ -42,7 +67,7 @@ const arfDetect = async messageInfo => {
42
67
  case 'message/feedback-report': {
43
68
  // found a feedback report
44
69
 
45
- const contents = decodeHeaders((attachment.content || '').toString());
70
+ const contents = decodeHeaders(attachment.content);
46
71
 
47
72
  Object.keys(contents).forEach(key => {
48
73
  let value = contents[key];
@@ -52,12 +77,14 @@ const arfDetect = async messageInfo => {
52
77
  }
53
78
 
54
79
  if (ARF_SINGLE.includes(key)) {
55
- value = Array.isArray(contents[key]) ? contents[key].join(',') : (contents[key] || '').toString();
80
+ value = capField(Array.isArray(contents[key]) ? contents[key].join(',') : (contents[key] || '').toString());
56
81
  } else if (!Array.isArray(value)) {
57
82
  value = []
58
83
  .concat(value || [])
59
- .map(element => (element || '').toString().trim())
84
+ .map(element => capField((element || '').toString().trim()))
60
85
  .filter(element => element);
86
+ } else {
87
+ value = value.map(element => (typeof element === 'string' ? capField(element) : element));
61
88
  }
62
89
 
63
90
  if (!value || !value.length) {
@@ -66,7 +93,7 @@ const arfDetect = async messageInfo => {
66
93
 
67
94
  switch (key) {
68
95
  case 'original-mail-from':
69
- value = value.replace(/^[\s<]*|[>\s]*$/g, '');
96
+ value = stripAngleBrackets(value);
70
97
  break;
71
98
 
72
99
  case 'arrival-date':
@@ -90,7 +117,7 @@ const arfDetect = async messageInfo => {
90
117
  case 'message/rfc822-headers':
91
118
  case 'text/rfc822-headers':
92
119
  case 'text/rfc822-header': {
93
- let contents = (attachment.content || '').toString();
120
+ let contents = capHeaderBlock(attachment.content);
94
121
  const headerPos = contents.match(/\r?\n\r?\n/);
95
122
 
96
123
  if (headerPos) {
package/lib/auth-token.js CHANGED
@@ -12,7 +12,7 @@ const tokenPermissions = require('./token-permissions');
12
12
  const tokenAuditLog = require('./token-audit-log');
13
13
  const { SURFACE_GRANTS } = require('./api-routes/permission-map');
14
14
  const { matchIp } = require('./utils/network');
15
- const { checkRateLimit, peekRateLimit } = require('./rate-limit');
15
+ const { windowBudget, reserveAttempts, releaseAttempts } = require('./rate-limit');
16
16
 
17
17
  // Reason-specific denial messages, shared verbatim by both auth handlers. The
18
18
  // generic "failed to authenticate" fallback and any protocol-specific error
@@ -40,51 +40,69 @@ const REASON_MESSAGES = {
40
40
  const AUTH_FAILURE_LIMIT = 20;
41
41
  const AUTH_FAILURE_WINDOW = 5 * 60; // seconds
42
42
 
43
+ // The per-username budget alone does not hold the shared password: that password is checked
44
+ // before the account is looked up, so rotating usernames buys a fresh budget per name. A second
45
+ // budget per client address, ignoring the username, bounds that. It only counts attempts whose
46
+ // password is not shaped like an API token, which is what keeps the property above: a stale
47
+ // token for one account never spends it, while a stale shared password breaks every account of
48
+ // that host anyway. Larger than the per-username one, as one address can front many accounts.
49
+ const AUTH_FAILURE_ADDRESS_LIMIT = 100;
50
+
51
+ const TOKEN_SHAPE = /^[0-9a-f]{64}$/i;
52
+
43
53
  const authFailureKey = (remoteAddress, account) => `auth:fail:${remoteAddress || 'unknown'}:${account || ''}`;
54
+ const authFailureAddressKey = remoteAddress => `auth:fail-addr:${remoteAddress || 'unknown'}`;
44
55
 
45
56
  /**
46
57
  * Runs a credential check under the client's failed-login budget.
47
58
  *
48
- * Looks before the attempt (a peek, so an accepted login spends nothing) and records only a
49
- * refusal. Everything `attempt` throws counts as one: the caller decides what belongs inside
50
- * the budget by what it puts in the function, so a refusal that is about the account rather
51
- * than the credential (an API-only account on the IMAP proxy) is left outside it.
59
+ * One attempt is reserved atomically before the check and given back when it is accepted, so
60
+ * only a refusal stays counted. Everything `attempt` throws counts as one: the caller decides what
61
+ * belongs inside the budget by what it puts in the function, so a refusal that is about the account
62
+ * rather than the credential (an API-only account on the IMAP proxy) is left outside it.
52
63
  *
53
64
  * @param {Object} client
54
65
  * @param {String} client.remoteAddress - client IP
55
66
  * @param {String} client.account - username the client is authenticating as
67
+ * @param {String} [client.password] - the presented password. When given, a password that is not
68
+ * token-shaped is also counted against the address budget, which ignores the username
56
69
  * @param {Function} attempt - async () => result; the credential check
57
70
  * @param {Function} limitedError - () => Error; the protocol-specific refusal for a spent budget
58
71
  * @returns {Promise<*>} whatever `attempt` resolves with
59
72
  */
60
- async function withAuthFailureBudget({ remoteAddress, account }, attempt, limitedError) {
61
- const key = authFailureKey(remoteAddress, account);
73
+ async function withAuthFailureBudget({ remoteAddress, account, password }, attempt, limitedError) {
74
+ const now = Date.now();
75
+ const budgets = [windowBudget(authFailureKey(remoteAddress, account), AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW, now)];
62
76
 
63
- let limit = await peekRateLimit(key, AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW);
64
- if (!limit.success) {
77
+ if (typeof password === 'string' && !TOKEN_SHAPE.test(password)) {
78
+ budgets.push(windowBudget(authFailureAddressKey(remoteAddress), AUTH_FAILURE_ADDRESS_LIMIT, AUTH_FAILURE_WINDOW, now));
79
+ }
80
+
81
+ // Reserved in every budget at once, or in none: INCR and the limit check are one step, so
82
+ // parallel connections cannot all read the same count and each go ahead
83
+ const { admitted, counts } = await reserveAttempts(budgets);
84
+ if (!admitted) {
65
85
  logger.warn({
66
86
  msg: 'Refusing authentication attempt, failure limit reached',
67
87
  remoteAddress,
68
88
  account,
69
- count: limit.count,
70
- allowed: limit.allowed,
71
- ttlReset: limit.ttlReset
89
+ count: counts[0],
90
+ allowed: AUTH_FAILURE_LIMIT,
91
+ addressCount: counts[1]
72
92
  });
73
93
  throw limitedError();
74
94
  }
75
95
 
76
- try {
77
- return await attempt();
78
- } catch (err) {
79
- // Never masks the refusal: a counter that could not be written is logged, and the
80
- // client still gets the error the attempt raised
81
- try {
82
- await checkRateLimit(key, 1, AUTH_FAILURE_LIMIT, AUTH_FAILURE_WINDOW);
83
- } catch (recordErr) {
84
- logger.error({ msg: 'Failed to record authentication failure', remoteAddress, account, err: recordErr });
85
- }
86
- throw err;
87
- }
96
+ // A refusal thrown here keeps its reservation: that is the recorded failure
97
+ const result = await attempt();
98
+
99
+ // Not awaited: an accepted login is neither held up by giving its reservation back nor failed
100
+ // by it. A reservation that could not be given back only costs this client one attempt
101
+ releaseAttempts(budgets.map(budget => budget.key)).catch(releaseErr => {
102
+ logger.error({ msg: 'Failed to release authentication attempt', remoteAddress, account, err: releaseErr });
103
+ });
104
+
105
+ return result;
88
106
  }
89
107
 
90
108
  /**
@@ -220,7 +238,9 @@ module.exports = {
220
238
  validateAuthToken,
221
239
  withAuthFailureBudget,
222
240
  authFailureKey,
241
+ authFailureAddressKey,
223
242
  AUTH_FAILURE_LIMIT,
243
+ AUTH_FAILURE_ADDRESS_LIMIT,
224
244
  AUTH_FAILURE_WINDOW,
225
245
  REASON_MESSAGES
226
246
  };