Skip to content

Commit a43d2de

Browse files
Harden security and reliability; add rename/move, health, README cleanup
Security: - Login: per-IP rate limit plus per-account exponential lockout (Throttle table), with a shared, unit-tested backoff schedule. - Quick-Upload: per-IP rate limit plus a per-(code, IP) ban after repeated wrong passwords, tuned not to punish an honest guest's occasional typo. - Strict Content-Security-Policy and security headers on the web app. Reliability: - Remote-Upload worker: capped retries with exponential backoff, permanent vs transient error classification, a transfer timeout that aborts a stalled body, and recovery of jobs whose RUNNING lease expired after a crash. - Maintenance loop: usage reconciliation (heals usedBytes drift), orphan-blob GC with a grace period, and audit/job/throttle retention. Admin can trigger a pass via POST /admin/maintenance. Observability: - /ready readiness probe (DB + storage) and authenticated /status; the web shows a banner warning signed-in users about degraded components (e.g. antivirus offline). Features: - Rename and move for files and folders (PATCH /files/:id, /folders/:id) with cycle protection; wired into the Drive UI. Testing: - Integration-test harness (Fastify inject against a real Postgres) covering login lockout, CSRF, encrypted upload/download/rename/move/delete, quota, folder cycle protection, health and maintenance reconciliation. CI gains a Postgres service. Docs/UX: de-emojified, more sober README; threat model updated; new env documented.
1 parent 8986c85 commit a43d2de

36 files changed

Lines changed: 1397 additions & 196 deletions

‎.env.example‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,19 @@ DEFAULT_USER_QUOTA_BYTES=10737418240
4949
# Maximum size for a single Remote-Upload download, in bytes (2 GiB).
5050
REMOTE_UPLOAD_MAX_BYTES=2147483648
5151

52+
# ── Rate limiting & maintenance ──────────────────────────────────────────────
53+
# Per-IP rate limiting (login/quick endpoints get stricter limits on top).
54+
RATE_LIMIT_ENABLED=true
55+
# Audit-log entries older than this are pruned by the maintenance pass.
56+
AUDIT_RETENTION_DAYS=90
57+
# Finished Remote-Upload jobs older than this are pruned.
58+
JOB_RETENTION_DAYS=30
59+
# A storage blob with no database row is deleted only once older than this (protects
60+
# in-flight uploads from the orphan garbage collector).
61+
ORPHAN_GRACE_HOURS=24
62+
# How often the maintenance pass (reconcile usage, GC orphans, prune logs) runs.
63+
MAINTENANCE_INTERVAL_HOURS=24
64+
5265
# ── Antivirus (ClamAV) — optional ───────────────────────────────────────────
5366
# If unreachable, uploads are accepted and marked SKIPPED rather than blocked.
5467
CLAMAV_ENABLED=true

‎.github/workflows/ci.yml‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,22 @@ jobs:
1313
build-test:
1414
name: Lint · Typecheck · Test · Build
1515
runs-on: ubuntu-latest
16+
services:
17+
postgres:
18+
image: postgres:16-alpine
19+
env:
20+
POSTGRES_USER: ocl
21+
POSTGRES_PASSWORD: ocl
22+
POSTGRES_DB: ocl_test
23+
ports:
24+
- 5432:5432
25+
options: >-
26+
--health-cmd "pg_isready -U ocl"
27+
--health-interval 5s
28+
--health-timeout 5s
29+
--health-retries 10
30+
env:
31+
DATABASE_URL: postgresql://ocl:ocl@localhost:5432/ocl_test
1632
steps:
1733
- uses: actions/checkout@v4
1834

@@ -40,7 +56,7 @@ jobs:
4056
- name: Lint
4157
run: pnpm -r lint
4258

43-
- name: Test
59+
- name: Test (unit + integration)
4460
run: pnpm -r test
4561

4662
- name: Build (web + api)

‎README.md‎

Lines changed: 63 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -1,139 +1,104 @@
1-
<div align="center">
1+
# OpenCoperLock
22

3-
# 🔐 OpenCoperLock
3+
A self-hostable private cloud for a single dedicated machine. It combines an ordinary
4+
file Drive with three things most "drop a file" tools lack: a code-gated Quick-Upload for
5+
any device, a server-side Remote-Upload from a link, and a hybrid encryption model that
6+
lets you choose, per folder, between server-side encryption at rest (scannable) and a true
7+
client-side zero-knowledge vault.
48

5-
**A self-hostable private cloud — a clean Drive plus advanced acquisition & security tooling.**
9+
Licensed under the GNU AGPLv3. If you host a modified version, your users are entitled to
10+
the source.
611

7-
[![License: AGPL v3](https://img.shields.io/badge/License-AGPL_v3-blue.svg)](./LICENSE)
8-
[![CI](https://github.com/softpython2884/opencoperlock/actions/workflows/ci.yml/badge.svg)](https://github.com/softpython2884/opencoperlock/actions/workflows/ci.yml)
9-
[![TypeScript](https://img.shields.io/badge/TypeScript-strict-3178c6.svg)](https://www.typescriptlang.org/)
12+
## What it does
1013

11-
</div>
14+
- **Drive** — browse, upload (streaming), download and delete files and folders, with a
15+
per-user storage quota and a deployment-wide cap.
16+
- **Quick-Upload** — open a temporary drop zone on any device by entering an active code,
17+
no full login required. Optional password, expiry and usage limit per code.
18+
- **Remote-Upload** — paste a link and the server fetches the file directly, so a phone on
19+
a metered connection never has to relay the bytes. SSRF-guarded.
20+
- **Antivirus** — files are scanned with ClamAV on upload; an optional VirusTotal hash
21+
lookup is available on demand. Infected files are quarantined.
22+
- **Hybrid encryption** — AES-256-GCM at rest by default (so files can be scanned), plus an
23+
opt-in zero-knowledge vault whose contents are encrypted in the browser and never
24+
readable by the server.
25+
- **Administration** — create users, set per-user quotas, define the global cap, manage
26+
Quick-Upload codes and read the audit log.
1227

13-
OpenCoperLock is an ultra-light, secure private cloud you run on your own dedicated
14-
machine or VM. It pairs a classic file **Drive** with three things most "drop a file"
15-
tools lack: a **nomadic Quick-Upload by code**, a **server-side Remote-Upload from a
16-
link**, and a **hybrid encryption** model that lets you choose between server-side
17-
encryption-at-rest (scannable) and a true client-side **Zero-Knowledge Vault**.
28+
## Architecture
1829

19-
> Built to be read, audited, and forked. AGPLv3 — if you host a modified version, your
20-
> users get the source.
21-
22-
---
23-
24-
## ✨ Features
25-
26-
| | Feature | What it does |
27-
|---|---|---|
28-
| 📁 | **Drive** | Browse, upload (streaming), download and delete files & folders. Per-user quota and a global storage cap. Minimalist UI, no heavy animations. |
29-
| ⚡ | **Quick-Upload by code** | Open a temporary drop zone on any device (phone, third-party PC) by entering an active code — no full login. |
30-
| 🌐 | **Remote-Upload** | Paste a link; the **server** downloads the file directly so your mobile connection (4G/5G) is never saturated. SSRF-guarded. |
31-
| 🛡️ | **Antivirus + VirusTotal** | Files are scanned with ClamAV on upload; optionally checked against the VirusTotal API. Infected files are quarantined. |
32-
| 🔒 | **Hybrid encryption** | Server-side AES-256-GCM at rest by default (so files can be scanned), **plus** an opt-in **Zero-Knowledge Vault** where files are encrypted in your browser and the server stays blind. |
33-
| 👤 | **Admin panel** | Create users, set per-user storage quotas, define the global storage cap, manage Quick-Upload codes, and read the audit log. |
34-
35-
---
36-
37-
## 🏗️ Architecture
38-
39-
A TypeScript monorepo (pnpm workspaces):
30+
A TypeScript monorepo managed with pnpm workspaces:
4031

4132
```
42-
opencoperlock/
43-
├─ apps/
44-
│ ├─ web/ # Next.js (App Router) — minimalist UI
45-
│ └─ api/ # Fastify API + background worker
46-
├─ packages/
47-
│ └─ shared/ # zod schemas, shared types, crypto helpers
48-
├─ infra/ # docker-compose, Dockerfiles, clamav config
49-
└─ docs/ # ARCHITECTURE, SECURITY, THREAT_MODEL, DEPLOYMENT
33+
apps/web Next.js (App Router) front end
34+
apps/api Fastify API + the Remote-Upload worker
35+
packages/shared zod schemas, shared types, server crypto, the SSRF guard, quota math
36+
infra Dockerfiles, docker-compose, ClamAV config
37+
docs architecture, security, threat model, deployment
5038
```
5139

52-
- **API**: Fastify + Prisma + PostgreSQL. Background jobs run on a DB-backed worker loop
53-
(no Redis required — Redis/BullMQ is an optional upgrade).
54-
- **Storage**: pluggable driver; ships with a local-filesystem driver, ready for S3-compatible later.
55-
- **Encryption**: see [`docs/SECURITY.md`](./docs/SECURITY.md) and [`docs/THREAT_MODEL.md`](./docs/THREAT_MODEL.md).
40+
The API uses Prisma and PostgreSQL. Background work runs on a database-backed worker loop
41+
inside the API process, which keeps a deployment to a single moving part; Redis/BullMQ is a
42+
documented upgrade for horizontal scale. Storage goes through a small driver interface; a
43+
local-filesystem driver ships, and an S3-compatible one can be added without touching the
44+
routes. See `docs/ARCHITECTURE.md` for the full design.
5645

57-
Read the full design in [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md).
46+
## Installation
5847

59-
---
48+
### Guided (dedicated Debian/Ubuntu server)
6049

61-
## 🚀 Quick start (Docker)
50+
The wizard installs prerequisites and configures PostgreSQL, the environment, the build,
51+
PM2, an nginx reverse proxy and a Let's Encrypt certificate:
6252

6353
```bash
6454
git clone https://github.com/softpython2884/opencoperlock.git
6555
cd opencoperlock
66-
cp .env.example .env
67-
# Edit .env — set strong values for POSTGRES_PASSWORD, MASTER_KEY,
68-
# SESSION_SECRET, ADMIN_EMAIL and ADMIN_PASSWORD.
69-
70-
docker compose -f infra/docker-compose.yml up --build
71-
```
72-
73-
Then open `http://localhost:3000` and sign in with the admin credentials from your `.env`.
74-
75-
Generate strong secrets:
76-
77-
```bash
78-
# 32-byte base64 keys for MASTER_KEY and SESSION_SECRET
79-
openssl rand -base64 32
56+
bash scripts/setup-wizard.sh
8057
```
8158

82-
See [`docs/DEPLOYMENT.md`](./docs/DEPLOYMENT.md) for production setup behind a reverse
83-
proxy with TLS (e.g. `copper.forgenet.fr`).
84-
85-
### One-command install (dedicated server)
59+
### Manual (PM2)
8660

87-
On a fresh Debian/Ubuntu box, the interactive wizard installs prerequisites and sets up
88-
PostgreSQL, `.env` (with generated secrets), the build, PM2, an nginx reverse proxy and a
89-
Let's Encrypt certificate:
61+
Provide your own PostgreSQL, then:
9062

9163
```bash
92-
git clone https://github.com/softpython2884/opencoperlock.git
93-
cd opencoperlock
94-
bash scripts/setup-wizard.sh
64+
cp .env.example .env # set secrets and paths
65+
./scripts/deploy.sh # install, build, migrate, seed
66+
pm2 start ecosystem.config.cjs
67+
pm2 save && pm2 startup
9568
```
9669

97-
### Quick start (bare-metal / PM2, manual)
98-
99-
Prefer to wire it up yourself? Provide your own PostgreSQL, then:
70+
### Docker
10071

10172
```bash
102-
cp .env.example .env # edit secrets + paths
103-
./scripts/deploy.sh # build, migrate, seed
104-
pm2 start ecosystem.config.cjs
105-
pm2 save && pm2 startup # restart on reboot
73+
cp .env.example .env
74+
docker compose -f infra/docker-compose.yml up --build -d
10675
```
10776

108-
Full PM2 walkthrough in [`docs/DEPLOYMENT.md`](./docs/DEPLOYMENT.md#bare-metal-with-pm2-dedicated-server).
109-
110-
---
77+
Generate strong secrets with `openssl rand -base64 32`. Full production notes, including
78+
reverse-proxy topology and backups, are in `docs/DEPLOYMENT.md`.
11179

112-
## 🧑‍💻 Local development
80+
## Development
11381

11482
```bash
11583
pnpm install
116-
# Start Postgres (and optional ClamAV) however you prefer, then:
117-
pnpm --filter @opencoperlock/api prisma:migrate
118-
pnpm --filter @opencoperlock/api db:seed
84+
pnpm --filter @opencoperlock/shared build
85+
pnpm --filter @opencoperlock/api prisma:generate
11986
pnpm dev
12087
```
12188

122-
Useful root scripts: `pnpm typecheck`, `pnpm lint`, `pnpm test`, `pnpm format`.
123-
124-
---
89+
The API needs a local PostgreSQL. ClamAV is optional in development; when it is
90+
unreachable, uploads are accepted and marked unscanned. Project gates: `pnpm typecheck`,
91+
`pnpm lint`, `pnpm test`.
12592

126-
## 🔐 Security
93+
## Security
12794

128-
Encryption model, trust boundaries and a threat model are documented in
129-
[`docs/SECURITY.md`](./docs/SECURITY.md) and [`docs/THREAT_MODEL.md`](./docs/THREAT_MODEL.md).
130-
To report a vulnerability, see [`SECURITY.md`](./SECURITY.md).
95+
The encryption model, trust boundaries and a candid threat model are documented in
96+
`docs/SECURITY.md` and `docs/THREAT_MODEL.md`. To report a vulnerability, see `SECURITY.md`.
13197

132-
## 🤝 Contributing
98+
## Contributing
13399

134-
Contributions are welcome — see [`CONTRIBUTING.md`](./CONTRIBUTING.md) and our
135-
[`CODE_OF_CONDUCT.md`](./CODE_OF_CONDUCT.md).
100+
See `CONTRIBUTING.md` and `CODE_OF_CONDUCT.md`.
136101

137-
## 📄 License
102+
## License
138103

139-
[GNU AGPL v3.0 or later](./LICENSE). © OpenCoperLock contributors.
104+
GNU AGPL v3.0 or later. See `LICENSE`.

‎apps/api/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
},
3636
"devDependencies": {
3737
"@types/node": "^22.10.2",
38+
"form-data": "^4.0.1",
3839
"pino-pretty": "^13.0.0",
3940
"prisma": "^6.1.0",
4041
"tsx": "^4.19.2",
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
-- AlterTable
2+
ALTER TABLE "RemoteUploadJob" ADD COLUMN "attempts" INTEGER NOT NULL DEFAULT 0,
3+
ADD COLUMN "nextRunAt" TIMESTAMP(3);
4+
5+
-- CreateTable
6+
CREATE TABLE "Throttle" (
7+
"id" TEXT NOT NULL,
8+
"bucket" TEXT NOT NULL,
9+
"key" TEXT NOT NULL,
10+
"failures" INTEGER NOT NULL DEFAULT 0,
11+
"firstFailAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
12+
"lockedUntil" TIMESTAMP(3),
13+
"updatedAt" TIMESTAMP(3) NOT NULL,
14+
15+
CONSTRAINT "Throttle_pkey" PRIMARY KEY ("id")
16+
);
17+
18+
-- CreateIndex
19+
CREATE INDEX "Throttle_lockedUntil_idx" ON "Throttle"("lockedUntil");
20+
21+
-- CreateIndex
22+
CREATE UNIQUE INDEX "Throttle_bucket_key_key" ON "Throttle"("bucket", "key");
23+
24+
-- CreateIndex
25+
CREATE INDEX "RemoteUploadJob_status_nextRunAt_idx" ON "RemoteUploadJob"("status", "nextRunAt");

‎apps/api/prisma/schema.prisma‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,11 +157,32 @@ model RemoteUploadJob {
157157
fileId String?
158158
// simple lease so a single worker loop processes each job once
159159
startedAt DateTime?
160+
// retry bookkeeping: how many times we've tried, and when the next try is allowed
161+
attempts Int @default(0)
162+
nextRunAt DateTime?
160163
createdAt DateTime @default(now())
161164
updatedAt DateTime @updatedAt
162165
163166
@@index([status])
164167
@@index([ownerId])
168+
@@index([status, nextRunAt])
169+
}
170+
171+
// Generic failure counter for brute-force protection. One row per (bucket, key):
172+
// - bucket "login" keyed by email -> account lockout with backoff
173+
// - bucket "quick" keyed by "<code>:<ip>" -> Quick-Upload password guessing ban
174+
// Rows are pruned by the maintenance loop once they expire.
175+
model Throttle {
176+
id String @id @default(cuid())
177+
bucket String
178+
key String
179+
failures Int @default(0)
180+
firstFailAt DateTime @default(now())
181+
lockedUntil DateTime?
182+
updatedAt DateTime @updatedAt
183+
184+
@@unique([bucket, key])
185+
@@index([lockedUntil])
165186
}
166187

167188
model AuditLog {

‎apps/api/src/env.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,18 @@ const envSchema = z.object({
2323
DEFAULT_USER_QUOTA_BYTES: z.coerce.number().int().nonnegative().default(10_737_418_240),
2424
REMOTE_UPLOAD_MAX_BYTES: z.coerce.number().int().positive().default(2_147_483_648),
2525

26+
// Maintenance / retention
27+
AUDIT_RETENTION_DAYS: z.coerce.number().int().positive().default(90),
28+
JOB_RETENTION_DAYS: z.coerce.number().int().positive().default(30),
29+
ORPHAN_GRACE_HOURS: z.coerce.number().int().positive().default(24),
30+
MAINTENANCE_INTERVAL_HOURS: z.coerce.number().int().positive().default(24),
31+
32+
// IP rate limiting. Disabled in tests so a shared client IP doesn't trip limits.
33+
RATE_LIMIT_ENABLED: z
34+
.enum(['true', 'false'])
35+
.default('true')
36+
.transform((v) => v === 'true'),
37+
2638
CLAMAV_ENABLED: z
2739
.enum(['true', 'false'])
2840
.default('false')

‎apps/api/src/index.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { loadEnv } from './env.js';
55
import { createContext } from './context.js';
66
import { buildServer } from './server.js';
77
import { startRemoteWorker } from './worker/remote-worker.js';
8+
import { startMaintenance } from './services/maintenance.js';
89
import { prisma } from './db.js';
910

1011
async function main(): Promise<void> {
@@ -19,10 +20,12 @@ async function main(): Promise<void> {
1920

2021
const app = await buildServer(ctx);
2122
const stopWorker = startRemoteWorker(ctx, app.log);
23+
const stopMaintenance = startMaintenance(ctx, app.log);
2224

2325
const shutdown = async (signal: string) => {
2426
app.log.info({ signal }, 'shutting down');
2527
stopWorker();
28+
stopMaintenance();
2629
await app.close();
2730
await prisma.$disconnect();
2831
process.exit(0);

‎apps/api/src/routes/admin.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { parseOr400 } from '../lib/validate.js';
1111
import { hashPassword } from '../services/password.js';
1212
import { toPublicQuickCode, toPublicUser } from '../lib/serialize.js';
1313
import { getGlobalCapBytes, getGlobalUsedBytes } from '../services/quota.js';
14+
import { runMaintenance } from '../services/maintenance.js';
1415
import { audit } from '../services/audit.js';
1516

1617
const GLOBAL_SETTING_ID = 'global';
@@ -112,6 +113,13 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
112113
return { ok: true };
113114
});
114115

116+
// ── Maintenance (manual trigger) ─────────────────────────────────────────--
117+
app.post('/maintenance', async (req) => {
118+
const summary = await runMaintenance(app.ctx, req.log);
119+
await audit(req, 'admin.maintenance.run');
120+
return summary;
121+
});
122+
115123
// ── Global settings ─────────────────────────────────────────────────────--
116124
app.get('/settings', async () => {
117125
const setting = await prisma.setting.findUnique({ where: { id: GLOBAL_SETTING_ID } });

0 commit comments

Comments
 (0)