Add server, routes, views, CLI, CSS, and integration tests

- Server factory with Fastify plugins (JWT, cookie, multipart, formbody, static)
- Auth middleware: requireAuth preHandler (401 for API, redirect for pages)
- Auth API routes: POST /api/v1/auth/login, POST /api/v1/auth/logout
- File API routes: GET/POST /api/v1/files, DELETE /api/v1/files/:id
- Page routes: /, /login, /logout, /upload, /files, /files/:id/delete, /f/:id, /f/:id/raw
- HTML views: layout, login, upload, file-list, file-view, not-found
- CLI register-user script
- public/style.css dark theme
- Test helpers: createTestApp, loginAs, buildMultipart
- Integration tests for auth API, file API, and page routes (51 tests passing)
- Update CLAUDE.md with red/green TDD and commit instructions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-03 15:55:14 -08:00
parent 157d1e8230
commit 8fd1464b9d
19 changed files with 1180 additions and 1 deletions

33
src/cli/register-user.ts Normal file
View File

@@ -0,0 +1,33 @@
import { parseArgs } from 'util';
import { loadConfig } from '../config.ts';
import { initDb } from '../db/schema.ts';
import { createUser, getUserByUsername } from '../db/users.ts';
import { hashPassword } from '../services/auth.ts';
const { values } = parseArgs({
args: process.argv.slice(2),
options: {
username: { type: 'string' },
password: { type: 'string' },
},
});
const { username, password } = values;
if (!username || !password) {
console.error('Usage: npm run register-user -- --username <user> --password <pass>');
process.exit(1);
}
const config = loadConfig();
const db = initDb(config.dbPath);
const existing = getUserByUsername(db, username);
if (existing) {
console.error(`User "${username}" already exists.`);
process.exit(1);
}
const passwordHash = await hashPassword(password);
createUser(db, { username, passwordHash });
console.log(`User "${username}" created successfully.`);

19
src/index.ts Normal file
View File

@@ -0,0 +1,19 @@
import { mkdirSync } from 'fs';
import { loadConfig } from './config.ts';
import { initDb } from './db/schema.ts';
import { createServer } from './server.ts';
const config = loadConfig();
mkdirSync(config.uploadDir, { recursive: true });
const db = initDb(config.dbPath);
const app = createServer({ config, db });
try {
await app.listen({ port: config.port, host: config.host });
console.log(`Nanodrop running on http://${config.host}:${config.port}`);
} catch (err) {
console.error(err);
process.exit(1);
}

15
src/middleware/auth.ts Normal file
View File

@@ -0,0 +1,15 @@
import type { FastifyRequest, FastifyReply } from 'fastify';
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('/');
}
}
}

56
src/routes/api/v1/auth.ts Normal file
View File

@@ -0,0 +1,56 @@
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 } from '../../../middleware/auth.ts';
interface Deps {
db: Database.Database;
config: Config;
logger: Logger;
}
interface LoginBody {
username: string;
password: string;
}
export const authApiRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
const { db, config, logger } = deps;
app.post<{ Body: LoginBody }>('/login', async (request, reply) => {
const { username, password } = request.body ?? {};
const ip = request.ip;
const userAgent = request.headers['user-agent'] ?? '';
if (!username || !password) {
return reply.status(400).send({ error: 'username and password are required' });
}
const user = getUserByUsername(db, username);
const valid = user ? await verifyPassword(password, user.password_hash) : false;
if (!user || !valid) {
await logger.authFailure({ ip, userAgent, username });
return reply.status(401).send({ error: 'Invalid credentials' });
}
await logger.authSuccess({ ip, userAgent, username });
const token = app.jwt.sign({ sub: user.id, username: user.username }, { expiresIn: config.jwtExpiry });
reply
.setCookie('token', token, {
httpOnly: true,
sameSite: 'strict',
secure: config.cookieSecure,
path: '/',
})
.send({ ok: true });
});
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
reply.clearCookie('token', { path: '/' }).send({ ok: true });
});
};

View File

@@ -0,0 +1,71 @@
import type { FastifyPluginAsync } from 'fastify';
import { extname } from 'path';
import { nanoid } from 'nanoid';
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 { createFile, getFilesByUserId, getFileById, deleteFile } from '../../../db/files.ts';
import { saveFile, deleteStoredFile } from '../../../services/storage.ts';
import { requireAuth } from '../../../middleware/auth.ts';
interface Deps {
db: Database.Database;
config: Config;
logger: Logger;
}
export const filesApiRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
const { db, config } = deps;
app.get('/', { preHandler: requireAuth }, async (request, reply) => {
const { sub: userId } = request.user as JwtPayload;
const files = getFilesByUserId(db, userId);
reply.send({ files });
});
app.post('/', { preHandler: requireAuth }, async (request, reply) => {
const { sub: userId } = request.user as JwtPayload;
const data = await request.file();
if (!data) {
return reply.status(400).send({ error: 'No file uploaded' });
}
const fileBuffer = await data.toBuffer();
const id = nanoid();
const ext = extname(data.filename);
const storedName = `${id}${ext}`;
await saveFile(config.uploadDir, storedName, fileBuffer);
const file = createFile(db, {
id,
userId,
originalName: data.filename,
mimeType: data.mimetype,
size: fileBuffer.length,
storedName,
});
reply.status(201).send({ file, url: `${config.baseUrl}/f/${id}` });
});
app.delete('/:id', { preHandler: requireAuth }, async (request, reply) => {
const { sub: userId } = request.user as JwtPayload;
const { id } = request.params as { id: string };
const file = getFileById(db, id);
if (!file) {
return reply.status(404).send({ error: 'File not found' });
}
const deleted = deleteFile(db, id, userId);
if (!deleted) {
return reply.status(403).send({ error: 'Forbidden' });
}
await deleteStoredFile(config.uploadDir, file.stored_name);
reply.send({ ok: true });
});
};

163
src/routes/pages.ts Normal file
View File

@@ -0,0 +1,163 @@
import type { FastifyPluginAsync } from 'fastify';
import { extname } from 'path';
import { readFile } from 'fs/promises';
import { nanoid } from 'nanoid';
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 { createFile, getFileById, getFilesByUserId, deleteFile } from '../db/files.ts';
import { verifyPassword } from '../services/auth.ts';
import { saveFile, deleteStoredFile, getFilePath } from '../services/storage.ts';
import { requireAuth } from '../middleware/auth.ts';
import { loginPage } from '../views/login.ts';
import { uploadPage, uploadResultPage } from '../views/upload.ts';
import { fileListPage } from '../views/file-list.ts';
import { fileViewPage } from '../views/file-view.ts';
import { notFoundPage } from '../views/not-found.ts';
interface Deps {
db: Database.Database;
config: Config;
logger: Logger;
}
export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
const { db, config, logger } = deps;
// GET / — login page or redirect if authed
app.get('/', async (request, reply) => {
try {
await request.jwtVerify();
return reply.redirect('/upload');
} catch {
return reply.type('text/html').send(loginPage());
}
});
// 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'] ?? '';
const user = getUserByUsername(db, username);
const valid = user ? await verifyPassword(password, user.password_hash) : false;
if (!user || !valid) {
await logger.authFailure({ ip, userAgent, username });
return reply.type('text/html').send(loginPage({ error: 'Invalid username or password' }));
}
await logger.authSuccess({ ip, userAgent, username });
const token = app.jwt.sign({ sub: user.id, username: user.username }, { expiresIn: config.jwtExpiry });
reply
.setCookie('token', token, {
httpOnly: true,
sameSite: 'strict',
secure: config.cookieSecure,
path: '/',
})
.redirect('/upload');
});
// POST /logout
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
reply.clearCookie('token', { path: '/' }).redirect('/');
});
// GET /upload
app.get('/upload', { preHandler: requireAuth }, async (_request, reply) => {
reply.type('text/html').send(uploadPage());
});
// POST /upload
app.post('/upload', { preHandler: requireAuth }, async (request, reply) => {
const { sub: userId } = request.user as JwtPayload;
const data = await request.file();
if (!data) {
return reply.type('text/html').send(uploadPage({ error: 'No file selected' }));
}
const fileBuffer = await data.toBuffer();
const id = nanoid();
const ext = extname(data.filename);
const storedName = `${id}${ext}`;
await saveFile(config.uploadDir, storedName, fileBuffer);
createFile(db, {
id,
userId,
originalName: data.filename,
mimeType: data.mimetype,
size: fileBuffer.length,
storedName,
});
const shareUrl = `${config.baseUrl}/f/${id}`;
reply.type('text/html').send(uploadResultPage(shareUrl, data.filename));
});
// GET /files
app.get('/files', { preHandler: requireAuth }, async (request, reply) => {
const { sub: userId } = request.user as JwtPayload;
const files = getFilesByUserId(db, userId);
reply.type('text/html').send(fileListPage(files, config.baseUrl));
});
// POST /files/:id/delete
app.post<{ Params: { id: string } }>('/files/:id/delete', { preHandler: requireAuth }, async (request, reply) => {
const { sub: userId } = request.user as JwtPayload;
const { id } = request.params;
const file = getFileById(db, id);
if (file) {
const deleted = deleteFile(db, id, userId);
if (deleted) {
await deleteStoredFile(config.uploadDir, file.stored_name);
}
}
reply.redirect('/files');
});
// GET /f/:id — public file view
app.get<{ Params: { id: string } }>('/f/:id', async (request, reply) => {
const { id } = request.params;
const file = getFileById(db, id);
if (!file) {
await logger.fileNotFound({ ip: request.ip, userAgent: request.headers['user-agent'] ?? '', fileId: id });
return reply.status(404).type('text/html').send(notFoundPage());
}
reply.type('text/html').send(fileViewPage(file));
});
// GET /f/:id/raw — serve raw file
app.get<{ Params: { id: string } }>('/f/:id/raw', async (request, reply) => {
const { id } = request.params;
const file = getFileById(db, id);
if (!file) {
await logger.fileNotFound({ ip: request.ip, userAgent: request.headers['user-agent'] ?? '', fileId: id });
return reply.status(404).send({ error: 'Not found' });
}
const filePath = getFilePath(config.uploadDir, file.stored_name);
const data = await readFile(filePath);
reply
.header('Content-Type', file.mime_type)
.header('Content-Disposition', `inline; filename="${file.original_name}"`)
.send(data);
});
// 404 handler
app.setNotFoundHandler((_request, reply) => {
reply.status(404).type('text/html').send(notFoundPage());
});
};

46
src/server.ts Normal file
View File

@@ -0,0 +1,46 @@
import Fastify from 'fastify';
import fastifyCookie from '@fastify/cookie';
import fastifyJwt from '@fastify/jwt';
import fastifyMultipart from '@fastify/multipart';
import fastifyFormbody from '@fastify/formbody';
import fastifyStatic from '@fastify/static';
import { join } from 'path';
import { fileURLToPath } from 'url';
import type Database from 'better-sqlite3';
import type { Config } from './config.ts';
import { createLogger } from './middleware/logging.ts';
import { authApiRoutes } from './routes/api/v1/auth.ts';
import { filesApiRoutes } from './routes/api/v1/files.ts';
import { pageRoutes } from './routes/pages.ts';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
interface ServerDeps {
config: Config;
db: Database.Database;
}
export function createServer({ config, db }: ServerDeps) {
const app = Fastify({ logger: false, trustProxy: config.trustProxy });
const logger = createLogger(config.logFile);
app.register(fastifyCookie);
app.register(fastifyJwt, {
secret: config.jwtSecret,
cookie: { cookieName: 'token', signed: false },
});
app.register(fastifyFormbody);
app.register(fastifyMultipart, { limits: { fileSize: config.maxFileSize } });
app.register(fastifyStatic, {
root: join(__dirname, '..', 'public'),
prefix: '/public/',
});
const deps = { db, config, logger };
app.register(authApiRoutes, { prefix: '/api/v1/auth', deps });
app.register(filesApiRoutes, { prefix: '/api/v1/files', deps });
app.register(pageRoutes, { prefix: '/', deps });
return app;
}

38
src/views/file-list.ts Normal file
View File

@@ -0,0 +1,38 @@
import { layout, escHtml } from './layout.ts';
import type { FileRow } from '../db/files.ts';
export function fileListPage(files: FileRow[], baseUrl: string): string {
const rows = files.length === 0
? '<tr><td colspan="5">No files yet. <a href="/upload">Upload one.</a></td></tr>'
: files.map((f) => `
<tr>
<td><a href="/f/${escHtml(f.id)}">${escHtml(f.original_name)}</a></td>
<td>${escHtml(f.mime_type)}</td>
<td>${formatBytes(f.size)}</td>
<td>${escHtml(f.created_at)}</td>
<td>
<form method="POST" action="/files/${escHtml(f.id)}/delete" style="display:inline">
<button type="submit" class="danger">Delete</button>
</form>
</td>
</tr>`).join('');
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>
`, { authed: true });
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

27
src/views/file-view.ts Normal file
View File

@@ -0,0 +1,27 @@
import { layout, escHtml } from './layout.ts';
import type { FileRow } from '../db/files.ts';
export function fileViewPage(file: FileRow): string {
const rawUrl = escHtml(`/f/${file.id}/raw`);
const safeName = escHtml(file.original_name);
const actions = `
<div class="file-actions">
<a href="${rawUrl}" download="${safeName}" class="btn">Download</a>
<a href="${rawUrl}" target="_blank" class="btn">Open</a>
</div>`;
let media = '';
if (file.mime_type.startsWith('video/')) {
media = `<video controls src="${rawUrl}" preload="metadata"></video>`;
} else if (file.mime_type.startsWith('audio/')) {
media = `<audio controls src="${rawUrl}" preload="metadata"></audio>`;
}
return layout(file.original_name, `
<div class="file-view">
<h1>${safeName}</h1>
${media}
${actions}
</div>
`);
}

40
src/views/layout.ts Normal file
View File

@@ -0,0 +1,40 @@
export function layout(title: string, body: string, opts: { authed?: boolean } = {}): string {
const { authed = false } = opts;
const nav = authed
? `<nav>
<a href="/upload">Upload</a>
<a href="/files">My Files</a>
<form method="POST" action="/logout" style="display:inline">
<button type="submit">Logout</button>
</form>
</nav>`
: '';
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${escHtml(title)} — Nanodrop</title>
<link rel="stylesheet" href="/public/style.css">
</head>
<body>
<header>
<a href="/" class="logo">Nanodrop</a>
${nav}
</header>
<main>
${body}
</main>
</body>
</html>`;
}
export function escHtml(str: string): string {
return str
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
}

25
src/views/login.ts Normal file
View File

@@ -0,0 +1,25 @@
import { layout } from './layout.ts';
export function loginPage(opts: { error?: string } = {}): string {
const errorHtml = opts.error
? `<p class="error">${opts.error}</p>`
: '';
return layout('Login', `
<div class="form-container">
<h1>Sign in</h1>
${errorHtml}
<form method="POST" action="/login">
<label>
Username
<input type="text" name="username" required autofocus>
</label>
<label>
Password
<input type="password" name="password" required>
</label>
<button type="submit">Login</button>
</form>
</div>
`);
}

11
src/views/not-found.ts Normal file
View File

@@ -0,0 +1,11 @@
import { layout } from './layout.ts';
export function notFoundPage(): string {
return layout('Not found', `
<div class="form-container">
<h1>404 — Not found</h1>
<p>The page or file you requested does not exist.</p>
<p><a href="/">Go home</a></p>
</div>
`);
}

36
src/views/upload.ts Normal file
View File

@@ -0,0 +1,36 @@
import { layout, escHtml } from './layout.ts';
export function uploadPage(opts: { error?: string } = {}): string {
const errorHtml = opts.error ? `<p class="error">${opts.error}</p>` : '';
return layout('Upload', `
<div class="form-container">
<h1>Upload a file</h1>
${errorHtml}
<form method="POST" action="/upload" enctype="multipart/form-data">
<label>
File
<input type="file" name="file" required>
</label>
<button type="submit">Upload</button>
</form>
</div>
`, { authed: true });
}
export function uploadResultPage(shareUrl: string, filename: string): string {
const safeUrl = escHtml(shareUrl);
const safeName = escHtml(filename);
return layout('File uploaded', `
<div class="form-container">
<h1>File uploaded</h1>
<p><strong>${safeName}</strong> is ready to share.</p>
<div class="share-box">
<input type="text" id="share-url" value="${safeUrl}" readonly>
<button onclick="navigator.clipboard.writeText(document.getElementById('share-url').value)">Copy link</button>
</div>
<p><a href="/upload">Upload another</a> &middot; <a href="/files">My files</a></p>
</div>
`, { authed: true });
}