@naman_deep_singh/security 1.1.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +358 -175
  2. package/dist/cjs/core/crypto/cryptoManager.d.ts +111 -0
  3. package/dist/cjs/core/crypto/cryptoManager.js +185 -0
  4. package/dist/cjs/core/crypto/index.d.ts +5 -4
  5. package/dist/cjs/core/crypto/index.js +12 -4
  6. package/dist/cjs/core/jwt/extractToken.d.ts +2 -2
  7. package/dist/cjs/core/jwt/extractToken.js +12 -7
  8. package/dist/cjs/core/jwt/generateTokens.d.ts +3 -6
  9. package/dist/cjs/core/jwt/generateTokens.js +10 -3
  10. package/dist/cjs/core/jwt/index.d.ts +1 -0
  11. package/dist/cjs/core/jwt/index.js +1 -0
  12. package/dist/cjs/core/jwt/jwtManager.d.ts +66 -0
  13. package/dist/cjs/core/jwt/jwtManager.js +319 -0
  14. package/dist/cjs/core/jwt/signToken.d.ts +1 -1
  15. package/dist/cjs/core/jwt/types.d.ts +22 -0
  16. package/dist/cjs/core/jwt/types.js +2 -0
  17. package/dist/cjs/core/jwt/validateToken.d.ts +1 -1
  18. package/dist/cjs/core/jwt/verify.d.ts +12 -7
  19. package/dist/cjs/core/jwt/verify.js +23 -3
  20. package/dist/cjs/core/password/passwordManager.d.ts +29 -0
  21. package/dist/cjs/core/password/passwordManager.js +242 -0
  22. package/dist/cjs/index.d.ts +11 -9
  23. package/dist/cjs/interfaces/jwt.interface.d.ts +47 -0
  24. package/dist/cjs/interfaces/jwt.interface.js +2 -0
  25. package/dist/cjs/interfaces/password.interface.d.ts +60 -0
  26. package/dist/cjs/interfaces/password.interface.js +2 -0
  27. package/dist/esm/core/crypto/cryptoManager.d.ts +111 -0
  28. package/dist/esm/core/crypto/cryptoManager.js +180 -0
  29. package/dist/esm/core/crypto/index.d.ts +5 -4
  30. package/dist/esm/core/crypto/index.js +5 -4
  31. package/dist/esm/core/jwt/extractToken.d.ts +2 -2
  32. package/dist/esm/core/jwt/extractToken.js +12 -7
  33. package/dist/esm/core/jwt/generateTokens.d.ts +3 -6
  34. package/dist/esm/core/jwt/generateTokens.js +10 -3
  35. package/dist/esm/core/jwt/index.d.ts +1 -0
  36. package/dist/esm/core/jwt/index.js +1 -0
  37. package/dist/esm/core/jwt/jwtManager.d.ts +66 -0
  38. package/dist/esm/core/jwt/jwtManager.js +312 -0
  39. package/dist/esm/core/jwt/signToken.d.ts +1 -1
  40. package/dist/esm/core/jwt/types.d.ts +22 -0
  41. package/dist/esm/core/jwt/types.js +1 -0
  42. package/dist/esm/core/jwt/validateToken.d.ts +1 -1
  43. package/dist/esm/core/jwt/verify.d.ts +12 -7
  44. package/dist/esm/core/jwt/verify.js +20 -2
  45. package/dist/esm/core/password/passwordManager.d.ts +29 -0
  46. package/dist/esm/core/password/passwordManager.js +235 -0
  47. package/dist/esm/index.d.ts +11 -9
  48. package/dist/esm/interfaces/jwt.interface.d.ts +47 -0
  49. package/dist/esm/interfaces/jwt.interface.js +1 -0
  50. package/dist/esm/interfaces/password.interface.d.ts +60 -0
  51. package/dist/esm/interfaces/password.interface.js +1 -0
  52. package/dist/types/core/crypto/cryptoManager.d.ts +111 -0
  53. package/dist/types/core/crypto/index.d.ts +5 -4
  54. package/dist/types/core/jwt/extractToken.d.ts +2 -2
  55. package/dist/types/core/jwt/generateTokens.d.ts +3 -6
  56. package/dist/types/core/jwt/index.d.ts +1 -0
  57. package/dist/types/core/jwt/jwtManager.d.ts +66 -0
  58. package/dist/types/core/jwt/signToken.d.ts +1 -1
  59. package/dist/types/core/jwt/types.d.ts +22 -0
  60. package/dist/types/core/jwt/validateToken.d.ts +1 -1
  61. package/dist/types/core/jwt/verify.d.ts +12 -7
  62. package/dist/types/core/password/passwordManager.d.ts +29 -0
  63. package/dist/types/index.d.ts +11 -9
  64. package/dist/types/interfaces/jwt.interface.d.ts +47 -0
  65. package/dist/types/interfaces/password.interface.d.ts +60 -0
  66. package/package.json +1 -1
@@ -0,0 +1,22 @@
1
+ import { JwtPayload } from "jsonwebtoken";
2
+ export interface AccessTokenBrand {
3
+ readonly access: unique symbol;
4
+ }
5
+ export interface RefreshTokenBrand {
6
+ readonly refresh: unique symbol;
7
+ }
8
+ export type AccessToken = string & AccessTokenBrand;
9
+ export type RefreshToken = string & RefreshTokenBrand;
10
+ export interface TokenPair {
11
+ accessToken: AccessToken;
12
+ refreshToken: RefreshToken;
13
+ }
14
+ export interface VerificationResult<T = JwtPayload> {
15
+ valid: boolean;
16
+ payload?: T | string;
17
+ error?: Error;
18
+ }
19
+ export interface TokenValidationOptions {
20
+ ignoreExpiration?: boolean;
21
+ ignoreIssuedAt?: boolean;
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -4,7 +4,7 @@ export interface TokenRequirements {
4
4
  forbiddenFields?: string[];
5
5
  validateTypes?: Record<string, "string" | "number" | "boolean">;
6
6
  }
7
- export declare function validateTokenPayload(payload: Record<string, any>, rules?: TokenRequirements): {
7
+ export declare function validateTokenPayload(payload: Record<string, unknown>, rules?: TokenRequirements): {
8
8
  valid: true;
9
9
  } | {
10
10
  valid: false;
@@ -1,13 +1,18 @@
1
- import { Secret, JwtPayload } from "jsonwebtoken";
1
+ import jwt, { Secret, JwtPayload } from "jsonwebtoken";
2
+ import { VerificationResult } from "./types";
2
3
  /**
3
4
  * Verify token (throws if invalid or expired)
4
5
  */
5
6
  export declare const verifyToken: (token: string, secret: Secret) => string | JwtPayload;
6
7
  /**
7
- * Safe verify — never throws, returns { valid, payload?, error? }
8
+ * Safe verify — never throws, returns structured result
8
9
  */
9
- export declare const safeVerifyToken: (token: string, secret: Secret) => {
10
- valid: boolean;
11
- payload?: string | JwtPayload;
12
- error?: unknown;
13
- };
10
+ export declare const safeVerifyToken: (token: string, secret: Secret) => VerificationResult;
11
+ /**
12
+ * Verify token with validation options
13
+ */
14
+ export declare const verifyTokenWithOptions: (token: string, secret: Secret, options?: jwt.VerifyOptions) => string | JwtPayload;
15
+ /**
16
+ * Safe verify with validation options
17
+ */
18
+ export declare const safeVerifyTokenWithOptions: (token: string, secret: Secret, options?: jwt.VerifyOptions) => VerificationResult;
@@ -6,7 +6,7 @@ export const verifyToken = (token, secret) => {
6
6
  return verify(token, secret);
7
7
  };
8
8
  /**
9
- * Safe verify — never throws, returns { valid, payload?, error? }
9
+ * Safe verify — never throws, returns structured result
10
10
  */
11
11
  export const safeVerifyToken = (token, secret) => {
12
12
  try {
@@ -14,6 +14,24 @@ export const safeVerifyToken = (token, secret) => {
14
14
  return { valid: true, payload: decoded };
15
15
  }
16
16
  catch (error) {
17
- return { valid: false, error };
17
+ return { valid: false, error: error };
18
+ }
19
+ };
20
+ /**
21
+ * Verify token with validation options
22
+ */
23
+ export const verifyTokenWithOptions = (token, secret, options = {}) => {
24
+ return verify(token, secret, options);
25
+ };
26
+ /**
27
+ * Safe verify with validation options
28
+ */
29
+ export const safeVerifyTokenWithOptions = (token, secret, options = {}) => {
30
+ try {
31
+ const decoded = verify(token, secret, options);
32
+ return { valid: true, payload: decoded };
33
+ }
34
+ catch (error) {
35
+ return { valid: false, error: error };
18
36
  }
19
37
  };
@@ -0,0 +1,29 @@
1
+ import { IPasswordManager, PasswordConfig, PasswordValidationResult, HashedPassword, PasswordStrength } from "../../interfaces/password.interface";
2
+ export declare class PasswordManager implements IPasswordManager {
3
+ private defaultConfig;
4
+ constructor(config?: PasswordConfig);
5
+ /**
6
+ * Hash a password asynchronously using bcrypt
7
+ */
8
+ hash(password: string, salt?: string): Promise<HashedPassword>;
9
+ /**
10
+ * Verify password against hash and salt
11
+ */
12
+ verify(password: string, hash: string, salt: string): Promise<boolean>;
13
+ /**
14
+ * Generate a random password
15
+ */
16
+ generate(length?: number, options?: PasswordConfig): string;
17
+ /**
18
+ * Validate password against configuration
19
+ */
20
+ validate(password: string, config?: PasswordConfig): PasswordValidationResult;
21
+ /**
22
+ * Check password strength
23
+ */
24
+ checkStrength(password: string): PasswordStrength;
25
+ /**
26
+ * Check if password hash needs upgrade (different salt rounds)
27
+ */
28
+ needsUpgrade(hash: string, currentConfig: PasswordConfig): boolean;
29
+ }
@@ -0,0 +1,235 @@
1
+ import bcrypt from "bcryptjs";
2
+ import crypto from "crypto";
3
+ import { ensureValidPassword, estimatePasswordEntropy } from "./utils";
4
+ import { BadRequestError, ValidationError } from "@naman_deep_singh/errors-utils";
5
+ export class PasswordManager {
6
+ constructor(config = {}) {
7
+ this.defaultConfig = {
8
+ saltRounds: 10,
9
+ minLength: 8,
10
+ maxLength: 128,
11
+ requireUppercase: true,
12
+ requireLowercase: true,
13
+ requireNumbers: true,
14
+ requireSpecialChars: false,
15
+ ...config
16
+ };
17
+ }
18
+ /**
19
+ * Hash a password asynchronously using bcrypt
20
+ */
21
+ async hash(password, salt) {
22
+ try {
23
+ ensureValidPassword(password);
24
+ // Validate password meets basic requirements
25
+ this.validate(password);
26
+ const saltRounds = this.defaultConfig.saltRounds;
27
+ let passwordSalt = salt;
28
+ if (!passwordSalt) {
29
+ passwordSalt = await bcrypt.genSalt(saltRounds);
30
+ }
31
+ const hash = await bcrypt.hash(password, passwordSalt);
32
+ return {
33
+ hash,
34
+ salt: passwordSalt
35
+ };
36
+ }
37
+ catch (error) {
38
+ if (error instanceof BadRequestError || error instanceof ValidationError) {
39
+ throw error;
40
+ }
41
+ throw new BadRequestError("Failed to hash password");
42
+ }
43
+ }
44
+ /**
45
+ * Verify password against hash and salt
46
+ */
47
+ async verify(password, hash, salt) {
48
+ try {
49
+ if (!password || !hash || !salt) {
50
+ return false;
51
+ }
52
+ // First verify with the provided salt
53
+ const isValid = await bcrypt.compare(password, hash);
54
+ // If invalid and different salt was used, try regenerating hash with new salt
55
+ if (!isValid && salt !== this.defaultConfig.saltRounds?.toString()) {
56
+ const newHash = await bcrypt.hash(password, salt);
57
+ return newHash === hash;
58
+ }
59
+ return isValid;
60
+ }
61
+ catch (error) {
62
+ return false;
63
+ }
64
+ }
65
+ /**
66
+ * Generate a random password
67
+ */
68
+ generate(length = 16, options = {}) {
69
+ const config = { ...this.defaultConfig, ...options };
70
+ if (length < config.minLength || length > config.maxLength) {
71
+ throw new ValidationError(`Password length must be between ${config.minLength} and ${config.maxLength}`);
72
+ }
73
+ let charset = "abcdefghijklmnopqrstuvwxyz";
74
+ if (config.requireUppercase)
75
+ charset += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
76
+ if (config.requireNumbers)
77
+ charset += "0123456789";
78
+ if (config.requireSpecialChars)
79
+ charset += "!@#$%^&*()_+-=[]{}|;:,.<>?";
80
+ let password = "";
81
+ const randomBytes = crypto.randomBytes(length);
82
+ for (let i = 0; i < length; i++) {
83
+ password += charset[randomBytes[i] % charset.length];
84
+ }
85
+ // Ensure all requirements are met
86
+ if (config.requireUppercase && !/[A-Z]/.test(password)) {
87
+ password = password.replace(/[a-z]/, 'A');
88
+ }
89
+ if (config.requireLowercase && !/[a-z]/.test(password)) {
90
+ password = password.replace(/[A-Z]/, 'a');
91
+ }
92
+ if (config.requireNumbers && !/[0-9]/.test(password)) {
93
+ password = password.replace(/[A-Za-z]/, '0');
94
+ }
95
+ if (config.requireSpecialChars && !/[^A-Za-z0-9]/.test(password)) {
96
+ password = password.replace(/[A-Za-z0-9]/, '!');
97
+ }
98
+ return password;
99
+ }
100
+ /**
101
+ * Validate password against configuration
102
+ */
103
+ validate(password, config = {}) {
104
+ const finalConfig = { ...this.defaultConfig, ...config };
105
+ const errors = [];
106
+ // Basic validation
107
+ if (!password || typeof password !== "string") {
108
+ errors.push("Password must be a non-empty string");
109
+ }
110
+ // Length validation
111
+ if (password.length < finalConfig.minLength) {
112
+ errors.push(`Password must be at least ${finalConfig.minLength} characters long`);
113
+ }
114
+ if (password.length > finalConfig.maxLength) {
115
+ errors.push(`Password must not exceed ${finalConfig.maxLength} characters`);
116
+ }
117
+ // Complexity requirements
118
+ if (finalConfig.requireUppercase && !/[A-Z]/.test(password)) {
119
+ errors.push("Password must contain at least one uppercase letter");
120
+ }
121
+ if (finalConfig.requireLowercase && !/[a-z]/.test(password)) {
122
+ errors.push("Password must contain at least one lowercase letter");
123
+ }
124
+ if (finalConfig.requireNumbers && !/[0-9]/.test(password)) {
125
+ errors.push("Password must contain at least one number");
126
+ }
127
+ if (finalConfig.requireSpecialChars && !/[^A-Za-z0-9]/.test(password)) {
128
+ errors.push("Password must contain at least one special character");
129
+ }
130
+ // Custom rules
131
+ if (finalConfig.customRules) {
132
+ finalConfig.customRules.forEach(rule => {
133
+ if (!rule.test(password)) {
134
+ errors.push(rule.message);
135
+ }
136
+ });
137
+ }
138
+ const strength = this.checkStrength(password);
139
+ const isValid = errors.length === 0;
140
+ return {
141
+ isValid,
142
+ errors,
143
+ strength
144
+ };
145
+ }
146
+ /**
147
+ * Check password strength
148
+ */
149
+ checkStrength(password) {
150
+ const entropy = estimatePasswordEntropy(password);
151
+ let score = 0;
152
+ const feedback = [];
153
+ const suggestions = [];
154
+ // Length scoring
155
+ if (password.length >= 8)
156
+ score++;
157
+ if (password.length >= 12)
158
+ score++;
159
+ if (password.length >= 16)
160
+ score++;
161
+ // Character variety scoring
162
+ if (/[a-z]/.test(password))
163
+ score++;
164
+ if (/[A-Z]/.test(password))
165
+ score++;
166
+ if (/[0-9]/.test(password))
167
+ score++;
168
+ if (/[^A-Za-z0-9]/.test(password))
169
+ score++;
170
+ // Common patterns deduction
171
+ if (/^[A-Za-z]+$/.test(password)) {
172
+ score--;
173
+ feedback.push("Consider adding numbers and symbols");
174
+ }
175
+ if (/^[0-9]+$/.test(password)) {
176
+ score -= 2;
177
+ feedback.push("Avoid using only numbers");
178
+ }
179
+ if (/([a-zA-Z0-9])\1{2,}/.test(password)) {
180
+ score--;
181
+ feedback.push("Avoid repeated characters");
182
+ }
183
+ if (/(?:012|123|234|345|456|567|678|789)/.test(password)) {
184
+ score--;
185
+ feedback.push("Avoid sequential patterns");
186
+ }
187
+ // Common passwords check
188
+ const commonPasswords = ['password', '123456', 'qwerty', 'admin', 'letmein'];
189
+ if (commonPasswords.some(common => password.toLowerCase().includes(common))) {
190
+ score = 0;
191
+ feedback.push("Avoid common passwords");
192
+ }
193
+ // Clamp score and determine label
194
+ score = Math.max(0, Math.min(4, score));
195
+ let label;
196
+ switch (score) {
197
+ case 0:
198
+ label = 'very-weak';
199
+ suggestions.push("Use a longer password with mixed characters");
200
+ break;
201
+ case 1:
202
+ label = 'weak';
203
+ suggestions.push("Add more character variety");
204
+ break;
205
+ case 2:
206
+ label = 'fair';
207
+ suggestions.push("Consider adding more length or character types");
208
+ break;
209
+ case 3:
210
+ label = 'good';
211
+ suggestions.push("Your password is reasonably secure");
212
+ break;
213
+ case 4:
214
+ label = 'strong';
215
+ suggestions.push("Your password is very secure");
216
+ break;
217
+ default:
218
+ label = 'very-weak';
219
+ }
220
+ return {
221
+ score,
222
+ label,
223
+ feedback,
224
+ suggestions
225
+ };
226
+ }
227
+ /**
228
+ * Check if password hash needs upgrade (different salt rounds)
229
+ */
230
+ needsUpgrade(hash, currentConfig) {
231
+ // Simple heuristic: if the hash doesn't match current salt rounds pattern
232
+ // In practice, you'd need to store the salt rounds with the hash
233
+ return false;
234
+ }
235
+ }
@@ -3,6 +3,7 @@ export * from "./core/jwt";
3
3
  export * from "./core/crypto";
4
4
  export { BadRequestError, UnauthorizedError, ValidationError, InternalServerError } from "@naman_deep_singh/errors-utils";
5
5
  import * as JWTUtils from "./core/jwt";
6
+ import * as CryptoUtils from "./core/crypto";
6
7
  declare const _default: {
7
8
  decrypt: (data: string, secret: string) => string;
8
9
  encrypt: (text: string, secret: string) => string;
@@ -10,14 +11,17 @@ declare const _default: {
10
11
  hmacVerify: (message: string, secret: string, signature: string) => boolean;
11
12
  randomToken: (length?: number) => string;
12
13
  generateStrongPassword: (length?: number) => string;
14
+ CryptoManager: typeof CryptoUtils.CryptoManager;
15
+ createCryptoManager: (config?: CryptoUtils.CryptoManagerConfig) => CryptoUtils.CryptoManager;
16
+ cryptoManager: CryptoUtils.CryptoManager;
13
17
  decodeToken(token: string): null | string | import("node_modules/@types/jsonwebtoken").JwtPayload;
14
18
  decodeTokenStrict(token: string): import("node_modules/@types/jsonwebtoken").JwtPayload;
15
19
  extractToken(sources: JWTUtils.TokenSources): string | null;
16
- rotateRefreshToken(oldToken: string, secret: import("node_modules/@types/jsonwebtoken").Secret): string;
17
- generateTokens: (payload: object, accessSecret: import("node_modules/@types/jsonwebtoken").Secret, refreshSecret: import("node_modules/@types/jsonwebtoken").Secret, accessExpiry?: string | number, refreshExpiry?: string | number) => JWTUtils.TokenPair;
20
+ rotateRefreshToken(oldToken: string, secret: import("node_modules/@types/jsonwebtoken").Secret): JWTUtils.RefreshToken;
21
+ generateTokens: (payload: Record<string, unknown>, accessSecret: import("node_modules/@types/jsonwebtoken").Secret, refreshSecret: import("node_modules/@types/jsonwebtoken").Secret, accessExpiry?: string | number, refreshExpiry?: string | number) => JWTUtils.TokenPair;
18
22
  parseDuration(input: string | number): number;
19
- signToken: (payload: Record<string, any>, secret: import("node_modules/@types/jsonwebtoken").Secret, expiresIn?: string | number, options?: import("node_modules/@types/jsonwebtoken").SignOptions) => string;
20
- validateTokenPayload(payload: Record<string, any>, rules?: JWTUtils.TokenRequirements): {
23
+ signToken: (payload: Record<string, unknown>, secret: import("node_modules/@types/jsonwebtoken").Secret, expiresIn?: string | number, options?: import("node_modules/@types/jsonwebtoken").SignOptions) => string;
24
+ validateTokenPayload(payload: Record<string, unknown>, rules?: JWTUtils.TokenRequirements): {
21
25
  valid: true;
22
26
  } | {
23
27
  valid: false;
@@ -25,11 +29,9 @@ declare const _default: {
25
29
  };
26
30
  isTokenExpired(payload: import("node_modules/@types/jsonwebtoken").JwtPayload): boolean;
27
31
  verifyToken: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret) => string | import("node_modules/@types/jsonwebtoken").JwtPayload;
28
- safeVerifyToken: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret) => {
29
- valid: boolean;
30
- payload?: string | import("node_modules/@types/jsonwebtoken").JwtPayload;
31
- error?: unknown;
32
- };
32
+ safeVerifyToken: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret) => JWTUtils.VerificationResult;
33
+ verifyTokenWithOptions: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret, options?: import("node_modules/@types/jsonwebtoken").VerifyOptions) => string | import("node_modules/@types/jsonwebtoken").JwtPayload;
34
+ safeVerifyTokenWithOptions: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret, options?: import("node_modules/@types/jsonwebtoken").VerifyOptions) => JWTUtils.VerificationResult;
33
35
  hashPasswordWithPepper(password: string, pepper: string): Promise<string>;
34
36
  hashPasswordWithPepperSync(password: string, pepper: string): string;
35
37
  hashPassword: (password: string, saltRounds?: number) => Promise<string>;
@@ -0,0 +1,47 @@
1
+ import { JwtPayload, Secret } from "jsonwebtoken";
2
+ export interface AccessToken extends String {
3
+ readonly __type: 'AccessToken';
4
+ }
5
+ export interface RefreshToken extends String {
6
+ readonly __type: 'RefreshToken';
7
+ }
8
+ export interface TokenPair {
9
+ accessToken: AccessToken;
10
+ refreshToken: RefreshToken;
11
+ }
12
+ export interface JWTConfig {
13
+ accessSecret: Secret;
14
+ refreshSecret: Secret;
15
+ accessExpiry?: string | number;
16
+ refreshExpiry?: string | number;
17
+ enableCaching?: boolean;
18
+ maxCacheSize?: number;
19
+ }
20
+ export interface TokenValidationOptions {
21
+ ignoreExpiration?: boolean;
22
+ ignoreNotBefore?: boolean;
23
+ audience?: string | string[];
24
+ issuer?: string;
25
+ algorithms?: string[];
26
+ }
27
+ export interface TokenGenerationOptions {
28
+ algorithm?: string;
29
+ expiresIn?: string | number;
30
+ audience?: string | string[];
31
+ issuer?: string;
32
+ subject?: string;
33
+ kid?: string;
34
+ }
35
+ export interface ITokenManager {
36
+ generateTokens(payload: Record<string, unknown>): Promise<TokenPair>;
37
+ generateAccessToken(payload: Record<string, unknown>): Promise<AccessToken>;
38
+ generateRefreshToken(payload: Record<string, unknown>): Promise<RefreshToken>;
39
+ verifyAccessToken(token: string): Promise<JwtPayload | string>;
40
+ verifyRefreshToken(token: string): Promise<JwtPayload | string>;
41
+ decodeToken(token: string, complete?: boolean): JwtPayload | string | null;
42
+ extractTokenFromHeader(authHeader: string): string | null;
43
+ validateToken(token: string, secret: Secret, options?: TokenValidationOptions): boolean;
44
+ rotateRefreshToken(oldToken: string): Promise<RefreshToken>;
45
+ isTokenExpired(token: string): boolean;
46
+ getTokenExpiration(token: string): Date | null;
47
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,60 @@
1
+ export interface PasswordConfig {
2
+ saltRounds?: number;
3
+ minLength?: number;
4
+ maxLength?: number;
5
+ requireUppercase?: boolean;
6
+ requireLowercase?: boolean;
7
+ requireNumbers?: boolean;
8
+ requireSpecialChars?: boolean;
9
+ customRules?: PasswordRule[];
10
+ }
11
+ export interface PasswordRule {
12
+ test: (password: string) => boolean;
13
+ message: string;
14
+ }
15
+ export interface PasswordStrength {
16
+ score: number;
17
+ label: 'very-weak' | 'weak' | 'fair' | 'good' | 'strong';
18
+ feedback: string[];
19
+ suggestions: string[];
20
+ }
21
+ export interface PasswordValidationResult {
22
+ isValid: boolean;
23
+ errors: string[];
24
+ strength: PasswordStrength;
25
+ }
26
+ export interface HashedPassword {
27
+ hash: string;
28
+ salt: string;
29
+ }
30
+ export interface IPasswordManager {
31
+ hash(password: string, salt?: string): Promise<HashedPassword>;
32
+ verify(password: string, hash: string, salt: string): Promise<boolean>;
33
+ generate(length?: number, options?: PasswordConfig): string;
34
+ validate(password: string, config?: PasswordConfig): PasswordValidationResult;
35
+ checkStrength(password: string): PasswordStrength;
36
+ needsUpgrade(hash: string, currentConfig: PasswordConfig): boolean;
37
+ }
38
+ export interface IPasswordStrengthChecker {
39
+ analyze(password: string): PasswordStrength;
40
+ checkLength(password: string): {
41
+ valid: boolean;
42
+ message: string;
43
+ };
44
+ checkComplexity(password: string, config: PasswordConfig): {
45
+ valid: boolean;
46
+ message: string;
47
+ }[];
48
+ checkCommonPasswords(password: string): {
49
+ valid: boolean;
50
+ message: string;
51
+ };
52
+ checkSequential(password: string): {
53
+ valid: boolean;
54
+ message: string;
55
+ };
56
+ checkRepetition(password: string): {
57
+ valid: boolean;
58
+ message: string;
59
+ };
60
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Configuration options for CryptoManager
3
+ */
4
+ export interface CryptoManagerConfig {
5
+ defaultAlgorithm?: string;
6
+ defaultEncoding?: BufferEncoding;
7
+ hmacAlgorithm?: string;
8
+ }
9
+ /**
10
+ * CryptoManager - Class-based wrapper for all cryptographic operations
11
+ * Provides a consistent interface for encryption, decryption, HMAC generation, and secure random generation
12
+ */
13
+ export declare class CryptoManager {
14
+ private config;
15
+ constructor(config?: CryptoManagerConfig);
16
+ /**
17
+ * Update configuration
18
+ */
19
+ updateConfig(config: Partial<CryptoManagerConfig>): void;
20
+ /**
21
+ * Get current configuration
22
+ */
23
+ getConfig(): Required<CryptoManagerConfig>;
24
+ /**
25
+ * Encrypt data using the default or specified algorithm
26
+ */
27
+ encrypt(plaintext: string, key: string, options?: {
28
+ algorithm?: string;
29
+ encoding?: BufferEncoding;
30
+ iv?: string;
31
+ }): string;
32
+ /**
33
+ * Decrypt data using the default or specified algorithm
34
+ */
35
+ decrypt(encryptedData: string, key: string, options?: {
36
+ algorithm?: string;
37
+ encoding?: BufferEncoding;
38
+ iv?: string;
39
+ }): string;
40
+ /**
41
+ * Generate HMAC signature
42
+ */
43
+ generateHmac(data: string, secret: string, options?: {
44
+ algorithm?: string;
45
+ encoding?: BufferEncoding;
46
+ }): string;
47
+ /**
48
+ * Generate cryptographically secure random bytes
49
+ */
50
+ generateSecureRandom(length: number, encoding?: BufferEncoding): string;
51
+ /**
52
+ * Verify HMAC signature
53
+ */
54
+ verifyHmac(data: string, secret: string, signature: string, options?: {
55
+ algorithm?: string;
56
+ encoding?: BufferEncoding;
57
+ }): boolean;
58
+ /**
59
+ * Create a key derivation function using PBKDF2
60
+ */
61
+ deriveKey(password: string, salt: string, iterations?: number, keyLength?: number): Promise<string>;
62
+ /**
63
+ * Hash data using SHA-256
64
+ */
65
+ sha256(data: string, encoding?: BufferEncoding): string;
66
+ /**
67
+ * Hash data using SHA-512
68
+ */
69
+ sha512(data: string, encoding?: BufferEncoding): string;
70
+ /**
71
+ * Generate a secure key pair for asymmetric encryption
72
+ */
73
+ generateKeyPair(options?: {
74
+ modulusLength?: number;
75
+ publicKeyEncoding?: {
76
+ type: string;
77
+ format: string;
78
+ };
79
+ privateKeyEncoding?: {
80
+ type: string;
81
+ format: string;
82
+ };
83
+ }): Promise<{
84
+ publicKey: string;
85
+ privateKey: string;
86
+ }>;
87
+ /**
88
+ * Encrypt data using RSA public key
89
+ */
90
+ rsaEncrypt(data: string, publicKey: string): Promise<string>;
91
+ /**
92
+ * Decrypt data using RSA private key
93
+ */
94
+ rsaDecrypt(encryptedData: string, privateKey: string): Promise<string>;
95
+ /**
96
+ * Create digital signature using RSA private key
97
+ */
98
+ rsaSign(data: string, privateKey: string, algorithm?: string): Promise<string>;
99
+ /**
100
+ * Verify digital signature using RSA public key
101
+ */
102
+ rsaVerify(data: string, signature: string, publicKey: string, algorithm?: string): Promise<boolean>;
103
+ }
104
+ /**
105
+ * Create a CryptoManager instance with default configuration
106
+ */
107
+ export declare const createCryptoManager: (config?: CryptoManagerConfig) => CryptoManager;
108
+ /**
109
+ * Default CryptoManager instance
110
+ */
111
+ export declare const cryptoManager: CryptoManager;
@@ -1,4 +1,5 @@
1
- export * from "./decrypt";
2
- export * from "./encrypt";
3
- export * from "./hmac";
4
- export * from "./random";
1
+ export { decrypt } from "./decrypt";
2
+ export { encrypt } from "./encrypt";
3
+ export { hmacSign, hmacVerify } from "./hmac";
4
+ export { randomToken, generateStrongPassword } from "./random";
5
+ export * from "./cryptoManager";
@@ -2,8 +2,8 @@ export interface TokenSources {
2
2
  header?: string | undefined | null;
3
3
  cookies?: Record<string, string> | undefined;
4
4
  query?: Record<string, string | undefined> | undefined;
5
- body?: Record<string, any> | undefined;
6
- wsMessage?: string | Record<string, any> | undefined;
5
+ body?: Record<string, unknown> | undefined;
6
+ wsMessage?: string | Record<string, unknown> | undefined;
7
7
  }
8
8
  /**
9
9
  * Universal token extractor
@@ -1,7 +1,4 @@
1
1
  import { Secret } from "jsonwebtoken";
2
- export interface TokenPair {
3
- accessToken: string;
4
- refreshToken: string;
5
- }
6
- export declare const generateTokens: (payload: object, accessSecret: Secret, refreshSecret: Secret, accessExpiry?: string | number, refreshExpiry?: string | number) => TokenPair;
7
- export declare function rotateRefreshToken(oldToken: string, secret: Secret): string;
2
+ import { RefreshToken, TokenPair } from "./types";
3
+ export declare const generateTokens: (payload: Record<string, unknown>, accessSecret: Secret, refreshSecret: Secret, accessExpiry?: string | number, refreshExpiry?: string | number) => TokenPair;
4
+ export declare function rotateRefreshToken(oldToken: string, secret: Secret): RefreshToken;