Files
TREK/client/src/pages/admin/AdminUserModals.tsx
T
Maurice 1ad2e92142 fix: make the app keyboard-reachable, and close four DoS-able patterns
The bulk of what SonarQube still had open on the reliability side, read site by
site rather than swept. Two clusters are worth calling out because they are
defects, not lint.

**Four regexes could be made to hang the process.** The worst is
`/.+@.+\..+/` in the forgot-password path: three unbounded `.+` that all
overlap, unanchored, on an endpoint that needs no login and whose schema is a
bare z.string() under a 100kb body cap. A thousand '@' characters had not
finished after 100 seconds — one request pins the event loop, and Node has one.
EMAIL_REGEX in auth.helpers is the same shape on register and profile update
(310ms for 8kb). The two tag strippers over an uploaded KML description and over
Commons metadata took 0.52s on a 16k run of '<'. Each rewrite was proven
equivalent by brute force against the original — millions of strings for the
coordinate patterns, 671,876 for the tag stripper — because a subtly different
regex on a parsing path is worse than the finding.

`<[^>]+>` could not be fixed in the pattern: `[^>]` matches `<` too, so the only
unambiguous form changes what happens to malformed markup. It is now a scan in
common/stripHtmlTags.ts, quirks included — `<>` is left alone, `<a<b>` is one
tag — with the equivalence pinned by a test that compares against the old regex
over every string up to length six.

**And roughly 500 places could only be reached with a mouse.** Clickable divs
became real buttons where the markup allowed (52 of them), took
role + tabIndex + Enter/Space where they had to stay divs, and modal backdrops
took role="presentation" — the honest role, since a backdrop is a mouse shortcut
for a Cancel control that is already in the tab order, and making it a button
plants a nameless full-screen tab stop around its own contents.

Alongside those: `.sort()` calls that now say the order they always had, `{n &&
<X/>}` guards that rendered a literal "0" for a zero-byte file and for a place at
latitude 0, an optimistic budget write that stored a boolean where the contract
and both transports use 0/1, and the Number statics.

sonar-project.properties documents the six that were deliberately left: two wiki
patterns with no overlapping quantifier pair whose "fix" would stop parsing
`[see [1]](url)`, four tar header fields bounded at 12-155 bytes by the format,
two djb2 hashes where the 32-bit wrap is the algorithm, two `| 0` that are also
coercing undefined to 0 on a path where the API sends no user_id, and the MCP
session maps Sonar reads as empty because they are filled from another module.
2026-08-25 19:26:38 +02:00

476 lines
18 KiB
TypeScript

import {
AlertTriangle,
ArrowUpCircle,
CheckCircle,
ExternalLink,
Eye,
EyeOff,
Fingerprint,
RefreshCw,
} from 'lucide-react';
import React from 'react';
import { adminApi } from '../../api/client';
import CustomSelect from '../../components/shared/CustomSelect';
import Modal from '../../components/shared/Modal';
import type { TranslationFn } from '../../types';
import type { useAdmin } from './useAdmin';
interface AdminUserModalsProps {
admin: ReturnType<typeof useAdmin>;
t: TranslationFn;
}
// The admin page's modal layer: create-user, edit-user, the "how to update"
// popup and the rotate-JWT confirmation. Pure layout around the useAdmin hook.
export default function AdminUserModals({ admin, t }: AdminUserModalsProps): React.ReactElement {
const {
logout,
navigate,
toast,
editingUser,
setEditingUser,
editForm,
setEditForm,
showCreateUser,
setShowCreateUser,
createForm,
setCreateForm,
updateInfo,
showUpdateModal,
setShowUpdateModal,
showRotateJwtModal,
setShowRotateJwtModal,
rotatingJwt,
setRotatingJwt,
handleCreateUser,
handleSaveUser,
} = admin;
const [showCreatePw, setShowCreatePw] = React.useState(false);
const [showEditPw, setShowEditPw] = React.useState(false);
return (
<>
{/* Create user modal */}
<Modal
isOpen={showCreateUser}
onClose={() => setShowCreateUser(false)}
title={t('admin.createUser')}
size="sm"
footer={
<div className="flex justify-end gap-3">
<button type="button"
onClick={() => setShowCreateUser(false)}
className="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-600 hover:bg-slate-50"
>
{t('common.cancel')}
</button>
<button type="button"
onClick={handleCreateUser}
className="rounded-lg bg-slate-900 px-4 py-2 text-sm text-white hover:bg-slate-700"
>
{t('admin.createUser')}
</button>
</div>
}
>
<div className="space-y-4">
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">{t('settings.username')} *</label>
<input
type="text"
value={createForm.username}
onChange={(e) => setCreateForm((f) => ({ ...f, username: e.target.value }))}
placeholder={t('settings.username')}
className="w-full rounded-lg border border-slate-300 px-3 py-2.5 text-sm text-slate-900 focus:border-transparent focus:ring-2 focus:ring-slate-400"
/>
</div>
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">{t('common.email')} *</label>
<input
type="email"
value={createForm.email}
onChange={(e) => setCreateForm((f) => ({ ...f, email: e.target.value }))}
placeholder={t('common.email')}
className="w-full rounded-lg border border-slate-300 px-3 py-2.5 text-sm text-slate-900 focus:border-transparent focus:ring-2 focus:ring-slate-400"
/>
</div>
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">{t('common.password')} *</label>
<div className="relative">
<input
type={showCreatePw ? 'text' : 'password'}
value={createForm.password}
onChange={(e) => setCreateForm((f) => ({ ...f, password: e.target.value }))}
placeholder={t('common.password')}
className="w-full rounded-lg border border-slate-300 px-3 py-2.5 pr-10 text-sm text-slate-900 focus:border-transparent focus:ring-2 focus:ring-slate-400"
/>
<button
type="button"
onClick={() => setShowCreatePw((v) => !v)}
tabIndex={-1}
aria-label="Show or hide password"
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-slate-400 hover:text-slate-600"
>
{showCreatePw ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
</div>
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">{t('settings.role')}</label>
<CustomSelect
value={createForm.role}
onChange={(value) => setCreateForm((f) => ({ ...f, role: String(value) }))}
options={[
{ value: 'user', label: t('settings.roleUser') },
{ value: 'admin', label: t('settings.roleAdmin') },
]}
/>
</div>
</div>
</Modal>
{/* Edit user modal */}
<Modal
isOpen={!!editingUser}
onClose={() => setEditingUser(null)}
title={t('admin.editUser')}
size="sm"
footer={
<div className="flex justify-end gap-3">
<button type="button"
onClick={() => setEditingUser(null)}
className="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-600 hover:bg-slate-50"
>
{t('common.cancel')}
</button>
<button type="button"
onClick={handleSaveUser}
className="rounded-lg bg-slate-900 px-4 py-2 text-sm text-white hover:bg-slate-700"
>
{t('common.save')}
</button>
</div>
}
>
{editingUser && (
<div className="space-y-4">
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">{t('settings.username')}</label>
<input
type="text"
value={editForm.username}
onChange={(e) => setEditForm((f) => ({ ...f, username: e.target.value }))}
className="w-full rounded-lg border border-slate-300 px-3 py-2.5 text-sm text-slate-900 focus:border-transparent focus:ring-2 focus:ring-slate-400"
/>
</div>
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">{t('common.email')}</label>
<input
type="email"
value={editForm.email}
onChange={(e) => setEditForm((f) => ({ ...f, email: e.target.value }))}
className="w-full rounded-lg border border-slate-300 px-3 py-2.5 text-sm text-slate-900 focus:border-transparent focus:ring-2 focus:ring-slate-400"
/>
</div>
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">
{t('admin.newPassword')}{' '}
<span className="font-normal text-slate-400">({t('admin.newPasswordHint')})</span>
</label>
<div className="relative">
<input
type={showEditPw ? 'text' : 'password'}
value={editForm.password}
onChange={(e) => setEditForm((f) => ({ ...f, password: e.target.value }))}
placeholder={t('admin.newPasswordPlaceholder')}
className="w-full rounded-lg border border-slate-300 px-3 py-2.5 pr-10 text-sm text-slate-900 focus:border-transparent focus:ring-2 focus:ring-slate-400"
/>
<button
type="button"
onClick={() => setShowEditPw((v) => !v)}
tabIndex={-1}
aria-label="Show or hide password"
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 text-slate-400 hover:text-slate-600"
>
{showEditPw ? <EyeOff size={16} /> : <Eye size={16} />}
</button>
</div>
</div>
<div>
<label className="mb-1.5 block text-sm font-medium text-slate-700">{t('settings.role')}</label>
<CustomSelect
value={editForm.role}
onChange={(value) => setEditForm((f) => ({ ...f, role: String(value) }))}
options={[
{ value: 'user', label: t('settings.roleUser') },
{ value: 'admin', label: t('settings.roleAdmin') },
]}
/>
</div>
<div className="border-t border-slate-100 pt-3">
<p className="mb-2 text-xs text-slate-400">{t('admin.passkey.resetHint')}</p>
<button
type="button"
onClick={async () => {
if (!editingUser) return;
if (!confirm(t('admin.passkey.resetConfirm', { name: editingUser.username }))) return;
try {
const r = await adminApi.resetUserPasskeys(editingUser.id);
toast.success(t('admin.passkey.resetDone', { count: r.deleted ?? 0 }));
} catch {
toast.error(t('common.error'));
}
}}
className="flex items-center gap-2 rounded-lg border border-red-200 px-3 py-2 text-sm text-red-600 hover:bg-red-50"
>
<Fingerprint size={14} /> {t('admin.passkey.reset')}
</button>
</div>
</div>
)}
</Modal>
{/* Update instructions popup */}
{showUpdateModal && (
<div
style={{
position: 'fixed',
inset: 0,
zIndex: 9999,
background: 'rgba(0,0,0,0.5)',
backdropFilter: 'blur(4px)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 16,
}}
role="presentation"
onClick={() => setShowUpdateModal(false)}
>
<div
role="presentation"
onClick={(e) => e.stopPropagation()}
style={{ width: '100%', maxWidth: 440, borderRadius: 16, overflow: 'hidden' }}
className="border border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-800"
>
<div
style={{
background: 'linear-gradient(135deg, #0f172a, #1e293b)',
padding: '20px 24px',
display: 'flex',
alignItems: 'center',
gap: 12,
}}
>
<div
className="bg-[rgba(255,255,255,0.2)]"
style={{
width: 40,
height: 40,
borderRadius: 10,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
}}
>
<ArrowUpCircle size={20} className="text-white" />
</div>
<div>
<h3
className="text-white"
style={{ margin: 0, fontSize: 'calc(16px * var(--fs-scale-subtitle, 1))', fontWeight: 700 }}
>
{t('admin.update.howTo')}
</h3>
<p
className="text-[rgba(255,255,255,0.8)]"
style={{ margin: '2px 0 0', fontSize: 'calc(12px * var(--fs-scale-body, 1))' }}
>
v{updateInfo?.current} → v{updateInfo?.latest}
</p>
</div>
</div>
<div style={{ padding: '20px 24px' }}>
<p
className="text-gray-700 dark:text-gray-300"
style={{ fontSize: 'calc(13px * var(--fs-scale-body, 1))', lineHeight: 1.6, margin: 0 }}
>
{(updateInfo?.is_docker === false
? t('admin.update.nonDockerText')
: t('admin.update.dockerText')
).replace('{version}', `v${updateInfo?.latest ?? ''}`)}
</p>
{updateInfo?.is_docker === false ? (
<a
href="https://github.com/liketrek/TREK/wiki/Updating"
target="_blank"
rel="noopener noreferrer"
style={{
marginTop: 14,
padding: '12px 14px',
borderRadius: 10,
fontSize: 'calc(13px * var(--fs-scale-body, 1))',
lineHeight: 1.5,
display: 'flex',
alignItems: 'center',
gap: 8,
textDecoration: 'none',
}}
className="border border-gray-200 bg-gray-50 text-gray-700 hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-200 dark:hover:bg-gray-800"
>
<ExternalLink className="h-4 w-4 flex-shrink-0" />
<span className="font-semibold underline">{t('admin.update.wikiLink')}</span>
</a>
) : (
<div
style={{
marginTop: 14,
padding: '12px 14px',
borderRadius: 10,
fontSize: 'calc(12px * var(--fs-scale-body, 1))',
lineHeight: 1.8,
fontFamily: 'monospace',
whiteSpace: 'pre-wrap',
wordBreak: 'break-all',
}}
className="border border-gray-700 bg-gray-900 text-gray-100 dark:bg-gray-950"
>
{`docker pull mauriceboe/trek:latest
docker stop trek && docker rm trek
docker run -d --name trek \\
-p 3000:3000 \\
-v /opt/trek/data:/app/data \\
-v /opt/trek/uploads:/app/uploads \\
--restart unless-stopped \\
mauriceboe/trek:latest`}
</div>
)}
<div
style={{
marginTop: 10,
padding: '10px 12px',
borderRadius: 10,
fontSize: 'calc(12px * var(--fs-scale-body, 1))',
lineHeight: 1.5,
}}
className="border border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300"
>
<div className="flex items-start gap-2">
<CheckCircle className="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
<span>{t('admin.update.dataInfo')}</span>
</div>
</div>
{updateInfo?.release_url && (
<div
style={{
marginTop: 10,
padding: '10px 12px',
borderRadius: 10,
fontSize: 'calc(12px * var(--fs-scale-body, 1))',
lineHeight: 1.5,
}}
className="border border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-300"
>
<div className="flex items-start gap-2">
<ExternalLink className="mt-0.5 h-3.5 w-3.5 flex-shrink-0" />
<span>
<a
href={updateInfo.release_url}
target="_blank"
rel="noopener noreferrer"
className="font-semibold underline"
>
{t('admin.update.button')}
</a>
</span>
</div>
</div>
)}
</div>
<div style={{ padding: '0 24px 20px', display: 'flex', justifyContent: 'flex-end' }}>
<button type="button"
onClick={() => setShowUpdateModal(false)}
className="bg-slate-900 text-white hover:bg-slate-700 dark:bg-white dark:text-slate-900 dark:hover:bg-gray-200"
style={{
padding: '9px 20px',
borderRadius: 10,
fontSize: 'calc(13px * var(--fs-scale-body, 1))',
fontWeight: 600,
border: 'none',
cursor: 'pointer',
fontFamily: 'inherit',
}}
>
{t('common.close')}
</button>
</div>
</div>
</div>
)}
{/* Rotate JWT Secret confirmation modal */}
<Modal
isOpen={showRotateJwtModal}
onClose={() => setShowRotateJwtModal(false)}
title="Rotate JWT Secret"
size="sm"
footer={
<div className="flex justify-end gap-3">
<button type="button"
onClick={() => setShowRotateJwtModal(false)}
disabled={rotatingJwt}
className="rounded-lg border border-slate-200 px-4 py-2 text-sm text-slate-600 hover:bg-slate-50 disabled:opacity-50"
>
{t('common.cancel')}
</button>
<button type="button"
onClick={async () => {
setRotatingJwt(true);
try {
await adminApi.rotateJwtSecret();
setShowRotateJwtModal(false);
logout();
navigate('/login', { state: { noRedirect: true } });
} catch {
toast.error(t('common.error'));
setRotatingJwt(false);
}
}}
disabled={rotatingJwt}
className="flex items-center gap-2 rounded-lg bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700 disabled:bg-red-300"
>
{rotatingJwt ? (
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
) : (
<RefreshCw className="h-4 w-4" />
)}
Rotate &amp; Log out
</button>
</div>
}
>
<div className="flex gap-3">
<div className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-full bg-red-100">
<AlertTriangle className="h-5 w-5 text-red-600" />
</div>
<div>
<p className="mb-1 text-sm font-medium text-slate-900">
Warning, this will invalidate all sessions and log you out.
</p>
<p className="text-xs text-slate-500">
A new JWT secret will be generated immediately. Every logged-in user — including you — will be signed out
and will need to log in again.
</p>
</div>
</div>
</Modal>
</>
);
}