@naman_deep_singh/security 1.2.0 → 1.3.1

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 (95) 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 +191 -0
  4. package/dist/cjs/core/crypto/decrypt.js +6 -6
  5. package/dist/cjs/core/crypto/encrypt.js +4 -4
  6. package/dist/cjs/core/crypto/hmac.js +1 -1
  7. package/dist/cjs/core/crypto/index.d.ts +5 -4
  8. package/dist/cjs/core/crypto/index.js +12 -4
  9. package/dist/cjs/core/crypto/random.js +2 -2
  10. package/dist/cjs/core/jwt/decode.d.ts +1 -1
  11. package/dist/cjs/core/jwt/decode.js +2 -2
  12. package/dist/cjs/core/jwt/extractToken.js +7 -7
  13. package/dist/cjs/core/jwt/generateTokens.d.ts +2 -2
  14. package/dist/cjs/core/jwt/generateTokens.js +10 -6
  15. package/dist/cjs/core/jwt/index.d.ts +8 -8
  16. package/dist/cjs/core/jwt/jwtManager.d.ts +67 -0
  17. package/dist/cjs/core/jwt/jwtManager.js +299 -0
  18. package/dist/cjs/core/jwt/parseDuration.js +3 -3
  19. package/dist/cjs/core/jwt/signToken.d.ts +1 -1
  20. package/dist/cjs/core/jwt/signToken.js +7 -7
  21. package/dist/cjs/core/jwt/types.d.ts +1 -1
  22. package/dist/cjs/core/jwt/validateToken.d.ts +2 -2
  23. package/dist/cjs/core/jwt/validateToken.js +3 -3
  24. package/dist/cjs/core/jwt/verify.d.ts +3 -2
  25. package/dist/cjs/core/password/hash.js +1 -1
  26. package/dist/cjs/core/password/index.d.ts +3 -3
  27. package/dist/cjs/core/password/passwordManager.d.ts +29 -0
  28. package/dist/cjs/core/password/passwordManager.js +243 -0
  29. package/dist/cjs/core/password/strength.d.ts +1 -1
  30. package/dist/cjs/core/password/strength.js +4 -4
  31. package/dist/cjs/core/password/utils.js +2 -2
  32. package/dist/cjs/core/password/verify.js +1 -1
  33. package/dist/cjs/index.d.ts +9 -5
  34. package/dist/cjs/index.js +2 -2
  35. package/dist/cjs/interfaces/jwt.interface.d.ts +47 -0
  36. package/dist/cjs/interfaces/jwt.interface.js +2 -0
  37. package/dist/cjs/interfaces/password.interface.d.ts +60 -0
  38. package/dist/cjs/interfaces/password.interface.js +2 -0
  39. package/dist/esm/core/crypto/cryptoManager.d.ts +111 -0
  40. package/dist/esm/core/crypto/cryptoManager.js +186 -0
  41. package/dist/esm/core/crypto/decrypt.js +7 -7
  42. package/dist/esm/core/crypto/encrypt.js +5 -5
  43. package/dist/esm/core/crypto/hmac.js +2 -2
  44. package/dist/esm/core/crypto/index.d.ts +5 -4
  45. package/dist/esm/core/crypto/index.js +5 -4
  46. package/dist/esm/core/crypto/random.js +3 -3
  47. package/dist/esm/core/jwt/decode.d.ts +1 -1
  48. package/dist/esm/core/jwt/decode.js +3 -3
  49. package/dist/esm/core/jwt/extractToken.js +7 -7
  50. package/dist/esm/core/jwt/generateTokens.d.ts +2 -2
  51. package/dist/esm/core/jwt/generateTokens.js +12 -8
  52. package/dist/esm/core/jwt/index.d.ts +8 -8
  53. package/dist/esm/core/jwt/index.js +8 -8
  54. package/dist/esm/core/jwt/jwtManager.d.ts +67 -0
  55. package/dist/esm/core/jwt/jwtManager.js +292 -0
  56. package/dist/esm/core/jwt/parseDuration.js +3 -3
  57. package/dist/esm/core/jwt/signToken.d.ts +1 -1
  58. package/dist/esm/core/jwt/signToken.js +9 -9
  59. package/dist/esm/core/jwt/types.d.ts +1 -1
  60. package/dist/esm/core/jwt/validateToken.d.ts +2 -2
  61. package/dist/esm/core/jwt/validateToken.js +3 -3
  62. package/dist/esm/core/jwt/verify.d.ts +3 -2
  63. package/dist/esm/core/jwt/verify.js +1 -1
  64. package/dist/esm/core/password/hash.js +3 -3
  65. package/dist/esm/core/password/index.d.ts +3 -3
  66. package/dist/esm/core/password/index.js +3 -3
  67. package/dist/esm/core/password/passwordManager.d.ts +29 -0
  68. package/dist/esm/core/password/passwordManager.js +236 -0
  69. package/dist/esm/core/password/strength.d.ts +1 -1
  70. package/dist/esm/core/password/strength.js +5 -5
  71. package/dist/esm/core/password/utils.js +4 -4
  72. package/dist/esm/core/password/verify.js +2 -2
  73. package/dist/esm/index.d.ts +9 -5
  74. package/dist/esm/index.js +7 -7
  75. package/dist/esm/interfaces/jwt.interface.d.ts +47 -0
  76. package/dist/esm/interfaces/jwt.interface.js +1 -0
  77. package/dist/esm/interfaces/password.interface.d.ts +60 -0
  78. package/dist/esm/interfaces/password.interface.js +1 -0
  79. package/dist/types/core/crypto/cryptoManager.d.ts +111 -0
  80. package/dist/types/core/crypto/index.d.ts +5 -4
  81. package/dist/types/core/jwt/decode.d.ts +1 -1
  82. package/dist/types/core/jwt/generateTokens.d.ts +2 -2
  83. package/dist/types/core/jwt/index.d.ts +8 -8
  84. package/dist/types/core/jwt/jwtManager.d.ts +67 -0
  85. package/dist/types/core/jwt/signToken.d.ts +1 -1
  86. package/dist/types/core/jwt/types.d.ts +1 -1
  87. package/dist/types/core/jwt/validateToken.d.ts +2 -2
  88. package/dist/types/core/jwt/verify.d.ts +3 -2
  89. package/dist/types/core/password/index.d.ts +3 -3
  90. package/dist/types/core/password/passwordManager.d.ts +29 -0
  91. package/dist/types/core/password/strength.d.ts +1 -1
  92. package/dist/types/index.d.ts +9 -5
  93. package/dist/types/interfaces/jwt.interface.d.ts +47 -0
  94. package/dist/types/interfaces/password.interface.d.ts +60 -0
  95. package/package.json +4 -3
@@ -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,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cryptoManager = exports.createCryptoManager = exports.CryptoManager = void 0;
4
+ const index_1 = require("./index");
5
+ /**
6
+ * Default configuration
7
+ */
8
+ const DEFAULT_CONFIG = {
9
+ defaultAlgorithm: 'aes-256-gcm',
10
+ defaultEncoding: 'utf8',
11
+ hmacAlgorithm: 'sha256',
12
+ };
13
+ /**
14
+ * CryptoManager - Class-based wrapper for all cryptographic operations
15
+ * Provides a consistent interface for encryption, decryption, HMAC generation, and secure random generation
16
+ */
17
+ class CryptoManager {
18
+ constructor(config = {}) {
19
+ this.config = { ...DEFAULT_CONFIG, ...config };
20
+ }
21
+ /**
22
+ * Update configuration
23
+ */
24
+ updateConfig(config) {
25
+ this.config = { ...this.config, ...config };
26
+ }
27
+ /**
28
+ * Get current configuration
29
+ */
30
+ getConfig() {
31
+ return { ...this.config };
32
+ }
33
+ /**
34
+ * Encrypt data using the default or specified algorithm
35
+ */
36
+ encrypt(plaintext, key, options) {
37
+ // For now, use the basic encrypt function
38
+ // TODO: Enhance to support different algorithms and options
39
+ return (0, index_1.encrypt)(plaintext, key);
40
+ }
41
+ /**
42
+ * Decrypt data using the default or specified algorithm
43
+ */
44
+ decrypt(encryptedData, key, options) {
45
+ // For now, use the basic decrypt function
46
+ // TODO: Enhance to support different algorithms and options
47
+ return (0, index_1.decrypt)(encryptedData, key);
48
+ }
49
+ /**
50
+ * Generate HMAC signature
51
+ */
52
+ generateHmac(data, secret, options) {
53
+ // Use the basic HMAC sign function for now
54
+ // TODO: Add support for different algorithms
55
+ return (0, index_1.hmacSign)(data, secret);
56
+ }
57
+ /**
58
+ * Generate cryptographically secure random bytes
59
+ */
60
+ generateSecureRandom(length, encoding = 'hex') {
61
+ // Use the basic random token function
62
+ return (0, index_1.randomToken)(length);
63
+ }
64
+ /**
65
+ * Verify HMAC signature
66
+ */
67
+ verifyHmac(data, secret, signature, options) {
68
+ // Use the basic HMAC verify function
69
+ return (0, index_1.hmacVerify)(data, secret, signature);
70
+ }
71
+ /**
72
+ * Create a key derivation function using PBKDF2
73
+ */
74
+ deriveKey(password, salt, iterations = 100000, keyLength = 32) {
75
+ return new Promise((resolve, reject) => {
76
+ const crypto = require('crypto');
77
+ crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (err, derivedKey) => {
78
+ if (err) {
79
+ reject(err);
80
+ }
81
+ else {
82
+ resolve(derivedKey.toString('hex'));
83
+ }
84
+ });
85
+ });
86
+ }
87
+ /**
88
+ * Hash data using SHA-256
89
+ */
90
+ sha256(data, encoding = 'hex') {
91
+ const crypto = require('crypto');
92
+ return crypto.createHash('sha256').update(data).digest(encoding);
93
+ }
94
+ /**
95
+ * Hash data using SHA-512
96
+ */
97
+ sha512(data, encoding = 'hex') {
98
+ const crypto = require('crypto');
99
+ return crypto.createHash('sha512').update(data).digest(encoding);
100
+ }
101
+ /**
102
+ * Generate a secure key pair for asymmetric encryption
103
+ */
104
+ generateKeyPair(options) {
105
+ return new Promise((resolve, reject) => {
106
+ const crypto = require('crypto');
107
+ const keyPair = crypto.generateKeyPairSync('rsa', {
108
+ modulusLength: options?.modulusLength || 2048,
109
+ publicKeyEncoding: options?.publicKeyEncoding || {
110
+ type: 'spki',
111
+ format: 'pem',
112
+ },
113
+ privateKeyEncoding: options?.privateKeyEncoding || {
114
+ type: 'pkcs8',
115
+ format: 'pem',
116
+ },
117
+ });
118
+ resolve(keyPair);
119
+ });
120
+ }
121
+ /**
122
+ * Encrypt data using RSA public key
123
+ */
124
+ rsaEncrypt(data, publicKey) {
125
+ return new Promise((resolve, reject) => {
126
+ const crypto = require('crypto');
127
+ const buffer = Buffer.from(data, 'utf8');
128
+ const encrypted = crypto.publicEncrypt(publicKey, buffer);
129
+ resolve(encrypted.toString('base64'));
130
+ });
131
+ }
132
+ /**
133
+ * Decrypt data using RSA private key
134
+ */
135
+ rsaDecrypt(encryptedData, privateKey) {
136
+ return new Promise((resolve, reject) => {
137
+ const crypto = require('crypto');
138
+ const buffer = Buffer.from(encryptedData, 'base64');
139
+ const decrypted = crypto.privateDecrypt(privateKey, buffer);
140
+ resolve(decrypted.toString('utf8'));
141
+ });
142
+ }
143
+ /**
144
+ * Create digital signature using RSA private key
145
+ */
146
+ rsaSign(data, privateKey, algorithm = 'sha256') {
147
+ return new Promise((resolve, reject) => {
148
+ const crypto = require('crypto');
149
+ const sign = crypto.createSign(algorithm);
150
+ sign.update(data);
151
+ sign.end();
152
+ try {
153
+ const signature = sign.sign(privateKey, 'base64');
154
+ resolve(signature);
155
+ }
156
+ catch (error) {
157
+ reject(error);
158
+ }
159
+ });
160
+ }
161
+ /**
162
+ * Verify digital signature using RSA public key
163
+ */
164
+ rsaVerify(data, signature, publicKey, algorithm = 'sha256') {
165
+ return new Promise((resolve, reject) => {
166
+ const crypto = require('crypto');
167
+ const verify = crypto.createVerify(algorithm);
168
+ verify.update(data);
169
+ verify.end();
170
+ try {
171
+ const isValid = verify.verify(publicKey, signature, 'base64');
172
+ resolve(isValid);
173
+ }
174
+ catch (error) {
175
+ reject(error);
176
+ }
177
+ });
178
+ }
179
+ }
180
+ exports.CryptoManager = CryptoManager;
181
+ /**
182
+ * Create a CryptoManager instance with default configuration
183
+ */
184
+ const createCryptoManager = (config) => {
185
+ return new CryptoManager(config);
186
+ };
187
+ exports.createCryptoManager = createCryptoManager;
188
+ /**
189
+ * Default CryptoManager instance
190
+ */
191
+ exports.cryptoManager = new CryptoManager();
@@ -5,17 +5,17 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.decrypt = void 0;
7
7
  const crypto_1 = __importDefault(require("crypto"));
8
- const ALGO = "AES-256-GCM";
8
+ const ALGO = 'AES-256-GCM';
9
9
  const decrypt = (data, secret) => {
10
- const [ivHex, encryptedHex] = data.split(":");
11
- const iv = Buffer.from(ivHex, "hex");
12
- const encrypted = Buffer.from(encryptedHex, "hex");
13
- const key = crypto_1.default.createHash("sha256").update(secret).digest();
10
+ const [ivHex, encryptedHex] = data.split(':');
11
+ const iv = Buffer.from(ivHex, 'hex');
12
+ const encrypted = Buffer.from(encryptedHex, 'hex');
13
+ const key = crypto_1.default.createHash('sha256').update(secret).digest();
14
14
  const decipher = crypto_1.default.createDecipheriv(ALGO, key, iv);
15
15
  const decrypted = Buffer.concat([
16
16
  decipher.update(encrypted),
17
17
  decipher.final(),
18
18
  ]);
19
- return decrypted.toString("utf8");
19
+ return decrypted.toString('utf8');
20
20
  };
21
21
  exports.decrypt = decrypt;
@@ -5,12 +5,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.encrypt = void 0;
7
7
  const crypto_1 = __importDefault(require("crypto"));
8
- const ALGO = "AES-256-GCM";
8
+ const ALGO = 'AES-256-GCM';
9
9
  const encrypt = (text, secret) => {
10
- const key = crypto_1.default.createHash("sha256").update(secret).digest();
10
+ const key = crypto_1.default.createHash('sha256').update(secret).digest();
11
11
  const iv = crypto_1.default.randomBytes(16);
12
12
  const cipher = crypto_1.default.createCipheriv(ALGO, key, iv);
13
- const encrypted = Buffer.concat([cipher.update(text, "utf8"), cipher.final()]);
14
- return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
13
+ const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
14
+ return `${iv.toString('hex')}:${encrypted.toString('hex')}`;
15
15
  };
16
16
  exports.encrypt = encrypt;
@@ -9,7 +9,7 @@ const crypto_1 = __importDefault(require("crypto"));
9
9
  * Sign message using HMAC SHA-256
10
10
  */
11
11
  const hmacSign = (message, secret) => {
12
- return crypto_1.default.createHmac("sha256", secret).update(message).digest("hex");
12
+ return crypto_1.default.createHmac('sha256', secret).update(message).digest('hex');
13
13
  };
14
14
  exports.hmacSign = hmacSign;
15
15
  /**
@@ -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';
@@ -14,7 +14,15 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./decrypt"), exports);
18
- __exportStar(require("./encrypt"), exports);
19
- __exportStar(require("./hmac"), exports);
20
- __exportStar(require("./random"), exports);
17
+ exports.generateStrongPassword = exports.randomToken = exports.hmacVerify = exports.hmacSign = exports.encrypt = exports.decrypt = void 0;
18
+ var decrypt_1 = require("./decrypt");
19
+ Object.defineProperty(exports, "decrypt", { enumerable: true, get: function () { return decrypt_1.decrypt; } });
20
+ var encrypt_1 = require("./encrypt");
21
+ Object.defineProperty(exports, "encrypt", { enumerable: true, get: function () { return encrypt_1.encrypt; } });
22
+ var hmac_1 = require("./hmac");
23
+ Object.defineProperty(exports, "hmacSign", { enumerable: true, get: function () { return hmac_1.hmacSign; } });
24
+ Object.defineProperty(exports, "hmacVerify", { enumerable: true, get: function () { return hmac_1.hmacVerify; } });
25
+ var random_1 = require("./random");
26
+ Object.defineProperty(exports, "randomToken", { enumerable: true, get: function () { return random_1.randomToken; } });
27
+ Object.defineProperty(exports, "generateStrongPassword", { enumerable: true, get: function () { return random_1.generateStrongPassword; } });
28
+ __exportStar(require("./cryptoManager"), exports);
@@ -9,13 +9,13 @@ const crypto_1 = __importDefault(require("crypto"));
9
9
  * Generate cryptographically secure random string
10
10
  */
11
11
  const randomToken = (length = 32) => {
12
- return crypto_1.default.randomBytes(length).toString("hex");
12
+ return crypto_1.default.randomBytes(length).toString('hex');
13
13
  };
14
14
  exports.randomToken = randomToken;
15
15
  /**
16
16
  * Generate a strong random password
17
17
  */
18
18
  const generateStrongPassword = (length = 16) => {
19
- return crypto_1.default.randomBytes(length).toString("hex").slice(0, length);
19
+ return crypto_1.default.randomBytes(length).toString('hex').slice(0, length);
20
20
  };
21
21
  exports.generateStrongPassword = generateStrongPassword;
@@ -1,4 +1,4 @@
1
- import { JwtPayload } from "jsonwebtoken";
1
+ import { type JwtPayload } from 'jsonwebtoken';
2
2
  /**
3
3
  * Flexible decode
4
4
  * Returns: null | string | JwtPayload
@@ -18,8 +18,8 @@ function decodeToken(token) {
18
18
  */
19
19
  function decodeTokenStrict(token) {
20
20
  const decoded = (0, jsonwebtoken_1.decode)(token);
21
- if (!decoded || typeof decoded === "string") {
22
- throw new Error("Invalid JWT payload structure");
21
+ if (!decoded || typeof decoded === 'string') {
22
+ throw new Error('Invalid JWT payload structure');
23
23
  }
24
24
  return decoded;
25
25
  }
@@ -8,16 +8,16 @@ function extractToken(sources) {
8
8
  const { header, cookies, query, body, wsMessage } = sources;
9
9
  // 1. Authorization: Bearer <token>
10
10
  if (header) {
11
- const parts = header.split(" ");
12
- if (parts.length === 2 && parts[0] === "Bearer")
11
+ const parts = header.split(' ');
12
+ if (parts.length === 2 && parts[0] === 'Bearer')
13
13
  return parts[1];
14
14
  }
15
15
  // 2. Cookies: token / accessToken
16
16
  if (cookies) {
17
- if (cookies["token"])
18
- return cookies["token"];
19
- if (cookies["accessToken"])
20
- return cookies["accessToken"];
17
+ if (cookies['token'])
18
+ return cookies['token'];
19
+ if (cookies['accessToken'])
20
+ return cookies['accessToken'];
21
21
  }
22
22
  // 3. Query params: ?token=xxx
23
23
  if (query?.token)
@@ -30,7 +30,7 @@ function extractToken(sources) {
30
30
  try {
31
31
  let msg = wsMessage;
32
32
  // If it's a JSON string → parse safely
33
- if (typeof wsMessage === "string") {
33
+ if (typeof wsMessage === 'string') {
34
34
  msg = JSON.parse(wsMessage);
35
35
  }
36
36
  // Ensure msg is an object before property access
@@ -1,4 +1,4 @@
1
- import { Secret } from "jsonwebtoken";
2
- import { RefreshToken, TokenPair } from "./types";
1
+ import { type Secret } from 'jsonwebtoken';
2
+ import type { RefreshToken, TokenPair } from './types';
3
3
  export declare const generateTokens: (payload: Record<string, unknown>, accessSecret: Secret, refreshSecret: Secret, accessExpiry?: string | number, refreshExpiry?: string | number) => TokenPair;
4
4
  export declare function rotateRefreshToken(oldToken: string, secret: Secret): RefreshToken;
@@ -8,9 +8,13 @@ const verify_1 = require("./verify");
8
8
  const createBrandedToken = (token, _brand) => {
9
9
  return token;
10
10
  };
11
- const generateTokens = (payload, accessSecret, refreshSecret, accessExpiry = "15m", refreshExpiry = "7d") => {
12
- const accessToken = (0, signToken_1.signToken)(payload, accessSecret, accessExpiry, { algorithm: "HS256" });
13
- const refreshToken = (0, signToken_1.signToken)(payload, refreshSecret, refreshExpiry, { algorithm: "HS256" });
11
+ const generateTokens = (payload, accessSecret, refreshSecret, accessExpiry = '15m', refreshExpiry = '7d') => {
12
+ const accessToken = (0, signToken_1.signToken)(payload, accessSecret, accessExpiry, {
13
+ algorithm: 'HS256',
14
+ });
15
+ const refreshToken = (0, signToken_1.signToken)(payload, refreshSecret, refreshExpiry, {
16
+ algorithm: 'HS256',
17
+ });
14
18
  return {
15
19
  accessToken: accessToken,
16
20
  refreshToken: refreshToken,
@@ -19,12 +23,12 @@ const generateTokens = (payload, accessSecret, refreshSecret, accessExpiry = "15
19
23
  exports.generateTokens = generateTokens;
20
24
  function rotateRefreshToken(oldToken, secret) {
21
25
  const decoded = (0, verify_1.verifyToken)(oldToken, secret);
22
- if (typeof decoded === "string") {
23
- throw new Error("Invalid token payload — expected JWT payload object");
26
+ if (typeof decoded === 'string') {
27
+ throw new Error('Invalid token payload — expected JWT payload object');
24
28
  }
25
29
  const payload = { ...decoded };
26
30
  delete payload.iat;
27
31
  delete payload.exp;
28
- const newToken = (0, signToken_1.signToken)(payload, secret, "7d");
32
+ const newToken = (0, signToken_1.signToken)(payload, secret, '7d');
29
33
  return newToken;
30
34
  }
@@ -1,8 +1,8 @@
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
+ 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';
@@ -0,0 +1,67 @@
1
+ import { type JwtPayload, type Secret } from 'jsonwebtoken';
2
+ import type { AccessToken, ITokenManager, JWTConfig, RefreshToken, TokenPair, 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
+ private cacheTTL;
10
+ constructor(config: JWTConfig);
11
+ /**
12
+ * Generate both access and refresh tokens
13
+ */
14
+ generateTokens(payload: Record<string, unknown>): Promise<TokenPair>;
15
+ /**
16
+ * Generate access token
17
+ */
18
+ generateAccessToken(payload: Record<string, unknown>): Promise<AccessToken>;
19
+ /**
20
+ * Generate refresh token
21
+ */
22
+ generateRefreshToken(payload: Record<string, unknown>): Promise<RefreshToken>;
23
+ /**
24
+ * Verify access token
25
+ */
26
+ verifyAccessToken(token: string): Promise<JwtPayload | string>;
27
+ /**
28
+ * Verify refresh token
29
+ */
30
+ verifyRefreshToken(token: string): Promise<JwtPayload | string>;
31
+ /**
32
+ * Decode token without verification
33
+ */
34
+ decodeToken(token: string, complete?: boolean): JwtPayload | string | null;
35
+ /**
36
+ * Extract token from Authorization header
37
+ */
38
+ extractTokenFromHeader(authHeader: string): string | null;
39
+ /**
40
+ * Validate token without throwing exceptions
41
+ */
42
+ validateToken(token: string, secret: Secret, options?: TokenValidationOptions): boolean;
43
+ /**
44
+ * Rotate refresh token
45
+ */
46
+ rotateRefreshToken(oldToken: string): Promise<RefreshToken>;
47
+ /**
48
+ * Check if token is expired
49
+ */
50
+ isTokenExpired(token: string): boolean;
51
+ /**
52
+ * Get token expiration date
53
+ */
54
+ getTokenExpiration(token: string): Date | null;
55
+ /**
56
+ * Clear token cache
57
+ */
58
+ clearCache(): void;
59
+ /**
60
+ * Get cache statistics
61
+ */
62
+ getCacheStats(): {
63
+ size: number;
64
+ maxSize: number;
65
+ } | null;
66
+ private validatePayload;
67
+ }