chore: replace hand-rolled layout() with @fastify/view + EJS #20

Merged
brendan merged 2 commits from chore/ejs-view-templates into main 2026-05-15 05:55:22 +00:00
17 changed files with 199 additions and 215 deletions

42
package-lock.json generated
View File

@@ -15,15 +15,18 @@
"@fastify/multipart": "^9.4.0", "@fastify/multipart": "^9.4.0",
"@fastify/rate-limit": "^10.3.0", "@fastify/rate-limit": "^10.3.0",
"@fastify/static": "^9.0.0", "@fastify/static": "^9.0.0",
"@fastify/view": "^11.1.1",
"bchen-sqlite-migrate": "git+https://gitea.bchen.dev/brendan/sqlite-migrate.git#v0.1.0", "bchen-sqlite-migrate": "git+https://gitea.bchen.dev/brendan/sqlite-migrate.git#v0.1.0",
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"better-sqlite3": "^12.6.2", "better-sqlite3": "^12.6.2",
"ejs": "^5.0.2",
"fastify": "^5.7.4", "fastify": "^5.7.4",
"nanoid": "^5.1.6" "nanoid": "^5.1.6"
}, },
"devDependencies": { "devDependencies": {
"@types/bcrypt": "^6.0.0", "@types/bcrypt": "^6.0.0",
"@types/better-sqlite3": "^7.6.13", "@types/better-sqlite3": "^7.6.13",
"@types/ejs": "^3.1.5",
"@types/node": "^25.3.3", "@types/node": "^25.3.3",
"tsx": "^4.21.0", "tsx": "^4.21.0",
"typescript": "^5.9.3", "typescript": "^5.9.3",
@@ -809,6 +812,26 @@
"glob": "^13.0.0" "glob": "^13.0.0"
} }
}, },
"node_modules/@fastify/view": {
"version": "11.1.1",
"resolved": "https://registry.npmjs.org/@fastify/view/-/view-11.1.1.tgz",
"integrity": "sha512-GiHqT3R2eKJgWmy0s45eELTC447a4+lTM2o+8fSWeKwBe9VToeePuHJcKtOEXPrKGSddGO0RsNayULiS3aeHeQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "MIT",
"dependencies": {
"fastify-plugin": "^5.0.0",
"toad-cache": "^3.7.0"
}
},
"node_modules/@jridgewell/sourcemap-codec": { "node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.5", "version": "1.5.5",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz",
@@ -1198,6 +1221,13 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/ejs": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/@types/ejs/-/ejs-3.1.5.tgz",
"integrity": "sha512-nv+GSx77ZtXiJzwKdsASqi+YQ5Z7vwHsTP0JY2SiQgjGckkBRKZnk8nIM+7oUZ1VCtuTz0+By4qVR7fqzp/Dfg==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": { "node_modules/@types/estree": {
"version": "1.0.9", "version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -1657,6 +1687,18 @@
"safe-buffer": "^5.0.1" "safe-buffer": "^5.0.1"
} }
}, },
"node_modules/ejs": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/ejs/-/ejs-5.0.2.tgz",
"integrity": "sha512-IpbUaI/CAW86l3f+T8zN0iggSc0LmMZLcIW5eRVStLVNCoTXkE0YlncbbH50fp8Cl6zHIky0sW2uUbhBqGw0Jw==",
"license": "Apache-2.0",
"bin": {
"ejs": "bin/cli.js"
},
"engines": {
"node": ">=0.12.18"
}
},
"node_modules/end-of-stream": { "node_modules/end-of-stream": {
"version": "1.4.5", "version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",

View File

@@ -23,15 +23,18 @@
"@fastify/multipart": "^9.4.0", "@fastify/multipart": "^9.4.0",
"@fastify/rate-limit": "^10.3.0", "@fastify/rate-limit": "^10.3.0",
"@fastify/static": "^9.0.0", "@fastify/static": "^9.0.0",
"@fastify/view": "^11.1.1",
"bchen-sqlite-migrate": "git+https://gitea.bchen.dev/brendan/sqlite-migrate.git#v0.1.0", "bchen-sqlite-migrate": "git+https://gitea.bchen.dev/brendan/sqlite-migrate.git#v0.1.0",
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"better-sqlite3": "^12.6.2", "better-sqlite3": "^12.6.2",
"ejs": "^5.0.2",
"fastify": "^5.7.4", "fastify": "^5.7.4",
"nanoid": "^5.1.6" "nanoid": "^5.1.6"
}, },
"devDependencies": { "devDependencies": {
"@types/bcrypt": "^6.0.0", "@types/bcrypt": "^6.0.0",
"@types/better-sqlite3": "^7.6.13", "@types/better-sqlite3": "^7.6.13",
"@types/ejs": "^3.1.5",
"@types/node": "^25.3.3", "@types/node": "^25.3.3",
"tsx": "^4.21.0", "tsx": "^4.21.0",
"typescript": "^5.9.3", "typescript": "^5.9.3",

View File

@@ -12,11 +12,12 @@ import { saveFile, deleteStoredFile, getFilePath } from '../services/storage.ts'
import { attemptLogin } from '../services/login-handler.ts'; import { attemptLogin } from '../services/login-handler.ts';
import { makeRequireAuth, issueSessionCookie } from '../middleware/auth.ts'; import { makeRequireAuth, issueSessionCookie } from '../middleware/auth.ts';
import { SESSION_COOKIE_NAME } from '../constants.ts'; import { SESSION_COOKIE_NAME } from '../constants.ts';
import { loginPage } from '../views/login.ts';
import { uploadPage, uploadResultPage } from '../views/upload.ts'; function formatBytes(bytes: number): string {
import { fileListPage } from '../views/file-list.ts'; if (bytes < 1024) return `${bytes} B`;
import { fileViewPage } from '../views/file-view.ts'; if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
import { notFoundPage } from '../views/not-found.ts'; return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
interface Deps { interface Deps {
db: Database.Database; db: Database.Database;
@@ -65,7 +66,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
await request.jwtVerify(); await request.jwtVerify();
return reply.redirect('/upload'); return reply.redirect('/upload');
} catch { } catch {
return reply.type('text/html').send(loginPage()); return reply.view('login.ejs', { title: 'Login', error: null });
} }
}); });
@@ -85,13 +86,12 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
if (result.kind === 'locked') { if (result.kind === 'locked') {
return reply return reply
.type('text/html')
.header('Retry-After', String(result.retryAfterSeconds)) .header('Retry-After', String(result.retryAfterSeconds))
.send(loginPage({ error: 'Invalid username or password' })); .view('login.ejs', { title: 'Login', error: 'Invalid username or password' });
} }
if (result.kind !== 'success') { if (result.kind !== 'success') {
return reply.type('text/html').send(loginPage({ error: 'Invalid username or password' })); return reply.view('login.ejs', { title: 'Login', error: 'Invalid username or password' });
} }
issueSessionCookie( issueSessionCookie(
@@ -111,7 +111,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
// GET /upload // GET /upload
app.get('/upload', { preHandler: requireAuth }, async (_request, reply) => { app.get('/upload', { preHandler: requireAuth }, async (_request, reply) => {
reply.type('text/html').send(uploadPage()); return reply.view('upload.ejs', { title: 'Upload', authed: true, error: null });
}); });
// POST /upload // POST /upload
@@ -120,7 +120,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
const data = await request.file(); const data = await request.file();
if (!data) { if (!data) {
return reply.type('text/html').send(uploadPage({ error: 'No file selected' })); return reply.view('upload.ejs', { title: 'Upload', authed: true, error: 'No file selected' });
} }
const fileBuffer = await data.toBuffer(); const fileBuffer = await data.toBuffer();
@@ -141,14 +141,15 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
}); });
const shareUrl = `${config.baseUrl}/f/${id}`; const shareUrl = `${config.baseUrl}/f/${id}`;
reply.type('text/html').send(uploadResultPage(shareUrl, data.filename)); return reply.view('upload-result.ejs', { title: 'File uploaded', authed: true, shareUrl, filename: data.filename });
}); });
// GET /files // GET /files
app.get('/files', { preHandler: requireAuth }, async (request, reply) => { app.get('/files', { preHandler: requireAuth }, async (request, reply) => {
const { sub: userId } = request.user as JwtPayload; const { sub: userId } = request.user as JwtPayload;
const files = getFilesByUserId(db, userId); const files = getFilesByUserId(db, userId);
reply.type('text/html').send(fileListPage(files, config.baseUrl)); const filesWithSize = files.map((f) => ({ ...f, sizeFormatted: formatBytes(f.size) }));
return reply.view('file-list.ejs', { title: 'My files', authed: true, files: filesWithSize, baseUrl: config.baseUrl });
}); });
// POST /files/:id/delete // POST /files/:id/delete
@@ -182,11 +183,17 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
if (!file) { if (!file) {
await logger.fileNotFound({ ip: request.ip, userAgent: request.headers['user-agent'] ?? '', fileId: id }); await logger.fileNotFound({ ip: request.ip, userAgent: request.headers['user-agent'] ?? '', fileId: id });
return reply.status(404).type('text/html').send(notFoundPage()); return reply.status(404).view('not-found.ejs', { title: 'Not found' });
} }
const isOwner = userId !== null && userId === file.user_id; const isOwner = userId !== null && userId === file.user_id;
reply.type('text/html').send(fileViewPage(file, isOwner)); return reply.view('file-view.ejs', {
title: file.original_name,
authed: isOwner,
hideHeader: !isOwner,
file,
isOwner,
});
}); });
// GET /f/:id/raw — serve raw file with range request support // GET /f/:id/raw — serve raw file with range request support
@@ -235,6 +242,6 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
// 404 handler // 404 handler
app.setNotFoundHandler((_request, reply) => { app.setNotFoundHandler((_request, reply) => {
reply.status(404).type('text/html').send(notFoundPage()); return reply.status(404).view('not-found.ejs', { title: 'Not found' });
}); });
}; };

View File

@@ -5,6 +5,8 @@ import fastifyMultipart from '@fastify/multipart';
import fastifyFormbody from '@fastify/formbody'; import fastifyFormbody from '@fastify/formbody';
import fastifyStatic from '@fastify/static'; import fastifyStatic from '@fastify/static';
import fastifyRateLimit from '@fastify/rate-limit'; import fastifyRateLimit from '@fastify/rate-limit';
import fastifyView from '@fastify/view';
import ejs from 'ejs';
import { join } from 'path'; import { join } from 'path';
import { fileURLToPath } from 'url'; import { fileURLToPath } from 'url';
import type Database from 'better-sqlite3'; import type Database from 'better-sqlite3';
@@ -39,6 +41,12 @@ export function createServer({ config, db }: ServerDeps) {
root: join(__dirname, '..', 'public'), root: join(__dirname, '..', 'public'),
prefix: '/public/', prefix: '/public/',
}); });
app.register(fastifyView, {
engine: { ejs },
root: join(__dirname, '..', 'views'),
layout: '_layout.ejs',
defaultContext: { authed: false, hideHeader: false },
});
app.register(fastifyRateLimit, { app.register(fastifyRateLimit, {
global: false, global: false,
keyGenerator: (req) => req.ip, keyGenerator: (req) => req.ip,

View File

@@ -1,44 +0,0 @@
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) => {
const shareUrl = `${baseUrl}/f/${escHtml(f.id)}`;
return `
<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>
<button class="copy-link" onclick="navigator.clipboard.writeText('${shareUrl}')">Copy link</button>
<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>
<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 });
}
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`;
}

View File

@@ -1,38 +0,0 @@
import { layout, escHtml } from './layout.ts';
import type { FileRow } from '../db/files.ts';
export function fileViewPage(file: FileRow, isOwner: boolean): 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>`;
const deleteForm = isOwner
? `<form method="POST" action="/files/${escHtml(file.id)}/delete">
<button type="submit" class="danger">Delete</button>
</form>`
: '';
let media = '';
if (file.mime_type.startsWith('image/')) {
media = `<img src="${rawUrl}" alt="${safeName}">`;
} else 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>`;
}
const layoutOpts = isOwner ? { authed: true } : { hideHeader: true };
return layout(file.original_name, `
<div class="file-view">
<h1>${safeName}</h1>
${media}
${actions}
${deleteForm}
</div>
`, layoutOpts);
}

View File

@@ -1,45 +0,0 @@
export function layout(title: string, body: string, opts: { authed?: boolean; hideHeader?: boolean } = {}): string {
const { authed = false, hideHeader = 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>`
: '';
const header = hideHeader
? ''
: ` <header>
<a href="/" class="logo">Nanodrop</a>
${nav}
</header>`;
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<title>${escHtml(title)} — Nanodrop</title>
<link rel="stylesheet" href="/public/style.css">
</head>
<body>
${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;');
}

View File

@@ -1,25 +0,0 @@
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>
`);
}

View File

@@ -1,11 +0,0 @@
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>
`);
}

View File

@@ -1,36 +0,0 @@
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 });
}

29
views/_layout.ejs Normal file
View File

@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<title><%= title %> — Nanodrop</title>
<link rel="stylesheet" href="/public/style.css">
</head>
<body>
<% if (!hideHeader) { %>
<header>
<a href="/" class="logo">Nanodrop</a>
<% if (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>
<% } %>
</header>
<% } %>
<main>
<%- body %>
</main>
</body>
</html>

31
views/file-list.ejs Normal file
View File

@@ -0,0 +1,31 @@
<h1>My files</h1>
<p><a href="/upload">Upload new file</a></p>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Name</th><th>Type</th><th>Size</th><th>Uploaded</th><th></th>
</tr>
</thead>
<tbody>
<% if (files.length === 0) { %>
<tr><td colspan="5">No files yet. <a href="/upload">Upload one.</a></td></tr>
<% } else { %>
<% files.forEach(function(f) { %>
<tr>
<td><a href="/f/<%= f.id %>"><%= f.original_name %></a></td>
<td><%= f.mime_type %></td>
<td><%= f.sizeFormatted %></td>
<td><%= f.created_at %></td>
<td>
<button class="copy-link" onclick="navigator.clipboard.writeText('<%= baseUrl %>/f/<%= f.id %>')">Copy link</button>
<form method="POST" action="/files/<%= f.id %>/delete" style="display:inline">
<button type="submit" class="danger">Delete</button>
</form>
</td>
</tr>
<% }); %>
<% } %>
</tbody>
</table>
</div>

19
views/file-view.ejs Normal file
View File

@@ -0,0 +1,19 @@
<div class="file-view">
<h1><%= file.original_name %></h1>
<% if (file.mime_type.startsWith('image/')) { %>
<img src="/f/<%= file.id %>/raw" alt="<%= file.original_name %>">
<% } else if (file.mime_type.startsWith('video/')) { %>
<video controls src="/f/<%= file.id %>/raw" preload="metadata"></video>
<% } else if (file.mime_type.startsWith('audio/')) { %>
<audio controls src="/f/<%= file.id %>/raw" preload="metadata"></audio>
<% } %>
<div class="file-actions">
<a href="/f/<%= file.id %>/raw" download="<%= file.original_name %>" class="btn">Download</a>
<a href="/f/<%= file.id %>/raw" target="_blank" class="btn">Open</a>
</div>
<% if (isOwner) { %>
<form method="POST" action="/files/<%= file.id %>/delete">
<button type="submit" class="danger">Delete</button>
</form>
<% } %>
</div>

17
views/login.ejs Normal file
View File

@@ -0,0 +1,17 @@
<div class="form-container">
<h1>Sign in</h1>
<% if (error) { %>
<p class="error"><%= error %></p>
<% } %>
<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>

5
views/not-found.ejs Normal file
View File

@@ -0,0 +1,5 @@
<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>

9
views/upload-result.ejs Normal file
View File

@@ -0,0 +1,9 @@
<div class="form-container">
<h1>File uploaded</h1>
<p><strong><%= filename %></strong> is ready to share.</p>
<div class="share-box">
<input type="text" id="share-url" value="<%= shareUrl %>" 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>

13
views/upload.ejs Normal file
View File

@@ -0,0 +1,13 @@
<div class="form-container">
<h1>Upload a file</h1>
<% if (error) { %>
<p class="error"><%= error %></p>
<% } %>
<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>