@seip/bluebird-js 0.1.6 → 0.2.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 (152) hide show
  1. package/.vscode/extensions.json +7 -7
  2. package/.vscode/settings.json +10 -10
  3. package/AGENTS.md +266 -116
  4. package/README.md +258 -245
  5. package/app/models/user.js +19 -0
  6. package/app/resources/html/home.html +137 -0
  7. package/app/resources/html/layouts/main.html +54 -0
  8. package/app/resources/html/notFound.html +14 -0
  9. package/app/resources/html/terms.html +46 -0
  10. package/app/resources/index.html +27 -0
  11. package/app/resources/layouts/AppLayout.jsx +89 -0
  12. package/app/resources/main.jsx +18 -0
  13. package/app/resources/pages/Dashboard.jsx +98 -0
  14. package/app/resources/pages/Home.jsx +140 -0
  15. package/app/resources/pages/Login.jsx +35 -0
  16. package/app/resources/pages/NotFound.jsx +16 -0
  17. package/app/resources/pages/Register.jsx +55 -0
  18. package/app/resources/routes.jsx +54 -0
  19. package/app/resources/spa.js +67 -0
  20. package/app/resources/styles.css +9 -0
  21. package/app/routes/api.js +85 -50
  22. package/app/routes/auth.js +209 -0
  23. package/app/routes/web.js +49 -37
  24. package/core/ai.d.ts +151 -151
  25. package/core/ai.js +1071 -1051
  26. package/core/app.d.ts +2 -18
  27. package/core/app.js +978 -792
  28. package/core/auth.d.ts +2 -13
  29. package/core/auth.js +444 -326
  30. package/core/cli/backup.js +167 -167
  31. package/core/cli/build.js +37 -0
  32. package/core/cli/dev.js +155 -0
  33. package/core/cli/doctor.js +37 -2
  34. package/core/cli/export.js +191 -0
  35. package/core/cli/init.js +101 -332
  36. package/core/cli/nginx.js +1 -1
  37. package/core/cli/templates.js +139 -0
  38. package/core/cli/view.js +73 -136
  39. package/core/config.js +44 -2
  40. package/core/csrf.js +156 -24
  41. package/core/database.js +737 -684
  42. package/core/debug.js +1 -1
  43. package/core/html.js +8 -1
  44. package/core/index.d.ts +1286 -1431
  45. package/core/paths.js +55 -0
  46. package/core/ratelimit.js +10 -1
  47. package/core/react/client/api.js +237 -0
  48. package/core/react/client/auth.js +236 -0
  49. package/core/react/client/components.js +1321 -0
  50. package/core/react/client/i18n.js +338 -0
  51. package/core/react/client/index.d.ts +249 -0
  52. package/core/react/client/index.js +49 -0
  53. package/core/react/client/router.js +26 -0
  54. package/core/react/client/theme.css +512 -0
  55. package/core/render-cache.js +250 -212
  56. package/core/render.d.ts +25 -21
  57. package/core/render.js +613 -603
  58. package/core/router.d.ts +2 -3
  59. package/core/router.js +171 -171
  60. package/core/seo.js +10 -0
  61. package/core/spa.js +599 -0
  62. package/core/view-loader.js +81 -455
  63. package/core/vite-plugin.d.ts +18 -0
  64. package/core/vite-plugin.js +162 -0
  65. package/core/vite.js +250 -145
  66. package/index.js +22 -18
  67. package/jsconfig.json +5 -3
  68. package/package.json +114 -92
  69. package/production.md +8 -3
  70. package/public/js/bluebird.js +1160 -0
  71. package/templates/_auth/app/database.js +19 -0
  72. package/templates/_auth/app/models/user.js +22 -0
  73. package/templates/_auth/app/routes/auth-router.js +304 -0
  74. package/templates/_base/app/resources/html/layouts/main.html +55 -0
  75. package/templates/_base/app/resources/html/notFound.html +14 -0
  76. package/templates/_base/app/resources/index.html +27 -0
  77. package/templates/_base/app/resources/styles.css +9 -0
  78. package/templates/api/app/models/note.js +18 -0
  79. package/templates/api/app/routes/api.js +82 -0
  80. package/templates/api/app/routes/auth.js +11 -0
  81. package/templates/api/index.js +19 -0
  82. package/templates/api/template.json +13 -0
  83. package/templates/auth/app/mail.js +11 -0
  84. package/templates/auth/app/models/password_reset.js +18 -0
  85. package/templates/auth/app/resources/html/home.html +21 -0
  86. package/templates/auth/app/resources/html/partials/nav.html +2 -0
  87. package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
  88. package/templates/auth/app/resources/main.jsx +18 -0
  89. package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
  90. package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
  91. package/templates/auth/app/resources/pages/Login.jsx +36 -0
  92. package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
  93. package/templates/auth/app/resources/pages/Profile.jsx +99 -0
  94. package/templates/auth/app/resources/pages/Register.jsx +50 -0
  95. package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
  96. package/templates/auth/app/resources/routes.jsx +54 -0
  97. package/templates/auth/app/resources/spa.js +29 -0
  98. package/templates/auth/app/routes/api.js +17 -0
  99. package/templates/auth/app/routes/auth.js +13 -0
  100. package/templates/auth/app/routes/web.js +21 -0
  101. package/templates/auth/index.js +19 -0
  102. package/templates/auth/template.json +15 -0
  103. package/templates/blank/app/models/.gitkeep +0 -0
  104. package/templates/blank/app/resources/html/home.html +27 -0
  105. package/templates/blank/app/resources/html/partials/nav.html +1 -0
  106. package/templates/blank/app/resources/main.jsx +16 -0
  107. package/templates/blank/app/resources/pages/Home.jsx +42 -0
  108. package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
  109. package/templates/blank/app/resources/routes.jsx +15 -0
  110. package/templates/blank/app/resources/spa.js +24 -0
  111. package/templates/blank/app/routes/api.js +11 -0
  112. package/templates/blank/app/routes/web.js +21 -0
  113. package/templates/blank/index.js +13 -0
  114. package/templates/blank/template.json +12 -0
  115. package/templates/blog/app/lib/blog.js +149 -0
  116. package/templates/blog/app/models/post.js +22 -0
  117. package/templates/blog/app/resources/html/home.html +28 -0
  118. package/templates/blog/app/resources/html/not-found.html +5 -0
  119. package/templates/blog/app/resources/html/partials/nav.html +2 -0
  120. package/templates/blog/app/resources/html/partials/post-card.html +9 -0
  121. package/templates/blog/app/resources/html/post.html +8 -0
  122. package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
  123. package/templates/blog/app/resources/main.jsx +18 -0
  124. package/templates/blog/app/resources/pages/Login.jsx +31 -0
  125. package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
  126. package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
  127. package/templates/blog/app/resources/pages/Posts.jsx +83 -0
  128. package/templates/blog/app/resources/pages/Register.jsx +43 -0
  129. package/templates/blog/app/resources/routes.jsx +51 -0
  130. package/templates/blog/app/resources/spa.js +25 -0
  131. package/templates/blog/app/resources/styles.css +40 -0
  132. package/templates/blog/app/routes/api.js +77 -0
  133. package/templates/blog/app/routes/auth.js +10 -0
  134. package/templates/blog/app/routes/web.js +114 -0
  135. package/templates/blog/index.js +21 -0
  136. package/templates/blog/template.json +14 -0
  137. package/vite.config.js +11 -0
  138. package/app/views/about.jsx +0 -98
  139. package/app/views/components/Header.jsx +0 -42
  140. package/app/views/components/LiveCounter.jsx +0 -66
  141. package/app/views/dashboard.jsx +0 -300
  142. package/app/views/index.jsx +0 -123
  143. package/app/views/layouts/main/view.jsx +0 -201
  144. package/app/views/legal/terms.html +0 -29
  145. package/app/views/login.jsx +0 -141
  146. package/core/actions.d.ts +0 -4
  147. package/core/actions.js +0 -329
  148. package/core/jsx.d.ts +0 -38
  149. package/core/jsx.js +0 -1432
  150. package/core/vite.d.ts +0 -3
  151. package/public/js/bluebird-client.js +0 -3161
  152. package/public/js/tailwind.js +0 -8
package/core/auth.js CHANGED
@@ -1,326 +1,444 @@
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: Config.isDesktop() ? false : 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
+ import Csrf from "./csrf.js";
5
+
6
+ const propsConfig = Config.props();
7
+ const production = !propsConfig.debug;
8
+
9
+ /**
10
+ * Checks whether a secret is long enough to sign and encrypt tokens in production.
11
+ * @param {string|undefined} secret
12
+ * @returns {boolean}
13
+ */
14
+ function isStrongSecret(secret) {
15
+ return typeof secret === "string" && secret.length >= 32 && secret !== "default";
16
+ }
17
+
18
+ /**
19
+ * Secret used when `JWT_SECRET` is missing or weak. Production gets a random per-process secret (tokens cannot
20
+ * be forged, but sessions end on restart and do not work across PM2 workers); development gets a stable
21
+ * secret derived from the project path so dev restarts keep you signed in.
22
+ */
23
+ const fallbackSecret = production
24
+ ? randomBytes(48).toString("hex")
25
+ : createHash("sha256").update(`bluebird-dev-secret:${Config.appDir()}`).digest("hex");
26
+
27
+ if (production && !isStrongSecret(process.env.JWT_SECRET || propsConfig.jwtSecret)) {
28
+ console.error(
29
+ "[AUTH] JWT_SECRET is missing or shorter than 32 characters. Using a random per-process secret: sessions end on restart and do not work across PM2 workers. Set JWT_SECRET in .env."
30
+ );
31
+ }
32
+
33
+ /**
34
+ * Resolves the signing secret: an explicit secret, then `JWT_SECRET` (must be strong in production), then the fallback.
35
+ * @param {string} [explicit]
36
+ * @returns {string}
37
+ */
38
+ function resolveSecret(explicit) {
39
+ if (explicit) return explicit;
40
+ const configured = process.env.JWT_SECRET || propsConfig.jwtSecret;
41
+ if (configured && (!production || isStrongSecret(configured))) return configured;
42
+ return fallbackSecret;
43
+ }
44
+
45
+ /**
46
+ * Resolves or derives the 256-bit AES encryption key from the provided secret.
47
+ * @param {string} secret
48
+ * @returns {Buffer}
49
+ */
50
+ function getAesKey(secret) {
51
+ const resolved = resolveSecret(secret);
52
+ return createHash("sha256").update(resolved).digest();
53
+ }
54
+
55
+ /**
56
+ * In-memory revocation map for single-instance or non-Redis environments.
57
+ * Maps sessionId to expiry timestamp in milliseconds.
58
+ * @type {Map<string, number>}
59
+ */
60
+ const revokedSessions = new Map();
61
+
62
+ /**
63
+ * Optional hook that reloads the user on every authenticated request (see `Auth.configure`).
64
+ * @type {((payload: Object, req: import('express').Request) => Promise<Object|null>|Object|null)|null}
65
+ */
66
+ let userResolver = null;
67
+
68
+ setInterval(() => {
69
+ if (revokedSessions.size === 0) return;
70
+ const now = Date.now();
71
+ for (const [id, exp] of revokedSessions) {
72
+ if (exp <= now) revokedSessions.delete(id);
73
+ }
74
+ }, 300000).unref();
75
+
76
+ /**
77
+ * Converts duration strings like "24h", "7d", "30m", "60s" to seconds.
78
+ * @param {string|number} duration
79
+ * @returns {number} Seconds.
80
+ */
81
+ function parseDuration(duration) {
82
+ if (typeof duration === "number") return duration;
83
+ const match = String(duration).match(/^(\d+)([smhd])$/);
84
+ if (!match) return 86400;
85
+ const val = parseInt(match[1], 10);
86
+ const unit = match[2];
87
+ if (unit === "s") return val;
88
+ if (unit === "m") return val * 60;
89
+ if (unit === "h") return val * 3600;
90
+ if (unit === "d") return val * 86400;
91
+ return 86400;
92
+ }
93
+
94
+ /**
95
+ * Auth class for JWT generation, AES-256-GCM encryption, session revocation, and role-aware route protection.
96
+ */
97
+ class Auth {
98
+ /**
99
+ * Encrypts a payload using AES-256-GCM.
100
+ * @param {Object} payload - The data to encrypt.
101
+ * @param {string} [secret] - The secret key for encryption.
102
+ * @returns {string} Encrypted string in format iv:tag:encrypted.
103
+ */
104
+ static encrypt(payload, secret) {
105
+ const resolvedSecret = resolveSecret(secret);
106
+ if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
107
+ const iv = randomBytes(12);
108
+ const key = getAesKey(resolvedSecret);
109
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
110
+ let encrypted = cipher.update(JSON.stringify(payload), "utf8", "hex");
111
+ encrypted += cipher.final("hex");
112
+ const tag = cipher.getAuthTag().toString("hex");
113
+ return `${iv.toString("hex")}:${tag}:${encrypted}`;
114
+ }
115
+
116
+ /**
117
+ * Decrypts a payload using AES-256-GCM.
118
+ * @param {string} data - Encrypted string in format iv:tag:encrypted.
119
+ * @param {string} [secret] - The secret key for decryption.
120
+ * @returns {Object|null} Decrypted object or null if decryption failed.
121
+ */
122
+ static decrypt(data, secret) {
123
+ const resolvedSecret = resolveSecret(secret);
124
+ if (!resolvedSecret) return null;
125
+ try {
126
+ const [ivHex, tagHex, encryptedHex] = data.split(":");
127
+ if (!ivHex || !tagHex || !encryptedHex) return null;
128
+
129
+ const iv = Buffer.from(ivHex, "hex");
130
+ const tag = Buffer.from(tagHex, "hex");
131
+ const key = getAesKey(resolvedSecret);
132
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
133
+ decipher.setAuthTag(tag);
134
+
135
+ let decrypted = decipher.update(encryptedHex, "hex", "utf8");
136
+ decrypted += decipher.final("utf8");
137
+ return JSON.parse(decrypted);
138
+ } catch {
139
+ return null;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Generates a signed JWT token with an AES-256-GCM encrypted payload.
145
+ * @param {Object} payload - The data to store in the token.
146
+ * @param {string} [secret] - The secret key.
147
+ * @param {string|number} [expiresIn="24h"] - Expiration duration string or seconds.
148
+ * @returns {string} Signed JWT token string.
149
+ */
150
+ static generateToken(payload, secret, expiresIn = "24h") {
151
+ const resolvedSecret = resolveSecret(secret);
152
+ if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
153
+
154
+ const encrypted = this.encrypt(payload, resolvedSecret);
155
+ const now = Math.floor(Date.now() / 1000);
156
+ const ttl = parseDuration(expiresIn);
157
+
158
+ const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString("base64url");
159
+ const body = Buffer.from(JSON.stringify({ data: encrypted, iat: now, exp: now + ttl })).toString("base64url");
160
+
161
+ const signature = createHmac("sha256", resolvedSecret)
162
+ .update(`${header}.${body}`)
163
+ .digest("base64url");
164
+
165
+ return `${header}.${body}.${signature}`;
166
+ }
167
+
168
+ /**
169
+ * Verifies a JWT token signature and decrypts its payload.
170
+ * @param {string} token - The token to verify.
171
+ * @param {string} [secret] - The secret key.
172
+ * @returns {Object|null} Decrypted payload or null if invalid or expired.
173
+ */
174
+ static verifyToken(token, secret) {
175
+ const resolvedSecret = resolveSecret(secret);
176
+ if (!resolvedSecret) throw new Error("FATAL: JWT_SECRET environment variable is not defined.");
177
+ try {
178
+ const parts = token.split(".");
179
+ if (parts.length !== 3) return null;
180
+ const [header, body, signature] = parts;
181
+
182
+ const expected = createHmac("sha256", resolvedSecret)
183
+ .update(`${header}.${body}`)
184
+ .digest("base64url");
185
+
186
+ const sigBuf = Buffer.from(signature);
187
+ const expBuf = Buffer.from(expected);
188
+ if (sigBuf.length !== expBuf.length) return null;
189
+ if (!timingSafeEqual(sigBuf, expBuf)) return null;
190
+
191
+ const decoded = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
192
+ if (!decoded || !decoded.data) return null;
193
+ if (Math.floor(Date.now() / 1000) > decoded.exp) return null;
194
+
195
+ return this.decrypt(decoded.data, resolvedSecret);
196
+ } catch {
197
+ return null;
198
+ }
199
+ }
200
+
201
+ /**
202
+ * Checks whether an authenticated user satisfies the required role or list of roles.
203
+ * Returns `true` for any authenticated user when `roles` is omitted or empty.
204
+ * @param {Object|null|undefined} user
205
+ * @param {string|string[]|null|undefined} roles
206
+ * @returns {boolean}
207
+ */
208
+ static hasRole(user, roles) {
209
+ if (!user) return false;
210
+ const required = Array.isArray(roles) ? roles.filter(Boolean) : roles ? [roles] : [];
211
+ if (required.length === 0) return true;
212
+ const userRoles = new Set();
213
+ if (typeof user.role === "string" && user.role) userRoles.add(user.role);
214
+ if (Array.isArray(user.roles)) {
215
+ for (const r of user.roles) {
216
+ if (typeof r === "string" && r) userRoles.add(r);
217
+ }
218
+ }
219
+ return required.some((r) => userRoles.has(r));
220
+ }
221
+
222
+ /**
223
+ * Resolves and validates the session payload from the request cookie or Authorization header.
224
+ * @param {import('express').Request} req
225
+ * @param {import('express').Response} res
226
+ * @param {Object} [options={}]
227
+ * @returns {Promise<Object|null>}
228
+ * @private
229
+ */
230
+ static async _resolveUser(req, res, options = {}) {
231
+ const { cookieKey = "auth" } = options;
232
+ const cookieToken = req.cookies?.[cookieKey];
233
+ const headerToken = req.headers.authorization?.split(" ")[1];
234
+ const token = cookieToken || headerToken;
235
+ if (!token) return null;
236
+
237
+ const clearInvalidCookie = () => {
238
+ if (cookieToken && typeof res.clearCookie === "function") {
239
+ res.clearCookie(cookieKey, { path: "/" });
240
+ }
241
+ };
242
+
243
+ const secret = resolveSecret(options.secret);
244
+ const decoded = this.verifyToken(token, secret);
245
+ if (!decoded) {
246
+ clearInvalidCookie();
247
+ return null;
248
+ }
249
+
250
+ if (decoded._sessionId && revokedSessions.has(decoded._sessionId)) {
251
+ const expiry = revokedSessions.get(decoded._sessionId);
252
+ if (Date.now() <= expiry) {
253
+ clearInvalidCookie();
254
+ return null;
255
+ }
256
+ revokedSessions.delete(decoded._sessionId);
257
+ }
258
+
259
+ let session = decoded;
260
+ const redisClient = getRedisClient();
261
+ if (redisClient && decoded._sessionId) {
262
+ try {
263
+ const sessionData = await redisClient.get(`session:${decoded._sessionId}`);
264
+ if (!sessionData) {
265
+ clearInvalidCookie();
266
+ return null;
267
+ }
268
+ session = JSON.parse(sessionData);
269
+ } catch {
270
+ session = decoded;
271
+ }
272
+ }
273
+
274
+ if (!userResolver || options.resolveUser === false) return session;
275
+ try {
276
+ const fresh = await userResolver(decoded, req);
277
+ if (!fresh) {
278
+ clearInvalidCookie();
279
+ return null;
280
+ }
281
+ return { ...fresh, _sessionId: decoded._sessionId, exp: decoded.exp };
282
+ } catch (err) {
283
+ console.error("[AUTH] resolveUser failed, rejecting the session:", err?.message || err);
284
+ return null;
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Configures global session behavior.
290
+ *
291
+ * `resolveUser(payload, req)` runs on every authenticated request (`Auth.protect`, `Auth.optional`) after the token
292
+ * signature is verified. Return the current user (fresh role, name, email) to accept the session, or `null` to reject it:
293
+ * e.g. the account was deleted, or its `session_version` changed after a password change or reset. Errors reject the session.
294
+ * Pass `resolveUser: null` to go back to trusting the token payload.
295
+ * @param {{ resolveUser?: ((payload: Object, req: import('express').Request) => Promise<Object|null>|Object|null)|null }} [options={}]
296
+ */
297
+ static configure(options = {}) {
298
+ if ("resolveUser" in options) {
299
+ userResolver = typeof options.resolveUser === "function" ? options.resolveUser : null;
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Middleware that optionally attaches the authenticated user (or `null` for guests) without rejecting.
305
+ * @param {Object} [options={}]
306
+ * @param {string} [options.key="user"]
307
+ * @param {string} [options.cookieKey="auth"]
308
+ * @param {string} [options.secret]
309
+ * @returns {Function} Express middleware.
310
+ */
311
+ static optional(options = {}) {
312
+ const { key = "user" } = options;
313
+ return async (req, res, next) => {
314
+ req[key] = await this._resolveUser(req, res, options);
315
+ next();
316
+ };
317
+ }
318
+
319
+ /**
320
+ * Middleware to protect routes with optional role enforcement.
321
+ * Reads token from cookie or Authorization header and clears invalid or revoked cookies.
322
+ * @param {Object} [options={}] - Protection options.
323
+ * @param {string|null} [options.redirect=null] - URL to redirect on failure (for web routes).
324
+ * @param {string} [options.key="user"] - Property name to attach decoded payload to req.
325
+ * @param {string} [options.cookieKey="auth"] - Cookie name to read the token from.
326
+ * @param {string|string[]|null} [options.roles=null] - Allowed role(s); when omitted, any authenticated user passes.
327
+ * @param {string} [options.secret] - Optional JWT secret override.
328
+ * @returns {Function} Express middleware.
329
+ */
330
+ static protect(options = {}) {
331
+ const { redirect = null, key = "user", roles = null } = options;
332
+
333
+ return async (req, res, next) => {
334
+ const expectsJson =
335
+ Boolean(req.xhr) ||
336
+ Boolean(req.headers?.accept?.includes("application/json")) ||
337
+ Boolean(req.path?.startsWith("/api")) ||
338
+ Boolean(req.baseUrl?.startsWith("/api"));
339
+
340
+ const user = await this._resolveUser(req, res, options);
341
+ if (!user) {
342
+ if (redirect && !expectsJson) return res.redirect(redirect);
343
+ return expectsJson
344
+ ? res.status(401).json({ status: "error", message: "Unauthorized" })
345
+ : res.status(401).send();
346
+ }
347
+
348
+ if (roles && !this.hasRole(user, roles)) {
349
+ if (redirect && !expectsJson) return res.redirect(redirect);
350
+ return expectsJson
351
+ ? res.status(403).json({ status: "error", message: "Forbidden" })
352
+ : res.status(403).send();
353
+ }
354
+
355
+ req[key] = user;
356
+ next();
357
+ };
358
+ }
359
+
360
+ /**
361
+ * Logs in a user by signing a JWT, storing the session in Redis if available,
362
+ * and setting an HttpOnly authentication cookie.
363
+ * @param {import('express').Response} res - The Express response object.
364
+ * @param {Object} data - The data to store in the token and session.
365
+ * @param {string} [key="auth"] - Cookie name to set.
366
+ * @param {Object} [options={}] - Additional options.
367
+ * @param {string|number} [options.expiresIn="24h"] - Token and session TTL.
368
+ * @param {boolean} [options.rotateCsrf=true] - Issue a fresh CSRF token cookie after login.
369
+ * @param {import('express').CookieOptions} [options.cookie] - Express cookie options override.
370
+ * @param {boolean} [options.setCookie=true] - Set `false` to only return the token (bearer clients such as static exports).
371
+ * @returns {Promise<string>} The generated token string.
372
+ */
373
+ static async login(res, data, key = "auth", options = {}) {
374
+ const { expiresIn = "24h", cookie = {} } = options;
375
+ const sessionId = randomUUID();
376
+ const tokenPayload = { ...data, _sessionId: sessionId };
377
+ const secret = resolveSecret(options.secret);
378
+ const token = this.generateToken(tokenPayload, secret, expiresIn);
379
+ const ttl = parseDuration(expiresIn);
380
+
381
+ const defaultCookieOptions = {
382
+ maxAge: ttl * 1000,
383
+ httpOnly: true,
384
+ secure: Config.isDesktop() ? false : production,
385
+ sameSite: "lax",
386
+ path: "/",
387
+ };
388
+
389
+ const redisClient = getRedisClient();
390
+ if (redisClient) {
391
+ try {
392
+ await redisClient.set(`session:${sessionId}`, JSON.stringify(data), { EX: ttl });
393
+ } catch (err) {
394
+ console.error("[AUTH] Failed to store session in Redis:", err.message);
395
+ }
396
+ }
397
+
398
+ if (options.setCookie === false) return token;
399
+ res.cookie(key, token, { ...defaultCookieOptions, ...cookie });
400
+ if (options.rotateCsrf !== false) Csrf.rotate(res);
401
+ return token;
402
+ }
403
+
404
+ /**
405
+ * Logs out a user by clearing the authentication cookie and revoking active sessions.
406
+ * @param {import('express').Response} res - The Express response object.
407
+ * @param {string} [key="auth"] - Cookie name to clear.
408
+ * @param {import('express').CookieOptions} [options={}] - Cookie options for clearing.
409
+ * @param {import('express').Request|null} [req=null] - Request object used to extract and revoke session.
410
+ * @returns {Promise<boolean>}
411
+ */
412
+ static async logout(res, key = "auth", options = {}, req = null) {
413
+ const request = req || res?.req;
414
+ if (request) {
415
+ const token = request.cookies?.[key] || request.headers?.authorization?.split(" ")[1];
416
+ if (token) {
417
+ const secret = resolveSecret(options.secret);
418
+ const decoded = this.verifyToken(token, secret);
419
+ if (decoded?._sessionId) {
420
+ const redisClient = getRedisClient();
421
+ if (redisClient) {
422
+ try {
423
+ await redisClient.del(`session:${decoded._sessionId}`);
424
+ } catch (err) {
425
+ console.error("[AUTH] Failed to delete session from Redis:", err.message);
426
+ }
427
+ }
428
+ const ttlMs = (decoded.exp ? decoded.exp * 1000 : Date.now() + 86400000) - Date.now();
429
+ if (ttlMs > 0) {
430
+ revokedSessions.set(decoded._sessionId, Date.now() + ttlMs);
431
+ }
432
+ }
433
+ }
434
+ }
435
+
436
+ const { rotateCsrf, secret: _secret, ...clearOptions } = options || {};
437
+ res.clearCookie(key, { path: "/", ...clearOptions });
438
+ if (rotateCsrf !== false) Csrf.rotate(res);
439
+ return true;
440
+ }
441
+ }
442
+
443
+ export { Auth };
444
+ export default Auth;