import type { Socket } from 'node:net'; import { SANDBOX_LABEL, SESSION_LABEL, type ManagedContainer } from '@homepage/protocol'; import type { SpawnerConfig } from './config.ts'; import { DockerClient, DockerError } from './docker.ts'; const MiB = 1024 * 1024; /** * The complete container configuration of a sandbox session. Only the * 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) { return { Image: config.image, User: 'guest', Hostname: 'sandbox', Env: [`SESSION_ID=${sessionId}`, `SESSION_EXPIRES_AT=${expiresAt}`, 'TERM=xterm-256color'], Tty: true, OpenStdin: true, StdinOnce: false, AttachStdin: true, AttachStdout: true, AttachStderr: true, NetworkDisabled: true, Labels: { [SANDBOX_LABEL]: '1', [SESSION_LABEL]: sessionId }, HostConfig: { Privileged: false, ReadonlyRootfs: true, NetworkMode: 'none', CapDrop: ['ALL'], SecurityOpt: ['no-new-privileges'], IpcMode: 'private', Memory: 80 * MiB, MemorySwap: 80 * MiB, NanoCpus: 500_000_000, PidsLimit: 50, Ulimits: [{ Name: 'nofile', Soft: 256, Hard: 256 }], Tmpfs: { '/home/guest': 'size=8m,mode=1777,noexec,nosuid', '/tmp': 'size=8m,noexec,nosuid', }, Binds: [`${config.contentDir}:/srv/www:ro`, `${config.statusDir}:/var/status:ro`], LogConfig: { Type: 'none', Config: {} }, AutoRemove: true, }, }; } type ContainerSummary = { Id: string; State: string; Labels?: Record; }; type ContainerDetails = { Id: string; State: { Status: string }; Config: { Labels?: Record }; }; export class SandboxManager { readonly config: SpawnerConfig; readonly docker: DockerClient; constructor(config: SpawnerConfig, docker = new DockerClient(config.dockerSocket)) { this.config = config; this.docker = docker; } async assertRuntime(): Promise { const info = await this.docker.call<{ DefaultRuntime?: string }>('GET', '/info'); if (info.DefaultRuntime !== 'runsc' && !this.config.allowNonGvisor) { throw new Error(`the sandbox daemon runs "${info.DefaultRuntime}" instead of gVisor (runsc)`); } } async spawn(sessionId: string, expiresAt: number): Promise { const existing = await this.list(); if (existing.length >= this.config.maxSandboxes) throw new Error('sandbox limit reached'); const created = await this.docker.call<{ Id: string }>( 'POST', `/containers/create?name=sandbox-${sessionId}`, containerSpec(this.config, sessionId, expiresAt), ); return created.Id; } /** Attaches before starting, so the motd and first prompt are not lost. */ async attach(containerId: string): Promise { const container = await this.managed(containerId); const stream = await this.docker.hijack( `/containers/${container.Id}/attach?stream=1&stdin=1&stdout=1&stderr=1`, ); if (container.State.Status === 'created') { try { await this.docker.call('POST', `/containers/${container.Id}/start`); } catch (error) { stream.destroy(); throw error; } } return stream; } async resize(containerId: string, cols: number, rows: number): Promise { const container = await this.managed(containerId); await this.docker.call('POST', `/containers/${container.Id}/resize?h=${rows}&w=${cols}`); } async kill(containerId: string): Promise { let container: ContainerDetails; try { container = await this.managed(containerId); } catch (error) { if (error instanceof DockerError && error.status === 404) return; throw error; } await this.remove(container.Id); } async list(): Promise { const filters = encodeURIComponent(JSON.stringify({ label: [`${SANDBOX_LABEL}=1`] })); const containers = await this.docker.call('GET', `/containers/json?all=1&filters=${filters}`); return containers .filter((container) => container.Labels?.[SANDBOX_LABEL] === '1') .map((container) => ({ containerId: container.Id, sessionId: container.Labels?.[SESSION_LABEL] ?? '', running: container.State === 'running', })); } /** Removes sandboxes left over from a previous run, because nobody can reach them anymore. */ async reapOrphans(): Promise { const containers = await this.list(); await Promise.all(containers.map((container) => this.remove(container.containerId))); return containers.length; } private async managed(containerId: string): Promise { const container = await this.docker.call('GET', `/containers/${containerId}/json`); if (container.Config.Labels?.[SANDBOX_LABEL] !== '1') throw new Error('not a sandbox container'); 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 { 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 stopped, gone or in removal. if (error instanceof DockerError && (error.status === 404 || error.status === 409)) return; throw error; } } }