fix(auth): bind a password reset link to the address it was mailed to

The reset request reads the account's address again inside the transaction that issues the link, and the link stores that address, so a link raced past an email change no longer resets the moved account. Links issued before this keep working until they expire.
This commit is contained in:
Maurice
2026-11-28 00:29:32 +01:00
parent 218304179c
commit 6bbe597719
9 changed files with 177 additions and 7 deletions
@@ -13,6 +13,7 @@ export class PasswordResetTokens {
consumed_at?: string | null;
created_at?: string | null;
created_ip?: string | null;
email?: string | null;
}
export const PasswordResetTokensSchema = defineEntity({
@@ -28,5 +29,6 @@ export const PasswordResetTokensSchema = defineEntity({
consumed_at: p.type(DbTimestampType).nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
created_ip: p.text().nullable(),
email: p.text().nullable(),
},
});
@@ -10,4 +10,5 @@ export interface PasswordResetTokensTable {
consumed_at: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
created_ip: InsertOptional<string | null>;
email: InsertOptional<string | null>;
}
@@ -0,0 +1,21 @@
import { engineDdl } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* A password reset link remembers the address it was mailed to, so it stops
* working once the account has moved to another address.
*
* `password_reset_tokens.email` holds the account's address at the moment the
* link was issued. Every link issued before this step starts empty and keeps
* working until it expires or is used, as it did before.
*/
export class Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to extends Migration {
override name = 'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to';
override up(): void {
engineDdl(this, {
sqlite: ['ALTER TABLE password_reset_tokens ADD COLUMN email TEXT'],
postgres: ['alter table "password_reset_tokens" add column "email" text null'],
});
}
}
@@ -13,6 +13,7 @@ export interface PasswordResetTokenRow {
consumed_at: string | null;
created_at: string | null;
created_ip: string | null;
email: string | null;
}
const _passwordResetTokenRowKeys: AssertRowKeys<PasswordResetTokenRow, PasswordResetTokens> = true;
@@ -23,6 +24,7 @@ export interface NewPasswordResetTokenRow {
token_hash: string;
expires_at: DbTimestamp;
created_ip: string | null;
email: string;
}
/** `AuthService.resetPassword`'s lookup (AU39). */
@@ -31,6 +33,7 @@ export interface PasswordResetTokenLookup {
user_id: number;
expires_at: string;
consumed_at: string | null;
email: string | null;
}
/**
@@ -78,6 +81,7 @@ export class PasswordResetTokensRepository extends TrekRepository<PasswordResetT
token_hash: row.token_hash,
expires_at: row.expires_at,
created_ip: row.created_ip,
email: row.email,
});
}
@@ -101,9 +105,18 @@ export class PasswordResetTokensRepository extends TrekRepository<PasswordResetT
* query.
*/
async findByTokenHash(hash: string): Promise<PasswordResetTokenLookup | null> {
const row = await this.findOne({ token_hash: hash }, { fields: ['id', 'user', 'expires_at', 'consumed_at'] });
const row = await this.findOne(
{ token_hash: hash },
{ fields: ['id', 'user', 'expires_at', 'consumed_at', 'email'] },
);
return row
? { id: row.id, user_id: row.user.id, expires_at: row.expires_at, consumed_at: row.consumed_at ?? null }
? {
id: row.id,
user_id: row.user.id,
expires_at: row.expires_at,
consumed_at: row.consumed_at ?? null,
email: row.email ?? null,
}
: null;
}
+18 -3
View File
@@ -987,11 +987,22 @@ export class AuthService {
const token_hash = hashResetToken(raw);
const expires_at = dbNow(new Date(Date.now() + PASSWORD_RESET_TTL_MS));
// Invalidate any prior unconsumed tokens for this user and issue the new one
// together, so there is always exactly one live reset link in flight.
await this.uow.transactional(async () => {
// together, so there is always exactly one live reset link in flight. The
// address is read again here: one changed since the lookup gets no link.
const issued = await this.uow.transactional(async () => {
const current = await this.usersRepo.getEmail(user.id);
if (current === null || current.toLowerCase() !== user.email.toLowerCase()) return false;
await this.passwordResetTokens.consumeAllLiveForUser(user.id);
await this.passwordResetTokens.insertToken({ user_id: user.id, token_hash, expires_at, created_ip: createdIp });
await this.passwordResetTokens.insertToken({
user_id: user.id,
token_hash,
expires_at,
created_ip: createdIp,
email: user.email,
});
return true;
});
if (!issued) return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'no_user' };
return { tokenForDelivery: raw, userId: user.id, userEmail: user.email, reason: 'issued' };
}
@@ -1028,6 +1039,10 @@ export class AuthService {
const user = await this.usersRepo.findResetTarget(row.user_id);
if (!user) throw new DomainError(400, 'Invalid or expired reset link');
// A link mailed to an address the account no longer has is dead.
if (row.email !== null && row.email.toLowerCase() !== user.email.toLowerCase()) {
throw new DomainError(400, 'Invalid or expired reset link');
}
// MFA gate. If enabled, require a valid TOTP or backup code.
const mfaOn = user.mfa_enabled === 1;