Skip to content

Commit 49773dc

Browse files
Installer nginx WebDAV fix, Quick-Upload anti-enumeration, WebDAV quota, account self-wipe & inactivity auto-delete
- setup-wizard.sh: the single-domain nginx now sets 'X-Forwarded-Prefix /api', so WebDAV mounts work out of the box (no more /dav/ hrefs that 404 behind the proxy). Legal page links /docs. - Quick-Upload anti-enumeration: invalid/expired/used codes return a uniform 403 'Access denied' (never 'code not found'), throttled per IP; creating an already-taken custom code also returns the generic 403 instead of 'already in use'. No oracle for probing which codes exist. - WebDAV: report the account quota via RFC 4331 quota-available/used-bytes, so the mounted drive shows your quota (e.g. 10 GB) instead of the server disk. - Account: 'Delete all my spaces' (password-confirmed, permanent) and an opt-in inactivity auto-wipe ('delete my files if I don't log in for N days') enforced by a daily maintenance job. Adds User.lastLoginAt / autoDeleteAfterDays (+ migration); login records lastLoginAt.
1 parent cffec1f commit 49773dc

12 files changed

Lines changed: 213 additions & 17 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
-- AlterTable
2+
ALTER TABLE "User" ADD COLUMN "lastLoginAt" TIMESTAMP(3),
3+
ADD COLUMN "autoDeleteAfterDays" INTEGER;

‎apps/api/prisma/schema.prisma‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ model User {
5858
// Two-factor (TOTP). `totpSecret` is also used as the pending secret during setup.
5959
totpSecret String?
6060
totpEnabled Boolean @default(false)
61+
// Last successful login, used by the optional inactivity auto-wipe.
62+
lastLoginAt DateTime?
63+
// If set, a daily job permanently deletes the user's files after this many days without a login.
64+
autoDeleteAfterDays Int?
6165
createdAt DateTime @default(now())
6266
updatedAt DateTime @updatedAt
6367

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

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import { audit } from '../services/audit.js';
2929
import { generateUniqueQuickCode, isCodeTakenError } from '../services/quickCode.js';
3030
import { generateToken } from '../services/apiToken.js';
3131
import { sendTestEvent } from '../services/webhooks.js';
32+
import { trashFile, trashFolder, emptyTrash } from '../services/trash.js';
3233

3334
export const accountRoutes: FastifyPluginAsync = async (app) => {
3435
app.addHook('preHandler', app.requireAuth);
@@ -63,7 +64,7 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
6364
const codeValue = body.code ?? (await generateUniqueQuickCode());
6465
if (body.code) {
6566
const clash = await prisma.quickUploadCode.findUnique({ where: { code: codeValue } });
66-
if (clash) return reply.code(409).send({ error: 'This code is already in use' });
67+
if (clash) return reply.code(403).send({ error: 'Access denied', code: 'UNAUTHORIZED' });
6768
}
6869

6970
try {
@@ -82,7 +83,7 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
8283
return reply.code(201).send({ code: toPublicQuickCode(code) });
8384
} catch (err) {
8485
// Lost a race for the same custom code between the check and the insert.
85-
if (isCodeTakenError(err)) return reply.code(409).send({ error: 'This code is already in use' });
86+
if (isCodeTakenError(err)) return reply.code(403).send({ error: 'Access denied', code: 'UNAUTHORIZED' });
8687
throw err;
8788
}
8889
});
@@ -194,6 +195,46 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
194195
return { ok: true };
195196
});
196197

198+
// GET/PATCH /account/auto-delete — opt-in inactivity wipe ("delete my files if I don't log in
199+
// for N days"). A daily maintenance job enforces it.
200+
app.get('/auto-delete', async (req) => {
201+
const u = await prisma.user.findUniqueOrThrow({
202+
where: { id: req.user!.id },
203+
select: { autoDeleteAfterDays: true, lastLoginAt: true },
204+
});
205+
return { autoDeleteAfterDays: u.autoDeleteAfterDays, lastLoginAt: u.lastLoginAt?.toISOString() ?? null };
206+
});
207+
208+
app.patch('/auto-delete', async (req, reply) => {
209+
const v = (req.body as { autoDeleteAfterDays?: unknown }).autoDeleteAfterDays;
210+
let days: number | null;
211+
if (v === null || v === undefined || v === 0) days = null; // off
212+
else if (typeof v === 'number' && Number.isInteger(v) && v >= 7 && v <= 3650) days = v;
213+
else return reply.code(400).send({ error: 'Invalid value' });
214+
await prisma.user.update({ where: { id: req.user!.id }, data: { autoDeleteAfterDays: days } });
215+
await audit(req, 'account.autodelete.set', { target: String(days) });
216+
return { autoDeleteAfterDays: days };
217+
});
218+
219+
// POST /account/wipe — permanently delete ALL of the user's spaces & files (password-gated).
220+
// The account itself is kept; this is the "start fresh" / panic button.
221+
app.post('/wipe', async (req, reply) => {
222+
const body = parseOr400(reply, passwordConfirmSchema, req.body);
223+
if (!body) return;
224+
const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } });
225+
if (!(await verifyPassword(user.passwordHash, body.password))) {
226+
return reply.code(401).send({ error: 'Incorrect password' });
227+
}
228+
// Trash every top-level space and any root-level files, then purge the trash — irreversible.
229+
const folders = await prisma.folder.findMany({ where: { ownerId: user.id, parentId: null, deletedAt: null }, select: { id: true } });
230+
for (const f of folders) await trashFolder(user.id, f.id);
231+
const rootFiles = await prisma.fileObject.findMany({ where: { ownerId: user.id, folderId: null, deletedAt: null }, select: { id: true } });
232+
for (const f of rootFiles) await trashFile(user.id, f.id);
233+
await emptyTrash(app.ctx, user.id);
234+
await audit(req, 'account.wipe');
235+
return { ok: true };
236+
});
237+
197238
// GET /account/export — a JSON copy of the user's data (metadata, not file contents).
198239
app.get('/export', async (req, reply) => {
199240
const userId = req.user!.id;

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
248248
const codeValue = body.code ?? (await generateUniqueQuickCode());
249249
if (body.code) {
250250
const clash = await prisma.quickUploadCode.findUnique({ where: { code: codeValue } });
251-
if (clash) return reply.code(409).send({ error: 'This code is already in use' });
251+
if (clash) return reply.code(403).send({ error: 'Access denied', code: 'UNAUTHORIZED' });
252252
}
253253

254254
try {
@@ -266,7 +266,7 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
266266
await audit(req, 'admin.quickcode.create', { target: code.id });
267267
return reply.code(201).send({ code: toPublicQuickCode(code) });
268268
} catch (err) {
269-
if (isCodeTakenError(err)) return reply.code(409).send({ error: 'This code is already in use' });
269+
if (isCodeTakenError(err)) return reply.code(403).send({ error: 'Access denied', code: 'UNAUTHORIZED' });
270270
throw err;
271271
}
272272
});

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
6363
ip: req.ip,
6464
userAgent: req.headers['user-agent'] ?? null,
6565
});
66+
// Record the login so the optional inactivity auto-wipe has a fresh activity timestamp.
67+
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date() } });
6668
setSessionCookie(reply, session.id, session.expiresAt, secureCookies);
6769
await audit(req, 'auth.login', { actorId: user.id });
6870
return { user: toPublicUser(user), csrfToken: session.csrfSecret };

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

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,21 @@ function isUsedUp(usageLimit: number | null, usageCount: number): boolean {
3434
export const quickRoutes: FastifyPluginAsync = async (app) => {
3535
// GET /quick/:code — lightweight validity probe for the guest UI.
3636
app.get('/:code', async (req, reply) => {
37+
// Throttle blind enumeration per IP, and NEVER reveal whether a code exists: an invalid,
38+
// expired or used-up code returns the same generic "access denied" as any other.
39+
const ipKey = `probe:${req.ip}`;
40+
const lock = await checkLock('quick', ipKey);
41+
if (lock.locked) {
42+
reply.header('Retry-After', String(lock.retryAfterSec));
43+
return reply.code(429).send({ error: 'Too many attempts. Try again later.', code: 'LOCKED' });
44+
}
3745
const code = String((req.params as { code: string }).code).toUpperCase();
3846
const entry = await prisma.quickUploadCode.findUnique({ where: { code } });
3947
if (!entry || isExpired(entry.expiresAt) || isUsedUp(entry.usageLimit, entry.usageCount)) {
40-
return reply.code(404).send({ error: 'Code not found or no longer active' });
48+
await recordFailure('quick', ipKey, QUICK_THROTTLE);
49+
return reply.code(403).send({ error: 'Access denied', code: 'UNAUTHORIZED' });
4150
}
51+
await clearFailures('quick', ipKey);
4252
return { valid: true, requiresPassword: entry.passwordHash !== null };
4353
});
4454

@@ -51,7 +61,9 @@ export const quickRoutes: FastifyPluginAsync = async (app) => {
5161
const code = String((req.params as { code: string }).code).toUpperCase();
5262
const entry = await prisma.quickUploadCode.findUnique({ where: { code } });
5363
if (!entry || isExpired(entry.expiresAt) || isUsedUp(entry.usageLimit, entry.usageCount)) {
54-
return reply.code(404).send({ error: 'Code not found or no longer active' });
64+
// Same generic response as the probe — no enumeration oracle, throttled per IP.
65+
await recordFailure('quick', `probe:${req.ip}`, QUICK_THROTTLE);
66+
return reply.code(403).send({ error: 'Access denied', code: 'UNAUTHORIZED' });
5567
}
5668

5769
// Ban an IP that keeps guessing this code's password. Keyed per (code, IP) so one

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

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import { decryptServerFile } from '../services/download.js';
1919
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
2020
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
2121
import { trashFile, trashFolder } from '../services/trash.js';
22+
import { remainingAllowance } from '../services/quota.js';
2223

2324
const PREFIX = '/dav';
2425
const READ_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'PROPFIND']);
@@ -84,9 +85,22 @@ async function resolvePath(ownerId: string, segments: string[]): Promise<Resolve
8485
return { type: 'missing', parentId, name: last };
8586
}
8687

87-
function propXml(base: string, segments: string[], isCollection: boolean, name: string, size: number, mtime: Date, mime: string): string {
88+
function propXml(
89+
base: string,
90+
segments: string[],
91+
isCollection: boolean,
92+
name: string,
93+
size: number,
94+
mtime: Date,
95+
mime: string,
96+
quota?: { used: number; available: number },
97+
): string {
98+
// RFC 4331 quota props make the OS show the account quota (not the server disk) on the mount.
99+
const quotaXml = quota
100+
? `<D:quota-available-bytes>${quota.available}</D:quota-available-bytes><D:quota-used-bytes>${quota.used}</D:quota-used-bytes>`
101+
: '';
88102
const props = isCollection
89-
? `<D:resourcetype><D:collection/></D:resourcetype>`
103+
? `<D:resourcetype><D:collection/></D:resourcetype>${quotaXml}`
90104
: `<D:resourcetype/><D:getcontentlength>${size}</D:getcontentlength><D:getcontenttype>${escapeXml(mime)}</D:getcontenttype>`;
91105
return (
92106
`<D:response><D:href>${escapeXml(hrefFor(base, segments, isCollection))}</D:href>` +
@@ -167,10 +181,20 @@ export const webdavRoutes: FastifyPluginAsync = async (app) => {
167181
if (node.type === 'invalid' || node.type === 'missing') return reply.code(404).send();
168182
const depth = String(req.headers.depth ?? '1');
169183
const parts: string[] = [];
184+
// Report the account quota on the queried collection so the mount shows the right size.
185+
let quota: { used: number; available: number } | undefined;
186+
if (node.type !== 'file') {
187+
const user = await prisma.user.findUnique({ where: { id: ownerId }, select: { usedBytes: true } });
188+
const avail = await remainingAllowance(ownerId);
189+
quota = {
190+
used: Number(user?.usedBytes ?? 0n),
191+
available: Number.isFinite(avail) ? Math.max(0, Math.floor(avail)) : 1_099_511_627_776, // 1 TiB if unlimited
192+
};
193+
}
170194
if (node.type === 'root') {
171-
parts.push(propXml(base, [], true, 'OpenCoperLock', 0, new Date(), ''));
195+
parts.push(propXml(base, [], true, 'OpenCoperLock', 0, new Date(), '', quota));
172196
} else if (node.type === 'folder') {
173-
parts.push(propXml(base, segments, true, node.folder.name, 0, node.folder.createdAt, ''));
197+
parts.push(propXml(base, segments, true, node.folder.name, 0, node.folder.createdAt, '', quota));
174198
} else {
175199
parts.push(propXml(base, segments, false, node.file.name, Number(node.file.sizeBytes), node.file.createdAt, node.file.mimeType));
176200
}

‎apps/api/src/services/maintenance.ts‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
import type { FastifyBaseLogger } from 'fastify';
1212
import type { AppContext } from '../context.js';
1313
import { prisma } from '../db.js';
14-
import { purgeExpiredTrash } from './trash.js';
14+
import { purgeExpiredTrash, trashFile, trashFolder, emptyTrash } from './trash.js';
1515

1616
export interface ReconcileResult {
1717
usersChecked: number;
@@ -98,6 +98,39 @@ export async function pruneThrottle(): Promise<number> {
9898
return res.count;
9999
}
100100

101+
/**
102+
* Opt-in inactivity wipe: for users who set `autoDeleteAfterDays`, permanently delete ALL their
103+
* files once they haven't logged in for that long. The account itself is kept. Irreversible.
104+
*/
105+
export async function enforceInactivityWipe(ctx: AppContext, log: FastifyBaseLogger): Promise<number> {
106+
const candidates = await prisma.user.findMany({
107+
where: { autoDeleteAfterDays: { not: null } },
108+
select: { id: true, autoDeleteAfterDays: true, lastLoginAt: true, createdAt: true },
109+
});
110+
const now = Date.now();
111+
let wiped = 0;
112+
for (const u of candidates) {
113+
const days = u.autoDeleteAfterDays!;
114+
const last = (u.lastLoginAt ?? u.createdAt).getTime();
115+
if (now - last < days * 24 * 60 * 60 * 1000) continue;
116+
117+
const folders = await prisma.folder.findMany({
118+
where: { ownerId: u.id, parentId: null, deletedAt: null },
119+
select: { id: true },
120+
});
121+
for (const f of folders) await trashFolder(u.id, f.id);
122+
const rootFiles = await prisma.fileObject.findMany({
123+
where: { ownerId: u.id, folderId: null, deletedAt: null },
124+
select: { id: true },
125+
});
126+
for (const f of rootFiles) await trashFile(u.id, f.id);
127+
await emptyTrash(ctx, u.id);
128+
log.warn({ userId: u.id, days }, 'inactivity auto-wipe: permanently deleted all files');
129+
wiped += 1;
130+
}
131+
return wiped;
132+
}
133+
101134
/** Run one full maintenance pass. Safe to call manually (admin) or on a timer. */
102135
export async function runMaintenance(ctx: AppContext, log: FastifyBaseLogger) {
103136
// Purge Trash past its retention window first, so reconcile/orphan steps see the freed space.
@@ -108,13 +141,15 @@ export async function runMaintenance(ctx: AppContext, log: FastifyBaseLogger) {
108141
const audit = await pruneAuditLog(ctx.env.AUDIT_RETENTION_DAYS);
109142
const jobs = await pruneJobs(ctx.env.JOB_RETENTION_DAYS);
110143
const throttle = await pruneThrottle();
144+
const inactivityWiped = await enforceInactivityWipe(ctx, log);
111145
const summary = {
112146
trashPurged,
113147
usersAdjusted: reconcile.usersAdjusted,
114148
orphansDeleted: orphans.deleted,
115149
auditPruned: audit,
116150
jobsPruned: jobs,
117151
throttlePruned: throttle,
152+
inactivityWiped,
118153
};
119154
log.info(summary, 'maintenance pass complete');
120155
return summary;

‎apps/web/src/app/(app)/account/page.tsx‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,23 +53,26 @@ export default function AccountPage() {
5353
const [newToken, setNewToken] = useState<string | null>(null);
5454
const [webhooks, setWebhooks] = useState<PublicWebhook[]>([]);
5555
const [nw, setNw] = useState({ url: '', secret: '', folderId: '' });
56+
const [autoDelete, setAutoDelete] = useState<number | null>(null);
5657
const [error, setError] = useState<string | null>(null);
5758

5859
const load = useCallback(async () => {
59-
const [s, sess, qc, fl, tk, wh] = await Promise.all([
60+
const [s, sess, qc, fl, tk, wh, ad] = await Promise.all([
6061
api.get<TwoFaStatus>('/2fa/status'),
6162
api.get<{ sessions: SessionInfo[] }>('/auth/sessions'),
6263
api.get<{ codes: PublicQuickCode[] }>('/account/quick-codes'),
6364
api.get<{ folders: PublicFolder[] }>('/folders'),
6465
api.get<{ tokens: PublicApiToken[] }>('/account/api-tokens'),
6566
api.get<{ webhooks: PublicWebhook[] }>('/account/webhooks'),
67+
api.get<{ autoDeleteAfterDays: number | null }>('/account/auto-delete'),
6668
]);
6769
setStatus(s);
6870
setSessions(sess.sessions);
6971
setCodes(qc.codes);
7072
setFolders(fl.folders);
7173
setTokens(tk.tokens);
7274
setWebhooks(wh.webhooks);
75+
setAutoDelete(ad.autoDeleteAfterDays);
7376
}, []);
7477

7578
useEffect(() => {
@@ -150,6 +153,21 @@ export default function AccountPage() {
150153
});
151154
}
152155

156+
async function wipeSpaces() {
157+
const password = await prompt({
158+
title: t('account.wipeTitle'),
159+
message: t('account.wipeMsg'),
160+
label: t('account.confirmPassword'),
161+
password: true,
162+
});
163+
if (!password) return;
164+
await wrap(async () => {
165+
await api.post('/account/wipe', { password });
166+
await refresh();
167+
toast(t('account.wipeDone'), 'success');
168+
});
169+
}
170+
153171
return (
154172
<div className="space-y-8">
155173
<h1 className="text-lg font-semibold">{t('account.title')}</h1>
@@ -507,16 +525,45 @@ export default function AccountPage() {
507525
<p className="text-xs text-neutral-400">{t('account.webdavCreds')}</p>
508526
</section>
509527

528+
{/* Inactivity auto-delete */}
529+
<section className="card space-y-3">
530+
<h2 className="font-semibold">{t('account.autoDeleteTitle')}</h2>
531+
<p className="text-sm text-neutral-500">{t('account.autoDeleteHint')}</p>
532+
<Select
533+
className="w-[16rem]"
534+
value={autoDelete === null ? '' : String(autoDelete)}
535+
onChange={(v) =>
536+
wrap(async () => {
537+
const days = v === '' ? null : Number(v);
538+
const res = await api.patch<{ autoDeleteAfterDays: number | null }>('/account/auto-delete', { autoDeleteAfterDays: days });
539+
setAutoDelete(res.autoDeleteAfterDays);
540+
toast(t('account.saved'), 'success');
541+
})
542+
}
543+
options={[
544+
{ value: '', label: t('account.autoDeleteNever') },
545+
{ value: '30', label: t('account.autoDelete1m') },
546+
{ value: '90', label: t('account.autoDelete3m') },
547+
{ value: '180', label: t('account.autoDelete6m') },
548+
{ value: '365', label: t('account.autoDelete1y') },
549+
]}
550+
/>
551+
{autoDelete !== null && <p className="text-xs text-amber-300">⚠️ {t('account.autoDeleteActive', { days: autoDelete })}</p>}
552+
</section>
553+
510554
{/* Data & privacy (GDPR) */}
511555
<section className="card space-y-3">
512556
<h2 className="font-semibold">{t('account.yourData')}</h2>
513557
<p className="text-sm text-neutral-500">
514558
{t('account.dataHint')}
515559
</p>
516-
<div className="flex gap-2">
560+
<div className="flex flex-wrap gap-2">
517561
<a className="btn-ghost" href={`${API_URL}/account/export`}>
518562
{t('account.exportData')}
519563
</a>
564+
<button className="btn-danger" onClick={wipeSpaces}>
565+
{t('account.wipeSpaces')}
566+
</button>
520567
<button className="btn-danger" onClick={deleteAccount}>
521568
{t('account.deleteAccount')}
522569
</button>

‎apps/web/src/app/legal/page.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ export default function LegalIndexPage() {
3737

3838
<h2>Documents</h2>
3939
<ul>
40+
<li><Link href="/docs">Documentation</Link></li>
4041
<li><Link href="/legal/terms">Conditions d’utilisation</Link></li>
4142
<li><Link href="/legal/privacy">Politique de confidentialité</Link></li>
4243
<li><Link href="/legal/license">Licence (GNU AGPLv3)</Link></li>

0 commit comments

Comments
 (0)