@veloxts/auth 0.6.56 → 0.6.58

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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # @veloxts/auth
2
2
 
3
+ ## 0.6.58
4
+
5
+ ### Patch Changes
6
+
7
+ - feat(router): add OpenAPI 3.0.3 specification generator
8
+ - Updated dependencies
9
+ - @veloxts/core@0.6.58
10
+ - @veloxts/router@0.6.58
11
+
12
+ ## 0.6.57
13
+
14
+ ### Patch Changes
15
+
16
+ - feat: add DI support to ecosystem packages and main packages
17
+ - Updated dependencies
18
+ - @veloxts/core@0.6.57
19
+ - @veloxts/router@0.6.57
20
+
3
21
  ## 0.6.56
4
22
 
5
23
  ### Patch Changes
package/dist/index.d.ts CHANGED
@@ -20,7 +20,7 @@ export { hashPassword, PasswordHasher, passwordHasher, verifyPassword, } from '.
20
20
  export { allOf, anyOf, authenticated, defineGuard, emailVerified, executeGuard, executeGuards, guard, hasAnyPermission, hasPermission, hasRole, not, userCan, } from './guards.js';
21
21
  export { authorize, can, cannot, clearPolicies, createAdminOnlyPolicy, createOwnerOrAdminPolicy, createPolicyBuilder, createReadOnlyPolicy, definePolicy, getPolicy, registerPolicy, } from './policies.js';
22
22
  export { authMiddleware, clearRateLimitStore, rateLimitMiddleware, } from './middleware.js';
23
- export type { AuthRateLimitConfig, AuthRateLimiterConfig } from './rate-limit.js';
23
+ export type { AuthRateLimitConfig, AuthRateLimiter, AuthRateLimiterConfig } from './rate-limit.js';
24
24
  export { authRateLimiter, clearAuthRateLimitStore, createAuthRateLimiter, stopAuthRateLimitCleanup, } from './rate-limit.js';
25
25
  export type { AuthPluginOptions, AuthService } from './plugin.js';
26
26
  export { authPlugin, defaultAuthPlugin, } from './plugin.js';
@@ -34,3 +34,24 @@ export type { BetterAuthAdapterConfig, BetterAuthApi, BetterAuthHandler, BetterA
34
34
  export { BetterAuthAdapter, createBetterAuthAdapter } from './adapters/better-auth.js';
35
35
  export type { PasswordPolicyConfig, PasswordValidationResult, UserInfo, } from './password-policy.js';
36
36
  export { checkPasswordBreach, checkPasswordStrength, isCommonPassword, PasswordPolicy, PasswordStrength, passwordPolicy, } from './password-policy.js';
37
+ /**
38
+ * DI tokens and providers for @veloxts/auth
39
+ *
40
+ * Use these to integrate auth services with the @veloxts/core DI container.
41
+ *
42
+ * @example
43
+ * ```typescript
44
+ * import { Container } from '@veloxts/core';
45
+ * import { registerAuthProviders, JWT_MANAGER, PASSWORD_HASHER } from '@veloxts/auth';
46
+ *
47
+ * const container = new Container();
48
+ * registerAuthProviders(container, {
49
+ * jwt: { secret: process.env.JWT_SECRET! }
50
+ * });
51
+ *
52
+ * const jwt = container.resolve(JWT_MANAGER);
53
+ * const hasher = container.resolve(PASSWORD_HASHER);
54
+ * ```
55
+ */
56
+ export { authServiceProvider, jwtManagerProvider, passwordHasherProvider, passwordHasherProviderWithDefaults, registerAuthProviders, } from './providers.js';
57
+ export { AUTH_CONFIG, AUTH_RATE_LIMITER, AUTH_SERVICE, CSRF_CONFIG, HASH_CONFIG, JWT_CONFIG, JWT_MANAGER, PASSWORD_HASHER, RATE_LIMIT_CONFIG, SESSION_CONFIG, SESSION_STORE, TOKEN_STORE, } from './tokens.js';
package/dist/index.js CHANGED
@@ -66,3 +66,37 @@ createAdapterAuthMiddleware, createAuthAdapterPlugin, defineAuthAdapter,
66
66
  isAuthAdapter, } from './adapter.js';
67
67
  export { BetterAuthAdapter, createBetterAuthAdapter } from './adapters/better-auth.js';
68
68
  export { checkPasswordBreach, checkPasswordStrength, isCommonPassword, PasswordPolicy, PasswordStrength, passwordPolicy, } from './password-policy.js';
69
+ // ============================================================================
70
+ // Dependency Injection
71
+ // ============================================================================
72
+ /**
73
+ * DI tokens and providers for @veloxts/auth
74
+ *
75
+ * Use these to integrate auth services with the @veloxts/core DI container.
76
+ *
77
+ * @example
78
+ * ```typescript
79
+ * import { Container } from '@veloxts/core';
80
+ * import { registerAuthProviders, JWT_MANAGER, PASSWORD_HASHER } from '@veloxts/auth';
81
+ *
82
+ * const container = new Container();
83
+ * registerAuthProviders(container, {
84
+ * jwt: { secret: process.env.JWT_SECRET! }
85
+ * });
86
+ *
87
+ * const jwt = container.resolve(JWT_MANAGER);
88
+ * const hasher = container.resolve(PASSWORD_HASHER);
89
+ * ```
90
+ */
91
+ // Provider exports - factory functions for registering services
92
+ export { authServiceProvider, jwtManagerProvider, passwordHasherProvider, passwordHasherProviderWithDefaults,
93
+ // Bulk registration helper
94
+ registerAuthProviders, } from './providers.js';
95
+ // Token exports - unique identifiers for DI resolution
96
+ export {
97
+ // Config tokens
98
+ AUTH_CONFIG, AUTH_RATE_LIMITER,
99
+ // Service tokens
100
+ AUTH_SERVICE, CSRF_CONFIG, HASH_CONFIG, JWT_CONFIG, JWT_MANAGER, PASSWORD_HASHER, RATE_LIMIT_CONFIG, SESSION_CONFIG,
101
+ // Store tokens
102
+ SESSION_STORE, TOKEN_STORE, } from './tokens.js';
package/dist/plugin.d.ts CHANGED
@@ -3,7 +3,7 @@
3
3
  * Fastify plugin that integrates authentication with VeloxApp
4
4
  * @module auth/plugin
5
5
  */
6
- import type { VeloxPlugin } from '@veloxts/core';
6
+ import type { Container, VeloxPlugin } from '@veloxts/core';
7
7
  import { PasswordHasher } from './hash.js';
8
8
  import { JwtManager } from './jwt.js';
9
9
  import { authMiddleware } from './middleware.js';
@@ -19,6 +19,32 @@ export interface AuthPluginOptions extends AuthConfig {
19
19
  * @default false
20
20
  */
21
21
  debug?: boolean;
22
+ /**
23
+ * DI container for service registration and resolution (optional)
24
+ *
25
+ * When provided, auth services are registered with the container and can be:
26
+ * - Resolved from the container directly
27
+ * - Mocked in tests by overriding registrations
28
+ * - Managed alongside other application services
29
+ *
30
+ * When not provided, services are created directly (legacy behavior).
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * import { Container } from '@veloxts/core';
35
+ * import { authPlugin, JWT_MANAGER } from '@veloxts/auth';
36
+ *
37
+ * const container = new Container();
38
+ * app.register(authPlugin({
39
+ * jwt: { secret: '...' },
40
+ * container,
41
+ * }));
42
+ *
43
+ * // Services now available from container
44
+ * const jwt = container.resolve(JWT_MANAGER);
45
+ * ```
46
+ */
47
+ container?: Container;
22
48
  }
23
49
  /**
24
50
  * Auth service instance attached to Fastify
package/dist/plugin.js CHANGED
@@ -7,6 +7,8 @@ import { createRequire } from 'node:module';
7
7
  import { PasswordHasher } from './hash.js';
8
8
  import { JwtManager } from './jwt.js';
9
9
  import { authMiddleware } from './middleware.js';
10
+ import { registerAuthProviders } from './providers.js';
11
+ import { AUTH_SERVICE } from './tokens.js';
10
12
  // Read version from package.json dynamically
11
13
  const require = createRequire(import.meta.url);
12
14
  const packageJson = require('../package.json');
@@ -62,40 +64,50 @@ export function authPlugin(options) {
62
64
  // The plugin decorates Fastify with auth functionality
63
65
  async register(server, _opts) {
64
66
  const config = { ...options, ..._opts };
65
- const { debug = false } = config;
67
+ const { debug = false, container } = config;
66
68
  if (debug) {
67
69
  server.log.info('Registering @veloxts/auth plugin');
68
70
  }
69
- // Create instances
70
- const jwt = new JwtManager(config.jwt);
71
- const hasher = new PasswordHasher(config.hash);
72
- const authMw = authMiddleware(config);
73
- // Create auth service
74
- const authService = {
75
- jwt,
76
- hasher,
77
- createTokens(user, additionalClaims) {
78
- return jwt.createTokenPair(user, additionalClaims);
79
- },
80
- verifyToken(token) {
81
- const payload = jwt.verifyToken(token);
82
- return {
83
- user: {
84
- id: payload.sub,
85
- email: payload.email,
86
- },
87
- token: payload,
88
- isAuthenticated: true,
89
- };
90
- },
91
- refreshTokens(refreshToken) {
92
- if (config.userLoader) {
93
- return jwt.refreshTokens(refreshToken, config.userLoader);
94
- }
95
- return jwt.refreshTokens(refreshToken);
96
- },
97
- middleware: authMw,
98
- };
71
+ let authService;
72
+ if (container) {
73
+ // DI-enabled path: Register providers and resolve from container
74
+ if (debug) {
75
+ server.log.info('Using DI container for auth services');
76
+ }
77
+ registerAuthProviders(container, config);
78
+ authService = container.resolve(AUTH_SERVICE);
79
+ }
80
+ else {
81
+ // Legacy path: Direct instantiation (backward compatible)
82
+ const jwt = new JwtManager(config.jwt);
83
+ const hasher = new PasswordHasher(config.hash);
84
+ const authMw = authMiddleware(config);
85
+ authService = {
86
+ jwt,
87
+ hasher,
88
+ createTokens(user, additionalClaims) {
89
+ return jwt.createTokenPair(user, additionalClaims);
90
+ },
91
+ verifyToken(token) {
92
+ const payload = jwt.verifyToken(token);
93
+ return {
94
+ user: {
95
+ id: payload.sub,
96
+ email: payload.email,
97
+ },
98
+ token: payload,
99
+ isAuthenticated: true,
100
+ };
101
+ },
102
+ refreshTokens(refreshToken) {
103
+ if (config.userLoader) {
104
+ return jwt.refreshTokens(refreshToken, config.userLoader);
105
+ }
106
+ return jwt.refreshTokens(refreshToken);
107
+ },
108
+ middleware: authMw,
109
+ };
110
+ }
99
111
  // Decorate server with auth service
100
112
  server.decorate('auth', authService);
101
113
  // Decorate requests with auth context (undefined initial value)
@@ -105,10 +117,10 @@ export function authPlugin(options) {
105
117
  if (config.autoExtract !== false) {
106
118
  server.addHook('preHandler', async (request) => {
107
119
  const authHeader = request.headers.authorization;
108
- const token = jwt.extractFromHeader(authHeader);
120
+ const token = authService.jwt.extractFromHeader(authHeader);
109
121
  if (token) {
110
122
  try {
111
- const payload = jwt.verifyToken(token);
123
+ const payload = authService.jwt.verifyToken(token);
112
124
  // Check if token is revoked
113
125
  if (config.isTokenRevoked && payload.jti) {
114
126
  const revoked = await config.isTokenRevoked(payload.jti);
@@ -0,0 +1,129 @@
1
+ /**
2
+ * DI Providers for @veloxts/auth
3
+ *
4
+ * Factory provider functions for registering auth services with the DI container.
5
+ * These providers allow services to be managed by the container for testability and flexibility.
6
+ *
7
+ * @module auth/providers
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { Container } from '@veloxts/core';
12
+ * import { registerAuthProviders, JWT_MANAGER } from '@veloxts/auth';
13
+ *
14
+ * const container = new Container();
15
+ * registerAuthProviders(container, {
16
+ * jwt: { secret: process.env.JWT_SECRET! }
17
+ * });
18
+ *
19
+ * const jwt = container.resolve(JWT_MANAGER);
20
+ * ```
21
+ */
22
+ import { type Container, type FactoryProvider } from '@veloxts/core';
23
+ import { PasswordHasher } from './hash.js';
24
+ import { JwtManager } from './jwt.js';
25
+ import type { AuthService } from './plugin.js';
26
+ import type { AuthConfig } from './types.js';
27
+ /**
28
+ * Creates a factory provider for JwtManager
29
+ *
30
+ * Requires JWT_CONFIG to be registered in the container.
31
+ *
32
+ * @example
33
+ * ```typescript
34
+ * container.register({ provide: JWT_CONFIG, useValue: { secret: '...' } });
35
+ * container.register(jwtManagerProvider());
36
+ * const jwt = container.resolve(JWT_MANAGER);
37
+ * ```
38
+ */
39
+ export declare function jwtManagerProvider(): FactoryProvider<JwtManager>;
40
+ /**
41
+ * Creates a factory provider for PasswordHasher
42
+ *
43
+ * Uses HASH_CONFIG if available, otherwise uses default config.
44
+ *
45
+ * @example
46
+ * ```typescript
47
+ * // With config
48
+ * container.register({ provide: HASH_CONFIG, useValue: { algorithm: 'argon2' } });
49
+ * container.register(passwordHasherProvider());
50
+ *
51
+ * // Or without config (uses defaults)
52
+ * container.register(passwordHasherProviderWithDefaults());
53
+ * ```
54
+ */
55
+ export declare function passwordHasherProvider(): FactoryProvider<PasswordHasher>;
56
+ /**
57
+ * Creates a factory provider for PasswordHasher with default config
58
+ *
59
+ * Use this when you don't need custom hash configuration.
60
+ */
61
+ export declare function passwordHasherProviderWithDefaults(): FactoryProvider<PasswordHasher>;
62
+ /**
63
+ * Creates a factory provider for the composite AuthService
64
+ *
65
+ * Requires JWT_MANAGER, PASSWORD_HASHER, and AUTH_CONFIG to be registered.
66
+ *
67
+ * @example
68
+ * ```typescript
69
+ * registerAuthProviders(container, config);
70
+ * const auth = container.resolve(AUTH_SERVICE);
71
+ * const tokens = auth.createTokens(user);
72
+ * ```
73
+ */
74
+ export declare function authServiceProvider(): FactoryProvider<AuthService>;
75
+ /**
76
+ * Registers all auth providers with a container
77
+ *
78
+ * This is the recommended way to set up auth services with DI.
79
+ * It registers config values and all service providers in the correct order.
80
+ *
81
+ * @param container - The DI container to register providers with
82
+ * @param config - Auth configuration (jwt config is required)
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * import { Container } from '@veloxts/core';
87
+ * import { registerAuthProviders, JWT_MANAGER, PASSWORD_HASHER } from '@veloxts/auth';
88
+ *
89
+ * const container = new Container();
90
+ *
91
+ * registerAuthProviders(container, {
92
+ * jwt: {
93
+ * secret: process.env.JWT_SECRET!,
94
+ * accessTokenExpiry: '15m',
95
+ * refreshTokenExpiry: '7d',
96
+ * },
97
+ * hash: {
98
+ * algorithm: 'bcrypt',
99
+ * bcryptRounds: 12,
100
+ * },
101
+ * });
102
+ *
103
+ * // Now resolve services from container
104
+ * const jwt = container.resolve(JWT_MANAGER);
105
+ * const hasher = container.resolve(PASSWORD_HASHER);
106
+ * const auth = container.resolve(AUTH_SERVICE);
107
+ * ```
108
+ */
109
+ export declare function registerAuthProviders(container: Container, config: AuthConfig): void;
110
+ /**
111
+ * Registers mock-friendly auth providers for testing
112
+ *
113
+ * Same as registerAuthProviders but allows individual service overrides.
114
+ *
115
+ * @example
116
+ * ```typescript
117
+ * // In tests
118
+ * const container = new Container();
119
+ * registerAuthProviders(container, testConfig);
120
+ *
121
+ * // Override with mock
122
+ * const mockJwt = { createTokenPair: vi.fn() } as unknown as JwtManager;
123
+ * container.register({ provide: JWT_MANAGER, useValue: mockJwt });
124
+ *
125
+ * // AuthService will now use the mock
126
+ * const auth = container.resolve(AUTH_SERVICE);
127
+ * ```
128
+ */
129
+ export { registerAuthProviders as registerAuthProvidersForTesting };
@@ -0,0 +1,213 @@
1
+ /**
2
+ * DI Providers for @veloxts/auth
3
+ *
4
+ * Factory provider functions for registering auth services with the DI container.
5
+ * These providers allow services to be managed by the container for testability and flexibility.
6
+ *
7
+ * @module auth/providers
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { Container } from '@veloxts/core';
12
+ * import { registerAuthProviders, JWT_MANAGER } from '@veloxts/auth';
13
+ *
14
+ * const container = new Container();
15
+ * registerAuthProviders(container, {
16
+ * jwt: { secret: process.env.JWT_SECRET! }
17
+ * });
18
+ *
19
+ * const jwt = container.resolve(JWT_MANAGER);
20
+ * ```
21
+ */
22
+ import { Scope } from '@veloxts/core';
23
+ import { PasswordHasher } from './hash.js';
24
+ import { JwtManager } from './jwt.js';
25
+ import { authMiddleware } from './middleware.js';
26
+ import { AUTH_CONFIG, AUTH_SERVICE, HASH_CONFIG, JWT_CONFIG, JWT_MANAGER, PASSWORD_HASHER, } from './tokens.js';
27
+ // ============================================================================
28
+ // Service Providers
29
+ // ============================================================================
30
+ /**
31
+ * Creates a factory provider for JwtManager
32
+ *
33
+ * Requires JWT_CONFIG to be registered in the container.
34
+ *
35
+ * @example
36
+ * ```typescript
37
+ * container.register({ provide: JWT_CONFIG, useValue: { secret: '...' } });
38
+ * container.register(jwtManagerProvider());
39
+ * const jwt = container.resolve(JWT_MANAGER);
40
+ * ```
41
+ */
42
+ export function jwtManagerProvider() {
43
+ return {
44
+ provide: JWT_MANAGER,
45
+ useFactory: (config) => new JwtManager(config),
46
+ inject: [JWT_CONFIG],
47
+ scope: Scope.SINGLETON,
48
+ };
49
+ }
50
+ /**
51
+ * Creates a factory provider for PasswordHasher
52
+ *
53
+ * Uses HASH_CONFIG if available, otherwise uses default config.
54
+ *
55
+ * @example
56
+ * ```typescript
57
+ * // With config
58
+ * container.register({ provide: HASH_CONFIG, useValue: { algorithm: 'argon2' } });
59
+ * container.register(passwordHasherProvider());
60
+ *
61
+ * // Or without config (uses defaults)
62
+ * container.register(passwordHasherProviderWithDefaults());
63
+ * ```
64
+ */
65
+ export function passwordHasherProvider() {
66
+ return {
67
+ provide: PASSWORD_HASHER,
68
+ useFactory: (config) => new PasswordHasher(config),
69
+ inject: [HASH_CONFIG],
70
+ scope: Scope.SINGLETON,
71
+ };
72
+ }
73
+ /**
74
+ * Creates a factory provider for PasswordHasher with default config
75
+ *
76
+ * Use this when you don't need custom hash configuration.
77
+ */
78
+ export function passwordHasherProviderWithDefaults() {
79
+ return {
80
+ provide: PASSWORD_HASHER,
81
+ useFactory: () => new PasswordHasher(),
82
+ inject: [],
83
+ scope: Scope.SINGLETON,
84
+ };
85
+ }
86
+ /**
87
+ * Creates a factory provider for the composite AuthService
88
+ *
89
+ * Requires JWT_MANAGER, PASSWORD_HASHER, and AUTH_CONFIG to be registered.
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * registerAuthProviders(container, config);
94
+ * const auth = container.resolve(AUTH_SERVICE);
95
+ * const tokens = auth.createTokens(user);
96
+ * ```
97
+ */
98
+ export function authServiceProvider() {
99
+ return {
100
+ provide: AUTH_SERVICE,
101
+ useFactory: (jwt, hasher, config) => {
102
+ const authMw = authMiddleware(config);
103
+ return {
104
+ jwt,
105
+ hasher,
106
+ createTokens(user, additionalClaims) {
107
+ return jwt.createTokenPair(user, additionalClaims);
108
+ },
109
+ verifyToken(token) {
110
+ const payload = jwt.verifyToken(token);
111
+ return {
112
+ user: {
113
+ id: payload.sub,
114
+ email: payload.email,
115
+ },
116
+ token: payload,
117
+ isAuthenticated: true,
118
+ };
119
+ },
120
+ refreshTokens(refreshToken) {
121
+ if (config.userLoader) {
122
+ return jwt.refreshTokens(refreshToken, config.userLoader);
123
+ }
124
+ return jwt.refreshTokens(refreshToken);
125
+ },
126
+ middleware: authMw,
127
+ };
128
+ },
129
+ inject: [JWT_MANAGER, PASSWORD_HASHER, AUTH_CONFIG],
130
+ scope: Scope.SINGLETON,
131
+ };
132
+ }
133
+ // ============================================================================
134
+ // Bulk Registration Helper
135
+ // ============================================================================
136
+ /**
137
+ * Registers all auth providers with a container
138
+ *
139
+ * This is the recommended way to set up auth services with DI.
140
+ * It registers config values and all service providers in the correct order.
141
+ *
142
+ * @param container - The DI container to register providers with
143
+ * @param config - Auth configuration (jwt config is required)
144
+ *
145
+ * @example
146
+ * ```typescript
147
+ * import { Container } from '@veloxts/core';
148
+ * import { registerAuthProviders, JWT_MANAGER, PASSWORD_HASHER } from '@veloxts/auth';
149
+ *
150
+ * const container = new Container();
151
+ *
152
+ * registerAuthProviders(container, {
153
+ * jwt: {
154
+ * secret: process.env.JWT_SECRET!,
155
+ * accessTokenExpiry: '15m',
156
+ * refreshTokenExpiry: '7d',
157
+ * },
158
+ * hash: {
159
+ * algorithm: 'bcrypt',
160
+ * bcryptRounds: 12,
161
+ * },
162
+ * });
163
+ *
164
+ * // Now resolve services from container
165
+ * const jwt = container.resolve(JWT_MANAGER);
166
+ * const hasher = container.resolve(PASSWORD_HASHER);
167
+ * const auth = container.resolve(AUTH_SERVICE);
168
+ * ```
169
+ */
170
+ export function registerAuthProviders(container, config) {
171
+ // Register config values
172
+ container.register({
173
+ provide: AUTH_CONFIG,
174
+ useValue: config,
175
+ });
176
+ container.register({
177
+ provide: JWT_CONFIG,
178
+ useValue: config.jwt,
179
+ });
180
+ // Register HASH_CONFIG if provided, otherwise use undefined
181
+ // PasswordHasher handles undefined config gracefully
182
+ container.register({
183
+ provide: HASH_CONFIG,
184
+ useValue: config.hash,
185
+ });
186
+ // Register service providers
187
+ container.register(jwtManagerProvider());
188
+ container.register(passwordHasherProvider());
189
+ container.register(authServiceProvider());
190
+ }
191
+ // ============================================================================
192
+ // Testing Utilities
193
+ // ============================================================================
194
+ /**
195
+ * Registers mock-friendly auth providers for testing
196
+ *
197
+ * Same as registerAuthProviders but allows individual service overrides.
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * // In tests
202
+ * const container = new Container();
203
+ * registerAuthProviders(container, testConfig);
204
+ *
205
+ * // Override with mock
206
+ * const mockJwt = { createTokenPair: vi.fn() } as unknown as JwtManager;
207
+ * container.register({ provide: JWT_MANAGER, useValue: mockJwt });
208
+ *
209
+ * // AuthService will now use the mock
210
+ * const auth = container.resolve(AUTH_SERVICE);
211
+ * ```
212
+ */
213
+ export { registerAuthProviders as registerAuthProvidersForTesting };
@@ -159,6 +159,13 @@ export declare function createAuthRateLimiter(config?: AuthRateLimiterConfig): {
159
159
  */
160
160
  getRemainingAttempts: (key: string, operation: "login" | "register" | "password-reset" | "refresh") => number;
161
161
  };
162
+ /**
163
+ * Type for the auth rate limiter instance returned by createAuthRateLimiter
164
+ *
165
+ * Provides rate limiting methods for login, register, password reset, and token refresh.
166
+ * Also includes utility methods for recording failures, resetting limits, and checking lockout status.
167
+ */
168
+ export type AuthRateLimiter = ReturnType<typeof createAuthRateLimiter>;
162
169
  /**
163
170
  * Pre-configured auth rate limiter with sensible defaults
164
171
  *
@@ -0,0 +1,135 @@
1
+ /**
2
+ * DI Tokens for @veloxts/auth
3
+ *
4
+ * Symbol-based tokens for type-safe dependency injection.
5
+ * These tokens allow services to be registered, resolved, and mocked via the DI container.
6
+ *
7
+ * @module auth/tokens
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { Container } from '@veloxts/core';
12
+ * import { JWT_MANAGER, JWT_CONFIG, registerAuthProviders } from '@veloxts/auth';
13
+ *
14
+ * const container = new Container();
15
+ * registerAuthProviders(container, { jwt: { secret: '...' } });
16
+ *
17
+ * const jwt = container.resolve(JWT_MANAGER);
18
+ * ```
19
+ */
20
+ import type { CsrfConfig } from './csrf.js';
21
+ import type { PasswordHasher } from './hash.js';
22
+ import type { JwtManager, TokenStore } from './jwt.js';
23
+ import type { AuthService } from './plugin.js';
24
+ import type { AuthRateLimiterConfig } from './rate-limit.js';
25
+ import type { SessionConfig, SessionStore } from './session.js';
26
+ import type { AuthConfig, HashConfig, JwtConfig } from './types.js';
27
+ /**
28
+ * Main auth configuration token
29
+ *
30
+ * Contains JWT config, hash config, and other auth settings.
31
+ */
32
+ export declare const AUTH_CONFIG: import("@veloxts/core").SymbolToken<AuthConfig>;
33
+ /**
34
+ * JWT configuration token
35
+ *
36
+ * Used to configure JwtManager (secret, expiry times, issuer, etc.)
37
+ */
38
+ export declare const JWT_CONFIG: import("@veloxts/core").SymbolToken<JwtConfig>;
39
+ /**
40
+ * Password hashing configuration token
41
+ *
42
+ * Used to configure PasswordHasher (algorithm, rounds, etc.)
43
+ */
44
+ export declare const HASH_CONFIG: import("@veloxts/core").SymbolToken<HashConfig>;
45
+ /**
46
+ * Session configuration token
47
+ *
48
+ * Used to configure SessionManager (store, cookie settings, expiration)
49
+ */
50
+ export declare const SESSION_CONFIG: import("@veloxts/core").SymbolToken<SessionConfig>;
51
+ /**
52
+ * CSRF protection configuration token
53
+ *
54
+ * Used to configure CsrfManager (cookie settings, validation rules)
55
+ */
56
+ export declare const CSRF_CONFIG: import("@veloxts/core").SymbolToken<CsrfConfig>;
57
+ /**
58
+ * Auth rate limiter configuration token
59
+ *
60
+ * Used to configure per-endpoint rate limits (login, register, reset, refresh)
61
+ */
62
+ export declare const RATE_LIMIT_CONFIG: import("@veloxts/core").SymbolToken<AuthRateLimiterConfig>;
63
+ /**
64
+ * JWT manager service token
65
+ *
66
+ * Provides token creation, verification, and refresh capabilities.
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * const jwt = container.resolve(JWT_MANAGER);
71
+ * const tokens = jwt.createTokenPair({ id: '1', email: 'user@example.com' });
72
+ * ```
73
+ */
74
+ export declare const JWT_MANAGER: import("@veloxts/core").SymbolToken<JwtManager>;
75
+ /**
76
+ * Password hasher service token
77
+ *
78
+ * Provides secure password hashing and verification.
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const hasher = container.resolve(PASSWORD_HASHER);
83
+ * const hash = await hasher.hash('password123');
84
+ * const valid = await hasher.verify('password123', hash);
85
+ * ```
86
+ */
87
+ export declare const PASSWORD_HASHER: import("@veloxts/core").SymbolToken<PasswordHasher>;
88
+ /**
89
+ * Auth service composite token
90
+ *
91
+ * Aggregates JWT manager, password hasher, and middleware into a single service.
92
+ * This is the main service attached to Fastify by the auth plugin.
93
+ */
94
+ export declare const AUTH_SERVICE: import("@veloxts/core").SymbolToken<AuthService>;
95
+ /**
96
+ * Auth rate limiter service token
97
+ *
98
+ * Provides per-endpoint rate limiting for authentication operations.
99
+ * Includes login, register, password reset, and refresh endpoints.
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * const rateLimiter = container.resolve(AUTH_RATE_LIMITER);
104
+ * // Use in procedures:
105
+ * procedure().use(rateLimiter.login((ctx) => ctx.input.email))
106
+ * ```
107
+ */
108
+ export declare const AUTH_RATE_LIMITER: import("@veloxts/core").SymbolToken<{
109
+ login: <TInput, TContext extends import("@veloxts/core").BaseContext, TOutput>(identifierFn?: (ctx: TContext & {
110
+ input?: unknown;
111
+ }) => string) => import("@veloxts/router").MiddlewareFunction<TInput, TContext, TContext, TOutput>;
112
+ register: <TInput, TContext extends import("@veloxts/core").BaseContext, TOutput>() => import("@veloxts/router").MiddlewareFunction<TInput, TContext, TContext, TOutput>;
113
+ passwordReset: <TInput, TContext extends import("@veloxts/core").BaseContext, TOutput>(identifierFn?: (ctx: TContext & {
114
+ input?: unknown;
115
+ }) => string) => import("@veloxts/router").MiddlewareFunction<TInput, TContext, TContext, TOutput>;
116
+ refresh: <TInput, TContext extends import("@veloxts/core").BaseContext, TOutput>() => import("@veloxts/router").MiddlewareFunction<TInput, TContext, TContext, TOutput>;
117
+ recordFailure: (key: string, operation: "login" | "register" | "password-reset") => void;
118
+ resetLimit: (key: string, operation: "login" | "register" | "password-reset") => void;
119
+ isLockedOut: (key: string, operation: "login" | "register" | "password-reset") => boolean;
120
+ getRemainingAttempts: (key: string, operation: "login" | "register" | "password-reset" | "refresh") => number;
121
+ }>;
122
+ /**
123
+ * Session store token
124
+ *
125
+ * Pluggable backend for session storage.
126
+ * Default: in-memory store (use Redis for production)
127
+ */
128
+ export declare const SESSION_STORE: import("@veloxts/core").SymbolToken<SessionStore>;
129
+ /**
130
+ * Token store token
131
+ *
132
+ * Pluggable backend for token revocation tracking.
133
+ * Used for JWT blacklist functionality.
134
+ */
135
+ export declare const TOKEN_STORE: import("@veloxts/core").SymbolToken<TokenStore>;
package/dist/tokens.js ADDED
@@ -0,0 +1,125 @@
1
+ /**
2
+ * DI Tokens for @veloxts/auth
3
+ *
4
+ * Symbol-based tokens for type-safe dependency injection.
5
+ * These tokens allow services to be registered, resolved, and mocked via the DI container.
6
+ *
7
+ * @module auth/tokens
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * import { Container } from '@veloxts/core';
12
+ * import { JWT_MANAGER, JWT_CONFIG, registerAuthProviders } from '@veloxts/auth';
13
+ *
14
+ * const container = new Container();
15
+ * registerAuthProviders(container, { jwt: { secret: '...' } });
16
+ *
17
+ * const jwt = container.resolve(JWT_MANAGER);
18
+ * ```
19
+ */
20
+ import { token } from '@veloxts/core';
21
+ // ============================================================================
22
+ // Configuration Tokens
23
+ // ============================================================================
24
+ /**
25
+ * Main auth configuration token
26
+ *
27
+ * Contains JWT config, hash config, and other auth settings.
28
+ */
29
+ export const AUTH_CONFIG = token.symbol('AUTH_CONFIG');
30
+ /**
31
+ * JWT configuration token
32
+ *
33
+ * Used to configure JwtManager (secret, expiry times, issuer, etc.)
34
+ */
35
+ export const JWT_CONFIG = token.symbol('JWT_CONFIG');
36
+ /**
37
+ * Password hashing configuration token
38
+ *
39
+ * Used to configure PasswordHasher (algorithm, rounds, etc.)
40
+ */
41
+ export const HASH_CONFIG = token.symbol('HASH_CONFIG');
42
+ /**
43
+ * Session configuration token
44
+ *
45
+ * Used to configure SessionManager (store, cookie settings, expiration)
46
+ */
47
+ export const SESSION_CONFIG = token.symbol('SESSION_CONFIG');
48
+ /**
49
+ * CSRF protection configuration token
50
+ *
51
+ * Used to configure CsrfManager (cookie settings, validation rules)
52
+ */
53
+ export const CSRF_CONFIG = token.symbol('CSRF_CONFIG');
54
+ /**
55
+ * Auth rate limiter configuration token
56
+ *
57
+ * Used to configure per-endpoint rate limits (login, register, reset, refresh)
58
+ */
59
+ export const RATE_LIMIT_CONFIG = token.symbol('RATE_LIMIT_CONFIG');
60
+ // ============================================================================
61
+ // Service Tokens
62
+ // ============================================================================
63
+ /**
64
+ * JWT manager service token
65
+ *
66
+ * Provides token creation, verification, and refresh capabilities.
67
+ *
68
+ * @example
69
+ * ```typescript
70
+ * const jwt = container.resolve(JWT_MANAGER);
71
+ * const tokens = jwt.createTokenPair({ id: '1', email: 'user@example.com' });
72
+ * ```
73
+ */
74
+ export const JWT_MANAGER = token.symbol('JWT_MANAGER');
75
+ /**
76
+ * Password hasher service token
77
+ *
78
+ * Provides secure password hashing and verification.
79
+ *
80
+ * @example
81
+ * ```typescript
82
+ * const hasher = container.resolve(PASSWORD_HASHER);
83
+ * const hash = await hasher.hash('password123');
84
+ * const valid = await hasher.verify('password123', hash);
85
+ * ```
86
+ */
87
+ export const PASSWORD_HASHER = token.symbol('PASSWORD_HASHER');
88
+ /**
89
+ * Auth service composite token
90
+ *
91
+ * Aggregates JWT manager, password hasher, and middleware into a single service.
92
+ * This is the main service attached to Fastify by the auth plugin.
93
+ */
94
+ export const AUTH_SERVICE = token.symbol('AUTH_SERVICE');
95
+ /**
96
+ * Auth rate limiter service token
97
+ *
98
+ * Provides per-endpoint rate limiting for authentication operations.
99
+ * Includes login, register, password reset, and refresh endpoints.
100
+ *
101
+ * @example
102
+ * ```typescript
103
+ * const rateLimiter = container.resolve(AUTH_RATE_LIMITER);
104
+ * // Use in procedures:
105
+ * procedure().use(rateLimiter.login((ctx) => ctx.input.email))
106
+ * ```
107
+ */
108
+ export const AUTH_RATE_LIMITER = token.symbol('AUTH_RATE_LIMITER');
109
+ // ============================================================================
110
+ // Store Tokens (Pluggable Backends)
111
+ // ============================================================================
112
+ /**
113
+ * Session store token
114
+ *
115
+ * Pluggable backend for session storage.
116
+ * Default: in-memory store (use Redis for production)
117
+ */
118
+ export const SESSION_STORE = token.symbol('SESSION_STORE');
119
+ /**
120
+ * Token store token
121
+ *
122
+ * Pluggable backend for token revocation tracking.
123
+ * Used for JWT blacklist functionality.
124
+ */
125
+ export const TOKEN_STORE = token.symbol('TOKEN_STORE');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@veloxts/auth",
3
- "version": "0.6.56",
3
+ "version": "0.6.58",
4
4
  "description": "Authentication and authorization system for VeloxTS framework",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -57,8 +57,8 @@
57
57
  "dependencies": {
58
58
  "@fastify/cookie": "11.0.2",
59
59
  "fastify": "5.6.2",
60
- "@veloxts/core": "0.6.56",
61
- "@veloxts/router": "0.6.56"
60
+ "@veloxts/core": "0.6.58",
61
+ "@veloxts/router": "0.6.58"
62
62
  },
63
63
  "peerDependencies": {
64
64
  "argon2": ">=0.30.0",
@@ -82,8 +82,8 @@
82
82
  "fastify-plugin": "5.1.0",
83
83
  "typescript": "5.9.3",
84
84
  "vitest": "4.0.16",
85
- "@veloxts/testing": "0.6.56",
86
- "@veloxts/validation": "0.6.56"
85
+ "@veloxts/testing": "0.6.58",
86
+ "@veloxts/validation": "0.6.58"
87
87
  },
88
88
  "keywords": [
89
89
  "velox",