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