Add tests for backend asset handling and frontend boot sequence, remove outdated MOTD script, and add icons.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0ad5b5f44f
commit
7937879ace
34 files changed
+613
-116
No files matched your search
@@ -0,0 +1,21 @@
|
||||
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { readTheme } from './assets.ts';
|
||||
|
||||
describe('readTheme', () => {
|
||||
const base = Buffer.from(':root { --text: white; }');
|
||||
|
||||
it('appends the override, so its rules win', async () => {
|
||||
const file = join(mkdtempSync(join(tmpdir(), 'theme-')), 'theme.css');
|
||||
writeFileSync(file, ':root { --text: red; }');
|
||||
|
||||
expect((await readTheme(base, file))?.toString()).toBe(':root { --text: white; }\n:root { --text: red; }');
|
||||
});
|
||||
|
||||
it('serves the built in theme without an override', async () => {
|
||||
expect(await readTheme(base, '/nonexistent/theme.css')).toBe(base);
|
||||
expect(await readTheme(undefined, '/nonexistent/theme.css')).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { extname, join, relative, sep } from 'node:path';
|
||||
import type { Font } from '@homepage/indexer';
|
||||
|
||||
export type Asset = {
|
||||
body: Buffer;
|
||||
@@ -50,3 +52,24 @@ export function loadAssets(directory: string): Map<string, Asset>
|
||||
if (index) assets.set('/', index);
|
||||
return assets;
|
||||
}
|
||||
|
||||
const FONT = /^\/assets\/jetbrains-mono-latin-(400|700)-normal-[^/]+\.woff2$/;
|
||||
|
||||
/** The Latin JetBrains Mono files of the frontend, so the static pages use the same font. */
|
||||
export function siteFonts(assets: Map<string, Asset>): Font[]
|
||||
{
|
||||
return [...assets.keys()].flatMap((path) =>
|
||||
{
|
||||
const match = FONT.exec(path);
|
||||
return match ? [{ url: path, weight: Number(match[1]) }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The built in theme followed by the optional override, whose rules win because they come later. */
|
||||
export async function readTheme(base: Buffer | undefined, overrideFile: string): Promise<Buffer | undefined>
|
||||
{
|
||||
if (!base) return undefined;
|
||||
|
||||
const override = await readFile(overrideFile).catch(() => undefined);
|
||||
return override ? Buffer.concat([base, Buffer.from('\n'), override]) : base;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { buildIndex, buildSite, reservedNames, type Site } from '@homepage/indexer';
|
||||
import { buildIndex, buildSite, reservedNames, type Font, type Site } from '@homepage/indexer';
|
||||
import type { BackendConfig } from './config.ts';
|
||||
import type { SessionHub } from './hub.ts';
|
||||
import type { Builtin } from './jobs.ts';
|
||||
@@ -11,6 +11,7 @@ export type BuiltinDependencies = {
|
||||
spawner: Pick<Spawner, 'kill'> & { list(): Promise<{ containerId: string; sessionId: string }[]> };
|
||||
started: number;
|
||||
setSite: (site: Site) => void;
|
||||
fonts?: Font[];
|
||||
log: (message: string) => void;
|
||||
};
|
||||
|
||||
@@ -34,7 +35,7 @@ export function createBuiltins(dependencies: BuiltinDependencies): Record<string
|
||||
if (index.hash === lastHash) return;
|
||||
lastHash = index.hash;
|
||||
|
||||
dependencies.setSite(buildSite(index, { siteUrl: config.siteUrl, legal: config.legalPages }));
|
||||
dependencies.setSite(buildSite(index, { siteUrl: config.siteUrl, legal: config.legalPages, fonts: dependencies.fonts }));
|
||||
|
||||
// The same warnings come back on every rebuild, so they are only logged when they change.
|
||||
const warnings = index.warnings.join('\n');
|
||||
|
||||
@@ -9,6 +9,8 @@ export type BackendConfig = {
|
||||
jobsFile: string;
|
||||
/** Directory the jobs service writes triggers for builtin jobs into; empty disables them. */
|
||||
triggerDir: string;
|
||||
/** Optional CSS appended to the theme of the frontend, which overrides its colors. */
|
||||
themeFile: string;
|
||||
/** Absolute URL of the site, for the sitemap. */
|
||||
siteUrl: string;
|
||||
/** Route name to content file, from LEGAL_PAGES like "impressum:impressum.txt". */
|
||||
@@ -62,6 +64,7 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
|
||||
contentDir: env.CONTENT_DIR ?? '/content',
|
||||
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
|
||||
triggerDir: env.TRIGGER_DIR ?? '',
|
||||
themeFile: env.THEME_FILE ?? '/config/theme.css',
|
||||
siteUrl: env.SITE_URL ?? 'https://security-command.org',
|
||||
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum:impressum.txt,datenschutz:datenschutz.txt'),
|
||||
statusDir: env.STATUS_DIR ?? '',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Site } from '@homepage/indexer';
|
||||
import { watchTree, watchTriggers } from '@homepage/jobs';
|
||||
import { SpawnerClient } from '@homepage/protocol';
|
||||
import { loadAssets } from './assets.ts';
|
||||
import { loadAssets, readTheme, siteFonts } from './assets.ts';
|
||||
import { createBuiltins } from './builtins.ts';
|
||||
import { loadConfig } from './config.ts';
|
||||
import { SessionHub } from './hub.ts';
|
||||
@@ -31,6 +31,7 @@ jobs = new BackendJobs(config.jobsFile, createBuiltins({
|
||||
spawner,
|
||||
started: Date.now(),
|
||||
setSite: (next) => { site = next; },
|
||||
fonts: siteFonts(assets),
|
||||
log,
|
||||
}), log);
|
||||
await jobs.start();
|
||||
@@ -57,7 +58,8 @@ async function healthy(): Promise<boolean>
|
||||
return ok;
|
||||
}
|
||||
|
||||
const server = createBackend(config, hub, { assets, healthy, site: () => site });
|
||||
const theme = () => readTheme(assets.get('/theme.css')?.body, config.themeFile);
|
||||
const server = createBackend(config, hub, { assets, healthy, site: () => site, theme });
|
||||
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
|
||||
|
||||
if (config.metricsPort > 0) createMetricsServer(hub).listen(config.metricsPort, config.host);
|
||||
|
||||
@@ -91,6 +91,7 @@ describe('backend', () => {
|
||||
contentDir: '',
|
||||
jobsFile: '',
|
||||
triggerDir: '',
|
||||
themeFile: '',
|
||||
siteUrl: 'https://security-command.org',
|
||||
legalPages: new Map(),
|
||||
statusDir: '',
|
||||
@@ -109,7 +110,7 @@ describe('backend', () => {
|
||||
|
||||
spawner = new FakeSpawner();
|
||||
hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 10_000, log: () => {} });
|
||||
server = createBackend(config, hub, { assets: ASSETS, site: () => SITE });
|
||||
server = createBackend(config, hub, { assets: ASSETS, site: () => SITE, theme: async () => Buffer.from(':root { --text: red; }') });
|
||||
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`;
|
||||
}
|
||||
@@ -421,6 +422,13 @@ describe('backend', () => {
|
||||
expect((await http('/%E0%A4%A')).status).toBe(404);
|
||||
});
|
||||
|
||||
it('serves the theme without caching it', async () => {
|
||||
const response = await http('/theme.css');
|
||||
expect(await response.text()).toBe(':root { --text: red; }');
|
||||
expect(response.headers.get('content-type')).toBe('text/css; charset=utf-8');
|
||||
expect(response.headers.get('cache-control')).toBe('no-cache');
|
||||
});
|
||||
|
||||
it('returns 404 for unknown paths', async () => {
|
||||
expect((await http('/../../etc/passwd')).status).toBe(404);
|
||||
expect((await http('/nothing')).status).toBe(404);
|
||||
|
||||
@@ -14,9 +14,12 @@ export type BackendOptions = {
|
||||
healthy?: () => Promise<boolean>;
|
||||
/** The static site of the content, rebuilt by the index job. */
|
||||
site?: () => Site | undefined;
|
||||
/** The theme with its override, read on every request so edits apply right away. */
|
||||
theme?: () => Promise<Buffer | undefined>;
|
||||
};
|
||||
|
||||
const MAX_FRAME_BYTES = 64 * 1024;
|
||||
const THEME_PATH = '/theme.css';
|
||||
const PING_INTERVAL_MS = 30_000;
|
||||
|
||||
// xterm.js creates style elements at runtime, so styles need 'unsafe-inline'.
|
||||
@@ -80,6 +83,9 @@ export function createBackend(config: BackendConfig, hub: SessionHub, options: B
|
||||
return send(response, ok ? 200 : 503, 'text/plain', ok ? 'ok' : 'degraded', { 'Cache-Control': 'no-store' }, head);
|
||||
}
|
||||
|
||||
const theme = path === THEME_PATH ? await options.theme?.() : undefined;
|
||||
if (theme) return send(response, 200, 'text/css; charset=utf-8', theme, { 'Cache-Control': 'no-cache' }, head);
|
||||
|
||||
const asset = assets.get(path);
|
||||
if (asset)
|
||||
{
|
||||
|
||||
@@ -6,6 +6,10 @@
|
||||
<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>
|
||||
<link rel="icon" href="/favicon.ico" sizes="48x48" />
|
||||
<link rel="icon" href="/icon-192.png" sizes="192x192" type="image/png" />
|
||||
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||
<link rel="stylesheet" href="/theme.css" />
|
||||
</head>
|
||||
<body>
|
||||
<header class="bar">
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 27 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 9.1 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 42 KiB |
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* Colors of the terminal and the static pages, taken from the Security Command
|
||||
* Gitea theme. On the server, config/theme.css is appended to this file, so an
|
||||
* override only needs the variables it changes. Most variables fall back to
|
||||
* the names Gitea themes use, so the :root block of a Gitea theme works as an
|
||||
* override as well.
|
||||
*/
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
|
||||
--background: var(--color-body, #060404);
|
||||
--surface: var(--color-box-header, #120e0e);
|
||||
--border: var(--color-light-border, #2a2223);
|
||||
--text: var(--color-text, #e6dfdf);
|
||||
--muted: var(--color-text-light-2, #948787);
|
||||
--accent: var(--color-primary, #d24654);
|
||||
--warning: var(--color-warning-text, #db6b76);
|
||||
--cursor: var(--color-primary, #d24654);
|
||||
--selection: var(--color-primary-alpha-50, #d2465480);
|
||||
|
||||
/* The two colors of the emblem on the boot screen, as in the favicon. */
|
||||
--logo-primary: #771f2f;
|
||||
--logo-secondary: #5c5555;
|
||||
|
||||
/* The 16 terminal colors. */
|
||||
--ansi-black: var(--color-ansi-black, #202225);
|
||||
--ansi-red: var(--color-ansi-red, #cc4848);
|
||||
--ansi-green: var(--color-ansi-green, #87ab63);
|
||||
--ansi-yellow: var(--color-ansi-yellow, #cc9903);
|
||||
--ansi-blue: var(--color-ansi-blue, #3a8ac6);
|
||||
--ansi-magenta: var(--color-ansi-magenta, #d22e8b);
|
||||
--ansi-cyan: var(--color-ansi-cyan, #00918a);
|
||||
--ansi-white: var(--color-ansi-white, #c1c3c8);
|
||||
--ansi-bright-black: var(--color-ansi-bright-black, #45484e);
|
||||
--ansi-bright-red: var(--color-ansi-bright-red, #d15a5a);
|
||||
--ansi-bright-green: var(--color-ansi-bright-green, #93b373);
|
||||
--ansi-bright-yellow: var(--color-ansi-bright-yellow, #eaaf03);
|
||||
--ansi-bright-blue: var(--color-ansi-bright-blue, #4e96cc);
|
||||
--ansi-bright-magenta: var(--color-ansi-bright-magenta, #d74397);
|
||||
--ansi-bright-cyan: var(--color-ansi-bright-cyan, #00b6ad);
|
||||
--ansi-bright-white: var(--color-ansi-bright-white, #f8f8f8);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { fetchLines, type BootColors } from './boot.ts';
|
||||
import { LOGO } from './logo.ts';
|
||||
|
||||
const COLORS: BootColors = { primary: [119, 31, 47], secondary: [92, 85, 85], accent: [210, 70, 84] };
|
||||
|
||||
const plain = (line: string) => line.replace(/\x1b\[[0-9;]*m/g, '');
|
||||
const width = (lines: string[]) => Math.max(...lines.map((line) => plain(line).length));
|
||||
|
||||
describe('fetchLines', () => {
|
||||
it('puts the emblem next to the facts when there is room', () => {
|
||||
const lines = fetchLines(100, COLORS);
|
||||
|
||||
expect(lines).toHaveLength(LOGO.length / 2);
|
||||
expect(lines.some((line) => /▀.*Kernel/.test(plain(line)))).toBe(true);
|
||||
expect(width(lines)).toBeLessThanOrEqual(100);
|
||||
});
|
||||
|
||||
it('draws the emblem in the colors of the theme', () => {
|
||||
const line = fetchLines(100, COLORS).join('');
|
||||
|
||||
expect(line).toContain('\x1b[38;2;119;31;47m');
|
||||
expect(line).toContain('\x1b[38;2;92;85;85m');
|
||||
expect(line).toContain('\x1b[1m\x1b[38;2;210;70;84mguest@security-command');
|
||||
});
|
||||
|
||||
it('stacks the emblem above the facts on narrow screens and drops it on tiny ones', () => {
|
||||
const narrow = fetchLines(40, COLORS);
|
||||
expect(plain(narrow[LOGO.length / 2 + 1]!)).toBe('guest@security-command');
|
||||
expect(width(narrow)).toBeLessThanOrEqual(40);
|
||||
|
||||
const tiny = fetchLines(30, COLORS);
|
||||
expect(plain(tiny[0]!)).toBe('guest@security-command');
|
||||
expect(tiny.some((line) => /[\u2580\u2584\u2588]/.test(line))).toBe(false);
|
||||
});
|
||||
});
|
||||
+88
-44
@@ -1,63 +1,111 @@
|
||||
import type { Terminal } from '@xterm/xterm';
|
||||
import type { EndReason } from './connection.ts';
|
||||
import { LOGO } from './logo.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',
|
||||
export type Rgb = [number, number, number];
|
||||
|
||||
/** Colors of the overview, taken from theme.css. */
|
||||
export type BootColors = {
|
||||
/** The red of the emblem. */
|
||||
primary: Rgb;
|
||||
/** The grey of the emblem. */
|
||||
secondary: Rgb;
|
||||
/** Name and keys of the facts. */
|
||||
accent: Rgb;
|
||||
};
|
||||
|
||||
const USER = 'guest@security-command';
|
||||
|
||||
/** Facts about every sandbox. The limits match the fixed flags of the spawner. */
|
||||
const FACTS: [string, string][] = [
|
||||
['OS', 'Debian 13 (trixie)'],
|
||||
['Kernel', 'gVisor, in user space'],
|
||||
['Shell', 'bash'],
|
||||
['Network', 'none'],
|
||||
['Rootfs', 'read only'],
|
||||
['Memory', '80 MiB'],
|
||||
['CPU', '0.5 cores'],
|
||||
['Isolation', 'one container per visitor'],
|
||||
];
|
||||
|
||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const KEY_WIDTH = Math.max(...FACTS.map(([key]) => key.length)) + 2;
|
||||
const INFO_WIDTH = Math.max(USER.length, ...FACTS.map(([, value]) => KEY_WIDTH + value.length));
|
||||
const LOGO_WIDTH = LOGO[0]!.length;
|
||||
const LOGO_GAP = 3;
|
||||
const PALETTE = [40, 41, 42, 43, 44, 45, 46, 47].map((color) => `\x1b[${color}m `).join('') + RESET;
|
||||
|
||||
/** Terminals need carriage returns; plain text files only have line feeds. */
|
||||
function toTerminal(text: string): string {
|
||||
return text.replace(/\r?\n/g, '\r\n');
|
||||
}
|
||||
const foreground = ([r, g, b]: Rgb) => `\x1b[38;2;${r};${g};${b}m`;
|
||||
const background = ([r, g, b]: Rgb) => `\x1b[48;2;${r};${g};${b}m`;
|
||||
|
||||
async function fetchMotd(): Promise<string | undefined>
|
||||
/** Draws two pixel rows per terminal row with half blocks, using the upper half for the top pixel. */
|
||||
function logoLines(colors: BootColors): string[]
|
||||
{
|
||||
try
|
||||
const color = (pixel: string) => (pixel === 'r' ? colors.primary : colors.secondary);
|
||||
const cell = (top: string, bottom: string) =>
|
||||
{
|
||||
const response = await fetch('/raw/motd');
|
||||
return response.ok ? await response.text() : undefined;
|
||||
if (top === ' ' && bottom === ' ') return '\x1b[0m ';
|
||||
if (top === bottom) return `\x1b[49m${foreground(color(top))}\u2588`;
|
||||
if (bottom === ' ') return `\x1b[49m${foreground(color(top))}\u2580`;
|
||||
if (top === ' ') return `\x1b[49m${foreground(color(bottom))}\u2584`;
|
||||
return `${foreground(color(top))}${background(color(bottom))}\u2580`;
|
||||
};
|
||||
|
||||
const lines: string[] = [];
|
||||
for (let row = 0; row < LOGO.length; row += 2)
|
||||
{
|
||||
const top = LOGO[row]!;
|
||||
const bottom = LOGO[row + 1] ?? '';
|
||||
lines.push([...top].map((pixel, column) => cell(pixel, bottom[column] ?? ' ')).join('') + RESET);
|
||||
}
|
||||
catch { return undefined; }
|
||||
return lines;
|
||||
}
|
||||
|
||||
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>
|
||||
/**
|
||||
* Lines of the fastfetch style overview: the emblem next to the facts, above
|
||||
* them on narrow screens, and left out where even that does not fit.
|
||||
*/
|
||||
export function fetchLines(cols: number, colors: BootColors): string[]
|
||||
{
|
||||
const motd = fetchMotd();
|
||||
const accent = `${BOLD}${foreground(colors.accent)}`;
|
||||
const info = [
|
||||
`${accent}${USER}${RESET}`,
|
||||
'-'.repeat(USER.length),
|
||||
...FACTS.map(([key, value]) => `${accent}${key.padEnd(KEY_WIDTH)}${RESET}${value}`),
|
||||
'',
|
||||
PALETTE,
|
||||
];
|
||||
|
||||
terminal.writeln(`${BOLD}security-command.org${RESET} ${DIM}terminal${RESET}`);
|
||||
terminal.writeln('');
|
||||
if (cols < LOGO_WIDTH) return info;
|
||||
|
||||
for (const check of CHECKS)
|
||||
const logo = logoLines(colors);
|
||||
if (cols < LOGO_WIDTH + LOGO_GAP + INFO_WIDTH) return [...logo, '', ...info];
|
||||
|
||||
// The facts sit in the middle of the emblem's height.
|
||||
const offset = Math.max(0, Math.floor((logo.length - info.length) / 2));
|
||||
return Array.from({ length: Math.max(logo.length, offset + info.length) }, (_, row) =>
|
||||
{
|
||||
await sleep(120);
|
||||
terminal.writeln(`${DIM}[${RESET}${GREEN} ok ${RESET}${DIM}]${RESET} ${check}`);
|
||||
}
|
||||
const left = logo[row] ?? ' '.repeat(LOGO_WIDTH);
|
||||
return `${left}${' '.repeat(LOGO_GAP)}${info[row - offset] ?? ''}`;
|
||||
});
|
||||
}
|
||||
|
||||
const text = await motd;
|
||||
if (text)
|
||||
{
|
||||
terminal.writeln('');
|
||||
terminal.write(toTerminal(text.trimEnd()));
|
||||
terminal.writeln('');
|
||||
}
|
||||
/** Any key or tap boots the sandbox. */
|
||||
const START_PROMPT = `${BOLD}...${RESET}`;
|
||||
|
||||
terminal.writeln('');
|
||||
terminal.write(startPrompt(touch));
|
||||
/**
|
||||
* xterm.js hides the cursor until the first focus or key press. Leaving the
|
||||
* alternate screen while on the normal one changes nothing else but shows it.
|
||||
*/
|
||||
const SHOW_CURSOR = '\x1b[?47l';
|
||||
|
||||
/** Shows the local boot screen. Nothing reaches the server until the visitor interacts. */
|
||||
export function showBoot(terminal: Terminal, colors: BootColors): void
|
||||
{
|
||||
terminal.write(`${SHOW_CURSOR}\r\n${fetchLines(terminal.cols, colors).join('\r\n')}\r\n\r\n${START_PROMPT}`);
|
||||
}
|
||||
|
||||
const END_MESSAGES: Record<EndReason, string> = {
|
||||
@@ -71,12 +119,8 @@ const END_MESSAGES: Record<EndReason, string> = {
|
||||
busy: 'all sandboxes and the queue are taken, try again in a few minutes',
|
||||
};
|
||||
|
||||
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 function solvingMessage(difficulty: number): string {
|
||||
return `\r\x1b[2K${DIM}solving a proof of work puzzle against abuse (${difficulty} bits)...${RESET}`;
|
||||
export function endMessage(reason: EndReason): string {
|
||||
return `\r\n${DIM}[${END_MESSAGES[reason]}]${RESET}\r\n${START_PROMPT}`;
|
||||
}
|
||||
|
||||
/** Rewrites the current line, so position updates do not pile up. */
|
||||
|
||||
@@ -32,7 +32,6 @@ function connect(token?: string)
|
||||
{
|
||||
const socket = new FakeSocket();
|
||||
const events = {
|
||||
solving: [] as number[],
|
||||
queued: [] as number[],
|
||||
ready: [] as Ready[],
|
||||
output: [] as string[],
|
||||
@@ -41,7 +40,6 @@ function connect(token?: string)
|
||||
};
|
||||
|
||||
const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, token, {
|
||||
solving: (difficulty) => events.solving.push(difficulty),
|
||||
queued: (position) => events.queued.push(position),
|
||||
ready: (session) => events.ready.push(session),
|
||||
output: (data) => events.output.push(new TextDecoder().decode(data)),
|
||||
@@ -71,7 +69,6 @@ describe('TerminalConnection', () => {
|
||||
connection.resize({ cols: 100, rows: 30 });
|
||||
await Promise.resolve();
|
||||
|
||||
expect(events.solving).toEqual([20]);
|
||||
expect(socket.sent.at(-1)).toBe('{"type":"hello","nonce":3020,"cols":100,"rows":30}');
|
||||
});
|
||||
|
||||
@@ -94,7 +91,6 @@ describe('TerminalConnection', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
expect(socket.sent).toEqual([`{"type":"resume","token":"${'A'.repeat(22)}","cols":80,"rows":24}`]);
|
||||
expect(events.solving).toEqual([]);
|
||||
});
|
||||
|
||||
it('passes queue positions, readiness, output and idle warnings on', () => {
|
||||
|
||||
@@ -14,12 +14,11 @@ export type EndReason = ExitReason | RefusalReason | 'lost' | 'rejected';
|
||||
export type Ready = { token: string; expiresAt: number; resumed: boolean };
|
||||
|
||||
export type ConnectionEvents = {
|
||||
solving(difficulty: number): void;
|
||||
queued(position: number): void;
|
||||
ready(session: Ready): void;
|
||||
output(data: Uint8Array): void;
|
||||
idle(secondsLeft: number): void;
|
||||
ended(reason: EndReason): void;
|
||||
queued(position: number): void;
|
||||
ready(session: Ready): void;
|
||||
output(data: Uint8Array): void;
|
||||
idle(secondsLeft: number): void;
|
||||
ended(reason: EndReason): void;
|
||||
};
|
||||
|
||||
export type SocketFactory = (url: string) => WebSocket;
|
||||
@@ -130,7 +129,6 @@ export class TerminalConnection
|
||||
|
||||
private greet(challenge: string, difficulty: number): void
|
||||
{
|
||||
this.events.solving(difficulty);
|
||||
this.solve(challenge, difficulty).then(
|
||||
(nonce) => this.control({ type: 'hello', nonce, ...this.size }),
|
||||
() => this.socket.close(),
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* The emblem of the favicon at 35 by 34 pixels: r is its red, g its grey and
|
||||
* a space the background. Two pixel rows share one terminal row.
|
||||
*/
|
||||
export const LOGO = [
|
||||
' rrrrrrrrrrrr ',
|
||||
' rrrrrrr rrrrrrr ',
|
||||
' rrrr rrrr ',
|
||||
' rrr rrr ',
|
||||
' rrr g g rrr ',
|
||||
' rrr g g rr ',
|
||||
' rr gg ggggggggggg rr ',
|
||||
' rrr gg gggggggggg gg rrr ',
|
||||
' rr gg gggggggg gg rr ',
|
||||
' rr gggg r gggggg r gggg rr ',
|
||||
' rr gggg rr gggg g r gggg rr ',
|
||||
' rr gg r gg r gg rr',
|
||||
' rr g g rr rrr g g rr',
|
||||
' rr rg g rrrr rr rrrr g gr rr',
|
||||
' rr r rr rrrrrrrrrrrrrrrrrr rr r rr',
|
||||
' rrr rrr g rrrrrrrrr rr g rrr rrr',
|
||||
' r rrrrrr grrrrrrrrrrrrrrg rrrrrr r',
|
||||
' r rr rrrrrrrrrrrrrrrrrrrr rr r',
|
||||
' rr g gg rrrrr rrrr rrrrr gg g rr',
|
||||
' rr gg gg rrrrrr rr rrrrrr gg gg rr',
|
||||
' rr gg gg rrrrrr rrrrrr gg g rr',
|
||||
' rr gg gg rrrrrrrrrrrr gg g rr',
|
||||
' rr gggggg rrrrrrrrrr ggggg rr',
|
||||
' rr gg gg r r gg gg rr ',
|
||||
' rr gggg ggg r r ggg ggg rr ',
|
||||
' rr ggg ggg rr ',
|
||||
' rrr g gg gg gg rrr ',
|
||||
' rr gg g gg g rr ',
|
||||
' rr gggg ggggg rr ',
|
||||
' rrr gg g rrr ',
|
||||
' rrr rrr ',
|
||||
' rrrr rrrr ',
|
||||
' rrrrrr rrrrrrr ',
|
||||
' rrrrrrrrrrrr ',
|
||||
];
|
||||
+14
-18
@@ -7,9 +7,10 @@ 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, queueMessage, solvingMessage } from './boot.ts';
|
||||
import { CONNECTING_MESSAGE, endMessage, queueMessage, showBoot } from './boot.ts';
|
||||
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
|
||||
import { createKeybar } from './keybar.ts';
|
||||
import { bootColors, terminalTheme } from './theme.ts';
|
||||
import { savedToken } from './token.ts';
|
||||
|
||||
type State = 'booting' | 'idle' | 'connecting' | 'active' | 'reconnecting';
|
||||
@@ -22,17 +23,14 @@ const touch = window.matchMedia('(pointer: coarse)').matches;
|
||||
const element = document.getElementById('terminal')!;
|
||||
const notice = document.getElementById('notice')!;
|
||||
|
||||
// The cursor stays a solid block without focus, so the prompt never looks inert.
|
||||
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',
|
||||
},
|
||||
fontFamily: '"JetBrains Mono", monospace',
|
||||
fontSize: touch ? 13 : 15,
|
||||
cursorBlink: true,
|
||||
cursorInactiveStyle: 'block',
|
||||
scrollback: 5000,
|
||||
theme: terminalTheme(),
|
||||
});
|
||||
|
||||
// The key bar takes its space before the first fit, so the grid never overflows.
|
||||
@@ -87,7 +85,6 @@ function size() {
|
||||
function connect(token?: string, redraw = false): void
|
||||
{
|
||||
connection = new TerminalConnection(terminalUrl(window.location), size(), token, {
|
||||
solving: (difficulty) => terminal.write(solvingMessage(difficulty)),
|
||||
queued: (position) => terminal.write(queueMessage(position)),
|
||||
ready: (session: Ready) =>
|
||||
{
|
||||
@@ -123,12 +120,12 @@ function ended(reason: EndReason): void
|
||||
|
||||
if (state === 'booting')
|
||||
{
|
||||
void boot();
|
||||
boot();
|
||||
return;
|
||||
}
|
||||
|
||||
state = 'idle';
|
||||
terminal.write(endMessage(reason, touch));
|
||||
terminal.write(endMessage(reason));
|
||||
}
|
||||
|
||||
function reconnect(): void
|
||||
@@ -169,10 +166,9 @@ function input(data: string): void
|
||||
else if (state === 'idle') start();
|
||||
}
|
||||
|
||||
async function boot(): Promise<void>
|
||||
function boot(): void
|
||||
{
|
||||
state = 'booting';
|
||||
await playBoot(terminal, touch);
|
||||
showBoot(terminal, bootColors());
|
||||
state = 'idle';
|
||||
}
|
||||
|
||||
@@ -184,4 +180,4 @@ new ResizeObserver(() => fit.fit()).observe(element);
|
||||
// A reload within the grace period picks the running sandbox up again.
|
||||
const token = savedToken.get();
|
||||
if (token) connect(token, true);
|
||||
else void boot();
|
||||
else boot();
|
||||
@@ -1,13 +1,5 @@
|
||||
/* Colors come from /theme.css. */
|
||||
:root {
|
||||
--background: #0b0d10;
|
||||
--surface: #12161b;
|
||||
--border: #1f262e;
|
||||
--text: #d6dde6;
|
||||
--muted: #7d8794;
|
||||
--accent: #7ee787;
|
||||
--warning: #e3b341;
|
||||
|
||||
color-scheme: dark;
|
||||
font-family: "JetBrains Mono", monospace;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { ITheme } from '@xterm/xterm';
|
||||
import type { BootColors, Rgb } from './boot.ts';
|
||||
|
||||
const COLORS = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] as const;
|
||||
|
||||
/** Reads a variable of theme.css, which loads before this script runs. */
|
||||
function variable(name: string): string {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim();
|
||||
}
|
||||
|
||||
/** Resolves any CSS color through the browser, so the theme may use every color syntax. */
|
||||
function rgb(value: string, fallback: Rgb): Rgb
|
||||
{
|
||||
const probe = document.createElement('span');
|
||||
probe.style.color = value;
|
||||
if (!probe.style.color) return fallback;
|
||||
|
||||
document.body.append(probe);
|
||||
const channels = getComputedStyle(probe).color.match(/\d+(\.\d+)?/g)?.slice(0, 3).map(Number);
|
||||
probe.remove();
|
||||
return channels?.length === 3 ? (channels as Rgb) : fallback;
|
||||
}
|
||||
|
||||
export function terminalTheme(): ITheme
|
||||
{
|
||||
const theme: Record<string, string> = {
|
||||
background: variable('background'),
|
||||
foreground: variable('text'),
|
||||
cursor: variable('cursor'),
|
||||
cursorAccent: variable('background'),
|
||||
selectionBackground: variable('selection'),
|
||||
};
|
||||
|
||||
for (const color of COLORS)
|
||||
{
|
||||
theme[color] = variable(`ansi-${color}`);
|
||||
theme[`bright${color[0]!.toUpperCase()}${color.slice(1)}`] = variable(`ansi-bright-${color}`);
|
||||
}
|
||||
|
||||
// Missing variables keep the defaults of xterm.js.
|
||||
return Object.fromEntries(Object.entries(theme).filter(([, value]) => value !== ''));
|
||||
}
|
||||
|
||||
export function bootColors(): BootColors
|
||||
{
|
||||
return {
|
||||
primary: rgb(variable('logo-primary'), [119, 31, 47]),
|
||||
secondary: rgb(variable('logo-secondary'), [92, 85, 85]),
|
||||
accent: rgb(variable('accent'), [210, 70, 84]),
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@ export default defineConfig({
|
||||
'/ls': backend,
|
||||
'/impressum': backend,
|
||||
'/datenschutz': backend,
|
||||
'/theme.css': backend,
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -35,7 +35,7 @@ describe('containerSpec', () => {
|
||||
});
|
||||
|
||||
it('mounts host paths read only', () => {
|
||||
expect(host.Binds).toEqual(['/srv/content:/srv/www:ro', '/srv/status:/var/status:ro']);
|
||||
expect(host.Binds).toEqual(['/srv/content:/home/guest:ro', '/srv/status:/var/status:ro']);
|
||||
expect(Object.values(host.Tmpfs).every((options) => options.includes('noexec'))).toBe(true);
|
||||
});
|
||||
|
||||
|
||||
@@ -37,11 +37,9 @@ export function containerSpec(config: SpawnerConfig, sessionId: string, expiresA
|
||||
NanoCpus: 500_000_000,
|
||||
PidsLimit: 50,
|
||||
Ulimits: [{ Name: 'nofile', Soft: 256, Hard: 256 }],
|
||||
Tmpfs: {
|
||||
'/home/guest': 'size=8m,mode=1777,noexec,nosuid',
|
||||
'/tmp': 'size=8m,noexec,nosuid',
|
||||
},
|
||||
Binds: [`${config.contentDir}:/srv/www:ro`, `${config.statusDir}:/var/status:ro`],
|
||||
// The content is the read only home directory, so /tmp is the only writable place.
|
||||
Tmpfs: { '/tmp': 'size=8m,noexec,nosuid' },
|
||||
Binds: [`${config.contentDir}:/home/guest:ro`, `${config.statusDir}:/var/status:ro`],
|
||||
LogConfig: { Type: 'none', Config: {} },
|
||||
AutoRemove: true,
|
||||
},
|
||||
@@ -91,7 +89,7 @@ export class SandboxManager {
|
||||
return created.Id;
|
||||
}
|
||||
|
||||
/** Attaches before starting, so the motd and first prompt are not lost. */
|
||||
/** Attaches before starting, so the first prompt is not lost. */
|
||||
async attach(containerId: string): Promise<Socket>
|
||||
{
|
||||
const container = await this.managed(containerId);
|
||||
|
||||
Reference in new issue
Block a user