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
5 changes: 5 additions & 0 deletions .changeset/recovery-code-budget.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'seamless-auth-api': patch
---

Self-service account recovery codes are stronger and their guesses are counted per account. Email codes are now six letters, like the sign-in code, and phone codes are eight digits. Each account may spend ten wrong recovery codes per channel in any 24 hours, counted across every `/recovery/start` and kept in the database. Once the budget is spent, `/recovery/start` sends no code and `/recovery/verify` checks none until the oldest wrong code is 24 hours old. Both answer as they otherwise would (`200` and `401 invalid_recovery_code`). The budget is separate for each channel and does not affect sign-in lockout or recovery codes. If it cannot be read, the channel is treated as spent.
20 changes: 17 additions & 3 deletions docs/account-recovery.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ open requests), and `GET /system-config/public` reports

| Route | Auth | What it does |
| ------------------------------- | ---------------------------- | --------------------------------------------------------------------------------- |
| `POST /recovery/start` | pre-auth token from `/login` | `{ channel: "email" \| "phone" }`, sends a six-digit code |
| `POST /recovery/start` | pre-auth token from `/login` | `{ channel: "email" \| "phone" }`, sends a code |
| `POST /recovery/verify` | the same attempt | `{ code }`, opens the request and starts the delay |
| `GET /recovery/status` | the same attempt | `{ state, requestedAt, completesAt }` |
| `POST /recovery/cancel` | none | `{ cancelToken }` from the notice |
Expand All @@ -91,9 +91,11 @@ open requests), and `GET /system-config/public` reports
1. **Start.** The code goes to the verified address on file for the channel, through the
same delivery as OTP codes (including external delivery, where the response carries
`delivery`). The answer is the same whether or not the account has a verified address
there, so it does not say which channels exist. The code lasts ten minutes and is stored
there, so it does not say which channels exist. Email codes are six letters, like the
sign-in code, and phone codes are eight digits. The code lasts ten minutes and is stored
hashed.
2. **Verify.** Five wrong codes void the request. The right one opens it: `state` is
2. **Verify.** Five wrong codes void the request, and every wrong code also counts against
the account's [failure budget](#failure-budget). The right one opens it: `state` is
`pending`, `completesAt` is now plus the delay, and a notice goes to the account's
verified email **and** phone saying recovery was requested, when it completes and how to
cancel it. The cancel link is `${FRONTEND_URL}/recovery/cancel#<token>`; the token is in
Expand All @@ -120,6 +122,18 @@ Starting is not enough to disturb anything: anyone who knows an address can star
a verified code opens, resumes or cancels a request. Five wrong codes on a resume void
that code and leave the open request as it was.

### Failure budget

An account may spend ten wrong codes on each channel in any 24 hours, counted across every
start and attempt and stored in the database, so starting again or reaching another
instance does not refill it. Once it is spent, start sends no code and verify checks none
until the oldest wrong code is 24 hours old. Both answer as they would anyway (`200` with
the usual message, `401` with `invalid_recovery_code`), so a spent budget does not reveal
that the account exists. The two channels have separate budgets, and none of this touches
sign-in lockout or recovery codes. If the count cannot be read, the channel is treated as
spent. Someone who knows an address can spend its budget and hold that channel's recovery
off for a day at a time; the other channel and recovery codes still work.

### Cancelling

`POST /recovery/cancel` with the token from the notice cancels the request whether it is
Expand Down
4 changes: 2 additions & 2 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"/recovery/start": {
"post": {
"summary": "Start account recovery",
"description": "Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one. Not subject to account lockout.",
"description": "Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one, or while the channel failure budget is spent. Not subject to account lockout.",
"tags": ["Recovery"],
"security": [{ "bearerAuth": [] }],
"requestBody": {
Expand Down Expand Up @@ -243,7 +243,7 @@
"/recovery/verify": {
"post": {
"summary": "Verify an account recovery code",
"description": "Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503.",
"description": "Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code, and ten on a channel within 24 hours stop that channel for the account until the oldest ages out, answering as a wrong code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503.",
"tags": ["Recovery"],
"security": [{ "bearerAuth": [] }],
"requestBody": {
Expand Down
18 changes: 16 additions & 2 deletions src/controllers/accountRecovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,17 @@ export const startAccountRecovery = async (req: Request, res: Response) => {
try {
const code = await startRecovery(user.id, channel, attemptId);

// Answers as if sent, so a spent budget does not confirm the account has the address.
if (code === null) {
await AuthEventService.log({
userId: user.id,
type: 'account_recovery_started',
req,
metadata: { channel, sent: false, reason: 'Recovery failure budget spent' },
});
return res.status(200).json({ message: RECOVERY_STARTED_MESSAGE });
}

if (!external) {
if (channel === 'email') {
await sendOTPEmail(to, code);
Expand Down Expand Up @@ -189,12 +200,15 @@ export const verifyAccountRecovery = async (req: Request, res: Response) => {
? await verifyRecovery(user.id, attemptId, req.body.code, delaySeconds)
: ({ outcome: 'invalid' } as const);

if (result.outcome === 'invalid') {
// A spent budget answers like a wrong code, so it is not an oracle on the account.
if (result.outcome === 'invalid' || result.outcome === 'locked') {
await AuthEventService.log({
userId: user.id,
type: 'account_recovery_failed',
req,
metadata: { reason: 'Invalid code' },
metadata: {
reason: result.outcome === 'locked' ? 'Recovery failure budget spent' : 'Invalid code',
},
});
return res.status(401).json({ error: 'invalid_recovery_code' });
}
Expand Down
4 changes: 2 additions & 2 deletions src/generated/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export interface paths {
put?: never;
/**
* Start account recovery
* @description Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one. Not subject to account lockout.
* @description Sends a code to the verified address on file for the channel. Answers the same whether or not the account has one, or while the channel failure budget is spent. Not subject to account lockout.
*/
post: {
parameters: {
Expand Down Expand Up @@ -249,7 +249,7 @@ export interface paths {
put?: never;
/**
* Verify an account recovery code
* @description Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503.
* @description Opens the request started on this attempt, which completes after the configured delay, and tells every verified address how to cancel it. A code for a request that is already open resumes it on this attempt. Five wrong codes void the code, and ten on a channel within 24 hours stop that channel for the account until the oldest ages out, answering as a wrong code. Answers 503 and voids the request when no verified address could be notified. A credentialed caller that owns delivery and lists `account_notice_email` / `account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as `deliveries` to send; one that does not list them gets the 503.
*/
post: {
parameters: {
Expand Down
7 changes: 5 additions & 2 deletions src/routes/accountRecovery.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ accountRecoveryRouter.post(
summary: 'Start account recovery',
description:
'Sends a code to the verified address on file for the channel. Answers the same ' +
'whether or not the account has one. Not subject to account lockout.',
'whether or not the account has one, or while the channel failure budget is spent. ' +
'Not subject to account lockout.',
tags: ['Recovery'],
schemas: {
body: AccountRecoveryStartRequestSchema,
Expand All @@ -73,7 +74,9 @@ accountRecoveryRouter.post(
description:
'Opens the request started on this attempt, which completes after the configured ' +
'delay, and tells every verified address how to cancel it. A code for a request ' +
'that is already open resumes it on this attempt. Five wrong codes void the code. ' +
'that is already open resumes it on this attempt. Five wrong codes void the code, and ' +
'ten on a channel within 24 hours stop that channel for the account until the oldest ' +
'ages out, answering as a wrong code. ' +
'Answers 503 and voids the request when no verified address could be notified. A ' +
'credentialed caller that owns delivery and lists `account_notice_email` / ' +
'`account_notice_sms` in `x-seamless-auth-delivery-kinds` gets the notices back as ' +
Expand Down
113 changes: 108 additions & 5 deletions src/services/accountRecoveryService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,106 @@
* See LICENSE file in the project root for full license information
*/

import { randomBytes } from 'crypto';
import { randomBytes, randomInt } from 'crypto';
import { Op } from 'sequelize';

import {
AccountRecoveryRequest,
RecoveryChannel,
StoredRecoveryState,
} from '../models/accountRecoveryRequests.js';
import { generateRandomPhoneOTP, hashOtpToken, otpHashMatches } from '../utils/otp.js';
import { AuthFailure } from '../models/authFailures.js';
import getLogger from '../utils/logger.js';
import { generateRandomEmailOTP, hashOtpToken, otpHashMatches } from '../utils/otp.js';
import { hashSha256 } from '../utils/utils.js';
import { revokeAllSessionsForUsers } from './sessionRevocation.js';

const logger = getLogger('accountRecoveryService');

export const RECOVERY_CODE_TTL_MS = 10 * 60 * 1000;
export const MAX_RECOVERY_CODE_ATTEMPTS = 5;

/**
* Wrong codes an account may spend on one channel in {@link RECOVERY_FAILURE_WINDOW_MS},
* across every start. Kept in the database so restarting the flow, or reaching another
* instance, does not refill it. Per channel, so spending one does not stop the other.
*/
export const RECOVERY_FAILURE_BUDGET = 10;
export const RECOVERY_FAILURE_WINDOW_MS = 24 * 60 * 60 * 1000;

// Not a lockout failure type, so these never lock the account out of signing in.
export function recoveryFailureType(channel: RecoveryChannel) {
return `account_recovery_${channel}_failed`;
}

function generateRecoveryCode(channel: RecoveryChannel) {
return channel === 'email'
? generateRandomEmailOTP()
: String(randomInt(10_000_000, 100_000_000));
}

async function spentRecoveryFailures(userId: string, channel: RecoveryChannel) {
return AuthFailure.count({
where: {
userId,
type: recoveryFailureType(channel),
occurredAt: { [Op.gte]: new Date(Date.now() - RECOVERY_FAILURE_WINDOW_MS) },
},
});
}

/** Whether the channel's budget is spent. An unreadable count is treated as spent. */
export async function isRecoveryChannelLocked(userId: string, channel: RecoveryChannel) {
try {
return (await spentRecoveryFailures(userId, channel)) >= RECOVERY_FAILURE_BUDGET;
} catch (error) {
logger.error(`Could not read the recovery failure count, treating it as spent: ${error}`);
return true;
}
}

async function releaseRecoveryGuess(claimId: string) {
try {
await AuthFailure.destroy({ where: { id: claimId } });
} catch (error) {
logger.error(`Could not release a recovery guess: ${error}`);
}
}

/**
* Spends one guess from the budget before the code is compared. The row is written
* first and the window counted after, so concurrent guesses on any instance each see
* the others and no more than the budget get through. Returns null, having spent
* nothing, when the budget is gone or cannot be checked.
*/
async function claimRecoveryGuess(userId: string, channel: RecoveryChannel) {
let claimId: string;

try {
claimId = (
await AuthFailure.create({
userId,
type: recoveryFailureType(channel),
occurredAt: new Date(),
})
).id;
} catch (error) {
logger.error(`Could not record a recovery guess, refusing it: ${error}`);
return null;
}

try {
if ((await spentRecoveryFailures(userId, channel)) <= RECOVERY_FAILURE_BUDGET) {
return claimId;
}
} catch (error) {
logger.error(`Could not read the recovery failure count, refusing the guess: ${error}`);
}

await releaseRecoveryGuess(claimId);
return null;
}

export type RecoveryState = 'pending' | 'ready' | 'cancelled' | 'completed';

export interface RecoveryStatus {
Expand Down Expand Up @@ -51,9 +136,15 @@ function hashCancelToken(token: string) {
*
* 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.
*
* Returns null, issuing nothing, while the channel's failure budget is spent.
*/
export async function startRecovery(userId: string, channel: RecoveryChannel, attemptId: string) {
const code = String(generateRandomPhoneOTP());
if (await isRecoveryChannelLocked(userId, channel)) {
return null;
}

const code = generateRecoveryCode(channel);
const codeFields = {
codeAttemptId: attemptId,
codeHash: hashOtpToken(code),
Expand Down Expand Up @@ -82,6 +173,7 @@ export async function startRecovery(userId: string, channel: RecoveryChannel, at

export type VerifyRecoveryResult =
| { outcome: 'invalid' }
| { outcome: 'locked' }
| { outcome: 'opened'; request: AccountRecoveryRequest; cancelToken: string }
| { outcome: 'resumed'; request: AccountRecoveryRequest };

Expand All @@ -98,7 +190,8 @@ function clearCode(request: AccountRecoveryRequest) {
/**
* Checks the code issued to this attempt. Each try is claimed with a conditional update
* before the code is compared, so parallel requests cannot spend more than
* {@link MAX_RECOVERY_CODE_ATTEMPTS} between them.
* {@link MAX_RECOVERY_CODE_ATTEMPTS} between them, or more than the account's
* {@link RECOVERY_FAILURE_BUDGET} on the channel.
*/
export async function verifyRecovery(
userId: string,
Expand Down Expand Up @@ -127,22 +220,32 @@ export async function verifyRecovery(
return { outcome: 'invalid' };
}

const guess = await claimRecoveryGuess(userId, request.channel);

if (!guess) {
return { outcome: 'locked' };
}

const [claimed] = await AccountRecoveryRequest.update(
{ failedAttempts: tries + 1 },
{ where: { id: request.id, failedAttempts: tries } },
);

if (claimed !== 1) {
await releaseRecoveryGuess(guess);
return { outcome: 'invalid' };
}

if (!otpHashMatches(request.codeHash, code)) {
// 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));
}
return { outcome: 'invalid' };
}

await releaseRecoveryGuess(guess);

if (request.state === 'pending') {
await request.update({ ...clearCode(request), attemptId, failedAttempts: 0 });
return { outcome: 'resumed', request };
Expand Down
30 changes: 30 additions & 0 deletions tests/factories/accountRecoveryStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { randomUUID } from 'crypto';
import { Op } from 'sequelize';

import { AccountRecoveryRequest } from '../../src/models/accountRecoveryRequests.js';
import { AuthFailure } from '../../src/models/authFailures.js';

type Row = Record<string, any>;
type Where = Record<string | symbol, any>;
Expand All @@ -16,6 +17,7 @@ function matchesCondition(value: any, condition: any): boolean {
if (op === Op.in) return operand.includes(value);
if (op === Op.ne) return operand === null ? value != null : value !== operand;
if (op === Op.lte) return value != null && +value <= +operand;
if (op === Op.gte) return value != null && +value >= +operand;
throw new Error(`Unsupported operator ${String(op)}`);
});
}
Expand All @@ -27,6 +29,32 @@ function matches(row: Row, where: Where) {
return Object.keys(where).every((key) => matchesCondition(row[key], where[key]));
}

/**
* An in-memory stand-in for `auth_failures`, which holds the recovery failure budget.
* Installed by {@link installAccountRecoveryStore}; call it again to get the rows.
*/
export function installAuthFailureStore() {
const failures: Row[] = [];

(AuthFailure.create as any).mockImplementation(async (data: Row) => {
const row = { id: randomUUID(), ...data };
failures.push(row);
return row;
});

(AuthFailure.count as any).mockImplementation(
async ({ where }: { where: Where }) => failures.filter((row) => matches(row, where)).length,
);

(AuthFailure.destroy as any).mockImplementation(async ({ where }: { where: Where }) => {
const found = failures.filter((row) => matches(row, where));
for (const row of found) failures.splice(failures.indexOf(row), 1);
return found.length;
});

return failures;
}

/**
* An in-memory stand-in for the requests table that honours the where clauses the
* service writes, so its conditional updates are exercised rather than assumed.
Expand All @@ -35,6 +63,8 @@ export function installAccountRecoveryStore() {
const rows: Row[] = [];
let clock = 0;

installAuthFailureStore();

const instance = (row: Row) => {
Object.defineProperties(row, {
update: { value: async (fields: Row) => Object.assign(row, fields), enumerable: false },
Expand Down
Loading