@naman_deep_singh/security 1.5.1 → 1.7.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 (107) hide show
  1. package/README.md +3 -3
  2. package/dist/cjs/core/crypto/CryptoManger.js +107 -0
  3. package/dist/cjs/core/crypto/index.js +13 -26
  4. package/dist/cjs/core/index.js +44 -0
  5. package/dist/cjs/core/jwt/{jwtManager.js → JWTManager.js} +22 -22
  6. package/dist/cjs/core/jwt/decode.js +2 -3
  7. package/dist/cjs/core/jwt/generateTokens.js +8 -8
  8. package/dist/cjs/core/jwt/index.js +23 -22
  9. package/dist/cjs/core/jwt/parseDuration.js +3 -3
  10. package/dist/cjs/core/jwt/signToken.js +4 -4
  11. package/dist/cjs/core/jwt/validateToken.js +4 -4
  12. package/dist/cjs/core/jwt/verify.js +13 -13
  13. package/dist/cjs/core/password/{passwordManager.js → PasswordManager.js} +8 -8
  14. package/dist/cjs/core/password/hash.js +6 -6
  15. package/dist/cjs/core/password/index.js +20 -17
  16. package/dist/cjs/core/password/strength.js +7 -7
  17. package/dist/cjs/core/password/utils.js +2 -2
  18. package/dist/cjs/core/password/verify.js +5 -5
  19. package/dist/cjs/index.js +4 -40
  20. package/dist/cjs/interfaces/index.js +2 -0
  21. package/dist/esm/core/crypto/CryptoManger.js +100 -0
  22. package/dist/esm/core/crypto/index.js +5 -5
  23. package/dist/esm/core/index.js +6 -0
  24. package/dist/esm/core/jwt/{jwtManager.js → JWTManager.js} +4 -4
  25. package/dist/esm/core/jwt/decode.js +1 -2
  26. package/dist/esm/core/jwt/generateTokens.js +3 -3
  27. package/dist/esm/core/jwt/index.js +8 -8
  28. package/dist/esm/core/jwt/parseDuration.js +1 -1
  29. package/dist/esm/core/jwt/signToken.js +2 -2
  30. package/dist/esm/core/jwt/validateToken.js +1 -1
  31. package/dist/esm/core/jwt/verify.js +1 -1
  32. package/dist/esm/core/password/{passwordManager.js → PasswordManager.js} +2 -2
  33. package/dist/esm/core/password/hash.js +4 -4
  34. package/dist/esm/core/password/index.js +5 -3
  35. package/dist/esm/core/password/strength.js +1 -1
  36. package/dist/esm/core/password/utils.js +1 -1
  37. package/dist/esm/core/password/verify.js +1 -1
  38. package/dist/esm/index.js +4 -13
  39. package/dist/esm/interfaces/index.js +1 -0
  40. package/dist/types/core/crypto/CryptoManger.d.ts +36 -0
  41. package/dist/types/core/crypto/index.d.ts +5 -5
  42. package/dist/types/core/index.d.ts +3 -0
  43. package/dist/{esm/core/jwt/jwtManager.d.ts → types/core/jwt/JWTManager.d.ts} +1 -1
  44. package/dist/types/core/jwt/generateTokens.d.ts +1 -1
  45. package/dist/types/core/jwt/index.d.ts +9 -8
  46. package/dist/types/core/jwt/verify.d.ts +1 -1
  47. package/dist/types/core/password/{passwordManager.d.ts → PasswordManager.d.ts} +1 -1
  48. package/dist/types/core/password/index.d.ts +6 -3
  49. package/dist/types/core/password/strength.d.ts +1 -1
  50. package/dist/types/index.d.ts +1 -40
  51. package/dist/types/interfaces/index.d.ts +2 -0
  52. package/package.json +33 -4
  53. package/dist/cjs/core/crypto/cryptoManager.d.ts +0 -111
  54. package/dist/cjs/core/crypto/cryptoManager.js +0 -208
  55. package/dist/cjs/core/crypto/decrypt.d.ts +0 -1
  56. package/dist/cjs/core/crypto/encrypt.d.ts +0 -1
  57. package/dist/cjs/core/crypto/hmac.d.ts +0 -8
  58. package/dist/cjs/core/crypto/index.d.ts +0 -5
  59. package/dist/cjs/core/crypto/random.d.ts +0 -8
  60. package/dist/cjs/core/jwt/decode.d.ts +0 -12
  61. package/dist/cjs/core/jwt/extractToken.d.ts +0 -11
  62. package/dist/cjs/core/jwt/generateTokens.d.ts +0 -4
  63. package/dist/cjs/core/jwt/index.d.ts +0 -8
  64. package/dist/cjs/core/jwt/jwtManager.d.ts +0 -43
  65. package/dist/cjs/core/jwt/parseDuration.d.ts +0 -1
  66. package/dist/cjs/core/jwt/signToken.d.ts +0 -2
  67. package/dist/cjs/core/jwt/types.d.ts +0 -22
  68. package/dist/cjs/core/jwt/validateToken.d.ts +0 -16
  69. package/dist/cjs/core/jwt/verify.d.ts +0 -18
  70. package/dist/cjs/core/password/hash.d.ts +0 -10
  71. package/dist/cjs/core/password/index.d.ts +0 -3
  72. package/dist/cjs/core/password/passwordManager.d.ts +0 -29
  73. package/dist/cjs/core/password/strength.d.ts +0 -2
  74. package/dist/cjs/core/password/types.d.ts +0 -7
  75. package/dist/cjs/core/password/utils.d.ts +0 -16
  76. package/dist/cjs/core/password/verify.d.ts +0 -10
  77. package/dist/cjs/index.d.ts +0 -40
  78. package/dist/cjs/interfaces/jwt.interface.d.ts +0 -47
  79. package/dist/cjs/interfaces/password.interface.d.ts +0 -60
  80. package/dist/esm/core/crypto/cryptoManager.d.ts +0 -111
  81. package/dist/esm/core/crypto/cryptoManager.js +0 -203
  82. package/dist/esm/core/crypto/decrypt.d.ts +0 -1
  83. package/dist/esm/core/crypto/encrypt.d.ts +0 -1
  84. package/dist/esm/core/crypto/hmac.d.ts +0 -8
  85. package/dist/esm/core/crypto/index.d.ts +0 -5
  86. package/dist/esm/core/crypto/random.d.ts +0 -8
  87. package/dist/esm/core/jwt/decode.d.ts +0 -12
  88. package/dist/esm/core/jwt/extractToken.d.ts +0 -11
  89. package/dist/esm/core/jwt/generateTokens.d.ts +0 -4
  90. package/dist/esm/core/jwt/index.d.ts +0 -8
  91. package/dist/esm/core/jwt/parseDuration.d.ts +0 -1
  92. package/dist/esm/core/jwt/signToken.d.ts +0 -2
  93. package/dist/esm/core/jwt/types.d.ts +0 -22
  94. package/dist/esm/core/jwt/validateToken.d.ts +0 -16
  95. package/dist/esm/core/jwt/verify.d.ts +0 -18
  96. package/dist/esm/core/password/hash.d.ts +0 -10
  97. package/dist/esm/core/password/index.d.ts +0 -3
  98. package/dist/esm/core/password/passwordManager.d.ts +0 -29
  99. package/dist/esm/core/password/strength.d.ts +0 -2
  100. package/dist/esm/core/password/types.d.ts +0 -7
  101. package/dist/esm/core/password/utils.d.ts +0 -16
  102. package/dist/esm/core/password/verify.d.ts +0 -10
  103. package/dist/esm/index.d.ts +0 -40
  104. package/dist/esm/interfaces/jwt.interface.d.ts +0 -47
  105. package/dist/esm/interfaces/password.interface.d.ts +0 -60
  106. package/dist/types/core/crypto/cryptoManager.d.ts +0 -111
  107. package/dist/types/core/jwt/jwtManager.d.ts +0 -43
@@ -1,16 +0,0 @@
1
- import type { JwtPayload } from 'jsonwebtoken';
2
- export interface TokenRequirements {
3
- requiredFields?: string[];
4
- forbiddenFields?: string[];
5
- validateTypes?: Record<string, 'string' | 'number' | 'boolean'>;
6
- }
7
- /**
8
- * Validates a JWT payload according to the provided rules.
9
- * Throws ValidationError if validation fails.
10
- */
11
- export declare function validateTokenPayload(payload: Record<string, unknown>, rules?: TokenRequirements): void;
12
- /**
13
- * Checks if a JWT payload is expired.
14
- * Returns true if expired or missing 'exp'.
15
- */
16
- export declare function isTokenExpired(payload: JwtPayload): boolean;
@@ -1,18 +0,0 @@
1
- import { type JwtPayload, type Secret, type VerifyOptions } from 'jsonwebtoken';
2
- import type { VerificationResult } from './types';
3
- /**
4
- * Verify token (throws UnauthorizedError if invalid or expired)
5
- */
6
- export declare const verifyToken: (token: string, secret: Secret) => string | JwtPayload;
7
- /**
8
- * Verify token with options
9
- */
10
- export declare const verifyTokenWithOptions: (token: string, secret: Secret, options?: VerifyOptions) => string | JwtPayload;
11
- /**
12
- * Safe verify — never throws, returns structured result with UnauthorizedError on failure
13
- */
14
- export declare const safeVerifyToken: (token: string, secret: Secret) => VerificationResult;
15
- /**
16
- * Safe verify with options — never throws, returns structured result with UnauthorizedError on failure
17
- */
18
- export declare const safeVerifyTokenWithOptions: (token: string, secret: Secret, options?: VerifyOptions) => VerificationResult;
@@ -1,10 +0,0 @@
1
- /**
2
- * Hash a password asynchronously using bcrypt.
3
- */
4
- export declare const hashPassword: (password: string, saltRounds?: number) => Promise<string>;
5
- export declare function hashPasswordWithPepper(password: string, pepper: string): Promise<string>;
6
- /**
7
- * Hash a password synchronously using bcrypt.
8
- */
9
- export declare const hashPasswordSync: (password: string, saltRounds?: number) => string;
10
- export declare function hashPasswordWithPepperSync(password: string, pepper: string): string;
@@ -1,3 +0,0 @@
1
- export * from './hash';
2
- export * from './strength';
3
- export * from './verify';
@@ -1,29 +0,0 @@
1
- import type { HashedPassword, IPasswordManager, PasswordConfig, PasswordStrength, PasswordValidationResult } 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 (saltRounds change)
27
- */
28
- needsUpgrade(_hash: string, _currentConfig: PasswordConfig): boolean;
29
- }
@@ -1,2 +0,0 @@
1
- import type { PasswordStrengthOptions } from './types';
2
- export declare const isPasswordStrong: (password: string, options?: PasswordStrengthOptions) => boolean;
@@ -1,7 +0,0 @@
1
- export interface PasswordStrengthOptions {
2
- minLength?: number;
3
- requireUppercase?: boolean;
4
- requireLowercase?: boolean;
5
- requireNumbers?: boolean;
6
- requireSymbols?: boolean;
7
- }
@@ -1,16 +0,0 @@
1
- /**
2
- * Ensure password is a valid non-empty string
3
- */
4
- export declare function ensureValidPassword(password: string): void;
5
- /**
6
- * Timing-safe comparison between two strings
7
- */
8
- export declare function safeCompare(a: string, b: string): boolean;
9
- /**
10
- * Estimate password entropy based on character pool
11
- */
12
- export declare function estimatePasswordEntropy(password: string): number;
13
- /**
14
- * Normalize password string to a consistent form
15
- */
16
- export declare function normalizePassword(password: string): string;
@@ -1,10 +0,0 @@
1
- /**
2
- * Compare a password with a stored hash asynchronously.
3
- */
4
- export declare const verifyPassword: (password: string, hash: string) => Promise<boolean>;
5
- export declare function verifyPasswordWithPepper(password: string, pepper: string, hash: string): Promise<boolean>;
6
- /**
7
- * Compare a password with a stored hash synchronously.
8
- */
9
- export declare const verifyPasswordSync: (password: string, hash: string) => boolean;
10
- export declare function verifyPasswordWithPepperSync(password: string, pepper: string, hash: string): Promise<boolean>;
@@ -1,40 +0,0 @@
1
- export * from './core/password';
2
- export * from './core/jwt';
3
- export * from './core/crypto';
4
- export { BadRequestError, UnauthorizedError, ValidationError, InternalServerError, } from '@naman_deep_singh/errors-utils';
5
- import * as CryptoUtils from './core/crypto';
6
- import * as JWTUtils from './core/jwt';
7
- declare const _default: {
8
- decrypt: (data: string, secret: string) => string;
9
- encrypt: (text: string, secret: string) => string;
10
- hmacSign: (message: string, secret: string) => string;
11
- hmacVerify: (message: string, secret: string, signature: string) => boolean;
12
- randomToken: (length?: number) => string;
13
- generateStrongPassword: (length?: number) => string;
14
- CryptoManager: typeof CryptoUtils.CryptoManager;
15
- createCryptoManager: (config?: CryptoUtils.CryptoManagerConfig) => CryptoUtils.CryptoManager;
16
- cryptoManager: CryptoUtils.CryptoManager;
17
- decodeToken(token: string): null | string | import("node_modules/@types/jsonwebtoken").JwtPayload;
18
- decodeTokenStrict(token: string): import("node_modules/@types/jsonwebtoken").JwtPayload;
19
- extractToken(sources: JWTUtils.TokenSources): string | null;
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;
22
- parseDuration(input: string | number): number;
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): void;
25
- isTokenExpired(payload: import("node_modules/@types/jsonwebtoken").JwtPayload): boolean;
26
- verifyToken: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret) => string | import("node_modules/@types/jsonwebtoken").JwtPayload;
27
- verifyTokenWithOptions: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret, options?: import("node_modules/@types/jsonwebtoken").VerifyOptions) => string | import("node_modules/@types/jsonwebtoken").JwtPayload;
28
- safeVerifyToken: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret) => JWTUtils.VerificationResult;
29
- safeVerifyTokenWithOptions: (token: string, secret: import("node_modules/@types/jsonwebtoken").Secret, options?: import("node_modules/@types/jsonwebtoken").VerifyOptions) => JWTUtils.VerificationResult;
30
- hashPasswordWithPepper(password: string, pepper: string): Promise<string>;
31
- hashPasswordWithPepperSync(password: string, pepper: string): string;
32
- hashPassword: (password: string, saltRounds?: number) => Promise<string>;
33
- hashPasswordSync: (password: string, saltRounds?: number) => string;
34
- isPasswordStrong: (password: string, options?: import("./core/password/types").PasswordStrengthOptions) => boolean;
35
- verifyPasswordWithPepper(password: string, pepper: string, hash: string): Promise<boolean>;
36
- verifyPasswordWithPepperSync(password: string, pepper: string, hash: string): Promise<boolean>;
37
- verifyPassword: (password: string, hash: string) => Promise<boolean>;
38
- verifyPasswordSync: (password: string, hash: string) => boolean;
39
- };
40
- export default _default;
@@ -1,47 +0,0 @@
1
- import type { 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
- }
@@ -1,60 +0,0 @@
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
- }
@@ -1,111 +0,0 @@
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,203 +0,0 @@
1
- import { CryptoIntegrityError } from '@naman_deep_singh/errors-utils';
2
- import { decrypt as functionalDecrypt, encrypt as functionalEncrypt, hmacSign as functionalHmacSign, hmacVerify as functionalHmacVerify, randomToken as functionalRandomToken, } from './index';
3
- /**
4
- * Default configuration
5
- */
6
- const DEFAULT_CONFIG = {
7
- defaultAlgorithm: 'aes-256-gcm',
8
- defaultEncoding: 'utf8',
9
- hmacAlgorithm: 'sha256',
10
- };
11
- /**
12
- * CryptoManager - Class-based wrapper for all cryptographic operations
13
- * Provides a consistent interface for encryption, decryption, HMAC generation, and secure random generation
14
- */
15
- export class CryptoManager {
16
- constructor(config = {}) {
17
- this.config = { ...DEFAULT_CONFIG, ...config };
18
- }
19
- /**
20
- * Update configuration
21
- */
22
- updateConfig(config) {
23
- this.config = { ...this.config, ...config };
24
- }
25
- /**
26
- * Get current configuration
27
- */
28
- getConfig() {
29
- return { ...this.config };
30
- }
31
- /**
32
- * Encrypt data using the default or specified algorithm
33
- */
34
- encrypt(plaintext, key, _options) {
35
- try {
36
- return functionalEncrypt(plaintext, key);
37
- }
38
- catch (error) {
39
- throw new CryptoIntegrityError({
40
- reason: 'Encryption failed',
41
- }, error instanceof Error ? error : undefined);
42
- }
43
- }
44
- /**
45
- * Decrypt data using the default or specified algorithm
46
- */
47
- decrypt(encryptedData, key, _options) {
48
- try {
49
- return functionalDecrypt(encryptedData, key);
50
- }
51
- catch (error) {
52
- throw new CryptoIntegrityError({
53
- reason: 'Decryption failed',
54
- }, error instanceof Error ? error : undefined);
55
- }
56
- }
57
- /**
58
- * Generate HMAC signature
59
- */
60
- generateHmac(data, secret, _options) {
61
- // Use the basic HMAC sign function for now
62
- // TODO: Add support for different algorithms
63
- return functionalHmacSign(data, secret);
64
- }
65
- /**
66
- * Generate cryptographically secure random bytes
67
- */
68
- generateSecureRandom(length, _encoding = 'hex') {
69
- // Use the basic random token function
70
- return functionalRandomToken(length);
71
- }
72
- /**
73
- * Verify HMAC signature
74
- */
75
- verifyHmac(data, secret, signature, _options) {
76
- // Use the basic HMAC verify function
77
- return functionalHmacVerify(data, secret, signature);
78
- }
79
- /**
80
- * Create a key derivation function using PBKDF2
81
- */
82
- deriveKey(password, salt, iterations = 100000, keyLength = 32) {
83
- return new Promise((resolve, reject) => {
84
- const crypto = require('crypto');
85
- crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (error, derivedKey) => {
86
- if (error) {
87
- reject(new CryptoIntegrityError({
88
- reason: 'Key derivation failed',
89
- }, error instanceof Error ? error : undefined));
90
- }
91
- else {
92
- resolve(derivedKey.toString('hex'));
93
- }
94
- });
95
- });
96
- }
97
- /**
98
- * Hash data using SHA-256
99
- */
100
- sha256(data, encoding = 'hex') {
101
- const crypto = require('crypto');
102
- return crypto.createHash('sha256').update(data).digest(encoding);
103
- }
104
- /**
105
- * Hash data using SHA-512
106
- */
107
- sha512(data, encoding = 'hex') {
108
- const crypto = require('crypto');
109
- return crypto.createHash('sha512').update(data).digest(encoding);
110
- }
111
- /**
112
- * Generate a secure key pair for asymmetric encryption
113
- */
114
- generateKeyPair(options) {
115
- return new Promise((resolve, _reject) => {
116
- const crypto = require('crypto');
117
- const keyPair = crypto.generateKeyPairSync('rsa', {
118
- modulusLength: options?.modulusLength || 2048,
119
- publicKeyEncoding: options?.publicKeyEncoding || {
120
- type: 'spki',
121
- format: 'pem',
122
- },
123
- privateKeyEncoding: options?.privateKeyEncoding || {
124
- type: 'pkcs8',
125
- format: 'pem',
126
- },
127
- });
128
- resolve(keyPair);
129
- });
130
- }
131
- /**
132
- * Encrypt data using RSA public key
133
- */
134
- rsaEncrypt(data, publicKey) {
135
- return new Promise((resolve, _reject) => {
136
- const crypto = require('crypto');
137
- const buffer = Buffer.from(data, 'utf8');
138
- const encrypted = crypto.publicEncrypt(publicKey, buffer);
139
- resolve(encrypted.toString('base64'));
140
- });
141
- }
142
- /**
143
- * Decrypt data using RSA private key
144
- */
145
- rsaDecrypt(encryptedData, privateKey) {
146
- return new Promise((resolve, _reject) => {
147
- const crypto = require('crypto');
148
- const buffer = Buffer.from(encryptedData, 'base64');
149
- const decrypted = crypto.privateDecrypt(privateKey, buffer);
150
- resolve(decrypted.toString('utf8'));
151
- });
152
- }
153
- /**
154
- * Create digital signature using RSA private key
155
- */
156
- rsaSign(data, privateKey, algorithm = 'sha256') {
157
- return new Promise((resolve, reject) => {
158
- const crypto = require('crypto');
159
- try {
160
- const sign = crypto.createSign(algorithm);
161
- sign.update(data);
162
- sign.end();
163
- const signature = sign.sign(privateKey, 'base64');
164
- resolve(signature);
165
- }
166
- catch (error) {
167
- reject(new CryptoIntegrityError({
168
- reason: 'RSA signing failed',
169
- }, error instanceof Error ? error : undefined));
170
- }
171
- });
172
- }
173
- /**
174
- * Verify digital signature using RSA public key
175
- */
176
- rsaVerify(data, signature, publicKey, algorithm = 'sha256') {
177
- return new Promise((resolve, reject) => {
178
- const crypto = require('crypto');
179
- try {
180
- const verify = crypto.createVerify(algorithm);
181
- verify.update(data);
182
- verify.end();
183
- const isValid = verify.verify(publicKey, signature, 'base64');
184
- resolve(isValid);
185
- }
186
- catch (error) {
187
- reject(new CryptoIntegrityError({
188
- reason: 'RSA verification failed',
189
- }, error instanceof Error ? error : undefined));
190
- }
191
- });
192
- }
193
- }
194
- /**
195
- * Create a CryptoManager instance with default configuration
196
- */
197
- export const createCryptoManager = (config) => {
198
- return new CryptoManager(config);
199
- };
200
- /**
201
- * Default CryptoManager instance
202
- */
203
- export const cryptoManager = new CryptoManager();
@@ -1 +0,0 @@
1
- export declare const decrypt: (data: string, secret: string) => string;
@@ -1 +0,0 @@
1
- export declare const encrypt: (text: string, secret: string) => string;
@@ -1,8 +0,0 @@
1
- /**
2
- * Sign message using HMAC SHA-256
3
- */
4
- export declare const hmacSign: (message: string, secret: string) => string;
5
- /**
6
- * Verify HMAC signature
7
- */
8
- export declare const hmacVerify: (message: string, secret: string, signature: string) => boolean;
@@ -1,5 +0,0 @@
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,8 +0,0 @@
1
- /**
2
- * Generate cryptographically secure random string
3
- */
4
- export declare const randomToken: (length?: number) => string;
5
- /**
6
- * Generate a strong random password
7
- */
8
- export declare const generateStrongPassword: (length?: number) => string;
@@ -1,12 +0,0 @@
1
- import { type JwtPayload } from 'jsonwebtoken';
2
- /**
3
- * Flexible decode
4
- * Returns: null | string | JwtPayload
5
- * Mirrors jsonwebtoken.decode()
6
- */
7
- export declare function decodeToken(token: string): null | string | JwtPayload;
8
- /**
9
- * Strict decode
10
- * Always returns JwtPayload or throws error
11
- */
12
- export declare function decodeTokenStrict(token: string): JwtPayload;
@@ -1,11 +0,0 @@
1
- export interface TokenSources {
2
- header?: string | undefined | null;
3
- cookies?: Record<string, string> | undefined;
4
- query?: Record<string, string | undefined> | undefined;
5
- body?: Record<string, unknown> | undefined;
6
- wsMessage?: string | Record<string, unknown> | undefined;
7
- }
8
- /**
9
- * Universal token extractor
10
- */
11
- export declare function extractToken(sources: TokenSources): string | null;
@@ -1,4 +0,0 @@
1
- import type { Secret } from 'jsonwebtoken';
2
- import type { 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;
@@ -1,8 +0,0 @@
1
- export * from './decode';
2
- export * from './extractToken';
3
- export * from './generateTokens';
4
- export * from './parseDuration';
5
- export * from './signToken';
6
- export * from './types';
7
- export * from './validateToken';
8
- export * from './verify';
@@ -1 +0,0 @@
1
- export declare function parseDuration(input: string | number): number;
@@ -1,2 +0,0 @@
1
- import { type Secret, type SignOptions } from 'jsonwebtoken';
2
- export declare const signToken: (payload: Record<string, unknown>, secret: Secret, expiresIn?: string | number, options?: SignOptions) => string;