feature: the VPN, the router, the name server and WebDAV are components switched on the System tab and installed on demand, Caddy from the Ubuntu archive is a dependency and serves every HTTP and HTTPS port, HTTPS is chosen at install, its certificate is of the Servers Issuing CA or self-signed by default, of ACME or of another CA, the issuing CAs are in one tab, a locked account is unlocked again, the name of a CA is fixed once the CA exists, and a run of setup is no longer cut short by a change.
Release / release (push) Failing after 8s

This commit is contained in:
slawek committed 2026-11-24 05:51:27 +01:00
1 parent a649331aa2
commit a7bfabcb89
97 files changed
+4498 -1834

No files matched your search

+55 -27
View File
@@ -11,15 +11,19 @@ import { useEffect, useState, type FormEvent } from 'react'
import OtpDialog from './OtpDialog.tsx'
import PasskeyDialog from './PasskeyDialog.tsx'
import ProfileDialog from './ProfileDialog.tsx'
import { Section } from './ServerPanel.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import Toolbar from './Toolbar.tsx'
import { ACCOUNT_SHAPE, CODE_PATTERN, USER_SHAPE, request, type Account, type User } from './api.ts'
/** The localStorage key of the page's layout. */
const LAYOUT_KEY = 'linux-manager-ui.account-layout'
/**
* The account of the signed-in user, from the server's /account, in two columns: the details with Change password,
* which opens the password dialog, and the passkeys in the first row, the enrolment for one-time passwords and the
* OpenVPN and the Apple VPN profile of a user with a certificate in the second. Each change but the removal of a
* passkey takes the current password and, for an enrolled user, a current code. A changed password ends the session,
* through onPasswordChanged.
* through onPasswordChanged. The panels are on a PanelBoard whose layout is kept in the browser.
*/
export default function AccountPanel(props: { onPasswordChanged: () => void }) {
const [account, setAccount] = useState<Account | null>(null)
@@ -35,6 +39,7 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
const [addingPasskey, setAddingPasskey] = useState(false)
const [profile, setProfile] = useState<'openvpn' | 'apple' | null>(null)
const [passkeyError, setPasskeyError] = useState<string | null>(null)
const board = useBoard(LAYOUT_KEY)
useEffect(() => {
request<Account>('GET', '/account', ACCOUNT_SHAPE)
@@ -100,20 +105,28 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
['One-time passwords', account.otp ? 'enrolled' : 'not enrolled'],
]
return (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' }, alignItems: 'start' }}>
<Section title="Account">
<Box component="dl" sx={{ display: 'grid', gridTemplateColumns: 'max-content 1fr', columnGap: 2, rowGap: 0.5, m: 0 }}>
{rows.map(([label, value]) => (
<Box key={label} sx={{ display: 'contents' }}>
<Typography component="dt" variant="body2" color="text.secondary">{label}</Typography>
<Typography component="dd" variant="body2" sx={{ m: 0 }}>{value}</Typography>
</Box>
))}
</Box>
<Button variant="outlined" startIcon={<Password />} sx={{ mt: 2 }} onClick={() => setChangingPassword(true)}>Change password</Button>
</Section>
<Section title="Passkeys">
const panels: BoardPanel[] = [
{
id: 'account',
title: 'Account',
content: (
<>
<Box component="dl" sx={{ display: 'grid', gridTemplateColumns: 'max-content 1fr', columnGap: 2, rowGap: 0.5, m: 0 }}>
{rows.map(([label, value]) => (
<Box key={label} sx={{ display: 'contents' }}>
<Typography component="dt" variant="body2" color="text.secondary">{label}</Typography>
<Typography component="dd" variant="body2" sx={{ m: 0 }}>{value}</Typography>
</Box>
))}
</Box>
<Button variant="outlined" startIcon={<Password />} sx={{ mt: 2 }} onClick={() => setChangingPassword(true)}>Change password</Button>
</>
),
},
{
id: 'passkeys',
title: 'Passkeys',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
{passkeyError && <Alert severity="error" sx={{ whiteSpace: 'pre-line', alignSelf: 'stretch' }}>{passkeyError}</Alert>}
{account.passkeys.length === 0
@@ -144,8 +157,12 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
)}
<Button variant="outlined" startIcon={<Key />} onClick={() => setAddingPasskey(true)}>Add a passkey</Button>
</Stack>
</Section>
<Section title="One-time passwords">
),
},
{
id: 'otp',
title: 'One-time passwords',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
<Typography variant="body2" color="text.secondary">
{account.otp
@@ -154,15 +171,26 @@ export default function AccountPanel(props: { onPasswordChanged: () => void }) {
</Typography>
<Button variant="outlined" onClick={() => setEnrolling(true)}>{account.otp ? 'Replace the authenticator' : 'Enrol'}</Button>
</Stack>
</Section>
{account.certificate && (
<Section title="VPN profiles">
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
<Button variant="outlined" startIcon={<Download />} onClick={() => setProfile('openvpn')}>Download the OpenVPN profile</Button>
<Button variant="outlined" startIcon={<Apple />} onClick={() => setProfile('apple')}>Download the Apple VPN profile (IKEv2)</Button>
</Stack>
</Section>
)}
),
},
...(account.certificate ? [{
id: 'profiles',
title: 'VPN profiles',
content: (
<Stack sx={{ gap: 2, alignItems: 'flex-start' }}>
<Button variant="outlined" startIcon={<Download />} onClick={() => setProfile('openvpn')}>Download the OpenVPN profile</Button>
<Button variant="outlined" startIcon={<Apple />} onClick={() => setProfile('apple')}>Download the Apple VPN profile (IKEv2)</Button>
</Stack>
),
}] : []),
]
return (
<Box component="section">
<Toolbar description="The account you are signed in with.">
<BoardButtons board={board} />
</Toolbar>
<Board board={board} panels={panels} />
<Dialog open={changingPassword} onClose={closePasswordDialog} fullWidth maxWidth="xs">
<form onSubmit={changePassword}>
<DialogTitle>Change password</DialogTitle>
+132
View File
@@ -0,0 +1,132 @@
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',
}
/** The problem of a custom ACME directory URL, or ''. */
function urlProblem(value: string) {
try {
const url = new URL(value.trim())
return url.protocol === 'https:' && url.hostname !== '' && url.hash === '' ? '' : 'An https:// URL.'
} catch {
return 'An https:// URL.'
}
}
/**
* A dialog that edits the ACME CA Caddy takes certificates from, for the server's FQDN with https.certificate acme and
* for the web sites with TLS acme: Let's Encrypt, with its staging environment, ZeroSSL, with an optional API key, or a
* custom directory URL with optional EAB credentials. A secret left empty keeps its value. onSave sends the ACME
* settings only; the dialog closes when it succeeds and shows the server's message when it fails.
*/
export default function AcmeSettingsDialog(props: {
current: HttpsSettings
onSave: (settings: HttpsChange) => Promise<void>
onCancel: () => void
}) {
const current = props.current
const [provider, setProvider] = useState<AcmeProvider>(current.acme_provider)
const [staging, setStaging] = useState(current.acme_staging)
const [url, setUrl] = useState(current.acme_url)
const [keyId, setKeyId] = useState(current.acme_eab_key_id)
const [macKey, setMacKey] = useState('')
const [apiKey, setApiKey] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const custom = provider === 'custom'
const eabProblem = custom && ((keyId !== '' && macKey === '' && !current.acme_eab_mac_key_set) || (keyId === '' && macKey !== ''))
? 'The key ID and the MAC key are given together.' : ''
const blocked = (custom && urlProblem(url) !== '') || eabProblem !== ''
async function submit(event: FormEvent) {
event.preventDefault()
if (blocked) {
return
}
setSaving(true)
setError(null)
const change: HttpsChange = {
acme_provider: provider, acme_staging: staging,
acme_url: custom ? url.trim() : current.acme_url, acme_eab_key_id: custom ? keyId.trim() : current.acme_eab_key_id,
}
if (custom && macKey !== '') {
change.acme_eab_mac_key = macKey
}
if (custom && keyId.trim() === '') {
change.acme_eab_mac_key = ''
}
if (provider === 'zerossl' && apiKey !== '') {
change.zerossl_api_key = apiKey
}
try {
await props.onSave(change)
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>ACME CA</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<Typography variant="body2" color="text.secondary">
Caddy takes certificates from this CA for the server, when its certificate is ACME, and for the web sites with TLS ACME.
</Typography>
<TextField select label="Provider" value={provider} onChange={(event) => setProvider(event.target.value as AcmeProvider)}>
{ACME_PROVIDERS.map((item) => <MenuItem key={item} value={item}>{PROVIDER_LABELS[item]}</MenuItem>)}
</TextField>
{provider === 'letsencrypt' && (
<FormControlLabel control={<Switch checked={staging} onChange={(event) => setStaging(event.target.checked)} />} label="Staging environment, for tests: no browser trusts its certificates" />
)}
{provider === 'zerossl' && (
<TextField
label="API key"
type="password"
value={apiKey}
autoComplete="off"
helperText={current.zerossl_api_key_set ? 'Set; empty keeps it.' : 'Optional; without it the EAB credentials come from the e-mail address of https.email.'}
onChange={(event) => setApiKey(event.target.value.trim())}
/>
)}
{custom && (
<>
<TextField
label="ACME directory URL"
value={url}
autoComplete="off"
error={url !== '' && urlProblem(url) !== ''}
helperText={(url !== '' && urlProblem(url)) || 'Such as a HashiCorp Vault, Caddy or Simple CA ACME directory; the CA of its HTTPS certificate is in the server\'s trust store.'}
onChange={(event) => setUrl(event.target.value.trim())}
/>
<TextField label="EAB key ID" value={keyId} autoComplete="off" helperText="Optional." onChange={(event) => setKeyId(event.target.value.trim())} />
<TextField
label="EAB MAC key"
type="password"
value={macKey}
autoComplete="off"
error={eabProblem !== ''}
helperText={eabProblem || (current.acme_eab_mac_key_set ? 'Set; empty keeps it.' : 'With the key ID.')}
onChange={(event) => setMacKey(event.target.value.trim())}
/>
</>
)}
<Alert severity="info">The server runs its setup again, which applies the change.</Alert>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel} disabled={saving}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>Save</Button>
</DialogActions>
</Dialog>
)
}
+37 -18
View File
@@ -14,7 +14,7 @@ import LogsPanel from './LogsPanel.tsx'
import MetricsPanel from './MetricsPanel.tsx'
import DockerPanel from './DockerPanel.tsx'
import DnsPanel from './DnsPanel.tsx'
import PageMenu, { CA_PATH, DOCKER_PATH, REMOTE_ACCESS_PATH, SHELL_PATH, SITES_PATH, SITE_TO_SITE_PATH, USERS_PATH, USER_PATH } from './PageMenu.tsx'
import PageMenu, { CA_PATH, DNS_PATH, DOCKER_PATH, REMOTE_ACCESS_PATH, SHELL_PATH, SITES_PATH, SITE_TO_SITE_PATH, USERS_PATH, USER_PATH } from './PageMenu.tsx'
import NetworkPanel from './NetworkPanel.tsx'
import RemoteAccessPanel from './RemoteAccessPanel.tsx'
import ServerPanel from './ServerPanel.tsx'
@@ -31,7 +31,7 @@ import SiteToSiteStatusPanel from './SiteToSiteStatusPanel.tsx'
import ThemeMenu from './ThemeMenu.tsx'
import UsersPanel from './UsersPanel.tsx'
import {
ACCOUNT_SHAPE, DETAILS_SHAPE, SESSION_EXPIRED, SESSION_SHAPE, request, type Account, type Info, type RemoteAccessSystem,
ACCOUNT_SHAPE, DETAILS_SHAPE, INFO_SHAPE, SESSION_EXPIRED, SESSION_SHAPE, request, type Account, type Info, type RemoteAccessSystem,
type RouterDetails, type Session,
} from './api.ts'
@@ -39,16 +39,16 @@ import {
type View = 'router' | 'metrics' | 'logs' | 'backup' | 'system'
type UsersView = 'users' | 'groups' | 'service-accounts'
type SiteToSiteView = 'status' | 'network' | 'connections'
type SitesView = 'sites' | 'files' | 'dns'
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', dns: 'dns.md' }
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. */
const RETURN_KEY = 'linux-manager-ui.return:'
/** The pages of an administrator besides Router, which every other path shows. */
const PAGE_PATHS = [USER_PATH, USERS_PATH, SITE_TO_SITE_PATH, REMOTE_ACCESS_PATH, CA_PATH, SITES_PATH, DOCKER_PATH, SHELL_PATH]
const PAGE_PATHS = [USER_PATH, USERS_PATH, SITE_TO_SITE_PATH, REMOTE_ACCESS_PATH, CA_PATH, SITES_PATH, DNS_PATH, DOCKER_PATH, SHELL_PATH]
/** The help topic of each page, a document of /docs; the Router, the Identities and the Web Sites page have one per tab. */
const HELP_TOPICS: Record<string, string> = {
@@ -56,6 +56,7 @@ const HELP_TOPICS: Record<string, string> = {
[SITE_TO_SITE_PATH]: 'site-to-site.md',
[REMOTE_ACCESS_PATH]: 'remote-access.md',
[CA_PATH]: 'certificates.md',
[DNS_PATH]: 'dns.md',
[DOCKER_PATH]: 'docker.md',
[SHELL_PATH]: 'shell.md',
}
@@ -68,7 +69,7 @@ const HELP_KEY = 'linux-manager-ui.help'
* every path, it then shows the user's own account; at USERS_PATH the server's users, groups or service accounts; at
* SITE_TO_SITE_PATH its site-to-site connections, their state and its network with its routes; at REMOTE_ACCESS_PATH its IKEv2, OpenVPN and
* WireGuard access; at CA_PATH its certificates; at SITES_PATH its web
* sites, the files of a site, opened from the sites too, and its name server; 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
* 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
@@ -86,12 +87,17 @@ export default function App(props: { info: Info }) {
const [sitesView, setSitesView] = useState<SitesView>('sites')
const [filesSite, setFilesSite] = useState<string | null>(null)
const [session, setSession] = useState<Session | null | undefined>(undefined)
// /api/info again once signed in, as the version is told only with a session.
const [info, setInfo] = useState<Info>(props.info)
const [role, setRole] = useState<{ name: string; admin: boolean } | null>(null)
// The router and the VPN components as router.enabled and vpn.enabled of /config, and whether Docker is installed;
// null while not known, when every page shows.
const [components, setComponents] = useState<{ router: boolean; vpn: boolean; docker: boolean } | null>(null)
const [components, setComponents] = useState<{ router: boolean; vpn: boolean; dns: boolean; docker: boolean } | null>(null)
// Raised by the System tab's components, so that the pages follow a component switched there.
const [componentsRead, setComponentsRead] = useState(0)
const routerOff = components?.router === false
const vpnOff = components?.vpn === false
const dnsOff = components?.dns === false
const dockerMissing = components?.docker === false
const page = PAGE_PATHS.find((path) => path === window.location.pathname) ?? '/'
const userPage = page === USER_PATH
@@ -137,6 +143,7 @@ export default function App(props: { info: Info }) {
request<Account>('GET', '/account', ACCOUNT_SHAPE)
.then((account) => setRole({ name: session.name, admin: account.admin }))
.catch(() => setRole({ name: session.name, admin: false }))
request<Info>('GET', '/info', INFO_SHAPE).then(setInfo).catch(() => undefined)
}, [session])
useEffect(() => {
@@ -147,10 +154,11 @@ export default function App(props: { info: Info }) {
.then((details) => setComponents({
router: details.configuration.router?.enabled === true,
vpn: details.configuration.vpn?.enabled === true,
dns: details.configuration.dns?.enabled === true,
docker: details.docker.installed,
}))
.catch(() => setComponents(null))
}, [admin])
}, [admin, componentsRead])
/** Opens the page of the path, keeping the page it was opened from in sessionStorage, or returns to that page from it. */
function toggle(path: string) {
@@ -184,14 +192,16 @@ export default function App(props: { info: Info }) {
<Typography variant="h5" component="h1">
Ubuntu Linux Manager
</Typography>
<Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'monospace' }}>
{props.info.version ?? 'development'}
</Typography>
{session && (
<Typography variant="caption" color="text.secondary" sx={{ fontFamily: 'monospace' }}>
{info.version ?? 'development'}
</Typography>
)}
</Stack>
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
Server status page:{' '}
{props.info.status_url
? <Link href={props.info.status_url} target="_blank" rel="noreferrer">{props.info.status_url}</Link>
{info.status_url
? <Link href={info.status_url} target="_blank" rel="noreferrer">{info.status_url}</Link>
: <b>not configured</b>}
</Typography>
</Box>
@@ -244,7 +254,7 @@ export default function App(props: { info: Info }) {
</Tooltip>
)}
{session && admin && (
<PageMenu path={page} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
<PageMenu path={page} hidden={[...(vpnOff ? [REMOTE_ACCESS_PATH] : []), ...(dnsOff ? [DNS_PATH] : []), ...(dockerMissing ? [DOCKER_PATH] : [])]} />
)}
</Stack>
</Stack>
@@ -263,7 +273,6 @@ export default function App(props: { info: Info }) {
<Tabs value={sitesView} onChange={(_event, next: SitesView) => setSitesView(next)} sx={{ mb: 3, borderBottom: 1, borderColor: 'divider' }}>
<Tab value="sites" label="Sites" />
<Tab value="files" label="Files" />
<Tab value="dns" label="DNS" />
</Tabs>
{sitesView === 'sites' && (
<SitesPanel
@@ -274,7 +283,17 @@ export default function App(props: { info: Info }) {
/>
)}
{sitesView === 'files' && <SiteFiles key={filesSite ?? ''} site={filesSite} onSite={setFilesSite} />}
{sitesView === 'dns' && <DnsPanel />}
</>
)}
{session && admin && page === DNS_PATH && dnsOff && (
<Typography color="text.secondary">
The name server is off on this server: it is switched on on the System tab of the Server page.
</Typography>
)}
{session && admin && page === DNS_PATH && !dnsOff && (
<>
<Typography variant="h6" component="h2" sx={{ mb: 2 }}>DNS</Typography>
<DnsPanel />
</>
)}
{session && admin && page === DOCKER_PATH && dockerMissing && (
@@ -294,7 +313,7 @@ export default function App(props: { info: Info }) {
)}
{session && admin && page === REMOTE_ACCESS_PATH && vpnOff && (
<Typography color="text.secondary">
The VPN is off on this server: IKEv2, OpenVPN and WireGuard need vpn.enabled in the configuration.
The VPN is off on this server: it is switched on on the System tab of the Server page.
</Typography>
)}
{session && admin && page === REMOTE_ACCESS_PATH && !vpnOff && (
@@ -344,7 +363,7 @@ export default function App(props: { info: Info }) {
{view === 'metrics' && <MetricsPanel />}
{view === 'logs' && <LogsPanel />}
{view === 'backup' && <BackupPanel />}
{view === 'system' && <SystemPanel />}
{view === 'system' && <SystemPanel onComponentsChange={() => setComponentsRead((value) => value + 1)} />}
</>
)}
</Container>
+96 -74
View File
@@ -5,11 +5,15 @@ import { Alert, Box, Button, Table, TableBody, TableCell, TableHead, TablePagina
import { useCallback, useEffect, useRef, useState } from 'react'
import BackupDialog from './BackupDialog.tsx'
import { BackupChip, TARGET_LABELS, backupRows, when } from './BackupSummary.tsx'
import { Pairs, Section, bytes } from './ServerPanel.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, bytes } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx'
import Toolbar from './Toolbar.tsx'
import { ApiError, BACKUP_KEEPS, BACKUP_SCHEDULES, BACKUP_SETTINGS_SHAPE, BACKUP_SHAPE, STARTED_SHAPE, request, type Backup } from './api.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.backup-layout'
/** The note shown after a change, which the server applies when linux-manager-setup has run again. */
const APPLIED = 'The server applies the change in the background.'
@@ -19,7 +23,8 @@ const WATCH_SECONDS = 3
/**
* The server's backups: the settings, the last run and the local archives, searched by name and time and shown a page at
* a time; edit the settings and start a backup now.
* While a backup runs, or after Run now until it has ended, the tab reads every WATCH_SECONDS.
* While a backup runs, or after Run now until it has ended, the tab reads every WATCH_SECONDS. The panels are on a
* PanelBoard whose layout is kept in the browser.
*/
export default function BackupPanel() {
const [backup, setBackup] = useState<Backup | null>(null)
@@ -28,6 +33,7 @@ export default function BackupPanel() {
const [note, setNote] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [editing, setEditing] = useState(false)
const board = useBoard(LAYOUT_KEY)
const [watching, setWatching] = useState(false)
const [search, setSearch] = useState('')
const [page, setPage] = useState(0)
@@ -87,6 +93,92 @@ export default function BackupPanel() {
const local = settings?.target === 'local'
const keeps = settings ? BACKUP_KEEPS.slice(BACKUP_SCHEDULES.indexOf(settings.schedule as (typeof BACKUP_SCHEDULES)[number])) : []
const panels: BoardPanel[] = backup && settings ? [
{
id: 'settings',
title: 'Settings',
content: (
<Pairs
rows={[
['Scheduled backups', settings.enabled ? 'on' : 'off'],
['Schedule', settings.schedule],
['Target', TARGET_LABELS[settings.target] ?? settings.target],
['Metrics database', settings.metrics ? 'included' : 'not included'],
...(local
? [
['Folder', settings.path],
['Kept', keeps.map((keep) => `${settings[keep]} ${keep.slice(5)}`).join(', ')],
['Cloud copy', settings.rclone_remote ? `${settings.rclone_mode} to ${settings.rclone_remote}` : 'none'],
] satisfies [string, string][]
: [
['Repository', settings.pbs_repository || '-'],
['Token secret', settings.pbs_password_set ? 'set' : 'missing'],
['Fingerprint', settings.pbs_fingerprint || '-'],
['Namespace', settings.pbs_namespace || '-'],
['Encryption key file', settings.pbs_keyfile || 'none'],
] satisfies [string, string][]),
]}
/>
),
},
{
id: 'last-run',
title: 'Last run',
content: (
<>
<Box sx={{ mb: 1 }}><BackupChip state={backup.state} /></Box>
<Pairs rows={backupRows(backup)} />
</>
),
},
...(local ? [{
id: 'archives',
title: 'Local archives',
wide: true,
content: (
<>
<Box sx={{ mb: 1 }}>
<SearchField value={search} onChange={(value) => { setSearch(value); setPage(0) }} />
</Box>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Archive</TableCell>
<TableCell>Time</TableCell>
<TableCell align="right">Size</TableCell>
</TableRow>
</TableHead>
<TableBody>
{archives.length === 0 && (
<TableRow>
<TableCell colSpan={3} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{archives.slice(shownPage * rows, (shownPage + 1) * rows).map((archive) => (
<TableRow key={archive.name} hover>
<TableCell sx={{ fontFamily: 'monospace' }}>{archive.name}</TableCell>
<TableCell>{when(archive.time)}</TableCell>
<TableCell align="right">{bytes(archive.size)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
<TablePagination
component="div"
count={archives.length}
page={shownPage}
rowsPerPage={rows}
rowsPerPageOptions={[10, 25, 50, 100]}
onPageChange={(_event, next) => setPage(next)}
onRowsPerPageChange={(event) => { setRows(Number(event.target.value)); setPage(0) }}
/>
</>
),
}] : []),
] : []
return (
<Box component="section">
<Toolbar description="Backups of the server's configuration, keys, users and metrics.">
@@ -96,6 +188,7 @@ export default function BackupPanel() {
<Button variant="outlined" startIcon={<PlayArrow />} disabled={busy || backup === null || running || watching} onClick={() => void runNow()}>
Run now
</Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh
</Button>
@@ -114,78 +207,7 @@ export default function BackupPanel() {
</Alert>
)}
{backup && settings && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Settings">
<Pairs
rows={[
['Scheduled backups', settings.enabled ? 'on' : 'off'],
['Schedule', settings.schedule],
['Target', TARGET_LABELS[settings.target] ?? settings.target],
['Metrics database', settings.metrics ? 'included' : 'not included'],
...(local
? [
['Folder', settings.path],
['Kept', keeps.map((keep) => `${settings[keep]} ${keep.slice(5)}`).join(', ')],
['Cloud copy', settings.rclone_remote ? `${settings.rclone_mode} to ${settings.rclone_remote}` : 'none'],
] satisfies [string, string][]
: [
['Repository', settings.pbs_repository || '-'],
['Token secret', settings.pbs_password_set ? 'set' : 'missing'],
['Fingerprint', settings.pbs_fingerprint || '-'],
['Namespace', settings.pbs_namespace || '-'],
['Encryption key file', settings.pbs_keyfile || 'none'],
] satisfies [string, string][]),
]}
/>
</Section>
<Section title="Last run">
<Box sx={{ mb: 1 }}><BackupChip state={backup.state} /></Box>
<Pairs rows={backupRows(backup)} />
</Section>
{local && (
<Section title="Local archives" wide>
<Box sx={{ mb: 1 }}>
<SearchField value={search} onChange={(value) => { setSearch(value); setPage(0) }} />
</Box>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Archive</TableCell>
<TableCell>Time</TableCell>
<TableCell align="right">Size</TableCell>
</TableRow>
</TableHead>
<TableBody>
{archives.length === 0 && (
<TableRow>
<TableCell colSpan={3} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{archives.slice(shownPage * rows, (shownPage + 1) * rows).map((archive) => (
<TableRow key={archive.name} hover>
<TableCell sx={{ fontFamily: 'monospace' }}>{archive.name}</TableCell>
<TableCell>{when(archive.time)}</TableCell>
<TableCell align="right">{bytes(archive.size)}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
<TablePagination
component="div"
count={archives.length}
page={shownPage}
rowsPerPage={rows}
rowsPerPageOptions={[10, 25, 50, 100]}
onPageChange={(_event, next) => setPage(next)}
onRowsPerPageChange={(event) => { setRows(Number(event.target.value)); setPage(0) }}
/>
</Section>
)}
</Box>
)}
{backup && settings && <Board board={board} panels={panels} />}
{editing && backup && (
<BackupDialog
+221 -210
View File
@@ -21,7 +21,9 @@ 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 { Pairs, Section } from './ServerPanel.tsx'
import ServerCertificatePanel from './ServerCertificatePanel.tsx'
import SetupCodeDialog from './SetupCodeDialog.tsx'
import {
ApiError, BUNDLE_SHAPE, CA_IMPORTED_SHAPE, CRL_IMPORTED_SHAPE, CSR_SHAPE, ISSUED_SHAPE, PFX_SHAPE, PKI_SETTINGS_SHAPE, PKI_SHAPE, REVOKED_SHAPE,
@@ -30,12 +32,16 @@ import {
} from './api.ts'
import { saveFile } from './saveFile.ts'
/** The tabs of the page: the root and the general information, the templates, the extended key usages, the two
* built-in issuing CAs, the general-purpose ones. */
type View = 'root' | 'templates' | 'usages' | 'p2s' | 's2s' | 'issuing'
/** The tabs of the page: the server's HTTPS (ServerCertificatePanel), the root and the general information, the
* templates, the extended key usages, the issuing CAs. */
type View = 'server' | 'root' | 'templates' | 'usages' | 'issuing'
/** The built-in CAs and the Simple CA issuing CA above them, whose certificates the Issuing CAs tab leaves out. */
const BUILTIN_CAS = ['root', 'upstream', 'p2s', 's2s']
/** The localStorage keys of the layouts of the Root and the Issuing CAs tabs. */
const ROOT_LAYOUT_KEY = 'linux-manager-ui.certificates-root-layout'
const ISSUING_LAYOUT_KEY = 'linux-manager-ui.certificates-issuing-layout'
/** The CAs above the issuing CAs, whose certificates the Issuing CAs tab leaves out. */
const UPPER_CAS = ['root', 'upstream']
/** Where the root CRL came from. */
const CRL_SOURCE_LABELS: Record<string, string> = { signed: 'signed by the server', uploaded: 'uploaded', fetched: 'fetched from Simple CA' }
@@ -48,6 +54,7 @@ const STATE_COLORS: Record<string, 'success' | 'warning' | 'error' | 'default'>
active: 'success',
valid: 'success',
pending: 'warning',
off: 'default',
missing: 'error',
expired: 'default',
revoked: 'error',
@@ -65,15 +72,17 @@ const REASON_LABELS: Record<string, string> = {
/**
* The server's PKI in tabs: Root, the root CA with the general settings and the certificates of the issuing CAs;
* The server's certificates in tabs: Server, the server's HTTPS (ServerCertificatePanel), shown first and also
* while the PKI cannot be read; Root, the root CA with the general settings and the certificates of the issuing CAs;
* Templates, the certificate templates, which are added, changed, removed and reset there; Extended key usages, the
* built-in ones and the custom ones, which are added, changed and removed there; P2S Issuing CA and S2S
* Issuing CA, each built-in CA with the certificates it issued; Issuing CAs, the general-purpose CAs, which are added,
* changed and removed there, with their certificates, filtered by CA. The warnings, Issue and Settings
* are above the tabs. Settings edits the pki section, Issue issues a certificate from a CSR or into a PFX file, a
* built-in ones and the custom ones, which are added, changed and removed there; Issuing CAs, the built-in p2s, s2s and
* servers and the custom CAs, which are added, changed and removed there, with the certificates of all of them, filtered
* by CA. The warnings are above the tabs, and so are Issue and Settings but on the Server tab, whose Refresh reads it
* again. Settings edits the pki section, Issue issues a certificate from a CSR or into a PFX file, a
* certificate of another system or of the server is revoked, an issuing CA waiting for the offline root gives its CSR
* and takes its signed certificate, the offline root takes its certificate and a CRL signed offline, and a Simple CA
* root takes a setup code for a new token.
* root takes a setup code for a new token. The panels of the Root and the Issuing CAs tabs are on a PanelBoard per tab
* whose layout is kept in the browser.
*/
export default function CertificatesPanel() {
const [pki, setPki] = useState<Pki | null>(null)
@@ -91,7 +100,10 @@ export default function CertificatesPanel() {
const [entering, setEntering] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [filter, setFilter] = useState('')
const [view, setView] = useState<View>('root')
const [view, setView] = useState<View>('server')
const [serverRead, setServerRead] = useState(0)
const rootBoard = useBoard(ROOT_LAYOUT_KEY)
const issuingBoard = useBoard(ISSUING_LAYOUT_KEY)
const refresh = useCallback(async () => {
setBusy(true)
@@ -257,11 +269,11 @@ export default function CertificatesPanel() {
}
const root = pki?.status.root
const general = pki?.status.authorities.filter((authority) => !authority.builtin) ?? []
const generalNames = [...new Set([...general.map((authority) => authority.name),
...(pki?.certificates ?? []).map((certificate) => certificate.ca).filter((name) => !BUILTIN_CAS.includes(name))])]
const generalCertificates = (pki?.certificates ?? [])
.filter((certificate) => !BUILTIN_CAS.includes(certificate.ca) && (filter === '' || certificate.ca === filter))
const authorities = pki?.status.authorities ?? []
const authorityNames = [...new Set([...authorities.map((authority) => authority.name),
...(pki?.certificates ?? []).map((certificate) => certificate.ca).filter((name) => !UPPER_CAS.includes(name))])]
const issuedCertificates = (pki?.certificates ?? [])
.filter((certificate) => !UPPER_CAS.includes(certificate.ca) && (filter === '' || certificate.ca === filter))
/** The actions of an issuing CA waiting for the offline root: download its CSR and import its signed certificate. */
const pendingActions = (name: string) => (
@@ -347,56 +359,198 @@ export default function CertificatesPanel() {
</Box>
)
/** A tab of a built-in issuing CA: its details, the actions while it waits for the offline root, its certificates. */
const builtinTab = (name: 'p2s' | 's2s', title: string) => {
const authority = pki?.status.authorities.find((item) => item.name === name)
return (
<Box sx={{ display: 'grid', gap: 2 }}>
<Section title={title}>
{authority ? (
const rootPanels: BoardPanel[] = pki ? [
{
id: 'root',
title: 'Root CA',
content: (
<>
{root && (
<>
<Pairs
rows={[
['Common name', authority.subject ?? authority.common_name],
['State', <Chip size="small" label={authority.state} color={STATE_COLORS[authority.state] ?? 'default'} />],
['Expires', when(authority.expires)],
['CRL valid until', when(authority.crl_next_update)],
['Templates', authority.templates.join(', ')],
['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'} />],
['Subject', root.subject ?? '-'],
['Expires', when(root.expires)],
['CRL valid until', when(root.crl_next_update)],
['CRL', CRL_SOURCE_LABELS[root.crl_source ?? ''] ?? '-'],
...(root.upstream ? [
['Simple CA issuing CA', `${root.upstream.name}: ${root.upstream.subject}`],
['Its expiry', when(root.upstream.expires)],
['Its CRL valid until', when(root.upstream.crl_next_update)],
] as [string, string][] : []),
...(root.source === 'simple-ca' ? [['Token valid until', root.token_expires ? when(root.token_expires) : 'no token']] as [string, string][] : []),
]}
/>
{authority.state === 'pending' && (
<Stack direction="row" sx={{ mt: 1, alignItems: 'center', justifyContent: 'flex-end', gap: 1 }}>
<Typography variant="body2" color="text.secondary">
{pki?.settings.root === 'offline' ? 'Waits for its certificate signed by the root:' : 'Waits for its certificate signed by Simple CA.'}
</Typography>
{pki?.settings.root === 'offline' && pendingActions(name)}
</Stack>
{root.state === 'pending' && root.source === 'local' && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>The server creates it once a platform is chosen.</Typography>
)}
{authority.state === 'active' && (
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle(name)}>
Download CA bundle
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end', gap: 1 }}>
{root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle('root')}>
Download root CA
</Button>
</Stack>
)}
)}
{root.source === 'offline' && root.state === 'pending' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setImporting('root')}>
Import root certificate
</Button>
)}
{root.source === 'offline' && root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setUploading(true)}>
Upload CRL
</Button>
)}
{root.source === 'simple-ca' && (
<Button size="small" variant="outlined" startIcon={<Key />} disabled={busy} onClick={() => setEntering(true)}>
Enter setup code
</Button>
)}
</Stack>
</>
) : <Typography variant="body2" color="text.secondary">None yet; the server creates it once a platform is chosen.</Typography>}
</Section>
<Section title="Certificates issued">{certificateTable((pki?.certificates ?? []).filter((certificate) => certificate.ca === name))}</Section>
</Box>
)
}
)}
</>
),
},
{
id: 'general',
title: 'General',
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`],
]}
/>
),
},
{
id: 'certificates',
title: 'Issuing CA certificates',
wide: true,
content: (
<>
{certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root' || certificate.ca === 'upstream'))}
{pki.status.retired.length > 0 && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{`Retired: ${pki.status.retired.map((retired) => `${retired.name} (${when(retired.retired)})`).join(', ')}`}
</Typography>
)}
</>
),
},
] : []
const issuingPanels: BoardPanel[] = pki ? [
{
id: 'authorities',
title: 'Issuing CAs',
wide: true,
content: (
<>
<Stack direction="row" sx={{ mb: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Add />} disabled={busy} onClick={() => setAuthority({})}>
Add issuing CA
</Button>
</Stack>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Common name</TableCell>
<TableCell>State</TableCell>
<TableCell>Expires</TableCell>
<TableCell>CRL valid until</TableCell>
<TableCell>Templates</TableCell>
<TableCell>ACME</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{authorities.map((authority) => (
<TableRow key={authority.name} hover>
<TableCell sx={{ whiteSpace: 'nowrap' }}>
{authority.name}
{authority.builtin && <Chip size="small" label="built-in" variant="outlined" sx={{ ml: 1 }} />}
</TableCell>
<TableCell>{authority.subject ?? authority.common_name}</TableCell>
<TableCell>
<Tooltip title={authority.state === 'off' ? `Made once ${authority.component}.enabled is true` : ''}>
<Chip size="small" label={authority.state} color={STATE_COLORS[authority.state] ?? 'default'} />
</Tooltip>
</TableCell>
<TableCell>{when(authority.expires)}</TableCell>
<TableCell>{when(authority.crl_next_update)}</TableCell>
<TableCell>{authority.templates.join(', ')}</TableCell>
<TableCell sx={{ wordBreak: 'break-all' }}>{authority.acme_url ?? (authority.acme ? 'waits for the certificate' : '-')}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authority.state === 'pending' && pki.settings.root === 'offline' && pendingActions(authority.name)}
{authority.state === 'active' && (
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authority.name)}><Download fontSize="small" /></IconButton>
</span>
</Tooltip>
)}
{!authority.builtin && (
<>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setAuthority({ name: authority.name })}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeAuthority(authority.name)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</>
),
},
{
id: 'certificates',
title: 'Certificates issued',
wide: true,
content: (
<>
<TextField select size="small" label="Issuing CA" value={filter} sx={{ mb: 1, minWidth: 200 }} onChange={(event) => setFilter(event.target.value)}>
<MenuItem value="">All</MenuItem>
{authorityNames.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
{certificateTable(issuedCertificates)}
</>
),
},
] : []
return (
<Box component="section">
<Toolbar description="The root CA and the issuing CAs for P2S, site-to-site and general use.">
<Button variant="contained" startIcon={<Add />} disabled={busy || pki === null} onClick={() => setIssuing(true)}>
Issue
</Button>
<Button variant="outlined" startIcon={<Settings />} disabled={busy || pki === null} onClick={() => setEditing(true)}>
Settings
</Button>
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
<Toolbar description="The server's HTTPS certificate and ACME CA, the root CA and the issuing CAs for P2S, site-to-site, servers and custom uses.">
{view !== 'server' && (
<>
<Button variant="contained" startIcon={<Add />} disabled={busy || pki === null} onClick={() => setIssuing(true)}>
Issue
</Button>
<Button variant="outlined" startIcon={<Settings />} disabled={busy || pki === null} onClick={() => setEditing(true)}>
Settings
</Button>
</>
)}
{view === 'root' && <BoardButtons board={rootBoard} />}
{view === 'issuing' && <BoardButtons board={issuingBoard} />}
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => view === 'server' ? setServerRead(serverRead + 1) : void refresh()}>
Refresh
</Button>
</Toolbar>
@@ -405,86 +559,17 @@ export default function CertificatesPanel() {
{note && <Alert severity="info" sx={{ mb: 2 }} onClose={() => setNote(null)}>{note}</Alert>}
{pki?.status.warnings.map((warning) => <Alert key={warning} severity="warning" sx={{ mb: 2 }}>{warning}</Alert>)}
{pki && (
<Tabs value={view} onChange={(_event, next: View) => setView(next)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}>
<Tab value="root" label="Root" />
<Tab value="templates" label="Templates" />
<Tab value="usages" label="Extended key usages" />
<Tab value="p2s" label="P2S Issuing CA" />
<Tab value="s2s" label="S2S Issuing CA" />
<Tab value="issuing" label="Issuing CAs" />
</Tabs>
)}
<Tabs value={view} onChange={(_event, next: View) => setView(next)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}>
<Tab value="server" label="Server" />
{pki && <Tab value="root" label="Root" />}
{pki && <Tab value="templates" label="Templates" />}
{pki && <Tab value="usages" label="Extended key usages" />}
{pki && <Tab value="issuing" label="Issuing CAs" />}
</Tabs>
{pki && view === 'root' && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Root CA">
{root && (
<>
<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'} />],
['Subject', root.subject ?? '-'],
['Expires', when(root.expires)],
['CRL valid until', when(root.crl_next_update)],
['CRL', CRL_SOURCE_LABELS[root.crl_source ?? ''] ?? '-'],
...(root.upstream ? [
['Simple CA issuing CA', `${root.upstream.name}: ${root.upstream.subject}`],
['Its expiry', when(root.upstream.expires)],
['Its CRL valid until', when(root.upstream.crl_next_update)],
] as [string, string][] : []),
...(root.source === 'simple-ca' ? [['Token valid until', root.token_expires ? when(root.token_expires) : 'no token']] as [string, string][] : []),
]}
/>
{root.state === 'pending' && root.source === 'local' && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>The server creates it once a platform is chosen.</Typography>
)}
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end', gap: 1 }}>
{root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle('root')}>
Download root CA
</Button>
)}
{root.source === 'offline' && root.state === 'pending' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setImporting('root')}>
Import root certificate
</Button>
)}
{root.source === 'offline' && root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setUploading(true)}>
Upload CRL
</Button>
)}
{root.source === 'simple-ca' && (
<Button size="small" variant="outlined" startIcon={<Key />} disabled={busy} onClick={() => setEntering(true)}>
Enter setup code
</Button>
)}
</Stack>
</>
)}
</Section>
<Section title="General">
<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`],
]}
/>
</Section>
<Section title="Issuing CA certificates" wide>
{certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root' || certificate.ca === 'upstream'))}
{pki.status.retired.length > 0 && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{`Retired: ${pki.status.retired.map((retired) => `${retired.name} (${when(retired.retired)})`).join(', ')}`}
</Typography>
)}
</Section>
</Box>
)}
{view === 'server' && <ServerCertificatePanel key={serverRead} />}
{pki && view === 'root' && <Board board={rootBoard} panels={rootPanels} />}
{pki && view === 'templates' && (
<Box sx={{ display: 'grid', gap: 2 }}>
@@ -610,81 +695,7 @@ export default function CertificatesPanel() {
</Box>
)}
{pki && view === 'p2s' && builtinTab('p2s', 'P2S Issuing CA: the VPN server certificate and the users\' certificates')}
{pki && view === 's2s' && builtinTab('s2s', 'S2S Issuing CA: the site-to-site certificates of the server and its peers')}
{pki && view === 'issuing' && (
<Box sx={{ display: 'grid', gap: 2 }}>
<Section title="General-purpose issuing CAs">
<Stack direction="row" sx={{ mb: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Add />} disabled={busy} onClick={() => setAuthority({})}>
Add issuing CA
</Button>
</Stack>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Common name</TableCell>
<TableCell>State</TableCell>
<TableCell>Expires</TableCell>
<TableCell>CRL valid until</TableCell>
<TableCell>Templates</TableCell>
<TableCell>ACME</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{general.length === 0 && (
<TableRow>
<TableCell colSpan={8} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{general.map((authority) => (
<TableRow key={authority.name} hover>
<TableCell>{authority.name}</TableCell>
<TableCell>{authority.subject ?? authority.common_name}</TableCell>
<TableCell><Chip size="small" label={authority.state} color={STATE_COLORS[authority.state] ?? 'default'} /></TableCell>
<TableCell>{when(authority.expires)}</TableCell>
<TableCell>{when(authority.crl_next_update)}</TableCell>
<TableCell>{authority.templates.join(', ')}</TableCell>
<TableCell sx={{ wordBreak: 'break-all' }}>{authority.acme_url ?? (authority.acme ? 'waits for the certificate' : '-')}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authority.state === 'pending' && pki.settings.root === 'offline' && pendingActions(authority.name)}
{authority.state === 'active' && (
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authority.name)}><Download fontSize="small" /></IconButton>
</span>
</Tooltip>
)}
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setAuthority({ name: authority.name })}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeAuthority(authority.name)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Section>
<Section title="Certificates issued">
<TextField select size="small" label="Issuing CA" value={filter} sx={{ mb: 1, minWidth: 200 }} onChange={(event) => setFilter(event.target.value)}>
<MenuItem value="">All</MenuItem>
{generalNames.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
{certificateTable(generalCertificates)}
</Section>
</Box>
)}
{pki && view === 'issuing' && <Board board={issuingBoard} panels={issuingPanels} />}
{editing && pki && (
<PkiSettingsDialog
+225
View File
@@ -0,0 +1,225 @@
import { Alert, Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, Table, TableBody, TableCell, TableRow, TextField, Typography } from '@mui/material'
import { useCallback, useEffect, useState, type FormEvent } from 'react'
import ConfirmDialog from './ConfirmDialog.tsx'
import { COMPONENTS_SHAPE, request, type Component } from './api.ts'
/** Seconds between two reads while a component is being installed. */
const POLL_SECONDS = 3
/** The name and what each component is. */
const LABELS: Record<Component['name'], [string, string]> = {
vpn: ['VPN', 'IKEv2, OpenVPN and WireGuard access for users, on the Remote Access page.'],
router: ['Router', 'Routing between the external and the internal interface, and site-to-site IPsec.'],
dns: ['Name server', 'PowerDNS, the primary name server of the server\'s domains, on the DNS page.'],
webdav: ['WebDAV', 'The folders of the web sites over WebDAV, with rclone behind Caddy.'],
}
/** The chip of a component's installation state. */
const STATE_COLORS: Record<Component['state'], 'default' | 'info' | 'success' | 'error'> = {
'not installed': 'default', installing: 'info', installed: 'success', failed: 'error',
}
/** An IPv4 address with its prefix length, as local.int_addr takes it. */
const ADDRESS_PREFIX = /^(\d{1,3}\.){3}\d{1,3}\/\d{1,2}$/
/** An IPv4 address. */
const ADDRESS = /^(\d{1,3}\.){3}\d{1,3}$/
/**
* The installable components of the server from /components, the VPN, the router, the name server and WebDAV, each
* with its switch and whether its packages are installed. Enable switches a component on, and the server installs its
* packages, which the panel follows every POLL_SECONDS seconds; Disable, after a confirmation, switches it off and
* keeps its packages. The router is offered only while the server has an interface for its internal side, and its
* Enable asks for that interface and, in manual mode, its address and gateway. onChange tells of every change made.
*/
export default function ComponentsPanel(props: { onChange?: () => void }) {
const [components, setComponents] = useState<Component[] | null>(null)
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [disabling, setDisabling] = useState<Component | null>(null)
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}`)
}
}, [])
useEffect(() => {
void read()
}, [read])
// A component switched on is followed while its packages are being installed or are still missing.
const pending = components?.some((item) => item.state === 'installing' || (item.enabled && item.state === 'not installed'))
useEffect(() => {
if (!pending) {
return
}
const timer = window.setInterval(() => void read(), POLL_SECONDS * 1000)
return () => window.clearInterval(timer)
}, [pending, read])
/** Sends the switch of a component, with the router's interface settings, and reads the answer. */
async function change(item: Component, body: Record<string, unknown>) {
setBusy(true)
setError(null)
try {
setComponents((await request<{ components: Component[] }>('PUT', `/components/${item.name}`, COMPONENTS_SHAPE, body)).components)
props.onChange?.()
} finally {
setBusy(false)
}
}
async function enable(item: Component) {
if (item.name === 'router') {
setRouter(item)
return
}
try {
await change(item, { enabled: true })
} catch (caught) {
setError((caught as Error).message)
}
}
return (
<Box>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }} onClose={() => setError(null)}>{error}</Alert>}
{components === null ? (
<Typography variant="body2" color="text.secondary">The components are not read yet.</Typography>
) : (
<Table size="small">
<TableBody>
{components.map((item) => {
const [label, description] = LABELS[item.name]
const unavailable = item.name === 'router' && item.available === false
return (
<TableRow key={item.name}>
<TableCell sx={{ width: 160, fontWeight: 500 }}>{label}</TableCell>
<TableCell>
<Typography variant="body2">{description}</Typography>
{unavailable && (
<Typography variant="body2" color="text.secondary">It needs a second network interface; the server has only one.</Typography>
)}
{item.enabled && item.state === 'failed' && (
<Typography variant="body2" color="error">The installation failed; Enable tries again, and the Logs tab has its output.</Typography>
)}
</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }}>
<Stack direction="row" sx={{ gap: 1, alignItems: 'center' }}>
<Chip size="small" label={item.enabled ? 'on' : 'off'} color={item.enabled ? 'success' : 'default'} variant="outlined" />
<Chip size="small" label={item.state} color={STATE_COLORS[item.state]} />
</Stack>
</TableCell>
<TableCell sx={{ width: 120, textAlign: 'right' }}>
{item.enabled && item.state !== 'failed' ? (
<Button size="small" variant="outlined" disabled={busy} onClick={() => setDisabling(item)}>Disable</Button>
) : (
<Button size="small" variant="contained" disabled={busy || unavailable} onClick={() => void enable(item)}>Enable</Button>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
)}
{disabling && (
<ConfirmDialog
title={`Disable the ${LABELS[disabling.name][0]}`}
message="The component stops and its settings are kept; its packages stay installed."
confirmLabel="Disable"
destructive
onCancel={() => setDisabling(null)}
onConfirm={() => {
const item = disabling
setDisabling(null)
change(item, { enabled: false }).catch((caught: Error) => setError(caught.message))
}}
/>
)}
{router && (
<RouterDialog
component={router}
onCancel={() => setRouter(null)}
onSave={async (values) => {
await change(router, { enabled: true, ...values })
setRouter(null)
}}
/>
)}
</Box>
)
}
/**
* A dialog that switches the router on: the internal interface, chosen from the server's interfaces but the external
* one, and in manual mode its address with the prefix length and the gateway of the internal network; in auto mode the
* server detects them. onSave sends them; the dialog shows the server's message when it fails.
*/
function RouterDialog(props: {
component: Component
onSave: (values: { internal_interface: string; int_addr: string; int_gateway_ip: string }) => Promise<void>
onCancel: () => void
}) {
const choices = props.component.interfaces ?? []
const mode = props.component.mode ?? 'manual'
const [internal, setInternal] = useState(props.component.internal_interface && choices.includes(props.component.internal_interface)
? props.component.internal_interface : choices[0] ?? '')
const [address, setAddress] = useState(props.component.int_addr ?? '')
const [gateway, setGateway] = useState(props.component.int_gateway_ip ?? '')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const manual = mode === 'manual'
const addressProblem = manual && !ADDRESS_PREFIX.test(address) ? 'An IPv4 address with its prefix length, such as 10.1.1.4/24.' : ''
const gatewayProblem = manual && !ADDRESS.test(gateway) ? 'An IPv4 address.' : ''
const blocked = (mode !== 'auto' && internal === '') || addressProblem !== '' || gatewayProblem !== ''
async function submit(event: FormEvent) {
event.preventDefault()
if (blocked) {
return
}
setSaving(true)
setError(null)
try {
await props.onSave({ internal_interface: mode === 'auto' ? '' : internal, int_addr: manual ? address : '', int_gateway_ip: manual ? gateway : '' })
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="xs" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>Enable the router</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
{mode === 'auto' ? (
<Typography variant="body2" color="text.secondary">In auto mode the server detects the internal interface, its address and its gateway.</Typography>
) : (
<TextField select label="Internal interface" value={internal} onChange={(event) => setInternal(event.target.value)}>
{choices.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
)}
{manual && (
<>
<TextField label="Address on the internal network" value={address} autoComplete="off" error={address !== '' && addressProblem !== ''} helperText={addressProblem || ' '} onChange={(event) => setAddress(event.target.value.trim())} />
<TextField label="Gateway of the internal network" value={gateway} autoComplete="off" error={gateway !== '' && gatewayProblem !== ''} helperText={gatewayProblem || ' '} onChange={(event) => setGateway(event.target.value.trim())} />
</>
)}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel} disabled={saving}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>Enable</Button>
</DialogActions>
</Dialog>
)
}
+78 -67
View File
@@ -9,13 +9,17 @@ import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import DnsDomainDialog from './DnsDomainDialog.tsx'
import DnsRecordDialog from './DnsRecordDialog.tsx'
import DnsSettingsDialog from './DnsSettingsDialog.tsx'
import { Pairs, Section } from './ServerPanel.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs } from './ServerPanel.tsx'
import Toolbar from './Toolbar.tsx'
import {
ApiError, DNS_DOMAIN_REMOVED_SHAPE, DNS_DOMAIN_SHAPE, DNS_RECORD_SHAPE, DNS_REMOVED_SHAPE, DNS_SETTINGS_SHAPE, DNS_SHAPE,
request, type Dns, type DnsDomain, type DnsRecord,
} from './api.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.dns-layout'
/** A table of records: name, type, content and TTL, with a remove action when onRemove is given. */
function Records(props: { records: DnsRecord[]; busy: boolean; onRemove?: (record: DnsRecord) => void }) {
return (
@@ -61,7 +65,8 @@ function Records(props: { records: DnsRecord[]; busy: boolean; onRemove?: (recor
* The server's name server, from its /dns: the settings of the dns section with whether PowerDNS is installed and runs,
* its primary name server, the server's FQDN, and the server's public IP, edited with Settings; the domains it is the
* primary of: add, edit and remove; and for the selected domain its manual records: add and remove, and the records it
* serves. The records of the web sites follow the DNS setting of each site on the Sites page.
* serves. The records of the web sites follow the DNS setting of each site on the Sites page. The panels are on a
* PanelBoard whose layout is kept in the browser.
*/
export default function DnsPanel() {
const [dns, setDns] = useState<Dns | null>(null)
@@ -73,6 +78,7 @@ export default function DnsPanel() {
const [editing, setEditing] = useState<DnsDomain | 'new' | null>(null)
const [addingRecord, setAddingRecord] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const board = useBoard(LAYOUT_KEY)
const refresh = useCallback(async () => {
setBusy(true)
@@ -131,6 +137,74 @@ export default function DnsPanel() {
() => request('DELETE', `${path}/records?${query.toString()}`, DNS_REMOVED_SHAPE))
}
const panels: BoardPanel[] = dns && section ? [
{
id: 'settings',
title: 'Settings',
wide: true,
content: (
<Pairs
rows={[
['State', <Chip key="state" size="small" label={!section.enabled ? 'disabled' : dns.running ? 'running' : 'not running'} color={!section.enabled ? 'default' : dns.running ? 'success' : 'warning'} />],
['PowerDNS', dns.installed ? 'installed' : 'not installed'],
['Primary name server', dns.nameserver || '-'],
['Secondary name server', section.secondary || (section.enabled ? 'not set' : '-')],
['Public IP address', dns.public_address || '-'],
['Listen', section.listen],
['TTL', `${section.ttl} seconds`],
]}
/>
),
},
{
id: 'domains',
title: 'Domains',
wide: true,
content: (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Domain</TableCell>
<TableCell align="right">Manual records</TableCell>
<TableCell align="right">TTL</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{dns.domains.length === 0 && (
<TableRow>
<TableCell colSpan={4} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{dns.domains.map((item) => (
<TableRow key={item.name} hover selected={item.name === selected} sx={{ cursor: 'pointer' }} onClick={() => setSelected(item.name)}>
<TableCell>{item.name}</TableCell>
<TableCell align="right">{item.manual.length}</TableCell>
<TableCell align="right">{item.ttl ?? section.ttl}</TableCell>
<TableCell align="right" onClick={(event) => event.stopPropagation()}>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(item)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeDomain(item)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
),
},
...(domain ? [
{ id: 'records', title: `Records served of ${domain.name}`, wide: true, content: <Records records={domain.records} busy={busy} /> },
{ id: 'manual', title: `Manual records of ${domain.name}`, wide: true, content: <Records records={domain.manual} busy={busy} onRemove={removeRecord} /> },
] : []),
] : []
return (
<Box component="section">
<Toolbar description="The primary name server of the server's domains.">
@@ -143,6 +217,7 @@ export default function DnsPanel() {
<Button variant="outlined" startIcon={<Add />} disabled={busy || !domain} onClick={() => setAddingRecord(true)}>
Add record
</Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh
</Button>
@@ -151,71 +226,7 @@ export default function DnsPanel() {
{error && <Alert severity={unavailable ? 'info' : 'error'} sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{dns?.problem && section?.enabled && <Alert severity="warning" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{dns.problem}</Alert>}
{dns && section && (
<Box sx={{ display: 'grid', gap: 2 }}>
<Section title="Settings">
<Pairs
rows={[
['State', <Chip key="state" size="small" label={!section.enabled ? 'disabled' : dns.running ? 'running' : 'not running'} color={!section.enabled ? 'default' : dns.running ? 'success' : 'warning'} />],
['PowerDNS', dns.installed ? 'installed' : 'not installed'],
['Primary name server', dns.nameserver || '-'],
['Secondary name server', section.secondary || (section.enabled ? 'not set' : '-')],
['Public IP address', dns.public_address || '-'],
['Listen', section.listen],
['TTL', `${section.ttl} seconds`],
]}
/>
</Section>
<Section title="Domains">
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Domain</TableCell>
<TableCell align="right">Manual records</TableCell>
<TableCell align="right">TTL</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{dns.domains.length === 0 && (
<TableRow>
<TableCell colSpan={4} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{dns.domains.map((item) => (
<TableRow key={item.name} hover selected={item.name === selected} sx={{ cursor: 'pointer' }} onClick={() => setSelected(item.name)}>
<TableCell>{item.name}</TableCell>
<TableCell align="right">{item.manual.length}</TableCell>
<TableCell align="right">{item.ttl ?? section.ttl}</TableCell>
<TableCell align="right" onClick={(event) => event.stopPropagation()}>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(item)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeDomain(item)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Section>
{domain && (
<>
<Section title={`Records served of ${domain.name}`}>
<Records records={domain.records} busy={busy} />
</Section>
<Section title={`Manual records of ${domain.name}`}>
<Records records={domain.manual} busy={busy} onRemove={removeRecord} />
</Section>
</>
)}
</Box>
)}
{dns && section && <Board board={board} panels={panels} />}
{settings && section && (
<DnsSettingsDialog
+13 -12
View File
@@ -1,22 +1,21 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Stack, Switch, TextField } from '@mui/material'
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
import { ADDRESS_PATTERN, LISTEN_CHOICES, ZONE_PATTERN, type DnsSettings, type Listen } from './api.ts'
/**
* A dialog that edits the server's dns section: whether the name server runs, the secondary name server of every
* domain, the interfaces it answers on and the TTL, and wan.public_address, the server's public IP the records of the
* sites with Public IP take. The primary name server is the server's FQDN, nameserver, shown and not edited. An enabled
* name server needs a secondary other than the server's FQDN. onSave sends the section and the public address; the
* dialog closes when it succeeds and shows the server's message when it fails.
* A dialog that edits the server's dns section but whether the name server runs, which the System tab switches: the
* secondary name server of every domain, the interfaces it answers on and the TTL, and wan.public_address, the server's
* public IP the records of the sites with Public IP take. The primary name server is the server's FQDN, nameserver,
* shown and not edited. The secondary is optional and is not the server's FQDN. onSave sends the
* settings and the public address; the dialog closes when it succeeds and shows the server's message when it fails.
*/
export default function DnsSettingsDialog(props: {
current: DnsSettings
nameserver: string
publicAddress: string
onSave: (settings: DnsSettings, publicAddress: string) => Promise<void>
onSave: (settings: Omit<DnsSettings, 'enabled'>, publicAddress: string) => Promise<void>
onCancel: () => void
}) {
const [enabled, setEnabled] = useState(props.current.enabled)
const [secondary, setSecondary] = useState(props.current.secondary)
const [publicAddress, setPublicAddress] = useState(props.publicAddress)
const [listen, setListen] = useState<Listen>(props.current.listen)
@@ -24,7 +23,7 @@ export default function DnsSettingsDialog(props: {
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const secondaryProblem = secondary === '' ? (enabled ? 'Required while enabled.' : '')
const secondaryProblem = secondary === '' ? ''
: !ZONE_PATTERN.test(secondary) ? 'A DNS name in lower case.'
: secondary === props.nameserver ? 'The secondary is not the server\'s FQDN, the primary.' : ''
const addressProblem = publicAddress === '' || ADDRESS_PATTERN.test(publicAddress) ? '' : 'Not an IP address.'
@@ -39,7 +38,7 @@ export default function DnsSettingsDialog(props: {
setSaving(true)
setError(null)
try {
await props.onSave({ enabled, secondary, listen, ttl: Number(ttl) }, publicAddress)
await props.onSave({ secondary, listen, ttl: Number(ttl) }, publicAddress)
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
@@ -52,7 +51,9 @@ export default function DnsSettingsDialog(props: {
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<FormControlLabel control={<Switch checked={enabled} onChange={(event) => setEnabled(event.target.checked)} />} label="Enabled" />
<Typography variant="body2" color="text.secondary">
The name server is {props.current.enabled ? 'on' : 'off'}; it is switched on and off on the System tab.
</Typography>
<TextField
label="Primary name server"
value={props.nameserver || '(the server has no FQDN)'}
@@ -65,7 +66,7 @@ export default function DnsSettingsDialog(props: {
autoFocus
autoComplete="off"
error={secondaryProblem !== ''}
helperText={secondaryProblem || 'The second NS of every domain; the addresses it resolves to may transfer the domains.'}
helperText={secondaryProblem || 'Optional: the second NS of every domain; the addresses it resolves to may transfer the domains. Empty: the server is the only name server.'}
onChange={(event) => setSecondary(event.target.value.trim().toLowerCase())}
/>
<TextField
+37 -25
View File
@@ -1,10 +1,14 @@
import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Typography } from '@mui/material'
import { Pairs, Section, text } from './ServerPanel.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, text } from './ServerPanel.tsx'
import Toolbar from './Toolbar.tsx'
import { DETAILS_SHAPE, STATUS_SHAPE, request, type RouterDetails, type RouterStatus } from './api.ts'
import { useRead } from './useRead.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.docker-layout'
/** Reads the server's /status/full and /config. */
const readDocker = async () => {
const [status, details] = await Promise.all([
@@ -17,42 +21,50 @@ const readDocker = async () => {
/**
* The state of Docker on the server: whether it is installed, the state of docker.service and of the server's Docker
* rules, from /status/full, and the ports exposed on the external interface and the rules of the LINUX-MANAGER-DOCKER
* chain, from /config.
* chain, from /config. The panels are on a PanelBoard whose layout is kept in the browser.
*/
export default function DockerPanel() {
const { data, error, busy, refresh } = useRead(readDocker)
const status = data?.status
const details = data?.details
const docker = status?.docker
const board = useBoard(LAYOUT_KEY)
const panels: BoardPanel[] = status && details ? [
{
id: 'status',
title: 'Status',
fixed: true,
content: (
<Pairs
rows={[
['Docker', docker === undefined ? 'unknown' : docker.installed ? 'installed' : 'not installed'],
['docker.service', text(docker?.service)],
['Docker rules', text(docker?.rules)],
['Exposed ports', text(details.docker.exposed_ports)],
]}
/>
),
},
{
id: 'rules',
title: 'Rules of LINUX-MANAGER-DOCKER',
content: details.docker.rules === null
? <Typography variant="body2" color="text.secondary">Not available.</Typography>
: (
<Box component="pre" sx={{ m: 0, overflow: 'auto', fontFamily: 'monospace', fontSize: 12 }}>
{details.docker.rules.length === 0 ? '(none)' : details.docker.rules.join('\n')}
</Box>
),
},
] : []
return (
<Box component="section">
<Toolbar description="Docker and its firewall rules.">
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>Refresh</Button>
</Toolbar>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{status && details && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Status">
<Pairs
rows={[
['Docker', docker === undefined ? 'unknown' : docker.installed ? 'installed' : 'not installed'],
['docker.service', text(docker?.service)],
['Docker rules', text(docker?.rules)],
['Exposed ports', text(details.docker.exposed_ports)],
]}
/>
</Section>
<Section title="Rules of LINUX-MANAGER-DOCKER">
{details.docker.rules === null
? <Typography variant="body2" color="text.secondary">Not available.</Typography>
: (
<Box component="pre" sx={{ m: 0, overflow: 'auto', fontFamily: 'monospace', fontSize: 12 }}>
{details.docker.rules.length === 0 ? '(none)' : details.docker.rules.join('\n')}
</Box>
)}
</Section>
</Box>
)}
<Board board={board} panels={panels} />
</Box>
)
}
+50 -18
View File
@@ -1,27 +1,44 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, Typography } from '@mui/material'
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, MenuItem, Stack, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
import type { HttpsSettings } from './api.ts'
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',
}
/**
* A dialog that switches the CA of the certificates Caddy obtains on the server: Let's Encrypt's staging environment,
* https.acme_staging, or Caddy's default CAs. onSave sends acme_staging; the dialog closes when it succeeds and shows
* the server's message when it fails.
* A dialog that edits where the certificate of the server's FQDN comes from, https.certificate: the ACME CA of
* AcmeSettingsDialog, a self-signed certificate valid for https.self_signed_days, the Servers Issuing CA, or another
* CA's certificate, imported on the Server tab of the Certificates page; self-signed is selected while the first setup
* has not chosen one. onSave sends the source and the validity
* only; the dialog closes when it succeeds and shows the server's message when it fails.
*/
export default function HttpsSettingsDialog(props: {
current: HttpsSettings
onSave: (settings: { acme_staging: boolean }) => Promise<void>
onSave: (settings: HttpsChange) => Promise<void>
onCancel: () => void
}) {
const [staging, setStaging] = useState(props.current.acme_staging)
const [certificate, setCertificate] = useState<HttpsCertificateSource>(props.current.certificate || 'self-signed')
const [days, setDays] = useState(String(props.current.self_signed_days))
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const daysProblem = /^\d{1,4}$/.test(days) && Number(days) >= 1 && Number(days) <= 3650 ? '' : '1 to 3650 days.'
const blocked = certificate === 'self-signed' && daysProblem !== ''
async function submit(event: FormEvent) {
event.preventDefault()
if (blocked) {
return
}
setSaving(true)
setError(null)
try {
await props.onSave({ acme_staging: staging })
await props.onSave(certificate === 'self-signed' ? { certificate, self_signed_days: Number(days) } : { certificate })
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
@@ -30,24 +47,39 @@ export default function HttpsSettingsDialog(props: {
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>HTTPS settings</DialogTitle>
<DialogTitle>HTTPS certificate</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<FormControlLabel control={<Switch checked={staging} onChange={(event) => setStaging(event.target.checked)} />} label="Let's Encrypt staging CA" />
<Typography variant="body2" color="text.secondary">
{staging
? 'Caddy takes every certificate from Let\'s Encrypt\'s staging environment, the web sites\' included. Its rate limits are far higher, but no browser trusts its certificates: for routers rebuilt often, for tests only.'
: 'Caddy takes its certificates from Let\'s Encrypt, and from ZeroSSL when Let\'s Encrypt refuses, such as for its limit of 5 certificates a week for the same name.'}
</Typography>
{staging !== props.current.acme_staging && (
<Alert severity="info">The server runs its setup again, which applies the change.</Alert>
<TextField select label="Certificate of the server" value={certificate} onChange={(event) => setCertificate(event.target.value as HttpsCertificateSource)}>
{HTTPS_CERTIFICATES.map((item) => <MenuItem key={item} value={item}>{CERTIFICATE_LABELS[item]}</MenuItem>)}
</TextField>
{certificate === 'acme' && (
<Typography variant="body2" color="text.secondary">
Caddy takes the certificate from the ACME CA, which its own settings choose.
</Typography>
)}
{certificate === 'self-signed' && (
<TextField
label="Validity (days)"
value={days}
error={daysProblem !== ''}
helperText={daysProblem || 'The server makes a new one when a third of it is left.'}
slotProps={{ htmlInput: { inputMode: 'numeric' } }}
onChange={(event) => setDays(event.target.value.trim())}
/>
)}
{certificate === 'external' && (
<Typography variant="body2" color="text.secondary">
The certificate is imported on this tab, from a CSR the server makes or as a PFX file. The server serves a self-signed certificate until then.
</Typography>
)}
<Alert severity="info">The server runs its setup again, which applies the change.</Alert>
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel} disabled={saving}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || staging === props.current.acme_staging}>Save</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>Save</Button>
</DialogActions>
</Dialog>
)
+8 -5
View File
@@ -2,13 +2,14 @@ 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, nameProblem } from './PkiSettingsDialog.tsx'
import { NAME_PATTERN, RESERVED, made, nameProblem } from './PkiSettingsDialog.tsx'
import { ROUTER_TEMPLATES, type Pki, type PkiIssuingCa } from './api.ts'
/**
* A dialog that adds a general-purpose issuing CA, or with name changes one: its name, fixed once it exists, its common
* name, the templates it issues and whether Caddy runs an ACME server for it. onSave gets the name and the options; the
* dialog closes when it succeeds and shows the server's message when it fails.
* name, fixed once the CA has its certificate or CSR, the templates it issues and whether Caddy runs an ACME server for
* it. onSave gets the name and the options; the dialog closes when it succeeds and shows the server's message when it
* fails.
*/
export default function IssuingCaDialog(props: {
pki: Pki
@@ -29,6 +30,7 @@ export default function IssuingCaDialog(props: {
const nameError = props.name !== undefined ? ''
: !NAME_PATTERN.test(name.trim()) || RESERVED.includes(name.trim()) ? 'Up to 31 lower case letters, digits and dashes, starting with a letter; not root, p2s or s2s.'
: taken ? 'An issuing CA has this name.' : ''
const commonNameFixed = existing !== undefined && made(existing)
const commonNameError = nameProblem(commonName)
const templatesError = templates.length === 0 ? 'At least one template.' : ''
const blocked = nameError !== '' || commonNameError !== '' || templatesError !== ''
@@ -57,7 +59,7 @@ export default function IssuingCaDialog(props: {
<Typography variant="body2" color="text.secondary">
{props.name === undefined
? 'The root signs the new CA at once while its key is on the server; otherwise the CA waits with a CSR for the offline root.'
: 'The common name applies when the CA is created; the templates and the ACME server apply at once.'}
: 'The templates and the ACME server apply at once.'}
</Typography>
<TextField
label="Name"
@@ -71,9 +73,10 @@ export default function IssuingCaDialog(props: {
<TextField
label="Common name"
value={commonName}
disabled={commonNameFixed}
autoComplete="off"
error={commonNameError !== ''}
helperText={commonNameError}
helperText={commonNameError || (commonNameFixed ? 'Fixed once the CA exists.' : '')}
onChange={(event) => setCommonName(event.target.value)}
/>
<Autocomplete
+6 -1
View File
@@ -1,4 +1,5 @@
import ArrowDropDown from '@mui/icons-material/ArrowDropDown'
import Dns from '@mui/icons-material/Dns'
import Hub from '@mui/icons-material/Hub'
import MenuIcon from '@mui/icons-material/Menu'
import People from '@mui/icons-material/People'
@@ -28,9 +29,12 @@ export const SITE_TO_SITE_PATH = '/site-to-site-manager'
/** The path of the Docker page: the state of Docker and of its rules. */
export const DOCKER_PATH = '/docker-manager'
/** The path of the Web Sites page: the sites Caddy serves, their files and the name server. */
/** The path of the Web Sites page: the sites Caddy serves and their files. */
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. */
export const SHELL_PATH = '/shell'
@@ -42,6 +46,7 @@ const PAGES: { path: string; label: string; icon: ReactNode }[] = [
{ path: REMOTE_ACCESS_PATH, label: 'Remote Access', icon: <VpnKey fontSize="small" /> },
{ path: CA_PATH, label: 'Certificates', icon: <VerifiedUser fontSize="small" /> },
{ 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" /> },
]
+67
View File
@@ -0,0 +1,67 @@
import UploadFile from '@mui/icons-material/UploadFile'
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogContentText, DialogTitle, Stack, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
/**
* A dialog that takes a PKCS#12 (PFX) file of another CA's certificate for the server's FQDN, with its key and chain,
* and its password. onSave sends the file in base64 and the password; the dialog closes when it succeeds and shows
* the server's message when it fails.
*/
export default function PfxDialog(props: { onSave: (pfx: string, password: string) => Promise<void>; onCancel: () => void }) {
const [file, setFile] = useState<{ name: string; data: string } | null>(null)
const [password, setPassword] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
/** Reads the chosen file as base64. */
async function choose(chosen: File | undefined) {
if (!chosen) {
return
}
const bytes = new Uint8Array(await chosen.arrayBuffer())
let binary = ''
bytes.forEach((byte) => {
binary += String.fromCharCode(byte)
})
setFile({ name: chosen.name, data: btoa(binary) })
}
async function submit(event: FormEvent) {
event.preventDefault()
if (!file) {
return
}
setSaving(true)
setError(null)
try {
await props.onSave(file.data, password)
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>Import a PFX file</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<DialogContentText>A certificate of another CA for the server's FQDN, with its key and chain.</DialogContentText>
<Stack direction="row" sx={{ alignItems: 'center', gap: 1 }}>
<Button component="label" variant="outlined" startIcon={<UploadFile />}>
Choose a file
<input hidden type="file" accept=".pfx,.p12" onChange={(event) => void choose(event.target.files?.[0])} />
</Button>
<Typography variant="body2" color="text.secondary">{file?.name ?? 'No file chosen.'}</Typography>
</Stack>
<TextField label="Password" type="password" value={password} autoComplete="off" onChange={(event) => setPassword(event.target.value)} />
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || !file}>Import</Button>
</DialogActions>
</Dialog>
)
}
+21 -11
View File
@@ -3,7 +3,7 @@ import {
Typography,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import { PKI_KEYS, PKI_PUBLISH, type Pki, type PkiRootSource, type PkiSettings, type PkiTemplate } from './api.ts'
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> = {
@@ -24,7 +24,7 @@ export const ROOT_SOURCE_LABELS: Record<PkiRootSource, string> = {
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']
export const RESERVED = ['root', 'upstream', 'p2s', 's2s', 'servers']
/** The longest common name of a CA, in characters. */
const CA_NAME_MAX = 64
@@ -37,6 +37,11 @@ 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.` : ''
@@ -59,10 +64,12 @@ export function daysProblem(value: number) {
/**
* 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, 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 the root exists. The server applies
* the names, lifetimes and key type when it creates a CA. onSave sends the settings; the dialog closes when it
* 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
* 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
* succeeds and shows the server's message when it fails.
*/
export default function PkiSettingsDialog(props: {
@@ -75,8 +82,9 @@ export default function PkiSettingsDialog(props: {
const [error, setError] = useState<string | null>(null)
const change = (values: Partial<PkiSettings>) => setSettings({ ...settings, ...values })
const fixed = (name: string) => props.pki.status.authorities.some((authority) => authority.name === name && made(authority))
const blocked = [
nameProblem(settings.root_name), nameProblem(settings.p2s_name), nameProblem(settings.s2s_name),
nameProblem(settings.p2s_name), nameProblem(settings.s2s_name),
daysProblem(settings.root_days), daysProblem(settings.ca_days), daysProblem(settings.crl_days), daysProblem(settings.root_crl_days),
settings.root === 'simple-ca' ? urlProblem(settings.simple_ca_url) : '',
].some((problem) => problem !== '')
@@ -107,6 +115,7 @@ export default function PkiSettingsDialog(props: {
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<Typography variant="body2" color="text.secondary">
Names, lifetimes and the key type apply when the server creates a CA; URLs apply to the certificates signed afterwards.
The P2S and site-to-site CAs are created when the VPN and the router are switched on.
</Typography>
<Typography variant="subtitle2">CAs</Typography>
<TextField label="Root CA source" value={ROOT_SOURCE_LABELS[settings.root]} disabled helperText="Fixed once the root exists." />
@@ -120,16 +129,17 @@ export default function PkiSettingsDialog(props: {
onChange={(event) => change({ simple_ca_url: event.target.value.trim() })}
/>
)}
{(['root', 'p2s', 's2s'] as const).filter((name) => name !== 'root' || settings.root === 'local').map((name) => {
const option = `${name}_name` as 'root_name' | 'p2s_name' | 's2s_name'
{(['p2s', 's2s'] as const).map((name) => {
const option = `${name}_name` as 'p2s_name' | 's2s_name'
return (
<TextField
key={name}
label={{ root: 'Root CA name', p2s: 'P2S CA name', s2s: 'Site-to-site CA name' }[name]}
label={{ p2s: 'P2S CA name', s2s: 'Site-to-site CA name' }[name]}
value={settings[option]}
disabled={fixed(name)}
autoComplete="off"
error={nameProblem(settings[option]) !== ''}
helperText={nameProblem(settings[option])}
helperText={nameProblem(settings[option]) || (fixed(name) ? 'Fixed once the CA exists.' : '')}
onChange={(event) => change({ [option]: event.target.value })}
/>
)
+92 -64
View File
@@ -3,16 +3,24 @@ 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 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, Section, bytes, ipsecRows, text } from './ServerPanel.tsx'
import { Copyable, Grid, IPSEC_HEADS, Pairs, bytes, ipsecRows, text } from './ServerPanel.tsx'
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,
} from './api.ts'
/** The localStorage key of each system's layout. */
const LAYOUT_KEYS: Record<RemoteAccessSystem, string> = {
p2s: 'linux-manager-ui.remote-access-p2s-layout',
openvpn: 'linux-manager-ui.remote-access-openvpn-layout',
wireguard: 'linux-manager-ui.remote-access-wireguard-layout',
}
/** What each system describes, above its panels. */
const DESCRIPTIONS: Record<RemoteAccessSystem, string> = {
p2s: 'IKEv2 remote access.',
@@ -26,7 +34,8 @@ const DESCRIPTIONS: Record<RemoteAccessSystem, string> = {
* IKEv2, from /config too, the IPsec security associations, child SAs, connections and connection children of all but
* the site-to-site connections, that is of IKEv2 access; for WireGuard, from /users and /config too, the peers of the users, added and removed here (WireGuardPeers), and each
* connection with its user, found by the peer's key, its IPs, endpoint, handshake and traffic. The server applies a
* change in the background; Refresh reads the state again.
* change in the background; Refresh reads the state again. The panels are on a PanelBoard whose layout
* is kept in the browser.
*/
export default function RemoteAccessPanel(props: { system: RemoteAccessSystem }) {
const [access, setAccess] = useState<RemoteAccess | null>(null)
@@ -35,6 +44,7 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
const [busy, setBusy] = useState(false)
const [editing, setEditing] = useState(false)
const [showConfig, setShowConfig] = useState(false)
const board = useBoard(LAYOUT_KEYS[props.system])
// WireGuard's: the users with their peers, and the server's details with each peer's key, endpoint and traffic.
const [users, setUsers] = useState<Users | null>(null)
const [details, setDetails] = useState<RouterDetails | null>(null)
@@ -91,10 +101,89 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
// An IPsec table is shown with rows, or with the note that the server could not read them.
const shown = (rows: string[][] | undefined) => ikev2 && details !== null && (rows === undefined || rows.length > 0)
const panels: BoardPanel[] = access ? [
{ id: 'settings', title: 'Settings', content: <Pairs rows={rows} /> },
{
id: 'state',
title: 'State',
content: (
<Pairs
rows={[
['Running', <Chip key="running" size="small" label={running ? 'running' : 'not running'} color={running ? 'success' : 'default'} />],
...(system === 'wireguard'
? [['Peers', peers === undefined || peers === null ? '-' : String(peers.length)] as [string, string]]
: [['Connected clients', clients === undefined || clients === null ? '-' : String(clients)] as [string, string]]),
]}
/>
),
},
...(shown(ipsec.sas) ? [{ id: 'ipsec-sas', title: 'IPsec security associations', wide: true, content: <Grid head={IPSEC_HEADS.sas} rows={ipsec.sas} /> }] : []),
...(shown(ipsec.childSas) ? [{ id: 'ipsec-child-sas', title: 'IPsec child SAs', wide: true, content: <Grid head={IPSEC_HEADS.childSas} rows={ipsec.childSas} /> }] : []),
...(shown(ipsec.connections) ? [{ id: 'ipsec-connections', title: 'IPsec connections', wide: true, content: <Grid head={IPSEC_HEADS.connections} rows={ipsec.connections} /> }] : []),
...(shown(ipsec.children) ? [{ id: 'ipsec-children', title: 'IPsec connection children', wide: true, content: <Grid head={IPSEC_HEADS.children} rows={ipsec.children} /> }] : []),
...(system === 'wireguard' ? [{
id: 'server',
title: 'Server',
wide: true,
content: (
<>
<Pairs
rows={[
['Public key', access.wireguard_server.public_key === null ? 'not made yet; setup makes it once WireGuard is enabled'
: <Copyable key="key" value={access.wireguard_server.public_key} label="public key" />],
['Endpoint', access.wireguard_server.endpoint ?? 'unknown: wan.local_fqdn is not set'],
['Allowed IPs', text(access.wireguard_server.allowed_ips)],
]}
/>
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end' }}>
<Button
size="small"
variant="outlined"
startIcon={<Description />}
disabled={!access.wireguard_server.public_key || !access.wireguard_server.endpoint}
onClick={() => setShowConfig(true)}
>
Show config
</Button>
</Stack>
</>
),
}] : []),
...(system === 'wireguard' ? [{
id: 'peers',
title: 'Peers',
wide: true,
content: <WireGuardPeers server={access.wireguard_server} users={users} onChanged={() => void refresh()} />,
}] : []),
...(system === 'wireguard' && running ? [{
id: 'connections',
title: 'Connections',
wide: true,
content: (
<Grid
head={['User', 'IPs', 'Endpoint', 'Handshake', 'Received', 'Sent']}
rows={details?.wireguard?.peers.map((peer) => {
// A peer is a user's by its key; one added to wg0.conf by hand has no user.
const owner = users?.users.find((user) => user.wireguard_peers.some((own) => own.public_key === peer.public_key))
return [
owner?.name ?? `- (${peer.public_key.slice(0, 8)}...)`,
peer.allowed_ips.join(', '),
peer.endpoint ?? '-',
peer.handshake_seconds_ago === null ? 'none' : `${peer.handshake_seconds_ago} s ago`,
bytes(peer.received_bytes),
bytes(peer.sent_bytes),
]
}) ?? undefined}
/>
),
}] : []),
] : []
return (
<Box component="section">
<Toolbar description={DESCRIPTIONS[system]}>
<Button variant="outlined" startIcon={<Edit />} disabled={!access || busy} onClick={() => setEditing(true)}>Edit</Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>Refresh</Button>
</Toolbar>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
@@ -105,68 +194,7 @@ export default function RemoteAccessPanel(props: { system: RemoteAccessSystem })
: `${REMOTE_ACCESS_LABELS[system]} is enabled but does not run yet. It needs wan.local_fqdn${access.local_fqdn ? '' : ', which is not set,'} and the server's VPN server certificate of the P2S issuing CA; the server applies a change within a moment.`}
</Alert>
)}
{access && (
<Box sx={{ display: 'grid', gap: 2, gridTemplateColumns: { xs: '1fr', md: '1fr 1fr' } }}>
<Section title="Settings"><Pairs rows={rows} /></Section>
<Section title="State">
<Pairs
rows={[
['Running', <Chip key="running" size="small" label={running ? 'running' : 'not running'} color={running ? 'success' : 'default'} />],
...(system === 'wireguard'
? [['Peers', peers === undefined || peers === null ? '-' : String(peers.length)] as [string, string]]
: [['Connected clients', clients === undefined || clients === null ? '-' : String(clients)] as [string, string]]),
]}
/>
</Section>
{shown(ipsec.sas) && <Section title="IPsec security associations" wide><Grid head={IPSEC_HEADS.sas} rows={ipsec.sas} /></Section>}
{shown(ipsec.childSas) && <Section title="IPsec child SAs" wide><Grid head={IPSEC_HEADS.childSas} rows={ipsec.childSas} /></Section>}
{shown(ipsec.connections) && <Section title="IPsec connections" wide><Grid head={IPSEC_HEADS.connections} rows={ipsec.connections} /></Section>}
{shown(ipsec.children) && <Section title="IPsec connection children" wide><Grid head={IPSEC_HEADS.children} rows={ipsec.children} /></Section>}
{system === 'wireguard' && (
<Section title="Server" wide>
<Pairs
rows={[
['Public key', access.wireguard_server.public_key === null ? 'not made yet; setup makes it once WireGuard is enabled'
: <Copyable key="key" value={access.wireguard_server.public_key} label="public key" />],
['Endpoint', access.wireguard_server.endpoint ?? 'unknown: wan.local_fqdn is not set'],
['Allowed IPs', text(access.wireguard_server.allowed_ips)],
]}
/>
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end' }}>
<Button
size="small"
variant="outlined"
startIcon={<Description />}
disabled={!access.wireguard_server.public_key || !access.wireguard_server.endpoint}
onClick={() => setShowConfig(true)}
>
Show config
</Button>
</Stack>
</Section>
)}
{system === 'wireguard' && <WireGuardPeers server={access.wireguard_server} users={users} onChanged={() => void refresh()} />}
{system === 'wireguard' && running && (
<Section title="Connections" wide>
<Grid
head={['User', 'IPs', 'Endpoint', 'Handshake', 'Received', 'Sent']}
rows={details?.wireguard?.peers.map((peer) => {
// A peer is a user's by its key; one added to wg0.conf by hand has no user.
const owner = users?.users.find((user) => user.wireguard_peers.some((own) => own.public_key === peer.public_key))
return [
owner?.name ?? `- (${peer.public_key.slice(0, 8)}...)`,
peer.allowed_ips.join(', '),
peer.endpoint ?? '-',
peer.handshake_seconds_ago === null ? 'none' : `${peer.handshake_seconds_ago} s ago`,
bytes(peer.received_bytes),
bytes(peer.sent_bytes),
]
}) ?? undefined}
/>
</Section>
)}
</Box>
)}
{access && <Board board={board} panels={panels} />}
{showConfig && access && (
<WireGuardConfigDialog title="WireGuard configuration of a device" server={access.wireguard_server} ips={null} onClose={() => setShowConfig(false)} />
)}
+187
View File
@@ -0,0 +1,187 @@
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 ImportDialog from './ImportDialog.tsx'
import PfxDialog from './PfxDialog.tsx'
import { Pairs, Section, text } from './ServerPanel.tsx'
import { saveFile } from './saveFile.ts'
import {
DETAILS_SHAPE, HTTPS_CSR_SHAPE, HTTPS_IMPORTED_SHAPE, HTTPS_SETTINGS_SHAPE, request, type HttpsCertificate, type HttpsChange,
type HttpsSettings, type RouterDetails,
} from './api.ts'
/**
* The Server tab of the Certificates page, the server's HTTPS from /config and /https/settings: whether HTTPS is on and
* for which name, with a chip while the certificate has another source than ACME and a button that opens
* HttpsSettingsDialog; the certificate of a source other than ACME, and, for one of another CA, Generate CSR, Import
* certificate and Import PFX; the ACME CA with a chip while it is Let's Encrypt's staging environment and a button that
* opens AcmeSettingsDialog; and Caddy, its version and the state of caddy.service. Until the first setup
* chooses the source, the HTTPS row says so and the served self-signed certificate is shown. Read when it is shown; the
* page's Refresh shows it again.
*/
export default function ServerCertificatePanel() {
const [details, setDetails] = useState<RouterDetails | null>(null)
const [certificate, setCertificate] = useState<HttpsCertificate | null>(null)
const [reading, setReading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [note, setNote] = useState<string | null>(null)
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)
}
}, [])
useEffect(() => {
void refresh()
}, [refresh])
/** Reads the server's https section from /https/settings and opens HttpsSettingsDialog or AcmeSettingsDialog with it. */
async function open(dialog: 'https' | 'acme') {
setError(null)
try {
setSettings({ dialog, settings: (await request<{ settings: HttpsSettings }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE)).settings })
} catch (caught) {
setError(`The server did not give its HTTPS settings: ${(caught as Error).message}`)
}
}
/** Sends a change of HttpsSettingsDialog or AcmeSettingsDialog to /https/settings and closes the dialog. */
async function save(values: HttpsChange) {
await request('PUT', '/https/settings', HTTPS_SETTINGS_SHAPE, values)
setSettings(null)
setNote('The server runs its setup again, which applies the change.')
void refresh()
}
/** Saves a new CSR for the server's FQDN, to be signed by another CA. */
async function downloadCsr() {
setError(null)
try {
const { csr } = await request<{ csr: string }>('POST', '/https/csr', HTTPS_CSR_SHAPE)
saveFile(`${certificate?.subject ?? 'server'}.csr`, csr, 'application/pkcs10')
void refresh()
} catch (caught) {
setError(`The server made no CSR: ${(caught as Error).message}`)
}
}
const https = details?.configuration.https
const fqdn = String(details?.configuration.wan?.local_fqdn ?? '')
const httpsOn = https?.enabled === true
const chosen = certificate !== null && certificate.source !== ''
const other = httpsOn && certificate !== null && certificate.source !== 'acme'
return (
<Box>
{error && <Alert severity="warning" sx={{ mb: 2 }} onClose={() => setError(null)}>{error}</Alert>}
{note && <Alert severity="info" sx={{ mb: 2 }} onClose={() => setNote(null)}>{note}</Alert>}
{details === null ? (
<Typography variant="body2" color="text.secondary">{reading ? 'Reading the server\'s HTTPS settings.' : 'The server\'s HTTPS settings are not read.'}</Typography>
) : (
<Section title="HTTPS">
<Pairs
rows={[
['HTTPS', (
<Stack key="https" direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
<span>{httpsOn ? (fqdn ? `on, for ${fqdn}` : 'on, but wan.local_fqdn is not set') : 'off'}</span>
{other && certificate.source !== '' && <Chip size="small" label={CERTIFICATE_LABELS[certificate.source]} color={certificate.served === certificate.source ? 'default' : 'warning'} />}
{httpsOn && !chosen && <Typography variant="body2" color="text.secondary">certificate chosen by the next setup</Typography>}
<Tooltip title="HTTPS certificate">
<IconButton size="small" aria-label="HTTPS certificate" onClick={() => void open('https')}>
<Settings fontSize="small" />
</IconButton>
</Tooltip>
</Stack>
)],
...(other ? [['HTTPS certificate', (
<Stack key="certificate" sx={{ gap: 0.5 }}>
<span>
{certificate.subject
? `${certificate.served === certificate.source || !chosen ? '' : 'self-signed until the chosen one is available: '}${certificate.subject}, issued by ${certificate.issuer ?? '-'}, expires ${when(certificate.expires)}`
: 'none yet'}
</span>
{certificate.source === 'external' && (
<Stack direction="row" sx={{ gap: 1, flexWrap: 'wrap' }}>
<Button size="small" variant="outlined" onClick={() => void downloadCsr()}>
{certificate.pending ? 'New CSR' : 'Generate CSR'}
</Button>
<Button size="small" variant="outlined" disabled={!certificate.pending} onClick={() => setImporting('certificate')}>
Import certificate
</Button>
<Button size="small" variant="outlined" onClick={() => setImporting('pfx')}>
Import PFX
</Button>
</Stack>
)}
</Stack>
)] as [string, ReactNode]] : []),
['ACME CA', (
<Stack key="acme" direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
<span>{PROVIDER_LABELS[https?.acme_provider as keyof typeof PROVIDER_LABELS] ?? text(https?.acme_provider)}</span>
{https?.acme_provider === 'letsencrypt' && https?.acme_staging === true && <Chip size="small" label="Let's Encrypt staging" color="warning" />}
<Tooltip title="ACME CA settings">
<IconButton size="small" aria-label="ACME CA settings" onClick={() => void open('acme')}>
<Settings fontSize="small" />
</IconButton>
</Tooltip>
</Stack>
)],
['Caddy', (
<Stack key="caddy" direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
<span>{details.caddy ? details.caddy.version : 'not installed'}</span>
{details.caddy?.service && <Chip size="small" label={details.caddy.service} color={details.caddy.service === 'active' ? 'success' : 'warning'} />}
</Stack>
)],
]}
/>
</Section>
)}
{settings?.dialog === 'https' && <HttpsSettingsDialog current={settings.settings} onCancel={() => setSettings(null)} onSave={save} />}
{settings?.dialog === 'acme' && <AcmeSettingsDialog current={settings.settings} onCancel={() => setSettings(null)} onSave={save} />}
{importing === 'certificate' && (
<ImportDialog
title="Import the HTTPS certificate"
message="The certificate another CA signed for the server's CSR, followed by its chain."
label="Certificate"
begin="-----BEGIN CERTIFICATE-----"
onCancel={() => setImporting(null)}
onSave={async (value) => {
await request('PUT', '/https/certificate', HTTPS_IMPORTED_SHAPE, { certificate: value })
setImporting(null)
setNote('The server runs its setup again, which serves the certificate.')
void refresh()
}}
/>
)}
{importing === 'pfx' && (
<PfxDialog
onCancel={() => setImporting(null)}
onSave={async (pfx, password) => {
await request('PUT', '/https/pfx', HTTPS_IMPORTED_SHAPE, { pfx, password })
setImporting(null)
setNote('The server runs its setup again, which serves the certificate.')
void refresh()
}}
/>
)}
</Box>
)
}
+24 -91
View File
@@ -1,16 +1,15 @@
import ContentCopy from '@mui/icons-material/ContentCopy'
import PlayArrow from '@mui/icons-material/PlayArrow'
import Refresh from '@mui/icons-material/Refresh'
import Settings from '@mui/icons-material/Settings'
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 HttpsSettingsDialog from './HttpsSettingsDialog.tsx'
import UpdatesNotice from './UpdatesNotice.tsx'
import { BackupChip, backupRows } from './BackupSummary.tsx'
import {
ApiError, BACKUP_SHAPE, DETAILS_SHAPE, HTTPS_SETTINGS_SHAPE, POSTGRESQL_SHAPE, STARTED_SHAPE, STATUS_SHAPE, request, type Backup,
type HttpsSettings, type PostgresqlDatabases, type RouterDetails, type RouterStatus,
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 { useBrowserSettings } from './settings.ts'
@@ -20,10 +19,10 @@ const LAYOUT_KEY = 'linux-manager-ui.router-layout'
/**
* The server's state: its status, ok or degraded on the title bar of the Status panel, with the update information of
* its packages (UpdatesNotice) at the top of that panel, its remote access clients, and from /config the status web
* service, HTTPS, with a chip while Caddy takes Let's Encrypt's staging CA and a button that opens HttpsSettingsDialog
* with /https/settings, and Caddy (version, source and the state of caddy.service) in it; the state of each of its systemd
* services and of Caddy in the Services panel; the Addresses panel's links to the status page, over HTTPS for
* wan.local_fqdn and over plain HTTP on the addresses web.listen names, and to the Manager over HTTPS, and the
* service; the state of each of its systemd services and of Caddy in the Services panel; the Addresses panel's links
* to the status page, over HTTPS for wan.local_fqdn and over plain HTTP on the addresses web.listen names, and to the
* Manager over HTTPS, and over plain HTTP on the addresses of its listen from /api/info while Caddy does not redirect
* it, each address once, and the
* OpenID Provider's issuer and discovery URL, each with a copy icon, or off while it is disabled; its
* backups with Run now, and its non-public details as tables and command output, with a panel per PostgreSQL
* cluster: its settings from /config and its databases with their sizes from /postgresql. Read at once, then as the
@@ -38,28 +37,17 @@ export default function ServerPanel() {
const [details, setDetails] = useState<RouterDetails | null>(null)
const [databases, setDatabases] = useState<PostgresqlDatabases | null>(null)
const [backup, setBackup] = useState<Backup | null>(null)
const [manager, setManager] = useState<Info['manager'] | null>(null)
const [problems, setProblems] = useState<{ status?: string; details?: string; databases?: string; backup?: string }>({})
const [starting, setStarting] = useState(false)
const [reading, setReading] = useState(true)
const board = useBoard(LAYOUT_KEY)
const [busy, setBusy] = useState(false)
const [httpsSettings, setHttpsSettings] = useState<HttpsSettings | null>(null)
const [httpsError, setHttpsError] = useState<string | null>(null)
/** Reads the server's https section from /https/settings and opens HttpsSettingsDialog with it. */
async function openHttps() {
setHttpsError(null)
try {
setHttpsSettings((await request<{ settings: HttpsSettings }>('GET', '/https/settings', HTTPS_SETTINGS_SHAPE)).settings)
} catch (caught) {
setHttpsError(`The server did not give its HTTPS settings: ${(caught as Error).message}`)
}
}
const refresh = useCallback(async () => {
setReading(true)
const found: { status?: string; details?: string; databases?: string; backup?: string } = {}
const [nextStatus, nextDetails, nextDatabases, nextBackup] = await Promise.all([
const [nextStatus, nextDetails, nextDatabases, nextBackup, nextInfo] = 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
@@ -78,7 +66,9 @@ export default function ServerPanel() {
}
return null
}),
request<Info>('GET', '/info', INFO_SHAPE).catch(() => null),
])
setManager(nextInfo?.manager ?? null)
setStatus(nextStatus)
setDetails(nextDetails)
setDatabases(nextDatabases)
@@ -108,12 +98,16 @@ export default function ServerPanel() {
const https = details?.configuration.https
const fqdn = String(details?.configuration.wan?.local_fqdn ?? '')
const httpsOn = https?.enabled === true
// The addresses the status web service listens on with plain HTTP, as web.listen names them.
const listen = String(web?.listen ?? 'both')
const plain = web?.enabled === false ? [] : [
// The plain HTTP URLs of a port on the addresses of the interfaces a listen setting names, each address once: without
// the router the internal address is the external one.
const plainUrls = (listen: string, port: unknown) => [...new Set([
...(listen !== 'external' && network?.internal_address ? [network.internal_address] : []),
...(listen !== 'internal' ? network?.external_addresses ?? [] : []),
].map((address) => `http://${String(address).split('/')[0]}:${text(web?.port)}`)
].map((address) => String(address).split('/')[0]))].map((address) => `http://${address}:${text(port)}`)
const plain = web?.enabled === false ? [] : plainUrls(String(web?.listen ?? 'both'), web?.port)
// The Manager over plain HTTP while Caddy does not redirect it to HTTPS.
const managerPlain = manager && (!httpsOn || !fqdn || https?.disable_auto_redirect === true)
? plainUrls(manager.listen, manager.port) : []
// The panels in their default order; a panel without data is left out, and keeps its place in the layout.
const panels: BoardPanel[] = []
@@ -164,39 +158,10 @@ export default function ServerPanel() {
</TableRow>
)}
{details && (
<>
<TableRow>
<TableCell>Status web service</TableCell>
<TableCell>{web?.enabled === false ? 'off' : `on, port ${text(web?.port)}`}</TableCell>
</TableRow>
<TableRow>
<TableCell>HTTPS</TableCell>
<TableCell>
<Stack direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
<span>{httpsOn ? (fqdn ? `on, for ${fqdn}` : 'on, but wan.local_fqdn is not set') : 'off'}</span>
{httpsOn && https?.acme_staging === true && <Chip size="small" label="Let's Encrypt staging" color="warning" />}
<Tooltip title="HTTPS settings">
<span>
<IconButton size="small" aria-label="HTTPS settings" disabled={busy} onClick={() => void openHttps()}>
<Settings fontSize="small" />
</IconButton>
</span>
</Tooltip>
</Stack>
</TableCell>
</TableRow>
<TableRow>
<TableCell>Caddy</TableCell>
<TableCell>
<Stack direction="row" sx={{ alignItems: 'center', gap: 1, flexWrap: 'wrap' }}>
<span>{details.caddy ? `${details.caddy.version}, ${sourceText(details.caddy.source, String(https?.caddy_source ?? 'ubuntu'))}` : `not installed; source ${sourceText(undefined, String(https?.caddy_source ?? 'ubuntu'))}`}</span>
{details.caddy?.service && (
<Chip size="small" label={details.caddy.service} color={details.caddy.service === 'active' ? 'success' : 'warning'} />
)}
</Stack>
</TableCell>
</TableRow>
</>
<TableRow>
<TableCell>Status web service</TableCell>
<TableCell>{web?.enabled === false ? 'off' : `on, port ${text(web?.port)}`}</TableCell>
</TableRow>
)}
</TableBody>
</Table>
@@ -284,7 +249,7 @@ export default function ServerPanel() {
<Pairs
rows={[
['Status page', <Links key="status" urls={[...(httpsOn && fqdn ? [`https://${fqdn}:${text(https?.web_port)}`] : []), ...plain]} />],
['Ubuntu Linux Manager', <Links key="manager" urls={httpsOn && fqdn ? [`https://${fqdn}:${text(https?.manager_port)}`] : []} />],
['Ubuntu Linux Manager', <Links key="manager" urls={[...(httpsOn && fqdn ? [`https://${fqdn}:${text(https?.manager_port)}`] : []), ...managerPlain]} />],
...(details.oidc?.issuer
? [
['OpenID Provider', <Copyable key="issuer" value={details.oidc.issuer} label="issuer" />],
@@ -375,21 +340,9 @@ export default function ServerPanel() {
{problems.details && <Alert severity="warning" sx={{ mb: 2 }}>{problems.details}</Alert>}
{problems.databases && <Alert severity="warning" sx={{ mb: 2 }}>{problems.databases}</Alert>}
{problems.backup && <Alert severity="warning" sx={{ mb: 2 }}>{problems.backup}</Alert>}
{httpsError && <Alert severity="warning" sx={{ mb: 2 }} onClose={() => setHttpsError(null)}>{httpsError}</Alert>}
<Board board={board} panels={panels} />
{httpsSettings && (
<HttpsSettingsDialog
current={httpsSettings}
onCancel={() => setHttpsSettings(null)}
onSave={async (values) => {
await request('PUT', '/https/settings', HTTPS_SETTINGS_SHAPE, values)
setHttpsSettings(null)
void refresh()
}}
/>
)}
</Box>
)
}
@@ -539,26 +492,6 @@ const SECTION_LABELS: Record<string, string> = {
https: 'HTTPS',
}
/** The names shown for where the server's Caddy comes from. */
const CADDY_SOURCES: Record<string, string> = { ubuntu: 'Ubuntu', upstream: 'Upstream' }
/**
* Where Caddy comes from: the source in effect (effective, of the installed Caddy) and https.caddy_source when it
* differs, which happens when ubuntu is configured after upstream's repository was, or before setup installed Caddy.
*/
function sourceText(effective: string | undefined, configured: string): string {
const name = (source: string) => CADDY_SOURCES[source] ?? source
if (effective === undefined) {
return `${name(configured)} (configured)`
}
if (effective === configured) {
return name(effective)
}
return effective === 'upstream'
? `${name(effective)} (configured: ${name(configured)}, which upstream's repository overrides)`
: `${name(effective)} (configured: ${name(configured)}; setup switches to it)`
}
/** Addresses as links that open in a new tab, one under the other, or a dash without any. */
function Links(props: { urls: string[] }) {
if (props.urls.length === 0) {
+1 -1
View File
@@ -80,7 +80,7 @@ export default function SiteDialog(props: {
: badHost ? `${badHost} is not a host name or an IP address.`
: tls !== 'none' && hostList.length === 0 ? 'Required with TLS.'
: tls === 'acme' && hostList.some((host) => host.startsWith('*.') || ADDRESS_PATTERN.test(host))
? "Let's Encrypt takes host names without wildcards." : ''
? 'ACME takes host names without wildcards.' : ''
const portProblem = /^\d{1,5}$/.test(port) && Number(port) >= 1 && Number(port) <= 65535 ? '' : 'A port from 1 to 65535.'
const caProblem = tls === 'ca' && ca === '' ? 'Required.' : ''
const certificateProblem = tls === 'file' && !certificate.includes('-----BEGIN CERTIFICATE-----') ? 'A PEM certificate chain.' : ''
+35 -24
View File
@@ -1,10 +1,14 @@
import Refresh from '@mui/icons-material/Refresh'
import { Alert, Box, Button, Stack } from '@mui/material'
import { Grid, IPSEC_HEADS, Section, duration, ipsecRows, text } from './ServerPanel.tsx'
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 Toolbar from './Toolbar.tsx'
import { DETAILS_SHAPE, request, type RouterDetails } from './api.ts'
import { useRead } from './useRead.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.site-to-site-status-layout'
/** Reads the server's /config. */
const readDetails = () => request<RouterDetails>('GET', '/config', DETAILS_SHAPE)
@@ -23,41 +27,48 @@ function uptimeOf(sas: RouterDetails['ipsec']['sas'], name: string) {
/**
* The state of the server's site-to-site connections, from its /config: each with the identities and subnets the
* router resolved for it and how long it has been up, and their IPsec security associations, child SAs, connections
* and connection children.
* and connection children. The panels are on a PanelBoard whose layout is kept in the browser.
*/
export default function SiteToSiteStatusPanel() {
const { data: details, error, busy, refresh } = useRead(readDetails)
const board = useBoard(LAYOUT_KEY)
const names = new Set((details?.network.site_to_site ?? []).map((connection) => connection.name))
const { sas, childSas, connections, children } = ipsecRows(details, (name) => names.has(name))
const panels: BoardPanel[] = details ? [
{
id: 'connections',
title: 'Site-to-site connections',
wide: true,
content: (
<Grid
head={['Connection', 'Local identity', 'Remote identity', 'Local CIDRs', 'Remote CIDRs', 'Uptime']}
rows={(details.network.site_to_site ?? []).map((connection) => [
connection.name,
text(connection.local_identity),
text(connection.remote_identity),
text(connection.local_cidrs),
text(connection.remote_cidrs),
uptimeOf(details.ipsec.sas, connection.name),
])}
/>
),
},
{ id: 'ipsec-sas', title: 'IPsec security associations', wide: true, content: <Grid head={IPSEC_HEADS.sas} rows={sas} /> },
{ id: 'ipsec-child-sas', title: 'IPsec child SAs', wide: true, content: <Grid head={IPSEC_HEADS.childSas} rows={childSas} /> },
{ id: 'ipsec-connections', title: 'IPsec connections', wide: true, content: <Grid head={IPSEC_HEADS.connections} rows={connections} /> },
{ id: 'ipsec-children', title: 'IPsec connection children', wide: true, content: <Grid head={IPSEC_HEADS.children} rows={children} /> },
] : []
return (
<Box component="section">
<Toolbar description="The state of the site-to-site connections.">
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>Refresh</Button>
</Toolbar>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{details && (
<Stack sx={{ gap: 2 }}>
<Section title="Site-to-site connections">
<Grid
head={['Connection', 'Local identity', 'Remote identity', 'Local CIDRs', 'Remote CIDRs', 'Uptime']}
rows={(details.network.site_to_site ?? []).map((connection) => [
connection.name,
text(connection.local_identity),
text(connection.remote_identity),
text(connection.local_cidrs),
text(connection.remote_cidrs),
uptimeOf(details.ipsec.sas, connection.name),
])}
/>
</Section>
<Section title="IPsec security associations"><Grid head={IPSEC_HEADS.sas} rows={sas} /></Section>
<Section title="IPsec child SAs"><Grid head={IPSEC_HEADS.childSas} rows={childSas} /></Section>
<Section title="IPsec connections"><Grid head={IPSEC_HEADS.connections} rows={connections} /></Section>
<Section title="IPsec connection children"><Grid head={IPSEC_HEADS.children} rows={children} /></Section>
</Stack>
)}
<Board board={board} panels={panels} />
</Box>
)
}
+104 -90
View File
@@ -9,7 +9,8 @@ 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 { Copyable, Pairs, Section } from './ServerPanel.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Copyable, Pairs } from './ServerPanel.tsx'
import SearchField, { matches } from './SearchField.tsx'
import SiteDialog, { type SiteSettings } from './SiteDialog.tsx'
import SitesSettingsDialog from './SitesSettingsDialog.tsx'
@@ -19,6 +20,9 @@ import {
SITE_DNS_LABELS, SITE_SHAPE, SITE_TLS_LABELS, request, type Group, type RouterDetails, type Site, type Sites,
} from './api.ts'
/** The localStorage key of the tab's layout. */
const LAYOUT_KEY = 'linux-manager-ui.sites-layout'
/** The URLs of a site: its scheme, each host name and its port when it is not the scheme's default. */
function siteUrls(site: Site) {
const scheme = site.tls === 'none' ? 'http' : 'https'
@@ -30,7 +34,8 @@ function siteUrls(site: Site) {
* The web sites of the server's /sites, which Caddy serves from folders on the server. The Settings panel shows the
* sites section, whether they are served, the largest upload and WebDAV with its URL, edited with Settings. The list
* shows each site with its URLs, port, interfaces, TLS, editors group, DNS and state: add, edit, enable, disable,
* remove, with its folder when asked, and open its files on the Files tab with onOpenFiles.
* remove, with its folder when asked, and open its files on the Files tab with onOpenFiles. The panels are on a
* PanelBoard whose layout is kept in the browser.
*/
export default function SitesPanel(props: { onOpenFiles: (name: string) => void }) {
const [sites, setSites] = useState<Sites | null>(null)
@@ -45,6 +50,7 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
const [settings, setSettings] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [search, setSearch] = useState('')
const board = useBoard(LAYOUT_KEY)
const refresh = useCallback(async () => {
setBusy(true)
@@ -115,6 +121,100 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
const section = sites?.settings
const shown = (sites?.sites ?? []).filter((site) => matches(search, [site.name, ...site.hosts, site.editors]))
const panels: BoardPanel[] = [
...(section ? [{
id: 'settings',
title: 'Settings',
wide: true,
content: (
<Pairs
rows={[
['State', <Chip key="state" size="small" label={section.enabled ? 'served' : 'not served'} color={section.enabled ? 'success' : 'default'} />],
['Largest upload', `${section.upload_max_mb} MiB`],
['WebDAV', <Chip key="webdav" size="small" label={section.webdav ? 'enabled' : 'disabled'} color={section.webdav ? 'success' : 'default'} />],
...(section.webdav && fqdn
? [['WebDAV URL', <Copyable key="url" value={`https://${fqdn}:${section.webdav_port}/`} label="WebDAV URL" />]] as [string, ReactNode][]
: []),
]}
/>
),
}] : []),
...(sites ? [{
id: 'sites',
title: 'Sites',
wide: true,
content: (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>URLs</TableCell>
<TableCell>Port</TableCell>
<TableCell>Listen</TableCell>
<TableCell>TLS</TableCell>
<TableCell>Editors</TableCell>
<TableCell>DNS</TableCell>
<TableCell>State</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{shown.length === 0 && (
<TableRow>
<TableCell colSpan={9} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{shown.map((site) => (
<TableRow key={site.name} hover>
<TableCell>{site.name}</TableCell>
<TableCell>
<Stack>
{siteUrls(site).map((url) => <Link key={url} href={url} target="_blank" rel="noreferrer">{url}</Link>)}
{site.hosts.length === 0 && 'any host name'}
</Stack>
</TableCell>
<TableCell>{site.port}</TableCell>
<TableCell>{site.listen}</TableCell>
<TableCell>{SITE_TLS_LABELS[site.tls]}{site.tls === 'ca' ? ` (${site.ca})` : ''}</TableCell>
<TableCell>{site.editors || '-'}</TableCell>
<TableCell>{SITE_DNS_LABELS[site.dns]}{site.dns === 'router' ? `, ${SITE_DNS_ADDRESS_LABELS[site.dns_address]}` : ''}</TableCell>
<TableCell sx={{ color: site.enabled ? 'success.main' : 'text.secondary' }}>{site.enabled ? 'enabled' : 'disabled'}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
<Tooltip title="Files">
<span>
<IconButton size="small" onClick={() => props.onOpenFiles(site.name)}><FolderOpen fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(site)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title={site.enabled ? 'Disable' : 'Enable'}>
<span>
<IconButton
size="small"
disabled={busy}
onClick={() => void change(() => request('PUT', `/sites/${site.name}`, SITE_SHAPE, { enabled: !site.enabled }))}
>
{site.enabled ? <Block fontSize="small" /> : <CheckCircle fontSize="small" />}
</IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => remove(site)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
),
}] : []),
]
return (
<Box component="section">
<Toolbar description="Static web sites Caddy serves from folders on the server.">
@@ -125,6 +225,7 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
<Button variant="contained" startIcon={<Add />} disabled={busy || sites === null} onClick={() => setAdding(true)}>
Add
</Button>
<BoardButtons board={board} />
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh
</Button>
@@ -132,94 +233,7 @@ export default function SitesPanel(props: { onOpenFiles: (name: string) => void
{error && <Alert severity={unavailable ? 'info' : 'error'} sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{section && (
<Box sx={{ mb: 2 }}>
<Section title="Settings">
<Pairs
rows={[
['State', <Chip key="state" size="small" label={section.enabled ? 'served' : 'not served'} color={section.enabled ? 'success' : 'default'} />],
['Largest upload', `${section.upload_max_mb} MiB`],
['WebDAV', <Chip key="webdav" size="small" label={section.webdav ? 'enabled' : 'disabled'} color={section.webdav ? 'success' : 'default'} />],
...(section.webdav && fqdn
? [['WebDAV URL', <Copyable key="url" value={`https://${fqdn}:${section.webdav_port}/`} label="WebDAV URL" />]] as [string, ReactNode][]
: []),
]}
/>
</Section>
</Box>
)}
{sites && (
<Section title="Sites">
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>URLs</TableCell>
<TableCell>Port</TableCell>
<TableCell>Listen</TableCell>
<TableCell>TLS</TableCell>
<TableCell>Editors</TableCell>
<TableCell>DNS</TableCell>
<TableCell>State</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{shown.length === 0 && (
<TableRow>
<TableCell colSpan={9} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{shown.map((site) => (
<TableRow key={site.name} hover>
<TableCell>{site.name}</TableCell>
<TableCell>
<Stack>
{siteUrls(site).map((url) => <Link key={url} href={url} target="_blank" rel="noreferrer">{url}</Link>)}
{site.hosts.length === 0 && 'any host name'}
</Stack>
</TableCell>
<TableCell>{site.port}</TableCell>
<TableCell>{site.listen}</TableCell>
<TableCell>{SITE_TLS_LABELS[site.tls]}{site.tls === 'ca' ? ` (${site.ca})` : ''}</TableCell>
<TableCell>{site.editors || '-'}</TableCell>
<TableCell>{SITE_DNS_LABELS[site.dns]}{site.dns === 'router' ? `, ${SITE_DNS_ADDRESS_LABELS[site.dns_address]}` : ''}</TableCell>
<TableCell sx={{ color: site.enabled ? 'success.main' : 'text.secondary' }}>{site.enabled ? 'enabled' : 'disabled'}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
<Tooltip title="Files">
<span>
<IconButton size="small" onClick={() => props.onOpenFiles(site.name)}><FolderOpen fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setEditing(site)}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title={site.enabled ? 'Disable' : 'Enable'}>
<span>
<IconButton
size="small"
disabled={busy}
onClick={() => void change(() => request('PUT', `/sites/${site.name}`, SITE_SHAPE, { enabled: !site.enabled }))}
>
{site.enabled ? <Block fontSize="small" /> : <CheckCircle fontSize="small" />}
</IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => remove(site)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Section>
)}
<Board board={board} panels={panels} />
{adding && (
<SiteDialog
+9 -8
View File
@@ -1,4 +1,4 @@
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, TextField } from '@mui/material'
import { Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, Stack, Switch, TextField, Typography } from '@mui/material'
import { useState, type FormEvent } from 'react'
import type { SitesSettings } from './api.ts'
@@ -6,18 +6,17 @@ import type { SitesSettings } from './api.ts'
const UPLOAD_MAX_MB = 10240
/**
* A dialog that edits the server's sites section: whether the sites are served, the largest upload in MiB, and WebDAV
* with its port. onSave sends the section; the dialog closes when it succeeds and shows the server's message when it
* fails.
* A dialog that edits the server's sites section: whether the sites are served, the largest upload in MiB, and the port
* of WebDAV, which the System tab switches. onSave sends the settings; the dialog closes when it succeeds and shows the
* server's message when it fails.
*/
export default function SitesSettingsDialog(props: {
current: SitesSettings
onSave: (settings: SitesSettings) => Promise<void>
onSave: (settings: Omit<SitesSettings, 'webdav'>) => Promise<void>
onCancel: () => void
}) {
const [enabled, setEnabled] = useState(props.current.enabled)
const [uploadMax, setUploadMax] = useState(String(props.current.upload_max_mb))
const [webdav, setWebdav] = useState(props.current.webdav)
const [port, setPort] = useState(String(props.current.webdav_port))
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -35,7 +34,7 @@ export default function SitesSettingsDialog(props: {
setSaving(true)
setError(null)
try {
await props.onSave({ enabled, upload_max_mb: Number(uploadMax), webdav, webdav_port: Number(port) })
await props.onSave({ enabled, upload_max_mb: Number(uploadMax), webdav_port: Number(port) })
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
@@ -58,7 +57,9 @@ export default function SitesSettingsDialog(props: {
slotProps={{ htmlInput: { inputMode: 'numeric' } }}
onChange={(event) => setUploadMax(event.target.value.trim())}
/>
<FormControlLabel control={<Switch checked={webdav} onChange={(event) => setWebdav(event.target.checked)} />} label="WebDAV" />
<Typography variant="body2" color="text.secondary">
WebDAV is {props.current.webdav ? 'on' : 'off'}; it is switched on and off on the System tab.
</Typography>
<TextField
label="WebDAV port"
value={port}
+11 -3
View File
@@ -1,5 +1,7 @@
import { Box } from '@mui/material'
import { Board, useBoard, type BoardPanel } from './PanelBoard.tsx'
import ComponentsPanel from './ComponentsPanel.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import Toolbar from './Toolbar.tsx'
import UpdatesNotice from './UpdatesNotice.tsx'
/** The localStorage key of the tab's layout. */
@@ -7,15 +9,21 @@ const LAYOUT_KEY = 'linux-manager-ui.system-layout'
/**
* The server's operating system: the System updates panel lists the packages apt-get upgrade would upgrade, with Check
* update and Upgrade (UpdatesNotice with system). The panel is on a PanelBoard whose layout is kept in the browser.
* update and Upgrade (UpdatesNotice with system), and the Components panel switches the installable components
* (ComponentsPanel), telling onComponentsChange of each change. The panels are on a PanelBoard whose layout is kept in
* the browser.
*/
export default function SystemPanel() {
export default function SystemPanel(props: { onComponentsChange?: () => void }) {
const board = useBoard(LAYOUT_KEY)
const panels: BoardPanel[] = [
{ id: 'updates', title: 'System updates', wide: true, fixed: true, content: <UpdatesNotice system /> },
{ id: 'components', title: 'Components', wide: true, content: <ComponentsPanel onChange={props.onComponentsChange} /> },
]
return (
<Box component="section">
<Toolbar description="The operating system's updates and the installable components.">
<BoardButtons board={board} />
</Toolbar>
<Board board={board} panels={panels} />
</Box>
)
+4 -4
View File
@@ -7,7 +7,6 @@ import { useState } from 'react'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import PeerDialog from './PeerDialog.tsx'
import WireGuardConfigDialog from './WireGuardConfigDialog.tsx'
import { Section } from './ServerPanel.tsx'
import { USER_SHAPE, request, type User, type Users, type WireGuardPeer, type WireGuardServer } from './api.ts'
import { saveFile } from './saveFile.ts'
import { clientConfig, nextFreeAddress } from './wireguard.ts'
@@ -19,7 +18,8 @@ import { clientConfig, nextFreeAddress } from './wireguard.ts'
* network of the server's WireGuard address. A change replaces the user's peers with PUT /users/<name>; the server
* writes them into wg0.conf in the background, and onChanged has the page read again. Each peer's configuration for its
* device, with its IPs, the server's public key, endpoint and allowed IPs (server), and a placeholder where the device's
* private key goes, which the server never has, shows in a dialog ready to copy (the eye) and downloads.
* private key goes, which the server never has, shows in a dialog ready to copy (the eye) and downloads. It is the
* content of a panel of the page's board.
*/
export default function WireGuardPeers(props: { server: WireGuardServer; users: Users | null; onChanged: () => void }) {
const answer = props.users
@@ -62,7 +62,7 @@ export default function WireGuardPeers(props: { server: WireGuardServer; users:
}
return (
<Section title="Peers" wide>
<>
{error && <Alert severity="error" sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{!answer && !error && <Typography variant="body2" color="text.secondary">Reading the peers...</Typography>}
{answer && (
@@ -162,6 +162,6 @@ export default function WireGuardPeers(props: { server: WireGuardServer; users:
/>
)}
{confirm && <ConfirmDialog {...confirm} />}
</Section>
</>
)
}
+108 -11
View File
@@ -1,7 +1,28 @@
/** GET /api/info: the version of the manager package and the URL of the status page of the server it manages. */
/**
* An installable component of the server as GET /components gives it: vpn, router, dns or webdav, its switch, and state,
* installing or failed while its installation runs or failed, else installed or not installed; the router also has
* available, whether the server has an interface for its internal side, the interfaces to choose from, general.mode and
* its current internal_interface, int_addr and int_gateway_ip.
*/
export type Component = {
name: 'vpn' | 'router' | 'dns' | 'webdav'
enabled: boolean
state: 'installing' | 'failed' | 'installed' | 'not installed'
available?: boolean
interfaces?: string[]
mode?: string
internal_interface?: string
int_addr?: string
int_gateway_ip?: string
}
/** GET /api/info: the URL of the status page of the server the manager manages, and with a session the version of the
* manager package, null without one. */
export type Info = {
version: string | null
status_url: string | null
/** The manager's plain HTTP site on the server: its port and the interfaces the firewall opens it on. */
manager?: { port: number; listen: string }
}
/**
@@ -107,7 +128,7 @@ export type RouterDetails = {
clusters: { version: string; name: string; port: number | null; status: string; data_directory: string; settings: Record<string, string> | null }[]
} | null
/** The installed Caddy and where it comes from, ubuntu or upstream; null when it is not installed. */
caddy?: { version: string; source: string; service?: string } | null
caddy?: { version: string; service?: string } | null
/** The OpenID Provider, its issuer null while it is disabled. */
oidc?: { enabled: boolean; issuer: string | null }
}
@@ -345,7 +366,7 @@ export const SAN_TYPES = ['dns', 'ip', 'email'] as const
export const REVOKE_REASONS = ['unspecified', 'key_compromise', 'affiliation_changed', 'superseded', 'cessation_of_operation', 'privilege_withdrawn'] as const
/** The built-in templates, which cannot be removed, and those only the server issues. */
export const BUILTIN_TEMPLATES = ['vpn-server', 'vpn-user', 'site-to-site', 'server', 'client'] as const
export const BUILTIN_TEMPLATES = ['vpn-server', 'vpn-user', 'mtls', 'server', 'client'] as const
export const ROUTER_TEMPLATES = ['vpn-server', 'vpn-user'] as const
/** A certificate template; pki.templates holds the options it changes or defines. */
@@ -373,6 +394,7 @@ export type PkiSettings = {
publish: string[]
p2s_name: string
s2s_name: string
servers_name: string
issuing_cas: Record<string, Partial<PkiIssuingCa>>
templates: Record<string, Partial<PkiTemplate>>
extended_key_usages: Record<string, string>
@@ -400,12 +422,16 @@ export type PkiRoot = {
token_expires: string | null
}
/** An issuing CA: state is active, pending (waiting for the offline root) or missing. */
/**
* An issuing CA: state is active, pending (waiting for its certificate), off (a built-in CA whose component, the
* configuration section named by component, is off) or missing.
*/
export type PkiAuthority = {
name: string
common_name: string
state: string
builtin: boolean
component: string | null
templates: string[]
acme: boolean
subject: string | null
@@ -467,14 +493,49 @@ export type MetricsSettings = {
otlp_username: string
} & Record<MetricsKeep, string>
/** The server's https section as GET /https/settings answers it; PUT /https/settings takes acme_staging. */
/** Where the certificate of the server's FQDN comes from, https.certificate. */
export const HTTPS_CERTIFICATES = ['acme', 'self-signed', 'ca', 'external'] as const
export type HttpsCertificateSource = (typeof HTTPS_CERTIFICATES)[number]
/** The ACME CA of the server and of the web sites with TLS acme, https.acme_provider. */
export const ACME_PROVIDERS = ['letsencrypt', 'zerossl', 'custom'] as const
export type AcmeProvider = (typeof ACME_PROVIDERS)[number]
/**
* The server's https section as GET /https/settings answers it, its secrets as <name>_set; PUT /https/settings takes
* the certificate source, '' until the first setup chooses it, and the ACME settings.
*/
export type HttpsSettings = {
enabled: boolean
email: string
web_port: number
manager_port: number
caddy_source: string
acme_staging: boolean
certificate: HttpsCertificateSource | ''
self_signed_days: number
acme_provider: AcmeProvider
acme_url: string
acme_eab_key_id: string
acme_eab_mac_key_set: boolean
zerossl_api_key_set: boolean
}
/** The changes PUT /https/settings takes; a secret left out keeps its value. */
export type HttpsChange = Partial<Pick<HttpsSettings, 'acme_staging' | 'certificate' | 'self_signed_days' | 'acme_provider' |
'acme_url' | 'acme_eab_key_id'>> & { acme_eab_mac_key?: string; zerossl_api_key?: string }
/**
* The server's HTTPS certificate: the chosen source, '' until the first setup chooses it, the one served (self-signed while the chosen one is not
* available, acme for Caddy's, null for none), its subject, issuer, names and expiry, and whether a CSR waits.
*/
export type HttpsCertificate = {
source: HttpsCertificateSource | ''
served: string | null
subject: string | null
issuer: string | null
sans: string[]
expires: string | null
pending: boolean
}
/** The average and the maximum of a value over a bucket; null without data. */
@@ -515,7 +576,7 @@ export type SiteTls = 'none' | 'acme' | 'ca' | 'file'
export const SITE_TLS: SiteTls[] = ['none', 'acme', 'ca', 'file']
export const SITE_TLS_LABELS: Record<SiteTls, string> = {
none: 'None (HTTP)',
acme: "Let's Encrypt",
acme: 'ACME',
ca: 'Issuing CA',
file: 'Certificate and key',
}
@@ -726,7 +787,7 @@ export const DETAILS_SHAPE = object({
settings: nullable(record(string)),
})),
})),
caddy: optional(nullable(object({ version: string, source: string, service: optional(string) }))),
caddy: optional(nullable(object({ version: string, service: optional(string) }))),
oidc: optional(object({ enabled: boolean, issuer: nullable(string) })),
})
@@ -919,6 +980,7 @@ const PKI_SETTINGS: Check = object({
publish: list(string),
p2s_name: string,
s2s_name: string,
servers_name: string,
issuing_cas: record(object({ name: optional(string), templates: optional(list(string)), acme: optional(boolean) })),
templates: record(isObject),
extended_key_usages: record(string),
@@ -958,6 +1020,7 @@ export const PKI_SHAPE = object({
common_name: string,
state: string,
builtin: boolean,
component: nullable(string),
templates: list(string),
acme: boolean,
subject: nullable(string),
@@ -1039,7 +1102,24 @@ export const EDITOR_CONTENT_SHAPE = object({ path: string, content: string, vers
export const EDITOR_SAVED_SHAPE = object({ path: string, version: string })
export const PROFILE_SHAPE = object({ name: string, profile: string })
export const OTP_SECRET_SHAPE = object({ name: string, secret: string, uri: string })
export const INFO_SHAPE = object({ version: nullable(string), status_url: nullable(string) })
export const INFO_SHAPE = object({
version: nullable(string), status_url: nullable(string), manager: optional(object({ port: number, listen: string })),
})
/** The shape of GET and PUT /components. */
export const COMPONENTS_SHAPE = object({
components: list(object({
name: string,
enabled: boolean,
state: string,
available: optional(boolean),
interfaces: optional(list(string)),
mode: optional(string),
internal_interface: optional(string),
int_addr: optional(string),
int_gateway_ip: optional(string),
})),
})
export const SESSION_SHAPE = object({ name: string })
export const UPGRADE_SHAPE = object({
state: string,
@@ -1076,17 +1156,34 @@ export const METRICS_SETTINGS_SHAPE = object({
}),
})
/** The shape of GET and PUT /https/settings. */
/** The shape of GET and PUT /https/settings; GET also has the certificate. */
export const HTTPS_SETTINGS_SHAPE = object({
settings: object({
enabled: boolean,
email: string,
web_port: number,
manager_port: number,
caddy_source: string,
acme_staging: boolean,
certificate: string,
self_signed_days: number,
acme_provider: string,
acme_url: string,
acme_eab_key_id: string,
acme_eab_mac_key_set: boolean,
zerossl_api_key_set: boolean,
}),
certificate: optional(object({
source: string,
served: nullable(string),
subject: nullable(string),
issuer: nullable(string),
sans: list(string),
expires: nullable(string),
pending: boolean,
})),
})
export const HTTPS_CSR_SHAPE = object({ csr: string })
export const HTTPS_IMPORTED_SHAPE = object({ subject: string, issuer: nullable(string), expires: string })
const AGGREGATE: Check = object({ avg: nullable(number), max: nullable(number) })