From 9647ac8c500cfa86a816641bceb2d960e4005bf1 Mon Sep 17 00:00:00 2001 From: Overlord Date: Tue, 13 Oct 2026 11:43:49 +0200 Subject: [PATCH] Add proof-of-work challenge, session hub support, and status metrics across backend and frontend apps. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/images.yml | 2 +- apps/backend/Dockerfile | 2 + apps/backend/src/config.ts | 62 +++-- apps/backend/src/hub.ts | 281 ++++++++++++++++++++ apps/backend/src/main.ts | 41 ++- apps/backend/src/server.test.ts | 351 +++++++++++++++++++------ apps/backend/src/server.ts | 105 +++----- apps/backend/src/session.ts | 157 +++++++---- apps/backend/src/status.test.ts | 46 ++++ apps/backend/src/status.ts | 65 +++++ apps/frontend/index.html | 1 + apps/frontend/src/boot.ts | 16 +- apps/frontend/src/connection.test.ts | 84 ++++-- apps/frontend/src/connection.ts | 80 +++++- apps/frontend/src/main.ts | 138 ++++++++-- apps/frontend/src/proof.worker.ts | 10 + apps/frontend/src/solver.ts | 22 ++ apps/frontend/src/style.css | 19 ++ apps/frontend/src/token.ts | 26 ++ deploy.sh | 6 +- deploy/compose.yml | 6 + deploy/env.example | 11 + deploy/nginx/security-command.org.conf | 2 - packages/protocol/package.json | 3 +- packages/protocol/src/index.ts | 1 + packages/protocol/src/proof.test.ts | 35 +++ packages/protocol/src/proof.ts | 128 +++++++++ packages/protocol/src/terminal.test.ts | 35 +++ packages/protocol/src/terminal.ts | 49 +++- 29 files changed, 1492 insertions(+), 292 deletions(-) create mode 100644 apps/backend/src/hub.ts create mode 100644 apps/backend/src/status.test.ts create mode 100644 apps/backend/src/status.ts create mode 100644 apps/frontend/src/proof.worker.ts create mode 100644 apps/frontend/src/solver.ts create mode 100644 apps/frontend/src/token.ts create mode 100644 packages/protocol/src/proof.test.ts create mode 100644 packages/protocol/src/proof.ts create mode 100644 packages/protocol/src/terminal.test.ts diff --git a/.gitea/workflows/images.yml b/.gitea/workflows/images.yml index 0920eac..d89dc54 100644 --- a/.gitea/workflows/images.yml +++ b/.gitea/workflows/images.yml @@ -67,5 +67,5 @@ jobs: - name: Build and push run: | 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" diff --git a/apps/backend/Dockerfile b/apps/backend/Dockerfile index 00424fa..5e3b678 100644 --- a/apps/backend/Dockerfile +++ b/apps/backend/Dockerfile @@ -6,6 +6,8 @@ RUN corepack pnpm install --frozen-lockfile \ && corepack pnpm --filter @homepage/backend --filter @homepage/frontend build 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/frontend/dist /app/public USER 10002:10002 diff --git a/apps/backend/src/config.ts b/apps/backend/src/config.ts index fd2332a..dadd6c2 100644 --- a/apps/backend/src/config.ts +++ b/apps/backend/src/config.ts @@ -1,30 +1,58 @@ export type BackendConfig = { - host: string; - port: number; - spawnerSocket: string; - frontendDir: string; + host: string; + port: number; + /** Port of the metrics endpoint; 0 disables it. Only published to the host's loopback. */ + 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. */ - allowedOrigins: string[]; - sessionSeconds: number; - outputRate: number; + allowedOrigins: string[]; + maxSessions: 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); - 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; } +function list(value: string | undefined): string[] { + return (value ?? '').split(',').map((entry) => entry.trim()).filter(Boolean); +} + 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', - frontendDir: env.FRONTEND_DIR ?? '/app/public', - 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), + const config: BackendConfig = { + host: env.HOST ?? '0.0.0.0', + port: integer(env, 'PORT', 8080), + metricsPort: integer(env, 'METRICS_PORT', 9090, 0), + spawnerSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock', + frontendDir: env.FRONTEND_DIR ?? '/app/public', + statusDir: env.STATUS_DIR ?? '', + 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; } diff --git a/apps/backend/src/hub.ts b/apps/backend/src/hub.ts new file mode 100644 index 0000000..c3e7b4b --- /dev/null +++ b/apps/backend/src/hub.ts @@ -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; + ended: Record; +}; + +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(); + private readonly byToken = new Map(); + private readonly queue: Waiting[] = []; + + private readonly counters = { + started: 0, + resumed: 0, + invalidProofs: 0, + refused: { busy: 0 } as Record, + ended: { closed: 0, expired: 0, idle: 0, error: 0, gone: 0 } as Record, + }; + + 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 })); + } +} diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts index 295ed8a..e740df2 100644 --- a/apps/backend/src/main.ts +++ b/apps/backend/src/main.ts @@ -1,10 +1,15 @@ import { SpawnerClient } from '@homepage/protocol'; import { loadAssets } from './assets.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 HEALTH_CACHE_MS = 10_000; +const STATUS_INTERVAL_MS = 5000; + const config = loadConfig(process.env); 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); 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 +{ + 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}`)); +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) { process.once(signal, () => { + hub.endAll('closed'); server.close(); - process.exit(0); + setTimeout(() => process.exit(0), 500); }); } diff --git a/apps/backend/src/server.test.ts b/apps/backend/src/server.test.ts index a086bf8..6afbf00 100644 --- a/apps/backend/src/server.test.ts +++ b/apps/backend/src/server.test.ts @@ -1,15 +1,15 @@ import type { AddressInfo } from 'node:net'; import type { Server } from 'node:http'; import { duplexPair, type Duplex } from 'node:stream'; +import { solveProof } from '@homepage/protocol/proof'; 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 { SessionHub } from './hub.ts'; import { createBackend } from './server.ts'; import type { Spawner } from './session.ts'; -const CONTAINER = 'aaaaaaaaaaaa'; - const INDEX = { body: Buffer.from(''), 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 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 { readonly calls: string[] = []; + readonly containers = new Map(); container?: Duplex; + private count = 0; - async spawn(sessionId: string): Promise { + async spawn(sessionId: string): Promise + { this.calls.push(`spawn ${sessionId.length}`); - return CONTAINER; + return `container${++this.count}`; } - async attach(): Promise + async attach(containerId: string): Promise { const [backendSide, containerSide] = duplexPair(); + this.containers.set(containerId, containerSide); this.container = containerSide; - this.calls.push('attach'); + this.calls.push(`attach ${containerId}`); backendSide.pause(); return backendSide; } @@ -50,143 +54,316 @@ function until(condition: () => boolean, timeoutMs = 2000): Promise const started = Date.now(); const check = () => { - if (condition()) return resolve(); - if (Date.now() - started > timeoutMs) return reject(new Error('condition not met in time')); + if (condition()) return resolve(); + if (Date.now() - started > timeoutMs) return reject(new Error('condition not met in time')); setTimeout(check, 5); }; check(); }); } +const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + describe('backend', () => { let server: Server; + let hub: SessionHub; let spawner: FakeSpawner; let url: string; - let config: BackendConfig; async function start(overrides: Partial = {}): Promise { - config = { - host: '127.0.0.1', - port: 0, - spawnerSocket: '', - frontendDir: '', - allowedOrigins: ['https://security-command.org'], - sessionSeconds: 60, - outputRate: 1024 * 1024, + const config: BackendConfig = { + host: '127.0.0.1', + port: 0, + metricsPort: 0, + spawnerSocket: '', + frontendDir: '', + statusDir: '', + 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, }; + 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((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 }; + async function restart(overrides: Partial): Promise + { + hub.endAll('closed'); + server.close(); + await start(overrides); + } + + type Client = { + socket: WebSocket; + messages: ServerMessage[]; + output: () => string; + closed: Promise; + has: (type: ServerMessage['type']) => boolean; + }; function connect(origin = 'https://security-command.org'): Promise { return new Promise((resolve, reject) => { - const socket = new WebSocket(url, { origin }); + const socket = new WebSocket(url, { origin }); + const messages: ServerMessage[] = []; const chunks: Buffer[] = []; - const closed = new Promise((done) => socket.on('close', done)); + const closed = new Promise((done) => socket.on('close', done)); + const has = (type: ServerMessage['type']) => messages.some((message) => message.type === type); 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('open', () => resolve({ socket, messages, output: () => Buffer.concat(chunks).toString(), closed, has })); socket.on('error', reject); }); } - async function ready(): Promise + /** Answers the connection's challenge like the browser does. */ + async function proof(client: Client): Promise + { + 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 { const client = await connect(); - client.socket.send(JSON.stringify({ type: 'hello', cols: 100, rows: 30 })); - await until(() => client.messages.some((message) => message.type === 'ready')); + client.socket.send(JSON.stringify({ type: 'hello', nonce: await proof(client), ...size })); return client; } + async function ready(): Promise + { + 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()); - 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 () => { + afterEach(() => + { + hub.endAll('closed'); 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(); + describe('sessions', () => { + 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(JSON.stringify({ type: 'hello', cols: 80, rows: 24 })); - await until(() => client.messages.some((message) => message.type === 'ready')); + client.socket.send(Buffer.from('echo hi')); + await until(() => client.output() === 'ECHO HI'); + expect(spawner.calls).toEqual(['spawn 16', 'attach container1', 'resize 100x30']); + }); - 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('forwards resizes', async () => { + const client = await ready(); + + client.socket.send(JSON.stringify({ type: 'resize', cols: 9999, rows: 40 })); + 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 () => { - const client = await connect(); + describe('reconnecting', () => { + it('resumes a session within the grace period', async () => { + const first = await ready(); + first.socket.terminate(); + await first.closed; - client.socket.send('{"type":"exec"}'); - expect(await client.closed).toBe(1008); - expect(spawner.calls).toEqual([]); + spawner.container!.write('missed while away'); + const second = await connect(); + 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 () => { - await expect(connect('https://evil.example')).rejects.toThrow('403'); - }); + describe('admission', () => { + it('sends a challenge right after connecting', async () => { + const client = await connect(); + await until(() => client.has('challenge')); - it('throttles output', async () => { - server.close(); - await start({ outputRate: 1000 }); - const client = await ready(); + expect(client.messages[0]).toEqual({ type: 'challenge', challenge: expect.stringMatching(/^[A-Za-z0-9_-]{22}$/), difficulty: 0 }); + }); - for (let i = 0; i < 5; i++) spawner.container!.write('x'.repeat(1000)); - await new Promise((resolve) => setTimeout(resolve, 300)); + it('refuses a hello without a valid proof of work', async () => { + await restart({ powDifficulty: 16 }); + const client = await connect(); + await until(() => client.has('challenge')); - expect(client.output().length).toBeGreaterThan(0); - expect(client.output().length).toBeLessThan(5000); + client.socket.send(JSON.stringify({ type: 'hello', nonce: 1, cols: 80, rows: 24 })); + 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', () => { diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts index 2c62f8f..36ca972 100644 --- a/apps/backend/src/server.ts +++ b/apps/backend/src/server.ts @@ -1,20 +1,21 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } 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 { TERMINAL_PATH } from '@homepage/protocol/terminal'; +import { WebSocketServer, type WebSocket } from 'ws'; import type { Asset } from './assets.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; + /** Resolves to false while the spawner is unreachable. */ + healthy?: () => Promise; +}; 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; - // xterm.js creates style elements at runtime, so styles need 'unsafe-inline'. const SECURITY_HEADERS = { 'Content-Security-Policy': [ @@ -51,75 +52,22 @@ function originAllowed(config: BackendConfig, request: IncomingMessage): boolean 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; - if (Array.isArray(data)) return Buffer.concat(data); - return Buffer.from(data); -} + const assets = options.assets ?? new Map(); + const healthy = options.healthy ?? (async () => true); -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, assets = new Map()): Server -{ - const server = createServer((request, response) => + const server = createServer(async (request, response) => { const head = request.method === '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; - 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); if (asset) @@ -143,7 +91,7 @@ export function createBackend(config: BackendConfig, spawner: Spawner, log: Logg { 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)); 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())); + }); +} diff --git a/apps/backend/src/session.ts b/apps/backend/src/session.ts index 4581bdc..c4afe7c 100644 --- a/apps/backend/src/session.ts +++ b/apps/backend/src/session.ts @@ -12,47 +12,67 @@ export type Spawner = { }; export type SessionOptions = { - sessionSeconds: number; - outputRate: number; - log: (message: string) => void; + sessionSeconds: number; + idleSeconds: number; + 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. */ 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. */ +/** + * 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 { - 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 options: SessionOptions; private readonly bucket: TokenBucket; + private readonly onRelease: (session: Session, reason: ExitReason) => void; + private socket?: WebSocket; 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); - } + private expiryTimer?: NodeJS.Timeout; + private idleTimer?: NodeJS.Timeout; + private warningTimer?: NodeJS.Timeout; + private graceTimer?: NodeJS.Timeout; + private recheckTimer?: NodeJS.Timeout; - get started(): boolean { - return this.stream !== undefined; - } - - async start(size: TerminalSize): Promise + constructor(spawner: Spawner, options: SessionOptions, onRelease: (session: Session, reason: ExitReason) => void) { - const expiresAt = Math.floor(Date.now() / 1000) + this.options.sessionSeconds; - this.containerId = await this.spawner.spawn(this.id, expiresAt); + this.spawner = spawner; + 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 + { + this.socket = socket; + this.containerId = await this.spawner.spawn(this.id, this.expiresAt); if (this.ended) return this.release(); const stream = await this.spawner.attach(this.containerId); @@ -68,49 +88,99 @@ export class Session 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`); + + if (this.socket) this.connect(this.socket, size, false); + else this.detach(socket); } - input(data: Buffer): void { - this.stream?.write(data); - } - - resize({ cols, rows }: TerminalSize): void + /** Attaches a resuming WebSocket. A still connected older one is replaced. */ + resume(socket: WebSocket, size: 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(() => {}); } - /** 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 { if (this.ended) return; this.ended = true; this.send({ type: 'exit', reason }); - this.socket.close(1000); + this.socket?.close(1000); + this.socket = undefined; this.release(); + this.options.log(`session ${this.id} ended (${reason})`); + this.onRelease(this, reason); } - /** Cleans up after the WebSocket is already gone. */ - dispose(): void + private connect(socket: WebSocket, size: TerminalSize, resumed: boolean): void { - if (this.ended) return; - this.ended = true; + clearTimeout(this.graceTimer); + this.socket = socket; - this.release(); - this.options.log(`session ${this.id} disconnected`); + this.send({ type: 'ready', token: this.token, expiresAt: this.expiresAt, resumed }); + 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 { - if (this.ended) return; + if (this.ended || !this.socket) + { + this.stream?.pause(); + return; + } this.socket.send(chunk, { binary: true }); this.bucket.take(chunk.length); @@ -127,7 +197,7 @@ export class Session clearTimeout(this.recheckTimer); 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(); else this.scheduleRecheck(); @@ -136,13 +206,12 @@ export class Session 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 { - clearTimeout(this.expiryTimer); - clearTimeout(this.recheckTimer); + for (const timer of [this.expiryTimer, this.idleTimer, this.warningTimer, this.graceTimer, this.recheckTimer]) clearTimeout(timer); this.stream?.destroy(); if (this.containerId) diff --git a/apps/backend/src/status.test.ts b/apps/backend/src/status.test.ts new file mode 100644 index 0000000..a3e744b --- /dev/null +++ b/apps/backend/src/status.test.ts @@ -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'); + }); +}); diff --git a/apps/backend/src/status.ts b/apps/backend/src/status.ts new file mode 100644 index 0000000..2ebe0b2 --- /dev/null +++ b/apps/backend/src/status.ts @@ -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'); +} diff --git a/apps/frontend/index.html b/apps/frontend/index.html index d8522ce..820b64f 100644 --- a/apps/frontend/index.html +++ b/apps/frontend/index.html @@ -16,6 +16,7 @@ datenschutz +