feat(auth): add signIn rate-limit backfill with dual ip/account budgets

Wires the rate-limit primitive end-to-end through auth.signIn as the
canonical credential-stuffing defence example:

- manifest: rateLimit [ip 5/1m, account 10/1h] on signIn use case
- use case: rateLimit: IRateLimit dep; dual consume + TooManyRequestsError
- binders: ctx.rateLimit ?? new NoopRateLimit() in bind-production + bind-dev-seed
- tRPC: TooManyRequestsError → TOO_MANY_REQUESTS error code in authProcedure
- tests: RecordingRateLimit dual-consume assertion; InMemoryRateLimit
  budget-1 ip + account rejection; coverage 100% on use-cases layer
- ESLint: _manifest-ast.js extractRateLimitNames handles RateLimitBudget
  objects ({name,window,budget}) in addition to plain string literals,
  no-undeclared-rate-limit passes on both "ip" and "account" call sites

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-20 09:22:41 +00:00
parent 91d7a24ed9
commit b61bb0c11e
17 changed files with 273 additions and 42 deletions

View File

@@ -1,6 +1,10 @@
import { z } from "zod";
import { AuthenticationError } from "../../entities/errors/auth";
import type { IRateLimit } from "@repo/core-shared/rate-limit";
import {
AuthenticationError,
TooManyRequestsError,
} from "../../entities/errors/auth";
import { cookieSchema } from "../../entities/models/cookie";
import { sessionSchema } from "../../entities/models/session";
import type { IUsersRepository } from "../repositories/users.repository.interface";
@@ -11,6 +15,7 @@ export const signInInputSchema = z
.object({
username: z.string().min(3).max(31),
password: z.string().min(6).max(255),
clientIp: z.string().optional(),
})
.strict();
export type SignInInput = z.infer<typeof signInInputSchema>;
@@ -26,9 +31,28 @@ export type SignInOutput = z.infer<typeof signInOutputSchema>;
export type ISignInUseCase = ReturnType<typeof signInUseCase>;
export const signInUseCase =
(usersRepository: IUsersRepository, authenticationService: IAuthenticationService) =>
(
usersRepository: IUsersRepository,
authenticationService: IAuthenticationService,
rateLimit: IRateLimit,
) =>
async (input: SignInInput): Promise<SignInOutput> => {
const existingUser = await usersRepository.getUserByUsername(input.username);
const { allowed: ipAllowed } = await rateLimit.consume(
"ip",
`signIn:ip:${input.clientIp ?? ""}`,
);
if (!ipAllowed) throw new TooManyRequestsError("Too many sign-in attempts");
const { allowed: accountAllowed } = await rateLimit.consume(
"account",
`signIn:account:${input.username}`,
);
if (!accountAllowed)
throw new TooManyRequestsError("Too many sign-in attempts");
const existingUser = await usersRepository.getUserByUsername(
input.username,
);
if (!existingUser) {
throw new AuthenticationError("User does not exist");
}