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

+284
View File
@@ -0,0 +1,284 @@
import Key from '@mui/icons-material/Key'
import Terminal from '@mui/icons-material/Terminal'
import { Alert, Box, Button, Paper, Stack, TextField, Typography, useColorScheme } from '@mui/material'
import { FitAddon } from '@xterm/addon-fit'
import { Terminal as XTerm, type ITheme } from '@xterm/xterm'
import '@xterm/xterm/css/xterm.css'
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react'
import EditorPanel from './EditorPanel.tsx'
import { ACCOUNT_SHAPE, CODE_PATTERN, PASSKEY_BEGUN_SHAPE, SHELL_TICKET_SHAPE, request, type Account, type EditorFile, type PasskeyBegun, type ShellTicket } from './api.ts'
/** The colours of the terminal in the light and the dark mode, those of VS Code's terminal. */
const THEMES: Record<'light' | 'dark', ITheme> = {
light: { background: '#ffffff', foreground: '#333333', cursor: '#333333', selectionBackground: '#add6ff' },
dark: { background: '#1e1e1e', foreground: '#cccccc', cursor: '#cccccc', selectionBackground: '#264f78' },
}
/** The fonts of VS Code's terminal on macOS, Windows and Linux. */
const FONT = "Menlo, Monaco, Consolas, 'Droid Sans Mono', 'DejaVu Sans Mono', 'Courier New', monospace"
/**
* A login shell on the router in an xterm.js terminal, as the signed-in user's console account; a user whose console
* login is not on is told how root switches it on. The router gives a ticket without a sign-in while the user's last
* use of a shell is within its web.shell_auth_timeout; otherwise the user signs in again with the password and the
* code, or with one of its passkeys, which the browser unlocks with the device's PIN or biometrics. With the ticket, a
* WebSocket to /api/shell carries the terminal: keystrokes and output as binary
* messages, the window size as a text message {cols, rows}. When the router or the connection ends the shell, the
* terminal stays readable with the reason above it, and New shell asks for a new ticket.
*
* A text message {editor: "open", session, id, path} of the router, sent when vre in the shell names a file, opens the
* file in the editor (EditorPanel) and calls onOpened. editorShown shows the editor in place of the terminal, which
* keeps running; onFiles is called with the number of open files, 0 once the last is closed or the shell ends.
*/
export default function ShellPanel(props: { editorShown: boolean; onFiles: (count: number) => void; onOpened: () => void }) {
const { onFiles } = props
const [files, setFiles] = useState<EditorFile[]>([])
const opened = useRef(props.onOpened)
const { mode, systemMode } = useColorScheme()
const scheme = (mode === 'system' ? systemMode : mode) === 'dark' ? 'dark' : 'light'
const [password, setPassword] = useState('')
const [code, setCode] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const [ticket, setTicket] = useState<string | null>(null)
const [reason, setReason] = useState<string | null>(null)
const [account, setAccount] = useState<Account | null>(null)
const [signIn, setSignIn] = useState(false)
const container = useRef<HTMLDivElement>(null)
const terminal = useRef<XTerm | null>(null)
const theme = useRef(THEMES[scheme])
const codeProblem = !CODE_PATTERN.test(code) ? 'Six digits.' : ''
const login = account?.console?.enabled && account.otp ? account.console : null
/** Asks the router for a ticket without signing in; the sign-in form shows when the router wants one. */
const reopen = useCallback(async () => {
setBusy(true)
setError(null)
setReason(null)
setTicket(null)
try {
const answer = await request<ShellTicket>('POST', '/shell', SHELL_TICKET_SHAPE, {})
setTicket(answer.ticket)
setSignIn(answer.ticket === null)
} catch (caught) {
setError((caught as Error).message)
setSignIn(true)
} finally {
setBusy(false)
}
}, [])
useEffect(() => {
request<Account>('GET', '/account', ACCOUNT_SHAPE).then(setAccount).catch((caught: Error) => setError(caught.message))
}, [])
const enabled = login !== null
useEffect(() => {
if (enabled) {
void reopen()
}
}, [enabled, reopen])
useEffect(() => {
opened.current = props.onOpened
}, [props.onOpened])
useEffect(() => {
onFiles(files.length)
}, [onFiles, files.length])
const terminalShown = !props.editorShown || files.length === 0
useEffect(() => {
if (terminalShown) {
terminal.current?.focus()
}
}, [terminalShown])
useEffect(() => {
theme.current = THEMES[scheme]
if (terminal.current) {
terminal.current.options.theme = THEMES[scheme]
}
}, [scheme])
// The terminal and its WebSocket live as long as the ticket that opened them.
useEffect(() => {
if (ticket === null || !container.current) {
return
}
const term = new XTerm({ cursorBlink: true, fontFamily: FONT, fontSize: 14, theme: theme.current })
const fit = new FitAddon()
term.loadAddon(fit)
term.open(container.current)
fit.fit()
terminal.current = term
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const socket = new WebSocket(`${protocol}://${window.location.host}/api/shell?ticket=${encodeURIComponent(ticket)}`)
socket.binaryType = 'arraybuffer'
const encoder = new TextEncoder()
const send = (data: Uint8Array<ArrayBuffer> | string) => {
if (socket.readyState === WebSocket.OPEN) {
socket.send(data)
}
}
socket.onopen = () => {
send(JSON.stringify({ cols: term.cols, rows: term.rows }))
term.focus()
}
socket.onmessage = (message) => {
if (message.data instanceof ArrayBuffer) {
term.write(new Uint8Array(message.data))
return
}
try {
const event: unknown = JSON.parse(String(message.data))
const { editor, session, id, path } = (event ?? {}) as Record<string, unknown>
if (editor === 'open' && typeof session === 'string' && typeof id === 'string' && typeof path === 'string') {
setFiles((current) => [...current, { session, id, path }])
opened.current()
}
} catch {
// A text message that is not an editor event is ignored.
}
}
socket.onclose = (closed) => {
term.options.disableStdin = true
term.options.cursorBlink = false
setFiles([])
setReason(closed.reason || 'The connection to the shell closed.')
}
term.onData((data) => send(encoder.encode(data)))
term.onBinary((data) => send(Uint8Array.from(data, (character) => character.charCodeAt(0))))
term.onResize(({ cols, rows }) => send(JSON.stringify({ cols, rows })))
// A terminal hidden behind the editor keeps its size.
const observer = new ResizeObserver(([entry]) => {
if (entry.contentRect.width > 0 && entry.contentRect.height > 0) {
fit.fit()
}
})
observer.observe(container.current)
return () => {
observer.disconnect()
socket.onclose = null
socket.close()
term.dispose()
terminal.current = null
setFiles([])
}
}, [ticket])
async function open(event: FormEvent) {
event.preventDefault()
if (password === '' || codeProblem !== '') {
return
}
setBusy(true)
setError(null)
try {
const answer = await request<ShellTicket>('POST', '/shell', SHELL_TICKET_SHAPE, { password, code })
setPassword('')
setCode('')
setReason(null)
setTicket(answer.ticket)
setSignIn(answer.ticket === null)
} catch (caught) {
setError((caught as Error).message)
} finally {
setBusy(false)
}
}
/** Opens a shell with one of the user's passkeys, which the router asks the browser for. */
async function openWithPasskey() {
setBusy(true)
setError(null)
try {
const begun = await request<PasskeyBegun<PublicKeyCredentialRequestOptionsJSON>>('POST', '/shell/passkey', PASSKEY_BEGUN_SHAPE, {})
const credential = await navigator.credentials.get({ publicKey: PublicKeyCredential.parseRequestOptionsFromJSON(begun.options.publicKey) })
if (!(credential instanceof PublicKeyCredential)) {
throw new Error('The browser gave no passkey.')
}
const answer = await request<ShellTicket>('POST', '/shell', SHELL_TICKET_SHAPE, { passkey: { id: begun.id, credential: credential.toJSON() } })
setPassword('')
setCode('')
setReason(null)
setTicket(answer.ticket)
setSignIn(answer.ticket === null)
} catch (caught) {
setError(caught instanceof DOMException && caught.name === 'NotAllowedError' ? 'No passkey was chosen.' : (caught as Error).message)
} finally {
setBusy(false)
}
}
return (
<Box component="section">
{ticket === null && account && !login && (
<Alert severity="info">
{account.console?.enabled
? 'The shell needs one-time passwords. Enrol an authenticator app on the Account page.'
: `Console login is not on for ${account.name}. Root on the router switches it on: vpn-router-user console ${account.name} --posix, or --account LOCAL to use a local account.`}
</Alert>
)}
{ticket === null && !account && error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
{ticket === null && login && signIn && (
<Box sx={{ display: 'flex', justifyContent: 'center', pt: 4 }}>
<Paper component="form" onSubmit={open} variant="outlined" sx={{ p: 3, width: '100%', maxWidth: 380 }}>
<Stack sx={{ gap: 2 }}>
<Typography variant="h6" component="h3">Open a shell</Typography>
<Typography variant="body2" color="text.secondary">
{`The shell runs on the router as ${login.local ? 'the local account' : 'your POSIX account'} ${login.account}. Sign in again to open it.`}
</Typography>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
<TextField label="Password" type="password" value={password} autoFocus autoComplete="current-password" onChange={(event) => setPassword(event.target.value)} />
<TextField
label="Code"
value={code}
autoComplete="one-time-code"
error={code !== '' && codeProblem !== ''}
helperText={code !== '' ? codeProblem : 'The code of your authenticator app.'}
slotProps={{ htmlInput: { inputMode: 'numeric', maxLength: 6 } }}
onChange={(event) => setCode(event.target.value.trim())}
/>
<Button type="submit" variant="contained" startIcon={<Terminal />} disabled={busy || password === '' || codeProblem !== ''}>
Open shell
</Button>
{account && account.passkeys.length > 0 && (
<Button variant="outlined" startIcon={<Key />} disabled={busy} onClick={() => void openWithPasskey()}>
Open with a passkey
</Button>
)}
</Stack>
</Paper>
</Box>
)}
{reason !== null && (
<Alert severity="info" sx={{ mb: 2 }} action={<Button color="inherit" size="small" disabled={busy} onClick={() => void reopen()}>New shell</Button>}>
{reason}
</Alert>
)}
{files.length > 0 && (
<Box sx={{ display: props.editorShown ? 'block' : 'none' }}>
<EditorPanel files={files} scheme={scheme} onClosed={(id) => setFiles((current) => current.filter((file) => file.id !== id))} />
</Box>
)}
{ticket !== null && (
<Box
sx={{
display: terminalShown ? 'block' : 'none',
height: 'calc(100vh - 220px)',
minHeight: 320,
p: 1,
borderRadius: 1,
border: 1,
borderColor: 'divider',
bgcolor: THEMES[scheme].background,
}}
>
<Box ref={container} sx={{ width: '100%', height: '100%' }} />
</Box>
)}
</Box>
)
}