feat(auth): wire lockout, rate-limit, and constant-time login into both routes
All checks were successful
Deploy to Homelab / deploy (push) Successful in 18s
All checks were successful
Deploy to Homelab / deploy (push) Successful in 18s
Both POST /login (HTML form) and POST /api/v1/auth/login now flow through the shared attemptLogin() handler. Locked accounts respond with 401 + Retry-After (generic body "Invalid credentials" / "Invalid username or password") so attackers can't use lockout state as a username-existence oracle. @fastify/rate-limit registered with global=false; only the two login routes opt in via per-route rateLimit config. File uploads and downloads keep full throughput. Custom errorResponseBuilder logs AUTH_RATE_LIMITED fire-and-forget so fail2ban can pick it up. createTestApp now accepts Partial<Config> overrides so integration tests can dial thresholds down without env-var mutation.
This commit is contained in:
@@ -6,10 +6,10 @@ import type Database from 'better-sqlite3';
|
||||
import type { Config } from '../config.ts';
|
||||
import type { Logger } from '../middleware/logging.ts';
|
||||
import type { JwtPayload } from '../types.ts';
|
||||
import { getUserByUsername } from '../db/users.ts';
|
||||
import type { LockoutService } from '../services/lockout.ts';
|
||||
import { createFile, getFileById, getFilesByUserId, deleteFile } from '../db/files.ts';
|
||||
import { verifyPassword } from '../services/auth.ts';
|
||||
import { saveFile, deleteStoredFile, getFilePath } from '../services/storage.ts';
|
||||
import { attemptLogin } from '../services/login-handler.ts';
|
||||
import { requireAuth, tokenCookieOptions } from '../middleware/auth.ts';
|
||||
import { loginPage } from '../views/login.ts';
|
||||
import { uploadPage, uploadResultPage } from '../views/upload.ts';
|
||||
@@ -21,6 +21,7 @@ interface Deps {
|
||||
db: Database.Database;
|
||||
config: Config;
|
||||
logger: Logger;
|
||||
lockout: LockoutService;
|
||||
}
|
||||
|
||||
function parseRangeHeader(header: string, fileSize: number): { start: number; end: number } | null {
|
||||
@@ -48,6 +49,12 @@ function parseRangeHeader(header: string, fileSize: number): { start: number; en
|
||||
|
||||
export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
|
||||
const { db, config, logger } = deps;
|
||||
const loginRateLimit = {
|
||||
rateLimit: {
|
||||
max: config.loginRateLimitMax,
|
||||
timeWindow: config.loginRateLimitWindowSeconds * 1000,
|
||||
},
|
||||
};
|
||||
|
||||
// GET / — login page or redirect if authed
|
||||
app.get('/', async (request, reply) => {
|
||||
@@ -60,24 +67,37 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
});
|
||||
|
||||
// POST /login — form login
|
||||
app.post<{ Body: { username?: string; password?: string } }>('/login', async (request, reply) => {
|
||||
const { username = '', password = '' } = request.body ?? {};
|
||||
const ip = request.ip;
|
||||
const userAgent = request.headers['user-agent'] ?? '';
|
||||
app.post<{ Body: { username?: string; password?: string } }>(
|
||||
'/login',
|
||||
{ config: loginRateLimit },
|
||||
async (request, reply) => {
|
||||
const { username = '', password = '' } = request.body ?? {};
|
||||
|
||||
const user = getUserByUsername(db, username);
|
||||
const valid = user ? await verifyPassword(password, user.password_hash) : false;
|
||||
const result = await attemptLogin(deps, {
|
||||
username,
|
||||
password,
|
||||
ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? '',
|
||||
});
|
||||
|
||||
if (!user || !valid) {
|
||||
await logger.authFailure({ ip, userAgent, username });
|
||||
return reply.type('text/html').send(loginPage({ error: 'Invalid username or password' }));
|
||||
}
|
||||
if (result.kind === 'locked') {
|
||||
return reply
|
||||
.type('text/html')
|
||||
.header('Retry-After', String(result.retryAfterSeconds))
|
||||
.send(loginPage({ error: 'Invalid username or password' }));
|
||||
}
|
||||
|
||||
await logger.authSuccess({ ip, userAgent, username });
|
||||
if (result.kind !== 'success') {
|
||||
return reply.type('text/html').send(loginPage({ error: 'Invalid username or password' }));
|
||||
}
|
||||
|
||||
const token = app.jwt.sign({ sub: user.id, username: user.username }, { expiresIn: config.jwtExpiry });
|
||||
reply.setCookie('token', token, tokenCookieOptions(config.cookieSecure)).redirect('/upload');
|
||||
});
|
||||
const token = app.jwt.sign(
|
||||
{ sub: result.user.id, username: result.user.username },
|
||||
{ expiresIn: config.jwtExpiry },
|
||||
);
|
||||
reply.setCookie('token', token, tokenCookieOptions(config.cookieSecure)).redirect('/upload');
|
||||
},
|
||||
);
|
||||
|
||||
// POST /logout
|
||||
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
|
||||
|
||||
Reference in New Issue
Block a user