feature: the package installs the Router Manager, which is no longer a package of its own.
Release / release (push) Failing after 4s

This commit is contained in:
slawek committed 2026-11-14 12:52:44 +01:00
1 parent 6d90441bee
commit 8efe21bfa6
129 files changed
+17381 -104

No files matched your search

+421
View File
@@ -0,0 +1,421 @@
import Add from '@mui/icons-material/Add'
import Delete from '@mui/icons-material/Delete'
import {
Alert, Autocomplete, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, FormGroup, IconButton, Stack, Switch,
TextField, Tooltip, Typography,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import type { Role, User } from './api.ts'
/** The names vpn-router-user accepts for a service account: a user name or a GUID in lowercase. */
const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}[a-z0-9]$|^[a-z]$|^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
/** A random GUID (version 4) in lowercase, from crypto.getRandomValues, which pages served over plain HTTP have too. */
function newGuid() {
const bytes = crypto.getRandomValues(new Uint8Array(16))
bytes[6] = (bytes[6] & 0x0f) | 0x40
bytes[8] = (bytes[8] & 0x3f) | 0x80
const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
/** The e-mail addresses vpn-router-user accepts: one @, no spaces, and a dot in the domain. */
const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/
/** The longest display name and description the router accepts. */
const DISPLAY_NAME_MAX = 64
const DESCRIPTION_MAX = 256
/** The most URIs of each kind and allowed groups of an OpenID Provider client, and the longest URI, the router accepts. */
const CLIENT_VALUES_MAX = 16
const URI_MAX = 1024
/** The hosts a client's URI may name over plain HTTP. */
const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '[::1]']
/** The names of a role and of a scope of a resource the router accepts. */
const ROLE_NAME = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/
const SCOPE_NAME = /^[a-z][a-z0-9._-]{0,63}$/
/** The grants a client may have besides the authorization code, with their labels. */
const GRANTS = [['client_credentials', 'Client credentials'], ['device_code', 'Device authorization']] as const
/** The settings of a service account that /service-accounts takes; an empty one removes it when editing. */
export type ServiceAccountSettings = {
display_name: string
description: string
email: string
redirect_uris: string[]
post_logout_redirect_uris: string[]
allowed_groups: string[]
grants: string[]
public_client: boolean
client_scopes: string[]
resource_scopes: string[]
roles: Role[]
}
/** Why the roles are refused by the router, or ''. */
function rolesProblem(roles: Role[]) {
for (const role of roles) {
if (!ROLE_NAME.test(role.name.trim())) {
return 'A role name is up to 64 letters, digits, dots, underscores and dashes, starting with a letter.'
}
if (role.description.trim().length > DESCRIPTION_MAX) {
return `A role description has at most ${DESCRIPTION_MAX} characters.`
}
}
const names = roles.map((role) => role.name.trim().toLowerCase())
return new Set(names).size === names.length ? '' : 'Each role name may appear once.'
}
/** The non-empty lines of a text field, trimmed. */
function lines(text: string) {
return text.split('\n').map((line) => line.trim()).filter((line) => line !== '')
}
/** Why the URIs of a text field are refused by the router, or ''. */
function urisProblem(text: string) {
const uris = lines(text)
if (uris.length > CLIENT_VALUES_MAX) {
return `At most ${CLIENT_VALUES_MAX} URIs.`
}
for (const uri of uris) {
let parsed: URL
try {
parsed = new URL(uri)
} catch {
return `${uri} is not a URI.`
}
if (uri.length > URI_MAX || uri.includes('#')
|| !(parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.includes(parsed.hostname)))) {
return `${uri}: an https URI, or an http URI of localhost, without a fragment.`
}
}
return ''
}
/**
* A dialog that adds a service account, with its name, a new GUID unless replaced by a user name, display name, description, optional e-mail address and a
* password typed twice, or, given an account, edits its display name, description and e-mail address. Both also set the OpenID Provider settings. As a
* client: the redirect URIs and the post-logout redirect URIs, one per line, the allowed groups, chosen from groups, the grants, whether it is public, with
* no secret, which client credentials need, and the client scopes, chosen from scopes, those of every resource; an account with redirect URIs or grants is
* a client, its name the client ID and its password the secret. As a resource: its scopes, typed, and its roles, each with a name, a description and the
* groups and accounts, chosen from accounts, it is assigned to. onSave sends them, trimmed, with the password when adding; the dialog closes when it
* succeeds and shows the router's message when it fails.
*/
export default function ServiceAccountDialog(props: {
account?: User
groups: string[]
accounts: string[]
scopes: string[]
onSave: (name: string, settings: ServiceAccountSettings, password: string) => Promise<void>
onCancel: () => void
}) {
const adding = props.account === undefined
const [name, setName] = useState(() => props.account?.name ?? newGuid())
const [displayName, setDisplayName] = useState(props.account?.display_name ?? '')
const [description, setDescription] = useState(props.account?.description ?? '')
const [email, setEmail] = useState(props.account?.email ?? '')
const [redirectUris, setRedirectUris] = useState((props.account?.redirect_uris ?? []).join('\n'))
const [logoutUris, setLogoutUris] = useState((props.account?.post_logout_redirect_uris ?? []).join('\n'))
const [allowedGroups, setAllowedGroups] = useState(props.account?.allowed_groups ?? [])
const [grants, setGrants] = useState(props.account?.grants ?? [])
const [publicClient, setPublicClient] = useState(props.account?.public_client ?? false)
const [clientScopes, setClientScopes] = useState(props.account?.client_scopes ?? [])
const [resourceScopes, setResourceScopes] = useState(props.account?.resource_scopes ?? [])
const [roles, setRoles] = useState<Role[]>(props.account?.roles ?? [])
const [password, setPassword] = useState('')
const [again, setAgain] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const nameProblem = adding && name !== '' && !NAME_PATTERN.test(name)
? 'A GUID, or up to 32 lower case letters, digits and dashes, starting with a letter and not ending with a dash.'
: ''
const displayNameProblem = displayName.trim().length > DISPLAY_NAME_MAX ? `At most ${DISPLAY_NAME_MAX} characters.` : ''
const descriptionProblem = description.trim().length > DESCRIPTION_MAX ? `At most ${DESCRIPTION_MAX} characters.` : ''
const emailProblem = email.trim() !== '' && !EMAIL_PATTERN.test(email.trim()) ? 'Not an e-mail address.' : ''
const againProblem = again !== '' && again !== password ? 'The passwords differ.' : ''
const redirectProblem = urisProblem(redirectUris)
const logoutProblem = urisProblem(logoutUris)
const groupsProblem = allowedGroups.length > CLIENT_VALUES_MAX ? `At most ${CLIENT_VALUES_MAX} groups.` : ''
const clientScopesProblem = clientScopes.length > CLIENT_VALUES_MAX ? `At most ${CLIENT_VALUES_MAX} scopes.` : ''
const resourceScopesProblem = resourceScopes.length > CLIENT_VALUES_MAX
? `At most ${CLIENT_VALUES_MAX} scopes.`
: resourceScopes.every((scope) => SCOPE_NAME.test(scope))
? ''
: 'A scope is up to 64 lower case letters, digits, dots, underscores and dashes, starting with a letter.'
const roleProblem = rolesProblem(roles)
const blocked = name === '' || nameProblem !== '' || displayNameProblem !== '' || descriptionProblem !== '' || emailProblem !== ''
|| redirectProblem !== '' || logoutProblem !== '' || groupsProblem !== '' || clientScopesProblem !== '' || resourceScopesProblem !== ''
|| roleProblem !== ''
|| (adding && (password === '' || again !== password))
/** Changes one role of the list. */
function setRole(index: number, change: Partial<Role>) {
setRoles((current) => current.map((role, at) => (at === index ? { ...role, ...change } : role)))
}
async function submit(event: FormEvent) {
event.preventDefault()
if (blocked) {
return
}
setSaving(true)
setError(null)
try {
await props.onSave(name, {
display_name: displayName.trim(),
description: description.trim(),
email: email.trim(),
redirect_uris: lines(redirectUris),
post_logout_redirect_uris: lines(logoutUris),
allowed_groups: allowedGroups,
grants: GRANTS.map(([grant]) => grant).filter((grant) => grants.includes(grant)),
public_client: publicClient,
client_scopes: [...clientScopes].sort(),
resource_scopes: [...resourceScopes].sort(),
roles: roles.map((role) => ({
name: role.name.trim(),
description: role.description.trim(),
groups: [...role.groups].sort(),
accounts: [...role.accounts].sort(),
})).sort((one, other) => one.name.localeCompare(other.name)),
}, 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>{adding ? 'Add service account' : `Edit service account ${props.account?.name}`}</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<TextField
label="Name"
value={name}
disabled={!adding}
autoFocus={adding}
autoComplete="off"
error={nameProblem !== ''}
helperText={nameProblem || (adding ? 'The name the other system signs in with: a new GUID, or a user name.' : 'The name the other system signs in with.')}
onChange={(event) => setName(event.target.value.trim().toLowerCase())}
/>
<TextField
label="Display name"
value={displayName}
autoFocus={!adding}
autoComplete="off"
error={displayNameProblem !== ''}
helperText={displayNameProblem || 'Optional.'}
onChange={(event) => setDisplayName(event.target.value)}
/>
<TextField
label="Description"
value={description}
autoComplete="off"
multiline
minRows={2}
error={descriptionProblem !== ''}
helperText={descriptionProblem || 'Optional: what the account is for.'}
onChange={(event) => setDescription(event.target.value)}
/>
<TextField
label="E-mail"
type="email"
value={email}
autoComplete="off"
error={emailProblem !== ''}
helperText={emailProblem || 'Optional, for notifications.'}
onChange={(event) => setEmail(event.target.value)}
/>
<Typography variant="subtitle2" sx={{ mt: 1 }}>As an OpenID Connect client</Typography>
<TextField
label="Redirect URIs"
value={redirectUris}
autoComplete="off"
multiline
minRows={2}
error={redirectProblem !== ''}
helperText={redirectProblem || 'Optional: the OpenID Connect redirect URIs of the client, one per line.'}
onChange={(event) => setRedirectUris(event.target.value)}
/>
<TextField
label="Post-logout redirect URIs"
value={logoutUris}
autoComplete="off"
multiline
minRows={1}
error={logoutProblem !== ''}
helperText={logoutProblem || 'Optional: the post-logout redirect URIs of the client, one per line.'}
onChange={(event) => setLogoutUris(event.target.value)}
/>
<Autocomplete
multiple
options={props.groups}
value={allowedGroups}
onChange={(_event, next) => setAllowedGroups(next)}
renderInput={(params) => (
<TextField
{...params}
label="Allowed groups"
error={groupsProblem !== ''}
helperText={groupsProblem || 'Optional: the groups whose members may sign in to the client.'}
/>
)}
/>
<Box>
<Typography variant="body2" color="text.secondary">Grants besides the authorization code, which the redirect URIs give</Typography>
<FormGroup row>
{GRANTS.map(([grant, label]) => (
<FormControlLabel
key={grant}
label={label}
control={(
<Checkbox
checked={grants.includes(grant)}
disabled={grant === 'client_credentials' && publicClient}
onChange={(event) => setGrants((current) => (event.target.checked
? [...current, grant]
: current.filter((value) => value !== grant)))}
/>
)}
/>
))}
</FormGroup>
<FormControlLabel
label="Public client (no secret)"
control={(
<Switch
checked={publicClient}
onChange={(event) => {
setPublicClient(event.target.checked)
if (event.target.checked) {
setGrants((current) => current.filter((value) => value !== 'client_credentials'))
}
}}
/>
)}
/>
</Box>
<Autocomplete
multiple
options={props.scopes}
value={clientScopes}
onChange={(_event, next) => setClientScopes(next)}
renderInput={(params) => (
<TextField
{...params}
label="Client scopes"
error={clientScopesProblem !== ''}
helperText={clientScopesProblem || 'Optional: the scopes of resources the client may ask for.'}
/>
)}
/>
<Typography variant="subtitle2" sx={{ mt: 1 }}>As a resource</Typography>
<Autocomplete
multiple
freeSolo
options={[]}
value={resourceScopes}
onChange={(_event, next) => setResourceScopes(next.map((scope) => scope.trim()).filter((scope) => scope !== ''))}
renderInput={(params) => (
<TextField
{...params}
label="Scopes"
error={resourceScopesProblem !== ''}
helperText={resourceScopesProblem || `Optional: the scopes clients ask for as ${name || '<name>'}:<scope>; type one and press Enter.`}
/>
)}
/>
<Stack sx={{ gap: 1.5 }}>
<Typography variant="body2" color="text.secondary">
Roles, which the tokens for this resource carry for the groups and accounts they are assigned to
</Typography>
{roles.map((role, index) => (
<Stack key={index} direction="row" sx={{ gap: 1, alignItems: 'flex-start' }}>
<Stack sx={{ gap: 1, flex: 1 }}>
<Stack direction="row" sx={{ gap: 1 }}>
<TextField
label="Role"
size="small"
value={role.name}
autoComplete="off"
error={!ROLE_NAME.test(role.name.trim())}
onChange={(event) => setRole(index, { name: event.target.value })}
/>
<TextField
label="Description"
size="small"
value={role.description}
autoComplete="off"
sx={{ flex: 1 }}
onChange={(event) => setRole(index, { description: event.target.value })}
/>
</Stack>
<Autocomplete
multiple
size="small"
options={props.groups}
value={role.groups}
onChange={(_event, next) => setRole(index, { groups: next })}
renderInput={(params) => <TextField {...params} label="Groups" />}
/>
<Autocomplete
multiple
size="small"
options={props.accounts}
value={role.accounts}
onChange={(_event, next) => setRole(index, { accounts: next })}
renderInput={(params) => <TextField {...params} label="Users and service accounts" />}
/>
</Stack>
<Tooltip title="Remove the role">
<IconButton onClick={() => setRoles((current) => current.filter((_role, at) => at !== index))}>
<Delete fontSize="small" />
</IconButton>
</Tooltip>
</Stack>
))}
{roleProblem && <Typography variant="caption" color="error">{roleProblem}</Typography>}
<Box>
<Button size="small" startIcon={<Add />} onClick={() => setRoles((current) => [...current, { name: '', description: '', groups: [], accounts: [] }])}>
Add role
</Button>
</Box>
</Stack>
{adding && (
<>
<TextField
label="Password"
type="password"
value={password}
autoComplete="new-password"
onChange={(event) => setPassword(event.target.value)}
/>
<TextField
label="Password again"
type="password"
value={again}
autoComplete="new-password"
error={againProblem !== ''}
helperText={againProblem}
onChange={(event) => setAgain(event.target.value)}
/>
</>
)}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>
{adding ? 'Add' : 'Save'}
</Button>
</DialogActions>
</Dialog>
)
}