Compare commits
6 Commits
chore/depe
...
feat/syste
| Author | SHA1 | Date | |
|---|---|---|---|
| c6aa030e54 | |||
| bbd292c085 | |||
| ad36b23061 | |||
| 11e87f353d | |||
| f4eaf88495 | |||
| d30f40ca71 |
22
package-lock.json
generated
22
package-lock.json
generated
@@ -13,6 +13,7 @@
|
||||
"@fastify/formbody": "^8.0.2",
|
||||
"@fastify/jwt": "^10.0.0",
|
||||
"@fastify/multipart": "^9.4.0",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/static": "^9.0.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
@@ -705,6 +706,27 @@
|
||||
"ipaddr.js": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@fastify/rate-limit": {
|
||||
"version": "10.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/rate-limit/-/rate-limit-10.3.0.tgz",
|
||||
"integrity": "sha512-eIGkG9XKQs0nyynatApA3EVrojHOuq4l6fhB4eeCk4PIOeadvOJz9/4w3vGI44Go17uaXOWEcPkaD8kuKm7g6Q==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/fastify"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/fastify"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@lukeed/ms": "^2.0.2",
|
||||
"fastify-plugin": "^5.0.0",
|
||||
"toad-cache": "^3.7.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@fastify/send": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.1.0.tgz",
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
"@fastify/formbody": "^8.0.2",
|
||||
"@fastify/jwt": "^10.0.0",
|
||||
"@fastify/multipart": "^9.4.0",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/static": "^9.0.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,400;0,500;0,600;1,400&display=swap');
|
||||
|
||||
/* ── Reset ──────────────────────────────────────────────── */
|
||||
*, *::before, *::after {
|
||||
box-sizing: border-box;
|
||||
@@ -18,7 +16,8 @@
|
||||
--gray-600:#555;
|
||||
--red: #c00;
|
||||
|
||||
--font: 'IBM Plex Mono', 'Courier New', monospace;
|
||||
--font: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||
--font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
||||
--border: 1px solid var(--black);
|
||||
--radius: 0;
|
||||
}
|
||||
@@ -28,6 +27,7 @@ html { font-size: 14px; }
|
||||
|
||||
body {
|
||||
font-family: var(--font);
|
||||
line-height: 1.5;
|
||||
background: var(--white);
|
||||
color: var(--black);
|
||||
min-height: 100vh;
|
||||
@@ -265,6 +265,7 @@ a.btn:hover {
|
||||
|
||||
.share-box input[readonly] {
|
||||
flex: 1;
|
||||
font-family: var(--font-mono);
|
||||
background: var(--gray-100);
|
||||
color: var(--gray-600);
|
||||
border-right: none;
|
||||
|
||||
@@ -10,6 +10,12 @@ export interface Config {
|
||||
baseUrl: string;
|
||||
cookieSecure: boolean;
|
||||
trustProxy: boolean;
|
||||
lockoutThreshold: number;
|
||||
lockoutBaseSeconds: number;
|
||||
lockoutMaxSeconds: number;
|
||||
loginMinResponseMs: number;
|
||||
loginRateLimitMax: number;
|
||||
loginRateLimitWindowSeconds: number;
|
||||
}
|
||||
|
||||
export function loadConfig(): Config {
|
||||
@@ -30,5 +36,11 @@ export function loadConfig(): Config {
|
||||
baseUrl: process.env.BASE_URL ?? 'http://localhost:3000',
|
||||
cookieSecure: process.env.COOKIE_SECURE === 'true',
|
||||
trustProxy: process.env.TRUST_PROXY === 'true',
|
||||
lockoutThreshold: parseInt(process.env.LOCKOUT_THRESHOLD ?? '5', 10),
|
||||
lockoutBaseSeconds: parseInt(process.env.LOCKOUT_BASE_SECONDS ?? '30', 10),
|
||||
lockoutMaxSeconds: parseInt(process.env.LOCKOUT_MAX_SECONDS ?? '3600', 10),
|
||||
loginMinResponseMs: parseInt(process.env.LOGIN_MIN_RESPONSE_MS ?? '350', 10),
|
||||
loginRateLimitMax: parseInt(process.env.LOGIN_RATE_LIMIT_MAX ?? '10', 10),
|
||||
loginRateLimitWindowSeconds: parseInt(process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS ?? '60', 10),
|
||||
};
|
||||
}
|
||||
|
||||
38
src/db/login-attempts.ts
Normal file
38
src/db/login-attempts.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
export interface LoginAttemptRow {
|
||||
username: string;
|
||||
failed_count: number;
|
||||
last_failed_at: string | null;
|
||||
locked_until: string | null;
|
||||
}
|
||||
|
||||
export function getLoginAttempt(
|
||||
db: Database.Database,
|
||||
username: string,
|
||||
): LoginAttemptRow | undefined {
|
||||
const stmt = db.prepare('SELECT * FROM login_attempts WHERE username = ?');
|
||||
return stmt.get(username) as LoginAttemptRow | undefined;
|
||||
}
|
||||
|
||||
export function recordFailure(
|
||||
db: Database.Database,
|
||||
username: string,
|
||||
lockedUntilIso: string | null,
|
||||
): LoginAttemptRow {
|
||||
const stmt = db.prepare(`
|
||||
INSERT INTO login_attempts (username, failed_count, last_failed_at, locked_until)
|
||||
VALUES (?, 1, datetime('now'), ?)
|
||||
ON CONFLICT(username) DO UPDATE SET
|
||||
failed_count = failed_count + 1,
|
||||
last_failed_at = datetime('now'),
|
||||
locked_until = excluded.locked_until
|
||||
RETURNING *
|
||||
`);
|
||||
return stmt.get(username, lockedUntilIso) as LoginAttemptRow;
|
||||
}
|
||||
|
||||
export function resetLoginAttempts(db: Database.Database, username: string): void {
|
||||
const stmt = db.prepare('DELETE FROM login_attempts WHERE username = ?');
|
||||
stmt.run(username);
|
||||
}
|
||||
@@ -22,6 +22,16 @@ export function initDb(dbPath: string): Database.Database {
|
||||
stored_name TEXT NOT NULL,
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS login_attempts (
|
||||
username TEXT PRIMARY KEY,
|
||||
failed_count INTEGER NOT NULL DEFAULT 0,
|
||||
last_failed_at TEXT,
|
||||
locked_until TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_login_attempts_locked_until
|
||||
ON login_attempts(locked_until);
|
||||
`);
|
||||
|
||||
return db;
|
||||
|
||||
@@ -12,9 +12,26 @@ interface FileNotFoundParams {
|
||||
fileId: string;
|
||||
}
|
||||
|
||||
interface AuthLockoutTriggeredParams extends AuthLogParams {
|
||||
durationSeconds: number;
|
||||
}
|
||||
|
||||
interface AuthLockedAttemptParams extends AuthLogParams {
|
||||
retryAfterSeconds: number;
|
||||
}
|
||||
|
||||
interface AuthRateLimitedParams {
|
||||
ip: string;
|
||||
userAgent: string;
|
||||
route: string;
|
||||
}
|
||||
|
||||
export interface Logger {
|
||||
authSuccess(params: AuthLogParams): Promise<void>;
|
||||
authFailure(params: AuthLogParams): Promise<void>;
|
||||
authLockoutTriggered(params: AuthLockoutTriggeredParams): Promise<void>;
|
||||
authLockedAttempt(params: AuthLockedAttemptParams): Promise<void>;
|
||||
authRateLimited(params: AuthRateLimitedParams): Promise<void>;
|
||||
fileNotFound(params: FileNotFoundParams): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -34,6 +51,12 @@ export function createLogger(logFile: string): Logger {
|
||||
return {
|
||||
authSuccess: (params) => write(authLine('AUTH_SUCCESS', params)),
|
||||
authFailure: (params) => write(authLine('AUTH_FAILURE', params)),
|
||||
authLockoutTriggered: ({ durationSeconds, ...auth }) =>
|
||||
write(`${authLine('AUTH_LOCKOUT_TRIGGERED', auth)} duration_seconds=${durationSeconds}`),
|
||||
authLockedAttempt: ({ retryAfterSeconds, ...auth }) =>
|
||||
write(`${authLine('AUTH_LOCKED_ATTEMPT', auth)} retry_after_seconds=${retryAfterSeconds}`),
|
||||
authRateLimited: ({ ip, userAgent, route }) =>
|
||||
write(`[${timestamp()}] AUTH_RATE_LIMITED ip=${ip} user-agent="${userAgent}" route="${route}"`),
|
||||
fileNotFound: ({ ip, userAgent, fileId }) =>
|
||||
write(`[${timestamp()}] FILE_NOT_FOUND ip=${ip} user-agent="${userAgent}" file_id="${fileId}"`),
|
||||
};
|
||||
|
||||
@@ -2,14 +2,15 @@ import type { FastifyPluginAsync } from 'fastify';
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { Config } from '../../../config.ts';
|
||||
import type { Logger } from '../../../middleware/logging.ts';
|
||||
import { getUserByUsername } from '../../../db/users.ts';
|
||||
import { verifyPassword } from '../../../services/auth.ts';
|
||||
import type { LockoutService } from '../../../services/lockout.ts';
|
||||
import { attemptLogin } from '../../../services/login-handler.ts';
|
||||
import { requireAuth, tokenCookieOptions } from '../../../middleware/auth.ts';
|
||||
|
||||
interface Deps {
|
||||
db: Database.Database;
|
||||
config: Config;
|
||||
logger: Logger;
|
||||
lockout: LockoutService;
|
||||
}
|
||||
|
||||
interface LoginBody {
|
||||
@@ -18,30 +19,50 @@ interface LoginBody {
|
||||
}
|
||||
|
||||
export const authApiRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
|
||||
const { db, config, logger } = deps;
|
||||
const { config } = deps;
|
||||
|
||||
app.post<{ Body: LoginBody }>('/login', async (request, reply) => {
|
||||
const { username, password } = request.body ?? {};
|
||||
const ip = request.ip;
|
||||
const userAgent = request.headers['user-agent'] ?? '';
|
||||
app.post<{ Body: LoginBody }>(
|
||||
'/login',
|
||||
{
|
||||
config: {
|
||||
rateLimit: {
|
||||
max: config.loginRateLimitMax,
|
||||
timeWindow: config.loginRateLimitWindowSeconds * 1000,
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const { username, password } = request.body ?? {};
|
||||
|
||||
if (!username || !password) {
|
||||
return reply.status(400).send({ error: 'username and password are required' });
|
||||
}
|
||||
const result = await attemptLogin(deps, {
|
||||
username: username ?? '',
|
||||
password: password ?? '',
|
||||
ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? '',
|
||||
});
|
||||
|
||||
const user = getUserByUsername(db, username);
|
||||
const valid = user ? await verifyPassword(password, user.password_hash) : false;
|
||||
if (result.kind === 'bad_request') {
|
||||
return reply.status(400).send({ error: 'username and password are required' });
|
||||
}
|
||||
|
||||
if (!user || !valid) {
|
||||
await logger.authFailure({ ip, userAgent, username });
|
||||
return reply.status(401).send({ error: 'Invalid credentials' });
|
||||
}
|
||||
if (result.kind === 'locked') {
|
||||
return reply
|
||||
.status(401)
|
||||
.header('Retry-After', String(result.retryAfterSeconds))
|
||||
.send({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
await logger.authSuccess({ ip, userAgent, username });
|
||||
if (result.kind === 'bad_credentials') {
|
||||
return reply.status(401).send({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
const token = app.jwt.sign({ sub: user.id, username: user.username }, { expiresIn: config.jwtExpiry });
|
||||
reply.setCookie('token', token, tokenCookieOptions(config.cookieSecure)).send({ ok: true });
|
||||
});
|
||||
const token = app.jwt.sign(
|
||||
{ sub: result.user.id, username: result.user.username },
|
||||
{ expiresIn: config.jwtExpiry },
|
||||
);
|
||||
reply.setCookie('token', token, tokenCookieOptions(config.cookieSecure)).send({ ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
|
||||
reply.clearCookie('token', { path: '/' }).send({ ok: true });
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -4,11 +4,13 @@ import fastifyJwt from '@fastify/jwt';
|
||||
import fastifyMultipart from '@fastify/multipart';
|
||||
import fastifyFormbody from '@fastify/formbody';
|
||||
import fastifyStatic from '@fastify/static';
|
||||
import fastifyRateLimit from '@fastify/rate-limit';
|
||||
import { join } from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { Config } from './config.ts';
|
||||
import { createLogger } from './middleware/logging.ts';
|
||||
import { createLockoutService } from './services/lockout.ts';
|
||||
import { authApiRoutes } from './routes/api/v1/auth.ts';
|
||||
import { filesApiRoutes } from './routes/api/v1/files.ts';
|
||||
import { pageRoutes } from './routes/pages.ts';
|
||||
@@ -23,6 +25,7 @@ interface ServerDeps {
|
||||
export function createServer({ config, db }: ServerDeps) {
|
||||
const app = Fastify({ logger: false, trustProxy: config.trustProxy });
|
||||
const logger = createLogger(config.logFile);
|
||||
const lockout = createLockoutService({ db, config });
|
||||
|
||||
app.register(fastifyCookie);
|
||||
app.register(fastifyJwt, {
|
||||
@@ -35,8 +38,20 @@ export function createServer({ config, db }: ServerDeps) {
|
||||
root: join(__dirname, '..', 'public'),
|
||||
prefix: '/public/',
|
||||
});
|
||||
app.register(fastifyRateLimit, {
|
||||
global: false,
|
||||
keyGenerator: (req) => req.ip,
|
||||
errorResponseBuilder: (req) => {
|
||||
void logger.authRateLimited({
|
||||
ip: req.ip,
|
||||
userAgent: req.headers['user-agent'] ?? '',
|
||||
route: req.url,
|
||||
});
|
||||
return { statusCode: 429, error: 'Too many requests' };
|
||||
},
|
||||
});
|
||||
|
||||
const deps = { db, config, logger };
|
||||
const deps = { db, config, logger, lockout };
|
||||
|
||||
app.register(authApiRoutes, { prefix: '/api/v1/auth', deps });
|
||||
app.register(filesApiRoutes, { prefix: '/api/v1/files', deps });
|
||||
|
||||
25
src/services/dummy-hash.ts
Normal file
25
src/services/dummy-hash.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import bcrypt from 'bcrypt';
|
||||
import { hashPassword } from './auth.ts';
|
||||
|
||||
let cachedHash: Promise<string> | null = null;
|
||||
|
||||
function getDummyHash(): Promise<string> {
|
||||
if (!cachedHash) {
|
||||
// Hash a value no caller will ever submit (cryptographically random
|
||||
// string generated once at module init). Cost factor matches real users
|
||||
// because hashPassword uses the same SALT_ROUNDS.
|
||||
const seed = `dummy:${Date.now()}:${Math.random()}:${process.pid}`;
|
||||
cachedHash = hashPassword(seed);
|
||||
}
|
||||
return cachedHash;
|
||||
}
|
||||
|
||||
export async function verifyAgainstDummy(password: string): Promise<boolean> {
|
||||
const hash = await getDummyHash();
|
||||
await bcrypt.compare(password, hash);
|
||||
return false;
|
||||
}
|
||||
|
||||
export function _resetDummyHashForTests(): void {
|
||||
cachedHash = null;
|
||||
}
|
||||
78
src/services/lockout.ts
Normal file
78
src/services/lockout.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { Config } from '../config.ts';
|
||||
import {
|
||||
getLoginAttempt,
|
||||
recordFailure as dbRecordFailure,
|
||||
resetLoginAttempts,
|
||||
} from '../db/login-attempts.ts';
|
||||
|
||||
export interface LockoutCheckResult {
|
||||
locked: boolean;
|
||||
retryAfterSeconds?: number;
|
||||
}
|
||||
|
||||
export interface LockoutFailureResult {
|
||||
locked: boolean;
|
||||
durationSeconds: number;
|
||||
failedCount: number;
|
||||
}
|
||||
|
||||
export interface LockoutService {
|
||||
check(username: string): LockoutCheckResult;
|
||||
recordFailure(username: string): LockoutFailureResult;
|
||||
recordSuccess(username: string): void;
|
||||
}
|
||||
|
||||
interface LockoutDeps {
|
||||
db: Database.Database;
|
||||
config: Config;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
function computeDurationSeconds(failedCount: number, config: Config): number {
|
||||
const { lockoutThreshold, lockoutBaseSeconds, lockoutMaxSeconds } = config;
|
||||
if (failedCount < lockoutThreshold) return 0;
|
||||
const exponent = failedCount - lockoutThreshold;
|
||||
const raw = lockoutBaseSeconds * 2 ** exponent;
|
||||
return Math.min(lockoutMaxSeconds, raw);
|
||||
}
|
||||
|
||||
export function createLockoutService(deps: LockoutDeps): LockoutService {
|
||||
const { db, config } = deps;
|
||||
const now = deps.now ?? ((): Date => new Date());
|
||||
|
||||
return {
|
||||
check(username: string): LockoutCheckResult {
|
||||
const row = getLoginAttempt(db, username);
|
||||
if (!row?.locked_until) return { locked: false };
|
||||
|
||||
const lockedUntilMs = Date.parse(row.locked_until);
|
||||
const remainingMs = lockedUntilMs - now().getTime();
|
||||
if (remainingMs <= 0) return { locked: false };
|
||||
|
||||
return { locked: true, retryAfterSeconds: Math.ceil(remainingMs / 1000) };
|
||||
},
|
||||
|
||||
recordFailure(username: string): LockoutFailureResult {
|
||||
const existing = getLoginAttempt(db, username);
|
||||
const nextCount = (existing?.failed_count ?? 0) + 1;
|
||||
const durationSeconds = computeDurationSeconds(nextCount, config);
|
||||
const lockedUntilIso =
|
||||
durationSeconds > 0
|
||||
? new Date(now().getTime() + durationSeconds * 1000).toISOString()
|
||||
: null;
|
||||
|
||||
dbRecordFailure(db, username, lockedUntilIso);
|
||||
|
||||
return {
|
||||
locked: durationSeconds > 0,
|
||||
durationSeconds,
|
||||
failedCount: nextCount,
|
||||
};
|
||||
},
|
||||
|
||||
recordSuccess(username: string): void {
|
||||
resetLoginAttempts(db, username);
|
||||
},
|
||||
};
|
||||
}
|
||||
90
src/services/login-handler.ts
Normal file
90
src/services/login-handler.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { Config } from '../config.ts';
|
||||
import type { Logger } from '../middleware/logging.ts';
|
||||
import type { LockoutService } from './lockout.ts';
|
||||
import { getUserByUsername } from '../db/users.ts';
|
||||
import { verifyPassword } from './auth.ts';
|
||||
import { verifyAgainstDummy } from './dummy-hash.ts';
|
||||
|
||||
interface UserRow {
|
||||
id: number;
|
||||
username: string;
|
||||
password_hash: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export type LoginResult =
|
||||
| { kind: 'success'; user: UserRow }
|
||||
| { kind: 'bad_credentials' }
|
||||
| { kind: 'locked'; retryAfterSeconds: number }
|
||||
| { kind: 'bad_request' };
|
||||
|
||||
export interface LoginHandlerDeps {
|
||||
db: Database.Database;
|
||||
config: Config;
|
||||
logger: Logger;
|
||||
lockout: LockoutService;
|
||||
}
|
||||
|
||||
export interface LoginInput {
|
||||
username: string;
|
||||
password: string;
|
||||
ip: string;
|
||||
userAgent: string;
|
||||
}
|
||||
|
||||
function canonicalize(username: string): string {
|
||||
return username.trim().toLowerCase();
|
||||
}
|
||||
|
||||
async function clamp(startMs: number, minMs: number): Promise<void> {
|
||||
const elapsed = Date.now() - startMs;
|
||||
const remaining = minMs - elapsed;
|
||||
if (remaining > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, remaining));
|
||||
}
|
||||
}
|
||||
|
||||
export async function attemptLogin(
|
||||
deps: LoginHandlerDeps,
|
||||
input: LoginInput,
|
||||
): Promise<LoginResult> {
|
||||
const { db, config, logger, lockout } = deps;
|
||||
const start = Date.now();
|
||||
|
||||
if (!input.username || !input.password) {
|
||||
// No clamp on bad_request — it's a programmer/format error from the caller,
|
||||
// not a credential test, so timing isn't sensitive.
|
||||
return { kind: 'bad_request' };
|
||||
}
|
||||
|
||||
const username = canonicalize(input.username);
|
||||
const logBase = { ip: input.ip, userAgent: input.userAgent, username };
|
||||
|
||||
const lockStatus = lockout.check(username);
|
||||
if (lockStatus.locked) {
|
||||
await logger.authLockedAttempt({ ...logBase, retryAfterSeconds: lockStatus.retryAfterSeconds! });
|
||||
await clamp(start, config.loginMinResponseMs);
|
||||
return { kind: 'locked', retryAfterSeconds: lockStatus.retryAfterSeconds! };
|
||||
}
|
||||
|
||||
const user = getUserByUsername(db, username);
|
||||
const valid = user
|
||||
? await verifyPassword(input.password, user.password_hash)
|
||||
: await verifyAgainstDummy(input.password);
|
||||
|
||||
if (user && valid) {
|
||||
lockout.recordSuccess(username);
|
||||
await logger.authSuccess(logBase);
|
||||
await clamp(start, config.loginMinResponseMs);
|
||||
return { kind: 'success', user };
|
||||
}
|
||||
|
||||
const failure = lockout.recordFailure(username);
|
||||
if (failure.locked) {
|
||||
await logger.authLockoutTriggered({ ...logBase, durationSeconds: failure.durationSeconds });
|
||||
}
|
||||
await logger.authFailure(logBase);
|
||||
await clamp(start, config.loginMinResponseMs);
|
||||
return { kind: 'bad_credentials' };
|
||||
}
|
||||
@@ -53,7 +53,7 @@ export interface TestContext {
|
||||
cleanup: () => void;
|
||||
}
|
||||
|
||||
export function createTestApp(): TestContext {
|
||||
export function createTestApp(overrides: Partial<Config> = {}): TestContext {
|
||||
const tmpDir = mkdtempSync(join(tmpdir(), 'nanodrop-int-'));
|
||||
const uploadDir = join(tmpDir, 'uploads');
|
||||
const logFile = join(tmpDir, 'test.log');
|
||||
@@ -74,6 +74,13 @@ export function createTestApp(): TestContext {
|
||||
baseUrl: 'http://localhost:3000',
|
||||
cookieSecure: false,
|
||||
trustProxy: false,
|
||||
lockoutThreshold: 5,
|
||||
lockoutBaseSeconds: 30,
|
||||
lockoutMaxSeconds: 3600,
|
||||
loginMinResponseMs: 0,
|
||||
loginRateLimitMax: 1000,
|
||||
loginRateLimitWindowSeconds: 60,
|
||||
...overrides,
|
||||
};
|
||||
|
||||
const app = createServer({ config, db });
|
||||
|
||||
135
tests/integration/auth-lockout.test.ts
Normal file
135
tests/integration/auth-lockout.test.ts
Normal file
@@ -0,0 +1,135 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { readFileSync } from 'fs';
|
||||
import { createTestApp, type TestContext } from '../helpers/setup.ts';
|
||||
import { createUser } from '../../src/db/users.ts';
|
||||
import { hashPassword } from '../../src/services/auth.ts';
|
||||
|
||||
async function attempt(
|
||||
ctx: TestContext,
|
||||
username: string,
|
||||
password: string,
|
||||
ip = '203.0.113.7',
|
||||
) {
|
||||
return ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/auth/login',
|
||||
headers: { 'content-type': 'application/json', 'x-forwarded-for': ip },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
}
|
||||
|
||||
describe('account lockout — JSON login', () => {
|
||||
let ctx: TestContext;
|
||||
|
||||
beforeEach(async () => {
|
||||
ctx = createTestApp({
|
||||
lockoutThreshold: 3,
|
||||
lockoutBaseSeconds: 60,
|
||||
loginMinResponseMs: 0,
|
||||
loginRateLimitMax: 1000, // effectively off for these cases
|
||||
});
|
||||
const hash = await hashPassword('correct-pw');
|
||||
createUser(ctx.db, { username: 'alice', passwordHash: hash });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx.app.close();
|
||||
ctx.cleanup();
|
||||
});
|
||||
|
||||
it('locks after threshold failed attempts and emits AUTH_LOCKOUT_TRIGGERED', async () => {
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
const third = await attempt(ctx, 'alice', 'wrong');
|
||||
expect(third.statusCode).toBe(401);
|
||||
|
||||
const log = readFileSync(ctx.logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_LOCKOUT_TRIGGERED/);
|
||||
expect(log).toMatch(/duration_seconds=60/);
|
||||
});
|
||||
|
||||
it('rejects correct password while locked with Retry-After header', async () => {
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
|
||||
const blocked = await attempt(ctx, 'alice', 'correct-pw');
|
||||
expect(blocked.statusCode).toBe(401);
|
||||
expect(blocked.headers['retry-after']).toBeDefined();
|
||||
expect(parseInt(String(blocked.headers['retry-after']), 10)).toBeGreaterThan(0);
|
||||
|
||||
// No success log was written for the locked attempt
|
||||
const log = readFileSync(ctx.logFile, 'utf-8');
|
||||
expect(log).not.toMatch(/AUTH_SUCCESS/);
|
||||
});
|
||||
|
||||
it('successful login resets the counter', async () => {
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
const ok = await attempt(ctx, 'alice', 'correct-pw');
|
||||
expect(ok.statusCode).toBe(200);
|
||||
|
||||
// After reset, two more wrong attempts should NOT lock (threshold is 3)
|
||||
await attempt(ctx, 'alice', 'wrong');
|
||||
const second = await attempt(ctx, 'alice', 'wrong');
|
||||
expect(second.statusCode).toBe(401);
|
||||
expect(second.headers['retry-after']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('canonicalizes username — ALICE and alice share the same lockout row', async () => {
|
||||
await attempt(ctx, 'ALICE', 'wrong');
|
||||
await attempt(ctx, 'Alice', 'wrong');
|
||||
const third = await attempt(ctx, 'alice', 'wrong');
|
||||
expect(third.statusCode).toBe(401);
|
||||
const log = readFileSync(ctx.logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_LOCKOUT_TRIGGERED/);
|
||||
});
|
||||
|
||||
it('unknown user accumulates failures (no enumeration via bypass)', async () => {
|
||||
await attempt(ctx, 'ghost', 'x');
|
||||
await attempt(ctx, 'ghost', 'x');
|
||||
await attempt(ctx, 'ghost', 'x');
|
||||
const fourth = await attempt(ctx, 'ghost', 'x');
|
||||
expect(fourth.statusCode).toBe(401);
|
||||
expect(fourth.headers['retry-after']).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('account lockout — form login', () => {
|
||||
let ctx: TestContext;
|
||||
|
||||
beforeEach(async () => {
|
||||
ctx = createTestApp({
|
||||
lockoutThreshold: 2,
|
||||
lockoutBaseSeconds: 30,
|
||||
loginMinResponseMs: 0,
|
||||
loginRateLimitMax: 1000,
|
||||
});
|
||||
const hash = await hashPassword('correct-pw');
|
||||
createUser(ctx.db, { username: 'alice', passwordHash: hash });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx.app.close();
|
||||
ctx.cleanup();
|
||||
});
|
||||
|
||||
async function formAttempt(username: string, password: string) {
|
||||
return ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/login',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
payload: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
|
||||
});
|
||||
}
|
||||
|
||||
it('locks the form login and renders generic error with Retry-After', async () => {
|
||||
await formAttempt('alice', 'wrong');
|
||||
await formAttempt('alice', 'wrong');
|
||||
|
||||
const blocked = await formAttempt('alice', 'correct-pw');
|
||||
expect(blocked.statusCode).toBe(200); // login page re-render, not redirect
|
||||
expect(blocked.body).toContain('Invalid username or password');
|
||||
expect(blocked.headers['retry-after']).toBeDefined();
|
||||
});
|
||||
});
|
||||
71
tests/integration/auth-rate-limit.test.ts
Normal file
71
tests/integration/auth-rate-limit.test.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { readFileSync } from 'fs';
|
||||
import { createTestApp, type TestContext } from '../helpers/setup.ts';
|
||||
import { createUser } from '../../src/db/users.ts';
|
||||
import { hashPassword } from '../../src/services/auth.ts';
|
||||
|
||||
describe('per-IP rate limit on login routes', () => {
|
||||
let ctx: TestContext;
|
||||
|
||||
beforeEach(async () => {
|
||||
ctx = createTestApp({
|
||||
loginRateLimitMax: 3,
|
||||
loginRateLimitWindowSeconds: 60,
|
||||
lockoutThreshold: 100, // disable lockout for this suite
|
||||
loginMinResponseMs: 0,
|
||||
});
|
||||
const hash = await hashPassword('correct-pw');
|
||||
createUser(ctx.db, { username: 'alice', passwordHash: hash });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await ctx.app.close();
|
||||
ctx.cleanup();
|
||||
});
|
||||
|
||||
async function loginRequest() {
|
||||
return ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/auth/login',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'alice', password: 'wrong' }),
|
||||
});
|
||||
}
|
||||
|
||||
it('returns 429 once IP exceeds the per-route limit and logs AUTH_RATE_LIMITED', async () => {
|
||||
expect((await loginRequest()).statusCode).toBe(401);
|
||||
expect((await loginRequest()).statusCode).toBe(401);
|
||||
expect((await loginRequest()).statusCode).toBe(401);
|
||||
const fourth = await loginRequest();
|
||||
expect(fourth.statusCode).toBe(429);
|
||||
expect(fourth.json().error).toBe('Too many requests');
|
||||
|
||||
// Wait for fire-and-forget log write
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
const log = readFileSync(ctx.logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_RATE_LIMITED/);
|
||||
expect(log).toMatch(/route="\/api\/v1\/auth\/login"/);
|
||||
});
|
||||
|
||||
it('does NOT throttle the file upload endpoint', async () => {
|
||||
// First, get a valid session
|
||||
const loginRes = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/auth/login',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'alice', password: 'correct-pw' }),
|
||||
});
|
||||
expect(loginRes.statusCode).toBe(200);
|
||||
const cookie = (loginRes.headers['set-cookie'] as string).split(';')[0].replace('token=', '');
|
||||
|
||||
// Now hit /upload (GET) repeatedly past the login-route limit threshold
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const r = await ctx.app.inject({
|
||||
method: 'GET',
|
||||
url: '/upload',
|
||||
cookies: { token: cookie },
|
||||
});
|
||||
expect(r.statusCode).toBe(200);
|
||||
}
|
||||
});
|
||||
});
|
||||
43
tests/integration/style.test.ts
Normal file
43
tests/integration/style.test.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { createTestApp, type TestContext } from '../helpers/setup.ts';
|
||||
|
||||
const STYLE_PATH = join(process.cwd(), 'public', 'style.css');
|
||||
|
||||
describe('public/style.css (file contents)', () => {
|
||||
const css = readFileSync(STYLE_PATH, 'utf8');
|
||||
|
||||
it('does not @import any external font CSS', () => {
|
||||
expect(css).not.toContain('googleapis.com');
|
||||
expect(css).not.toContain('@import');
|
||||
});
|
||||
|
||||
it('does not reference the previous IBM Plex Mono webfont', () => {
|
||||
expect(css).not.toContain('IBM Plex');
|
||||
});
|
||||
|
||||
it('uses the system sans-serif stack as its default font', () => {
|
||||
expect(css).toContain('-apple-system');
|
||||
});
|
||||
|
||||
it('keeps a monospace stack available via --font-mono for code-like UI', () => {
|
||||
expect(css).toContain('--font-mono');
|
||||
expect(css).toMatch(/\.share-box input\[readonly\][\s\S]*?font-family:\s*var\(--font-mono\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET /public/style.css', () => {
|
||||
let ctx: TestContext;
|
||||
|
||||
beforeEach(() => { ctx = createTestApp(); });
|
||||
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
|
||||
|
||||
it('serves the stylesheet as text/css with no external font import', async () => {
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/public/style.css' });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['content-type']).toMatch(/text\/css/);
|
||||
expect(res.body).not.toContain('googleapis.com');
|
||||
expect(res.body).toContain('-apple-system');
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,12 @@ describe('config', () => {
|
||||
delete process.env.BASE_URL;
|
||||
delete process.env.COOKIE_SECURE;
|
||||
delete process.env.TRUST_PROXY;
|
||||
delete process.env.LOCKOUT_THRESHOLD;
|
||||
delete process.env.LOCKOUT_BASE_SECONDS;
|
||||
delete process.env.LOCKOUT_MAX_SECONDS;
|
||||
delete process.env.LOGIN_MIN_RESPONSE_MS;
|
||||
delete process.env.LOGIN_RATE_LIMIT_MAX;
|
||||
delete process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS;
|
||||
|
||||
const { loadConfig } = await import('../../src/config.ts');
|
||||
const config = loadConfig();
|
||||
@@ -37,6 +43,12 @@ describe('config', () => {
|
||||
expect(config.baseUrl).toBe('http://localhost:3000');
|
||||
expect(config.cookieSecure).toBe(false);
|
||||
expect(config.trustProxy).toBe(false);
|
||||
expect(config.lockoutThreshold).toBe(5);
|
||||
expect(config.lockoutBaseSeconds).toBe(30);
|
||||
expect(config.lockoutMaxSeconds).toBe(3600);
|
||||
expect(config.loginMinResponseMs).toBe(350);
|
||||
expect(config.loginRateLimitMax).toBe(10);
|
||||
expect(config.loginRateLimitWindowSeconds).toBe(60);
|
||||
});
|
||||
|
||||
it('reads values from env vars', async () => {
|
||||
@@ -60,6 +72,26 @@ describe('config', () => {
|
||||
expect(config.maxFileSize).toBe(52428800);
|
||||
});
|
||||
|
||||
it('reads lockout and rate-limit values from env vars', async () => {
|
||||
process.env.JWT_SECRET = 'my-secret';
|
||||
process.env.LOCKOUT_THRESHOLD = '3';
|
||||
process.env.LOCKOUT_BASE_SECONDS = '15';
|
||||
process.env.LOCKOUT_MAX_SECONDS = '900';
|
||||
process.env.LOGIN_MIN_RESPONSE_MS = '50';
|
||||
process.env.LOGIN_RATE_LIMIT_MAX = '20';
|
||||
process.env.LOGIN_RATE_LIMIT_WINDOW_SECONDS = '120';
|
||||
|
||||
const { loadConfig } = await import('../../src/config.ts');
|
||||
const config = loadConfig();
|
||||
|
||||
expect(config.lockoutThreshold).toBe(3);
|
||||
expect(config.lockoutBaseSeconds).toBe(15);
|
||||
expect(config.lockoutMaxSeconds).toBe(900);
|
||||
expect(config.loginMinResponseMs).toBe(50);
|
||||
expect(config.loginRateLimitMax).toBe(20);
|
||||
expect(config.loginRateLimitWindowSeconds).toBe(120);
|
||||
});
|
||||
|
||||
it('throws when JWT_SECRET is missing', async () => {
|
||||
delete process.env.JWT_SECRET;
|
||||
const { loadConfig } = await import('../../src/config.ts');
|
||||
|
||||
58
tests/unit/dummy-hash.test.ts
Normal file
58
tests/unit/dummy-hash.test.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import bcrypt from 'bcrypt';
|
||||
import { verifyAgainstDummy, _resetDummyHashForTests } from '../../src/services/dummy-hash.ts';
|
||||
import { hashPassword, verifyPassword } from '../../src/services/auth.ts';
|
||||
|
||||
describe('dummy hash', () => {
|
||||
beforeEach(() => {
|
||||
_resetDummyHashForTests();
|
||||
});
|
||||
|
||||
it('always returns false', async () => {
|
||||
expect(await verifyAgainstDummy('whatever')).toBe(false);
|
||||
expect(await verifyAgainstDummy('')).toBe(false);
|
||||
expect(await verifyAgainstDummy('admin')).toBe(false);
|
||||
});
|
||||
|
||||
it('takes comparable time to verifying a real bcrypt hash (within 5x)', async () => {
|
||||
// Warm dummy hash so the cache is hot.
|
||||
await verifyAgainstDummy('warmup');
|
||||
const realHash = await hashPassword('actual-password');
|
||||
|
||||
const start1 = Date.now();
|
||||
await verifyPassword('actual-password', realHash);
|
||||
const realMs = Date.now() - start1;
|
||||
|
||||
const start2 = Date.now();
|
||||
await verifyAgainstDummy('any-password');
|
||||
const dummyMs = Date.now() - start2;
|
||||
|
||||
// Both should be in the same ballpark — bcrypt cost factor is the same.
|
||||
// Generous bound to avoid flakes on slow CI.
|
||||
expect(dummyMs).toBeGreaterThan(realMs / 5);
|
||||
expect(dummyMs).toBeLessThan(realMs * 5);
|
||||
}, 10_000);
|
||||
|
||||
it('memoizes the dummy hash across calls', async () => {
|
||||
// First call computes, subsequent calls reuse — covered by cache hit
|
||||
// being noticeably faster than a fresh hash. Just assert the function
|
||||
// is callable repeatedly without error.
|
||||
await verifyAgainstDummy('a');
|
||||
await verifyAgainstDummy('b');
|
||||
await verifyAgainstDummy('c');
|
||||
expect(true).toBe(true);
|
||||
});
|
||||
|
||||
it('runs a real bcrypt comparison (does not short-circuit)', async () => {
|
||||
// Spy by counting bcrypt.compare calls would be nice, but bcrypt
|
||||
// is a compiled module. Indirect check: the call must actually take
|
||||
// bcrypt-comparison time after warmup.
|
||||
await verifyAgainstDummy('warmup');
|
||||
const start = Date.now();
|
||||
await verifyAgainstDummy('test');
|
||||
const elapsed = Date.now() - start;
|
||||
// bcrypt 12 rounds takes >50ms on any modern CPU
|
||||
expect(elapsed).toBeGreaterThan(20);
|
||||
expect(bcrypt).toBeDefined();
|
||||
}, 10_000);
|
||||
});
|
||||
127
tests/unit/lockout-service.test.ts
Normal file
127
tests/unit/lockout-service.test.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { initDb } from '../../src/db/schema.ts';
|
||||
import type { Config } from '../../src/config.ts';
|
||||
import { createLockoutService } from '../../src/services/lockout.ts';
|
||||
import { recordFailure as dbRecordFailure } from '../../src/db/login-attempts.ts';
|
||||
|
||||
function makeConfig(overrides: Partial<Config> = {}): Config {
|
||||
return {
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
jwtSecret: 'x',
|
||||
jwtExpiry: '1h',
|
||||
dbPath: ':memory:',
|
||||
uploadDir: '/tmp',
|
||||
logFile: '/tmp/x.log',
|
||||
maxFileSize: 0,
|
||||
baseUrl: '',
|
||||
cookieSecure: false,
|
||||
trustProxy: false,
|
||||
lockoutThreshold: 3,
|
||||
lockoutBaseSeconds: 10,
|
||||
lockoutMaxSeconds: 80,
|
||||
loginMinResponseMs: 0,
|
||||
loginRateLimitMax: 0,
|
||||
loginRateLimitWindowSeconds: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('lockout service', () => {
|
||||
let db: Database.Database;
|
||||
let nowMs: number;
|
||||
const now = (): Date => new Date(nowMs);
|
||||
|
||||
beforeEach(() => {
|
||||
db = initDb(':memory:');
|
||||
nowMs = Date.UTC(2026, 0, 1, 0, 0, 0);
|
||||
});
|
||||
|
||||
describe('check', () => {
|
||||
it('returns not-locked when no row exists', () => {
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
expect(svc.check('alice')).toEqual({ locked: false });
|
||||
});
|
||||
|
||||
it('returns not-locked when locked_until is in the past', () => {
|
||||
const past = new Date(nowMs - 1000).toISOString();
|
||||
dbRecordFailure(db, 'alice', past);
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
expect(svc.check('alice')).toEqual({ locked: false });
|
||||
});
|
||||
|
||||
it('returns locked with retry-after seconds when locked_until is in the future', () => {
|
||||
const future = new Date(nowMs + 30_000).toISOString();
|
||||
dbRecordFailure(db, 'alice', future);
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
expect(svc.check('alice')).toEqual({ locked: true, retryAfterSeconds: 30 });
|
||||
});
|
||||
|
||||
it('rounds up sub-second remainder so retry-after is never 0', () => {
|
||||
const future = new Date(nowMs + 100).toISOString();
|
||||
dbRecordFailure(db, 'alice', future);
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
expect(svc.check('alice').retryAfterSeconds).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordFailure', () => {
|
||||
it('does not lock under threshold', () => {
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
const r1 = svc.recordFailure('alice');
|
||||
expect(r1).toEqual({ locked: false, durationSeconds: 0, failedCount: 1 });
|
||||
const r2 = svc.recordFailure('alice');
|
||||
expect(r2).toEqual({ locked: false, durationSeconds: 0, failedCount: 2 });
|
||||
});
|
||||
|
||||
it('locks with base duration at threshold', () => {
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
svc.recordFailure('alice');
|
||||
svc.recordFailure('alice');
|
||||
const r3 = svc.recordFailure('alice');
|
||||
expect(r3.locked).toBe(true);
|
||||
expect(r3.durationSeconds).toBe(10);
|
||||
expect(r3.failedCount).toBe(3);
|
||||
});
|
||||
|
||||
it('doubles duration past threshold', () => {
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
svc.recordFailure('alice'); // 1
|
||||
svc.recordFailure('alice'); // 2
|
||||
expect(svc.recordFailure('alice').durationSeconds).toBe(10); // 3 -> base
|
||||
expect(svc.recordFailure('alice').durationSeconds).toBe(20); // 4
|
||||
expect(svc.recordFailure('alice').durationSeconds).toBe(40); // 5
|
||||
expect(svc.recordFailure('alice').durationSeconds).toBe(80); // 6 -> cap
|
||||
expect(svc.recordFailure('alice').durationSeconds).toBe(80); // 7 -> still cap
|
||||
});
|
||||
|
||||
it('persists locked_until reachable via check', () => {
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
svc.recordFailure('alice');
|
||||
svc.recordFailure('alice');
|
||||
svc.recordFailure('alice');
|
||||
const status = svc.check('alice');
|
||||
expect(status.locked).toBe(true);
|
||||
expect(status.retryAfterSeconds).toBe(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recordSuccess', () => {
|
||||
it('clears the attempt row', () => {
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
svc.recordFailure('alice');
|
||||
svc.recordFailure('alice');
|
||||
svc.recordSuccess('alice');
|
||||
// Next failure starts at 1, no lock
|
||||
const r = svc.recordFailure('alice');
|
||||
expect(r.failedCount).toBe(1);
|
||||
expect(r.locked).toBe(false);
|
||||
});
|
||||
|
||||
it('is a no-op for unknown username', () => {
|
||||
const svc = createLockoutService({ db, config: makeConfig(), now });
|
||||
expect(() => svc.recordSuccess('ghost')).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -50,6 +50,48 @@ describe('middleware/logging', () => {
|
||||
expect(existsSync(logFile)).toBe(true);
|
||||
});
|
||||
|
||||
it('writes AUTH_LOCKOUT_TRIGGERED log entry with duration', async () => {
|
||||
const logger = createLogger(logFile);
|
||||
await logger.authLockoutTriggered({
|
||||
ip: '1.2.3.4',
|
||||
userAgent: 'TestAgent/1.0',
|
||||
username: 'alice',
|
||||
durationSeconds: 60,
|
||||
});
|
||||
const content = readFileSync(logFile, 'utf-8');
|
||||
expect(content).toMatch(/AUTH_LOCKOUT_TRIGGERED/);
|
||||
expect(content).toMatch(/ip=1\.2\.3\.4/);
|
||||
expect(content).toMatch(/username="alice"/);
|
||||
expect(content).toMatch(/duration_seconds=60/);
|
||||
});
|
||||
|
||||
it('writes AUTH_LOCKED_ATTEMPT log entry with retry-after', async () => {
|
||||
const logger = createLogger(logFile);
|
||||
await logger.authLockedAttempt({
|
||||
ip: '1.2.3.4',
|
||||
userAgent: 'TestAgent/1.0',
|
||||
username: 'alice',
|
||||
retryAfterSeconds: 25,
|
||||
});
|
||||
const content = readFileSync(logFile, 'utf-8');
|
||||
expect(content).toMatch(/AUTH_LOCKED_ATTEMPT/);
|
||||
expect(content).toMatch(/username="alice"/);
|
||||
expect(content).toMatch(/retry_after_seconds=25/);
|
||||
});
|
||||
|
||||
it('writes AUTH_RATE_LIMITED log entry with route', async () => {
|
||||
const logger = createLogger(logFile);
|
||||
await logger.authRateLimited({
|
||||
ip: '9.9.9.9',
|
||||
userAgent: 'curl/7.0',
|
||||
route: '/api/v1/auth/login',
|
||||
});
|
||||
const content = readFileSync(logFile, 'utf-8');
|
||||
expect(content).toMatch(/AUTH_RATE_LIMITED/);
|
||||
expect(content).toMatch(/ip=9\.9\.9\.9/);
|
||||
expect(content).toMatch(/route="\/api\/v1\/auth\/login"/);
|
||||
});
|
||||
|
||||
it('appends multiple entries', async () => {
|
||||
const logger = createLogger(logFile);
|
||||
await logger.authSuccess({ ip: '1.1.1.1', userAgent: 'a', username: 'u1' });
|
||||
|
||||
72
tests/unit/login-attempts-db.test.ts
Normal file
72
tests/unit/login-attempts-db.test.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { initDb } from '../../src/db/schema.ts';
|
||||
import {
|
||||
getLoginAttempt,
|
||||
recordFailure,
|
||||
resetLoginAttempts,
|
||||
} from '../../src/db/login-attempts.ts';
|
||||
|
||||
describe('login-attempts db', () => {
|
||||
let db: Database.Database;
|
||||
|
||||
beforeEach(() => {
|
||||
db = initDb(':memory:');
|
||||
});
|
||||
|
||||
it('returns undefined for an unknown username', () => {
|
||||
expect(getLoginAttempt(db, 'ghost')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('inserts a row on first failure with count=1 and no lock', () => {
|
||||
const row = recordFailure(db, 'alice', null);
|
||||
expect(row.username).toBe('alice');
|
||||
expect(row.failed_count).toBe(1);
|
||||
expect(row.last_failed_at).toBeTruthy();
|
||||
expect(row.locked_until).toBeNull();
|
||||
});
|
||||
|
||||
it('increments failed_count on subsequent failures', () => {
|
||||
recordFailure(db, 'alice', null);
|
||||
recordFailure(db, 'alice', null);
|
||||
const row = recordFailure(db, 'alice', null);
|
||||
expect(row.failed_count).toBe(3);
|
||||
});
|
||||
|
||||
it('persists locked_until when supplied', () => {
|
||||
const lockedUntil = new Date(Date.now() + 30_000).toISOString();
|
||||
const row = recordFailure(db, 'alice', lockedUntil);
|
||||
expect(row.locked_until).toBe(lockedUntil);
|
||||
});
|
||||
|
||||
it('updates locked_until on subsequent failures', () => {
|
||||
recordFailure(db, 'alice', null);
|
||||
const newLock = new Date(Date.now() + 60_000).toISOString();
|
||||
const row = recordFailure(db, 'alice', newLock);
|
||||
expect(row.failed_count).toBe(2);
|
||||
expect(row.locked_until).toBe(newLock);
|
||||
});
|
||||
|
||||
it('resetLoginAttempts deletes the row', () => {
|
||||
recordFailure(db, 'alice', null);
|
||||
resetLoginAttempts(db, 'alice');
|
||||
expect(getLoginAttempt(db, 'alice')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reset on a missing username is a no-op', () => {
|
||||
expect(() => resetLoginAttempts(db, 'ghost')).not.toThrow();
|
||||
});
|
||||
|
||||
it('tracks failures for non-existent users (no FK to users table)', () => {
|
||||
const row = recordFailure(db, 'never-existed-user', null);
|
||||
expect(row.failed_count).toBe(1);
|
||||
});
|
||||
|
||||
it('getLoginAttempt returns the stored row', () => {
|
||||
recordFailure(db, 'alice', null);
|
||||
recordFailure(db, 'alice', null);
|
||||
const row = getLoginAttempt(db, 'alice');
|
||||
expect(row?.username).toBe('alice');
|
||||
expect(row?.failed_count).toBe(2);
|
||||
});
|
||||
});
|
||||
212
tests/unit/login-handler.test.ts
Normal file
212
tests/unit/login-handler.test.ts
Normal file
@@ -0,0 +1,212 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { mkdtempSync, rmSync, readFileSync } from 'fs';
|
||||
import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import type Database from 'better-sqlite3';
|
||||
import { initDb } from '../../src/db/schema.ts';
|
||||
import { createUser } from '../../src/db/users.ts';
|
||||
import { hashPassword } from '../../src/services/auth.ts';
|
||||
import { createLogger } from '../../src/middleware/logging.ts';
|
||||
import { createLockoutService } from '../../src/services/lockout.ts';
|
||||
import { attemptLogin } from '../../src/services/login-handler.ts';
|
||||
import { _resetDummyHashForTests } from '../../src/services/dummy-hash.ts';
|
||||
import type { Config } from '../../src/config.ts';
|
||||
|
||||
function makeConfig(overrides: Partial<Config> = {}): Config {
|
||||
return {
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
jwtSecret: 'x',
|
||||
jwtExpiry: '1h',
|
||||
dbPath: ':memory:',
|
||||
uploadDir: '/tmp',
|
||||
logFile: '/tmp/x.log',
|
||||
maxFileSize: 0,
|
||||
baseUrl: '',
|
||||
cookieSecure: false,
|
||||
trustProxy: false,
|
||||
lockoutThreshold: 2,
|
||||
lockoutBaseSeconds: 60,
|
||||
lockoutMaxSeconds: 600,
|
||||
loginMinResponseMs: 50,
|
||||
loginRateLimitMax: 0,
|
||||
loginRateLimitWindowSeconds: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('login handler', () => {
|
||||
let db: Database.Database;
|
||||
let logDir: string;
|
||||
let logFile: string;
|
||||
let config: Config;
|
||||
|
||||
beforeEach(async () => {
|
||||
_resetDummyHashForTests();
|
||||
db = initDb(':memory:');
|
||||
logDir = mkdtempSync(join(tmpdir(), 'nanodrop-handler-'));
|
||||
logFile = join(logDir, 'test.log');
|
||||
config = makeConfig({ logFile });
|
||||
const passwordHash = await hashPassword('correct-pw');
|
||||
createUser(db, { username: 'alice', passwordHash });
|
||||
// Warm dummy hash so timing assertions don't include the first cold compute.
|
||||
const { verifyAgainstDummy } = await import('../../src/services/dummy-hash.ts');
|
||||
await verifyAgainstDummy('warmup');
|
||||
});
|
||||
|
||||
function buildDeps() {
|
||||
const logger = createLogger(logFile);
|
||||
const lockout = createLockoutService({ db, config });
|
||||
return { db, config, logger, lockout };
|
||||
}
|
||||
|
||||
it('returns success for valid credentials and resets lockout', async () => {
|
||||
const deps = buildDeps();
|
||||
const result = await attemptLogin(deps, {
|
||||
username: 'alice',
|
||||
password: 'correct-pw',
|
||||
ip: '1.1.1.1',
|
||||
userAgent: 'ua',
|
||||
});
|
||||
expect(result.kind).toBe('success');
|
||||
if (result.kind === 'success') {
|
||||
expect(result.user.username).toBe('alice');
|
||||
}
|
||||
const log = readFileSync(logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_SUCCESS/);
|
||||
});
|
||||
|
||||
it('returns bad_credentials and logs failure on wrong password', async () => {
|
||||
const deps = buildDeps();
|
||||
const result = await attemptLogin(deps, {
|
||||
username: 'alice',
|
||||
password: 'wrong',
|
||||
ip: '1.1.1.1',
|
||||
userAgent: 'ua',
|
||||
});
|
||||
expect(result.kind).toBe('bad_credentials');
|
||||
const log = readFileSync(logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_FAILURE/);
|
||||
expect(log).toMatch(/username="alice"/);
|
||||
});
|
||||
|
||||
it('returns bad_credentials for unknown user (still runs bcrypt against dummy)', async () => {
|
||||
const deps = buildDeps();
|
||||
const start = Date.now();
|
||||
const result = await attemptLogin(deps, {
|
||||
username: 'ghost',
|
||||
password: 'whatever',
|
||||
ip: '1.1.1.1',
|
||||
userAgent: 'ua',
|
||||
});
|
||||
const elapsed = Date.now() - start;
|
||||
expect(result.kind).toBe('bad_credentials');
|
||||
// Must spend bcrypt-comparable time even for unknown user.
|
||||
expect(elapsed).toBeGreaterThan(20);
|
||||
const log = readFileSync(logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_FAILURE/);
|
||||
expect(log).toMatch(/username="ghost"/);
|
||||
}, 10_000);
|
||||
|
||||
it('canonicalizes username (lowercase + trim) before lookup and lockout', async () => {
|
||||
const deps = buildDeps();
|
||||
const result = await attemptLogin(deps, {
|
||||
username: ' ALICE ',
|
||||
password: 'correct-pw',
|
||||
ip: '1.1.1.1',
|
||||
userAgent: 'ua',
|
||||
});
|
||||
expect(result.kind).toBe('success');
|
||||
});
|
||||
|
||||
it('returns bad_request when username or password is empty', async () => {
|
||||
const deps = buildDeps();
|
||||
const r1 = await attemptLogin(deps, { username: '', password: 'x', ip: '1', userAgent: 'ua' });
|
||||
expect(r1.kind).toBe('bad_request');
|
||||
const r2 = await attemptLogin(deps, { username: 'alice', password: '', ip: '1', userAgent: 'ua' });
|
||||
expect(r2.kind).toBe('bad_request');
|
||||
});
|
||||
|
||||
it('triggers lockout at threshold and logs AUTH_LOCKOUT_TRIGGERED', async () => {
|
||||
const deps = buildDeps();
|
||||
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
|
||||
const second = await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
|
||||
expect(second.kind).toBe('bad_credentials');
|
||||
const log = readFileSync(logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_LOCKOUT_TRIGGERED/);
|
||||
expect(log).toMatch(/duration_seconds=60/);
|
||||
});
|
||||
|
||||
it('returns locked + retry-after on subsequent attempt; correct password still rejected', async () => {
|
||||
const deps = buildDeps();
|
||||
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
|
||||
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
|
||||
|
||||
const blocked = await attemptLogin(deps, {
|
||||
username: 'alice',
|
||||
password: 'correct-pw',
|
||||
ip: '1.1.1.1',
|
||||
userAgent: 'ua',
|
||||
});
|
||||
expect(blocked.kind).toBe('locked');
|
||||
if (blocked.kind === 'locked') {
|
||||
expect(blocked.retryAfterSeconds).toBeGreaterThan(0);
|
||||
expect(blocked.retryAfterSeconds).toBeLessThanOrEqual(60);
|
||||
}
|
||||
|
||||
const log = readFileSync(logFile, 'utf-8');
|
||||
expect(log).toMatch(/AUTH_LOCKED_ATTEMPT/);
|
||||
// Even though password was correct, no AUTH_SUCCESS for this attempt.
|
||||
const successCount = (log.match(/AUTH_SUCCESS/g) ?? []).length;
|
||||
expect(successCount).toBe(0);
|
||||
});
|
||||
|
||||
it('does NOT call bcrypt when account is locked (short-circuits)', async () => {
|
||||
const deps = buildDeps();
|
||||
// Lock the account.
|
||||
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
|
||||
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
|
||||
|
||||
// Locked attempt with constant-time clamp at 50ms — should be roughly clamp duration,
|
||||
// not bcrypt time (250ms+).
|
||||
const start = Date.now();
|
||||
await attemptLogin(deps, { username: 'alice', password: 'correct-pw', ip: '1', userAgent: 'ua' });
|
||||
const elapsed = Date.now() - start;
|
||||
// Clamp is 50ms; allow generous slack but assert well under bcrypt cost.
|
||||
expect(elapsed).toBeLessThan(150);
|
||||
});
|
||||
|
||||
it('respects loginMinResponseMs clamp on bad_credentials', async () => {
|
||||
config = makeConfig({ logFile, loginMinResponseMs: 200 });
|
||||
const deps = buildDeps();
|
||||
const start = Date.now();
|
||||
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
|
||||
const elapsed = Date.now() - start;
|
||||
expect(elapsed).toBeGreaterThanOrEqual(190);
|
||||
}, 10_000);
|
||||
|
||||
it('successful login between failures resets the counter', async () => {
|
||||
const deps = buildDeps();
|
||||
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
|
||||
await attemptLogin(deps, { username: 'alice', password: 'correct-pw', ip: '1', userAgent: 'ua' });
|
||||
const r = await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
|
||||
// After reset, this is failure #1 — well under threshold of 2, so no lock yet.
|
||||
expect(r.kind).toBe('bad_credentials');
|
||||
// No AUTH_LOCKOUT_TRIGGERED in log.
|
||||
const log = readFileSync(logFile, 'utf-8');
|
||||
expect(log).not.toMatch(/AUTH_LOCKOUT_TRIGGERED/);
|
||||
});
|
||||
|
||||
it('unknown username also accumulates lockout', async () => {
|
||||
const deps = buildDeps();
|
||||
await attemptLogin(deps, { username: 'ghost', password: 'x', ip: '1', userAgent: 'ua' });
|
||||
await attemptLogin(deps, { username: 'ghost', password: 'x', ip: '1', userAgent: 'ua' });
|
||||
const r = await attemptLogin(deps, { username: 'ghost', password: 'x', ip: '1', userAgent: 'ua' });
|
||||
expect(r.kind).toBe('locked');
|
||||
}, 10_000);
|
||||
|
||||
// Cleanup
|
||||
beforeEach(() => {
|
||||
return () => rmSync(logDir, { recursive: true, force: true });
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user