Introduce backend app for WebSocket terminal sessions and sandbox orchestration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-13 00:22:49 +02:00
1 parent 7b1df2607e
commit 91049379f7
22 files changed
+808 -11

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
# Build context is the repository root.
FROM node:24-alpine AS build
WORKDIR /src
COPY . .
RUN corepack pnpm install --frozen-lockfile \
&& corepack pnpm --filter @homepage/backend build
FROM node:24-alpine
COPY --from=build /src/apps/backend/dist/backend.js /app/backend.js
USER 10002:10002
EXPOSE 8080
CMD ["node", "/app/backend.js"]
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@homepage/backend",
"private": true,
"type": "module",
"scripts": {
"build": "esbuild src/main.ts --bundle --platform=node --target=node24 --format=esm --external:bufferutil --external:utf-8-validate --banner:js=\"import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);\" --outfile=dist/backend.js"
},
"dependencies": {
"@homepage/protocol": "workspace:*",
"ws": "^8.22.0"
},
"devDependencies": {
"@types/ws": "^8.18.2"
}
}
+28
View File
@@ -0,0 +1,28 @@
export type BackendConfig = {
host: string;
port: number;
spawnerSocket: string;
/** Exact origins allowed to open terminal sessions. Empty allows every origin. */
allowedOrigins: string[];
sessionSeconds: number;
outputRate: number;
};
function integer(env: NodeJS.ProcessEnv, name: string, fallback: number): number
{
const value = Number(env[name] ?? fallback);
if (!Number.isInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
return value;
}
export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
{
return {
host: env.HOST ?? '0.0.0.0',
port: integer(env, 'PORT', 8080),
spawnerSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock',
allowedOrigins: (env.ALLOWED_ORIGINS ?? '').split(',').map((origin) => origin.trim()).filter(Boolean),
sessionSeconds: integer(env, 'SESSION_SECONDS', 20 * 60),
outputRate: integer(env, 'OUTPUT_BYTES_PER_SECOND', 1024 * 1024),
};
}
+24
View File
@@ -0,0 +1,24 @@
import { SpawnerClient } from '@homepage/protocol';
import { loadConfig } from './config.ts';
import { createBackend } from './server.ts';
const log = (message: string) => console.log(`[backend] ${message}`);
const config = loadConfig(process.env);
const spawner = new SpawnerClient(config.spawnerSocket);
// Sessions live in memory, so sandboxes of a previous backend process are unreachable.
const orphans = await spawner.list();
await Promise.all(orphans.map((container) => spawner.kill(container.containerId)));
if (orphans.length > 0) log(`removed ${orphans.length} orphaned sandbox(es)`);
const server = createBackend(config, spawner, log);
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
for (const signal of ['SIGTERM', 'SIGINT'] as const)
{
process.once(signal, () => {
server.close();
process.exit(0);
});
}
+186
View File
@@ -0,0 +1,186 @@
import type { AddressInfo } from 'node:net';
import type { Server } from 'node:http';
import { duplexPair, type Duplex } from 'node:stream';
import type { ServerMessage } from '@homepage/protocol/terminal';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { WebSocket } from 'ws';
import type { BackendConfig } from './config.ts';
import { createBackend } from './server.ts';
import type { Spawner } from './session.ts';
const CONTAINER = 'aaaaaaaaaaaa';
/** Hands out one in-memory stream pair per spawn; the far end plays the container. */
class FakeSpawner implements Spawner
{
readonly calls: string[] = [];
container?: Duplex;
async spawn(sessionId: string): Promise<string> {
this.calls.push(`spawn ${sessionId.length}`);
return CONTAINER;
}
async attach(): Promise<Duplex>
{
const [backendSide, containerSide] = duplexPair();
this.container = containerSide;
this.calls.push('attach');
backendSide.pause();
return backendSide;
}
async resize(_containerId: string, cols: number, rows: number): Promise<void> {
this.calls.push(`resize ${cols}x${rows}`);
}
async kill(containerId: string): Promise<void> {
this.calls.push(`kill ${containerId}`);
}
}
function until(condition: () => boolean, timeoutMs = 2000): Promise<void>
{
return new Promise((resolve, reject) =>
{
const started = Date.now();
const check = () =>
{
if (condition()) return resolve();
if (Date.now() - started > timeoutMs) return reject(new Error('condition not met in time'));
setTimeout(check, 5);
};
check();
});
}
describe('backend', () => {
let server: Server;
let spawner: FakeSpawner;
let url: string;
let config: BackendConfig;
async function start(overrides: Partial<BackendConfig> = {}): Promise<void>
{
config = {
host: '127.0.0.1',
port: 0,
spawnerSocket: '',
allowedOrigins: ['https://security-command.org'],
sessionSeconds: 60,
outputRate: 1024 * 1024,
...overrides,
};
spawner = new FakeSpawner();
server = createBackend(config, spawner, () => {});
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`;
}
type Client = { socket: WebSocket; messages: ServerMessage[]; output: () => string; closed: Promise<number> };
function connect(origin = 'https://security-command.org'): Promise<Client>
{
return new Promise((resolve, reject) =>
{
const socket = new WebSocket(url, { origin });
const messages: ServerMessage[] = [];
const chunks: Buffer[] = [];
const closed = new Promise<number>((done) => socket.on('close', done));
socket.on('message', (data, isBinary) =>
{
if (isBinary) chunks.push(data as Buffer);
else messages.push(JSON.parse(data.toString()) as ServerMessage);
});
socket.on('open', () => resolve({ socket, messages, output: () => Buffer.concat(chunks).toString(), closed }));
socket.on('error', reject);
});
}
async function ready(): Promise<Client>
{
const client = await connect();
client.socket.send(JSON.stringify({ type: 'hello', cols: 100, rows: 30 }));
await until(() => client.messages.some((message) => message.type === 'ready'));
return client;
}
beforeEach(() => start());
afterEach(() => server.close());
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('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();
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 () => {
const client = await connect();
client.socket.send(Buffer.from('early'));
client.socket.send(JSON.stringify({ type: 'hello', cols: 80, rows: 24 }));
await until(() => client.messages.some((message) => message.type === '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 () => {
server.close();
await start({ outputRate: 1000 });
const client = await ready();
for (let i = 0; i < 5; i++) spawner.container!.write('x'.repeat(1000));
await new Promise((resolve) => setTimeout(resolve, 300));
expect(client.output().length).toBeGreaterThan(0);
expect(client.output().length).toBeLessThan(5000);
});
});
+137
View File
@@ -0,0 +1,137 @@
import { createServer, type IncomingMessage, type Server } from 'node:http';
import type { Duplex } from 'node:stream';
import { InvalidMessageError, parseClientMessage, TERMINAL_PATH } from '@homepage/protocol/terminal';
import { WebSocketServer, type RawData, type WebSocket } from 'ws';
import type { BackendConfig } from './config.ts';
import { Session, type Spawner } from './session.ts';
export type Logger = (message: string) => void;
const MAX_FRAME_BYTES = 64 * 1024;
const HELLO_TIMEOUT_MS = 10_000;
const PING_INTERVAL_MS = 30_000;
/** Close code for protocol violations by the client. */
const POLICY_VIOLATION = 1008;
function reject(socket: Duplex, status: number, reason: string): void
{
socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
}
function originAllowed(config: BackendConfig, request: IncomingMessage): boolean
{
// Without this check, any website could open sessions from its visitors'
// browsers and spend the sandbox slots under their IP addresses.
if (config.allowedOrigins.length === 0) return true;
return config.allowedOrigins.includes(request.headers.origin ?? '');
}
function toBuffer(data: RawData): Buffer
{
if (Buffer.isBuffer(data)) return data;
if (Array.isArray(data)) return Buffer.concat(data);
return Buffer.from(data);
}
function handleConnection(socket: WebSocket, spawner: Spawner, config: BackendConfig, log: Logger): void
{
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): Server
{
const server = createServer((request, response) =>
{
if (request.method === 'GET' && request.url === '/healthz')
{
response.writeHead(200, { 'Content-Type': 'text/plain' }).end('ok');
return;
}
response.writeHead(404, { 'Content-Type': 'text/plain' }).end('not found');
});
const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
const alive = new WeakSet<WebSocket>();
server.on('upgrade', (request, socket, head) =>
{
if (new URL(request.url ?? '/', 'http://backend').pathname !== TERMINAL_PATH) return reject(socket, 404, 'Not Found');
if (!originAllowed(config, request)) return reject(socket, 403, 'Forbidden');
sockets.handleUpgrade(request, socket, head, (websocket) =>
{
alive.add(websocket);
websocket.on('pong', () => alive.add(websocket));
handleConnection(websocket, spawner, config, log);
});
});
// Proxies such as Cloudflare drop idle WebSockets after about 100 seconds.
const pinger = setInterval(() =>
{
for (const websocket of sockets.clients)
{
if (!alive.has(websocket))
{
websocket.terminate();
continue;
}
alive.delete(websocket);
websocket.ping();
}
}, PING_INTERVAL_MS);
server.on('close', () => clearInterval(pinger));
return server;
}
+156
View File
@@ -0,0 +1,156 @@
import { randomBytes } from 'node:crypto';
import type { Duplex } from 'node:stream';
import type { ExitReason, ServerMessage, TerminalSize } from '@homepage/protocol/terminal';
import type { WebSocket } from 'ws';
import { TokenBucket } from './throttle.ts';
export type Spawner = {
spawn(sessionId: string, expiresAt: number): Promise<string>;
attach(containerId: string): Promise<Duplex>;
resize(containerId: string, cols: number, rows: number): Promise<void>;
kill(containerId: string): Promise<void>;
};
export type SessionOptions = {
sessionSeconds: number;
outputRate: number;
log: (message: string) => void;
};
/** Output pauses above the high mark of unsent WebSocket bytes and resumes below the low mark. */
const HIGH_WATER_MARK = 256 * 1024;
const LOW_WATER_MARK = 64 * 1024;
const RECHECK_MS = 25;
/** One visitor's terminal: a WebSocket bridged to one sandbox container. */
export class Session
{
readonly id = randomBytes(12).toString('base64url');
private readonly socket: WebSocket;
private readonly spawner: Spawner;
private readonly options: SessionOptions;
private readonly bucket: TokenBucket;
private containerId?: string;
private stream?: Duplex;
private expiryTimer?: NodeJS.Timeout;
private recheckTimer?: NodeJS.Timeout;
private ended = false;
constructor(socket: WebSocket, spawner: Spawner, options: SessionOptions) {
this.socket = socket;
this.spawner = spawner;
this.options = options;
this.bucket = new TokenBucket(options.outputRate);
}
get started(): boolean {
return this.stream !== undefined;
}
async start(size: TerminalSize): Promise<void>
{
const expiresAt = Math.floor(Date.now() / 1000) + this.options.sessionSeconds;
this.containerId = await this.spawner.spawn(this.id, expiresAt);
if (this.ended) return this.release();
const stream = await this.spawner.attach(this.containerId);
if (this.ended)
{
stream.destroy();
return this.release();
}
this.stream = stream;
stream.on('data', (chunk: Buffer) => this.forward(chunk));
stream.on('end', () => this.end('closed'));
stream.on('close', () => this.end('closed'));
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.options.log(`session ${this.id} started`);
}
input(data: Buffer): void {
this.stream?.write(data);
}
resize({ cols, rows }: TerminalSize): void
{
if (!this.containerId || this.ended) return;
this.spawner.resize(this.containerId, cols, rows).catch(() => {});
}
/** Ends the session, tells the visitor why, and removes the container. */
end(reason: ExitReason): void
{
if (this.ended) return;
this.ended = true;
this.send({ type: 'exit', reason });
this.socket.close(1000);
this.release();
this.options.log(`session ${this.id} ended (${reason})`);
}
/** Cleans up after the WebSocket is already gone. */
dispose(): void
{
if (this.ended) return;
this.ended = true;
this.release();
this.options.log(`session ${this.id} disconnected`);
}
private forward(chunk: Buffer): void
{
if (this.ended) return;
this.socket.send(chunk, { binary: true });
this.bucket.take(chunk.length);
if (this.socket.bufferedAmount > HIGH_WATER_MARK || this.bucket.available() <= 0)
{
this.stream?.pause();
this.scheduleRecheck();
}
}
private scheduleRecheck(): void
{
clearTimeout(this.recheckTimer);
this.recheckTimer = setTimeout(() =>
{
if (this.ended) return;
if (this.socket.bufferedAmount < LOW_WATER_MARK && this.bucket.available() > 0) this.stream?.resume();
else this.scheduleRecheck();
}, Math.max(RECHECK_MS, this.bucket.millisecondsUntilAvailable()));
}
private send(message: ServerMessage): void
{
if (this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(message));
}
private release(): void
{
clearTimeout(this.expiryTimer);
clearTimeout(this.recheckTimer);
this.stream?.destroy();
if (this.containerId)
{
const containerId = this.containerId;
this.spawner.kill(containerId).catch((error: unknown) =>
this.options.log(`could not remove ${containerId.slice(0, 12)}: ${String(error)}`),
);
}
}
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { TokenBucket } from './throttle.ts';
describe('TokenBucket', () => {
it('starts full and goes into debt', () => {
let now = 0;
const bucket = new TokenBucket(1000, 1000, () => now);
bucket.take(1500);
expect(bucket.available()).toBe(-500);
expect(bucket.millisecondsUntilAvailable()).toBe(500);
});
it('refills over time up to its capacity', () => {
let now = 0;
const bucket = new TokenBucket(1000, 1000, () => now);
bucket.take(1000);
now = 250;
expect(bucket.available()).toBe(250);
now = 5000;
expect(bucket.available()).toBe(1000);
expect(bucket.millisecondsUntilAvailable()).toBe(0);
});
});
+41
View File
@@ -0,0 +1,41 @@
/**
* Token bucket that may go into debt: a chunk that was already read is always
* sent, and the stream stays paused until the debt is paid off.
*/
export class TokenBucket
{
readonly rate: number;
readonly capacity: number;
private readonly now: () => number;
private tokens: number;
private last: number;
constructor(rate: number, capacity = rate, now = () => performance.now()) {
this.rate = rate;
this.capacity = capacity;
this.now = now;
this.tokens = capacity;
this.last = now();
}
take(amount: number): void {
this.refill();
this.tokens -= amount;
}
available(): number {
this.refill();
return this.tokens;
}
millisecondsUntilAvailable(): number {
const tokens = this.available();
return tokens > 0 ? 0 : Math.ceil((-tokens / this.rate) * 1000);
}
private refill(): void {
const now = this.now();
this.tokens = Math.min(this.capacity, this.tokens + ((now - this.last) / 1000) * this.rate);
this.last = now;
}
}