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
@@ -3,10 +3,11 @@ FROM node:24-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY . .
|
||||
RUN corepack pnpm install --frozen-lockfile \
|
||||
&& corepack pnpm --filter @homepage/backend build
|
||||
&& corepack pnpm --filter @homepage/backend --filter @homepage/frontend build
|
||||
|
||||
FROM node:24-alpine
|
||||
COPY --from=build /src/apps/backend/dist/backend.js /app/backend.js
|
||||
COPY --from=build /src/apps/frontend/dist /app/public
|
||||
USER 10002:10002
|
||||
EXPOSE 8080
|
||||
CMD ["node", "/app/backend.js"]
|
||||
@@ -0,0 +1,52 @@
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { extname, join, relative, sep } from 'node:path';
|
||||
|
||||
export type Asset = {
|
||||
body: Buffer;
|
||||
type: string;
|
||||
/** Vite puts a content hash into every file name below assets/. */
|
||||
immutable: boolean;
|
||||
};
|
||||
|
||||
const TYPES: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.ico': 'image/x-icon',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
};
|
||||
|
||||
function walk(directory: string): string[]
|
||||
{
|
||||
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) =>
|
||||
{
|
||||
const path = join(directory, entry.name);
|
||||
if (entry.isDirectory()) return walk(path);
|
||||
return entry.isFile() ? [path] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** Loads the built frontend into memory, keyed by URL path. The index page is also served at "/". */
|
||||
export function loadAssets(directory: string): Map<string, Asset>
|
||||
{
|
||||
const assets = new Map<string, Asset>();
|
||||
if (!existsSync(directory)) return assets;
|
||||
|
||||
for (const file of walk(directory))
|
||||
{
|
||||
const path = `/${relative(directory, file).split(sep).join('/')}`;
|
||||
assets.set(path, {
|
||||
body: readFileSync(file),
|
||||
type: TYPES[extname(file)] ?? 'application/octet-stream',
|
||||
immutable: path.startsWith('/assets/'),
|
||||
});
|
||||
}
|
||||
|
||||
const index = assets.get('/index.html');
|
||||
if (index) assets.set('/', index);
|
||||
return assets;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ export type BackendConfig = {
|
||||
host: string;
|
||||
port: number;
|
||||
spawnerSocket: string;
|
||||
frontendDir: string;
|
||||
/** Exact origins allowed to open terminal sessions. Empty allows every origin. */
|
||||
allowedOrigins: string[];
|
||||
sessionSeconds: number;
|
||||
@@ -21,6 +22,7 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
|
||||
host: env.HOST ?? '0.0.0.0',
|
||||
port: integer(env, 'PORT', 8080),
|
||||
spawnerSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock',
|
||||
frontendDir: env.FRONTEND_DIR ?? '/app/public',
|
||||
allowedOrigins: (env.ALLOWED_ORIGINS ?? '').split(',').map((origin) => origin.trim()).filter(Boolean),
|
||||
sessionSeconds: integer(env, 'SESSION_SECONDS', 20 * 60),
|
||||
outputRate: integer(env, 'OUTPUT_BYTES_PER_SECOND', 1024 * 1024),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { SpawnerClient } from '@homepage/protocol';
|
||||
import { loadAssets } from './assets.ts';
|
||||
import { loadConfig } from './config.ts';
|
||||
import { createBackend } from './server.ts';
|
||||
|
||||
@@ -12,7 +13,10 @@ const orphans = await spawner.list();
|
||||
await Promise.all(orphans.map((container) => spawner.kill(container.containerId)));
|
||||
if (orphans.length > 0) log(`removed ${orphans.length} orphaned sandbox(es)`);
|
||||
|
||||
const server = createBackend(config, spawner, log);
|
||||
const assets = loadAssets(config.frontendDir);
|
||||
if (assets.size === 0) log(`no frontend found in ${config.frontendDir}`);
|
||||
|
||||
const server = createBackend(config, spawner, log, assets);
|
||||
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
|
||||
|
||||
for (const signal of ['SIGTERM', 'SIGINT'] as const)
|
||||
|
||||
@@ -10,6 +10,10 @@ import type { Spawner } from './session.ts';
|
||||
|
||||
const CONTAINER = 'aaaaaaaaaaaa';
|
||||
|
||||
const INDEX = { body: Buffer.from('<!doctype html>'), type: 'text/html; charset=utf-8', immutable: false };
|
||||
const SCRIPT = { body: Buffer.from('console.log(1)'), type: 'text/javascript; charset=utf-8', immutable: true };
|
||||
const ASSETS = new Map([['/', INDEX], ['/index.html', INDEX], ['/assets/index-abc.js', SCRIPT]]);
|
||||
|
||||
/** Hands out one in-memory stream pair per spawn; the far end plays the container. */
|
||||
class FakeSpawner implements Spawner
|
||||
{
|
||||
@@ -66,13 +70,14 @@ describe('backend', () => {
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
spawnerSocket: '',
|
||||
frontendDir: '',
|
||||
allowedOrigins: ['https://security-command.org'],
|
||||
sessionSeconds: 60,
|
||||
outputRate: 1024 * 1024,
|
||||
...overrides,
|
||||
};
|
||||
spawner = new FakeSpawner();
|
||||
server = createBackend(config, spawner, () => {});
|
||||
server = createBackend(config, spawner, () => {}, ASSETS);
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/ws`;
|
||||
}
|
||||
@@ -183,4 +188,35 @@ describe('backend', () => {
|
||||
expect(client.output().length).toBeGreaterThan(0);
|
||||
expect(client.output().length).toBeLessThan(5000);
|
||||
});
|
||||
|
||||
describe('http', () => {
|
||||
const http = (path: string, method = 'GET') => fetch(url.replace('ws://', 'http://').replace('/ws', path), { method });
|
||||
|
||||
it('serves the terminal page with security headers', async () => {
|
||||
const response = await http('/');
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.text()).toBe('<!doctype html>');
|
||||
expect(response.headers.get('cache-control')).toBe('no-cache');
|
||||
expect(response.headers.get('content-security-policy')).toContain("frame-ancestors 'none'");
|
||||
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
|
||||
});
|
||||
|
||||
it('caches hashed assets forever', async () => {
|
||||
const response = await http('/assets/index-abc.js');
|
||||
expect(response.headers.get('cache-control')).toContain('immutable');
|
||||
expect(response.headers.get('content-type')).toContain('text/javascript');
|
||||
});
|
||||
|
||||
it('answers HEAD without a body and refuses other methods', async () => {
|
||||
const head = await http('/', 'HEAD');
|
||||
expect(head.status).toBe(200);
|
||||
expect(await head.text()).toBe('');
|
||||
expect((await http('/', 'POST')).status).toBe(405);
|
||||
});
|
||||
|
||||
it('returns 404 for unknown paths', async () => {
|
||||
expect((await http('/../../etc/passwd')).status).toBe(404);
|
||||
expect((await http('/nothing')).status).toBe(404);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import { createServer, type IncomingMessage, type Server } from 'node:http';
|
||||
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
|
||||
import type { Duplex } from 'node:stream';
|
||||
import { InvalidMessageError, parseClientMessage, TERMINAL_PATH } from '@homepage/protocol/terminal';
|
||||
import { WebSocketServer, type RawData, type WebSocket } from 'ws';
|
||||
import type { Asset } from './assets.ts';
|
||||
import type { BackendConfig } from './config.ts';
|
||||
import { Session, type Spawner } from './session.ts';
|
||||
|
||||
@@ -14,6 +15,29 @@ const PING_INTERVAL_MS = 30_000;
|
||||
/** Close code for protocol violations by the client. */
|
||||
const POLICY_VIOLATION = 1008;
|
||||
|
||||
// xterm.js creates style elements at runtime, so styles need 'unsafe-inline'.
|
||||
const SECURITY_HEADERS = {
|
||||
'Content-Security-Policy': [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
"style-src 'self' 'unsafe-inline'",
|
||||
"img-src 'self' data:",
|
||||
"connect-src 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
"base-uri 'none'",
|
||||
"form-action 'none'",
|
||||
].join('; '),
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
|
||||
};
|
||||
|
||||
function send(response: ServerResponse, status: number, type: string, body: string | Buffer, headers: Record<string, string> = {}, head = false): void
|
||||
{
|
||||
response.writeHead(status, { ...SECURITY_HEADERS, 'Content-Type': type, 'Content-Length': Buffer.byteLength(body), ...headers });
|
||||
response.end(head ? undefined : body);
|
||||
}
|
||||
|
||||
function reject(socket: Duplex, status: number, reason: string): void
|
||||
{
|
||||
socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||
@@ -87,17 +111,24 @@ function handleConnection(socket: WebSocket, spawner: Spawner, config: BackendCo
|
||||
});
|
||||
}
|
||||
|
||||
export function createBackend(config: BackendConfig, spawner: Spawner, log: Logger): Server
|
||||
export function createBackend(config: BackendConfig, spawner: Spawner, log: Logger, assets = new Map<string, Asset>()): Server
|
||||
{
|
||||
const server = createServer((request, response) =>
|
||||
{
|
||||
if (request.method === 'GET' && request.url === '/healthz')
|
||||
const head = request.method === 'HEAD';
|
||||
if (request.method !== 'GET' && !head) return send(response, 405, 'text/plain', 'method not allowed', { Allow: 'GET, HEAD' });
|
||||
|
||||
const path = new URL(request.url ?? '/', 'http://backend').pathname;
|
||||
if (path === '/healthz') return send(response, 200, 'text/plain', 'ok', {}, head);
|
||||
|
||||
const asset = assets.get(path);
|
||||
if (asset)
|
||||
{
|
||||
response.writeHead(200, { 'Content-Type': 'text/plain' }).end('ok');
|
||||
return;
|
||||
const cache = asset.immutable ? 'public, max-age=31536000, immutable' : 'no-cache';
|
||||
return send(response, 200, asset.type, asset.body, { 'Cache-Control': cache }, head);
|
||||
}
|
||||
|
||||
response.writeHead(404, { 'Content-Type': 'text/plain' }).end('not found');
|
||||
send(response, 404, 'text/plain', 'not found', {}, head);
|
||||
});
|
||||
|
||||
const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, interactive-widget=resizes-content" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="description" content="security-command.org: a real Linux shell in a disposable gVisor sandbox." />
|
||||
<title>security-command.org</title>
|
||||
</head>
|
||||
<body>
|
||||
<header class="bar">
|
||||
<span class="site">security-command.org</span>
|
||||
<nav>
|
||||
<a href="/impressum">impressum</a>
|
||||
<span aria-hidden="true">·</span>
|
||||
<a href="/datenschutz">datenschutz</a>
|
||||
</nav>
|
||||
</header>
|
||||
<main id="terminal" aria-label="Terminal"></main>
|
||||
<div id="keybar" class="keybar" hidden></div>
|
||||
<noscript>
|
||||
<p class="noscript">The terminal needs JavaScript. The content is also available as <a href="/ls">plain pages</a>.</p>
|
||||
</noscript>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "@homepage/frontend",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/jetbrains-mono": "^5.3.0",
|
||||
"@homepage/protocol": "workspace:*",
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/addon-web-links": "^0.12.0",
|
||||
"@xterm/addon-webgl": "^0.19.0",
|
||||
"@xterm/xterm": "^6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^8.3.4"
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"es2024",
|
||||
"dom",
|
||||
"dom.iterable"
|
||||
],
|
||||
"types": [
|
||||
"vite/client"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src",
|
||||
"vite.config.ts"
|
||||
],
|
||||
"exclude": []
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { defineConfig } from 'vite';
|
||||
|
||||
const backend = 'http://127.0.0.1:8380';
|
||||
|
||||
export default defineConfig({
|
||||
build: {
|
||||
target: 'es2022',
|
||||
assetsDir: 'assets',
|
||||
},
|
||||
server: {
|
||||
proxy: {
|
||||
'/ws': { target: backend, ws: true },
|
||||
'/raw': backend,
|
||||
'/ls': backend,
|
||||
'/impressum': backend,
|
||||
'/datenschutz': backend,
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user