@tylix/auth 1.3.0 → 1.5.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/README.md +284 -14
- package/package.json +95 -9
- package/src/client/client.d.ts +14 -0
- package/src/client/client.js +83 -0
- package/src/cookies/authCookies.d.ts +8 -6
- package/src/cookies/authCookies.js +43 -28
- package/src/core/crypto.js +143 -0
- package/src/core/keys.js +83 -0
- package/src/core/seal.js +43 -0
- package/src/generators/AuthGenerator.d.ts +9 -3
- package/src/generators/AuthGenerator.js +16 -4
- package/src/generators/templates/auth-controller-ts.tyx +401 -98
- package/src/generators/templates/auth-controller.tyx +384 -96
- package/src/generators/templates/auth-session-migration-ts.tyx +34 -0
- package/src/generators/templates/auth-session-migration.tyx +32 -0
- package/src/generators/templates/auth-session-model-ts.tyx +53 -0
- package/src/generators/templates/auth-session-model.tyx +34 -0
- package/src/generators/templates/auth-validator-ts.tyx +17 -0
- package/src/generators/templates/auth-validator.tyx +17 -0
- package/src/generators/templates/oauth-account-migration-ts.tyx +29 -0
- package/src/generators/templates/oauth-account-migration.tyx +27 -0
- package/src/generators/templates/oauth-account-model-ts.tyx +65 -0
- package/src/generators/templates/oauth-account-model.tyx +45 -0
- package/src/generators/templates/password-reset-model-ts.tyx +26 -4
- package/src/generators/templates/password-reset-model.tyx +26 -4
- package/src/generators/templates/reset-password-view.html +30 -3
- package/src/generators/templates/verify-email-view.html +30 -3
- package/src/http/cookies.js +91 -0
- package/src/http/origin.js +68 -0
- package/src/http/request.js +179 -0
- package/src/index.d.ts +9 -1
- package/src/index.js +5 -0
- package/src/integrations/h3.d.ts +6 -0
- package/src/integrations/h3.js +70 -0
- package/src/integrations/hono.d.ts +6 -0
- package/src/integrations/hono.js +36 -0
- package/src/integrations/next.d.ts +16 -0
- package/src/integrations/next.js +36 -0
- package/src/integrations/node.d.ts +7 -0
- package/src/integrations/node.js +87 -0
- package/src/integrations/routes.js +92 -0
- package/src/integrations/sveltekit.d.ts +5 -0
- package/src/integrations/sveltekit.js +52 -0
- package/src/integrations/web.js +69 -0
- package/src/mfa/totp.js +150 -0
- package/src/oauth/oauth.js +142 -0
- package/src/oauth/providers.js +112 -0
- package/src/password/hashPassword.d.ts +5 -1
- package/src/password/hashPassword.js +96 -30
- package/src/password/index.d.ts +2 -0
- package/src/password/index.js +2 -0
- package/src/password/policy.js +108 -0
- package/src/rateLimiter/loginRateLimiter.js +16 -6
- package/src/ratelimit/limiter.js +129 -0
- package/src/session/adapters/keyValue.js +87 -0
- package/src/session/adapters/memory.js +38 -0
- package/src/session/adapters/model.js +97 -0
- package/src/session/adapters/prisma.js +67 -0
- package/src/session/adapters/sql.js +128 -0
- package/src/session/createAuth.js +420 -0
- package/src/token/jwt.js +144 -0
- package/src/token/signToken.js +41 -22
- package/src/tylix/accessTokens.js +61 -0
- package/src/web.d.ts +359 -0
- package/src/web.js +47 -0
|
@@ -2,26 +2,34 @@
|
|
|
2
2
|
* Generated by Tylix
|
|
3
3
|
*
|
|
4
4
|
* Generator: AuthGenerator
|
|
5
|
-
* Version: 0.
|
|
5
|
+
* Version: 0.2.0
|
|
6
6
|
* Feature: Auth
|
|
7
7
|
*
|
|
8
8
|
* Do not edit this section.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import {
|
|
11
|
+
import { randomBytes } from "node:crypto";
|
|
12
|
+
import { createRateLimiter, getStore } from "@tylix/core";
|
|
12
13
|
import { User } from "../models/User.js";
|
|
13
|
-
import {
|
|
14
|
+
import { AuthSession } from "../models/AuthSession.js";
|
|
14
15
|
import { PasswordReset } from "../models/PasswordReset.js";
|
|
16
|
+
import { OAuthAccount } from "../models/OAuthAccount.js";
|
|
15
17
|
import {
|
|
18
|
+
createAuth,
|
|
19
|
+
modelAdapter,
|
|
20
|
+
createLoginThrottle,
|
|
21
|
+
checkPasswordStrength,
|
|
16
22
|
verifyPassword,
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
needsRehash,
|
|
24
|
+
applyCookies,
|
|
25
|
+
sha256Hex,
|
|
26
|
+
setSessionGuard,
|
|
27
|
+
ACCESS_TOKEN_COOKIE,
|
|
28
|
+
REFRESH_TOKEN_COOKIE,
|
|
29
|
+
createOAuth,
|
|
30
|
+
google,
|
|
31
|
+
github,
|
|
32
|
+
OAuthError,
|
|
25
33
|
} from "@tylix/auth";
|
|
26
34
|
import { sendVerificationEmail, sendPasswordResetEmail } from "../mail/mailer.js";
|
|
27
35
|
import {
|
|
@@ -29,16 +37,45 @@ import {
|
|
|
29
37
|
validateLogin,
|
|
30
38
|
validateForgotPassword,
|
|
31
39
|
validateResetPassword,
|
|
40
|
+
validateChangePassword,
|
|
41
|
+
validateResendVerification,
|
|
32
42
|
} from "../validators/AuthValidator.js";
|
|
33
43
|
|
|
34
|
-
|
|
44
|
+
// Access tokens are short-lived on purpose: the refresh session (30 days,
|
|
45
|
+
// rotated on every use) is what keeps people signed in. Anything longer
|
|
46
|
+
// than an hour is capped.
|
|
47
|
+
const DEFAULT_ACCESS_TOKEN_TTL_SECONDS = 15 * 60;
|
|
48
|
+
const MAX_ACCESS_TOKEN_TTL_SECONDS = 60 * 60;
|
|
49
|
+
const EMAIL_VERIFY_TTL = "24h";
|
|
35
50
|
|
|
36
|
-
// In-memory limits (per server process).
|
|
37
51
|
// Counted in the app's store (STORE_DRIVER), so the limits hold across
|
|
38
52
|
// every worker and server, not per process.
|
|
53
|
+
const sharedStore = {
|
|
54
|
+
get: (key) => getStore().get(key),
|
|
55
|
+
increment: (key, options) => getStore().increment(key, options),
|
|
56
|
+
delete: (key) => getStore().delete(key),
|
|
57
|
+
};
|
|
58
|
+
const loginThrottle = createLoginThrottle({ store: sharedStore });
|
|
39
59
|
const registerLimiter = createRateLimiter({ name: "register", max: 20, windowMs: 60 * 60 * 1000, store: "shared" });
|
|
40
60
|
const forgotIpLimiter = createRateLimiter({ name: "forgot-password-ip", max: 10, windowMs: 15 * 60 * 1000, store: "shared" });
|
|
41
61
|
const forgotEmailLimiter = createRateLimiter({ name: "forgot-password-email", max: 5, windowMs: 60 * 60 * 1000, store: "shared" });
|
|
62
|
+
const resendIpLimiter = createRateLimiter({ name: "resend-verification-ip", max: 10, windowMs: 15 * 60 * 1000, store: "shared" });
|
|
63
|
+
const resendEmailLimiter = createRateLimiter({ name: "resend-verification-email", max: 3, windowMs: 60 * 60 * 1000, store: "shared" });
|
|
64
|
+
const changePasswordLimiter = createRateLimiter({ name: "change-password", max: 10, windowMs: 15 * 60 * 1000, store: "shared" });
|
|
65
|
+
const oauthLimiter = createRateLimiter({ name: "oauth-callback", max: 30, windowMs: 15 * 60 * 1000, store: "shared" });
|
|
66
|
+
|
|
67
|
+
// Social sign-in ("Continue with Google / GitHub"). A provider is on once
|
|
68
|
+
// its client id and secret are in .env. Register this callback URL with
|
|
69
|
+
// the provider: <APP_URL>/api/auth/oauth/<provider>/callback
|
|
70
|
+
// Google: https://console.cloud.google.com/apis/credentials
|
|
71
|
+
// GitHub: https://github.com/settings/developers
|
|
72
|
+
// Add another provider (discord, gitlab, microsoft from @tylix/auth, or
|
|
73
|
+
// your own oauthProvider()) by adding a row here and a button on the
|
|
74
|
+
// login and register pages.
|
|
75
|
+
const OAUTH_PROVIDERS = {
|
|
76
|
+
google: { name: "Google", env: "GOOGLE", create: google },
|
|
77
|
+
github: { name: "GitHub", env: "GITHUB", create: github },
|
|
78
|
+
};
|
|
42
79
|
|
|
43
80
|
// Emails are case-insensitive: always compare and store them trimmed and lowercased.
|
|
44
81
|
function normalizeEmail(value) {
|
|
@@ -49,20 +86,91 @@ function clientIp(req) {
|
|
|
49
86
|
return req.ip ?? "unknown";
|
|
50
87
|
}
|
|
51
88
|
|
|
89
|
+
// Verification links are bound to the address they were sent to, so a
|
|
90
|
+
// link stops working if the account's email changes.
|
|
91
|
+
async function emailFingerprint(email) {
|
|
92
|
+
return (await sha256Hex(`email-verify:${normalizeEmail(email)}`)).slice(0, 32);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function tooMany(res, retryAfterSeconds, message = "Too many requests.") {
|
|
96
|
+
res.setHeader("Retry-After", String(retryAfterSeconds));
|
|
97
|
+
return res.status(429).json({ error: `${message} Try again in ${retryAfterSeconds} seconds.` });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function redirect(res, location, cookies = []) {
|
|
101
|
+
applyCookies(res, cookies);
|
|
102
|
+
res.statusCode = 302;
|
|
103
|
+
res.setHeader("Location", location);
|
|
104
|
+
res.setHeader("Cache-Control", "no-store");
|
|
105
|
+
res.end();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Social sign-in problems go back to the login page as a short code
|
|
109
|
+
// (never free text, so the URL can't be used to show a crafted message).
|
|
110
|
+
function backToLogin(res, code, cookies = []) {
|
|
111
|
+
redirect(res, `/login?error=${encodeURIComponent(code)}`, cookies);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Accounts created through a provider get a random password nobody
|
|
115
|
+
// knows. "Forgot password" sets a real one if the user wants it.
|
|
116
|
+
function unusablePassword() {
|
|
117
|
+
return randomBytes(32).toString("base64url");
|
|
118
|
+
}
|
|
119
|
+
|
|
52
120
|
export class AuthController {
|
|
53
|
-
constructor({ secret, tokenExpiresInSeconds, mailConfig } = {}) {
|
|
54
|
-
this.secret = secret;
|
|
55
|
-
this.accessTokenTtlSeconds = tokenExpiresInSeconds ?? DEFAULT_ACCESS_TOKEN_TTL_SECONDS;
|
|
121
|
+
constructor({ secret, tokenExpiresInSeconds, mailConfig, checkBreachedPasswords = false, appUrl } = {}) {
|
|
56
122
|
this.mailConfig = mailConfig;
|
|
123
|
+
this.appUrl = appUrl ?? process.env.APP_URL;
|
|
124
|
+
this.checkBreachedPasswords = checkBreachedPasswords;
|
|
125
|
+
this.auth = createAuth({
|
|
126
|
+
secret,
|
|
127
|
+
adapter: modelAdapter(AuthSession),
|
|
128
|
+
accessTokenTtl: Math.min(tokenExpiresInSeconds ?? DEFAULT_ACCESS_TOKEN_TTL_SECONDS, MAX_ACCESS_TOKEN_TTL_SECONDS),
|
|
129
|
+
sessionTtl: "30d",
|
|
130
|
+
idleTimeout: "14d",
|
|
131
|
+
cookies: {
|
|
132
|
+
accessName: ACCESS_TOKEN_COOKIE,
|
|
133
|
+
refreshName: REFRESH_TOKEN_COOKIE,
|
|
134
|
+
// The names are fixed (the SSR session code and devtools read
|
|
135
|
+
// them); the Tylix server adds HSTS in production instead.
|
|
136
|
+
prefix: false,
|
|
137
|
+
// Reaches /api/auth/refresh AND /api/auth/logout, so logging
|
|
138
|
+
// out really ends the session server-side.
|
|
139
|
+
refreshPath: "/api/auth",
|
|
140
|
+
legacyRefreshPaths: ["/api/auth/refresh"],
|
|
141
|
+
},
|
|
142
|
+
// The Tylix server already refuses cross-site writes (Sec-Fetch-Site
|
|
143
|
+
// / Origin, honouring TRUSTED_ORIGINS) before any route runs.
|
|
144
|
+
csrf: false,
|
|
145
|
+
// req.user.userId keeps working in every controller.
|
|
146
|
+
claims: (session) => ({ userId: session.userId }),
|
|
147
|
+
onEvent: (event) => {
|
|
148
|
+
if (event.type === "session.reuse_detected") {
|
|
149
|
+
console.warn(`[auth] A refresh token was used twice: session ${event.sessionId} of user ${event.userId} was ended (possible token theft).`);
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
// requireAuth (every .auth() route) now also checks that the token's
|
|
155
|
+
// session still exists: logout and password resets apply at once.
|
|
156
|
+
setSessionGuard((claims) => this.auth.isSessionActive(claims.sid, claims.uid));
|
|
157
|
+
|
|
158
|
+
// PKCE, a sealed state cookie and same-site return paths; see
|
|
159
|
+
// createOAuth in @tylix/auth.
|
|
160
|
+
this.oauth = createOAuth({ sealer: this.auth.sealer, trustProxy: this.auth.options.trustProxy });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async passwordProblems(password, user) {
|
|
164
|
+
const { ok, errors } = await checkPasswordStrength(password, {
|
|
165
|
+
userInputs: [user.email, user.name],
|
|
166
|
+
breached: this.checkBreachedPasswords,
|
|
167
|
+
});
|
|
168
|
+
return ok ? null : errors;
|
|
57
169
|
}
|
|
58
170
|
|
|
59
171
|
async register(req, res) {
|
|
60
172
|
const limit = await registerLimiter(clientIp(req));
|
|
61
|
-
if (!limit.allowed)
|
|
62
|
-
return res.status(429).json({
|
|
63
|
-
error: `Too many sign-ups from this address. Try again in ${limit.retryAfterSeconds} seconds.`,
|
|
64
|
-
});
|
|
65
|
-
}
|
|
173
|
+
if (!limit.allowed) return tooMany(res, limit.retryAfterSeconds, "Too many sign-ups from this address.");
|
|
66
174
|
|
|
67
175
|
const result = validateRegister(req.body);
|
|
68
176
|
if (!result.valid) {
|
|
@@ -70,6 +178,11 @@ export class AuthController {
|
|
|
70
178
|
}
|
|
71
179
|
|
|
72
180
|
const email = normalizeEmail(req.body.email);
|
|
181
|
+
const passwordErrors = await this.passwordProblems(req.body.password, { email, name: req.body.name });
|
|
182
|
+
if (passwordErrors) {
|
|
183
|
+
return res.status(422).json({ errors: { password: passwordErrors } });
|
|
184
|
+
}
|
|
185
|
+
|
|
73
186
|
if (await User.findByEmail(email)) {
|
|
74
187
|
return res.status(422).json({ errors: { email: ["This email is already registered."] } });
|
|
75
188
|
}
|
|
@@ -82,12 +195,7 @@ export class AuthController {
|
|
|
82
195
|
password: req.body.password,
|
|
83
196
|
});
|
|
84
197
|
|
|
85
|
-
|
|
86
|
-
{ userId: user.id, purpose: "email-verify" },
|
|
87
|
-
this.secret,
|
|
88
|
-
{ expiresInSeconds: 60 * 60 * 24 },
|
|
89
|
-
);
|
|
90
|
-
await sendVerificationEmail(user, verificationToken, this.mailConfig);
|
|
198
|
+
await this.sendVerification(user);
|
|
91
199
|
|
|
92
200
|
return res.status(201).json({
|
|
93
201
|
user: User.toSafeObject(user),
|
|
@@ -95,6 +203,14 @@ export class AuthController {
|
|
|
95
203
|
});
|
|
96
204
|
}
|
|
97
205
|
|
|
206
|
+
async sendVerification(user) {
|
|
207
|
+
const token = await this.auth.tokens.sign(
|
|
208
|
+
{ uid: user.id, eh: await emailFingerprint(user.email) },
|
|
209
|
+
{ type: "email-verify", expiresIn: EMAIL_VERIFY_TTL },
|
|
210
|
+
);
|
|
211
|
+
await sendVerificationEmail(user, token, this.mailConfig);
|
|
212
|
+
}
|
|
213
|
+
|
|
98
214
|
async login(req, res) {
|
|
99
215
|
const result = validateLogin(req.body);
|
|
100
216
|
if (!result.valid) {
|
|
@@ -102,23 +218,17 @@ export class AuthController {
|
|
|
102
218
|
}
|
|
103
219
|
|
|
104
220
|
const email = normalizeEmail(req.body.email);
|
|
105
|
-
const {
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
error: `Too many failed attempts. Try again in ${retryAfterSeconds} seconds.`,
|
|
109
|
-
});
|
|
110
|
-
}
|
|
221
|
+
const attempt = { identifier: email, ip: clientIp(req) };
|
|
222
|
+
const throttle = await loginThrottle.check(attempt);
|
|
223
|
+
if (!throttle.allowed) return tooMany(res, throttle.retryAfterSeconds, "Too many failed attempts.");
|
|
111
224
|
|
|
112
225
|
const user = await User.findByEmail(email);
|
|
113
226
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
const passwordMatches = await verifyPassword(req.body.password, user.password);
|
|
120
|
-
if (!passwordMatches) {
|
|
121
|
-
recordFailedLogin(email);
|
|
227
|
+
// Without a user the same scrypt work is still done (against a dummy
|
|
228
|
+
// hash), so response times don't reveal which emails are registered.
|
|
229
|
+
const passwordMatches = await verifyPassword(req.body.password, user?.password ?? null);
|
|
230
|
+
if (!user || !passwordMatches) {
|
|
231
|
+
await loginThrottle.fail(attempt);
|
|
122
232
|
return res.status(401).json({ error: "Invalid email or password." });
|
|
123
233
|
}
|
|
124
234
|
|
|
@@ -129,50 +239,66 @@ export class AuthController {
|
|
|
129
239
|
});
|
|
130
240
|
}
|
|
131
241
|
|
|
132
|
-
|
|
242
|
+
await loginThrottle.succeed(attempt);
|
|
133
243
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
244
|
+
// Old-format or weaker hashes are upgraded while we have the password.
|
|
245
|
+
if (needsRehash(user.password)) {
|
|
246
|
+
await User.updatePassword(user.id, req.body.password);
|
|
247
|
+
}
|
|
138
248
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
accessTtlSeconds: this.accessTokenTtlSeconds,
|
|
143
|
-
refreshTtlSeconds,
|
|
144
|
-
});
|
|
249
|
+
// "Remember me" unticked -> the cookies end with the browser session.
|
|
250
|
+
const { cookies } = await this.auth.signIn(req, user.id, { persistent: req.body.remember !== false });
|
|
251
|
+
applyCookies(res, cookies);
|
|
145
252
|
|
|
146
253
|
return res.json({ user: User.toSafeObject(user) });
|
|
147
254
|
}
|
|
148
255
|
|
|
149
256
|
async refresh(req, res) {
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
const record = await RefreshToken.findValid(rawToken);
|
|
156
|
-
if (!record) {
|
|
157
|
-
clearAuthCookies(res);
|
|
257
|
+
const result = await this.auth.refresh(req);
|
|
258
|
+
applyCookies(res, result.cookies);
|
|
259
|
+
if (!result.ok) {
|
|
158
260
|
return res.status(401).json({ error: "Refresh token invalid or expired." });
|
|
159
261
|
}
|
|
262
|
+
return res.json({ ok: true });
|
|
263
|
+
}
|
|
160
264
|
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
265
|
+
async logout(req, res) {
|
|
266
|
+
const { cookies } = await this.auth.signOut(req);
|
|
267
|
+
applyCookies(res, cookies);
|
|
268
|
+
return res.status(204).send();
|
|
269
|
+
}
|
|
164
270
|
|
|
165
|
-
|
|
271
|
+
// Ends every session of the signed-in user, on every device.
|
|
272
|
+
async logoutAll(req, res) {
|
|
273
|
+
await this.auth.revokeAllSessions(req.user.userId);
|
|
274
|
+
applyCookies(res, this.auth.clearCookies(req));
|
|
275
|
+
return res.status(204).send();
|
|
276
|
+
}
|
|
166
277
|
|
|
167
|
-
|
|
278
|
+
async sessions(req, res) {
|
|
279
|
+
const sessions = await this.auth.listSessions(req.user.userId, { currentSessionId: req.user.sid });
|
|
280
|
+
return res.json({
|
|
281
|
+
sessions: sessions.map((s) => ({
|
|
282
|
+
id: s.id,
|
|
283
|
+
current: s.current,
|
|
284
|
+
createdAt: new Date(s.createdAt).toISOString(),
|
|
285
|
+
lastUsedAt: new Date(s.lastUsedAt).toISOString(),
|
|
286
|
+
expiresAt: new Date(s.expiresAt).toISOString(),
|
|
287
|
+
ip: s.ip,
|
|
288
|
+
userAgent: s.userAgent,
|
|
289
|
+
})),
|
|
290
|
+
});
|
|
168
291
|
}
|
|
169
292
|
|
|
170
|
-
async
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
293
|
+
async revokeSession(req, res) {
|
|
294
|
+
// Only the user's own sessions; someone else's id looks unknown.
|
|
295
|
+
const id = String(req.params.id ?? "");
|
|
296
|
+
const own = await this.auth.listSessions(req.user.userId);
|
|
297
|
+
if (!own.some((s) => s.id === id)) {
|
|
298
|
+
return res.status(404).json({ error: "Session not found." });
|
|
174
299
|
}
|
|
175
|
-
|
|
300
|
+
await this.auth.revokeSession(id);
|
|
301
|
+
if (id === req.user.sid) applyCookies(res, this.auth.clearCookies(req));
|
|
176
302
|
return res.status(204).send();
|
|
177
303
|
}
|
|
178
304
|
|
|
@@ -186,31 +312,46 @@ export class AuthController {
|
|
|
186
312
|
|
|
187
313
|
async verifyEmail(req, res) {
|
|
188
314
|
const token = req.query.token;
|
|
189
|
-
if (!token) {
|
|
315
|
+
if (!token || typeof token !== "string") {
|
|
190
316
|
return res.status(400).json({ error: "Missing verification token." });
|
|
191
317
|
}
|
|
192
318
|
|
|
193
|
-
const { valid, payload } =
|
|
194
|
-
if (!valid
|
|
319
|
+
const { valid, payload } = await this.auth.tokens.verify(token, { type: "email-verify" });
|
|
320
|
+
if (!valid) {
|
|
195
321
|
return res.status(400).json({ error: "Invalid or expired verification link." });
|
|
196
322
|
}
|
|
197
323
|
|
|
198
|
-
const user = await User.find(payload.
|
|
199
|
-
if (!user) {
|
|
200
|
-
return res.status(
|
|
324
|
+
const user = await User.find(payload.uid);
|
|
325
|
+
if (!user || payload.eh !== (await emailFingerprint(user.email))) {
|
|
326
|
+
return res.status(400).json({ error: "Invalid or expired verification link." });
|
|
201
327
|
}
|
|
202
328
|
|
|
203
|
-
await User.markEmailVerified(user.id);
|
|
329
|
+
if (!User.isEmailVerified(user)) await User.markEmailVerified(user.id);
|
|
204
330
|
return res.json({ ok: true, message: "Email verified. You can now log in." });
|
|
205
331
|
}
|
|
206
332
|
|
|
333
|
+
async resendVerification(req, res) {
|
|
334
|
+
const ipLimit = await resendIpLimiter(clientIp(req));
|
|
335
|
+
if (!ipLimit.allowed) return tooMany(res, ipLimit.retryAfterSeconds);
|
|
336
|
+
|
|
337
|
+
const result = validateResendVerification(req.body);
|
|
338
|
+
if (!result.valid) {
|
|
339
|
+
return res.status(422).json({ errors: result.errors });
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
const email = normalizeEmail(req.body.email);
|
|
343
|
+
const emailLimit = await resendEmailLimiter(email);
|
|
344
|
+
const user = await User.findByEmail(email);
|
|
345
|
+
if (user && emailLimit.allowed && !User.isEmailVerified(user)) {
|
|
346
|
+
// Not awaited, for the same reason as in forgotPassword.
|
|
347
|
+
this.sendVerification(user).catch((err) => console.error("Verification email failed:", err));
|
|
348
|
+
}
|
|
349
|
+
return res.json({ ok: true, message: "If that email needs verifying, a new link has been sent." });
|
|
350
|
+
}
|
|
351
|
+
|
|
207
352
|
async forgotPassword(req, res) {
|
|
208
353
|
const ipLimit = await forgotIpLimiter(clientIp(req));
|
|
209
|
-
if (!ipLimit.allowed)
|
|
210
|
-
return res.status(429).json({
|
|
211
|
-
error: `Too many requests. Try again in ${ipLimit.retryAfterSeconds} seconds.`,
|
|
212
|
-
});
|
|
213
|
-
}
|
|
354
|
+
if (!ipLimit.allowed) return tooMany(res, ipLimit.retryAfterSeconds);
|
|
214
355
|
|
|
215
356
|
const result = validateForgotPassword(req.body);
|
|
216
357
|
if (!result.valid) {
|
|
@@ -225,12 +366,11 @@ export class AuthController {
|
|
|
225
366
|
const user = await User.findByEmail(email);
|
|
226
367
|
|
|
227
368
|
if (user && emailLimit.allowed) {
|
|
228
|
-
|
|
229
|
-
//
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
console.error("Password reset email failed:", err);
|
|
233
|
-
});
|
|
369
|
+
// Not awaited: waiting for the database and mail server only when
|
|
370
|
+
// the address exists would let response time reveal who is registered.
|
|
371
|
+
PasswordReset.issue(user.email)
|
|
372
|
+
.then(({ rawToken }) => sendPasswordResetEmail(user, rawToken, this.mailConfig))
|
|
373
|
+
.catch((err) => console.error("Password reset email failed:", err));
|
|
234
374
|
}
|
|
235
375
|
|
|
236
376
|
// Always respond the same way whether or not the email exists,
|
|
@@ -250,21 +390,169 @@ export class AuthController {
|
|
|
250
390
|
// An unknown email gets the same answer as a bad token, so this
|
|
251
391
|
// endpoint can't be used to find out who is registered.
|
|
252
392
|
const user = await User.findByEmail(normalizeEmail(req.body.email));
|
|
253
|
-
|
|
393
|
+
const record = user ? await PasswordReset.findValid(req.body.token, user.email) : null;
|
|
394
|
+
if (!user || !record) {
|
|
254
395
|
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
255
396
|
}
|
|
256
397
|
|
|
257
|
-
|
|
258
|
-
|
|
398
|
+
// Checked before the link is used up, so a rejected password can be retried.
|
|
399
|
+
const passwordErrors = await this.passwordProblems(req.body.password, user);
|
|
400
|
+
if (passwordErrors) {
|
|
401
|
+
return res.status(422).json({ errors: { password: passwordErrors } });
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
if (!(await PasswordReset.consume(record))) {
|
|
259
405
|
return res.status(400).json({ error: "Invalid or expired reset link." });
|
|
260
406
|
}
|
|
261
407
|
|
|
262
408
|
await User.updatePassword(user.id, req.body.password);
|
|
263
|
-
await PasswordReset.
|
|
264
|
-
//
|
|
265
|
-
|
|
266
|
-
|
|
409
|
+
await PasswordReset.invalidateFor(user.email);
|
|
410
|
+
// The link reached the inbox, which proves the address.
|
|
411
|
+
if (!User.isEmailVerified(user)) await User.markEmailVerified(user.id);
|
|
412
|
+
// Resetting the password ends every session, in case the reset was
|
|
413
|
+
// triggered because the account was compromised.
|
|
414
|
+
await this.auth.revokeAllSessions(user.id);
|
|
415
|
+
applyCookies(res, this.auth.clearCookies(req));
|
|
267
416
|
|
|
268
417
|
return res.json({ ok: true, message: "Password updated. Please log in again." });
|
|
269
418
|
}
|
|
270
|
-
|
|
419
|
+
|
|
420
|
+
// For a signed-in user: needs the current password; keeps this session
|
|
421
|
+
// and ends all others.
|
|
422
|
+
async changePassword(req, res) {
|
|
423
|
+
const limit = await changePasswordLimiter(String(req.user.userId));
|
|
424
|
+
if (!limit.allowed) return tooMany(res, limit.retryAfterSeconds);
|
|
425
|
+
|
|
426
|
+
const result = validateChangePassword(req.body);
|
|
427
|
+
if (!result.valid) {
|
|
428
|
+
return res.status(422).json({ errors: result.errors });
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const user = await User.find(req.user.userId);
|
|
432
|
+
if (!user || !(await verifyPassword(req.body.currentPassword, user.password))) {
|
|
433
|
+
return res.status(422).json({ errors: { currentPassword: ["Your current password is incorrect."] } });
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const passwordErrors = await this.passwordProblems(req.body.password, user);
|
|
437
|
+
if (passwordErrors) {
|
|
438
|
+
return res.status(422).json({ errors: { password: passwordErrors } });
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
await User.updatePassword(user.id, req.body.password);
|
|
442
|
+
await this.auth.revokeAllSessions(user.id, { exceptSessionId: req.user.sid });
|
|
443
|
+
return res.json({ ok: true, message: "Password changed. You have been signed out on other devices." });
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// --- Social sign-in -------------------------------------------------
|
|
447
|
+
|
|
448
|
+
// Which providers this app offers, for pages that want to hide the
|
|
449
|
+
// buttons of providers that aren't configured yet.
|
|
450
|
+
async oauthProviders(req, res) {
|
|
451
|
+
return res.json({
|
|
452
|
+
providers: Object.entries(OAUTH_PROVIDERS).map(([id, p]) => ({
|
|
453
|
+
id,
|
|
454
|
+
name: p.name,
|
|
455
|
+
enabled: Boolean(process.env[`${p.env}_CLIENT_ID`] && process.env[`${p.env}_CLIENT_SECRET`]),
|
|
456
|
+
})),
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
oauthProviderFor(req, id) {
|
|
461
|
+
const entry = Object.hasOwn(OAUTH_PROVIDERS, id) ? OAUTH_PROVIDERS[id] : null;
|
|
462
|
+
if (!entry) return { error: "oauth_unknown" };
|
|
463
|
+
const clientId = process.env[`${entry.env}_CLIENT_ID`];
|
|
464
|
+
const clientSecret = process.env[`${entry.env}_CLIENT_SECRET`];
|
|
465
|
+
const base = (this.appUrl || `http://${req.headers.host ?? "localhost:3000"}`).replace(/\/$/, "");
|
|
466
|
+
const redirectUri = `${base}/api/auth/oauth/${id}/callback`;
|
|
467
|
+
if (!clientId || !clientSecret) {
|
|
468
|
+
console.warn(
|
|
469
|
+
`[auth] ${entry.name} sign-in isn't configured. Set ${entry.env}_CLIENT_ID and ${entry.env}_CLIENT_SECRET in .env, ` +
|
|
470
|
+
`and register ${redirectUri} as the callback URL with ${entry.name}.`,
|
|
471
|
+
);
|
|
472
|
+
return { error: "oauth_unavailable" };
|
|
473
|
+
}
|
|
474
|
+
return { provider: entry.create({ clientId, clientSecret, redirectUri }), name: entry.name };
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// GET /api/auth/oauth/:provider -> the provider's consent screen.
|
|
478
|
+
async oauthStart(req, res) {
|
|
479
|
+
const { provider, error } = this.oauthProviderFor(req, String(req.params.provider ?? ""));
|
|
480
|
+
if (!provider) return backToLogin(res, error);
|
|
481
|
+
const returnTo = typeof req.query.returnTo === "string" ? req.query.returnTo : "/dashboard";
|
|
482
|
+
const { url, cookies } = await this.oauth.start(provider, req, { returnTo });
|
|
483
|
+
return redirect(res, url, cookies);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
// GET /api/auth/oauth/:provider/callback: the provider sends the user
|
|
487
|
+
// back here. Signs them in (creating or linking the account) and
|
|
488
|
+
// returns them to where they started.
|
|
489
|
+
async oauthCallback(req, res) {
|
|
490
|
+
const limit = await oauthLimiter(clientIp(req));
|
|
491
|
+
if (!limit.allowed) return backToLogin(res, "oauth_rate_limited");
|
|
492
|
+
|
|
493
|
+
const { provider, name, error } = this.oauthProviderFor(req, String(req.params.provider ?? ""));
|
|
494
|
+
if (!provider) return backToLogin(res, error);
|
|
495
|
+
|
|
496
|
+
let result;
|
|
497
|
+
try {
|
|
498
|
+
result = await this.oauth.callback(provider, req);
|
|
499
|
+
} catch (err) {
|
|
500
|
+
if (!(err instanceof OAuthError)) throw err;
|
|
501
|
+
if (err.code === "provider_error") return backToLogin(res, "oauth_cancelled", err.cookies);
|
|
502
|
+
console.warn(`[auth] ${name} sign-in failed (${err.code}): ${err.message}`);
|
|
503
|
+
return backToLogin(res, "oauth_failed", err.cookies);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
const { user, error: problem } = await this.userForOAuthProfile(result.profile);
|
|
507
|
+
if (!user) return backToLogin(res, problem, result.cookies);
|
|
508
|
+
|
|
509
|
+
const { cookies } = await this.auth.signIn(req, user.id, { persistent: true });
|
|
510
|
+
return redirect(res, result.returnTo, [...result.cookies, ...cookies]);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// The user a provider profile belongs to: the linked account, else the
|
|
514
|
+
// account with the same (provider-verified) email, else a new one.
|
|
515
|
+
async userForOAuthProfile(profile) {
|
|
516
|
+
const linked = await OAuthAccount.findFor(profile.provider, profile.id);
|
|
517
|
+
if (linked) {
|
|
518
|
+
const user = await User.find(linked.user_id);
|
|
519
|
+
if (user) return { user };
|
|
520
|
+
await OAuthAccount.delete(linked.id); // its user was deleted
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// Only an address the provider has verified may be matched or used:
|
|
524
|
+
// otherwise anyone could take over an account by putting its email
|
|
525
|
+
// on their own GitHub profile.
|
|
526
|
+
const email = normalizeEmail(profile.email);
|
|
527
|
+
if (!email) return { error: "oauth_no_email" };
|
|
528
|
+
if (!profile.emailVerified) return { error: "oauth_email_unverified" };
|
|
529
|
+
|
|
530
|
+
let user = await User.findByEmail(email);
|
|
531
|
+
if (user && !User.isEmailVerified(user)) {
|
|
532
|
+
// An unverified account with this address may have been opened
|
|
533
|
+
// by someone else, waiting for the real owner to link it. The
|
|
534
|
+
// owner, now proven, takes it over: that password and every
|
|
535
|
+
// session of the account stop working.
|
|
536
|
+
await User.updatePassword(user.id, unusablePassword());
|
|
537
|
+
await this.auth.revokeAllSessions(user.id);
|
|
538
|
+
await User.markEmailVerified(user.id);
|
|
539
|
+
}
|
|
540
|
+
if (!user) {
|
|
541
|
+
user = await User.create({
|
|
542
|
+
name: profile.name || email.split("@")[0],
|
|
543
|
+
email,
|
|
544
|
+
password: unusablePassword(),
|
|
545
|
+
});
|
|
546
|
+
if (!user) return { error: "oauth_failed" };
|
|
547
|
+
await User.markEmailVerified(user.id);
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
try {
|
|
551
|
+
await OAuthAccount.link(user.id, profile);
|
|
552
|
+
} catch (err) {
|
|
553
|
+
// Two callbacks raced and the other one linked it first.
|
|
554
|
+
if (!(await OAuthAccount.findFor(profile.provider, profile.id))) throw err;
|
|
555
|
+
}
|
|
556
|
+
return { user };
|
|
557
|
+
}
|
|
558
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generated by Tylix
|
|
3
|
+
*
|
|
4
|
+
* Generator: AuthGenerator
|
|
5
|
+
* Version: 0.2.0
|
|
6
|
+
* Feature: AuthSession
|
|
7
|
+
*
|
|
8
|
+
* Do not edit this section.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import type { Schema, CreateTableBuilder } from "@tylix/shared";
|
|
12
|
+
|
|
13
|
+
export const up = async (schema: Schema) => {
|
|
14
|
+
await schema.createTable("auth_sessions", (table: CreateTableBuilder) => {
|
|
15
|
+
table.increments("id");
|
|
16
|
+
table.string("sid").unique();
|
|
17
|
+
table.integer("user_id");
|
|
18
|
+
table.string("token_hash");
|
|
19
|
+
table.string("prev_token_hash");
|
|
20
|
+
table.datetime("rotated_at");
|
|
21
|
+
table.datetime("last_used_at");
|
|
22
|
+
table.datetime("expires_at");
|
|
23
|
+
table.datetime("idle_expires_at");
|
|
24
|
+
table.integer("persistent");
|
|
25
|
+
table.string("ip");
|
|
26
|
+
table.text("user_agent");
|
|
27
|
+
table.text("data");
|
|
28
|
+
table.timestamps();
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const down = async (schema: Schema) => {
|
|
33
|
+
await schema.dropTable("auth_sessions");
|
|
34
|
+
};
|