Skip to content

Commit 0b9c4d3

Browse files
feat: ZK instant-delete, per-user trash retention, admin "empty storage"
Zero-Knowledge instant delete — deleting a vault file or folder now removes it permanently at once instead of sending it to the Trash. Vault content is opaque ciphertext the server can't preview or restore, so a recoverable Trash adds nothing; the quota is freed immediately. (DELETE /zk/files/:id, plus the encMode==ZK / isZeroKnowledge branches of the file/folder routes.) Per-user trash retention — each user chooses how long deleted items linger before auto-purge (User.trashRetentionDays, default 7 days, 0 = never), picked from a selector in the Trash page. Maintenance now purges each user's Trash on their own window instead of a single instance-wide cutoff. Admin "empty a user's storage" — a new admin action permanently deletes all of a user's files, folders and the Shared Spaces they own WITHOUT deleting the account (frees their quota; login and settings remain). Service wipeOwnerContent + POST /admin/users/:id/purge-content. Docs updated (vault permanent delete, configurable retention, admin empty storage). Tests: ZK instant delete, retention purge (7d vs never) and account persistence, admin purge-content keeping the account.
1 parent dc20340 commit 0b9c4d3

14 files changed

Lines changed: 328 additions & 18 deletions

File tree

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
-- AlterTable
2+
ALTER TABLE "User" ADD COLUMN "trashRetentionDays" INTEGER NOT NULL DEFAULT 7;

‎apps/api/prisma/schema.prisma‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,8 @@ model User {
6969
lastLoginAt DateTime?
7070
// If set, a daily job permanently deletes the user's files after this many days without a login.
7171
autoDeleteAfterDays Int?
72+
// Days an item stays in the Trash before it is auto-purged. 0 = never auto-purge.
73+
trashRetentionDays Int @default(7)
7274
// The build (git SHA) for which this user last dismissed the "What's new" dialog. null until
7375
// they first load the app; lets us show release notes exactly once per update, per user.
7476
lastSeenVersion String?

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,26 @@ export const accountRoutes: FastifyPluginAsync = async (app) => {
216216
return { autoDeleteAfterDays: days };
217217
});
218218

219+
// GET/PATCH /account/trash-retention — how many days items linger in the Trash before being
220+
// auto-purged (0 = never; the user empties it manually).
221+
app.get('/trash-retention', async (req) => {
222+
const u = await prisma.user.findUniqueOrThrow({
223+
where: { id: req.user!.id },
224+
select: { trashRetentionDays: true },
225+
});
226+
return { trashRetentionDays: u.trashRetentionDays };
227+
});
228+
229+
app.patch('/trash-retention', async (req, reply) => {
230+
const v = (req.body as { trashRetentionDays?: unknown }).trashRetentionDays;
231+
if (typeof v !== 'number' || !Number.isInteger(v) || v < 0 || v > 3650) {
232+
return reply.code(400).send({ error: 'trashRetentionDays must be an integer between 0 and 3650' });
233+
}
234+
await prisma.user.update({ where: { id: req.user!.id }, data: { trashRetentionDays: v } });
235+
await audit(req, 'account.trashretention.set', { target: String(v) });
236+
return { trashRetentionDays: v };
237+
});
238+
219239
// POST /account/wipe — permanently delete ALL of the user's spaces & files (password-gated).
220240
// The account itself is kept; this is the "start fresh" / panic button.
221241
app.post('/wipe', async (req, reply) => {

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

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { generateUniqueQuickCode, isCodeTakenError } from '../services/quickCode
1212
import { toPublicQuickCode, toPublicUser } from '../lib/serialize.js';
1313
import { getGlobalCapBytes, getGlobalUsedBytes } from '../services/quota.js';
1414
import { ensureFastUploadFolder } from '../services/systemFolders.js';
15+
import { wipeOwnerContent } from '../services/trash.js';
1516
import { runMaintenance } from '../services/maintenance.js';
1617
import {
1718
commitsBehind,
@@ -126,6 +127,18 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
126127
return { ok: true };
127128
});
128129

130+
// POST /admin/users/:id/purge-content — empty a user's storage (all files, folders and the
131+
// Shared Spaces they own) WITHOUT deleting the account. Frees their quota; the account, its
132+
// login and settings remain.
133+
app.post('/users/:id/purge-content', async (req, reply) => {
134+
const { id } = req.params as { id: string };
135+
const target = await prisma.user.findUnique({ where: { id } });
136+
if (!target) return reply.code(404).send({ error: 'User not found' });
137+
const result = await wipeOwnerContent(app.ctx, id);
138+
await audit(req, 'admin.user.purgeContent', { target: id });
139+
return result;
140+
});
141+
129142
// ── Operational alerts ───────────────────────────────────────────────────--
130143
app.get('/alerts', async () => {
131144
const [globalUsedBytes, globalCapBytes, infectedCount, users] = await Promise.all([

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

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { parseOr400 } from '../lib/validate.js';
55
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
66
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
77
import { decryptServerFile } from '../services/download.js';
8-
import { trashFile } from '../services/trash.js';
8+
import { hardDeleteFile, trashFile } from '../services/trash.js';
99
import { pruneVersions, snapshotVersion } from '../services/versioning.js';
1010
import { adjustUsage } from '../services/quota.js';
1111
import { toPublicFile } from '../lib/serialize.js';
@@ -212,10 +212,18 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
212212
return { file: toPublicFile(updated) };
213213
});
214214

215-
// DELETE /files/:id — move the file to the Trash (soft-delete). It keeps counting against
216-
// quota until it is restored or permanently purged from the Trash.
215+
// DELETE /files/:id — Trash a normal file (recoverable, still counts against quota until
216+
// purged). A Zero-Knowledge file is permanently deleted at once instead (opaque ciphertext has
217+
// no business sitting in a recoverable Trash); this also frees its quota immediately.
217218
app.delete('/:id', async (req, reply) => {
218219
const { id } = req.params as { id: string };
220+
const file = await prisma.fileObject.findFirst({ where: { id, ownerId: req.user!.id, spaceId: null } });
221+
if (!file) return reply.code(404).send({ error: 'File not found' });
222+
if (file.encMode === 'ZK') {
223+
await hardDeleteFile(app.ctx, req.user!.id, id);
224+
await audit(req, 'file.delete', { target: id });
225+
return { ok: true };
226+
}
219227
const ok = await trashFile(req.user!.id, id);
220228
if (!ok) return reply.code(404).send({ error: 'File not found' });
221229
await audit(req, 'file.trash', { target: id });

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

Lines changed: 10 additions & 3 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 { trashFolder } from '../services/trash.js';
6+
import { hardDeleteFolder, 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's personal
@@ -103,10 +103,17 @@ export const folderRoutes: FastifyPluginAsync = async (app) => {
103103
}
104104
});
105105

106-
// DELETE /folders/:id — move the folder (and its whole subtree) to the Trash. Nothing is
107-
// destroyed and no quota is released until it is purged from the Trash.
106+
// DELETE /folders/:id — Trash a normal folder (recoverable). A Zero-Knowledge vault is instead
107+
// permanently deleted at once: its contents are opaque ciphertext with no use in a Trash.
108108
app.delete('/:id', async (req, reply) => {
109109
const { id } = req.params as { id: string };
110+
const folder = await prisma.folder.findFirst({ where: { id, ownerId: req.user!.id, spaceId: null } });
111+
if (!folder) return reply.code(404).send({ error: 'Folder not found' });
112+
if (folder.isZeroKnowledge) {
113+
await hardDeleteFolder(app.ctx, req.user!.id, id);
114+
await audit(req, 'folder.delete', { target: id });
115+
return { ok: true };
116+
}
110117
const ok = await trashFolder(req.user!.id, id);
111118
if (!ok) return reply.code(404).send({ error: 'Folder not found' });
112119
await audit(req, 'folder.trash', { target: id });

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

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +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';
12+
import { hardDeleteFile } from '../services/trash.js';
1313
import { audit } from '../services/audit.js';
1414
import { FileTooLargeError } from '../services/ingest.js';
1515
import { Transform, pipeline, type Readable } from 'node:stream';
@@ -218,15 +218,17 @@ export const zkRoutes: FastifyPluginAsync = async (app) => {
218218
return reply.send(app.ctx.storage.createReadStream(file.storageKey));
219219
});
220220

221-
// DELETE /zk/files/:id — move a vault file to the Trash (soft-delete).
221+
// DELETE /zk/files/:id — permanently delete a vault file immediately (NOT via the Trash).
222+
// Vault content is opaque ciphertext the server can't preview or meaningfully restore, so a
223+
// recoverable Trash adds nothing — deleting means gone, and the quota is freed at once.
222224
app.delete('/files/:id', async (req, reply) => {
223225
const { id } = req.params as { id: string };
224226
const file = await prisma.fileObject.findFirst({
225227
where: { id, ownerId: req.user!.id, encMode: 'ZK', deletedAt: null },
226228
});
227229
if (!file) return reply.code(404).send({ error: 'File not found' });
228-
await trashFile(req.user!.id, file.id);
229-
await audit(req, 'zk.trash', { target: file.id });
230+
await hardDeleteFile(app.ctx, req.user!.id, file.id);
231+
await audit(req, 'zk.delete', { target: file.id });
230232
return { ok: true };
231233
});
232234
};

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

Lines changed: 4 additions & 4 deletions
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, trashFile, trashFolder, emptyTrash } from './trash.js';
14+
import { purgeExpiredTrashPerUser, trashFile, trashFolder, emptyTrash } from './trash.js';
1515

1616
export interface ReconcileResult {
1717
usersChecked: number;
@@ -133,9 +133,9 @@ export async function enforceInactivityWipe(ctx: AppContext, log: FastifyBaseLog
133133

134134
/** Run one full maintenance pass. Safe to call manually (admin) or on a timer. */
135135
export async function runMaintenance(ctx: AppContext, log: FastifyBaseLogger) {
136-
// Purge Trash past its retention window first, so reconcile/orphan steps see the freed space.
137-
const trashCutoff = new Date(Date.now() - ctx.env.TRASH_RETENTION_DAYS * 24 * 60 * 60 * 1000);
138-
const trashPurged = await purgeExpiredTrash(ctx, trashCutoff);
136+
// Purge each user's Trash per their own retention setting first, so the reconcile/orphan steps
137+
// below see the freed space.
138+
const trashPurged = await purgeExpiredTrashPerUser(ctx);
139139
const reconcile = await reconcileUsage();
140140
const orphans = await collectOrphans(ctx, ctx.env.ORPHAN_GRACE_HOURS, log);
141141
const audit = await pruneAuditLog(ctx.env.AUDIT_RETENTION_DAYS);

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

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,64 @@ export async function purgeFolder(ctx: AppContext, ownerId: string, folderId: st
124124
return true;
125125
}
126126

127+
// ── Permanent delete (no Trash) ──────────────────────────────────────────────
128+
129+
/**
130+
* Permanently delete a file immediately, bypassing the Trash. Used for Zero-Knowledge content:
131+
* it is opaque ciphertext the server can't preview or restore meaningfully, so a recoverable
132+
* Trash adds no value — deleting means gone.
133+
*/
134+
export async function hardDeleteFile(ctx: AppContext, ownerId: string, fileId: string): Promise<boolean> {
135+
const file = await prisma.fileObject.findFirst({
136+
where: { id: fileId, ownerId, spaceId: null },
137+
select: { id: true, storageKey: true, sizeBytes: true },
138+
});
139+
if (!file) return false;
140+
await purgeFiles(ctx, ownerId, [file]);
141+
return true;
142+
}
143+
144+
/** Permanently delete a folder subtree immediately, bypassing the Trash (Zero-Knowledge vaults). */
145+
export async function hardDeleteFolder(ctx: AppContext, ownerId: string, folderId: string): Promise<boolean> {
146+
const folder = await prisma.folder.findFirst({ where: { id: folderId, ownerId, spaceId: null } });
147+
if (!folder) return false;
148+
const ids = await subtreeFolderIds(ownerId, folderId);
149+
const files = await prisma.fileObject.findMany({
150+
where: { folderId: { in: ids } },
151+
select: { id: true, storageKey: true, sizeBytes: true },
152+
});
153+
await purgeFiles(ctx, ownerId, files);
154+
await prisma.folder.deleteMany({ where: { id: { in: ids } } });
155+
return true;
156+
}
157+
158+
export interface WipeContentResult {
159+
filesDeleted: number;
160+
freedBytes: number;
161+
}
162+
163+
/**
164+
* Permanently delete ALL of a user's stored content while KEEPING their account: every file
165+
* (personal Drive, vaults, Trash, and the Shared Spaces they own), the folders, and the Shared
166+
* Spaces they own are removed, and their usedBytes is reset to 0. Their membership of spaces
167+
* owned by OTHER users is untouched. Used by the admin "empty a user's storage" action and by
168+
* the self-service account wipe.
169+
*/
170+
export async function wipeOwnerContent(ctx: AppContext, ownerId: string): Promise<WipeContentResult> {
171+
const files = await prisma.fileObject.findMany({
172+
where: { ownerId },
173+
select: { id: true, storageKey: true, sizeBytes: true },
174+
});
175+
const freed = await purgeFiles(ctx, ownerId, files); // blobs + versions + rows + quota
176+
// Drop the Shared Spaces this user owns (cascades their members and any leftover space folders),
177+
// then the personal folder trees.
178+
await prisma.sharedSpace.deleteMany({ where: { ownerId } });
179+
await prisma.folder.deleteMany({ where: { ownerId } });
180+
// Authoritative reset — the user now stores nothing.
181+
await prisma.user.update({ where: { id: ownerId }, data: { usedBytes: 0n } });
182+
return { filesDeleted: files.length, freedBytes: freed };
183+
}
184+
127185
export async function emptyTrash(ctx: AppContext, ownerId: string): Promise<void> {
128186
const folders = await prisma.folder.findMany({
129187
where: { ownerId, spaceId: null, deletedAt: { not: null }, OR: [{ parentId: null }, { parent: { deletedAt: null } }] },
@@ -165,6 +223,38 @@ export async function purgeExpiredTrash(ctx: AppContext, cutoff: Date): Promise<
165223
return purged;
166224
}
167225

226+
/** Purge one owner's items trashed before `cutoff`. */
227+
async function purgeExpiredTrashForOwner(ctx: AppContext, ownerId: string, cutoff: Date): Promise<number> {
228+
const folders = await prisma.folder.findMany({
229+
where: { ownerId, spaceId: null, deletedAt: { lt: cutoff } },
230+
select: { id: true },
231+
});
232+
for (const f of folders) await purgeFolder(ctx, ownerId, f.id).catch(() => {});
233+
const files = await prisma.fileObject.findMany({
234+
where: { ownerId, spaceId: null, deletedAt: { lt: cutoff } },
235+
select: { id: true, storageKey: true, sizeBytes: true },
236+
});
237+
await purgeFiles(ctx, ownerId, files).catch(() => {});
238+
return folders.length + files.length;
239+
}
240+
241+
/**
242+
* Maintenance: purge each user's Trash according to THAT user's chosen retention window
243+
* (User.trashRetentionDays; 0 = never auto-purge). Replaces a single instance-wide cutoff so
244+
* everyone controls how long their own deleted items linger.
245+
*/
246+
export async function purgeExpiredTrashPerUser(ctx: AppContext): Promise<number> {
247+
const users = await prisma.user.findMany({ select: { id: true, trashRetentionDays: true } });
248+
let purged = 0;
249+
for (const u of users) {
250+
const days = u.trashRetentionDays ?? 7;
251+
if (days <= 0) continue; // 0 = keep until manually emptied
252+
const cutoff = new Date(Date.now() - days * 24 * 60 * 60 * 1000);
253+
purged += await purgeExpiredTrashForOwner(ctx, u.id, cutoff).catch(() => 0);
254+
}
255+
return purged;
256+
}
257+
168258
// ── Trash listing ──────────────────────────────────────────────────────────--
169259

170260
export interface TrashEntry {

0 commit comments

Comments
 (0)