@veloxts/auth 0.3.4 → 0.3.6
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/README.md +425 -22
- package/dist/__integration__/fixtures.d.ts +41 -0
- package/dist/__integration__/fixtures.d.ts.map +1 -0
- package/dist/__integration__/fixtures.js +79 -0
- package/dist/__integration__/fixtures.js.map +1 -0
- package/dist/__integration__/setup.d.ts +26 -0
- package/dist/__integration__/setup.d.ts.map +1 -0
- package/dist/__integration__/setup.js +28 -0
- package/dist/__integration__/setup.js.map +1 -0
- package/dist/csrf.d.ts +9 -3
- package/dist/csrf.d.ts.map +1 -1
- package/dist/csrf.js +9 -3
- package/dist/csrf.js.map +1 -1
- package/dist/guards.d.ts +12 -9
- package/dist/guards.d.ts.map +1 -1
- package/dist/guards.js +17 -5
- package/dist/guards.js.map +1 -1
- package/dist/hash.d.ts +7 -1
- package/dist/hash.d.ts.map +1 -1
- package/dist/hash.js +20 -4
- package/dist/hash.js.map +1 -1
- package/dist/index.d.ts +10 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +43 -7
- package/dist/index.js.map +1 -1
- package/dist/jwt.d.ts +34 -5
- package/dist/jwt.d.ts.map +1 -1
- package/dist/jwt.js +154 -28
- package/dist/jwt.js.map +1 -1
- package/dist/middleware.d.ts +18 -6
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +23 -11
- package/dist/middleware.js.map +1 -1
- package/dist/password-policy.d.ts +259 -0
- package/dist/password-policy.d.ts.map +1 -0
- package/dist/password-policy.js +529 -0
- package/dist/password-policy.js.map +1 -0
- package/dist/plugin.d.ts +25 -7
- package/dist/plugin.d.ts.map +1 -1
- package/dist/plugin.js +28 -9
- package/dist/plugin.js.map +1 -1
- package/dist/rate-limit.d.ts +231 -0
- package/dist/rate-limit.d.ts.map +1 -0
- package/dist/rate-limit.js +352 -0
- package/dist/rate-limit.js.map +1 -0
- package/dist/session.d.ts +9 -3
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +9 -3
- package/dist/session.js.map +1 -1
- package/dist/types.d.ts +11 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +30 -7
package/dist/plugin.js
CHANGED
|
@@ -16,7 +16,7 @@ export const AUTH_VERSION = packageJson.version ?? '0.0.0-unknown';
|
|
|
16
16
|
// Auth Plugin
|
|
17
17
|
// ============================================================================
|
|
18
18
|
/**
|
|
19
|
-
* Creates the VeloxTS auth plugin
|
|
19
|
+
* Creates the VeloxTS auth plugin (succinct API)
|
|
20
20
|
*
|
|
21
21
|
* This plugin provides:
|
|
22
22
|
* - JWT token management (access + refresh tokens)
|
|
@@ -26,9 +26,9 @@ export const AUTH_VERSION = packageJson.version ?? '0.0.0-unknown';
|
|
|
26
26
|
*
|
|
27
27
|
* @example
|
|
28
28
|
* ```typescript
|
|
29
|
-
* import {
|
|
29
|
+
* import { authPlugin } from '@veloxts/auth';
|
|
30
30
|
*
|
|
31
|
-
* const
|
|
31
|
+
* const auth = authPlugin({
|
|
32
32
|
* jwt: {
|
|
33
33
|
* secret: process.env.JWT_SECRET!,
|
|
34
34
|
* accessTokenExpiry: '15m',
|
|
@@ -44,7 +44,7 @@ export const AUTH_VERSION = packageJson.version ?? '0.0.0-unknown';
|
|
|
44
44
|
* });
|
|
45
45
|
*
|
|
46
46
|
* // Register with VeloxApp
|
|
47
|
-
* app.register(
|
|
47
|
+
* await app.register(auth);
|
|
48
48
|
*
|
|
49
49
|
* // Use in procedures
|
|
50
50
|
* const { middleware, requireAuth } = app.auth.middleware;
|
|
@@ -54,11 +54,12 @@ export const AUTH_VERSION = packageJson.version ?? '0.0.0-unknown';
|
|
|
54
54
|
* .query(async ({ ctx }) => ctx.user);
|
|
55
55
|
* ```
|
|
56
56
|
*/
|
|
57
|
-
export function
|
|
57
|
+
export function authPlugin(options) {
|
|
58
58
|
return {
|
|
59
59
|
name: '@veloxts/auth',
|
|
60
60
|
version: AUTH_VERSION,
|
|
61
|
-
dependencies
|
|
61
|
+
// No explicit dependencies - works with any Fastify instance
|
|
62
|
+
// The plugin decorates Fastify with auth functionality
|
|
62
63
|
async register(server, _opts) {
|
|
63
64
|
const config = { ...options, ..._opts };
|
|
64
65
|
const { debug = false } = config;
|
|
@@ -157,17 +158,35 @@ export function createAuthPlugin(options) {
|
|
|
157
158
|
},
|
|
158
159
|
};
|
|
159
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Creates the VeloxTS auth plugin
|
|
163
|
+
*
|
|
164
|
+
* @deprecated Use `authPlugin()` instead. Will be removed in v0.9.
|
|
165
|
+
*/
|
|
166
|
+
export const createAuthPlugin = authPlugin;
|
|
160
167
|
/**
|
|
161
168
|
* Default auth plugin with minimal configuration
|
|
162
|
-
*
|
|
169
|
+
*
|
|
170
|
+
* Uses environment variables for configuration:
|
|
171
|
+
* - `JWT_SECRET` (required): Secret for signing JWT tokens
|
|
172
|
+
*
|
|
173
|
+
* @throws {Error} If JWT_SECRET environment variable is not set
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```typescript
|
|
177
|
+
* import { defaultAuthPlugin } from '@veloxts/auth';
|
|
178
|
+
*
|
|
179
|
+
* // Requires JWT_SECRET environment variable
|
|
180
|
+
* await app.register(defaultAuthPlugin());
|
|
181
|
+
* ```
|
|
163
182
|
*/
|
|
164
|
-
export function
|
|
183
|
+
export function defaultAuthPlugin() {
|
|
165
184
|
const secret = process.env.JWT_SECRET;
|
|
166
185
|
if (!secret) {
|
|
167
186
|
throw new Error('JWT_SECRET environment variable is required for auth plugin. ' +
|
|
168
187
|
'Set it to a secure random string of at least 32 characters.');
|
|
169
188
|
}
|
|
170
|
-
return
|
|
189
|
+
return authPlugin({
|
|
171
190
|
jwt: { secret },
|
|
172
191
|
});
|
|
173
192
|
}
|
package/dist/plugin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin.js","sourceRoot":"","sources":["../src/plugin.ts"],"names":[],"mappings":"AAAA;;;;GA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
|
+
* Authentication-specific rate limiting
|
|
3
|
+
*
|
|
4
|
+
* Provides specialized rate limiters for authentication endpoints with:
|
|
5
|
+
* - Per-email+IP tracking (prevents brute force on specific accounts)
|
|
6
|
+
* - Account lockout detection
|
|
7
|
+
* - Separate limits for login, register, and password reset
|
|
8
|
+
* - Progressive backoff support
|
|
9
|
+
*
|
|
10
|
+
* @module auth/rate-limit
|
|
11
|
+
*/
|
|
12
|
+
import type { BaseContext } from '@veloxts/core';
|
|
13
|
+
import type { MiddlewareFunction } from '@veloxts/router';
|
|
14
|
+
/**
|
|
15
|
+
* Configuration for auth rate limiting
|
|
16
|
+
*/
|
|
17
|
+
export interface AuthRateLimitConfig {
|
|
18
|
+
/**
|
|
19
|
+
* Maximum attempts before lockout
|
|
20
|
+
* @default 5
|
|
21
|
+
*/
|
|
22
|
+
maxAttempts?: number;
|
|
23
|
+
/**
|
|
24
|
+
* Window duration in milliseconds
|
|
25
|
+
* @default 900000 (15 minutes)
|
|
26
|
+
*/
|
|
27
|
+
windowMs?: number;
|
|
28
|
+
/**
|
|
29
|
+
* Lockout duration in milliseconds after max attempts exceeded
|
|
30
|
+
* @default 900000 (15 minutes)
|
|
31
|
+
*/
|
|
32
|
+
lockoutDurationMs?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Custom key generator for rate limiting
|
|
35
|
+
* Default uses IP + identifier (email)
|
|
36
|
+
*/
|
|
37
|
+
keyGenerator?: (ctx: BaseContext, identifier?: string) => string;
|
|
38
|
+
/**
|
|
39
|
+
* Error message when rate limited
|
|
40
|
+
* @default 'Too many attempts. Please try again later.'
|
|
41
|
+
*/
|
|
42
|
+
message?: string;
|
|
43
|
+
/**
|
|
44
|
+
* Enable progressive backoff (double lockout on repeated violations)
|
|
45
|
+
* @default false
|
|
46
|
+
*/
|
|
47
|
+
progressiveBackoff?: boolean;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Configuration for the auth rate limiter factory
|
|
51
|
+
*/
|
|
52
|
+
export interface AuthRateLimiterConfig {
|
|
53
|
+
/**
|
|
54
|
+
* Rate limit for login attempts
|
|
55
|
+
* @default { maxAttempts: 5, windowMs: 900000 }
|
|
56
|
+
*/
|
|
57
|
+
login?: AuthRateLimitConfig;
|
|
58
|
+
/**
|
|
59
|
+
* Rate limit for registration attempts
|
|
60
|
+
* @default { maxAttempts: 3, windowMs: 3600000 }
|
|
61
|
+
*/
|
|
62
|
+
register?: AuthRateLimitConfig;
|
|
63
|
+
/**
|
|
64
|
+
* Rate limit for password reset requests
|
|
65
|
+
* @default { maxAttempts: 3, windowMs: 3600000 }
|
|
66
|
+
*/
|
|
67
|
+
passwordReset?: AuthRateLimitConfig;
|
|
68
|
+
/**
|
|
69
|
+
* Rate limit for token refresh
|
|
70
|
+
* @default { maxAttempts: 10, windowMs: 60000 }
|
|
71
|
+
*/
|
|
72
|
+
refresh?: AuthRateLimitConfig;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Stop cleanup interval (for testing)
|
|
76
|
+
*/
|
|
77
|
+
export declare function stopAuthRateLimitCleanup(): void;
|
|
78
|
+
/**
|
|
79
|
+
* Clear all rate limit entries (for testing)
|
|
80
|
+
*/
|
|
81
|
+
export declare function clearAuthRateLimitStore(): void;
|
|
82
|
+
/**
|
|
83
|
+
* Creates an authentication rate limiter
|
|
84
|
+
*
|
|
85
|
+
* This factory returns rate limit middlewares configured for different
|
|
86
|
+
* auth operations with sensible defaults.
|
|
87
|
+
*
|
|
88
|
+
* @example
|
|
89
|
+
* ```typescript
|
|
90
|
+
* const authRateLimiter = createAuthRateLimiter({
|
|
91
|
+
* login: { maxAttempts: 5, windowMs: 15 * 60 * 1000 },
|
|
92
|
+
* register: { maxAttempts: 3, windowMs: 60 * 60 * 1000 },
|
|
93
|
+
* });
|
|
94
|
+
*
|
|
95
|
+
* // Apply to procedures
|
|
96
|
+
* const login = procedure()
|
|
97
|
+
* .use(authRateLimiter.login(ctx => ctx.input.email))
|
|
98
|
+
* .mutation(loginHandler);
|
|
99
|
+
*
|
|
100
|
+
* const register = procedure()
|
|
101
|
+
* .use(authRateLimiter.register())
|
|
102
|
+
* .mutation(registerHandler);
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
export declare function createAuthRateLimiter(config?: AuthRateLimiterConfig): {
|
|
106
|
+
/**
|
|
107
|
+
* Rate limiter for login attempts
|
|
108
|
+
*
|
|
109
|
+
* @param identifierFn - Function to extract identifier (email) from context
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* ```typescript
|
|
113
|
+
* login: procedure()
|
|
114
|
+
* .use(authRateLimiter.login((ctx) => (ctx.input as { email: string }).email))
|
|
115
|
+
* .input(LoginSchema)
|
|
116
|
+
* .mutation(handler)
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
login: <TInput, TContext extends BaseContext, TOutput>(identifierFn?: (ctx: TContext & {
|
|
120
|
+
input?: unknown;
|
|
121
|
+
}) => string) => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
122
|
+
/**
|
|
123
|
+
* Rate limiter for registration attempts
|
|
124
|
+
* Uses IP-only by default (no identifier needed)
|
|
125
|
+
*/
|
|
126
|
+
register: <TInput, TContext extends BaseContext, TOutput>() => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
127
|
+
/**
|
|
128
|
+
* Rate limiter for password reset requests
|
|
129
|
+
*
|
|
130
|
+
* @param identifierFn - Optional function to extract identifier (email)
|
|
131
|
+
*/
|
|
132
|
+
passwordReset: <TInput, TContext extends BaseContext, TOutput>(identifierFn?: (ctx: TContext & {
|
|
133
|
+
input?: unknown;
|
|
134
|
+
}) => string) => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
135
|
+
/**
|
|
136
|
+
* Rate limiter for token refresh
|
|
137
|
+
*/
|
|
138
|
+
refresh: <TInput, TContext extends BaseContext, TOutput>() => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
139
|
+
/**
|
|
140
|
+
* Record a failed attempt (call after authentication fails)
|
|
141
|
+
*
|
|
142
|
+
* This allows tracking failures even when rate limit hasn't been hit,
|
|
143
|
+
* enabling account lockout after X failed passwords.
|
|
144
|
+
*
|
|
145
|
+
* @param key - Rate limit key (usually IP:email or IP)
|
|
146
|
+
* @param operation - Operation type for key namespacing
|
|
147
|
+
*/
|
|
148
|
+
recordFailure: (key: string, operation: "login" | "register" | "password-reset") => void;
|
|
149
|
+
/**
|
|
150
|
+
* Reset rate limit for a key (call after successful auth)
|
|
151
|
+
*/
|
|
152
|
+
resetLimit: (key: string, operation: "login" | "register" | "password-reset") => void;
|
|
153
|
+
/**
|
|
154
|
+
* Check if a key is currently locked out
|
|
155
|
+
*/
|
|
156
|
+
isLockedOut: (key: string, operation: "login" | "register" | "password-reset") => boolean;
|
|
157
|
+
/**
|
|
158
|
+
* Get remaining attempts for a key
|
|
159
|
+
*/
|
|
160
|
+
getRemainingAttempts: (key: string, operation: "login" | "register" | "password-reset" | "refresh") => number;
|
|
161
|
+
};
|
|
162
|
+
/**
|
|
163
|
+
* Pre-configured auth rate limiter with sensible defaults
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* ```typescript
|
|
167
|
+
* import { authRateLimiter } from '@veloxts/auth';
|
|
168
|
+
*
|
|
169
|
+
* const login = procedure()
|
|
170
|
+
* .use(authRateLimiter.login((ctx) => ctx.input.email))
|
|
171
|
+
* .mutation(handler);
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
174
|
+
export declare const authRateLimiter: {
|
|
175
|
+
/**
|
|
176
|
+
* Rate limiter for login attempts
|
|
177
|
+
*
|
|
178
|
+
* @param identifierFn - Function to extract identifier (email) from context
|
|
179
|
+
*
|
|
180
|
+
* @example
|
|
181
|
+
* ```typescript
|
|
182
|
+
* login: procedure()
|
|
183
|
+
* .use(authRateLimiter.login((ctx) => (ctx.input as { email: string }).email))
|
|
184
|
+
* .input(LoginSchema)
|
|
185
|
+
* .mutation(handler)
|
|
186
|
+
* ```
|
|
187
|
+
*/
|
|
188
|
+
login: <TInput, TContext extends BaseContext, TOutput>(identifierFn?: (ctx: TContext & {
|
|
189
|
+
input?: unknown;
|
|
190
|
+
}) => string) => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
191
|
+
/**
|
|
192
|
+
* Rate limiter for registration attempts
|
|
193
|
+
* Uses IP-only by default (no identifier needed)
|
|
194
|
+
*/
|
|
195
|
+
register: <TInput, TContext extends BaseContext, TOutput>() => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
196
|
+
/**
|
|
197
|
+
* Rate limiter for password reset requests
|
|
198
|
+
*
|
|
199
|
+
* @param identifierFn - Optional function to extract identifier (email)
|
|
200
|
+
*/
|
|
201
|
+
passwordReset: <TInput, TContext extends BaseContext, TOutput>(identifierFn?: (ctx: TContext & {
|
|
202
|
+
input?: unknown;
|
|
203
|
+
}) => string) => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
204
|
+
/**
|
|
205
|
+
* Rate limiter for token refresh
|
|
206
|
+
*/
|
|
207
|
+
refresh: <TInput, TContext extends BaseContext, TOutput>() => MiddlewareFunction<TInput, TContext, TContext, TOutput>;
|
|
208
|
+
/**
|
|
209
|
+
* Record a failed attempt (call after authentication fails)
|
|
210
|
+
*
|
|
211
|
+
* This allows tracking failures even when rate limit hasn't been hit,
|
|
212
|
+
* enabling account lockout after X failed passwords.
|
|
213
|
+
*
|
|
214
|
+
* @param key - Rate limit key (usually IP:email or IP)
|
|
215
|
+
* @param operation - Operation type for key namespacing
|
|
216
|
+
*/
|
|
217
|
+
recordFailure: (key: string, operation: "login" | "register" | "password-reset") => void;
|
|
218
|
+
/**
|
|
219
|
+
* Reset rate limit for a key (call after successful auth)
|
|
220
|
+
*/
|
|
221
|
+
resetLimit: (key: string, operation: "login" | "register" | "password-reset") => void;
|
|
222
|
+
/**
|
|
223
|
+
* Check if a key is currently locked out
|
|
224
|
+
*/
|
|
225
|
+
isLockedOut: (key: string, operation: "login" | "register" | "password-reset") => boolean;
|
|
226
|
+
/**
|
|
227
|
+
* Get remaining attempts for a key
|
|
228
|
+
*/
|
|
229
|
+
getRemainingAttempts: (key: string, operation: "login" | "register" | "password-reset" | "refresh") => number;
|
|
230
|
+
};
|
|
231
|
+
//# sourceMappingURL=rate-limit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAQ1D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;OAGG;IACH,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM,KAAK,MAAM,CAAC;IAEjE;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAgBD;;GAEG;AACH,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAE5B;;;OAGG;IACH,QAAQ,CAAC,EAAE,mBAAmB,CAAC;IAE/B;;;OAGG;IACH,aAAa,CAAC,EAAE,mBAAmB,CAAC;IAEpC;;;OAGG;IACH,OAAO,CAAC,EAAE,mBAAmB,CAAC;CAC/B;AAiDD;;GAEG;AACH,wBAAgB,wBAAwB,IAAI,IAAI,CAK/C;AAED;;GAEG;AACH,wBAAgB,uBAAuB,IAAI,IAAI,CAE9C;AASD;;;;;;;;;;;;;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AAO,iBACpC,CAAC,GAAG,EAAE,QAAQ,GAAG;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,KAAK,MAAM,KAC7D,kBAAkB,CAAC,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC;IAI1D;;;OAGG;eACQ,MAAM,EAAE,QAAQ,SAAS,WAAW,EAAE,OAAO,OAAK,kBAAkB,CAC7E,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,OAAO,CACR;IAID;;;;OAIG;oBACa,MAAM,EAAE,QAAQ,SAAS,WAAW,EAAE,OAAO,iBAC5C,CAAC,GAAG,EAAE,QAAQ,GAAG;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,KAAK,MAAM,KAC7D,kBAAkB,CAAC,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC;IAI1D;;OAEG;cACO,MAAM,EAAE,QAAQ,SAAS,WAAW,EAAE,OAAO,OAAK,kBAAkB,CAC5E,MAAM,EACN,QAAQ,EACR,QAAQ,EACR,OAAO,CACR;IAID;;;;;;;;OAQG;yBACkB,MAAM,aAAa,OAAO,GAAG,UAAU,GAAG,gBAAgB;IAiC/E;;OAEG;sBACe,MAAM,aAAa,OAAO,GAAG,UAAU,GAAG,gBAAgB;IAK5E;;OAEG;uBACgB,MAAM,aAAa,OAAO,GAAG,UAAU,GAAG,gBAAgB,KAAG,OAAO;IAYvF;;OAEG;gCAEI,MAAM,aACA,OAAO,GAAG,UAAU,GAAG,gBAAgB,GAAG,SAAS,KAC7D,MAAM;CAwJyC,CAAC"}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authentication-specific rate limiting
|
|
3
|
+
*
|
|
4
|
+
* Provides specialized rate limiters for authentication endpoints with:
|
|
5
|
+
* - Per-email+IP tracking (prevents brute force on specific accounts)
|
|
6
|
+
* - Account lockout detection
|
|
7
|
+
* - Separate limits for login, register, and password reset
|
|
8
|
+
* - Progressive backoff support
|
|
9
|
+
*
|
|
10
|
+
* @module auth/rate-limit
|
|
11
|
+
*/
|
|
12
|
+
import { AuthError } from './types.js';
|
|
13
|
+
// ============================================================================
|
|
14
|
+
// Rate Limit Store
|
|
15
|
+
// ============================================================================
|
|
16
|
+
/**
|
|
17
|
+
* In-memory rate limit store
|
|
18
|
+
*
|
|
19
|
+
* PRODUCTION NOTE: Replace with Redis for horizontal scaling:
|
|
20
|
+
* ```typescript
|
|
21
|
+
* import Redis from 'ioredis';
|
|
22
|
+
* const redis = new Redis(process.env.REDIS_URL);
|
|
23
|
+
*
|
|
24
|
+
* // Store entry as JSON with TTL
|
|
25
|
+
* await redis.setex(`ratelimit:${key}`, ttlSeconds, JSON.stringify(entry));
|
|
26
|
+
*
|
|
27
|
+
* // Get entry
|
|
28
|
+
* const data = await redis.get(`ratelimit:${key}`);
|
|
29
|
+
* const entry = data ? JSON.parse(data) : null;
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
const authRateLimitStore = new Map();
|
|
33
|
+
/**
|
|
34
|
+
* Cleanup interval reference
|
|
35
|
+
*/
|
|
36
|
+
let cleanupInterval = null;
|
|
37
|
+
/**
|
|
38
|
+
* Start periodic cleanup of expired entries
|
|
39
|
+
*/
|
|
40
|
+
function startCleanup() {
|
|
41
|
+
if (cleanupInterval)
|
|
42
|
+
return;
|
|
43
|
+
cleanupInterval = setInterval(() => {
|
|
44
|
+
const now = Date.now();
|
|
45
|
+
for (const [key, entry] of authRateLimitStore.entries()) {
|
|
46
|
+
// Remove if both window and lockout have expired
|
|
47
|
+
const windowExpired = entry.windowResetAt <= now;
|
|
48
|
+
const lockoutExpired = !entry.lockoutUntil || entry.lockoutUntil <= now;
|
|
49
|
+
if (windowExpired && lockoutExpired) {
|
|
50
|
+
authRateLimitStore.delete(key);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}, 60000); // Run every minute
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Stop cleanup interval (for testing)
|
|
57
|
+
*/
|
|
58
|
+
export function stopAuthRateLimitCleanup() {
|
|
59
|
+
if (cleanupInterval) {
|
|
60
|
+
clearInterval(cleanupInterval);
|
|
61
|
+
cleanupInterval = null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Clear all rate limit entries (for testing)
|
|
66
|
+
*/
|
|
67
|
+
export function clearAuthRateLimitStore() {
|
|
68
|
+
authRateLimitStore.clear();
|
|
69
|
+
}
|
|
70
|
+
// Start cleanup on module load
|
|
71
|
+
startCleanup();
|
|
72
|
+
// ============================================================================
|
|
73
|
+
// Auth Rate Limiter
|
|
74
|
+
// ============================================================================
|
|
75
|
+
/**
|
|
76
|
+
* Creates an authentication rate limiter
|
|
77
|
+
*
|
|
78
|
+
* This factory returns rate limit middlewares configured for different
|
|
79
|
+
* auth operations with sensible defaults.
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* ```typescript
|
|
83
|
+
* const authRateLimiter = createAuthRateLimiter({
|
|
84
|
+
* login: { maxAttempts: 5, windowMs: 15 * 60 * 1000 },
|
|
85
|
+
* register: { maxAttempts: 3, windowMs: 60 * 60 * 1000 },
|
|
86
|
+
* });
|
|
87
|
+
*
|
|
88
|
+
* // Apply to procedures
|
|
89
|
+
* const login = procedure()
|
|
90
|
+
* .use(authRateLimiter.login(ctx => ctx.input.email))
|
|
91
|
+
* .mutation(loginHandler);
|
|
92
|
+
*
|
|
93
|
+
* const register = procedure()
|
|
94
|
+
* .use(authRateLimiter.register())
|
|
95
|
+
* .mutation(registerHandler);
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
export function createAuthRateLimiter(config = {}) {
|
|
99
|
+
// Default configurations
|
|
100
|
+
const loginConfig = {
|
|
101
|
+
maxAttempts: config.login?.maxAttempts ?? 5,
|
|
102
|
+
windowMs: config.login?.windowMs ?? 15 * 60 * 1000, // 15 minutes
|
|
103
|
+
lockoutDurationMs: config.login?.lockoutDurationMs ?? 15 * 60 * 1000,
|
|
104
|
+
keyGenerator: config.login?.keyGenerator ?? defaultKeyGenerator,
|
|
105
|
+
message: config.login?.message ?? 'Too many login attempts. Please try again later.',
|
|
106
|
+
progressiveBackoff: config.login?.progressiveBackoff ?? true,
|
|
107
|
+
};
|
|
108
|
+
const registerConfig = {
|
|
109
|
+
maxAttempts: config.register?.maxAttempts ?? 3,
|
|
110
|
+
windowMs: config.register?.windowMs ?? 60 * 60 * 1000, // 1 hour
|
|
111
|
+
lockoutDurationMs: config.register?.lockoutDurationMs ?? 60 * 60 * 1000,
|
|
112
|
+
keyGenerator: config.register?.keyGenerator ?? ((ctx) => ctx.request.ip ?? 'unknown'),
|
|
113
|
+
message: config.register?.message ?? 'Too many registration attempts. Please try again later.',
|
|
114
|
+
progressiveBackoff: config.register?.progressiveBackoff ?? false,
|
|
115
|
+
};
|
|
116
|
+
const passwordResetConfig = {
|
|
117
|
+
maxAttempts: config.passwordReset?.maxAttempts ?? 3,
|
|
118
|
+
windowMs: config.passwordReset?.windowMs ?? 60 * 60 * 1000, // 1 hour
|
|
119
|
+
lockoutDurationMs: config.passwordReset?.lockoutDurationMs ?? 60 * 60 * 1000,
|
|
120
|
+
keyGenerator: config.passwordReset?.keyGenerator ?? ((ctx) => ctx.request.ip ?? 'unknown'),
|
|
121
|
+
message: config.passwordReset?.message ?? 'Too many password reset attempts. Please try again later.',
|
|
122
|
+
progressiveBackoff: config.passwordReset?.progressiveBackoff ?? false,
|
|
123
|
+
};
|
|
124
|
+
const refreshConfig = {
|
|
125
|
+
maxAttempts: config.refresh?.maxAttempts ?? 10,
|
|
126
|
+
windowMs: config.refresh?.windowMs ?? 60 * 1000, // 1 minute
|
|
127
|
+
lockoutDurationMs: config.refresh?.lockoutDurationMs ?? 60 * 1000,
|
|
128
|
+
keyGenerator: config.refresh?.keyGenerator ?? ((ctx) => ctx.request.ip ?? 'unknown'),
|
|
129
|
+
message: config.refresh?.message ?? 'Too many token refresh attempts. Please try again later.',
|
|
130
|
+
progressiveBackoff: config.refresh?.progressiveBackoff ?? false,
|
|
131
|
+
};
|
|
132
|
+
return {
|
|
133
|
+
/**
|
|
134
|
+
* Rate limiter for login attempts
|
|
135
|
+
*
|
|
136
|
+
* @param identifierFn - Function to extract identifier (email) from context
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* ```typescript
|
|
140
|
+
* login: procedure()
|
|
141
|
+
* .use(authRateLimiter.login((ctx) => (ctx.input as { email: string }).email))
|
|
142
|
+
* .input(LoginSchema)
|
|
143
|
+
* .mutation(handler)
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
login: (identifierFn) => {
|
|
147
|
+
return createRateLimitMiddleware(loginConfig, 'login', identifierFn);
|
|
148
|
+
},
|
|
149
|
+
/**
|
|
150
|
+
* Rate limiter for registration attempts
|
|
151
|
+
* Uses IP-only by default (no identifier needed)
|
|
152
|
+
*/
|
|
153
|
+
register: () => {
|
|
154
|
+
return createRateLimitMiddleware(registerConfig, 'register');
|
|
155
|
+
},
|
|
156
|
+
/**
|
|
157
|
+
* Rate limiter for password reset requests
|
|
158
|
+
*
|
|
159
|
+
* @param identifierFn - Optional function to extract identifier (email)
|
|
160
|
+
*/
|
|
161
|
+
passwordReset: (identifierFn) => {
|
|
162
|
+
return createRateLimitMiddleware(passwordResetConfig, 'password-reset', identifierFn);
|
|
163
|
+
},
|
|
164
|
+
/**
|
|
165
|
+
* Rate limiter for token refresh
|
|
166
|
+
*/
|
|
167
|
+
refresh: () => {
|
|
168
|
+
return createRateLimitMiddleware(refreshConfig, 'refresh');
|
|
169
|
+
},
|
|
170
|
+
/**
|
|
171
|
+
* Record a failed attempt (call after authentication fails)
|
|
172
|
+
*
|
|
173
|
+
* This allows tracking failures even when rate limit hasn't been hit,
|
|
174
|
+
* enabling account lockout after X failed passwords.
|
|
175
|
+
*
|
|
176
|
+
* @param key - Rate limit key (usually IP:email or IP)
|
|
177
|
+
* @param operation - Operation type for key namespacing
|
|
178
|
+
*/
|
|
179
|
+
recordFailure: (key, operation) => {
|
|
180
|
+
const fullKey = `auth:${operation}:${key}`;
|
|
181
|
+
const config = operation === 'login'
|
|
182
|
+
? loginConfig
|
|
183
|
+
: operation === 'register'
|
|
184
|
+
? registerConfig
|
|
185
|
+
: passwordResetConfig;
|
|
186
|
+
const now = Date.now();
|
|
187
|
+
const entry = authRateLimitStore.get(fullKey);
|
|
188
|
+
if (!entry || entry.windowResetAt <= now) {
|
|
189
|
+
// Start new window
|
|
190
|
+
authRateLimitStore.set(fullKey, {
|
|
191
|
+
attempts: 1,
|
|
192
|
+
windowResetAt: now + config.windowMs,
|
|
193
|
+
lockoutUntil: null,
|
|
194
|
+
lockoutCount: entry?.lockoutCount ?? 0,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
// Increment in current window
|
|
199
|
+
entry.attempts++;
|
|
200
|
+
// Check if lockout should trigger
|
|
201
|
+
if (entry.attempts >= config.maxAttempts) {
|
|
202
|
+
const lockoutMultiplier = config.progressiveBackoff ? 2 ** entry.lockoutCount : 1;
|
|
203
|
+
entry.lockoutUntil = now + config.lockoutDurationMs * lockoutMultiplier;
|
|
204
|
+
entry.lockoutCount++;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
/**
|
|
209
|
+
* Reset rate limit for a key (call after successful auth)
|
|
210
|
+
*/
|
|
211
|
+
resetLimit: (key, operation) => {
|
|
212
|
+
const fullKey = `auth:${operation}:${key}`;
|
|
213
|
+
authRateLimitStore.delete(fullKey);
|
|
214
|
+
},
|
|
215
|
+
/**
|
|
216
|
+
* Check if a key is currently locked out
|
|
217
|
+
*/
|
|
218
|
+
isLockedOut: (key, operation) => {
|
|
219
|
+
const fullKey = `auth:${operation}:${key}`;
|
|
220
|
+
const entry = authRateLimitStore.get(fullKey);
|
|
221
|
+
if (!entry || !entry.lockoutUntil)
|
|
222
|
+
return false;
|
|
223
|
+
if (entry.lockoutUntil <= Date.now()) {
|
|
224
|
+
// Lockout expired
|
|
225
|
+
return false;
|
|
226
|
+
}
|
|
227
|
+
return true;
|
|
228
|
+
},
|
|
229
|
+
/**
|
|
230
|
+
* Get remaining attempts for a key
|
|
231
|
+
*/
|
|
232
|
+
getRemainingAttempts: (key, operation) => {
|
|
233
|
+
const fullKey = `auth:${operation}:${key}`;
|
|
234
|
+
const config = operation === 'login'
|
|
235
|
+
? loginConfig
|
|
236
|
+
: operation === 'register'
|
|
237
|
+
? registerConfig
|
|
238
|
+
: operation === 'refresh'
|
|
239
|
+
? refreshConfig
|
|
240
|
+
: passwordResetConfig;
|
|
241
|
+
const entry = authRateLimitStore.get(fullKey);
|
|
242
|
+
if (!entry || entry.windowResetAt <= Date.now()) {
|
|
243
|
+
return config.maxAttempts;
|
|
244
|
+
}
|
|
245
|
+
return Math.max(0, config.maxAttempts - entry.attempts);
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
// ============================================================================
|
|
250
|
+
// Internal Helpers
|
|
251
|
+
// ============================================================================
|
|
252
|
+
/**
|
|
253
|
+
* Default key generator combining IP and identifier
|
|
254
|
+
*/
|
|
255
|
+
function defaultKeyGenerator(ctx, identifier) {
|
|
256
|
+
const ip = ctx.request.ip ?? 'unknown';
|
|
257
|
+
return identifier ? `${ip}:${identifier.toLowerCase()}` : ip;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Creates the actual rate limit middleware
|
|
261
|
+
*/
|
|
262
|
+
function createRateLimitMiddleware(config, operation, identifierFn) {
|
|
263
|
+
return async ({ ctx, input, next }) => {
|
|
264
|
+
const now = Date.now();
|
|
265
|
+
// Generate rate limit key
|
|
266
|
+
const identifier = identifierFn ? identifierFn({ ...ctx, input }) : undefined;
|
|
267
|
+
const baseKey = config.keyGenerator(ctx, identifier);
|
|
268
|
+
const key = `auth:${operation}:${baseKey}`;
|
|
269
|
+
// Get or create entry
|
|
270
|
+
let entry = authRateLimitStore.get(key);
|
|
271
|
+
// Check if currently locked out
|
|
272
|
+
if (entry?.lockoutUntil && entry.lockoutUntil > now) {
|
|
273
|
+
const retryAfter = Math.ceil((entry.lockoutUntil - now) / 1000);
|
|
274
|
+
// Set headers
|
|
275
|
+
ctx.reply.header('X-RateLimit-Limit', String(config.maxAttempts));
|
|
276
|
+
ctx.reply.header('X-RateLimit-Remaining', '0');
|
|
277
|
+
ctx.reply.header('X-RateLimit-Reset', String(Math.ceil(entry.lockoutUntil / 1000)));
|
|
278
|
+
ctx.reply.header('Retry-After', String(retryAfter));
|
|
279
|
+
throw new AuthError(`${config.message} Try again in ${formatDuration(retryAfter * 1000)}.`, 429, 'RATE_LIMIT_EXCEEDED');
|
|
280
|
+
}
|
|
281
|
+
// Clean up expired window
|
|
282
|
+
if (entry && entry.windowResetAt <= now) {
|
|
283
|
+
// Preserve lockout count for progressive backoff
|
|
284
|
+
const lockoutCount = entry.lockoutCount;
|
|
285
|
+
entry = {
|
|
286
|
+
attempts: 0,
|
|
287
|
+
windowResetAt: now + config.windowMs,
|
|
288
|
+
lockoutUntil: null,
|
|
289
|
+
lockoutCount,
|
|
290
|
+
};
|
|
291
|
+
authRateLimitStore.set(key, entry);
|
|
292
|
+
}
|
|
293
|
+
// Initialize if no entry
|
|
294
|
+
if (!entry) {
|
|
295
|
+
entry = {
|
|
296
|
+
attempts: 0,
|
|
297
|
+
windowResetAt: now + config.windowMs,
|
|
298
|
+
lockoutUntil: null,
|
|
299
|
+
lockoutCount: 0,
|
|
300
|
+
};
|
|
301
|
+
authRateLimitStore.set(key, entry);
|
|
302
|
+
}
|
|
303
|
+
// Increment attempt count
|
|
304
|
+
entry.attempts++;
|
|
305
|
+
// Set rate limit headers
|
|
306
|
+
const remaining = Math.max(0, config.maxAttempts - entry.attempts);
|
|
307
|
+
ctx.reply.header('X-RateLimit-Limit', String(config.maxAttempts));
|
|
308
|
+
ctx.reply.header('X-RateLimit-Remaining', String(remaining));
|
|
309
|
+
ctx.reply.header('X-RateLimit-Reset', String(Math.ceil(entry.windowResetAt / 1000)));
|
|
310
|
+
// Check if limit exceeded
|
|
311
|
+
if (entry.attempts > config.maxAttempts) {
|
|
312
|
+
// Apply lockout
|
|
313
|
+
const lockoutMultiplier = config.progressiveBackoff ? 2 ** entry.lockoutCount : 1;
|
|
314
|
+
entry.lockoutUntil = now + config.lockoutDurationMs * lockoutMultiplier;
|
|
315
|
+
entry.lockoutCount++;
|
|
316
|
+
const retryAfter = Math.ceil((entry.lockoutUntil - now) / 1000);
|
|
317
|
+
ctx.reply.header('Retry-After', String(retryAfter));
|
|
318
|
+
throw new AuthError(`${config.message} Try again in ${formatDuration(retryAfter * 1000)}.`, 429, 'RATE_LIMIT_EXCEEDED');
|
|
319
|
+
}
|
|
320
|
+
return next();
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Format duration in human-readable form
|
|
325
|
+
*/
|
|
326
|
+
function formatDuration(ms) {
|
|
327
|
+
const seconds = Math.ceil(ms / 1000);
|
|
328
|
+
if (seconds < 60)
|
|
329
|
+
return `${seconds} second${seconds !== 1 ? 's' : ''}`;
|
|
330
|
+
const minutes = Math.ceil(seconds / 60);
|
|
331
|
+
if (minutes < 60)
|
|
332
|
+
return `${minutes} minute${minutes !== 1 ? 's' : ''}`;
|
|
333
|
+
const hours = Math.ceil(minutes / 60);
|
|
334
|
+
return `${hours} hour${hours !== 1 ? 's' : ''}`;
|
|
335
|
+
}
|
|
336
|
+
// ============================================================================
|
|
337
|
+
// Convenience Export
|
|
338
|
+
// ============================================================================
|
|
339
|
+
/**
|
|
340
|
+
* Pre-configured auth rate limiter with sensible defaults
|
|
341
|
+
*
|
|
342
|
+
* @example
|
|
343
|
+
* ```typescript
|
|
344
|
+
* import { authRateLimiter } from '@veloxts/auth';
|
|
345
|
+
*
|
|
346
|
+
* const login = procedure()
|
|
347
|
+
* .use(authRateLimiter.login((ctx) => ctx.input.email))
|
|
348
|
+
* .mutation(handler);
|
|
349
|
+
* ```
|
|
350
|
+
*/
|
|
351
|
+
export const authRateLimiter = createAuthRateLimiter();
|
|
352
|
+
//# sourceMappingURL=rate-limit.js.map
|