@naman_deep_singh/security 1.2.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 (35) hide show
  1. package/README.md +355 -176
  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/jwtManager.d.ts +66 -0
  7. package/dist/cjs/core/jwt/jwtManager.js +319 -0
  8. package/dist/cjs/core/password/passwordManager.d.ts +29 -0
  9. package/dist/cjs/core/password/passwordManager.js +242 -0
  10. package/dist/cjs/index.d.ts +4 -0
  11. package/dist/cjs/interfaces/jwt.interface.d.ts +47 -0
  12. package/dist/cjs/interfaces/jwt.interface.js +2 -0
  13. package/dist/cjs/interfaces/password.interface.d.ts +60 -0
  14. package/dist/cjs/interfaces/password.interface.js +2 -0
  15. package/dist/esm/core/crypto/cryptoManager.d.ts +111 -0
  16. package/dist/esm/core/crypto/cryptoManager.js +180 -0
  17. package/dist/esm/core/crypto/index.d.ts +5 -4
  18. package/dist/esm/core/crypto/index.js +5 -4
  19. package/dist/esm/core/jwt/jwtManager.d.ts +66 -0
  20. package/dist/esm/core/jwt/jwtManager.js +312 -0
  21. package/dist/esm/core/password/passwordManager.d.ts +29 -0
  22. package/dist/esm/core/password/passwordManager.js +235 -0
  23. package/dist/esm/index.d.ts +4 -0
  24. package/dist/esm/interfaces/jwt.interface.d.ts +47 -0
  25. package/dist/esm/interfaces/jwt.interface.js +1 -0
  26. package/dist/esm/interfaces/password.interface.d.ts +60 -0
  27. package/dist/esm/interfaces/password.interface.js +1 -0
  28. package/dist/types/core/crypto/cryptoManager.d.ts +111 -0
  29. package/dist/types/core/crypto/index.d.ts +5 -4
  30. package/dist/types/core/jwt/jwtManager.d.ts +66 -0
  31. package/dist/types/core/password/passwordManager.d.ts +29 -0
  32. package/dist/types/index.d.ts +4 -0
  33. package/dist/types/interfaces/jwt.interface.d.ts +47 -0
  34. package/dist/types/interfaces/password.interface.d.ts +60 -0
  35. package/package.json +1 -1
@@ -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,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -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;
@@ -0,0 +1,180 @@
1
+ import { encrypt as functionalEncrypt, decrypt as functionalDecrypt, hmacSign as functionalHmacSign, hmacVerify as functionalHmacVerify, randomToken as functionalRandomToken } from './index';
2
+ /**
3
+ * Default configuration
4
+ */
5
+ const DEFAULT_CONFIG = {
6
+ defaultAlgorithm: 'aes-256-gcm',
7
+ defaultEncoding: 'utf8',
8
+ hmacAlgorithm: 'sha256'
9
+ };
10
+ /**
11
+ * CryptoManager - Class-based wrapper for all cryptographic operations
12
+ * Provides a consistent interface for encryption, decryption, HMAC generation, and secure random generation
13
+ */
14
+ export class CryptoManager {
15
+ constructor(config = {}) {
16
+ this.config = { ...DEFAULT_CONFIG, ...config };
17
+ }
18
+ /**
19
+ * Update configuration
20
+ */
21
+ updateConfig(config) {
22
+ this.config = { ...this.config, ...config };
23
+ }
24
+ /**
25
+ * Get current configuration
26
+ */
27
+ getConfig() {
28
+ return { ...this.config };
29
+ }
30
+ /**
31
+ * Encrypt data using the default or specified algorithm
32
+ */
33
+ encrypt(plaintext, key, options) {
34
+ // For now, use the basic encrypt function
35
+ // TODO: Enhance to support different algorithms and options
36
+ return functionalEncrypt(plaintext, key);
37
+ }
38
+ /**
39
+ * Decrypt data using the default or specified algorithm
40
+ */
41
+ decrypt(encryptedData, key, options) {
42
+ // For now, use the basic decrypt function
43
+ // TODO: Enhance to support different algorithms and options
44
+ return functionalDecrypt(encryptedData, key);
45
+ }
46
+ /**
47
+ * Generate HMAC signature
48
+ */
49
+ generateHmac(data, secret, options) {
50
+ // Use the basic HMAC sign function for now
51
+ // TODO: Add support for different algorithms
52
+ return functionalHmacSign(data, secret);
53
+ }
54
+ /**
55
+ * Generate cryptographically secure random bytes
56
+ */
57
+ generateSecureRandom(length, encoding = 'hex') {
58
+ // Use the basic random token function
59
+ return functionalRandomToken(length);
60
+ }
61
+ /**
62
+ * Verify HMAC signature
63
+ */
64
+ verifyHmac(data, secret, signature, options) {
65
+ // Use the basic HMAC verify function
66
+ return functionalHmacVerify(data, secret, signature);
67
+ }
68
+ /**
69
+ * Create a key derivation function using PBKDF2
70
+ */
71
+ deriveKey(password, salt, iterations = 100000, keyLength = 32) {
72
+ return new Promise((resolve, reject) => {
73
+ const crypto = require('crypto');
74
+ crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (err, derivedKey) => {
75
+ if (err) {
76
+ reject(err);
77
+ }
78
+ else {
79
+ resolve(derivedKey.toString('hex'));
80
+ }
81
+ });
82
+ });
83
+ }
84
+ /**
85
+ * Hash data using SHA-256
86
+ */
87
+ sha256(data, encoding = 'hex') {
88
+ const crypto = require('crypto');
89
+ return crypto.createHash('sha256').update(data).digest(encoding);
90
+ }
91
+ /**
92
+ * Hash data using SHA-512
93
+ */
94
+ sha512(data, encoding = 'hex') {
95
+ const crypto = require('crypto');
96
+ return crypto.createHash('sha512').update(data).digest(encoding);
97
+ }
98
+ /**
99
+ * Generate a secure key pair for asymmetric encryption
100
+ */
101
+ generateKeyPair(options) {
102
+ return new Promise((resolve, reject) => {
103
+ const crypto = require('crypto');
104
+ const keyPair = crypto.generateKeyPairSync('rsa', {
105
+ modulusLength: options?.modulusLength || 2048,
106
+ publicKeyEncoding: options?.publicKeyEncoding || { type: 'spki', format: 'pem' },
107
+ privateKeyEncoding: options?.privateKeyEncoding || { type: 'pkcs8', format: 'pem' }
108
+ });
109
+ resolve(keyPair);
110
+ });
111
+ }
112
+ /**
113
+ * Encrypt data using RSA public key
114
+ */
115
+ rsaEncrypt(data, publicKey) {
116
+ return new Promise((resolve, reject) => {
117
+ const crypto = require('crypto');
118
+ const buffer = Buffer.from(data, 'utf8');
119
+ const encrypted = crypto.publicEncrypt(publicKey, buffer);
120
+ resolve(encrypted.toString('base64'));
121
+ });
122
+ }
123
+ /**
124
+ * Decrypt data using RSA private key
125
+ */
126
+ rsaDecrypt(encryptedData, privateKey) {
127
+ return new Promise((resolve, reject) => {
128
+ const crypto = require('crypto');
129
+ const buffer = Buffer.from(encryptedData, 'base64');
130
+ const decrypted = crypto.privateDecrypt(privateKey, buffer);
131
+ resolve(decrypted.toString('utf8'));
132
+ });
133
+ }
134
+ /**
135
+ * Create digital signature using RSA private key
136
+ */
137
+ rsaSign(data, privateKey, algorithm = 'sha256') {
138
+ return new Promise((resolve, reject) => {
139
+ const crypto = require('crypto');
140
+ const sign = crypto.createSign(algorithm);
141
+ sign.update(data);
142
+ sign.end();
143
+ try {
144
+ const signature = sign.sign(privateKey, 'base64');
145
+ resolve(signature);
146
+ }
147
+ catch (error) {
148
+ reject(error);
149
+ }
150
+ });
151
+ }
152
+ /**
153
+ * Verify digital signature using RSA public key
154
+ */
155
+ rsaVerify(data, signature, publicKey, algorithm = 'sha256') {
156
+ return new Promise((resolve, reject) => {
157
+ const crypto = require('crypto');
158
+ const verify = crypto.createVerify(algorithm);
159
+ verify.update(data);
160
+ verify.end();
161
+ try {
162
+ const isValid = verify.verify(publicKey, signature, 'base64');
163
+ resolve(isValid);
164
+ }
165
+ catch (error) {
166
+ reject(error);
167
+ }
168
+ });
169
+ }
170
+ }
171
+ /**
172
+ * Create a CryptoManager instance with default configuration
173
+ */
174
+ export const createCryptoManager = (config) => {
175
+ return new CryptoManager(config);
176
+ };
177
+ /**
178
+ * Default CryptoManager instance
179
+ */
180
+ export const cryptoManager = new 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";
@@ -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";
@@ -0,0 +1,66 @@
1
+ import { JwtPayload, Secret } from "jsonwebtoken";
2
+ import { ITokenManager, TokenPair, AccessToken, RefreshToken, JWTConfig, TokenValidationOptions } from "../../interfaces/jwt.interface";
3
+ export declare class JWTManager implements ITokenManager {
4
+ private accessSecret;
5
+ private refreshSecret;
6
+ private accessExpiry;
7
+ private refreshExpiry;
8
+ private cache?;
9
+ constructor(config: JWTConfig);
10
+ /**
11
+ * Generate both access and refresh tokens
12
+ */
13
+ generateTokens(payload: Record<string, unknown>): Promise<TokenPair>;
14
+ /**
15
+ * Generate access token
16
+ */
17
+ generateAccessToken(payload: Record<string, unknown>): Promise<AccessToken>;
18
+ /**
19
+ * Generate refresh token
20
+ */
21
+ generateRefreshToken(payload: Record<string, unknown>): Promise<RefreshToken>;
22
+ /**
23
+ * Verify access token
24
+ */
25
+ verifyAccessToken(token: string): Promise<JwtPayload | string>;
26
+ /**
27
+ * Verify refresh token
28
+ */
29
+ verifyRefreshToken(token: string): Promise<JwtPayload | string>;
30
+ /**
31
+ * Decode token without verification
32
+ */
33
+ decodeToken(token: string, complete?: boolean): JwtPayload | string | null;
34
+ /**
35
+ * Extract token from Authorization header
36
+ */
37
+ extractTokenFromHeader(authHeader: string): string | null;
38
+ /**
39
+ * Validate token without throwing exceptions
40
+ */
41
+ validateToken(token: string, secret: Secret, options?: TokenValidationOptions): boolean;
42
+ /**
43
+ * Rotate refresh token
44
+ */
45
+ rotateRefreshToken(oldToken: string): Promise<RefreshToken>;
46
+ /**
47
+ * Check if token is expired
48
+ */
49
+ isTokenExpired(token: string): boolean;
50
+ /**
51
+ * Get token expiration date
52
+ */
53
+ getTokenExpiration(token: string): Date | null;
54
+ /**
55
+ * Clear token cache
56
+ */
57
+ clearCache(): void;
58
+ /**
59
+ * Get cache statistics
60
+ */
61
+ getCacheStats(): {
62
+ size: number;
63
+ maxSize: number;
64
+ } | null;
65
+ private validatePayload;
66
+ }