29 Commits

Author SHA1 Message Date
c6aa030e54 refactor(style): drop custom webfont, use system fonts
Removes the IBM Plex Mono Google Fonts @import, replaces the --font CSS
variable with a cross-platform system sans-serif stack, and adds a
--font-mono variable for the share-URL readonly input so copy/share text
stays monospace. Also adds line-height: 1.5 to body to compensate for
the system fonts' tighter default leading.

No font asset files exist in /public; layout.ts has no font <link> tags
to remove. Acceptance check: build + 112 tests pass; new
tests/integration/style.test.ts asserts no @import / IBM Plex / external
font URL remains and that the system stack is wired up.
2026-05-03 15:20:22 -07:00
bbd292c085 feat(auth): wire lockout, rate-limit, and constant-time login into both routes
All checks were successful
Deploy to Homelab / deploy (push) Successful in 18s
Both POST /login (HTML form) and POST /api/v1/auth/login now flow through
the shared attemptLogin() handler. Locked accounts respond with 401 +
Retry-After (generic body "Invalid credentials" / "Invalid username or
password") so attackers can't use lockout state as a username-existence
oracle.

@fastify/rate-limit registered with global=false; only the two login
routes opt in via per-route rateLimit config. File uploads and downloads
keep full throughput. Custom errorResponseBuilder logs AUTH_RATE_LIMITED
fire-and-forget so fail2ban can pick it up.

createTestApp now accepts Partial<Config> overrides so integration tests
can dial thresholds down without env-var mutation.
2026-05-03 03:41:51 -07:00
ad36b23061 feat(auth): add shared login handler with constant-time clamp
All checks were successful
Deploy to Homelab / deploy (push) Successful in 18s
Single attemptLogin() orchestrates lockout check, bcrypt verify (against
real or dummy hash), success/failure logging, and a configurable minimum
response-time clamp. Both login routes will share this — no duplication.

Adds three logger events for the operator's escalation pipeline:
AUTH_LOCKOUT_TRIGGERED, AUTH_LOCKED_ATTEMPT, and AUTH_RATE_LIMITED.
fail2ban filters can pick these up to escalate persistent attackers from
in-app lockout to IP ban.

Constant-time defense: unknown users still pay bcrypt cost (via dummy hash)
and the clamp ensures locked-vs-unknown-vs-wrong-password aren't
distinguishable by response time. Username is canonicalized (lowercase + trim)
before lookup so attackers can't bypass lockout via case variation.
2026-05-03 03:34:15 -07:00
11e87f353d feat(auth): add login-attempts DB layer and lockout service
All checks were successful
Deploy to Homelab / deploy (push) Successful in 18s
Persists per-username failed-attempt counts and computed locked_until
timestamps. Lockout service computes exponential-backoff durations
(min(base * 2^(count-threshold), max)) with auto-unlock once locked_until
passes. Successful login deletes the row, resetting the counter.

Pure DB-keyed lockout — survives server restarts and shares state across
both login routes (HTML and JSON) when wired in a later step.
2026-05-03 03:29:09 -07:00
f4eaf88495 feat(auth): add login_attempts schema, lockout config, dummy-hash helper
All checks were successful
Deploy to Homelab / deploy (push) Successful in 29s
Lays the foundation for brute-force defense: per-username attempt tracking
table, configurable lockout/rate-limit thresholds, and a memoized dummy
bcrypt hash so unknown-user paths can be timed identically to wrong-password
paths in a later step.

Adds @fastify/rate-limit dependency for upcoming per-IP rate-limit on
login routes.
2026-05-03 03:26:46 -07:00
d30f40ca71 Merge pull request 'chore: patch dependency vulnerabilities via npm audit fix' (#1) from chore/dependency-security-audit into main
All checks were successful
Deploy to Homelab / deploy (push) Successful in 29s
Reviewed-on: #1
2026-05-03 10:08:43 +00:00
f27ba4922a chore: patch dependency vulnerabilities via npm audit fix
Resolves 7 advisories (1 critical, 3 high, 3 moderate) without
package.json range changes:
- fast-jwt: algorithm confusion, cache key collision, ReDoS
- fastify: content-type validation bypass, host spoofing
- @fastify/static: path traversal & encoded-separator route bypass
- vite (dev only): WS file read, fs.deny bypass, .map traversal
- postcss/picomatch/brace-expansion (transitive): XSS, ReDoS, DoS

npm audit clean; 61 tests pass.
2026-05-03 03:06:47 -07:00
4e89e9783c chore: gitignore .claude/settings.local.json
All checks were successful
Deploy to Homelab / deploy (push) Successful in 1m16s
2026-05-03 02:52:37 -07:00
455cb53aa8 docs: authorize autonomous commits and pushes for this project
Standing authorization so any Claude Code instance commits work after
each logical change (build+tests green) and pushes to the upstream
branch, without waiting to be asked. Force-push and pushes to main from
a feature branch still require explicit approval.
2026-05-03 02:52:27 -07:00
418a553429 refactor: remove unused exported type interfaces
All checks were successful
Deploy to Homelab / deploy (push) Successful in 19s
CreateFileParams, UserRow, CreateUserParams, and MultipartFile were
exported but never imported outside their own modules. Narrowed visibility
to module-local to keep the public surface minimal.

Confirmed with knip (zero findings) and all 61 tests passing.
2026-03-17 10:44:23 -07:00
e25c715fb7 Merge branch 'main' of https://gitea.bchen.dev/brendan/nanodrop
All checks were successful
Deploy to Homelab / deploy (push) Successful in 48s
2026-03-16 16:18:03 -07:00
9fefe5c65d Add HTTP range request support for video streaming
Safari and other browsers require Accept-Ranges: bytes and 206 Partial
Content responses to play video. Without this, large videos fail to load
(especially in Safari) because the entire file had to buffer in memory
before sending.

- Replace readFile + Buffer with createReadStream for efficient streaming
- Parse Range header (start-end, start-, and suffix -N forms)
- Return 206 Partial Content with Content-Range for range requests
- Return 416 Range Not Satisfiable for out-of-bounds ranges
- Add Accept-Ranges: bytes to all raw file responses

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 16:12:21 -07:00
e2944fd828 Export max file size variable
All checks were successful
Deploy to Homelab / deploy (push) Successful in 19s
2026-03-05 20:39:45 +00:00
a4e6a5784a Ensure that app is not accessible via LAN
All checks were successful
Deploy to Homelab / deploy (push) Successful in 17s
2026-03-04 09:48:58 -08:00
241078316c Update Docker port mapping to match both to env var
All checks were successful
Deploy to Homelab / deploy (push) Successful in 8s
2026-03-04 09:44:38 -08:00
85b6f8df2c Export additional variables 2026-03-04 09:44:28 -08:00
00ab308280 Use direct deploy flow without Tailscale
Some checks failed
Deploy to Homelab / deploy (push) Failing after 37s
Directly connect to the public IP of the server, which is static anyways.
2026-03-04 17:38:32 +00:00
d616d4e067 Use an experimental deploy flow
Some checks failed
Deploy to Homelab / deploy (push) Failing after 12s
2026-03-04 09:00:51 +00:00
82793c6d0d Add SSH deployment workflow
Some checks failed
Deploy to Homelab / deploy (push) Failing after 1m37s
2026-03-03 17:08:39 -08:00
8b27038793 Update README 2026-03-03 16:36:06 -08:00
191f5298d1 Update button styling and render additional elements on file page if authenticated 2026-03-03 16:35:02 -08:00
c017761bd1 README: add Caddy reverse proxy example
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 16:20:47 -08:00
c9e2d36e78 Add README with setup, Docker, and fail2ban instructions
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 16:19:35 -08:00
5a47ae938e Fix four bugs and add logo/branding polish
- docker-compose: add register-user service (profiles: [tools]) with YAML anchor to avoid env duplication
- src/index.ts: show localhost instead of 0.0.0.0 in startup message
- file-view: render <img> inline for image/* MIME types
- file-list: add Copy link button per row (requires baseUrl param)
- layout: add hideLogo option; file view page hides the logo
- style.css: remove uppercase from .logo (Nanodrop not NANODROP), add button.copy-link styles, add .file-view img styles, widen last td

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 16:18:34 -08:00
b5ea21d44c Use inline env vars in docker-compose, verify Docker build works
- docker-compose.yml: replace env_file with explicit environment block
  so all variables are passable directly (JWT_SECRET required, rest have defaults)
- Confirmed Docker image builds successfully

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 16:04:56 -08:00
751862a486 Redesign frontend: IBM Plex Mono, black/white editorial aesthetic
- IBM Plex Mono font from Google Fonts for the monospace character
- Pure black/white/gray palette — no colors except red for errors/danger
- 1px solid black borders system throughout (no shadows, no rounding)
- Header nav uses border-left separators with hover backgrounds
- Primary button: solid black; copy button: white outline (visually distinct)
- Share box: readonly input + copy button flush with no gap
- Table: outer border + gray header row + subtle row hover
- File view: centered with border around video/audio players
- Danger button: red outline, fills on hover

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 16:04:18 -08:00
8d5e5c8a4d Fix TypeScript config for .ts import extensions
- allowImportingTsExtensions: true + noEmit: true in tsconfig
- build script runs tsc --noEmit (type-check only)
- Dockerfile simplified to single stage using tsx at runtime
  (no tsc compilation needed; tsx handles .ts imports natively)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 16:02:29 -08:00
6d8fb9105d Code review fixes, Docker, and deployment config
- Fix tsconfig: switch to ESNext/Bundler module resolution (tsx compatible)
- Sanitize file extensions against path traversal (^.[a-zA-Z0-9]+$ only)
- Sanitize Content-Disposition filename to prevent header injection
- Extract tokenCookieOptions helper to eliminate duplication across auth handlers
- Remove unused baseUrl param from fileListPage
- Add Dockerfile (multi-stage build with alpine + native tools for bcrypt)
- Add docker-compose.yml with named volume for data persistence
- Add .env.example with all environment variables documented

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-03 15:58:39 -08:00
8fd1464b9d 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>
2026-03-03 15:55:14 -08:00
46 changed files with 3177 additions and 37 deletions

11
.env.example Normal file
View File

@@ -0,0 +1,11 @@
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
MAX_FILE_SIZE=104857600
BASE_URL=http://localhost:3000
COOKIE_SECURE=false
TRUST_PROXY=false

48
.github/workflows/deploy-homelab.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
name: "Deploy to Homelab"
on:
push:
branches:
- main
workflow_dispatch:
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v3
- name: Set up SSH key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/id_ed25519
chmod 600 ~/.ssh/id_ed25519
ssh-keyscan ${{ vars.HOST }} >> ~/.ssh/known_hosts
- name: Remove directory from server
run: |
ssh -i ~/.ssh/id_ed25519 ${{ vars.USERNAME }}@${{ vars.HOST }} << 'EOF'
rm -rf ~/${{ vars.DIRECTORY_NAME }}
EOF
# Avoid needing to set up SSH access to GitHub for this user
- name: Transfer repository files to server
run: |
scp -i ~/.ssh/id_ed25519 -r ./* ${{ vars.USERNAME }}@${{ vars.HOST }}:~/${{ vars.DIRECTORY_NAME }}
- name: Deploy on server with Docker
run: |
ssh -i ~/.ssh/id_ed25519 ${{ vars.USERNAME }}@${{ vars.HOST }} << 'EOF'
cd ~/${{ vars.DIRECTORY_NAME }}
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
EOF

3
.gitignore vendored
View File

@@ -141,3 +141,6 @@ dist
# Project # Project
data/ data/
dist/ dist/
# Claude Code (personal, machine-specific)
.claude/settings.local.json

View File

@@ -21,8 +21,21 @@ Simple file-sharing platform. TypeScript + Fastify + SQLite.
## Code Quality ## Code Quality
- Review code after every change. Refactor for readability. - Review code after every change. Refactor for readability.
- Use TDD: write tests first, then implement. - Use strict red/green TDD: write the test first, confirm it FAILS (red), then implement until it passes (green).
- Build and test after every change. - Build and test after every change.
- Break large functions into smaller ones, extract duplicate code. - Break large functions into smaller ones, extract duplicate code.
- Search for duplicated code in tests and extract into reusable helpers. - Search for duplicated code in tests and extract into reusable helpers.
- Commit after every logical set of changes. Keep commits small and focused. - Commit after every logical set of changes. Keep commits small and focused.
## Autonomous Commits (Standing Authorization)
Any Claude Code instance working on this project has standing authorization to commit work without asking. Apply this proactively, not when reminded.
- After every logical set of changes that builds and tests cleanly (`npm run build && npm test`), create a commit immediately. Do not wait for the user to ask.
- Use Conventional Commits (`feat:`, `fix:`, `refactor:`, `docs:`, `test:`, `chore:`, `perf:`, `ci:`) with a concise subject. Add a body only when the *why* isn't obvious from the diff.
- One logical change per commit. If you touched multiple unrelated things, split into separate commits.
- After committing, also push to the tracked remote (`git push`) — standard `git push` to the current branch's upstream is authorized. **Never** force-push (`--force`, `--force-with-lease`) and **never** push to `main` from a feature branch directly without an explicit request.
- **Never** stage `.env`, `data/`, secrets, or anything matching a credential pattern. Prefer `git add <specific files>` over `git add -A`/`git add .`.
- If the build or tests fail, do **not** commit. Fix or revert, then either commit a working state or report the failure.
- Skip the commit if there are no changes (don't create empty commits).
- If you find yourself amending or rewriting prior commits, stop and ask first — autonomy covers new commits, not history rewrites.

19
Dockerfile Normal file
View File

@@ -0,0 +1,19 @@
FROM node:22-alpine
# Install native build tools for bcrypt
RUN apk add --no-cache python3 make g++
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY tsconfig.json ./
COPY src ./src
COPY public ./public
RUN mkdir -p /app/data/uploads
EXPOSE 3000
CMD ["node", "--import", "tsx", "src/index.ts"]

168
README.md Normal file
View File

@@ -0,0 +1,168 @@
# Nanodrop
Vibe coded alternative to Google Drive for sharing files
- Server-rendered HTML, no client-side framework
- SQLite database, files stored on disk
- JWT authentication via httpOnly cookies
- REST API alongside the web UI
## Stack
- **Runtime:** Node.js 22
- **Framework:** Fastify
- **Database:** SQLite (better-sqlite3)
- **Language:** TypeScript (ESM, run directly via tsx)
---
## Quick start (local)
```sh
npm install
JWT_SECRET=changeme npm run dev
```
Create a user first:
```sh
npm run register-user -- --username alice --password secret
```
Then open `http://localhost:3000`.
---
## Docker
### Build and run
```sh
docker compose up -d
```
Requires a `.env` file (or environment variables) with at minimum:
```env
JWT_SECRET=your-secret-here
```
All data (database + uploads) is stored in the `nanodrop-data` Docker volume.
### Register a user in Docker
```sh
docker compose run --rm register-user --username alice --password secret
```
### Environment variables
| 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) |
| `DB_PATH` | `./data/nanodrop.db` | SQLite database path |
| `UPLOAD_DIR` | `./data/uploads` | Upload storage directory |
| `LOG_FILE` | `./data/nanodrop.log` | Auth and access log path |
| `MAX_FILE_SIZE` | `104857600` | Max upload size in bytes (100 MB) |
| `COOKIE_SECURE` | `false` | Set `true` when serving over HTTPS |
| `TRUST_PROXY` | `false` | Set `true` when behind a reverse proxy |
### Reverse proxy
Set `TRUST_PROXY=true` when running behind a reverse proxy so Nanodrop sees the real client IP in logs.
**Caddy** (`Caddyfile`):
```caddy
files.example.com {
reverse_proxy localhost:3000
request_body {
max_size 110MB
}
}
```
Caddy sets `X-Forwarded-For` and handles TLS automatically. Set `COOKIE_SECURE=true` since traffic to the app arrives over HTTPS.
**nginx** (`sites-available/nanodrop`):
```nginx
server {
server_name files.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 110M;
}
}
```
---
## Fail2ban
Nanodrop logs failed login attempts to `LOG_FILE` (default `./data/nanodrop.log`) in this format:
```
[2026-03-03T12:00:00.000Z] AUTH_FAILURE ip=203.0.113.42 user-agent="curl/8.0" username="admin"
```
### 1. Create a filter
`/etc/fail2ban/filter.d/nanodrop.conf`:
```ini
[Definition]
failregex = ^.* AUTH_FAILURE ip=<HOST> .*$
ignoreregex =
```
### 2. Create a jail
`/etc/fail2ban/jail.d/nanodrop.conf`:
```ini
[nanodrop]
enabled = true
filter = nanodrop
logpath = /path/to/nanodrop.log
maxretry = 5
findtime = 60
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
volumes:
- /var/lib/nanodrop:/app/data
```
Then set `logpath = /var/lib/nanodrop/nanodrop.log`.
### 3. Reload fail2ban
```sh
sudo fail2ban-client reload
sudo fail2ban-client status nanodrop
```
---
## Development
```sh
npm run dev # start with hot reload via tsx
npm test # run all tests (vitest)
npm run build # type check (tsc --noEmit)
```

33
docker-compose.yml Normal file
View File

@@ -0,0 +1,33 @@
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}"
MAX_FILE_SIZE: "${MAX_FILE_SIZE:-104857600}"
BASE_URL: "${BASE_URL:-http://localhost:3000}"
COOKIE_SECURE: "${COOKIE_SECURE:-false}"
TRUST_PROXY: "${TRUST_PROXY:-false}"
services:
nanodrop:
build: .
ports:
- "127.0.0.1:${PORT:-3000}:${PORT:-3000}"
environment: { <<: *env }
volumes:
- nanodrop-data:/app/data
restart: unless-stopped
register-user:
build: .
profiles: [tools]
entrypoint: ["node", "--import", "tsx", "src/cli/register-user.ts"]
environment: { <<: *env }
volumes:
- nanodrop-data:/app/data
volumes:
nanodrop-data:

78
package-lock.json generated
View File

@@ -13,6 +13,7 @@
"@fastify/formbody": "^8.0.2", "@fastify/formbody": "^8.0.2",
"@fastify/jwt": "^10.0.0", "@fastify/jwt": "^10.0.0",
"@fastify/multipart": "^9.4.0", "@fastify/multipart": "^9.4.0",
"@fastify/rate-limit": "^10.3.0",
"@fastify/static": "^9.0.0", "@fastify/static": "^9.0.0",
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"better-sqlite3": "^12.6.2", "better-sqlite3": "^12.6.2",
@@ -705,6 +706,27 @@
"ipaddr.js": "^2.1.0" "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": { "node_modules/@fastify/send": {
"version": "4.1.0", "version": "4.1.0",
"resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.1.0.tgz", "resolved": "https://registry.npmjs.org/@fastify/send/-/send-4.1.0.tgz",
@@ -729,9 +751,9 @@
} }
}, },
"node_modules/@fastify/static": { "node_modules/@fastify/static": {
"version": "9.0.0", "version": "9.1.3",
"resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.0.0.tgz", "resolved": "https://registry.npmjs.org/@fastify/static/-/static-9.1.3.tgz",
"integrity": "sha512-r64H8Woe/vfilg5RTy7lwWlE8ZZcTrc3kebYFMEUBrMqlydhQyoiExQXdYAy2REVpST/G35+stAM8WYp1WGmMA==", "integrity": "sha512-aXrYtsiryLhRxRNaxNqsn7FUISeb7rB9q4eHUPIot5aeQBLNahnz1m6thzm7JWC1poSGXS9XrX8DvuMivp2hkQ==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -1471,9 +1493,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/brace-expansion": { "node_modules/brace-expansion": {
"version": "5.0.4", "version": "5.0.5",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.4.tgz", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz",
"integrity": "sha512-h+DEnpVvxmfVefa4jFbCf5HdH5YMDXRsmKflpf1pILZWRFlTbJpxeU55nJl4Smt5HQaGzg1o6RHFPJaOqnmBDg==", "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"balanced-match": "^4.0.2" "balanced-match": "^4.0.2"
@@ -1738,15 +1760,16 @@
} }
}, },
"node_modules/fast-jwt": { "node_modules/fast-jwt": {
"version": "6.1.0", "version": "6.2.4",
"resolved": "https://registry.npmjs.org/fast-jwt/-/fast-jwt-6.1.0.tgz", "resolved": "https://registry.npmjs.org/fast-jwt/-/fast-jwt-6.2.4.tgz",
"integrity": "sha512-cGK/TXlud8INL49Iv7yRtZy0PHzNJId1shfqNCqdF0gOlWiy+1FPgjxX+ZHp/CYxFYDaoNnxeYEGzcXSkahUEQ==", "integrity": "sha512-IoQa53wI6TbARU2yelb0L44ggFQnP2qVcwswCSYHbCAWuwpr70icDb3QjG0v01I8Tt01rVGDkN/rRvpk0lKFTA==",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@lukeed/ms": "^2.0.2", "@lukeed/ms": "^2.0.2",
"asn1.js": "^5.4.1", "asn1.js": "^5.4.1",
"ecdsa-sig-formatter": "^1.0.11", "ecdsa-sig-formatter": "^1.0.11",
"mnemonist": "^0.40.0" "mnemonist": "^0.40.0",
"safe-regex2": "^5.1.0"
}, },
"engines": { "engines": {
"node": ">=20" "node": ">=20"
@@ -1790,9 +1813,9 @@
} }
}, },
"node_modules/fastify": { "node_modules/fastify": {
"version": "5.7.4", "version": "5.8.5",
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.7.4.tgz", "resolved": "https://registry.npmjs.org/fastify/-/fastify-5.8.5.tgz",
"integrity": "sha512-e6l5NsRdaEP8rdD8VR0ErJASeyaRbzXYpmkrpr2SuvuMq6Si3lvsaVy5C+7gLanEkvjpMDzBXWE5HPeb/hgTxA==", "integrity": "sha512-Yqptv59pQzPgQUSIm87hMqHJmdkb1+GPxdE6vW6FRyVE9G86mt7rOghitiU4JHRaTyDUk9pfeKmDeu70lAwM4Q==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -1814,7 +1837,7 @@
"fast-json-stringify": "^6.0.0", "fast-json-stringify": "^6.0.0",
"find-my-way": "^9.0.0", "find-my-way": "^9.0.0",
"light-my-request": "^6.0.0", "light-my-request": "^6.0.0",
"pino": "^10.1.0", "pino": "^9.14.0 || ^10.1.0",
"process-warning": "^5.0.0", "process-warning": "^5.0.0",
"rfdc": "^1.3.1", "rfdc": "^1.3.1",
"secure-json-parse": "^4.0.0", "secure-json-parse": "^4.0.0",
@@ -2304,9 +2327,9 @@
"license": "ISC" "license": "ISC"
}, },
"node_modules/picomatch": { "node_modules/picomatch": {
"version": "4.0.3", "version": "4.0.4",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"engines": { "engines": {
@@ -2354,9 +2377,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/postcss": { "node_modules/postcss": {
"version": "8.5.8", "version": "8.5.13",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.8.tgz", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.13.tgz",
"integrity": "sha512-OW/rX8O/jXnm82Ey1k44pObPtdblfiuWnrd8X7GJ7emImCOstunGbXUpp7HdBrFQX6rJzn3sPT397Wp5aCwCHg==", "integrity": "sha512-qif0+jGGZoLWdHey3UFHHWP0H7Gbmsk8T5VEqyYFbWqPr1XqvLGBbk/sl8V5exGmcYJklJOhOQq1pV9IcsiFag==",
"dev": true, "dev": true,
"funding": [ "funding": [
{ {
@@ -2608,9 +2631,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/safe-regex2": { "node_modules/safe-regex2": {
"version": "5.0.0", "version": "5.1.1",
"resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.0.0.tgz", "resolved": "https://registry.npmjs.org/safe-regex2/-/safe-regex2-5.1.1.tgz",
"integrity": "sha512-YwJwe5a51WlK7KbOJREPdjNrpViQBI3p4T50lfwPuDhZnE3XGVTlGvi+aolc5+RvxDD6bnUmjVsU9n1eboLUYw==", "integrity": "sha512-mOSBvHGDZMuIEZMdOz/aCEYDCv0E7nfcNsIhUF+/P+xC7Hyf3FkvymqgPbg9D1EdSGu+uKbJgy09K/RKKc7kJA==",
"funding": [ "funding": [
{ {
"type": "github", "type": "github",
@@ -2624,6 +2647,9 @@
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"ret": "~0.5.0" "ret": "~0.5.0"
},
"bin": {
"safe-regex2": "bin/safe-regex2.js"
} }
}, },
"node_modules/safe-stable-stringify": { "node_modules/safe-stable-stringify": {
@@ -2977,9 +3003,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/vite": { "node_modules/vite": {
"version": "7.3.1", "version": "7.3.2",
"resolved": "https://registry.npmjs.org/vite/-/vite-7.3.1.tgz", "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz",
"integrity": "sha512-w+N7Hifpc3gRjZ63vYBXA56dvvRlNWRczTdmCBBa+CotUzAPf5b7YMdMR/8CQoeYE5LX3W4wj6RYTgonm1b9DA==", "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {

View File

@@ -5,7 +5,7 @@
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"build": "tsc", "build": "tsc --noEmit",
"dev": "tsx src/index.ts", "dev": "tsx src/index.ts",
"test": "vitest run", "test": "vitest run",
"test:watch": "vitest", "test:watch": "vitest",
@@ -18,6 +18,7 @@
"@fastify/formbody": "^8.0.2", "@fastify/formbody": "^8.0.2",
"@fastify/jwt": "^10.0.0", "@fastify/jwt": "^10.0.0",
"@fastify/multipart": "^9.4.0", "@fastify/multipart": "^9.4.0",
"@fastify/rate-limit": "^10.3.0",
"@fastify/static": "^9.0.0", "@fastify/static": "^9.0.0",
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"better-sqlite3": "^12.6.2", "better-sqlite3": "^12.6.2",

419
public/style.css Normal file
View File

@@ -0,0 +1,419 @@
/* ── Reset ──────────────────────────────────────────────── */
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* ── Tokens ─────────────────────────────────────────────── */
:root {
--black: #000;
--white: #fff;
--gray-50: #fafafa;
--gray-100:#f0f0f0;
--gray-200:#e0e0e0;
--gray-400:#999;
--gray-600:#555;
--red: #c00;
--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;
}
/* ── Base ───────────────────────────────────────────────── */
html { font-size: 14px; }
body {
font-family: var(--font);
line-height: 1.5;
background: var(--white);
color: var(--black);
min-height: 100vh;
display: flex;
flex-direction: column;
-webkit-font-smoothing: antialiased;
}
a {
color: var(--black);
text-decoration: underline;
text-underline-offset: 3px;
}
a:hover { color: var(--gray-600); }
/* ── Header ─────────────────────────────────────────────── */
header {
display: flex;
align-items: center;
gap: 2rem;
padding: 0 2rem;
height: 48px;
border-bottom: var(--border);
flex-shrink: 0;
}
.logo {
font-size: 13px;
font-weight: 600;
letter-spacing: 0.02em;
text-decoration: none;
color: var(--black);
}
.logo:hover { color: var(--gray-600); }
nav {
display: flex;
align-items: center;
gap: 0;
margin-left: auto;
}
nav a {
display: block;
padding: 0 1rem;
height: 48px;
line-height: 48px;
font-size: 12px;
letter-spacing: 0.04em;
text-decoration: none;
color: var(--gray-600);
border-left: var(--border);
}
nav a:hover {
color: var(--black);
background: var(--gray-100);
}
nav form {
display: contents;
}
nav button[type="submit"] {
display: block;
padding: 0 1rem;
height: 48px;
font-size: 12px;
letter-spacing: 0.04em;
background: none;
border: none;
border-left: var(--border);
color: var(--gray-600);
cursor: pointer;
font-family: var(--font);
}
nav button[type="submit"]:hover {
color: var(--black);
background: var(--gray-100);
}
/* ── Main ───────────────────────────────────────────────── */
main {
flex: 1;
padding: 3rem 2rem;
}
/* ── Form Container ─────────────────────────────────────── */
.form-container {
max-width: 400px;
}
.form-container h1 {
font-size: 16px;
font-weight: 600;
letter-spacing: 0.02em;
margin-bottom: 2rem;
padding-bottom: 1rem;
border-bottom: var(--border);
}
form {
display: flex;
flex-direction: column;
gap: 1.25rem;
}
label {
display: flex;
flex-direction: column;
gap: 0.375rem;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--gray-600);
}
input[type="text"],
input[type="password"],
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);
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);
}
input[type="file"] {
padding: 0.5rem;
cursor: pointer;
}
input[type="file"]::-webkit-file-upload-button {
font-family: var(--font);
font-size: 11px;
letter-spacing: 0.02em;
background: var(--black);
color: var(--white);
border: none;
padding: 0.3rem 0.6rem;
cursor: pointer;
margin-right: 0.75rem;
}
input[type="file"]::file-selector-button {
font-family: var(--font);
font-size: 11px;
letter-spacing: 0.02em;
background: var(--black);
color: var(--white);
border: none;
padding: 0.3rem 0.6rem;
cursor: pointer;
margin-right: 0.75rem;
}
/* ── Primary Button ─────────────────────────────────────── */
button[type="submit"],
.btn-primary {
display: inline-block;
padding: 0.6rem 1.25rem;
font-family: var(--font);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.02em;
background: var(--black);
color: var(--white);
border: var(--border);
cursor: pointer;
transition: background 0.1s, color 0.1s;
text-align: center;
}
button[type="submit"]:hover,
.btn-primary:hover {
background: var(--gray-600);
}
/* ── Danger Button ──────────────────────────────────────── */
button.danger {
display: inline-block;
padding: 0.3rem 0.6rem;
font-family: var(--font);
font-size: 11px;
letter-spacing: 0.04em;
background: none;
color: var(--red);
border: 1px solid var(--red);
cursor: pointer;
}
button.danger:hover {
background: var(--red);
color: var(--white);
}
/* ── Generic Link-button (.btn for file-view) ───────────── */
a.btn {
display: inline-block;
padding: 0.6rem 1.25rem;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.02em;
text-decoration: none;
background: var(--black);
color: var(--white);
border: var(--border);
transition: background 0.1s;
}
a.btn:hover {
background: var(--gray-600);
color: var(--white);
}
/* ── Error ──────────────────────────────────────────────── */
.error {
font-size: 12px;
color: var(--red);
padding: 0.6rem 0.75rem;
border: 1px solid var(--red);
background: #fff5f5;
margin-bottom: 0.5rem;
}
/* ── Share Box ──────────────────────────────────────────── */
.share-box {
display: flex;
gap: 0;
margin: 1.25rem 0 1rem;
}
.share-box input[readonly] {
flex: 1;
font-family: var(--font-mono);
background: var(--gray-100);
color: var(--gray-600);
border-right: none;
cursor: text;
}
.share-box input[readonly]:focus {
box-shadow: none;
background: var(--gray-100);
}
/* Copy button — outline style, distinct from submit */
.share-box button {
padding: 0.6rem 1rem;
font-family: var(--font);
font-size: 11px;
font-weight: 600;
letter-spacing: 0.02em;
background: var(--white);
color: var(--black);
border: var(--border);
cursor: pointer;
white-space: nowrap;
transition: background 0.1s;
flex-shrink: 0;
}
.share-box button:hover {
background: var(--gray-100);
}
/* ── Table ──────────────────────────────────────────────── */
h1 {
font-size: 16px;
font-weight: 600;
letter-spacing: 0.02em;
margin-bottom: 1.25rem;
padding-bottom: 1rem;
border-bottom: var(--border);
}
h1 + p {
margin-bottom: 1.5rem;
font-size: 12px;
}
table {
width: 100%;
border-collapse: collapse;
border: var(--border);
}
th {
padding: 0.6rem 1rem;
font-size: 11px;
font-weight: 600;
letter-spacing: 0.06em;
text-transform: uppercase;
text-align: left;
background: var(--gray-100);
border-bottom: var(--border);
color: var(--gray-600);
}
td {
padding: 0.6rem 1rem;
font-size: 12px;
border-bottom: 1px solid var(--gray-200);
vertical-align: middle;
}
tr:last-child td { border-bottom: none; }
tr:hover td { background: var(--gray-50); }
td a {
font-weight: 500;
}
td:last-child {
width: 160px;
text-align: right;
white-space: nowrap;
}
/* ── Copy Link Button ───────────────────────────────────── */
button.copy-link {
display: inline-block;
padding: 0.3rem 0.6rem;
font-family: var(--font);
font-size: 11px;
letter-spacing: 0.04em;
background: var(--white);
color: var(--black);
border: var(--border);
cursor: pointer;
margin-right: 0.4rem;
}
button.copy-link:hover {
background: var(--gray-100);
}
/* ── File View ──────────────────────────────────────────── */
.file-view {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: calc(100vh - 48px - 6rem);
gap: 1.5rem;
text-align: center;
max-width: 800px;
margin: 0 auto;
}
.file-view h1 {
font-size: 13px;
font-weight: 400;
color: var(--gray-600);
word-break: break-all;
border-bottom: none;
padding-bottom: 0;
margin-bottom: 0;
}
.file-view img,
.file-view video,
.file-view audio {
width: 100%;
max-width: 720px;
border: var(--border);
display: block;
}
.file-actions {
display: flex;
gap: 0.75rem;
}
/* ── Utility ─────────────────────────────────────────────── */
.form-container > p {
font-size: 12px;
color: var(--gray-600);
margin-top: 1rem;
line-height: 1.7;
}
.form-container > p strong {
color: var(--black);
font-weight: 600;
}
.form-container > p a {
color: var(--black);
}

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.`);

View File

@@ -10,6 +10,12 @@ export interface Config {
baseUrl: string; baseUrl: string;
cookieSecure: boolean; cookieSecure: boolean;
trustProxy: boolean; trustProxy: boolean;
lockoutThreshold: number;
lockoutBaseSeconds: number;
lockoutMaxSeconds: number;
loginMinResponseMs: number;
loginRateLimitMax: number;
loginRateLimitWindowSeconds: number;
} }
export function loadConfig(): Config { export function loadConfig(): Config {
@@ -30,5 +36,11 @@ export function loadConfig(): Config {
baseUrl: process.env.BASE_URL ?? 'http://localhost:3000', baseUrl: process.env.BASE_URL ?? 'http://localhost:3000',
cookieSecure: process.env.COOKIE_SECURE === 'true', cookieSecure: process.env.COOKIE_SECURE === 'true',
trustProxy: process.env.TRUST_PROXY === '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),
}; };
} }

View File

@@ -10,7 +10,7 @@ export interface FileRow {
created_at: string; created_at: string;
} }
export interface CreateFileParams { interface CreateFileParams {
id: string; id: string;
userId: number; userId: number;
originalName: string; originalName: string;

38
src/db/login-attempts.ts Normal file
View 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);
}

View File

@@ -22,6 +22,16 @@ export function initDb(dbPath: string): Database.Database {
stored_name TEXT NOT NULL, stored_name TEXT NOT NULL,
created_at TEXT DEFAULT (datetime('now')) 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; return db;

View File

@@ -1,13 +1,13 @@
import type Database from 'better-sqlite3'; import type Database from 'better-sqlite3';
export interface UserRow { interface UserRow {
id: number; id: number;
username: string; username: string;
password_hash: string; password_hash: string;
created_at: string; created_at: string;
} }
export interface CreateUserParams { interface CreateUserParams {
username: string; username: string;
passwordHash: string; passwordHash: string;
} }

20
src/index.ts Normal file
View File

@@ -0,0 +1,20 @@
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 });
const displayHost = config.host === '0.0.0.0' ? 'localhost' : config.host;
console.log(`Nanodrop running on http://${displayHost}:${config.port}`);
} catch (err) {
console.error(err);
process.exit(1);
}

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

@@ -0,0 +1,24 @@
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('/');
}
}
}
export function tokenCookieOptions(secure: boolean): {
httpOnly: boolean;
sameSite: 'strict';
secure: boolean;
path: string;
} {
return { httpOnly: true, sameSite: 'strict', secure, path: '/' };
}

View File

@@ -12,9 +12,26 @@ interface FileNotFoundParams {
fileId: string; 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 { export interface Logger {
authSuccess(params: AuthLogParams): Promise<void>; authSuccess(params: AuthLogParams): Promise<void>;
authFailure(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>; fileNotFound(params: FileNotFoundParams): Promise<void>;
} }
@@ -34,6 +51,12 @@ export function createLogger(logFile: string): Logger {
return { return {
authSuccess: (params) => write(authLine('AUTH_SUCCESS', params)), authSuccess: (params) => write(authLine('AUTH_SUCCESS', params)),
authFailure: (params) => write(authLine('AUTH_FAILURE', 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 }) => fileNotFound: ({ ip, userAgent, fileId }) =>
write(`[${timestamp()}] FILE_NOT_FOUND ip=${ip} user-agent="${userAgent}" file_id="${fileId}"`), write(`[${timestamp()}] FILE_NOT_FOUND ip=${ip} user-agent="${userAgent}" file_id="${fileId}"`),
}; };

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

@@ -0,0 +1,70 @@
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 type { LockoutService } from '../../../services/lockout.ts';
import { attemptLogin } from '../../../services/login-handler.ts';
import { requireAuth, tokenCookieOptions } from '../../../middleware/auth.ts';
interface Deps {
db: Database.Database;
config: Config;
logger: Logger;
lockout: LockoutService;
}
interface LoginBody {
username: string;
password: string;
}
export const authApiRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
const { config } = deps;
app.post<{ Body: LoginBody }>(
'/login',
{
config: {
rateLimit: {
max: config.loginRateLimitMax,
timeWindow: config.loginRateLimitWindowSeconds * 1000,
},
},
},
async (request, reply) => {
const { username, password } = request.body ?? {};
const result = await attemptLogin(deps, {
username: username ?? '',
password: password ?? '',
ip: request.ip,
userAgent: request.headers['user-agent'] ?? '',
});
if (result.kind === 'bad_request') {
return reply.status(400).send({ error: 'username and password are required' });
}
if (result.kind === 'locked') {
return reply
.status(401)
.header('Retry-After', String(result.retryAfterSeconds))
.send({ error: 'Invalid credentials' });
}
if (result.kind === 'bad_credentials') {
return reply.status(401).send({ error: 'Invalid credentials' });
}
const token = app.jwt.sign(
{ sub: result.user.id, username: result.user.username },
{ expiresIn: config.jwtExpiry },
);
reply.setCookie('token', token, tokenCookieOptions(config.cookieSecure)).send({ ok: true });
},
);
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
reply.clearCookie('token', { path: '/' }).send({ ok: true });
});
};

View File

@@ -0,0 +1,72 @@
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 rawExt = extname(data.filename);
const ext = /^\.[a-zA-Z0-9]+$/.test(rawExt) ? rawExt : '';
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 });
});
};

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

@@ -0,0 +1,234 @@
import type { FastifyPluginAsync } from 'fastify';
import { extname } from 'path';
import { createReadStream } from 'fs';
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 type { LockoutService } from '../services/lockout.ts';
import { createFile, getFileById, getFilesByUserId, deleteFile } from '../db/files.ts';
import { saveFile, deleteStoredFile, getFilePath } from '../services/storage.ts';
import { attemptLogin } from '../services/login-handler.ts';
import { requireAuth, tokenCookieOptions } from '../middleware/auth.ts';
import { loginPage } from '../views/login.ts';
import { uploadPage, uploadResultPage } from '../views/upload.ts';
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;
lockout: LockoutService;
}
function parseRangeHeader(header: string, fileSize: number): { start: number; end: number } | null {
const match = header.match(/^bytes=(\d*)-(\d*)$/);
if (!match) return null;
const [, rawStart, rawEnd] = match;
let start: number;
let end: number;
if (rawStart === '') {
// Suffix range: bytes=-N (last N bytes)
const suffix = parseInt(rawEnd, 10);
start = Math.max(0, fileSize - suffix);
end = fileSize - 1;
} else {
start = parseInt(rawStart, 10);
end = rawEnd === '' ? fileSize - 1 : parseInt(rawEnd, 10);
}
if (start > end || end >= fileSize) return null;
return { start, end };
}
export const pageRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
const { db, config, logger } = deps;
const loginRateLimit = {
rateLimit: {
max: config.loginRateLimitMax,
timeWindow: config.loginRateLimitWindowSeconds * 1000,
},
};
// GET / — login page or redirect if authed
app.get('/', async (request, reply) => {
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',
{ config: loginRateLimit },
async (request, reply) => {
const { username = '', password = '' } = request.body ?? {};
const result = await attemptLogin(deps, {
username,
password,
ip: request.ip,
userAgent: request.headers['user-agent'] ?? '',
});
if (result.kind === 'locked') {
return reply
.type('text/html')
.header('Retry-After', String(result.retryAfterSeconds))
.send(loginPage({ error: 'Invalid username or password' }));
}
if (result.kind !== 'success') {
return reply.type('text/html').send(loginPage({ error: 'Invalid username or password' }));
}
const token = app.jwt.sign(
{ sub: result.user.id, username: result.user.username },
{ expiresIn: config.jwtExpiry },
);
reply.setCookie('token', token, tokenCookieOptions(config.cookieSecure)).redirect('/upload');
},
);
// POST /logout
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
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 rawExt = extname(data.filename);
const ext = /^\.[a-zA-Z0-9]+$/.test(rawExt) ? rawExt : '';
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 (owner-aware)
app.get<{ Params: { id: string } }>('/f/:id', async (request, reply) => {
const { id } = request.params;
let userId: number | null = null;
try {
await request.jwtVerify();
userId = (request.user as JwtPayload).sub;
} catch { /* not logged in — fine */ }
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());
}
const isOwner = userId !== null && userId === file.user_id;
reply.type('text/html').send(fileViewPage(file, isOwner));
});
// GET /f/:id/raw — serve raw file with range request support
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 safeFilename = file.original_name.replace(/["\\\r\n]/g, '_');
reply
.header('Content-Type', file.mime_type)
.header('Content-Disposition', `inline; filename="${safeFilename}"`)
.header('Accept-Ranges', 'bytes');
const rangeHeader = request.headers['range'];
if (!rangeHeader) {
reply.header('Content-Length', file.size);
return reply.send(createReadStream(filePath));
}
const range = parseRangeHeader(rangeHeader, file.size);
if (!range) {
return reply
.status(416)
.header('Content-Range', `bytes */${file.size}`)
.send();
}
const { start, end } = range;
const chunkSize = end - start + 1;
return reply
.status(206)
.header('Content-Range', `bytes ${start}-${end}/${file.size}`)
.header('Content-Length', chunkSize)
.send(createReadStream(filePath, { start, end }));
});
// 404 handler
app.setNotFoundHandler((_request, reply) => {
reply.status(404).type('text/html').send(notFoundPage());
});
};

61
src/server.ts Normal file
View File

@@ -0,0 +1,61 @@
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 fastifyRateLimit from '@fastify/rate-limit';
import { join } from 'path';
import { fileURLToPath } from 'url';
import type Database from 'better-sqlite3';
import type { Config } from './config.ts';
import { createLogger } from './middleware/logging.ts';
import { createLockoutService } from './services/lockout.ts';
import { authApiRoutes } from './routes/api/v1/auth.ts';
import { filesApiRoutes } from './routes/api/v1/files.ts';
import { pageRoutes } from './routes/pages.ts';
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);
const lockout = createLockoutService({ db, config });
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/',
});
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, lockout };
app.register(authApiRoutes, { prefix: '/api/v1/auth', deps });
app.register(filesApiRoutes, { prefix: '/api/v1/files', deps });
app.register(pageRoutes, { prefix: '/', deps });
return app;
}

View 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
View 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);
},
};
}

View 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' };
}

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

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

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

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

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

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

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 });
}

95
tests/helpers/setup.ts Normal file
View File

@@ -0,0 +1,95 @@
import { mkdtempSync, rmSync, mkdirSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { initDb } from '../../src/db/schema.ts';
import { createServer } from '../../src/server.ts';
import type { Config } from '../../src/config.ts';
import type Database from 'better-sqlite3';
import type { FastifyInstance } from 'fastify';
export async function loginAs(app: FastifyInstance, username: string, password: string): Promise<string> {
const res = await app.inject({
method: 'POST',
url: '/api/v1/auth/login',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username, password }),
});
const cookie = res.headers['set-cookie'] as string;
return cookie.split(';')[0].replace('token=', '');
}
interface MultipartFile {
filename: string;
contentType: string;
data: Buffer;
}
export function buildMultipart(files: Record<string, MultipartFile>): { payload: Buffer; headers: Record<string, string> } {
const boundary = '----TestBoundary' + Math.random().toString(36).slice(2);
const parts: Buffer[] = [];
for (const [fieldname, file] of Object.entries(files)) {
parts.push(Buffer.from(
`--${boundary}\r\n` +
`Content-Disposition: form-data; name="${fieldname}"; filename="${file.filename}"\r\n` +
`Content-Type: ${file.contentType}\r\n\r\n`,
));
parts.push(file.data);
parts.push(Buffer.from('\r\n'));
}
parts.push(Buffer.from(`--${boundary}--\r\n`));
return {
payload: Buffer.concat(parts),
headers: { 'content-type': `multipart/form-data; boundary=${boundary}` },
};
}
export interface TestContext {
app: FastifyInstance;
db: Database.Database;
uploadDir: string;
logFile: string;
cleanup: () => void;
}
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');
mkdirSync(uploadDir, { recursive: true });
const db = initDb(':memory:');
const config: Config = {
port: 0,
host: '127.0.0.1',
jwtSecret: 'test-secret-key',
jwtExpiry: '1h',
dbPath: ':memory:',
uploadDir,
logFile,
maxFileSize: 10 * 1024 * 1024,
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 });
return {
app,
db,
uploadDir,
logFile,
cleanup: () => rmSync(tmpDir, { recursive: true, force: true }),
};
}

View File

@@ -0,0 +1,101 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createTestApp, type TestContext } from '../helpers/setup.ts';
import { createUser } from '../../src/db/users.ts';
import { hashPassword } from '../../src/services/auth.ts';
describe('POST /api/v1/auth/login', () => {
let ctx: TestContext;
beforeEach(async () => {
ctx = createTestApp();
const hash = await hashPassword('secret');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
});
afterEach(async () => {
await ctx.app.close();
ctx.cleanup();
});
it('returns 200 and sets cookie on valid credentials', 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.json()).toEqual({ ok: true });
expect(res.headers['set-cookie']).toMatch(/token=/);
});
it('returns 401 on wrong password', 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: 'wrong' }),
});
expect(res.statusCode).toBe(401);
});
it('returns 401 on unknown user', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: '/api/v1/auth/login',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'ghost', password: 'x' }),
});
expect(res.statusCode).toBe(401);
});
it('returns 400 when fields are missing', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: '/api/v1/auth/login',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'alice' }),
});
expect(res.statusCode).toBe(400);
});
});
describe('POST /api/v1/auth/logout', () => {
let ctx: TestContext;
let token: string;
beforeEach(async () => {
ctx = createTestApp();
const hash = await hashPassword('secret');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
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' }),
});
const cookie = res.headers['set-cookie'] as string;
token = cookie.split(';')[0].replace('token=', '');
});
afterEach(async () => {
await ctx.app.close();
ctx.cleanup();
});
it('clears cookie on logout', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: '/api/v1/auth/logout',
cookies: { token },
});
expect(res.statusCode).toBe(200);
expect(res.headers['set-cookie']).toMatch(/token=;/);
});
it('returns 401 without cookie', async () => {
const res = await ctx.app.inject({ method: 'POST', url: '/api/v1/auth/logout' });
expect(res.statusCode).toBe(401);
});
});

View 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();
});
});

View File

@@ -0,0 +1,71 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { readFileSync } from 'fs';
import { createTestApp, type TestContext } from '../helpers/setup.ts';
import { createUser } from '../../src/db/users.ts';
import { hashPassword } from '../../src/services/auth.ts';
describe('per-IP rate limit on login routes', () => {
let ctx: TestContext;
beforeEach(async () => {
ctx = createTestApp({
loginRateLimitMax: 3,
loginRateLimitWindowSeconds: 60,
lockoutThreshold: 100, // disable lockout for this suite
loginMinResponseMs: 0,
});
const hash = await hashPassword('correct-pw');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
});
afterEach(async () => {
await ctx.app.close();
ctx.cleanup();
});
async function loginRequest() {
return ctx.app.inject({
method: 'POST',
url: '/api/v1/auth/login',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'alice', password: 'wrong' }),
});
}
it('returns 429 once IP exceeds the per-route limit and logs AUTH_RATE_LIMITED', async () => {
expect((await loginRequest()).statusCode).toBe(401);
expect((await loginRequest()).statusCode).toBe(401);
expect((await loginRequest()).statusCode).toBe(401);
const fourth = await loginRequest();
expect(fourth.statusCode).toBe(429);
expect(fourth.json().error).toBe('Too many requests');
// Wait for fire-and-forget log write
await new Promise((r) => setTimeout(r, 50));
const log = readFileSync(ctx.logFile, 'utf-8');
expect(log).toMatch(/AUTH_RATE_LIMITED/);
expect(log).toMatch(/route="\/api\/v1\/auth\/login"/);
});
it('does NOT throttle the file upload endpoint', async () => {
// First, get a valid session
const loginRes = await ctx.app.inject({
method: 'POST',
url: '/api/v1/auth/login',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ username: 'alice', password: 'correct-pw' }),
});
expect(loginRes.statusCode).toBe(200);
const cookie = (loginRes.headers['set-cookie'] as string).split(';')[0].replace('token=', '');
// Now hit /upload (GET) repeatedly past the login-route limit threshold
for (let i = 0; i < 6; i++) {
const r = await ctx.app.inject({
method: 'GET',
url: '/upload',
cookies: { token: cookie },
});
expect(r.statusCode).toBe(200);
}
});
});

View File

@@ -0,0 +1,120 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createTestApp, type TestContext, loginAs, buildMultipart } from '../helpers/setup.ts';
import { createUser } from '../../src/db/users.ts';
import { hashPassword } from '../../src/services/auth.ts';
describe('GET /api/v1/files', () => {
let ctx: TestContext;
let token: string;
beforeEach(async () => {
ctx = createTestApp();
const hash = await hashPassword('secret');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
token = await loginAs(ctx.app, 'alice', 'secret');
});
afterEach(async () => {
await ctx.app.close();
ctx.cleanup();
});
it('returns empty list for new user', async () => {
const res = await ctx.app.inject({
method: 'GET',
url: '/api/v1/files',
cookies: { token },
});
expect(res.statusCode).toBe(200);
expect(res.json().files).toEqual([]);
});
it('returns 401 without auth', async () => {
const res = await ctx.app.inject({ method: 'GET', url: '/api/v1/files' });
expect(res.statusCode).toBe(401);
});
});
describe('POST /api/v1/files', () => {
let ctx: TestContext;
let token: string;
beforeEach(async () => {
ctx = createTestApp();
const hash = await hashPassword('secret');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
token = await loginAs(ctx.app, 'alice', 'secret');
});
afterEach(async () => {
await ctx.app.close();
ctx.cleanup();
});
it('uploads a file and returns url', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: '/api/v1/files',
cookies: { token },
...buildMultipart({ file: { filename: 'test.txt', contentType: 'text/plain', data: Buffer.from('hello') } }),
});
expect(res.statusCode).toBe(201);
const body = res.json();
expect(body.url).toMatch(/\/f\//);
expect(body.file.original_name).toBe('test.txt');
});
it('returns 401 without auth', async () => {
const res = await ctx.app.inject({ method: 'POST', url: '/api/v1/files' });
expect(res.statusCode).toBe(401);
});
});
describe('DELETE /api/v1/files/:id', () => {
let ctx: TestContext;
let token: string;
let fileId: string;
beforeEach(async () => {
ctx = createTestApp();
const hash = await hashPassword('secret');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
token = await loginAs(ctx.app, 'alice', 'secret');
const uploadRes = await ctx.app.inject({
method: 'POST',
url: '/api/v1/files',
cookies: { token },
...buildMultipart({ file: { filename: 'f.txt', contentType: 'text/plain', data: Buffer.from('data') } }),
});
fileId = uploadRes.json().file.id;
});
afterEach(async () => {
await ctx.app.close();
ctx.cleanup();
});
it('deletes an owned file', async () => {
const res = await ctx.app.inject({
method: 'DELETE',
url: `/api/v1/files/${fileId}`,
cookies: { token },
});
expect(res.statusCode).toBe(200);
});
it('returns 404 for non-existent file', async () => {
const res = await ctx.app.inject({
method: 'DELETE',
url: '/api/v1/files/doesnotexist',
cookies: { token },
});
expect(res.statusCode).toBe(404);
});
it('returns 401 without auth', async () => {
const res = await ctx.app.inject({ method: 'DELETE', url: `/api/v1/files/${fileId}` });
expect(res.statusCode).toBe(401);
});
});

View File

@@ -0,0 +1,308 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createTestApp, type TestContext, loginAs, buildMultipart } from '../helpers/setup.ts';
import { createUser } from '../../src/db/users.ts';
import { hashPassword } from '../../src/services/auth.ts';
async function setup() {
const ctx = createTestApp();
const hash = await hashPassword('secret');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
return ctx;
}
describe('GET /', () => {
let ctx: TestContext;
beforeEach(async () => { ctx = await setup(); });
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
it('shows login page when unauthenticated', async () => {
const res = await ctx.app.inject({ method: 'GET', url: '/' });
expect(res.statusCode).toBe(200);
expect(res.headers['content-type']).toMatch(/text\/html/);
expect(res.body).toContain('Sign in');
});
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 } });
expect(res.statusCode).toBe(302);
expect(res.headers['location']).toBe('/upload');
});
});
describe('POST /login (page)', () => {
let ctx: TestContext;
beforeEach(async () => { ctx = await setup(); });
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
it('redirects to /upload on valid credentials', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: '/login',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
payload: 'username=alice&password=secret',
});
expect(res.statusCode).toBe(302);
expect(res.headers['location']).toBe('/upload');
expect(res.headers['set-cookie']).toMatch(/token=/);
});
it('shows login page with error on invalid credentials', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: '/login',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
payload: 'username=alice&password=wrong',
});
expect(res.statusCode).toBe(200);
expect(res.body).toContain('Invalid');
});
});
describe('GET /upload + POST /upload', () => {
let ctx: TestContext;
let token: string;
beforeEach(async () => {
ctx = await setup();
token = await loginAs(ctx.app, 'alice', 'secret');
});
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 } });
expect(res.statusCode).toBe(200);
expect(res.body).toContain('Upload');
});
it('redirects to / when not authenticated', async () => {
const res = await ctx.app.inject({ method: 'GET', url: '/upload' });
expect(res.statusCode).toBe(302);
expect(res.headers['location']).toBe('/');
});
it('shows result page after upload', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: '/upload',
cookies: { token },
...buildMultipart({ file: { filename: 'doc.txt', contentType: 'text/plain', data: Buffer.from('content') } }),
});
expect(res.statusCode).toBe(200);
expect(res.body).toContain('doc.txt');
expect(res.body).toContain('/f/');
});
});
describe('GET /f/:id and GET /f/:id/raw', () => {
let ctx: TestContext;
let fileId: string;
beforeEach(async () => {
ctx = await setup();
const token = await loginAs(ctx.app, 'alice', 'secret');
const uploadRes = await ctx.app.inject({
method: 'POST',
url: '/upload',
cookies: { token },
...buildMultipart({ file: { filename: 'hello.txt', contentType: 'text/plain', data: Buffer.from('hello!') } }),
});
// Extract file id from response body
const match = uploadRes.body.match(/\/f\/([^/"]+)/);
fileId = match?.[1] ?? '';
});
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
it('shows file view page', async () => {
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}` });
expect(res.statusCode).toBe(200);
expect(res.body).toContain('hello.txt');
});
it('serves raw file', async () => {
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}/raw` });
expect(res.statusCode).toBe(200);
expect(res.body).toBe('hello!');
expect(res.headers['accept-ranges']).toBe('bytes');
});
it('returns 206 for a byte range request', async () => {
const res = await ctx.app.inject({
method: 'GET',
url: `/f/${fileId}/raw`,
headers: { range: 'bytes=0-3' },
});
expect(res.statusCode).toBe(206);
expect(res.headers['content-range']).toBe('bytes 0-3/6');
expect(res.headers['content-length']).toBe('4');
expect(res.body).toBe('hell');
});
it('returns 206 for an open-ended range request', async () => {
const res = await ctx.app.inject({
method: 'GET',
url: `/f/${fileId}/raw`,
headers: { range: 'bytes=2-' },
});
expect(res.statusCode).toBe(206);
expect(res.headers['content-range']).toBe('bytes 2-5/6');
expect(res.body).toBe('llo!');
});
it('returns 206 for a suffix range request', async () => {
const res = await ctx.app.inject({
method: 'GET',
url: `/f/${fileId}/raw`,
headers: { range: 'bytes=-3' },
});
expect(res.statusCode).toBe(206);
expect(res.headers['content-range']).toBe('bytes 3-5/6');
expect(res.body).toBe('lo!');
});
it('returns 416 for an unsatisfiable range', async () => {
const res = await ctx.app.inject({
method: 'GET',
url: `/f/${fileId}/raw`,
headers: { range: 'bytes=100-200' },
});
expect(res.statusCode).toBe(416);
expect(res.headers['content-range']).toBe('bytes */6');
});
it('returns 404 for unknown file', async () => {
const res = await ctx.app.inject({ method: 'GET', url: '/f/doesnotexist' });
expect(res.statusCode).toBe(404);
});
});
describe('GET /f/:id — image inline', () => {
let ctx: TestContext;
let fileId: string;
beforeEach(async () => {
ctx = await setup();
const token = await loginAs(ctx.app, 'alice', 'secret');
const uploadRes = await ctx.app.inject({
method: 'POST',
url: '/upload',
cookies: { token },
...buildMultipart({ file: { filename: 'photo.png', contentType: 'image/png', data: Buffer.from('fakepng') } }),
});
const match = uploadRes.body.match(/\/f\/([^/"]+)/);
fileId = match?.[1] ?? '';
});
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
it('shows <img> tag for image files', async () => {
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}` });
expect(res.statusCode).toBe(200);
expect(res.body).toContain('<img');
});
});
describe('GET /files — copy link', () => {
let ctx: TestContext;
let token: string;
beforeEach(async () => {
ctx = await setup();
token = await loginAs(ctx.app, 'alice', 'secret');
await ctx.app.inject({
method: 'POST',
url: '/upload',
cookies: { 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 } });
expect(res.statusCode).toBe(200);
expect(res.body).toContain('Copy link');
});
});
describe('GET /f/:id — owner-aware header', () => {
let ctx: TestContext;
let aliceToken: string;
let bobToken: string;
let fileId: string;
beforeEach(async () => {
ctx = createTestApp();
const hash = await hashPassword('secret');
createUser(ctx.db, { username: 'alice', passwordHash: hash });
createUser(ctx.db, { username: 'bob', passwordHash: hash });
aliceToken = await loginAs(ctx.app, 'alice', 'secret');
bobToken = await loginAs(ctx.app, 'bob', 'secret');
const uploadRes = await ctx.app.inject({
method: 'POST',
url: '/upload',
cookies: { token: aliceToken },
...buildMultipart({ file: { filename: 'owned.txt', contentType: 'text/plain', data: Buffer.from('data') } }),
});
const match = uploadRes.body.match(/\/f\/([^/"]+)/);
fileId = match?.[1] ?? '';
});
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 } });
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 } });
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 } });
expect(res.statusCode).toBe(200);
expect(res.body).not.toContain('<header');
});
it('no header when unauthenticated', async () => {
const res = await ctx.app.inject({ method: 'GET', url: `/f/${fileId}` });
expect(res.statusCode).toBe(200);
expect(res.body).not.toContain('<header');
});
});
describe('POST /files/:id/delete', () => {
let ctx: TestContext;
let token: string;
let fileId: string;
beforeEach(async () => {
ctx = await setup();
token = await loginAs(ctx.app, 'alice', 'secret');
const uploadRes = await ctx.app.inject({
method: 'POST',
url: '/upload',
cookies: { token },
...buildMultipart({ file: { filename: 'del.txt', contentType: 'text/plain', data: Buffer.from('bye') } }),
});
const match = uploadRes.body.match(/\/f\/([^/"]+)/);
fileId = match?.[1] ?? '';
});
afterEach(async () => { await ctx.app.close(); ctx.cleanup(); });
it('deletes and redirects to /files', async () => {
const res = await ctx.app.inject({
method: 'POST',
url: `/files/${fileId}/delete`,
cookies: { token },
});
expect(res.statusCode).toBe(302);
expect(res.headers['location']).toBe('/files');
});
});

View 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');
});
});

View File

@@ -23,6 +23,12 @@ describe('config', () => {
delete process.env.BASE_URL; delete process.env.BASE_URL;
delete process.env.COOKIE_SECURE; delete process.env.COOKIE_SECURE;
delete process.env.TRUST_PROXY; 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 { loadConfig } = await import('../../src/config.ts');
const config = loadConfig(); const config = loadConfig();
@@ -37,6 +43,12 @@ describe('config', () => {
expect(config.baseUrl).toBe('http://localhost:3000'); expect(config.baseUrl).toBe('http://localhost:3000');
expect(config.cookieSecure).toBe(false); expect(config.cookieSecure).toBe(false);
expect(config.trustProxy).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 () => { it('reads values from env vars', async () => {
@@ -60,6 +72,26 @@ describe('config', () => {
expect(config.maxFileSize).toBe(52428800); 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 () => { it('throws when JWT_SECRET is missing', async () => {
delete process.env.JWT_SECRET; delete process.env.JWT_SECRET;
const { loadConfig } = await import('../../src/config.ts'); const { loadConfig } = await import('../../src/config.ts');

View 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);
});

View File

@@ -0,0 +1,127 @@
import { describe, it, expect, beforeEach } from 'vitest';
import type Database from 'better-sqlite3';
import { initDb } from '../../src/db/schema.ts';
import type { Config } from '../../src/config.ts';
import { createLockoutService } from '../../src/services/lockout.ts';
import { recordFailure as dbRecordFailure } from '../../src/db/login-attempts.ts';
function makeConfig(overrides: Partial<Config> = {}): Config {
return {
port: 0,
host: '127.0.0.1',
jwtSecret: 'x',
jwtExpiry: '1h',
dbPath: ':memory:',
uploadDir: '/tmp',
logFile: '/tmp/x.log',
maxFileSize: 0,
baseUrl: '',
cookieSecure: false,
trustProxy: false,
lockoutThreshold: 3,
lockoutBaseSeconds: 10,
lockoutMaxSeconds: 80,
loginMinResponseMs: 0,
loginRateLimitMax: 0,
loginRateLimitWindowSeconds: 0,
...overrides,
};
}
describe('lockout service', () => {
let db: Database.Database;
let nowMs: number;
const now = (): Date => new Date(nowMs);
beforeEach(() => {
db = initDb(':memory:');
nowMs = Date.UTC(2026, 0, 1, 0, 0, 0);
});
describe('check', () => {
it('returns not-locked when no row exists', () => {
const svc = createLockoutService({ db, config: makeConfig(), now });
expect(svc.check('alice')).toEqual({ locked: false });
});
it('returns not-locked when locked_until is in the past', () => {
const past = new Date(nowMs - 1000).toISOString();
dbRecordFailure(db, 'alice', past);
const svc = createLockoutService({ db, config: makeConfig(), now });
expect(svc.check('alice')).toEqual({ locked: false });
});
it('returns locked with retry-after seconds when locked_until is in the future', () => {
const future = new Date(nowMs + 30_000).toISOString();
dbRecordFailure(db, 'alice', future);
const svc = createLockoutService({ db, config: makeConfig(), now });
expect(svc.check('alice')).toEqual({ locked: true, retryAfterSeconds: 30 });
});
it('rounds up sub-second remainder so retry-after is never 0', () => {
const future = new Date(nowMs + 100).toISOString();
dbRecordFailure(db, 'alice', future);
const svc = createLockoutService({ db, config: makeConfig(), now });
expect(svc.check('alice').retryAfterSeconds).toBe(1);
});
});
describe('recordFailure', () => {
it('does not lock under threshold', () => {
const svc = createLockoutService({ db, config: makeConfig(), now });
const r1 = svc.recordFailure('alice');
expect(r1).toEqual({ locked: false, durationSeconds: 0, failedCount: 1 });
const r2 = svc.recordFailure('alice');
expect(r2).toEqual({ locked: false, durationSeconds: 0, failedCount: 2 });
});
it('locks with base duration at threshold', () => {
const svc = createLockoutService({ db, config: makeConfig(), now });
svc.recordFailure('alice');
svc.recordFailure('alice');
const r3 = svc.recordFailure('alice');
expect(r3.locked).toBe(true);
expect(r3.durationSeconds).toBe(10);
expect(r3.failedCount).toBe(3);
});
it('doubles duration past threshold', () => {
const svc = createLockoutService({ db, config: makeConfig(), now });
svc.recordFailure('alice'); // 1
svc.recordFailure('alice'); // 2
expect(svc.recordFailure('alice').durationSeconds).toBe(10); // 3 -> base
expect(svc.recordFailure('alice').durationSeconds).toBe(20); // 4
expect(svc.recordFailure('alice').durationSeconds).toBe(40); // 5
expect(svc.recordFailure('alice').durationSeconds).toBe(80); // 6 -> cap
expect(svc.recordFailure('alice').durationSeconds).toBe(80); // 7 -> still cap
});
it('persists locked_until reachable via check', () => {
const svc = createLockoutService({ db, config: makeConfig(), now });
svc.recordFailure('alice');
svc.recordFailure('alice');
svc.recordFailure('alice');
const status = svc.check('alice');
expect(status.locked).toBe(true);
expect(status.retryAfterSeconds).toBe(10);
});
});
describe('recordSuccess', () => {
it('clears the attempt row', () => {
const svc = createLockoutService({ db, config: makeConfig(), now });
svc.recordFailure('alice');
svc.recordFailure('alice');
svc.recordSuccess('alice');
// Next failure starts at 1, no lock
const r = svc.recordFailure('alice');
expect(r.failedCount).toBe(1);
expect(r.locked).toBe(false);
});
it('is a no-op for unknown username', () => {
const svc = createLockoutService({ db, config: makeConfig(), now });
expect(() => svc.recordSuccess('ghost')).not.toThrow();
});
});
});

View File

@@ -50,6 +50,48 @@ describe('middleware/logging', () => {
expect(existsSync(logFile)).toBe(true); 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 () => { it('appends multiple entries', async () => {
const logger = createLogger(logFile); const logger = createLogger(logFile);
await logger.authSuccess({ ip: '1.1.1.1', userAgent: 'a', username: 'u1' }); await logger.authSuccess({ ip: '1.1.1.1', userAgent: 'a', username: 'u1' });

View 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);
});
});

View File

@@ -0,0 +1,212 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { mkdtempSync, rmSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import type Database from 'better-sqlite3';
import { initDb } from '../../src/db/schema.ts';
import { createUser } from '../../src/db/users.ts';
import { hashPassword } from '../../src/services/auth.ts';
import { createLogger } from '../../src/middleware/logging.ts';
import { createLockoutService } from '../../src/services/lockout.ts';
import { attemptLogin } from '../../src/services/login-handler.ts';
import { _resetDummyHashForTests } from '../../src/services/dummy-hash.ts';
import type { Config } from '../../src/config.ts';
function makeConfig(overrides: Partial<Config> = {}): Config {
return {
port: 0,
host: '127.0.0.1',
jwtSecret: 'x',
jwtExpiry: '1h',
dbPath: ':memory:',
uploadDir: '/tmp',
logFile: '/tmp/x.log',
maxFileSize: 0,
baseUrl: '',
cookieSecure: false,
trustProxy: false,
lockoutThreshold: 2,
lockoutBaseSeconds: 60,
lockoutMaxSeconds: 600,
loginMinResponseMs: 50,
loginRateLimitMax: 0,
loginRateLimitWindowSeconds: 0,
...overrides,
};
}
describe('login handler', () => {
let db: Database.Database;
let logDir: string;
let logFile: string;
let config: Config;
beforeEach(async () => {
_resetDummyHashForTests();
db = initDb(':memory:');
logDir = mkdtempSync(join(tmpdir(), 'nanodrop-handler-'));
logFile = join(logDir, 'test.log');
config = makeConfig({ logFile });
const passwordHash = await hashPassword('correct-pw');
createUser(db, { username: 'alice', passwordHash });
// Warm dummy hash so timing assertions don't include the first cold compute.
const { verifyAgainstDummy } = await import('../../src/services/dummy-hash.ts');
await verifyAgainstDummy('warmup');
});
function buildDeps() {
const logger = createLogger(logFile);
const lockout = createLockoutService({ db, config });
return { db, config, logger, lockout };
}
it('returns success for valid credentials and resets lockout', async () => {
const deps = buildDeps();
const result = await attemptLogin(deps, {
username: 'alice',
password: 'correct-pw',
ip: '1.1.1.1',
userAgent: 'ua',
});
expect(result.kind).toBe('success');
if (result.kind === 'success') {
expect(result.user.username).toBe('alice');
}
const log = readFileSync(logFile, 'utf-8');
expect(log).toMatch(/AUTH_SUCCESS/);
});
it('returns bad_credentials and logs failure on wrong password', async () => {
const deps = buildDeps();
const result = await attemptLogin(deps, {
username: 'alice',
password: 'wrong',
ip: '1.1.1.1',
userAgent: 'ua',
});
expect(result.kind).toBe('bad_credentials');
const log = readFileSync(logFile, 'utf-8');
expect(log).toMatch(/AUTH_FAILURE/);
expect(log).toMatch(/username="alice"/);
});
it('returns bad_credentials for unknown user (still runs bcrypt against dummy)', async () => {
const deps = buildDeps();
const start = Date.now();
const result = await attemptLogin(deps, {
username: 'ghost',
password: 'whatever',
ip: '1.1.1.1',
userAgent: 'ua',
});
const elapsed = Date.now() - start;
expect(result.kind).toBe('bad_credentials');
// Must spend bcrypt-comparable time even for unknown user.
expect(elapsed).toBeGreaterThan(20);
const log = readFileSync(logFile, 'utf-8');
expect(log).toMatch(/AUTH_FAILURE/);
expect(log).toMatch(/username="ghost"/);
}, 10_000);
it('canonicalizes username (lowercase + trim) before lookup and lockout', async () => {
const deps = buildDeps();
const result = await attemptLogin(deps, {
username: ' ALICE ',
password: 'correct-pw',
ip: '1.1.1.1',
userAgent: 'ua',
});
expect(result.kind).toBe('success');
});
it('returns bad_request when username or password is empty', async () => {
const deps = buildDeps();
const r1 = await attemptLogin(deps, { username: '', password: 'x', ip: '1', userAgent: 'ua' });
expect(r1.kind).toBe('bad_request');
const r2 = await attemptLogin(deps, { username: 'alice', password: '', ip: '1', userAgent: 'ua' });
expect(r2.kind).toBe('bad_request');
});
it('triggers lockout at threshold and logs AUTH_LOCKOUT_TRIGGERED', async () => {
const deps = buildDeps();
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
const second = await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
expect(second.kind).toBe('bad_credentials');
const log = readFileSync(logFile, 'utf-8');
expect(log).toMatch(/AUTH_LOCKOUT_TRIGGERED/);
expect(log).toMatch(/duration_seconds=60/);
});
it('returns locked + retry-after on subsequent attempt; correct password still rejected', async () => {
const deps = buildDeps();
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1.1.1.1', userAgent: 'ua' });
const blocked = await attemptLogin(deps, {
username: 'alice',
password: 'correct-pw',
ip: '1.1.1.1',
userAgent: 'ua',
});
expect(blocked.kind).toBe('locked');
if (blocked.kind === 'locked') {
expect(blocked.retryAfterSeconds).toBeGreaterThan(0);
expect(blocked.retryAfterSeconds).toBeLessThanOrEqual(60);
}
const log = readFileSync(logFile, 'utf-8');
expect(log).toMatch(/AUTH_LOCKED_ATTEMPT/);
// Even though password was correct, no AUTH_SUCCESS for this attempt.
const successCount = (log.match(/AUTH_SUCCESS/g) ?? []).length;
expect(successCount).toBe(0);
});
it('does NOT call bcrypt when account is locked (short-circuits)', async () => {
const deps = buildDeps();
// Lock the account.
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
// Locked attempt with constant-time clamp at 50ms — should be roughly clamp duration,
// not bcrypt time (250ms+).
const start = Date.now();
await attemptLogin(deps, { username: 'alice', password: 'correct-pw', ip: '1', userAgent: 'ua' });
const elapsed = Date.now() - start;
// Clamp is 50ms; allow generous slack but assert well under bcrypt cost.
expect(elapsed).toBeLessThan(150);
});
it('respects loginMinResponseMs clamp on bad_credentials', async () => {
config = makeConfig({ logFile, loginMinResponseMs: 200 });
const deps = buildDeps();
const start = Date.now();
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
const elapsed = Date.now() - start;
expect(elapsed).toBeGreaterThanOrEqual(190);
}, 10_000);
it('successful login between failures resets the counter', async () => {
const deps = buildDeps();
await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
await attemptLogin(deps, { username: 'alice', password: 'correct-pw', ip: '1', userAgent: 'ua' });
const r = await attemptLogin(deps, { username: 'alice', password: 'wrong', ip: '1', userAgent: 'ua' });
// After reset, this is failure #1 — well under threshold of 2, so no lock yet.
expect(r.kind).toBe('bad_credentials');
// No AUTH_LOCKOUT_TRIGGERED in log.
const log = readFileSync(logFile, 'utf-8');
expect(log).not.toMatch(/AUTH_LOCKOUT_TRIGGERED/);
});
it('unknown username also accumulates lockout', async () => {
const deps = buildDeps();
await attemptLogin(deps, { username: 'ghost', password: 'x', ip: '1', userAgent: 'ua' });
await attemptLogin(deps, { username: 'ghost', password: 'x', ip: '1', userAgent: 'ua' });
const r = await attemptLogin(deps, { username: 'ghost', password: 'x', ip: '1', userAgent: 'ua' });
expect(r.kind).toBe('locked');
}, 10_000);
// Cleanup
beforeEach(() => {
return () => rmSync(logDir, { recursive: true, force: true });
});
});

View File

@@ -3,16 +3,13 @@
"target": "ES2022", "target": "ES2022",
"module": "NodeNext", "module": "NodeNext",
"moduleResolution": "NodeNext", "moduleResolution": "NodeNext",
"outDir": "dist", "allowImportingTsExtensions": true,
"rootDir": "src", "noEmit": true,
"strict": true, "strict": true,
"esModuleInterop": true, "esModuleInterop": true,
"skipLibCheck": true, "skipLibCheck": true,
"forceConsistentCasingInFileNames": true, "forceConsistentCasingInFileNames": true,
"resolveJsonModule": true, "resolveJsonModule": true
"declaration": true,
"declarationMap": true,
"sourceMap": true
}, },
"include": ["src/**/*"], "include": ["src/**/*"],
"exclude": ["node_modules", "dist", "tests"] "exclude": ["node_modules", "dist", "tests"]