From d9b0667abdfccc60cddb6b687132a6918f4c3051 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 4 Dec 2026 22:48:58 -0500 Subject: [PATCH 1/2] fix(otp): store one-time codes per attempt and verify under a row lock --- .changeset/per-attempt-one-time-codes.md | 15 + src/controllers/admin.ts | 4 - src/controllers/magicLinks.ts | 6 +- src/controllers/otp.ts | 26 +- src/controllers/registration.ts | 12 +- .../20261204120000-add-one-time-codes.cjs | 56 ++ src/models/accountRecoveryRequests.ts | 8 + src/models/oneTimeCodes.ts | 79 ++ src/models/users.ts | 24 - src/services/accountClaim.ts | 36 +- src/services/accountRecoveryService.ts | 62 +- src/services/oauthService.ts | 23 +- src/utils/otp.ts | 274 ++++--- tests/e2e/authFlow.spec.ts | 9 +- tests/factories/accountRecoveryStore.ts | 5 + tests/factories/userFactory.ts | 2 + tests/integration/admin/admin.spec.ts | 7 +- .../authentication/decoyParity.spec.ts | 4 - .../integration/breakGlass/breakGlass.spec.ts | 5 +- tests/integration/magicLink/magicLink.spec.ts | 28 + tests/integration/otp/otp.security.spec.ts | 9 +- tests/integration/otp/otp.spec.ts | 2 + .../recovery/accountRecovery.spec.ts | 3 + .../integration/registration/register.spec.ts | 69 +- tests/postgres/accountRecovery.spec.ts | 47 ++ tests/postgres/oneTimeCodes.spec.ts | 107 +++ tests/postgres/oneTimeCredentials.spec.ts | 31 +- tests/postgres/unverifiedPhoneClaim.spec.ts | 10 +- tests/setup/mocks.ts | 18 +- tests/unit/controllers/otp.spec.ts | 116 ++- tests/unit/models/models.spec.ts | 1 + tests/unit/services/accountClaim.spec.ts | 74 +- .../services/accountRecoveryService.spec.ts | 70 +- tests/unit/services/oauthIdToken.spec.ts | 13 +- tests/unit/services/oauthService.spec.ts | 45 +- tests/unit/utils/otp.spec.ts | 750 +++++++++++------- 36 files changed, 1441 insertions(+), 609 deletions(-) create mode 100644 .changeset/per-attempt-one-time-codes.md create mode 100644 src/migrations/20261204120000-add-one-time-codes.cjs create mode 100644 src/models/oneTimeCodes.ts create mode 100644 tests/postgres/oneTimeCodes.spec.ts diff --git a/.changeset/per-attempt-one-time-codes.md b/.changeset/per-attempt-one-time-codes.md new file mode 100644 index 00000000..e86dabb7 --- /dev/null +++ b/.changeset/per-attempt-one-time-codes.md @@ -0,0 +1,15 @@ +--- +'seamless-auth-api': minor +--- + +One-time codes are now stored per sign-in or registration attempt instead of in a single slot on the user. + +Before, every email and phone code for an account lived in one pair of columns on `users`. Starting a flow for an address replaced the code the owner was waiting on, and a recovery resume wrote its code over the open request's. Now: + +- A new `one_time_codes` table holds each code hashed, keyed by user, channel and the attempt that asked for it (the ephemeral token's attempt, or the access session). Sending again for the same attempt replaces only that attempt's code. +- **Breaking:** a code verifies only on the attempt that requested it. A client that starts a new attempt (a second `POST /login`, for example) must send a new code on that attempt rather than submit one sent to the earlier one. +- A code also verifies only while the account still holds the address it was sent to. +- Spending a code and applying the verification happen under a lock on the user row, so a verification and an account claim racing each other can no longer act on a stale copy of the account. Magic link and OAuth claims take the same lock. +- Account recovery always opens its own `awaiting_code` request. A resume records the request it resumes (`resumesRequestId`) and no longer replaces the owner's code on it. + +The migration adds the table and the column. The old code columns on `users` stay in place and are no longer read, so an instance on the previous release keeps working during a rolling deploy. A code sent by the previous release does not verify on this one; it expires within five minutes and a new one can be sent. diff --git a/src/controllers/admin.ts b/src/controllers/admin.ts index 14ddbd81..e45652d5 100644 --- a/src/controllers/admin.ts +++ b/src/controllers/admin.ts @@ -330,8 +330,6 @@ export const updateUser = async (req: ServiceRequest, res: Response) => { if (nextPhone === null) { updateData.phone = null; updateData.phoneVerified = false; - updateData.phoneVerificationToken = null; - updateData.phoneVerificationTokenExpiry = null; } else if (typeof nextPhone === 'string') { const normalizedPhone = normalizePhoneNumber(nextPhone); @@ -343,8 +341,6 @@ export const updateUser = async (req: ServiceRequest, res: Response) => { } updateData.phone = normalizedPhone; - updateData.phoneVerificationToken = null; - updateData.phoneVerificationTokenExpiry = null; if (normalizedPhone !== user.phone && !phoneVerifiedSupplied) { updateData.phoneVerified = false; diff --git a/src/controllers/magicLinks.ts b/src/controllers/magicLinks.ts index f353b6e3..76515196 100644 --- a/src/controllers/magicLinks.ts +++ b/src/controllers/magicLinks.ts @@ -17,7 +17,7 @@ import { MagicLinkConfirmBodySchema, MagicLinkRequestQuerySchema, } from '../schemas/magiclink.requests.js'; -import { claimUnverifiedAccount } from '../services/accountClaim.js'; +import { claimUnverifiedAccount, withLockedUser } from '../services/accountClaim.js'; import { AuthEventService } from '../services/authEventService.js'; import { rejectWeakFactorForBreakGlass } from '../services/breakGlassService.js'; import { passkeyEnrollmentPrompt } from '../services/enrollmentService.js'; @@ -469,9 +469,7 @@ export async function pollMagicLinkConfirmation(req: Request, res: Response) { req, }); - claimUnverifiedAccount(user, authReq.attemptId); - - await user.save(); + await withLockedUser(user, (locked) => claimUnverifiedAccount(locked, authReq.attemptId)); // A different route completed the sign-in, so any half-finished WebAuthn // ceremony for this user should not still be redeemable. diff --git a/src/controllers/otp.ts b/src/controllers/otp.ts index fa2f4e98..d06b082c 100644 --- a/src/controllers/otp.ts +++ b/src/controllers/otp.ts @@ -26,6 +26,7 @@ import getLogger from '../utils/logger.js'; import { generateEmailOTP, generatePhoneOTP, + hasPendingOtp, verifyEmailOTP, verifyPhoneOTP, } from '../utils/otp.js'; @@ -100,7 +101,7 @@ export const sendPhoneOTP = async (req: Request, res: Response) => { // Re-minted with the attempt it arrived on, so a resend neither starts a new one nor // extends it. Before the send, so an attempt that cannot continue sends nothing. const token = await reissueEphemeralToken(user.id, authReq); - const generatedToken = await generatePhoneOTP(user, { + const generatedToken = await generatePhoneOTP(user, authReq, { sendMessage: !useExternalDelivery, }); @@ -177,7 +178,7 @@ export const sendEmailOTP = async (req: Request, res: Response) => { logger.info('User requested an email OTP'); const token = await reissueEphemeralToken(user.id, authReq); - const generatedToken = await generateEmailOTP(user, { + const generatedToken = await generateEmailOTP(user, authReq, { sendMessage: !useExternalDelivery, }); await AuthEventService.log({ @@ -312,7 +313,7 @@ export const verifyPhoneNumber = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Not allowed' }); } - if (!user || !user.phoneVerificationTokenExpiry || !user.phoneVerificationToken) { + if (!(await hasPendingOtp(user, 'phone', authReq))) { logger.warn('Failed to find a user for this phone verification token'); await AuthEventService.log({ userId: user.id, @@ -335,7 +336,10 @@ export const verifyPhoneNumber = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Not allowed' }); } - const verificationResult = await verifyPhoneOTP(user, verificationToken, authReq.attemptId); + const verificationResult = await verifyPhoneOTP(user, verificationToken, authReq, { + attemptId: authReq.attemptId, + unverifiedOnly: true, + }); user = verificationResult.user; const verified = verificationResult.verified; @@ -404,7 +408,7 @@ export const verifyEmail = async (req: Request, res: Response) => { logger.info('Verifying email'); - if (!user || !user.emailVerificationTokenExpiry || !user.emailVerificationToken) { + if (!(await hasPendingOtp(user, 'email', authReq))) { logger.warn(`Failed to find a user for this email verification token`); await AuthEventService.log({ userId: user.id, @@ -437,7 +441,9 @@ export const verifyEmail = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Not allowed' }); } - const verificationResult = await verifyEmailOTP(user, verificationToken, authReq.attemptId); + const verificationResult = await verifyEmailOTP(user, verificationToken, authReq, { + attemptId: authReq.attemptId, + }); user = verificationResult.user; const verified = verificationResult.verified; @@ -532,7 +538,7 @@ export const verifyLoginPhoneNumber = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Not allowed' }); } - if (!user || !user.phoneVerificationTokenExpiry || !user.phoneVerificationToken) { + if (!(await hasPendingOtp(user, 'phone', authReq))) { logger.warn('Failed to find a user for this phone verification token'); await AuthEventService.log({ userId: user.id, @@ -555,7 +561,7 @@ export const verifyLoginPhoneNumber = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Not allowed' }); } - const verificationResult = await verifyPhoneOTP(user, verificationToken); + const verificationResult = await verifyPhoneOTP(user, verificationToken, authReq); user = verificationResult.user; const verified = verificationResult.verified; @@ -632,7 +638,7 @@ export const verifyLoginEmail = async (req: Request, res: Response) => { logger.info('Verifying login email'); - if (!user || !user.emailVerificationTokenExpiry || !user.emailVerificationToken) { + if (!(await hasPendingOtp(user, 'email', authReq))) { logger.warn(`Failed to find a user for this email verification token`); await AuthEventService.log({ userId: user.id, @@ -665,7 +671,7 @@ export const verifyLoginEmail = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Not allowed' }); } - const verificationResult = await verifyEmailOTP(user, verificationToken); + const verificationResult = await verifyEmailOTP(user, verificationToken, authReq); user = verificationResult.user; const verified = verificationResult.verified; diff --git a/src/controllers/registration.ts b/src/controllers/registration.ts index e2090a16..1d62970b 100644 --- a/src/controllers/registration.ts +++ b/src/controllers/registration.ts @@ -20,7 +20,7 @@ import { registrationDecoySubjectFor } from '../services/decoyPrincipal.js'; import { DeliveryError } from '../services/deliveryError.js'; import { AuthenticatedRequest } from '../types/types.js'; import getLogger from '../utils/logger.js'; -import { generateEmailOTP, generatePhoneOTP, verifyPhoneOTP } from '../utils/otp.js'; +import { generateEmailOTP, generatePhoneOTP, hasPendingOtp, verifyPhoneOTP } from '../utils/otp.js'; import { isValidEmail, isValidPhoneNumber, normalizePhoneNumber } from '../utils/utils.js'; const logger = getLogger('registration'); @@ -40,7 +40,7 @@ async function sendRegistrationEmailOtp( let otp: string; try { - otp = await generateEmailOTP(user, { sendMessage }); + otp = await generateEmailOTP(user, { attemptId }, { sendMessage }); } catch (error) { if (error instanceof DeliveryError) { await AuthEventService.log({ @@ -330,8 +330,6 @@ export const registerPhone = async (req: Request, res: Response) => { await user.update({ phone: normalizedPhone, phoneVerified: phoneChanged ? false : user.phoneVerified, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, }); user.phone = normalizedPhone; @@ -341,7 +339,7 @@ export const registerPhone = async (req: Request, res: Response) => { const shouldSendVerification = phoneChanged || !user.phoneVerified; const phoneOtp = shouldSendVerification - ? await generatePhoneOTP(user, { sendMessage: !useExternalDelivery }) + ? await generatePhoneOTP(user, authReq, { sendMessage: !useExternalDelivery }) : null; await AuthEventService.log({ @@ -387,7 +385,7 @@ export const verifyRegisteredPhone = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Unauthorized' }); } - if (!user.phone || !user.phoneVerificationTokenExpiry || !user.phoneVerificationToken) { + if (!user.phone || !(await hasPendingOtp(user, 'phone', authReq))) { await AuthEventService.log({ userId: user.id, type: 'verify_otp_suspicious', @@ -410,7 +408,7 @@ export const verifyRegisteredPhone = async (req: Request, res: Response) => { } try { - const verificationResult = await verifyPhoneOTP(user, verificationToken); + const verificationResult = await verifyPhoneOTP(user, verificationToken, authReq); if (!verificationResult.verified) { await AuthEventService.log({ diff --git a/src/migrations/20261204120000-add-one-time-codes.cjs b/src/migrations/20261204120000-add-one-time-codes.cjs new file mode 100644 index 00000000..a05cd7dc --- /dev/null +++ b/src/migrations/20261204120000-add-one-time-codes.cjs @@ -0,0 +1,56 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +'use strict'; + +/** + * One-time codes stored per attempt rather than in one slot on the user, so a send from one + * attempt no longer replaces the code another attempt is waiting on. The old columns on + * `users` are left in place, unread, so an instance still running the previous release + * keeps working during a rolling deploy. + * + * A recovery resume code gets its own row pointing at the request it resumes, for the same + * reason: written onto the open request, it replaced the owner's. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + CREATE TABLE IF NOT EXISTS public.one_time_codes ( + id uuid NOT NULL, + "userId" uuid NOT NULL, + channel character varying(16) NOT NULL, + "attemptKey" character varying(255) NOT NULL, + destination character varying(255) NOT NULL, + "codeHash" character varying(255) NOT NULL, + "expiresAt" timestamp with time zone NOT NULL, + "createdAt" timestamp with time zone NOT NULL, + "updatedAt" timestamp with time zone NOT NULL, + CONSTRAINT one_time_codes_pkey PRIMARY KEY (id), + CONSTRAINT "one_time_codes_userId_fkey" + FOREIGN KEY ("userId") REFERENCES public.users(id) ON UPDATE CASCADE ON DELETE CASCADE + ); + + CREATE UNIQUE INDEX IF NOT EXISTS idx_one_time_codes_attempt + ON public.one_time_codes USING btree ("userId", channel, "attemptKey"); + + CREATE INDEX IF NOT EXISTS idx_one_time_codes_expires + ON public.one_time_codes USING btree ("expiresAt"); + + ALTER TABLE public.account_recovery_requests + ADD COLUMN IF NOT EXISTS "resumesRequestId" uuid + REFERENCES public.account_recovery_requests(id) ON UPDATE CASCADE ON DELETE CASCADE; + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + ALTER TABLE public.account_recovery_requests DROP COLUMN IF EXISTS "resumesRequestId"; + DROP TABLE IF EXISTS public.one_time_codes; + `); + }, +}; diff --git a/src/models/accountRecoveryRequests.ts b/src/models/accountRecoveryRequests.ts index f54021ff..c8837a9a 100644 --- a/src/models/accountRecoveryRequests.ts +++ b/src/models/accountRecoveryRequests.ts @@ -20,6 +20,8 @@ export interface AccountRecoveryRequestAttributes { channel: RecoveryChannel; state: StoredRecoveryState; attemptId?: string | null; + // Set on a code issued to resume an open request, which the code row points at. + resumesRequestId?: string | null; codeAttemptId?: string | null; codeHash?: string | null; codeExpiresAt?: Date | null; @@ -37,6 +39,7 @@ type AccountRecoveryRequestCreationAttributes = Optional< AccountRecoveryRequestAttributes, | 'id' | 'attemptId' + | 'resumesRequestId' | 'codeAttemptId' | 'codeHash' | 'codeExpiresAt' @@ -57,6 +60,7 @@ export class AccountRecoveryRequest declare channel: RecoveryChannel; declare state: StoredRecoveryState; declare attemptId: string | null; + declare resumesRequestId: string | null; declare codeAttemptId: string | null; declare codeHash: string | null; declare codeExpiresAt: Date | null; @@ -94,6 +98,10 @@ const initializeAccountRecoveryRequestModel = (sequelize: Sequelize) => { type: DataTypes.STRING, allowNull: true, }, + resumesRequestId: { + type: DataTypes.UUID, + allowNull: true, + }, codeAttemptId: { type: DataTypes.STRING, allowNull: true, diff --git a/src/models/oneTimeCodes.ts b/src/models/oneTimeCodes.ts new file mode 100644 index 00000000..42d2e92f --- /dev/null +++ b/src/models/oneTimeCodes.ts @@ -0,0 +1,79 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +import { + CreationOptional, + DataTypes, + InferAttributes, + InferCreationAttributes, + Model, + Sequelize, +} from 'sequelize'; + +export type OneTimeCodeChannel = 'email' | 'phone'; + +export class OneTimeCode extends Model< + InferAttributes, + InferCreationAttributes +> { + declare id: CreationOptional; + declare userId: string; + declare channel: OneTimeCodeChannel; + declare attemptKey: string; + // The address the code was sent to. A code only verifies while it is still the account's. + declare destination: string; + declare codeHash: string; + declare expiresAt: Date; + declare createdAt: CreationOptional; + declare updatedAt: CreationOptional; +} + +const initializeOneTimeCodeModel = (sequelize: Sequelize) => { + OneTimeCode.init( + { + id: { + type: DataTypes.UUID, + primaryKey: true, + defaultValue: DataTypes.UUIDV4, + }, + userId: { + type: DataTypes.UUID, + allowNull: false, + }, + channel: { + type: DataTypes.STRING(16), + allowNull: false, + }, + attemptKey: { + type: DataTypes.STRING(255), + allowNull: false, + }, + destination: { + type: DataTypes.STRING(255), + allowNull: false, + }, + codeHash: { + type: DataTypes.STRING(255), + allowNull: false, + }, + expiresAt: { + type: DataTypes.DATE, + allowNull: false, + }, + createdAt: DataTypes.DATE, + updatedAt: DataTypes.DATE, + }, + { + sequelize, + tableName: 'one_time_codes', + timestamps: true, + }, + ); + + return OneTimeCode; +}; + +export default initializeOneTimeCodeModel; diff --git a/src/models/users.ts b/src/models/users.ts index bc2aa507..3c8f69ae 100644 --- a/src/models/users.ts +++ b/src/models/users.ts @@ -17,10 +17,6 @@ export interface UserAttributes { phone: string | null; roles?: string[]; revoked?: boolean; - emailVerificationToken?: string | null; - emailVerificationTokenExpiry?: number | null; - phoneVerificationToken?: string | null; - phoneVerificationTokenExpiry?: number | null; emailVerified?: boolean; phoneVerified?: boolean; phoneVerifiedAttemptId?: string | null; @@ -41,10 +37,6 @@ export class User extends Model implements UserAttributes { declare email: string; declare phone: string | null; declare revoked: boolean; - declare emailVerificationToken: string | null; - declare emailVerificationTokenExpiry: number | null; - declare phoneVerificationToken: string | null; - declare phoneVerificationTokenExpiry: number | null; declare emailVerified: boolean; declare phoneVerified: boolean; declare phoneVerifiedAttemptId: string | null; @@ -116,22 +108,6 @@ const initializeUserModel = (sequelize: Sequelize) => { allowNull: false, defaultValue: [], }, - emailVerificationToken: { - type: DataTypes.STRING, - allowNull: true, - }, - emailVerificationTokenExpiry: { - type: DataTypes.BIGINT, - allowNull: true, - }, - phoneVerificationToken: { - type: DataTypes.STRING, - allowNull: true, - }, - phoneVerificationTokenExpiry: { - type: DataTypes.BIGINT, - allowNull: true, - }, revoked: { type: DataTypes.BOOLEAN, allowNull: false, diff --git a/src/services/accountClaim.ts b/src/services/accountClaim.ts index 9d5bbbad..3fde6c0f 100644 --- a/src/services/accountClaim.ts +++ b/src/services/accountClaim.ts @@ -4,11 +4,13 @@ * See LICENSE file in the project root for full license information */ -import type { User } from '../models/users.js'; +import type { Transaction } from 'sequelize'; + +import { User } from '../models/users.js'; /** * Marks an unverified account as claimed by the attempt that just proved its email - * address. Does not save. + * address. Does not save; use {@link withLockedUser} so it reads the row as it is now. * * Anyone can start a registration for an address and verify a phone on the account it * creates, so a phone verified before the address was proven only stays if the same @@ -21,16 +23,38 @@ export function claimUnverifiedAccount(user: User, attemptId?: string): boolean user.verified = true; user.emailVerified = true; - user.emailVerificationToken = null; - user.emailVerificationTokenExpiry = null; if (user.phoneVerified && (!attemptId || user.phoneVerifiedAttemptId !== attemptId)) { user.phone = null; user.phoneVerified = false; - user.phoneVerificationToken = null; - user.phoneVerificationTokenExpiry = null; } user.phoneVerifiedAttemptId = null; return true; } + +/** + * Runs `apply` on the user's row as it stands, locked until `apply`'s changes are saved. + * + * A claim decides whether to keep a phone from the phone columns, and a phone verification + * decides whether it may run from `verified`. Read from a copy loaded earlier in the + * request, either could act on a value the other had just changed, and keep a phone it + * should have wiped. Holding the row lock serialises them. `apply` returning false saves + * nothing. + */ +export async function withLockedUser( + user: User, + apply: (user: User, transaction: Transaction) => boolean | Promise, + transaction?: Transaction, +): Promise { + const run = async (tx: Transaction) => { + await user.reload({ transaction: tx, lock: true }); + + if (!(await apply(user, tx))) return false; + + await user.save({ transaction: tx }); + return true; + }; + + return transaction ? run(transaction) : User.sequelize!.transaction(run); +} diff --git a/src/services/accountRecoveryService.ts b/src/services/accountRecoveryService.ts index 53217503..181339e8 100644 --- a/src/services/accountRecoveryService.ts +++ b/src/services/accountRecoveryService.ts @@ -128,14 +128,14 @@ function hashCancelToken(token: string) { } /** - * Issues a code for `attemptId`. When the user already has an open request on this - * channel, the code goes on that request, so verifying it resumes the request on the new - * attempt with its clock unchanged. Otherwise it starts a new one. Ephemeral tokens live - * for minutes and the delay is hours, so coming back means a new attempt, and the same - * channel is how the requester proves it is them again. + * Issues a code for `attemptId`, on a row of its own. When the user already has an open + * request on this channel, the row points at it, so verifying the code resumes that + * request on the new attempt with its clock unchanged. Otherwise verifying it starts a new + * one. Ephemeral tokens live for minutes and the delay is hours, so coming back means a new + * attempt, and the same channel is how the requester proves it is them again. * - * Nothing earlier is cancelled here. A stranger who knows the address can call this, and - * only a verified code may cancel the owner's request. + * Nothing on the open request is touched here. A stranger who knows the address can call + * this, and a code written onto the open request replaced the one its owner was using. * * Returns null, issuing nothing, while the channel's failure budget is spent. */ @@ -145,12 +145,6 @@ export async function startRecovery(userId: string, channel: RecoveryChannel, at } const code = generateRecoveryCode(channel); - const codeFields = { - codeAttemptId: attemptId, - codeHash: hashOtpToken(code), - codeExpiresAt: new Date(Date.now() + RECOVERY_CODE_TTL_MS), - failedAttempts: 0, - }; await AccountRecoveryRequest.update( { state: 'void', codeHash: null, codeAttemptId: null }, @@ -162,11 +156,16 @@ export async function startRecovery(userId: string, channel: RecoveryChannel, at order: [['requestedAt', 'DESC']], }); - if (open) { - await open.update(codeFields); - } else { - await AccountRecoveryRequest.create({ userId, channel, state: 'awaiting_code', ...codeFields }); - } + await AccountRecoveryRequest.create({ + userId, + channel, + state: 'awaiting_code', + resumesRequestId: open?.id ?? null, + codeAttemptId: attemptId, + codeHash: hashOtpToken(code), + codeExpiresAt: new Date(Date.now() + RECOVERY_CODE_TTL_MS), + failedAttempts: 0, + }); return code; } @@ -177,13 +176,12 @@ export type VerifyRecoveryResult = | { outcome: 'opened'; request: AccountRecoveryRequest; cancelToken: string } | { outcome: 'resumed'; request: AccountRecoveryRequest }; -function clearCode(request: AccountRecoveryRequest) { +function clearCode() { return { codeHash: null, codeAttemptId: null, codeExpiresAt: null, - // A resumed request survives a spent or exhausted code; a new one does not. - ...(request.state === 'awaiting_code' ? { state: 'void' as const } : {}), + state: 'void' as const, }; } @@ -203,7 +201,7 @@ export async function verifyRecovery( where: { userId, codeAttemptId: attemptId, - state: { [Op.in]: ['awaiting_code', 'pending'] }, + state: 'awaiting_code', codeHash: { [Op.ne]: null }, }, order: [['createdAt', 'DESC']], @@ -216,7 +214,7 @@ export async function verifyRecovery( const tries = request.failedAttempts ?? 0; if (request.codeExpiresAt.getTime() <= Date.now() || tries >= MAX_RECOVERY_CODE_ATTEMPTS) { - await request.update(clearCode(request)); + await request.update(clearCode()); return { outcome: 'invalid' }; } @@ -239,23 +237,31 @@ export async function verifyRecovery( // Email codes are letters, compared case-insensitively like the login OTP. if (!otpHashMatches(request.codeHash, code.toUpperCase())) { if (tries + 1 >= MAX_RECOVERY_CODE_ATTEMPTS) { - await request.update(clearCode(request)); + await request.update(clearCode()); } return { outcome: 'invalid' }; } await releaseRecoveryGuess(guess); - if (request.state === 'pending') { - await request.update({ ...clearCode(request), attemptId, failedAttempts: 0 }); - return { outcome: 'resumed', request }; + if (request.resumesRequestId) { + const [moved] = await AccountRecoveryRequest.update( + { attemptId }, + { where: { id: request.resumesRequestId, userId, state: 'pending' } }, + ); + await request.update(clearCode()); + + const resumed = + moved === 1 ? await AccountRecoveryRequest.findByPk(request.resumesRequestId) : null; + + return resumed ? { outcome: 'resumed', request: resumed } : { outcome: 'invalid' }; } const cancelToken = randomBytes(32).toString('base64url'); const requestedAt = new Date(); const [opened] = await AccountRecoveryRequest.update( { - ...clearCode(request), + ...clearCode(), state: 'pending', attemptId, failedAttempts: 0, diff --git a/src/services/oauthService.ts b/src/services/oauthService.ts index a47e27f0..34828115 100644 --- a/src/services/oauthService.ts +++ b/src/services/oauthService.ts @@ -22,6 +22,7 @@ import { UserExternalId } from '../models/userExternalIds.js'; import { User } from '../models/users.js'; import type { OAuthProviderConfig } from '../schemas/systemConfig.schema.js'; import getLogger from '../utils/logger.js'; +import { withLockedUser } from './accountClaim.js'; import { normalizeLoginPolicy } from './loginPolicyService.js'; import { discoverOAuthEndpoints } from './oauthDiscovery.js'; import { claimOAuthStateUse } from './oidcPayloadStore.js'; @@ -792,17 +793,17 @@ function parseOAuthProfile( * phone (an imported one) is kept. */ async function claimUnverifiedAccount(user: User, emailVerified: boolean) { - if (user.verified) return; - - await user.update({ - verified: true, - ...(emailVerified ? { emailVerified: true } : {}), - emailVerificationToken: null, - emailVerificationTokenExpiry: null, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, - phoneVerifiedAttemptId: null, - ...(user.phoneVerified ? { phone: null, phoneVerified: false } : {}), + await withLockedUser(user, (locked) => { + if (locked.verified) return false; + + locked.verified = true; + if (emailVerified) locked.emailVerified = true; + locked.phoneVerifiedAttemptId = null; + if (locked.phoneVerified) { + locked.phone = null; + locked.phoneVerified = false; + } + return true; }); } diff --git a/src/utils/otp.ts b/src/utils/otp.ts index 4ce1e285..872fce32 100644 --- a/src/utils/otp.ts +++ b/src/utils/otp.ts @@ -5,10 +5,12 @@ */ import { randomInt, timingSafeEqual } from 'crypto'; +import { Op, UniqueConstraintError } from 'sequelize'; import { reviewCodeFor } from '../lib/reviewAccounts.js'; +import { OneTimeCode, OneTimeCodeChannel } from '../models/oneTimeCodes.js'; import { User } from '../models/users.js'; -import { claimUnverifiedAccount } from '../services/accountClaim.js'; +import { claimUnverifiedAccount, withLockedUser } from '../services/accountClaim.js'; import { sendOTPEmail, sendOTPSMS } from '../services/messagingService.js'; import getLogger from './logger.js'; import { hashSha256 } from './utils.js'; @@ -49,45 +51,109 @@ export function otpHashMatches(storedHash: string, code: string) { return safeStringEqual(storedHash, hashOtpToken(code.trim())); } -function otpMatchesStoredValue( - storedToken: string, - verificationToken: string, - normalize: (token: string) => string, +const OTP_TTL_MS = 5 * 60 * 1000; + +/** + * Who a code belongs to: the sign-in or registration attempt an ephemeral token carries, + * or the access session that asked for it. A code is only checked against the codes its + * own attempt was sent, so a send from another attempt neither replaces it nor can be + * used in its place. + */ +export interface OtpScope { + attemptId?: string; + sessionId?: string; +} + +export function otpAttemptKey(scope: OtpScope): string { + if (scope.attemptId) return `attempt:${scope.attemptId}`; + if (scope.sessionId) return `session:${scope.sessionId}`; + return 'unscoped'; +} + +async function storeOtp( + user: User, + channel: OneTimeCodeChannel, + destination: string, + code: string, + scope: OtpScope, ) { - // OTPs are always stored hashed (`sha256:` prefix). Compare the hash of the - // normalized submission against the stored hash in constant time. Plaintext OTPs - // are no longer accepted; any issued before hashing (5-min TTL) simply expire. - return safeStringEqual(storedToken, hashOtpToken(normalize(verificationToken))); + const now = new Date(); + const attemptKey = otpAttemptKey(scope); + + await OneTimeCode.destroy({ + where: { + userId: user.id, + [Op.or]: [{ expiresAt: { [Op.lte]: now } }, { channel, attemptKey }], + }, + }); + + const issued = { + destination, + codeHash: hashOtpToken(code), + expiresAt: new Date(now.getTime() + OTP_TTL_MS), + }; + + try { + await OneTimeCode.create({ userId: user.id, channel, attemptKey, ...issued }); + } catch (error) { + // A resend for the same attempt stored its row between the delete and this insert. The + // code about to be sent is this one, so it replaces that row rather than failing the send. + if (!(error instanceof UniqueConstraintError)) throw error; + + await OneTimeCode.update(issued, { where: { userId: user.id, channel, attemptKey } }); + } } -type OtpIssuance = - | { emailVerificationToken: string; emailVerificationTokenExpiry: number } - | { phoneVerificationToken: string; phoneVerificationTokenExpiry: number }; +/** Whether this attempt has a live code waiting on the channel. */ +export async function hasPendingOtp(user: User, channel: OneTimeCodeChannel, scope: OtpScope) { + const pending = await OneTimeCode.count({ + where: { + userId: user.id, + channel, + attemptKey: otpAttemptKey(scope), + expiresAt: { [Op.gt]: new Date() }, + }, + }); -// Two requests holding the same code both pass the in-memory comparison, so the clear is -// conditional on the issuance that was compared: whichever clears it first wins and the -// other sees no affected rows. The expiry is part of the match because a review account -// is issued the same code each time, so the hash alone does not identify one issuance. + return pending > 0; +} + +// Deleting the row is the claim: two requests holding the same code cannot both delete it, +// so exactly one of them goes on to apply the verification. The user row is locked before +// it is read, so what `apply` decides from is what is saved. async function consumeOtp( user: User, - issuance: OtpIssuance, - applyVerification: () => void, + channel: OneTimeCodeChannel, + destination: string | null, + code: string, + scope: OtpScope, + apply: (user: User) => boolean, ): Promise { - const cleared = Object.fromEntries(Object.keys(issuance).map((column) => [column, null])); + if (!destination) return false; return User.sequelize!.transaction(async (transaction) => { - const [claimed] = await User.update(cleared, { - where: { id: user.id, ...issuance }, + const claimed = await OneTimeCode.destroy({ + where: { + userId: user.id, + channel, + attemptKey: otpAttemptKey(scope), + destination, + codeHash: hashOtpToken(code), + expiresAt: { [Op.gt]: new Date() }, + }, transaction, }); - if (claimed === 0) { - return false; - } + if (claimed === 0) return false; - applyVerification(); - await user.save({ transaction }); - return true; + return withLockedUser( + user, + (locked) => { + const current = channel === 'email' ? locked.email : locked.phone; + return current === destination && apply(locked); + }, + transaction, + ); }); } @@ -105,28 +171,21 @@ export const generateRandomPhoneOTP = (): number => { export const generateEmailOTP = async ( user: User, + scope: OtpScope, options: GenerateOtpOptions = {}, ): Promise => { if (!user) { throw new Error('Cannot generate email OTP for non-exsistent user'); } - // Set the token and the expiry time (ALWAYS 5 mins) - const now = new Date(); - now.setMinutes(now.getMinutes() + 5); - const reviewCode = reviewCodeFor(user.email); if (reviewCode) { logger.info('Issuing the configured review code to a review account'); } const emailToken = reviewCode ?? generateRandomEmailOTP(); - const emailVerificationTokenExpiry = now.getTime(); try { - await user.update({ - emailVerificationToken: hashOtpToken(normalizeEmailOtp(emailToken)), - emailVerificationTokenExpiry, - }); + await storeOtp(user, 'email', user.email, normalizeEmailOtp(emailToken), scope); } catch (error) { logger.error(`Error generate email OTP: ${error}`); throw new Error('Failed to set user OTP', { cause: error }); @@ -142,6 +201,7 @@ export const generateEmailOTP = async ( export const generatePhoneOTP = async ( user: User, + scope: OtpScope, options: GenerateOtpOptions = {}, ): Promise => { if (!user) { @@ -152,18 +212,10 @@ export const generatePhoneOTP = async ( throw new Error('Cannot generate phone OTP without a registered phone number'); } - // Set the token and the expiry time (ALWAYS 5 mins) - const now = new Date(); - now.setMinutes(now.getMinutes() + 5); - const phoneToken = generateRandomPhoneOTP(); - const phoneVerificationTokenExpiry = now.getTime(); try { - await user.update({ - phoneVerificationToken: hashOtpToken(String(phoneToken)), - phoneVerificationTokenExpiry, - }); + await storeOtp(user, 'phone', user.phone, String(phoneToken), scope); } catch (error) { logger.error(`Error generate phone OTP: ${error}`); throw new Error('Failed to set user OTP', { cause: error }); @@ -176,95 +228,77 @@ export const generatePhoneOTP = async ( return phoneToken; }; +export interface VerifyOtpOptions { + /** Recorded as the attempt that verified the phone, which a later claim reads. */ + attemptId?: string; + /** + * Refuse once the account is verified. Proving a phone on an account that signs in takes + * an access session, so the registration route must not succeed against a claim that + * landed after it read the account. + */ + unverifiedOnly?: boolean; +} + export const verifyPhoneOTP = async ( user: User, verificationToken: string, - attemptId?: string, + scope: OtpScope, + options: VerifyOtpOptions = {}, ): Promise<{ user: User; verified: boolean }> => { - if (!user || !user.phoneVerificationToken || !user.phoneVerificationTokenExpiry) { - throw new Error('Cannot verify phone OTP due to incomplete user data'); - } + let verified: boolean; - if ( - otpMatchesStoredValue(user.phoneVerificationToken, verificationToken, normalizePhoneOtp) && - user.phoneVerificationTokenExpiry > new Date().getTime() - ) { - let claimed: boolean; - try { - claimed = await consumeOtp( - user, - { - phoneVerificationToken: user.phoneVerificationToken, - phoneVerificationTokenExpiry: user.phoneVerificationTokenExpiry, - }, - () => { - user.phoneVerified = true; - user.phoneVerificationToken = null; - user.phoneVerificationTokenExpiry = null; - user.phoneVerifiedAttemptId = attemptId ?? null; - - if (user.emailVerified && !user.verified) { - user.verified = true; - } - }, - ); - } catch (error) { - logger.error(`Error verifying phone OTP: ${error}`); - throw new Error('Failed to update user verification via phone OTP', { cause: error }); - } - - if (!claimed) { - logger.warn('Phone OTP was consumed by a concurrent verification'); - return { user, verified: false }; - } - } else { - return { user, verified: false }; + try { + verified = await consumeOtp( + user, + 'phone', + user.phone, + normalizePhoneOtp(verificationToken), + scope, + (locked) => { + if (options.unverifiedOnly && locked.verified) return false; + + locked.phoneVerified = true; + locked.phoneVerifiedAttemptId = options.attemptId ?? null; + + if (locked.emailVerified && !locked.verified) { + locked.verified = true; + } + return true; + }, + ); + } catch (error) { + logger.error(`Error verifying phone OTP: ${error}`); + throw new Error('Failed to update user verification via phone OTP', { cause: error }); } - return { user, verified: true }; + return { user, verified }; }; export const verifyEmailOTP = async ( user: User, verificationToken: string, - attemptId?: string, + scope: OtpScope, + options: Pick = {}, ): Promise<{ user: User; verified: boolean }> => { - if (!user || !user.emailVerificationToken || !user.emailVerificationTokenExpiry) { - throw new Error('Cannot verify email OTP due to incomplete user data'); - } + let verified: boolean; - if ( - otpMatchesStoredValue(user.emailVerificationToken, verificationToken, normalizeEmailOtp) && - user.emailVerificationTokenExpiry > new Date().getTime() - ) { - let claimed: boolean; - try { - claimed = await consumeOtp( - user, - { - emailVerificationToken: user.emailVerificationToken, - emailVerificationTokenExpiry: user.emailVerificationTokenExpiry, - }, - () => { - user.emailVerified = true; - user.emailVerificationToken = null; - user.emailVerificationTokenExpiry = null; - - claimUnverifiedAccount(user, attemptId); - }, - ); - } catch (error) { - logger.error(`Error verifying email OTP: ${error}`); - throw new Error('Failed to update user verification via email OTP', { cause: error }); - } - - if (!claimed) { - logger.warn('Email OTP was consumed by a concurrent verification'); - return { user, verified: false }; - } - } else { - return { user, verified: false }; + try { + verified = await consumeOtp( + user, + 'email', + user.email, + normalizeEmailOtp(verificationToken), + scope, + (locked) => { + locked.emailVerified = true; + claimUnverifiedAccount(locked, options.attemptId); + return true; + }, + ); + } catch (error) { + logger.error(`Error verifying email OTP: ${error}`); + throw new Error('Failed to update user verification via email OTP', { cause: error }); } - return { user, verified: true }; + return { user, verified }; }; diff --git a/tests/e2e/authFlow.spec.ts b/tests/e2e/authFlow.spec.ts index d3f0afa8..d745df44 100644 --- a/tests/e2e/authFlow.spec.ts +++ b/tests/e2e/authFlow.spec.ts @@ -18,6 +18,7 @@ vi.mock('../../../src/services/authEventService.js', () => ({ })); import { User } from '../../src/models/users.js'; +import { OneTimeCode } from '../../src/models/oneTimeCodes.js'; import { Session } from '../../src/models/sessions.js'; import { signEphemeralToken, signAccessToken, generateRefreshToken } from '../../src/lib/token.js'; @@ -75,7 +76,13 @@ describe('E2E Auth Flow', () => { .set('Authorization', 'Bearer ephemeral-token'); expect(otpRes.status).toBe(200); - expect(generateEmailOTP).toHaveBeenCalled(); + expect(generateEmailOTP).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ attemptId: 'attempt-1' }), + expect.anything(), + ); + // The code the send stored is waiting on this attempt. + (OneTimeCode.count as any).mockResolvedValue(1); (verifyEmailOTP as any).mockResolvedValue({ user: buildUser({ diff --git a/tests/factories/accountRecoveryStore.ts b/tests/factories/accountRecoveryStore.ts index 449b74c2..abad77a3 100644 --- a/tests/factories/accountRecoveryStore.ts +++ b/tests/factories/accountRecoveryStore.ts @@ -78,6 +78,7 @@ export function installAccountRecoveryStore() { const row = instance({ id: randomUUID(), attemptId: null, + resumesRequestId: null, codeAttemptId: null, codeHash: null, codeExpiresAt: null, @@ -103,6 +104,10 @@ export function installAccountRecoveryStore() { }, ); + (AccountRecoveryRequest.findByPk as any).mockImplementation( + async (id: string) => rows.find((row) => row.id === id) ?? null, + ); + (AccountRecoveryRequest.findAll as any).mockImplementation( async ({ where, order }: { where: Where; order?: [string, string][] }) => { const found = rows.filter((row) => matches(row, where)); diff --git a/tests/factories/userFactory.ts b/tests/factories/userFactory.ts index 1f21f264..e986e282 100644 --- a/tests/factories/userFactory.ts +++ b/tests/factories/userFactory.ts @@ -15,6 +15,8 @@ export function buildUser(overrides: Partial = {}) { update: vi.fn(), destroy: vi.fn(), save: vi.fn(), + // The row lock a claim or verification takes rereads the row; the copy stands in for it. + reload: vi.fn(), ...overrides, }; } diff --git a/tests/integration/admin/admin.spec.ts b/tests/integration/admin/admin.spec.ts index 456eac40..e402285c 100644 --- a/tests/integration/admin/admin.spec.ts +++ b/tests/integration/admin/admin.spec.ts @@ -1013,12 +1013,7 @@ describe('PATCH /admin/users/:userId', () => { expect(res.status).toBe(200); expect(user.update).toHaveBeenCalledWith( - { - phone: null, - phoneVerified: false, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, - }, + { phone: null, phoneVerified: false }, expect.anything(), ); }); diff --git a/tests/integration/authentication/decoyParity.spec.ts b/tests/integration/authentication/decoyParity.spec.ts index d9e047e2..b4268b19 100644 --- a/tests/integration/authentication/decoyParity.spec.ts +++ b/tests/integration/authentication/decoyParity.spec.ts @@ -85,10 +85,6 @@ beforeEach(() => { function realUser(overrides: Record = {}) { return buildUser({ verified: true, - emailVerificationToken: null, - emailVerificationTokenExpiry: null, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, ...overrides, }); } diff --git a/tests/integration/breakGlass/breakGlass.spec.ts b/tests/integration/breakGlass/breakGlass.spec.ts index 8b83b063..ef041e36 100644 --- a/tests/integration/breakGlass/breakGlass.spec.ts +++ b/tests/integration/breakGlass/breakGlass.spec.ts @@ -36,6 +36,7 @@ import { import { AuthFailure } from '../../../src/models/authFailures.js'; import { Credential } from '../../../src/models/credentials.js'; import { RecoveryCode } from '../../../src/models/recoveryCodes.js'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { Session } from '../../../src/models/sessions.js'; import { TotpCredential } from '../../../src/models/totpCredentials.js'; import { User } from '../../../src/models/users.js'; @@ -60,8 +61,6 @@ function account(overrides: Record) { return buildUser({ verified: true, revoked: false, - emailVerificationToken: 'hashed', - emailVerificationTokenExpiry: new Date(Date.now() + 100_000), ...overrides, }); } @@ -462,6 +461,7 @@ describe('factors that prove only an address', () => { it('still signs an ordinary user in with email OTP under the same policy', async () => { currentUser = ordinary(); (verifyEmailOTP as any).mockResolvedValue({ user: currentUser, verified: true }); + (OneTimeCode.count as any).mockResolvedValue(1); const res = await request(app) .post('/otp/verify-login-email-otp') @@ -474,6 +474,7 @@ describe('factors that prove only an address', () => { it('signs a listed account without an admin role in with email OTP like anyone else', async () => { currentUser = listedNonAdmin(); (verifyEmailOTP as any).mockResolvedValue({ user: currentUser, verified: true }); + (OneTimeCode.count as any).mockResolvedValue(1); const res = await request(app) .post('/otp/verify-login-email-otp') diff --git a/tests/integration/magicLink/magicLink.spec.ts b/tests/integration/magicLink/magicLink.spec.ts index 9bad7638..0af1367e 100644 --- a/tests/integration/magicLink/magicLink.spec.ts +++ b/tests/integration/magicLink/magicLink.spec.ts @@ -762,6 +762,7 @@ it('creates session when magic link completed', async () => { roles: ['user'], save: vi.fn(), update: vi.fn(), + reload: vi.fn(), }; (User.findOne as any).mockResolvedValue(user); @@ -810,6 +811,7 @@ it('answers 503 when a fail-closed pre_token hook cannot be used, and creates no roles: ['user'], save: vi.fn(), update: vi.fn(), + reload: vi.fn(), }; (User.findOne as any).mockResolvedValue(user); (MagicLinkToken.findOne as any).mockResolvedValue( @@ -841,6 +843,7 @@ describe('magic link attempt binding and redemption', () => { roles: ['user'], save: vi.fn(), update: vi.fn(), + reload: vi.fn(), }); it('stores the requesting attempt on the link', async () => { @@ -896,9 +899,33 @@ describe('magic link attempt binding and redemption', () => { phoneVerifiedAttemptId: null, }), ); + expect(user.reload).toHaveBeenCalledWith(expect.objectContaining({ lock: true })); expect(user.save).toHaveBeenCalled(); }); + it('decides the claim from the locked row, not the copy loaded before it', async () => { + const user = { + ...completedUser(), + verified: false, + emailVerified: false, + phone: '+15550100', + phoneVerified: true, + phoneVerifiedAttemptId: 'attempt-other', + }; + // Another request claimed the account between this poll's read and its lock. + user.reload.mockImplementationOnce(async () => { + Object.assign(user, { verified: true, emailVerified: true, phoneVerifiedAttemptId: null }); + }); + (User.findOne as any).mockResolvedValue(user); + mockConfirmedLink(); + + const res = await request(app).get('/magic-link/check'); + + expect(res.status).toBe(200); + expect(user).toEqual(expect.objectContaining({ phone: '+15550100', phoneVerified: true })); + expect(user.save).not.toHaveBeenCalled(); + }); + it('keeps a phone the same attempt verified', async () => { const user = { ...completedUser(), @@ -1024,6 +1051,7 @@ describe('magic link full sign-in sequence (regression)', () => { roles: ['user'], save: vi.fn(), update: vi.fn(), + reload: vi.fn(), }; (User.findOne as any).mockResolvedValue(user); // clearAllMocks (beforeEach) clears calls but not implementations, so reset the diff --git a/tests/integration/otp/otp.security.spec.ts b/tests/integration/otp/otp.security.spec.ts index 5cdc77ca..4f519544 100644 --- a/tests/integration/otp/otp.security.spec.ts +++ b/tests/integration/otp/otp.security.spec.ts @@ -4,6 +4,7 @@ import { Application } from 'express'; import { createApp } from '../../../src/app'; import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { verifyPhoneOTP, verifyEmailOTP } from '../../../src/utils/otp.js'; let app: Application; @@ -18,6 +19,8 @@ beforeEach(() => { // The shared auth mock injects an already verified account, which email verification // refuses unless email OTP is a login method. (getSystemConfig as any).mockResolvedValue({ login_methods: ['passkey', 'email_otp'] }); + // A code is waiting, so each rejection below comes from verification itself. + (OneTimeCode.count as any).mockResolvedValue(1); }); describe('OTP Security - Phone Verification', () => { @@ -48,8 +51,6 @@ describe('OTP Security - Phone Verification', () => { (verifyPhoneOTP as any).mockResolvedValue({ user: { id: 'user-1', - phoneVerificationToken: '123456', - phoneVerificationTokenExpiry: new Date(Date.now() - 1000), // expired email: 'test@example.com', phone: '+14155552671', verified: true, @@ -73,8 +74,6 @@ describe('OTP Security - Phone Verification', () => { (verifyPhoneOTP as any).mockResolvedValue({ user: { id: 'user-1', - phoneVerificationToken: '123456', - phoneVerificationTokenExpiry: new Date(Date.now() + 100000), email: 'test@example.com', phone: '+14155552671', verified: true, @@ -123,8 +122,6 @@ describe('OTP Security - Email Verification', () => { (verifyEmailOTP as any).mockResolvedValue({ user: { id: 'user-1', - emailVerificationToken: '123456', - emailVerificationTokenExpiry: new Date(Date.now() - 1000), email: 'test@example.com', phone: '+14155552671', verified: true, diff --git a/tests/integration/otp/otp.spec.ts b/tests/integration/otp/otp.spec.ts index 57e2870f..0eb0014c 100644 --- a/tests/integration/otp/otp.spec.ts +++ b/tests/integration/otp/otp.spec.ts @@ -2,6 +2,7 @@ import request from 'supertest'; import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest'; import { createApp } from '../../../src/app'; import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { Application } from 'express'; vi.mock('../../../src/models/authEvents.js', () => ({ @@ -149,6 +150,7 @@ describe('OTP - Verify Email', () => { }); it('succeeds when OTP valid', async () => { + (OneTimeCode.count as any).mockResolvedValue(1); (verifyEmailOTP as any).mockResolvedValue({ user: { id: 'user-1', diff --git a/tests/integration/recovery/accountRecovery.spec.ts b/tests/integration/recovery/accountRecovery.spec.ts index e5e79daa..b7794068 100644 --- a/tests/integration/recovery/accountRecovery.spec.ts +++ b/tests/integration/recovery/accountRecovery.spec.ts @@ -580,6 +580,9 @@ describe('POST /recovery/verify', () => { expect(resumed.status).toBe(200); expect(resumed.body.completesAt).toBe(opened.body.completesAt); expect(sendNoticeEmail).not.toHaveBeenCalled(); + const pending = rows.filter((row) => row.state === 'pending'); + expect(pending).toHaveLength(1); + expect(pending[0].attemptId).toBe('attempt-2'); }); }); diff --git a/tests/integration/registration/register.spec.ts b/tests/integration/registration/register.spec.ts index 4f55d7fc..5a28f772 100644 --- a/tests/integration/registration/register.spec.ts +++ b/tests/integration/registration/register.spec.ts @@ -15,7 +15,8 @@ vi.mock('../../../src/models/users.js', () => ({ }, })); -vi.mock('../../../src/utils/otp.js', () => ({ +vi.mock('../../../src/utils/otp.js', async (importOriginal) => ({ + ...(await importOriginal()), generateEmailOTP: vi.fn(), generatePhoneOTP: vi.fn(), verifyPhoneOTP: vi.fn(), @@ -48,6 +49,7 @@ import { registerPhone, verifyRegisteredPhone, } from '../../../src/controllers/registration.js'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { Session } from '../../../src/models/sessions.js'; import { buildFreshStepUpSession } from '../../factories/sessionFactory.js'; @@ -104,7 +106,9 @@ describe('POST /registration/register', () => { expect(User.create).toHaveBeenCalled(); expect(signEphemeralToken).toHaveBeenCalledWith(user.id, expect.any(String)); - expect(generateEmailOTP).toHaveBeenCalledWith(user, { sendMessage: true }); + // The code belongs to the attempt the ephemeral token carries. + const [, attemptId] = (signEphemeralToken as any).mock.calls[0]; + expect(generateEmailOTP).toHaveBeenCalledWith(user, { attemptId }, { sendMessage: true }); expect(generatePhoneOTP).not.toHaveBeenCalled(); }); @@ -119,7 +123,9 @@ describe('POST /registration/register', () => { expect(User.create).not.toHaveBeenCalled(); expect(signEphemeralToken).toHaveBeenCalledWith(user.id, expect.any(String)); - expect(generateEmailOTP).toHaveBeenCalledWith(user, { sendMessage: true }); + // The code belongs to the attempt the ephemeral token carries. + const [, attemptId] = (signEphemeralToken as any).mock.calls[0]; + expect(generateEmailOTP).toHaveBeenCalledWith(user, { attemptId }, { sendMessage: true }); expect(generatePhoneOTP).not.toHaveBeenCalled(); }); @@ -194,7 +200,9 @@ describe('POST /registration/register', () => { expect(res.status).toBe(200); expect(res.body.sub).toBe(user.id); expect(signEphemeralToken).toHaveBeenCalledWith(user.id, expect.any(String)); - expect(generateEmailOTP).toHaveBeenCalledWith(user, { sendMessage: true }); + // The code belongs to the attempt the ephemeral token carries. + const [, attemptId] = (signEphemeralToken as any).mock.calls[0]; + expect(generateEmailOTP).toHaveBeenCalledWith(user, { attemptId }, { sendMessage: true }); expect(AuthEventService.log).not.toHaveBeenCalledWith( expect.objectContaining({ type: 'registration_failed' }), ); @@ -240,7 +248,9 @@ describe('POST /registration/register', () => { to: user.email, token: 'EMAILME', }); - expect(generateEmailOTP).toHaveBeenCalledWith(user, { sendMessage: false }); + // The code belongs to the attempt the ephemeral token carries. + const [, attemptId] = (signEphemeralToken as any).mock.calls[0]; + expect(generateEmailOTP).toHaveBeenCalledWith(user, { attemptId }, { sendMessage: false }); }); it('treats null phone as omitted', async () => { @@ -306,7 +316,11 @@ describe('POST /registration/register', () => { expect(User.create).not.toHaveBeenCalled(); // Continues as the email's owner, and the other account's phone is left alone. expect(emailOwner.update).not.toHaveBeenCalled(); - expect(generateEmailOTP).toHaveBeenCalledWith(emailOwner, expect.anything()); + expect(generateEmailOTP).toHaveBeenCalledWith( + emailOwner, + { attemptId: expect.any(String) }, + expect.anything(), + ); }); it('fails without email', async () => { @@ -489,7 +503,11 @@ describe('POST /registration/phone', () => { to: '+14155550000', token: 123456, }); - expect(generatePhoneOTP).toHaveBeenCalled(); + expect(generatePhoneOTP).toHaveBeenCalledWith( + expect.objectContaining({ phone: '+14155550000' }), + expect.objectContaining({ sessionId: 'session-1' }), + { sendMessage: false }, + ); }); it('rejects an in-use phone number', async () => { @@ -550,15 +568,35 @@ describe('POST /registration/phone', () => { describe('POST /registration/phone/verify', () => { it('verifies a registered phone number', async () => { + (OneTimeCode.count as any).mockResolvedValue(1); + const res = await request(app) .post('/registration/phone/verify') .send({ verificationToken: '123456' }); expect(res.status).toBe(200); - expect(verifyPhoneOTP).toHaveBeenCalled(); + expect(OneTimeCode.count).toHaveBeenCalledWith({ + where: expect.objectContaining({ channel: 'phone', attemptKey: 'attempt:attempt-1' }), + }); + expect(verifyPhoneOTP).toHaveBeenCalledWith( + expect.objectContaining({ id: 'user-1' }), + '123456', + expect.objectContaining({ attemptId: 'attempt-1', sessionId: 'session-1' }), + ); + }); + + it('rejects verification when this attempt has no code waiting', async () => { + const res = await request(app) + .post('/registration/phone/verify') + .send({ verificationToken: '123456' }); + + expect(res.status).toBe(401); + expect(res.body.error).toBe('Failed to verify OTP'); + expect(verifyPhoneOTP).not.toHaveBeenCalled(); }); it('rejects an incorrect verification token', async () => { + (OneTimeCode.count as any).mockResolvedValue(1); (verifyPhoneOTP as any).mockResolvedValue({ verified: false }); const res = await request(app) @@ -571,6 +609,7 @@ describe('POST /registration/phone/verify', () => { it('returns 500 when verification throws', async () => { (verifyPhoneOTP as any).mockRejectedValue(new Error('boom')); + (OneTimeCode.count as any).mockResolvedValue(1); const res = await request(app) .post('/registration/phone/verify') @@ -594,11 +633,8 @@ describe('POST /registration/phone/verify', () => { it('rejects verification when phone verification data is missing', async () => { const res = buildRes(); - const user = buildUser({ - phone: null, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, - }); + const user = buildUser({ phone: null }); + (OneTimeCode.count as any).mockResolvedValue(1); await verifyRegisteredPhone(buildReq({ user, body: { verificationToken: '123456' } }), res); @@ -608,11 +644,8 @@ describe('POST /registration/phone/verify', () => { it('rejects verification when the token is missing from the request', async () => { const res = buildRes(); - const user = buildUser({ - phone: '+14155552671', - phoneVerificationToken: '123456', - phoneVerificationTokenExpiry: new Date(Date.now() + 100000), - }); + const user = buildUser({ phone: '+14155552671' }); + (OneTimeCode.count as any).mockResolvedValue(1); await verifyRegisteredPhone(buildReq({ user, body: {} }), res); diff --git a/tests/postgres/accountRecovery.spec.ts b/tests/postgres/accountRecovery.spec.ts index d72b5c09..b11d09c0 100644 --- a/tests/postgres/accountRecovery.spec.ts +++ b/tests/postgres/accountRecovery.spec.ts @@ -57,6 +57,53 @@ describe('account recovery against Postgres', () => { expect(await AccountRecoveryRequest.count({ where: { userId } })).toBe(0); }); + it('resumes through a row of its own, leaving the open request as it was', async () => { + const owner = randomUUID(); + await getSequelize().query( + `INSERT INTO users (id, email, roles, created_at, updated_at) + VALUES (:id, :email, '{user}', now(), now())`, + { replacements: { id: owner, email: `recovery-${owner}@example.com` } }, + ); + const opened = await verifyRecovery( + owner, + 'attempt-r1', + (await startRecovery(owner, 'email', 'attempt-r1'))!, + 3600, + ); + if (opened.outcome !== 'opened') throw new Error('not opened'); + const before = (await AccountRecoveryRequest.findByPk(opened.request.id))!.toJSON(); + + const resumeCode = (await startRecovery(owner, 'email', 'attempt-r2'))!; + + expect((await AccountRecoveryRequest.findByPk(opened.request.id))!.toJSON()).toEqual(before); + const resumeRow = await AccountRecoveryRequest.findOne({ + where: { userId: owner, codeAttemptId: 'attempt-r2' }, + }); + expect(resumeRow).toMatchObject({ + state: 'awaiting_code', + resumesRequestId: opened.request.id, + }); + + const resumed = await verifyRecovery(owner, 'attempt-r2', resumeCode, 3600); + expect(resumed.outcome).toBe('resumed'); + if (resumed.outcome !== 'resumed') throw new Error('not resumed'); + expect(resumed.request.id).toBe(opened.request.id); + expect(resumed.request).toMatchObject({ state: 'pending', attemptId: 'attempt-r2' }); + expect(+resumed.request.completesAt!).toBe(+before.completesAt!); + await expect(AccountRecoveryRequest.findByPk(resumeRow!.id)).resolves.toMatchObject({ + state: 'void', + codeHash: null, + }); + + const late = (await startRecovery(owner, 'email', 'attempt-r3'))!; + await cancelRecoveryForUser(owner, opened.request.id); + expect((await verifyRecovery(owner, 'attempt-r3', late, 3600)).outcome).toBe('invalid'); + await expect(AccountRecoveryRequest.findByPk(opened.request.id)).resolves.toMatchObject({ + state: 'cancelled', + attemptId: 'attempt-r2', + }); + }); + it('supersedes other open requests only when told to, and voids an unannounced one', async () => { const owner = randomUUID(); await getSequelize().query( diff --git a/tests/postgres/oneTimeCodes.spec.ts b/tests/postgres/oneTimeCodes.spec.ts new file mode 100644 index 00000000..73683458 --- /dev/null +++ b/tests/postgres/oneTimeCodes.spec.ts @@ -0,0 +1,107 @@ +import { randomUUID } from 'crypto'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { OneTimeCode } from '../../src/models/oneTimeCodes.js'; +import { User } from '../../src/models/users.js'; +import { + generateEmailOTP, + generatePhoneOTP, + hasPendingOtp, + verifyEmailOTP, + verifyPhoneOTP, +} from '../../src/utils/otp.js'; + +async function createUser(values: Partial = {}) { + const id = randomUUID(); + await User.create({ id, email: `codes-${id}@example.com`, roles: ['user'], ...values }); + return (await User.findByPk(id))!; +} + +const send = { sendMessage: false }; + +beforeAll(async () => { + await initializeModels(); +}); + +afterAll(async () => { + await getSequelize().close(); +}); + +// Codes used to share one slot on the user, so a second attempt's send replaced the code +// the first was waiting on. Each attempt now holds its own row. +describe('one-time codes per attempt', () => { + it('keeps a code for each attempt, and each verifies only on its own', async () => { + const user = await createUser(); + const a = { attemptId: randomUUID() }; + const b = { attemptId: randomUUID() }; + + const codeA = await generateEmailOTP(user, a, send); + const codeB = await generateEmailOTP(user, b, send); + + expect(await OneTimeCode.count({ where: { userId: user.id } })).toBe(2); + await expect(hasPendingOtp(user, 'email', a)).resolves.toBe(true); + await expect(hasPendingOtp(user, 'email', b)).resolves.toBe(true); + + if (codeA !== codeB) { + expect((await verifyEmailOTP(user, codeA, b)).verified).toBe(false); + } + expect((await verifyEmailOTP(user, codeA, a)).verified).toBe(true); + expect((await verifyEmailOTP(user, codeB, b)).verified).toBe(true); + expect(await OneTimeCode.count({ where: { userId: user.id } })).toBe(0); + }); + + it('does not verify a code on an attempt that was never sent one', async () => { + const user = await createUser({ phone: `+1415${String(Date.now()).slice(-7)}` }); + const a = { attemptId: randomUUID() }; + + const code = await generatePhoneOTP(user, a, send); + + expect((await verifyPhoneOTP(user, String(code), { attemptId: randomUUID() })).verified).toBe( + false, + ); + expect((await verifyPhoneOTP(user, String(code), { sessionId: randomUUID() })).verified).toBe( + false, + ); + expect((await verifyPhoneOTP(user, String(code), {})).verified).toBe(false); + await expect(User.findByPk(user.id)).resolves.toMatchObject({ phoneVerified: false }); + + expect((await verifyPhoneOTP(user, String(code), a)).verified).toBe(true); + await expect(User.findByPk(user.id)).resolves.toMatchObject({ phoneVerified: true }); + }); + + it('replaces only the same attempt code on a resend', async () => { + const user = await createUser(); + const a = { attemptId: randomUUID() }; + + const first = await generateEmailOTP(user, a, send); + const second = await generateEmailOTP(user, a, send); + + expect(await OneTimeCode.count({ where: { userId: user.id } })).toBe(1); + if (first !== second) { + expect((await verifyEmailOTP(user, first, a)).verified).toBe(false); + } + expect((await verifyEmailOTP(user, second, a)).verified).toBe(true); + }); + + it('does not verify a code once the address it went to has changed', async () => { + const user = await createUser(); + const a = { attemptId: randomUUID() }; + const code = await generateEmailOTP(user, a, send); + + await User.update({ email: `moved-${user.id}@example.com` }, { where: { id: user.id } }); + await user.reload(); + + expect((await verifyEmailOTP(user, code, a)).verified).toBe(false); + await expect(User.findByPk(user.id)).resolves.toMatchObject({ emailVerified: false }); + }); + + it('goes with the user', async () => { + const user = await createUser(); + await generateEmailOTP(user, { attemptId: randomUUID() }, send); + + await user.destroy(); + + expect(await OneTimeCode.count({ where: { userId: user.id } })).toBe(0); + }); +}); diff --git a/tests/postgres/oneTimeCredentials.spec.ts b/tests/postgres/oneTimeCredentials.spec.ts index da177e41..4564a474 100644 --- a/tests/postgres/oneTimeCredentials.spec.ts +++ b/tests/postgres/oneTimeCredentials.spec.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'crypto'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { OneTimeCode } from '../../src/models/oneTimeCodes.js'; import { TotpCredential } from '../../src/models/totpCredentials.js'; import { User } from '../../src/models/users.js'; import { @@ -9,7 +10,12 @@ import { verifyEnabledTotp, verifyTotpEnrollment, } from '../../src/services/totpService.js'; -import { hashOtpToken, verifyEmailOTP, verifyPhoneOTP } from '../../src/utils/otp.js'; +import { + generateEmailOTP, + generatePhoneOTP, + verifyEmailOTP, + verifyPhoneOTP, +} from '../../src/utils/otp.js'; import { generateTotpCode } from '../../src/utils/totp.js'; const SECRET = 'JBSWY3DPEHPK3PXP'; @@ -40,37 +46,34 @@ afterAll(async () => { describe('one-time credentials under concurrent submission', () => { it('accepts one valid email OTP exactly once', async () => { - const id = await createUser({ - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: Date.now() + 60_000, - }); + const id = await createUser(); + const scope = { attemptId: randomUUID() }; + const code = await generateEmailOTP((await User.findByPk(id))!, scope, { sendMessage: false }); const winners = await contend( async () => (await User.findByPk(id))!, - async (user) => (await verifyEmailOTP(user, 'abcdef')).verified, + async (user) => (await verifyEmailOTP(user, code.toLowerCase(), scope)).verified, ); expect(winners).toBe(1); + await expect(OneTimeCode.count({ where: { userId: id } })).resolves.toBe(0); const stored = await User.findByPk(id); - expect(stored?.emailVerificationToken).toBeNull(); expect(stored?.emailVerified).toBe(true); }); it('accepts one valid phone OTP exactly once', async () => { - const id = await createUser({ - phone: '+14155552671', - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: Date.now() + 60_000, - }); + const id = await createUser({ phone: '+14155552671' }); + const scope = { attemptId: randomUUID() }; + const code = await generatePhoneOTP((await User.findByPk(id))!, scope, { sendMessage: false }); const winners = await contend( async () => (await User.findByPk(id))!, - async (user) => (await verifyPhoneOTP(user, '123456')).verified, + async (user) => (await verifyPhoneOTP(user, String(code), scope)).verified, ); expect(winners).toBe(1); + await expect(OneTimeCode.count({ where: { userId: id } })).resolves.toBe(0); const stored = await User.findByPk(id); - expect(stored?.phoneVerificationToken).toBeNull(); expect(stored?.phoneVerified).toBe(true); }); diff --git a/tests/postgres/unverifiedPhoneClaim.spec.ts b/tests/postgres/unverifiedPhoneClaim.spec.ts index 547e606c..88ad8a5d 100644 --- a/tests/postgres/unverifiedPhoneClaim.spec.ts +++ b/tests/postgres/unverifiedPhoneClaim.spec.ts @@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { invalidateSystemConfigCache } from '../../src/config/getSystemConfig.js'; import { getSequelize, initializeModels } from '../../src/models/index.js'; +import { OneTimeCode } from '../../src/models/oneTimeCodes.js'; import { SystemConfig } from '../../src/models/systemConfig.js'; import { User } from '../../src/models/users.js'; import { buildSystemConfig } from '../factories/systemConfigFactory.js'; @@ -107,8 +108,9 @@ describe('a phone planted before the owner claims the account', () => { .set('Authorization', `Bearer ${byEmail.body.token}`); expect(send.status).toBe(400); - await user.reload(); - expect(user.phoneVerificationToken).toBeNull(); + await expect(OneTimeCode.count({ where: { userId: user.id, channel: 'phone' } })).resolves.toBe( + 0, + ); }); it('does not accept a code sent before the claim', async () => { @@ -166,8 +168,10 @@ describe('a phone planted before the owner claims the account', () => { expect(send.status).toBe(200); expect(send.body.delivery).toBeUndefined(); + await expect(OneTimeCode.count({ where: { userId: user.id, channel: 'phone' } })).resolves.toBe( + 0, + ); await user.reload(); - expect(user.phoneVerificationToken).toBeNull(); expect(user.phoneVerified).toBe(false); }); }); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index 7d91b11e..c89a0355 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -133,6 +133,7 @@ vi.mock('../../src/models/recoveryCodes.js', () => ({ vi.mock('../../src/models/accountRecoveryRequests.js', () => ({ AccountRecoveryRequest: { create: vi.fn(), + findByPk: vi.fn(async () => null), findOne: vi.fn(async () => null), findAll: vi.fn(async () => []), update: vi.fn(async () => [0]), @@ -258,6 +259,16 @@ vi.mock('../../src/models/rolePermissions.js', () => ({ }, })); +vi.mock('../../src/models/oneTimeCodes.js', () => ({ + OneTimeCode: { + create: vi.fn(), + update: vi.fn(async () => [1]), + count: vi.fn(async () => 0), + // Defaults to claiming one code, the uncontended outcome of a matching verification. + destroy: vi.fn(async () => 1), + }, +})); + vi.mock('../../src/models/sessions.js', () => ({ Session: { create: vi.fn(), @@ -328,13 +339,6 @@ vi.mock('../../src/middleware/attachAuthMiddleware.js', async (importOriginal) = phone: '+14155552671', roles: ['user'], - // required for verification flows - emailVerificationToken: '123456', - emailVerificationTokenExpiry: new Date(Date.now() + 100000), - - phoneVerificationToken: '123456', - phoneVerificationTokenExpiry: new Date(Date.now() + 100000), - verified: true, emailVerified: true, phoneVerified: true, diff --git a/tests/unit/controllers/otp.spec.ts b/tests/unit/controllers/otp.spec.ts index 2e27d40b..cb686cfe 100644 --- a/tests/unit/controllers/otp.spec.ts +++ b/tests/unit/controllers/otp.spec.ts @@ -9,6 +9,7 @@ const generateEmailOTPMock = vi.fn(); const generatePhoneOTPMock = vi.fn(); const verifyEmailOTPMock = vi.fn(); const verifyPhoneOTPMock = vi.fn(); +const hasPendingOtpMock = vi.fn(); const getSystemConfigMock = vi.fn(); const isValidEmailMock = vi.fn(); const isValidPhoneNumberMock = vi.fn(); @@ -51,6 +52,7 @@ vi.mock('../../../src/utils/otp.js', () => ({ generatePhoneOTP: generatePhoneOTPMock, verifyEmailOTP: verifyEmailOTPMock, verifyPhoneOTP: verifyPhoneOTPMock, + hasPendingOtp: hasPendingOtpMock, })); vi.mock('../../../src/utils/utils.js', () => ({ @@ -71,10 +73,6 @@ type MockUser = { verified?: boolean; emailVerified?: boolean; phoneVerified?: boolean; - emailVerificationToken?: string; - emailVerificationTokenExpiry?: Date | null; - phoneVerificationToken?: string; - phoneVerificationTokenExpiry?: Date | null; update: ReturnType; }; @@ -87,10 +85,6 @@ function buildUser(overrides: Partial = {}): MockUser { verified: true, emailVerified: true, phoneVerified: true, - emailVerificationToken: 'EMAILOTP', - emailVerificationTokenExpiry: new Date(Date.now() + 60_000), - phoneVerificationToken: '123456', - phoneVerificationTokenExpiry: new Date(Date.now() + 60_000), update: vi.fn(), ...overrides, }; @@ -134,6 +128,8 @@ beforeEach(() => { reissueEphemeralTokenMock.mockResolvedValue('ephemeral-token'); generatePhoneOTPMock.mockResolvedValue('654321'); generateEmailOTPMock.mockResolvedValue('ABCDEF'); + // A code is waiting on the request's attempt unless a test says otherwise. + hasPendingOtpMock.mockResolvedValue(true); getSystemConfigMock.mockResolvedValue({ login_methods: ['passkey', 'magic_link', 'email_otp', 'phone_otp'], passkey_login_fallback_enabled: true, @@ -158,7 +154,7 @@ describe('otp controller', () => { await sendPhoneOTP(req, res); - expect(generatePhoneOTPMock).toHaveBeenCalledWith(user, { sendMessage: false }); + expect(generatePhoneOTPMock).toHaveBeenCalledWith(user, req, { sendMessage: false }); expect(reissueEphemeralTokenMock).toHaveBeenCalledWith(user.id, req); expect(res.status).toHaveBeenCalledWith(200); expect(res.json).toHaveBeenCalledWith({ @@ -217,7 +213,7 @@ describe('otp controller', () => { await sendEmailOTP(req, res); - expect(generateEmailOTPMock).toHaveBeenCalledWith(user, { sendMessage: false }); + expect(generateEmailOTPMock).toHaveBeenCalledWith(user, req, { sendMessage: false }); expect(res.status).toHaveBeenCalledWith(200); expect(res.json).toHaveBeenCalledWith({ message: 'success', @@ -248,20 +244,19 @@ describe('otp controller', () => { expect(res.json).toHaveBeenCalledWith({ error: 'login_method_disabled' }); }); - it('returns 401 when phone verification data is missing', async () => { + it('returns 401 when no phone code is waiting on this attempt', async () => { const { verifyPhoneNumber } = await loadOtpController(); - const user = buildUser({ - verified: false, - phoneVerificationToken: undefined, - phoneVerificationTokenExpiry: null, - }); + const user = buildUser({ verified: false }); const req = buildReq(user, { body: { verificationToken: '123456' }, }); const res = buildRes(); + hasPendingOtpMock.mockResolvedValue(false); await verifyPhoneNumber(req, res); + expect(hasPendingOtpMock).toHaveBeenCalledWith(user, 'phone', req); + expect(verifyPhoneOTPMock).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'Not allowed' }); }); @@ -790,6 +785,42 @@ describe('otp controller', () => { expect(res.json).toHaveBeenCalledWith({ message: 'Success' }); }); + it('checks each code against the attempt that asked for it', async () => { + const otp = await loadOtpController(); + const user = unclaimedUser(); + const req = buildReq(user, { attemptId: 'attempt-a', body: { verificationToken: '123456' } }); + verifyPhoneOTPMock.mockResolvedValue({ user, verified: false }); + verifyEmailOTPMock.mockResolvedValue({ user, verified: false }); + + await otp.verifyPhoneNumber(req, buildRes()); + await otp.verifyEmail(req, buildRes()); + + // The registration phone route must not succeed against a claim that landed first. + expect(verifyPhoneOTPMock).toHaveBeenCalledWith(user, '123456', req, { + attemptId: 'attempt-a', + unverifiedOnly: true, + }); + expect(verifyEmailOTPMock).toHaveBeenCalledWith(user, '123456', req, { + attemptId: 'attempt-a', + }); + }); + + it('checks login codes against the attempt that asked for them', async () => { + const otp = await loadOtpController(); + const user = buildUser(); + const req = buildReq(user, { attemptId: 'attempt-a', body: { verificationToken: '123456' } }); + verifyPhoneOTPMock.mockResolvedValue({ user, verified: false }); + verifyEmailOTPMock.mockResolvedValue({ user, verified: false }); + + await otp.verifyLoginPhoneNumber(req, buildRes()); + await otp.verifyLoginEmail(req, buildRes()); + + expect(hasPendingOtpMock).toHaveBeenCalledWith(user, 'phone', req); + expect(hasPendingOtpMock).toHaveBeenCalledWith(user, 'email', req); + expect(verifyPhoneOTPMock).toHaveBeenCalledWith(user, '123456', req); + expect(verifyEmailOTPMock).toHaveBeenCalledWith(user, '123456', req); + }); + it('returns 401 when phone verification does not match', async () => { const { verifyPhoneNumber } = await loadOtpController(); const res = buildRes(); @@ -818,17 +849,17 @@ describe('otp controller', () => { expect(res.json).toHaveBeenCalledWith({ error: 'Internal server error' }); }); - it('returns 401 when the email verification token or expiry is missing', async () => { + it('returns 401 when no email code is waiting on this attempt', async () => { const { verifyEmail } = await loadOtpController(); const res = buildRes(); + const user = buildUser(); + const req = buildReq(user, { body: { verificationToken: 'EMAILOTP' } }); + hasPendingOtpMock.mockResolvedValue(false); - await verifyEmail( - buildReq(buildUser({ emailVerificationTokenExpiry: null }), { - body: { verificationToken: 'EMAILOTP' }, - }), - res, - ); + await verifyEmail(req, res); + expect(hasPendingOtpMock).toHaveBeenCalledWith(user, 'email', req); + expect(verifyEmailOTPMock).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'Not allowed' }); }); @@ -907,17 +938,17 @@ describe('otp controller', () => { expect(verifyPhoneOTPMock).not.toHaveBeenCalled(); }); - it('returns 401 when login phone verification data is missing', async () => { + it('returns 401 when no login phone code is waiting on this attempt', async () => { const { verifyLoginPhoneNumber } = await loadOtpController(); const res = buildRes(); + const user = buildUser(); + const req = buildReq(user, { body: { verificationToken: '123456' } }); + hasPendingOtpMock.mockResolvedValue(false); - await verifyLoginPhoneNumber( - buildReq(buildUser({ phoneVerificationToken: undefined }), { - body: { verificationToken: '123456' }, - }), - res, - ); + await verifyLoginPhoneNumber(req, res); + expect(hasPendingOtpMock).toHaveBeenCalledWith(user, 'phone', req); + expect(verifyPhoneOTPMock).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'Not allowed' }); }); @@ -964,6 +995,17 @@ describe('otp controller', () => { expect(res.json).toHaveBeenCalledWith({ error: 'Internal server error' }); }); + it('stops email verification when the user is locked out', async () => { + const { verifyEmail } = await loadOtpController(); + const res = buildRes(); + rejectIfUserLockedMock.mockResolvedValue(true); + + await verifyEmail(buildReq(buildUser(), { body: { verificationToken: 'EMAILOTP' } }), res); + + expect(hasPendingOtpMock).not.toHaveBeenCalled(); + expect(verifyEmailOTPMock).not.toHaveBeenCalled(); + }); + it('stops login email verification when the user is locked out', async () => { const { verifyLoginEmail } = await loadOtpController(); const res = buildRes(); @@ -974,17 +1016,17 @@ describe('otp controller', () => { expect(verifyEmailOTPMock).not.toHaveBeenCalled(); }); - it('returns 401 when login email verification data is missing', async () => { + it('returns 401 when no login email code is waiting on this attempt', async () => { const { verifyLoginEmail } = await loadOtpController(); const res = buildRes(); + const user = buildUser(); + const req = buildReq(user, { body: { verificationToken: 'EMAILOTP' } }); + hasPendingOtpMock.mockResolvedValue(false); - await verifyLoginEmail( - buildReq(buildUser({ emailVerificationToken: undefined }), { - body: { verificationToken: 'EMAILOTP' }, - }), - res, - ); + await verifyLoginEmail(req, res); + expect(hasPendingOtpMock).toHaveBeenCalledWith(user, 'email', req); + expect(verifyEmailOTPMock).not.toHaveBeenCalled(); expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'Not allowed' }); }); diff --git a/tests/unit/models/models.spec.ts b/tests/unit/models/models.spec.ts index 648762dc..e36b9ecd 100644 --- a/tests/unit/models/models.spec.ts +++ b/tests/unit/models/models.spec.ts @@ -27,6 +27,7 @@ vi.unmock('../../../src/models/userExternalIds.js'); vi.unmock('../../../src/models/policyVersions.js'); vi.unmock('../../../src/models/policyDrafts.js'); vi.unmock('../../../src/models/oidcClientLinks.js'); +vi.unmock('../../../src/models/oneTimeCodes.js'); // The predicate the loader filters on. It used to ask whether a file ended with its own // extension, which is always true, so everything but index was imported and required to diff --git a/tests/unit/services/accountClaim.spec.ts b/tests/unit/services/accountClaim.spec.ts index 37e00a59..55df31e5 100644 --- a/tests/unit/services/accountClaim.spec.ts +++ b/tests/unit/services/accountClaim.spec.ts @@ -1,17 +1,14 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; -import { claimUnverifiedAccount } from '../../../src/services/accountClaim.js'; +import { User } from '../../../src/models/users.js'; +import { claimUnverifiedAccount, withLockedUser } from '../../../src/services/accountClaim.js'; function user(overrides: Record = {}) { return { verified: false, emailVerified: false, - emailVerificationToken: 'hash', - emailVerificationTokenExpiry: 1, phone: '+15550100', phoneVerified: true, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, phoneVerifiedAttemptId: 'attempt-a', ...overrides, } as never as Parameters[0]; @@ -26,8 +23,6 @@ describe('claimUnverifiedAccount', () => { expect.objectContaining({ verified: true, emailVerified: true, - emailVerificationToken: null, - emailVerificationTokenExpiry: null, phoneVerifiedAttemptId: null, }), ); @@ -44,7 +39,7 @@ describe('claimUnverifiedAccount', () => { it.each([['attempt-b'], [undefined]])( 'drops a phone verified by another attempt (%s)', (attempt) => { - const account = user({ phoneVerificationToken: 'pending', phoneVerificationTokenExpiry: 2 }); + const account = user(); claimUnverifiedAccount(account, attempt); @@ -52,8 +47,7 @@ describe('claimUnverifiedAccount', () => { expect.objectContaining({ phone: null, phoneVerified: false, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, + phoneVerifiedAttemptId: null, }), ); }, @@ -66,3 +60,61 @@ describe('claimUnverifiedAccount', () => { expect(account).toEqual(expect.objectContaining({ phone: '+15550100', phoneVerified: true })); }); }); + +describe('withLockedUser', () => { + function lockable(overrides: Record = {}) { + return { + ...user(overrides), + reload: vi.fn(), + save: vi.fn(), + } as any; + } + + it('saves nothing when apply declines', async () => { + const account = lockable(); + const apply = vi.fn(() => false); + + await expect(withLockedUser(account, apply)).resolves.toBe(false); + + expect(account.reload).toHaveBeenCalledWith({ transaction: {}, lock: true }); + expect(apply).toHaveBeenCalledWith(account, {}); + expect(account.save).not.toHaveBeenCalled(); + }); + + it('reuses a transaction it is given', async () => { + const account = lockable(); + const tx = { id: 'outer' } as any; + + await expect(withLockedUser(account, () => true, tx)).resolves.toBe(true); + + expect(User.sequelize!.transaction).not.toHaveBeenCalled(); + expect(account.reload).toHaveBeenCalledWith({ transaction: tx, lock: true }); + expect(account.save).toHaveBeenCalledWith({ transaction: tx }); + }); + + it('opens a transaction of its own otherwise', async () => { + const account = lockable(); + const tx = { id: 'own' }; + vi.mocked(User.sequelize!.transaction).mockImplementationOnce(((fn: any) => fn(tx)) as any); + + await expect(withLockedUser(account, async () => true)).resolves.toBe(true); + + expect(User.sequelize!.transaction).toHaveBeenCalledTimes(1); + expect(account.reload).toHaveBeenCalledWith({ transaction: tx, lock: true }); + expect(account.save).toHaveBeenCalledWith({ transaction: tx }); + }); + + it('decides from the row as reloaded, not the copy it was handed', async () => { + const account = lockable({ verified: false }); + account.reload.mockImplementationOnce(async () => { + account.verified = true; + }); + + await expect( + withLockedUser(account, (locked) => claimUnverifiedAccount(locked, 'attempt-b')), + ).resolves.toBe(false); + + expect(account.phone).toBe('+15550100'); + expect(account.save).not.toHaveBeenCalled(); + }); +}); diff --git a/tests/unit/services/accountRecoveryService.spec.ts b/tests/unit/services/accountRecoveryService.spec.ts index b4705c66..d46e5df5 100644 --- a/tests/unit/services/accountRecoveryService.spec.ts +++ b/tests/unit/services/accountRecoveryService.spec.ts @@ -102,6 +102,38 @@ describe('startRecovery', () => { expect(rows.map((row) => row.state)).toEqual(['void', 'awaiting_code']); }); + it('issues a resume code on a row of its own, leaving the open request untouched', async () => { + await open('attempt-1', 'email'); + const before = { ...rows[0] }; + (AccountRecoveryRequest.update as any).mockClear(); + + const code = (await startRecovery('user-1', 'email', 'attempt-2'))!; + + expect(rows).toHaveLength(2); + expect({ ...rows[0] }).toEqual(before); + expect(rows[1]).toMatchObject({ + state: 'awaiting_code', + channel: 'email', + resumesRequestId: rows[0].id, + codeAttemptId: 'attempt-2', + }); + expect(rows[1].codeHash).toMatch(/^sha256:/); + expect(rows[1].codeHash).not.toContain(code); + // The only update is the void of this attempt's own earlier codes, which never matches + // a pending request. + expect(AccountRecoveryRequest.update).toHaveBeenCalledTimes(1); + expect(AccountRecoveryRequest.update).toHaveBeenCalledWith(expect.anything(), { + where: { userId: 'user-1', codeAttemptId: 'attempt-2', state: 'awaiting_code' }, + }); + }); + + it('keeps the owner able to finish its own code while a stranger starts a resume', async () => { + const code = (await startRecovery('user-1', 'email', 'attempt-1'))!; + await startRecovery('user-1', 'email', 'attempt-2'); + + expect((await verifyRecovery('user-1', 'attempt-1', code, HOUR)).outcome).toBe('opened'); + }); + it('does not cancel an open request, since anyone who knows the address can start one', async () => { await open('attempt-1', 'email'); await startRecovery('user-1', 'phone', 'attempt-2'); @@ -263,8 +295,43 @@ describe('verifyRecovery', () => { const result = await verifyRecovery('user-1', 'attempt-2', code, HOUR * 48); expect(result.outcome).toBe('resumed'); - expect(rows).toHaveLength(1); + expect(result.outcome === 'resumed' && result.request).toBe(rows[0]); + expect(rows).toHaveLength(2); expect(rows[0]).toMatchObject({ state: 'pending', attemptId: 'attempt-2', completesAt }); + expect(rows[1]).toMatchObject({ state: 'void', resumesRequestId: rows[0].id, codeHash: null }); + expect(AccountRecoveryRequest.update).toHaveBeenCalledWith( + { attemptId: 'attempt-2' }, + { where: { id: rows[0].id, userId: 'user-1', state: 'pending' } }, + ); + }); + + it('refuses a resume code once the request it resumes is no longer pending', async () => { + const { request } = await open('attempt-1', 'email'); + const code = (await startRecovery('user-1', 'email', 'attempt-2'))!; + // The owner cancels between the resume code being sent and it being used. + rows[0].state = 'cancelled'; + + expect(await verifyRecovery('user-1', 'attempt-2', code, HOUR)).toEqual({ + outcome: 'invalid', + }); + expect(rows[0]).toMatchObject({ state: 'cancelled', attemptId: 'attempt-1' }); + expect(rows[1]).toMatchObject({ state: 'void', resumesRequestId: request.id, codeHash: null }); + expect(AccountRecoveryRequest.findByPk).not.toHaveBeenCalled(); + }); + + it('refuses a resume code whose request is gone by the time it is read back', async () => { + await open('attempt-1', 'email'); + const code = (await startRecovery('user-1', 'email', 'attempt-2'))!; + (AccountRecoveryRequest.findByPk as any).mockResolvedValueOnce(null); + + expect((await verifyRecovery('user-1', 'attempt-2', code, HOUR)).outcome).toBe('invalid'); + }); + + it('resumes only through a code issued for the resume, not the open request itself', async () => { + await open('attempt-1', 'email'); + // A pending request holds no code, so the opening attempt has nothing left to verify. + expect((await verifyRecovery('user-1', 'attempt-1', 'AAAAAA', HOUR)).outcome).toBe('invalid'); + expect(rows[0]).toMatchObject({ state: 'pending', attemptId: 'attempt-1' }); }); it('leaves an open request intact when a resume code is guessed wrong too often', async () => { @@ -276,6 +343,7 @@ describe('verifyRecovery', () => { } expect(rows[0]).toMatchObject({ state: 'pending', attemptId: 'attempt-1', codeHash: null }); + expect(rows[1]).toMatchObject({ state: 'void', resumesRequestId: rows[0].id }); }); }); diff --git a/tests/unit/services/oauthIdToken.spec.ts b/tests/unit/services/oauthIdToken.spec.ts index 26f68798..7eaeb70f 100644 --- a/tests/unit/services/oauthIdToken.spec.ts +++ b/tests/unit/services/oauthIdToken.spec.ts @@ -208,7 +208,12 @@ describe('resolveOAuthUser with imported users', () => { }; it('links a first sign-in to the user imported under that id, without trusting the email', async () => { - const imported = buildUser({ id: 'imported', email: 'ada@town.example', verified: false }); + const imported = buildUser({ + id: 'imported', + email: 'ada@town.example', + verified: false, + emailVerified: false, + }); (OAuthIdentity.findOne as any).mockResolvedValue(null); (UserExternalId.findOne as any).mockResolvedValue({ userId: 'imported' }); (User.findByPk as any).mockResolvedValue(imported); @@ -219,9 +224,9 @@ describe('resolveOAuthUser with imported users', () => { expect(UserExternalId.findOne).toHaveBeenCalledWith({ where: { source: 'entra-id', externalId: 'oid-1' }, }); - const [values] = (imported.update as any).mock.calls[0]; - expect(values).toMatchObject({ verified: true }); - expect(values).not.toHaveProperty('emailVerified'); + expect(imported.save).toHaveBeenCalledTimes(1); + expect(imported.verified).toBe(true); + expect(imported.emailVerified).toBe(false); expect(User.findOne).not.toHaveBeenCalled(); }); diff --git a/tests/unit/services/oauthService.spec.ts b/tests/unit/services/oauthService.spec.ts index 557efeb9..6f13ba09 100644 --- a/tests/unit/services/oauthService.spec.ts +++ b/tests/unit/services/oauthService.spec.ts @@ -1171,14 +1171,37 @@ describe('oauthService', () => { }), ).resolves.toBe(imported); - expect(imported.update).toHaveBeenCalledWith( - expect.objectContaining({ verified: true, emailVerified: true }), - ); + expect(imported.reload).toHaveBeenCalledWith(expect.objectContaining({ lock: true })); + expect(imported.save).toHaveBeenCalledTimes(1); // The factory's phone is verified, which on an unclaimed account means someone other // than the owner proved it. - expect(imported.update).toHaveBeenCalledWith( - expect.objectContaining({ phone: null, phoneVerified: false }), - ); + expect(imported).toMatchObject({ + verified: true, + emailVerified: true, + phone: null, + phoneVerified: false, + phoneVerifiedAttemptId: null, + }); + }); + + it('leaves an account another request claimed first, deciding from the locked row', async () => { + const imported = buildUser({ email: 'ada@example.com', verified: false }); + imported.reload.mockImplementationOnce(async () => { + Object.assign(imported, { verified: true }); + }); + (OAuthIdentity.findOne as any).mockResolvedValue(null); + (User.findOne as any).mockResolvedValue(imported); + (OAuthIdentity.findOrCreate as any).mockResolvedValue([]); + + await resolveOAuthUser(provider, { + subject: 'provider-user', + email: 'ada@example.com', + emailVerified: true, + raw: {}, + }); + + expect(imported.save).not.toHaveBeenCalled(); + expect(imported).toMatchObject({ phone: '+14155552671', phoneVerified: true }); }); it('keeps an unverified phone, such as an imported one, when the account is claimed', async () => { @@ -1199,9 +1222,13 @@ describe('oauthService', () => { raw: {}, }); - const [values] = (imported.update as any).mock.calls[0]; - expect(values).not.toHaveProperty('phone'); - expect(values).toMatchObject({ verified: true, phoneVerificationToken: null }); + expect(imported.save).toHaveBeenCalledTimes(1); + expect(imported).toMatchObject({ + verified: true, + phone: '+14155552671', + phoneVerified: false, + phoneVerifiedAttemptId: null, + }); }); it('does not create a new user when signup is disabled', async () => { diff --git a/tests/unit/utils/otp.spec.ts b/tests/unit/utils/otp.spec.ts index f460059d..b326e7c0 100644 --- a/tests/unit/utils/otp.spec.ts +++ b/tests/unit/utils/otp.spec.ts @@ -1,3 +1,4 @@ +import { Op } from 'sequelize'; import { beforeEach, describe, expect, it, vi } from 'vitest'; vi.unmock('../../../src/utils/otp.js'); @@ -12,39 +13,102 @@ import { generateEmailOTP, generatePhoneOTP, hashOtpToken, + hasPendingOtp, + otpHashMatches, + otpAttemptKey, verifyPhoneOTP, verifyEmailOTP, } from '../../../src/utils/otp.js'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { User } from '../../../src/models/users.js'; import { sendOTPEmail, sendOTPSMS } from '../../../src/services/messagingService'; + +type Row = Record; + +const A = { attemptId: 'attempt-a' }; +const B = { attemptId: 'attempt-b' }; + function buildUser(overrides: any = {}) { return { + id: 'user-1', email: 'test@example.com', phone: '+14155552671', - emailVerificationToken: null, - emailVerificationTokenExpiry: null, - phoneVerificationToken: null, - phoneVerificationTokenExpiry: null, - emailVerified: false, phoneVerified: false, verified: false, update: vi.fn().mockResolvedValue(undefined), save: vi.fn().mockResolvedValue(undefined), + reload: vi.fn().mockResolvedValue(undefined), ...overrides, }; } -describe('OTP utils', () => { - beforeEach(() => { - vi.resetModules(); - vi.clearAllMocks(); +function matches(row: Row, where: Row): boolean { + return Reflect.ownKeys(where).every((key) => { + const condition = where[key as string]; + if (key === Op.or) return condition.some((branch: Row) => matches(row, branch)); + + const value = row[key as string]; + if (condition && typeof condition === 'object' && !(condition instanceof Date)) { + return Object.getOwnPropertySymbols(condition).every((op) => { + if (op === Op.gt) return +value > +condition[op]; + if (op === Op.lte) return +value <= +condition[op]; + throw new Error(`Unsupported operator ${String(op)}`); + }); + } + return value === condition; + }); +} + +/** An in-memory `one_time_codes` that honours the where clauses the helpers write. */ +function installOneTimeCodeStore() { + const codes: Row[] = []; + + (OneTimeCode.create as any).mockImplementation(async (data: Row) => { + codes.push({ ...data }); + return data; + }); + (OneTimeCode.count as any).mockImplementation( + async ({ where }: { where: Row }) => codes.filter((row) => matches(row, where)).length, + ); + (OneTimeCode.destroy as any).mockImplementation(async ({ where }: { where: Row }) => { + const hit = codes.filter((row) => matches(row, where)); + for (const row of hit) codes.splice(codes.indexOf(row), 1); + return hit.length; }); + return codes; +} + +function plant(codes: Row[], overrides: Row = {}) { + codes.push({ + userId: 'user-1', + channel: 'phone', + attemptKey: otpAttemptKey(A), + destination: '+14155552671', + codeHash: hashOtpToken('123456'), + expiresAt: new Date(Date.now() + 60_000), + ...overrides, + }); +} + +const emailRow = { + channel: 'email', + destination: 'test@example.com', + codeHash: hashOtpToken('ABCDEF'), +}; + +let codes: Row[]; + +beforeEach(() => { + codes = installOneTimeCodeStore(); +}); + +describe('OTP utils', () => { describe('generateRandomEmailOTP', () => { it('returns 6 uppercase letters', () => { const otp = generateRandomEmailOTP(); @@ -63,35 +127,94 @@ describe('OTP utils', () => { }); }); - // --------------------------- - // Generate OTP - // --------------------------- + describe('otpHashMatches', () => { + it('matches only the stored hash of the trimmed code', () => { + expect(otpHashMatches(hashOtpToken('ABCDEF'), ' ABCDEF ')).toBe(true); + expect(otpHashMatches(hashOtpToken('ABCDEF'), 'ABCDEG')).toBe(false); + expect(otpHashMatches('ABCDEF', 'ABCDEF')).toBe(false); + }); + }); + + describe('otpAttemptKey', () => { + it('keys on the attempt, then the session, then nothing', () => { + expect(otpAttemptKey({ attemptId: 'a', sessionId: 's' })).toBe('attempt:a'); + expect(otpAttemptKey({ sessionId: 's' })).toBe('session:s'); + expect(otpAttemptKey({})).toBe('unscoped'); + }); + }); + describe('generateEmailOTP', () => { - it('updates user and sends email', async () => { + it('replaces only its own attempt code, sweeping expired ones, then sends', async () => { const user = buildUser(); + const before = Date.now(); - const token = await generateEmailOTP(user as any); + const token = await generateEmailOTP(user as any, A); - expect(user.update).toHaveBeenCalled(); - expect(user.update).toHaveBeenCalledWith( - expect.objectContaining({ - emailVerificationToken: hashOtpToken(token), - emailVerificationTokenExpiry: expect.any(Number), - }), + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { + userId: 'user-1', + [Op.or]: [ + { expiresAt: { [Op.lte]: expect.any(Date) } }, + { channel: 'email', attemptKey: 'attempt:attempt-a' }, + ], + }, + }); + expect(OneTimeCode.create).toHaveBeenCalledWith({ + userId: 'user-1', + channel: 'email', + attemptKey: 'attempt:attempt-a', + destination: 'test@example.com', + codeHash: hashOtpToken(token), + expiresAt: expect.any(Date), + }); + const [{ expiresAt }] = (OneTimeCode.create as any).mock.calls[0]; + expect(+expiresAt - before).toBeGreaterThanOrEqual(5 * 60 * 1000); + expect(+expiresAt - Date.now()).toBeLessThanOrEqual(5 * 60 * 1000); + expect((OneTimeCode.destroy as any).mock.invocationCallOrder[0]).toBeLessThan( + (OneTimeCode.create as any).mock.invocationCallOrder[0], + ); + expect(sendOTPEmail).toHaveBeenCalledWith('test@example.com', token); + }); + + it('leaves another attempt code in place and removes expired ones', async () => { + plant(codes, { channel: 'email', attemptKey: 'attempt:attempt-b', destination: 'b' }); + plant(codes, { + channel: 'email', + attemptKey: 'attempt:attempt-c', + expiresAt: new Date(Date.now() - 1), + }); + plant(codes, { channel: 'email', attemptKey: 'attempt:attempt-a', destination: 'old' }); + plant(codes, { channel: 'phone', attemptKey: 'attempt:attempt-a' }); + + await generateEmailOTP(buildUser() as any, A, { sendMessage: false }); + + expect(codes.map((row) => [row.channel, row.attemptKey, row.destination])).toEqual([ + ['email', 'attempt:attempt-b', 'b'], + ['phone', 'attempt:attempt-a', '+14155552671'], + ['email', 'attempt:attempt-a', 'test@example.com'], + ]); + expect(sendOTPEmail).not.toHaveBeenCalled(); + }); + + it('scopes a code asked for by an access session to that session', async () => { + await generateEmailOTP(buildUser() as any, { sessionId: 'session-1' }); + + expect(OneTimeCode.create).toHaveBeenCalledWith( + expect.objectContaining({ attemptKey: 'session:session-1' }), ); - expect(sendOTPEmail).toHaveBeenCalled(); }); it('throws if user missing', async () => { - await expect(generateEmailOTP(null as any)).rejects.toThrow(); + await expect(generateEmailOTP(null as any, A)).rejects.toThrow(); }); - it('throws on update failure', async () => { - const user = buildUser({ - update: vi.fn().mockRejectedValue(new Error('fail')), - }); + it('throws and sends nothing when the code cannot be stored', async () => { + (OneTimeCode.create as any).mockRejectedValueOnce(new Error('fail')); - await expect(generateEmailOTP(user as any)).rejects.toThrow(); + await expect(generateEmailOTP(buildUser() as any, A)).rejects.toThrow( + 'Failed to set user OTP', + ); + expect(sendOTPEmail).not.toHaveBeenCalled(); }); it('issues the configured code to a review account, which then verifies', async () => { @@ -100,16 +223,15 @@ describe('OTP utils', () => { try { const user = buildUser(); - const token = await generateEmailOTP(user as any); + const token = await generateEmailOTP(user as any, A); expect(token).toBe('REVUEW'); - expect(user.update).toHaveBeenCalledWith( - expect.objectContaining({ emailVerificationToken: hashOtpToken('REVUEW') }), + expect(OneTimeCode.create).toHaveBeenCalledWith( + expect.objectContaining({ codeHash: hashOtpToken('REVUEW') }), ); expect(sendOTPEmail).toHaveBeenCalledWith('test@example.com', 'REVUEW'); - const issued = user.update.mock.calls[0][0]; - const result = await verifyEmailOTP(buildUser({ ...issued }) as any, 'revuew'); + const result = await verifyEmailOTP(user as any, 'revuew', A); expect(result.verified).toBe(true); } finally { delete process.env.REVIEW_ACCOUNT_EMAILS; @@ -119,154 +241,326 @@ describe('OTP utils', () => { }); describe('generatePhoneOTP', () => { - it('updates user and sends sms', async () => { - const user = buildUser(); - - const token = await generatePhoneOTP(user as any); + it('stores the code for its attempt and the phone it is sent to, then sends', async () => { + const token = await generatePhoneOTP(buildUser() as any, A); - expect(user.update).toHaveBeenCalled(); - expect(user.update).toHaveBeenCalledWith( - expect.objectContaining({ - phoneVerificationToken: hashOtpToken(String(token)), - phoneVerificationTokenExpiry: expect.any(Number), - }), - ); - expect(sendOTPSMS).toHaveBeenCalled(); + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { + userId: 'user-1', + [Op.or]: [ + { expiresAt: { [Op.lte]: expect.any(Date) } }, + { channel: 'phone', attemptKey: 'attempt:attempt-a' }, + ], + }, + }); + expect(OneTimeCode.create).toHaveBeenCalledWith({ + userId: 'user-1', + channel: 'phone', + attemptKey: 'attempt:attempt-a', + destination: '+14155552671', + codeHash: hashOtpToken(String(token)), + expiresAt: expect.any(Date), + }); + expect(sendOTPSMS).toHaveBeenCalledWith('+14155552671', token); }); it('throws if user missing', async () => { - await expect(generatePhoneOTP(null as any)).rejects.toThrow(); + await expect(generatePhoneOTP(null as any, A)).rejects.toThrow(); }); it('throws when the user has no registered phone number', async () => { const user = buildUser({ phone: null }); - await expect(generatePhoneOTP(user as any)).rejects.toThrow( + await expect(generatePhoneOTP(user as any, A)).rejects.toThrow( 'without a registered phone number', ); + expect(OneTimeCode.create).not.toHaveBeenCalled(); + }); + + // A resend for the same attempt stored its row between the delete and the insert. + it('replaces the row a concurrent resend stored, and sends this code', async () => { + const { UniqueConstraintError } = await import('sequelize'); + (OneTimeCode.create as any).mockRejectedValueOnce(new UniqueConstraintError({})); + const user = buildUser() as any; + + const code = await generatePhoneOTP(user, A); + + expect(OneTimeCode.update).toHaveBeenCalledWith( + expect.objectContaining({ destination: user.phone, expiresAt: expect.any(Date) }), + { where: { userId: user.id, channel: 'phone', attemptKey: otpAttemptKey(A) } }, + ); + expect(sendOTPSMS).toHaveBeenCalledWith(user.phone, code); + }); + + it('throws when the insert fails for another reason', async () => { + (OneTimeCode.create as any).mockRejectedValueOnce(new Error('db down')); + + await expect(generatePhoneOTP(buildUser() as any, A)).rejects.toThrow( + 'Failed to set user OTP', + ); + expect(OneTimeCode.update).not.toHaveBeenCalled(); }); it('throws when persisting the generated phone OTP fails', async () => { - const user = buildUser({ - update: vi.fn().mockRejectedValue(new Error('db down')), + (OneTimeCode.destroy as any).mockRejectedValueOnce(new Error('db down')); + + await expect(generatePhoneOTP(buildUser() as any, A)).rejects.toThrow( + 'Failed to set user OTP', + ); + expect(sendOTPSMS).not.toHaveBeenCalled(); + }); + }); + + describe('hasPendingOtp', () => { + it('counts only live codes for this attempt on the channel', async () => { + const user = buildUser(); + + expect(await hasPendingOtp(user as any, 'phone', A)).toBe(false); + expect(OneTimeCode.count).toHaveBeenCalledWith({ + where: { + userId: 'user-1', + channel: 'phone', + attemptKey: 'attempt:attempt-a', + expiresAt: { [Op.gt]: expect.any(Date) }, + }, }); - await expect(generatePhoneOTP(user as any)).rejects.toThrow('Failed to set user OTP'); + plant(codes, { attemptKey: 'attempt:attempt-b' }); + plant(codes, { expiresAt: new Date(Date.now() - 1) }); + plant(codes, { channel: 'email' }); + expect(await hasPendingOtp(user as any, 'phone', A)).toBe(false); + + plant(codes); + expect(await hasPendingOtp(user as any, 'phone', A)).toBe(true); }); }); - // --------------------------- - // Verify Phone OTP - // --------------------------- describe('verifyPhoneOTP', () => { it('verifies valid OTP', async () => { - const user = buildUser({ - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: Date.now() + 10000, - emailVerified: true, - }); + plant(codes); + const user = buildUser({ emailVerified: true }); - const result = await verifyPhoneOTP(user as any, '123456'); + const result = await verifyPhoneOTP(user as any, '123456', A); expect(result.verified).toBe(true); expect(user.phoneVerified).toBe(true); expect(user.verified).toBe(true); - expect(user.save).toHaveBeenCalled(); + expect(user.reload).toHaveBeenCalledWith({ transaction: {}, lock: true }); + expect(user.save).toHaveBeenCalledWith({ transaction: {} }); + expect(codes).toHaveLength(0); }); - it('returns false for invalid token', async () => { - const user = buildUser({ - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: Date.now() + 10000, + it("claims the code by the caller's own attempt and destination", async () => { + plant(codes); + + await verifyPhoneOTP(buildUser() as any, ' 123456 ', A); + + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { + userId: 'user-1', + channel: 'phone', + attemptKey: 'attempt:attempt-a', + destination: '+14155552671', + codeHash: hashOtpToken('123456'), + expiresAt: { [Op.gt]: expect.any(Date) }, + }, + transaction: {}, }); + }); + + it.each([ + ['a wrong code', {}, '654321', A], + ['a code sent to another attempt', {}, '123456', B], + ['an expired code', { expiresAt: new Date(Date.now() - 1) }, '123456', A], + ['a code sent to an earlier phone', { destination: '+14155550000' }, '123456', A], + ])('verifies nothing for %s', async (_name, row, code, scope) => { + plant(codes, row); + const user = buildUser({ emailVerified: true }); - const result = await verifyPhoneOTP(user as any, 'wrong'); + const result = await verifyPhoneOTP(user as any, code, scope); expect(result.verified).toBe(false); + expect(user.reload).not.toHaveBeenCalled(); + expect(user.save).not.toHaveBeenCalled(); + expect(user.phoneVerified).toBe(false); + expect(codes).toHaveLength(1); + }); + + it('verifies nothing when a concurrent request claimed the code first', async () => { + (OneTimeCode.destroy as any).mockResolvedValueOnce(0); + const user = buildUser({ emailVerified: true }); + + const result = await verifyPhoneOTP(user as any, '123456', A, { attemptId: 'attempt-a' }); + + expect(result.verified).toBe(false); + expect(user.reload).not.toHaveBeenCalled(); + expect(user.save).not.toHaveBeenCalled(); + expect(user.phoneVerified).toBe(false); + expect(user.phoneVerifiedAttemptId).toBeUndefined(); }); it('records the attempt that verified the phone', async () => { - const user = buildUser({ - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: Date.now() + 10000, - }); + plant(codes); + const user = buildUser(); - await verifyPhoneOTP(user as any, '123456', 'attempt-a'); + await verifyPhoneOTP(user as any, '123456', A, { attemptId: 'attempt-a' }); expect(user.phoneVerified).toBe(true); expect(user.phoneVerifiedAttemptId).toBe('attempt-a'); + expect(user.verified).toBe(false); }); - it('returns false for expired token', async () => { - const user = buildUser({ - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: Date.now() - 1000, + it('fails when the locked row no longer holds the phone the code went to', async () => { + plant(codes); + const user = buildUser(); + user.reload.mockImplementationOnce(async () => { + user.phone = '+14155550000'; }); - const result = await verifyPhoneOTP(user as any, '123456'); + const result = await verifyPhoneOTP(user as any, '123456', A); expect(result.verified).toBe(false); + expect(user.phoneVerified).toBe(false); + expect(user.save).not.toHaveBeenCalled(); }); - it('throws if missing data', async () => { + it('fails a registration verify once a claim verified the account first', async () => { + // The planted-phone race: the owner's email claim lands after this request read the + // account as unverified. The locked reread sees the claim and the phone is refused. + plant(codes); const user = buildUser(); + user.reload.mockImplementationOnce(async () => { + Object.assign(user, { verified: true, emailVerified: true }); + }); + + const result = await verifyPhoneOTP(user as any, '123456', A, { + attemptId: 'attempt-a', + unverifiedOnly: true, + }); + + expect(result.verified).toBe(false); + expect(user.phoneVerified).toBe(false); + expect(user.phoneVerifiedAttemptId).toBeUndefined(); + expect(user.save).not.toHaveBeenCalled(); + }); + + it('verifies a phone on a verified account when not limited to unverified ones', async () => { + plant(codes); + const user = buildUser({ verified: true, emailVerified: true }); - await expect(verifyPhoneOTP(user as any, '123')).rejects.toThrow(); + const result = await verifyPhoneOTP(user as any, '123456', A); + + expect(result.verified).toBe(true); + expect(user.phoneVerified).toBe(true); + expect(user.save).toHaveBeenCalled(); + }); + + it('verifies nothing for an account without a phone', async () => { + const user = buildUser({ phone: null }); + + expect((await verifyPhoneOTP(user as any, '123456', A)).verified).toBe(false); + expect(OneTimeCode.destroy).not.toHaveBeenCalled(); + }); + + it('throws when the claim fails', async () => { + (OneTimeCode.destroy as any).mockRejectedValueOnce(new Error('db down')); + + await expect(verifyPhoneOTP(buildUser() as any, '123456', A)).rejects.toThrow( + 'Failed to update user verification via phone OTP', + ); }); }); - // --------------------------- - // Verify Email OTP - // --------------------------- describe('verifyEmailOTP', () => { it('verifies valid OTP (case insensitive)', async () => { - const user = buildUser({ - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: Date.now() + 10000, - phone: null, - }); + plant(codes, emailRow); + const user = buildUser({ phone: null }); - const result = await verifyEmailOTP(user as any, 'abcdef'); + const result = await verifyEmailOTP(user as any, 'abcdef', A); expect(result.verified).toBe(true); expect(user.emailVerified).toBe(true); expect(user.verified).toBe(true); - expect(user.save).toHaveBeenCalled(); + expect(user.save).toHaveBeenCalledWith({ transaction: {} }); + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: expect.objectContaining({ + channel: 'email', + attemptKey: 'attempt:attempt-a', + destination: 'test@example.com', + codeHash: hashOtpToken('ABCDEF'), + }), + transaction: {}, + }); }); it('returns false for invalid token', async () => { - const user = buildUser({ - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: Date.now() + 10000, - }); + plant(codes, emailRow); + const user = buildUser(); - const result = await verifyEmailOTP(user as any, 'wrong'); + const result = await verifyEmailOTP(user as any, 'wrong', A); expect(result.verified).toBe(false); + expect(user.save).not.toHaveBeenCalled(); }); - it('throws if missing data', async () => { + it('returns false for a code sent to another attempt', async () => { + plant(codes, { ...emailRow, attemptKey: 'attempt:attempt-b' }); const user = buildUser(); - await expect(verifyEmailOTP(user as any, '123')).rejects.toThrow(); + expect((await verifyEmailOTP(user as any, 'abcdef', A)).verified).toBe(false); + expect(user.emailVerified).toBe(false); + }); + + it('fails when the locked row no longer holds the address the code went to', async () => { + plant(codes, emailRow); + const user = buildUser(); + user.reload.mockImplementationOnce(async () => { + user.email = 'changed@example.com'; + }); + + const result = await verifyEmailOTP(user as any, 'abcdef', A); + + expect(result.verified).toBe(false); + expect(user.emailVerified).toBe(false); + expect(user.save).not.toHaveBeenCalled(); + }); + + it('verifies nothing when a concurrent request claimed the code first', async () => { + (OneTimeCode.destroy as any).mockResolvedValueOnce(0); + const user = buildUser({ phone: null }); + + const result = await verifyEmailOTP(user as any, 'abcdef', A); + + expect(result.verified).toBe(false); + expect(user.save).not.toHaveBeenCalled(); + expect(user.emailVerified).toBe(false); + expect(user.verified).toBe(false); + }); + + it('throws when the claim fails', async () => { + (OneTimeCode.destroy as any).mockRejectedValueOnce(new Error('db down')); + + await expect(verifyEmailOTP(buildUser() as any, 'abcdef', A)).rejects.toThrow( + 'Failed to update user verification via email OTP', + ); }); describe('a phone verified before the address was proven', () => { // Anyone can start a registration for an address and verify their own phone on // the account it creates. Only the attempt that verified the phone keeps it. - const pending = (overrides: any = {}) => - buildUser({ - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: Date.now() + 10000, + const pending = (overrides: any = {}, attemptKey = 'attempt:attempt-a') => { + plant(codes, { ...emailRow, attemptKey }); + return buildUser({ phoneVerified: true, phoneVerifiedAttemptId: 'attempt-a', ...overrides, }); + }; it('is kept when the same attempt verifies the email (phone-first sign up)', async () => { const user = pending(); - await verifyEmailOTP(user as any, 'abcdef', 'attempt-a'); + await verifyEmailOTP(user as any, 'abcdef', A, { attemptId: 'attempt-a' }); expect(user.verified).toBe(true); expect(user.phone).toBe('+14155552671'); @@ -275,9 +569,9 @@ describe('OTP utils', () => { }); it('is removed when a different attempt verifies the email', async () => { - const user = pending(); + const user = pending({}, 'attempt:attempt-b'); - await verifyEmailOTP(user as any, 'abcdef', 'attempt-b'); + await verifyEmailOTP(user as any, 'abcdef', B, { attemptId: 'attempt-b' }); expect(user.verified).toBe(true); expect(user.phone).toBeNull(); @@ -288,253 +582,165 @@ describe('OTP utils', () => { it('is removed when the attempt is unknown', async () => { const user = pending(); - await verifyEmailOTP(user as any, 'abcdef'); + await verifyEmailOTP(user as any, 'abcdef', A); expect(user.phone).toBeNull(); expect(user.phoneVerified).toBe(false); }); + it('is removed when it was verified after this request read the account', async () => { + // The stale copy shows no phone; the locked reread shows the one another attempt + // verified meanwhile, and that is what the claim decides from. + const user = pending({ phone: null, phoneVerified: false, phoneVerifiedAttemptId: null }); + user.reload.mockImplementationOnce(async () => { + Object.assign(user, { + phone: '+14155559999', + phoneVerified: true, + phoneVerifiedAttemptId: 'attempt-b', + }); + }); + + const result = await verifyEmailOTP(user as any, 'abcdef', A, { attemptId: 'attempt-a' }); + + expect(result.verified).toBe(true); + expect(user.phone).toBeNull(); + expect(user.phoneVerified).toBe(false); + expect(user.save).toHaveBeenCalledTimes(1); + }); + it('is left alone once the account is already verified', async () => { - const user = pending({ verified: true, emailVerified: true }); + const user = pending({ verified: true, emailVerified: true }, 'attempt:attempt-b'); - await verifyEmailOTP(user as any, 'abcdef', 'attempt-b'); + const result = await verifyEmailOTP(user as any, 'abcdef', B, { attemptId: 'attempt-b' }); + expect(result.verified).toBe(true); expect(user.phone).toBe('+14155552671'); expect(user.phoneVerified).toBe(true); }); }); }); }); + it('rejects legacy plaintext phone OTP values (hashed-only after hardening)', async () => { - const user = buildUser({ - phoneVerificationToken: '123456', - phoneVerificationTokenExpiry: Date.now() + 10000, - emailVerified: true, - }); + plant(codes, { codeHash: '123456' }); - const result = await verifyPhoneOTP(user as any, '123456'); + const result = await verifyPhoneOTP(buildUser({ emailVerified: true }) as any, '123456', A); expect(result.verified).toBe(false); }); it('rejects legacy plaintext email OTP values (hashed-only after hardening)', async () => { - const user = buildUser({ - emailVerificationToken: 'ABCDEF', - emailVerificationTokenExpiry: Date.now() + 10000, - phone: null, - }); + plant(codes, { ...emailRow, codeHash: 'ABCDEF' }); - const result = await verifyEmailOTP(user as any, 'abcdef'); + const result = await verifyEmailOTP(buildUser({ phone: null }) as any, 'abcdef', A); expect(result.verified).toBe(false); }); -describe('OTP regression — hardened behavior', () => { - beforeEach(() => { - vi.clearAllMocks(); - }); - +describe('OTP regression: hardened behavior', () => { it('email OTP round-trips: a generated token verifies against the stored hash', async () => { - const issuingUser = buildUser(); - const token = await generateEmailOTP(issuingUser as any, { sendMessage: false }); - const stored = (issuingUser.update as any).mock.calls[0][0].emailVerificationToken; - - const verifyingUser = buildUser({ - emailVerificationToken: stored, - emailVerificationTokenExpiry: Date.now() + 100000, - }); + const user = buildUser(); + const token = await generateEmailOTP(user as any, A, { sendMessage: false }); - expect((await verifyEmailOTP(verifyingUser as any, token)).verified).toBe(true); + expect((await verifyEmailOTP(user as any, token, A)).verified).toBe(true); }); it('email OTP round-trip is case-insensitive', async () => { - const issuingUser = buildUser(); - const token = await generateEmailOTP(issuingUser as any, { sendMessage: false }); - const stored = (issuingUser.update as any).mock.calls[0][0].emailVerificationToken; - - const verifyingUser = buildUser({ - emailVerificationToken: stored, - emailVerificationTokenExpiry: Date.now() + 100000, - }); + const user = buildUser(); + const token = await generateEmailOTP(user as any, A, { sendMessage: false }); - expect((await verifyEmailOTP(verifyingUser as any, token.toLowerCase())).verified).toBe(true); + expect((await verifyEmailOTP(user as any, token.toLowerCase(), A)).verified).toBe(true); }); it('phone OTP round-trips: a generated token verifies against the stored hash', async () => { - const issuingUser = buildUser(); - const token = await generatePhoneOTP(issuingUser as any, { sendMessage: false }); - const stored = (issuingUser.update as any).mock.calls[0][0].phoneVerificationToken; + const user = buildUser(); + const token = await generatePhoneOTP(user as any, A, { sendMessage: false }); - const verifyingUser = buildUser({ - phoneVerificationToken: stored, - phoneVerificationTokenExpiry: Date.now() + 100000, - }); + expect((await verifyPhoneOTP(user as any, String(token), A)).verified).toBe(true); + }); + + it('a code verifies once', async () => { + const user = buildUser(); + const token = await generatePhoneOTP(user as any, A, { sendMessage: false }); - expect((await verifyPhoneOTP(verifyingUser as any, String(token))).verified).toBe(true); + expect((await verifyPhoneOTP(user as any, String(token), A)).verified).toBe(true); + expect((await verifyPhoneOTP(user as any, String(token), A)).verified).toBe(false); }); - it('stores OTPs hashed at rest (sha256: prefix, never the plaintext code)', async () => { + it('a send for one attempt does not replace the code another attempt holds', async () => { const user = buildUser(); - const token = await generateEmailOTP(user as any, { sendMessage: false }); - const stored = (user.update as any).mock.calls[0][0].emailVerificationToken; + const first = await generatePhoneOTP(user as any, A, { sendMessage: false }); + const second = await generatePhoneOTP(user as any, B, { sendMessage: false }); - expect(stored).toMatch(/^sha256:[a-f0-9]{64}$/); - expect(stored).not.toContain(token); + expect(codes).toHaveLength(2); + expect((await verifyPhoneOTP(user as any, String(second), B)).verified).toBe(true); + expect((await verifyPhoneOTP(user as any, String(first), A)).verified).toBe(true); }); -}); -describe('OTP verification save failures', () => { - beforeEach(() => { - vi.clearAllMocks(); + it('a code does not verify on another attempt', async () => { + const user = buildUser(); + const token = await generateEmailOTP(user as any, A, { sendMessage: false }); + + expect((await verifyEmailOTP(user as any, token, B)).verified).toBe(false); + expect(codes).toHaveLength(1); }); + it('stores OTPs hashed at rest (sha256: prefix, never the plaintext code)', async () => { + const token = await generateEmailOTP(buildUser() as any, A, { sendMessage: false }); + const [{ codeHash }] = (OneTimeCode.create as any).mock.calls[0]; + + expect(codeHash).toMatch(/^sha256:[a-f0-9]{64}$/); + expect(codeHash).not.toContain(token); + }); +}); + +describe('OTP verification save failures', () => { it('throws when persisting a verified phone OTP fails', async () => { + plant(codes); const user = buildUser({ - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: Date.now() + 10000, emailVerified: true, save: vi.fn().mockRejectedValue(new Error('db down')), }); - await expect(verifyPhoneOTP(user as any, '123456')).rejects.toThrow( + await expect(verifyPhoneOTP(user as any, '123456', A)).rejects.toThrow( 'Failed to update user verification via phone OTP', ); expect(user.save).toHaveBeenCalled(); }); it('throws when persisting a verified email OTP fails', async () => { + plant(codes, emailRow); const user = buildUser({ - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: Date.now() + 10000, phone: null, save: vi.fn().mockRejectedValue(new Error('db down')), }); - await expect(verifyEmailOTP(user as any, 'abcdef')).rejects.toThrow( + await expect(verifyEmailOTP(user as any, 'abcdef', A)).rejects.toThrow( 'Failed to update user verification via email OTP', ); expect(user.save).toHaveBeenCalled(); }); it('leaves an already-verified user verified after email OTP', async () => { - const user = buildUser({ - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: Date.now() + 10000, - phone: null, - verified: true, - }); + plant(codes, emailRow); + const user = buildUser({ phone: null, verified: true }); - const result = await verifyEmailOTP(user as any, 'abcdef'); + const result = await verifyEmailOTP(user as any, 'abcdef', A); expect(result.verified).toBe(true); expect(user.verified).toBe(true); }); -}); - -describe('OTP consumption under concurrency', () => { - // Two requests holding the same valid code both pass the comparison, so the clear is - // conditional on the issuance that was compared and only one of them may win it. - beforeEach(() => { - vi.clearAllMocks(); - }); - - const emailPending = (overrides: any = {}) => - buildUser({ - id: 'user-1', - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: 1_900_000_000_000, - phone: null, - ...overrides, - }); - - const phonePending = (overrides: any = {}) => - buildUser({ - id: 'user-1', - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: 1_900_000_000_000, - emailVerified: true, - ...overrides, - }); - - it('clears the email OTP only where it still holds the compared issuance', async () => { - const user = emailPending(); - - await expect(verifyEmailOTP(user as any, 'abcdef')).resolves.toMatchObject({ - verified: true, - }); - - expect(User.update).toHaveBeenCalledWith( - { emailVerificationToken: null, emailVerificationTokenExpiry: null }, - { - where: { - id: 'user-1', - emailVerificationToken: hashOtpToken('ABCDEF'), - emailVerificationTokenExpiry: 1_900_000_000_000, - }, - transaction: expect.anything(), - }, - ); - expect(user.save).toHaveBeenCalledWith({ transaction: expect.anything() }); - }); - - it('fails the email OTP when a concurrent verification already consumed it', async () => { - (User.update as any).mockResolvedValueOnce([0]); - const user = emailPending(); - - const result = await verifyEmailOTP(user as any, 'abcdef'); - - expect(result.verified).toBe(false); - expect(user.save).not.toHaveBeenCalled(); - expect(user.emailVerified).toBe(false); - expect(user.verified).toBe(false); - }); - - it('clears the phone OTP only where it still holds the compared issuance', async () => { - const user = phonePending(); - - await expect(verifyPhoneOTP(user as any, '123456')).resolves.toMatchObject({ - verified: true, - }); - - expect(User.update).toHaveBeenCalledWith( - { phoneVerificationToken: null, phoneVerificationTokenExpiry: null }, - { - where: { - id: 'user-1', - phoneVerificationToken: hashOtpToken('123456'), - phoneVerificationTokenExpiry: 1_900_000_000_000, - }, - transaction: expect.anything(), - }, - ); - expect(user.save).toHaveBeenCalledWith({ transaction: expect.anything() }); - }); - - it('fails the phone OTP when a concurrent verification already consumed it', async () => { - (User.update as any).mockResolvedValueOnce([0]); - const user = phonePending(); - - const result = await verifyPhoneOTP(user as any, '123456', 'attempt-a'); - - expect(result.verified).toBe(false); - expect(user.save).not.toHaveBeenCalled(); - expect(user.phoneVerified).toBe(false); - expect(user.phoneVerifiedAttemptId).toBeUndefined(); - }); - - it('throws when the conditional email OTP clear fails', async () => { - (User.update as any).mockRejectedValueOnce(new Error('db down')); - await expect(verifyEmailOTP(emailPending() as any, 'abcdef')).rejects.toThrow( - 'Failed to update user verification via email OTP', - ); - }); + it('runs the claim and the save in one transaction', async () => { + const tx = { id: 'tx' }; + (User.sequelize!.transaction as any).mockImplementationOnce((fn: any) => fn(tx)); + plant(codes); + const user = buildUser(); - it('throws when the conditional phone OTP clear fails', async () => { - (User.update as any).mockRejectedValueOnce(new Error('db down')); + await verifyPhoneOTP(user as any, '123456', A); - await expect(verifyPhoneOTP(phonePending() as any, '123456')).rejects.toThrow( - 'Failed to update user verification via phone OTP', - ); + expect(OneTimeCode.destroy).toHaveBeenCalledWith(expect.objectContaining({ transaction: tx })); + expect(user.reload).toHaveBeenCalledWith({ transaction: tx, lock: true }); + expect(user.save).toHaveBeenCalledWith({ transaction: tx }); }); }); From 2071ec871d78912a39dba52bf371ba4ef4087146 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 4 Dec 2026 22:55:57 -0500 Subject: [PATCH 2/2] fix(otp): drop other attempts' codes on a claim and refuse unscoped codes --- .changeset/per-attempt-one-time-codes.md | 3 +- src/controllers/magicLinks.ts | 13 +++++- src/lib/otpScope.ts | 23 +++++++++++ src/services/accountClaim.ts | 22 +++++++++- src/services/oauthService.ts | 6 ++- src/utils/otp.ts | 38 +++++++----------- tests/integration/magicLink/magicLink.spec.ts | 7 ++++ .../integration/registration/register.spec.ts | 2 +- tests/postgres/oneTimeCodes.spec.ts | 17 +++++++- tests/unit/services/accountClaim.spec.ts | 40 ++++++++++++++++++- tests/unit/services/oauthService.spec.ts | 6 +++ tests/unit/utils/otp.spec.ts | 17 +++++++- 12 files changed, 159 insertions(+), 35 deletions(-) create mode 100644 src/lib/otpScope.ts diff --git a/.changeset/per-attempt-one-time-codes.md b/.changeset/per-attempt-one-time-codes.md index e86dabb7..bf94040b 100644 --- a/.changeset/per-attempt-one-time-codes.md +++ b/.changeset/per-attempt-one-time-codes.md @@ -10,6 +10,7 @@ Before, every email and phone code for an account lived in one pair of columns o - **Breaking:** a code verifies only on the attempt that requested it. A client that starts a new attempt (a second `POST /login`, for example) must send a new code on that attempt rather than submit one sent to the earlier one. - A code also verifies only while the account still holds the address it was sent to. - Spending a code and applying the verification happen under a lock on the user row, so a verification and an account claim racing each other can no longer act on a stale copy of the account. Magic link and OAuth claims take the same lock. +- Claiming an unverified account (by email code, magic link or OAuth) drops the codes other attempts requested before the address was proven. - Account recovery always opens its own `awaiting_code` request. A resume records the request it resumes (`resumesRequestId`) and no longer replaces the owner's code on it. -The migration adds the table and the column. The old code columns on `users` stay in place and are no longer read, so an instance on the previous release keeps working during a rolling deploy. A code sent by the previous release does not verify on this one; it expires within five minutes and a new one can be sent. +The migration adds the table and the column. The old code columns on `users` stay in place and are no longer read, so an instance on the previous release keeps working during a rolling deploy. A code sent by the previous release does not verify on this one; it expires within five minutes and a new one can be sent. A recovery resume started on this release but verified on an instance still running the previous one opens a new recovery request instead of resuming, which only restarts the delay. diff --git a/src/controllers/magicLinks.ts b/src/controllers/magicLinks.ts index 76515196..bb6e190f 100644 --- a/src/controllers/magicLinks.ts +++ b/src/controllers/magicLinks.ts @@ -17,7 +17,11 @@ import { MagicLinkConfirmBodySchema, MagicLinkRequestQuerySchema, } from '../schemas/magiclink.requests.js'; -import { claimUnverifiedAccount, withLockedUser } from '../services/accountClaim.js'; +import { + claimUnverifiedAccount, + discardOtherAttemptsCodes, + withLockedUser, +} from '../services/accountClaim.js'; import { AuthEventService } from '../services/authEventService.js'; import { rejectWeakFactorForBreakGlass } from '../services/breakGlassService.js'; import { passkeyEnrollmentPrompt } from '../services/enrollmentService.js'; @@ -469,7 +473,12 @@ export async function pollMagicLinkConfirmation(req: Request, res: Response) { req, }); - await withLockedUser(user, (locked) => claimUnverifiedAccount(locked, authReq.attemptId)); + await withLockedUser(user, async (locked, transaction) => { + if (!claimUnverifiedAccount(locked, authReq.attemptId)) return false; + + await discardOtherAttemptsCodes(locked, { attemptId: authReq.attemptId }, transaction); + return true; + }); // A different route completed the sign-in, so any half-finished WebAuthn // ceremony for this user should not still be redeemable. diff --git a/src/lib/otpScope.ts b/src/lib/otpScope.ts new file mode 100644 index 00000000..f071bef9 --- /dev/null +++ b/src/lib/otpScope.ts @@ -0,0 +1,23 @@ +/* + * Copyright © 2026 Fells Code, LLC + * Licensed under the Apache License, Version 2.0 + * See LICENSE file in the project root for full license information + */ + +/** + * Who a code belongs to: the sign-in or registration attempt an ephemeral token carries, + * or the access session that asked for it. A code is only checked against the codes its + * own attempt was sent, so a send from another attempt neither replaces it nor can be + * used in its place. + */ +export interface OtpScope { + attemptId?: string; + sessionId?: string; +} + +export function otpAttemptKey(scope: OtpScope): string { + if (scope.attemptId) return `attempt:${scope.attemptId}`; + if (scope.sessionId) return `session:${scope.sessionId}`; + // Codes from callers with no scope would all share one slot, the thing this table removes. + throw new Error('A one-time code needs an attempt or session scope'); +} diff --git a/src/services/accountClaim.ts b/src/services/accountClaim.ts index 3fde6c0f..3fd71499 100644 --- a/src/services/accountClaim.ts +++ b/src/services/accountClaim.ts @@ -4,8 +4,10 @@ * See LICENSE file in the project root for full license information */ -import type { Transaction } from 'sequelize'; +import { Op, type Transaction } from 'sequelize'; +import { otpAttemptKey, type OtpScope } from '../lib/otpScope.js'; +import { OneTimeCode } from '../models/oneTimeCodes.js'; import { User } from '../models/users.js'; /** @@ -58,3 +60,21 @@ export async function withLockedUser( return transaction ? run(transaction) : User.sequelize!.transaction(run); } + +/** + * Drops the codes other attempts are still waiting on, once an account has been claimed. + * They were requested before anyone proved the address, so none may finish a flow on the + * account it now is. With no scope, every pending code goes. + */ +export async function discardOtherAttemptsCodes( + user: User, + scope: OtpScope | null, + transaction: Transaction, +): Promise { + const keep = scope?.attemptId || scope?.sessionId ? otpAttemptKey(scope) : null; + + await OneTimeCode.destroy({ + where: keep ? { userId: user.id, attemptKey: { [Op.ne]: keep } } : { userId: user.id }, + transaction, + }); +} diff --git a/src/services/oauthService.ts b/src/services/oauthService.ts index 34828115..84136c81 100644 --- a/src/services/oauthService.ts +++ b/src/services/oauthService.ts @@ -22,7 +22,7 @@ import { UserExternalId } from '../models/userExternalIds.js'; import { User } from '../models/users.js'; import type { OAuthProviderConfig } from '../schemas/systemConfig.schema.js'; import getLogger from '../utils/logger.js'; -import { withLockedUser } from './accountClaim.js'; +import { discardOtherAttemptsCodes, withLockedUser } from './accountClaim.js'; import { normalizeLoginPolicy } from './loginPolicyService.js'; import { discoverOAuthEndpoints } from './oauthDiscovery.js'; import { claimOAuthStateUse } from './oidcPayloadStore.js'; @@ -793,9 +793,11 @@ function parseOAuthProfile( * phone (an imported one) is kept. */ async function claimUnverifiedAccount(user: User, emailVerified: boolean) { - await withLockedUser(user, (locked) => { + await withLockedUser(user, async (locked, transaction) => { if (locked.verified) return false; + await discardOtherAttemptsCodes(locked, null, transaction); + locked.verified = true; if (emailVerified) locked.emailVerified = true; locked.phoneVerifiedAttemptId = null; diff --git a/src/utils/otp.ts b/src/utils/otp.ts index 872fce32..372dcc4e 100644 --- a/src/utils/otp.ts +++ b/src/utils/otp.ts @@ -5,12 +5,17 @@ */ import { randomInt, timingSafeEqual } from 'crypto'; -import { Op, UniqueConstraintError } from 'sequelize'; +import { Op, type Transaction, UniqueConstraintError } from 'sequelize'; +import { otpAttemptKey, type OtpScope } from '../lib/otpScope.js'; import { reviewCodeFor } from '../lib/reviewAccounts.js'; import { OneTimeCode, OneTimeCodeChannel } from '../models/oneTimeCodes.js'; import { User } from '../models/users.js'; -import { claimUnverifiedAccount, withLockedUser } from '../services/accountClaim.js'; +import { + claimUnverifiedAccount, + discardOtherAttemptsCodes, + withLockedUser, +} from '../services/accountClaim.js'; import { sendOTPEmail, sendOTPSMS } from '../services/messagingService.js'; import getLogger from './logger.js'; import { hashSha256 } from './utils.js'; @@ -53,22 +58,7 @@ export function otpHashMatches(storedHash: string, code: string) { const OTP_TTL_MS = 5 * 60 * 1000; -/** - * Who a code belongs to: the sign-in or registration attempt an ephemeral token carries, - * or the access session that asked for it. A code is only checked against the codes its - * own attempt was sent, so a send from another attempt neither replaces it nor can be - * used in its place. - */ -export interface OtpScope { - attemptId?: string; - sessionId?: string; -} - -export function otpAttemptKey(scope: OtpScope): string { - if (scope.attemptId) return `attempt:${scope.attemptId}`; - if (scope.sessionId) return `session:${scope.sessionId}`; - return 'unscoped'; -} +export { otpAttemptKey, type OtpScope } from '../lib/otpScope.js'; async function storeOtp( user: User, @@ -127,7 +117,7 @@ async function consumeOtp( destination: string | null, code: string, scope: OtpScope, - apply: (user: User) => boolean, + apply: (user: User, transaction: Transaction) => boolean | Promise, ): Promise { if (!destination) return false; @@ -148,9 +138,9 @@ async function consumeOtp( return withLockedUser( user, - (locked) => { + async (locked, tx) => { const current = channel === 'email' ? locked.email : locked.phone; - return current === destination && apply(locked); + return current === destination && apply(locked, tx); }, transaction, ); @@ -289,9 +279,11 @@ export const verifyEmailOTP = async ( user.email, normalizeEmailOtp(verificationToken), scope, - (locked) => { + async (locked, transaction) => { locked.emailVerified = true; - claimUnverifiedAccount(locked, options.attemptId); + if (claimUnverifiedAccount(locked, options.attemptId)) { + await discardOtherAttemptsCodes(locked, scope, transaction); + } return true; }, ); diff --git a/tests/integration/magicLink/magicLink.spec.ts b/tests/integration/magicLink/magicLink.spec.ts index 0af1367e..d9d6cf55 100644 --- a/tests/integration/magicLink/magicLink.spec.ts +++ b/tests/integration/magicLink/magicLink.spec.ts @@ -1,8 +1,10 @@ import { mintInternalServiceToken } from '../../factories/serviceTokenFactory.js'; +import { Op } from 'sequelize'; import request from 'supertest'; import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { Application } from 'express'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { User } from '../../../src/models/users.js'; import { Credential } from '../../../src/models/credentials.js'; import { MagicLinkToken } from '../../../src/models/magicLinks.js'; @@ -901,6 +903,10 @@ describe('magic link attempt binding and redemption', () => { ); expect(user.reload).toHaveBeenCalledWith(expect.objectContaining({ lock: true })); expect(user.save).toHaveBeenCalled(); + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { userId: user.id, attemptKey: { [Op.ne]: expect.stringMatching(/^attempt:/) } }, + transaction: expect.anything(), + }); }); it('decides the claim from the locked row, not the copy loaded before it', async () => { @@ -924,6 +930,7 @@ describe('magic link attempt binding and redemption', () => { expect(res.status).toBe(200); expect(user).toEqual(expect.objectContaining({ phone: '+15550100', phoneVerified: true })); expect(user.save).not.toHaveBeenCalled(); + expect(OneTimeCode.destroy).not.toHaveBeenCalled(); }); it('keeps a phone the same attempt verified', async () => { diff --git a/tests/integration/registration/register.spec.ts b/tests/integration/registration/register.spec.ts index 5a28f772..f3c4efc6 100644 --- a/tests/integration/registration/register.spec.ts +++ b/tests/integration/registration/register.spec.ts @@ -647,7 +647,7 @@ describe('POST /registration/phone/verify', () => { const user = buildUser({ phone: '+14155552671' }); (OneTimeCode.count as any).mockResolvedValue(1); - await verifyRegisteredPhone(buildReq({ user, body: {} }), res); + await verifyRegisteredPhone(buildReq({ user, body: {}, sessionId: 'session-1' }), res); expect(res.status).toHaveBeenCalledWith(401); expect(res.json).toHaveBeenCalledWith({ error: 'Not allowed' }); diff --git a/tests/postgres/oneTimeCodes.spec.ts b/tests/postgres/oneTimeCodes.spec.ts index 73683458..a4448fa0 100644 --- a/tests/postgres/oneTimeCodes.spec.ts +++ b/tests/postgres/oneTimeCodes.spec.ts @@ -32,7 +32,7 @@ afterAll(async () => { // the first was waiting on. Each attempt now holds its own row. describe('one-time codes per attempt', () => { it('keeps a code for each attempt, and each verifies only on its own', async () => { - const user = await createUser(); + const user = await createUser({ verified: true, emailVerified: true }); const a = { attemptId: randomUUID() }; const b = { attemptId: randomUUID() }; @@ -51,6 +51,19 @@ describe('one-time codes per attempt', () => { expect(await OneTimeCode.count({ where: { userId: user.id } })).toBe(0); }); + it("drops other attempts' codes when one attempt claims the account", async () => { + const user = await createUser({ phone: `+1415${String(Date.now()).slice(-7)}` }); + const owner = { attemptId: randomUUID() }; + const other = { attemptId: randomUUID() }; + + const ownerCode = await generateEmailOTP(user, owner, send); + const otherPhoneCode = await generatePhoneOTP(user, other, send); + + expect((await verifyEmailOTP(user, ownerCode, owner)).verified).toBe(true); + expect(await OneTimeCode.count({ where: { userId: user.id } })).toBe(0); + expect((await verifyPhoneOTP(user, String(otherPhoneCode), other)).verified).toBe(false); + }); + it('does not verify a code on an attempt that was never sent one', async () => { const user = await createUser({ phone: `+1415${String(Date.now()).slice(-7)}` }); const a = { attemptId: randomUUID() }; @@ -63,7 +76,7 @@ describe('one-time codes per attempt', () => { expect((await verifyPhoneOTP(user, String(code), { sessionId: randomUUID() })).verified).toBe( false, ); - expect((await verifyPhoneOTP(user, String(code), {})).verified).toBe(false); + await expect(verifyPhoneOTP(user, String(code), {})).rejects.toThrow(); await expect(User.findByPk(user.id)).resolves.toMatchObject({ phoneVerified: false }); expect((await verifyPhoneOTP(user, String(code), a)).verified).toBe(true); diff --git a/tests/unit/services/accountClaim.spec.ts b/tests/unit/services/accountClaim.spec.ts index 55df31e5..8c58f08e 100644 --- a/tests/unit/services/accountClaim.spec.ts +++ b/tests/unit/services/accountClaim.spec.ts @@ -1,7 +1,13 @@ +import { Op } from 'sequelize'; import { describe, expect, it, vi } from 'vitest'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { User } from '../../../src/models/users.js'; -import { claimUnverifiedAccount, withLockedUser } from '../../../src/services/accountClaim.js'; +import { + claimUnverifiedAccount, + discardOtherAttemptsCodes, + withLockedUser, +} from '../../../src/services/accountClaim.js'; function user(overrides: Record = {}) { return { @@ -118,3 +124,35 @@ describe('withLockedUser', () => { expect(account.save).not.toHaveBeenCalled(); }); }); + +describe('discardOtherAttemptsCodes', () => { + const tx = {} as never; + const account = { id: 'user-1' } as never; + + it("keeps only the claiming attempt's codes", async () => { + await discardOtherAttemptsCodes(account, { attemptId: 'a' }, tx); + + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { userId: 'user-1', attemptKey: { [Op.ne]: 'attempt:a' } }, + transaction: tx, + }); + }); + + it('keys on the session when there is no attempt', async () => { + await discardOtherAttemptsCodes(account, { sessionId: 's' }, tx); + + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { userId: 'user-1', attemptKey: { [Op.ne]: 'session:s' } }, + transaction: tx, + }); + }); + + it.each([[null], [{}]])('drops every pending code without a scope (%o)', async (scope) => { + await discardOtherAttemptsCodes(account, scope, tx); + + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { userId: 'user-1' }, + transaction: tx, + }); + }); +}); diff --git a/tests/unit/services/oauthService.spec.ts b/tests/unit/services/oauthService.spec.ts index 6f13ba09..35c85285 100644 --- a/tests/unit/services/oauthService.spec.ts +++ b/tests/unit/services/oauthService.spec.ts @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; import { OAuthIdentity } from '../../../src/models/oauthIdentities.js'; +import { OneTimeCode } from '../../../src/models/oneTimeCodes.js'; import { User } from '../../../src/models/users.js'; import { buildOAuthAuthorizationUrl, @@ -1182,6 +1183,10 @@ describe('oauthService', () => { phoneVerified: false, phoneVerifiedAttemptId: null, }); + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { userId: imported.id }, + transaction: expect.anything(), + }); }); it('leaves an account another request claimed first, deciding from the locked row', async () => { @@ -1202,6 +1207,7 @@ describe('oauthService', () => { expect(imported.save).not.toHaveBeenCalled(); expect(imported).toMatchObject({ phone: '+14155552671', phoneVerified: true }); + expect(OneTimeCode.destroy).not.toHaveBeenCalled(); }); it('keeps an unverified phone, such as an imported one, when the account is claimed', async () => { diff --git a/tests/unit/utils/otp.spec.ts b/tests/unit/utils/otp.spec.ts index b326e7c0..cb58be47 100644 --- a/tests/unit/utils/otp.spec.ts +++ b/tests/unit/utils/otp.spec.ts @@ -136,10 +136,10 @@ describe('OTP utils', () => { }); describe('otpAttemptKey', () => { - it('keys on the attempt, then the session, then nothing', () => { + it('keys on the attempt, then the session, and refuses neither', () => { expect(otpAttemptKey({ attemptId: 'a', sessionId: 's' })).toBe('attempt:a'); expect(otpAttemptKey({ sessionId: 's' })).toBe('session:s'); - expect(otpAttemptKey({})).toBe('unscoped'); + expect(() => otpAttemptKey({})).toThrow('needs an attempt or session scope'); }); }); @@ -491,6 +491,19 @@ describe('OTP utils', () => { }), transaction: {}, }); + // The claim drops codes other attempts requested before the address was proven. + expect(OneTimeCode.destroy).toHaveBeenCalledWith({ + where: { userId: user.id, attemptKey: { [Op.ne]: 'attempt:attempt-a' } }, + transaction: {}, + }); + }); + + it("leaves other attempts' codes alone on an account that was already claimed", async () => { + plant(codes, emailRow); + const user = buildUser({ phone: null, verified: true, emailVerified: true }); + + expect((await verifyEmailOTP(user as any, 'abcdef', A)).verified).toBe(true); + expect(OneTimeCode.destroy).toHaveBeenCalledTimes(1); }); it('returns false for invalid token', async () => {