@basaltkit/auth 3.0.0 → 3.2.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.
@@ -5,57 +5,125 @@ export declare class AccountLockedError extends BasaltError {
5
5
  readonly status = 429;
6
6
  constructor(retryAfterMs: number);
7
7
  }
8
+ /** A throttle counter's state within its current window. */
9
+ export interface ThrottleWindow {
10
+ /** Attempts counted in the current window. */
11
+ count: number;
12
+ /** Milliseconds until the window closes and the counter starts over. */
13
+ retryAfterMs: number;
14
+ }
15
+ /**
16
+ * Where throttle counters live. The default {@link MemoryThrottleStore} is per
17
+ * process; pass a shared one ({@link RedisThrottleStore}) so every replica of a
18
+ * cluster spends ONE budget — otherwise an attacker gets `maxAttempts` guesses
19
+ * per replica, and a lockout on one replica is not seen by the others.
20
+ *
21
+ * Methods may be sync or async: an in-process store stays synchronous (so the
22
+ * count moves before any await), a network store returns promises. `hit` MUST
23
+ * be atomic — increment and read in one step — since it is what bounds a
24
+ * parallel burst. Keys arrive already digested (never a raw email).
25
+ */
26
+ export interface ThrottleStore {
27
+ /**
28
+ * Atomically counts one attempt and returns the new state. The first hit of
29
+ * a key opens a fixed window of `windowMs`; later hits do not extend it.
30
+ */
31
+ hit(key: string, windowMs: number): ThrottleWindow | Promise<ThrottleWindow>;
32
+ /** The current state without counting; null when the key has no live window. */
33
+ peek(key: string): ThrottleWindow | null | Promise<ThrottleWindow | null>;
34
+ /** Gives one attempt back (a successful attempt must not consume budget). */
35
+ release(key: string): void | Promise<void>;
36
+ /** Forgets the key. */
37
+ reset(key: string): void | Promise<void>;
38
+ }
39
+ export interface MemoryThrottleStoreOptions {
40
+ /**
41
+ * Upper bound on tracked keys. When full, expired entries are swept and then
42
+ * the oldest ones are evicted, so failed logins with unique identifiers
43
+ * cannot grow the heap without limit. Default 100 000.
44
+ */
45
+ maxEntries?: number;
46
+ /** Injectable clock for tests. */
47
+ clock?: () => number;
48
+ }
49
+ /** In-process {@link ThrottleStore} (the default): synchronous and bounded. */
50
+ export declare class MemoryThrottleStore implements ThrottleStore {
51
+ private readonly entries;
52
+ private readonly maxEntries;
53
+ private readonly clock;
54
+ constructor(options?: MemoryThrottleStoreOptions);
55
+ /** Number of keys currently tracked. */
56
+ get size(): number;
57
+ /** Total characters retained in keys — diagnostics for memory bounds. */
58
+ retainedKeyChars(): number;
59
+ private live;
60
+ private store;
61
+ hit(key: string, windowMs: number): ThrottleWindow;
62
+ peek(key: string): ThrottleWindow | null;
63
+ release(key: string): void;
64
+ reset(key: string): void;
65
+ }
8
66
  export interface LoginThrottleOptions {
9
67
  /** Failed attempts allowed within the window. Default 5. */
10
68
  maxAttempts?: number;
11
- /** Rolling window in ms. Default 15 minutes. */
69
+ /** Fixed window in ms, opened by the first attempt. Default 15 minutes. */
12
70
  windowMs?: number;
13
71
  /**
14
- * Upper bound on tracked identifiers. When full, expired entries are swept
15
- * and then the oldest ones are evicted, so failed logins with unique
16
- * identifiers cannot grow the heap without limit. Default 100 000.
72
+ * Where the counters live. Default: a private {@link MemoryThrottleStore}
73
+ * (per process). Pass a shared store — e.g. {@link RedisThrottleStore} — to
74
+ * enforce one budget across every replica.
75
+ */
76
+ store?: ThrottleStore;
77
+ /**
78
+ * Key prefix separating this throttle's counters from others sharing the
79
+ * same store (Auth uses `login`, `login-ip` and `email-request`).
17
80
  */
81
+ namespace?: string;
82
+ /** Bound of the default in-memory store (ignored with `store`). Default 100 000. */
18
83
  maxEntries?: number;
19
- /** Injectable clock for tests. */
84
+ /** Injectable clock for the default in-memory store (ignored with `store`). */
20
85
  clock?: () => number;
21
86
  }
87
+ type Awaitable<T> = T | Promise<T>;
22
88
  /**
23
89
  * Brute-force guard: counts failed logins per identifier (email) within a
24
- * rolling window and locks the account once the budget is spent. A successful
25
- * login clears the counter. In-memory per process; back it with Redis for a
26
- * cluster by supplying the same behavior.
90
+ * fixed window and locks the account once the budget is spent. A successful
91
+ * login clears the counter. Counters live in a {@link ThrottleStore}: in memory
92
+ * per process by default, or shared across replicas (Redis).
27
93
  *
28
- * Identifiers are stored as SHA-256 digests (fixed size, never the raw email),
29
- * and the table is bounded by {@link LoginThrottleOptions.maxEntries}.
94
+ * Identifiers are handed to the store as SHA-256 digests (fixed size, never
95
+ * the raw email).
30
96
  *
31
97
  * Use {@link reserve} before verifying credentials: it counts the attempt
32
- * synchronously, so a parallel burst cannot run more verifications than the
98
+ * atomically (synchronously with the memory store, in one Redis script with a
99
+ * shared one), so a parallel burst cannot run more verifications than the
33
100
  * budget allows. {@link release} gives the reservation back on success.
101
+ *
102
+ * Every method returns synchronously with a synchronous store (the default)
103
+ * and a promise otherwise; `await` the result when the store may be async.
34
104
  */
35
105
  export declare class LoginThrottle {
36
- private readonly failures;
106
+ private readonly store;
37
107
  private readonly maxAttempts;
38
108
  private readonly windowMs;
39
- private readonly maxEntries;
40
- private readonly clock;
109
+ private readonly prefix;
41
110
  constructor(options?: LoginThrottleOptions);
42
- /** Number of identifiers currently tracked. */
111
+ /** Number of identifiers currently tracked (in-memory store only; 0 otherwise). */
43
112
  get size(): number;
44
- /** Total characters retained in keys — diagnostics for memory bounds. */
113
+ /** Total characters retained in keys — diagnostics for memory bounds (in-memory store only). */
45
114
  retainedKeyChars(): number;
46
- private digest;
47
- private live;
48
- private store;
115
+ private key;
49
116
  /** Throws {@link AccountLockedError} when the key is currently locked. */
50
- assertAllowed(key: string): void;
51
- recordFailure(key: string): void;
117
+ assertAllowed(key: string): Awaitable<void>;
118
+ recordFailure(key: string): Awaitable<void>;
52
119
  /**
53
- * Atomically checks the budget and counts this attempt (synchronously, before
54
- * any await), throwing {@link AccountLockedError} when it is spent. Pair with
55
- * {@link release} on success; a failure simply keeps the reservation.
120
+ * Atomically counts this attempt and throws {@link AccountLockedError} when
121
+ * it exceeds the budget. Pair with {@link release} on success; a failure
122
+ * simply keeps the reservation.
56
123
  */
57
- reserve(key: string): void;
124
+ reserve(key: string): Awaitable<void>;
58
125
  /** Returns one reservation (a successful attempt must not consume budget). */
59
- release(key: string): void;
60
- reset(key: string): void;
126
+ release(key: string): Awaitable<void>;
127
+ reset(key: string): Awaitable<void>;
61
128
  }
129
+ export {};
package/dist/throttle.js CHANGED
@@ -9,108 +9,147 @@ export class AccountLockedError extends BasaltError {
9
9
  this.retryAfterMs = retryAfterMs;
10
10
  }
11
11
  }
12
- /**
13
- * Brute-force guard: counts failed logins per identifier (email) within a
14
- * rolling window and locks the account once the budget is spent. A successful
15
- * login clears the counter. In-memory per process; back it with Redis for a
16
- * cluster by supplying the same behavior.
17
- *
18
- * Identifiers are stored as SHA-256 digests (fixed size, never the raw email),
19
- * and the table is bounded by {@link LoginThrottleOptions.maxEntries}.
20
- *
21
- * Use {@link reserve} before verifying credentials: it counts the attempt
22
- * synchronously, so a parallel burst cannot run more verifications than the
23
- * budget allows. {@link release} gives the reservation back on success.
24
- */
25
- export class LoginThrottle {
26
- failures = new Map();
27
- maxAttempts;
28
- windowMs;
12
+ /** In-process {@link ThrottleStore} (the default): synchronous and bounded. */
13
+ export class MemoryThrottleStore {
14
+ entries = new Map();
29
15
  maxEntries;
30
16
  clock;
31
17
  constructor(options = {}) {
32
- this.maxAttempts = options.maxAttempts ?? 5;
33
- this.windowMs = options.windowMs ?? 15 * 60_000;
34
18
  this.maxEntries = Math.max(1, options.maxEntries ?? 100_000);
35
19
  this.clock = options.clock ?? (() => Date.now());
36
20
  }
37
- /** Number of identifiers currently tracked. */
21
+ /** Number of keys currently tracked. */
38
22
  get size() {
39
- return this.failures.size;
23
+ return this.entries.size;
40
24
  }
41
25
  /** Total characters retained in keys — diagnostics for memory bounds. */
42
26
  retainedKeyChars() {
43
27
  let n = 0;
44
- for (const key of this.failures.keys())
28
+ for (const key of this.entries.keys())
45
29
  n += key.length;
46
30
  return n;
47
31
  }
48
- digest(key) {
49
- return createHash('sha256').update(key).digest('base64url');
50
- }
51
- live(digest, now) {
52
- const entry = this.failures.get(digest);
32
+ live(key, now) {
33
+ const entry = this.entries.get(key);
53
34
  if (entry && now >= entry.resetAt) {
54
- this.failures.delete(digest);
35
+ this.entries.delete(key);
55
36
  return undefined;
56
37
  }
57
38
  return entry;
58
39
  }
59
- store(digest, entry, now) {
60
- if (!this.failures.has(digest) && this.failures.size >= this.maxEntries) {
61
- for (const [k, e] of this.failures)
40
+ store(key, entry, now) {
41
+ if (!this.entries.has(key) && this.entries.size >= this.maxEntries) {
42
+ for (const [k, e] of this.entries)
62
43
  if (now >= e.resetAt)
63
- this.failures.delete(k);
44
+ this.entries.delete(k);
64
45
  // Still full: evict the oldest entries (Map iterates in insertion order).
65
- for (const k of this.failures.keys()) {
66
- if (this.failures.size < this.maxEntries)
46
+ for (const k of this.entries.keys()) {
47
+ if (this.entries.size < this.maxEntries)
67
48
  break;
68
- this.failures.delete(k);
49
+ this.entries.delete(k);
69
50
  }
70
51
  }
71
- this.failures.set(digest, entry);
52
+ this.entries.set(key, entry);
53
+ }
54
+ hit(key, windowMs) {
55
+ const now = this.clock();
56
+ const entry = this.live(key, now) ?? { count: 0, resetAt: now + windowMs };
57
+ entry.count += 1;
58
+ this.store(key, entry, now);
59
+ return { count: entry.count, retryAfterMs: entry.resetAt - now };
60
+ }
61
+ peek(key) {
62
+ const now = this.clock();
63
+ const entry = this.live(key, now);
64
+ return entry ? { count: entry.count, retryAfterMs: entry.resetAt - now } : null;
65
+ }
66
+ release(key) {
67
+ const entry = this.live(key, this.clock());
68
+ if (!entry)
69
+ return;
70
+ entry.count -= 1;
71
+ if (entry.count <= 0)
72
+ this.entries.delete(key);
73
+ }
74
+ reset(key) {
75
+ this.entries.delete(key);
76
+ }
77
+ }
78
+ const isPromise = (value) => typeof value?.then === 'function';
79
+ /** Runs `next` on a value that may or may not be a promise — sync in, sync out. */
80
+ function chain(value, next) {
81
+ return isPromise(value) ? value.then(next) : next(value);
82
+ }
83
+ /**
84
+ * Brute-force guard: counts failed logins per identifier (email) within a
85
+ * fixed window and locks the account once the budget is spent. A successful
86
+ * login clears the counter. Counters live in a {@link ThrottleStore}: in memory
87
+ * per process by default, or shared across replicas (Redis).
88
+ *
89
+ * Identifiers are handed to the store as SHA-256 digests (fixed size, never
90
+ * the raw email).
91
+ *
92
+ * Use {@link reserve} before verifying credentials: it counts the attempt
93
+ * atomically (synchronously with the memory store, in one Redis script with a
94
+ * shared one), so a parallel burst cannot run more verifications than the
95
+ * budget allows. {@link release} gives the reservation back on success.
96
+ *
97
+ * Every method returns synchronously with a synchronous store (the default)
98
+ * and a promise otherwise; `await` the result when the store may be async.
99
+ */
100
+ export class LoginThrottle {
101
+ store;
102
+ maxAttempts;
103
+ windowMs;
104
+ prefix;
105
+ constructor(options = {}) {
106
+ this.maxAttempts = options.maxAttempts ?? 5;
107
+ this.windowMs = options.windowMs ?? 15 * 60_000;
108
+ this.prefix = options.namespace ? `${options.namespace}:` : '';
109
+ this.store =
110
+ options.store ??
111
+ new MemoryThrottleStore({
112
+ ...(options.maxEntries !== undefined ? { maxEntries: options.maxEntries } : {}),
113
+ ...(options.clock ? { clock: options.clock } : {}),
114
+ });
115
+ }
116
+ /** Number of identifiers currently tracked (in-memory store only; 0 otherwise). */
117
+ get size() {
118
+ return this.store instanceof MemoryThrottleStore ? this.store.size : 0;
119
+ }
120
+ /** Total characters retained in keys — diagnostics for memory bounds (in-memory store only). */
121
+ retainedKeyChars() {
122
+ return this.store instanceof MemoryThrottleStore ? this.store.retainedKeyChars() : 0;
123
+ }
124
+ key(key) {
125
+ return `${this.prefix}${createHash('sha256').update(key).digest('base64url')}`;
72
126
  }
73
127
  /** Throws {@link AccountLockedError} when the key is currently locked. */
74
128
  assertAllowed(key) {
75
- const now = this.clock();
76
- const entry = this.live(this.digest(key), now);
77
- if (entry && entry.count >= this.maxAttempts) {
78
- throw new AccountLockedError(entry.resetAt - now);
79
- }
129
+ return chain(this.store.peek(this.key(key)), (window) => {
130
+ if (window && window.count >= this.maxAttempts)
131
+ throw new AccountLockedError(window.retryAfterMs);
132
+ });
80
133
  }
81
134
  recordFailure(key) {
82
- const now = this.clock();
83
- const digest = this.digest(key);
84
- const entry = this.live(digest, now) ?? { count: 0, resetAt: now + this.windowMs };
85
- entry.count += 1;
86
- this.store(digest, entry, now);
135
+ return chain(this.store.hit(this.key(key), this.windowMs), () => undefined);
87
136
  }
88
137
  /**
89
- * Atomically checks the budget and counts this attempt (synchronously, before
90
- * any await), throwing {@link AccountLockedError} when it is spent. Pair with
91
- * {@link release} on success; a failure simply keeps the reservation.
138
+ * Atomically counts this attempt and throws {@link AccountLockedError} when
139
+ * it exceeds the budget. Pair with {@link release} on success; a failure
140
+ * simply keeps the reservation.
92
141
  */
93
142
  reserve(key) {
94
- const now = this.clock();
95
- const digest = this.digest(key);
96
- const entry = this.live(digest, now);
97
- if (entry && entry.count >= this.maxAttempts)
98
- throw new AccountLockedError(entry.resetAt - now);
99
- const next = entry ?? { count: 0, resetAt: now + this.windowMs };
100
- next.count += 1;
101
- this.store(digest, next, now);
143
+ return chain(this.store.hit(this.key(key), this.windowMs), (window) => {
144
+ if (window.count > this.maxAttempts)
145
+ throw new AccountLockedError(window.retryAfterMs);
146
+ });
102
147
  }
103
148
  /** Returns one reservation (a successful attempt must not consume budget). */
104
149
  release(key) {
105
- const digest = this.digest(key);
106
- const entry = this.live(digest, this.clock());
107
- if (!entry)
108
- return;
109
- entry.count -= 1;
110
- if (entry.count <= 0)
111
- this.failures.delete(digest);
150
+ return this.store.release(this.key(key));
112
151
  }
113
152
  reset(key) {
114
- this.failures.delete(this.digest(key));
153
+ return this.store.reset(this.key(key));
115
154
  }
116
155
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "3.0.0",
3
+ "version": "3.2.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },
@@ -18,18 +18,18 @@
18
18
  "dist"
19
19
  ],
20
20
  "dependencies": {
21
- "@basaltkit/core": "^1.3.1",
22
- "@basaltkit/http": "^2.1.0"
21
+ "@basaltkit/core": "^1.4.0",
22
+ "@basaltkit/http": "^2.4.0"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "zod": "^4.0.0"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.5.1",
28
+ "@types/node": "^26.6.1",
29
29
  "typescript": "^7.0.2",
30
- "vitest": "^5.0.0",
31
- "zod": "^4.5.4",
32
- "@basaltkit/fastify": "^2.1.0",
30
+ "vitest": "^5.0.1",
31
+ "zod": "^4.6.5",
32
+ "@basaltkit/fastify": "^2.3.0",
33
33
  "@basaltkit/tsconfig": "^0.24.0"
34
34
  },
35
35
  "publishConfig": {