Skip to content
Merged
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
11 changes: 11 additions & 0 deletions .changeset/step-up-factor-age.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'seamless-auth-api': minor
---

Step-up and factor enrollment are stricter.

- A step-up only accepts a passkey or TOTP enrolled before the session signed in. One added during the session works from the next sign-in. `/totp/verify-mfa` answers `401 step_up_unavailable` for a TOTP that is too new, and `/step-up/webauthn/start` leaves out passkeys that are too new.
- Passkey and TOTP enrollment, phone registration and recovery code generation need a fresh step-up (`403 step_up_required`) when the account already has a passkey or TOTP. An account with neither needs a sign-in from the last five minutes, and otherwise gets `403 reauthentication_required`. Recovery sessions are exempt.
- `DELETE /users/credentials` needs a fresh step-up.

Clients that add a passkey or TOTP from an existing session should run a step-up when they get `step_up_required`, and ask the user to sign in again when they get `reauthentication_required`.
18 changes: 16 additions & 2 deletions docs/security-posture.md
Original file line number Diff line number Diff line change
Expand Up @@ -839,13 +839,27 @@ step-up has to happen on that same session within five minutes. The full route l
`403 step_up_required` body are in
[Admin Operations](./admin-operations.md#step-up-on-admin-writes).

A step-up only counts when it is made with a factor the account had before the session signed
in. A passkey or TOTP added since, by whoever holds the session, cannot vouch for that session;
it is accepted after the next sign-in. For a session from a token exchange, "signed in" means
the earliest session in its lineage, and a lineage that cannot be read counts no factor at all.

Adding a factor needs proof as well. Passkey and TOTP enrollment, phone registration and
recovery code generation answer `403 step_up_required` until an account that already has a
passkey or TOTP has stepped up, and `403 reauthentication_required` to an account with neither
whose sign-in is more than five minutes old. A recovery session is exempt, since enrolling is
what it is for. Deleting a passkey (`DELETE /users/credentials`) also needs a fresh step-up.

### What is still accepted

- **A fresh step-up is a window, not a per-request proof.** For five minutes after a step-up,
the session's access token makes guarded writes on its own. Shortening the window is a
`requireStepUp({ maxAgeSeconds })` change per route.
- **Self-service account deletion is not guarded.** `DELETE /users/delete` deletes the caller's
own account and is open to accounts with no passkey or TOTP, which could never step up.
- **A factor added in a session is trusted from the next sign-in.** Enrolling it needs the
proof above, not a second factor's approval after the fact, and the owner is not yet sent a
notice when one is added.
- **An account with no factor can add its first one with a recent sign-in alone.** It has
nothing else to prove with.
- **Enrollment invites are not guarded.** They email existing users a sign-in link and change
no account.

Expand Down
1 change: 1 addition & 0 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -36232,6 +36232,7 @@
},
"delete": {
"summary": "Delete credential",
"description": "Needs a fresh step-up.",
"tags": ["Users"],
"security": [{ "bearerAuth": [] }],
"requestBody": {
Expand Down
31 changes: 28 additions & 3 deletions src/controllers/stepUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ import { buildPrfAuthenticationExtensions, containsPrfOutput } from '../lib/weba
import { Credential } from '../models/credentials.js';
import { AuthEventService } from '../services/authEventService.js';
import {
factorPredatesSignIn,
getSessionStepUpStatus,
getStepUpSignInTime,
recordStepUpVerification,
serializeStepUpStatus,
} from '../services/stepUpService.js';
Expand All @@ -30,13 +32,17 @@ const logger = getLogger('step-up');

function filterAssertionCredentials(
credentials: Credential[],
options: { credentialId?: string; requiresPrf: boolean },
options: { credentialId?: string; requiresPrf: boolean; signedInAt: Date | null },
) {
return credentials.filter((credential) => {
if (options.credentialId && credential.id !== options.credentialId) {
return false;
}

if (!factorPredatesSignIn(credential.createdAt, options.signedInAt)) {
return false;
}

if (options.requiresPrf && !credential.prfCapable) {
return false;
}
Expand Down Expand Up @@ -70,22 +76,29 @@ export const startWebAuthnStepUp = async (req: Request, res: Response) => {
const user = authReq.user;
const { credentialId, prf } = req.body ?? {};

if (!user?.id) {
if (!user?.id || !authReq.sessionId) {
await AuthEventService.log({
userId: null,
type: 'step_up_suspicious',
req,
metadata: { reason: 'No authenticated user' },
metadata: { reason: 'No authenticated user or session' },
});
return res.status(401).json({ error: 'unauthorized' });
}

try {
const { sessionFound, signedInAt } = await getStepUpSignInTime(authReq.sessionId, user.id);

if (!sessionFound) {
return res.status(401).json({ error: 'unauthorized' });
}

const credentials = await Credential.findAll({ where: { userId: user.id } });

const assertionCredentials = filterAssertionCredentials(credentials ?? [], {
credentialId,
requiresPrf: Boolean(prf),
signedInAt,
});

if (!assertionCredentials || assertionCredentials.length === 0) {
Expand Down Expand Up @@ -198,6 +211,18 @@ export const finishWebAuthnStepUp = async (req: Request, res: Response) => {
return res.status(401).json({ error: 'step_up_failed' });
}

const { signedInAt } = await getStepUpSignInTime(authReq.sessionId, user.id);

if (!factorPredatesSignIn(credential.createdAt, signedInAt)) {
await AuthEventService.log({
userId: user.id,
type: 'step_up_failed',
req,
metadata: { reason: 'Credential enrolled after sign-in' },
});
return res.status(401).json({ error: 'step_up_failed' });
}

const expectedChallenge = issued.challenge;

try {
Expand Down
17 changes: 15 additions & 2 deletions src/controllers/totp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ import { rejectIfUserLocked } from '../services/lockoutPolicyService.js';
import { isPasskeyRequiredForUser } from '../services/loginPolicyService.js';
import { issueSessionAndRespond } from '../services/sessionIssuance.js';
import { liftRecoveryRestriction } from '../services/sessionService.js';
import { recordStepUpVerification, serializeStepUpStatus } from '../services/stepUpService.js';
import {
getStepUpSignInTime,
recordStepUpVerification,
serializeStepUpStatus,
} from '../services/stepUpService.js';
import {
disableTotp,
getTotpStatus,
Expand Down Expand Up @@ -252,7 +256,13 @@ export const verifyTotpMfa = async (req: Request, res: Response) => {
return;
}

const result = await verifyEnabledTotp(user.id, code);
const { sessionFound, signedInAt } = await getStepUpSignInTime(authReq.sessionId, user.id);

if (!sessionFound) {
return res.status(401).json({ error: 'unauthorized' });
}

const result = await verifyEnabledTotp(user.id, code, { enrolledBefore: signedInAt });

if (!result.verified) {
await AuthEventService.log({
Expand All @@ -261,6 +271,9 @@ export const verifyTotpMfa = async (req: Request, res: Response) => {
req,
metadata: { reason: result.reason, method: 'totp' },
});
if (result.reason === 'enrolled_after_sign_in') {
return res.status(401).json({ error: 'step_up_unavailable' });
}
return res.status(401).json({ error: 'totp_verification_failed' });
}

Expand Down
5 changes: 4 additions & 1 deletion src/generated/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34676,7 +34676,10 @@ export interface paths {
};
};
};
/** Delete credential */
/**
* Delete credential
* @description Needs a fresh step-up.
*/
delete: {
parameters: {
query?: never;
Expand Down
91 changes: 91 additions & 0 deletions src/middleware/requireFactorEnrollmentProof.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* 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 { NextFunction, Request, Response } from 'express';

import { Credential } from '../models/credentials.js';
import { TotpCredential } from '../models/totpCredentials.js';
import {
findCurrentSession,
FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS,
getStepUpStatusFromSession,
serializeStepUpStatus,
} from '../services/stepUpService.js';
import { AuthenticatedRequest } from '../types/types.js';
import {
DeviceStepUpAwareHandler,
refuseDeviceSessionWithoutStepUp,
} from './requireDeviceSessionStepUp.js';

async function hasStepUpFactor(userId: string) {
const [passkeys, totp] = await Promise.all([
Credential.count({ where: { userId } }),
TotpCredential.count({ where: { userId, enabled: true } }),
]);

return passkeys > 0 || totp > 0;
}

function signedInRecently(authTime: Date | null | undefined, now = Date.now()) {
if (!authTime) return false;

return now - new Date(authTime).getTime() <= FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS * 1000;
}

/**
* For a route that adds something the account can sign in or step up with. An access token
* alone is not enough: whoever holds a stolen one could add their own factor and keep the
* account. An account that has a factor proves it with a fresh step-up, which only a factor
* from before this sign-in can satisfy. An account with none has nothing to prove with, so
* the sign-in itself must be recent. A recovery session exists to enrol and is let through.
*/
export const requireFactorEnrollmentProof: DeviceStepUpAwareHandler = async (
req: Request,
res: Response,
next: NextFunction,
) => {
if (refuseDeviceSessionWithoutStepUp(req, res)) return;

const authReq = req as AuthenticatedRequest;
if (authReq.recoverySession) return next();

const userId = authReq.user?.id;
const session =
userId && authReq.sessionId ? await findCurrentSession(authReq.sessionId, userId) : null;

if (!userId || !session) {
res.status(401).json({ error: 'unauthorized' });
return;
}

if (await hasStepUpFactor(userId)) {
const status = getStepUpStatusFromSession(session);

if (!status.fresh) {
res.status(403).json({
error: 'step_up_required',
message: 'Recent step-up authentication is required',
...serializeStepUpStatus(status),
});
return;
}

return next();
}

if (!signedInRecently(session.authTime)) {
res.status(403).json({
error: 'reauthentication_required',
message: 'Sign in again to add a sign-in method',
maxAgeSeconds: FIRST_FACTOR_SIGN_IN_MAX_AGE_SECONDS,
});
return;
}

return next();
};

requireFactorEnrollmentProof.seamlessDeviceStepUp = true;
1 change: 1 addition & 0 deletions src/models/credentials.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export class Credential extends Model {
declare platform: string | null;
declare browser: string | null;
declare deviceInfo: string | null;
declare readonly createdAt: Date;

declare readonly user?: User;

Expand Down
4 changes: 2 additions & 2 deletions src/routes/recoveryCodes.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
} from '../controllers/recoveryCodes.js';
import { createRouter } from '../lib/createRouter.js';
import { otpIdentityLimiter, otpIpLimiter } from '../middleware/rateLimit.js';
import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js';
import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js';
import { ErrorSchema } from '../schemas/generic.responses.js';
import {
RecoveryCodeRedeemRequestSchema,
Expand Down Expand Up @@ -44,7 +44,7 @@ recoveryCodesRouter.get(
recoveryCodesRouter.post(
'/',
{
middleware: [requireDeviceSessionStepUp],
middleware: [requireFactorEnrollmentProof],
auth: 'access',
allowRecoverySession: true,
summary: 'Generate recovery codes',
Expand Down
6 changes: 3 additions & 3 deletions src/routes/registration.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import { register, registerPhone, verifyRegisteredPhone } from '../controllers/registration.js';
import { createRouter } from '../lib/createRouter.js';
import { otpIdentityLimiter, otpIpLimiter } from '../middleware/rateLimit.js';
import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js';
import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js';
import { ErrorSchema } from '../schemas/generic.responses.js';
import { VerifyOTPRequestSchema } from '../schemas/otp.requests.js';
import { OTPVerifyTokenSuccessSchema } from '../schemas/otp.responses.js';
Expand Down Expand Up @@ -51,7 +51,7 @@ registrationRouter.post(
auth: 'access',
summary: 'Register a phone number for the authenticated user',
tags: ['Registration'],
middleware: [requireDeviceSessionStepUp, otpIpLimiter, otpIdentityLimiter],
middleware: [requireFactorEnrollmentProof, otpIpLimiter, otpIdentityLimiter],

schemas: {
body: RegisterPhoneRequestSchema,
Expand All @@ -71,7 +71,7 @@ registrationRouter.post(
registrationRouter.post(
'/phone/verify',
{
middleware: [requireDeviceSessionStepUp],
middleware: [requireFactorEnrollmentProof],
auth: 'access',
summary: 'Verify the authenticated user phone number',
tags: ['Registration'],
Expand Down
5 changes: 3 additions & 2 deletions src/routes/totp.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import { createRouter } from '../lib/createRouter.js';
import { otpIdentityLimiter, otpIpLimiter } from '../middleware/rateLimit.js';
import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js';
import { requireFactorEnrollmentProof } from '../middleware/requireFactorEnrollmentProof.js';
import {
ErrorSchema,
InternalErrorSchema,
Expand Down Expand Up @@ -54,7 +55,7 @@ totpRouter.get(
totpRouter.post(
'/enroll/start',
{
middleware: [requireDeviceSessionStepUp],
middleware: [requireFactorEnrollmentProof],
auth: 'access',
allowRecoverySession: true,
summary: 'Start TOTP enrollment',
Expand All @@ -75,7 +76,7 @@ totpRouter.post(
totpRouter.post(
'/enroll/verify',
{
middleware: [requireDeviceSessionStepUp, otpIpLimiter, otpIdentityLimiter],
middleware: [requireFactorEnrollmentProof, otpIpLimiter, otpIdentityLimiter],
auth: 'access',
allowRecoverySession: true,
summary: 'Verify TOTP enrollment',
Expand Down
5 changes: 3 additions & 2 deletions src/routes/users.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { DeleteCredentialRequestSchema, UpdateCredentialRequestSchema } from '@s
import { getEffectivePermissions } from '../controllers/permissions.js';
import { deleteCredential, deleteUser, getUser, updateCredential } from '../controllers/user.js';
import { createRouter } from '../lib/createRouter.js';
import { requireDeviceSessionStepUp } from '../middleware/requireDeviceSessionStepUp.js';
import { requireStepUp } from '../middleware/requireStepUp.js';
import { CredentialUpdateResponseSchema } from '../schemas/credential.responses.js';
import { ErrorSchema, MessageSchema } from '../schemas/generic.responses.js';
Expand Down Expand Up @@ -96,15 +95,17 @@ usersRouter.delete(
usersRouter.delete(
'/credentials',
{
middleware: [requireDeviceSessionStepUp],
middleware: [requireStepUp()],
auth: 'access',
tags: ['Users'],
summary: 'Delete credential',
description: 'Needs a fresh step-up.',

schemas: {
body: DeleteCredentialRequestSchema,
response: {
200: MessageSchema,
403: StepUpRequiredErrorSchema,
},
},
},
Expand Down
Loading