Skip to content

Commit 58b9b11

Browse files
Add upload progress, admin alerts, and GDPR self-service
- Upload progress: an XHR-based uploader reports byte progress; the Drive shows a per-file progress bar (fetch cannot report upload progress). - Admin alerts: GET /admin/alerts surfaces operational warnings (infected files, global storage near the cap, users near their quota), shown on the Admin page. - GDPR self-service: GET /account/export downloads a JSON copy of the user's data (profile, folders, file metadata, shares, sessions, recent activity); POST /account/delete permanently removes the account and its storage blobs after a password confirmation, with a guard against deleting the only administrator. Tests: export, delete (+ wrong password, + last-admin guard), and infected-file alerts. Suite now 32 API tests. Checklist updated.
1 parent e6113ba commit 58b9b11

9 files changed

Lines changed: 305 additions & 5 deletions

File tree

‎TEST-CHECKLIST.md‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,4 +100,17 @@ Versioning (text-like files: txt, md, csv, json, log, yml, …):
100100
creates a separate file (no versioning), as before.
101101
- [ ] **Quota**: deleting a versioned file frees the space of the file *and* its versions.
102102

103+
## Upload progress, admin alerts & GDPR self-service (lot 4)
104+
105+
- [ ] **Upload progress**: upload a larger file in the Drive → a progress bar shows the
106+
percentage (and "Uploading X of N" for multiple files).
107+
- [ ] **Admin alerts**: the Admin page shows an Alerts box when something needs attention —
108+
e.g. an infected file exists, global storage is ≥90% of the cap, or a user is ≥90% of
109+
their quota. (Set a small global cap to see the storage warning.)
110+
- [ ] **Export my data**: Account → "Export my data" downloads a JSON file with your
111+
profile, folders, file metadata, shares, sessions and recent activity.
112+
- [ ] **Delete my account**: Account → "Delete my account" (password required) removes the
113+
account and all files, then signs you out. The only administrator cannot delete
114+
themselves.
115+
103116
<!-- New features are appended below as they are built. -->

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

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
/**
2+
* Self-service account actions for data-protection (GDPR): export a copy of your data, and
3+
* permanently delete your account. Both are scoped strictly to the requesting user.
4+
*/
5+
import type { FastifyPluginAsync } from 'fastify';
6+
import { passwordConfirmSchema } from '@opencoperlock/shared';
7+
import { prisma } from '../db.js';
8+
import { parseOr400 } from '../lib/validate.js';
9+
import { verifyPassword } from '../services/password.js';
10+
import { remainingRecoveryCodes } from '../services/recovery.js';
11+
import { toPublicFile, toPublicFolder, toPublicShare, toPublicUser } from '../lib/serialize.js';
12+
import { clearSessionCookie } from '../lib/cookies.js';
13+
import { audit } from '../services/audit.js';
14+
15+
export const accountRoutes: FastifyPluginAsync = async (app) => {
16+
app.addHook('preHandler', app.requireAuth);
17+
const secureCookies = app.ctx.env.NODE_ENV === 'production';
18+
19+
// GET /account/export — a JSON copy of the user's data (metadata, not file contents).
20+
app.get('/export', async (req, reply) => {
21+
const userId = req.user!.id;
22+
const [user, folders, files, shares, sessions, logs] = await Promise.all([
23+
prisma.user.findUniqueOrThrow({ where: { id: userId } }),
24+
prisma.folder.findMany({ where: { ownerId: userId } }),
25+
prisma.fileObject.findMany({ where: { ownerId: userId } }),
26+
prisma.shareLink.findMany({ where: { ownerId: userId } }),
27+
prisma.session.findMany({
28+
where: { userId },
29+
select: { ip: true, userAgent: true, lastSeenAt: true, createdAt: true },
30+
}),
31+
prisma.auditLog.findMany({ where: { actorId: userId }, orderBy: { createdAt: 'desc' }, take: 1000 }),
32+
]);
33+
34+
const data = {
35+
exportedAt: new Date().toISOString(),
36+
user: { ...toPublicUser(user), twoFactorEnabled: user.totpEnabled },
37+
recoveryCodesRemaining: await remainingRecoveryCodes(userId),
38+
folders: folders.map(toPublicFolder),
39+
files: files.map(toPublicFile),
40+
shares: shares.map((s) => toPublicShare(s, '')),
41+
sessions: sessions.map((s) => ({
42+
ip: s.ip,
43+
userAgent: s.userAgent,
44+
lastSeenAt: s.lastSeenAt.toISOString(),
45+
createdAt: s.createdAt.toISOString(),
46+
})),
47+
activity: logs.map((l) => ({ action: l.action, target: l.target, ip: l.ip, at: l.createdAt.toISOString() })),
48+
};
49+
50+
await audit(req, 'account.export');
51+
reply
52+
.header('Content-Type', 'application/json')
53+
.header('Content-Disposition', 'attachment; filename="opencoperlock-export.json"');
54+
return reply.send(JSON.stringify(data, null, 2));
55+
});
56+
57+
// POST /account/delete — permanently delete the account (password required). Removes the
58+
// user's storage blobs first, then the row (which cascades folders/files/shares/etc.).
59+
app.post('/delete', async (req, reply) => {
60+
const body = parseOr400(reply, passwordConfirmSchema, req.body);
61+
if (!body) return;
62+
const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } });
63+
if (!(await verifyPassword(user.passwordHash, body.password))) {
64+
return reply.code(401).send({ error: 'Incorrect password' });
65+
}
66+
// Don't allow the last admin to delete themselves and lock the instance out.
67+
if (user.role === 'ADMIN') {
68+
const admins = await prisma.user.count({ where: { role: 'ADMIN' } });
69+
if (admins <= 1) {
70+
return reply.code(400).send({ error: 'Cannot delete the only administrator account' });
71+
}
72+
}
73+
74+
const [files, versions] = await Promise.all([
75+
prisma.fileObject.findMany({ where: { ownerId: user.id }, select: { storageKey: true } }),
76+
prisma.fileVersion.findMany({ where: { file: { ownerId: user.id } }, select: { storageKey: true } }),
77+
]);
78+
for (const f of [...files, ...versions]) {
79+
await app.ctx.storage.delete(f.storageKey).catch(() => {});
80+
}
81+
await audit(req, 'account.delete', { actorId: user.id, target: user.id });
82+
await prisma.user.delete({ where: { id: user.id } });
83+
clearSessionCookie(reply, secureCookies);
84+
return { ok: true };
85+
});
86+
};

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,31 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
113113
return { ok: true };
114114
});
115115

116+
// ── Operational alerts ───────────────────────────────────────────────────--
117+
app.get('/alerts', async () => {
118+
const [globalUsedBytes, globalCapBytes, infectedCount, users] = await Promise.all([
119+
getGlobalUsedBytes(),
120+
getGlobalCapBytes(),
121+
prisma.fileObject.count({ where: { avStatus: 'INFECTED' } }),
122+
prisma.user.findMany({ where: { quotaBytes: { not: null } }, select: { email: true, usedBytes: true, quotaBytes: true } }),
123+
]);
124+
125+
const warnings: string[] = [];
126+
if (globalCapBytes > 0 && globalUsedBytes / globalCapBytes >= 0.9) {
127+
warnings.push(`Global storage is at ${Math.round((globalUsedBytes / globalCapBytes) * 100)}% of the cap.`);
128+
}
129+
if (infectedCount > 0) {
130+
warnings.push(`${infectedCount} file(s) were flagged as infected and quarantined from scanning.`);
131+
}
132+
const nearQuota = users
133+
.filter((u) => u.quotaBytes && Number(u.usedBytes) / Number(u.quotaBytes) >= 0.9)
134+
.map((u) => u.email);
135+
if (nearQuota.length > 0) {
136+
warnings.push(`${nearQuota.length} user(s) are near their quota: ${nearQuota.slice(0, 5).join(', ')}.`);
137+
}
138+
return { warnings, infectedCount };
139+
});
140+
116141
// ── Maintenance (manual trigger) ─────────────────────────────────────────--
117142
app.post('/maintenance', async (req) => {
118143
const summary = await runMaintenance(app.ctx, req.log);

‎apps/api/src/server.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { remoteRoutes } from './routes/remote.js';
1616
import { shareRoutes } from './routes/shares.js';
1717
import { sharePublicRoutes } from './routes/share-public.js';
1818
import { twoFactorRoutes } from './routes/twofa.js';
19+
import { accountRoutes } from './routes/account.js';
1920
import { adminRoutes } from './routes/admin.js';
2021

2122
export async function buildServer(ctx: AppContext): Promise<FastifyInstance> {
@@ -75,6 +76,7 @@ export async function buildServer(ctx: AppContext): Promise<FastifyInstance> {
7576
await app.register(shareRoutes, { prefix: '/shares' });
7677
await app.register(sharePublicRoutes, { prefix: '/s' });
7778
await app.register(twoFactorRoutes, { prefix: '/2fa' });
79+
await app.register(accountRoutes, { prefix: '/account' });
7880
await app.register(adminRoutes, { prefix: '/admin' });
7981

8082
app.setErrorHandler((err: { statusCode?: number; message?: string }, req, reply) => {

‎apps/api/test/integration.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,77 @@ runIf('API integration', () => {
421421
});
422422
});
423423

424+
describe('account (GDPR) and admin alerts', () => {
425+
it('exports the user data as JSON', async () => {
426+
await createUser({ email: 'exp@test.local', password: 'correct-horse-battery' });
427+
const auth = await login(app, 'exp@test.local', 'correct-horse-battery');
428+
await uploadFile(app, '/files', auth, 'a.txt', Buffer.from('hi'));
429+
const res = await app.inject({ method: 'GET', url: '/account/export', headers: { cookie: auth.cookie } });
430+
expect(res.statusCode).toBe(200);
431+
const data = JSON.parse(res.body);
432+
expect(data.user.email).toBe('exp@test.local');
433+
expect(data.files).toHaveLength(1);
434+
expect(Array.isArray(data.activity)).toBe(true);
435+
});
436+
437+
it('deletes the account after password confirmation, removing data', async () => {
438+
const user = await createUser({ email: 'del@test.local', password: 'correct-horse-battery' });
439+
const auth = await login(app, 'del@test.local', 'correct-horse-battery');
440+
await uploadFile(app, '/files', auth, 'a.txt', Buffer.from('bye'));
441+
442+
const wrong = await app.inject({
443+
method: 'POST',
444+
url: '/account/delete',
445+
headers: authHeaders(auth),
446+
payload: { password: 'nope' },
447+
});
448+
expect(wrong.statusCode).toBe(401);
449+
450+
const ok = await app.inject({
451+
method: 'POST',
452+
url: '/account/delete',
453+
headers: authHeaders(auth),
454+
payload: { password: 'correct-horse-battery' },
455+
});
456+
expect(ok.statusCode).toBe(200);
457+
expect(await prisma.user.findUnique({ where: { id: user.id } })).toBeNull();
458+
expect(await prisma.fileObject.count({ where: { ownerId: user.id } })).toBe(0);
459+
});
460+
461+
it('refuses to delete the only administrator', async () => {
462+
await createUser({ email: 'soleadmin@test.local', password: 'correct-horse-battery', role: 'ADMIN' });
463+
const auth = await login(app, 'soleadmin@test.local', 'correct-horse-battery');
464+
const res = await app.inject({
465+
method: 'POST',
466+
url: '/account/delete',
467+
headers: authHeaders(auth),
468+
payload: { password: 'correct-horse-battery' },
469+
});
470+
expect(res.statusCode).toBe(400);
471+
});
472+
473+
it('reports infected-file alerts to admins', async () => {
474+
const admin = await createUser({ email: 'al@test.local', password: 'correct-horse-battery', role: 'ADMIN' });
475+
await prisma.fileObject.create({
476+
data: {
477+
ownerId: admin.id,
478+
name: 'bad',
479+
sizeBytes: 1n,
480+
storageKey: 'ab/cd/infected1',
481+
encMode: 'SERVER',
482+
wrappedKey: 'k',
483+
iv: 'i',
484+
authTag: 't',
485+
avStatus: 'INFECTED',
486+
},
487+
});
488+
const auth = await login(app, 'al@test.local', 'correct-horse-battery');
489+
const res = await app.inject({ method: 'GET', url: '/admin/alerts', headers: { cookie: auth.cookie } });
490+
expect(res.json().infectedCount).toBeGreaterThanOrEqual(1);
491+
expect(res.json().warnings.some((w: string) => w.includes('infected'))).toBe(true);
492+
});
493+
});
494+
424495
describe('admin maintenance', () => {
425496
it('reconciles a drifted usedBytes counter', async () => {
426497
const admin = await createUser({

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

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
* and a list of active sessions (with IP / user-agent) that the user can revoke.
66
*/
77
import { useCallback, useEffect, useState } from 'react';
8-
import { api, ApiError } from '@/lib/api';
8+
import { useRouter } from 'next/navigation';
9+
import { api, API_URL, ApiError } from '@/lib/api';
10+
import { useAuth } from '@/lib/auth';
911

1012
interface TwoFaStatus {
1113
enabled: boolean;
@@ -26,6 +28,8 @@ interface SessionInfo {
2628
}
2729

2830
export default function AccountPage() {
31+
const { refresh } = useAuth();
32+
const router = useRouter();
2933
const [status, setStatus] = useState<TwoFaStatus | null>(null);
3034
const [setup, setSetup] = useState<SetupData | null>(null);
3135
const [token, setToken] = useState('');
@@ -102,6 +106,18 @@ export default function AccountPage() {
102106
});
103107
}
104108

109+
async function deleteAccount() {
110+
const password = window.prompt(
111+
'This permanently deletes your account and all your files. Enter your password to confirm.',
112+
);
113+
if (!password) return;
114+
await wrap(async () => {
115+
await api.post('/account/delete', { password });
116+
await refresh();
117+
router.replace('/login');
118+
});
119+
}
120+
105121
return (
106122
<div className="space-y-8">
107123
<h1 className="text-lg font-semibold">Account security</h1>
@@ -201,6 +217,23 @@ export default function AccountPage() {
201217
))}
202218
</div>
203219
</section>
220+
221+
{/* Data & privacy (GDPR) */}
222+
<section className="card space-y-3">
223+
<h2 className="font-semibold">Your data</h2>
224+
<p className="text-sm text-neutral-500">
225+
Download a copy of your account data, or permanently delete your account and all of
226+
your files. Deletion cannot be undone.
227+
</p>
228+
<div className="flex gap-2">
229+
<a className="btn-ghost" href={`${API_URL}/account/export`}>
230+
Export my data
231+
</a>
232+
<button className="btn-danger" onClick={deleteAccount}>
233+
Delete my account
234+
</button>
235+
</div>
236+
</section>
204237
</div>
205238
);
206239
}

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

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,23 @@ export default function AdminPage() {
3333
// new-user form
3434
const [nu, setNu] = useState({ email: '', password: '', role: 'USER' });
3535

36+
const [alerts, setAlerts] = useState<string[]>([]);
37+
3638
const loadAll = useCallback(async () => {
37-
const [s, u, c, a, settings] = await Promise.all([
39+
const [s, u, c, a, settings, al] = await Promise.all([
3840
api.get<Stats>('/admin/stats'),
3941
api.get<{ users: PublicUser[] }>('/admin/users'),
4042
api.get<{ codes: PublicQuickCode[] }>('/admin/quick-codes'),
4143
api.get<{ logs: AuditEntry[] }>('/admin/audit?limit=50'),
4244
api.get<{ globalStorageCapBytes: number }>('/admin/settings'),
45+
api.get<{ warnings: string[] }>('/admin/alerts'),
4346
]);
4447
setStats(s);
4548
setUsers(u.users);
4649
setCodes(c.codes);
4750
setAudit(a.logs);
4851
setCap(String(s.globalCapBytes));
52+
setAlerts(al.warnings);
4953
void settings;
5054
}, []);
5155

@@ -67,6 +71,17 @@ export default function AdminPage() {
6771
<div className="space-y-8">
6872
{error && <p className="text-sm text-red-600">{error}</p>}
6973

74+
{alerts.length > 0 && (
75+
<div className="rounded-lg border border-amber-300 bg-amber-50 p-3 dark:border-amber-800 dark:bg-amber-950">
76+
<p className="mb-1 text-sm font-medium text-amber-800 dark:text-amber-200">Alerts</p>
77+
<ul className="list-inside list-disc text-sm text-amber-800 dark:text-amber-200">
78+
{alerts.map((a, i) => (
79+
<li key={i}>{a}</li>
80+
))}
81+
</ul>
82+
</div>
83+
)}
84+
7085
{/* Stats */}
7186
{stats && (
7287
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">

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

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ export default function DrivePage() {
1313
const [currentId, setCurrentId] = useState<string | null>(null);
1414
const [error, setError] = useState<string | null>(null);
1515
const [uploading, setUploading] = useState(false);
16+
const [progress, setProgress] = useState<{ index: number; total: number; fraction: number } | null>(null);
1617
const fileInput = useRef<HTMLInputElement>(null);
1718

1819
const loadFolders = useCallback(async () => {
@@ -55,20 +56,25 @@ export default function DrivePage() {
5556

5657
async function onUpload(list: FileList | null) {
5758
if (!list || list.length === 0) return;
59+
const files = Array.from(list);
5860
setUploading(true);
5961
setError(null);
6062
try {
61-
for (const file of Array.from(list)) {
63+
for (let i = 0; i < files.length; i += 1) {
6264
const form = new FormData();
63-
form.append('file', file);
65+
form.append('file', files[i]);
6466
const q = currentId ? `?folderId=${currentId}` : '';
65-
await api.upload(`/files${q}`, form);
67+
setProgress({ index: i + 1, total: files.length, fraction: 0 });
68+
await api.uploadWithProgress(`/files${q}`, form, (fraction) =>
69+
setProgress({ index: i + 1, total: files.length, fraction }),
70+
);
6671
}
6772
await Promise.all([loadFiles(currentId), refresh()]);
6873
} catch (err) {
6974
setError(err instanceof ApiError ? err.message : 'Upload failed');
7075
} finally {
7176
setUploading(false);
77+
setProgress(null);
7278
if (fileInput.current) fileInput.current.value = '';
7379
}
7480
}
@@ -230,6 +236,23 @@ export default function DrivePage() {
230236

231237
{error && <p className="text-sm text-red-600">{error}</p>}
232238

239+
{progress && (
240+
<div className="space-y-1">
241+
<div className="flex justify-between text-xs text-neutral-500">
242+
<span>
243+
Uploading {progress.index} of {progress.total}…
244+
</span>
245+
<span>{Math.round(progress.fraction * 100)}%</span>
246+
</div>
247+
<div className="h-1.5 w-full overflow-hidden rounded bg-neutral-200 dark:bg-neutral-800">
248+
<div
249+
className="h-full bg-accent transition-[width] duration-150"
250+
style={{ width: `${Math.round(progress.fraction * 100)}%` }}
251+
/>
252+
</div>
253+
</div>
254+
)}
255+
233256
<div
234257
className="card divide-y divide-neutral-100 p-0 dark:divide-neutral-800"
235258
onDragOver={(e) => e.preventDefault()}

0 commit comments

Comments
 (0)