feature: the CA certificates and CRLs are always published over HTTP and HTTPS on the status and Manager ports, the Shell page is an entry of the page menu, and the web interface passes its lint.
Release / release (push) Successful in 26s

This commit is contained in:
slawek committed 2026-11-24 18:06:34 +01:00
1 parent 4b5318c676
commit 0cec95c19b
72 files changed
+910 -861

No files matched your search

+2 -1
View File
@@ -11,7 +11,8 @@ import { useEffect, useState, type FormEvent } from 'react'
import OtpDialog from './OtpDialog.tsx'
import PasskeyDialog from './PasskeyDialog.tsx'
import ProfileDialog from './ProfileDialog.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import Toolbar from './Toolbar.tsx'
import { ACCOUNT_SHAPE, CODE_PATTERN, USER_SHAPE, request, type Account, type User } from './api.ts'
+1 -7
View File
@@ -1,13 +1,7 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, Switch, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
import { ACME_PROVIDERS, type AcmeProvider, type HttpsChange, type HttpsSettings } from './api.ts'
/** The labels of the ACME providers. */
export const PROVIDER_LABELS: Record<AcmeProvider, string> = {
letsencrypt: 'Let\'s Encrypt',
zerossl: 'ZeroSSL',
custom: 'Custom directory URL',
}
import { PROVIDER_LABELS } from './https.ts'
/** The problem of a custom ACME directory URL, or ''. */
function urlProblem(value: string) {
+6 -20
View File
@@ -2,7 +2,6 @@ import AccountCircle from '@mui/icons-material/AccountCircle'
import EditNote from '@mui/icons-material/EditNote'
import HelpOutline from '@mui/icons-material/HelpOutlineOutlined'
import Logout from '@mui/icons-material/Logout'
import Terminal from '@mui/icons-material/Terminal'
import { Box, Button, CircularProgress, Container, IconButton, Link, Stack, Tab, Tabs, Tooltip, Typography } from '@mui/material'
import { useCallback, useEffect, useState } from 'react'
import AccountPanel from './AccountPanel.tsx'
@@ -44,7 +43,7 @@ type SitesView = 'sites' | 'files'
/** The help topic of each tab of the Web Sites page. */
const SITES_TOPICS: Record<SitesView, string> = { sites: 'sites.md', files: 'site-files.md' }
/** The prefix of the sessionStorage keys of the pages the account and the shell page were opened from, by their paths. */
/** The prefix of the sessionStorage key of the page the account page was opened from, by its path. */
const RETURN_KEY = 'linux-manager-ui.return:'
/** The pages of an administrator besides Router, which every other path shows. */
@@ -71,11 +70,10 @@ const HELP_KEY = 'linux-manager-ui.help'
* WireGuard access; at CA_PATH its certificates; at SITES_PATH its web
* sites and the files of a site, opened from the sites too; at DNS_PATH its name server, while it is on; at DOCKER_PATH the state of Docker; at SHELL_PATH a shell on the server; otherwise the state of the server, with the update information of its packages in
* the Status panel, its metrics, its logs, its backups or the updates of its system's packages. A page shows one tab at a time, each read only while shown. An
* administrator switches pages with the page menu at the right end of the header; the button with the user's name,
* left of Sign out, opens the user's own account, and an administrator's shell button, left of it, the shell; pressed
* on their page, each returns to the page it was opened from; with the browser setting shellNewTab the shell button opens
* the shell in a new tab instead. While files are open in the shell's editor, the editor
* button left of the shell button switches the Shell page between the terminal and the editor. The help button, between the theme switcher and the page menu, opens or closes the help on
* administrator switches pages with the page menu at the right end of the header, whose Shell entry opens the shell in
* a new tab with the browser setting shellNewTab; the button with the user's name, left of Sign out, opens the user's
* own account, and pressed on it returns to the page it was opened from. While files are open in the shell's editor, the
* editor button left of the user's name switches the Shell page between the terminal and the editor. The help button, between the theme switcher and the page menu, opens or closes the help on
* the right (HelpPanel) at the topic of the page and tab shown (HELP_TOPICS), the page moving left; the browser keeps
* whether it is open. A call answered 401 ends the session and asks for a sign-in again.
*/
@@ -219,18 +217,6 @@ export default function App(props: { info: Info }) {
</IconButton>
</Tooltip>
)}
{session && admin && (
<Tooltip title={page === SHELL_PATH ? 'Back from the shell' : 'Shell'}>
<IconButton
aria-label="shell"
color={page === SHELL_PATH ? 'primary' : 'default'}
onClick={() => (shellNewTab && page !== SHELL_PATH ? window.open(SHELL_PATH, '_blank') : toggle(SHELL_PATH))}
sx={page === SHELL_PATH ? { bgcolor: 'action.selected' } : undefined}
>
<Terminal />
</IconButton>
</Tooltip>
)}
{session && (
<>
<Button variant={userPage ? 'contained' : 'outlined'} startIcon={<AccountCircle />} onClick={() => toggle(USER_PATH)} sx={{ textTransform: 'none' }}>
@@ -254,7 +240,7 @@ export default function App(props: { info: Info }) {
</Tooltip>
)}
{session && admin && (
<PageMenu path={page} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dnsOff ? [DNS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
<PageMenu path={page} newTab={shellNewTab ? [SHELL_PATH] : []} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dnsOff ? [DNS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
)}
</Stack>
</Stack>
+1 -1
View File
@@ -3,7 +3,7 @@ import {
TextField, Typography,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import { TARGET_LABELS } from './BackupSummary.tsx'
import { TARGET_LABELS } from './backup.ts'
import { BACKUP_KEEPS, BACKUP_SCHEDULES, BACKUP_TARGETS, RCLONE_MODES, type Backup, type BackupKeep, type BackupSettings } from './api.ts'
/** The labels of the retention settings. */
+13 -8
View File
@@ -4,10 +4,15 @@ import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Table, TableBody, TableCell, TableHead, TablePagination, TableRow } from '@mui/material'
import { useCallback, useEffect, useRef, useState } from 'react'
import BackupDialog from './BackupDialog.tsx'
import { BackupChip, TARGET_LABELS, backupRows, when } from './BackupSummary.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, bytes } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx'
import { BackupChip } from './BackupSummary.tsx'
import { backupRows, TARGET_LABELS } from './backup.ts'
import { when } from './format.ts'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Pairs } from './ServerPanel.tsx'
import { bytes } from './format.ts'
import SearchField from './SearchField.tsx'
import { matches } from './search.ts'
import Toolbar from './Toolbar.tsx'
import { ApiError, BACKUP_KEEPS, BACKUP_SCHEDULES, BACKUP_SETTINGS_SHAPE, BACKUP_SHAPE, STARTED_SHAPE, request, type Backup } from './api.ts'
@@ -41,22 +46,22 @@ export default function BackupPanel() {
// The start of the last run when Run now was pressed; watching ends once a later run has ended.
const startedBefore = useRef<string | null>(null)
/** Reads the backups; the state changes only once the server answers. */
const refresh = useCallback(async () => {
try {
const found = await request<Backup>('GET', '/backup', BACKUP_SHAPE)
await request<Backup>('GET', '/backup', BACKUP_SHAPE).then((found) => {
setBackup(found)
setError(null)
setUnavailable(false)
if (found.state && found.state.result !== 'running' && found.state.started !== startedBefore.current) {
setWatching(false)
}
} catch (caught) {
}, (caught) => {
const failure = caught as ApiError
setBackup(null)
setUnavailable(failure.status === 404)
setError(failure.message)
setWatching(false)
}
})
}, [])
useEffect(() => {
+1 -36
View File
@@ -1,6 +1,5 @@
import { Chip } from '@mui/material'
import { bytes } from './ServerPanel.tsx'
import type { Backup, BackupState } from './api.ts'
import type { BackupState } from './api.ts'
/** The colour of each result of a backup run. */
const RESULT_COLORS: Record<string, 'success' | 'warning' | 'error' | 'info'> = {
@@ -11,43 +10,9 @@ const RESULT_COLORS: Record<string, 'success' | 'warning' | 'error' | 'info'> =
running: 'info',
}
/** The labels of the backup targets. */
export const TARGET_LABELS: Record<string, string> = { local: 'Local folder', pbs: 'Proxmox Backup Server' }
/** A time of the server in the browser's format, or a dash. */
export function when(time: string | null | undefined) {
return time ? new Date(time).toLocaleString() : '-'
}
/** The result of the last backup run as a chip, or "never" before the first. */
export function BackupChip(props: { state: BackupState | null }) {
return props.state
? <Chip size="small" label={props.state.result} color={RESULT_COLORS[props.state.result] ?? 'default'} />
: <Chip size="small" label="never" variant="outlined" />
}
/** The schedule, the next run (as systemd shows it) and the last run of the server's backups, as rows of Pairs. */
export function backupRows(backup: Backup): [string, string][] {
const { settings, state } = backup
const rows: [string, string][] = [
['Backups', settings.enabled ? `${settings.schedule}, to ${TARGET_LABELS[settings.target] ?? settings.target}` : 'off'],
['Next run', backup.next ?? '-'],
]
if (!state) {
return [...rows, ['Last run', 'none']]
}
rows.push(
['Last run', `${when(state.started)}${state.finished ? ` to ${new Date(state.finished).toLocaleTimeString()}` : ''}`],
['Last result', state.result],
)
if (state.archive ?? state.snapshot) {
rows.push(['Last backup', `${state.archive ?? state.snapshot}${state.size === null ? '' : `, ${bytes(state.size)}`}`])
}
if (state.cloud) {
rows.push(['Cloud copy', `${state.cloud.mode} to ${state.cloud.remote}: ${state.cloud.error ?? state.cloud.result}`])
}
if (state.error) {
rows.push(['Error', state.error])
}
return rows
}
+29 -22
View File
@@ -12,7 +12,7 @@ import {
Tooltip, Typography,
} from '@mui/material'
import { useCallback, useEffect, useState } from 'react'
import { when } from './BackupSummary.tsx'
import { when } from './format.ts'
import CertificateDialog from './CertificateDialog.tsx'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import ImportDialog from './ImportDialog.tsx'
@@ -20,8 +20,10 @@ import IssuingCaDialog from './IssuingCaDialog.tsx'
import TemplateDialog from './TemplateDialog.tsx'
import Toolbar from './Toolbar.tsx'
import EkuDialog from './EkuDialog.tsx'
import PkiSettingsDialog, { PUBLISH_LABELS, ROOT_SOURCE_LABELS } from './PkiSettingsDialog.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import PkiSettingsDialog from './PkiSettingsDialog.tsx'
import { ROOT_SOURCE_LABELS } from './pki.ts'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Pairs, Section } from './ServerPanel.tsx'
import ServerCertificatePanel from './ServerCertificatePanel.tsx'
import SetupCodeDialog from './SetupCodeDialog.tsx'
@@ -89,7 +91,7 @@ export default function CertificatesPanel() {
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [note, setNote] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [editing, setEditing] = useState(false)
const [authority, setAuthority] = useState<{ name?: string } | null>(null)
const [template, setTemplate] = useState<{ name?: string } | null>(null)
@@ -105,25 +107,31 @@ export default function CertificatesPanel() {
const rootBoard = useBoard(ROOT_LAYOUT_KEY)
const issuingBoard = useBoard(ISSUING_LAYOUT_KEY)
const refresh = useCallback(async () => {
setBusy(true)
try {
setPki(await request<Pki>('GET', '/ca', PKI_SHAPE))
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setPki(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
/** Reads the PKI; the state changes only once the server answers. */
const read = useCallback(async () => {
await request<Pki>('GET', '/ca', PKI_SHAPE)
.then((found) => {
setPki(found)
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setPki(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the PKI again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Saves the certificates a client trusts the CA with: the root alone, or an issuing CA followed by the root. */
async function downloadBundle(name: string) {
@@ -370,7 +378,7 @@ export default function CertificatesPanel() {
<Pairs
rows={[
['Source', root.source === 'simple-ca' ? `Simple CA, ${root.simple_ca_url}` : ROOT_SOURCE_LABELS[root.source]],
['State', <Chip size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
['State', <Chip key="state" size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
['Subject', root.subject ?? '-'],
['Expires', when(root.expires)],
['CRL valid until', when(root.crl_next_update)],
@@ -419,7 +427,6 @@ export default function CertificatesPanel() {
content: (
<Pairs
rows={[
['Published at', pki.settings.publish.map((item) => PUBLISH_LABELS[item] ?? item).join('; ') || 'nowhere'],
['CA key', pki.settings.key],
['Lifetimes', `root ${pki.settings.root_days} days, issuing CAs ${pki.settings.ca_days} days`],
['CRLs', `issuing CAs ${pki.settings.crl_days} days, root ${pki.settings.root_crl_days} days`],
+4 -5
View File
@@ -40,11 +40,10 @@ export default function ComponentsPanel(props: { onChange?: () => void }) {
const [router, setRouter] = useState<Component | null>(null)
const read = useCallback(async () => {
try {
setComponents((await request<{ components: Component[] }>('GET', '/components', COMPONENTS_SHAPE)).components)
} catch (caught) {
setError(`The server did not give its components: ${(caught as Error).message}`)
}
await request<{ components: Component[] }>('GET', '/components', COMPONENTS_SHAPE).then(
(found) => setComponents(found.components),
(caught) => setError(`The server did not give its components: ${(caught as Error).message}`),
)
}, [])
useEffect(() => {
+25 -18
View File
@@ -9,7 +9,8 @@ import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import DnsDomainDialog from './DnsDomainDialog.tsx'
import DnsRecordDialog from './DnsRecordDialog.tsx'
import DnsSettingsDialog from './DnsSettingsDialog.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Pairs } from './ServerPanel.tsx'
import Toolbar from './Toolbar.tsx'
import {
@@ -72,7 +73,7 @@ export default function DnsPanel() {
const [dns, setDns] = useState<Dns | null>(null)
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [settings, setSettings] = useState(false)
const [selected, setSelected] = useState<string | null>(null)
const [editing, setEditing] = useState<DnsDomain | 'new' | null>(null)
@@ -80,25 +81,31 @@ export default function DnsPanel() {
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const board = useBoard(LAYOUT_KEY)
const refresh = useCallback(async () => {
setBusy(true)
try {
setDns(await request<Dns>('GET', '/dns', DNS_SHAPE))
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setDns(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
/** Reads the name server's state; the state changes only once the server answers. */
const read = useCallback(async () => {
await request<Dns>('GET', '/dns', DNS_SHAPE)
.then((found) => {
setDns(found)
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setDns(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the name server's state again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Ask for a confirmation, then send the removal and refresh. */
function confirmRemove(title: string, message: string, send: () => Promise<unknown>) {
+4 -2
View File
@@ -1,7 +1,9 @@
import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Typography } from '@mui/material'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, text } from './ServerPanel.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Pairs } from './ServerPanel.tsx'
import { text } from './format.ts'
import Toolbar from './Toolbar.tsx'
import { DETAILS_SHAPE, STATUS_SHAPE, request, type RouterDetails, type RouterStatus } from './api.ts'
import { useRead } from './useRead.ts'
+30 -24
View File
@@ -9,7 +9,8 @@ import { useCallback, useEffect, useState } from 'react'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import GroupDialog from './GroupDialog.tsx'
import { Section } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx'
import SearchField from './SearchField.tsx'
import { matches } from './search.ts'
import Toolbar from './Toolbar.tsx'
import { ApiError, GROUPS_SHAPE, GROUP_SHAPE, REMOVED_SHAPE, SERVICE_ACCOUNTS_SHAPE, USERS_SHAPE, request, type Group, type User } from './api.ts'
@@ -23,37 +24,42 @@ export default function GroupsPanel() {
const [users, setUsers] = useState<string[]>([])
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [adding, setAdding] = useState(false)
const [editing, setEditing] = useState<Group | null>(null)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [search, setSearch] = useState('')
const refresh = useCallback(async () => {
setBusy(true)
try {
const [found, people, services] = await Promise.all([
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
request<{ service_accounts: User[] }>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
])
setGroups(found.groups)
setUsers([...people.users, ...services.service_accounts.filter((account) => !account.internal)].map((user) => user.name).sort())
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setGroups(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
/** Reads the groups with the users and service accounts; the state changes only once the server answers. */
const read = useCallback(async () => {
await Promise.all([
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
request<{ service_accounts: User[] }>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
])
.then(([found, people, services]) => {
setGroups(found.groups)
setUsers([...people.users, ...services.service_accounts.filter((account) => !account.internal)].map((user) => user.name).sort())
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setGroups(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the groups again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Runs a change of a group, then reads the list again; a failure is shown above the list. */
async function change(work: () => Promise<unknown>) {
+6 -4
View File
@@ -71,16 +71,18 @@ export default function HelpPanel(props: { open: boolean; topic: string; onClose
const { mode, systemMode } = useColorScheme()
const scheme = (mode === 'system' ? systemMode : mode) === 'dark' ? 'dark' : 'light'
const [history, setHistory] = useState<string[]>([props.topic])
const [topic, setTopic] = useState(props.topic)
const [title, setTitle] = useState('Help')
const [error, setError] = useState<string | null>(null)
const content = useRef<HTMLDivElement>(null)
// A new topic starts the history again.
if (topic !== props.topic) {
setTopic(props.topic)
setHistory([props.topic])
}
const current = history[history.length - 1]
const [path, anchor] = current.split('#')
useEffect(() => {
setHistory([props.topic])
}, [props.topic])
useEffect(() => {
if (!props.open) {
return
+1 -8
View File
@@ -1,14 +1,7 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
import { HTTPS_CERTIFICATES, type HttpsCertificateSource, type HttpsChange, type HttpsSettings } from './api.ts'
/** The labels of the sources of the server's certificate. */
export const CERTIFICATE_LABELS: Record<HttpsCertificateSource, string> = {
acme: 'ACME',
'self-signed': 'Self-signed',
ca: 'Servers Issuing CA of the server\'s PKI',
external: 'Another CA: a CSR signed there, or a PFX',
}
import { CERTIFICATE_LABELS } from './https.ts'
/**
* A dialog that edits where the certificate of the server's FQDN comes from, https.certificate: the ACME CA of
+1 -1
View File
@@ -2,7 +2,7 @@ import {
Alert, Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, TextField, Typography,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import { NAME_PATTERN, RESERVED, made, nameProblem } from './PkiSettingsDialog.tsx'
import { made, NAME_PATTERN, nameProblem, RESERVED } from './pki.ts'
import { ROUTER_TEMPLATES, type Pki, type PkiIssuingCa } from './api.ts'
/**
+33 -18
View File
@@ -38,25 +38,40 @@ export default function LogsPanel() {
.catch((caught) => setError((caught as Error).message))
}, [])
const read = useCallback(async () => {
if (kind === 'file' && !file) {
setLines(null)
return
}
setBusy(true)
const query = kind === 'journal'
// The query of the log chosen, null while the Files tab has no file.
const query = kind === 'file' && !file
? null
: kind === 'journal'
? `/logs/journal?lines=${count}${unit ? `&unit=${encodeURIComponent(unit)}` : ''}`
: `/logs/file?lines=${count}&path=${encodeURIComponent(file)}`
try {
setLines((await request<{ lines: string[] }>('GET', query, LOG_LINES_SHAPE)).lines)
setError(null)
} catch (caught) {
setLines(null)
setError((caught as Error).message)
} finally {
setBusy(false)
// The query whose answer is shown.
const [shown, setShown] = useState<string | null>(null)
const reading = busy || (sources !== null && query !== null && shown !== query)
/** Reads the log chosen; the state changes only once the server answers. */
const read = useCallback(async () => {
if (query === null) {
return
}
}, [kind, unit, file, count])
await request<{ lines: string[] }>('GET', query, LOG_LINES_SHAPE)
.then((found) => {
setLines(found.lines)
setError(null)
}, (caught) => {
setLines(null)
setError((caught as Error).message)
})
.finally(() => {
setShown(query)
setBusy(false)
})
}, [query])
/** Reads the log again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
if (sources) {
@@ -104,13 +119,13 @@ export default function LogsPanel() {
<VerticalAlignBottom fontSize="small" sx={{ mr: 0.5 }} />
Follow
</ToggleButton>
<Button variant="outlined" startIcon={<Refresh />} disabled={busy || follow || !sources} onClick={() => void read()}>
<Button variant="outlined" startIcon={<Refresh />} disabled={reading || follow || !sources} onClick={() => void refresh()}>
Refresh
</Button>
</Toolbar>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{kind === 'file' && sources && sources.files.length === 0 && <Alert severity="info" sx={{ mb: 2 }}>No log files are configured.</Alert>}
<LogView lines={lines} empty={busy ? '(reading)' : '(no lines)'} maxHeight={600} follow={follow} />
<LogView lines={query === null ? null : lines} empty={reading ? '(reading)' : '(no lines)'} maxHeight={600} follow={follow} />
</Box>
)
}
+31 -16
View File
@@ -4,8 +4,9 @@ import { Alert, Box, Button, Stack, ToggleButton, ToggleButtonGroup, Typography
import { LineChart } from '@mui/x-charts/LineChart'
import { useCallback, useEffect, useState } from 'react'
import MetricsSettingsDialog from './MetricsSettingsDialog.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { bytes } from './ServerPanel.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { bytes } from './format.ts'
import {
METRICS_RANGES, METRICS_SETTINGS_SHAPE, METRICS_SHAPE, request, type Aggregate, type MetricsHistory, type MetricsRange,
type MetricsSettings,
@@ -74,6 +75,8 @@ export default function MetricsPanel() {
const [error, setError] = useState<string | null>(null)
const [reading, setReading] = useState(true)
const [at, setAt] = useState<Date | null>(null)
// The end of the axis until the first read answers.
const [opened] = useState(() => new Date())
const [hidden, setHidden] = useState<Record<string, string[]>>(readHidden)
const [settings, setSettings] = useState<(MetricsSettings & { otlp_password_set: boolean }) | null>(null)
const [opening, setOpening] = useState(false)
@@ -99,24 +102,31 @@ export default function MetricsPanel() {
})
}
const refresh = useCallback(async () => {
setReading(true)
try {
setHistory(await request<MetricsHistory>('GET', `/metrics/history?range=${range}`, METRICS_SHAPE))
setError(null)
} catch (caught) {
setError(`The server did not give its metrics: ${(caught as Error).message}`)
}
setAt(new Date())
setReading(false)
/** Reads the metrics of the view; the state changes only once the server answers. */
const read = useCallback(async () => {
await request<MetricsHistory>('GET', `/metrics/history?range=${range}`, METRICS_SHAPE)
.then((found) => {
setHistory(found)
setError(null)
}, (caught) => setError(`The server did not give its metrics: ${(caught as Error).message}`))
.finally(() => {
setAt(new Date())
setReading(false)
})
}, [range])
/** Reads the metrics again, reading until the server answers. */
const refresh = useCallback(() => {
setReading(true)
return read()
}, [read])
// A read at once and on every change of the view, then every metricsRefresh seconds of the browser's settings, unless
// it is manual (0).
const { metricsRefresh } = useBrowserSettings()
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
useEffect(() => {
if (metricsRefresh === 0) {
return
@@ -133,7 +143,7 @@ export default function MetricsPanel() {
const tunnels = [...new Set(points.flatMap((point) => Object.keys(point.site_to_site)))].sort()
const format = new Intl.DateTimeFormat(undefined, RANGES[range].format)
// The axis spans the whole view, whatever part of it has data.
const end = at ?? new Date()
const end = at ?? opened
const start = RANGES[range].start(end)
const percent = (value: number) => `${value.toFixed(1)} %`
@@ -226,7 +236,12 @@ export default function MetricsPanel() {
return (
<Box component="section">
<Stack direction="row" sx={{ mb: 2, alignItems: 'center', gap: 2, flexWrap: 'wrap' }}>
<ToggleButtonGroup size="small" exclusive value={range} onChange={(_event, next: MetricsRange | null) => next && setRange(next)}>
<ToggleButtonGroup size="small" exclusive value={range} onChange={(_event, next: MetricsRange | null) => {
if (next) {
setReading(true)
setRange(next)
}
}}>
{METRICS_RANGES.map((name) => <ToggleButton key={name} value={name}>{RANGES[name].label}</ToggleButton>)}
</ToggleButtonGroup>
<ToggleButtonGroup size="small" exclusive value={consolidation} onChange={(_event, next: Consolidation | null) => next && setConsolidation(next)}>
+4 -2
View File
@@ -1,7 +1,9 @@
import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button } from '@mui/material'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Grid, Pairs, text } from './ServerPanel.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Grid, Pairs } from './ServerPanel.tsx'
import { text } from './format.ts'
import Toolbar from './Toolbar.tsx'
import { DETAILS_SHAPE, request, type RouterDetails } from './api.ts'
import { useRead } from './useRead.ts'
+14 -5
View File
@@ -6,6 +6,7 @@ import People from '@mui/icons-material/People'
import Public from '@mui/icons-material/Public'
import ViewInAr from '@mui/icons-material/ViewInAr'
import Router from '@mui/icons-material/Router'
import Terminal from '@mui/icons-material/Terminal'
import VerifiedUser from '@mui/icons-material/VerifiedUser'
import VpnKey from '@mui/icons-material/VpnKey'
import { Button, ListItemIcon, ListItemText, Menu, MenuItem } from '@mui/material'
@@ -35,7 +36,7 @@ export const SITES_PATH = '/sites-manager'
/** The path of the DNS page: the name server's settings, domains and records. */
export const DNS_PATH = '/dns-manager'
/** The path of the shell page: a login shell on the server, opened with the shell button of the header, not the menu. */
/** The path of the Shell page: a login shell on the server. */
export const SHELL_PATH = '/shell'
/** The pages of an administrator in the menu: path, label and icon. */
@@ -48,13 +49,15 @@ const PAGES: { path: string; label: string; icon: ReactNode }[] = [
{ path: SITES_PATH, label: 'Web Sites', icon: <Public fontSize="small" /> },
{ path: DNS_PATH, label: 'DNS', icon: <Dns fontSize="small" /> },
{ path: DOCKER_PATH, label: 'Docker', icon: <ViewInAr fontSize="small" /> },
{ path: SHELL_PATH, label: 'Shell', icon: <Terminal fontSize="small" /> },
]
/**
* A button naming the page shown, or Pages on the account and the shell page, whose menu opens the pages of an
* administrator but those of hidden, the pages of a component switched off or of software the server does not have.
* A button naming the page shown, or Pages on the account page, whose menu opens the pages of an administrator but
* those of hidden, the pages of a component switched off or of software the server does not have; the pages of newTab
* open in a new tab.
*/
export default function PageMenu(props: { path: string; hidden: string[] }) {
export default function PageMenu(props: { path: string; hidden: string[]; newTab: string[] }) {
const [anchor, setAnchor] = useState<HTMLElement | null>(null)
const current = PAGES.find((page) => page.path === props.path) ?? { path: props.path, label: 'Pages', icon: <MenuIcon fontSize="small" /> }
return (
@@ -72,7 +75,13 @@ export default function PageMenu(props: { path: string; hidden: string[] }) {
</Button>
<Menu anchorEl={anchor} open={anchor !== null} onClose={() => setAnchor(null)}>
{PAGES.filter((page) => !props.hidden.includes(page.path)).map((page) => (
<MenuItem key={page.path} component="a" href={page.path} selected={page.path === current.path}>
<MenuItem
key={page.path}
component="a"
href={page.path}
{...(props.newTab.includes(page.path) && page.path !== current.path ? { target: '_blank', rel: 'noreferrer' } : {})}
selected={page.path === current.path}
>
<ListItemIcon>{page.icon}</ListItemIcon>
<ListItemText>{page.label}</ListItemText>
</MenuItem>
+2 -49
View File
@@ -13,7 +13,8 @@ import {
import { DndContext, KeyboardSensor, PointerSensor, closestCenter, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core'
import { SortableContext, arrayMove, rectSortingStrategy, sortableKeyboardCoordinates, useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { useState, type ReactNode } from 'react'
import type { ReactNode } from 'react'
import type { BoardState, Layout } from './useBoard.ts'
/** Colours of the panel titles: brown in the light scheme, gold in the dark one. */
const TITLE_LIGHT = '#8b4513'
@@ -25,44 +26,6 @@ const TITLE_DARK = '#d4af37'
*/
export type BoardPanel = { id: string; title: string; actions?: ReactNode; content: ReactNode; wide?: boolean; fixed?: boolean }
/** The layout of a board: the order of the panel ids, the width chosen for a panel, and the hidden and the folded panels. */
export type Layout = { order: string[]; widths: Record<string, 'wide' | 'single'>; hidden: string[]; folded: string[] }
const EMPTY: Layout = { order: [], widths: {}, hidden: [], folded: [] }
/** The layout kept in localStorage under key, or an empty one when there is none or it cannot be read. */
function readLayout(key: string): Layout {
try {
const value: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null')
if (value !== null && typeof value === 'object') {
const stored = value as Partial<Layout>
const strings = (items: unknown) => (Array.isArray(items) ? items.filter((item): item is string => typeof item === 'string') : [])
return {
order: strings(stored.order),
widths: stored.widths !== null && typeof stored.widths === 'object' ? stored.widths : {},
hidden: strings(stored.hidden),
folded: strings(stored.folded),
}
}
} catch {
// A layout that cannot be read is replaced by the default.
}
return EMPTY
}
/** The layout of a board kept in the browser's localStorage under key, and a function that changes and keeps it. */
export function useLayout(key: string): [Layout, (change: (current: Layout) => Layout) => void] {
const [layout, setLayout] = useState<Layout>(() => readLayout(key))
function update(change: (current: Layout) => Layout) {
setLayout((current) => {
const next = change(current)
window.localStorage.setItem(key, JSON.stringify(next))
return next
})
}
return [layout, update]
}
/** The panels in the order of the layout; a panel the layout does not know yet comes after the known ones, in the given order. */
function ordered(panels: BoardPanel[], layout: Layout) {
const rank = (panel: BoardPanel) => {
@@ -230,16 +193,6 @@ export function PanelsDialog(props: { open: boolean; panels: BoardPanel[]; layou
)
}
/** The state of a page's board: its layout kept in the browser under key, whether it is edited, and the Panels dialog. */
export type BoardState = ReturnType<typeof useBoard>
export function useBoard(key: string) {
const [layout, setLayout] = useLayout(key)
const [editing, setEditing] = useState(false)
const [choosing, setChoosing] = useState(false)
return { layout, setLayout, editing, setEditing, choosing, setChoosing }
}
/** The buttons of a board: Edit layout, Done while editing, and Panels, which opens the Panels dialog. */
export function BoardButtons(props: { board: BoardState }) {
const { editing, setEditing, setChoosing } = props.board
+5 -80
View File
@@ -1,72 +1,15 @@
import {
Alert, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, TextField,
Typography,
Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiAuthority, type PkiRootSource, type PkiSettings, type PkiTemplate } from './api.ts'
/** The labels of the publishing endpoints. */
export const PUBLISH_LABELS: Record<string, string> = {
http: 'HTTP on the status port, served by the web service',
'http-80': 'HTTP on port 80, served by Caddy',
https: 'HTTPS on the HTTPS status port, served by Caddy',
'https-default': 'HTTPS on port 443, served by Caddy',
}
/** The labels of the sources of the root CA. */
export const ROOT_SOURCE_LABELS: Record<PkiRootSource, string> = {
local: 'Created by the server',
offline: 'Offline',
'simple-ca': 'Simple CA',
}
/** The name of an issuing CA or a template, as the server accepts it. */
export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/
/** The names the issuing CAs of pki.issuing_cas cannot have. */
export const RESERVED = ['root', 'upstream', 'p2s', 's2s', 'servers']
/** The longest common name of a CA, in characters. */
const CA_NAME_MAX = 64
/** The longest lifetime the server accepts, in days. */
const DAYS_MAX = 36500
/** A new template's options. */
export const NEW_TEMPLATE: PkiTemplate = {
key: 'rsa-3072', days: 365, key_usage: ['digital_signature'], extended_key_usage: [], subject: 'name', sans: [], policies: [],
}
/** Whether an issuing CA has its certificate or its CSR, which fix its common name. */
export function made(authority: PkiAuthority) {
return authority.state === 'active' || authority.state === 'pending'
}
/** A common name's problem, or ''. */
export function nameProblem(value: string) {
return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : ''
}
/** The problem of the URL of a Simple CA service, or ''. */
export function urlProblem(value: string) {
try {
const url = new URL(value.trim())
return url.protocol === 'https:' && url.hostname !== '' && url.search === '' && url.hash === '' ? '' : 'An https:// URL.'
} catch {
return 'An https:// URL.'
}
}
/** A lifetime's problem, or ''. */
export function daysProblem(value: number) {
return !Number.isInteger(value) || value < 1 || value > DAYS_MAX ? `1 to ${DAYS_MAX} days.` : ''
}
import { PKI_KEYS, type Pki, type PkiSettings } from './api.ts'
import { ROOT_SOURCE_LABELS, daysProblem, made, nameProblem, urlProblem } from './pki.ts'
/**
* A dialog that edits the server's pki section but the general-purpose issuing CAs, the templates and the custom
* extended key usages, which IssuingCaDialog, TemplateDialog and EkuDialog edit: the names of the P2S and site-to-site
* CAs, the lifetimes and key type of the CAs, the validity of the CRLs, where certificates and CRLs are published and,
* with a Simple CA root, the URL of the service. The source of the root is shown and not edited, as it is fixed once
* CAs, the lifetimes and key type of the CAs, the validity of the CRLs and, with a Simple CA root, the URL of the
* service. The source of the root is shown and not edited, as it is fixed once
* the root exists. The root and the Servers CA are made by the first setup, so their names are not shown; the P2S and
* site-to-site CAs are made when the VPN and the router are switched on, and their names are fixed from then on. The
* server applies the lifetimes and key type when it creates a CA. onSave sends the settings; the dialog closes when it
@@ -188,24 +131,6 @@ export default function PkiSettingsDialog(props: {
onChange={(event) => change({ root_crl_days: number(event.target.value) })}
/>
</Stack>
<Typography variant="subtitle2">Published certificates and CRLs</Typography>
<Box>
{PKI_PUBLISH.map((item) => (
<FormControlLabel
key={item}
sx={{ display: 'flex' }}
control={
<Checkbox
checked={settings.publish.includes(item)}
onChange={(event) => change({
publish: PKI_PUBLISH.filter((name) => (name === item ? event.target.checked : settings.publish.includes(name))),
})}
/>
}
label={PUBLISH_LABELS[item]}
/>
))}
</Box>
</Stack>
</DialogContent>
<DialogActions>
+30 -24
View File
@@ -3,12 +3,15 @@ import Edit from '@mui/icons-material/Edit'
import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Chip, Stack } from '@mui/material'
import { useCallback, useEffect, useState } from 'react'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import RemoteAccessDialog from './RemoteAccessDialog.tsx'
import Toolbar from './Toolbar.tsx'
import WireGuardConfigDialog from './WireGuardConfigDialog.tsx'
import WireGuardPeers from './WireGuardPeers.tsx'
import { Copyable, Grid, IPSEC_HEADS, Pairs, bytes, ipsecRows, text } from './ServerPanel.tsx'
import { Copyable, Grid, Pairs } from './ServerPanel.tsx'
import { bytes, text } from './format.ts'
import { IPSEC_HEADS, ipsecRows } from './ipsec.ts'
import {
DETAILS_SHAPE, REMOTE_ACCESS_LABELS, REMOTE_ACCESS_SECTION_SHAPES, REMOTE_ACCESS_SHAPE, STATUS_SHAPE, USERS_SHAPE, request,
type RemoteAccess, type RemoteAccessSystem, type RouterDetails, type RouterStatus, type Users,
@@ -41,7 +44,7 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
const [access, setAccess] = useState<RemoteAccess | null>(null)
const [status, setStatus] = useState<RouterStatus | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [editing, setEditing] = useState(false)
const [showConfig, setShowConfig] = useState(false)
const board = useBoard(LAYOUT_KEYS[props.system])
@@ -52,30 +55,33 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
// IKEv2's: the server's details with its IPsec SAs and connections, those of IKEv2 access being all but site to site.
const ikev2 = props.system === 'p2s'
const refresh = useCallback(async () => {
setBusy(true)
try {
const [nextAccess, nextStatus, nextUsers, nextDetails] = await Promise.all([
request<RemoteAccess>('GET', '/remote-access', REMOTE_ACCESS_SHAPE),
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE),
wireguard ? request<Users>('GET', '/users', USERS_SHAPE) : null,
wireguard || ikev2 ? request<RouterDetails>('GET', '/config', DETAILS_SHAPE) : null,
])
setAccess(nextAccess)
setStatus(nextStatus)
setUsers(nextUsers)
setDetails(nextDetails)
setError(null)
} catch (caught) {
setError((caught as Error).message)
} finally {
setBusy(false)
}
/** Reads the access of the system with what it shows; the state changes only once the server answers. */
const read = useCallback(async () => {
await Promise.all([
request<RemoteAccess>('GET', '/remote-access', REMOTE_ACCESS_SHAPE),
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE),
wireguard ? request<Users>('GET', '/users', USERS_SHAPE) : null,
wireguard || ikev2 ? request<RouterDetails>('GET', '/config', DETAILS_SHAPE) : null,
])
.then(([nextAccess, nextStatus, nextUsers, nextDetails]) => {
setAccess(nextAccess)
setStatus(nextStatus)
setUsers(nextUsers)
setDetails(nextDetails)
setError(null)
}, (caught) => setError((caught as Error).message))
.finally(() => setBusy(false))
}, [wireguard, ikev2])
/** Reads the access again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
async function save(settings: Record<string, unknown>) {
await request('PUT', `/remote-access/${props.system}`, REMOTE_ACCESS_SECTION_SHAPES[props.system], settings)
-6
View File
@@ -14,9 +14,3 @@ export default function SearchField(props: { value: string; onChange: (value: st
/>
)
}
/** Whether any of the texts contains the search, ignoring case; an empty search matches everything. */
export function matches(search: string, texts: (string | null | undefined)[]) {
const wanted = search.trim().toLowerCase()
return wanted === '' || texts.some((text) => text?.toLowerCase().includes(wanted))
}
+27 -21
View File
@@ -1,12 +1,15 @@
import Settings from '@mui/icons-material/Settings'
import { Alert, Box, Button, Chip, IconButton, Stack, Tooltip, Typography } from '@mui/material'
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import AcmeSettingsDialog, { PROVIDER_LABELS } from './AcmeSettingsDialog.tsx'
import { when } from './BackupSummary.tsx'
import HttpsSettingsDialog, { CERTIFICATE_LABELS } from './HttpsSettingsDialog.tsx'
import AcmeSettingsDialog from './AcmeSettingsDialog.tsx'
import { PROVIDER_LABELS } from './https.ts'
import { when } from './format.ts'
import HttpsSettingsDialog from './HttpsSettingsDialog.tsx'
import { CERTIFICATE_LABELS } from './https.ts'
import ImportDialog from './ImportDialog.tsx'
import PfxDialog from './PfxDialog.tsx'
import { Pairs, Section, text } from './ServerPanel.tsx'
import { Pairs, Section } from './ServerPanel.tsx'
import { text } from './format.ts'
import { saveFile } from './saveFile.ts'
import {
DETAILS_SHAPE, HTTPS_CSR_SHAPE, HTTPS_IMPORTED_SHAPE, HTTPS_SETTINGS_SHAPE, request, type HttpsCertificate, type HttpsChange,
@@ -31,26 +34,29 @@ export default function ServerCertificatePanel() {
const [settings, setSettings] = useState<{ dialog: 'https' | 'acme'; settings: HttpsSettings } | null>(null)
const [importing, setImporting] = useState<'certificate' | 'pfx' | null>(null)
const refresh = useCallback(async () => {
setReading(true)
try {
const [nextDetails, nextHttps] = await Promise.all([
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
request<{ certificate?: HttpsCertificate }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE),
])
setDetails(nextDetails)
setCertificate(nextHttps.certificate ?? null)
setError(null)
} catch (caught) {
setError(`The server did not give its HTTPS settings: ${(caught as Error).message}`)
} finally {
setReading(false)
}
/** Reads the server's details and HTTPS certificate; the state changes only once the server answers. */
const read = useCallback(async () => {
await Promise.all([
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
request<{ certificate?: HttpsCertificate }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE),
])
.then(([nextDetails, nextHttps]) => {
setDetails(nextDetails)
setCertificate(nextHttps.certificate ?? null)
setError(null)
}, (caught) => setError(`The server did not give its HTTPS settings: ${(caught as Error).message}`))
.finally(() => setReading(false))
}, [])
/** Reads the details and the certificate again, reading until the server answers. */
const refresh = useCallback(() => {
setReading(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Reads the server's https section from /https/settings and opens HttpsSettingsDialog or AcmeSettingsDialog with it. */
async function open(dialog: 'https' | 'acme') {
+25 -108
View File
@@ -3,14 +3,17 @@ import PlayArrow from '@mui/icons-material/PlayArrow'
import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Chip, IconButton, Link, Paper, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip, Typography } from '@mui/material'
import { Fragment, useCallback, useEffect, useState, type ReactNode } from 'react'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import UpdatesNotice from './UpdatesNotice.tsx'
import { BackupChip, backupRows } from './BackupSummary.tsx'
import { BackupChip } from './BackupSummary.tsx'
import { backupRows } from './backup.ts'
import {
ApiError, BACKUP_SHAPE, DETAILS_SHAPE, INFO_SHAPE, POSTGRESQL_SHAPE,
STARTED_SHAPE, STATUS_SHAPE, request, type Backup, type Info, type PostgresqlDatabases,
type RouterDetails, type RouterStatus,
} from './api.ts'
import { bytes, text } from './format.ts'
import { useBrowserSettings } from './settings.ts'
/** The localStorage key of the tab's layout. */
@@ -44,10 +47,10 @@ export default function ServerPanel() {
const board = useBoard(LAYOUT_KEY)
const [busy, setBusy] = useState(false)
const refresh = useCallback(async () => {
setReading(true)
/** Reads the server's state; the state changes only once the server answers. */
const read = useCallback(async () => {
const found: { status?: string; details?: string; databases?: string; backup?: string } = {}
const [nextStatus, nextDetails, nextDatabases, nextBackup, nextInfo] = await Promise.all([
await Promise.all([
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE).catch((error: Error) => {
found.status = `The server did not give its status: ${error.message}`
return null
@@ -67,24 +70,31 @@ export default function ServerPanel() {
return null
}),
request<Info>('GET', '/info', INFO_SHAPE).catch(() => null),
])
setManager(nextInfo?.manager ?? null)
setStatus(nextStatus)
setDetails(nextDetails)
setDatabases(nextDatabases)
setBackup(nextBackup)
setProblems(found)
setReading(false)
]).then(([nextStatus, nextDetails, nextDatabases, nextBackup, nextInfo]) => {
setManager(nextInfo?.manager ?? null)
setStatus(nextStatus)
setDetails(nextDetails)
setDatabases(nextDatabases)
setBackup(nextBackup)
setProblems(found)
setReading(false)
})
}, [])
/** Reads the server's state again, reading until the server answers. */
const refresh = useCallback(() => {
setReading(true)
return read()
}, [read])
// A read at once and when a check for updates, an upgrade or a reboot ends, then every routerRefresh seconds of the
// browser's settings, unless it is manual (0); nothing is read while one of them runs (busy).
const { routerRefresh } = useBrowserSettings()
useEffect(() => {
if (!busy) {
void refresh()
void read()
}
}, [refresh, busy])
}, [read, busy])
useEffect(() => {
if (routerRefresh === 0 || busy) {
return
@@ -347,14 +357,6 @@ export default function ServerPanel() {
)
}
/** A value as text: lists joined with commas, an empty value as a dash. */
export function text(value: unknown): string {
if (Array.isArray(value)) {
return value.length === 0 ? '-' : value.join(', ')
}
return value === undefined || value === null || value === '' ? '-' : String(value)
}
/** The names shown for the server's systemd units; a unit not listed is shown by its unit name. */
const UNIT_LABELS: Record<string, string> = {
'linux-manager-setup': 'Linux Manager Setup',
@@ -364,7 +366,6 @@ const UNIT_LABELS: Record<string, string> = {
slapd: 'OpenLDAP',
}
/** Colours of the panel titles: brown in the light scheme, gold in the dark one. */
const TITLE_LIGHT = '#8b4513'
const TITLE_DARK = '#d4af37'
@@ -474,7 +475,6 @@ function Addressed(props: { text: string }) {
})
}
/** Whether a configuration section is in use: not switched off, and with at least one value set. */
/** The headings of the sections of the configuration; a section not listed is headed by its name. */
const SECTION_LABELS: Record<string, string> = {
@@ -507,86 +507,3 @@ function Links(props: { urls: string[] }) {
function sectionConfigured(values: Record<string, unknown>) {
return values.enabled !== false && Object.values(values).some((value) => text(value) !== '-')
}
/** The column titles of the IPsec tables of ipsecRows. */
export const IPSEC_HEADS = {
sas: ['Connection', 'State', 'Local', 'Remote', 'Algorithms', 'Up'],
childSas: ['Child SA', 'State', 'Traffic selectors', 'In', 'Out', 'Up'],
connections: ['Connection', 'Version', 'Local address', 'Local identity', 'Remote address', 'Remote identity', 'Authentication'],
children: ['Child', 'Mode', 'Local traffic selectors', 'Remote traffic selectors'],
}
/**
* The rows of the IPsec tables of the server's /config for the connections whose names keep accepts: the IKE SAs, their
* child SAs, the connections and their children; undefined where the server could not list them.
*/
export function ipsecRows(details: RouterDetails | null, keep: (name: string) => boolean) {
const sas = details?.ipsec.sas?.filter((sa) => keep(sa.name))
const connections = details?.ipsec.connections?.filter((connection) => keep(connection.name))
return {
sas: sas?.map((sa) => [
sa.name,
sa.state,
`${sa['local-id']} @ ${sa['local-host']}`,
`${sa['remote-id']} @ ${sa['remote-host']}`,
[`${text(sa['encr-alg'])}-${text(sa['encr-keysize'])}`, sa['integ-alg'], sa['dh-group']].filter(Boolean).join(', '),
sa.established === undefined ? '-' : duration(Number(sa.established)),
]),
childSas: sas?.flatMap((sa) =>
Object.values(sa['child-sas'] ?? {}).map((child) => [
`${sa.name}/${child.name}`,
`${child.state}, ${child.mode}`,
`${child['local-ts'].join(', ')} <-> ${child['remote-ts'].join(', ')}`,
`${bytes(Number(child['bytes-in']))}, ${child['packets-in']} packets`,
`${bytes(Number(child['bytes-out']))}, ${child['packets-out']} packets`,
child['install-time'] === undefined ? '-' : duration(Number(child['install-time'])),
]),
),
connections: connections?.map((connection) => {
const local = authOf(connection, 'local')
const remote = authOf(connection, 'remote')
return [
connection.name,
connection.version,
text(connection.local_addrs),
text(local.id),
text(connection.remote_addrs),
text(remote.id),
local.class === remote.class ? text(local.class) : `${text(local.class)} / ${text(remote.class)}`,
]
}),
children: connections?.flatMap((connection) =>
Object.entries(connection.children ?? {}).map(([name, child]) => [
`${connection.name}/${name}`,
child.mode,
child['local-ts'].join(', '),
child['remote-ts'].join(', '),
]),
),
}
}
/** The authentication round of one side of a connection: swanctl names them local-1, remote-1 and so on. */
function authOf(connection: Record<string, unknown>, side: 'local' | 'remote'): { class?: string; id?: string } {
const round = Object.entries(connection).find(([key, value]) => key.startsWith(`${side}-`) && typeof value === 'object' && value !== null)
return (round?.[1] ?? {}) as { class?: string; id?: string }
}
/** Seconds as "1h 2m 3s". */
export function duration(seconds: number) {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
return [h && `${h}h`, (h || m) && `${m}m`, `${seconds % 60}s`].filter(Boolean).join(' ')
}
/** Bytes in B, KiB, MiB or GiB. */
export function bytes(count: number) {
const units = ['B', 'KiB', 'MiB', 'GiB']
let value = count
let unit = 0
while (value >= 1024 && unit < units.length - 1) {
value /= 1024
unit += 1
}
return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`
}
+32 -26
View File
@@ -10,7 +10,8 @@ import { Alert, Box, Button, IconButton, Table, TableBody, TableCell, TableHead,
import { useCallback, useEffect, useState } from 'react'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import { Section } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx'
import SearchField from './SearchField.tsx'
import { matches } from './search.ts'
import ServiceAccountDialog from './ServiceAccountDialog.tsx'
import Toolbar from './Toolbar.tsx'
import UserDialog from './UserDialog.tsx'
@@ -57,40 +58,45 @@ export default function ServiceAccountsPanel() {
const [users, setUsers] = useState<string[]>([])
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [adding, setAdding] = useState(false)
const [editing, setEditing] = useState<User | null>(null)
const [password, setPassword] = useState<string | null>(null)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [search, setSearch] = useState('')
const refresh = useCallback(async () => {
setBusy(true)
try {
const [found, groupList, userList] = await Promise.all([
request<ServiceAccounts>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
])
setAccounts(found.service_accounts)
setOidc(found.oidc)
setGroups(groupList.groups.map((group) => group.name))
setUsers(userList.users.map((user) => user.name))
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setAccounts(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
/** Reads the service accounts with the groups and users; the state changes only once the server answers. */
const read = useCallback(async () => {
await Promise.all([
request<ServiceAccounts>('GET', '/service-accounts', SERVICE_ACCOUNTS_SHAPE),
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<{ users: User[] }>('GET', '/users', USERS_SHAPE),
])
.then(([found, groupList, userList]) => {
setAccounts(found.service_accounts)
setOidc(found.oidc)
setGroups(groupList.groups.map((group) => group.name))
setUsers(userList.users.map((user) => user.name))
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setAccounts(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the service accounts again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Runs a change of an account, then reads the list again; a failure is shown above the list. */
async function change(work: () => Promise<unknown>) {
+2 -2
View File
@@ -5,8 +5,8 @@ import { DEFAULT_SETTINGS, REFRESH_CHOICES, refreshLabel, saveBrowserSettings, u
/**
* An icon button that opens the settings of this browser: how often the Overview and the Metrics tab read the server on
* their own, or manual, when they read only when opened and on Refresh, and whether the shell button opens the shell in
* a new tab. A change applies at once and is kept in the browser; Defaults sets every setting back.
* their own, or manual, when they read only when opened and on Refresh, and whether the page menu opens the Shell page
* in a new tab. A change applies at once and is kept in the browser; Defaults sets every setting back.
*/
export default function SettingsButton() {
const [open, setOpen] = useState(false)
+10 -9
View File
@@ -69,16 +69,17 @@ export default function ShellPanel(props: { editorShown: boolean; onFiles: (coun
}
}, [])
// The account, then a ticket when its console login is usable.
useEffect(() => {
request<Account>('GET', '/account', ACCOUNT_SHAPE).then(setAccount).catch((caught: Error) => setError(caught.message))
}, [])
const enabled = login !== null
useEffect(() => {
if (enabled) {
void reopen()
}
}, [enabled, reopen])
request<Account>('GET', '/account', ACCOUNT_SHAPE)
.then((found) => {
setAccount(found)
if (found.console?.enabled && found.otp) {
void reopen()
}
})
.catch((caught: Error) => setError(caught.message))
}, [reopen])
useEffect(() => {
opened.current = props.onOpened
+35 -20
View File
@@ -13,7 +13,8 @@ import {
} from '@mui/material'
import { useCallback, useEffect, useState, type DragEvent, type FormEvent } from 'react'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import { Section, bytes } from './ServerPanel.tsx'
import { Section } from './ServerPanel.tsx'
import { bytes } from './format.ts'
import Toolbar from './Toolbar.tsx'
import {
ApiError, SITES_SHAPE, SITE_FILES_SHAPE, SITE_FOLDER_SHAPE, SITE_PATH_SHAPE, download, encodedPath, request, upload,
@@ -77,7 +78,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
const [path, setPath] = useState('')
const [folder, setFolder] = useState<SiteFolder | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [working, setWorking] = useState(false)
const [progress, setProgress] = useState<{ name: string; share: number } | null>(null)
const [extract, setExtract] = useState(true)
const [creating, setCreating] = useState(false)
@@ -91,29 +92,43 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
request<Sites>('GET', '/sites', SITES_SHAPE).then(setSites).catch((caught) => setError((caught as ApiError).message))
}, [])
const refresh = useCallback(async () => {
if (!site) {
// The address of the folder shown, null without a site, and the one whose answer is shown.
const address = site ? `${base}/${encodedPath(path)}` : null
const [shown, setShown] = useState<string | null>(null)
const busy = working || (address !== null && shown !== address)
/** Reads the folder; the state changes only once the server answers. */
const read = useCallback(async () => {
if (address === null) {
return
}
setBusy(true)
try {
setFolder(await request<SiteFolder>('GET', `${base}/${encodedPath(path)}`, SITE_FOLDER_SHAPE))
setError(null)
} catch (caught) {
setFolder(null)
setError((caught as Error).message)
} finally {
setBusy(false)
}
}, [site, base, path])
await request<SiteFolder>('GET', address, SITE_FOLDER_SHAPE)
.then((found) => {
setFolder(found)
setError(null)
}, (caught) => {
setFolder(null)
setError((caught as Error).message)
})
.finally(() => {
setShown(address)
setWorking(false)
})
}, [address])
/** Reads the folder again, busy until the server answers. */
const refresh = useCallback(() => {
setWorking(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Runs a change of the files, then reads the folder again; a failure is shown above the list. */
async function change(work: () => Promise<unknown>) {
setBusy(true)
setWorking(true)
let failure: string | null = null
try {
await work()
@@ -130,7 +145,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
async function send(files: File[]) {
const limit = (sites?.settings.upload_max_mb ?? 0) * 1024 * 1024
const failures: string[] = []
setBusy(true)
setWorking(true)
for (const file of files) {
if (limit && file.size > limit) {
failures.push(`${file.name}: larger than ${sites?.settings.upload_max_mb} MiB.`)
@@ -146,7 +161,7 @@ export default function SiteFiles(props: { site: string | null; onSite: (name: s
}
}
setProgress(null)
setBusy(false)
setWorking(false)
await refresh()
setError(failures.length ? failures.join('\n') : null)
}
+23 -18
View File
@@ -30,31 +30,36 @@ export default function SiteToSitePanel() {
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [note, setNote] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [adding, setAdding] = useState(false)
const [editing, setEditing] = useState<SiteToSiteConnection | null>(null)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const refresh = useCallback(async () => {
setBusy(true)
try {
const found = await request<{ connections: SiteToSiteConnection[] }>('GET', '/site-to-site', SITE_TO_SITE_SHAPE)
setConnections(found.connections)
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setConnections(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
/** Reads the connections; the state changes only once the server answers. */
const read = useCallback(async () => {
await request<{ connections: SiteToSiteConnection[] }>('GET', '/site-to-site', SITE_TO_SITE_SHAPE)
.then((found) => {
setConnections(found.connections)
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setConnections(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the connections again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
function remove(connection: SiteToSiteConnection) {
setConfirm({
+5 -2
View File
@@ -1,7 +1,10 @@
import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button } from '@mui/material'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Grid, IPSEC_HEADS, duration, ipsecRows, text } from './ServerPanel.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Grid } from './ServerPanel.tsx'
import { duration, text } from './format.ts'
import { IPSEC_HEADS, ipsecRows } from './ipsec.ts'
import Toolbar from './Toolbar.tsx'
import { DETAILS_SHAPE, request, type RouterDetails } from './api.ts'
import { useRead } from './useRead.ts'
+36 -29
View File
@@ -9,9 +9,11 @@ import Settings from '@mui/icons-material/Settings'
import { Alert, Box, Button, Checkbox, Chip, FormControlLabel, IconButton, Link, Stack, Table, TableBody, TableCell, TableHead, TableRow, Tooltip } from '@mui/material'
import { useCallback, useEffect, useState, type ReactNode } from 'react'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import { Copyable, Pairs } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx'
import SearchField from './SearchField.tsx'
import { matches } from './search.ts'
import SiteDialog, { type SiteSettings } from './SiteDialog.tsx'
import SitesSettingsDialog from './SitesSettingsDialog.tsx'
import Toolbar from './Toolbar.tsx'
@@ -44,7 +46,7 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
const [groups, setGroups] = useState<string[]>([])
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [adding, setAdding] = useState(false)
const [editing, setEditing] = useState<Site | null>(null)
const [settings, setSettings] = useState(false)
@@ -52,35 +54,40 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
const [search, setSearch] = useState('')
const board = useBoard(LAYOUT_KEY)
const refresh = useCallback(async () => {
setBusy(true)
try {
const [found, groupList, details] = await Promise.all([
request<Sites>('GET', '/sites', SITES_SHAPE),
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
])
setSites(found)
setGroups(groupList.groups.map((group) => group.name))
const wan = details.configuration.wan ?? {}
const pki = details.configuration.pki ?? {}
setFqdn(typeof wan.local_fqdn === 'string' ? wan.local_fqdn : '')
setCas(typeof pki.issuing_cas === 'object' && pki.issuing_cas !== null ? Object.keys(pki.issuing_cas) : [])
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setSites(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
/** Reads the sites with the groups and the server's details; the state changes only once the server answers. */
const read = useCallback(async () => {
await Promise.all([
request<Sites>('GET', '/sites', SITES_SHAPE),
request<{ groups: Group[] }>('GET', '/groups', GROUPS_SHAPE),
request<RouterDetails>('GET', '/config', DETAILS_SHAPE),
])
.then(([found, groupList, details]) => {
setSites(found)
setGroups(groupList.groups.map((group) => group.name))
const wan = details.configuration.wan ?? {}
const pki = details.configuration.pki ?? {}
setFqdn(typeof wan.local_fqdn === 'string' ? wan.local_fqdn : '')
setCas(typeof pki.issuing_cas === 'object' && pki.issuing_cas !== null ? Object.keys(pki.issuing_cas) : [])
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setSites(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the sites again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Runs a change of a site, then reads the list again; a failure is shown above the list. */
async function change(work: () => Promise<unknown>) {
+2 -1
View File
@@ -1,6 +1,7 @@
import { Box } from '@mui/material'
import ComponentsPanel from './ComponentsPanel.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Board, BoardButtons, type BoardPanel } from './PanelBoard.tsx'
import { useBoard } from './useBoard.ts'
import Toolbar from './Toolbar.tsx'
import UpdatesNotice from './UpdatesNotice.tsx'
+1 -1
View File
@@ -2,7 +2,7 @@ import {
Alert, Autocomplete, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import { NAME_PATTERN, NEW_TEMPLATE, daysProblem } from './PkiSettingsDialog.tsx'
import { daysProblem, NAME_PATTERN, NEW_TEMPLATE } from './pki.ts'
import {
BUILTIN_TEMPLATES, KEY_USAGES, OID_PATTERN, PKI_KEYS, SAN_TYPES, TEMPLATE_SUBJECTS, type Pki, type PkiTemplate,
} from './api.ts'
+2 -5
View File
@@ -50,16 +50,13 @@ export default function UpdatesNotice(props: { onBusy?: (busy: boolean) => void;
const [rebooting, setRebooting] = useState(false)
const read = useCallback(async () => {
try {
const next = await request<UpgradeState>('GET', upgradePath, UPGRADE_SHAPE)
await request<UpgradeState>('GET', upgradePath, UPGRADE_SHAPE).then((next) => {
setUpgrade(next)
setUnreachable(false)
if (next.state !== 'running') {
request<Updates>('GET', updatesPath, UPDATES_SHAPE).then(setUpdates, (caught: Error) => setError(caught.message))
}
} catch {
setUnreachable(true)
}
}, () => setUnreachable(true))
}, [updatesPath, upgradePath])
useEffect(() => {
+25 -18
View File
@@ -20,7 +20,8 @@ import OtpDialog from './OtpDialog.tsx'
import PersonDialog from './PersonDialog.tsx'
import ProfileDialog from './ProfileDialog.tsx'
import { Section } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx'
import SearchField from './SearchField.tsx'
import { matches } from './search.ts'
import Toolbar from './Toolbar.tsx'
import UserDialog from './UserDialog.tsx'
import {
@@ -54,7 +55,7 @@ export default function UsersPanel() {
const [users, setUsers] = useState<User[] | null>(null)
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const [adding, setAdding] = useState(false)
const [password, setPassword] = useState<string | null>(null)
const [details, setDetails] = useState<User | null>(null)
@@ -66,8 +67,8 @@ export default function UsersPanel() {
const [search, setSearch] = useState('')
const [kind, setKind] = useState<Kind>('all')
const refresh = useCallback(async () => {
setBusy(true)
/** Reads the users; the state changes only once the server answers. */
const read = useCallback(async () => {
// The status has openvpn and p2s while the server runs OpenVPN and IKEv2, which the profiles need; null while it is
// not known.
request<RouterStatus>('GET', '/status/full', STATUS_SHAPE)
@@ -79,23 +80,29 @@ export default function UsersPanel() {
setOpenvpn(null)
setP2s(null)
})
try {
setUsers((await request<{ users: User[] }>('GET', '/users', USERS_SHAPE)).users)
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setUsers(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
await request<{ users: User[] }>('GET', '/users', USERS_SHAPE)
.then((found) => {
setUsers(found.users)
setError(null)
setUnavailable(false)
}, (caught) => {
const failure = caught as ApiError
setUsers(null)
setUnavailable(failure.status === 404)
setError(failure.message)
})
.finally(() => setBusy(false))
}, [])
/** Reads the users again, busy until the server answers. */
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
/** Runs a change of a user, then reads the list again; a failure is shown above the list after the reading. */
async function change(work: () => Promise<unknown>) {
-5
View File
@@ -346,9 +346,6 @@ export type Backup = {
/** The key types of the CAs and of the templates. */
export const PKI_KEYS = ['rsa-2048', 'rsa-3072', 'rsa-4096', 'ec-p256', 'ec-p384'] as const
/** Where the CA certificates and CRLs are published, in the order the certificates list the URLs. */
export const PKI_PUBLISH = ['http', 'http-80', 'https', 'https-default'] as const
/** The key usages a template may give. */
export const KEY_USAGES = ['digital_signature', 'content_commitment', 'key_encipherment', 'data_encipherment', 'key_agreement'] as const
@@ -391,7 +388,6 @@ export type PkiSettings = {
key: string
crl_days: number
root_crl_days: number
publish: string[]
p2s_name: string
s2s_name: string
servers_name: string
@@ -977,7 +973,6 @@ const PKI_SETTINGS: Check = object({
key: string,
crl_days: number,
root_crl_days: number,
publish: list(string),
p2s_name: string,
s2s_name: string,
servers_name: string,
+31
View File
@@ -0,0 +1,31 @@
import type { Backup } from './api.ts'
import { bytes, when } from './format.ts'
/** The labels of the backup targets. */
export const TARGET_LABELS: Record<string, string> = { local: 'Local folder', pbs: 'Proxmox Backup Server' }
/** The schedule, the next run (as systemd shows it) and the last run of the server's backups, as rows of Pairs. */
export function backupRows(backup: Backup): [string, string][] {
const { settings, state } = backup
const rows: [string, string][] = [
['Backups', settings.enabled ? `${settings.schedule}, to ${TARGET_LABELS[settings.target] ?? settings.target}` : 'off'],
['Next run', backup.next ?? '-'],
]
if (!state) {
return [...rows, ['Last run', 'none']]
}
rows.push(
['Last run', `${when(state.started)}${state.finished ? ` to ${new Date(state.finished).toLocaleTimeString()}` : ''}`],
['Last result', state.result],
)
if (state.archive ?? state.snapshot) {
rows.push(['Last backup', `${state.archive ?? state.snapshot}${state.size === null ? '' : `, ${bytes(state.size)}`}`])
}
if (state.cloud) {
rows.push(['Cloud copy', `${state.cloud.mode} to ${state.cloud.remote}: ${state.cloud.error ?? state.cloud.result}`])
}
if (state.error) {
rows.push(['Error', state.error])
}
return rows
}
+31
View File
@@ -0,0 +1,31 @@
/** A time of the server in the browser's format, or a dash. */
export function when(time: string | null | undefined) {
return time ? new Date(time).toLocaleString() : '-'
}
/** A value as text: lists joined with commas, an empty value as a dash. */
export function text(value: unknown): string {
if (Array.isArray(value)) {
return value.length === 0 ? '-' : value.join(', ')
}
return value === undefined || value === null || value === '' ? '-' : String(value)
}
/** Seconds as "1h 2m 3s". */
export function duration(seconds: number) {
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
return [h && `${h}h`, (h || m) && `${m}m`, `${seconds % 60}s`].filter(Boolean).join(' ')
}
/** Bytes in B, KiB, MiB or GiB. */
export function bytes(count: number) {
const units = ['B', 'KiB', 'MiB', 'GiB']
let value = count
let unit = 0
while (value >= 1024 && unit < units.length - 1) {
value /= 1024
unit += 1
}
return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`
}
+16
View File
@@ -0,0 +1,16 @@
import type { AcmeProvider, HttpsCertificateSource } from './api.ts'
/** The labels of the sources of the server's certificate. */
export const CERTIFICATE_LABELS: Record<HttpsCertificateSource, string> = {
acme: 'ACME',
'self-signed': 'Self-signed',
ca: 'Servers Issuing CA of the server\'s PKI',
external: 'Another CA: a CSR signed there, or a PFX',
}
/** The labels of the ACME providers. */
export const PROVIDER_LABELS: Record<AcmeProvider, string> = {
letsencrypt: 'Let\'s Encrypt',
zerossl: 'ZeroSSL',
custom: 'Custom directory URL',
}
+66
View File
@@ -0,0 +1,66 @@
import type { RouterDetails } from './api.ts'
import { bytes, duration, text } from './format.ts'
/** The column titles of the IPsec tables of ipsecRows. */
export const IPSEC_HEADS = {
sas: ['Connection', 'State', 'Local', 'Remote', 'Algorithms', 'Up'],
childSas: ['Child SA', 'State', 'Traffic selectors', 'In', 'Out', 'Up'],
connections: ['Connection', 'Version', 'Local address', 'Local identity', 'Remote address', 'Remote identity', 'Authentication'],
children: ['Child', 'Mode', 'Local traffic selectors', 'Remote traffic selectors'],
}
/**
* The rows of the IPsec tables of the server's /config for the connections whose names keep accepts: the IKE SAs, their
* child SAs, the connections and their children; undefined where the server could not list them.
*/
export function ipsecRows(details: RouterDetails | null, keep: (name: string) => boolean) {
const sas = details?.ipsec.sas?.filter((sa) => keep(sa.name))
const connections = details?.ipsec.connections?.filter((connection) => keep(connection.name))
return {
sas: sas?.map((sa) => [
sa.name,
sa.state,
`${sa['local-id']} @ ${sa['local-host']}`,
`${sa['remote-id']} @ ${sa['remote-host']}`,
[`${text(sa['encr-alg'])}-${text(sa['encr-keysize'])}`, sa['integ-alg'], sa['dh-group']].filter(Boolean).join(', '),
sa.established === undefined ? '-' : duration(Number(sa.established)),
]),
childSas: sas?.flatMap((sa) =>
Object.values(sa['child-sas'] ?? {}).map((child) => [
`${sa.name}/${child.name}`,
`${child.state}, ${child.mode}`,
`${child['local-ts'].join(', ')} <-> ${child['remote-ts'].join(', ')}`,
`${bytes(Number(child['bytes-in']))}, ${child['packets-in']} packets`,
`${bytes(Number(child['bytes-out']))}, ${child['packets-out']} packets`,
child['install-time'] === undefined ? '-' : duration(Number(child['install-time'])),
]),
),
connections: connections?.map((connection) => {
const local = authOf(connection, 'local')
const remote = authOf(connection, 'remote')
return [
connection.name,
connection.version,
text(connection.local_addrs),
text(local.id),
text(connection.remote_addrs),
text(remote.id),
local.class === remote.class ? text(local.class) : `${text(local.class)} / ${text(remote.class)}`,
]
}),
children: connections?.flatMap((connection) =>
Object.entries(connection.children ?? {}).map(([name, child]) => [
`${connection.name}/${name}`,
child.mode,
child['local-ts'].join(', '),
child['remote-ts'].join(', '),
]),
),
}
}
/** The authentication round of one side of a connection: swanctl names them local-1, remote-1 and so on. */
function authOf(connection: Record<string, unknown>, side: 'local' | 'remote'): { class?: string; id?: string } {
const round = Object.entries(connection).find(([key, value]) => key.startsWith(`${side}-`) && typeof value === 'object' && value !== null)
return (round?.[1] ?? {}) as { class?: string; id?: string }
}
+50
View File
@@ -0,0 +1,50 @@
import type { PkiAuthority, PkiRootSource, PkiTemplate } from './api.ts'
/** The labels of the sources of the root CA. */
export const ROOT_SOURCE_LABELS: Record<PkiRootSource, string> = {
local: 'Created by the server',
offline: 'Offline',
'simple-ca': 'Simple CA',
}
/** The name of an issuing CA or a template, as the server accepts it. */
export const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}$/
/** The names the issuing CAs of pki.issuing_cas cannot have. */
export const RESERVED = ['root', 'upstream', 'p2s', 's2s', 'servers']
/** The longest common name of a CA, in characters. */
const CA_NAME_MAX = 64
/** The longest lifetime the server accepts, in days. */
const DAYS_MAX = 36500
/** A new template's options. */
export const NEW_TEMPLATE: PkiTemplate = {
key: 'rsa-3072', days: 365, key_usage: ['digital_signature'], extended_key_usage: [], subject: 'name', sans: [], policies: [],
}
/** Whether an issuing CA has its certificate or its CSR, which fix its common name. */
export function made(authority: PkiAuthority) {
return authority.state === 'active' || authority.state === 'pending'
}
/** A common name's problem, or ''. */
export function nameProblem(value: string) {
return value.trim() === '' || value.trim().length > CA_NAME_MAX ? `1 to ${CA_NAME_MAX} characters.` : ''
}
/** The problem of the URL of a Simple CA service, or ''. */
export function urlProblem(value: string) {
try {
const url = new URL(value.trim())
return url.protocol === 'https:' && url.hostname !== '' && url.search === '' && url.hash === '' ? '' : 'An https:// URL.'
} catch {
return 'An https:// URL.'
}
}
/** A lifetime's problem, or ''. */
export function daysProblem(value: number) {
return !Number.isInteger(value) || value < 1 || value > DAYS_MAX ? `1 to ${DAYS_MAX} days.` : ''
}
+5
View File
@@ -0,0 +1,5 @@
/** Whether any of the texts contains the search, ignoring case; an empty search matches everything. */
export function matches(search: string, texts: (string | null | undefined)[]) {
const wanted = search.trim().toLowerCase()
return wanted === '' || texts.some((text) => text?.toLowerCase().includes(wanted))
}
+1 -1
View File
@@ -3,7 +3,7 @@ import { useSyncExternalStore } from 'react'
/**
* The settings of this browser: the seconds between the automatic reads of the Overview and the Metrics tab, 0 for
* manual, whether the WireGuard configuration dialog leaves out the lines a client fills in (wireguardPrefilled), and
* whether the shell button opens the shell in a new tab (shellNewTab).
* whether the page menu opens the Shell page in a new tab (shellNewTab).
*/
export type BrowserSettings = { routerRefresh: number; metricsRefresh: number; wireguardPrefilled: boolean; shellNewTab: boolean }
+49
View File
@@ -0,0 +1,49 @@
import { useState } from 'react'
/** The layout of a board: the order of the panel ids, the width chosen for a panel, and the hidden and the folded panels. */
export type Layout = { order: string[]; widths: Record<string, 'wide' | 'single'>; hidden: string[]; folded: string[] }
const EMPTY: Layout = { order: [], widths: {}, hidden: [], folded: [] }
/** The layout kept in localStorage under key, or an empty one when there is none or it cannot be read. */
function readLayout(key: string): Layout {
try {
const value: unknown = JSON.parse(window.localStorage.getItem(key) ?? 'null')
if (value !== null && typeof value === 'object') {
const stored = value as Partial<Layout>
const strings = (items: unknown) => (Array.isArray(items) ? items.filter((item): item is string => typeof item === 'string') : [])
return {
order: strings(stored.order),
widths: stored.widths !== null && typeof stored.widths === 'object' ? stored.widths : {},
hidden: strings(stored.hidden),
folded: strings(stored.folded),
}
}
} catch {
// A layout that cannot be read is replaced by the default.
}
return EMPTY
}
/** The layout of a board kept in the browser's localStorage under key, and a function that changes and keeps it. */
function useLayout(key: string): [Layout, (change: (current: Layout) => Layout) => void] {
const [layout, setLayout] = useState<Layout>(() => readLayout(key))
function update(change: (current: Layout) => Layout) {
setLayout((current) => {
const next = change(current)
window.localStorage.setItem(key, JSON.stringify(next))
return next
})
}
return [layout, update]
}
/** The state of a page's board: its layout kept in the browser under key, whether it is edited, and the Panels dialog. */
export type BoardState = ReturnType<typeof useBoard>
export function useBoard(key: string) {
const [layout, setLayout] = useLayout(key)
const [editing, setEditing] = useState(false)
const [choosing, setChoosing] = useState(false)
return { layout, setLayout, editing, setEditing, choosing, setChoosing }
}
+16 -13
View File
@@ -8,23 +8,26 @@ import { useCallback, useEffect, useState } from 'react'
export function useRead<T>(load: () => Promise<T>) {
const [data, setData] = useState<T | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [busy, setBusy] = useState(true)
const refresh = useCallback(async () => {
setBusy(true)
try {
setData(await load())
setError(null)
} catch (caught) {
setError((caught as Error).message)
} finally {
setBusy(false)
}
// The state changes only once load answers.
const read = useCallback(async () => {
await load()
.then((answer) => {
setData(answer)
setError(null)
}, (caught) => setError((caught as Error).message))
.finally(() => setBusy(false))
}, [load])
const refresh = useCallback(() => {
setBusy(true)
return read()
}, [read])
useEffect(() => {
void refresh()
}, [refresh])
void read()
}, [read])
return { data, error, busy, refresh }
}