Skip to content

Commit 93ad0a8

Browse files
Admin: configure the VirusTotal API key from the panel
The VT key was .env-only. Now an admin can set/replace/clear it from Admin ▸ VirusTotal, stored in the Setting row and applied live (no restart). A DB key overrides VIRUSTOTAL_API_KEY; clearing it reverts to .env. The key is never echoed back — the UI only shows Active/Inactive. - Setting.virustotalApiKey column (+ migration); VirusTotalClient.setKey() for hot-swap. - index.ts loads the stored key at boot; GET/PATCH /admin/settings handle it (fields are now independently optional). Schema updated, FR/EN strings added.
1 parent 5bfffa6 commit 93ad0a8

8 files changed

Lines changed: 107 additions & 8 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 "Setting" ADD COLUMN "virustotalApiKey" TEXT;

‎apps/api/prisma/schema.prisma‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,8 @@ model Setting {
270270
// single-row table (id = "global")
271271
id String @id @default("global")
272272
globalStorageCapBytes BigInt @default(0)
273+
// Optional VirusTotal API key set from the admin panel; overrides VIRUSTOTAL_API_KEY in .env.
274+
virustotalApiKey String?
273275
updatedAt DateTime @updatedAt
274276
}
275277

‎apps/api/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ async function main(): Promise<void> {
2424
await mkdir(env.QUARANTINE_PATH, { recursive: true });
2525
}
2626

27+
// A VirusTotal key stored from the admin panel overrides the one from .env.
28+
const setting = await prisma.setting.findUnique({ where: { id: 'global' } }).catch(() => null);
29+
if (setting?.virustotalApiKey) ctx.virustotal.setKey(setting.virustotalApiKey);
30+
2731
const app = await buildServer(ctx);
2832
const stopWorker = startRemoteWorker(ctx, app.log);
2933
const stopMaintenance = startMaintenance(ctx, app.log);

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

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -190,19 +190,37 @@ export const adminRoutes: FastifyPluginAsync = async (app) => {
190190
// ── Global settings ─────────────────────────────────────────────────────--
191191
app.get('/settings', async () => {
192192
const setting = await prisma.setting.findUnique({ where: { id: GLOBAL_SETTING_ID } });
193-
return { globalStorageCapBytes: Number(setting?.globalStorageCapBytes ?? 0n) };
193+
return {
194+
globalStorageCapBytes: Number(setting?.globalStorageCapBytes ?? 0n),
195+
// Never echo the key back — only whether scanning is currently active.
196+
virustotalConfigured: app.ctx.virustotal.enabled,
197+
};
194198
});
195199

196200
app.patch('/settings', async (req, reply) => {
197201
const body = parseOr400(reply, updateSettingsSchema, req.body);
198202
if (!body) return;
203+
// Build the update from only the provided fields, so the VT key and the cap can be saved
204+
// independently from their own forms.
205+
const data: { globalStorageCapBytes?: bigint; virustotalApiKey?: string | null } = {};
206+
if (body.globalStorageCapBytes !== undefined) data.globalStorageCapBytes = BigInt(body.globalStorageCapBytes);
207+
if (body.virustotalApiKey !== undefined) data.virustotalApiKey = body.virustotalApiKey.trim() || null;
208+
199209
const setting = await prisma.setting.upsert({
200210
where: { id: GLOBAL_SETTING_ID },
201-
create: { id: GLOBAL_SETTING_ID, globalStorageCapBytes: BigInt(body.globalStorageCapBytes) },
202-
update: { globalStorageCapBytes: BigInt(body.globalStorageCapBytes) },
211+
create: { id: GLOBAL_SETTING_ID, ...data },
212+
update: data,
203213
});
214+
215+
// Apply the key change live: a stored key overrides .env; clearing it reverts to .env.
216+
if (body.virustotalApiKey !== undefined) {
217+
app.ctx.virustotal.setKey(setting.virustotalApiKey ?? app.ctx.env.VIRUSTOTAL_API_KEY);
218+
}
204219
await audit(req, 'admin.settings.update');
205-
return { globalStorageCapBytes: Number(setting.globalStorageCapBytes) };
220+
return {
221+
globalStorageCapBytes: Number(setting.globalStorageCapBytes),
222+
virustotalConfigured: app.ctx.virustotal.enabled,
223+
};
206224
});
207225

208226
// ── Quick-Upload codes ──────────────────────────────────────────────────--

‎apps/api/src/security/virustotal.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,16 @@ export interface VirusTotalReport {
1313
}
1414

1515
export class VirusTotalClient {
16-
constructor(private readonly apiKey: string) {}
16+
private apiKey: string;
17+
18+
constructor(apiKey: string) {
19+
this.apiKey = apiKey;
20+
}
21+
22+
/** Swap the API key at runtime (admin can set/clear it from the panel without a restart). */
23+
setKey(apiKey: string): void {
24+
this.apiKey = apiKey ?? '';
25+
}
1726

1827
get enabled(): boolean {
1928
return this.apiKey.length > 0;

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

Lines changed: 50 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ export default function AdminPage() {
3232
const [codes, setCodes] = useState<PublicQuickCode[]>([]);
3333
const [audit, setAudit] = useState<AuditEntry[]>([]);
3434
const [cap, setCap] = useState('0');
35+
const [vtConfigured, setVtConfigured] = useState(false);
36+
const [vtKey, setVtKey] = useState('');
3537
const [error, setError] = useState<string | null>(null);
3638

3739
// new-user form
@@ -47,7 +49,7 @@ export default function AdminPage() {
4749
api.get<{ users: PublicUser[] }>('/admin/users'),
4850
api.get<{ codes: PublicQuickCode[] }>('/admin/quick-codes'),
4951
api.get<{ logs: AuditEntry[] }>('/admin/audit?limit=50'),
50-
api.get<{ globalStorageCapBytes: number }>('/admin/settings'),
52+
api.get<{ globalStorageCapBytes: number; virustotalConfigured: boolean }>('/admin/settings'),
5153
api.get<{ warnings: string[] }>('/admin/alerts'),
5254
]);
5355
setStats(s);
@@ -56,7 +58,7 @@ export default function AdminPage() {
5658
setAudit(a.logs);
5759
setCap(String(s.globalCapBytes));
5860
setAlerts(al.warnings);
59-
void settings;
61+
setVtConfigured(settings.virustotalConfigured);
6062
}, []);
6163

6264
useEffect(() => {
@@ -123,6 +125,52 @@ export default function AdminPage() {
123125
</div>
124126
</section>
125127

128+
{/* VirusTotal */}
129+
<section className="card space-y-2">
130+
<div className="flex items-center justify-between">
131+
<h2 className="font-semibold">{t('admin.vtTitle')}</h2>
132+
<span className={`chip ${vtConfigured ? 'bg-emerald-500/10 text-emerald-300' : 'bg-white/[0.05] text-zinc-400'}`}>
133+
{vtConfigured ? t('admin.vtActive') : t('admin.vtInactive')}
134+
</span>
135+
</div>
136+
<p className="text-sm text-neutral-500">{t('admin.vtHint')}</p>
137+
<div className="flex gap-2">
138+
<input
139+
className="input font-mono"
140+
type="password"
141+
placeholder={vtConfigured ? t('admin.vtPlaceholderSet') : t('admin.vtPlaceholder')}
142+
value={vtKey}
143+
onChange={(e) => setVtKey(e.target.value)}
144+
/>
145+
<button
146+
className="btn-primary whitespace-nowrap"
147+
onClick={() =>
148+
wrap(async () => {
149+
const res = await api.patch<{ virustotalConfigured: boolean }>('/admin/settings', { virustotalApiKey: vtKey.trim() });
150+
setVtConfigured(res.virustotalConfigured);
151+
setVtKey('');
152+
})
153+
}
154+
>
155+
{t('admin.save')}
156+
</button>
157+
</div>
158+
{vtConfigured && (
159+
<button
160+
className="text-xs text-red-300 hover:underline"
161+
onClick={() =>
162+
wrap(async () => {
163+
const res = await api.patch<{ virustotalConfigured: boolean }>('/admin/settings', { virustotalApiKey: '' });
164+
setVtConfigured(res.virustotalConfigured);
165+
setVtKey('');
166+
})
167+
}
168+
>
169+
{t('admin.vtClear')}
170+
</button>
171+
)}
172+
</section>
173+
126174
{/* Users */}
127175
<section className="card space-y-3">
128176
<h2 className="font-semibold">{t('admin.users')}</h2>

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,13 @@ const fr: Dict = {
323323
'admin.statStorageUsed': 'Stockage utilisé',
324324
'admin.statGlobalCap': 'Plafond global',
325325
'admin.unlimited': 'Illimité',
326+
'admin.vtTitle': 'VirusTotal',
327+
'admin.vtHint': 'Clé API VirusTotal pour la vérification à la demande (seul le hash SHA-256 est envoyé, jamais le fichier). Remplace la valeur du .env.',
328+
'admin.vtActive': 'Actif',
329+
'admin.vtInactive': 'Inactif',
330+
'admin.vtPlaceholder': 'Clé API VirusTotal',
331+
'admin.vtPlaceholderSet': '•••••••• (clé enregistrée — saisir pour remplacer)',
332+
'admin.vtClear': 'Supprimer la clé',
326333
'admin.globalCapTitle': 'Plafond de stockage global',
327334
'admin.globalCapHint': 'Total d’octets pour tous les utilisateurs. 0 = illimité.',
328335
'admin.users': 'Utilisateurs',
@@ -756,6 +763,13 @@ const en: Dict = {
756763
'admin.statStorageUsed': 'Storage used',
757764
'admin.statGlobalCap': 'Global cap',
758765
'admin.unlimited': 'Unlimited',
766+
'admin.vtTitle': 'VirusTotal',
767+
'admin.vtHint': 'VirusTotal API key for on-demand checks (only the SHA-256 hash is sent, never the file). Overrides the .env value.',
768+
'admin.vtActive': 'Active',
769+
'admin.vtInactive': 'Inactive',
770+
'admin.vtPlaceholder': 'VirusTotal API key',
771+
'admin.vtPlaceholderSet': '•••••••• (key saved — type to replace)',
772+
'admin.vtClear': 'Remove key',
759773
'admin.globalCapTitle': 'Global storage cap',
760774
'admin.globalCapHint': 'Total bytes across all users. 0 = unlimited.',
761775
'admin.users': 'Users',

‎packages/shared/src/schemas.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,9 @@ export type UpdateUserInput = z.infer<typeof updateUserSchema>;
156156

157157
export const updateSettingsSchema = z.object({
158158
// 0 = unlimited.
159-
globalStorageCapBytes: z.number().int().nonnegative(),
159+
globalStorageCapBytes: z.number().int().nonnegative().optional(),
160+
// Empty string clears the stored key (reverting to the .env value, if any).
161+
virustotalApiKey: z.string().max(200).optional(),
160162
});
161163
export type UpdateSettingsInput = z.infer<typeof updateSettingsSchema>;
162164

0 commit comments

Comments
 (0)