@seip/bluebird-js 0.1.7 → 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.
- package/AGENTS.md +726 -620
- package/README.md +615 -607
- package/app/models/user.js +19 -0
- package/app/resources/html/home.html +137 -0
- package/app/resources/html/layouts/main.html +54 -0
- package/app/resources/html/notFound.html +14 -0
- package/app/resources/html/terms.html +46 -0
- package/app/resources/index.html +27 -0
- package/app/resources/layouts/AppLayout.jsx +89 -0
- package/app/resources/main.jsx +18 -0
- package/app/resources/pages/Dashboard.jsx +98 -0
- package/app/resources/pages/Home.jsx +140 -0
- package/app/resources/pages/Login.jsx +35 -0
- package/app/resources/pages/NotFound.jsx +16 -0
- package/app/resources/pages/Register.jsx +55 -0
- package/app/resources/routes.jsx +54 -0
- package/app/resources/spa.js +67 -0
- package/app/resources/styles.css +9 -0
- package/app/routes/api.js +85 -50
- package/app/routes/auth.js +209 -0
- package/app/routes/web.js +59 -47
- package/core/ai.js +30 -10
- package/core/app.d.ts +2 -18
- package/core/app.js +987 -801
- package/core/auth.d.ts +2 -13
- package/core/auth.js +444 -326
- package/core/cli/build.js +37 -0
- package/core/cli/dev.js +155 -0
- package/core/cli/doctor.js +37 -2
- package/core/cli/export.js +191 -0
- package/core/cli/init.js +91 -322
- package/core/cli/nginx.js +1 -1
- package/core/cli/templates.js +139 -0
- package/core/cli/view.js +98 -161
- package/core/config.js +44 -2
- package/core/csrf.js +156 -24
- package/core/database.js +1184 -1131
- package/core/debug.js +1 -1
- package/core/html.js +8 -1
- package/core/index.d.ts +126 -310
- package/core/paths.js +55 -0
- package/core/ratelimit.js +10 -1
- package/core/react/client/api.js +237 -0
- package/core/react/client/auth.js +236 -0
- package/core/react/client/components.js +1321 -0
- package/core/react/client/i18n.js +338 -0
- package/core/react/client/index.d.ts +249 -0
- package/core/react/client/index.js +49 -0
- package/core/react/client/router.js +26 -0
- package/core/react/client/theme.css +512 -0
- package/core/render-cache.js +250 -212
- package/core/render.d.ts +25 -21
- package/core/render.js +738 -736
- package/core/router.d.ts +2 -3
- package/core/router.js +171 -171
- package/core/seo.js +10 -0
- package/core/spa.js +599 -0
- package/core/view-loader.js +155 -613
- package/core/vite-plugin.d.ts +18 -0
- package/core/vite-plugin.js +162 -0
- package/core/vite.js +250 -145
- package/index.js +22 -18
- package/jsconfig.json +5 -3
- package/package.json +114 -92
- package/production.md +8 -3
- package/public/js/bluebird.js +1160 -0
- package/templates/_auth/app/database.js +19 -0
- package/templates/_auth/app/models/user.js +22 -0
- package/templates/_auth/app/routes/auth-router.js +304 -0
- package/templates/_base/app/resources/html/layouts/main.html +55 -0
- package/templates/_base/app/resources/html/notFound.html +14 -0
- package/templates/_base/app/resources/index.html +27 -0
- package/templates/_base/app/resources/styles.css +9 -0
- package/templates/api/app/models/note.js +18 -0
- package/templates/api/app/routes/api.js +82 -0
- package/templates/api/app/routes/auth.js +11 -0
- package/templates/api/index.js +19 -0
- package/templates/api/template.json +13 -0
- package/templates/auth/app/mail.js +11 -0
- package/templates/auth/app/models/password_reset.js +18 -0
- package/templates/auth/app/resources/html/home.html +21 -0
- package/templates/auth/app/resources/html/partials/nav.html +2 -0
- package/templates/auth/app/resources/layouts/AppLayout.jsx +60 -0
- package/templates/auth/app/resources/main.jsx +18 -0
- package/templates/auth/app/resources/pages/Dashboard.jsx +51 -0
- package/templates/auth/app/resources/pages/ForgotPassword.jsx +34 -0
- package/templates/auth/app/resources/pages/Login.jsx +36 -0
- package/templates/auth/app/resources/pages/NotFound.jsx +16 -0
- package/templates/auth/app/resources/pages/Profile.jsx +99 -0
- package/templates/auth/app/resources/pages/Register.jsx +50 -0
- package/templates/auth/app/resources/pages/ResetPassword.jsx +50 -0
- package/templates/auth/app/resources/routes.jsx +54 -0
- package/templates/auth/app/resources/spa.js +29 -0
- package/templates/auth/app/routes/api.js +17 -0
- package/templates/auth/app/routes/auth.js +13 -0
- package/templates/auth/app/routes/web.js +21 -0
- package/templates/auth/index.js +19 -0
- package/templates/auth/template.json +15 -0
- package/templates/blank/app/models/.gitkeep +0 -0
- package/templates/blank/app/resources/html/home.html +27 -0
- package/templates/blank/app/resources/html/partials/nav.html +1 -0
- package/templates/blank/app/resources/main.jsx +16 -0
- package/templates/blank/app/resources/pages/Home.jsx +42 -0
- package/templates/blank/app/resources/pages/NotFound.jsx +27 -0
- package/templates/blank/app/resources/routes.jsx +15 -0
- package/templates/blank/app/resources/spa.js +24 -0
- package/templates/blank/app/routes/api.js +11 -0
- package/templates/blank/app/routes/web.js +21 -0
- package/templates/blank/index.js +13 -0
- package/templates/blank/template.json +12 -0
- package/templates/blog/app/lib/blog.js +149 -0
- package/templates/blog/app/models/post.js +22 -0
- package/templates/blog/app/resources/html/home.html +28 -0
- package/templates/blog/app/resources/html/not-found.html +5 -0
- package/templates/blog/app/resources/html/partials/nav.html +2 -0
- package/templates/blog/app/resources/html/partials/post-card.html +9 -0
- package/templates/blog/app/resources/html/post.html +8 -0
- package/templates/blog/app/resources/layouts/AdminLayout.jsx +54 -0
- package/templates/blog/app/resources/main.jsx +18 -0
- package/templates/blog/app/resources/pages/Login.jsx +31 -0
- package/templates/blog/app/resources/pages/NotFound.jsx +16 -0
- package/templates/blog/app/resources/pages/PostEditor.jsx +51 -0
- package/templates/blog/app/resources/pages/Posts.jsx +83 -0
- package/templates/blog/app/resources/pages/Register.jsx +43 -0
- package/templates/blog/app/resources/routes.jsx +51 -0
- package/templates/blog/app/resources/spa.js +25 -0
- package/templates/blog/app/resources/styles.css +40 -0
- package/templates/blog/app/routes/api.js +77 -0
- package/templates/blog/app/routes/auth.js +10 -0
- package/templates/blog/app/routes/web.js +114 -0
- package/templates/blog/index.js +21 -0
- package/templates/blog/template.json +14 -0
- package/vite.config.js +11 -0
- package/app/views/components/Header.jsx +0 -42
- package/app/views/components/LiveCounter.jsx +0 -67
- package/app/views/layouts/main/view.jsx +0 -201
- package/app/views/legal/terms.html +0 -29
- package/app/views/pages/about.jsx +0 -98
- package/app/views/pages/dashboard.jsx +0 -278
- package/app/views/pages/index.jsx +0 -123
- package/app/views/pages/login.jsx +0 -141
- package/core/actions.d.ts +0 -4
- package/core/actions.js +0 -355
- package/core/jsx.d.ts +0 -38
- package/core/jsx.js +0 -1597
- package/core/vite.d.ts +0 -3
- package/public/js/bluebird-client.js +0 -3265
- 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
|
-
|
|
6
|
-
const
|
|
7
|
-
const production = !propsConfig.debug;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*/
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
.
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
*
|
|
170
|
-
* @param {string
|
|
171
|
-
* @param {string} [
|
|
172
|
-
* @
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
const
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
if (
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
const
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
*
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
if (
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
|
|
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
|
+
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;
|