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
View File
@@ -16,6 +16,7 @@
<a href="/datenschutz">datenschutz</a>
</nav>
</header>
<div id="notice" class="notice" role="status" aria-live="polite" hidden></div>
<main id="terminal" aria-label="Terminal"></main>
<div id="keybar" class="keybar" hidden></div>
<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> = {
closed: 'session closed',
expired: 'session expired (time limit reached)',
idle: 'session ended after a while without input',
error: 'the sandbox could not be started',
gone: 'the previous session has ended',
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 {
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 { TerminalConnection, terminalUrl, type EndReason } from './connection.ts';
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
class FakeSocket
{
@@ -22,18 +22,35 @@ class FakeSocket
this.readyState = WebSocket.OPEN;
this.onopen?.();
}
receive(message: unknown): void {
this.onmessage?.({ data: JSON.stringify(message) });
}
}
function connect()
function connect(token?: string)
{
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 }, {
ready: () => events.ready++,
output: (data) => events.output.push(new TextDecoder().decode(data)),
ended: (reason) => events.ended.push(reason),
}, () => socket as unknown as WebSocket);
const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, token, {
solving: (difficulty) => events.solving.push(difficulty),
queued: (position) => events.queued.push(position),
ready: (session) => events.ready.push(session),
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 };
}
@@ -46,7 +63,19 @@ describe('terminalUrl', () => {
});
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();
connection.input('ignored before open');
@@ -54,28 +83,46 @@ describe('TerminalConnection', () => {
connection.input('ls\r');
expect(socket.binaryType).toBe('arraybuffer');
expect(socket.sent[0]).toBe('{"type":"hello","cols":80,"rows":24}');
expect(new TextDecoder().decode(socket.sent[1] as Uint8Array)).toBe('ls\r');
expect(socket.sent).toHaveLength(2);
expect(new TextDecoder().decode(socket.sent[0] as Uint8Array)).toBe('ls\r');
expect(socket.sent).toHaveLength(1);
});
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();
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.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.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();
expired.socket.open();
expired.socket.onmessage?.({ data: '{"type":"exit","reason":"expired"}' });
expired.socket.receive({ type: 'exit', reason: 'expired' });
expired.socket.close();
const refused = connect();
refused.socket.open();
refused.socket.receive({ type: 'refused', reason: 'busy' });
refused.socket.close();
const lost = connect();
lost.socket.open();
lost.socket.close();
@@ -85,6 +132,7 @@ describe('TerminalConnection', () => {
rejected.socket.close();
expect(expired.events.ended).toEqual(['expired']);
expect(refused.events.ended).toEqual(['busy']);
expect(lost.events.ended).toEqual(['lost']);
expect(rejected.events.ended).toEqual(['rejected']);
});
@@ -94,6 +142,6 @@ describe('TerminalConnection', () => {
socket.open();
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,
type ClientMessage,
type ExitReason,
type RefusalReason,
type ServerMessage,
type TerminalSize,
} from '@homepage/protocol/terminal';
import { solveInWorker, type Solver } from './solver.ts';
/** 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 = {
ready(): void;
output(data: Uint8Array): void;
ended(reason: EndReason): void;
solving(difficulty: number): void;
queued(position: number): 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 ConnectionOptions = {
createSocket?: SocketFactory;
solve?: Solver;
};
export function terminalUrl(location: Pick<Location, 'protocol' | 'host'>): string
{
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
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
{
private readonly socket: WebSocket;
private readonly events: ConnectionEvents;
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 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.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.onopen = () =>
{
this.opened = true;
this.control({ type: 'hello', ...size });
if (token) this.control({ type: 'resume', token, ...this.size });
};
this.socket.onmessage = (event: MessageEvent) =>
@@ -54,15 +76,36 @@ export class TerminalConnection
}
const message = JSON.parse(String(event.data)) as ServerMessage;
if (message.type === 'ready') this.events.ready();
else this.exitReason = message.reason;
switch (message.type)
{
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 = () =>
{
if (this.ended) return;
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));
}
resize(size: TerminalSize): void {
resize(size: TerminalSize): void
{
this.size = size;
this.control({ type: 'resize', ...size });
}
@@ -83,6 +128,15 @@ export class TerminalConnection
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 {
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 { WebglAddon } from '@xterm/addon-webgl';
import { Terminal } from '@xterm/xterm';
import { CONNECTING_MESSAGE, endMessage, playBoot } from './boot.ts';
import { TerminalConnection, terminalUrl } from './connection.ts';
import { CONNECTING_MESSAGE, endMessage, playBoot, queueMessage, solvingMessage } from './boot.ts';
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.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 element = document.getElementById('terminal')!;
const notice = document.getElementById('notice')!;
const terminal = new Terminal({
fontFamily: '"JetBrains Mono", monospace',
@@ -57,33 +63,117 @@ terminal.focus();
let state: State = 'booting';
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
{
state = 'connecting';
terminal.write(CONNECTING_MESSAGE);
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));
},
});
connect();
}
function input(data: string): void
{
if (state === 'active') connection?.input(data);
else if (state === 'idle') start();
if (state === 'active')
{
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);
@@ -91,5 +181,7 @@ terminal.onBinary((data) => { if (state === 'active') connection?.inputBinary(da
terminal.onResize(({ cols, rows }) => connection?.resize({ cols, rows }));
new ResizeObserver(() => fit.fit()).observe(element);
await playBoot(terminal, touch);
state = 'idle';
// A reload within the grace period picks the running sandbox up again.
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;
--muted: #7d8794;
--accent: #7ee787;
--warning: #e3b341;
color-scheme: dark;
font-family: "JetBrains Mono", monospace;
@@ -61,6 +62,19 @@ body {
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 {
flex: 1;
min-height: 0;
@@ -72,6 +86,11 @@ body {
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 {
display: flex;
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. */ }
},
};