Simplify boot sequence, remove terminal emblem, and introduce fastfetch script for sandbox login facts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7937879ace
commit
5f3ff481b4
24 files changed
+232
-240
No files matched your search
@@ -5,7 +5,7 @@ import type { WebSocket } from 'ws';
|
||||
import { TokenBucket } from './throttle.ts';
|
||||
|
||||
export type Spawner = {
|
||||
spawn(sessionId: string, expiresAt: number): Promise<string>;
|
||||
spawn(sessionId: string, expiresAt: number, size: TerminalSize): Promise<string>;
|
||||
attach(containerId: string): Promise<Duplex>;
|
||||
resize(containerId: string, cols: number, rows: number): Promise<void>;
|
||||
kill(containerId: string): Promise<void>;
|
||||
@@ -72,7 +72,7 @@ export class Session
|
||||
async start(socket: WebSocket, size: TerminalSize): Promise<void>
|
||||
{
|
||||
this.socket = socket;
|
||||
this.containerId = await this.spawner.spawn(this.id, this.expiresAt);
|
||||
this.containerId = await this.spawner.spawn(this.id, this.expiresAt, size);
|
||||
if (this.ended) return this.release();
|
||||
|
||||
const stream = await this.spawner.attach(this.containerId);
|
||||
|
||||
@@ -18,10 +18,6 @@
|
||||
--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);
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,111 +1,21 @@
|
||||
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 RESET = '\x1b[0m';
|
||||
|
||||
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 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;
|
||||
|
||||
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`;
|
||||
|
||||
/** Draws two pixel rows per terminal row with half blocks, using the upper half for the top pixel. */
|
||||
function logoLines(colors: BootColors): string[]
|
||||
{
|
||||
const color = (pixel: string) => (pixel === 'r' ? colors.primary : colors.secondary);
|
||||
const cell = (top: string, bottom: string) =>
|
||||
{
|
||||
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);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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,
|
||||
];
|
||||
|
||||
if (cols < LOGO_WIDTH) return info;
|
||||
|
||||
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) =>
|
||||
{
|
||||
const left = logo[row] ?? ' '.repeat(LOGO_WIDTH);
|
||||
return `${left}${' '.repeat(LOGO_GAP)}${info[row - offset] ?? ''}`;
|
||||
});
|
||||
}
|
||||
|
||||
/** Any key or tap boots the sandbox. */
|
||||
const START_PROMPT = `${BOLD}...${RESET}`;
|
||||
|
||||
/**
|
||||
* 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}`);
|
||||
/**
|
||||
* The boot screen is only the cursor, which shows that the terminal waits for
|
||||
* a key. Nothing reaches the server until the visitor presses one.
|
||||
*/
|
||||
export function showBoot(terminal: Terminal): void {
|
||||
terminal.write(SHOW_CURSOR);
|
||||
}
|
||||
|
||||
const END_MESSAGES: Record<EndReason, string> = {
|
||||
@@ -120,7 +30,7 @@ const END_MESSAGES: Record<EndReason, string> = {
|
||||
};
|
||||
|
||||
export function endMessage(reason: EndReason): string {
|
||||
return `\r\n${DIM}[${END_MESSAGES[reason]}]${RESET}\r\n${START_PROMPT}`;
|
||||
return `\r\n${DIM}[${END_MESSAGES[reason]}]${RESET}\r\n`;
|
||||
}
|
||||
|
||||
/** Rewrites the current line, so position updates do not pile up. */
|
||||
@@ -128,4 +38,5 @@ export function queueMessage(position: number): string {
|
||||
return `\r\x1b[2K${DIM}the server is limited right now, position ${position} in the queue...${RESET}`;
|
||||
}
|
||||
|
||||
export const CONNECTING_MESSAGE = `\r\n\r\n${DIM}connecting...${RESET}\r\n`;
|
||||
/** Starts where the cursor waits: on the empty boot screen or below the end message. */
|
||||
export const CONNECTING_MESSAGE = `${DIM}connecting...${RESET}\r\n`;
|
||||
@@ -1,40 +0,0 @@
|
||||
/**
|
||||
* 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 ',
|
||||
];
|
||||
@@ -10,7 +10,7 @@ import { Terminal } from '@xterm/xterm';
|
||||
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 { terminalTheme } from './theme.ts';
|
||||
import { savedToken } from './token.ts';
|
||||
|
||||
type State = 'booting' | 'idle' | 'connecting' | 'active' | 'reconnecting';
|
||||
@@ -168,7 +168,7 @@ function input(data: string): void
|
||||
|
||||
function boot(): void
|
||||
{
|
||||
showBoot(terminal, bootColors());
|
||||
showBoot(terminal);
|
||||
state = 'idle';
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ body {
|
||||
border-bottom: 1px solid var(--border);
|
||||
font-size: 0.8rem;
|
||||
color: var(--muted);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.bar .site {
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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;
|
||||
|
||||
@@ -8,19 +7,6 @@ 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> = {
|
||||
@@ -40,12 +26,3 @@ export function terminalTheme(): ITheme
|
||||
// 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,7 +14,8 @@ const client = new SpawnerClient(socketPath);
|
||||
async function run(): Promise<void>
|
||||
{
|
||||
const sessionId = randomBytes(12).toString('base64url');
|
||||
const containerId = await client.spawn(sessionId, Math.floor(Date.now() / 1000) + 20 * 60);
|
||||
const size = { cols: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 };
|
||||
const containerId = await client.spawn(sessionId, Math.floor(Date.now() / 1000) + 20 * 60, size);
|
||||
const stream = await client.attach(containerId);
|
||||
|
||||
const resize = () => client.resize(containerId, process.stdout.columns, process.stdout.rows).catch(() => {});
|
||||
|
||||
@@ -13,7 +13,7 @@ const config: SpawnerConfig = {
|
||||
};
|
||||
|
||||
describe('containerSpec', () => {
|
||||
const spec = containerSpec(config, 'session123', 1_800_000_000);
|
||||
const spec = containerSpec(config, 'session123', 1_800_000_000, { cols: 100, rows: 30 });
|
||||
const host = spec.HostConfig;
|
||||
|
||||
it('isolates the sandbox', () => {
|
||||
@@ -23,7 +23,7 @@ describe('containerSpec', () => {
|
||||
expect(spec.NetworkDisabled).toBe(true);
|
||||
expect(host.CapDrop).toEqual(['ALL']);
|
||||
expect(host.SecurityOpt).toContain('no-new-privileges');
|
||||
expect(spec.User).toBe('guest');
|
||||
expect(spec.User).toBe('agent');
|
||||
});
|
||||
|
||||
it('limits resources', () => {
|
||||
@@ -35,10 +35,14 @@ describe('containerSpec', () => {
|
||||
});
|
||||
|
||||
it('mounts host paths read only', () => {
|
||||
expect(host.Binds).toEqual(['/srv/content:/home/guest:ro', '/srv/status:/var/status:ro']);
|
||||
expect(host.Binds).toEqual(['/srv/content:/home/agent:ro', '/srv/status:/var/status:ro']);
|
||||
expect(Object.values(host.Tmpfs).every((options) => options.includes('noexec'))).toBe(true);
|
||||
});
|
||||
|
||||
it('starts the terminal at the size of the browser', () => {
|
||||
expect(host.ConsoleSize).toEqual([30, 100]);
|
||||
});
|
||||
|
||||
it('passes only the session id and expiry into the container', () => {
|
||||
expect(spec.Env).toEqual(['SESSION_ID=session123', 'SESSION_EXPIRES_AT=1800000000', 'TERM=xterm-256color']);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Socket } from 'node:net';
|
||||
import { SANDBOX_LABEL, SESSION_LABEL, type ManagedContainer } from '@homepage/protocol';
|
||||
import { SANDBOX_LABEL, SESSION_LABEL, type ManagedContainer, type TerminalSize } from '@homepage/protocol';
|
||||
import type { SpawnerConfig } from './config.ts';
|
||||
import { DockerClient, DockerError } from './docker.ts';
|
||||
|
||||
@@ -10,12 +10,12 @@ const MiB = 1024 * 1024;
|
||||
* validated session id and expiry come from outside. It must stay identical
|
||||
* to deploy/host/sandbox-flags.sh.
|
||||
*/
|
||||
export function containerSpec(config: SpawnerConfig, sessionId: string, expiresAt: number)
|
||||
export function containerSpec(config: SpawnerConfig, sessionId: string, expiresAt: number, size: TerminalSize)
|
||||
{
|
||||
return {
|
||||
Image: config.image,
|
||||
User: 'guest',
|
||||
Hostname: 'sandbox',
|
||||
User: 'agent',
|
||||
Hostname: 'security-command',
|
||||
Env: [`SESSION_ID=${sessionId}`, `SESSION_EXPIRES_AT=${expiresAt}`, 'TERM=xterm-256color'],
|
||||
Tty: true,
|
||||
OpenStdin: true,
|
||||
@@ -39,8 +39,9 @@ export function containerSpec(config: SpawnerConfig, sessionId: string, expiresA
|
||||
Ulimits: [{ Name: 'nofile', Soft: 256, Hard: 256 }],
|
||||
// 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`],
|
||||
Binds: [`${config.contentDir}:/home/agent:ro`, `${config.statusDir}:/var/status:ro`],
|
||||
LogConfig: { Type: 'none', Config: {} },
|
||||
ConsoleSize: [size.rows, size.cols],
|
||||
AutoRemove: true,
|
||||
},
|
||||
};
|
||||
@@ -75,7 +76,7 @@ export class SandboxManager {
|
||||
}
|
||||
}
|
||||
|
||||
async spawn(sessionId: string, expiresAt: number): Promise<string>
|
||||
async spawn(sessionId: string, expiresAt: number, size: TerminalSize): Promise<string>
|
||||
{
|
||||
const existing = await this.list();
|
||||
if (existing.length >= this.config.maxSandboxes) throw new Error('sandbox limit reached');
|
||||
@@ -83,7 +84,7 @@ export class SandboxManager {
|
||||
const created = await this.docker.call<{ Id: string }>(
|
||||
'POST',
|
||||
`/containers/create?name=sandbox-${sessionId}`,
|
||||
containerSpec(this.config, sessionId, expiresAt),
|
||||
containerSpec(this.config, sessionId, expiresAt, size),
|
||||
);
|
||||
|
||||
return created.Id;
|
||||
|
||||
@@ -113,7 +113,7 @@ describe('spawner server', () => {
|
||||
});
|
||||
|
||||
it('creates a sandbox with the hardcoded spec', async () => {
|
||||
const containerId = await client.spawn('session123', Math.floor(Date.now() / 1000) + 600);
|
||||
const containerId = await client.spawn('session123', Math.floor(Date.now() / 1000) + 600, { cols: 80, rows: 24 });
|
||||
expect(containerId).toBe('ccccccccccc2');
|
||||
const create = calls.find((call) => call.path === '/containers/create');
|
||||
expect(create?.body).toMatchObject({ Image: 'sandbox@sha256:abc', HostConfig: { NetworkMode: 'none' } });
|
||||
@@ -121,8 +121,8 @@ describe('spawner server', () => {
|
||||
|
||||
it('refuses to spawn beyond the sandbox limit', async () => {
|
||||
const expiresAt = Math.floor(Date.now() / 1000) + 600;
|
||||
await client.spawn('session123', expiresAt);
|
||||
await expect(client.spawn('session456', expiresAt)).rejects.toThrow('sandbox limit reached');
|
||||
await client.spawn('session123', expiresAt, { cols: 80, rows: 24 });
|
||||
await expect(client.spawn('session456', expiresAt, { cols: 80, rows: 24 })).rejects.toThrow('sandbox limit reached');
|
||||
});
|
||||
|
||||
it('attaches before starting and bridges the stream', async () => {
|
||||
|
||||
@@ -40,7 +40,7 @@ async function handle(connection: Socket, manager: SandboxManager, log: Logger):
|
||||
switch (request.op)
|
||||
{
|
||||
case 'spawn': {
|
||||
const containerId = await manager.spawn(request.sessionId, request.expiresAt);
|
||||
const containerId = await manager.spawn(request.sessionId, request.expiresAt, { cols: request.cols, rows: request.rows });
|
||||
log(`spawned ${containerId.slice(0, 12)} for session ${request.sessionId}`);
|
||||
respond(connection, { ok: true, containerId });
|
||||
break;
|
||||
|
||||
Reference in new issue
Block a user