@seip/bluebird-js 0.0.1 → 0.1.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 (81) hide show
  1. package/.env_example +53 -53
  2. package/AGENTS.md +426 -403
  3. package/LICENSE +1 -1
  4. package/README.md +292 -285
  5. package/app/routes/api.js +50 -50
  6. package/app/routes/web.js +55 -53
  7. package/app/views/about.js +63 -0
  8. package/app/views/dashboard.js +147 -0
  9. package/app/views/index.js +80 -0
  10. package/app/views/layouts/main/view.js +81 -0
  11. package/app/views/legal/terms.html +19 -0
  12. package/app/views/login.js +80 -0
  13. package/core/app.d.ts +18 -18
  14. package/core/app.js +684 -644
  15. package/core/auth.d.ts +13 -13
  16. package/core/auth.js +326 -326
  17. package/core/cache.d.ts +17 -17
  18. package/core/cache.js +475 -475
  19. package/core/cli/doctor.js +287 -287
  20. package/core/cli/ecosystem.js +162 -162
  21. package/core/cli/init.js +779 -779
  22. package/core/cli/migrate.js +541 -541
  23. package/core/cli/model.js +66 -66
  24. package/core/cli/nginx.js +199 -199
  25. package/core/cli/route.js +120 -120
  26. package/core/cli/view.js +55 -36
  27. package/core/config.d.ts +3 -3
  28. package/core/config.js +111 -111
  29. package/core/csrf.d.ts +3 -3
  30. package/core/csrf.js +114 -114
  31. package/core/database.d.ts +15 -15
  32. package/core/database.js +636 -636
  33. package/core/debug.d.ts +3 -3
  34. package/core/debug.js +249 -249
  35. package/core/hash.d.ts +3 -3
  36. package/core/hash.js +194 -194
  37. package/core/html.d.ts +42 -0
  38. package/core/html.js +217 -0
  39. package/core/index.d.ts +1176 -1071
  40. package/core/logger.d.ts +3 -3
  41. package/core/logger.js +127 -124
  42. package/core/middleware.d.ts +3 -3
  43. package/core/middleware.js +28 -28
  44. package/core/model.d.ts +19 -19
  45. package/core/model.js +600 -600
  46. package/core/queue.d.ts +13 -13
  47. package/core/queue.js +172 -172
  48. package/core/ratelimit.d.ts +3 -3
  49. package/core/ratelimit.js +145 -145
  50. package/core/redis.d.ts +21 -21
  51. package/core/redis.js +230 -230
  52. package/core/render-cache.js +212 -0
  53. package/core/render.d.ts +3 -3
  54. package/core/render.js +199 -555
  55. package/core/router.d.ts +3 -3
  56. package/core/router.js +171 -171
  57. package/core/seo.d.ts +3 -3
  58. package/core/seo.js +106 -106
  59. package/core/swagger.d.ts +3 -3
  60. package/core/swagger.js +60 -60
  61. package/core/upload.d.ts +13 -13
  62. package/core/upload.js +102 -102
  63. package/core/util/colors.js +82 -82
  64. package/core/validate.d.ts +15 -15
  65. package/core/validate.js +364 -364
  66. package/core/view-loader.js +162 -0
  67. package/core/vite.d.ts +3 -3
  68. package/core/vite.js +145 -145
  69. package/core/ws.d.ts +13 -13
  70. package/core/ws.js +245 -245
  71. package/index.js +18 -18
  72. package/jsconfig.json +15 -15
  73. package/package.json +85 -86
  74. package/production.md +273 -273
  75. package/public/css/bluebird.min.css +1 -1
  76. package/public/js/bluebird-client.js +1780 -1662
  77. package/public/js/bluebird.min.js +1072 -1072
  78. package/app/views/about.html +0 -161
  79. package/app/views/dashboard.html +0 -140
  80. package/app/views/index.html +0 -150
  81. package/app/views/login.html +0 -144
package/core/auth.js CHANGED
@@ -1,326 +1,326 @@
1
- import { createHmac, timingSafeEqual, createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
2
- import Config from "./config.js";
3
- import { getRedisClient } from "./cache.js";
4
-
5
- const propsConfig = Config.props();
6
- const jwtSecret = propsConfig.jwtSecret;
7
- const production = !propsConfig.debug;
8
-
9
- if (production && (!jwtSecret || jwtSecret === "default" || jwtSecret.length < 32)) {
10
- console.error("[AUTH FATAL] JWT_SECRET must be defined with at least 32 characters in production mode.");
11
- }
12
-
13
- /**
14
- * Resolves or derives the 256-bit AES encryption key from the provided secret.
15
- * @param {string} secret
16
- * @returns {Buffer}
17
- */
18
- function getAesKey(secret) {
19
- const resolved = secret || process.env.JWT_SECRET || propsConfig.jwtSecret || "default";
20
- return createHash("sha256").update(resolved).digest();
21
- }
22
-
23
- /**
24
- * In-memory revocation map for single-instance or non-Redis environments.
25
- * Maps sessionId to expiry timestamp in milliseconds.
26
- * @type {Map<string, number>}
27
- */
28
- const revokedSessions = new Map();
29
-
30
- setInterval(() => {
31
- if (revokedSessions.size === 0) return;
32
- const now = Date.now();
33
- for (const [id, exp] of revokedSessions) {
34
- if (exp <= now) revokedSessions.delete(id);
35
- }
36
- }, 300000).unref();
37
-
38
- /**
39
- * Converts duration strings like "24h", "7d", "30m", "60s" to seconds.
40
- * @param {string|number} duration
41
- * @returns {number} Seconds.
42
- */
43
- function parseDuration(duration) {
44
- if (typeof duration === "number") return duration;
45
- const match = String(duration).match(/^(\d+)([smhd])$/);
46
- if (!match) return 86400;
47
- const val = parseInt(match[1], 10);
48
- const unit = match[2];
49
- if (unit === "s") return val;
50
- if (unit === "m") return val * 60;
51
- if (unit === "h") return val * 3600;
52
- if (unit === "d") return val * 86400;
53
- return 86400;
54
- }
55
-
56
- /**
57
- * Auth class for JWT generation and verification using native node:crypto.
58
- * Tokens are signed with HMAC-HS256 and payload encrypted with AES-256-GCM.
59
- */
60
- class Auth {
61
- /**
62
- * Encrypts a payload using AES-256-GCM.
63
- * @param {Object} payload - The data to encrypt.
64
- * @param {string} [secret] - The secret key for encryption.
65
- * @returns {string} Encrypted string in format iv:tag:encrypted.
66
- */
67
- static encrypt(payload, secret = process.env.JWT_SECRET || jwtSecret) {
68
- const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
69
- if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
70
- const iv = randomBytes(12);
71
- const key = getAesKey(resolvedSecret);
72
- const cipher = createCipheriv("aes-256-gcm", key, iv);
73
- let encrypted = cipher.update(JSON.stringify(payload), "utf8", "hex");
74
- encrypted += cipher.final("hex");
75
- const tag = cipher.getAuthTag().toString("hex");
76
- return `${iv.toString("hex")}:${tag}:${encrypted}`;
77
- }
78
-
79
- /**
80
- * Decrypts a payload using AES-256-GCM.
81
- * @param {string} data - Encrypted string in format iv:tag:encrypted.
82
- * @param {string} [secret] - The secret key for decryption.
83
- * @returns {Object|null} Decrypted object or null if decryption failed.
84
- */
85
- static decrypt(data, secret = process.env.JWT_SECRET || jwtSecret) {
86
- const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
87
- if (!resolvedSecret) return null;
88
- try {
89
- const [ivHex, tagHex, encryptedHex] = data.split(":");
90
- if (!ivHex || !tagHex || !encryptedHex) return null;
91
-
92
- const iv = Buffer.from(ivHex, "hex");
93
- const tag = Buffer.from(tagHex, "hex");
94
- const key = getAesKey(resolvedSecret);
95
- const decipher = createDecipheriv("aes-256-gcm", key, iv);
96
- decipher.setAuthTag(tag);
97
-
98
- let decrypted = decipher.update(encryptedHex, "hex", "utf8");
99
- decrypted += decipher.final("utf8");
100
- return JSON.parse(decrypted);
101
- } catch {
102
- return null;
103
- }
104
- }
105
-
106
- /**
107
- * Generates a signed JWT token with an AES-256-GCM encrypted payload.
108
- * The token is signed with HMAC-HS256 using native node:crypto.
109
- * @param {Object} payload - The data to store in the token.
110
- * @param {string} [secret] - The secret key (defaults to JWT_SECRET env var).
111
- * @param {string|number} [expiresIn="24h"] - Expiration duration string or seconds.
112
- * @returns {string} Signed JWT token string.
113
- */
114
- static generateToken(payload, secret = process.env.JWT_SECRET || jwtSecret, expiresIn = "24h") {
115
- const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
116
- if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
117
-
118
- const encrypted = this.encrypt(payload, resolvedSecret);
119
- const now = Math.floor(Date.now() / 1000);
120
- const ttl = parseDuration(expiresIn);
121
-
122
- const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url");
123
- const body = Buffer.from(JSON.stringify({ data: encrypted, iat: now, exp: now + ttl })).toString("base64url");
124
-
125
- const signature = createHmac("sha256", resolvedSecret)
126
- .update(`${header}.${body}`)
127
- .digest("base64url");
128
-
129
- return `${header}.${body}.${signature}`;
130
- }
131
-
132
- /**
133
- * Verifies a JWT token signature and decrypts its payload.
134
- * @param {string} token - The token to verify.
135
- * @param {string} [secret] - The secret key (defaults to JWT_SECRET env var).
136
- * @returns {Object|null} Decrypted payload or null if invalid or expired.
137
- */
138
- static verifyToken(token, secret = process.env.JWT_SECRET || jwtSecret) {
139
- const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
140
- if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
141
- try {
142
- const parts = token.split(".");
143
- if (parts.length !== 3) return null;
144
- const [header, body, signature] = parts;
145
-
146
- const expected = createHmac("sha256", resolvedSecret)
147
- .update(`${header}.${body}`)
148
- .digest("base64url");
149
-
150
- const sigBuf = Buffer.from(signature);
151
- const expBuf = Buffer.from(expected);
152
- if (sigBuf.length !== expBuf.length) return null;
153
- if (!timingSafeEqual(sigBuf, expBuf)) return null;
154
-
155
- const decoded = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
156
- if (!decoded || !decoded.data) return null;
157
- if (Math.floor(Date.now() / 1000) > decoded.exp) return null;
158
-
159
- return this.decrypt(decoded.data, resolvedSecret);
160
- } catch {
161
- return null;
162
- }
163
- }
164
-
165
- /**
166
- * Middleware to protect routes. Reads token from cookie or Authorization header.
167
- * Clears invalid or expired authentication cookies to prevent replay attempts.
168
- * Falls back to JWT payload when Redis is temporarily unreachable.
169
- * @param {Object} [options={}] - Protection options.
170
- * @param {string|null} [options.redirect=null] - URL to redirect on failure (for web routes).
171
- * @param {string} [options.key="user"] - Property name to attach decoded payload to req.
172
- * @param {string} [options.cookieKey="auth"] - Cookie name to read the token from.
173
- * @returns {Function} Express middleware.
174
- */
175
- static protect(options = {}) {
176
- const { redirect = null, key = "user", cookieKey = "auth" } = options;
177
-
178
- return async (req, res, next) => {
179
- const cookieToken = req.cookies?.[cookieKey];
180
- const headerToken = req.headers.authorization?.split(" ")[1];
181
- const token = cookieToken || headerToken;
182
-
183
- const expectsJson =
184
- Boolean(req.xhr) ||
185
- Boolean(req.headers?.accept?.includes("application/json")) ||
186
- Boolean(req.path?.startsWith("/api"));
187
-
188
- if (!token) {
189
- if (redirect && !expectsJson) return res.redirect(redirect);
190
- return expectsJson
191
- ? res.status(401).json({ message: "Unauthorized" })
192
- : res.status(401).send();
193
- }
194
-
195
- const secret = options.secret || process.env.JWT_SECRET || jwtSecret;
196
- const decoded = this.verifyToken(token, secret);
197
- if (!decoded) {
198
- if (cookieToken && typeof res.clearCookie === "function") {
199
- res.clearCookie(cookieKey, { path: "/" });
200
- }
201
- if (redirect && !expectsJson) return res.redirect(redirect);
202
- return expectsJson
203
- ? res.status(401).json({ message: "Unauthorized" })
204
- : res.status(401).send();
205
- }
206
-
207
- if (decoded._sessionId && revokedSessions.has(decoded._sessionId)) {
208
- const expiry = revokedSessions.get(decoded._sessionId);
209
- if (Date.now() <= expiry) {
210
- if (cookieToken && typeof res.clearCookie === "function") {
211
- res.clearCookie(cookieKey, { path: "/" });
212
- }
213
- if (redirect && !expectsJson) return res.redirect(redirect);
214
- return expectsJson
215
- ? res.status(401).json({ message: "Unauthorized" })
216
- : res.status(401).send();
217
- }
218
- revokedSessions.delete(decoded._sessionId);
219
- }
220
-
221
- const redisClient = getRedisClient();
222
- if (redisClient && decoded._sessionId) {
223
- try {
224
- const sessionData = await redisClient.get(`session:${decoded._sessionId}`);
225
- if (!sessionData) {
226
- if (cookieToken && typeof res.clearCookie === "function") {
227
- res.clearCookie(cookieKey, { path: "/" });
228
- }
229
- if (redirect && !expectsJson) return res.redirect(redirect);
230
- return expectsJson
231
- ? res.status(401).json({ message: "Unauthorized" })
232
- : res.status(401).send();
233
- }
234
- req[key] = JSON.parse(sessionData);
235
- return next();
236
- } catch {
237
- req[key] = decoded;
238
- return next();
239
- }
240
- }
241
-
242
- req[key] = decoded;
243
- next();
244
- };
245
- }
246
-
247
- /**
248
- * Logs in a user by signing a JWT, storing the session in Redis if available,
249
- * and setting an HttpOnly authentication cookie.
250
- * @param {import('express').Response} res - The Express response object.
251
- * @param {Object} data - The data to store in the token and session.
252
- * @param {string} [key="auth"] - Cookie name to set.
253
- * @param {Object} [options={}] - Additional options.
254
- * @param {string|number} [options.expiresIn="24h"] - Token and session TTL.
255
- * @param {import('express').CookieOptions} [options.cookie] - Express cookie options override.
256
- * @returns {Promise<string>} The generated token string.
257
- */
258
- static async login(res, data, key = "auth", options = {}) {
259
- const { expiresIn = "24h", cookie = {} } = options;
260
- const sessionId = randomUUID();
261
- const tokenPayload = { ...data, _sessionId: sessionId };
262
- const secret = options.secret || process.env.JWT_SECRET || jwtSecret;
263
- const token = this.generateToken(tokenPayload, secret, expiresIn);
264
- const ttl = parseDuration(expiresIn);
265
-
266
- const defaultCookieOptions = {
267
- maxAge: ttl * 1000,
268
- httpOnly: true,
269
- secure: production,
270
- sameSite: "lax",
271
- path: "/",
272
- };
273
-
274
- const redisClient = getRedisClient();
275
- if (redisClient) {
276
- try {
277
- await redisClient.set(`session:${sessionId}`, JSON.stringify(data), { EX: ttl });
278
- } catch (err) {
279
- console.error("[AUTH] Failed to store session in Redis:", err.message);
280
- }
281
- }
282
-
283
- res.cookie(key, token, { ...defaultCookieOptions, ...cookie });
284
- return token;
285
- }
286
-
287
- /**
288
- * Logs out a user by clearing the authentication cookie and removing active sessions.
289
- * Automatically inspects res.req when req parameter is omitted.
290
- * @param {import('express').Response} res - The Express response object.
291
- * @param {string} [key="auth"] - Cookie name to clear.
292
- * @param {import('express').CookieOptions} [options={}] - Cookie options for clearing.
293
- * @param {import('express').Request|null} [req=null] - Request object used to extract and revoke session.
294
- * @returns {Promise<boolean>}
295
- */
296
- static async logout(res, key = "auth", options = {}, req = null) {
297
- const request = req || res?.req;
298
- if (request) {
299
- const token = request.cookies?.[key] || request.headers?.authorization?.split(" ")[1];
300
- if (token) {
301
- const secret = options.secret || process.env.JWT_SECRET || jwtSecret;
302
- const decoded = this.verifyToken(token, secret);
303
- if (decoded?._sessionId) {
304
- const redisClient = getRedisClient();
305
- if (redisClient) {
306
- try {
307
- await redisClient.del(`session:${decoded._sessionId}`);
308
- } catch (err) {
309
- console.error("[AUTH] Failed to delete session from Redis:", err.message);
310
- }
311
- }
312
- const ttlMs = (decoded.exp ? decoded.exp * 1000 : Date.now() + 86400000) - Date.now();
313
- if (ttlMs > 0) {
314
- revokedSessions.set(decoded._sessionId, Date.now() + ttlMs);
315
- }
316
- }
317
- }
318
- }
319
-
320
- res.clearCookie(key, { path: "/", ...options });
321
- return true;
322
- }
323
- }
324
-
325
- export { Auth };
326
- export default Auth;
1
+ import { createHmac, timingSafeEqual, createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import Config from "./config.js";
3
+ import { getRedisClient } from "./cache.js";
4
+
5
+ const propsConfig = Config.props();
6
+ const jwtSecret = propsConfig.jwtSecret;
7
+ const production = !propsConfig.debug;
8
+
9
+ if (production && (!jwtSecret || jwtSecret === "default" || jwtSecret.length < 32)) {
10
+ console.error("[AUTH FATAL] JWT_SECRET must be defined with at least 32 characters in production mode.");
11
+ }
12
+
13
+ /**
14
+ * Resolves or derives the 256-bit AES encryption key from the provided secret.
15
+ * @param {string} secret
16
+ * @returns {Buffer}
17
+ */
18
+ function getAesKey(secret) {
19
+ const resolved = secret || process.env.JWT_SECRET || propsConfig.jwtSecret || "default";
20
+ return createHash("sha256").update(resolved).digest();
21
+ }
22
+
23
+ /**
24
+ * In-memory revocation map for single-instance or non-Redis environments.
25
+ * Maps sessionId to expiry timestamp in milliseconds.
26
+ * @type {Map<string, number>}
27
+ */
28
+ const revokedSessions = new Map();
29
+
30
+ setInterval(() => {
31
+ if (revokedSessions.size === 0) return;
32
+ const now = Date.now();
33
+ for (const [id, exp] of revokedSessions) {
34
+ if (exp <= now) revokedSessions.delete(id);
35
+ }
36
+ }, 300000).unref();
37
+
38
+ /**
39
+ * Converts duration strings like "24h", "7d", "30m", "60s" to seconds.
40
+ * @param {string|number} duration
41
+ * @returns {number} Seconds.
42
+ */
43
+ function parseDuration(duration) {
44
+ if (typeof duration === "number") return duration;
45
+ const match = String(duration).match(/^(\d+)([smhd])$/);
46
+ if (!match) return 86400;
47
+ const val = parseInt(match[1], 10);
48
+ const unit = match[2];
49
+ if (unit === "s") return val;
50
+ if (unit === "m") return val * 60;
51
+ if (unit === "h") return val * 3600;
52
+ if (unit === "d") return val * 86400;
53
+ return 86400;
54
+ }
55
+
56
+ /**
57
+ * Auth class for JWT generation and verification using native node:crypto.
58
+ * Tokens are signed with HMAC-HS256 and payload encrypted with AES-256-GCM.
59
+ */
60
+ class Auth {
61
+ /**
62
+ * Encrypts a payload using AES-256-GCM.
63
+ * @param {Object} payload - The data to encrypt.
64
+ * @param {string} [secret] - The secret key for encryption.
65
+ * @returns {string} Encrypted string in format iv:tag:encrypted.
66
+ */
67
+ static encrypt(payload, secret = process.env.JWT_SECRET || jwtSecret) {
68
+ const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
69
+ if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
70
+ const iv = randomBytes(12);
71
+ const key = getAesKey(resolvedSecret);
72
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
73
+ let encrypted = cipher.update(JSON.stringify(payload), "utf8", "hex");
74
+ encrypted += cipher.final("hex");
75
+ const tag = cipher.getAuthTag().toString("hex");
76
+ return `${iv.toString("hex")}:${tag}:${encrypted}`;
77
+ }
78
+
79
+ /**
80
+ * Decrypts a payload using AES-256-GCM.
81
+ * @param {string} data - Encrypted string in format iv:tag:encrypted.
82
+ * @param {string} [secret] - The secret key for decryption.
83
+ * @returns {Object|null} Decrypted object or null if decryption failed.
84
+ */
85
+ static decrypt(data, secret = process.env.JWT_SECRET || jwtSecret) {
86
+ const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
87
+ if (!resolvedSecret) return null;
88
+ try {
89
+ const [ivHex, tagHex, encryptedHex] = data.split(":");
90
+ if (!ivHex || !tagHex || !encryptedHex) return null;
91
+
92
+ const iv = Buffer.from(ivHex, "hex");
93
+ const tag = Buffer.from(tagHex, "hex");
94
+ const key = getAesKey(resolvedSecret);
95
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
96
+ decipher.setAuthTag(tag);
97
+
98
+ let decrypted = decipher.update(encryptedHex, "hex", "utf8");
99
+ decrypted += decipher.final("utf8");
100
+ return JSON.parse(decrypted);
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Generates a signed JWT token with an AES-256-GCM encrypted payload.
108
+ * The token is signed with HMAC-HS256 using native node:crypto.
109
+ * @param {Object} payload - The data to store in the token.
110
+ * @param {string} [secret] - The secret key (defaults to JWT_SECRET env var).
111
+ * @param {string|number} [expiresIn="24h"] - Expiration duration string or seconds.
112
+ * @returns {string} Signed JWT token string.
113
+ */
114
+ static generateToken(payload, secret = process.env.JWT_SECRET || jwtSecret, expiresIn = "24h") {
115
+ const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
116
+ if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
117
+
118
+ const encrypted = this.encrypt(payload, resolvedSecret);
119
+ const now = Math.floor(Date.now() / 1000);
120
+ const ttl = parseDuration(expiresIn);
121
+
122
+ const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url");
123
+ const body = Buffer.from(JSON.stringify({ data: encrypted, iat: now, exp: now + ttl })).toString("base64url");
124
+
125
+ const signature = createHmac("sha256", resolvedSecret)
126
+ .update(`${header}.${body}`)
127
+ .digest("base64url");
128
+
129
+ return `${header}.${body}.${signature}`;
130
+ }
131
+
132
+ /**
133
+ * Verifies a JWT token signature and decrypts its payload.
134
+ * @param {string} token - The token to verify.
135
+ * @param {string} [secret] - The secret key (defaults to JWT_SECRET env var).
136
+ * @returns {Object|null} Decrypted payload or null if invalid or expired.
137
+ */
138
+ static verifyToken(token, secret = process.env.JWT_SECRET || jwtSecret) {
139
+ const resolvedSecret = secret || process.env.JWT_SECRET || jwtSecret;
140
+ if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
141
+ try {
142
+ const parts = token.split(".");
143
+ if (parts.length !== 3) return null;
144
+ const [header, body, signature] = parts;
145
+
146
+ const expected = createHmac("sha256", resolvedSecret)
147
+ .update(`${header}.${body}`)
148
+ .digest("base64url");
149
+
150
+ const sigBuf = Buffer.from(signature);
151
+ const expBuf = Buffer.from(expected);
152
+ if (sigBuf.length !== expBuf.length) return null;
153
+ if (!timingSafeEqual(sigBuf, expBuf)) return null;
154
+
155
+ const decoded = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
156
+ if (!decoded || !decoded.data) return null;
157
+ if (Math.floor(Date.now() / 1000) > decoded.exp) return null;
158
+
159
+ return this.decrypt(decoded.data, resolvedSecret);
160
+ } catch {
161
+ return null;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Middleware to protect routes. Reads token from cookie or Authorization header.
167
+ * Clears invalid or expired authentication cookies to prevent replay attempts.
168
+ * Falls back to JWT payload when Redis is temporarily unreachable.
169
+ * @param {Object} [options={}] - Protection options.
170
+ * @param {string|null} [options.redirect=null] - URL to redirect on failure (for web routes).
171
+ * @param {string} [options.key="user"] - Property name to attach decoded payload to req.
172
+ * @param {string} [options.cookieKey="auth"] - Cookie name to read the token from.
173
+ * @returns {Function} Express middleware.
174
+ */
175
+ static protect(options = {}) {
176
+ const { redirect = null, key = "user", cookieKey = "auth" } = options;
177
+
178
+ return async (req, res, next) => {
179
+ const cookieToken = req.cookies?.[cookieKey];
180
+ const headerToken = req.headers.authorization?.split(" ")[1];
181
+ const token = cookieToken || headerToken;
182
+
183
+ const expectsJson =
184
+ Boolean(req.xhr) ||
185
+ Boolean(req.headers?.accept?.includes("application/json")) ||
186
+ Boolean(req.path?.startsWith("/api"));
187
+
188
+ if (!token) {
189
+ if (redirect && !expectsJson) return res.redirect(redirect);
190
+ return expectsJson
191
+ ? res.status(401).json({ message: "Unauthorized" })
192
+ : res.status(401).send();
193
+ }
194
+
195
+ const secret = options.secret || process.env.JWT_SECRET || jwtSecret;
196
+ const decoded = this.verifyToken(token, secret);
197
+ if (!decoded) {
198
+ if (cookieToken && typeof res.clearCookie === "function") {
199
+ res.clearCookie(cookieKey, { path: "/" });
200
+ }
201
+ if (redirect && !expectsJson) return res.redirect(redirect);
202
+ return expectsJson
203
+ ? res.status(401).json({ message: "Unauthorized" })
204
+ : res.status(401).send();
205
+ }
206
+
207
+ if (decoded._sessionId && revokedSessions.has(decoded._sessionId)) {
208
+ const expiry = revokedSessions.get(decoded._sessionId);
209
+ if (Date.now() <= expiry) {
210
+ if (cookieToken && typeof res.clearCookie === "function") {
211
+ res.clearCookie(cookieKey, { path: "/" });
212
+ }
213
+ if (redirect && !expectsJson) return res.redirect(redirect);
214
+ return expectsJson
215
+ ? res.status(401).json({ message: "Unauthorized" })
216
+ : res.status(401).send();
217
+ }
218
+ revokedSessions.delete(decoded._sessionId);
219
+ }
220
+
221
+ const redisClient = getRedisClient();
222
+ if (redisClient && decoded._sessionId) {
223
+ try {
224
+ const sessionData = await redisClient.get(`session:${decoded._sessionId}`);
225
+ if (!sessionData) {
226
+ if (cookieToken && typeof res.clearCookie === "function") {
227
+ res.clearCookie(cookieKey, { path: "/" });
228
+ }
229
+ if (redirect && !expectsJson) return res.redirect(redirect);
230
+ return expectsJson
231
+ ? res.status(401).json({ message: "Unauthorized" })
232
+ : res.status(401).send();
233
+ }
234
+ req[key] = JSON.parse(sessionData);
235
+ return next();
236
+ } catch {
237
+ req[key] = decoded;
238
+ return next();
239
+ }
240
+ }
241
+
242
+ req[key] = decoded;
243
+ next();
244
+ };
245
+ }
246
+
247
+ /**
248
+ * Logs in a user by signing a JWT, storing the session in Redis if available,
249
+ * and setting an HttpOnly authentication cookie.
250
+ * @param {import('express').Response} res - The Express response object.
251
+ * @param {Object} data - The data to store in the token and session.
252
+ * @param {string} [key="auth"] - Cookie name to set.
253
+ * @param {Object} [options={}] - Additional options.
254
+ * @param {string|number} [options.expiresIn="24h"] - Token and session TTL.
255
+ * @param {import('express').CookieOptions} [options.cookie] - Express cookie options override.
256
+ * @returns {Promise<string>} The generated token string.
257
+ */
258
+ static async login(res, data, key = "auth", options = {}) {
259
+ const { expiresIn = "24h", cookie = {} } = options;
260
+ const sessionId = randomUUID();
261
+ const tokenPayload = { ...data, _sessionId: sessionId };
262
+ const secret = options.secret || process.env.JWT_SECRET || jwtSecret;
263
+ const token = this.generateToken(tokenPayload, secret, expiresIn);
264
+ const ttl = parseDuration(expiresIn);
265
+
266
+ const defaultCookieOptions = {
267
+ maxAge: ttl * 1000,
268
+ httpOnly: true,
269
+ secure: production,
270
+ sameSite: "lax",
271
+ path: "/",
272
+ };
273
+
274
+ const redisClient = getRedisClient();
275
+ if (redisClient) {
276
+ try {
277
+ await redisClient.set(`session:${sessionId}`, JSON.stringify(data), { EX: ttl });
278
+ } catch (err) {
279
+ console.error("[AUTH] Failed to store session in Redis:", err.message);
280
+ }
281
+ }
282
+
283
+ res.cookie(key, token, { ...defaultCookieOptions, ...cookie });
284
+ return token;
285
+ }
286
+
287
+ /**
288
+ * Logs out a user by clearing the authentication cookie and removing active sessions.
289
+ * Automatically inspects res.req when req parameter is omitted.
290
+ * @param {import('express').Response} res - The Express response object.
291
+ * @param {string} [key="auth"] - Cookie name to clear.
292
+ * @param {import('express').CookieOptions} [options={}] - Cookie options for clearing.
293
+ * @param {import('express').Request|null} [req=null] - Request object used to extract and revoke session.
294
+ * @returns {Promise<boolean>}
295
+ */
296
+ static async logout(res, key = "auth", options = {}, req = null) {
297
+ const request = req || res?.req;
298
+ if (request) {
299
+ const token = request.cookies?.[key] || request.headers?.authorization?.split(" ")[1];
300
+ if (token) {
301
+ const secret = options.secret || process.env.JWT_SECRET || jwtSecret;
302
+ const decoded = this.verifyToken(token, secret);
303
+ if (decoded?._sessionId) {
304
+ const redisClient = getRedisClient();
305
+ if (redisClient) {
306
+ try {
307
+ await redisClient.del(`session:${decoded._sessionId}`);
308
+ } catch (err) {
309
+ console.error("[AUTH] Failed to delete session from Redis:", err.message);
310
+ }
311
+ }
312
+ const ttlMs = (decoded.exp ? decoded.exp * 1000 : Date.now() + 86400000) - Date.now();
313
+ if (ttlMs > 0) {
314
+ revokedSessions.set(decoded._sessionId, Date.now() + ttlMs);
315
+ }
316
+ }
317
+ }
318
+ }
319
+
320
+ res.clearCookie(key, { path: "/", ...options });
321
+ return true;
322
+ }
323
+ }
324
+
325
+ export { Auth };
326
+ export default Auth;