@tylix/auth 0.2.1 → 0.4.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/package.json +9 -5
- package/src/generators/templates/auth-controller-ts.tyx +74 -29
- package/src/generators/templates/auth-controller.tyx +72 -29
- package/src/generators/templates/auth-validator-ts.tyx +35 -2
- package/src/generators/templates/auth-validator.tyx +28 -3
- package/src/generators/templates/user-model-ts.tyx +26 -23
- package/src/generators/templates/user-model.tyx +13 -3
package/package.json
CHANGED
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tylix/auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"tylix",
|
|
7
|
+
"auth"
|
|
8
|
+
],
|
|
5
9
|
"main": "./src/index.js",
|
|
6
10
|
"types": "./src/index.d.ts",
|
|
7
11
|
"scripts": {
|
|
8
12
|
"test": "node --test src/**/*.test.js"
|
|
9
13
|
},
|
|
10
14
|
"dependencies": {
|
|
11
|
-
"@tylix/core": "^0.
|
|
12
|
-
"@tylix/generator": "^0.
|
|
13
|
-
"@tylix/orm": "^0.
|
|
14
|
-
"@tylix/shared": "^0.
|
|
15
|
+
"@tylix/core": "^0.4.0",
|
|
16
|
+
"@tylix/generator": "^0.4.0",
|
|
17
|
+
"@tylix/orm": "^0.4.0",
|
|
18
|
+
"@tylix/shared": "^0.4.0"
|
|
15
19
|
}
|
|
16
20
|
}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* Do not edit this section.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { createRateLimiter } from "@tylix/core";
|
|
11
12
|
import type { TylixRequest, TylixResponse } from "@tylix/core";
|
|
12
13
|
import { User } from "../models/User.js";
|
|
13
14
|
import { RefreshToken } from "../models/RefreshToken.js";
|
|
@@ -33,6 +34,20 @@ import {
|
|
|
33
34
|
|
|
34
35
|
const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 15 * 60;
|
|
35
36
|
|
|
37
|
+
// In-memory limits (per server process).
|
|
38
|
+
const registerLimiter = createRateLimiter({ max: 20, windowMs: 60 * 60 * 1000 });
|
|
39
|
+
const forgotIpLimiter = createRateLimiter({ max: 10, windowMs: 15 * 60 * 1000 });
|
|
40
|
+
const forgotEmailLimiter = createRateLimiter({ max: 5, windowMs: 60 * 60 * 1000 });
|
|
41
|
+
|
|
42
|
+
// Emails are case-insensitive: always compare and store them trimmed and lowercased.
|
|
43
|
+
function normalizeEmail(value: unknown): string {
|
|
44
|
+
return String(value ?? "").trim().toLowerCase();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function clientIp(req: TylixRequest): string {
|
|
48
|
+
return (req as unknown as { ip?: string }).ip ?? "unknown";
|
|
49
|
+
}
|
|
50
|
+
|
|
36
51
|
interface AuthControllerOptions {
|
|
37
52
|
secret: string;
|
|
38
53
|
tokenExpiresInSeconds?: number;
|
|
@@ -51,27 +66,40 @@ export class AuthController {
|
|
|
51
66
|
}
|
|
52
67
|
|
|
53
68
|
async register(req: TylixRequest, res: TylixResponse) {
|
|
69
|
+
const limit = registerLimiter(clientIp(req));
|
|
70
|
+
if (!limit.allowed) {
|
|
71
|
+
return res.status(429).json({
|
|
72
|
+
error: `Too many sign-ups from this address. Try again in ${limit.retryAfterSeconds} seconds.`,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
54
76
|
const result = validateRegister(req.body);
|
|
55
77
|
if (!result.valid) {
|
|
56
78
|
return res.status(422).json({ errors: result.errors });
|
|
57
79
|
}
|
|
58
80
|
|
|
59
|
-
const
|
|
60
|
-
if (
|
|
81
|
+
const email = normalizeEmail(req.body.email);
|
|
82
|
+
if (await User.findByEmail(email)) {
|
|
61
83
|
return res.status(422).json({ errors: { email: ["This email is already registered."] } });
|
|
62
84
|
}
|
|
63
85
|
|
|
64
|
-
|
|
86
|
+
// Only these fields are accepted from the request. Passing req.body
|
|
87
|
+
// straight through would let a client set email_verified_at.
|
|
88
|
+
const user = await User.create({
|
|
89
|
+
name: req.body.name as string,
|
|
90
|
+
email,
|
|
91
|
+
password: req.body.password as string,
|
|
92
|
+
});
|
|
65
93
|
if (!user) {
|
|
66
94
|
return res.status(500).json({ error: "Failed to create user." });
|
|
67
95
|
}
|
|
68
96
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
);
|
|
74
|
-
await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
97
|
+
const verificationToken = signToken(
|
|
98
|
+
{ userId: user.id, purpose: "email-verify" },
|
|
99
|
+
this.secret,
|
|
100
|
+
{ expiresInSeconds: 60 * 60 * 24 },
|
|
101
|
+
);
|
|
102
|
+
await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
75
103
|
|
|
76
104
|
return res.status(201).json({
|
|
77
105
|
user: User.toSafeObject(user),
|
|
@@ -85,25 +113,24 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
85
113
|
return res.status(422).json({ errors: result.errors });
|
|
86
114
|
}
|
|
87
115
|
|
|
88
|
-
const
|
|
89
|
-
const { allowed, retryAfterSeconds } = checkLoginAllowed(
|
|
116
|
+
const email = normalizeEmail(req.body.email);
|
|
117
|
+
const { allowed, retryAfterSeconds } = checkLoginAllowed(email);
|
|
90
118
|
if (!allowed) {
|
|
91
119
|
return res.status(429).json({
|
|
92
120
|
error: `Too many failed attempts. Try again in ${retryAfterSeconds} seconds.`,
|
|
93
121
|
});
|
|
94
122
|
}
|
|
95
123
|
|
|
96
|
-
const
|
|
97
|
-
const user = users.find((u) => u.email === req.body.email);
|
|
124
|
+
const user = await User.findByEmail(email);
|
|
98
125
|
|
|
99
126
|
if (!user) {
|
|
100
|
-
recordFailedLogin(
|
|
127
|
+
recordFailedLogin(email);
|
|
101
128
|
return res.status(401).json({ error: "Invalid email or password." });
|
|
102
129
|
}
|
|
103
130
|
|
|
104
131
|
const passwordMatches = await verifyPassword(req.body.password as string, user.password);
|
|
105
132
|
if (!passwordMatches) {
|
|
106
|
-
recordFailedLogin(
|
|
133
|
+
recordFailedLogin(email);
|
|
107
134
|
return res.status(401).json({ error: "Invalid email or password." });
|
|
108
135
|
}
|
|
109
136
|
|
|
@@ -114,7 +141,7 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
114
141
|
});
|
|
115
142
|
}
|
|
116
143
|
|
|
117
|
-
clearLoginAttempts(
|
|
144
|
+
clearLoginAttempts(email);
|
|
118
145
|
|
|
119
146
|
const accessToken = signToken({ userId: user.id }, this.secret, {
|
|
120
147
|
expiresInSeconds: this.accessTokenTtlSeconds,
|
|
@@ -190,19 +217,36 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
190
217
|
}
|
|
191
218
|
|
|
192
219
|
async forgotPassword(req: TylixRequest, res: TylixResponse) {
|
|
220
|
+
const ipLimit = forgotIpLimiter(clientIp(req));
|
|
221
|
+
if (!ipLimit.allowed) {
|
|
222
|
+
return res.status(429).json({
|
|
223
|
+
error: `Too many requests. Try again in ${ipLimit.retryAfterSeconds} seconds.`,
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
193
227
|
const result = validateForgotPassword(req.body);
|
|
194
228
|
if (!result.valid) {
|
|
195
229
|
return res.status(422).json({ errors: result.errors });
|
|
196
230
|
}
|
|
197
231
|
|
|
198
|
-
const
|
|
199
|
-
const user = users.find((u) => u.email === req.body.email);
|
|
232
|
+
const email = normalizeEmail(req.body.email);
|
|
200
233
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
234
|
+
// Counted for every address, registered or not, so hitting this limit
|
|
235
|
+
// reveals nothing. When it is hit we answer as normal but send nothing.
|
|
236
|
+
const emailLimit = forgotEmailLimiter(email);
|
|
237
|
+
const user = await User.findByEmail(email);
|
|
238
|
+
|
|
239
|
+
if (user && emailLimit.allowed) {
|
|
240
|
+
const { rawToken } = await PasswordReset.issue(user.email);
|
|
241
|
+
// Not awaited: waiting for the mail server only when the address
|
|
242
|
+
// exists would let response time reveal who is registered.
|
|
243
|
+
void sendPasswordResetEmail(user, rawToken, this.mailConfig).catch((err: unknown) => {
|
|
244
|
+
console.error("Password reset email failed:", err);
|
|
245
|
+
});
|
|
246
|
+
}
|
|
205
247
|
|
|
248
|
+
// Always respond the same way whether or not the email exists,
|
|
249
|
+
// so this endpoint can't be used to enumerate registered users.
|
|
206
250
|
return res.json({
|
|
207
251
|
ok: true,
|
|
208
252
|
message: "If that email is registered, a reset link has been sent.",
|
|
@@ -215,15 +259,16 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
215
259
|
return res.status(422).json({ errors: result.errors });
|
|
216
260
|
}
|
|
217
261
|
|
|
218
|
-
|
|
219
|
-
|
|
262
|
+
// An unknown email gets the same answer as a bad token, so this
|
|
263
|
+
// endpoint can't be used to find out who is registered.
|
|
264
|
+
const user = await User.findByEmail(normalizeEmail(req.body.email));
|
|
265
|
+
if (!user) {
|
|
220
266
|
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
221
267
|
}
|
|
222
268
|
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
return res.status(404).json({ error: "User not found." });
|
|
269
|
+
const record = await PasswordReset.findValid(req.body.token as string, user.email);
|
|
270
|
+
if (!record) {
|
|
271
|
+
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
227
272
|
}
|
|
228
273
|
|
|
229
274
|
await User.updatePassword(user.id, req.body.password as string);
|
|
@@ -232,4 +277,4 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
232
277
|
|
|
233
278
|
return res.json({ ok: true, message: "Password updated. Please log in again." });
|
|
234
279
|
}
|
|
235
|
-
}
|
|
280
|
+
}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
* Do not edit this section.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
+
import { createRateLimiter } from "@tylix/core";
|
|
11
12
|
import { User } from "../models/User.js";
|
|
12
13
|
import { RefreshToken } from "../models/RefreshToken.js";
|
|
13
14
|
import { PasswordReset } from "../models/PasswordReset.js";
|
|
@@ -32,6 +33,20 @@ import {
|
|
|
32
33
|
|
|
33
34
|
const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 15 * 60; // 15 minutes, used if config doesn't specify one
|
|
34
35
|
|
|
36
|
+
// In-memory limits (per server process).
|
|
37
|
+
const registerLimiter = createRateLimiter({ max: 20, windowMs: 60 * 60 * 1000 });
|
|
38
|
+
const forgotIpLimiter = createRateLimiter({ max: 10, windowMs: 15 * 60 * 1000 });
|
|
39
|
+
const forgotEmailLimiter = createRateLimiter({ max: 5, windowMs: 60 * 60 * 1000 });
|
|
40
|
+
|
|
41
|
+
// Emails are case-insensitive: always compare and store them trimmed and lowercased.
|
|
42
|
+
function normalizeEmail(value) {
|
|
43
|
+
return String(value ?? "").trim().toLowerCase();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function clientIp(req) {
|
|
47
|
+
return req.ip ?? "unknown";
|
|
48
|
+
}
|
|
49
|
+
|
|
35
50
|
export class AuthController {
|
|
36
51
|
constructor({ secret, tokenExpiresInSeconds, mailConfig } = {}) {
|
|
37
52
|
this.secret = secret;
|
|
@@ -40,24 +55,37 @@ export class AuthController {
|
|
|
40
55
|
}
|
|
41
56
|
|
|
42
57
|
async register(req, res) {
|
|
58
|
+
const limit = registerLimiter(clientIp(req));
|
|
59
|
+
if (!limit.allowed) {
|
|
60
|
+
return res.status(429).json({
|
|
61
|
+
error: `Too many sign-ups from this address. Try again in ${limit.retryAfterSeconds} seconds.`,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
43
65
|
const result = validateRegister(req.body);
|
|
44
66
|
if (!result.valid) {
|
|
45
67
|
return res.status(422).json({ errors: result.errors });
|
|
46
68
|
}
|
|
47
69
|
|
|
48
|
-
const
|
|
49
|
-
if (
|
|
70
|
+
const email = normalizeEmail(req.body.email);
|
|
71
|
+
if (await User.findByEmail(email)) {
|
|
50
72
|
return res.status(422).json({ errors: { email: ["This email is already registered."] } });
|
|
51
73
|
}
|
|
52
74
|
|
|
53
|
-
|
|
75
|
+
// Only these fields are accepted from the request. Passing req.body
|
|
76
|
+
// straight through would let a client set email_verified_at.
|
|
77
|
+
const user = await User.create({
|
|
78
|
+
name: req.body.name,
|
|
79
|
+
email,
|
|
80
|
+
password: req.body.password,
|
|
81
|
+
});
|
|
54
82
|
|
|
55
83
|
const verificationToken = signToken(
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
);
|
|
60
|
-
await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
84
|
+
{ userId: user.id, purpose: "email-verify" },
|
|
85
|
+
this.secret,
|
|
86
|
+
{ expiresInSeconds: 60 * 60 * 24 },
|
|
87
|
+
);
|
|
88
|
+
await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
61
89
|
|
|
62
90
|
return res.status(201).json({
|
|
63
91
|
user: User.toSafeObject(user),
|
|
@@ -71,25 +99,24 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
71
99
|
return res.status(422).json({ errors: result.errors });
|
|
72
100
|
}
|
|
73
101
|
|
|
74
|
-
const
|
|
75
|
-
const { allowed, retryAfterSeconds } = checkLoginAllowed(
|
|
102
|
+
const email = normalizeEmail(req.body.email);
|
|
103
|
+
const { allowed, retryAfterSeconds } = checkLoginAllowed(email);
|
|
76
104
|
if (!allowed) {
|
|
77
105
|
return res.status(429).json({
|
|
78
106
|
error: `Too many failed attempts. Try again in ${retryAfterSeconds} seconds.`,
|
|
79
107
|
});
|
|
80
108
|
}
|
|
81
109
|
|
|
82
|
-
const
|
|
83
|
-
const user = users.find((u) => u.email === req.body.email);
|
|
110
|
+
const user = await User.findByEmail(email);
|
|
84
111
|
|
|
85
112
|
if (!user) {
|
|
86
|
-
recordFailedLogin(
|
|
113
|
+
recordFailedLogin(email);
|
|
87
114
|
return res.status(401).json({ error: "Invalid email or password." });
|
|
88
115
|
}
|
|
89
116
|
|
|
90
117
|
const passwordMatches = await verifyPassword(req.body.password, user.password);
|
|
91
118
|
if (!passwordMatches) {
|
|
92
|
-
recordFailedLogin(
|
|
119
|
+
recordFailedLogin(email);
|
|
93
120
|
return res.status(401).json({ error: "Invalid email or password." });
|
|
94
121
|
}
|
|
95
122
|
|
|
@@ -100,7 +127,7 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
100
127
|
});
|
|
101
128
|
}
|
|
102
129
|
|
|
103
|
-
clearLoginAttempts(
|
|
130
|
+
clearLoginAttempts(email);
|
|
104
131
|
|
|
105
132
|
const accessToken = signToken({ userId: user.id }, this.secret, {
|
|
106
133
|
expiresInSeconds: this.accessTokenTtlSeconds,
|
|
@@ -176,21 +203,36 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
176
203
|
}
|
|
177
204
|
|
|
178
205
|
async forgotPassword(req, res) {
|
|
206
|
+
const ipLimit = forgotIpLimiter(clientIp(req));
|
|
207
|
+
if (!ipLimit.allowed) {
|
|
208
|
+
return res.status(429).json({
|
|
209
|
+
error: `Too many requests. Try again in ${ipLimit.retryAfterSeconds} seconds.`,
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
|
|
179
213
|
const result = validateForgotPassword(req.body);
|
|
180
214
|
if (!result.valid) {
|
|
181
215
|
return res.status(422).json({ errors: result.errors });
|
|
182
216
|
}
|
|
183
217
|
|
|
184
|
-
const
|
|
185
|
-
|
|
218
|
+
const email = normalizeEmail(req.body.email);
|
|
219
|
+
|
|
220
|
+
// Counted for every address, registered or not, so hitting this limit
|
|
221
|
+
// reveals nothing. When it is hit we answer as normal but send nothing.
|
|
222
|
+
const emailLimit = forgotEmailLimiter(email);
|
|
223
|
+
const user = await User.findByEmail(email);
|
|
224
|
+
|
|
225
|
+
if (user && emailLimit.allowed) {
|
|
226
|
+
const { rawToken } = await PasswordReset.issue(user.email);
|
|
227
|
+
// Not awaited: waiting for the mail server only when the address
|
|
228
|
+
// exists would let response time reveal who is registered.
|
|
229
|
+
sendPasswordResetEmail(user, rawToken, this.mailConfig).catch((err) => {
|
|
230
|
+
console.error("Password reset email failed:", err);
|
|
231
|
+
});
|
|
232
|
+
}
|
|
186
233
|
|
|
187
234
|
// Always respond the same way whether or not the email exists,
|
|
188
235
|
// so this endpoint can't be used to enumerate registered users.
|
|
189
|
-
if (user) {
|
|
190
|
-
const { rawToken } = await PasswordReset.issue(user.email);
|
|
191
|
-
await sendPasswordResetEmail(user, rawToken, this.mailConfig);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
236
|
return res.json({
|
|
195
237
|
ok: true,
|
|
196
238
|
message: "If that email is registered, a reset link has been sent.",
|
|
@@ -203,15 +245,16 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
203
245
|
return res.status(422).json({ errors: result.errors });
|
|
204
246
|
}
|
|
205
247
|
|
|
206
|
-
|
|
207
|
-
|
|
248
|
+
// An unknown email gets the same answer as a bad token, so this
|
|
249
|
+
// endpoint can't be used to find out who is registered.
|
|
250
|
+
const user = await User.findByEmail(normalizeEmail(req.body.email));
|
|
251
|
+
if (!user) {
|
|
208
252
|
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
209
253
|
}
|
|
210
254
|
|
|
211
|
-
const
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
return res.status(404).json({ error: "User not found." });
|
|
255
|
+
const record = await PasswordReset.findValid(req.body.token, user.email);
|
|
256
|
+
if (!record) {
|
|
257
|
+
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
215
258
|
}
|
|
216
259
|
|
|
217
260
|
await User.updatePassword(user.id, req.body.password);
|
|
@@ -222,4 +265,4 @@ await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
|
222
265
|
|
|
223
266
|
return res.json({ ok: true, message: "Password updated. Please log in again." });
|
|
224
267
|
}
|
|
225
|
-
}
|
|
268
|
+
}
|
|
@@ -10,6 +10,11 @@
|
|
|
10
10
|
|
|
11
11
|
import { validate, required, isString, isEmail } from "@tylix/shared";
|
|
12
12
|
|
|
13
|
+
const MIN_PASSWORD_LENGTH = 8;
|
|
14
|
+
const MAX_PASSWORD_LENGTH = 128;
|
|
15
|
+
|
|
16
|
+
type ValidationResult = ReturnType<typeof validate>;
|
|
17
|
+
|
|
13
18
|
const registerSchema = {
|
|
14
19
|
name: [required, isString],
|
|
15
20
|
email: [required, isString, isEmail],
|
|
@@ -31,8 +36,36 @@ const resetPasswordSchema = {
|
|
|
31
36
|
password: [required, isString],
|
|
32
37
|
};
|
|
33
38
|
|
|
39
|
+
// Only for passwords being set (register, reset). Login must not enforce
|
|
40
|
+
// it, so people with older, shorter passwords can still sign in.
|
|
41
|
+
function enforcePasswordLength(
|
|
42
|
+
data: Record<string, unknown>,
|
|
43
|
+
result: ValidationResult,
|
|
44
|
+
): ValidationResult {
|
|
45
|
+
const password = data?.password;
|
|
46
|
+
if (typeof password !== "string") return result;
|
|
47
|
+
|
|
48
|
+
const existing =
|
|
49
|
+
(result as unknown as { errors?: Record<string, string[]> }).errors ?? {};
|
|
50
|
+
if (existing.password?.length) return result;
|
|
51
|
+
|
|
52
|
+
let message: string | null = null;
|
|
53
|
+
if (password.length < MIN_PASSWORD_LENGTH) {
|
|
54
|
+
message = `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`;
|
|
55
|
+
} else if (password.length > MAX_PASSWORD_LENGTH) {
|
|
56
|
+
message = `Password must be at most ${MAX_PASSWORD_LENGTH} characters.`;
|
|
57
|
+
}
|
|
58
|
+
if (!message) return result;
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
...result,
|
|
62
|
+
valid: false,
|
|
63
|
+
errors: { ...existing, password: [message] },
|
|
64
|
+
} as unknown as ValidationResult;
|
|
65
|
+
}
|
|
66
|
+
|
|
34
67
|
export function validateRegister(data: Record<string, unknown>) {
|
|
35
|
-
return validate(data, registerSchema);
|
|
68
|
+
return enforcePasswordLength(data, validate(data, registerSchema));
|
|
36
69
|
}
|
|
37
70
|
|
|
38
71
|
export function validateLogin(data: Record<string, unknown>) {
|
|
@@ -44,5 +77,5 @@ export function validateForgotPassword(data: Record<string, unknown>) {
|
|
|
44
77
|
}
|
|
45
78
|
|
|
46
79
|
export function validateResetPassword(data: Record<string, unknown>) {
|
|
47
|
-
return validate(data, resetPasswordSchema);
|
|
80
|
+
return enforcePasswordLength(data, validate(data, resetPasswordSchema));
|
|
48
81
|
}
|
|
@@ -10,6 +10,9 @@
|
|
|
10
10
|
|
|
11
11
|
import { validate, required, isString, isEmail } from "@tylix/shared";
|
|
12
12
|
|
|
13
|
+
const MIN_PASSWORD_LENGTH = 8;
|
|
14
|
+
const MAX_PASSWORD_LENGTH = 128;
|
|
15
|
+
|
|
13
16
|
const registerSchema = {
|
|
14
17
|
name: [required, isString],
|
|
15
18
|
email: [required, isString, isEmail],
|
|
@@ -31,8 +34,30 @@ const resetPasswordSchema = {
|
|
|
31
34
|
password: [required, isString],
|
|
32
35
|
};
|
|
33
36
|
|
|
37
|
+
// Only for passwords being set (register, reset). Login must not enforce
|
|
38
|
+
// it, so people with older, shorter passwords can still sign in.
|
|
39
|
+
function enforcePasswordLength(data, result) {
|
|
40
|
+
const password = data?.password;
|
|
41
|
+
if (typeof password !== "string") return result;
|
|
42
|
+
if (result.errors?.password?.length) return result;
|
|
43
|
+
|
|
44
|
+
let message = null;
|
|
45
|
+
if (password.length < MIN_PASSWORD_LENGTH) {
|
|
46
|
+
message = `Password must be at least ${MIN_PASSWORD_LENGTH} characters.`;
|
|
47
|
+
} else if (password.length > MAX_PASSWORD_LENGTH) {
|
|
48
|
+
message = `Password must be at most ${MAX_PASSWORD_LENGTH} characters.`;
|
|
49
|
+
}
|
|
50
|
+
if (!message) return result;
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
...result,
|
|
54
|
+
valid: false,
|
|
55
|
+
errors: { ...(result.errors ?? {}), password: [message] },
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
34
59
|
export function validateRegister(data) {
|
|
35
|
-
return validate(data, registerSchema);
|
|
60
|
+
return enforcePasswordLength(data, validate(data, registerSchema));
|
|
36
61
|
}
|
|
37
62
|
|
|
38
63
|
export function validateLogin(data) {
|
|
@@ -44,5 +69,5 @@ export function validateForgotPassword(data) {
|
|
|
44
69
|
}
|
|
45
70
|
|
|
46
71
|
export function validateResetPassword(data) {
|
|
47
|
-
return validate(data, resetPasswordSchema);
|
|
48
|
-
}
|
|
72
|
+
return enforcePasswordLength(data, validate(data, resetPasswordSchema));
|
|
73
|
+
}
|
|
@@ -24,34 +24,39 @@ export interface UserAttributes {
|
|
|
24
24
|
|
|
25
25
|
export type SafeUser = Omit<UserAttributes, "password">;
|
|
26
26
|
|
|
27
|
-
interface UserCreateInput {
|
|
28
|
-
name: string;
|
|
29
|
-
email: string;
|
|
30
|
-
password: string;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
27
|
export class User extends Model {
|
|
34
28
|
static table = "users";
|
|
35
29
|
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
];
|
|
30
|
+
static fillable: string[] = [
|
|
31
|
+
"name",
|
|
32
|
+
"email",
|
|
33
|
+
"password",
|
|
34
|
+
"email_verified_at",
|
|
35
|
+
];
|
|
42
36
|
|
|
43
37
|
static async all(): Promise<UserAttributes[]> {
|
|
44
|
-
|
|
45
|
-
}
|
|
38
|
+
return (await super.all()) as UserAttributes[];
|
|
39
|
+
}
|
|
46
40
|
|
|
47
|
-
static async find(id: number | string): Promise<UserAttributes | null> {
|
|
48
|
-
|
|
49
|
-
}
|
|
41
|
+
static async find(id: number | string): Promise<UserAttributes | null> {
|
|
42
|
+
return (await super.find(id)) as UserAttributes | null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// email_verified_at is dropped here on purpose: verification is only
|
|
46
|
+
// ever set through markEmailVerified(), never through create().
|
|
47
|
+
static async create(data: Record<string, unknown>): Promise<UserAttributes | null> {
|
|
48
|
+
const { email_verified_at: _ignored, ...rest } = data;
|
|
49
|
+
const email = typeof rest.email === "string" ? rest.email.trim().toLowerCase() : rest.email;
|
|
50
|
+
const hashed = await hashPassword(rest.password as string);
|
|
51
|
+
return (await super.create({ ...rest, email, password: hashed })) as UserAttributes | null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Emails are stored lowercased, so the lookup is lowercased too.
|
|
55
|
+
static async findByEmail(email: unknown): Promise<UserAttributes | null> {
|
|
56
|
+
const normalized = String(email ?? "").trim().toLowerCase();
|
|
57
|
+
return (await this.query().where("email", normalized).first()) as UserAttributes | null;
|
|
58
|
+
}
|
|
50
59
|
|
|
51
|
-
static async create(data: Record<string, unknown>): Promise<UserAttributes | null> {
|
|
52
|
-
const hashed = await hashPassword(data.password as string);
|
|
53
|
-
return (await super.create({ ...data, password: hashed })) as UserAttributes | null;
|
|
54
|
-
}
|
|
55
60
|
static async updatePassword(id: number, plainPassword: string) {
|
|
56
61
|
const hashed = await hashPassword(plainPassword);
|
|
57
62
|
return this.update(id, { password: hashed });
|
|
@@ -70,6 +75,4 @@ static async create(data: Record<string, unknown>): Promise<UserAttributes | nul
|
|
|
70
75
|
const { password, ...safe } = user;
|
|
71
76
|
return safe;
|
|
72
77
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
78
|
}
|
|
@@ -21,9 +21,19 @@ export class User extends Model {
|
|
|
21
21
|
"email_verified_at",
|
|
22
22
|
];
|
|
23
23
|
|
|
24
|
+
// email_verified_at is dropped here on purpose: verification is only
|
|
25
|
+
// ever set through markEmailVerified(), never through create().
|
|
24
26
|
static async create(data) {
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
+
const { email_verified_at, ...rest } = data;
|
|
28
|
+
const email = typeof rest.email === "string" ? rest.email.trim().toLowerCase() : rest.email;
|
|
29
|
+
const hashed = await hashPassword(rest.password);
|
|
30
|
+
return super.create({ ...rest, email, password: hashed });
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Emails are stored lowercased, so the lookup is lowercased too.
|
|
34
|
+
static async findByEmail(email) {
|
|
35
|
+
const normalized = String(email ?? "").trim().toLowerCase();
|
|
36
|
+
return this.query().where("email", normalized).first();
|
|
27
37
|
}
|
|
28
38
|
|
|
29
39
|
// ASSUMPTION: Model exposes a generic `update(id, data)` — mirrors the
|
|
@@ -47,4 +57,4 @@ export class User extends Model {
|
|
|
47
57
|
const { password, ...safe } = user;
|
|
48
58
|
return safe;
|
|
49
59
|
}
|
|
50
|
-
}
|
|
60
|
+
}
|