Files
linux-cloud-router/web/src/DnsPanel.tsx
T

264 lines
11 KiB
TypeScript

import Add from '@mui/icons-material/Add'
import Delete from '@mui/icons-material/Delete'
import Edit from '@mui/icons-material/Edit'
import Refresh from '@mui/icons-material/Refresh'
import Settings from '@mui/icons-material/Settings'
import { Alert, Box, Button, Chip, IconButton, Table, TableBody, TableCell, TableHead, TableRow, Tooltip } from '@mui/material'
import { useCallback, useEffect, useState } from 'react'
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 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'
/** 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 (
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Type</TableCell>
<TableCell>Content</TableCell>
<TableCell align="right">TTL</TableCell>
{props.onRemove && <TableCell align="right">Actions</TableCell>}
</TableRow>
</TableHead>
<TableBody>
{props.records.length === 0 && (
<TableRow>
<TableCell colSpan={props.onRemove ? 5 : 4} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{props.records.map((record) => (
<TableRow key={`${record.name} ${record.type} ${record.content}`} hover>
<TableCell>{record.name}</TableCell>
<TableCell>{record.type}</TableCell>
<TableCell sx={{ fontFamily: 'monospace', fontSize: 13, wordBreak: 'break-all' }}>{record.content}</TableCell>
<TableCell align="right">{record.ttl}</TableCell>
{props.onRemove && (
<TableCell align="right">
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={props.busy} onClick={() => props.onRemove?.(record)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</TableCell>
)}
</TableRow>
))}
</TableBody>
</Table>
)
}
/**
* 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.
*/
export default function DnsPanel() {
const [dns, setDns] = useState<Dns | null>(null)
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [busy, setBusy] = useState(false)
const [settings, setSettings] = useState(false)
const [selected, setSelected] = useState<string | null>(null)
const [editing, setEditing] = useState<DnsDomain | 'new' | null>(null)
const [addingRecord, setAddingRecord] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const refresh = useCallback(async () => {
setBusy(true)
try {
setDns(await request<Dns>('GET', '/dns', DNS_SHAPE))
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setDns(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
}, [])
useEffect(() => {
void refresh()
}, [refresh])
/** Ask for a confirmation, then send the removal and refresh. */
function confirmRemove(title: string, message: string, send: () => Promise<unknown>) {
setConfirm({
title,
message,
confirmLabel: 'Remove',
destructive: true,
onCancel: () => setConfirm(null),
onConfirm: async () => {
setConfirm(null)
setBusy(true)
try {
await send()
setError(null)
} catch (caught) {
setError((caught as Error).message)
}
await refresh()
},
})
}
const section = dns?.settings
const domain = dns?.domains.find((item) => item.name === selected) ?? null
const path = domain ? `/dns/domains/${encodeURIComponent(domain.name)}` : ''
function removeDomain(item: DnsDomain) {
confirmRemove('Remove domain', `Remove the domain ${item.name} with its manual records?`,
() => request('DELETE', `/dns/domains/${encodeURIComponent(item.name)}`, DNS_DOMAIN_REMOVED_SHAPE))
}
function removeRecord(record: DnsRecord) {
const query = new URLSearchParams({ name: `${record.name}.`, type: record.type, content: record.content })
confirmRemove('Remove record', `Remove the ${record.type} record of ${record.name}?`,
() => request('DELETE', `${path}/records?${query.toString()}`, DNS_REMOVED_SHAPE))
}
return (
<Box component="section">
<Toolbar description="The primary name server of the server's domains.">
<Button variant="outlined" startIcon={<Settings />} disabled={busy || !section} onClick={() => setSettings(true)}>
Settings
</Button>
<Button variant="contained" startIcon={<Add />} disabled={busy || !section} onClick={() => setEditing('new')}>
Add domain
</Button>
<Button variant="outlined" startIcon={<Add />} disabled={busy || !domain} onClick={() => setAddingRecord(true)}>
Add record
</Button>
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => void refresh()}>
Refresh
</Button>
</Toolbar>
{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>
)}
{settings && section && (
<DnsSettingsDialog
current={section}
nameserver={dns.nameserver}
publicAddress={dns.public_address}
onCancel={() => setSettings(false)}
onSave={async (values, publicAddress) => {
await request('PUT', '/dns', DNS_SETTINGS_SHAPE, { ...values, public_address: publicAddress })
setSettings(false)
await refresh()
}}
/>
)}
{editing && (
<DnsDomainDialog
current={editing === 'new' ? undefined : editing}
onCancel={() => setEditing(null)}
onSave={async (values) => {
if (editing === 'new') {
await request('POST', '/dns/domains', DNS_DOMAIN_SHAPE, values)
} else {
await request('PUT', `/dns/domains/${encodeURIComponent(editing.name)}`, DNS_DOMAIN_SHAPE, { ttl: values.ttl })
}
setEditing(null)
setSelected(values.name)
await refresh()
}}
/>
)}
{addingRecord && domain && (
<DnsRecordDialog
domain={domain.name}
onCancel={() => setAddingRecord(false)}
onSave={async (record) => {
await request('POST', `${path}/records`, DNS_RECORD_SHAPE, record)
setAddingRecord(false)
await refresh()
}}
/>
)}
{confirm && <ConfirmDialog {...confirm} />}
</Box>
)
}