diff --git a/.gitea/workflows/images.yml b/.gitea/workflows/images.yml index 527c678..0920eac 100644 --- a/.gitea/workflows/images.yml +++ b/.gitea/workflows/images.yml @@ -52,3 +52,20 @@ jobs: image="$REGISTRY/homepage-spawner" docker build -f apps/spawner/Dockerfile -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" . docker push --all-tags "$image" + + backend: + needs: check + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Log in to the registry + run: > + echo "${{ secrets.REGISTRY_TOKEN }}" + | docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER }}" --password-stdin + + - 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 push --all-tags "$image" diff --git a/apps/backend/Dockerfile b/apps/backend/Dockerfile new file mode 100644 index 0000000..72f3f77 --- /dev/null +++ b/apps/backend/Dockerfile @@ -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"] diff --git a/apps/backend/package.json b/apps/backend/package.json new file mode 100644 index 0000000..ebf2fb6 --- /dev/null +++ b/apps/backend/package.json @@ -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" + } +} diff --git a/apps/backend/src/config.ts b/apps/backend/src/config.ts new file mode 100644 index 0000000..62c0e3f --- /dev/null +++ b/apps/backend/src/config.ts @@ -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), + }; +} diff --git a/apps/backend/src/main.ts b/apps/backend/src/main.ts new file mode 100644 index 0000000..d51d87b --- /dev/null +++ b/apps/backend/src/main.ts @@ -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); + }); +} diff --git a/apps/backend/src/server.test.ts b/apps/backend/src/server.test.ts new file mode 100644 index 0000000..1a542e8 --- /dev/null +++ b/apps/backend/src/server.test.ts @@ -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 { + this.calls.push(`spawn ${sessionId.length}`); + return CONTAINER; + } + + async attach(): Promise + { + const [backendSide, containerSide] = duplexPair(); + this.container = containerSide; + this.calls.push('attach'); + backendSide.pause(); + return backendSide; + } + + async resize(_containerId: string, cols: number, rows: number): Promise { + this.calls.push(`resize ${cols}x${rows}`); + } + + async kill(containerId: string): Promise { + this.calls.push(`kill ${containerId}`); + } +} + +function until(condition: () => boolean, timeoutMs = 2000): Promise +{ + 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 = {}): Promise + { + 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((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 }; + + function connect(origin = 'https://security-command.org'): Promise + { + return new Promise((resolve, reject) => + { + const socket = new WebSocket(url, { origin }); + const messages: ServerMessage[] = []; + const chunks: Buffer[] = []; + const closed = new Promise((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 + { + 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); + }); +}); diff --git a/apps/backend/src/server.ts b/apps/backend/src/server.ts new file mode 100644 index 0000000..182c727 --- /dev/null +++ b/apps/backend/src/server.ts @@ -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(); + + 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; +} diff --git a/apps/backend/src/session.ts b/apps/backend/src/session.ts new file mode 100644 index 0000000..4581bdc --- /dev/null +++ b/apps/backend/src/session.ts @@ -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; + attach(containerId: string): Promise; + resize(containerId: string, cols: number, rows: number): Promise; + kill(containerId: string): Promise; +}; + +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 + { + 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)}`), + ); + } + } +} diff --git a/apps/backend/src/throttle.test.ts b/apps/backend/src/throttle.test.ts new file mode 100644 index 0000000..5429007 --- /dev/null +++ b/apps/backend/src/throttle.test.ts @@ -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); + }); +}); diff --git a/apps/backend/src/throttle.ts b/apps/backend/src/throttle.ts new file mode 100644 index 0000000..9c67908 --- /dev/null +++ b/apps/backend/src/throttle.ts @@ -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; + } +} diff --git a/apps/spawner/src/sandbox.ts b/apps/spawner/src/sandbox.ts index 92b90fd..1dd2eef 100644 --- a/apps/spawner/src/sandbox.ts +++ b/apps/spawner/src/sandbox.ts @@ -7,8 +7,8 @@ const MiB = 1024 * 1024; /** * The complete container configuration of a sandbox session. Only the - * validated session id and expiry come from outside. Keep in sync with - * deploy/host/sandbox-flags.sh. + * validated session id and expiry come from outside. It must stay identical + * to deploy/host/sandbox-flags.sh. */ export function containerSpec(config: SpawnerConfig, sessionId: string, expiresAt: number) { @@ -157,12 +157,22 @@ export class SandboxManager { return container; } + /** + * Kills before removing, because Podman's forced removal first sends SIGTERM + * and waits ten seconds, which an interactive bash ignores. + */ private async remove(containerId: string): Promise { - try { await this.docker.call('DELETE', `/containers/${containerId}?force=1`); } + await this.tolerateGone(this.docker.call('POST', `/containers/${containerId}/kill?signal=SIGKILL`)); + await this.tolerateGone(this.docker.call('DELETE', `/containers/${containerId}?force=1`)); + } + + private async tolerateGone(call: Promise): Promise + { + try { await call; } catch (error) { - // A container with AutoRemove may already be gone or in removal. + // A container with AutoRemove may already be stopped, gone or in removal. if (error instanceof DockerError && (error.status === 404 || error.status === 409)) return; throw error; } diff --git a/apps/spawner/src/server.test.ts b/apps/spawner/src/server.test.ts index 8d6fda0..5eadcd9 100644 --- a/apps/spawner/src/server.test.ts +++ b/apps/spawner/src/server.test.ts @@ -56,6 +56,7 @@ function fakeDocker(socketPath: string, calls: Call[]): Promise { return send(204); } if (url.pathname.endsWith('/resize')) return send(200); + if (url.pathname.endsWith('/kill')) return send(204); if (req.method === 'DELETE') { containers.delete(id); return send(204); diff --git a/deploy.sh b/deploy.sh index 72520ae..3e0c147 100755 --- a/deploy.sh +++ b/deploy.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash -# Deploys the terminal homepage on this host. Clone the repository into -# /srv/security-command.org and run this script for the first setup and for -# every update. +# Deploys the terminal homepage on this host from its clone in +# /srv/security-command.org. The same run covers the first setup and every +# update. # # Usage: sudo ./deploy.sh [--no-pull] # --no-pull deploy the checked out commit without pulling (allows local changes) @@ -74,8 +74,10 @@ pull_image() { commit=$(as_owner git rev-parse HEAD) sandbox_tag="${REGISTRY}/homepage-sandbox:${commit}" spawner_tag="${REGISTRY}/homepage-spawner:${commit}" +backend_tag="${REGISTRY}/homepage-backend:${commit}" pull_image sandbox_docker "$sandbox_tag" pull_image docker "$spawner_tag" +pull_image docker "$backend_tag" digest() { "$1" image inspect --format '{{index .RepoDigests 0}}' "$2"; } # The spawner runs as 10001 and shares group 10100 with the backend. @@ -84,6 +86,7 @@ install -d -o 10001 -g 10100 -m 0750 runtime/spawner cat > runtime/deploy.env < MAX_CONTROL_BYTES) invalid('message too long'); + + let input: unknown; + try { input = JSON.parse(text); } + catch { invalid('malformed json'); } + + if (typeof input !== 'object' || input === null || Array.isArray(input)) invalid('message must be an object'); + + const message = input as Record; + const type = Object.hasOwn(message, 'type') ? message.type : undefined; + if (type !== 'hello' && type !== 'resize') invalid('unknown message type'); + + return { type, cols: size(message.cols), rows: size(message.rows) }; +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 67eeb1f..cf79a29 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -179,6 +179,19 @@ importers: specifier: ~5.0.3 version: 5.0.3(@types/node@26.6.5)(vite@8.3.4(@types/node@26.6.5)(esbuild@0.28.2)) + apps/backend: + dependencies: + '@homepage/protocol': + specifier: workspace:* + version: link:../../packages/protocol + ws: + specifier: ^8.22.0 + version: 8.22.0 + devDependencies: + '@types/ws': + specifier: ^8.18.2 + version: 8.18.2 + apps/spawner: dependencies: '@homepage/protocol': @@ -469,6 +482,9 @@ packages: '@types/node@26.6.5': resolution: {integrity: sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==} + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + '@typescript/typescript-aix-ppc64@7.0.2': resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} engines: {node: '>=16.20.0'} @@ -862,6 +878,18 @@ packages: engines: {node: '>=20.11'} hasBin: true + ws@8.22.0: + resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + snapshots: '@esbuild/aix-ppc64@0.28.2': @@ -1013,6 +1041,10 @@ snapshots: dependencies: undici-types: 8.9.0 + '@types/ws@8.18.2': + dependencies: + '@types/node': 26.6.5 + '@typescript/typescript-aix-ppc64@7.0.2': optional: true @@ -1294,3 +1326,5 @@ snapshots: - msw why-is-node-running@3.2.1: {} + + ws@8.22.0: {}