From b841c2d1f6b201043e111d5975c5aaa23cae3631 Mon Sep 17 00:00:00 2001 From: Overlord Date: Tue, 13 Oct 2026 10:36:23 +0200 Subject: [PATCH] Add frontend app with terminal UI, sandbox integration, and asset handling. Co-Authored-By: Claude Opus 5.5 --- apps/backend/Dockerfile | 3 +- apps/backend/src/assets.ts | 52 ++++++++++++ apps/backend/src/config.ts | 2 + apps/backend/src/main.ts | 6 +- apps/backend/src/server.test.ts | 38 ++++++++- apps/backend/src/server.ts | 43 ++++++++-- apps/frontend/index.html | 26 ++++++ apps/frontend/package.json | 20 +++++ apps/frontend/src/boot.ts | 75 +++++++++++++++++ apps/frontend/src/connection.test.ts | 99 +++++++++++++++++++++++ apps/frontend/src/connection.ts | 93 ++++++++++++++++++++++ apps/frontend/src/keybar.ts | 41 ++++++++++ apps/frontend/src/main.ts | 95 ++++++++++++++++++++++ apps/frontend/src/style.css | 115 +++++++++++++++++++++++++++ apps/frontend/tsconfig.json | 18 +++++ apps/frontend/vite.config.ts | 19 +++++ package.json | 2 +- pnpm-lock.yaml | 50 ++++++++++++ tsconfig.json | 16 +++- 19 files changed, 800 insertions(+), 13 deletions(-) create mode 100644 apps/backend/src/assets.ts create mode 100644 apps/frontend/index.html create mode 100644 apps/frontend/package.json create mode 100644 apps/frontend/src/boot.ts create mode 100644 apps/frontend/src/connection.test.ts create mode 100644 apps/frontend/src/connection.ts create mode 100644 apps/frontend/src/keybar.ts create mode 100644 apps/frontend/src/main.ts create mode 100644 apps/frontend/src/style.css create mode 100644 apps/frontend/tsconfig.json create mode 100644 apps/frontend/vite.config.ts diff --git a/apps/backend/Dockerfile b/apps/backend/Dockerfile index 72f3f77..00424fa 100644 --- a/apps/backend/Dockerfile +++ b/apps/backend/Dockerfile @@ -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"] diff --git a/apps/backend/src/assets.ts b/apps/backend/src/assets.ts new file mode 100644 index 0000000..c6b1178 --- /dev/null +++ b/apps/backend/src/assets.ts @@ -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 = { + '.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 +{ + const assets = new Map(); + 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; +} diff --git a/apps/backend/src/config.ts b/apps/backend/src/config.ts index 62c0e3f..fd2332a 100644 --- a/apps/backend/src/config.ts +++ b/apps/backend/src/config.ts @@ -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), diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts index d51d87b..295ed8a 100644 --- a/apps/backend/src/main.ts +++ b/apps/backend/src/main.ts @@ -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) diff --git a/apps/backend/src/server.test.ts b/apps/backend/src/server.test.ts index 1a542e8..a086bf8 100644 --- a/apps/backend/src/server.test.ts +++ b/apps/backend/src/server.test.ts @@ -10,6 +10,10 @@ import type { Spawner } from './session.ts'; const CONTAINER = 'aaaaaaaaaaaa'; +const INDEX = { body: Buffer.from(''), 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((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(''); + 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); + }); + }); }); diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts index 182c727..2c62f8f 100644 --- a/apps/backend/src/server.ts +++ b/apps/backend/src/server.ts @@ -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 = {}, 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()): 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 }); diff --git a/apps/frontend/index.html b/apps/frontend/index.html new file mode 100644 index 0000000..d8522ce --- /dev/null +++ b/apps/frontend/index.html @@ -0,0 +1,26 @@ + + + + + + + + security-command.org + + +
+ security-command.org + +
+
+ + + + + diff --git a/apps/frontend/package.json b/apps/frontend/package.json new file mode 100644 index 0000000..8a29db9 --- /dev/null +++ b/apps/frontend/package.json @@ -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" + } +} diff --git a/apps/frontend/src/boot.ts b/apps/frontend/src/boot.ts new file mode 100644 index 0000000..cab2204 --- /dev/null +++ b/apps/frontend/src/boot.ts @@ -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 +{ + 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 +{ + 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 = { + 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}`; diff --git a/apps/frontend/src/connection.test.ts b/apps/frontend/src/connection.test.ts new file mode 100644 index 0000000..41f0450 --- /dev/null +++ b/apps/frontend/src/connection.test.ts @@ -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]); + }); +}); diff --git a/apps/frontend/src/connection.ts b/apps/frontend/src/connection.ts new file mode 100644 index 0000000..bb17541 --- /dev/null +++ b/apps/frontend/src/connection.ts @@ -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): 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): void { + if (this.socket.readyState === WebSocket.OPEN) this.socket.send(data); + } +} diff --git a/apps/frontend/src/keybar.ts b/apps/frontend/src/keybar.ts new file mode 100644 index 0000000..7566cfc --- /dev/null +++ b/apps/frontend/src/keybar.ts @@ -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; +} diff --git a/apps/frontend/src/main.ts b/apps/frontend/src/main.ts new file mode 100644 index 0000000..9b7b835 --- /dev/null +++ b/apps/frontend/src/main.ts @@ -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'; diff --git a/apps/frontend/src/style.css b/apps/frontend/src/style.css new file mode 100644 index 0000000..526b611 --- /dev/null +++ b/apps/frontend/src/style.css @@ -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; + } +} diff --git a/apps/frontend/tsconfig.json b/apps/frontend/tsconfig.json new file mode 100644 index 0000000..c0310b0 --- /dev/null +++ b/apps/frontend/tsconfig.json @@ -0,0 +1,18 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "lib": [ + "es2024", + "dom", + "dom.iterable" + ], + "types": [ + "vite/client" + ] + }, + "include": [ + "src", + "vite.config.ts" + ], + "exclude": [] +} diff --git a/apps/frontend/vite.config.ts b/apps/frontend/vite.config.ts new file mode 100644 index 0000000..a2de64a --- /dev/null +++ b/apps/frontend/vite.config.ts @@ -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, + }, + }, +}); diff --git a/package.json b/package.json index 207aa66..27e01b2 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "node": ">=24" }, "scripts": { - "typecheck": "tsc -p .", + "typecheck": "tsc -p . && tsc -p apps/frontend", "test": "vitest run", "build": "pnpm -r build" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cf79a29..673ddc5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -192,6 +192,31 @@ importers: specifier: ^8.18.2 version: 8.18.2 + apps/frontend: + dependencies: + '@fontsource/jetbrains-mono': + specifier: ^5.3.0 + version: 5.3.0 + '@homepage/protocol': + specifier: workspace:* + version: link:../../packages/protocol + '@xterm/addon-fit': + specifier: ^0.11.0 + version: 0.11.0 + '@xterm/addon-web-links': + specifier: ^0.12.0 + version: 0.12.0 + '@xterm/addon-webgl': + specifier: ^0.19.0 + version: 0.19.0 + '@xterm/xterm': + specifier: ^6.0.0 + version: 6.0.0 + devDependencies: + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@26.6.5)(esbuild@0.28.2) + apps/spawner: dependencies: '@homepage/protocol': @@ -358,6 +383,9 @@ packages: cpu: [x64] os: [win32] + '@fontsource/jetbrains-mono@5.3.0': + resolution: {integrity: sha512-fqDfB5I9f1p1TV486aUgB9t8zP84P0O1FtQR5Ol9vjwPy+S+EIGlVYm1cvj2W5shcZMTg2nZFdVMoH5wFu8a1A==} + '@jridgewell/resolve-uri@3.1.2': resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} engines: {node: '>=6.0.0'} @@ -619,6 +647,18 @@ packages: '@vitest/spy@5.0.3': resolution: {integrity: sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==} + '@xterm/addon-fit@0.11.0': + resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==} + + '@xterm/addon-web-links@0.12.0': + resolution: {integrity: sha512-4Smom3RPyVp7ZMYOYDoC/9eGJJJqYhnPLGGqJ6wOBfB8VxPViJNSKdgRYb8NpaM6YSelEKbA2SStD7lGyqaobw==} + + '@xterm/addon-webgl@0.19.0': + resolution: {integrity: sha512-b3fMOsyLVuCeNJWxolACEUED0vm7qC0cy4wRvf3oURSzDTYVQiGPhTnhWZwIHdvC48Y+oLhvYXnY4XDXPoJo6A==} + + '@xterm/xterm@6.0.0': + resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==} + assertion-error@2.0.1: resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} engines: {node: '>=12'} @@ -970,6 +1010,8 @@ snapshots: '@esbuild/win32-x64@0.28.2': optional: true + '@fontsource/jetbrains-mono@5.3.0': {} + '@jridgewell/resolve-uri@3.1.2': {} '@jridgewell/sourcemap-codec@1.6.0': {} @@ -1116,6 +1158,14 @@ snapshots: '@vitest/spy@5.0.3': {} + '@xterm/addon-fit@0.11.0': {} + + '@xterm/addon-web-links@0.12.0': {} + + '@xterm/addon-webgl@0.19.0': {} + + '@xterm/xterm@6.0.0': {} + assertion-error@2.0.1: {} chai@6.3.0: {} diff --git a/tsconfig.json b/tsconfig.json index 551e614..355ae6d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,8 +3,12 @@ "target": "es2024", "module": "nodenext", "moduleResolution": "nodenext", - "lib": ["es2024"], - "types": ["node"], + "lib": [ + "es2024" + ], + "types": [ + "node" + ], "strict": true, "noUncheckedIndexedAccess": true, "noImplicitOverride": true, @@ -14,5 +18,11 @@ "noEmit": true, "skipLibCheck": true }, - "include": ["apps/*/src", "packages/*/src"] + "include": [ + "apps/*/src", + "packages/*/src" + ], + "exclude": [ + "apps/frontend" + ] }