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
@@ -120,6 +120,10 @@ containers keep the mount of the old one.
|
||||
|
||||
- Startup files such as `.bashrc` in the content are ignored by the
|
||||
sandbox shell, which only reads the configuration in the image.
|
||||
- Executables in `.local/bin` of the content are on the `PATH` ahead of the
|
||||
built in commands, so the content can carry small scripts. The emblem and
|
||||
facts shown at login come from `fastfetch`, which
|
||||
`.local/bin/fastfetch` replaces.
|
||||
|
||||
## Theme
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
# shellcheck disable=SC2034
|
||||
SANDBOX_FLAGS=(
|
||||
--read-only --network none --cap-drop ALL
|
||||
--security-opt no-new-privileges --user guest
|
||||
--security-opt no-new-privileges --user agent
|
||||
--memory 80m --memory-swap 80m --cpus 0.5 --pids-limit 50
|
||||
--ulimit nofile=256:256
|
||||
--tmpfs /tmp:size=8m,noexec,nosuid
|
||||
--log-driver none
|
||||
--hostname sandbox
|
||||
--hostname security-command
|
||||
)
|
||||
@@ -48,7 +48,7 @@ check "no network interfaces besides lo" \
|
||||
"tail -n +3 /proc/net/dev | awk '{print \$1}' | grep -v '^lo:' | wc -l" '^0$'
|
||||
check "curl cannot reach anything" \
|
||||
'curl -sS --max-time 3 http://1.1.1.1 >/dev/null && echo reachable' 'curl: \([0-9]+\)'
|
||||
check "runs as guest" 'id' 'uid=1000\(guest\)'
|
||||
check "runs as agent" 'id' 'uid=1000\(agent\)'
|
||||
check "no effective capabilities" 'grep CapEff /proc/self/status' 'CapEff:\s+0+$'
|
||||
check "no new privileges" 'grep NoNewPrivs /proc/self/status' 'NoNewPrivs:\s+1'
|
||||
check "no setuid binaries" 'find / -xdev -perm /6000 -type f 2>/dev/null | wc -l' '^0$'
|
||||
|
||||
@@ -100,7 +100,7 @@ const STYLE = `
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; background: var(--background); color: var(--text); font: 15px/1.6 "JetBrains Mono", ui-monospace, monospace; font-variant-ligatures: no-contextual; }
|
||||
header, main, footer { max-width: 60rem; margin: 0 auto; padding: 0.75rem 1rem; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; justify-content: space-between; border-bottom: 1px solid var(--border); font-size: 0.85rem; }
|
||||
header { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; justify-content: space-between; border-bottom: 1px solid var(--border); font-size: 0.85rem; user-select: none; }
|
||||
header .site { color: var(--accent); }
|
||||
nav a { margin-left: 0.75rem; }
|
||||
a { color: var(--accent); }
|
||||
|
||||
@@ -81,7 +81,6 @@ export function buildSite(index: ContentIndex, options: SiteOptions): Site
|
||||
{
|
||||
const pages = new Map<string, SitePage>();
|
||||
const nav: Link[] = [
|
||||
{ label: 'terminal', href: '/' },
|
||||
{ label: 'ls', href: '/ls' },
|
||||
...[...options.legal.keys()].map((route) => ({ label: route, href: `/${route}` })),
|
||||
];
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { connect, type Socket } from 'node:net';
|
||||
import { readLine } from './lines.ts';
|
||||
import type { ManagedContainer, SpawnerRequest, SpawnerResponse } from './spawner.ts';
|
||||
import type { TerminalSize } from './terminal.ts';
|
||||
|
||||
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
|
||||
@@ -13,8 +14,9 @@ export class SpawnerClient
|
||||
|
||||
constructor(socketPath: string) { this.socketPath = socketPath; }
|
||||
|
||||
async spawn(sessionId: string, expiresAt: number): Promise<string> {
|
||||
const response = await this.request({ op: 'spawn', sessionId, expiresAt });
|
||||
/** The terminal size is set before the shell starts, so its first output already fits. */
|
||||
async spawn(sessionId: string, expiresAt: number, size: TerminalSize): Promise<string> {
|
||||
const response = await this.request({ op: 'spawn', sessionId, expiresAt, ...size });
|
||||
return response.containerId!;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,12 @@ const parse = (value: unknown) => parseRequest(JSON.stringify(value), now);
|
||||
|
||||
describe('parseRequest', () => {
|
||||
it('accepts a valid spawn', () => {
|
||||
expect(parse({ op: 'spawn', sessionId: 'abcdEFGH_-12', expiresAt: now + 1200 })).toEqual({
|
||||
expect(parse({ op: 'spawn', sessionId: 'abcdEFGH_-12', expiresAt: now + 1200, cols: 900, rows: 40 })).toEqual({
|
||||
op: 'spawn',
|
||||
sessionId: 'abcdEFGH_-12',
|
||||
expiresAt: now + 1200,
|
||||
cols: 500,
|
||||
rows: 40,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,6 +21,7 @@ describe('parseRequest', () => {
|
||||
['expiry in the past', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now }],
|
||||
['expiry too far ahead', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + MAX_SESSION_SECONDS + 1 }],
|
||||
['fractional expiry', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + 1.5 }],
|
||||
['missing terminal size', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + 60 }],
|
||||
['uppercase container id', { op: 'kill', containerId: 'ABCDEF123456' }],
|
||||
['container id with path', { op: 'attach', containerId: '../../info' }],
|
||||
['unknown op', { op: 'exec', containerId: 'abcdef123456' }],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { MAX_TERMINAL_SIZE } from './terminal.ts';
|
||||
import { MAX_TERMINAL_SIZE, type TerminalSize } from './terminal.ts';
|
||||
|
||||
export const SANDBOX_LABEL = 'org.security-command.sandbox';
|
||||
export const SESSION_LABEL = 'org.security-command.session';
|
||||
@@ -7,7 +7,7 @@ export const MAX_REQUEST_BYTES = 4096;
|
||||
export const MAX_SESSION_SECONDS = 6 * 60 * 60;
|
||||
|
||||
export type SpawnerRequest =
|
||||
| { op: 'spawn'; sessionId: string; expiresAt: number }
|
||||
| ({ op: 'spawn'; sessionId: string; expiresAt: number } & TerminalSize)
|
||||
| { op: 'attach'; containerId: string }
|
||||
| { op: 'resize'; containerId: string; cols: number; rows: number }
|
||||
| { op: 'kill'; containerId: string }
|
||||
@@ -74,7 +74,13 @@ export function parseRequest(line: string, nowSeconds = Math.floor(Date.now() /
|
||||
expiresAt > nowSeconds + MAX_SESSION_SECONDS
|
||||
) { invalid('invalid expiry'); }
|
||||
|
||||
return { op: 'spawn', sessionId: sessionId(field(request, 'sessionId')), expiresAt };
|
||||
return {
|
||||
op: 'spawn',
|
||||
sessionId: sessionId(field(request, 'sessionId')),
|
||||
expiresAt,
|
||||
cols: terminalSize(field(request, 'cols')),
|
||||
rows: terminalSize(field(request, 'rows')),
|
||||
};
|
||||
}
|
||||
|
||||
case 'attach':
|
||||
|
||||
+8
-8
@@ -17,16 +17,16 @@ RUN rm -f /etc/dpkg/dpkg.cfg.d/docker \
|
||||
# shell configuration lives in /etc.
|
||||
# Setuid binaries are useless under no-new-privileges, so they are stripped
|
||||
# to keep the attack surface minimal even if that option is ever dropped.
|
||||
RUN useradd --uid 1000 --no-create-home --home-dir /home/guest --shell /bin/bash guest \
|
||||
&& mkdir /home/guest \
|
||||
RUN useradd --uid 1000 --no-create-home --home-dir /home/agent --shell /bin/bash agent \
|
||||
&& mkdir /home/agent \
|
||||
&& find / -xdev -perm /6000 -type f -exec chmod a-s {} +
|
||||
|
||||
COPY etc/ /etc/
|
||||
COPY --chmod=0755 bin/status /usr/local/bin/status
|
||||
COPY --chmod=0755 bin/ /usr/local/bin/
|
||||
|
||||
ENV PATH=/usr/local/bin:/usr/bin:/bin:/usr/games
|
||||
USER guest
|
||||
WORKDIR /home/guest
|
||||
# Startup files in the home directory belong to the content, so bash only
|
||||
# reads the system wide configuration.
|
||||
CMD ["/bin/bash", "--rcfile", "/etc/bash.bashrc", "-i"]
|
||||
USER agent
|
||||
WORKDIR /home/agent
|
||||
# Debian's bash always reads /etc/bash.bashrc. Startup files in the home
|
||||
# directory belong to the content, so an empty file replaces ~/.bashrc.
|
||||
CMD ["/bin/bash", "--rcfile", "/dev/null", "-i"]
|
||||
Executable
+157
@@ -0,0 +1,157 @@
|
||||
#!/bin/bash
|
||||
# Shows the emblem of security-command.org next to facts about this sandbox,
|
||||
# in the style of fastfetch. A content file .local/bin/fastfetch replaces it.
|
||||
|
||||
# Foreground and background colors of the emblem's pixels.
|
||||
declare -A fg=([r]=$'\e[38;2;119;31;47m' [g]=$'\e[38;2;92;85;85m')
|
||||
declare -A bg=([r]=$'\e[48;2;119;31;47m' [g]=$'\e[48;2;92;85;85m')
|
||||
accent=$'\e[1;31m'
|
||||
reset=$'\e[0m'
|
||||
|
||||
# The emblem of the favicon: r is its red, g its grey, a space the background.
|
||||
# Two pixel rows share one terminal row through half blocks.
|
||||
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 '
|
||||
)
|
||||
|
||||
# Sizes in the binary units fastfetch prints.
|
||||
size() {
|
||||
awk -v bytes="$1" 'BEGIN {
|
||||
split("B KiB MiB GiB TiB", units)
|
||||
for (unit = 1; bytes >= 1024 && unit < 5; unit++) bytes /= 1024
|
||||
printf "%.2f %s", bytes, units[unit]
|
||||
}'
|
||||
}
|
||||
|
||||
usage() { printf '%s / %s (%d%%)' "$(size "$1")" "$(size "$2")" $(($2 > 0 ? $1 * 100 / $2 : 0)); }
|
||||
|
||||
plural() { (($1 == 1)) && echo "$1 $2" || echo "$1 ${2}s"; }
|
||||
|
||||
format_uptime() {
|
||||
local seconds=${1%.*} parts=()
|
||||
((seconds < 60)) && { plural "$seconds" sec; return; }
|
||||
((seconds >= 86400)) && parts+=("$(plural $((seconds / 86400)) day)")
|
||||
((seconds / 3600 % 24)) && parts+=("$(plural $((seconds / 3600 % 24)) hour)")
|
||||
((seconds / 60 % 60)) && parts+=("$(plural $((seconds / 60 % 60)) min)")
|
||||
local IFS=,
|
||||
local joined="${parts[*]}"
|
||||
echo "${joined//,/, }"
|
||||
}
|
||||
|
||||
. /etc/os-release
|
||||
read -r up _ < /proc/uptime
|
||||
mem_total=$(awk '/^MemTotal:/ { print $2 * 1024 }' /proc/meminfo)
|
||||
mem_free=$(awk '/^MemAvailable:/ { print $2 * 1024 }' /proc/meminfo)
|
||||
if [[ -r /sys/fs/cgroup/memory.max && $(< /sys/fs/cgroup/memory.max) != max ]]; then
|
||||
mem_total=$(< /sys/fs/cgroup/memory.max)
|
||||
mem_used=$(< /sys/fs/cgroup/memory.current)
|
||||
else
|
||||
mem_used=$((mem_total - mem_free))
|
||||
fi
|
||||
# The cgroup limit wins over /proc/meminfo, which may describe the host.
|
||||
swap=$(awk '/^SwapTotal:/ { print $2 * 1024 }' /proc/meminfo)
|
||||
[[ -r /sys/fs/cgroup/memory.swap.max && $(< /sys/fs/cgroup/memory.swap.max) != max ]] && swap=$(< /sys/fs/cgroup/memory.swap.max)
|
||||
read -r disk_size disk_used disk_type < <(df -B1 --output=size,used,fstype / | tail -n 1)
|
||||
[[ $(awk '$2 == "/" { print $4 }' /proc/mounts | tail -n 1) == ro* ]] && disk_type+=' [Read-only]'
|
||||
cpu=$(awk -F ': ' '/^model name/ { print $2; exit }' /proc/cpuinfo)
|
||||
host=container
|
||||
dmesg 2>/dev/null | grep -q gVisor && host=gVisor
|
||||
|
||||
facts=(
|
||||
"OS|$PRETTY_NAME $(uname -m)"
|
||||
"Host|$host"
|
||||
"Kernel|$(uname -sr)"
|
||||
"Uptime|$(format_uptime "$up")"
|
||||
"Packages|$(dpkg-query -f '.\n' -W | wc -l) (dpkg)"
|
||||
"Shell|bash ${BASH_VERSION%%[(-]*}"
|
||||
"Terminal|xterm.js"
|
||||
"CPU|${cpu:-unknown} ($(nproc))"
|
||||
"Memory|$(usage "$mem_used" "$mem_total")"
|
||||
"Swap|$( ((swap > 0)) && size "$swap" || echo Disabled)"
|
||||
"Disk (/)|$(usage "$disk_used" "$disk_size") - $disk_type"
|
||||
"Locale|${LANG:-C}"
|
||||
)
|
||||
|
||||
emblem=()
|
||||
for ((y = 0; y < ${#logo[@]}; y += 2)); do
|
||||
top=${logo[y]} bottom=${logo[y + 1]} line=''
|
||||
for ((x = 0; x < ${#top}; x++)); do
|
||||
t=${top:x:1} b=${bottom:x:1}
|
||||
if [[ $t == ' ' && $b == ' ' ]]; then line+="$reset "
|
||||
elif [[ $t == "$b" ]]; then line+=$'\e[49m'"${fg[$t]}█"
|
||||
elif [[ $b == ' ' ]]; then line+=$'\e[49m'"${fg[$t]}▀"
|
||||
elif [[ $t == ' ' ]]; then line+=$'\e[49m'"${fg[$b]}▄"
|
||||
else line+="${fg[$t]}${bg[$b]}▀"
|
||||
fi
|
||||
done
|
||||
emblem+=("$line$reset")
|
||||
done
|
||||
|
||||
user=${USER:-$(id -un)}
|
||||
title="$accent$user$reset@$accent$HOSTNAME$reset"
|
||||
title_width=$((${#user} + 1 + ${#HOSTNAME}))
|
||||
dashes=$(printf '%*s' "$title_width" '')
|
||||
info=("$title" "${dashes// /-}")
|
||||
info_width=$title_width
|
||||
for fact in "${facts[@]}"; do
|
||||
key=${fact%%|*} value=${fact#*|}
|
||||
info+=("$accent$key$reset: $value")
|
||||
((${#key} + 2 + ${#value} > info_width)) && info_width=$((${#key} + 2 + ${#value}))
|
||||
done
|
||||
blocks() { for color in "$@"; do printf '\e[%sm ' "$color"; done; printf '%s' "$reset"; }
|
||||
info+=('' "$(blocks 40 41 42 43 44 45 46 47)" "$(blocks 100 101 102 103 104 105 106 107)")
|
||||
|
||||
cols=$(tput cols 2>/dev/null || echo 80)
|
||||
width=${#logo[0]}
|
||||
gap=3
|
||||
|
||||
echo
|
||||
if ((cols < width)); then
|
||||
printf '%s\n' "${info[@]}"
|
||||
elif ((cols < width + gap + info_width)); then
|
||||
printf '%s\n' "${emblem[@]}" '' "${info[@]}"
|
||||
else
|
||||
offset=$(((${#emblem[@]} - ${#info[@]}) / 2))
|
||||
((offset < 0)) && offset=0
|
||||
rows=$((${#emblem[@]} > offset + ${#info[@]} ? ${#emblem[@]} : offset + ${#info[@]}))
|
||||
for ((row = 0; row < rows; row++)); do
|
||||
left=${emblem[row]:-$(printf '%*s' "$width" '')}
|
||||
right=''
|
||||
((row >= offset)) && right=${info[row - offset]}
|
||||
printf '%s%*s%s\n' "$left" "$gap" '' "$right"
|
||||
done
|
||||
fi
|
||||
echo
|
||||
@@ -11,8 +11,14 @@ export XDG_CONFIG_HOME=/tmp/.config
|
||||
export XDG_CACHE_HOME=/tmp/.cache
|
||||
export XDG_STATE_HOME=/tmp/.local/state
|
||||
|
||||
PS1='\[\e[1;31m\]guest@security-command\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '
|
||||
PS1='\[\e[1;31m\]\u@\h\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '
|
||||
|
||||
alias ls='ls --color=auto'
|
||||
alias ll='ls -lah --color=auto'
|
||||
alias grep='grep --color=auto'
|
||||
|
||||
# The content may carry small scripts, which take precedence over the built in ones.
|
||||
PATH="$HOME/.local/bin:$PATH"
|
||||
|
||||
# Only the first shell of a session greets the visitor.
|
||||
[[ $SHLVL == 1 ]] && fastfetch
|
||||
Reference in new issue
Block a user