Files
security-command.org/apps/backend/src/hub.ts
T

287 lines
8.4 KiB
TypeScript

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;
}
/** Ids of every session that still owns a container, used to tell orphans apart. */
sessionIds(): Set<string> {
return new Set([...this.sessions].map((session) => session.id));
}
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 }));
}
}