@proteinjs/user-server 1.22.3 → 1.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/dist/generated/index.js +1 -1
  3. package/dist/generated/index.js.map +1 -1
  4. package/dist/index.d.ts +1 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js.map +1 -1
  7. package/dist/src/routes/executePasswordReset.js +3 -1
  8. package/dist/src/routes/executePasswordReset.js.map +1 -1
  9. package/dist/src/routes/initiatePasswordReset.d.ts.map +1 -1
  10. package/dist/src/routes/initiatePasswordReset.js +14 -12
  11. package/dist/src/routes/initiatePasswordReset.js.map +1 -1
  12. package/dist/src/routes/login.js +18 -14
  13. package/dist/src/routes/login.js.map +1 -1
  14. package/dist/src/services/Signup.d.ts +10 -0
  15. package/dist/src/services/Signup.d.ts.map +1 -1
  16. package/dist/src/services/Signup.js +51 -21
  17. package/dist/src/services/Signup.js.map +1 -1
  18. package/dist/src/throttle/MemoryThrottleWindowStore.d.ts +28 -0
  19. package/dist/src/throttle/MemoryThrottleWindowStore.d.ts.map +1 -0
  20. package/dist/src/throttle/MemoryThrottleWindowStore.js +108 -0
  21. package/dist/src/throttle/MemoryThrottleWindowStore.js.map +1 -0
  22. package/dist/src/throttle/PasswordResetThrottle.d.ts +9 -8
  23. package/dist/src/throttle/PasswordResetThrottle.d.ts.map +1 -1
  24. package/dist/src/throttle/PasswordResetThrottle.js +63 -15
  25. package/dist/src/throttle/PasswordResetThrottle.js.map +1 -1
  26. package/dist/src/throttle/SignInThrottle.d.ts +21 -15
  27. package/dist/src/throttle/SignInThrottle.d.ts.map +1 -1
  28. package/dist/src/throttle/SignInThrottle.js +94 -25
  29. package/dist/src/throttle/SignInThrottle.js.map +1 -1
  30. package/dist/src/throttle/SlidingWindow.d.ts +6 -4
  31. package/dist/src/throttle/SlidingWindow.d.ts.map +1 -1
  32. package/dist/src/throttle/SlidingWindow.js +6 -4
  33. package/dist/src/throttle/SlidingWindow.js.map +1 -1
  34. package/dist/src/throttle/StoredWindow.d.ts +59 -0
  35. package/dist/src/throttle/StoredWindow.d.ts.map +1 -0
  36. package/dist/src/throttle/StoredWindow.js +209 -0
  37. package/dist/src/throttle/StoredWindow.js.map +1 -0
  38. package/dist/src/throttle/ThrottleWindowStore.d.ts +38 -0
  39. package/dist/src/throttle/ThrottleWindowStore.d.ts.map +1 -0
  40. package/dist/src/throttle/ThrottleWindowStore.js +3 -0
  41. package/dist/src/throttle/ThrottleWindowStore.js.map +1 -0
  42. package/dist/test/MemoryThrottleWindowStore.test.d.ts +2 -0
  43. package/dist/test/MemoryThrottleWindowStore.test.d.ts.map +1 -0
  44. package/dist/test/MemoryThrottleWindowStore.test.js +210 -0
  45. package/dist/test/MemoryThrottleWindowStore.test.js.map +1 -0
  46. package/dist/test/NoAddressesInLogs.integration.test.js +13 -11
  47. package/dist/test/NoAddressesInLogs.integration.test.js.map +1 -1
  48. package/dist/test/SharedThrottleWindows.integration.test.d.ts +2 -0
  49. package/dist/test/SharedThrottleWindows.integration.test.d.ts.map +1 -0
  50. package/dist/test/SharedThrottleWindows.integration.test.js +756 -0
  51. package/dist/test/SharedThrottleWindows.integration.test.js.map +1 -0
  52. package/dist/test/SignupRace.integration.test.d.ts +2 -0
  53. package/dist/test/SignupRace.integration.test.d.ts.map +1 -0
  54. package/dist/test/SignupRace.integration.test.js +320 -0
  55. package/dist/test/SignupRace.integration.test.js.map +1 -0
  56. package/dist/test/UserServerTestEnvironment.d.ts.map +1 -1
  57. package/dist/test/UserServerTestEnvironment.js +3 -0
  58. package/dist/test/UserServerTestEnvironment.js.map +1 -1
  59. package/generated/index.ts +1 -1
  60. package/index.ts +4 -0
  61. package/package.json +5 -5
  62. package/src/routes/executePasswordReset.ts +1 -1
  63. package/src/routes/initiatePasswordReset.ts +2 -1
  64. package/src/routes/login.ts +2 -2
  65. package/src/services/Signup.ts +30 -11
  66. package/src/throttle/MemoryThrottleWindowStore.ts +60 -0
  67. package/src/throttle/PasswordResetThrottle.ts +14 -11
  68. package/src/throttle/SignInThrottle.ts +27 -19
  69. package/src/throttle/SlidingWindow.ts +6 -4
  70. package/src/throttle/StoredWindow.ts +132 -0
  71. package/src/throttle/ThrottleWindowStore.ts +41 -0
  72. package/test/MemoryThrottleWindowStore.test.ts +74 -0
  73. package/test/NoAddressesInLogs.integration.test.ts +9 -8
  74. package/test/SharedThrottleWindows.integration.test.ts +407 -0
  75. package/test/SignupRace.integration.test.ts +230 -0
  76. package/test/UserServerTestEnvironment.ts +3 -0
@@ -322,6 +322,14 @@ export class Signup implements SignupService {
322
322
  * a person's row under it would make the boot sync refuse the declaration (it never takes over
323
323
  * a row it does not own), so the address is refused here in plain words — the declared machine
324
324
  * accounts of this build are the list, nothing else.
325
+ *
326
+ * 'exists' means the address has an account this call did not create — found by the check, or
327
+ * written by a concurrent create between the check and this insert. Two creates for one address
328
+ * both pass the check; the database's unique index on the address refuses the second insert, and
329
+ * that refusal is the same fact the check reads, so the second answers 'exists' exactly as if it
330
+ * had arrived a moment later: its caller gets the existing-address response, no session, and the
331
+ * owner's mail — never the database's sentence, which names the address. An insert that fails
332
+ * while the address still has no account is a real failure and throws.
325
333
  */
326
334
  async createAccount(account: {
327
335
  name: string;
@@ -330,28 +338,39 @@ export class Signup implements SignupService {
330
338
  emailVerified: boolean;
331
339
  invitedBy: User['invitedBy'];
332
340
  }): Promise<'created' | 'exists'> {
333
- const db = getDbAsSystem();
334
341
  const email = account.email.toLowerCase();
335
342
  if (getMachineAccounts().some((machineAccount) => machineAccount.email === email)) {
336
343
  throw new Error(`This address can't be registered.`);
337
344
  }
338
345
 
339
- const existingUser = await db.get(tables.User, { email });
340
- if (existingUser) {
346
+ if (await this.hasAccount(email)) {
341
347
  return 'exists';
342
348
  }
343
349
 
344
- await db.insert(tables.User, {
345
- name: account.name,
346
- email,
347
- password: await new PasswordHasher().hash(account.password),
348
- emailVerified: account.emailVerified,
349
- roles: [],
350
- invitedBy: account.invitedBy,
351
- });
350
+ const password = await new PasswordHasher().hash(account.password);
351
+ try {
352
+ await getDbAsSystem().insert(tables.User, {
353
+ name: account.name,
354
+ email,
355
+ password,
356
+ emailVerified: account.emailVerified,
357
+ roles: [],
358
+ invitedBy: account.invitedBy,
359
+ });
360
+ } catch (error: unknown) {
361
+ if (await this.hasAccount(email)) {
362
+ return 'exists';
363
+ }
364
+ throw error;
365
+ }
352
366
  return 'created';
353
367
  }
354
368
 
369
+ /** Whether an account holds `email` (already lowercased) — the one existence read `createAccount` makes. */
370
+ private async hasAccount(email: string): Promise<boolean> {
371
+ return Boolean(await getDbAsSystem().get(tables.User, { email }));
372
+ }
373
+
355
374
  /** Resolves an invite token, distinguishing "expired" from "never existed / already revoked". */
356
375
  private async lookupInvite(token: string): Promise<InviteLookup> {
357
376
  const db = getDbAsSystem();
@@ -0,0 +1,60 @@
1
+ import { ThrottleWindowStore } from './ThrottleWindowStore';
2
+
3
+ /**
4
+ * The library's own `ThrottleWindowStore`: windows held in this process's memory. It is the
5
+ * default when no shared store is registered — right for tests and single-process servers; in a
6
+ * deployment of several processes each keeps its own counts (register a shared store there).
7
+ *
8
+ * BOUNDED like `SlidingWindow`: at most `maxKeys` keys are held; at the bound the oldest-touched
9
+ * key is forgotten first, so a flood of fresh keys degrades the friction before it grows memory.
10
+ */
11
+ export class MemoryThrottleWindowStore implements ThrottleWindowStore {
12
+ private static readonly DEFAULT_MAX_KEYS = 10_000;
13
+
14
+ private readonly maxKeys: number;
15
+ private readonly now: () => number;
16
+ /** key → its count and when its window ends, in touch order. */
17
+ private readonly windows = new Map<string, { count: number; expiresAt: number }>();
18
+
19
+ constructor(options?: { maxKeys?: number; now?: () => number }) {
20
+ this.maxKeys = options?.maxKeys ?? MemoryThrottleWindowStore.DEFAULT_MAX_KEYS;
21
+ this.now = options?.now ?? Date.now;
22
+ }
23
+
24
+ async increment(key: string, windowMs: number): Promise<number> {
25
+ const window = this.live(key) ?? { count: 0, expiresAt: this.now() + windowMs };
26
+ window.count++;
27
+ this.touch(key, window);
28
+ return window.count;
29
+ }
30
+
31
+ async read(key: string): Promise<number> {
32
+ return this.live(key)?.count ?? 0;
33
+ }
34
+
35
+ async clear(key: string): Promise<void> {
36
+ this.windows.delete(key);
37
+ }
38
+
39
+ /** `key`'s window while it lasts; an ended one is dropped. */
40
+ private live(key: string): { count: number; expiresAt: number } | undefined {
41
+ const window = this.windows.get(key);
42
+ if (window && window.expiresAt <= this.now()) {
43
+ this.windows.delete(key);
44
+ return undefined;
45
+ }
46
+ return window;
47
+ }
48
+
49
+ /** Store `key`'s window as the most recently touched, evicting the oldest-touched key at the bound. */
50
+ private touch(key: string, window: { count: number; expiresAt: number }): void {
51
+ if (!this.windows.has(key) && this.windows.size >= this.maxKeys) {
52
+ const oldest = this.windows.keys().next().value;
53
+ if (oldest !== undefined) {
54
+ this.windows.delete(oldest);
55
+ }
56
+ }
57
+ this.windows.delete(key);
58
+ this.windows.set(key, window);
59
+ }
60
+ }
@@ -1,4 +1,5 @@
1
1
  import { SlidingWindow } from './SlidingWindow';
2
+ import { StoredWindow } from './StoredWindow';
2
3
  import { ThrottleWindow } from './SignInThrottle';
3
4
 
4
5
  /**
@@ -9,11 +10,12 @@ import { ThrottleWindow } from './SignInThrottle';
9
10
  * same sentence as always (see the route).
10
11
  *
11
12
  * 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.
13
+ * (it is stored). The per-address window is a `StoredWindow`: counted in the store the deployment
14
+ * registers (`DefaultThrottleWindowStoreFactory`), so with a shared store it is one count across
15
+ * every replica and survives a deploy; while that store fails it counts in this process's memory
16
+ * (the named fallback, see `StoredWindow`), so the door still mints and mails. The per-client window stays in process memory (`SlidingWindow`), per
17
+ * replica — the second line behind a per-address limit at the load balancer (see
18
+ * `SignInThrottle`).
17
19
  */
18
20
  export class PasswordResetThrottle {
19
21
  /**
@@ -24,14 +26,14 @@ export class PasswordResetThrottle {
24
26
  private static readonly CLIENT_WINDOW_MS = 60 * 60 * 1000;
25
27
 
26
28
  /**
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
+ * Per address: 3 requests in an hour's window. A person whose mail is slow asks once or twice
30
+ * more; beyond that it is mail aimed at somebody's inbox.
29
31
  */
30
32
  private static readonly ACCOUNT_LIMIT = 3;
31
33
  private static readonly ACCOUNT_WINDOW_MS = 60 * 60 * 1000;
32
34
 
33
35
  private readonly clients: SlidingWindow;
34
- private readonly accounts: SlidingWindow;
36
+ private readonly accounts: StoredWindow;
35
37
 
36
38
  constructor(options?: { now?: () => number }) {
37
39
  this.clients = new SlidingWindow({
@@ -39,7 +41,8 @@ export class PasswordResetThrottle {
39
41
  limit: PasswordResetThrottle.CLIENT_LIMIT,
40
42
  now: options?.now,
41
43
  });
42
- this.accounts = new SlidingWindow({
44
+ this.accounts = new StoredWindow({
45
+ name: 'reset-address',
43
46
  windowMs: PasswordResetThrottle.ACCOUNT_WINDOW_MS,
44
47
  limit: PasswordResetThrottle.ACCOUNT_LIMIT,
45
48
  now: options?.now,
@@ -47,11 +50,11 @@ export class PasswordResetThrottle {
47
50
  }
48
51
 
49
52
  /** Count this request and answer which window refuses it, if any. */
50
- admit(client: string, account: string): ThrottleWindow | undefined {
53
+ async admit(client: string, account: string): Promise<ThrottleWindow | undefined> {
51
54
  if (this.clients.hit(client)) {
52
55
  return 'client';
53
56
  }
54
- if (this.accounts.hit(account)) {
57
+ if (await this.accounts.hit(account)) {
55
58
  return 'account';
56
59
  }
57
60
  return undefined;
@@ -1,4 +1,5 @@
1
1
  import { SlidingWindow } from './SlidingWindow';
2
+ import { StoredWindow } from './StoredWindow';
2
3
 
3
4
  /** Which window refused a try: the client's (its coarse IP hash) or the account's (its digest). */
4
5
  export type ThrottleWindow = 'client' | 'account';
@@ -19,13 +20,20 @@ export type ThrottleWindow = 'client' | 'account';
19
20
  * has an account, in the same time a refused password takes (the door runs the same password
20
21
  * check and discards its verdict).
21
22
  *
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.
23
+ * WHERE THE COUNTS LIVE. The account window is a `StoredWindow`: counted in the store the
24
+ * deployment registers (`DefaultThrottleWindowStoreFactory`), so with a shared store it is ONE
25
+ * count across every replica and survives a deploy; while that store fails it counts in this
26
+ * process's memory (the named fallback, see `StoredWindow`). The client window stays in process memory (`SlidingWindow`), per replica: a
27
+ * deployment that needs one per-address wall across replicas puts it in front of the servers (a
28
+ * rate limit at the load balancer, keyed on the client address); this window is the second line
29
+ * behind it, and keeping it local keeps the per-try forgiveness of a success exact and cheap.
26
30
  */
27
31
  export class SignInThrottle {
28
- /** What a throttled try is told — in plain words, the same for every address, known or not. */
32
+ /**
33
+ * What a throttled try is told — in plain words, the same for every address, known or not. The
34
+ * sign-in, sign-up and reset forms say the same when a load balancer's per-address limit answers
35
+ * 429 in front of the door (@proteinjs/user-ui `AuthApi.TOO_MANY_ATTEMPTS`).
36
+ */
29
37
  static readonly ANSWER = 'Too many attempts. Try again in a few minutes.';
30
38
 
31
39
  /**
@@ -39,17 +47,16 @@ export class SignInThrottle {
39
47
  private static readonly CLIENT_WINDOW_MS = 10 * 60 * 1000;
40
48
 
41
49
  /**
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.
50
+ * Per account: 10 tries in a 15-minute window (a success clears them, so only wrong ones ever add
51
+ * up). Someone who has forgotten a password tries a handful and asks for a reset link; ten wrong
52
+ * in a quarter of an hour is guessing, and counting per account holds however many devices the
53
+ * guesses come from. "A few minutes" in the answer is honest: the window ends within 15.
47
54
  */
48
55
  private static readonly ACCOUNT_LIMIT = 10;
49
56
  private static readonly ACCOUNT_WINDOW_MS = 15 * 60 * 1000;
50
57
 
51
58
  private readonly clients: SlidingWindow;
52
- private readonly accounts: SlidingWindow;
59
+ private readonly accounts: StoredWindow;
53
60
 
54
61
  constructor(options?: { now?: () => number }) {
55
62
  this.clients = new SlidingWindow({
@@ -57,7 +64,8 @@ export class SignInThrottle {
57
64
  limit: SignInThrottle.CLIENT_LIMIT,
58
65
  now: options?.now,
59
66
  });
60
- this.accounts = new SlidingWindow({
67
+ this.accounts = new StoredWindow({
68
+ name: 'sign-in-account',
61
69
  windowMs: SignInThrottle.ACCOUNT_WINDOW_MS,
62
70
  limit: SignInThrottle.ACCOUNT_LIMIT,
63
71
  now: options?.now,
@@ -71,26 +79,26 @@ export class SignInThrottle {
71
79
  * count is taken here, before the try is judged, so tries in flight at once cannot all pass
72
80
  * the window; a success clears it (`recordSuccess`).
73
81
  */
74
- admit(client: string, account?: string): ThrottleWindow | undefined {
82
+ async admit(client: string, account?: string): Promise<ThrottleWindow | undefined> {
75
83
  if (this.clients.hit(client)) {
76
84
  return 'client';
77
85
  }
78
- if (account !== undefined && this.accounts.hit(account)) {
86
+ if (account !== undefined && (await this.accounts.hit(account))) {
79
87
  return 'account';
80
88
  }
81
89
  return undefined;
82
90
  }
83
91
 
84
92
  /**
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.
93
+ * The account proved itself: its window opens again, on every replica. When it was a sign-in try
94
+ * from `client` (rather than a reset link redeemed), that try is forgiven — a success never
95
+ * counts against the device.
88
96
  */
89
- recordSuccess(account: string, client?: string): void {
90
- this.accounts.clear(account);
97
+ async recordSuccess(account: string, client?: string): Promise<void> {
91
98
  if (client !== undefined) {
92
99
  this.clients.forgive(client);
93
100
  }
101
+ await this.accounts.clear(account);
94
102
  }
95
103
  }
96
104
 
@@ -1,13 +1,15 @@
1
1
  /**
2
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).
3
+ * `limit`. The per-CLIENT window the throttled doors share — the sign-in and password-reset doors
4
+ * in this package, and any consumer door throttling per client (lifted from the invite-request
5
+ * door's per-IP throttle, which it replaces). The windows that must hold across replicas (per
6
+ * account, per reset address) are `StoredWindow`s, counted in a shared `ThrottleWindowStore`.
6
7
  *
7
8
  * Held in process memory only, which is what makes it cheap and what bounds it:
8
9
  * - PER PROCESS. Each replica keeps its own windows, so behind a load balancer spreading a
9
10
  * 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
+ * A throttle built on this is friction, not the wall — the per-address wall across replicas
12
+ * belongs in front of the servers (a rate limit at the load balancer).
11
13
  * - BOUNDED. At most `maxKeys` keys are tracked; at the bound the oldest-touched key is
12
14
  * forgotten first, so a flood of fresh keys degrades the friction before it grows memory.
13
15
  *
@@ -0,0 +1,132 @@
1
+ import { SourceRepository } from '@proteinjs/reflection';
2
+ import { Logger } from '@proteinjs/logger';
3
+ import { DefaultThrottleWindowStoreFactory, ThrottleWindowStore } from './ThrottleWindowStore';
4
+ import { MemoryThrottleWindowStore } from './MemoryThrottleWindowStore';
5
+
6
+ /**
7
+ * A throttle window counted in a `ThrottleWindowStore` — the windows that must hold across server
8
+ * processes (the sign-in door's per-account window, the reset door's per-address window). The
9
+ * store is the one a consuming application registers through `DefaultThrottleWindowStoreFactory`
10
+ * (read on every call, so a registration made after start-up is honoured), else the library's own
11
+ * per-process `MemoryThrottleWindowStore`. The window's name prefixes every key, so windows sharing
12
+ * one store never meet.
13
+ *
14
+ * THE NAMED FALLBACK when the store fails — an error, or no answer within `STORE_DEADLINE_MS` (a
15
+ * client queueing commands while it reconnects never answers at all): the window COUNTS IN THIS
16
+ * PROCESS'S MEMORY (the `MemoryThrottleWindowStore` it already holds) until the store answers
17
+ * again — `hit` counts and judges there, `clear` clears there. A door that cannot reach the shared
18
+ * count still counts the way a single process does: each process holds its own count for the
19
+ * outage (at most the limit per process), behind the per-client window and any per-address limit
20
+ * in front of the servers — where refusing every try would lock out every person for a blip with
21
+ * a sentence that is untrue for them. The outage is one WARN line per window saying so, however
22
+ * many tries meet it, and one INFO line when the store answers again; the store then counts again
23
+ * from what it holds (the outage's tries were this process's own). A success clears the memory
24
+ * window as well as the store's, so an account that proved itself starts clean in both.
25
+ *
26
+ * THE SHADOW: every try the store answers is counted in the memory window too, so memory always
27
+ * holds this process's own count — judged by the store while it answers, by memory when it does
28
+ * not. An outage therefore continues from what this process already counted (nine wrong tries,
29
+ * then the store fails: the eleventh is refused), never from zero.
30
+ */
31
+ export class StoredWindow {
32
+ /** How long a door waits on the store before counting in memory: well above a healthy store's milliseconds. */
33
+ private static readonly STORE_DEADLINE_MS = 2000;
34
+ private static readonly FACTORY = '@proteinjs/user-server/DefaultThrottleWindowStoreFactory';
35
+
36
+ private readonly name: string;
37
+ private readonly windowMs: number;
38
+ private readonly limit: number;
39
+ private readonly memory: ThrottleWindowStore;
40
+ private readonly logger = new Logger({ name: 'StoredWindow' });
41
+ /** Whether the last call met a failed store — the outage is logged once, on the way in. */
42
+ private storeUnavailable = false;
43
+
44
+ constructor(options: { name: string; windowMs: number; limit: number; now?: () => number }) {
45
+ this.name = options.name;
46
+ this.windowMs = options.windowMs;
47
+ this.limit = options.limit;
48
+ this.memory = new MemoryThrottleWindowStore({ now: options.now });
49
+ }
50
+
51
+ /**
52
+ * Count an attempt for `key` and answer whether it is over the window — `true` means refuse.
53
+ * Every attempt is counted (the window's end is fixed at its first count, so counting a refused
54
+ * attempt never extends it): in the store, and in this process's memory too (the shadow) — judged
55
+ * by the store when it answers, by memory when it fails (see the class comment).
56
+ */
57
+ async hit(key: string): Promise<boolean> {
58
+ let answer: { count: number; store: ThrottleWindowStore };
59
+ try {
60
+ answer = await this.withDeadline(async (store) => ({
61
+ count: await store.increment(this.key(key), this.windowMs),
62
+ store,
63
+ }));
64
+ this.answered();
65
+ } catch (error) {
66
+ this.failed(error);
67
+ return (await this.memory.increment(this.key(key), this.windowMs)) > this.limit;
68
+ }
69
+ if (answer.store !== this.memory) {
70
+ // The shadow: this process's own count, for the outage (no shared store registered: counted once).
71
+ await this.memory.increment(this.key(key), this.windowMs);
72
+ }
73
+ return answer.count > this.limit;
74
+ }
75
+
76
+ /** Forget `key`'s window — in this process's memory, and in the store when it answers. */
77
+ async clear(key: string): Promise<void> {
78
+ await this.memory.clear(this.key(key));
79
+ try {
80
+ await this.withDeadline((store) => store.clear(this.key(key)));
81
+ this.answered();
82
+ } catch (error) {
83
+ this.failed(error);
84
+ }
85
+ }
86
+
87
+ /** The registered shared store, else the library's own. */
88
+ private store(): ThrottleWindowStore {
89
+ const factory = SourceRepository.get().object<DefaultThrottleWindowStoreFactory>(StoredWindow.FACTORY);
90
+ return factory ? factory.getStore() : this.memory;
91
+ }
92
+
93
+ private key(key: string): string {
94
+ return `${this.name}:${key}`;
95
+ }
96
+
97
+ private async withDeadline<T>(call: (store: ThrottleWindowStore) => Promise<T>): Promise<T> {
98
+ let timer: ReturnType<typeof setTimeout> | undefined;
99
+ const deadline = new Promise<never>((_, reject) => {
100
+ timer = setTimeout(
101
+ () => reject(new Error(`no answer within ${StoredWindow.STORE_DEADLINE_MS} ms`)),
102
+ StoredWindow.STORE_DEADLINE_MS
103
+ );
104
+ });
105
+ try {
106
+ return await Promise.race([call(this.store()), deadline]);
107
+ } finally {
108
+ if (timer !== undefined) {
109
+ clearTimeout(timer);
110
+ }
111
+ }
112
+ }
113
+
114
+ private failed(error: unknown): void {
115
+ if (this.storeUnavailable) {
116
+ return;
117
+ }
118
+ this.storeUnavailable = true;
119
+ this.logger.warn({
120
+ message: "Throttle window store unavailable; counting in this process's memory until it answers",
121
+ obj: { window: this.name, errorMessage: error instanceof Error ? error.message : String(error) },
122
+ });
123
+ }
124
+
125
+ private answered(): void {
126
+ if (!this.storeUnavailable) {
127
+ return;
128
+ }
129
+ this.storeUnavailable = false;
130
+ this.logger.info({ message: 'Throttle window store answering again', obj: { window: this.name } });
131
+ }
132
+ }
@@ -0,0 +1,41 @@
1
+ import { Loadable } from '@proteinjs/reflection';
2
+
3
+ /**
4
+ * Where a throttle counts the windows that must hold across server processes — the windows keyed
5
+ * on something other than the device (the sign-in door's per-account window, the reset door's
6
+ * per-address window; see `StoredWindow`). A window here is a TTL: it opens at a key's first count
7
+ * and lasts the `windowMs` that count was given; counts inside it add up; at its end the key is
8
+ * gone and the next count opens a fresh window.
9
+ *
10
+ * The library's own store is `MemoryThrottleWindowStore` — per process, which is right for tests
11
+ * and single-process servers. A deployment of several processes registers a SHARED store (one
12
+ * every process reads and writes) through `DefaultThrottleWindowStoreFactory`, so a window is one
13
+ * count across replicas and survives a restart or a deploy.
14
+ *
15
+ * Keys are digests (see `RequestDigests`) prefixed with the window's name — never an address — so
16
+ * nothing identifying reaches the store.
17
+ */
18
+ export interface ThrottleWindowStore {
19
+ /**
20
+ * Count one attempt for `key` and answer how many the key holds inside its window, this one
21
+ * included. The first count opens the window with `windowMs` as its TTL; later counts never
22
+ * extend it. Atomic across every caller of the store: attempts in flight at once each get their
23
+ * own count.
24
+ */
25
+ increment(key: string, windowMs: number): Promise<number>;
26
+
27
+ /** How many attempts `key` holds inside its window (0 when it holds none). */
28
+ read(key: string): Promise<number>;
29
+
30
+ /** Forget `key`'s window. */
31
+ clear(key: string): Promise<void>;
32
+ }
33
+
34
+ /**
35
+ * The seam a consuming application registers its shared store through (discovered like every
36
+ * other `Default…Factory`). Without a registration the counted windows use the library's own
37
+ * per-process store.
38
+ */
39
+ export interface DefaultThrottleWindowStoreFactory extends Loadable {
40
+ getStore(): ThrottleWindowStore;
41
+ }
@@ -0,0 +1,74 @@
1
+ import { MemoryThrottleWindowStore } from '../src/throttle/MemoryThrottleWindowStore';
2
+
3
+ /**
4
+ * The library's own window store (the default when no shared store is registered): a count per
5
+ * key inside a window that opens at the key's first count and lasts the window it was given (its
6
+ * TTL), then is gone. `increment` answers the count including this one; `read` only reads;
7
+ * `clear` forgets. Bounded like `SlidingWindow`: at the bound the oldest-touched key goes first.
8
+ */
9
+ describe('MemoryThrottleWindowStore', () => {
10
+ const MINUTE = 60 * 1000;
11
+ let now = 1_700_000_000_000;
12
+ const clock = () => now;
13
+
14
+ it('counts each attempt inside the window, this one included; read only reads', async () => {
15
+ const store = new MemoryThrottleWindowStore({ now: clock });
16
+
17
+ expect(await store.read('a')).toBe(0);
18
+ expect([
19
+ await store.increment('a', 10 * MINUTE),
20
+ await store.increment('a', 10 * MINUTE),
21
+ await store.increment('a', 10 * MINUTE),
22
+ ]).toEqual([1, 2, 3]);
23
+ expect(await store.read('a')).toBe(3);
24
+ expect(await store.read('a')).toBe(3);
25
+ });
26
+
27
+ it('keeps each key in its own window', async () => {
28
+ const store = new MemoryThrottleWindowStore({ now: clock });
29
+ await store.increment('a', 10 * MINUTE);
30
+ await store.increment('a', 10 * MINUTE);
31
+
32
+ expect(await store.increment('b', 10 * MINUTE)).toBe(1);
33
+ expect(await store.read('a')).toBe(2);
34
+ });
35
+
36
+ it('the window is a TTL from the first count: counts inside it add up, and at its end the key is gone', async () => {
37
+ const store = new MemoryThrottleWindowStore({ now: clock });
38
+ const start = now;
39
+ await store.increment('a', 10 * MINUTE);
40
+ now = start + 9 * MINUTE;
41
+ expect(await store.increment('a', 10 * MINUTE)).toBe(2); // a later count never extends the window
42
+
43
+ now = start + 10 * MINUTE;
44
+ expect(await store.read('a')).toBe(0);
45
+ expect(await store.increment('a', 10 * MINUTE)).toBe(1); // a fresh window
46
+ now = start + 19 * MINUTE;
47
+ expect(await store.read('a')).toBe(1);
48
+ });
49
+
50
+ it('clear forgets the key', async () => {
51
+ const store = new MemoryThrottleWindowStore({ now: clock });
52
+ await store.increment('a', 10 * MINUTE);
53
+ await store.increment('a', 10 * MINUTE);
54
+
55
+ await store.clear('a');
56
+
57
+ expect(await store.read('a')).toBe(0);
58
+ expect(await store.increment('a', 10 * MINUTE)).toBe(1);
59
+ await store.clear('never-seen'); // nothing to forget, nothing thrown
60
+ });
61
+
62
+ it('bounds the keys it holds: at the bound the oldest-touched key is forgotten first', async () => {
63
+ const store = new MemoryThrottleWindowStore({ maxKeys: 2, now: clock });
64
+ await store.increment('a', 10 * MINUTE);
65
+ await store.increment('b', 10 * MINUTE);
66
+ await store.increment('a', 10 * MINUTE); // 'a' is now the most recently touched
67
+
68
+ await store.increment('c', 10 * MINUTE); // at the bound: 'b' goes
69
+
70
+ expect(await store.read('a')).toBe(2);
71
+ expect(await store.read('b')).toBe(0);
72
+ expect(await store.read('c')).toBe(1);
73
+ });
74
+ });
@@ -252,7 +252,7 @@ describe('no e-mail address reaches the server log', () => {
252
252
  expect(log.text).toContain(digests.account('logs-signup@test.local'));
253
253
  });
254
254
 
255
- it("a double sign-up race: the database's refusal names the address — the log carries its digest instead", async () => {
255
+ it("a double sign-up race: the loser answers 'exists' — the same bytes, no session, no refusal line, no address", async () => {
256
256
  // Both requests pass the existence check before either writes: each one's password hash is held
257
257
  // until both have arrived, so both inserts race and the unique index on the address refuses one —
258
258
  // the refusal's own words name the address it refused.
@@ -288,18 +288,19 @@ describe('no e-mail address reaches the server log', () => {
288
288
  }
289
289
  });
290
290
 
291
- // One account, one session; the loser was refused by the index and logged it — the refusal
292
- // naming the index, the address in its words replaced by the address's digest.
291
+ // One account, one session; the loser's refused insert re-read the address and answered 'exists':
292
+ // both bodies are the existing-address response (`{}`), no refusal line is written, and the two
293
+ // account lines carry the account digest.
293
294
  expect((await getDbAsSystem().query(tables.User, { email: 'logs-race@test.local' })).length).toBe(1);
294
295
  expect(outcomes.filter((outcome) => outcome.loggedInAs === 'logs-race@test.local')).toHaveLength(1);
295
- const refusal = log.linesContaining('Signup failed');
296
- expect(refusal.lines).toHaveLength(1);
297
- expect(refusal.text).toContain('user_email_unique');
298
- expect(refusal.addresses).toEqual([]);
299
- expect(refusal.text).toContain(digests.address('logs-race@test.local'));
296
+ expect(outcomes.map((outcome) => outcome.body)).toEqual([{}, {}]);
297
+ expect(log.linesContaining('Signup failed').lines).toHaveLength(0);
298
+ expect(log.linesContaining('already exists').text).toContain(digests.account('logs-race@test.local'));
299
+ expect(log.linesContaining('Created user').text).toContain(digests.account('logs-race@test.local'));
300
300
  // The database driver's own line for the refused statement is the driver's (the version a
301
301
  // package lock pins decides whether it prints bound values); this door's lines are the ones above.
302
302
  expect(log.linesContaining('[signup]').addresses).toEqual([]);
303
+ expect(log.linesContaining('[Signup.createUser]').addresses).toEqual([]);
303
304
  });
304
305
 
305
306
  it('an invite whose send or write fails with the address in its error: the invitee by its digest, the error too', async () => {