Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(auth): retire password reset links when the account's email or password changes

Maurice4f66a344ca3d
diff --git a/server/src/nest/admin/admin.service.ts b/server/src/nest/admin/admin.service.ts
index 2c534e0bf..2b01897fb 100644
--- a/server/src/nest/admin/admin.service.ts
+++ b/server/src/nest/admin/admin.service.ts
@@ -275,7 +275,8 @@ export class AdminService {
// An address the admin enters is one the admin vouches for, so an SSO sign-in
// may link to it again. The edit dialog sends the email on every save, so only
// a new address counts, not the unchanged one or the same one in another case.
- if (email && email.toLowerCase() !== user.email.toLowerCase()) patch.email_self_asserted = 0;
+ const emailChanged = !!email && email.toLowerCase() !== user.email.toLowerCase();
+ if (emailChanged) patch.email_self_asserted = 0;
if (role) patch.role = role;
if (password) {
patch.password_hash = passwordHash!;
@@ -302,6 +303,9 @@ export class AdminService {
}
}
await this.users.applyAdminEdit(userId, patch);
+ // A reset link sent to the old address, or asked for before the admin set
+ // a password, must not reopen the account afterwards.
+ if (emailChanged || password) await this.auth.retirePasswordResetLinks(userId);
if (password) {
// The version bump only invalidates JWT cookies. These two stores carry
diff --git a/server/src/nest/auth/auth.service.ts b/server/src/nest/auth/auth.service.ts
index 65c3a8e34..6a31966f8 100644
--- a/server/src/nest/auth/auth.service.ts
+++ b/server/src/nest/auth/auth.service.ts
@@ -209,6 +209,7 @@ export class AuthService {
// Reset-email delivery (canonical app URL, never request headers)
getAppUrl() { return getAppUrl(); }
sendPasswordResetEmail(email: string, url: string, userId: number | null) { return this.mailer.sendPasswordResetEmail(email, url, userId); }
+ retirePasswordResetLinks(userId: number) { return this.passwordResetTokens.consumeAllLiveForUser(userId); }
// -------------------------------------------------------------------------
// Toggles + tokens
@@ -651,9 +652,8 @@ export class AuthService {
await this.uow.transactional(async () => {
await this.usersRepo.setPassword(userId, hash, newPv);
- // A password change ends every session (the pv bump covers the tokens from
- // before sessions were tracked) and prunes the MCP static token and OAuth
- // bearer-token stores to match, the same set the password reset revokes.
+ // Ends every session, reset link, MCP and OAuth token, the same set the password reset revokes.
+ await this.retirePasswordResetLinks(userId);
await this.mcpTokens.deleteAllForUser(userId);
try { await this.oauthTokens.revokeAllForUser(userId); } catch { /* no oauth_tokens in very old installs */ }
// Push devices keep receiving notifications without any session, so they
diff --git a/server/src/nest/auth/user-profile.service.ts b/server/src/nest/auth/user-profile.service.ts
index 66bc28076..484555bf8 100644
--- a/server/src/nest/auth/user-profile.service.ts
+++ b/server/src/nest/auth/user-profile.service.ts
@@ -1,7 +1,9 @@
import { readEnv, getAppUrl } from '../../app-config';
import { AppSettings } from '../../db/entities/AppSettings.entity';
+import { PasswordResetTokens } from '../../db/entities/PasswordResetTokens.entity';
import { Users } from '../../db/entities/Users.entity';
import type { AppSettingsRepository } from '../../db/repositories/AppSettings.repository';
+import type { PasswordResetTokensRepository } from '../../db/repositories/PasswordResetTokens.repository';
import {
UserIdentityTakenError,
type UsersRepository,
@@ -58,6 +60,7 @@ export class UserProfileService {
private readonly uow: UnitOfWork,
@InjectRepository(AppSettings) private readonly appSettings: AppSettingsRepository,
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
+ @InjectRepository(PasswordResetTokens) private readonly passwordResetTokens: PasswordResetTokensRepository,
) {}
/**
@@ -282,6 +285,9 @@ export class UserProfileService {
try {
await this.uow.transactional(async () => {
await this.usersRepo.patchProfile(userId, changes);
+ // A reset link is a credential sent to the address the account had,
+ // so it must not outlive the move to another one.
+ if (emailChanged) await this.passwordResetTokens.consumeAllLiveForUser(userId);
if (!keyLocked) await this.mirrorInstanceKeys(body, isAdmin);
});
} catch (err) {
diff --git a/server/tests/integration/password-reset-link-retirement.test.ts b/server/tests/integration/password-reset-link-retirement.test.ts
new file mode 100644
index 000000000..42afc790f
--- /dev/null
+++ b/server/tests/integration/password-reset-link-retirement.test.ts
@@ -0,0 +1,136 @@
+/**
+ * A password reset link is a credential delivered to the account's email
+ * address. Once the account's address or password changes, a link sent
+ * before that must stop working, whoever changed it: the user in their own
+ * settings or an admin in the user list. A link requested afterwards works.
+ *
+ * Boots the whole app and drives the registered routes; only the delivery of
+ * the reset mail is replaced, so the test can read the link from it.
+ */
+import { buildApp } from '../../src/bootstrap';
+import { AuthService } from '../../src/nest/auth/auth.service';
+import { authCookie } from '../helpers/auth';
+import type { FactoryOrm } from '../helpers/factories/context';
+import { makeAdmin, makeUser } from '../helpers/factories/users';
+import { resetDatabase } from '../helpers/reset-database';
+import { resetRateLimits } from '../helpers/test-db';
+import { MikroORM } from '@mikro-orm/core';
+import type { INestApplication } from '@nestjs/common';
+
+import type { Application } from 'express';
+import request from 'supertest';
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+let nestApp: INestApplication;
+let app: Application;
+let orm: FactoryOrm;
+let delivered: { email: string; url: string }[];
+
+beforeAll(async () => {
+ nestApp = await buildApp();
+ app = nestApp.getHttpAdapter().getInstance();
+ orm = nestApp.get(MikroORM);
+ vi.spyOn(nestApp.get(AuthService), 'sendPasswordResetEmail').mockImplementation(async (email, url) => {
+ delivered.push({ email, url });
+ return { delivered: 'email' };
+ });
+});
+
+beforeEach(async () => {
+ await resetDatabase(orm);
+ await resetRateLimits(nestApp);
+ delivered = [];
+});
+
+afterAll(async () => {
+ vi.restoreAllMocks();
+ await nestApp.close();
+});
+
+/** Asks for a reset link for this address and returns the token in it. */
+async function resetToken(email: string): Promise<string> {
+ const before = delivered.length;
+ const res = await request(app).post('/api/auth/forgot-password').send({ email });
+ expect(res.status).toBe(200);
+ expect(delivered).toHaveLength(before + 1);
+ expect(delivered[before].email).toBe(email);
+ const token = new URL(delivered[before].url).searchParams.get('token');
+ expect(token).toBeTruthy();
+ return token as string;
+}
+
+function useToken(token: string, newPassword: string) {
+ return request(app).post('/api/auth/reset-password').send({ token, new_password: newPassword });
+}
+
+describe('password reset links after the account changes', () => {
+ it('PWRESET-RETIRE-001: a link sent to the old address stops working once the user changes their email', async () => {
+ const { user } = await makeUser(orm);
+ const oldLink = await resetToken(user.email);
+
+ const changed = await request(app)
+ .put('/api/auth/me/settings')
+ .set('Cookie', authCookie(user.id))
+ .send({ email: '[email protected]' });
+ expect(changed.status).toBe(200);
+
+ const reset = await useToken(oldLink, 'Recovered2026!x');
+ expect(reset.status).toBe(400);
+ const login = await request(app)
+ .post('/api/auth/login')
+ .send({ email: '[email protected]', password: 'Recovered2026!x' });
+ expect(login.status).toBe(401);
+
+ // A link sent to the new address works.
+ const freshLink = await resetToken('[email protected]');
+ expect((await useToken(freshLink, 'Current2026!x')).status).toBe(200);
+ });
+
+ it('PWRESET-RETIRE-002: saving the same address, or it in another case, keeps the link', async () => {
+ const { user } = await makeUser(orm);
+ const link = await resetToken(user.email);
+
+ const saved = await request(app)
+ .put('/api/auth/me/settings')
+ .set('Cookie', authCookie(user.id))
+ .send({ email: user.email.toUpperCase(), username: 'renamed_user' });
+ expect(saved.status).toBe(200);
+
+ expect((await useToken(link, 'StillMine2026!x')).status).toBe(200);
+ });
+
+ it('PWRESET-RETIRE-003: a link stops working once the user changes their password', async () => {
+ const { user, password } = await makeUser(orm);
+ const link = await resetToken(user.email);
+
+ const changed = await request(app)
+ .put('/api/auth/me/password')
+ .set('Cookie', authCookie(user.id))
+ .send({ current_password: password, new_password: 'Changed2026!x' });
+ expect(changed.status).toBe(200);
+
+ expect((await useToken(link, 'Recovered2026!x')).status).toBe(400);
+ });
+
+ it("PWRESET-RETIRE-004: a link stops working once an admin changes the user's email or sets a password", async () => {
+ const { user: admin } = await makeAdmin(orm);
+ const { user: emailUser } = await makeUser(orm);
+ const { user: passwordUser } = await makeUser(orm);
+ const emailLink = await resetToken(emailUser.email);
+ const passwordLink = await resetToken(passwordUser.email);
+
+ const moved = await request(app)
+ .put(`/api/admin/users/${emailUser.id}`)
+ .set('Cookie', authCookie(admin.id))
+ .send({ email: '[email protected]' });
+ expect(moved.status).toBe(200);
+ const reset = await request(app)
+ .put(`/api/admin/users/${passwordUser.id}`)
+ .set('Cookie', authCookie(admin.id))
+ .send({ password: 'AdminSet2026!x' });
+ expect(reset.status).toBe(200);
+
+ expect((await useToken(emailLink, 'Recovered2026!x')).status).toBe(400);
+ expect((await useToken(passwordLink, 'Recovered2026!x')).status).toBe(400);
+ });
+});
diff --git a/server/tests/unit/nest/user-profile.service.test.ts b/server/tests/unit/nest/user-profile.service.test.ts
index c658c3a9a..7c6bca3fa 100644
--- a/server/tests/unit/nest/user-profile.service.test.ts
+++ b/server/tests/unit/nest/user-profile.service.test.ts
@@ -17,6 +17,7 @@ import { resetTestDb } from '../../helpers/test-db';
import {
createTestUnitOfWork,
createTestAppSettingsRepo,
+ createTestPasswordResetTokensRepo,
createTestUsersRepo,
sharedTestOrm,
} from '../../helpers/test-uow';
@@ -69,6 +70,7 @@ beforeAll(async () => {
await createTestUnitOfWork(testDb),
await createTestAppSettingsRepo(testDb),
await createTestUsersRepo(testDb),
+ await createTestPasswordResetTokensRepo(testDb),
);
});