Add frontend app with terminal UI, sandbox integration, and asset handling.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
91049379f7
commit
b841c2d1f6
19 files changed
+800
-13
No files matched your search
@@ -0,0 +1,75 @@
|
||||
import type { Terminal } from '@xterm/xterm';
|
||||
import type { EndReason } from './connection.ts';
|
||||
|
||||
const DIM = '\x1b[2m';
|
||||
const BOLD = '\x1b[1m';
|
||||
const GREEN = '\x1b[32m';
|
||||
const RESET = '\x1b[0m';
|
||||
|
||||
const CHECKS = [
|
||||
'gVisor sandbox runtime',
|
||||
'read only root filesystem',
|
||||
'network disabled',
|
||||
'one container per visitor',
|
||||
];
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Terminals need carriage returns; plain text files only have line feeds. */
|
||||
function toTerminal(text: string): string {
|
||||
return text.replace(/\r?\n/g, '\r\n');
|
||||
}
|
||||
|
||||
async function fetchMotd(): Promise<string | undefined>
|
||||
{
|
||||
try
|
||||
{
|
||||
const response = await fetch('/raw/motd');
|
||||
return response.ok ? await response.text() : undefined;
|
||||
}
|
||||
catch { return undefined; }
|
||||
}
|
||||
|
||||
export function startPrompt(touch: boolean): string {
|
||||
return `${BOLD}${touch ? 'tap' : 'press any key'} to boot your sandbox${RESET}`;
|
||||
}
|
||||
|
||||
/** Plays the local boot screen. Nothing reaches the server until the visitor interacts. */
|
||||
export async function playBoot(terminal: Terminal, touch: boolean): Promise<void>
|
||||
{
|
||||
const motd = fetchMotd();
|
||||
|
||||
terminal.writeln(`${BOLD}security-command.org${RESET} ${DIM}terminal${RESET}`);
|
||||
terminal.writeln('');
|
||||
|
||||
for (const check of CHECKS)
|
||||
{
|
||||
await sleep(120);
|
||||
terminal.writeln(`${DIM}[${RESET}${GREEN} ok ${RESET}${DIM}]${RESET} ${check}`);
|
||||
}
|
||||
|
||||
const text = await motd;
|
||||
if (text)
|
||||
{
|
||||
terminal.writeln('');
|
||||
terminal.write(toTerminal(text.trimEnd()));
|
||||
terminal.writeln('');
|
||||
}
|
||||
|
||||
terminal.writeln('');
|
||||
terminal.write(startPrompt(touch));
|
||||
}
|
||||
|
||||
const END_MESSAGES: Record<EndReason, string> = {
|
||||
closed: 'session closed',
|
||||
expired: 'session expired (time limit reached)',
|
||||
error: 'the sandbox could not be started',
|
||||
lost: 'connection lost',
|
||||
rejected: 'the server refused the connection',
|
||||
};
|
||||
|
||||
export function endMessage(reason: EndReason, touch: boolean): string {
|
||||
return `\r\n${DIM}[${END_MESSAGES[reason]}]${RESET}\r\n${startPrompt(touch).replace('boot your sandbox', 'start a new session')}`;
|
||||
}
|
||||
|
||||
export const CONNECTING_MESSAGE = `\r\n\r\n${DIM}connecting...${RESET}`;
|
||||
@@ -0,0 +1,99 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { TerminalConnection, terminalUrl, type EndReason } from './connection.ts';
|
||||
|
||||
class FakeSocket
|
||||
{
|
||||
binaryType = 'blob';
|
||||
readyState: number = WebSocket.CONNECTING;
|
||||
sent: (string | Uint8Array)[] = [];
|
||||
onopen?: () => void;
|
||||
onmessage?: (event: { data: unknown }) => void;
|
||||
onclose?: () => void;
|
||||
|
||||
send(data: string | Uint8Array): void {
|
||||
this.sent.push(data);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.onclose?.();
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.readyState = WebSocket.OPEN;
|
||||
this.onopen?.();
|
||||
}
|
||||
}
|
||||
|
||||
function connect()
|
||||
{
|
||||
const socket = new FakeSocket();
|
||||
const events = { ready: 0, output: [] as string[], ended: [] as EndReason[] };
|
||||
|
||||
const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, {
|
||||
ready: () => events.ready++,
|
||||
output: (data) => events.output.push(new TextDecoder().decode(data)),
|
||||
ended: (reason) => events.ended.push(reason),
|
||||
}, () => socket as unknown as WebSocket);
|
||||
|
||||
return { socket, events, connection };
|
||||
}
|
||||
|
||||
describe('terminalUrl', () => {
|
||||
it('follows the page protocol', () => {
|
||||
expect(terminalUrl({ protocol: 'https:', host: 'security-command.org' })).toBe('wss://security-command.org/ws');
|
||||
expect(terminalUrl({ protocol: 'http:', host: 'localhost:5173' })).toBe('ws://localhost:5173/ws');
|
||||
});
|
||||
});
|
||||
|
||||
describe('TerminalConnection', () => {
|
||||
it('greets with the terminal size and uses binary frames', () => {
|
||||
const { socket, connection } = connect();
|
||||
|
||||
connection.input('ignored before open');
|
||||
socket.open();
|
||||
connection.input('ls\r');
|
||||
|
||||
expect(socket.binaryType).toBe('arraybuffer');
|
||||
expect(socket.sent[0]).toBe('{"type":"hello","cols":80,"rows":24}');
|
||||
expect(new TextDecoder().decode(socket.sent[1] as Uint8Array)).toBe('ls\r');
|
||||
expect(socket.sent).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('passes output and readiness on', () => {
|
||||
const { socket, events } = connect();
|
||||
socket.open();
|
||||
|
||||
socket.onmessage?.({ data: '{"type":"ready"}' });
|
||||
socket.onmessage?.({ data: new TextEncoder().encode('hi').buffer });
|
||||
|
||||
expect(events.ready).toBe(1);
|
||||
expect(events.output).toEqual(['hi']);
|
||||
});
|
||||
|
||||
it('reports the server reason, a lost connection, or a refusal', () => {
|
||||
const expired = connect();
|
||||
expired.socket.open();
|
||||
expired.socket.onmessage?.({ data: '{"type":"exit","reason":"expired"}' });
|
||||
expired.socket.close();
|
||||
|
||||
const lost = connect();
|
||||
lost.socket.open();
|
||||
lost.socket.close();
|
||||
|
||||
const rejected = connect();
|
||||
rejected.socket.close();
|
||||
rejected.socket.close();
|
||||
|
||||
expect(expired.events.ended).toEqual(['expired']);
|
||||
expect(lost.events.ended).toEqual(['lost']);
|
||||
expect(rejected.events.ended).toEqual(['rejected']);
|
||||
});
|
||||
|
||||
it('encodes binary input byte by byte', () => {
|
||||
const { socket, connection } = connect();
|
||||
socket.open();
|
||||
|
||||
connection.inputBinary('\x1b[M\xff');
|
||||
expect([...(socket.sent[1] as Uint8Array)]).toEqual([0x1b, 0x5b, 0x4d, 0xff]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import {
|
||||
TERMINAL_PATH,
|
||||
type ClientMessage,
|
||||
type ExitReason,
|
||||
type ServerMessage,
|
||||
type TerminalSize,
|
||||
} from '@homepage/protocol/terminal';
|
||||
|
||||
/** Why a session ended: the server's reason, or what the browser observed. */
|
||||
export type EndReason = ExitReason | 'lost' | 'rejected';
|
||||
|
||||
export type ConnectionEvents = {
|
||||
ready(): void;
|
||||
output(data: Uint8Array): void;
|
||||
ended(reason: EndReason): void;
|
||||
};
|
||||
|
||||
export type SocketFactory = (url: string) => WebSocket;
|
||||
|
||||
export function terminalUrl(location: Pick<Location, 'protocol' | 'host'>): string
|
||||
{
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
|
||||
return `${scheme}://${location.host}${TERMINAL_PATH}`;
|
||||
}
|
||||
|
||||
/** One sandbox session over a WebSocket, from the hello until it ends. */
|
||||
export class TerminalConnection
|
||||
{
|
||||
private readonly socket: WebSocket;
|
||||
private readonly events: ConnectionEvents;
|
||||
private readonly encoder = new TextEncoder();
|
||||
private exitReason?: ExitReason;
|
||||
private opened = false;
|
||||
private ended = false;
|
||||
|
||||
constructor(url: string, size: TerminalSize, events: ConnectionEvents, createSocket: SocketFactory = (target) => new WebSocket(target))
|
||||
{
|
||||
this.events = events;
|
||||
this.socket = createSocket(url);
|
||||
this.socket.binaryType = 'arraybuffer';
|
||||
|
||||
this.socket.onopen = () =>
|
||||
{
|
||||
this.opened = true;
|
||||
this.control({ type: 'hello', ...size });
|
||||
};
|
||||
|
||||
this.socket.onmessage = (event: MessageEvent) =>
|
||||
{
|
||||
if (event.data instanceof ArrayBuffer)
|
||||
{
|
||||
this.events.output(new Uint8Array(event.data));
|
||||
return;
|
||||
}
|
||||
|
||||
const message = JSON.parse(String(event.data)) as ServerMessage;
|
||||
if (message.type === 'ready') this.events.ready();
|
||||
else this.exitReason = message.reason;
|
||||
};
|
||||
|
||||
this.socket.onclose = () =>
|
||||
{
|
||||
if (this.ended) return;
|
||||
this.ended = true;
|
||||
this.events.ended(this.exitReason ?? (this.opened ? 'lost' : 'rejected'));
|
||||
};
|
||||
}
|
||||
|
||||
input(data: string): void {
|
||||
this.send(this.encoder.encode(data));
|
||||
}
|
||||
|
||||
/** Input that xterm reports as binary, one byte per character (mouse reports). */
|
||||
inputBinary(data: string): void {
|
||||
this.send(Uint8Array.from(data, (character) => character.charCodeAt(0) & 0xff));
|
||||
}
|
||||
|
||||
resize(size: TerminalSize): void {
|
||||
this.control({ type: 'resize', ...size });
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.socket.close();
|
||||
}
|
||||
|
||||
private control(message: ClientMessage): void {
|
||||
this.send(JSON.stringify(message));
|
||||
}
|
||||
|
||||
private send(data: string | Uint8Array<ArrayBuffer>): void {
|
||||
if (this.socket.readyState === WebSocket.OPEN) this.socket.send(data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
type Key = {
|
||||
label: string;
|
||||
/** Escape sequence, or a function when it depends on the terminal mode. */
|
||||
sequence: string | ((applicationCursor: boolean) => string);
|
||||
};
|
||||
|
||||
const arrow = (code: string) => (applicationCursor: boolean) => `\x1b${applicationCursor ? 'O' : '['}${code}`;
|
||||
|
||||
const KEYS: Key[] = [
|
||||
{ label: 'tab', sequence: '\t' },
|
||||
{ label: 'esc', sequence: '\x1b' },
|
||||
{ label: 'ctrl-c', sequence: '\x03' },
|
||||
{ label: '↑', sequence: arrow('A') },
|
||||
{ label: '↓', sequence: arrow('B') },
|
||||
{ label: '←', sequence: arrow('D') },
|
||||
{ label: '→', sequence: arrow('C') },
|
||||
{ label: 'ls', sequence: 'ls\r' },
|
||||
{ label: 'cd ..', sequence: 'cd ..\r' },
|
||||
{ label: 'status', sequence: 'status\r' },
|
||||
];
|
||||
|
||||
/** Buttons for keys that phone keyboards lack. They only exist on touch devices. */
|
||||
export function createKeybar(container: HTMLElement, applicationCursor: () => boolean, send: (data: string) => void): void
|
||||
{
|
||||
for (const key of KEYS)
|
||||
{
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.textContent = key.label;
|
||||
|
||||
// Keeps the focus, and with it the on screen keyboard, in the terminal.
|
||||
button.addEventListener('pointerdown', (event) => event.preventDefault());
|
||||
button.addEventListener('click', () =>
|
||||
send(typeof key.sequence === 'string' ? key.sequence : key.sequence(applicationCursor())),
|
||||
);
|
||||
|
||||
container.append(button);
|
||||
}
|
||||
|
||||
container.hidden = false;
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import '@fontsource/jetbrains-mono/400.css';
|
||||
import '@fontsource/jetbrains-mono/700.css';
|
||||
import '@xterm/xterm/css/xterm.css';
|
||||
import './style.css';
|
||||
|
||||
import { FitAddon } from '@xterm/addon-fit';
|
||||
import { WebLinksAddon } from '@xterm/addon-web-links';
|
||||
import { WebglAddon } from '@xterm/addon-webgl';
|
||||
import { Terminal } from '@xterm/xterm';
|
||||
import { CONNECTING_MESSAGE, endMessage, playBoot } from './boot.ts';
|
||||
import { TerminalConnection, terminalUrl } from './connection.ts';
|
||||
import { createKeybar } from './keybar.ts';
|
||||
|
||||
type State = 'booting' | 'idle' | 'connecting' | 'active';
|
||||
|
||||
const touch = window.matchMedia('(pointer: coarse)').matches;
|
||||
const element = document.getElementById('terminal')!;
|
||||
|
||||
const terminal = new Terminal({
|
||||
fontFamily: '"JetBrains Mono", monospace',
|
||||
fontSize: touch ? 13 : 15,
|
||||
cursorBlink: true,
|
||||
scrollback: 5000,
|
||||
theme: {
|
||||
background: '#0b0d10',
|
||||
foreground: '#d6dde6',
|
||||
cursor: '#7ee787',
|
||||
selectionBackground: '#2b3a4a',
|
||||
},
|
||||
});
|
||||
|
||||
// The key bar takes its space before the first fit, so the grid never overflows.
|
||||
if (touch)
|
||||
{
|
||||
createKeybar(document.getElementById('keybar')!, () => terminal.modes.applicationCursorKeysMode, input);
|
||||
element.addEventListener('click', () => { if (state === 'idle') start(); });
|
||||
}
|
||||
|
||||
const fit = new FitAddon();
|
||||
terminal.loadAddon(fit);
|
||||
terminal.loadAddon(new WebLinksAddon());
|
||||
|
||||
// Measuring cells before the font is ready would size the grid wrongly.
|
||||
await Promise.all([document.fonts.load('15px "JetBrains Mono"'), document.fonts.load('bold 15px "JetBrains Mono"')]);
|
||||
terminal.open(element);
|
||||
|
||||
try
|
||||
{
|
||||
const webgl = new WebglAddon();
|
||||
webgl.onContextLoss(() => webgl.dispose());
|
||||
terminal.loadAddon(webgl);
|
||||
}
|
||||
catch { /* The DOM renderer remains as a fallback without WebGL. */ }
|
||||
|
||||
fit.fit();
|
||||
terminal.focus();
|
||||
|
||||
let state: State = 'booting';
|
||||
let connection: TerminalConnection | undefined;
|
||||
|
||||
function start(): void
|
||||
{
|
||||
state = 'connecting';
|
||||
terminal.write(CONNECTING_MESSAGE);
|
||||
|
||||
connection = new TerminalConnection(terminalUrl(window.location), { cols: terminal.cols, rows: terminal.rows }, {
|
||||
ready: () =>
|
||||
{
|
||||
state = 'active';
|
||||
terminal.reset();
|
||||
terminal.focus();
|
||||
},
|
||||
output: (data) => terminal.write(data),
|
||||
ended: (reason) =>
|
||||
{
|
||||
state = 'idle';
|
||||
connection = undefined;
|
||||
terminal.write(endMessage(reason, touch));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function input(data: string): void
|
||||
{
|
||||
if (state === 'active') connection?.input(data);
|
||||
else if (state === 'idle') start();
|
||||
}
|
||||
|
||||
terminal.onData(input);
|
||||
terminal.onBinary((data) => { if (state === 'active') connection?.inputBinary(data); });
|
||||
terminal.onResize(({ cols, rows }) => connection?.resize({ cols, rows }));
|
||||
new ResizeObserver(() => fit.fit()).observe(element);
|
||||
|
||||
await playBoot(terminal, touch);
|
||||
state = 'idle';
|
||||
@@ -0,0 +1,115 @@
|
||||
:root {
|
||||
--background: #0b0d10;
|
||||
--surface: #12161b;
|
||||
--border: #1f262e;
|
||||
--text: #d6dde6;
|
||||
--muted: #7d8794;
|
||||
--accent: #7ee787;
|
||||
|
||||
color-scheme: dark;
|
||||
font-family: "JetBrains Mono", monospace;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
background: var(--background);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bar {
|
||||
display: flex;
|
||||
flex: none;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
padding: 0.35rem 1rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 0.8rem;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.bar .site {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.bar nav {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.bar a {
|
||||
color: var(--muted);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.bar a:hover,
|
||||
.bar a:focus-visible {
|
||||
color: var(--text);
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#terminal {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* The fit addon subtracts padding of the xterm element, not of its container. */
|
||||
#terminal .xterm {
|
||||
height: 100%;
|
||||
padding: 0.5rem 0 0 1rem;
|
||||
}
|
||||
|
||||
.keybar {
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 0.4rem;
|
||||
padding: 0.4rem 1rem calc(0.4rem + env(safe-area-inset-bottom));
|
||||
overflow-x: auto;
|
||||
border-top: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.keybar[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.keybar button {
|
||||
flex: none;
|
||||
min-width: 2.75rem;
|
||||
min-height: 2.25rem;
|
||||
padding: 0 0.6rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0.3rem;
|
||||
background: var(--background);
|
||||
color: var(--text);
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.noscript {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.noscript a {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
#terminal .xterm {
|
||||
padding-left: 0.5rem;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user