Add proof-of-work challenge, session hub support, and status metrics across backend and frontend apps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-13 11:43:49 +02:00
1 parent b841c2d1f6
commit 9647ac8c50
29 files changed
+1492 -292

No files matched your search

+1 -1
View File
@@ -67,5 +67,5 @@ jobs:
- name: Build and push - name: Build and push
run: | run: |
image="$REGISTRY/homepage-backend" image="$REGISTRY/homepage-backend"
docker build -f apps/backend/Dockerfile -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" . docker build -f apps/backend/Dockerfile --build-arg BUILD_SHA=${{ gitea.sha }} -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" .
docker push --all-tags "$image" docker push --all-tags "$image"
+2
View File
@@ -6,6 +6,8 @@ RUN corepack pnpm install --frozen-lockfile \
&& corepack pnpm --filter @homepage/backend --filter @homepage/frontend build && corepack pnpm --filter @homepage/backend --filter @homepage/frontend build
FROM node:24-alpine FROM node:24-alpine
ARG BUILD_SHA=dev
ENV BUILD_SHA=${BUILD_SHA}
COPY --from=build /src/apps/backend/dist/backend.js /app/backend.js COPY --from=build /src/apps/backend/dist/backend.js /app/backend.js
COPY --from=build /src/apps/frontend/dist /app/public COPY --from=build /src/apps/frontend/dist /app/public
USER 10002:10002 USER 10002:10002
+45 -17
View File
@@ -1,30 +1,58 @@
export type BackendConfig = { export type BackendConfig = {
host: string; host: string;
port: number; port: number;
spawnerSocket: string; /** Port of the metrics endpoint; 0 disables it. Only published to the host's loopback. */
frontendDir: string; metricsPort: number;
spawnerSocket: string;
frontendDir: string;
/** Directory for the status file shown in sandboxes; empty disables it. */
statusDir: string;
build: string;
/** Exact origins allowed to open terminal sessions. Empty allows every origin. */ /** Exact origins allowed to open terminal sessions. Empty allows every origin. */
allowedOrigins: string[]; allowedOrigins: string[];
sessionSeconds: number; maxSessions: number;
outputRate: number; maxQueue: number;
powDifficulty: number;
sessionSeconds: number;
idleSeconds: number;
idleWarningSeconds: number;
graceSeconds: number;
outputRate: number;
}; };
function integer(env: NodeJS.ProcessEnv, name: string, fallback: number): number function integer(env: NodeJS.ProcessEnv, name: string, fallback: number, minimum = 1): number
{ {
const value = Number(env[name] ?? fallback); const value = Number(env[name] ?? fallback);
if (!Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`); if (!Number.isInteger(value) || value < minimum) throw new Error(`${name} must be an integer of at least ${minimum}`);
return value; return value;
} }
function list(value: string | undefined): string[] {
return (value ?? '').split(',').map((entry) => entry.trim()).filter(Boolean);
}
export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
{ {
return { const config: BackendConfig = {
host: env.HOST ?? '0.0.0.0', host: env.HOST ?? '0.0.0.0',
port: integer(env, 'PORT', 8080), port: integer(env, 'PORT', 8080),
spawnerSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock', metricsPort: integer(env, 'METRICS_PORT', 9090, 0),
frontendDir: env.FRONTEND_DIR ?? '/app/public', spawnerSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock',
allowedOrigins: (env.ALLOWED_ORIGINS ?? '').split(',').map((origin) => origin.trim()).filter(Boolean), frontendDir: env.FRONTEND_DIR ?? '/app/public',
sessionSeconds: integer(env, 'SESSION_SECONDS', 20 * 60), statusDir: env.STATUS_DIR ?? '',
outputRate: integer(env, 'OUTPUT_BYTES_PER_SECOND', 1024 * 1024), build: env.BUILD_SHA ?? 'dev',
allowedOrigins: list(env.ALLOWED_ORIGINS),
maxSessions: integer(env, 'MAX_SESSIONS', 12),
maxQueue: integer(env, 'MAX_QUEUE', 20, 0),
powDifficulty: integer(env, 'POW_DIFFICULTY', 20, 0),
sessionSeconds: integer(env, 'SESSION_SECONDS', 20 * 60),
idleSeconds: integer(env, 'IDLE_SECONDS', 180),
idleWarningSeconds: integer(env, 'IDLE_WARNING_SECONDS', 30),
graceSeconds: integer(env, 'GRACE_SECONDS', 45),
outputRate: integer(env, 'OUTPUT_BYTES_PER_SECOND', 1024 * 1024),
}; };
if (config.idleWarningSeconds >= config.idleSeconds) throw new Error('IDLE_WARNING_SECONDS must be below IDLE_SECONDS');
if (config.powDifficulty > 28) throw new Error('POW_DIFFICULTY above 28 would take phones minutes');
return config;
} }
+281
View File
@@ -0,0 +1,281 @@
import { randomBytes } from 'node:crypto';
import { verifyProof } from '@homepage/protocol/proof';
import {
InvalidMessageError,
parseClientMessage,
type ExitReason,
type RefusalReason,
type ServerMessage,
type TerminalSize,
} from '@homepage/protocol/terminal';
import type { RawData, WebSocket } from 'ws';
import { Session, type SessionOptions, type Spawner } from './session.ts';
export type HubOptions = SessionOptions & {
maxSessions: number;
maxQueue: number;
/** Leading zero bits a new sandbox costs while the server is mostly idle. */
powDifficulty: number;
helloTimeoutMs: number;
/** Called whenever the number of sessions or queued visitors changes. */
onChange?: () => void;
};
export type HubStats = {
maxSessions: number;
starting: number;
active: number;
grace: number;
queued: number;
difficulty: number;
started: number;
resumed: number;
invalidProofs: number;
refused: Record<RefusalReason, number>;
ended: Record<ExitReason, number>;
};
type Waiting = {
socket: WebSocket;
size: TerminalSize;
assign: (session: Session) => void;
};
/** Close code for protocol violations by the client. */
const POLICY_VIOLATION = 1008;
/** Close code asking the client to try again later. */
const TRY_AGAIN_LATER = 1013;
function toBuffer(data: RawData): Buffer
{
if (Buffer.isBuffer(data)) return data;
if (Array.isArray(data)) return Buffer.concat(data);
return Buffer.from(data);
}
function send(socket: WebSocket, message: ServerMessage): void {
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(message));
}
/**
* Admission for all sandbox sessions: proof of work instead of per address
* limits, the global slot limit, the first come first served queue and
* resuming by token. No visitor address is ever looked at.
*/
export class SessionHub
{
private readonly spawner: Spawner;
private readonly options: HubOptions;
private readonly sessions = new Set<Session>();
private readonly byToken = new Map<string, Session>();
private readonly queue: Waiting[] = [];
private readonly counters = {
started: 0,
resumed: 0,
invalidProofs: 0,
refused: { busy: 0 } as Record<RefusalReason, number>,
ended: { closed: 0, expired: 0, idle: 0, error: 0, gone: 0 } as Record<ExitReason, number>,
};
constructor(spawner: Spawner, options: HubOptions) {
this.spawner = spawner;
this.options = options;
}
/** Sandboxes get more expensive as the slots fill up, so the last ones and the queue cost the most. */
difficulty(): number
{
const load = (this.sessions.size + this.queue.length) / this.options.maxSessions;
if (load >= 0.9) return this.options.powDifficulty + 3;
if (load >= 0.75) return this.options.powDifficulty + 2;
if (load >= 0.5) return this.options.powDifficulty + 1;
return this.options.powDifficulty;
}
stats(): HubStats
{
const states = [...this.sessions].map((session) => session.state);
return {
maxSessions: this.options.maxSessions,
starting: states.filter((state) => state === 'starting').length,
active: states.filter((state) => state === 'active').length,
grace: states.filter((state) => state === 'grace').length,
queued: this.queue.length,
difficulty: this.difficulty(),
started: this.counters.started,
resumed: this.counters.resumed,
invalidProofs: this.counters.invalidProofs,
refused: { ...this.counters.refused },
ended: { ...this.counters.ended },
};
}
/**
* Takes over a new WebSocket and hands it a challenge right away. The first
* control message decides: a hello with a solving nonce asks for a new
* sandbox, a resume with a token continues an existing one.
*/
connect(socket: WebSocket): void
{
const challenge = randomBytes(16).toString('base64url');
const difficulty = this.difficulty();
send(socket, { type: 'challenge', challenge, difficulty });
let session: Session | undefined;
let waiting: Waiting | undefined;
let greeted = false;
const helloTimer = setTimeout(() => socket.close(POLICY_VIOLATION, 'hello expected'), this.options.helloTimeoutMs);
socket.on('message', (data, isBinary) =>
{
if (isBinary)
{
session?.input(socket, toBuffer(data));
return;
}
let message;
try { message = parseClientMessage(toBuffer(data).toString('utf8')); }
catch (error)
{
if (!(error instanceof InvalidMessageError)) throw error;
socket.close(POLICY_VIOLATION, error.message);
return;
}
if (message.type === 'resize')
{
if (session) session.resize(socket, message);
else if (waiting) waiting.size = message;
return;
}
if (greeted) return;
greeted = true;
clearTimeout(helloTimer);
const size = { cols: message.cols, rows: message.rows };
if (message.type === 'resume')
{
session = this.resume(socket, message.token, size);
return;
}
if (!verifyProof(challenge, message.nonce, difficulty))
{
this.counters.invalidProofs++;
socket.close(POLICY_VIOLATION, 'invalid proof of work');
return;
}
waiting = this.admit(socket, size, (assigned) =>
{
session = assigned;
waiting = undefined;
});
});
socket.on('close', () =>
{
clearTimeout(helloTimer);
session?.detach(socket);
if (waiting) this.leaveQueue(waiting);
});
}
/** Ends every session, for example on shutdown. */
endAll(reason: ExitReason): void {
for (const session of [...this.sessions]) session.end(reason);
}
private resume(socket: WebSocket, token: string, size: TerminalSize): Session | undefined
{
const session = this.byToken.get(token);
if (!session)
{
send(socket, { type: 'exit', reason: 'gone' });
socket.close(1000);
return undefined;
}
this.counters.resumed++;
session.resume(socket, size);
return session;
}
/** Starts a session right away, queues the visitor, or refuses. Returns the queue entry. */
private admit(socket: WebSocket, size: TerminalSize, assign: (session: Session) => void): Waiting | undefined
{
if (this.sessions.size < this.options.maxSessions && this.queue.length === 0)
{
assign(this.startSession(socket, size));
return undefined;
}
if (this.queue.length >= this.options.maxQueue)
{
this.counters.refused.busy++;
send(socket, { type: 'refused', reason: 'busy' });
socket.close(TRY_AGAIN_LATER);
return undefined;
}
const waiting = { socket, size, assign };
this.queue.push(waiting);
send(socket, { type: 'queued', position: this.queue.length });
this.options.onChange?.();
return waiting;
}
private startSession(socket: WebSocket, size: TerminalSize): Session
{
this.counters.started++;
const session = new Session(this.spawner, this.options, (ended, reason) =>
{
this.sessions.delete(ended);
this.byToken.delete(ended.token);
this.counters.ended[reason]++;
this.drainQueue();
this.options.onChange?.();
});
this.sessions.add(session);
this.byToken.set(session.token, session);
this.options.onChange?.();
session.start(socket, size).catch((error: unknown) =>
{
this.options.log(`session ${session.id} failed to start: ${String(error)}`);
session.end('error');
});
return session;
}
private leaveQueue(waiting: Waiting): void
{
const index = this.queue.indexOf(waiting);
if (index === -1) return;
this.queue.splice(index, 1);
this.announcePositions();
this.options.onChange?.();
}
private drainQueue(): void
{
while (this.sessions.size < this.options.maxSessions && this.queue.length > 0)
{
const next = this.queue.shift()!;
next.assign(this.startSession(next.socket, next.size));
}
this.announcePositions();
}
private announcePositions(): void {
this.queue.forEach((waiting, index) => send(waiting.socket, { type: 'queued', position: index + 1 }));
}
}
+38 -3
View File
@@ -1,10 +1,15 @@
import { SpawnerClient } from '@homepage/protocol'; import { SpawnerClient } from '@homepage/protocol';
import { loadAssets } from './assets.ts'; import { loadAssets } from './assets.ts';
import { loadConfig } from './config.ts'; import { loadConfig } from './config.ts';
import { createBackend } from './server.ts'; import { SessionHub } from './hub.ts';
import { createBackend, createMetricsServer } from './server.ts';
import { renderStatus, writeStatus } from './status.ts';
const log = (message: string) => console.log(`[backend] ${message}`); const log = (message: string) => console.log(`[backend] ${message}`);
const HEALTH_CACHE_MS = 10_000;
const STATUS_INTERVAL_MS = 5000;
const config = loadConfig(process.env); const config = loadConfig(process.env);
const spawner = new SpawnerClient(config.spawnerSocket); const spawner = new SpawnerClient(config.spawnerSocket);
@@ -16,13 +21,43 @@ if (orphans.length > 0) log(`removed ${orphans.length} orphaned sandbox(es)`);
const assets = loadAssets(config.frontendDir); const assets = loadAssets(config.frontendDir);
if (assets.size === 0) log(`no frontend found in ${config.frontendDir}`); if (assets.size === 0) log(`no frontend found in ${config.frontendDir}`);
const server = createBackend(config, spawner, log, assets); const started = Date.now();
function updateStatus(): void
{
if (!config.statusDir) return;
try { writeStatus(config.statusDir, renderStatus(hub.stats(), (Date.now() - started) / 1000, config.build)); }
catch (error) { log(`could not write the status file: ${String(error)}`); }
}
// Solving the proof of work happens after connecting, so slow phones get time for it.
const hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 90_000, log, onChange: updateStatus });
// The public health check asks the spawner at most every few seconds, so it cannot be used to flood it.
let health = { ok: true, checkedAt: 0 };
async function healthy(): Promise<boolean>
{
if (Date.now() - health.checkedAt < HEALTH_CACHE_MS) return health.ok;
const ok = await spawner.list().then(() => true, () => false);
health = { ok, checkedAt: Date.now() };
return ok;
}
const server = createBackend(config, hub, { assets, healthy });
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`)); server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
if (config.metricsPort > 0) createMetricsServer(hub).listen(config.metricsPort, config.host);
// Besides changes, the uptime line needs a regular refresh.
updateStatus();
setInterval(updateStatus, STATUS_INTERVAL_MS);
for (const signal of ['SIGTERM', 'SIGINT'] as const) for (const signal of ['SIGTERM', 'SIGINT'] as const)
{ {
process.once(signal, () => { process.once(signal, () => {
hub.endAll('closed');
server.close(); server.close();
process.exit(0); setTimeout(() => process.exit(0), 500);
}); });
} }
+264 -87
View File
@@ -1,15 +1,15 @@
import type { AddressInfo } from 'node:net'; import type { AddressInfo } from 'node:net';
import type { Server } from 'node:http'; import type { Server } from 'node:http';
import { duplexPair, type Duplex } from 'node:stream'; import { duplexPair, type Duplex } from 'node:stream';
import { solveProof } from '@homepage/protocol/proof';
import type { ServerMessage } from '@homepage/protocol/terminal'; import type { ServerMessage } from '@homepage/protocol/terminal';
import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { WebSocket } from 'ws'; import { WebSocket } from 'ws';
import type { BackendConfig } from './config.ts'; import type { BackendConfig } from './config.ts';
import { SessionHub } from './hub.ts';
import { createBackend } from './server.ts'; import { createBackend } from './server.ts';
import type { Spawner } from './session.ts'; import type { Spawner } from './session.ts';
const CONTAINER = 'aaaaaaaaaaaa';
const INDEX = { body: Buffer.from('<!doctype html>'), type: 'text/html; charset=utf-8', immutable: false }; const INDEX = { body: Buffer.from('<!doctype html>'), type: 'text/html; charset=utf-8', immutable: false };
const SCRIPT = { body: Buffer.from('console.log(1)'), type: 'text/javascript; charset=utf-8', immutable: true }; const 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]]); const ASSETS = new Map([['/', INDEX], ['/index.html', INDEX], ['/assets/index-abc.js', SCRIPT]]);
@@ -18,18 +18,22 @@ const ASSETS = new Map([['/', INDEX], ['/index.html', INDEX], ['/assets/index-ab
class FakeSpawner implements Spawner class FakeSpawner implements Spawner
{ {
readonly calls: string[] = []; readonly calls: string[] = [];
readonly containers = new Map<string, Duplex>();
container?: Duplex; container?: Duplex;
private count = 0;
async spawn(sessionId: string): Promise<string> { async spawn(sessionId: string): Promise<string>
{
this.calls.push(`spawn ${sessionId.length}`); this.calls.push(`spawn ${sessionId.length}`);
return CONTAINER; return `container${++this.count}`;
} }
async attach(): Promise<Duplex> async attach(containerId: string): Promise<Duplex>
{ {
const [backendSide, containerSide] = duplexPair(); const [backendSide, containerSide] = duplexPair();
this.containers.set(containerId, containerSide);
this.container = containerSide; this.container = containerSide;
this.calls.push('attach'); this.calls.push(`attach ${containerId}`);
backendSide.pause(); backendSide.pause();
return backendSide; return backendSide;
} }
@@ -50,143 +54,316 @@ function until(condition: () => boolean, timeoutMs = 2000): Promise<void>
const started = Date.now(); const started = Date.now();
const check = () => const check = () =>
{ {
if (condition()) return resolve(); if (condition()) return resolve();
if (Date.now() - started > timeoutMs) return reject(new Error('condition not met in time')); if (Date.now() - started > timeoutMs) return reject(new Error('condition not met in time'));
setTimeout(check, 5); setTimeout(check, 5);
}; };
check(); check();
}); });
} }
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe('backend', () => { describe('backend', () => {
let server: Server; let server: Server;
let hub: SessionHub;
let spawner: FakeSpawner; let spawner: FakeSpawner;
let url: string; let url: string;
let config: BackendConfig;
async function start(overrides: Partial<BackendConfig> = {}): Promise<void> async function start(overrides: Partial<BackendConfig> = {}): Promise<void>
{ {
config = { const config: BackendConfig = {
host: '127.0.0.1', host: '127.0.0.1',
port: 0, port: 0,
spawnerSocket: '', metricsPort: 0,
frontendDir: '', spawnerSocket: '',
allowedOrigins: ['https://security-command.org'], frontendDir: '',
sessionSeconds: 60, statusDir: '',
outputRate: 1024 * 1024, build: 'test',
allowedOrigins: ['https://security-command.org'],
maxSessions: 12,
maxQueue: 20,
powDifficulty: 0,
sessionSeconds: 60,
idleSeconds: 60,
idleWarningSeconds: 10,
graceSeconds: 45,
outputRate: 1024 * 1024,
...overrides, ...overrides,
}; };
spawner = new FakeSpawner(); spawner = new FakeSpawner();
server = createBackend(config, spawner, () => {}, ASSETS); hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 10_000, log: () => {} });
server = createBackend(config, hub, { assets: ASSETS });
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve)); 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`; url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/ws`;
} }
type Client = { socket: WebSocket; messages: ServerMessage[]; output: () => string; closed: Promise<number> }; async function restart(overrides: Partial<BackendConfig>): Promise<void>
{
hub.endAll('closed');
server.close();
await start(overrides);
}
type Client = {
socket: WebSocket;
messages: ServerMessage[];
output: () => string;
closed: Promise<number>;
has: (type: ServerMessage['type']) => boolean;
};
function connect(origin = 'https://security-command.org'): Promise<Client> function connect(origin = 'https://security-command.org'): Promise<Client>
{ {
return new Promise((resolve, reject) => return new Promise((resolve, reject) =>
{ {
const socket = new WebSocket(url, { origin }); const socket = new WebSocket(url, { origin });
const messages: ServerMessage[] = []; const messages: ServerMessage[] = [];
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
const closed = new Promise<number>((done) => socket.on('close', done)); const closed = new Promise<number>((done) => socket.on('close', done));
const has = (type: ServerMessage['type']) => messages.some((message) => message.type === type);
socket.on('message', (data, isBinary) => socket.on('message', (data, isBinary) =>
{ {
if (isBinary) chunks.push(data as Buffer); if (isBinary) chunks.push(data as Buffer);
else messages.push(JSON.parse(data.toString()) as ServerMessage); else messages.push(JSON.parse(data.toString()) as ServerMessage);
}); });
socket.on('open', () => resolve({ socket, messages, output: () => Buffer.concat(chunks).toString(), closed })); socket.on('open', () => resolve({ socket, messages, output: () => Buffer.concat(chunks).toString(), closed, has }));
socket.on('error', reject); socket.on('error', reject);
}); });
} }
async function ready(): Promise<Client> /** Answers the connection's challenge like the browser does. */
async function proof(client: Client): Promise<number>
{
await until(() => client.has('challenge'));
const message = client.messages.find((entry) => entry.type === 'challenge');
if (message?.type !== 'challenge') throw new Error('no challenge');
return solveProof(message.challenge, message.difficulty)!;
}
async function hello(size = { cols: 100, rows: 30 }): Promise<Client>
{ {
const client = await connect(); const client = await connect();
client.socket.send(JSON.stringify({ type: 'hello', cols: 100, rows: 30 })); client.socket.send(JSON.stringify({ type: 'hello', nonce: await proof(client), ...size }));
await until(() => client.messages.some((message) => message.type === 'ready'));
return client; return client;
} }
async function ready(): Promise<Client>
{
const client = await hello();
await until(() => client.has('ready'));
return client;
}
function tokenOf(client: Client): string
{
const message = client.messages.find((entry) => entry.type === 'ready');
if (message?.type !== 'ready') throw new Error('no ready message');
return message.token;
}
beforeEach(() => start()); beforeEach(() => start());
afterEach(() => server.close()); afterEach(() =>
{
it('bridges input and output after the hello', async () => { hub.endAll('closed');
const client = await ready();
spawner.container!.on('data', (data: Buffer) => spawner.container!.write(data.toString().toUpperCase()));
client.socket.send(Buffer.from('echo hi'));
await until(() => client.output() === 'ECHO HI');
expect(spawner.calls).toEqual(['spawn 16', 'attach', 'resize 100x30']);
});
it('forwards resizes and removes the container when the visitor leaves', async () => {
const client = await ready();
client.socket.send(JSON.stringify({ type: 'resize', cols: 9999, rows: 40 }));
await until(() => spawner.calls.includes('resize 500x40'));
client.socket.close();
await until(() => spawner.calls.includes(`kill ${CONTAINER}`));
});
it('reports when the shell exits', async () => {
const client = await ready();
spawner.container!.end();
expect(await client.closed).toBe(1000);
expect(client.messages).toContainEqual({ type: 'exit', reason: 'closed' });
expect(spawner.calls).toContain(`kill ${CONTAINER}`);
});
it('expires sessions', async () => {
server.close(); server.close();
await start({ sessionSeconds: 1 });
const client = await ready();
expect(await client.closed).toBe(1000);
expect(client.messages).toContainEqual({ type: 'exit', reason: 'expired' });
}); });
it('ignores terminal input before the session started', async () => { describe('sessions', () => {
const client = await connect(); it('bridges input and output after the hello', async () => {
const client = await ready();
spawner.container!.on('data', (data: Buffer) => spawner.container!.write(data.toString().toUpperCase()));
client.socket.send(Buffer.from('early')); client.socket.send(Buffer.from('echo hi'));
client.socket.send(JSON.stringify({ type: 'hello', cols: 80, rows: 24 })); await until(() => client.output() === 'ECHO HI');
await until(() => client.messages.some((message) => message.type === 'ready')); expect(spawner.calls).toEqual(['spawn 16', 'attach container1', 'resize 100x30']);
});
const received: string[] = []; it('forwards resizes', async () => {
spawner.container!.on('data', (data: Buffer) => received.push(data.toString())); const client = await ready();
client.socket.send(Buffer.from('late'));
await until(() => received.length > 0); client.socket.send(JSON.stringify({ type: 'resize', cols: 9999, rows: 40 }));
expect(received.join('')).toBe('late'); await until(() => spawner.calls.includes('resize 500x40'));
});
it('reports when the shell exits', async () => {
const client = await ready();
spawner.container!.end();
expect(await client.closed).toBe(1000);
expect(client.messages).toContainEqual({ type: 'exit', reason: 'closed' });
expect(spawner.calls).toContain('kill container1');
});
it('expires sessions', async () => {
await restart({ sessionSeconds: 1 });
const client = await ready();
expect(await client.closed).toBe(1000);
expect(client.messages).toContainEqual({ type: 'exit', reason: 'expired' });
});
it('warns about and ends idle sessions', async () => {
await restart({ idleSeconds: 0.4, idleWarningSeconds: 0.2 });
const client = await ready();
expect(await client.closed).toBe(1000);
expect(client.messages).toContainEqual({ type: 'idle', secondsLeft: 0.2 });
expect(client.messages).toContainEqual({ type: 'exit', reason: 'idle' });
});
it('ignores terminal input before the session started', async () => {
const client = await connect();
const nonce = await proof(client);
client.socket.send(Buffer.from('early'));
client.socket.send(JSON.stringify({ type: 'hello', nonce, cols: 80, rows: 24 }));
await until(() => client.has('ready'));
const received: string[] = [];
spawner.container!.on('data', (data: Buffer) => received.push(data.toString()));
client.socket.send(Buffer.from('late'));
await until(() => received.length > 0);
expect(received.join('')).toBe('late');
});
it('closes the connection on invalid control messages', async () => {
const client = await connect();
client.socket.send('{"type":"exec"}');
expect(await client.closed).toBe(1008);
expect(spawner.calls).toEqual([]);
});
it('rejects foreign origins', async () => {
await expect(connect('https://evil.example')).rejects.toThrow('403');
});
it('throttles output', async () => {
await restart({ outputRate: 1000 });
const client = await ready();
for (let i = 0; i < 5; i++) spawner.container!.write('x'.repeat(1000));
await sleep(300);
expect(client.output().length).toBeGreaterThan(0);
expect(client.output().length).toBeLessThan(5000);
});
}); });
it('closes the connection on invalid control messages', async () => { describe('reconnecting', () => {
const client = await connect(); it('resumes a session within the grace period', async () => {
const first = await ready();
first.socket.terminate();
await first.closed;
client.socket.send('{"type":"exec"}'); spawner.container!.write('missed while away');
expect(await client.closed).toBe(1008); const second = await connect();
expect(spawner.calls).toEqual([]); second.socket.send(JSON.stringify({ type: 'resume', token: tokenOf(first), cols: 90, rows: 20 }));
await until(() => second.output() === 'missed while away');
expect(second.messages).toContainEqual(expect.objectContaining({ type: 'ready', resumed: true, token: tokenOf(first) }));
expect(spawner.calls.filter((call) => call.startsWith('spawn'))).toHaveLength(1);
expect(spawner.calls).not.toContain('kill container1');
});
it('moves the session to the newest connection', async () => {
const first = await ready();
const second = await connect();
second.socket.send(JSON.stringify({ type: 'resume', token: tokenOf(first), cols: 80, rows: 24 }));
expect(await first.closed).toBe(1000);
await until(() => second.has('ready'));
});
it('removes the container after the grace period and answers late resumes with gone', async () => {
await restart({ graceSeconds: 0.2 });
const first = await ready();
first.socket.terminate();
await until(() => spawner.calls.includes('kill container1'));
const late = await connect();
late.socket.send(JSON.stringify({ type: 'resume', token: tokenOf(first), cols: 80, rows: 24 }));
await late.closed;
expect(late.messages.at(-1)).toEqual({ type: 'exit', reason: 'gone' });
});
}); });
it('rejects foreign origins', async () => { describe('admission', () => {
await expect(connect('https://evil.example')).rejects.toThrow('403'); it('sends a challenge right after connecting', async () => {
}); const client = await connect();
await until(() => client.has('challenge'));
it('throttles output', async () => { expect(client.messages[0]).toEqual({ type: 'challenge', challenge: expect.stringMatching(/^[A-Za-z0-9_-]{22}$/), difficulty: 0 });
server.close(); });
await start({ outputRate: 1000 });
const client = await ready();
for (let i = 0; i < 5; i++) spawner.container!.write('x'.repeat(1000)); it('refuses a hello without a valid proof of work', async () => {
await new Promise((resolve) => setTimeout(resolve, 300)); await restart({ powDifficulty: 16 });
const client = await connect();
await until(() => client.has('challenge'));
expect(client.output().length).toBeGreaterThan(0); client.socket.send(JSON.stringify({ type: 'hello', nonce: 1, cols: 80, rows: 24 }));
expect(client.output().length).toBeLessThan(5000); expect(await client.closed).toBe(1008);
expect(spawner.calls).toEqual([]);
expect(hub.stats().invalidProofs).toBe(1);
});
it('raises the difficulty as the slots fill up', async () => {
await restart({ maxSessions: 2, powDifficulty: 4 });
expect(hub.difficulty()).toBe(4);
await ready();
expect(hub.difficulty()).toBe(5);
await ready();
expect(hub.difficulty()).toBe(7);
});
it('queues visitors while all slots are taken', async () => {
await restart({ maxSessions: 1 });
await ready();
const waiting = await hello();
await until(() => waiting.has('queued'));
expect(waiting.messages.filter((message) => message.type === 'queued')).toEqual([{ type: 'queued', position: 1 }]);
spawner.container!.end();
await until(() => waiting.has('ready'));
});
it('updates queue positions when someone ahead leaves', async () => {
await restart({ maxSessions: 1 });
await ready();
const ahead = await hello();
const behind = await hello();
await until(() => behind.has('queued'));
ahead.socket.close();
const positions = () => behind.messages.filter((message) => message.type === 'queued');
await until(() => positions().length === 2);
expect(positions()).toEqual([{ type: 'queued', position: 2 }, { type: 'queued', position: 1 }]);
});
it('refuses visitors when the queue is full', async () => {
await restart({ maxSessions: 1, maxQueue: 0 });
await ready();
const refused = await hello();
expect(await refused.closed).toBe(1013);
expect(refused.messages.at(-1)).toEqual({ type: 'refused', reason: 'busy' });
});
it('reports counts in its stats', async () => {
await restart({ maxSessions: 1 });
await ready();
const waiting = await hello();
await until(() => waiting.has('queued'));
expect(hub.stats()).toMatchObject({ active: 1, queued: 1, started: 1 });
});
}); });
describe('http', () => { describe('http', () => {
+34 -71
View File
@@ -1,20 +1,21 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'; import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import type { Duplex } from 'node:stream'; import type { Duplex } from 'node:stream';
import { InvalidMessageError, parseClientMessage, TERMINAL_PATH } from '@homepage/protocol/terminal'; import { TERMINAL_PATH } from '@homepage/protocol/terminal';
import { WebSocketServer, type RawData, type WebSocket } from 'ws'; import { WebSocketServer, type WebSocket } from 'ws';
import type { Asset } from './assets.ts'; import type { Asset } from './assets.ts';
import type { BackendConfig } from './config.ts'; import type { BackendConfig } from './config.ts';
import { Session, type Spawner } from './session.ts'; import type { SessionHub } from './hub.ts';
import { renderMetrics } from './status.ts';
export type Logger = (message: string) => void; export type BackendOptions = {
assets?: Map<string, Asset>;
/** Resolves to false while the spawner is unreachable. */
healthy?: () => Promise<boolean>;
};
const MAX_FRAME_BYTES = 64 * 1024; const MAX_FRAME_BYTES = 64 * 1024;
const HELLO_TIMEOUT_MS = 10_000;
const PING_INTERVAL_MS = 30_000; 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'. // xterm.js creates style elements at runtime, so styles need 'unsafe-inline'.
const SECURITY_HEADERS = { const SECURITY_HEADERS = {
'Content-Security-Policy': [ 'Content-Security-Policy': [
@@ -51,75 +52,22 @@ function originAllowed(config: BackendConfig, request: IncomingMessage): boolean
return config.allowedOrigins.includes(request.headers.origin ?? ''); return config.allowedOrigins.includes(request.headers.origin ?? '');
} }
function toBuffer(data: RawData): Buffer export function createBackend(config: BackendConfig, hub: SessionHub, options: BackendOptions = {}): Server
{ {
if (Buffer.isBuffer(data)) return data; const assets = options.assets ?? new Map<string, Asset>();
if (Array.isArray(data)) return Buffer.concat(data); const healthy = options.healthy ?? (async () => true);
return Buffer.from(data);
}
function handleConnection(socket: WebSocket, spawner: Spawner, config: BackendConfig, log: Logger): void const server = createServer(async (request, response) =>
{
const session = new Session(socket, spawner, {
sessionSeconds: config.sessionSeconds,
outputRate: config.outputRate,
log,
});
let greeted = false;
const helloTimer = setTimeout(() => socket.close(POLICY_VIOLATION, 'hello expected'), HELLO_TIMEOUT_MS);
socket.on('message', (data, isBinary) =>
{
if (isBinary)
{
if (session.started) session.input(toBuffer(data));
return;
}
try
{
const message = parseClientMessage(toBuffer(data).toString('utf8'));
if (message.type === 'resize')
{
session.resize(message);
return;
}
if (greeted) return;
greeted = true;
clearTimeout(helloTimer);
session.start(message).catch((error: unknown) =>
{
log(`session ${session.id} failed to start: ${String(error)}`);
session.end('error');
});
}
catch (error)
{
if (!(error instanceof InvalidMessageError)) throw error;
socket.close(POLICY_VIOLATION, error.message);
}
});
socket.on('close', () =>
{
clearTimeout(helloTimer);
session.dispose();
});
}
export function createBackend(config: BackendConfig, spawner: Spawner, log: Logger, assets = new Map<string, Asset>()): Server
{
const server = createServer((request, response) =>
{ {
const head = request.method === 'HEAD'; const head = request.method === 'HEAD';
if (request.method !== 'GET' && !head) return send(response, 405, 'text/plain', 'method not allowed', { Allow: 'GET, 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; const path = new URL(request.url ?? '/', 'http://backend').pathname;
if (path === '/healthz') return send(response, 200, 'text/plain', 'ok', {}, head); if (path === '/healthz')
{
const ok = await healthy();
return send(response, ok ? 200 : 503, 'text/plain', ok ? 'ok' : 'degraded', { 'Cache-Control': 'no-store' }, head);
}
const asset = assets.get(path); const asset = assets.get(path);
if (asset) if (asset)
@@ -143,7 +91,7 @@ export function createBackend(config: BackendConfig, spawner: Spawner, log: Logg
{ {
alive.add(websocket); alive.add(websocket);
websocket.on('pong', () => alive.add(websocket)); websocket.on('pong', () => alive.add(websocket));
handleConnection(websocket, spawner, config, log); hub.connect(websocket);
}); });
}); });
@@ -166,3 +114,18 @@ export function createBackend(config: BackendConfig, spawner: Spawner, log: Logg
server.on('close', () => clearInterval(pinger)); server.on('close', () => clearInterval(pinger));
return server; return server;
} }
/** Prometheus metrics on their own port, which compose only publishes to the host's loopback. */
export function createMetricsServer(hub: SessionHub): Server
{
return createServer((request, response) =>
{
if (request.url !== '/metrics')
{
response.writeHead(404).end();
return;
}
response.writeHead(200, { 'Content-Type': 'text/plain; version=0.0.4' }).end(renderMetrics(hub.stats()));
});
}
+113 -44
View File
@@ -12,47 +12,67 @@ export type Spawner = {
}; };
export type SessionOptions = { export type SessionOptions = {
sessionSeconds: number; sessionSeconds: number;
outputRate: number; idleSeconds: number;
log: (message: string) => void; idleWarningSeconds: number;
graceSeconds: number;
outputRate: number;
log: (message: string) => void;
}; };
export type SessionState = 'starting' | 'active' | 'grace';
/** Output pauses above the high mark of unsent WebSocket bytes and resumes below the low mark. */ /** Output pauses above the high mark of unsent WebSocket bytes and resumes below the low mark. */
const HIGH_WATER_MARK = 256 * 1024; const HIGH_WATER_MARK = 256 * 1024;
const LOW_WATER_MARK = 64 * 1024; const LOW_WATER_MARK = 64 * 1024;
const RECHECK_MS = 25; const RECHECK_MS = 25;
/** One visitor's terminal: a WebSocket bridged to one sandbox container. */ /**
* One visitor's sandbox. The container outlives single WebSockets: when the
* connection drops, the session waits for a resume with its token until the
* grace period ends.
*/
export class Session export class Session
{ {
readonly id = randomBytes(12).toString('base64url'); readonly id = randomBytes(12).toString('base64url');
readonly token = randomBytes(16).toString('base64url');
readonly expiresAt: number;
private readonly socket: WebSocket;
private readonly spawner: Spawner; private readonly spawner: Spawner;
private readonly options: SessionOptions; private readonly options: SessionOptions;
private readonly bucket: TokenBucket; private readonly bucket: TokenBucket;
private readonly onRelease: (session: Session, reason: ExitReason) => void;
private socket?: WebSocket;
private containerId?: string; private containerId?: string;
private stream?: Duplex; private stream?: Duplex;
private expiryTimer?: NodeJS.Timeout;
private recheckTimer?: NodeJS.Timeout;
private ended = false; private ended = false;
constructor(socket: WebSocket, spawner: Spawner, options: SessionOptions) { private expiryTimer?: NodeJS.Timeout;
this.socket = socket; private idleTimer?: NodeJS.Timeout;
this.spawner = spawner; private warningTimer?: NodeJS.Timeout;
this.options = options; private graceTimer?: NodeJS.Timeout;
this.bucket = new TokenBucket(options.outputRate); private recheckTimer?: NodeJS.Timeout;
}
get started(): boolean { constructor(spawner: Spawner, options: SessionOptions, onRelease: (session: Session, reason: ExitReason) => void)
return this.stream !== undefined;
}
async start(size: TerminalSize): Promise<void>
{ {
const expiresAt = Math.floor(Date.now() / 1000) + this.options.sessionSeconds; this.spawner = spawner;
this.containerId = await this.spawner.spawn(this.id, expiresAt); this.options = options;
this.onRelease = onRelease;
this.bucket = new TokenBucket(options.outputRate);
this.expiresAt = Math.floor(Date.now() / 1000) + options.sessionSeconds;
}
get state(): SessionState
{
if (!this.stream) return 'starting';
return this.socket ? 'active' : 'grace';
}
async start(socket: WebSocket, size: TerminalSize): Promise<void>
{
this.socket = socket;
this.containerId = await this.spawner.spawn(this.id, this.expiresAt);
if (this.ended) return this.release(); if (this.ended) return this.release();
const stream = await this.spawner.attach(this.containerId); const stream = await this.spawner.attach(this.containerId);
@@ -68,49 +88,99 @@ export class Session
stream.on('close', () => this.end('closed')); stream.on('close', () => this.end('closed'));
stream.on('error', () => this.end('error')); stream.on('error', () => this.end('error'));
this.send({ type: 'ready' });
this.resize(size);
stream.resume();
this.expiryTimer = setTimeout(() => this.end('expired'), this.options.sessionSeconds * 1000); this.expiryTimer = setTimeout(() => this.end('expired'), this.options.sessionSeconds * 1000);
this.options.log(`session ${this.id} started`); this.options.log(`session ${this.id} started`);
if (this.socket) this.connect(this.socket, size, false);
else this.detach(socket);
} }
input(data: Buffer): void { /** Attaches a resuming WebSocket. A still connected older one is replaced. */
this.stream?.write(data); resume(socket: WebSocket, size: TerminalSize): void
}
resize({ cols, rows }: TerminalSize): void
{ {
if (!this.containerId || this.ended) return; if (this.ended || !this.stream) return;
const previous = this.socket;
this.socket = undefined;
previous?.close(1000, 'resumed elsewhere');
this.connect(socket, size, true);
this.options.log(`session ${this.id} resumed`);
}
/** Called when a WebSocket closes. Only the current one starts the grace period. */
detach(socket: WebSocket): void
{
if (this.ended || (this.socket && this.socket !== socket)) return;
this.socket = undefined;
if (!this.stream) return;
this.stream.pause();
clearTimeout(this.graceTimer);
this.graceTimer = setTimeout(() => this.end('closed'), this.options.graceSeconds * 1000);
}
input(socket: WebSocket, data: Buffer): void
{
if (socket !== this.socket || !this.stream) return;
this.stream.write(data);
this.touch();
}
resize(socket: WebSocket, { cols, rows }: TerminalSize): void
{
if (socket !== this.socket || !this.containerId || this.ended) return;
this.spawner.resize(this.containerId, cols, rows).catch(() => {}); this.spawner.resize(this.containerId, cols, rows).catch(() => {});
} }
/** Ends the session, tells the visitor why, and removes the container. */ /** Ends the session, tells a connected visitor why, and removes the container. */
end(reason: ExitReason): void end(reason: ExitReason): void
{ {
if (this.ended) return; if (this.ended) return;
this.ended = true; this.ended = true;
this.send({ type: 'exit', reason }); this.send({ type: 'exit', reason });
this.socket.close(1000); this.socket?.close(1000);
this.socket = undefined;
this.release(); this.release();
this.options.log(`session ${this.id} ended (${reason})`); this.options.log(`session ${this.id} ended (${reason})`);
this.onRelease(this, reason);
} }
/** Cleans up after the WebSocket is already gone. */ private connect(socket: WebSocket, size: TerminalSize, resumed: boolean): void
dispose(): void
{ {
if (this.ended) return; clearTimeout(this.graceTimer);
this.ended = true; this.socket = socket;
this.release(); this.send({ type: 'ready', token: this.token, expiresAt: this.expiresAt, resumed });
this.options.log(`session ${this.id} disconnected`); this.resize(socket, size);
this.touch();
this.stream?.resume();
}
/** Restarts the idle countdown, including the warning shortly before it ends. */
private touch(): void
{
clearTimeout(this.idleTimer);
clearTimeout(this.warningTimer);
const { idleSeconds, idleWarningSeconds } = this.options;
this.warningTimer = setTimeout(
() => this.send({ type: 'idle', secondsLeft: idleWarningSeconds }),
(idleSeconds - idleWarningSeconds) * 1000,
);
this.idleTimer = setTimeout(() => this.end('idle'), idleSeconds * 1000);
} }
private forward(chunk: Buffer): void private forward(chunk: Buffer): void
{ {
if (this.ended) return; if (this.ended || !this.socket)
{
this.stream?.pause();
return;
}
this.socket.send(chunk, { binary: true }); this.socket.send(chunk, { binary: true });
this.bucket.take(chunk.length); this.bucket.take(chunk.length);
@@ -127,7 +197,7 @@ export class Session
clearTimeout(this.recheckTimer); clearTimeout(this.recheckTimer);
this.recheckTimer = setTimeout(() => this.recheckTimer = setTimeout(() =>
{ {
if (this.ended) return; if (this.ended || !this.socket) return;
if (this.socket.bufferedAmount < LOW_WATER_MARK && this.bucket.available() > 0) this.stream?.resume(); if (this.socket.bufferedAmount < LOW_WATER_MARK && this.bucket.available() > 0) this.stream?.resume();
else this.scheduleRecheck(); else this.scheduleRecheck();
@@ -136,13 +206,12 @@ export class Session
private send(message: ServerMessage): void private send(message: ServerMessage): void
{ {
if (this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(message)); if (this.socket && this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(message));
} }
private release(): void private release(): void
{ {
clearTimeout(this.expiryTimer); for (const timer of [this.expiryTimer, this.idleTimer, this.warningTimer, this.graceTimer, this.recheckTimer]) clearTimeout(timer);
clearTimeout(this.recheckTimer);
this.stream?.destroy(); this.stream?.destroy();
if (this.containerId) if (this.containerId)
+46
View File
@@ -0,0 +1,46 @@
import { mkdtempSync, readdirSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import type { HubStats } from './hub.ts';
import { renderMetrics, renderStatus, writeStatus } from './status.ts';
const stats: HubStats = {
maxSessions: 12,
starting: 1,
active: 3,
grace: 1,
queued: 2,
difficulty: 21,
started: 40,
resumed: 4,
invalidProofs: 5,
refused: { busy: 3 },
ended: { closed: 30, expired: 2, idle: 3, error: 0, gone: 1 },
};
describe('status', () => {
it('renders aggregates only', () => {
expect(renderStatus(stats, 3 * 86_400 + 4 * 3600, 'a1b2c3d4e5')).toBe(
'sessions 5/12\nqueue 2\nuptime 3d 4h\nbuild a1b2c3d\n',
);
});
it('replaces the file atomically', () => {
const directory = mkdtempSync(join(tmpdir(), 'status-'));
writeStatus(directory, 'first');
writeStatus(directory, 'second');
expect(readFileSync(join(directory, 'status'), 'utf8')).toBe('second');
expect(readdirSync(directory)).toEqual(['status']);
});
it('renders Prometheus metrics', () => {
const metrics = renderMetrics(stats);
expect(metrics).toContain('homepage_sessions{state="active"} 3');
expect(metrics).toContain('homepage_sessions_refused_total{reason="busy"} 3');
expect(metrics).toContain('homepage_pow_difficulty 21');
expect(metrics).toContain('homepage_sessions_ended_total{reason="idle"} 3');
});
});
+65
View File
@@ -0,0 +1,65 @@
import { renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { HubStats } from './hub.ts';
function duration(seconds: number): string
{
const days = Math.floor(seconds / 86_400);
const hours = Math.floor((seconds % 86_400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) return `${days}d ${hours}h`;
if (hours > 0) return `${hours}h ${minutes}m`;
return `${minutes}m`;
}
/** The file every sandbox can read at /var/status/status. Aggregates only, nothing about other visitors. */
export function renderStatus(stats: HubStats, uptimeSeconds: number, build: string): string
{
const sessions = stats.starting + stats.active + stats.grace;
return [
`sessions ${sessions}/${stats.maxSessions}`,
`queue ${stats.queued}`,
`uptime ${duration(uptimeSeconds)}`,
`build ${build.slice(0, 7)}`,
'',
].join('\n');
}
/**
* Writes the status atomically: sandboxes see the directory through a bind
* mount, so a rename makes the new content visible without a partial read.
*/
export function writeStatus(directory: string, content: string): void
{
const temporary = join(directory, '.status.tmp');
writeFileSync(temporary, content, { mode: 0o644 });
renameSync(temporary, join(directory, 'status'));
}
export function renderMetrics(stats: HubStats): string
{
const lines = [
'# TYPE homepage_sessions gauge',
`homepage_sessions{state="starting"} ${stats.starting}`,
`homepage_sessions{state="active"} ${stats.active}`,
`homepage_sessions{state="grace"} ${stats.grace}`,
`homepage_sessions{state="queued"} ${stats.queued}`,
'# TYPE homepage_sessions_max gauge',
`homepage_sessions_max ${stats.maxSessions}`,
'# TYPE homepage_pow_difficulty gauge',
`homepage_pow_difficulty ${stats.difficulty}`,
'# TYPE homepage_invalid_proofs_total counter',
`homepage_invalid_proofs_total ${stats.invalidProofs}`,
'# TYPE homepage_sessions_started_total counter',
`homepage_sessions_started_total ${stats.started}`,
'# TYPE homepage_sessions_resumed_total counter',
`homepage_sessions_resumed_total ${stats.resumed}`,
'# TYPE homepage_sessions_refused_total counter',
...Object.entries(stats.refused).map(([reason, count]) => `homepage_sessions_refused_total{reason="${reason}"} ${count}`),
'# TYPE homepage_sessions_ended_total counter',
...Object.entries(stats.ended).map(([reason, count]) => `homepage_sessions_ended_total{reason="${reason}"} ${count}`),
'',
];
return lines.join('\n');
}
+1
View File
@@ -16,6 +16,7 @@
<a href="/datenschutz">datenschutz</a> <a href="/datenschutz">datenschutz</a>
</nav> </nav>
</header> </header>
<div id="notice" class="notice" role="status" aria-live="polite" hidden></div>
<main id="terminal" aria-label="Terminal"></main> <main id="terminal" aria-label="Terminal"></main>
<div id="keybar" class="keybar" hidden></div> <div id="keybar" class="keybar" hidden></div>
<noscript> <noscript>
+14 -2
View File
@@ -63,13 +63,25 @@ export async function playBoot(terminal: Terminal, touch: boolean): Promise<void
const END_MESSAGES: Record<EndReason, string> = { const END_MESSAGES: Record<EndReason, string> = {
closed: 'session closed', closed: 'session closed',
expired: 'session expired (time limit reached)', expired: 'session expired (time limit reached)',
idle: 'session ended after a while without input',
error: 'the sandbox could not be started', error: 'the sandbox could not be started',
gone: 'the previous session has ended',
lost: 'connection lost', lost: 'connection lost',
rejected: 'the server refused the connection', rejected: 'the server is not reachable',
busy: 'all sandboxes and the queue are taken, try again in a few minutes',
}; };
export function endMessage(reason: EndReason, touch: boolean): string { 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')}`; 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}`; export function solvingMessage(difficulty: number): string {
return `\r\x1b[2K${DIM}solving a proof of work puzzle against abuse (${difficulty} bits)...${RESET}`;
}
/** Rewrites the current line, so position updates do not pile up. */
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`;
+66 -18
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { TerminalConnection, terminalUrl, type EndReason } from './connection.ts'; import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
class FakeSocket class FakeSocket
{ {
@@ -22,18 +22,35 @@ class FakeSocket
this.readyState = WebSocket.OPEN; this.readyState = WebSocket.OPEN;
this.onopen?.(); this.onopen?.();
} }
receive(message: unknown): void {
this.onmessage?.({ data: JSON.stringify(message) });
}
} }
function connect() function connect(token?: string)
{ {
const socket = new FakeSocket(); const socket = new FakeSocket();
const events = { ready: 0, output: [] as string[], ended: [] as EndReason[] }; const events = {
solving: [] as number[],
queued: [] as number[],
ready: [] as Ready[],
output: [] as string[],
idle: [] as number[],
ended: [] as EndReason[],
};
const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, { const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, token, {
ready: () => events.ready++, solving: (difficulty) => events.solving.push(difficulty),
output: (data) => events.output.push(new TextDecoder().decode(data)), queued: (position) => events.queued.push(position),
ended: (reason) => events.ended.push(reason), ready: (session) => events.ready.push(session),
}, () => socket as unknown as WebSocket); output: (data) => events.output.push(new TextDecoder().decode(data)),
idle: (seconds) => events.idle.push(seconds),
ended: (reason) => events.ended.push(reason),
}, {
createSocket: () => socket as unknown as WebSocket,
solve: async (challenge, difficulty) => challenge.length * 1000 + difficulty,
});
return { socket, events, connection }; return { socket, events, connection };
} }
@@ -46,7 +63,19 @@ describe('terminalUrl', () => {
}); });
describe('TerminalConnection', () => { describe('TerminalConnection', () => {
it('greets with the terminal size and uses binary frames', () => { it('answers the challenge with a hello carrying the solved nonce and the latest size', async () => {
const { socket, events, connection } = connect();
socket.open();
socket.receive({ type: 'challenge', challenge: 'abc', difficulty: 20 });
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}');
});
it('uses binary frames for terminal input', () => {
const { socket, connection } = connect(); const { socket, connection } = connect();
connection.input('ignored before open'); connection.input('ignored before open');
@@ -54,28 +83,46 @@ describe('TerminalConnection', () => {
connection.input('ls\r'); connection.input('ls\r');
expect(socket.binaryType).toBe('arraybuffer'); expect(socket.binaryType).toBe('arraybuffer');
expect(socket.sent[0]).toBe('{"type":"hello","cols":80,"rows":24}'); expect(new TextDecoder().decode(socket.sent[0] as Uint8Array)).toBe('ls\r');
expect(new TextDecoder().decode(socket.sent[1] as Uint8Array)).toBe('ls\r'); expect(socket.sent).toHaveLength(1);
expect(socket.sent).toHaveLength(2);
}); });
it('passes output and readiness on', () => { it('resumes with a token and ignores the challenge', async () => {
const { socket, events } = connect('A'.repeat(22));
socket.open();
socket.receive({ type: 'challenge', challenge: 'abc', difficulty: 20 });
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', () => {
const { socket, events } = connect(); const { socket, events } = connect();
socket.open(); socket.open();
socket.onmessage?.({ data: '{"type":"ready"}' }); socket.receive({ type: 'queued', position: 3 });
socket.receive({ type: 'ready', token: 't', expiresAt: 1, resumed: false });
socket.onmessage?.({ data: new TextEncoder().encode('hi').buffer }); socket.onmessage?.({ data: new TextEncoder().encode('hi').buffer });
socket.receive({ type: 'idle', secondsLeft: 30 });
expect(events.ready).toBe(1); expect(events.queued).toEqual([3]);
expect(events.ready).toEqual([{ token: 't', expiresAt: 1, resumed: false }]);
expect(events.output).toEqual(['hi']); expect(events.output).toEqual(['hi']);
expect(events.idle).toEqual([30]);
}); });
it('reports the server reason, a lost connection, or a refusal', () => { it('reports the server reason, a refusal, a lost connection, or an unreachable server', () => {
const expired = connect(); const expired = connect();
expired.socket.open(); expired.socket.open();
expired.socket.onmessage?.({ data: '{"type":"exit","reason":"expired"}' }); expired.socket.receive({ type: 'exit', reason: 'expired' });
expired.socket.close(); expired.socket.close();
const refused = connect();
refused.socket.open();
refused.socket.receive({ type: 'refused', reason: 'busy' });
refused.socket.close();
const lost = connect(); const lost = connect();
lost.socket.open(); lost.socket.open();
lost.socket.close(); lost.socket.close();
@@ -85,6 +132,7 @@ describe('TerminalConnection', () => {
rejected.socket.close(); rejected.socket.close();
expect(expired.events.ended).toEqual(['expired']); expect(expired.events.ended).toEqual(['expired']);
expect(refused.events.ended).toEqual(['busy']);
expect(lost.events.ended).toEqual(['lost']); expect(lost.events.ended).toEqual(['lost']);
expect(rejected.events.ended).toEqual(['rejected']); expect(rejected.events.ended).toEqual(['rejected']);
}); });
@@ -94,6 +142,6 @@ describe('TerminalConnection', () => {
socket.open(); socket.open();
connection.inputBinary('\x1b[M\xff'); connection.inputBinary('\x1b[M\xff');
expect([...(socket.sent[1] as Uint8Array)]).toEqual([0x1b, 0x5b, 0x4d, 0xff]); expect([...(socket.sent[0] as Uint8Array)]).toEqual([0x1b, 0x5b, 0x4d, 0xff]);
}); });
}); });
+67 -13
View File
@@ -2,47 +2,69 @@ import {
TERMINAL_PATH, TERMINAL_PATH,
type ClientMessage, type ClientMessage,
type ExitReason, type ExitReason,
type RefusalReason,
type ServerMessage, type ServerMessage,
type TerminalSize, type TerminalSize,
} from '@homepage/protocol/terminal'; } from '@homepage/protocol/terminal';
import { solveInWorker, type Solver } from './solver.ts';
/** Why a session ended: the server's reason, or what the browser observed. */ /** Why a session ended: the server's reason, or what the browser observed. */
export type EndReason = ExitReason | 'lost' | 'rejected'; export type EndReason = ExitReason | RefusalReason | 'lost' | 'rejected';
export type Ready = { token: string; expiresAt: number; resumed: boolean };
export type ConnectionEvents = { export type ConnectionEvents = {
ready(): void; solving(difficulty: number): void;
output(data: Uint8Array): void; queued(position: number): void;
ended(reason: EndReason): void; ready(session: Ready): void;
output(data: Uint8Array): void;
idle(secondsLeft: number): void;
ended(reason: EndReason): void;
}; };
export type SocketFactory = (url: string) => WebSocket; export type SocketFactory = (url: string) => WebSocket;
export type ConnectionOptions = {
createSocket?: SocketFactory;
solve?: Solver;
};
export function terminalUrl(location: Pick<Location, 'protocol' | 'host'>): string export function terminalUrl(location: Pick<Location, 'protocol' | 'host'>): string
{ {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'; const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
return `${scheme}://${location.host}${TERMINAL_PATH}`; return `${scheme}://${location.host}${TERMINAL_PATH}`;
} }
/** One sandbox session over a WebSocket, from the hello until it ends. */ /**
* One WebSocket to the backend. It either asks for a new sandbox, after
* solving the server's proof of work, or resumes an existing one with a token.
* It reports everything until the socket closes.
*/
export class TerminalConnection export class TerminalConnection
{ {
private readonly socket: WebSocket; private readonly socket: WebSocket;
private readonly events: ConnectionEvents; private readonly events: ConnectionEvents;
private readonly encoder = new TextEncoder(); private readonly encoder = new TextEncoder();
private exitReason?: ExitReason; private readonly token?: string;
private readonly solve: Solver;
private size: TerminalSize;
private endReason?: ExitReason | RefusalReason;
private opened = false; private opened = false;
private ended = false; private ended = false;
constructor(url: string, size: TerminalSize, events: ConnectionEvents, createSocket: SocketFactory = (target) => new WebSocket(target)) constructor(url: string, size: TerminalSize, token: string | undefined, events: ConnectionEvents, options: ConnectionOptions = {})
{ {
this.events = events; this.events = events;
this.socket = createSocket(url); this.size = size;
this.token = token;
this.solve = options.solve ?? solveInWorker;
this.socket = (options.createSocket ?? ((target) => new WebSocket(target)))(url);
this.socket.binaryType = 'arraybuffer'; this.socket.binaryType = 'arraybuffer';
this.socket.onopen = () => this.socket.onopen = () =>
{ {
this.opened = true; this.opened = true;
this.control({ type: 'hello', ...size }); if (token) this.control({ type: 'resume', token, ...this.size });
}; };
this.socket.onmessage = (event: MessageEvent) => this.socket.onmessage = (event: MessageEvent) =>
@@ -54,15 +76,36 @@ export class TerminalConnection
} }
const message = JSON.parse(String(event.data)) as ServerMessage; const message = JSON.parse(String(event.data)) as ServerMessage;
if (message.type === 'ready') this.events.ready(); switch (message.type)
else this.exitReason = message.reason; {
case 'challenge':
if (!this.token) this.greet(message.challenge, message.difficulty);
break;
case 'queued':
this.events.queued(message.position);
break;
case 'ready':
this.events.ready({ token: message.token, expiresAt: message.expiresAt, resumed: message.resumed });
break;
case 'idle':
this.events.idle(message.secondsLeft);
break;
case 'exit':
case 'refused':
this.endReason = message.reason;
break;
}
}; };
this.socket.onclose = () => this.socket.onclose = () =>
{ {
if (this.ended) return; if (this.ended) return;
this.ended = true; this.ended = true;
this.events.ended(this.exitReason ?? (this.opened ? 'lost' : 'rejected')); this.events.ended(this.endReason ?? (this.opened ? 'lost' : 'rejected'));
}; };
} }
@@ -75,7 +118,9 @@ export class TerminalConnection
this.send(Uint8Array.from(data, (character) => character.charCodeAt(0) & 0xff)); this.send(Uint8Array.from(data, (character) => character.charCodeAt(0) & 0xff));
} }
resize(size: TerminalSize): void { resize(size: TerminalSize): void
{
this.size = size;
this.control({ type: 'resize', ...size }); this.control({ type: 'resize', ...size });
} }
@@ -83,6 +128,15 @@ export class TerminalConnection
this.socket.close(); this.socket.close();
} }
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(),
);
}
private control(message: ClientMessage): void { private control(message: ClientMessage): void {
this.send(JSON.stringify(message)); this.send(JSON.stringify(message));
} }
+115 -23
View File
@@ -7,14 +7,20 @@ import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links'; import { WebLinksAddon } from '@xterm/addon-web-links';
import { WebglAddon } from '@xterm/addon-webgl'; import { WebglAddon } from '@xterm/addon-webgl';
import { Terminal } from '@xterm/xterm'; import { Terminal } from '@xterm/xterm';
import { CONNECTING_MESSAGE, endMessage, playBoot } from './boot.ts'; import { CONNECTING_MESSAGE, endMessage, playBoot, queueMessage, solvingMessage } from './boot.ts';
import { TerminalConnection, terminalUrl } from './connection.ts'; import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
import { createKeybar } from './keybar.ts'; import { createKeybar } from './keybar.ts';
import { savedToken } from './token.ts';
type State = 'booting' | 'idle' | 'connecting' | 'active'; type State = 'booting' | 'idle' | 'connecting' | 'active' | 'reconnecting';
/** Reconnecting stops shortly before the server's grace period would end anyway. */
const RECONNECT_DEADLINE_MS = 40_000;
const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000];
const touch = window.matchMedia('(pointer: coarse)').matches; const touch = window.matchMedia('(pointer: coarse)').matches;
const element = document.getElementById('terminal')!; const element = document.getElementById('terminal')!;
const notice = document.getElementById('notice')!;
const terminal = new Terminal({ const terminal = new Terminal({
fontFamily: '"JetBrains Mono", monospace', fontFamily: '"JetBrains Mono", monospace',
@@ -57,33 +63,117 @@ terminal.focus();
let state: State = 'booting'; let state: State = 'booting';
let connection: TerminalConnection | undefined; let connection: TerminalConnection | undefined;
let reconnectStarted = 0;
let reconnectAttempt = 0;
function showNotice(text: string): void
{
notice.textContent = text;
notice.hidden = false;
}
function hideNotice(): void {
notice.hidden = true;
}
function size() {
return { cols: terminal.cols, rows: terminal.rows };
}
/**
* Opens a connection. With a token it resumes; after a page reload the
* screen is empty, so Ctrl-L asks the shell or program to redraw itself.
*/
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) =>
{
savedToken.set(session.token);
hideNotice();
reconnectAttempt = 0;
if (!session.resumed) terminal.reset();
state = 'active';
terminal.focus();
if (session.resumed && redraw) connection?.input('\x0c');
},
output: (data) => terminal.write(data),
idle: (secondsLeft) => showNotice(`no input for a while, the session ends in ${secondsLeft} seconds unless you type`),
ended: (reason) => ended(reason),
});
}
function ended(reason: EndReason): void
{
connection = undefined;
const dropped = reason === 'lost' || reason === 'rejected';
if (dropped && (state === 'active' || state === 'reconnecting') && savedToken.get())
{
reconnect();
return;
}
savedToken.clear();
hideNotice();
if (state === 'booting')
{
void boot();
return;
}
state = 'idle';
terminal.write(endMessage(reason, touch));
}
function reconnect(): void
{
if (state !== 'reconnecting')
{
state = 'reconnecting';
reconnectStarted = Date.now();
}
if (Date.now() - reconnectStarted > RECONNECT_DEADLINE_MS)
{
state = 'active';
savedToken.clear();
ended('lost');
return;
}
showNotice('connection lost, reconnecting...');
const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt++, RECONNECT_DELAYS_MS.length - 1)];
setTimeout(() => connect(savedToken.get()), delay);
}
function start(): void function start(): void
{ {
state = 'connecting'; state = 'connecting';
terminal.write(CONNECTING_MESSAGE); terminal.write(CONNECTING_MESSAGE);
connect();
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 function input(data: string): void
{ {
if (state === 'active') connection?.input(data); if (state === 'active')
else if (state === 'idle') start(); {
hideNotice();
connection?.input(data);
}
else if (state === 'idle') start();
}
async function boot(): Promise<void>
{
state = 'booting';
await playBoot(terminal, touch);
state = 'idle';
} }
terminal.onData(input); terminal.onData(input);
@@ -91,5 +181,7 @@ terminal.onBinary((data) => { if (state === 'active') connection?.inputBinary(da
terminal.onResize(({ cols, rows }) => connection?.resize({ cols, rows })); terminal.onResize(({ cols, rows }) => connection?.resize({ cols, rows }));
new ResizeObserver(() => fit.fit()).observe(element); new ResizeObserver(() => fit.fit()).observe(element);
await playBoot(terminal, touch); // A reload within the grace period picks the running sandbox up again.
state = 'idle'; const token = savedToken.get();
if (token) connect(token, true);
else void boot();
+10
View File
@@ -0,0 +1,10 @@
import { solveProof } from '@homepage/protocol/proof';
type Task = { challenge: string; difficulty: number };
const scope = globalThis as unknown as {
onmessage: ((event: MessageEvent<Task>) => void) | null;
postMessage: (nonce: number | undefined) => void;
};
scope.onmessage = ({ data }) => scope.postMessage(solveProof(data.challenge, data.difficulty));
+22
View File
@@ -0,0 +1,22 @@
export type Solver = (challenge: string, difficulty: number) => Promise<number>;
/** Solves the proof of work in a worker, so the page stays responsive meanwhile. */
export const solveInWorker: Solver = (challenge, difficulty) => new Promise((resolve, reject) =>
{
const worker = new Worker(new URL('./proof.worker.ts', import.meta.url), { type: 'module' });
worker.onmessage = ({ data }: MessageEvent<number | undefined>) =>
{
worker.terminate();
if (data === undefined) reject(new Error('no solution found'));
else resolve(data);
};
worker.onerror = (event) =>
{
worker.terminate();
reject(new Error(event.message));
};
worker.postMessage({ challenge, difficulty });
});
+19
View File
@@ -5,6 +5,7 @@
--text: #d6dde6; --text: #d6dde6;
--muted: #7d8794; --muted: #7d8794;
--accent: #7ee787; --accent: #7ee787;
--warning: #e3b341;
color-scheme: dark; color-scheme: dark;
font-family: "JetBrains Mono", monospace; font-family: "JetBrains Mono", monospace;
@@ -61,6 +62,19 @@ body {
text-decoration: underline; text-decoration: underline;
} }
.notice {
flex: none;
padding: 0.35rem 1rem;
border-bottom: 1px solid var(--border);
background: var(--surface);
color: var(--warning);
font-size: 0.8rem;
}
.notice[hidden] {
display: none;
}
#terminal { #terminal {
flex: 1; flex: 1;
min-height: 0; min-height: 0;
@@ -72,6 +86,11 @@ body {
padding: 0.5rem 0 0 1rem; padding: 0.5rem 0 0 1rem;
} }
/* xterm paints its viewport black, which would show in the padding. */
#terminal .xterm-viewport {
background-color: var(--background);
}
.keybar { .keybar {
display: flex; display: flex;
flex: none; flex: none;
+26
View File
@@ -0,0 +1,26 @@
const KEY = 'sandbox-token';
/**
* The reconnect token of the current session. It lives in sessionStorage, so
* it survives reloads of this tab but no other tab sees it. Storage can be
* unavailable (private modes, blocked site data), which only disables resuming.
*/
export const savedToken = {
get(): string | undefined
{
try { return sessionStorage.getItem(KEY) ?? undefined; }
catch { return undefined; }
},
set(token: string): void
{
try { sessionStorage.setItem(KEY, token); }
catch { /* Resuming is a convenience; the session works without it. */ }
},
clear(): void
{
try { sessionStorage.removeItem(KEY); }
catch { /* Nothing was stored, so there is nothing to clear. */ }
},
};
+4 -2
View File
@@ -80,9 +80,11 @@ pull_image docker "$spawner_tag"
pull_image docker "$backend_tag" pull_image docker "$backend_tag"
digest() { "$1" image inspect --format '{{index .RepoDigests 0}}' "$2"; } digest() { "$1" image inspect --format '{{index .RepoDigests 0}}' "$2"; }
# The spawner runs as 10001 and shares group 10100 with the backend. # The spawner runs as 10001 and shares group 10100 with the backend, which
install -d -m 0755 runtime runtime/status # runs as 10002 and writes the status file that sandboxes read.
install -d -m 0755 runtime
install -d -o 10001 -g 10100 -m 0750 runtime/spawner install -d -o 10001 -g 10100 -m 0750 runtime/spawner
install -d -o 10002 -g 10002 -m 0755 runtime/status
cat > runtime/deploy.env <<EOF cat > runtime/deploy.env <<EOF
SANDBOX_IMAGE=$(digest sandbox_docker "$sandbox_tag") SANDBOX_IMAGE=$(digest sandbox_docker "$sandbox_tag")
SPAWNER_IMAGE=$(digest docker "$spawner_tag") SPAWNER_IMAGE=$(digest docker "$spawner_tag")
+6
View File
@@ -41,11 +41,17 @@ services:
depends_on: [spawner] depends_on: [spawner]
ports: ports:
- "127.0.0.1:${BACKEND_PORT:-8380}:8080" - "127.0.0.1:${BACKEND_PORT:-8380}:8080"
- "127.0.0.1:${METRICS_PORT:-9380}:9090"
environment: environment:
SPAWNER_SOCKET: /run/spawner/spawner.sock SPAWNER_SOCKET: /run/spawner/spawner.sock
STATUS_DIR: /run/status
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://security-command.org} ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://security-command.org}
MAX_SESSIONS: ${MAX_SESSIONS:-12}
MAX_QUEUE: ${MAX_QUEUE:-20}
POW_DIFFICULTY: ${POW_DIFFICULTY:-20}
volumes: volumes:
- ./runtime/spawner:/run/spawner - ./runtime/spawner:/run/spawner
- ./runtime/status:/run/status
logging: logging:
driver: json-file driver: json-file
options: options:
+11
View File
@@ -9,3 +9,14 @@ BACKEND_PORT=8380
# Comma separated origins allowed to open terminal sessions. # Comma separated origins allowed to open terminal sessions.
ALLOWED_ORIGINS=https://security-command.org ALLOWED_ORIGINS=https://security-command.org
# Local port of the Prometheus metrics, published to loopback only.
METRICS_PORT=9380
# Session limits.
MAX_SESSIONS=12
MAX_QUEUE=20
# Leading zero bits of SHA-256 a new sandbox costs while the server is mostly
# idle. Each extra bit doubles the work; 20 takes about a second on a desktop.
POW_DIFFICULTY=20
-2
View File
@@ -5,14 +5,12 @@ location / {
proxy_pass http://127.0.0.1:8380; proxy_pass http://127.0.0.1:8380;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
} }
location = /ws { location = /ws {
proxy_pass http://127.0.0.1:8380; proxy_pass http://127.0.0.1:8380;
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Upgrade $http_upgrade; proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade"; proxy_set_header Connection "upgrade";
proxy_read_timeout 120s; proxy_read_timeout 120s;
+2 -1
View File
@@ -4,6 +4,7 @@
"type": "module", "type": "module",
"exports": { "exports": {
".": "./src/index.ts", ".": "./src/index.ts",
"./terminal": "./src/terminal.ts" "./terminal": "./src/terminal.ts",
"./proof": "./src/proof.ts"
} }
} }
+1
View File
@@ -2,3 +2,4 @@ export * from './spawner.ts';
export * from './lines.ts'; export * from './lines.ts';
export * from './client.ts'; export * from './client.ts';
export * from './terminal.ts'; export * from './terminal.ts';
export * from './proof.ts';
+35
View File
@@ -0,0 +1,35 @@
import { createHash } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import { sha256, solveProof, verifyProof } from './proof.ts';
const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
describe('sha256', () => {
it.each(['', 'abc', 'challenge:12345', 'x'.repeat(55), 'x'.repeat(56), 'y'.repeat(64), 'z'.repeat(200)])(
'matches node for a message of %#',
(message) => {
expect(hex(sha256(Buffer.from(message)))).toBe(createHash('sha256').update(message).digest('hex'));
},
);
});
describe('proof of work', () => {
it('finds a nonce the verifier accepts', () => {
const nonce = solveProof('AAAAAAAAAAAAAAAAAAAAAA', 12)!;
expect(verifyProof('AAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(true);
expect(verifyProof('BAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(false);
});
it('agrees with node about the leading zero bits', () => {
const nonce = solveProof('challenge', 10)!;
const digest = createHash('sha256').update(`challenge:${nonce}`).digest();
expect(digest[0]).toBe(0);
expect(digest[1]! >> 6).toBe(0);
});
it('stops after the given number of attempts', () => {
expect(solveProof('challenge', 32, 0, 100)).toBeUndefined();
});
});
+128
View File
@@ -0,0 +1,128 @@
/**
* Proof of work for new sandboxes: find a nonce so that SHA-256 of
* "challenge:nonce" starts with a number of zero bits. Browser and backend
* share this file, so both compute exactly the same hash. Free of Node imports.
*/
const K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
const rotate = (value: number, bits: number) => (value >>> bits) | (value << (32 - bits));
/** Processes one 64 byte block. The first 16 words of w hold the block; w has room for 64. */
function compress(state: Uint32Array, w: Uint32Array): void
{
for (let i = 16; i < 64; i++)
{
const s0 = rotate(w[i - 15]!, 7) ^ rotate(w[i - 15]!, 18) ^ (w[i - 15]! >>> 3);
const s1 = rotate(w[i - 2]!, 17) ^ rotate(w[i - 2]!, 19) ^ (w[i - 2]! >>> 10);
w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) | 0;
}
let [a, b, c, d, e, f, g, h] = state as unknown as number[];
for (let i = 0; i < 64; i++)
{
const t1 = (h! + (rotate(e!, 6) ^ rotate(e!, 11) ^ rotate(e!, 25)) + ((e! & f!) ^ (~e! & g!)) + K[i]! + w[i]!) | 0;
const t2 = ((rotate(a!, 2) ^ rotate(a!, 13) ^ rotate(a!, 22)) + ((a! & b!) ^ (a! & c!) ^ (b! & c!))) | 0;
h = g; g = f; f = e; e = (d! + t1) | 0;
d = c; c = b; b = a; a = (t1 + t2) | 0;
}
state[0] = (state[0]! + a!) | 0; state[1] = (state[1]! + b!) | 0;
state[2] = (state[2]! + c!) | 0; state[3] = (state[3]! + d!) | 0;
state[4] = (state[4]! + e!) | 0; state[5] = (state[5]! + f!) | 0;
state[6] = (state[6]! + g!) | 0; state[7] = (state[7]! + h!) | 0;
}
export function sha256(message: Uint8Array): Uint8Array
{
const blocks = Math.ceil((message.length + 9) / 64);
const padded = new Uint8Array(blocks * 64);
padded.set(message);
padded[message.length] = 0x80;
const view = new DataView(padded.buffer);
view.setUint32(padded.length - 8, Math.floor(message.length / 0x20000000));
view.setUint32(padded.length - 4, (message.length * 8) >>> 0);
const state = Uint32Array.from(INITIAL);
const w = new Uint32Array(64);
for (let block = 0; block < blocks; block++)
{
for (let i = 0; i < 16; i++) w[i] = view.getUint32(block * 64 + i * 4);
compress(state, w);
}
const digest = new Uint8Array(32);
const output = new DataView(digest.buffer);
state.forEach((word, i) => output.setUint32(i * 4, word));
return digest;
}
function leadingZeroBits(words: ArrayLike<number>): number
{
let bits = 0;
for (let i = 0; i < words.length; i++)
{
const zeros = Math.clz32(words[i]!);
bits += zeros;
if (zeros < 32) break;
}
return bits;
}
function encode(text: string): Uint8Array {
return Uint8Array.from(text, (character) => character.charCodeAt(0) & 0xff);
}
export function verifyProof(challenge: string, nonce: number, difficulty: number): boolean
{
const digest = sha256(encode(`${challenge}:${nonce}`));
const view = new DataView(digest.buffer);
const words = Array.from({ length: 8 }, (_, i) => view.getUint32(i * 4));
return leadingZeroBits(words) >= difficulty;
}
/**
* Searches nonces from start for at most count attempts. Challenge and nonce
* fit into one block, so the block is rebuilt in place without allocations.
*/
export function solveProof(challenge: string, difficulty: number, start = 0, count = Number.MAX_SAFE_INTEGER): number | undefined
{
const prefix = encode(`${challenge}:`);
if (prefix.length + 16 > 55) throw new Error('challenge too long for a single block');
const block = new Uint8Array(64);
const view = new DataView(block.buffer);
const state = new Uint32Array(8);
const w = new Uint32Array(64);
block.set(prefix);
for (let nonce = start; nonce < start + count; nonce++)
{
const digits = String(nonce);
const length = prefix.length + digits.length;
for (let i = 0; i < digits.length; i++) block[prefix.length + i] = digits.charCodeAt(i);
block[length] = 0x80;
block.fill(0, length + 1, 60);
view.setUint32(60, length * 8);
for (let i = 0; i < 16; i++) w[i] = view.getUint32(i * 4);
state.set(INITIAL);
compress(state, w);
if (leadingZeroBits(state) >= difficulty) return nonce;
}
return undefined;
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest';
import { InvalidMessageError, parseClientMessage } from './terminal.ts';
const TOKEN = 'A'.repeat(21) + '_';
const parse = (value: unknown) => parseClientMessage(JSON.stringify(value));
describe('parseClientMessage', () => {
it('accepts hello, resize and resume', () => {
expect(parse({ type: 'hello', nonce: 7, cols: 80, rows: 24 })).toEqual({ type: 'hello', nonce: 7, cols: 80, rows: 24 });
expect(parse({ type: 'resize', cols: 0, rows: 9999 })).toEqual({ type: 'resize', cols: 1, rows: 500 });
expect(parse({ type: 'resume', token: TOKEN, cols: 80, rows: 24 })).toEqual({
type: 'resume',
token: TOKEN,
cols: 80,
rows: 24,
});
});
it.each([
['unknown type', { type: 'exec', cols: 80, rows: 24 }],
['missing size', { type: 'hello', nonce: 1 }],
['missing nonce', { type: 'hello', cols: 80, rows: 24 }],
['negative nonce', { type: 'hello', nonce: -1, cols: 80, rows: 24 }],
['fractional nonce', { type: 'hello', nonce: 1.5, cols: 80, rows: 24 }],
['short token', { type: 'resume', token: 'abc', cols: 80, rows: 24 }],
['token with symbols', { type: 'resume', token: 'A'.repeat(21) + '/', cols: 80, rows: 24 }],
['inherited type', JSON.parse('{"__proto__":{"type":"hello"},"nonce":1,"cols":80,"rows":24}')],
])('rejects %s', (_name, value) => {
expect(() => parse(value)).toThrow(InvalidMessageError);
});
it('rejects oversized messages', () => {
expect(() => parseClientMessage(' '.repeat(2000))).toThrow(InvalidMessageError);
});
});
+41 -8
View File
@@ -8,17 +8,30 @@ export const TERMINAL_PATH = '/ws';
export const MAX_CONTROL_BYTES = 1024; export const MAX_CONTROL_BYTES = 1024;
export const MAX_TERMINAL_SIZE = 500; export const MAX_TERMINAL_SIZE = 500;
/** Reconnect tokens are 16 random bytes in base64url. */
const TOKEN = /^[A-Za-z0-9_-]{22}$/;
export type TerminalSize = { cols: number; rows: number }; export type TerminalSize = { cols: number; rows: number };
/** A new sandbox needs a nonce that solves the connection's challenge, see proof.ts. */
export type ClientMessage = export type ClientMessage =
| ({ type: 'hello' } & TerminalSize) | ({ type: 'hello'; nonce: number } & TerminalSize)
| ({ type: 'resume'; token: string } & TerminalSize)
| ({ type: 'resize' } & TerminalSize); | ({ type: 'resize' } & TerminalSize);
export type ExitReason = 'closed' | 'expired' | 'error'; /** Why the server ended a session. "gone" answers a resume whose session no longer exists. */
export type ExitReason = 'closed' | 'expired' | 'idle' | 'error' | 'gone';
/** Why the server did not start a session. */
export type RefusalReason = 'busy';
export type ServerMessage = export type ServerMessage =
| { type: 'ready' } | { type: 'challenge'; challenge: string; difficulty: number }
| { type: 'exit'; reason: ExitReason }; | { type: 'queued'; position: number }
| { type: 'ready'; token: string; expiresAt: number; resumed: boolean }
| { type: 'idle'; secondsLeft: number }
| { type: 'exit'; reason: ExitReason }
| { type: 'refused'; reason: RefusalReason };
export class InvalidMessageError extends Error {} export class InvalidMessageError extends Error {}
@@ -43,9 +56,29 @@ export function parseClientMessage(text: string): ClientMessage
if (typeof input !== 'object' || input === null || Array.isArray(input)) invalid('message must be an object'); if (typeof input !== 'object' || input === null || Array.isArray(input)) invalid('message must be an object');
const message = input as Record<string, unknown>; const message = input as Record<string, unknown>;
const type = Object.hasOwn(message, 'type') ? message.type : undefined; const field = (name: string) => (Object.hasOwn(message, name) ? message[name] : undefined);
if (type !== 'hello' && type !== 'resize') invalid('unknown message type'); const type = field('type');
const terminal = { cols: size(field('cols')), rows: size(field('rows')) };
return { type, cols: size(message.cols), rows: size(message.rows) }; switch (type)
{
case 'hello': {
const nonce = field('nonce');
if (typeof nonce !== 'number' || !Number.isSafeInteger(nonce) || nonce < 0) invalid('invalid nonce');
return { type, nonce, ...terminal };
}
case 'resize':
return { type, ...terminal };
case 'resume': {
const token = field('token');
if (typeof token !== 'string' || !TOKEN.test(token)) invalid('invalid token');
return { type, token, ...terminal };
}
default:
return invalid('unknown message type');
}
} }