14 Commits

Author SHA1 Message Date
829037f89c Merge pull request 'chore: replace hand-rolled layout() with @fastify/view + EJS' (#20) from chore/ejs-view-templates into main
All checks were successful
Deploy to birb co. production / deploy (push) Successful in 30s
2026-05-15 05:55:22 +00:00
5586a8cf19 refactor: remove redundant FileRow type annotation in pages.ts map callback 2026-05-14 22:51:27 -07:00
118ea15b4a chore: replace hand-rolled layout() with @fastify/view + EJS
Convert all src/views/*.ts template-literal modules to .ejs templates
under views/. Register @fastify/view plugin in server.ts with EJS
engine and _layout.ejs as the layout file. Update route handlers to
use reply.view() instead of reply.send(layout(...)). Delete the old
TypeScript view modules and layout.ts.

Closes #19
2026-05-14 22:48:41 -07:00
6e6f4b1acf Merge pull request 'chore: bump Dockerfile base to node:24-alpine and add git for npm git-URL deps' (#10) from chore/dockerfile-git-and-node24 into main
All checks were successful
Deploy to birb co. production / deploy (push) Successful in 47s
2026-05-12 18:48:49 +00:00
2df7546779 chore: bump Dockerfile base to node:24-alpine and add git for npm git-URL deps
Deploy CI was failing on `npm ci` because the base image lacked `git`,
which npm needs to resolve `bchen-sqlite-migrate` from its git URL.
Bumping the base from node:22-alpine to node:24-alpine in the same change
aligns the image with authd's stack (npm 11.x) — both native deps support
Node 24 prebuilds.
2026-05-12 11:45:02 -07:00
83a128f917 Merge pull request 'feat: adopt bchen-sqlite-migrate package; replace inline SCHEMA_DDL' (#9) from feat/adopt-sqlite-migrate into main
Some checks failed
Deploy to birb co. production / deploy (push) Failing after 10s
2026-05-12 15:08:33 +00:00
436f7417be feat: adopt bchen-sqlite-migrate package; replace inline SCHEMA_DDL
Phase 3 of the cross-project sqlite-migrate adoption — port nanodrop to
consume bchen-sqlite-migrate@v0.1.0. Replaces the inline db.exec(...)
block in src/db/schema.ts with applyMigrations(db, MIGRATIONS_DIR,
{ genesisProbeTable: 'users' }).

The genesis-probe (table 'users' exists) handles pre-existing prod DBs
automatically — first deploy after merge stamps 0001_init as applied
without re-executing, subsequent boots are no-ops.

Adds three npm scripts (db:migrate, db:status, db:stamp) and a
byte-stability test pinning sha256(0001_init.sql) so the migration is
treated as immutable history.
2026-05-12 08:02:36 -07:00
3f8da8c12c Merge pull request 'feat: auto OS-driven dark mode (prefers-color-scheme)' (#8) from feat/auto-dark-mode into main
All checks were successful
Deploy to birb co. production / deploy (push) Successful in 18s
2026-05-11 16:56:44 +00:00
38e7c0c4a1 refactor: restore var(--border) shorthand after dark-mode tokenization
The dark-mode refactor expanded `border: var(--border);` to
`1px solid var(--border-color);` in three rules (.share-box button,
th, button.copy-link). The rest of the file still uses the
var(--border) shorthand for the same value, so restore it for
consistency.

`--border` is defined as `1px solid var(--border-color)`, so the
substitution is byte-equivalent at the cascade level: same border
in light mode, same border in dark mode, identical to the prior
commit.

Behavior unchanged. 130/130 tests pass; tsc --noEmit clean.
2026-05-11 09:53:24 -07:00
012c544bdc feat: auto OS-driven dark mode (prefers-color-scheme)
Refactor public/style.css to semantic CSS custom properties under :root
(light palette by default) and add a @media (prefers-color-scheme: dark)
override block that flips background/foreground/accent/danger tokens to
a soft near-black palette. The original --black/--white/--gray-*/--red
literal tokens and the lone #fff5f5 floating literal are gone — every
color now derives from a semantic token, so the dark override is the
only place that re-declares them.

Add <meta name="color-scheme" content="light dark"> to the shared
layout <head> so the browser renders its UA backdrop, native scrollbars,
and form-control popups in the user's preferred scheme before the
stylesheet parses — this is what avoids a white flash on initial paint
in dark mode.

No toggle, no JS, no preference persistence — the page follows the OS
setting directly via the media query. The 16px font-size rule on
text-entry inputs is preserved (still asserted by tests/integration
/style.test.ts).
2026-05-11 09:50:44 -07:00
398c008c32 Merge pull request 'chore: drop pre-emptive 'compose down' so failed builds don't take prod offline' (#7) from chore/nanodrop-deploy-skip-preemptive-down into main
All checks were successful
Deploy to birb co. production / deploy (push) Successful in 18s
2026-05-11 07:50:11 +00:00
95201eb406 chore: drop pre-emptive 'compose down' so failed builds don't take prod offline
Matches the cross-project pattern already applied to authd PR #12, buchinese
PR #8, inventory PR #19, and movement PR #16. The pre-emptive `docker compose
down` destroyed the running container BEFORE `docker compose up -d --build`
had a chance to verify the new image builds — a single npm ci lockfile
mismatch (buchinese PR #6, 2026-05-10) was enough to put prod to HTTP 502 for
the entire human-intervention turnaround. `docker compose up -d --build`
builds first; only on successful build does compose recreate the container.
On build failure compose exits non-zero with the previous container still
serving traffic. `--remove-orphans` is a drop-in cleanup for renamed/removed
services.

No test added (no CI-yaml tests exist in this project; matches 4 precedent
PRs). Refactor pass expected to be a noop.
2026-05-11 00:47:25 -07:00
4df874b695 Merge pull request 'chore: bump form input font-size to 16px to prevent iOS focus-zoom' (#6) from chore/nanodrop-ios-input-no-zoom into main
All checks were successful
Deploy to birb co. production / deploy (push) Successful in 17s
2026-05-11 03:12:44 +00:00
5d6cb390a4 chore: bump form input font-size to 16px to prevent iOS focus-zoom
Final retrofit in the cross-project iOS focus-zoom chore (after authd PR
#11, buchinese PR #5, inventory PR #18, movement PR #15). Enforces the
standing rule in ~/.claude/CLAUDE.md: text-entry inputs must compute to
font-size >= 16px so iOS Safari does not auto-zoom on focus.
2026-05-10 20:08:53 -07:00
29 changed files with 1322 additions and 820 deletions

View File

@@ -51,6 +51,5 @@ jobs:
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
docker compose -f compose.yaml up -d --build --remove-orphans
EOF

View File

@@ -1,7 +1,7 @@
FROM node:22-alpine
FROM node:24-alpine
# Install native build tools for bcrypt
RUN apk add --no-cache python3 make g++
# Install native build tools for bcrypt/better-sqlite3 + git for npm git-URL deps
RUN apk add --no-cache python3 make g++ git
WORKDIR /app

1374
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -9,7 +9,10 @@
"dev": "tsx src/index.ts",
"test": "vitest run",
"test:watch": "vitest",
"register-user": "tsx src/cli/register-user.ts"
"register-user": "tsx src/cli/register-user.ts",
"db:migrate": "tsx src/scripts/db-migrate.ts",
"db:status": "tsx src/scripts/db-status.ts",
"db:stamp": "tsx src/scripts/db-stamp.ts"
},
"author": "",
"license": "ISC",
@@ -20,14 +23,18 @@
"@fastify/multipart": "^9.4.0",
"@fastify/rate-limit": "^10.3.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",
"bcrypt": "^6.0.0",
"better-sqlite3": "^12.6.2",
"ejs": "^5.0.2",
"fastify": "^5.7.4",
"nanoid": "^5.1.6"
},
"devDependencies": {
"@types/bcrypt": "^6.0.0",
"@types/better-sqlite3": "^7.6.13",
"@types/ejs": "^3.1.5",
"@types/node": "^25.3.3",
"tsx": "^4.21.0",
"typescript": "^5.9.3",

View File

@@ -7,29 +7,60 @@
/* ── Tokens ─────────────────────────────────────────────── */
:root {
--black: #000;
--white: #fff;
--gray-50: #fafafa;
--gray-100:#f0f0f0;
--gray-200:#e0e0e0;
--gray-400:#999;
--gray-600:#555;
--red: #c00;
--bg: #fff;
--bg-elevated: #f0f0f0;
--bg-hover: #fafafa;
--fg: #000;
--fg-muted: #555;
--fg-on-accent: #fff;
--border-color: #000;
--border-subtle: #e0e0e0;
--accent: #000;
--accent-hover: #555;
--danger: #c00;
--danger-bg: #fff5f5;
--danger-fg: #fff;
--input-bg: #fff;
--input-bg-focus: #fafafa;
--input-fg: #000;
--input-border: #000;
--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);
--border: 1px solid var(--border-color);
--radius: 0;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #0f1115;
--bg-elevated: #1a1d23;
--bg-hover: #1f2228;
--fg: #e5e7eb;
--fg-muted: #9ca3af;
--fg-on-accent: #0f1115;
--border-color: #2a2e36;
--border-subtle: #272b33;
--accent: #e5e7eb;
--accent-hover: #cbd0d8;
--danger: #f87171;
--danger-bg: #2a1414;
--danger-fg: #0f1115;
--input-bg: #1a1d23;
--input-bg-focus: #222630;
--input-fg: #e5e7eb;
--input-border: #3a3f48;
}
}
/* ── Base ───────────────────────────────────────────────── */
html { font-size: 14px; }
body {
font-family: var(--font);
line-height: 1.5;
background: var(--white);
color: var(--black);
background: var(--bg);
color: var(--fg);
min-height: 100vh;
display: flex;
flex-direction: column;
@@ -37,11 +68,11 @@ body {
}
a {
color: var(--black);
color: var(--fg);
text-decoration: underline;
text-underline-offset: 3px;
}
a:hover { color: var(--gray-600); }
a:hover { color: var(--fg-muted); }
/* ── Header ─────────────────────────────────────────────── */
header {
@@ -59,9 +90,9 @@ header {
font-weight: 600;
letter-spacing: 0.02em;
text-decoration: none;
color: var(--black);
color: var(--fg);
}
.logo:hover { color: var(--gray-600); }
.logo:hover { color: var(--fg-muted); }
nav {
display: flex;
@@ -78,12 +109,12 @@ nav a {
font-size: 12px;
letter-spacing: 0.04em;
text-decoration: none;
color: var(--gray-600);
color: var(--fg-muted);
border-left: var(--border);
}
nav a:hover {
color: var(--black);
background: var(--gray-100);
color: var(--fg);
background: var(--bg-elevated);
}
nav form {
@@ -99,13 +130,13 @@ nav button[type="submit"] {
background: none;
border: none;
border-left: var(--border);
color: var(--gray-600);
color: var(--fg-muted);
cursor: pointer;
font-family: var(--font);
}
nav button[type="submit"]:hover {
color: var(--black);
background: var(--gray-100);
color: var(--fg);
background: var(--bg-elevated);
}
/* ── Main ───────────────────────────────────────────────── */
@@ -141,7 +172,7 @@ label {
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--gray-600);
color: var(--fg-muted);
}
input[type="text"],
@@ -150,17 +181,17 @@ input[type="file"] {
width: 100%;
padding: 0.6rem 0.75rem;
font-family: var(--font);
font-size: 13px;
background: var(--white);
border: var(--border);
color: var(--black);
font-size: 16px;
background: var(--input-bg);
border: 1px solid var(--input-border);
color: var(--input-fg);
outline: none;
transition: background 0.1s;
}
input[type="text"]:focus,
input[type="password"]:focus {
background: var(--gray-50);
box-shadow: inset 0 0 0 2px var(--black);
background: var(--input-bg-focus);
box-shadow: inset 0 0 0 2px var(--accent);
}
input[type="file"] {
@@ -171,8 +202,8 @@ input[type="file"]::-webkit-file-upload-button {
font-family: var(--font);
font-size: 11px;
letter-spacing: 0.02em;
background: var(--black);
color: var(--white);
background: var(--accent);
color: var(--fg-on-accent);
border: none;
padding: 0.3rem 0.6rem;
cursor: pointer;
@@ -182,8 +213,8 @@ input[type="file"]::file-selector-button {
font-family: var(--font);
font-size: 11px;
letter-spacing: 0.02em;
background: var(--black);
color: var(--white);
background: var(--accent);
color: var(--fg-on-accent);
border: none;
padding: 0.3rem 0.6rem;
cursor: pointer;
@@ -199,16 +230,17 @@ button[type="submit"],
font-size: 11px;
font-weight: 600;
letter-spacing: 0.02em;
background: var(--black);
color: var(--white);
border: var(--border);
background: var(--accent);
color: var(--fg-on-accent);
border: 1px solid var(--accent);
cursor: pointer;
transition: background 0.1s, color 0.1s;
text-align: center;
}
button[type="submit"]:hover,
.btn-primary:hover {
background: var(--gray-600);
background: var(--accent-hover);
border-color: var(--accent-hover);
}
/* ── Danger Button ──────────────────────────────────────── */
@@ -219,13 +251,13 @@ button.danger {
font-size: 11px;
letter-spacing: 0.04em;
background: none;
color: var(--red);
border: 1px solid var(--red);
color: var(--danger);
border: 1px solid var(--danger);
cursor: pointer;
}
button.danger:hover {
background: var(--red);
color: var(--white);
background: var(--danger);
color: var(--danger-fg);
}
/* ── Generic Link-button (.btn for file-view) ───────────── */
@@ -236,23 +268,23 @@ a.btn {
font-weight: 600;
letter-spacing: 0.02em;
text-decoration: none;
background: var(--black);
color: var(--white);
border: var(--border);
background: var(--accent);
color: var(--fg-on-accent);
border: 1px solid var(--accent);
transition: background 0.1s;
}
a.btn:hover {
background: var(--gray-600);
color: var(--white);
background: var(--accent-hover);
color: var(--fg-on-accent);
}
/* ── Error ──────────────────────────────────────────────── */
.error {
font-size: 12px;
color: var(--red);
color: var(--danger);
padding: 0.6rem 0.75rem;
border: 1px solid var(--red);
background: #fff5f5;
border: 1px solid var(--danger);
background: var(--danger-bg);
margin-bottom: 0.5rem;
}
@@ -266,14 +298,14 @@ a.btn:hover {
.share-box input[readonly] {
flex: 1;
font-family: var(--font-mono);
background: var(--gray-100);
color: var(--gray-600);
background: var(--bg-elevated);
color: var(--fg-muted);
border-right: none;
cursor: text;
}
.share-box input[readonly]:focus {
box-shadow: none;
background: var(--gray-100);
background: var(--bg-elevated);
}
/* Copy button — outline style, distinct from submit */
@@ -283,8 +315,8 @@ a.btn:hover {
font-size: 11px;
font-weight: 600;
letter-spacing: 0.02em;
background: var(--white);
color: var(--black);
background: var(--bg);
color: var(--fg);
border: var(--border);
cursor: pointer;
white-space: nowrap;
@@ -292,7 +324,7 @@ a.btn:hover {
flex-shrink: 0;
}
.share-box button:hover {
background: var(--gray-100);
background: var(--bg-elevated);
}
/* ── Table ──────────────────────────────────────────────── */
@@ -329,21 +361,21 @@ th {
letter-spacing: 0.06em;
text-transform: uppercase;
text-align: left;
background: var(--gray-100);
background: var(--bg-elevated);
border-bottom: var(--border);
color: var(--gray-600);
color: var(--fg-muted);
}
td {
padding: 0.6rem 1rem;
font-size: 12px;
border-bottom: 1px solid var(--gray-200);
border-bottom: 1px solid var(--border-subtle);
vertical-align: middle;
}
tr:last-child td { border-bottom: none; }
tr:hover td { background: var(--gray-50); }
tr:hover td { background: var(--bg-hover); }
td a {
font-weight: 500;
@@ -362,14 +394,14 @@ button.copy-link {
font-family: var(--font);
font-size: 11px;
letter-spacing: 0.04em;
background: var(--white);
color: var(--black);
background: var(--bg);
color: var(--fg);
border: var(--border);
cursor: pointer;
margin-right: 0.4rem;
}
button.copy-link:hover {
background: var(--gray-100);
background: var(--bg-elevated);
}
/* ── File View ──────────────────────────────────────────── */
@@ -388,7 +420,7 @@ button.copy-link:hover {
.file-view h1 {
font-size: 13px;
font-weight: 400;
color: var(--gray-600);
color: var(--fg-muted);
word-break: break-all;
border-bottom: none;
padding-bottom: 0;
@@ -412,14 +444,14 @@ button.copy-link:hover {
/* ── Utility ─────────────────────────────────────────────── */
.form-container > p {
font-size: 12px;
color: var(--gray-600);
color: var(--fg-muted);
margin-top: 1rem;
line-height: 1.7;
}
.form-container > p strong {
color: var(--black);
color: var(--fg);
font-weight: 600;
}
.form-container > p a {
color: var(--black);
color: var(--fg);
}

View File

@@ -0,0 +1,26 @@
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
original_name TEXT NOT NULL,
mime_type TEXT NOT NULL,
size INTEGER NOT NULL,
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);

View File

@@ -1,38 +1,27 @@
import path from 'node:path';
import Database from 'better-sqlite3';
import { applyMigrations } from 'bchen-sqlite-migrate';
export const MIGRATIONS_DIR = path.resolve(import.meta.dirname, 'migrations');
export function applySchema(db: Database.Database): void {
applyMigrations(db, MIGRATIONS_DIR, { genesisProbeTable: 'users' });
}
export function initDb(dbPath: string): Database.Database {
const db = new Database(dbPath);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS files (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
original_name TEXT NOT NULL,
mime_type TEXT NOT NULL,
size INTEGER NOT NULL,
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);
`);
const stampGenesis = process.env.DB_MIGRATIONS_STAMP_GENESIS === '1';
const summary = applyMigrations(db, MIGRATIONS_DIR, {
stampGenesis,
genesisProbeTable: 'users',
logger: (msg) => process.stdout.write(`${msg}\n`),
});
process.stdout.write(
`migrations: ${summary.applied + summary.alreadyApplied} applied, ${summary.pending} pending\n`,
);
return db;
}

View File

@@ -12,11 +12,12 @@ import { saveFile, deleteStoredFile, getFilePath } from '../services/storage.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';
import { fileViewPage } from '../views/file-view.ts';
import { notFoundPage } from '../views/not-found.ts';
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`;
}
interface Deps {
db: Database.Database;
@@ -65,7 +66,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
await request.jwtVerify();
return reply.redirect('/upload');
} 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') {
return reply
.type('text/html')
.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') {
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(
@@ -111,7 +111,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
// GET /upload
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
@@ -120,7 +120,7 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
const data = await request.file();
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();
@@ -141,14 +141,15 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
});
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
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));
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
@@ -182,11 +183,17 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
if (!file) {
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;
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
@@ -235,6 +242,6 @@ export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps
// 404 handler
app.setNotFoundHandler((_request, reply) => {
reply.status(404).type('text/html').send(notFoundPage());
return reply.status(404).view('not-found.ejs', { title: 'Not found' });
});
};

21
src/scripts/_db-cli.ts Normal file
View File

@@ -0,0 +1,21 @@
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
import Database from 'better-sqlite3';
import { loadConfig } from '../config.ts';
import { MIGRATIONS_DIR } from '../db/schema.ts';
export interface DbCliContext {
db: Database.Database;
migrationsDir: string;
}
export function openDbFromConfig(): DbCliContext {
const config = loadConfig();
mkdirSync(dirname(config.dbPath), { recursive: true });
const db = new Database(config.dbPath);
db.pragma('journal_mode = WAL');
db.pragma('foreign_keys = ON');
return { db, migrationsDir: MIGRATIONS_DIR };
}

26
src/scripts/db-migrate.ts Normal file
View File

@@ -0,0 +1,26 @@
import { applyMigrations } from 'bchen-sqlite-migrate';
import { openDbFromConfig } from './_db-cli.ts';
const { db, migrationsDir } = openDbFromConfig();
const stampGenesis = process.env.DB_MIGRATIONS_STAMP_GENESIS === '1';
const summary = applyMigrations(db, migrationsDir, {
stampGenesis,
genesisProbeTable: 'users',
logger: (msg) => process.stdout.write(`${msg}\n`),
});
if (summary.stamped.length > 0) {
process.stdout.write(`stamped:${summary.stamped.join(',')}\n`);
}
if (summary.applied === 0 && summary.stamped.length === 0) {
process.stdout.write(`pending:none\n`);
} else if (summary.applied > 0) {
process.stdout.write(`applied:${summary.applied}\n`);
}
process.stdout.write(
`migrations: ${summary.applied + summary.alreadyApplied} applied, ${summary.pending} pending\n`,
);
db.close();
process.exit(0);

22
src/scripts/db-stamp.ts Normal file
View File

@@ -0,0 +1,22 @@
import { stampMigration } from 'bchen-sqlite-migrate';
import { openDbFromConfig } from './_db-cli.ts';
const version = process.argv[2];
if (!version) {
process.stderr.write('Usage: npm run db:stamp -- <version>\n');
process.exit(1);
}
const { db, migrationsDir } = openDbFromConfig();
try {
const file = stampMigration(db, migrationsDir, version);
process.stdout.write(`stamped:${file.version}\n`);
db.close();
process.exit(0);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
process.stderr.write(`error: ${msg}\n`);
db.close();
process.exit(1);
}

34
src/scripts/db-status.ts Normal file
View File

@@ -0,0 +1,34 @@
import { listMigrations, readAppliedRows } from 'bchen-sqlite-migrate';
import { openDbFromConfig } from './_db-cli.ts';
const { db, migrationsDir } = openDbFromConfig();
const files = listMigrations(migrationsDir);
const appliedByVersion = new Map(readAppliedRows(db).map((r) => [r.version, r]));
let exitCode = 0;
const pending: string[] = [];
const mismatched: string[] = [];
for (const file of files) {
const applied = appliedByVersion.get(file.version);
if (!applied) {
pending.push(file.version);
process.stdout.write(`pending:${file.version}\n`);
continue;
}
if (applied.checksum !== file.checksum) {
mismatched.push(file.version);
process.stdout.write(`checksum-mismatch:${file.version}\n`);
exitCode = 2;
continue;
}
process.stdout.write(`applied:${file.version}\n`);
}
if (pending.length === 0 && mismatched.length === 0) {
process.stdout.write(`pending:none\n`);
}
db.close();
process.exit(exitCode);

View File

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

View File

@@ -29,6 +29,11 @@ describe('GET /', () => {
expect(res.statusCode).toBe(302);
expect(res.headers['location']).toBe('/upload');
});
it('emits <meta name="color-scheme" content="light dark"> in <head>', async () => {
const res = await ctx.app.inject({ method: 'GET', url: '/' });
expect(res.body).toMatch(/<meta\s+name="color-scheme"\s+content="light dark"/);
});
});
describe('POST /login (page)', () => {

View File

@@ -25,6 +25,29 @@ describe('public/style.css (file contents)', () => {
expect(css).toContain('--font-mono');
expect(css).toMatch(/\.share-box input\[readonly\][\s\S]*?font-family:\s*var\(--font-mono\)/);
});
it('uses font-size >= 16px on text-entry inputs to prevent iOS focus-zoom', () => {
expect(css).toMatch(
/input\[type="text"\][\s\S]*?input\[type="password"\][\s\S]*?\{[\s\S]*?font-size:\s*(1[6-9]|[2-9]\d)px/
);
});
it('declares a prefers-color-scheme: dark override', () => {
expect(css).toMatch(/@media\s*\(\s*prefers-color-scheme:\s*dark\s*\)/);
});
it('uses CSS custom properties for the core palette', () => {
expect(css).toMatch(/--bg:/);
expect(css).toMatch(/--fg:/);
expect(css).toMatch(/--accent:/);
});
it('does not contain unreplaced literal hex colors outside the :root and @media blocks', () => {
const stripped = css
.replace(/:root\s*\{[\s\S]*?\}/g, '')
.replace(/@media\s*\([^)]*\)\s*\{[\s\S]*?\}\s*\}/g, '');
expect(stripped).not.toMatch(/#[0-9a-fA-F]{3,6}\b/);
});
});
describe('GET /public/style.css', () => {

View File

@@ -0,0 +1,18 @@
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { resolve } from 'node:path';
import { describe, it, expect } from 'vitest';
const EXPECTED_0001_SHA256 =
'34f092b4bb8544a48acfee0fad08d51b1b75fedf4ffdfbcb790d2656d0f1d57a';
describe('migrations byte stability', () => {
it('0001_init.sql sha256 is frozen — edit means new migration, not edit-in-place', () => {
const body = readFileSync(
resolve(import.meta.dirname, '..', '..', 'src', 'db', 'migrations', '0001_init.sql'),
'utf8',
);
const actual = createHash('sha256').update(body).digest('hex');
expect(actual).toBe(EXPECTED_0001_SHA256);
});
});

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>