Skip to content

Commit 5bfffa6

Browse files
Quick-Upload codes: self-service per-user management
Quick-Upload codes were admin-only. Now every user creates and manages their own from Account settings: pick a target folder (their own non-vault folders, default Fast-Upload), an optional memorable code and a usage limit, copy a ready /q?code=… share link, and revoke. - account.ts: GET/POST/DELETE /account/quick-codes, strictly scoped to createdById = the requesting user (mirrors the admin logic, owner-checked). - Account page: new Quick-Upload section; the public /q page now prefills the code from the ?code= query so shared links work in one click. - The admin global view is unchanged.
1 parent 119a4e9 commit 5bfffa6

4 files changed

Lines changed: 182 additions & 6 deletions

File tree

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

Lines changed: 62 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,78 @@
33
* permanently delete your account. Both are scoped strictly to the requesting user.
44
*/
55
import type { FastifyPluginAsync } from 'fastify';
6-
import { passwordConfirmSchema } from '@opencoperlock/shared';
6+
import { passwordConfirmSchema, createQuickCodeSchema, randomCode } from '@opencoperlock/shared';
77
import { prisma } from '../db.js';
88
import { parseOr400 } from '../lib/validate.js';
9-
import { verifyPassword } from '../services/password.js';
9+
import { verifyPassword, hashPassword } from '../services/password.js';
1010
import { remainingRecoveryCodes } from '../services/recovery.js';
11-
import { toPublicFile, toPublicFolder, toPublicShare, toPublicUser } from '../lib/serialize.js';
11+
import { toPublicFile, toPublicFolder, toPublicShare, toPublicUser, toPublicQuickCode } from '../lib/serialize.js';
1212
import { clearSessionCookie } from '../lib/cookies.js';
1313
import { audit } from '../services/audit.js';
1414

1515
export const accountRoutes: FastifyPluginAsync = async (app) => {
1616
app.addHook('preHandler', app.requireAuth);
1717
const secureCookies = app.ctx.env.NODE_ENV === 'production';
1818

19+
// ── Quick-Upload codes (self-service) ────────────────────────────────────────
20+
// Every user manages their OWN Quick-Upload codes here; an anonymous guest with the code
21+
// can drop files straight into the chosen folder. Strictly scoped to the requesting user.
22+
23+
app.get('/quick-codes', async (req) => {
24+
const codes = await prisma.quickUploadCode.findMany({
25+
where: { createdById: req.user!.id },
26+
orderBy: { createdAt: 'desc' },
27+
});
28+
return { codes: codes.map(toPublicQuickCode) };
29+
});
30+
31+
app.post('/quick-codes', async (req, reply) => {
32+
const body = parseOr400(reply, createQuickCodeSchema, req.body);
33+
if (!body) return;
34+
35+
if (body.targetFolderId) {
36+
const folder = await prisma.folder.findFirst({
37+
where: { id: body.targetFolderId, ownerId: req.user!.id },
38+
});
39+
if (!folder) return reply.code(404).send({ error: 'Target folder not found' });
40+
if (folder.isZeroKnowledge) {
41+
return reply.code(400).send({ error: 'A vault cannot be a Quick-Upload target' });
42+
}
43+
}
44+
45+
const codeValue = body.code ?? randomCode();
46+
if (body.code) {
47+
const clash = await prisma.quickUploadCode.findUnique({ where: { code: codeValue } });
48+
if (clash) return reply.code(409).send({ error: 'This code is already in use' });
49+
}
50+
51+
const code = await prisma.quickUploadCode.create({
52+
data: {
53+
code: codeValue,
54+
createdById: req.user!.id,
55+
targetFolderId: body.targetFolderId ?? null,
56+
maxBytes: body.maxBytes == null ? null : BigInt(body.maxBytes),
57+
expiresAt: body.expiresAt ?? null,
58+
usageLimit: body.usageLimit ?? null,
59+
passwordHash: body.password ? await hashPassword(body.password) : null,
60+
},
61+
});
62+
await audit(req, 'account.quickcode.create', { target: code.id });
63+
return reply.code(201).send({ code: toPublicQuickCode(code) });
64+
});
65+
66+
app.delete('/quick-codes/:id', async (req, reply) => {
67+
const { id } = req.params as { id: string };
68+
// Scope the delete to the owner so a user can only remove their own codes.
69+
const existing = await prisma.quickUploadCode.findFirst({
70+
where: { id, createdById: req.user!.id },
71+
});
72+
if (!existing) return reply.code(404).send({ error: 'Code not found' });
73+
await prisma.quickUploadCode.delete({ where: { id } });
74+
await audit(req, 'account.quickcode.delete', { target: id });
75+
return { ok: true };
76+
});
77+
1978
// GET /account/export — a JSON copy of the user's data (metadata, not file contents).
2079
app.get('/export', async (req, reply) => {
2180
const userId = req.user!.id;

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

Lines changed: 90 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
*/
77
import { useCallback, useEffect, useState } from 'react';
88
import { useRouter } from 'next/navigation';
9+
import type { PublicQuickCode, PublicFolder } from '@opencoperlock/shared/client';
910
import { api, API_URL, ApiError } from '@/lib/api';
1011
import { useAuth } from '@/lib/auth';
1112
import { useT } from '@/lib/i18n';
12-
import { prompt } from '@/components/ui/overlays';
13+
import { prompt, toast } from '@/components/ui/overlays';
1314

1415
interface TwoFaStatus {
1516
enabled: boolean;
@@ -38,15 +39,22 @@ export default function AccountPage() {
3839
const [token, setToken] = useState('');
3940
const [recoveryCodes, setRecoveryCodes] = useState<string[] | null>(null);
4041
const [sessions, setSessions] = useState<SessionInfo[]>([]);
42+
const [codes, setCodes] = useState<PublicQuickCode[]>([]);
43+
const [folders, setFolders] = useState<PublicFolder[]>([]);
44+
const [nc, setNc] = useState({ code: '', targetFolderId: '', usageLimit: '' });
4145
const [error, setError] = useState<string | null>(null);
4246

4347
const load = useCallback(async () => {
44-
const [s, sess] = await Promise.all([
48+
const [s, sess, qc, fl] = await Promise.all([
4549
api.get<TwoFaStatus>('/2fa/status'),
4650
api.get<{ sessions: SessionInfo[] }>('/auth/sessions'),
51+
api.get<{ codes: PublicQuickCode[] }>('/account/quick-codes'),
52+
api.get<{ folders: PublicFolder[] }>('/folders'),
4753
]);
4854
setStatus(s);
4955
setSessions(sess.sessions);
56+
setCodes(qc.codes);
57+
setFolders(fl.folders);
5058
}, []);
5159

5260
useEffect(() => {
@@ -224,6 +232,86 @@ export default function AccountPage() {
224232
</div>
225233
</section>
226234

235+
{/* Quick-Upload codes */}
236+
<section className="card space-y-3">
237+
<h2 className="font-semibold">{t('account.quickCodes')}</h2>
238+
<p className="text-sm text-neutral-500">{t('account.quickCodesHint')}</p>
239+
<div className="flex flex-wrap items-end gap-2">
240+
<input
241+
className="input max-w-[12rem] font-mono uppercase tracking-wide"
242+
placeholder={t('account.quickCodePlaceholder')}
243+
value={nc.code}
244+
onChange={(e) => setNc({ ...nc, code: e.target.value.toUpperCase() })}
245+
/>
246+
<select
247+
className="input max-w-[14rem]"
248+
value={nc.targetFolderId}
249+
onChange={(e) => setNc({ ...nc, targetFolderId: e.target.value })}
250+
>
251+
<option value="">{t('account.quickCodeDefaultFolder')}</option>
252+
{folders
253+
.filter((f) => !f.isZeroKnowledge)
254+
.map((f) => (
255+
<option key={f.id} value={f.id}>
256+
{f.name}
257+
</option>
258+
))}
259+
</select>
260+
<input
261+
className="input max-w-[9rem]"
262+
type="number"
263+
min={1}
264+
placeholder={t('account.quickCodeUsageLimit')}
265+
value={nc.usageLimit}
266+
onChange={(e) => setNc({ ...nc, usageLimit: e.target.value })}
267+
/>
268+
<button
269+
className="btn-primary"
270+
onClick={() =>
271+
wrap(async () => {
272+
await api.post('/account/quick-codes', {
273+
code: nc.code.trim() || undefined,
274+
targetFolderId: nc.targetFolderId || null,
275+
usageLimit: Number(nc.usageLimit) || null,
276+
});
277+
setNc({ code: '', targetFolderId: '', usageLimit: '' });
278+
})
279+
}
280+
>
281+
{t('account.quickCodeCreate')}
282+
</button>
283+
</div>
284+
<div className="divide-y divide-neutral-100 dark:divide-neutral-800">
285+
{codes.map((c) => (
286+
<div key={c.id} className="flex items-center justify-between gap-2 py-2 text-sm">
287+
<div className="min-w-0">
288+
<code className="rounded bg-neutral-100 px-1.5 py-0.5 font-mono dark:bg-neutral-800">{c.code}</code>{' '}
289+
<span className="text-xs text-neutral-400">
290+
{c.usageLimit !== null
291+
? t('account.quickUsedLimited', { count: c.usageCount, limit: c.usageLimit })
292+
: t('account.quickUsed', { count: c.usageCount })}
293+
</span>
294+
</div>
295+
<div className="flex shrink-0 gap-2">
296+
<button
297+
className="btn-ghost px-2 py-1"
298+
onClick={async () => {
299+
await navigator.clipboard?.writeText(`${window.location.origin}/q?code=${encodeURIComponent(c.code)}`).catch(() => {});
300+
toast(t('account.quickLinkCopied'), 'success');
301+
}}
302+
>
303+
{t('account.quickCopyLink')}
304+
</button>
305+
<button className="btn-danger px-2 py-1" onClick={() => wrap(() => api.del(`/account/quick-codes/${c.id}`))}>
306+
{t('account.revoke')}
307+
</button>
308+
</div>
309+
</div>
310+
))}
311+
{codes.length === 0 && <p className="py-2 text-sm text-neutral-400">{t('account.noQuickCodes')}</p>}
312+
</div>
313+
</section>
314+
227315
{/* Data & privacy (GDPR) */}
228316
<section className="card space-y-3">
229317
<h2 className="font-semibold">{t('account.yourData')}</h2>

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use client';
22

3-
import { useRef, useState } from 'react';
3+
import { useEffect, useRef, useState } from 'react';
44
import Link from 'next/link';
55
import { UploadCloud, CheckCircle2 } from 'lucide-react';
66
import { API_URL } from '@/lib/api';
@@ -25,6 +25,13 @@ export default function QuickUploadPage() {
2525
const [dragging, setDragging] = useState(false);
2626
const fileInput = useRef<HTMLInputElement>(null);
2727

28+
// Prefill the code from a shared `/q?code=XXX` link (read from the URL to avoid pulling the
29+
// whole page into a Suspense boundary, which useSearchParams would require).
30+
useEffect(() => {
31+
const c = new URLSearchParams(window.location.search).get('code');
32+
if (c) setCode(c.toUpperCase());
33+
}, []);
34+
2835
async function check(e: React.FormEvent) {
2936
e.preventDefault();
3037
setError(null);

‎apps/web/src/lib/i18n.tsx‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -295,6 +295,17 @@ const fr: Dict = {
295295
'account.unknownDevice': 'appareil inconnu',
296296
'account.lastSeen': 'vu pour la dernière fois {date}',
297297
'account.revoke': 'Révoquer',
298+
'account.quickCodes': 'Codes Quick-Upload',
299+
'account.quickCodesHint': 'Créez un code à partager : n’importe qui pourra déposer des fichiers dans le dossier choisi, sans compte.',
300+
'account.quickCodePlaceholder': 'Code (optionnel)',
301+
'account.quickCodeDefaultFolder': 'Dossier Fast-Upload (par défaut)',
302+
'account.quickCodeUsageLimit': 'Limite',
303+
'account.quickCodeCreate': 'Créer',
304+
'account.quickUsed': '{count} dépôt(s)',
305+
'account.quickUsedLimited': '{count}/{limit} dépôt(s)',
306+
'account.quickCopyLink': 'Copier le lien',
307+
'account.quickLinkCopied': 'Lien copié',
308+
'account.noQuickCodes': 'Aucun code pour le moment.',
298309
'account.yourData': 'Vos données',
299310
'account.dataHint':
300311
'Téléchargez une copie des données de votre compte, ou supprimez définitivement votre compte et tous vos fichiers. La suppression est irréversible.',
@@ -718,6 +729,17 @@ const en: Dict = {
718729
'account.unknownDevice': 'unknown device',
719730
'account.lastSeen': 'last seen {date}',
720731
'account.revoke': 'Revoke',
732+
'account.quickCodes': 'Quick-Upload codes',
733+
'account.quickCodesHint': 'Create a code to share: anyone can drop files into the chosen folder, no account needed.',
734+
'account.quickCodePlaceholder': 'Code (optional)',
735+
'account.quickCodeDefaultFolder': 'Fast-Upload folder (default)',
736+
'account.quickCodeUsageLimit': 'Limit',
737+
'account.quickCodeCreate': 'Create',
738+
'account.quickUsed': '{count} upload(s)',
739+
'account.quickUsedLimited': '{count}/{limit} upload(s)',
740+
'account.quickCopyLink': 'Copy link',
741+
'account.quickLinkCopied': 'Link copied',
742+
'account.noQuickCodes': 'No codes yet.',
721743
'account.yourData': 'Your data',
722744
'account.dataHint':
723745
'Download a copy of your account data, or permanently delete your account and all of your files. Deletion cannot be undone.',

0 commit comments

Comments
 (0)