@proteinjs/user-server 1.22.1 → 1.22.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 (84) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/generated/index.js +1 -1
  3. package/dist/generated/index.js.map +1 -1
  4. package/dist/index.d.ts +3 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +9 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/src/authentication/PasswordHasher.d.ts +9 -0
  9. package/dist/src/authentication/PasswordHasher.d.ts.map +1 -1
  10. package/dist/src/authentication/PasswordHasher.js +25 -0
  11. package/dist/src/authentication/PasswordHasher.js.map +1 -1
  12. package/dist/src/authentication/authenticate.d.ts +15 -0
  13. package/dist/src/authentication/authenticate.d.ts.map +1 -1
  14. package/dist/src/authentication/authenticate.js +55 -20
  15. package/dist/src/authentication/authenticate.js.map +1 -1
  16. package/dist/src/routes/executePasswordReset.d.ts +4 -0
  17. package/dist/src/routes/executePasswordReset.d.ts.map +1 -1
  18. package/dist/src/routes/executePasswordReset.js +7 -0
  19. package/dist/src/routes/executePasswordReset.js.map +1 -1
  20. package/dist/src/routes/initiatePasswordReset.d.ts +7 -0
  21. package/dist/src/routes/initiatePasswordReset.d.ts.map +1 -1
  22. package/dist/src/routes/initiatePasswordReset.js +28 -10
  23. package/dist/src/routes/initiatePasswordReset.js.map +1 -1
  24. package/dist/src/routes/login.d.ts +8 -0
  25. package/dist/src/routes/login.d.ts.map +1 -1
  26. package/dist/src/routes/login.js +63 -22
  27. package/dist/src/routes/login.js.map +1 -1
  28. package/dist/src/throttle/ClientAddress.d.ts +35 -0
  29. package/dist/src/throttle/ClientAddress.d.ts.map +1 -0
  30. package/dist/src/throttle/ClientAddress.js +48 -0
  31. package/dist/src/throttle/ClientAddress.js.map +1 -0
  32. package/dist/src/throttle/PasswordResetThrottle.d.ts +39 -0
  33. package/dist/src/throttle/PasswordResetThrottle.d.ts.map +1 -0
  34. package/dist/src/throttle/PasswordResetThrottle.js +59 -0
  35. package/dist/src/throttle/PasswordResetThrottle.js.map +1 -0
  36. package/dist/src/throttle/RequestDigests.d.ts +42 -0
  37. package/dist/src/throttle/RequestDigests.d.ts.map +1 -0
  38. package/dist/src/throttle/RequestDigests.js +96 -0
  39. package/dist/src/throttle/RequestDigests.js.map +1 -0
  40. package/dist/src/throttle/SignInThrottle.d.ts +67 -0
  41. package/dist/src/throttle/SignInThrottle.d.ts.map +1 -0
  42. package/dist/src/throttle/SignInThrottle.js +91 -0
  43. package/dist/src/throttle/SignInThrottle.js.map +1 -0
  44. package/dist/src/throttle/SlidingWindow.d.ts +51 -0
  45. package/dist/src/throttle/SlidingWindow.d.ts.map +1 -0
  46. package/dist/src/throttle/SlidingWindow.js +85 -0
  47. package/dist/src/throttle/SlidingWindow.js.map +1 -0
  48. package/dist/test/ClientAddress.test.d.ts +2 -0
  49. package/dist/test/ClientAddress.test.d.ts.map +1 -0
  50. package/dist/test/ClientAddress.test.js +51 -0
  51. package/dist/test/ClientAddress.test.js.map +1 -0
  52. package/dist/test/InitiatePasswordReset.test.js +373 -5
  53. package/dist/test/InitiatePasswordReset.test.js.map +1 -1
  54. package/dist/test/LoginThrottle.integration.test.d.ts +2 -0
  55. package/dist/test/LoginThrottle.integration.test.d.ts.map +1 -0
  56. package/dist/test/LoginThrottle.integration.test.js +616 -0
  57. package/dist/test/LoginThrottle.integration.test.js.map +1 -0
  58. package/dist/test/RequestDigests.test.d.ts +2 -0
  59. package/dist/test/RequestDigests.test.d.ts.map +1 -0
  60. package/dist/test/RequestDigests.test.js +73 -0
  61. package/dist/test/RequestDigests.test.js.map +1 -0
  62. package/dist/test/SlidingWindow.test.d.ts +2 -0
  63. package/dist/test/SlidingWindow.test.d.ts.map +1 -0
  64. package/dist/test/SlidingWindow.test.js +72 -0
  65. package/dist/test/SlidingWindow.test.js.map +1 -0
  66. package/generated/index.ts +1 -1
  67. package/index.ts +5 -0
  68. package/package.json +2 -2
  69. package/src/authentication/PasswordHasher.ts +18 -1
  70. package/src/authentication/authenticate.ts +36 -9
  71. package/src/routes/executePasswordReset.ts +7 -0
  72. package/src/routes/initiatePasswordReset.ts +29 -11
  73. package/src/routes/login.ts +39 -8
  74. package/src/throttle/ClientAddress.ts +47 -0
  75. package/src/throttle/PasswordResetThrottle.ts +62 -0
  76. package/src/throttle/RequestDigests.ts +97 -0
  77. package/src/throttle/SignInThrottle.ts +98 -0
  78. package/src/throttle/SlidingWindow.ts +90 -0
  79. package/test/ClientAddress.test.ts +54 -0
  80. package/test/InitiatePasswordReset.test.ts +212 -6
  81. package/test/LoginThrottle.integration.test.ts +339 -0
  82. package/test/RequestDigests.test.ts +81 -0
  83. package/test/SlidingWindow.test.ts +85 -0
  84. package/test/setup.js +2 -0
@@ -8,6 +8,15 @@ import {
8
8
  getDefaultPasswordResetEmailConfigFactory as getDefaultConfigFactory,
9
9
  } from '@proteinjs/email-server';
10
10
  import { PasswordResetToken } from '../authentication/PasswordResetToken';
11
+ import { ClientAddress } from '../throttle/ClientAddress';
12
+ import { RequestDigests } from '../throttle/RequestDigests';
13
+ import { passwordResetThrottle } from '../throttle/PasswordResetThrottle';
14
+
15
+ /**
16
+ * The door's one answer: the same words for an address with an account or without, inside or
17
+ * past a window, mailed or not — the page shows exactly this sentence.
18
+ */
19
+ const ONE_ANSWER = { message: 'If that address has an account, a reset link is on its way.' };
11
20
 
12
21
  /**
13
22
  * Route for initiating a password reset process.
@@ -16,6 +25,13 @@ import { PasswordResetToken } from '../authentication/PasswordResetToken';
16
25
  * its expiry on the user row — and mails the token to the account as a reset link. The token is
17
26
  * withdrawn again when the mail fails to send.
18
27
  *
28
+ * ONE ANSWER: every request with an address is answered `ONE_ANSWER` — BEFORE the address is
29
+ * looked up — whether it has an account, is throttled (`PasswordResetThrottle`: per client and
30
+ * per address), is inside the account's five-minute gap, or its mail fails; so neither the
31
+ * words, the status nor the timing say whether an address has an account. The work runs after
32
+ * the answer. Every request is one outcome line carrying the account digest and the coarse IP
33
+ * hash (`RequestDigests`) — never the address.
34
+ *
19
35
  * Requires an implementation of `DefaultPasswordResetEmailConfigFactory` to build the password reset email with.
20
36
  *
21
37
  * @bodyParam {string} email - The email address of the user requesting a password reset.
@@ -34,16 +50,20 @@ export const initiatePasswordReset: Route = {
34
50
  return;
35
51
  }
36
52
 
53
+ const digests = new RequestDigests();
54
+ const fields = { account: digests.account(requestedEmail), ip: digests.coarseIp(new ClientAddress().of(request)) };
55
+ const window = passwordResetThrottle.admit(fields.ip, fields.account);
56
+ response.send(ONE_ANSWER);
57
+ if (window) {
58
+ logger.warn({ message: `Password reset throttled`, obj: { ...fields, window } });
59
+ return;
60
+ }
61
+
37
62
  const email = requestedEmail.toLowerCase();
38
63
  const db = getDbAsSystem();
39
-
40
- const genericResponse = { message: 'If an account with that email exists, we have sent a password reset link.' };
41
-
42
64
  const user = await db.get(tables.User, { email });
43
65
  if (!user) {
44
- logger.info({ message: `Password reset requested for non-existent user`, obj: { email } });
45
- // Don't reveal that the user doesn't exist
46
- response.send(genericResponse);
66
+ logger.info({ message: `Password reset requested for non-existent user`, obj: fields });
47
67
  return;
48
68
  }
49
69
 
@@ -51,8 +71,7 @@ export const initiatePasswordReset: Route = {
51
71
  const resetToken = new PasswordResetToken();
52
72
  const mintedAt = resetToken.mintedAt(user);
53
73
  if (mintedAt && moment().diff(mintedAt, 'minutes') < 5) {
54
- logger.info({ message: `Password reset requested too soon for user`, obj: { email } });
55
- response.send(genericResponse);
74
+ logger.info({ message: `Password reset requested too soon for user`, obj: fields });
56
75
  return;
57
76
  }
58
77
 
@@ -81,12 +100,11 @@ export const initiatePasswordReset: Route = {
81
100
  ...config.options,
82
101
  });
83
102
 
84
- response.send(genericResponse);
103
+ logger.info({ message: `Password reset link mailed`, obj: fields });
85
104
  } catch (error: any) {
86
- logger.error({ message: `Failed to send password reset email`, obj: { email }, error });
105
+ logger.error({ message: `Failed to send password reset email`, obj: fields, error });
87
106
  // The link never reached the account: withdraw the token so asking again is not throttled
88
107
  await resetToken.revoke(user, passwordResetToken);
89
- response.status(500).send({ error: 'Failed to send password reset email. Please try again later.' });
90
108
  }
91
109
  },
92
110
  };
@@ -1,34 +1,65 @@
1
1
  import { Route } from '@proteinjs/server-api';
2
2
  import { routes } from '@proteinjs/user';
3
- import { authenticate } from '../authentication/authenticate';
3
+ import { Logger } from '@proteinjs/logger';
4
+ import { authenticate, checkPassword } from '../authentication/authenticate';
4
5
  import { establishSession } from '../authentication/establishSession';
5
6
  import { AccountDeletion } from '../services/AccountDeletion';
7
+ import { ClientAddress } from '../throttle/ClientAddress';
8
+ import { RequestDigests } from '../throttle/RequestDigests';
9
+ import { SignInThrottle, signInThrottle } from '../throttle/SignInThrottle';
6
10
 
11
+ /**
12
+ * `POST /user/login`. Throttled per client and per account (`SignInThrottle`): a throttled try
13
+ * is told "Too many attempts. Try again in a few minutes." whether or not the address has an
14
+ * account, after the same password check a refusal runs (verdict discarded), so neither the
15
+ * words nor the timing tell. Every refusal is a "Sign-in refused" line and every throttled try
16
+ * its own "Sign-in throttled" line, carrying the account digest and the coarse IP hash
17
+ * (`RequestDigests`) — never the address.
18
+ */
7
19
  export const login: Route = {
8
20
  path: routes.login.path,
9
21
  method: routes.login.method,
10
22
  onRequest: async (request: any, response): Promise<void> => {
11
- const credentials: { email: string; password: string } = request.body;
12
- if (!credentials.email || !credentials.password) {
23
+ const logger = new Logger({ name: 'login' });
24
+ const credentials = request.body ?? {};
25
+ // A field that is not text is a blank one — never something to call methods on.
26
+ const email: string = typeof credentials.email === 'string' ? credentials.email : '';
27
+ const password: string = typeof credentials.password === 'string' ? credentials.password : '';
28
+ const digests = new RequestDigests();
29
+ const ip = digests.coarseIp(new ClientAddress().of(request));
30
+ const account = email ? digests.account(email) : undefined;
31
+ const fields = account ? { account, ip } : { ip };
32
+
33
+ // The account is counted only when a password came with the try: a blank one judges nothing.
34
+ const window = signInThrottle.admit(ip, password ? account : undefined);
35
+ if (window) {
36
+ await checkPassword(email, password);
37
+ logger.warn({ message: 'Sign-in throttled', obj: { ...fields, window } });
38
+ response.send({ error: SignInThrottle.ANSWER });
39
+ return;
40
+ }
41
+
42
+ if (!email || !password || !account) {
13
43
  const error = `Email and password cannot be blank`;
14
- console.error(error);
44
+ logger.info({ message: 'Sign-in refused', obj: { ...fields, reason: error } });
15
45
  response.send({ error });
16
46
  return;
17
47
  }
18
48
 
19
- const result = await authenticate(credentials.email, credentials.password);
49
+ const result = await authenticate(email, password);
20
50
  if (result !== true) {
21
- console.error(result);
51
+ logger.info({ message: 'Sign-in refused', obj: { ...fields, reason: result } });
22
52
  response.send({ error: result });
23
53
  return;
24
54
  }
55
+ signInThrottle.recordSuccess(account, ip);
25
56
 
26
57
  // Cancel-by-login: a pending-deletion account's successful authentication IS the cancel
27
58
  // signal. The restore runs synchronously here, BEFORE request.login, so the first
28
59
  // authenticated paint sees the fully restored account (no transient).
29
60
  let outcome: Awaited<ReturnType<AccountDeletion['cancelPendingDeletion']>>;
30
61
  try {
31
- outcome = await new AccountDeletion().cancelPendingDeletion(credentials.email);
62
+ outcome = await new AccountDeletion().cancelPendingDeletion(email);
32
63
  } catch (error) {
33
64
  // Security boundary: the login response never carries internal error detail — an
34
65
  // attacker probing emails must learn nothing from failure shapes (founder ruling
@@ -45,7 +76,7 @@ export const login: Route = {
45
76
  return;
46
77
  }
47
78
 
48
- await establishSession(request, credentials.email);
79
+ await establishSession(request, email);
49
80
  response.send({});
50
81
  },
51
82
  };
@@ -0,0 +1,47 @@
1
+ /** The request fields the read needs — an express request has all of them. */
2
+ type ClientRequest = {
3
+ app?: { get?: (setting: string) => unknown };
4
+ headers?: Record<string, string | string[] | undefined>;
5
+ socket?: { remoteAddress?: string };
6
+ };
7
+
8
+ /**
9
+ * The client's address, as a throttle should key on it.
10
+ *
11
+ * Behind Google's external Application Load Balancer the `X-Forwarded-For` header ENDS with the
12
+ * two entries the balancer appends — `<client-ip>,<load-balancer-ip>` — and everything before
13
+ * them is whatever the client itself sent. So the client is the second entry from the right:
14
+ * - never the LAST entry: that is the balancer's own forwarding-rule address, the same for every
15
+ * visitor. It is what express's `request.ip` resolves to under the server's `trust proxy 1`
16
+ * (one trusted hop: the Google front end that opened the connection), so a throttle keyed on
17
+ * `request.ip` there is one bucket for the whole world;
18
+ * - never the FIRST entry: a client can send its own header, and the balancer keeps it.
19
+ *
20
+ * Only when the server trusts a proxy (the deployed shape; `trust proxy` is unset in
21
+ * development) is the header read at all. A request that did not come through the balancer —
22
+ * no appended pair: an in-cluster call, a probe — and every request in development key on the
23
+ * connection's own address.
24
+ */
25
+ export class ClientAddress {
26
+ /** How many entries the load balancer appends to the header: the client, then itself. */
27
+ private static readonly BALANCER_APPENDED_ENTRIES = 2;
28
+
29
+ of(request: ClientRequest): string {
30
+ if (request.app?.get?.('trust proxy')) {
31
+ const entries = this.forwardedFor(request);
32
+ if (entries.length >= ClientAddress.BALANCER_APPENDED_ENTRIES) {
33
+ return entries[entries.length - ClientAddress.BALANCER_APPENDED_ENTRIES];
34
+ }
35
+ }
36
+ return request.socket?.remoteAddress ?? '';
37
+ }
38
+
39
+ private forwardedFor(request: ClientRequest): string[] {
40
+ const header = request.headers?.['x-forwarded-for'];
41
+ const value = Array.isArray(header) ? header.join(',') : header ?? '';
42
+ return value
43
+ .split(',')
44
+ .map((entry) => entry.trim())
45
+ .filter((entry) => entry.length > 0);
46
+ }
47
+ }
@@ -0,0 +1,62 @@
1
+ import { SlidingWindow } from './SlidingWindow';
2
+ import { ThrottleWindow } from './SignInThrottle';
3
+
4
+ /**
5
+ * The password-reset door's two windows (`POST /user/initiate-password-reset`), keyed by digests
6
+ * (`RequestDigests`), never by an address. Both count every request, whether or not the address
7
+ * has an account — a window that only counted real accounts would itself say which addresses
8
+ * have one. Past either window nothing is looked up, minted or mailed; the door's answer is the
9
+ * same sentence as always (see the route).
10
+ *
11
+ * These sit on top of the account row's own five-minute gap between links, which spans replicas
12
+ * (it is stored); the windows are in process memory (`SlidingWindow`): per replica. A
13
+ * deployment of three replicas behind a load balancer (up to ten under load) keeps three sets
14
+ * of windows, so its effective ceiling is ~3× the numbers below (up to ~10×) — for one address
15
+ * still at most one mail per five minutes. Friction, not the wall — a shared store is a
16
+ * separate step.
17
+ */
18
+ export class PasswordResetThrottle {
19
+ /**
20
+ * Per client: 10 requests an hour. Someone asking for their own address again, or a household
21
+ * asking for a few addresses, passes; a script sweeping addresses stops at ten.
22
+ */
23
+ private static readonly CLIENT_LIMIT = 10;
24
+ private static readonly CLIENT_WINDOW_MS = 60 * 60 * 1000;
25
+
26
+ /**
27
+ * Per address: 3 requests an hour. A person whose mail is slow asks once or twice more; beyond
28
+ * that it is mail aimed at somebody's inbox.
29
+ */
30
+ private static readonly ACCOUNT_LIMIT = 3;
31
+ private static readonly ACCOUNT_WINDOW_MS = 60 * 60 * 1000;
32
+
33
+ private readonly clients: SlidingWindow;
34
+ private readonly accounts: SlidingWindow;
35
+
36
+ constructor(options?: { now?: () => number }) {
37
+ this.clients = new SlidingWindow({
38
+ windowMs: PasswordResetThrottle.CLIENT_WINDOW_MS,
39
+ limit: PasswordResetThrottle.CLIENT_LIMIT,
40
+ now: options?.now,
41
+ });
42
+ this.accounts = new SlidingWindow({
43
+ windowMs: PasswordResetThrottle.ACCOUNT_WINDOW_MS,
44
+ limit: PasswordResetThrottle.ACCOUNT_LIMIT,
45
+ now: options?.now,
46
+ });
47
+ }
48
+
49
+ /** Count this request and answer which window refuses it, if any. */
50
+ admit(client: string, account: string): ThrottleWindow | undefined {
51
+ if (this.clients.hit(client)) {
52
+ return 'client';
53
+ }
54
+ if (this.accounts.hit(account)) {
55
+ return 'account';
56
+ }
57
+ return undefined;
58
+ }
59
+ }
60
+
61
+ /** The process-wide windows the reset door shares — they must span requests. */
62
+ export const passwordResetThrottle = new PasswordResetThrottle();
@@ -0,0 +1,97 @@
1
+ import { createHmac } from 'crypto';
2
+
3
+ /**
4
+ * The two keyed digests the throttled doors key their windows on and write on their log lines,
5
+ * in place of what they stand for:
6
+ * - `account(email)` — the ACCOUNT DIGEST: a keyed hash of the trimmed, lowercased address.
7
+ * One address gives one digest however it was typed, on every replica and across restarts, so
8
+ * an operator can say "one account" across lines without the address.
9
+ * - `coarseIp(address)` — the COARSE IP HASH: a keyed hash of the client address at the grain
10
+ * one device holds (an IPv4 address; an IPv6 /64, inside which a device rotates freely), so
11
+ * an operator can say "one device" and a throttle cannot be dodged by rotating inside a /64.
12
+ *
13
+ * Keyed with HMAC-SHA256 under a key DERIVED from the session secret — the one secret every
14
+ * replica already shares, the same keying the invite-request door's IP hash uses; derived per
15
+ * purpose, never used raw, so neither digest weakens the session's own use of it, and the two
16
+ * digests never collide in meaning. Truncated to 64 bits: enough to tell accounts and devices
17
+ * apart, useless to anyone without the key — never the address, never a plain hash a list of
18
+ * addresses could reverse.
19
+ *
20
+ * The key is the deployment's `SESSION_SECRET` unless the constructor is given one (the tests).
21
+ * Without either the digests refuse to run: a server with no `SESSION_SECRET` has no sessions
22
+ * either (the session middleware refuses to start), so nothing ever runs unkeyed — never a plain
23
+ * hash a list of addresses could reverse, never a per-process key that quietly stops matching
24
+ * across replicas.
25
+ */
26
+ export class RequestDigests {
27
+ /** Hex characters kept from the HMAC: 64 bits. */
28
+ private static readonly DIGEST_HEX_LENGTH = 16;
29
+
30
+ constructor(private readonly options?: { secret?: string }) {}
31
+
32
+ /** The account digest of an address, however it was typed. */
33
+ account(email: string): string {
34
+ return this.digest('account-digest', email.trim().toLowerCase());
35
+ }
36
+
37
+ /** The coarse IP hash of a client address (see `ClientAddress`). */
38
+ coarseIp(address: string): string {
39
+ return this.digest('coarse-ip', this.coarsen(address.trim().toLowerCase()));
40
+ }
41
+
42
+ private digest(purpose: string, value: string): string {
43
+ return createHmac('sha256', `${purpose}:${this.secret()}`)
44
+ .update(value)
45
+ .digest('hex')
46
+ .slice(0, RequestDigests.DIGEST_HEX_LENGTH);
47
+ }
48
+
49
+ private secret(): string {
50
+ const configured = this.options?.secret ?? process.env.SESSION_SECRET;
51
+ if (!configured) {
52
+ throw new Error(
53
+ 'SESSION_SECRET is not set: the account digest and the coarse IP hash need the key every replica shares'
54
+ );
55
+ }
56
+ return configured;
57
+ }
58
+
59
+ /** An IPv4 address as itself (an IPv4-mapped IPv6 address as its IPv4); an IPv6 address as its /64. */
60
+ private coarsen(address: string): string {
61
+ const mapped = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/.exec(address);
62
+ if (mapped) {
63
+ return mapped[1];
64
+ }
65
+ if (!address.includes(':')) {
66
+ return address;
67
+ }
68
+ const groups = this.ipv6Groups(address.split('%')[0]);
69
+ return groups ? `${groups.slice(0, 4).join(':')}::/64` : address;
70
+ }
71
+
72
+ /** The first four groups (the /64) of an IPv6 address, each without leading zeros; undefined when it does not parse. */
73
+ private ipv6Groups(address: string): string[] | undefined {
74
+ const halves = address.split('::');
75
+ if (halves.length > 2) {
76
+ return undefined;
77
+ }
78
+ const parts = (half: string | undefined) => (half ? half.split(':') : []);
79
+ const head = parts(halves[0]);
80
+ const tail = parts(halves[1]);
81
+ // A trailing dotted IPv4 part stands for two groups.
82
+ const groupsIn = (list: string[]) => list.reduce((count, part) => count + (part.includes('.') ? 2 : 1), 0);
83
+ const missing = 8 - groupsIn(head) - groupsIn(tail);
84
+ if (missing < 0 || (halves.length === 1 && missing !== 0)) {
85
+ return undefined;
86
+ }
87
+ const zeros: string[] = [];
88
+ for (let i = 0; i < missing; i++) {
89
+ zeros.push('0');
90
+ }
91
+ const groups = head.concat(zeros, tail).slice(0, 4);
92
+ if (groups.some((group) => !/^[0-9a-f]{1,4}$/.test(group))) {
93
+ return undefined;
94
+ }
95
+ return groups.map((group) => parseInt(group, 16).toString(16));
96
+ }
97
+ }
@@ -0,0 +1,98 @@
1
+ import { SlidingWindow } from './SlidingWindow';
2
+
3
+ /** Which window refused a try: the client's (its coarse IP hash) or the account's (its digest). */
4
+ export type ThrottleWindow = 'client' | 'account';
5
+
6
+ /**
7
+ * The sign-in door's two windows (`POST /user/login`), keyed by digests (`RequestDigests`),
8
+ * never by an address:
9
+ * - per CLIENT: every try that is not a success counts — wrong passwords, blank ones too, the
10
+ * client made them — so one device cannot sweep many accounts; a successful sign-in never
11
+ * counts (it is forgiven the moment it succeeds), so the people behind one shared address
12
+ * signing in do not spend the window on each other;
13
+ * - per ACCOUNT: every try that carries a password counts (a blank submission judges no
14
+ * password, so it never counts), so guesses spread over many devices still stop; a success
15
+ * clears the account's count. A try is counted as it ARRIVES, before it is judged: tries in
16
+ * flight at the same moment cannot all pass the window together.
17
+ *
18
+ * A throttled try is told `ANSWER` whichever window refused it and whether or not the address
19
+ * has an account, in the same time a refused password takes (the door runs the same password
20
+ * check and discards its verdict).
21
+ *
22
+ * The windows are in process memory (`SlidingWindow`): per replica. A deployment of three
23
+ * replicas behind a load balancer (up to ten under load) keeps three sets of windows, so its
24
+ * effective ceiling is ~3× the numbers below (up to ~10×). Friction, not the wall — a shared
25
+ * store is a separate step.
26
+ */
27
+ export class SignInThrottle {
28
+ /** What a throttled try is told — in plain words, the same for every address, known or not. */
29
+ static readonly ANSWER = 'Too many attempts. Try again in a few minutes.';
30
+
31
+ /**
32
+ * Per client: 50 tries that are not successes in 10 minutes (the founder's number, 2026-09-23).
33
+ * Successes never count, so an office or a school behind one address signing in at nine o'clock
34
+ * never spends this window on itself — only its mistypes do, and fifty wrong or blank tries in
35
+ * ten minutes is beyond any human population behind one address; a guessing script from one
36
+ * device is held to ~300 tries an hour per replica.
37
+ */
38
+ private static readonly CLIENT_LIMIT = 50;
39
+ private static readonly CLIENT_WINDOW_MS = 10 * 60 * 1000;
40
+
41
+ /**
42
+ * Per account: 10 tries in 15 minutes (a success clears them, so only wrong ones ever add up).
43
+ * Someone who has forgotten a password tries a handful and asks for a reset link; ten wrong in
44
+ * a quarter of an hour is guessing, and counting per account holds however many devices the
45
+ * guesses come from. "A few minutes" in the answer is honest: the oldest try leaves the window
46
+ * within 15.
47
+ */
48
+ private static readonly ACCOUNT_LIMIT = 10;
49
+ private static readonly ACCOUNT_WINDOW_MS = 15 * 60 * 1000;
50
+
51
+ private readonly clients: SlidingWindow;
52
+ private readonly accounts: SlidingWindow;
53
+
54
+ constructor(options?: { now?: () => number }) {
55
+ this.clients = new SlidingWindow({
56
+ windowMs: SignInThrottle.CLIENT_WINDOW_MS,
57
+ limit: SignInThrottle.CLIENT_LIMIT,
58
+ now: options?.now,
59
+ });
60
+ this.accounts = new SlidingWindow({
61
+ windowMs: SignInThrottle.ACCOUNT_WINDOW_MS,
62
+ limit: SignInThrottle.ACCOUNT_LIMIT,
63
+ now: options?.now,
64
+ });
65
+ }
66
+
67
+ /**
68
+ * Count this try against the client and against the account, and answer which window refuses
69
+ * it, if any. `account` is the digest of the address tried, given only when a password came
70
+ * with it (a blank submission judges no password, so it never counts toward an account). The
71
+ * count is taken here, before the try is judged, so tries in flight at once cannot all pass
72
+ * the window; a success clears it (`recordSuccess`).
73
+ */
74
+ admit(client: string, account?: string): ThrottleWindow | undefined {
75
+ if (this.clients.hit(client)) {
76
+ return 'client';
77
+ }
78
+ if (account !== undefined && this.accounts.hit(account)) {
79
+ return 'account';
80
+ }
81
+ return undefined;
82
+ }
83
+
84
+ /**
85
+ * The account proved itself: its window opens again. When it was a sign-in try from `client`
86
+ * (rather than a reset link redeemed), that try is forgiven — a success never counts against
87
+ * the device.
88
+ */
89
+ recordSuccess(account: string, client?: string): void {
90
+ this.accounts.clear(account);
91
+ if (client !== undefined) {
92
+ this.clients.forgive(client);
93
+ }
94
+ }
95
+ }
96
+
97
+ /** The process-wide windows the sign-in door shares — they must span requests. */
98
+ export const signInThrottle = new SignInThrottle();
@@ -0,0 +1,90 @@
1
+ /**
2
+ * A per-key sliding window: how many attempts a key made in the last `windowMs`, against a
3
+ * `limit`. The one window every throttled door shares — the sign-in and password-reset doors in
4
+ * this package, and any consumer door throttling per client (lifted from the invite-request
5
+ * door's per-IP throttle, which it replaces).
6
+ *
7
+ * Held in process memory only, which is what makes it cheap and what bounds it:
8
+ * - PER PROCESS. Each replica keeps its own windows, so behind a load balancer spreading a
9
+ * client over N replicas the effective ceiling is ~N× the limit; a restart forgets them.
10
+ * A throttle built on this is friction, not the wall. A shared store is a separate step.
11
+ * - BOUNDED. At most `maxKeys` keys are tracked; at the bound the oldest-touched key is
12
+ * forgotten first, so a flood of fresh keys degrades the friction before it grows memory.
13
+ *
14
+ * Keys are whatever the caller passes — callers pass digests (see `RequestDigests`), never raw
15
+ * addresses, so nothing identifying is held here either.
16
+ */
17
+ export class SlidingWindow {
18
+ private static readonly DEFAULT_MAX_KEYS = 10_000;
19
+
20
+ private readonly windowMs: number;
21
+ private readonly limit: number;
22
+ private readonly maxKeys: number;
23
+ private readonly now: () => number;
24
+ /** key → the counted attempt times inside the window (pruned on touch), in touch order. */
25
+ private readonly attempts = new Map<string, number[]>();
26
+
27
+ constructor(options: { windowMs: number; limit: number; maxKeys?: number; now?: () => number }) {
28
+ this.windowMs = options.windowMs;
29
+ this.limit = options.limit;
30
+ this.maxKeys = options.maxKeys ?? SlidingWindow.DEFAULT_MAX_KEYS;
31
+ this.now = options.now ?? Date.now;
32
+ }
33
+
34
+ /**
35
+ * Record an attempt for `key` and answer whether it was over the window — `true` means refuse.
36
+ * A refused attempt is not counted, so a key drains one window after its last counted attempt.
37
+ */
38
+ hit(key: string): boolean {
39
+ if (this.isOver(key)) {
40
+ this.touch(key, this.inWindow(key));
41
+ return true;
42
+ }
43
+ this.record(key);
44
+ return false;
45
+ }
46
+
47
+ /** Whether `key` has used up its window, without counting anything. */
48
+ isOver(key: string): boolean {
49
+ return this.inWindow(key).length >= this.limit;
50
+ }
51
+
52
+ /** Count an attempt for `key` without answering (for doors that judge the attempt first). */
53
+ record(key: string): void {
54
+ const attempts = this.inWindow(key);
55
+ attempts.push(this.now());
56
+ this.touch(key, attempts);
57
+ }
58
+
59
+ /** Forget `key`'s attempts. */
60
+ clear(key: string): void {
61
+ this.attempts.delete(key);
62
+ }
63
+
64
+ /**
65
+ * Uncount `key`'s latest attempt (for doors that count a try as it arrives and learn afterwards
66
+ * that it should never have counted — a sign-in that succeeded).
67
+ */
68
+ forgive(key: string): void {
69
+ const attempts = this.inWindow(key);
70
+ attempts.pop();
71
+ this.touch(key, attempts);
72
+ }
73
+
74
+ private inWindow(key: string): number[] {
75
+ const cutoff = this.now() - this.windowMs;
76
+ return (this.attempts.get(key) ?? []).filter((time) => time > cutoff);
77
+ }
78
+
79
+ /** Store `key`'s attempts as the most recently touched, evicting the oldest-touched key at the bound. */
80
+ private touch(key: string, attempts: number[]): void {
81
+ if (!this.attempts.has(key) && this.attempts.size >= this.maxKeys) {
82
+ const oldest = this.attempts.keys().next().value;
83
+ if (oldest !== undefined) {
84
+ this.attempts.delete(oldest);
85
+ }
86
+ }
87
+ this.attempts.delete(key);
88
+ this.attempts.set(key, attempts);
89
+ }
90
+ }
@@ -0,0 +1,54 @@
1
+ import { ClientAddress } from '../src/throttle/ClientAddress';
2
+
3
+ /**
4
+ * Which address a throttle keys on. Behind Google's external Application Load Balancer the
5
+ * header ends `<client-ip>,<load-balancer-ip>` — the balancer appends both, and anything before
6
+ * them is whatever the client itself sent. So the client is the SECOND entry from the right:
7
+ * never the last (the balancer's own address, the same for every visitor — a throttle keyed on
8
+ * it is one bucket for the whole world) and never the first (client-supplied, rotatable at will).
9
+ */
10
+ describe('ClientAddress', () => {
11
+ const behindTheBalancer = (forwardedFor: string | undefined, socketAddress = '35.191.0.10') => ({
12
+ app: { get: (setting: string) => (setting === 'trust proxy' ? 1 : undefined) },
13
+ headers: forwardedFor === undefined ? {} : { 'x-forwarded-for': forwardedFor },
14
+ socket: { remoteAddress: socketAddress },
15
+ // What express's own `request.ip` resolves to under `trust proxy 1`: the header's last entry.
16
+ ip: forwardedFor?.split(',').pop()?.trim() ?? socketAddress,
17
+ });
18
+
19
+ it("reads the client the balancer appended, not the balancer's own address", () => {
20
+ const request = behindTheBalancer('198.51.100.23, 34.120.1.1');
21
+
22
+ expect(new ClientAddress().of(request)).toBe('198.51.100.23');
23
+ expect(request.ip).toBe('34.120.1.1');
24
+ });
25
+
26
+ it('ignores whatever the client put in the header itself', () => {
27
+ const spoofed = behindTheBalancer('203.0.113.99, 10.0.0.1, 198.51.100.23, 34.120.1.1');
28
+
29
+ expect(new ClientAddress().of(spoofed)).toBe('198.51.100.23');
30
+ });
31
+
32
+ it('reads IPv6 clients the same way', () => {
33
+ expect(new ClientAddress().of(behindTheBalancer('2001:db8:1:2:3:4:5:6,34.120.1.1'))).toBe('2001:db8:1:2:3:4:5:6');
34
+ });
35
+
36
+ it('a request that did not come through the balancer (no appended pair) keys on its own connection', () => {
37
+ expect(new ClientAddress().of(behindTheBalancer(undefined, '10.8.0.7'))).toBe('10.8.0.7');
38
+ expect(new ClientAddress().of(behindTheBalancer('10.8.0.9', '10.8.0.7'))).toBe('10.8.0.7');
39
+ });
40
+
41
+ it('with no proxy trusted (development) the connection is the client, and a forwarded header is ignored', () => {
42
+ const direct = {
43
+ app: { get: () => false },
44
+ headers: { 'x-forwarded-for': '203.0.113.99, 198.51.100.23' },
45
+ socket: { remoteAddress: '::1' },
46
+ };
47
+
48
+ expect(new ClientAddress().of(direct)).toBe('::1');
49
+ });
50
+
51
+ it('a request with no connection details at all reads as the empty address', () => {
52
+ expect(new ClientAddress().of({})).toBe('');
53
+ });
54
+ });