Skip to content

Commit 6e6c170

Browse files
Add Trash (soft-delete) with restore, purge and auto-retention
Deleting a file or folder now moves it to the Trash instead of destroying it: - Schema: deletedAt on FileObject and Folder (+ indexes), new migration. - services/trash.ts: trash/restore/purge for files and folders (folder ops cascade the whole subtree), listTrash (only Trash 'roots'), emptyTrash, and purgeExpiredTrash for retention. Trashed files keep counting against quota until purged; restore re-homes to root if the original parent is gone/trashed. - Routes: DELETE /files|/folders|/zk now soft-delete; new /trash routes (list, restore, purge, empty). Listings and folder-share entries exclude trashed. - Maintenance auto-purges past TRASH_RETENTION_DAYS (default 30). - Web: Corbeille page (restore / delete-forever / empty) + sidebar link; Drive delete copy reworded to 'mettre à la corbeille'. - Tests: file + folder trash lifecycle; updated the delete-quota test (41 pass).
1 parent f59c533 commit 6e6c170

16 files changed

Lines changed: 570 additions & 57 deletions

File tree

‎.env.example‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,10 @@ CLAMAV_PORT=3310
7979
# Leave empty to disable. With a key, files can be checked by hash on demand.
8080
VIRUSTOTAL_API_KEY=
8181

82+
# ── Trash retention ──────────────────────────────────────────────────────────
83+
# Days a soft-deleted file/folder stays in the Trash before being purged automatically.
84+
TRASH_RETENTION_DAYS=30
85+
8286
# ── Version tracking & self-update ───────────────────────────────────────────
8387
# The admin panel reads the deployed git SHA, compares it to this GitHub repo/branch,
8488
# and can trigger an in-place update (git reset + rebuild + PM2 reload).
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
-- AlterTable
2+
ALTER TABLE "FileObject" ADD COLUMN "deletedAt" TIMESTAMP(3);
3+
4+
-- AlterTable
5+
ALTER TABLE "Folder" ADD COLUMN "deletedAt" TIMESTAMP(3);
6+
7+
-- CreateIndex
8+
CREATE INDEX "FileObject_deletedAt_idx" ON "FileObject"("deletedAt");
9+
10+
-- CreateIndex
11+
CREATE INDEX "Folder_deletedAt_idx" ON "Folder"("deletedAt");

‎apps/api/prisma/schema.prisma‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,13 +113,17 @@ model Folder {
113113
// Per-vault random salt for the client's PBKDF2 key derivation (ZK folders only).
114114
// Not secret; storing it per vault defeats cross-vault precomputation. null = legacy.
115115
zkSalt String?
116+
// Soft-delete: when set, the folder is in the Trash (hidden from the Drive) until it is
117+
// restored or purged. Trashing a folder cascades this timestamp to its whole subtree.
118+
deletedAt DateTime?
116119
createdAt DateTime @default(now())
117120
118121
files FileObject[]
119122
shares ShareLink[]
120123
121124
@@unique([ownerId, parentId, name])
122125
@@index([ownerId])
126+
@@index([deletedAt])
123127
}
124128

125129
model FileObject {
@@ -153,13 +157,17 @@ model FileObject {
153157
154158
sha256 String?
155159
avStatus AvStatus @default(PENDING)
160+
// Soft-delete: when set, the file is in the Trash (hidden from listings) until restored
161+
// or purged. Trashed files still count against quota until they are permanently removed.
162+
deletedAt DateTime?
156163
createdAt DateTime @default(now())
157164
158165
shares ShareLink[]
159166
versions FileVersion[]
160167
161168
@@index([ownerId])
162169
@@index([folderId])
170+
@@index([deletedAt])
163171
}
164172

165173
// A prior revision of a SERVER-mode file (kept for text-like files). Holds its own

‎apps/api/src/env.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ const envSchema = z.object({
3838
// Maintenance / retention
3939
AUDIT_RETENTION_DAYS: z.coerce.number().int().positive().default(90),
4040
JOB_RETENTION_DAYS: z.coerce.number().int().positive().default(30),
41+
// How long items stay in the Trash before being purged automatically.
42+
TRASH_RETENTION_DAYS: z.coerce.number().int().positive().default(30),
4143
ORPHAN_GRACE_HOURS: z.coerce.number().int().positive().default(24),
4244
MAINTENANCE_INTERVAL_HOURS: z.coerce.number().int().positive().default(24),
4345

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

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
ingestPlaintext,
1010
} from '../services/ingest.js';
1111
import { decryptServerFile } from '../services/download.js';
12+
import { trashFile } from '../services/trash.js';
1213
import {
1314
findVersionTarget,
1415
isVersionable,
@@ -26,7 +27,7 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
2627
app.get('/', async (req) => {
2728
const { folderId } = req.query as { folderId?: string };
2829
const files = await prisma.fileObject.findMany({
29-
where: { ownerId: req.user!.id, folderId: folderId ?? null },
30+
where: { ownerId: req.user!.id, folderId: folderId ?? null, deletedAt: null },
3031
orderBy: { createdAt: 'desc' },
3132
});
3233
return { files: files.map(toPublicFile) };
@@ -240,22 +241,13 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
240241
return { file: toPublicFile(updated) };
241242
});
242243

243-
// DELETE /files/:id — remove the blob, its versions, and release all their quota.
244+
// DELETE /files/:id — move the file to the Trash (soft-delete). It keeps counting against
245+
// quota until it is restored or permanently purged from the Trash.
244246
app.delete('/:id', async (req, reply) => {
245247
const { id } = req.params as { id: string };
246-
const file = await prisma.fileObject.findFirst({ where: { id, ownerId: req.user!.id } });
247-
if (!file) return reply.code(404).send({ error: 'File not found' });
248-
249-
const versions = await prisma.fileVersion.findMany({ where: { fileId: id } });
250-
let freed = Number(file.sizeBytes);
251-
await app.ctx.storage.delete(file.storageKey).catch((err) => req.log.warn({ err }, 'blob delete failed'));
252-
for (const v of versions) {
253-
await app.ctx.storage.delete(v.storageKey).catch(() => {});
254-
freed += Number(v.sizeBytes);
255-
}
256-
await prisma.fileObject.delete({ where: { id: file.id } }); // cascades version rows
257-
await adjustUsage(req.user!.id, -freed);
258-
await audit(req, 'file.delete', { target: file.id });
248+
const ok = await trashFile(req.user!.id, id);
249+
if (!ok) return reply.code(404).send({ error: 'File not found' });
250+
await audit(req, 'file.trash', { target: id });
259251
return { ok: true };
260252
});
261253

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

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { createFolderSchema, randomToken, updateFolderSchema } from '@opencoperl
33
import { prisma } from '../db.js';
44
import { parseOr400 } from '../lib/validate.js';
55
import { toPublicFolder } from '../lib/serialize.js';
6-
import { adjustUsage } from '../services/quota.js';
6+
import { trashFolder } from '../services/trash.js';
77
import { audit } from '../services/audit.js';
88

99
/** Collect a folder's id plus all descendant ids (breadth-first), scoped to one owner. */
@@ -25,7 +25,7 @@ export const folderRoutes: FastifyPluginAsync = async (app) => {
2525
// GET /folders — flat list of the user's folders (the SPA assembles the tree).
2626
app.get('/', async (req) => {
2727
const folders = await prisma.folder.findMany({
28-
where: { ownerId: req.user!.id },
28+
where: { ownerId: req.user!.id, deletedAt: null },
2929
orderBy: { name: 'asc' },
3030
});
3131
return { folders: folders.map(toPublicFolder) };
@@ -99,32 +99,13 @@ export const folderRoutes: FastifyPluginAsync = async (app) => {
9999
}
100100
});
101101

102-
// DELETE /folders/:id — recursively delete the folder, its subfolders and files,
103-
// releasing storage blobs and quota.
102+
// DELETE /folders/:id — move the folder (and its whole subtree) to the Trash. Nothing is
103+
// destroyed and no quota is released until it is purged from the Trash.
104104
app.delete('/:id', async (req, reply) => {
105105
const { id } = req.params as { id: string };
106-
const root = await prisma.folder.findFirst({ where: { id, ownerId: req.user!.id } });
107-
if (!root) return reply.code(404).send({ error: 'Folder not found' });
108-
109-
const ids = await collectSubtree(root.id, req.user!.id);
110-
const files = await prisma.fileObject.findMany({ where: { folderId: { in: ids } } });
111-
const fileIds = files.map((f) => f.id);
112-
const versions = await prisma.fileVersion.findMany({ where: { fileId: { in: fileIds } } });
113-
let freed = 0;
114-
for (const file of files) {
115-
await app.ctx.storage.delete(file.storageKey).catch((err) => req.log.warn({ err }, 'blob delete failed'));
116-
freed += Number(file.sizeBytes);
117-
}
118-
for (const v of versions) {
119-
await app.ctx.storage.delete(v.storageKey).catch(() => {});
120-
freed += Number(v.sizeBytes);
121-
}
122-
await prisma.fileObject.deleteMany({ where: { folderId: { in: ids } } });
123-
if (freed > 0) await adjustUsage(req.user!.id, -freed);
124-
// Deleting the root cascades the subfolder rows (FolderChildren onDelete: Cascade).
125-
await prisma.folder.delete({ where: { id: root.id } });
126-
127-
await audit(req, 'folder.delete', { target: root.id });
128-
return { ok: true, freedBytes: freed };
106+
const ok = await trashFolder(req.user!.id, id);
107+
if (!ok) return reply.code(404).send({ error: 'Folder not found' });
108+
await audit(req, 'folder.trash', { target: id });
109+
return { ok: true };
129110
});
130111
};

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* Trash management: list soft-deleted items, restore them, or permanently purge them.
3+
* Deleting a file/folder elsewhere moves it here (see services/trash.ts); this is where it
4+
* comes back from — or is destroyed for good.
5+
*/
6+
import type { FastifyPluginAsync } from 'fastify';
7+
import { prisma } from '../db.js';
8+
import {
9+
emptyTrash,
10+
listTrash,
11+
purgeFile,
12+
purgeFolder,
13+
restoreFile,
14+
restoreFolder,
15+
} from '../services/trash.js';
16+
import { audit } from '../services/audit.js';
17+
18+
export const trashRoutes: FastifyPluginAsync = async (app) => {
19+
app.addHook('preHandler', app.requireAuth);
20+
21+
// GET /trash — the Trash "roots" (items deleted directly, newest first).
22+
app.get('/', async (req) => {
23+
return { entries: await listTrash(req.user!.id) };
24+
});
25+
26+
// POST /trash/files/:id/restore
27+
app.post('/files/:id/restore', async (req, reply) => {
28+
const { id } = req.params as { id: string };
29+
if (!(await restoreFile(req.user!.id, id))) return reply.code(404).send({ error: 'Item not found in Trash' });
30+
await audit(req, 'trash.restore', { target: id });
31+
return { ok: true };
32+
});
33+
34+
// POST /trash/folders/:id/restore
35+
app.post('/folders/:id/restore', async (req, reply) => {
36+
const { id } = req.params as { id: string };
37+
if (!(await restoreFolder(req.user!.id, id))) return reply.code(404).send({ error: 'Item not found in Trash' });
38+
await audit(req, 'trash.restore', { target: id });
39+
return { ok: true };
40+
});
41+
42+
// DELETE /trash/files/:id — purge permanently.
43+
app.delete('/files/:id', async (req, reply) => {
44+
const { id } = req.params as { id: string };
45+
if (!(await purgeFile(app.ctx, req.user!.id, id))) return reply.code(404).send({ error: 'Item not found in Trash' });
46+
await audit(req, 'trash.purge', { target: id });
47+
return { ok: true };
48+
});
49+
50+
// DELETE /trash/folders/:id — purge permanently (whole subtree).
51+
app.delete('/folders/:id', async (req, reply) => {
52+
const { id } = req.params as { id: string };
53+
if (!(await purgeFolder(app.ctx, req.user!.id, id))) return reply.code(404).send({ error: 'Item not found in Trash' });
54+
await audit(req, 'trash.purge', { target: id });
55+
return { ok: true };
56+
});
57+
58+
// POST /trash/empty — purge everything in the user's Trash.
59+
app.post('/empty', async (req) => {
60+
await emptyTrash(app.ctx, req.user!.id);
61+
await audit(req, 'trash.empty');
62+
// Surface the freed-up running total so the client can refresh the storage gauge.
63+
const user = await prisma.user.findUnique({ where: { id: req.user!.id }, select: { usedBytes: true } });
64+
return { ok: true, usedBytes: Number(user?.usedBytes ?? 0) };
65+
});
66+
};

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

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import { zkFileMetaSchema } from '@opencoperlock/shared';
99
import { prisma } from '../db.js';
1010
import { newStorageKey } from '../storage/index.js';
1111
import { adjustUsage, remainingAllowance } from '../services/quota.js';
12+
import { trashFile } from '../services/trash.js';
1213
import { audit } from '../services/audit.js';
1314
import { FileTooLargeError } from '../services/ingest.js';
1415
import type { Readable } from 'node:stream';
@@ -37,7 +38,7 @@ export const zkRoutes: FastifyPluginAsync = async (app) => {
3738
if (!folder) return reply.code(404).send({ error: 'Vault folder not found' });
3839

3940
const files = await prisma.fileObject.findMany({
40-
where: { ownerId: req.user!.id, folderId, encMode: 'ZK' },
41+
where: { ownerId: req.user!.id, folderId, encMode: 'ZK', deletedAt: null },
4142
orderBy: { createdAt: 'desc' },
4243
});
4344
return {
@@ -127,17 +128,15 @@ export const zkRoutes: FastifyPluginAsync = async (app) => {
127128
return reply.send(app.ctx.storage.createReadStream(file.storageKey));
128129
});
129130

130-
// DELETE /zk/files/:id — remove a vault file.
131+
// DELETE /zk/files/:id — move a vault file to the Trash (soft-delete).
131132
app.delete('/files/:id', async (req, reply) => {
132133
const { id } = req.params as { id: string };
133134
const file = await prisma.fileObject.findFirst({
134-
where: { id, ownerId: req.user!.id, encMode: 'ZK' },
135+
where: { id, ownerId: req.user!.id, encMode: 'ZK', deletedAt: null },
135136
});
136137
if (!file) return reply.code(404).send({ error: 'File not found' });
137-
await app.ctx.storage.delete(file.storageKey).catch(() => {});
138-
await prisma.fileObject.delete({ where: { id: file.id } });
139-
await adjustUsage(req.user!.id, -Number(file.sizeBytes));
140-
await audit(req, 'zk.delete', { target: file.id });
138+
await trashFile(req.user!.id, file.id);
139+
await audit(req, 'zk.trash', { target: file.id });
141140
return { ok: true };
142141
});
143142
};

‎apps/api/src/server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import authPlugin from './plugins/auth.js';
1111
import { authRoutes } from './routes/auth.js';
1212
import { folderRoutes } from './routes/folders.js';
1313
import { fileRoutes } from './routes/files.js';
14+
import { trashRoutes } from './routes/trash.js';
1415
import { zkRoutes } from './routes/zk.js';
1516
import { quickRoutes } from './routes/quick.js';
1617
import { remoteRoutes } from './routes/remote.js';
@@ -72,6 +73,7 @@ export async function buildServer(ctx: AppContext): Promise<FastifyInstance> {
7273
await app.register(authRoutes, { prefix: '/auth' });
7374
await app.register(folderRoutes, { prefix: '/folders' });
7475
await app.register(fileRoutes, { prefix: '/files' });
76+
await app.register(trashRoutes, { prefix: '/trash' });
7577
await app.register(zkRoutes, { prefix: '/zk' });
7678
await app.register(quickRoutes, { prefix: '/quick' });
7779
await app.register(remoteRoutes, { prefix: '/remote' });

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +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';
1415

1516
export interface ReconcileResult {
1617
usersChecked: number;
@@ -99,12 +100,16 @@ export async function pruneThrottle(): Promise<number> {
99100

100101
/** Run one full maintenance pass. Safe to call manually (admin) or on a timer. */
101102
export async function runMaintenance(ctx: AppContext, log: FastifyBaseLogger) {
103+
// Purge Trash past its retention window first, so reconcile/orphan steps see the freed space.
104+
const trashCutoff = new Date(Date.now() - ctx.env.TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000);
105+
const trashPurged = await purgeExpiredTrash(ctx, trashCutoff);
102106
const reconcile = await reconcileUsage();
103107
const orphans = await collectOrphans(ctx, ctx.env.ORPHAN_GRACE_HOURS, log);
104108
const audit = await pruneAuditLog(ctx.env.AUDIT_RETENTION_DAYS);
105109
const jobs = await pruneJobs(ctx.env.JOB_RETENTION_DAYS);
106110
const throttle = await pruneThrottle();
107111
const summary = {
112+
trashPurged,
108113
usersAdjusted: reconcile.usersAdjusted,
109114
orphansDeleted: orphans.deleted,
110115
auditPruned: audit,

0 commit comments

Comments
 (0)