@proteinjs/user-server 1.22.4 → 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.
- package/CHANGELOG.md +18 -0
- package/dist/generated/index.js +1 -1
- package/dist/generated/index.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/src/routes/executePasswordReset.js +3 -1
- package/dist/src/routes/executePasswordReset.js.map +1 -1
- package/dist/src/routes/initiatePasswordReset.d.ts.map +1 -1
- package/dist/src/routes/initiatePasswordReset.js +14 -12
- package/dist/src/routes/initiatePasswordReset.js.map +1 -1
- package/dist/src/routes/login.js +18 -14
- package/dist/src/routes/login.js.map +1 -1
- package/dist/src/throttle/MemoryThrottleWindowStore.d.ts +28 -0
- package/dist/src/throttle/MemoryThrottleWindowStore.d.ts.map +1 -0
- package/dist/src/throttle/MemoryThrottleWindowStore.js +108 -0
- package/dist/src/throttle/MemoryThrottleWindowStore.js.map +1 -0
- package/dist/src/throttle/PasswordResetThrottle.d.ts +9 -8
- package/dist/src/throttle/PasswordResetThrottle.d.ts.map +1 -1
- package/dist/src/throttle/PasswordResetThrottle.js +63 -15
- package/dist/src/throttle/PasswordResetThrottle.js.map +1 -1
- package/dist/src/throttle/SignInThrottle.d.ts +21 -15
- package/dist/src/throttle/SignInThrottle.d.ts.map +1 -1
- package/dist/src/throttle/SignInThrottle.js +94 -25
- package/dist/src/throttle/SignInThrottle.js.map +1 -1
- package/dist/src/throttle/SlidingWindow.d.ts +6 -4
- package/dist/src/throttle/SlidingWindow.d.ts.map +1 -1
- package/dist/src/throttle/SlidingWindow.js +6 -4
- package/dist/src/throttle/SlidingWindow.js.map +1 -1
- package/dist/src/throttle/StoredWindow.d.ts +59 -0
- package/dist/src/throttle/StoredWindow.d.ts.map +1 -0
- package/dist/src/throttle/StoredWindow.js +209 -0
- package/dist/src/throttle/StoredWindow.js.map +1 -0
- package/dist/src/throttle/ThrottleWindowStore.d.ts +38 -0
- package/dist/src/throttle/ThrottleWindowStore.d.ts.map +1 -0
- package/dist/src/throttle/ThrottleWindowStore.js +3 -0
- package/dist/src/throttle/ThrottleWindowStore.js.map +1 -0
- package/dist/test/MemoryThrottleWindowStore.test.d.ts +2 -0
- package/dist/test/MemoryThrottleWindowStore.test.d.ts.map +1 -0
- package/dist/test/MemoryThrottleWindowStore.test.js +210 -0
- package/dist/test/MemoryThrottleWindowStore.test.js.map +1 -0
- package/dist/test/SharedThrottleWindows.integration.test.d.ts +2 -0
- package/dist/test/SharedThrottleWindows.integration.test.d.ts.map +1 -0
- package/dist/test/SharedThrottleWindows.integration.test.js +756 -0
- package/dist/test/SharedThrottleWindows.integration.test.js.map +1 -0
- package/dist/test/UserServerTestEnvironment.d.ts.map +1 -1
- package/dist/test/UserServerTestEnvironment.js +3 -0
- package/dist/test/UserServerTestEnvironment.js.map +1 -1
- package/generated/index.ts +1 -1
- package/index.ts +4 -0
- package/package.json +5 -5
- package/src/routes/executePasswordReset.ts +1 -1
- package/src/routes/initiatePasswordReset.ts +2 -1
- package/src/routes/login.ts +2 -2
- package/src/throttle/MemoryThrottleWindowStore.ts +60 -0
- package/src/throttle/PasswordResetThrottle.ts +14 -11
- package/src/throttle/SignInThrottle.ts +27 -19
- package/src/throttle/SlidingWindow.ts +6 -4
- package/src/throttle/StoredWindow.ts +132 -0
- package/src/throttle/ThrottleWindowStore.ts +41 -0
- package/test/MemoryThrottleWindowStore.test.ts +74 -0
- package/test/SharedThrottleWindows.integration.test.ts +407 -0
- package/test/UserServerTestEnvironment.ts +3 -0
|
@@ -52,8 +52,9 @@ export const initiatePasswordReset: Route = {
|
|
|
52
52
|
|
|
53
53
|
const digests = new RequestDigests();
|
|
54
54
|
const fields = { account: digests.account(requestedEmail), ip: digests.coarseIp(new ClientAddress().of(request)) };
|
|
55
|
-
const window = passwordResetThrottle.admit(fields.ip, fields.account);
|
|
56
55
|
response.send(ONE_ANSWER);
|
|
56
|
+
// Counted after the answer: the count is a shared store's round trip, and the answer never waits on it.
|
|
57
|
+
const window = await passwordResetThrottle.admit(fields.ip, fields.account);
|
|
57
58
|
if (window) {
|
|
58
59
|
logger.warn({ message: `Password reset throttled`, obj: { ...fields, window } });
|
|
59
60
|
return;
|
package/src/routes/login.ts
CHANGED
|
@@ -31,7 +31,7 @@ export const login: Route = {
|
|
|
31
31
|
const fields = account ? { account, ip } : { ip };
|
|
32
32
|
|
|
33
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);
|
|
34
|
+
const window = await signInThrottle.admit(ip, password ? account : undefined);
|
|
35
35
|
if (window) {
|
|
36
36
|
await checkPassword(email, password);
|
|
37
37
|
logger.warn({ message: 'Sign-in throttled', obj: { ...fields, window } });
|
|
@@ -52,7 +52,7 @@ export const login: Route = {
|
|
|
52
52
|
response.send({ error: result });
|
|
53
53
|
return;
|
|
54
54
|
}
|
|
55
|
-
signInThrottle.recordSuccess(account, ip);
|
|
55
|
+
await signInThrottle.recordSuccess(account, ip);
|
|
56
56
|
|
|
57
57
|
// Cancel-by-login: a pending-deletion account's successful authentication IS the cancel
|
|
58
58
|
// signal. The restore runs synchronously here, BEFORE request.login, so the first
|
|
@@ -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)
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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
|
|
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:
|
|
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
|
|
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
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
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
|
-
/**
|
|
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
|
|
43
|
-
* Someone who has forgotten a password tries a handful and asks for a reset link; ten wrong
|
|
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
|
|
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:
|
|
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
|
|
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
|
|
86
|
-
* (rather than a reset link redeemed), that try is forgiven — a success never
|
|
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
|
|
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
|
|
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
|
+
});
|