Repository navigation
feat(auth): add email-based forgot/reset password flow #56
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mankatcheung
merged 4 commits into
main
from
feature/jef-16-forgotreset-password-via-email
Jul 23, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2598ae6
feat(auth): add email-based forgot/reset password flow
mankatcheung d69b349
merge main into fix/jef-16-security
mankatcheung ae81b89
fix: complete local IEmailService test stubs after merge
mankatcheung db27590
fix(auth): harden password reset flow (JEF-24, JEF-25, JEF-26)
mankatcheung File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
12 changes: 12 additions & 0 deletions
12
apps/api/prisma/migrations/20260722213047_add_password_reset_tokens/migration.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| CREATE TABLE "PasswordResetToken" ( | ||
| "id" TEXT NOT NULL PRIMARY KEY, | ||
| "userId" TEXT NOT NULL, | ||
| "tokenHash" TEXT NOT NULL, | ||
| "expiresAt" DATETIME NOT NULL, | ||
| "usedAt" DATETIME, | ||
| "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, | ||
| CONSTRAINT "PasswordResetToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User" ("id") ON DELETE CASCADE ON UPDATE CASCADE | ||
| ); | ||
|
|
||
| CREATE UNIQUE INDEX "PasswordResetToken_tokenHash_key" ON "PasswordResetToken"("tokenHash"); | ||
| CREATE INDEX "PasswordResetToken_userId_idx" ON "PasswordResetToken"("userId"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
147 changes: 147 additions & 0 deletions
147
apps/api/src/__tests__/application/auth/RequestPasswordResetUseCase.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| import { describe, it, expect, vi, beforeEach } from 'vitest'; | ||
| import { RequestPasswordResetUseCase } from '@/use-cases/auth/RequestPasswordResetUseCase.js'; | ||
| import { | ||
| makeUserRepository, | ||
| makePasswordResetTokenRepository, | ||
| makeUser, | ||
| makeRateLimiter, | ||
| } from '@/__tests__/helpers/mocks.js'; | ||
| import type { IEmailService } from '@/use-cases/ports/IEmailService.js'; | ||
|
|
||
| const makeEmailService = (overrides?: Partial<IEmailService>): IEmailService => ({ | ||
| sendFollowUpReminder: vi.fn().mockResolvedValue(undefined), | ||
| sendWeeklyDigest: vi.fn().mockResolvedValue(undefined), | ||
| sendPasswordReset: vi.fn().mockResolvedValue(undefined), | ||
| sendEmailVerification: vi.fn().mockResolvedValue(undefined), | ||
| ...overrides, | ||
| }); | ||
|
|
||
| const makeDeps = (overrides?: object) => ({ | ||
| userRepository: makeUserRepository(), | ||
| passwordResetTokenRepository: makePasswordResetTokenRepository(), | ||
| emailService: makeEmailService(), | ||
| passwordResetRateLimiter: makeRateLimiter(), | ||
| generateId: vi.fn().mockReturnValue('generated-id'), | ||
| webAppOrigin: 'http://localhost:3000', | ||
| ...overrides, | ||
| }); | ||
|
|
||
| describe('RequestPasswordResetUseCase', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('silently no-ops when the email does not match a user', async () => { | ||
| const userRepository = makeUserRepository({ findByEmail: vi.fn().mockResolvedValue(null) }); | ||
| const passwordResetTokenRepository = makePasswordResetTokenRepository(); | ||
| const emailService = makeEmailService(); | ||
|
|
||
| await new RequestPasswordResetUseCase( | ||
| makeDeps({ userRepository, passwordResetTokenRepository, emailService }), | ||
| ).execute({ email: 'nobody@example.com', ipAddress: '127.0.0.1' }); | ||
|
|
||
| expect(passwordResetTokenRepository.create).not.toHaveBeenCalled(); | ||
| expect(emailService.sendPasswordReset).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('deletes existing tokens, creates a new one, and emails a reset link', async () => { | ||
| const user = makeUser({ id: 'user-1', email: 'test@example.com' }); | ||
| const userRepository = makeUserRepository({ findByEmail: vi.fn().mockResolvedValue(user) }); | ||
| const passwordResetTokenRepository = makePasswordResetTokenRepository(); | ||
| const emailService = makeEmailService(); | ||
|
|
||
| await new RequestPasswordResetUseCase( | ||
| makeDeps({ | ||
| userRepository, | ||
| passwordResetTokenRepository, | ||
| emailService, | ||
| webAppOrigin: 'https://app.jobfinder.com', | ||
| }), | ||
| ).execute({ email: 'test@example.com', ipAddress: '127.0.0.1' }); | ||
|
|
||
| expect(passwordResetTokenRepository.deleteAllForUser).toHaveBeenCalledWith('user-1'); | ||
| expect(passwordResetTokenRepository.create).toHaveBeenCalledWith( | ||
| expect.objectContaining({ id: 'generated-id', userId: 'user-1' }), | ||
| ); | ||
| expect(emailService.sendPasswordReset).toHaveBeenCalledWith( | ||
| 'test@example.com', | ||
| expect.stringMatching(/^https:\/\/app\.jobfinder\.com\/reset-password\?token=[a-f0-9]+$/), | ||
| ); | ||
| }); | ||
|
|
||
| it('sets an expiry roughly one hour in the future', async () => { | ||
| const user = makeUser({ id: 'user-1' }); | ||
| const userRepository = makeUserRepository({ findByEmail: vi.fn().mockResolvedValue(user) }); | ||
| const passwordResetTokenRepository = makePasswordResetTokenRepository(); | ||
|
|
||
| const before = Date.now(); | ||
| await new RequestPasswordResetUseCase( | ||
| makeDeps({ userRepository, passwordResetTokenRepository }), | ||
| ).execute({ email: 'test@example.com', ipAddress: '127.0.0.1' }); | ||
| const after = Date.now(); | ||
|
|
||
| const createCall = vi.mocked(passwordResetTokenRepository.create).mock.calls[0][0]; | ||
| const expiresAtMs = createCall.expiresAt.getTime(); | ||
| expect(expiresAtMs).toBeGreaterThanOrEqual(before + 60 * 60 * 1000 - 1000); | ||
| expect(expiresAtMs).toBeLessThanOrEqual(after + 60 * 60 * 1000 + 1000); | ||
| }); | ||
|
|
||
| it('does not let an email-provider failure surface differently than the unknown-email no-op', async () => { | ||
| const user = makeUser({ id: 'user-1', email: 'test@example.com' }); | ||
| const userRepository = makeUserRepository({ findByEmail: vi.fn().mockResolvedValue(user) }); | ||
| const emailService = makeEmailService({ | ||
| sendPasswordReset: vi.fn().mockRejectedValue(new Error('Brevo API error 500')), | ||
| }); | ||
|
|
||
| await expect( | ||
| new RequestPasswordResetUseCase(makeDeps({ userRepository, emailService })).execute({ | ||
| email: 'test@example.com', | ||
| ipAddress: '127.0.0.1', | ||
| }), | ||
| ).resolves.toBeUndefined(); | ||
| }); | ||
|
|
||
| it('rate-limits by email address regardless of whether the account exists', async () => { | ||
| const userRepository = makeUserRepository({ findByEmail: vi.fn().mockResolvedValue(null) }); | ||
| const rateLimiter = makeRateLimiter({ consume: vi.fn().mockReturnValue(false) }); | ||
|
|
||
| const err = await new RequestPasswordResetUseCase( | ||
| makeDeps({ userRepository, passwordResetRateLimiter: rateLimiter }), | ||
| ) | ||
| .execute({ email: 'nobody@example.com', ipAddress: '127.0.0.1' }) | ||
| .catch((e) => e); | ||
|
|
||
| expect((err as { code: string }).code).toBe('RATE_LIMITED'); | ||
| expect(rateLimiter.consume).toHaveBeenCalledWith('password-reset:email:nobody@example.com'); | ||
| expect(userRepository.findByEmail).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('rate-limits by IP address in addition to email', async () => { | ||
| const rateLimiter = makeRateLimiter({ | ||
| consume: vi.fn().mockImplementation((key: string) => !key.startsWith('password-reset:ip:')), | ||
| }); | ||
|
|
||
| const err = await new RequestPasswordResetUseCase( | ||
| makeDeps({ passwordResetRateLimiter: rateLimiter }), | ||
| ) | ||
| .execute({ email: 'test@example.com', ipAddress: '203.0.113.5' }) | ||
| .catch((e) => e); | ||
|
|
||
| expect((err as { code: string }).code).toBe('RATE_LIMITED'); | ||
| expect(rateLimiter.consume).toHaveBeenCalledWith('password-reset:ip:203.0.113.5'); | ||
| }); | ||
|
|
||
| it('lowercases the email when building the rate-limit key', async () => { | ||
| const rateLimiter = makeRateLimiter(); | ||
| const userRepository = makeUserRepository({ findByEmail: vi.fn().mockResolvedValue(null) }); | ||
|
|
||
| await new RequestPasswordResetUseCase( | ||
| makeDeps({ userRepository, passwordResetRateLimiter: rateLimiter }), | ||
| ).execute({ | ||
| email: 'Test@Example.com', | ||
| ipAddress: null, | ||
| }); | ||
|
|
||
| expect(rateLimiter.consume).toHaveBeenCalledWith('password-reset:email:test@example.com'); | ||
| }); | ||
| }); |
129 changes: 129 additions & 0 deletions
129
apps/api/src/__tests__/application/auth/ResetPasswordUseCase.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| import { createHash } from 'crypto'; | ||
| import { describe, it, expect, vi, beforeEach } from 'vitest'; | ||
| import bcrypt from 'bcryptjs'; | ||
| import { ResetPasswordUseCase } from '@/use-cases/auth/ResetPasswordUseCase.js'; | ||
| import { | ||
| makeUserRepository, | ||
| makePasswordResetTokenRepository, | ||
| makePasswordResetToken, | ||
| makeSessionRepository, | ||
| } from '@/__tests__/helpers/mocks.js'; | ||
|
|
||
| vi.mock('bcryptjs', () => ({ | ||
| default: { | ||
| hash: vi.fn(), | ||
| compare: vi.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| const RAW_TOKEN = 'raw-reset-token'; | ||
| const TOKEN_HASH = createHash('sha256').update(RAW_TOKEN).digest('hex'); | ||
|
|
||
| const makeDeps = (overrides?: object) => ({ | ||
| userRepository: makeUserRepository(), | ||
| passwordResetTokenRepository: makePasswordResetTokenRepository(), | ||
| sessionRepository: makeSessionRepository(), | ||
| ...overrides, | ||
| }); | ||
|
|
||
| describe('ResetPasswordUseCase', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('throws VALIDATION when the new password is too short', async () => { | ||
| const userRepository = makeUserRepository(); | ||
|
|
||
| const err = await new ResetPasswordUseCase(makeDeps({ userRepository })) | ||
| .execute({ token: RAW_TOKEN, newPassword: 'short1' }) | ||
| .catch((e) => e); | ||
|
|
||
| expect((err as { code: string }).code).toBe('VALIDATION'); | ||
| expect(userRepository.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('throws UNAUTHORIZED when no token matches the hash', async () => { | ||
| const passwordResetTokenRepository = makePasswordResetTokenRepository({ | ||
| findByTokenHash: vi.fn().mockResolvedValue(null), | ||
| }); | ||
| const userRepository = makeUserRepository(); | ||
|
|
||
| const err = await new ResetPasswordUseCase( | ||
| makeDeps({ userRepository, passwordResetTokenRepository }), | ||
| ) | ||
| .execute({ token: RAW_TOKEN, newPassword: 'newPassword123' }) | ||
| .catch((e) => e); | ||
|
|
||
| expect((err as { code: string }).code).toBe('UNAUTHORIZED'); | ||
| expect(userRepository.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('throws UNAUTHORIZED when the token was already used', async () => { | ||
| const resetToken = makePasswordResetToken({ | ||
| tokenHash: TOKEN_HASH, | ||
| usedAt: new Date('2024-01-01T00:30:00.000Z'), | ||
| }); | ||
| const passwordResetTokenRepository = makePasswordResetTokenRepository({ | ||
| findByTokenHash: vi.fn().mockResolvedValue(resetToken), | ||
| }); | ||
| const userRepository = makeUserRepository(); | ||
|
|
||
| const err = await new ResetPasswordUseCase( | ||
| makeDeps({ userRepository, passwordResetTokenRepository }), | ||
| ) | ||
| .execute({ token: RAW_TOKEN, newPassword: 'newPassword123' }) | ||
| .catch((e) => e); | ||
|
|
||
| expect((err as { code: string }).code).toBe('UNAUTHORIZED'); | ||
| expect(userRepository.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('throws UNAUTHORIZED when the token has expired', async () => { | ||
| const resetToken = makePasswordResetToken({ | ||
| tokenHash: TOKEN_HASH, | ||
| expiresAt: new Date(Date.now() - 1000), | ||
| }); | ||
| const passwordResetTokenRepository = makePasswordResetTokenRepository({ | ||
| findByTokenHash: vi.fn().mockResolvedValue(resetToken), | ||
| }); | ||
| const userRepository = makeUserRepository(); | ||
|
|
||
| const err = await new ResetPasswordUseCase( | ||
| makeDeps({ userRepository, passwordResetTokenRepository }), | ||
| ) | ||
| .execute({ token: RAW_TOKEN, newPassword: 'newPassword123' }) | ||
| .catch((e) => e); | ||
|
|
||
| expect((err as { code: string }).code).toBe('UNAUTHORIZED'); | ||
| expect(userRepository.update).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('updates the password, marks the token used, and revokes all sessions for a valid token', async () => { | ||
| const resetToken = makePasswordResetToken({ | ||
| id: 'reset-1', | ||
| userId: 'user-1', | ||
| tokenHash: TOKEN_HASH, | ||
| expiresAt: new Date(Date.now() + 60 * 60 * 1000), | ||
| }); | ||
| const passwordResetTokenRepository = makePasswordResetTokenRepository({ | ||
| findByTokenHash: vi.fn().mockResolvedValue(resetToken), | ||
| }); | ||
| const userRepository = makeUserRepository(); | ||
| const sessionRepository = makeSessionRepository(); | ||
| vi.mocked(bcrypt.hash).mockResolvedValue('new-hashed-password' as never); | ||
|
|
||
| await new ResetPasswordUseCase( | ||
| makeDeps({ userRepository, passwordResetTokenRepository, sessionRepository }), | ||
| ).execute({ | ||
| token: RAW_TOKEN, | ||
| newPassword: 'newPassword123', | ||
| }); | ||
|
|
||
| expect(bcrypt.hash).toHaveBeenCalledWith('newPassword123', 12); | ||
| expect(userRepository.update).toHaveBeenCalledWith('user-1', { | ||
| passwordHash: 'new-hashed-password', | ||
| }); | ||
| expect(passwordResetTokenRepository.markUsed).toHaveBeenCalledWith('reset-1'); | ||
| expect(sessionRepository.revokeAllForUser).toHaveBeenCalledWith('user-1'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔒 Security & Privacy | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: mankatcheung/job-finder
Length of output: 26895
🏁 Script executed:
Repository: mankatcheung/job-finder
Length of output: 6232
Make reset-token claims atomic.
ResetPasswordUseCase.execute()reads the token, then separately callsmarkUsed(), while the repository only doesupdate({ id }, { usedAt })with nowhere: { usedAt: null }. Concurrent reset requests can both pass theusedAtguard and complete updates. ChangemarkUsed()into a conditional update that updates only whenusedAt IS NULL, throw if only one row is claimed, and wrap the password update/session revocation in the same transaction.🤖 Prompt for AI Agents