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 server 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 server 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 server 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 server, sent when lme 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([]) 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(null) const [ticket, setTicket] = useState(null) const [reason, setReason] = useState(null) const [account, setAccount] = useState(null) const [signIn, setSignIn] = useState(false) const container = useRef(null) const terminal = useRef(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 server for a ticket without signing in; the sign-in form shows when the server wants one. */ const reopen = useCallback(async () => { setBusy(true) setError(null) setReason(null) setTicket(null) try { const answer = await request('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('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 | 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 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('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 server asks the browser for. */ async function openWithPasskey() { setBusy(true) setError(null) try { const begun = await request>('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('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 ( {ticket === null && account && !login && ( {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 server switches it on: linux-manager-user console ${account.name} --posix, or --account LOCAL to use a local account.`} )} {ticket === null && !account && error && {error}} {ticket === null && login && signIn && ( Open a shell {`The shell runs on the server as ${login.local ? 'the local account' : 'your POSIX account'} ${login.account}. Sign in again to open it.`} {error && {error}} setPassword(event.target.value)} /> setCode(event.target.value.trim())} /> {account && account.passkeys.length > 0 && ( )} )} {reason !== null && ( void reopen()}>New shell}> {reason} )} {files.length > 0 && ( setFiles((current) => current.filter((file) => file.id !== id))} /> )} {ticket !== null && ( )} ) }