Introduce spawner app with sandboxing support and client protocol implementation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-12 23:49:05 +02:00
1 parent 571f43457d
commit 7b1df2607e
26 files changed
+2438 -5

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
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. Keep in sync with
* 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<string, string>;
};
type ContainerDetails = {
Id: string;
State: { Status: string };
Config: { Labels?: Record<string, string> };
};
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<void>
{
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<string>
{
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<Socket>
{
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<void> {
const container = await this.managed(containerId);
await this.docker.call('POST', `/containers/${container.Id}/resize?h=${rows}&w=${cols}`);
}
async kill(containerId: string): Promise<void>
{
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<ManagedContainer[]>
{
const filters = encodeURIComponent(JSON.stringify({ label: [`${SANDBOX_LABEL}=1`] }));
const containers = await this.docker.call<ContainerSummary[]>('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<number> {
const containers = await this.list();
await Promise.all(containers.map((container) => this.remove(container.containerId)));
return containers.length;
}
private async managed(containerId: string): Promise<ContainerDetails> {
const container = await this.docker.call<ContainerDetails>('GET', `/containers/${containerId}/json`);
if (container.Config.Labels?.[SANDBOX_LABEL] !== '1') throw new Error('not a sandbox container');
return container;
}
private async remove(containerId: string): Promise<void>
{
try { await this.docker.call('DELETE', `/containers/${containerId}?force=1`); }
catch (error)
{
// A container with AutoRemove may already be gone or in removal.
if (error instanceof DockerError && (error.status === 404 || error.status === 409)) return;
throw error;
}
}
}