From 98e5d055484da78db69edb8598f550b56189d502 Mon Sep 17 00:00:00 2001 From: joshua Date: Fri, 30 Oct 2026 08:47:04 +0200 Subject: [PATCH 1/2] WIP 1.51.17: forgot password and sign-in don't reveal accounts Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot --- CHANGELOG.md | 19 +++++ WHATS-NEW.md | 5 ++ backend/src/controllers/userController.js | 85 ++++++++++----------- backend/src/routes/userRoutes.js | 2 +- backend/src/services/auth.ts | 11 ++- backend/src/v2/resources/peopleMessaging.ts | 2 +- backend/tests/accountEnumeration.test.ts | 83 ++++++++++++++++++++ docs/HANDOVER.md | 3 +- e2e/api-v2.spec.ts | 13 +++- frontend/src/lib/api-v2/openapi.json | 2 +- frontend/src/lib/api-v2/schema.d.ts | 2 +- 11 files changed, 174 insertions(+), 53 deletions(-) create mode 100644 backend/tests/accountEnumeration.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 914c5ad..3d20297 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ and this project follows [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [1.51.17] - 2026-10-30 — security release + +### Security + +- **Forgot password no longer reveals whether an account exists.** It answered "Email not found" + (404) for an unknown address, so anyone could check which emails have accounts. It now gives + the same answer and status for every address, sent before any work that only happens for a + real account (so the response time doesn't tell either); the reset link is made and sent + afterwards. Applies to `POST /api/users/forgot` and `POST /api/v2/auth/password/forgot`. +- **Sign-in no longer reveals it either.** An unknown email answered "User does not exist" (with a + different status on v1); it now gets exactly the answer a wrong password gets, after a password + check against a stand-in hash so it takes as long. +- Forgot password is rate-limited like sign-in, so it can't be used to flood someone's inbox with + reset emails. + +### Upgrading + +- Update as soon as you can. Nothing else changes; the forgot-password page shows the new message. + ## [1.51.16] - 2026-10-30 ### Added diff --git a/WHATS-NEW.md b/WHATS-NEW.md index 7658069..b87b5d5 100644 --- a/WHATS-NEW.md +++ b/WHATS-NEW.md @@ -12,6 +12,11 @@ Write for church admins, not developers: no environment variables, endpoints or developer log is CHANGELOG.md. A tagged version without a section here shows "No details given". --> +## 1.51.17 — security update + +- **Better protection for people's accounts.** The forgot-password and sign-in pages no longer + let anyone find out whether an email address has an account here. + ## 1.51.16 - **The move to the new server connection is complete.** Payment confirmations from Yoco and diff --git a/backend/src/controllers/userController.js b/backend/src/controllers/userController.js index c84dfcd..494bbcc 100644 --- a/backend/src/controllers/userController.js +++ b/backend/src/controllers/userController.js @@ -539,55 +539,52 @@ const requestPasswordReset = async (req, res) => { const user = await prisma.user.findUnique({ where: { email } }); - // Explicitly check existence as requested - if (!user) { - return res.status(404).json({ message: 'Email not found' }); - } - - // Create token valid for 1 hour - const token = uuidv4(); - const expiresAt = new Date(Date.now() + 60 * 60 * 1000); - - // If PasswordReset model isn't available (migration not run), return clear error - if (!prisma.passwordReset || typeof prisma.passwordReset.create !== 'function' || typeof prisma.passwordReset.updateMany !== 'function') { - console.warn('[PasswordReset] Prisma model not available. Run Prisma migrations to enable password reset tokens.'); - return res.status(500).json({ message: 'Password reset is not available. Please contact support.' }); - } - - // Invalidate previous tokens (optional) - await prisma.passwordReset.updateMany({ - where: { userId: user.id, used: false, expiresAt: { gt: new Date() } }, - data: { used: true } - }); - - await prisma.passwordReset.create({ - data: { - id: uuidv4(), - userId: user.id, - token, - expiresAt, - used: false - } - }); - - const baseUrl = process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001'; - const resetUrl = `${baseUrl.replace(/\/$/, '')}/reset-password?token=${encodeURIComponent(token)}`; - - const { sendMail, buildPasswordResetEmail } = require('../utils/email'); - const emailContent = buildPasswordResetEmail({ name: user.name, resetUrl }); - // Security: always email - sendMail({ to: user.email, subject: 'Reset your password', ...emailContent }) - .catch(e => console.warn('[password reset email] Failed:', e?.message || e)); - // Also WhatsApp if preferred (security message — sent in addition to email) - const { waText } = require('../utils/notify'); - waText(user, emailContent.text).catch(() => {}); - - return res.json({ message: 'If that email exists, a password reset link has been sent.' }); + // Security (1.51.17): the same answer, with the same status, whether or not an account has + // this email — and it's sent before any work that only happens for real accounts, so the + // response time doesn't tell either. The link is made and sent afterwards. + res.json({ message: GENERIC_RESET_MESSAGE }); + if (user) sendPasswordResetLink(user).catch(e => console.warn('[password reset] Failed:', e?.message || e)); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; +const GENERIC_RESET_MESSAGE = 'If an account uses that email, we\'ve sent it a link to reset the password.'; + +/** A one-hour reset link for this account, by email (and WhatsApp when they prefer it). */ +async function sendPasswordResetLink(user) { + const token = uuidv4(); + const expiresAt = new Date(Date.now() + 60 * 60 * 1000); + + // Invalidate previous tokens (optional) + await prisma.passwordReset.updateMany({ + where: { userId: user.id, used: false, expiresAt: { gt: new Date() } }, + data: { used: true } + }); + + await prisma.passwordReset.create({ + data: { + id: uuidv4(), + userId: user.id, + token, + expiresAt, + used: false + } + }); + + const baseUrl = process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001'; + const resetUrl = `${baseUrl.replace(/\/$/, '')}/reset-password?token=${encodeURIComponent(token)}`; + + const { sendMail, buildPasswordResetEmail } = require('../utils/email'); + const emailContent = buildPasswordResetEmail({ name: user.name, resetUrl }); + // Security: always email + sendMail({ to: user.email, subject: 'Reset your password', ...emailContent }) + .catch(e => console.warn('[password reset email] Failed:', e?.message || e)); + // Also WhatsApp if preferred (security message — sent in addition to email) + const { waText } = require('../utils/notify'); + waText(user, emailContent.text).catch(() => {}); +} + // @desc Reset password using token // @route POST /api/users/reset // @access Public diff --git a/backend/src/routes/userRoutes.js b/backend/src/routes/userRoutes.js index 4b28446..c5f037a 100644 --- a/backend/src/routes/userRoutes.js +++ b/backend/src/routes/userRoutes.js @@ -33,7 +33,7 @@ router.post('/', registerUser); router.post('/login', loginLimiter, loginUser); router.post('/login/2fa', loginLimiter, verifyLoginTwoFactor); router.post('/login/2fa/resend', loginLimiter, resendLoginTwoFactor); -router.post('/forgot', requestPasswordReset); +router.post('/forgot', loginLimiter, requestPasswordReset); router.post('/reset', resetPassword); router.post('/activate', activateAccount); diff --git a/backend/src/services/auth.ts b/backend/src/services/auth.ts index 6a4b68d..56ab378 100644 --- a/backend/src/services/auth.ts +++ b/backend/src/services/auth.ts @@ -207,6 +207,10 @@ export type LoginResult = | { status: 'signed_in'; session: Session } | { status: 'code_required'; challenge: { challengeId: string; method: string; destination: string | null }; enrolling: boolean }; +let standIn: Promise | null = null; +/** A hash nobody's password matches, so a sign-in with an unknown email does the same work. */ +const standInHash = () => (standIn ??= auth.hashPassword(uuidv4())); + const MAX_ATTEMPTS = 5; const LOCK_TIME = 5 * 60 * 1000; @@ -219,7 +223,12 @@ export async function logIn(input: { identifier: string; password: string; devic // SA local format (0xx) → international (27xx) const normalizedPhone = whatsapp().normalizeZAPhone(rawInput) || rawInput.replace(/\D/g, ''); const user = await prisma.user.findFirst({ where: { OR: [{ email: rawInput }, ...(normalizedPhone ? [{ phoneNumber: normalizedPhone }] : [])] } }); - if (!user) return fail(401, 'User does not exist'); + // Security (1.51.17): an unknown email answers like a wrong password — same message and + // status, and a password check against a stand-in hash so it takes as long. + if (!user) { + await auth.comparePassword(input.password, await standInHash()); + return fail(401, 'Invalid email or password', undefined, { v1Status: 400 }); + } if (!user.isActive) { // Resend the activation link on each attempt, in case the earlier one expired. diff --git a/backend/src/v2/resources/peopleMessaging.ts b/backend/src/v2/resources/peopleMessaging.ts index 1ac1793..9b885c9 100644 --- a/backend/src/v2/resources/peopleMessaging.ts +++ b/backend/src/v2/resources/peopleMessaging.ts @@ -44,7 +44,7 @@ const qs = (req: Request) => (req.originalUrl.includes('?') ? req.originalUrl.sl // ─── Accounts ──────────────────────────────────────────────────────────────── v1Route({ method: 'post', path: '/auth/login/code/resend', tag: 'Accounts', summary: 'Send the sign-in code again', access: 'public', middleware: [loginLimiter], body: loose, v1: users.resendLoginTwoFactor }); -v1Route({ method: 'post', path: '/auth/password/forgot', tag: 'Accounts', summary: 'Email me a link to reset my password', description: 'NOT_FOUND when no account has that email (as v1 does).', access: 'public', body: z.looseObject({ email: z.string().max(200) }), v1: users.requestPasswordReset }); +v1Route({ method: 'post', path: '/auth/password/forgot', tag: 'Accounts', summary: 'Email me a link to reset my password', description: 'Always the same answer, so it doesn\'t say whether an account has that email. Rate-limited like sign-in.', access: 'public', middleware: [loginLimiter], body: z.looseObject({ email: z.string().max(200) }), v1: users.requestPasswordReset }); v1Route({ method: 'post', path: '/auth/password/reset', tag: 'Accounts', summary: 'Set a new password with a reset link', access: 'public', body: loose, v1: users.resetPassword }); v1Route({ method: 'post', path: '/auth/activate', tag: 'Accounts', summary: 'Activate an account with its link', access: 'public', body: loose, v1: users.activateAccount }); v1Route({ method: 'post', path: '/me/sessions/revoke', tag: 'Me', summary: 'Sign out everywhere else', access: 'user', body: loose, v1: users.revokeMySession }); diff --git a/backend/tests/accountEnumeration.test.ts b/backend/tests/accountEnumeration.test.ts new file mode 100644 index 0000000..d804a8f --- /dev/null +++ b/backend/tests/accountEnumeration.test.ts @@ -0,0 +1,83 @@ +/** + * 1.51.17 security fix: nothing public says whether an account exists. Forgot-password answers + * the same for every email (before doing any per-account work), and sign-in with an unknown email + * answers exactly like a wrong password. + */ +const mockDb = { + user: { findUnique: jest.fn(), findFirst: jest.fn(), update: jest.fn() }, + passwordReset: { updateMany: jest.fn(), create: jest.fn() }, +}; +jest.mock('../src/config/db', () => mockDb); +const mockCompare = jest.fn(async () => false); +jest.mock('../src/config/auth', () => ({ comparePassword: (...a: unknown[]) => (mockCompare as jest.Mock)(...a), hashPassword: async () => 'stand-in-hash', generateToken: () => 't' })); +const mockSendMail = jest.fn(async () => undefined); +jest.mock('../src/utils/email', () => ({ sendMail: (...a: unknown[]) => (mockSendMail as jest.Mock)(...a), buildPasswordResetEmail: () => ({ html: '', text: 'reset' }) })); +jest.mock('../src/utils/notify', () => ({ waText: async () => undefined })); +jest.mock('../src/utils/securityEvents', () => ({ logSecurityEvent: async () => undefined, getRecentSecurityEvents: async () => [] })); +jest.mock('../src/utils/whatsapp', () => ({ normalizeZAPhone: () => null, isValidZAPhone: () => false })); + +import { logIn } from '../src/services/auth'; +import { ServiceError } from '../src/services/errors'; +// eslint-disable-next-line @typescript-eslint/no-require-imports +const { requestPasswordReset } = require('../src/controllers/userController'); + +type Answer = { status: number; body: unknown }; +function call(handler: (req: unknown, res: unknown) => Promise, body: object): Promise { + return new Promise(resolve => { + let status = 200; + const res = { + statusCode: 200, + status(n: number) { status = n; this.statusCode = n; return this; }, + json(b: unknown) { resolve({ status, body: b }); return this; }, + }; + handler({ body, headers: {}, ip: '127.0.0.1' }, res); + }); +} + +const realUser = { id: 'u1', name: 'Thandi', email: 'thandi@example.org', isActive: true, password: 'real-hash', failedAttempts: 0, lockUntil: null, role: 'user' }; + +beforeEach(() => jest.clearAllMocks()); + +describe('forgot password', () => { + test('answers the same, with the same status, for an email with and without an account', async () => { + mockDb.user.findUnique.mockResolvedValueOnce(null); + const unknown = await call(requestPasswordReset, { email: 'nobody@example.org' }); + mockDb.user.findUnique.mockResolvedValueOnce(realUser); + const known = await call(requestPasswordReset, { email: realUser.email }); + expect(unknown).toEqual(known); + expect(known.status).toBe(200); + }); + + test('only a real account gets a link, made after the answer is sent', async () => { + mockDb.user.findUnique.mockResolvedValueOnce(null); + await call(requestPasswordReset, { email: 'nobody@example.org' }); + await new Promise(r => setImmediate(r)); + expect(mockDb.passwordReset.create).not.toHaveBeenCalled(); + expect(mockSendMail).not.toHaveBeenCalled(); + + mockDb.user.findUnique.mockResolvedValueOnce(realUser); + const answered = call(requestPasswordReset, { email: realUser.email }); + await answered; + await new Promise(r => setImmediate(r)); + expect(mockDb.passwordReset.create).toHaveBeenCalledTimes(1); + expect(mockSendMail).toHaveBeenCalledWith(expect.objectContaining({ to: realUser.email })); + }); +}); + +describe('sign-in', () => { + const failure = async (p: Promise) => { try { await p; } catch (e) { return e as ServiceError; } throw new Error('expected a refusal'); }; + + test('an unknown email is refused exactly like a wrong password', async () => { + mockDb.user.findFirst.mockResolvedValueOnce(null); + const unknown = await failure(logIn({ identifier: 'nobody@example.org', password: 'x' }, { ip: '1', userAgent: 'jest' })); + mockDb.user.findFirst.mockResolvedValueOnce(realUser); + const wrong = await failure(logIn({ identifier: realUser.email, password: 'x' }, { ip: '1', userAgent: 'jest' })); + expect({ message: unknown.message, status: unknown.statusCode, v1: unknown.v1Status }).toEqual({ message: wrong.message, status: wrong.statusCode, v1: wrong.v1Status }); + }); + + test('an unknown email still does a password check, so it takes as long', async () => { + mockDb.user.findFirst.mockResolvedValueOnce(null); + await failure(logIn({ identifier: 'nobody@example.org', password: 'guess' }, { ip: '1', userAgent: 'jest' })); + expect(mockCompare).toHaveBeenCalledWith('guess', 'stand-in-hash'); + }); +}); diff --git a/docs/HANDOVER.md b/docs/HANDOVER.md index 3617b71..243d74e 100644 --- a/docs/HANDOVER.md +++ b/docs/HANDOVER.md @@ -1,6 +1,6 @@ # Handover — where things stand and how to carry on -Last updated: 2026-10-30, after **1.51.16** (and Hub 1.5.0). The plan itself is in +Last updated: 2026-10-30, after **1.51.17** (and Hub 1.5.0). The plan itself is in [ROADMAP-v2.md](./ROADMAP-v2.md) (decisions table at the end); the previous round of features is in [FEATURES-ROUND-1.md](./FEATURES-ROUND-1.md). @@ -17,6 +17,7 @@ encrypted settings unreadable or break existing installs. | 1.51.3 | **Express 5** (qs query parser and `req.body = {}` kept); scanner and at-the-door on v2 check-in; shared middleware answers v2-shaped on `/api/v2` (`legacyErrorsToV2`, `reason`); v1 `Deprecation` + `successor-version` headers (`src/v2/deprecation.ts`) | | 1.51.2 | **v2 accounts and check-in**: signup, login (+ code step), `PATCH /me`; check-in look-up and scan with `outcome`s. `src/services/auth.ts` (from userController) and `src/services/checkin.ts` (from ticketController); login/signup/profile pages on v2 | | 1.51.1 | **v2 registrations and payments**: register, get, cancel, checkout; create/cancel moved to `src/services/registrations.ts`, online checkout to `src/services/payments.ts` (v1 uses them too); typed frontend calls (`apiV2`, `npm run api:types`); register page, Pay now and My Events cancel on v2 | +| 1.51.17 | **Security:** forgot-password and sign-in don't reveal whether an account exists (same answer, status and timing); forgot-password rate-limited | | 1.51.16 | **Incoming webhooks and message links on v2** — `src/v2/links.ts` (`/api/v2/webhooks/…`, one-click unsubscribe, 308s for old links); provider URLs and email links point at v2 | | 1.51.15 | **Privacy and admin on v2** — `resources/adminPrivacy.ts`; every frontend call on v2; impersonation end/log allowed on v2 while read-only | | 1.51.14 | **People and messaging on v2** — `resources/peopleMessaging.ts`; `/event-listing` for the public pages; `defineRoute` refuses duplicates | diff --git a/e2e/api-v2.spec.ts b/e2e/api-v2.spec.ts index 66d58f4..b0240ff 100644 --- a/e2e/api-v2.spec.ts +++ b/e2e/api-v2.spec.ts @@ -307,9 +307,16 @@ test.describe("API v2", () => { const users = (await (await request.get(`${API}/api/v2/users?page=1&limit=2`, { headers: sup })).json()).data; expect(users).toMatchObject({ page: 1, limit: 2 }); - // As v1: an unknown email is NOT_FOUND. - const forgot = await request.post(`${API}/api/v2/auth/password/forgot`, { data: { email: "nobody-e2e@example.com" } }); - expect((await forgot.json()).error.code).toBe("NOT_FOUND"); + // Forgot-password doesn't say whether an account exists (1.51.17): the same answer either way. + const unknown = await request.post(`${API}/api/v2/auth/password/forgot`, { data: { email: "nobody-e2e@example.com" } }); + const known = await request.post(`${API}/api/v2/auth/password/forgot`, { data: { email: seed().users.user.email } }); + expect(unknown.status()).toBe(200); + expect(await unknown.json()).toEqual(await known.json()); + // Nor does sign-in: an unknown email is refused like a wrong password. + const noAccount = await request.post(`${API}/api/v2/auth/login`, { data: { identifier: "nobody-e2e@example.com", password: "Wrong-password-1" } }); + const wrongPassword = await request.post(`${API}/api/v2/auth/login`, { data: { identifier: seed().users.user.email, password: "Wrong-password-1" } }); + expect(noAccount.status()).toBe(wrongPassword.status()); + expect(await noAccount.json()).toEqual(await wrongPassword.json()); }); test("privacy and admin: settings, my data, the audit log, webhooks, backups", async ({ request }) => { diff --git a/frontend/src/lib/api-v2/openapi.json b/frontend/src/lib/api-v2/openapi.json index 406d09e..505071a 100644 --- a/frontend/src/lib/api-v2/openapi.json +++ b/frontend/src/lib/api-v2/openapi.json @@ -29239,7 +29239,7 @@ "Accounts" ], "summary": "Email me a link to reset my password", - "description": "NOT_FOUND when no account has that email (as v1 does).\n\n**Who:** Anyone.", + "description": "Always the same answer, so it doesn't say whether an account has that email. Rate-limited like sign-in.\n\n**Who:** Anyone.", "operationId": "postAuthPasswordForgot", "parameters": [], "requestBody": { diff --git a/frontend/src/lib/api-v2/schema.d.ts b/frontend/src/lib/api-v2/schema.d.ts index aeb5aa4..d94cd79 100644 --- a/frontend/src/lib/api-v2/schema.d.ts +++ b/frontend/src/lib/api-v2/schema.d.ts @@ -4509,7 +4509,7 @@ export interface paths { put?: never; /** * Email me a link to reset my password - * @description NOT_FOUND when no account has that email (as v1 does). + * @description Always the same answer, so it doesn't say whether an account has that email. Rate-limited like sign-in. * * **Who:** Anyone. */ From d49aebb1b0ad4cb602b480454f55aeb4bf3e5db6 Mon Sep 17 00:00:00 2001 From: joshua Date: Fri, 30 Oct 2026 08:51:41 +0200 Subject: [PATCH 2/2] Security: forgot password and sign-in don't reveal accounts (1.51.17) - Forgot password answers the same (message, status, timing) for every email; the reset link is made and sent after the answer. Rate-limited like sign-in. - Sign-in with an unknown email is refused exactly like a wrong password, after a password check against a stand-in hash. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot --- backend/package-lock.json | 4 ++-- backend/package.json | 2 +- frontend/package-lock.json | 4 ++-- frontend/package.json | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/backend/package-lock.json b/backend/package-lock.json index 338fb8b..2c49bba 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -1,12 +1,12 @@ { "name": "event-management-backend", - "version": "1.51.16", + "version": "1.51.17", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "event-management-backend", - "version": "1.51.16", + "version": "1.51.17", "hasInstallScript": true, "dependencies": { "@cj-tech-master/excelts": "^10.2.0", diff --git a/backend/package.json b/backend/package.json index 1c30f4b..970b39e 100644 --- a/backend/package.json +++ b/backend/package.json @@ -1,6 +1,6 @@ { "name": "event-management-backend", - "version": "1.51.16", + "version": "1.51.17", "description": "Event Management System Backend", "main": "src/index.js", "scripts": { diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 20c7489..b505e04 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "hope-events-frontend", - "version": "1.51.16", + "version": "1.51.17", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "hope-events-frontend", - "version": "1.51.16", + "version": "1.51.17", "dependencies": { "@dnd-kit/core": "^6.3.1", "@hookform/resolvers": "^5.2.1", diff --git a/frontend/package.json b/frontend/package.json index 5e4b402..e2a975f 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "hope-events-frontend", - "version": "1.51.16", + "version": "1.51.17", "private": true, "scripts": { "dev": "next dev", diff --git a/package-lock.json b/package-lock.json index 6f5c5eb..870efcf 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "hope-events", - "version": "1.51.16", + "version": "1.51.17", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "hope-events", - "version": "1.51.16", + "version": "1.51.17", "license": "ISC", "devDependencies": { "@axe-core/playwright": "^4.14.0", diff --git a/package.json b/package.json index 2fc678d..01028c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "hope-events", - "version": "1.51.16", + "version": "1.51.17", "main": "index.js", "scripts": { "dev:backend": "cd backend && npm run dev",