Compare commits
18 Commits
chore/depe
...
bee3cd2e98
| Author | SHA1 | Date | |
|---|---|---|---|
| bee3cd2e98 | |||
| 512300f475 | |||
| aed9931e14 | |||
| 3b3a56cd94 | |||
| cbc22dcac4 | |||
| a4355e1ef3 | |||
| 0f0c2f0e96 | |||
| 623a3374cf | |||
| 86870db726 | |||
| 42a9530ed0 | |||
| d9592100cc | |||
| 49eeb1cc49 | |||
| c6aa030e54 | |||
| bbd292c085 | |||
| ad36b23061 | |||
| 11e87f353d | |||
| f4eaf88495 | |||
| d30f40ca71 |
@@ -1,7 +1,6 @@
|
||||
PORT=3000
|
||||
HOST=0.0.0.0
|
||||
JWT_SECRET=change-me-to-a-long-random-secret
|
||||
JWT_EXPIRY=7d
|
||||
DB_PATH=./data/nanodrop.db
|
||||
UPLOAD_DIR=./data/uploads
|
||||
LOG_FILE=./data/nanodrop.log
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
name: "Deploy to Homelab"
|
||||
name: "Deploy to birb co. production"
|
||||
|
||||
on:
|
||||
push:
|
||||
@@ -14,6 +14,15 @@ jobs:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Validate required secrets
|
||||
run: |
|
||||
set -euo pipefail
|
||||
: "${SSH_PRIVATE_KEY:?SSH_PRIVATE_KEY secret must be set}"
|
||||
: "${JWT_SECRET:?JWT_SECRET secret must be set}"
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
JWT_SECRET: ${{ secrets.JWT_SECRET }}
|
||||
|
||||
- name: Set up SSH key
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
@@ -34,15 +43,14 @@ jobs:
|
||||
|
||||
- name: Deploy on server with Docker
|
||||
run: |
|
||||
ssh -i ~/.ssh/id_ed25519 ${{ vars.USERNAME }}@${{ vars.HOST }} << 'EOF'
|
||||
ssh -i ~/.ssh/id_ed25519 ${{ vars.USERNAME }}@${{ vars.HOST }} << EOF
|
||||
cd ~/${{ vars.DIRECTORY_NAME }}
|
||||
export JWT_SECRET='${{ secrets.JWT_SECRET }}'
|
||||
export TRUST_PROXY=true
|
||||
export COOKIE_SECURE=true
|
||||
export JWT_SECRET=${{ secrets.JWT_SECRET }}
|
||||
export PORT=${{ vars.PORT }}
|
||||
export BASE_URL=${{ vars.BASE_URL }}
|
||||
export MAX_FILE_SIZE=${{ vars.MAX_FILE_SIZE }}
|
||||
docker compose -f docker-compose.yml down
|
||||
docker compose -f docker-compose.yml up -d --build
|
||||
export PORT='${{ vars.PORT }}'
|
||||
export BASE_URL='${{ vars.BASE_URL }}'
|
||||
export MAX_FILE_SIZE='${{ vars.MAX_FILE_SIZE }}'
|
||||
docker compose -f compose.yaml down
|
||||
docker compose -f compose.yaml up -d --build
|
||||
EOF
|
||||
|
||||
@@ -60,7 +60,6 @@ docker compose run --rm register-user --username alice --password secret
|
||||
| Variable | Default | Description |
|
||||
|---|---|---|
|
||||
| `JWT_SECRET` | *(required)* | Secret key for signing JWTs |
|
||||
| `JWT_EXPIRY` | `7d` | JWT token lifetime |
|
||||
| `PORT` | `3000` | Port to listen on |
|
||||
| `HOST` | `0.0.0.0` | Host to bind |
|
||||
| `BASE_URL` | `http://localhost:3000` | Public base URL (used in share links) |
|
||||
@@ -71,6 +70,8 @@ docker compose run --rm register-user --username alice --password secret
|
||||
| `COOKIE_SECURE` | `false` | Set `true` when serving over HTTPS |
|
||||
| `TRUST_PROXY` | `false` | Set `true` when behind a reverse proxy |
|
||||
|
||||
Session lifetime is family-pinned to 30 days with sliding renewal (see `src/constants.ts`). Not configurable per deployment.
|
||||
|
||||
### Reverse proxy
|
||||
|
||||
Set `TRUST_PROXY=true` when running behind a reverse proxy so Nanodrop sees the real client IP in logs.
|
||||
@@ -143,7 +144,7 @@ bantime = 600
|
||||
Adjust `logpath` to wherever your `LOG_FILE` is. With Docker, the log file lives inside the `nanodrop-data` volume — mount it to a host path or bind-mount a host directory instead of the named volume to make it accessible to fail2ban:
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml override
|
||||
# compose.yaml override
|
||||
volumes:
|
||||
- /var/lib/nanodrop:/app/data
|
||||
```
|
||||
|
||||
@@ -2,7 +2,6 @@ x-env: &env
|
||||
PORT: "${PORT:-3000}"
|
||||
HOST: "${HOST:-0.0.0.0}"
|
||||
JWT_SECRET: "${JWT_SECRET}"
|
||||
JWT_EXPIRY: "${JWT_EXPIRY:-7d}"
|
||||
DB_PATH: "${DB_PATH:-./data/nanodrop.db}"
|
||||
UPLOAD_DIR: "${UPLOAD_DIR:-./data/uploads}"
|
||||
LOG_FILE: "${LOG_FILE:-./data/nanodrop.log}"
|
||||
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;
|
||||
@@ -309,10 +310,16 @@ h1 + p {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
border: var(--border);
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
min-width: 100%;
|
||||
border-collapse: collapse;
|
||||
border: var(--border);
|
||||
}
|
||||
|
||||
th {
|
||||
|
||||
@@ -2,7 +2,6 @@ export interface Config {
|
||||
port: number;
|
||||
host: string;
|
||||
jwtSecret: string;
|
||||
jwtExpiry: string;
|
||||
dbPath: string;
|
||||
uploadDir: string;
|
||||
logFile: string;
|
||||
@@ -10,6 +9,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 {
|
||||
@@ -22,7 +27,6 @@ export function loadConfig(): Config {
|
||||
port: parseInt(process.env.PORT ?? '3000', 10),
|
||||
host: process.env.HOST ?? '0.0.0.0',
|
||||
jwtSecret,
|
||||
jwtExpiry: process.env.JWT_EXPIRY ?? '7d',
|
||||
dbPath: process.env.DB_PATH ?? './data/nanodrop.db',
|
||||
uploadDir: process.env.UPLOAD_DIR ?? './data/uploads',
|
||||
logFile: process.env.LOG_FILE ?? './data/nanodrop.log',
|
||||
@@ -30,5 +34,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),
|
||||
};
|
||||
}
|
||||
|
||||
8
src/constants.ts
Normal file
8
src/constants.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
// Family-wide session policy. Used by every bchen.dev app's session cookie.
|
||||
// DO NOT diverge per-app — coherence across apps is a feature.
|
||||
|
||||
export const SESSION_TTL_DAYS = 30;
|
||||
export const SESSION_TTL_SECONDS = SESSION_TTL_DAYS * 24 * 60 * 60;
|
||||
export const SESSION_RENEW_THRESHOLD_SECONDS = 60 * 60;
|
||||
export const SESSION_COOKIE_NAME = 'nanodrop_session';
|
||||
export const LOGOUT_PATHS = new Set<string>(['/logout', '/api/v1/auth/logout']);
|
||||
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;
|
||||
|
||||
@@ -1,24 +1,47 @@
|
||||
import type { FastifyRequest, FastifyReply } from 'fastify';
|
||||
import type { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify';
|
||||
import type { Config } from '../config.ts';
|
||||
import type { JwtPayload } from '../types.ts';
|
||||
import { SESSION_COOKIE_NAME, SESSION_TTL_SECONDS } from '../constants.ts';
|
||||
import { slideSessionIfNeeded } from './session-renewal.ts';
|
||||
|
||||
export async function requireAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch {
|
||||
// API routes get 401, page routes get redirect
|
||||
const isApi = request.url.startsWith('/api/');
|
||||
if (isApi) {
|
||||
reply.status(401).send({ error: 'Unauthorized' });
|
||||
} else {
|
||||
reply.redirect('/');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function tokenCookieOptions(secure: boolean): {
|
||||
export function sessionCookieOptions(secure: boolean): {
|
||||
httpOnly: boolean;
|
||||
sameSite: 'strict';
|
||||
secure: boolean;
|
||||
path: string;
|
||||
maxAge: number;
|
||||
} {
|
||||
return { httpOnly: true, sameSite: 'strict', secure, path: '/' };
|
||||
return {
|
||||
httpOnly: true,
|
||||
sameSite: 'strict',
|
||||
secure,
|
||||
path: '/',
|
||||
maxAge: SESSION_TTL_SECONDS,
|
||||
};
|
||||
}
|
||||
|
||||
export function issueSessionCookie(
|
||||
reply: FastifyReply,
|
||||
server: FastifyInstance,
|
||||
claims: JwtPayload,
|
||||
cookieSecure: boolean,
|
||||
): void {
|
||||
const token = server.jwt.sign(claims, { expiresIn: SESSION_TTL_SECONDS });
|
||||
reply.setCookie(SESSION_COOKIE_NAME, token, sessionCookieOptions(cookieSecure));
|
||||
}
|
||||
|
||||
export function makeRequireAuth(config: Config) {
|
||||
return async function requireAuth(request: FastifyRequest, reply: FastifyReply): Promise<void> {
|
||||
try {
|
||||
const payload = await request.jwtVerify<JwtPayload>();
|
||||
slideSessionIfNeeded(request, reply, payload, request.server, config.cookieSecure);
|
||||
} catch {
|
||||
const isApi = request.url.startsWith('/api/');
|
||||
if (isApi) {
|
||||
reply.status(401).send({ error: 'Unauthorized' });
|
||||
} else {
|
||||
reply.redirect('/');
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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}"`),
|
||||
};
|
||||
|
||||
27
src/middleware/session-renewal.ts
Normal file
27
src/middleware/session-renewal.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { FastifyRequest, FastifyReply, FastifyInstance } from 'fastify';
|
||||
import type { JwtPayload } from '../types.ts';
|
||||
import { LOGOUT_PATHS, SESSION_RENEW_THRESHOLD_SECONDS } from '../constants.ts';
|
||||
import { issueSessionCookie } from './auth.ts';
|
||||
|
||||
// Family pattern includes an mfa-pending early-return; nanodrop has no MFA, so this is N/A.
|
||||
export function slideSessionIfNeeded(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
payload: JwtPayload,
|
||||
server: FastifyInstance,
|
||||
cookieSecure: boolean,
|
||||
): void {
|
||||
const path = request.url.split('?', 1)[0];
|
||||
if (LOGOUT_PATHS.has(path)) return;
|
||||
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const iat = payload.iat ?? 0;
|
||||
if (nowSec - iat < SESSION_RENEW_THRESHOLD_SECONDS) return;
|
||||
|
||||
issueSessionCookie(
|
||||
reply,
|
||||
server,
|
||||
{ sub: payload.sub, username: payload.username },
|
||||
cookieSecure,
|
||||
);
|
||||
}
|
||||
@@ -2,14 +2,16 @@ 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 { requireAuth, tokenCookieOptions } from '../../../middleware/auth.ts';
|
||||
import type { LockoutService } from '../../../services/lockout.ts';
|
||||
import { attemptLogin } from '../../../services/login-handler.ts';
|
||||
import { makeRequireAuth, issueSessionCookie } from '../../../middleware/auth.ts';
|
||||
import { SESSION_COOKIE_NAME } from '../../../constants.ts';
|
||||
|
||||
interface Deps {
|
||||
db: Database.Database;
|
||||
config: Config;
|
||||
logger: Logger;
|
||||
lockout: LockoutService;
|
||||
}
|
||||
|
||||
interface LoginBody {
|
||||
@@ -18,32 +20,55 @@ interface LoginBody {
|
||||
}
|
||||
|
||||
export const authApiRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
|
||||
const { db, config, logger } = deps;
|
||||
const { config } = deps;
|
||||
const requireAuth = makeRequireAuth(config);
|
||||
|
||||
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 });
|
||||
});
|
||||
issueSessionCookie(
|
||||
reply,
|
||||
app,
|
||||
{ sub: result.user.id, username: result.user.username },
|
||||
config.cookieSecure,
|
||||
);
|
||||
reply.send({ ok: true });
|
||||
},
|
||||
);
|
||||
|
||||
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
|
||||
reply.clearCookie('token', { path: '/' }).send({ ok: true });
|
||||
reply.clearCookie(SESSION_COOKIE_NAME, { path: '/' }).send({ ok: true });
|
||||
});
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { Logger } from '../../../middleware/logging.ts';
|
||||
import type { JwtPayload } from '../../../types.ts';
|
||||
import { createFile, getFilesByUserId, getFileById, deleteFile } from '../../../db/files.ts';
|
||||
import { saveFile, deleteStoredFile } from '../../../services/storage.ts';
|
||||
import { requireAuth } from '../../../middleware/auth.ts';
|
||||
import { makeRequireAuth } from '../../../middleware/auth.ts';
|
||||
|
||||
interface Deps {
|
||||
db: Database.Database;
|
||||
@@ -17,6 +17,7 @@ interface Deps {
|
||||
|
||||
export const filesApiRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
|
||||
const { db, config } = deps;
|
||||
const requireAuth = makeRequireAuth(config);
|
||||
|
||||
app.get('/', { preHandler: requireAuth }, async (request, reply) => {
|
||||
const { sub: userId } = request.user as JwtPayload;
|
||||
|
||||
@@ -6,11 +6,12 @@ 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 { requireAuth, tokenCookieOptions } from '../middleware/auth.ts';
|
||||
import { attemptLogin } from '../services/login-handler.ts';
|
||||
import { makeRequireAuth, issueSessionCookie } from '../middleware/auth.ts';
|
||||
import { SESSION_COOKIE_NAME } from '../constants.ts';
|
||||
import { loginPage } from '../views/login.ts';
|
||||
import { uploadPage, uploadResultPage } from '../views/upload.ts';
|
||||
import { fileListPage } from '../views/file-list.ts';
|
||||
@@ -21,6 +22,7 @@ interface Deps {
|
||||
db: Database.Database;
|
||||
config: Config;
|
||||
logger: Logger;
|
||||
lockout: LockoutService;
|
||||
}
|
||||
|
||||
function parseRangeHeader(header: string, fileSize: number): { start: number; end: number } | null {
|
||||
@@ -48,8 +50,16 @@ function parseRangeHeader(header: string, fileSize: number): { start: number; en
|
||||
|
||||
export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
|
||||
const { db, config, logger } = deps;
|
||||
const requireAuth = makeRequireAuth(config);
|
||||
const loginRateLimit = {
|
||||
rateLimit: {
|
||||
max: config.loginRateLimitMax,
|
||||
timeWindow: config.loginRateLimitWindowSeconds * 1000,
|
||||
},
|
||||
};
|
||||
|
||||
// GET / — login page or redirect if authed
|
||||
// opportunistic auth — does not slide the session; see middleware/session-renewal.ts
|
||||
app.get('/', async (request, reply) => {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
@@ -60,28 +70,43 @@ 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');
|
||||
});
|
||||
issueSessionCookie(
|
||||
reply,
|
||||
app,
|
||||
{ sub: result.user.id, username: result.user.username },
|
||||
config.cookieSecure,
|
||||
);
|
||||
reply.redirect('/upload');
|
||||
},
|
||||
);
|
||||
|
||||
// POST /logout
|
||||
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
|
||||
reply.clearCookie('token', { path: '/' }).redirect('/');
|
||||
reply.clearCookie(SESSION_COOKIE_NAME, { path: '/' }).redirect('/');
|
||||
});
|
||||
|
||||
// GET /upload
|
||||
@@ -143,6 +168,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
|
||||
});
|
||||
|
||||
// GET /f/:id — public file view (owner-aware)
|
||||
// opportunistic auth — does not slide the session; see middleware/session-renewal.ts
|
||||
app.get<{ Params: { id: string } }>('/f/:id', async (request, reply) => {
|
||||
const { id } = request.params;
|
||||
|
||||
|
||||
@@ -4,11 +4,14 @@ 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 { SESSION_COOKIE_NAME } from './constants.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,11 +26,12 @@ 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, {
|
||||
secret: config.jwtSecret,
|
||||
cookie: { cookieName: 'token', signed: false },
|
||||
cookie: { cookieName: SESSION_COOKIE_NAME, signed: false },
|
||||
});
|
||||
app.register(fastifyFormbody);
|
||||
app.register(fastifyMultipart, { limits: { fileSize: config.maxFileSize } });
|
||||
@@ -35,8 +39,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' };
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
export interface JwtPayload {
|
||||
sub: number;
|
||||
username: string;
|
||||
iat?: number;
|
||||
}
|
||||
|
||||
@@ -24,14 +24,16 @@ export function fileListPage(files: FileRow[], baseUrl: string): string {
|
||||
return layout('My files', `
|
||||
<h1>My files</h1>
|
||||
<p><a href="/upload">Upload new file</a></p>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th><th>Type</th><th>Size</th><th>Uploaded</th><th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rows}</tbody>
|
||||
</table>
|
||||
<div class="table-wrap">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th><th>Type</th><th>Size</th><th>Uploaded</th><th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>${rows}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`, { authed: true });
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { tmpdir } from 'os';
|
||||
import { join } from 'path';
|
||||
import { initDb } from '../../src/db/schema.ts';
|
||||
import { createServer } from '../../src/server.ts';
|
||||
import { SESSION_COOKIE_NAME } from '../../src/constants.ts';
|
||||
import type { Config } from '../../src/config.ts';
|
||||
import type Database from 'better-sqlite3';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
@@ -15,7 +16,7 @@ export async function loginAs(app: FastifyInstance, username: string, password:
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
const cookie = res.headers['set-cookie'] as string;
|
||||
return cookie.split(';')[0].replace('token=', '');
|
||||
return cookie.split(';')[0].replace(`${SESSION_COOKIE_NAME}=`, '');
|
||||
}
|
||||
|
||||
interface MultipartFile {
|
||||
@@ -53,7 +54,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');
|
||||
@@ -66,7 +67,6 @@ export function createTestApp(): TestContext {
|
||||
port: 0,
|
||||
host: '127.0.0.1',
|
||||
jwtSecret: 'test-secret-key',
|
||||
jwtExpiry: '1h',
|
||||
dbPath: ':memory:',
|
||||
uploadDir,
|
||||
logFile,
|
||||
@@ -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 });
|
||||
|
||||
@@ -26,7 +26,8 @@ describe('POST /api/v1/auth/login', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json()).toEqual({ ok: true });
|
||||
expect(res.headers['set-cookie']).toMatch(/token=/);
|
||||
expect(res.headers['set-cookie']).toMatch(/nanodrop_session=/);
|
||||
expect(res.headers['set-cookie']).toMatch(/Max-Age=2592000/);
|
||||
});
|
||||
|
||||
it('returns 401 on wrong password', async () => {
|
||||
@@ -76,7 +77,7 @@ describe('POST /api/v1/auth/logout', () => {
|
||||
body: JSON.stringify({ username: 'alice', password: 'secret' }),
|
||||
});
|
||||
const cookie = res.headers['set-cookie'] as string;
|
||||
token = cookie.split(';')[0].replace('token=', '');
|
||||
token = cookie.split(';')[0].replace('nanodrop_session=', '');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -88,10 +89,10 @@ describe('POST /api/v1/auth/logout', () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/auth/logout',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['set-cookie']).toMatch(/token=;/);
|
||||
expect(res.headers['set-cookie']).toMatch(/nanodrop_session=;/);
|
||||
});
|
||||
|
||||
it('returns 401 without cookie', async () => {
|
||||
|
||||
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('nanodrop_session=', '');
|
||||
|
||||
// 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: { nanodrop_session: cookie },
|
||||
});
|
||||
expect(r.statusCode).toBe(200);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -23,7 +23,7 @@ describe('GET /api/v1/files', () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/files',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.json().files).toEqual([]);
|
||||
@@ -55,7 +55,7 @@ describe('POST /api/v1/files', () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/files',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
...buildMultipart({ file: { filename: 'test.txt', contentType: 'text/plain', data: Buffer.from('hello') } }),
|
||||
});
|
||||
expect(res.statusCode).toBe(201);
|
||||
@@ -84,7 +84,7 @@ describe('DELETE /api/v1/files/:id', () => {
|
||||
const uploadRes = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/files',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
...buildMultipart({ file: { filename: 'f.txt', contentType: 'text/plain', data: Buffer.from('data') } }),
|
||||
});
|
||||
fileId = uploadRes.json().file.id;
|
||||
@@ -99,7 +99,7 @@ describe('DELETE /api/v1/files/:id', () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/api/v1/files/${fileId}`,
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
});
|
||||
@@ -108,7 +108,7 @@ describe('DELETE /api/v1/files/:id', () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'DELETE',
|
||||
url: '/api/v1/files/doesnotexist',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(404);
|
||||
});
|
||||
|
||||
@@ -25,7 +25,7 @@ describe('GET /', () => {
|
||||
|
||||
it('redirects to /upload when authenticated', async () => {
|
||||
const token = await loginAs(ctx.app, 'alice', 'secret');
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/', cookies: { token } });
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/', cookies: { nanodrop_session: token } });
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers['location']).toBe('/upload');
|
||||
});
|
||||
@@ -46,7 +46,7 @@ describe('POST /login (page)', () => {
|
||||
});
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers['location']).toBe('/upload');
|
||||
expect(res.headers['set-cookie']).toMatch(/token=/);
|
||||
expect(res.headers['set-cookie']).toMatch(/nanodrop_session=/);
|
||||
});
|
||||
|
||||
it('shows login page with error on invalid credentials', async () => {
|
||||
@@ -72,7 +72,7 @@ describe('GET /upload + POST /upload', () => {
|
||||
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
|
||||
|
||||
it('shows upload form', async () => {
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/upload', cookies: { token } });
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/upload', cookies: { nanodrop_session: token } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toContain('Upload');
|
||||
});
|
||||
@@ -87,7 +87,7 @@ describe('GET /upload + POST /upload', () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/upload',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
...buildMultipart({ file: { filename: 'doc.txt', contentType: 'text/plain', data: Buffer.from('content') } }),
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
@@ -106,7 +106,7 @@ describe('GET /f/:id and GET /f/:id/raw', () => {
|
||||
const uploadRes = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/upload',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
...buildMultipart({ file: { filename: 'hello.txt', contentType: 'text/plain', data: Buffer.from('hello!') } }),
|
||||
});
|
||||
// Extract file id from response body
|
||||
@@ -188,7 +188,7 @@ describe('GET /f/:id — image inline', () => {
|
||||
const uploadRes = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/upload',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
...buildMultipart({ file: { filename: 'photo.png', contentType: 'image/png', data: Buffer.from('fakepng') } }),
|
||||
});
|
||||
const match = uploadRes.body.match(/\/f\/([^/"]+)/);
|
||||
@@ -213,16 +213,17 @@ describe('GET /files — copy link', () => {
|
||||
await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/upload',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
...buildMultipart({ file: { filename: 'test.txt', contentType: 'text/plain', data: Buffer.from('hi') } }),
|
||||
});
|
||||
});
|
||||
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
|
||||
|
||||
it('shows Copy link button for each file', async () => {
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/files', cookies: { token } });
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/files', cookies: { nanodrop_session: token } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toContain('Copy link');
|
||||
expect(res.body).toContain('class="table-wrap"');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -244,7 +245,7 @@ describe('GET /f/:id — owner-aware header', () => {
|
||||
const uploadRes = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/upload',
|
||||
cookies: { token: aliceToken },
|
||||
cookies: { nanodrop_session: aliceToken },
|
||||
...buildMultipart({ file: { filename: 'owned.txt', contentType: 'text/plain', data: Buffer.from('data') } }),
|
||||
});
|
||||
const match = uploadRes.body.match(/\/f\/([^/"]+)/);
|
||||
@@ -253,19 +254,19 @@ describe('GET /f/:id — owner-aware header', () => {
|
||||
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
|
||||
|
||||
it('shows nav when owner views their file', async () => {
|
||||
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}`, cookies: { token: aliceToken } });
|
||||
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}`, cookies: { nanodrop_session: aliceToken } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toContain('My Files');
|
||||
});
|
||||
|
||||
it('shows delete button when owner views', async () => {
|
||||
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}`, cookies: { token: aliceToken } });
|
||||
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}`, cookies: { nanodrop_session: aliceToken } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).toContain('delete');
|
||||
});
|
||||
|
||||
it('no header when non-owner views', async () => {
|
||||
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}`, cookies: { token: bobToken } });
|
||||
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}`, cookies: { nanodrop_session: bobToken } });
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.body).not.toContain('<header');
|
||||
});
|
||||
@@ -288,7 +289,7 @@ describe('POST /files/:id/delete', () => {
|
||||
const uploadRes = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/upload',
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
...buildMultipart({ file: { filename: 'del.txt', contentType: 'text/plain', data: Buffer.from('bye') } }),
|
||||
});
|
||||
const match = uploadRes.body.match(/\/f\/([^/"]+)/);
|
||||
@@ -300,7 +301,7 @@ describe('POST /files/:id/delete', () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: `/files/${fileId}/delete`,
|
||||
cookies: { token },
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(302);
|
||||
expect(res.headers['location']).toBe('/files');
|
||||
|
||||
100
tests/integration/session-persistence.test.ts
Normal file
100
tests/integration/session-persistence.test.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { createTestApp, type TestContext, loginAs } from '../helpers/setup.ts';
|
||||
import { createUser } from '../../src/db/users.ts';
|
||||
import { hashPassword } from '../../src/services/auth.ts';
|
||||
|
||||
describe('session persistence (sliding renewal)', () => {
|
||||
let ctx: TestContext;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
|
||||
|
||||
ctx = createTestApp();
|
||||
const hash = await hashPassword('secret');
|
||||
createUser(ctx.db, { username: 'alice', passwordHash: hash });
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await ctx.app.close();
|
||||
ctx.cleanup();
|
||||
});
|
||||
|
||||
it('login response includes Set-Cookie with Max-Age=2592000', async () => {
|
||||
const res = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/auth/login',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ username: 'alice', password: 'secret' }),
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['set-cookie']).toMatch(/nanodrop_session=/);
|
||||
expect(res.headers['set-cookie']).toMatch(/Max-Age=2592000/);
|
||||
});
|
||||
|
||||
it('request 25 days after login triggers a fresh Set-Cookie', async () => {
|
||||
const token = await loginAs(ctx.app, 'alice', 'secret');
|
||||
vi.setSystemTime(new Date('2026-01-26T00:00:00Z')); // +25 days
|
||||
|
||||
const res = await ctx.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/files',
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['set-cookie']).toBeTruthy();
|
||||
expect(res.headers['set-cookie']).toMatch(/nanodrop_session=/);
|
||||
expect(res.headers['set-cookie']).toMatch(/Max-Age=2592000/);
|
||||
});
|
||||
|
||||
it('request within renewal threshold does NOT include a fresh Set-Cookie', async () => {
|
||||
const token = await loginAs(ctx.app, 'alice', 'secret');
|
||||
vi.setSystemTime(new Date('2026-01-01T00:30:00Z')); // +30 minutes (under 1 hour)
|
||||
|
||||
const res = await ctx.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/files',
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
expect(res.headers['set-cookie']).toBeFalsy();
|
||||
});
|
||||
|
||||
it('logout still clears cookie even after renewal threshold has passed', async () => {
|
||||
const token = await loginAs(ctx.app, 'alice', 'secret');
|
||||
vi.setSystemTime(new Date('2026-01-01T02:00:00Z')); // +2 hours (past threshold)
|
||||
|
||||
const res = await ctx.app.inject({
|
||||
method: 'POST',
|
||||
url: '/api/v1/auth/logout',
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(200);
|
||||
const setCookie = res.headers['set-cookie'] as string | string[];
|
||||
const setCookieStr = Array.isArray(setCookie) ? setCookie.join('\n') : setCookie;
|
||||
// Cookie cleared (Max-Age=0 or empty value)
|
||||
expect(setCookieStr).toMatch(/nanodrop_session=;/);
|
||||
// No fresh session cookie issued by the renewer
|
||||
const freshIssue = /nanodrop_session=eyJ/.test(setCookieStr);
|
||||
expect(freshIssue).toBe(false);
|
||||
});
|
||||
|
||||
it('request 31 days after login is bounced (idle lapse)', async () => {
|
||||
const token = await loginAs(ctx.app, 'alice', 'secret');
|
||||
vi.setSystemTime(new Date('2026-02-01T01:00:00Z')); // +31 days, past 30-day TTL
|
||||
|
||||
const res = await ctx.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/files',
|
||||
cookies: { nanodrop_session: token },
|
||||
});
|
||||
expect(res.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it('anonymous request to /api/v1/files returns 401 with no Set-Cookie', async () => {
|
||||
const res = await ctx.app.inject({ method: 'GET', url: '/api/v1/files' });
|
||||
expect(res.statusCode).toBe(401);
|
||||
expect(res.headers['set-cookie']).toBeFalsy();
|
||||
});
|
||||
});
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,6 @@ describe('config', () => {
|
||||
process.env.JWT_SECRET = 'test-secret';
|
||||
delete process.env.PORT;
|
||||
delete process.env.HOST;
|
||||
delete process.env.JWT_EXPIRY;
|
||||
delete process.env.DB_PATH;
|
||||
delete process.env.UPLOAD_DIR;
|
||||
delete process.env.LOG_FILE;
|
||||
@@ -23,13 +22,18 @@ 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();
|
||||
|
||||
expect(config.port).toBe(3000);
|
||||
expect(config.host).toBe('0.0.0.0');
|
||||
expect(config.jwtExpiry).toBe('7d');
|
||||
expect(config.dbPath).toBe('./data/nanodrop.db');
|
||||
expect(config.uploadDir).toBe('./data/uploads');
|
||||
expect(config.logFile).toBe('./data/nanodrop.log');
|
||||
@@ -37,13 +41,18 @@ 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 () => {
|
||||
process.env.JWT_SECRET = 'my-secret';
|
||||
process.env.PORT = '4000';
|
||||
process.env.HOST = '127.0.0.1';
|
||||
process.env.JWT_EXPIRY = '1d';
|
||||
process.env.COOKIE_SECURE = 'true';
|
||||
process.env.TRUST_PROXY = 'true';
|
||||
process.env.MAX_FILE_SIZE = '52428800';
|
||||
@@ -54,12 +63,31 @@ describe('config', () => {
|
||||
expect(config.port).toBe(4000);
|
||||
expect(config.host).toBe('127.0.0.1');
|
||||
expect(config.jwtSecret).toBe('my-secret');
|
||||
expect(config.jwtExpiry).toBe('1d');
|
||||
expect(config.cookieSecure).toBe(true);
|
||||
expect(config.trustProxy).toBe(true);
|
||||
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);
|
||||
});
|
||||
126
tests/unit/lockout-service.test.ts
Normal file
126
tests/unit/lockout-service.test.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
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',
|
||||
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);
|
||||
});
|
||||
});
|
||||
211
tests/unit/login-handler.test.ts
Normal file
211
tests/unit/login-handler.test.ts
Normal file
@@ -0,0 +1,211 @@
|
||||
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',
|
||||
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 });
|
||||
});
|
||||
});
|
||||
117
tests/unit/session-renewal.test.ts
Normal file
117
tests/unit/session-renewal.test.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import Fastify, { type FastifyInstance } from 'fastify';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
import fastifyJwt from '@fastify/jwt';
|
||||
import { slideSessionIfNeeded } from '../../src/middleware/session-renewal.ts';
|
||||
import type { JwtPayload } from '../../src/types.ts';
|
||||
import {
|
||||
SESSION_COOKIE_NAME,
|
||||
SESSION_RENEW_THRESHOLD_SECONDS,
|
||||
SESSION_TTL_SECONDS,
|
||||
} from '../../src/constants.ts';
|
||||
|
||||
async function buildTestServer(): Promise<FastifyInstance> {
|
||||
const app = Fastify();
|
||||
await app.register(fastifyCookie);
|
||||
await app.register(fastifyJwt, {
|
||||
secret: 'test-secret',
|
||||
cookie: { cookieName: SESSION_COOKIE_NAME, signed: false },
|
||||
});
|
||||
await app.ready();
|
||||
return app;
|
||||
}
|
||||
|
||||
const NOW_ISO = '2026-01-01T12:00:00Z';
|
||||
const NOW_SEC = Math.floor(new Date(NOW_ISO).getTime() / 1000);
|
||||
|
||||
describe('slideSessionIfNeeded', () => {
|
||||
let app: FastifyInstance;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.useFakeTimers({ toFake: ['Date'] });
|
||||
vi.setSystemTime(new Date(NOW_ISO));
|
||||
app = await buildTestServer();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await app.close();
|
||||
});
|
||||
|
||||
function fakeReply(): { setCookieCalls: Array<{ name: string; value: string; opts: Record<string, unknown> }> } & Record<string, unknown> {
|
||||
const setCookieCalls: Array<{ name: string; value: string; opts: Record<string, unknown> }> = [];
|
||||
return {
|
||||
setCookieCalls,
|
||||
setCookie(name: string, value: string, opts: Record<string, unknown>) {
|
||||
setCookieCalls.push({ name, value, opts });
|
||||
return this;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fakeRequest(url: string): { url: string } {
|
||||
return { url };
|
||||
}
|
||||
|
||||
it('re-issues cookie when now - iat >= SESSION_RENEW_THRESHOLD_SECONDS', () => {
|
||||
const reply = fakeReply();
|
||||
const payload: JwtPayload = {
|
||||
sub: 1,
|
||||
username: 'alice',
|
||||
iat: NOW_SEC - SESSION_RENEW_THRESHOLD_SECONDS,
|
||||
};
|
||||
slideSessionIfNeeded(fakeRequest('/upload') as never, reply as never, payload, app, false);
|
||||
expect(reply.setCookieCalls.length).toBe(1);
|
||||
expect(reply.setCookieCalls[0].name).toBe(SESSION_COOKIE_NAME);
|
||||
expect(reply.setCookieCalls[0].opts.maxAge).toBe(SESSION_TTL_SECONDS);
|
||||
});
|
||||
|
||||
it('skips re-issue when now - iat < SESSION_RENEW_THRESHOLD_SECONDS', () => {
|
||||
const reply = fakeReply();
|
||||
const payload: JwtPayload = {
|
||||
sub: 1,
|
||||
username: 'alice',
|
||||
iat: NOW_SEC - (SESSION_RENEW_THRESHOLD_SECONDS - 1),
|
||||
};
|
||||
slideSessionIfNeeded(fakeRequest('/upload') as never, reply as never, payload, app, false);
|
||||
expect(reply.setCookieCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it('skips re-issue on /logout path', () => {
|
||||
const reply = fakeReply();
|
||||
const payload: JwtPayload = { sub: 1, username: 'alice', iat: 0 }; // ancient
|
||||
slideSessionIfNeeded(fakeRequest('/logout') as never, reply as never, payload, app, false);
|
||||
expect(reply.setCookieCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it('skips re-issue on /api/v1/auth/logout path', () => {
|
||||
const reply = fakeReply();
|
||||
const payload: JwtPayload = { sub: 1, username: 'alice', iat: 0 };
|
||||
slideSessionIfNeeded(fakeRequest('/api/v1/auth/logout') as never, reply as never, payload, app, false);
|
||||
expect(reply.setCookieCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it('skips re-issue when /logout has a query string', () => {
|
||||
const reply = fakeReply();
|
||||
const payload: JwtPayload = { sub: 1, username: 'alice', iat: 0 };
|
||||
slideSessionIfNeeded(fakeRequest('/logout?redirect=foo') as never, reply as never, payload, app, false);
|
||||
expect(reply.setCookieCalls.length).toBe(0);
|
||||
});
|
||||
|
||||
it('treats missing iat as 0 (forces refresh)', () => {
|
||||
const reply = fakeReply();
|
||||
const payload: JwtPayload = { sub: 1, username: 'alice' };
|
||||
slideSessionIfNeeded(fakeRequest('/upload') as never, reply as never, payload, app, false);
|
||||
expect(reply.setCookieCalls.length).toBe(1);
|
||||
});
|
||||
|
||||
it('produces a cookie carrying Max-Age=SESSION_TTL_SECONDS', () => {
|
||||
const reply = fakeReply();
|
||||
const payload: JwtPayload = { sub: 1, username: 'alice', iat: 0 };
|
||||
slideSessionIfNeeded(fakeRequest('/upload') as never, reply as never, payload, app, true);
|
||||
expect(reply.setCookieCalls[0].opts.maxAge).toBe(SESSION_TTL_SECONDS);
|
||||
expect(reply.setCookieCalls[0].opts.secure).toBe(true);
|
||||
expect(reply.setCookieCalls[0].opts.httpOnly).toBe(true);
|
||||
expect(reply.setCookieCalls[0].opts.sameSite).toBe('strict');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user