From 44dd86d7492b9015886b1beaa0506c5682ef50bb Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 4 Dec 2026 22:42:22 -0500 Subject: [PATCH 1/2] fix(registration): make phone numbers unique only once verified A unique constraint over every row let anyone attach a stranger's number to an account of their own without proving it, so its owner could never add it, and the 409 from /registration/phone told any signed-in caller which numbers were registered. Only verified numbers are unique now; a code goes out either way and a number another account has verified is refused at verification. --- .changeset/unverified-phone-squatting.md | 14 ++++ openapi.json | 42 +++++++---- src/controllers/otp.ts | 11 +++ src/controllers/registration.ts | 43 ++++++------ src/generated/api.ts | 69 +++++++++++++------ src/lib/phoneInUse.ts | 28 ++++++++ .../20261204130000-unique-verified-phone.cjs | 36 ++++++++++ src/models/users.ts | 3 +- src/routes/otp.routes.ts | 2 + src/routes/registration.routes.ts | 7 +- .../integration/registration/register.spec.ts | 49 +++++++++++-- tests/postgres/verifiedPhoneUnique.spec.ts | 50 ++++++++++++++ tests/unit/controllers/otp.spec.ts | 21 ++++++ tests/unit/lib/phoneInUse.spec.ts | 27 ++++++++ 14 files changed, 339 insertions(+), 63 deletions(-) create mode 100644 .changeset/unverified-phone-squatting.md create mode 100644 src/lib/phoneInUse.ts create mode 100644 src/migrations/20261204130000-unique-verified-phone.cjs create mode 100644 tests/postgres/verifiedPhoneUnique.spec.ts create mode 100644 tests/unit/lib/phoneInUse.spec.ts diff --git a/.changeset/unverified-phone-squatting.md b/.changeset/unverified-phone-squatting.md new file mode 100644 index 00000000..16e43cd3 --- /dev/null +++ b/.changeset/unverified-phone-squatting.md @@ -0,0 +1,14 @@ +--- +'seamless-auth-api': minor +--- + +Phone numbers are now unique only once verified, and `POST /registration/phone` no longer answers 409. + +Before, a unique constraint covered every row. Registering a stranger's number on an account, without proving it, kept the number's owner from ever adding it. The 409 from `POST /registration/phone` also told any signed-in caller whether a number was registered. Now: + +- A migration replaces the `users_phone_key` unique constraint with a unique index on `phone` where `phone_verified` is true. Any number of unverified accounts may hold the same number. Verifying it claims it. +- `POST /registration/register` drops a supplied phone only when another account has verified it. +- **Breaking:** `POST /registration/phone` sends a code whether or not another account holds the number, and no longer answers 409. +- **Breaking:** `POST /registration/phone/verify` and `POST /otp/verify-phone-otp` answer 409 (`Phone number in use`) when another account has already verified the number. That is the only point where it shows, and only to someone who has just proven they hold the phone. + +The down migration restores the full unique constraint and fails if two accounts hold the same number. diff --git a/openapi.json b/openapi.json index 4955a6a7..d5d034f4 100644 --- a/openapi.json +++ b/openapi.json @@ -28237,6 +28237,7 @@ "/otp/verify-phone-otp": { "post": { "summary": "Verify phone OTP", + "description": "Answers 409 when another account has already verified the number.", "tags": ["OTP"], "security": [{ "bearerAuth": [] }], "requestBody": { @@ -28357,6 +28358,19 @@ } } }, + "409": { + "description": "HTTP 409", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, "429": { "description": "HTTP 429", "content": { @@ -29268,6 +29282,7 @@ "/registration/phone": { "post": { "summary": "Register a phone number for the authenticated user", + "description": "Sends a code whether or not another account holds the number, so the answer does not say which numbers are registered. A number another account has verified is refused at verification with 409.", "tags": ["Registration"], "security": [{ "bearerAuth": [] }], "requestBody": { @@ -29485,19 +29500,6 @@ } } }, - "409": { - "description": "HTTP 409", - "content": { - "application/json": { - "example": { "message": "string", "error": "string" }, - "schema": { - "type": "object", - "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, - "required": ["error"] - } - } - } - }, "429": { "description": "HTTP 429", "content": { @@ -29530,6 +29532,7 @@ "/registration/phone/verify": { "post": { "summary": "Verify the authenticated user phone number", + "description": "Answers 409 when another account has already verified the number.", "tags": ["Registration"], "security": [{ "bearerAuth": [] }], "requestBody": { @@ -29670,6 +29673,19 @@ } } }, + "409": { + "description": "HTTP 409", + "content": { + "application/json": { + "example": { "message": "string", "error": "string" }, + "schema": { + "type": "object", + "properties": { "message": { "type": "string" }, "error": { "type": "string" } }, + "required": ["error"] + } + } + } + }, "429": { "description": "HTTP 429", "content": { diff --git a/src/controllers/otp.ts b/src/controllers/otp.ts index fa2f4e98..9b53fcd3 100644 --- a/src/controllers/otp.ts +++ b/src/controllers/otp.ts @@ -7,6 +7,7 @@ import { Request, Response } from 'express'; import { canReturnExternalDelivery } from '../lib/externalDelivery.js'; +import { isPhoneInUseError, PHONE_IN_USE_BODY } from '../lib/phoneInUse.js'; import { reviewAccountMetadata } from '../lib/reviewAccounts.js'; import { reissueEphemeralToken } from '../lib/token.js'; import { AuthEventService } from '../services/authEventService.js'; @@ -372,6 +373,16 @@ export const verifyPhoneNumber = async (req: Request, res: Response) => { return res.status(401).json({ error: 'Not allowed' }); } } catch (error) { + if (isPhoneInUseError(error)) { + await AuthEventService.log({ + userId: user.id, + type: 'verify_otp_failed', + req, + metadata: { reason: 'Phone already verified on another account.' }, + }); + return res.status(409).json(PHONE_IN_USE_BODY); + } + logger.error(`Failed to verify OTP: ${error}`); return res.status(500).json({ error: 'Internal server error' }); } diff --git a/src/controllers/registration.ts b/src/controllers/registration.ts index e2090a16..431b0e70 100644 --- a/src/controllers/registration.ts +++ b/src/controllers/registration.ts @@ -12,6 +12,7 @@ import { getSystemConfig } from '../config/getSystemConfig.js'; import { EPHEMERAL_TOKEN_TTL_SECONDS } from '../lib/ephemeralTokenTtl.js'; import { canReturnExternalDelivery } from '../lib/externalDelivery.js'; import { withOwnerAdminRole } from '../lib/ownerAdmin.js'; +import { isPhoneInUseError, PHONE_IN_USE_BODY } from '../lib/phoneInUse.js'; import { reviewAccountMetadata } from '../lib/reviewAccounts.js'; import { signEphemeralToken } from '../lib/token.js'; import { User } from '../models/users.js'; @@ -112,7 +113,9 @@ export const register = async (req: Request, res: Response) => { const [existingEmailUser, existingPhoneUser] = await Promise.all([ User.findOne({ where: { email: normalizedEmail } }), - normalizedPhone ? User.findOne({ where: { phone: normalizedPhone } }) : Promise.resolve(null), + normalizedPhone + ? User.findOne({ where: { phone: normalizedPhone, phoneVerified: true } }) + : Promise.resolve(null), ]); // Recorded rather than refused. Answering 409 told an unauthenticated caller whether @@ -138,8 +141,9 @@ export const register = async (req: Request, res: Response) => { }); } - // A phone already held by another account is dropped rather than attached, so a - // conflicting one cannot change the answer or breach the unique constraint. + // A phone another account has verified is dropped rather than attached, so a + // conflicting one cannot change the answer. One only attached elsewhere is no conflict: + // unproven numbers do not hold the number against its owner. const attachablePhone = existingPhoneUser ? null : normalizedPhone; let user: User; @@ -172,8 +176,7 @@ export const register = async (req: Request, res: Response) => { const raced = await User.findOne({ where: { email: normalizedEmail } }); - // Something other than this address, so there is no account to continue as. The - // unique index on phone is the only other one an insert here can breach. + // Something other than this address, so there is no account to continue as. if (!raced) throw error; logger.info('Registration raced another request for the same address'); @@ -309,22 +312,10 @@ export const registerPhone = async (req: Request, res: Response) => { return res.status(400).json({ error: 'Invalid data' }); } - const existingPhoneUser = await User.findOne({ where: { phone: normalizedPhone } }); - - if (existingPhoneUser && existingPhoneUser.id !== user.id) { - await AuthEventService.log({ - userId: user.id, - type: 'registration_suspicious', - req, - metadata: { reason: 'Phone registration attempted with an in-use phone number.' }, - }); - - return res.status(409).json({ - error: 'Phone number in use', - message: 'The provided phone number is already registered to another account.', - }); - } - + // No answer here says whether another account holds the number: that would tell any + // signed-in caller which numbers are registered. A code goes out either way, and a + // number another account has verified is refused only at verification, to the person + // who has just shown they hold it. const phoneChanged = user.phone !== normalizedPhone; await user.update({ @@ -432,6 +423,16 @@ export const verifyRegisteredPhone = async (req: Request, res: Response) => { return res.status(200).json({ message: 'Success' }); } catch (error: unknown) { + if (isPhoneInUseError(error)) { + await AuthEventService.log({ + userId: user.id, + type: 'verify_otp_failed', + req, + metadata: { reason: 'Phone already verified on another account.' }, + }); + return res.status(409).json(PHONE_IN_USE_BODY); + } + logger.error(`Failed to verify registered phone: ${String(error)}`); return res.status(500).json({ error: 'Internal server error' }); } diff --git a/src/generated/api.ts b/src/generated/api.ts index 1d54d40c..d690f484 100644 --- a/src/generated/api.ts +++ b/src/generated/api.ts @@ -26556,7 +26556,10 @@ export interface paths { }; get?: never; put?: never; - /** Verify phone OTP */ + /** + * Verify phone OTP + * @description Answers 409 when another account has already verified the number. + */ post: { parameters: { query?: never; @@ -26679,6 +26682,24 @@ export interface paths { }; }; }; + /** @description HTTP 409 */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; /** @description HTTP 429 */ 429: { headers: { @@ -27736,7 +27757,10 @@ export interface paths { }; get?: never; put?: never; - /** Register a phone number for the authenticated user */ + /** + * Register a phone number for the authenticated user + * @description Sends a code whether or not another account holds the number, so the answer does not say which numbers are registered. A number another account has verified is refused at verification with 409. + */ post: { parameters: { query?: never; @@ -27915,24 +27939,6 @@ export interface paths { }; }; }; - /** @description HTTP 409 */ - 409: { - headers: { - [name: string]: unknown; - }; - content: { - /** - * @example { - * "message": "string", - * "error": "string" - * } - */ - 'application/json': { - message?: string; - error: string; - }; - }; - }; /** @description HTTP 429 */ 429: { headers: { @@ -27986,7 +27992,10 @@ export interface paths { }; get?: never; put?: never; - /** Verify the authenticated user phone number */ + /** + * Verify the authenticated user phone number + * @description Answers 409 when another account has already verified the number. + */ post: { parameters: { query?: never; @@ -28120,6 +28129,24 @@ export interface paths { }; }; }; + /** @description HTTP 409 */ + 409: { + headers: { + [name: string]: unknown; + }; + content: { + /** + * @example { + * "message": "string", + * "error": "string" + * } + */ + 'application/json': { + message?: string; + error: string; + }; + }; + }; /** @description HTTP 429 */ 429: { headers: { diff --git a/src/lib/phoneInUse.ts b/src/lib/phoneInUse.ts new file mode 100644 index 00000000..fdbfb8b3 --- /dev/null +++ b/src/lib/phoneInUse.ts @@ -0,0 +1,28 @@ +/* + * 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 { UniqueConstraintError } from 'sequelize'; + +/** + * Whether verifying a phone failed because another account had already verified the same + * number. Only verified numbers are unique, so this is the one point where it can show, and + * only to someone who has just proven they hold the phone. + */ +export function isPhoneInUseError(error: unknown): boolean { + let current: unknown = error; + + for (let depth = 0; current instanceof Error && depth < 5; depth++) { + if (current instanceof UniqueConstraintError) return true; + current = current.cause; + } + + return false; +} + +export const PHONE_IN_USE_BODY = { + error: 'Phone number in use', + message: 'This phone number is already verified on another account.', +} as const; diff --git a/src/migrations/20261204130000-unique-verified-phone.cjs b/src/migrations/20261204130000-unique-verified-phone.cjs new file mode 100644 index 00000000..3619f444 --- /dev/null +++ b/src/migrations/20261204130000-unique-verified-phone.cjs @@ -0,0 +1,36 @@ +/* + * 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'; + +/** + * Phone numbers are unique only once verified. A unique constraint over every row let anyone + * register a stranger's number on an account of their own without proving it, and the + * number's owner could then never add it. Any number of unverified rows may now hold the + * same number; verifying it is what claims it. + * + * Existing data already satisfies the partial index. The down migration fails if two rows + * hold the same number, which only this migration allows. + * + * @type {import('sequelize-cli').Migration} + */ +module.exports = { + async up(queryInterface) { + await queryInterface.sequelize.query(` + CREATE UNIQUE INDEX IF NOT EXISTS users_verified_phone_key + ON public.users USING btree (phone) WHERE phone_verified = true; + + ALTER TABLE public.users DROP CONSTRAINT IF EXISTS users_phone_key; + `); + }, + + async down(queryInterface) { + await queryInterface.sequelize.query(` + ALTER TABLE public.users ADD CONSTRAINT users_phone_key UNIQUE (phone); + DROP INDEX IF EXISTS public.users_verified_phone_key; + `); + }, +}; diff --git a/src/models/users.ts b/src/models/users.ts index bc2aa507..bda92e97 100644 --- a/src/models/users.ts +++ b/src/models/users.ts @@ -106,10 +106,11 @@ const initializeUserModel = (sequelize: Sequelize) => { allowNull: false, unique: true, }, + // Unique only where verified (`users_verified_phone_key`), so an unproven number on one + // account cannot keep its owner from adding it to theirs. phone: { type: DataTypes.STRING, allowNull: true, - unique: true, }, roles: { type: DataTypes.ARRAY(DataTypes.STRING), diff --git a/src/routes/otp.routes.ts b/src/routes/otp.routes.ts index 50e3b980..80b2419a 100644 --- a/src/routes/otp.routes.ts +++ b/src/routes/otp.routes.ts @@ -241,6 +241,7 @@ otpRouter.post( adapter: { credential: 'registration', issues: 'session' }, auth: 'ephemeral', summary: 'Verify phone OTP', + description: 'Answers 409 when another account has already verified the number.', decoy: decoyVerifyPhoneOtp, tags: ['OTP'], middleware: [otpIpLimiter, otpIdentityLimiter], @@ -252,6 +253,7 @@ otpRouter.post( 200: OTPVerifyTokenSuccessSchema, 403: ErrorSchema, 401: ErrorSchema, + 409: ErrorSchema, 500: ErrorSchema, }, }, diff --git a/src/routes/registration.routes.ts b/src/routes/registration.routes.ts index 2a404539..34b11118 100644 --- a/src/routes/registration.routes.ts +++ b/src/routes/registration.routes.ts @@ -51,6 +51,10 @@ registrationRouter.post( adapter: { delivery: true }, auth: 'access', summary: 'Register a phone number for the authenticated user', + description: + 'Sends a code whether or not another account holds the number, so the answer does not ' + + 'say which numbers are registered. A number another account has verified is refused at ' + + 'verification with 409.', tags: ['Registration'], middleware: [requireFactorEnrollmentProof, otpIpLimiter, otpIdentityLimiter], @@ -61,7 +65,6 @@ registrationRouter.post( 200: RegisterPhoneSuccessSchema, 400: ErrorSchema, 401: ErrorSchema, - 409: ErrorSchema, 500: ErrorSchema, }, }, @@ -75,6 +78,7 @@ registrationRouter.post( middleware: [requireFactorEnrollmentProof], auth: 'access', summary: 'Verify the authenticated user phone number', + description: 'Answers 409 when another account has already verified the number.', tags: ['Registration'], schemas: { @@ -83,6 +87,7 @@ registrationRouter.post( response: { 200: OTPVerifyTokenSuccessSchema, 401: ErrorSchema, + 409: ErrorSchema, 500: ErrorSchema, }, }, diff --git a/tests/integration/registration/register.spec.ts b/tests/integration/registration/register.spec.ts index 4f55d7fc..72d658ed 100644 --- a/tests/integration/registration/register.spec.ts +++ b/tests/integration/registration/register.spec.ts @@ -292,6 +292,22 @@ describe('POST /registration/register', () => { expect(User.create).toHaveBeenCalledWith(expect.objectContaining({ phone: null })); }); + // A number only attached to another account, unproven, does not hold it against its owner. + it('attaches a phone that only an unverified account holds', async () => { + (User.findOne as any).mockResolvedValue(null); + (User.create as any).mockResolvedValue(buildUser({ id: 'new-user', verified: false })); + + const res = await request(app) + .post('/registration/register') + .send(buildRegistrationRequest({ phone: '+14155552671' })); + + expect(res.status).toBe(200); + expect(User.findOne).toHaveBeenCalledWith({ + where: { phone: '+14155552671', phoneVerified: true }, + }); + expect(User.create).toHaveBeenCalledWith(expect.objectContaining({ phone: '+14155552671' })); + }); + it('does not reveal that the identifiers belong to different accounts', async () => { const emailOwner = buildUser({ id: 'user-1', email: 'test@example.com' }); (User.findOne as any) @@ -492,13 +508,16 @@ describe('POST /registration/phone', () => { expect(generatePhoneOTP).toHaveBeenCalled(); }); - it('rejects an in-use phone number', async () => { - (User.findOne as any).mockResolvedValue(buildUser({ id: 'other-user' })); + // Refusing a number another account holds told any signed-in caller which numbers are + // registered. A code goes out either way; a verified holder is refused at verification. + it('answers a number another account holds as it answers any other', async () => { + (User.findOne as any).mockResolvedValue(buildUser({ id: 'other-user', phoneVerified: true })); const res = await request(app).post('/registration/phone').send({ phone: '+14155550000' }); - expect(res.status).toBe(409); - expect(generatePhoneOTP).not.toHaveBeenCalled(); + expect(res.status).toBe(200); + expect(User.findOne).not.toHaveBeenCalled(); + expect(generatePhoneOTP).toHaveBeenCalled(); }); it('rejects an invalid phone number', async () => { @@ -520,8 +539,8 @@ describe('POST /registration/phone', () => { expect(generatePhoneOTP).not.toHaveBeenCalled(); }); - it('returns 500 when the phone lookup throws', async () => { - (User.findOne as any).mockRejectedValue(new Error('db down')); + it('returns 500 when the code cannot be issued', async () => { + (generatePhoneOTP as any).mockRejectedValue(new Error('db down')); const res = await request(app).post('/registration/phone').send({ phone: '+14155550000' }); @@ -558,6 +577,24 @@ describe('POST /registration/phone/verify', () => { expect(verifyPhoneOTP).toHaveBeenCalled(); }); + it('refuses a number another account has already verified with 409', async () => { + (verifyPhoneOTP as any).mockRejectedValue( + new Error('Failed to update user verification via phone OTP', { + cause: new UniqueConstraintError({}), + }), + ); + + const res = await request(app) + .post('/registration/phone/verify') + .send({ verificationToken: '123456' }); + + expect(res.status).toBe(409); + expect(res.body.error).toBe('Phone number in use'); + expect(AuthEventService.log).toHaveBeenCalledWith( + expect.objectContaining({ type: 'verify_otp_failed' }), + ); + }); + it('rejects an incorrect verification token', async () => { (verifyPhoneOTP as any).mockResolvedValue({ verified: false }); diff --git a/tests/postgres/verifiedPhoneUnique.spec.ts b/tests/postgres/verifiedPhoneUnique.spec.ts new file mode 100644 index 00000000..c9b67cff --- /dev/null +++ b/tests/postgres/verifiedPhoneUnique.spec.ts @@ -0,0 +1,50 @@ +import { randomUUID } from 'crypto'; +import { UniqueConstraintError } from 'sequelize'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; + +import { getSequelize, initializeModels } from '../../src/models/index.js'; + +type Models = Awaited>; + +let User: Models['User']; + +function createUser(phone: string, phoneVerified = false) { + const id = randomUUID(); + return User.create({ id, email: `phone-${id}@example.com`, phone, phoneVerified }); +} + +beforeAll(async () => { + ({ User } = await initializeModels()); +}); + +afterAll(async () => { + await getSequelize().close(); +}); + +describe('phone uniqueness', () => { + it('lets unverified accounts hold the same number', async () => { + const phone = `+1415555${String(Math.floor(Math.random() * 10_000)).padStart(4, '0')}`; + + await createUser(phone); + await expect(createUser(phone)).resolves.toBeTruthy(); + }); + + it('lets the owner verify a number a stranger attached without proving it', async () => { + const phone = '+14155550101'; + await createUser(phone); + const owner = await createUser(phone); + + await expect(owner.update({ phoneVerified: true })).resolves.toBeTruthy(); + }); + + it('refuses a second account verifying a number one already has', async () => { + const phone = '+14155550102'; + await createUser(phone, true); + const second = await createUser(phone); + + await expect(second.update({ phoneVerified: true })).rejects.toBeInstanceOf( + UniqueConstraintError, + ); + await expect(createUser(phone, true)).rejects.toBeInstanceOf(UniqueConstraintError); + }); +}); diff --git a/tests/unit/controllers/otp.spec.ts b/tests/unit/controllers/otp.spec.ts index 2e27d40b..baf0cfd6 100644 --- a/tests/unit/controllers/otp.spec.ts +++ b/tests/unit/controllers/otp.spec.ts @@ -804,6 +804,27 @@ describe('otp controller', () => { expect(res.json).toHaveBeenCalledWith({ error: 'Not allowed' }); }); + it('answers 409 when another account has already verified the number', async () => { + const { UniqueConstraintError } = await import('sequelize'); + const { verifyPhoneNumber } = await loadOtpController(); + const res = buildRes(); + verifyPhoneOTPMock.mockRejectedValue( + new Error('Failed to update user verification via phone OTP', { + cause: new UniqueConstraintError({}), + }), + ); + + await verifyPhoneNumber( + buildReq(unclaimedUser(), { body: { verificationToken: '123456' } }), + res, + ); + + expect(res.status).toHaveBeenCalledWith(409); + expect(res.json).toHaveBeenCalledWith( + expect.objectContaining({ error: 'Phone number in use' }), + ); + }); + it('returns 500 when phone verification throws', async () => { const { verifyPhoneNumber } = await loadOtpController(); const res = buildRes(); diff --git a/tests/unit/lib/phoneInUse.spec.ts b/tests/unit/lib/phoneInUse.spec.ts new file mode 100644 index 00000000..d90b3764 --- /dev/null +++ b/tests/unit/lib/phoneInUse.spec.ts @@ -0,0 +1,27 @@ +import { UniqueConstraintError, ValidationError } from 'sequelize'; +import { describe, expect, it } from 'vitest'; + +import { isPhoneInUseError } from '../../../src/lib/phoneInUse.js'; + +describe('isPhoneInUseError', () => { + it('recognises a unique violation directly or as the cause of a wrapping error', () => { + const unique = new UniqueConstraintError({}); + + expect(isPhoneInUseError(unique)).toBe(true); + expect(isPhoneInUseError(new Error('wrapped', { cause: unique }))).toBe(true); + }); + + it('is false for any other failure', () => { + expect(isPhoneInUseError(new Error('db down'))).toBe(false); + expect(isPhoneInUseError(new ValidationError('bad', []))).toBe(false); + expect(isPhoneInUseError('not an error')).toBe(false); + expect(isPhoneInUseError(undefined)).toBe(false); + }); + + it('stops following a chain of causes after a few links', () => { + let error: Error = new UniqueConstraintError({}); + for (let i = 0; i < 6; i++) error = new Error(`wrap ${i}`, { cause: error }); + + expect(isPhoneInUseError(error)).toBe(false); + }); +}); From 3289c0c63ab1bbc9cbbe479a8eb7897f1cc6e521 Mon Sep 17 00:00:00 2001 From: Brandon Corbett Date: Fri, 4 Dec 2026 22:45:38 -0500 Subject: [PATCH 2/2] fix(registration): bound codes per number and treat only verified numbers as taken Import matched unverified holders as owners, an admin update that hit the verified-phone index answered 500, and without the 409 nothing bounded how many accounts could send codes to one number. --- .changeset/unverified-phone-squatting.md | 3 ++ src/controllers/admin.ts | 6 ++++ src/middleware/rateLimit.ts | 19 ++++++++++ src/routes/registration.routes.ts | 13 +++++-- src/services/userImportService.ts | 6 +++- tests/integration/admin/admin.spec.ts | 14 ++++++++ .../rateLimit/identityFlowLimits.spec.ts | 36 +++++++++++++++++++ tests/setup/mocks.ts | 1 + tests/unit/services/userImportService.spec.ts | 17 +++++++++ 9 files changed, 112 insertions(+), 3 deletions(-) diff --git a/.changeset/unverified-phone-squatting.md b/.changeset/unverified-phone-squatting.md index 16e43cd3..e9fa5668 100644 --- a/.changeset/unverified-phone-squatting.md +++ b/.changeset/unverified-phone-squatting.md @@ -9,6 +9,9 @@ Before, a unique constraint covered every row. Registering a stranger's number o - A migration replaces the `users_phone_key` unique constraint with a unique index on `phone` where `phone_verified` is true. Any number of unverified accounts may hold the same number. Verifying it claims it. - `POST /registration/register` drops a supplied phone only when another account has verified it. - **Breaking:** `POST /registration/phone` sends a code whether or not another account holds the number, and no longer answers 409. +- `POST /registration/phone` is now also limited per destination number, at four times `flow_rate_limits.otp.perIdentity` per window. Without the 409, that limit is what bounds how many codes other accounts can send to one number. +- User import treats a number as taken only when another account has verified it. +- `PATCH /admin/users/{userId}` answers 409 instead of 500 when another account already holds the email or has verified the phone. - **Breaking:** `POST /registration/phone/verify` and `POST /otp/verify-phone-otp` answer 409 (`Phone number in use`) when another account has already verified the number. That is the only point where it shows, and only to someone who has just proven they hold the phone. The down migration restores the full unique constraint and fails if two accounts hold the same number. diff --git a/src/controllers/admin.ts b/src/controllers/admin.ts index 14ddbd81..bf48cf3e 100644 --- a/src/controllers/admin.ts +++ b/src/controllers/admin.ts @@ -404,6 +404,12 @@ export const updateUser = async (req: ServiceRequest, res: Response) => { }, }); } catch (error) { + // Email is unique, and a phone is once verified, so another account can hold either. + if (error instanceof UniqueConstraintError) { + res.status(409).json({ error: 'Email or phone number already in use' }); + return; + } + logger.error(`Failed to update user ${error}`); res.status(500).json({ error: 'Failed to update user' }); return; diff --git a/src/middleware/rateLimit.ts b/src/middleware/rateLimit.ts index aa6e0f75..10c8b513 100644 --- a/src/middleware/rateLimit.ts +++ b/src/middleware/rateLimit.ts @@ -10,6 +10,7 @@ import rateLimit, { ipKeyGenerator, RateLimitRequestHandler } from 'express-rate import { getSystemConfig } from '../config/getSystemConfig.js'; import { AuthenticatedRequest } from '../types/types.js'; +import { normalizePhoneNumber } from '../utils/utils.js'; import { rateLimitsDisabled } from './rateLimitsDisabled.js'; import { TOO_MANY_REQUESTS_BODY } from './tooManyRequests.js'; @@ -228,3 +229,21 @@ const sessionExchangeCachedLimiter = createFlowLimiter( export function sessionExchangeLimiter(req: Request, res: Response, next: NextFunction) { return sessionExchangeCachedLimiter(req, res, next); } + +// Keyed on the number a code is sent to. Each account and attempt has its own allowance, so +// without this many accounts could each send codes to one stranger's phone. +function getTargetPhoneKey(req: Request) { + const body = req.body as { phone?: unknown } | undefined; + const phone = typeof body?.phone === 'string' ? normalizePhoneNumber(body.phone) : null; + + return phone ? `phone:${phone}` : `ip:${clientAddressKey(req)}`; +} + +const otpPhoneTargetCachedLimiter = createFlowLimiter( + (limits) => limits.otp.perIdentity * IDENTIFIER_ATTEMPT_MULTIPLIER, + getTargetPhoneKey, +); + +export function otpPhoneTargetLimiter(req: Request, res: Response, next: NextFunction) { + return otpPhoneTargetCachedLimiter(req, res, next); +} diff --git a/src/routes/registration.routes.ts b/src/routes/registration.routes.ts index 34b11118..c81904e0 100644 --- a/src/routes/registration.routes.ts +++ b/src/routes/registration.routes.ts @@ -6,7 +6,11 @@ import { register, registerPhone, verifyRegisteredPhone } from '../controllers/registration.js'; import { createRouter } from '../lib/createRouter.js'; -import { otpIdentityLimiter, otpIpLimiter } from '../middleware/rateLimit.js'; +import { + otpIdentityLimiter, + otpIpLimiter, + otpPhoneTargetLimiter, +} from '../middleware/rateLimit.js'; import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js'; import { ErrorSchema } from '../schemas/generic.responses.js'; import { VerifyOTPRequestSchema } from '../schemas/otp.requests.js'; @@ -56,7 +60,12 @@ registrationRouter.post( 'say which numbers are registered. A number another account has verified is refused at ' + 'verification with 409.', tags: ['Registration'], - middleware: [requireFactorEnrollmentProof, otpIpLimiter, otpIdentityLimiter], + middleware: [ + requireFactorEnrollmentProof, + otpIpLimiter, + otpIdentityLimiter, + otpPhoneTargetLimiter, + ], schemas: { body: RegisterPhoneRequestSchema, diff --git a/src/services/userImportService.ts b/src/services/userImportService.ts index 145734fc..266c095a 100644 --- a/src/services/userImportService.ts +++ b/src/services/userImportService.ts @@ -102,7 +102,11 @@ async function loadContext(request: ImportUsersRequest) { }) : Promise.resolve([]), User.findAll({ where: { email: { [Op.in]: emails } } }), - phones.length ? User.findAll({ where: { phone: { [Op.in]: phones } } }) : Promise.resolve([]), + // Only a verified number belongs to an account. An unverified one may be attached to + // several, by anyone, and must not keep the import from giving it to its owner. + phones.length + ? User.findAll({ where: { phone: { [Op.in]: phones }, phoneVerified: true } }) + : Promise.resolve([]), orgIds.length ? Organization.findAll({ where: { id: { [Op.in]: orgIds } } }) : Promise.resolve([]), diff --git a/tests/integration/admin/admin.spec.ts b/tests/integration/admin/admin.spec.ts index 456eac40..ffac6981 100644 --- a/tests/integration/admin/admin.spec.ts +++ b/tests/integration/admin/admin.spec.ts @@ -1098,6 +1098,20 @@ describe('PATCH /admin/users/:userId', () => { ); }); + it('answers 409 when another account already holds the address or verified phone', async () => { + const { UniqueConstraintError } = await import('sequelize'); + const user = buildUser(); + (user.update as any).mockRejectedValue(new UniqueConstraintError({})); + (User.findByPk as any).mockResolvedValue(user); + + const res = await request(app) + .patch('/admin/users/user-1') + .send({ roles: ['admin'] }); + + expect(res.status).toBe(409); + expect(res.body.error).toBe('Email or phone number already in use'); + }); + it('returns 500 when the user update fails', async () => { const user = buildUser(); (user.update as any).mockRejectedValue(new Error('boom')); diff --git a/tests/integration/rateLimit/identityFlowLimits.spec.ts b/tests/integration/rateLimit/identityFlowLimits.spec.ts index 1cad692f..9d3d20f4 100644 --- a/tests/integration/rateLimit/identityFlowLimits.spec.ts +++ b/tests/integration/rateLimit/identityFlowLimits.spec.ts @@ -120,3 +120,39 @@ describe.each(['otpIdentityLimiter', 'magicLinkEmailLimiter'] as const)('%s', (n expect(await status(app, 'owner@example.com', 'owner')).toBe(200); }); }); + +describe('otpPhoneTargetLimiter', () => { + async function phoneApp() { + vi.resetModules(); + const { otpPhoneTargetLimiter } = await import('../../../src/middleware/rateLimit.js'); + const app = express(); + app.use(express.json()); + app.post('/phone', otpPhoneTargetLimiter as IdentityLimiter, (_req, res) => { + res.status(200).json({ ok: true }); + }); + return app as Application; + } + + // Each account has its own allowance, so the number itself is what bounds codes sent to it. + it('caps codes sent to one number however it is written, and leaves other numbers alone', async () => { + const app = await phoneApp(); + + for (let i = 0; i < 20; i++) { + const phone = i % 2 ? '+14155552671' : '+1 (415) 555-2671'; + expect((await request(app).post('/phone').send({ phone })).status).toBe(200); + } + + expect((await request(app).post('/phone').send({ phone: '+14155552671' })).status).toBe(429); + expect((await request(app).post('/phone').send({ phone: '+14155552672' })).status).toBe(200); + }); + + it('falls back to the requester address without a usable number', async () => { + const app = await phoneApp(); + + for (let i = 0; i < 20; i++) { + await request(app).post('/phone').send({ phone: 'not-a-phone' }); + } + + expect((await request(app).post('/phone').send({})).status).toBe(429); + }); +}); diff --git a/tests/setup/mocks.ts b/tests/setup/mocks.ts index 7d91b11e..6757ea63 100644 --- a/tests/setup/mocks.ts +++ b/tests/setup/mocks.ts @@ -373,6 +373,7 @@ vi.mock('../../src/middleware/rateLimit.js', () => ({ sessionExchangeLimiter: (_req: any, _res: any, next: any) => next(), otpIpLimiter: (_req: any, _res: any, next: any) => next(), otpIdentityLimiter: (_req: any, _res: any, next: any) => next(), + otpPhoneTargetLimiter: (_req: any, _res: any, next: any) => next(), dynamicRateLimit: (_req: any, _res: any, next: any) => next(), dynamicSlowDown: (_req: any, _res: any, next: any) => next(), })); diff --git a/tests/unit/services/userImportService.spec.ts b/tests/unit/services/userImportService.spec.ts index 15f5a59c..afb85630 100644 --- a/tests/unit/services/userImportService.spec.ts +++ b/tests/unit/services/userImportService.spec.ts @@ -1,3 +1,4 @@ +import { Op } from 'sequelize'; import { beforeEach, describe, expect, it, vi } from 'vitest'; import { getSystemConfig } from '../../../src/config/getSystemConfig.js'; @@ -313,6 +314,22 @@ describe('importUsers', () => { expect(response.results[1].reason).toBe('duplicate_in_batch'); }); + // An unverified number may be attached to several accounts, by anyone, so only a verified + // holder can keep an import from giving the number to its owner. + it('looks for phone holders among verified numbers only', async () => { + mockUsers(); + + await importUsers({ + source: 'csv', + dryRun: true, + users: [{ email: 'a@example.com', phone: '+1 415 555 2671' }], + }); + + expect(User.findAll).toHaveBeenCalledWith({ + where: { phone: { [Op.in]: ['+14155552671'] }, phoneVerified: true }, + }); + }); + it('rejects a phone number held by another account and an invalid one', async () => { mockUsers({ byPhone: [existingUser({ phone: '+14155552671' })] });