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
16 changes: 16 additions & 0 deletions .changeset/per-attempt-one-time-codes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'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.
- 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. 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.
4 changes: 0 additions & 4 deletions src/controllers/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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;
Expand Down
13 changes: 10 additions & 3 deletions src/controllers/magicLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ import {
MagicLinkConfirmBodySchema,
MagicLinkRequestQuerySchema,
} from '../schemas/magiclink.requests.js';
import { claimUnverifiedAccount } 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';
Expand Down Expand Up @@ -469,9 +473,12 @@ export async function pollMagicLinkConfirmation(req: Request, res: Response) {
req,
});

claimUnverifiedAccount(user, authReq.attemptId);
await withLockedUser(user, async (locked, transaction) => {
if (!claimUnverifiedAccount(locked, authReq.attemptId)) return false;

await user.save();
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.
Expand Down
26 changes: 16 additions & 10 deletions src/controllers/otp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import getLogger from '../utils/logger.js';
import {
generateEmailOTP,
generatePhoneOTP,
hasPendingOtp,
verifyEmailOTP,
verifyPhoneOTP,
} from '../utils/otp.js';
Expand Down Expand Up @@ -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,
});

Expand Down Expand Up @@ -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({
Expand Down Expand Up @@ -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,
Expand All @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand All @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down
12 changes: 5 additions & 7 deletions src/controllers/registration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand All @@ -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({
Expand Down Expand Up @@ -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;
Expand All @@ -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({
Expand Down Expand Up @@ -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',
Expand All @@ -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({
Expand Down
23 changes: 23 additions & 0 deletions src/lib/otpScope.ts
Original file line number Diff line number Diff line change
@@ -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');
}
56 changes: 56 additions & 0 deletions src/migrations/20261204120000-add-one-time-codes.cjs
Original file line number Diff line number Diff line change
@@ -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;
`);
},
};
8 changes: 8 additions & 0 deletions src/models/accountRecoveryRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -37,6 +39,7 @@ type AccountRecoveryRequestCreationAttributes = Optional<
AccountRecoveryRequestAttributes,
| 'id'
| 'attemptId'
| 'resumesRequestId'
| 'codeAttemptId'
| 'codeHash'
| 'codeExpiresAt'
Expand All @@ -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;
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading