Compare commits
20 Commits
157d1e8230
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 418a553429 | |||
| e25c715fb7 | |||
| 9fefe5c65d | |||
| e2944fd828 | |||
| a4e6a5784a | |||
| 241078316c | |||
| 85b6f8df2c | |||
| 00ab308280 | |||
| d616d4e067 | |||
| 82793c6d0d | |||
| 8b27038793 | |||
| 191f5298d1 | |||
| c017761bd1 | |||
| c9e2d36e78 | |||
| 5a47ae938e | |||
| b5ea21d44c | |||
| 751862a486 | |||
| 8d5e5c8a4d | |||
| 6d8fb9105d | |||
| 8fd1464b9d |
11
.env.example
Normal file
11
.env.example
Normal 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
48
.github/workflows/deploy-homelab.yml
vendored
Normal 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
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ 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.
|
||||||
|
|||||||
19
Dockerfile
Normal file
19
Dockerfile
Normal 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
168
README.md
Normal 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
33
docker-compose.yml
Normal 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:
|
||||||
@@ -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",
|
||||||
|
|||||||
418
public/style.css
Normal file
418
public/style.css
Normal file
@@ -0,0 +1,418 @@
|
|||||||
|
@import url('https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,400;0,500;0,600;1,400&display=swap');
|
||||||
|
|
||||||
|
/* ── Reset ──────────────────────────────────────────────── */
|
||||||
|
*, *::before, *::after {
|
||||||
|
box-sizing: border-box;
|
||||||
|
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: 'IBM Plex Mono', 'Courier New', monospace;
|
||||||
|
--border: 1px solid var(--black);
|
||||||
|
--radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ── Base ───────────────────────────────────────────────── */
|
||||||
|
html { font-size: 14px; }
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: var(--font);
|
||||||
|
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;
|
||||||
|
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
33
src/cli/register-user.ts
Normal 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.`);
|
||||||
@@ -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;
|
||||||
|
|||||||
@@ -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
20
src/index.ts
Normal 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
24
src/middleware/auth.ts
Normal 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: '/' };
|
||||||
|
}
|
||||||
49
src/routes/api/v1/auth.ts
Normal file
49
src/routes/api/v1/auth.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import type { FastifyPluginAsync } from 'fastify';
|
||||||
|
import type Database from 'better-sqlite3';
|
||||||
|
import type { Config } from '../../../config.ts';
|
||||||
|
import type { Logger } from '../../../middleware/logging.ts';
|
||||||
|
import { getUserByUsername } from '../../../db/users.ts';
|
||||||
|
import { verifyPassword } from '../../../services/auth.ts';
|
||||||
|
import { requireAuth, tokenCookieOptions } from '../../../middleware/auth.ts';
|
||||||
|
|
||||||
|
interface Deps {
|
||||||
|
db: Database.Database;
|
||||||
|
config: Config;
|
||||||
|
logger: Logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LoginBody {
|
||||||
|
username: string;
|
||||||
|
password: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authApiRoutes: FastifyPluginAsync<{ deps: Deps }> = async (app, { deps }) => {
|
||||||
|
const { db, config, logger } = deps;
|
||||||
|
|
||||||
|
app.post<{ Body: LoginBody }>('/login', async (request, reply) => {
|
||||||
|
const { username, password } = request.body ?? {};
|
||||||
|
const ip = request.ip;
|
||||||
|
const userAgent = request.headers['user-agent'] ?? '';
|
||||||
|
|
||||||
|
if (!username || !password) {
|
||||||
|
return reply.status(400).send({ error: 'username and password are required' });
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = getUserByUsername(db, username);
|
||||||
|
const valid = user ? await verifyPassword(password, user.password_hash) : false;
|
||||||
|
|
||||||
|
if (!user || !valid) {
|
||||||
|
await logger.authFailure({ ip, userAgent, username });
|
||||||
|
return reply.status(401).send({ error: 'Invalid credentials' });
|
||||||
|
}
|
||||||
|
|
||||||
|
await logger.authSuccess({ ip, userAgent, username });
|
||||||
|
|
||||||
|
const token = app.jwt.sign({ sub: user.id, username: user.username }, { expiresIn: config.jwtExpiry });
|
||||||
|
reply.setCookie('token', token, tokenCookieOptions(config.cookieSecure)).send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/logout', { preHandler: requireAuth }, async (_request, reply) => {
|
||||||
|
reply.clearCookie('token', { path: '/' }).send({ ok: true });
|
||||||
|
});
|
||||||
|
};
|
||||||
72
src/routes/api/v1/files.ts
Normal file
72
src/routes/api/v1/files.ts
Normal 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 });
|
||||||
|
});
|
||||||
|
};
|
||||||
214
src/routes/pages.ts
Normal file
214
src/routes/pages.ts
Normal file
@@ -0,0 +1,214 @@
|
|||||||
|
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 { getUserByUsername } from '../db/users.ts';
|
||||||
|
import { createFile, getFileById, getFilesByUserId, deleteFile } from '../db/files.ts';
|
||||||
|
import { verifyPassword } from '../services/auth.ts';
|
||||||
|
import { saveFile, deleteStoredFile, getFilePath } from '../services/storage.ts';
|
||||||
|
import { requireAuth, 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
// GET / — login page or redirect if authed
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
try {
|
||||||
|
await request.jwtVerify();
|
||||||
|
return reply.redirect('/upload');
|
||||||
|
} catch {
|
||||||
|
return reply.type('text/html').send(loginPage());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// POST /login — form login
|
||||||
|
app.post<{ Body: { username?: string; password?: string } }>('/login', async (request, reply) => {
|
||||||
|
const { username = '', password = '' } = request.body ?? {};
|
||||||
|
const ip = request.ip;
|
||||||
|
const userAgent = request.headers['user-agent'] ?? '';
|
||||||
|
|
||||||
|
const user = getUserByUsername(db, username);
|
||||||
|
const valid = user ? await verifyPassword(password, user.password_hash) : false;
|
||||||
|
|
||||||
|
if (!user || !valid) {
|
||||||
|
await logger.authFailure({ ip, userAgent, username });
|
||||||
|
return reply.type('text/html').send(loginPage({ error: 'Invalid username or password' }));
|
||||||
|
}
|
||||||
|
|
||||||
|
await logger.authSuccess({ ip, userAgent, username });
|
||||||
|
|
||||||
|
const token = app.jwt.sign({ sub: user.id, username: user.username }, { expiresIn: config.jwtExpiry });
|
||||||
|
reply.setCookie('token', token, 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());
|
||||||
|
});
|
||||||
|
};
|
||||||
46
src/server.ts
Normal file
46
src/server.ts
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
import Fastify from 'fastify';
|
||||||
|
import fastifyCookie from '@fastify/cookie';
|
||||||
|
import fastifyJwt from '@fastify/jwt';
|
||||||
|
import fastifyMultipart from '@fastify/multipart';
|
||||||
|
import fastifyFormbody from '@fastify/formbody';
|
||||||
|
import fastifyStatic from '@fastify/static';
|
||||||
|
import { join } from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
import type Database from 'better-sqlite3';
|
||||||
|
import type { Config } from './config.ts';
|
||||||
|
import { createLogger } from './middleware/logging.ts';
|
||||||
|
import { authApiRoutes } from './routes/api/v1/auth.ts';
|
||||||
|
import { filesApiRoutes } from './routes/api/v1/files.ts';
|
||||||
|
import { pageRoutes } from './routes/pages.ts';
|
||||||
|
|
||||||
|
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||||
|
|
||||||
|
interface ServerDeps {
|
||||||
|
config: Config;
|
||||||
|
db: Database.Database;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createServer({ config, db }: ServerDeps) {
|
||||||
|
const app = Fastify({ logger: false, trustProxy: config.trustProxy });
|
||||||
|
const logger = createLogger(config.logFile);
|
||||||
|
|
||||||
|
app.register(fastifyCookie);
|
||||||
|
app.register(fastifyJwt, {
|
||||||
|
secret: config.jwtSecret,
|
||||||
|
cookie: { cookieName: 'token', signed: false },
|
||||||
|
});
|
||||||
|
app.register(fastifyFormbody);
|
||||||
|
app.register(fastifyMultipart, { limits: { fileSize: config.maxFileSize } });
|
||||||
|
app.register(fastifyStatic, {
|
||||||
|
root: join(__dirname, '..', 'public'),
|
||||||
|
prefix: '/public/',
|
||||||
|
});
|
||||||
|
|
||||||
|
const deps = { db, config, logger };
|
||||||
|
|
||||||
|
app.register(authApiRoutes, { prefix: '/api/v1/auth', deps });
|
||||||
|
app.register(filesApiRoutes, { prefix: '/api/v1/files', deps });
|
||||||
|
app.register(pageRoutes, { prefix: '/', deps });
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
42
src/views/file-list.ts
Normal file
42
src/views/file-list.ts
Normal 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
38
src/views/file-view.ts
Normal 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
44
src/views/layout.ts
Normal 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, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
.replace(/'/g, ''');
|
||||||
|
}
|
||||||
25
src/views/login.ts
Normal file
25
src/views/login.ts
Normal 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
11
src/views/not-found.ts
Normal 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
36
src/views/upload.ts
Normal 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> · <a href="/files">My files</a></p>
|
||||||
|
</div>
|
||||||
|
`, { authed: true });
|
||||||
|
}
|
||||||
88
tests/helpers/setup.ts
Normal file
88
tests/helpers/setup.ts
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
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(): 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,
|
||||||
|
};
|
||||||
|
|
||||||
|
const app = createServer({ config, db });
|
||||||
|
|
||||||
|
return {
|
||||||
|
app,
|
||||||
|
db,
|
||||||
|
uploadDir,
|
||||||
|
logFile,
|
||||||
|
cleanup: () => rmSync(tmpDir, { recursive: true, force: true }),
|
||||||
|
};
|
||||||
|
}
|
||||||
101
tests/integration/auth-api.test.ts
Normal file
101
tests/integration/auth-api.test.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
120
tests/integration/files-api.test.ts
Normal file
120
tests/integration/files-api.test.ts
Normal 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);
|
||||||
|
});
|
||||||
|
});
|
||||||
308
tests/integration/pages.test.ts
Normal file
308
tests/integration/pages.test.ts
Normal 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');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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"]
|
||||||
|
|||||||
Reference in New Issue
Block a user