Add frontend app with terminal UI, sandbox integration, and asset handling.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OverlordandClaude Bot committed 2026-10-13 10:36:23 +02:00
1 parent 91049379f7
commit b841c2d1f6
19 files changed
+800 -13

No files matched your search

+2 -1
View File
@@ -3,10 +3,11 @@ FROM node:24-alpine AS build
WORKDIR /src
COPY . .
RUN corepack pnpm install --frozen-lockfile \
&& corepack pnpm --filter @homepage/backend build
&& corepack pnpm --filter @homepage/backend --filter @homepage/frontend build
FROM node:24-alpine
COPY --from=build /src/apps/backend/dist/backend.js /app/backend.js
COPY --from=build /src/apps/frontend/dist /app/public
USER 10002:10002
EXPOSE 8080
CMD ["node", "/app/backend.js"]
+52
View File
@@ -0,0 +1,52 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { extname, join, relative, sep } from 'node:path';
export type Asset = {
body: Buffer;
type: string;
/** Vite puts a content hash into every file name below assets/. */
immutable: boolean;
};
const TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.txt': 'text/plain; charset=utf-8',
};
function walk(directory: string): string[]
{
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) =>
{
const path = join(directory, entry.name);
if (entry.isDirectory()) return walk(path);
return entry.isFile() ? [path] : [];
});
}
/** Loads the built frontend into memory, keyed by URL path. The index page is also served at "/". */
export function loadAssets(directory: string): Map<string, Asset>
{
const assets = new Map<string, Asset>();
if (!existsSync(directory)) return assets;
for (const file of walk(directory))
{
const path = `/${relative(directory, file).split(sep).join('/')}`;
assets.set(path, {
body: readFileSync(file),
type: TYPES[extname(file)] ?? 'application/octet-stream',
immutable: path.startsWith('/assets/'),
});
}
const index = assets.get('/index.html');
if (index) assets.set('/', index);
return assets;
}
+2
View File
@@ -2,6 +2,7 @@ export type BackendConfig = {
host: string;
port: number;
spawnerSocket: string;
frontendDir: string;
/** Exact origins allowed to open terminal sessions. Empty allows every origin. */
allowedOrigins: string[];
sessionSeconds: number;
@@ -21,6 +22,7 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
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),
+5 -1
View File
@@ -1,4 +1,5 @@
import { SpawnerClient } from '@homepage/protocol';
import { loadAssets } from './assets.ts';
import { loadConfig } from './config.ts';
import { createBackend } from './server.ts';
@@ -12,7 +13,10 @@ 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);
const assets = loadAssets(config.frontendDir);
if (assets.size === 0) log(`no frontend found in ${config.frontendDir}`);
const server = createBackend(config, spawner, log, assets);
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
for (const signal of ['SIGTERM', 'SIGINT'] as const)
+37 -1
View File
@@ -10,6 +10,10 @@ import type { Spawner } from './session.ts';
const CONTAINER = 'aaaaaaaaaaaa';
const INDEX = { body: Buffer.from('<!doctype html>'), 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]]);
/** Hands out one in-memory stream pair per spawn; the far end plays the container. */
class FakeSpawner implements Spawner
{
@@ -66,13 +70,14 @@ describe('backend', () => {
host: '127.0.0.1',
port: 0,
spawnerSocket: '',
frontendDir: '',
allowedOrigins: ['https://security-command.org'],
sessionSeconds: 60,
outputRate: 1024 * 1024,
...overrides,
};
spawner = new FakeSpawner();
server = createBackend(config, spawner, () => {});
server = createBackend(config, spawner, () => {}, ASSETS);
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/ws`;
}
@@ -183,4 +188,35 @@ describe('backend', () => {
expect(client.output().length).toBeGreaterThan(0);
expect(client.output().length).toBeLessThan(5000);
});
describe('http', () => {
const http = (path: string, method = 'GET') => fetch(url.replace('ws://', 'http://').replace('/ws', path), { method });
it('serves the terminal page with security headers', async () => {
const response = await http('/');
expect(response.status).toBe(200);
expect(await response.text()).toBe('<!doctype html>');
expect(response.headers.get('cache-control')).toBe('no-cache');
expect(response.headers.get('content-security-policy')).toContain("frame-ancestors 'none'");
expect(response.headers.get('x-content-type-options')).toBe('nosniff');
});
it('caches hashed assets forever', async () => {
const response = await http('/assets/index-abc.js');
expect(response.headers.get('cache-control')).toContain('immutable');
expect(response.headers.get('content-type')).toContain('text/javascript');
});
it('answers HEAD without a body and refuses other methods', async () => {
const head = await http('/', 'HEAD');
expect(head.status).toBe(200);
expect(await head.text()).toBe('');
expect((await http('/', 'POST')).status).toBe(405);
});
it('returns 404 for unknown paths', async () => {
expect((await http('/../../etc/passwd')).status).toBe(404);
expect((await http('/nothing')).status).toBe(404);
});
});
});
+37 -6
View File
@@ -1,7 +1,8 @@
import { createServer, type IncomingMessage, type Server } from 'node:http';
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 type { Asset } from './assets.ts';
import type { BackendConfig } from './config.ts';
import { Session, type Spawner } from './session.ts';
@@ -14,6 +15,29 @@ 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': [
"default-src 'self'",
"script-src 'self'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data:",
"connect-src 'self'",
"frame-ancestors 'none'",
"base-uri 'none'",
"form-action 'none'",
].join('; '),
'X-Content-Type-Options': 'nosniff',
'Referrer-Policy': 'no-referrer',
'Permissions-Policy': 'camera=(), microphone=(), geolocation=()',
};
function send(response: ServerResponse, status: number, type: string, body: string | Buffer, headers: Record<string, string> = {}, head = false): void
{
response.writeHead(status, { ...SECURITY_HEADERS, 'Content-Type': type, 'Content-Length': Buffer.byteLength(body), ...headers });
response.end(head ? undefined : body);
}
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`);
@@ -87,17 +111,24 @@ function handleConnection(socket: WebSocket, spawner: Spawner, config: BackendCo
});
}
export function createBackend(config: BackendConfig, spawner: Spawner, log: Logger): Server
export function createBackend(config: BackendConfig, spawner: Spawner, log: Logger, assets = new Map<string, Asset>()): Server
{
const server = createServer((request, response) =>
{
if (request.method === 'GET' && request.url === '/healthz')
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);
const asset = assets.get(path);
if (asset)
{
response.writeHead(200, { 'Content-Type': 'text/plain' }).end('ok');
return;
const cache = asset.immutable ? 'public, max-age=31536000, immutable' : 'no-cache';
return send(response, 200, asset.type, asset.body, { 'Cache-Control': cache }, head);
}
response.writeHead(404, { 'Content-Type': 'text/plain' }).end('not found');
send(response, 404, 'text/plain', 'not found', {}, head);
});
const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });