Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/unverified-phone-squatting.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
'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.
- `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.
42 changes: 29 additions & 13 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down
6 changes: 6 additions & 0 deletions src/controllers/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions src/controllers/otp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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' });
}
Expand Down
43 changes: 22 additions & 21 deletions src/controllers/registration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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' });
}
Expand Down
69 changes: 48 additions & 21 deletions src/generated/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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: {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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: {
Expand Down
28 changes: 28 additions & 0 deletions src/lib/phoneInUse.ts
Original file line number Diff line number Diff line change
@@ -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;
19 changes: 19 additions & 0 deletions src/middleware/rateLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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);
}
Loading
Loading