Files
security-command.org/apps/backend/src/server.ts
T

166 lines
6.0 KiB
TypeScript

import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
import type { Duplex } from 'node:stream';
import type { Site } from '@homepage/indexer';
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 type { SessionHub } from './hub.ts';
import { renderMetrics } from './status.ts';
export type BackendOptions = {
assets?: Map<string, Asset>;
/** Resolves to false while the spawner is unreachable. */
healthy?: () => Promise<boolean>;
/** The static site of the content, rebuilt by the index job. */
site?: () => Site | undefined;
/** The theme with its override, read on every request so edits apply right away. */
theme?: () => Promise<Buffer | undefined>;
};
const MAX_FRAME_BYTES = 64 * 1024;
const THEME_PATH = '/theme.css';
const PING_INTERVAL_MS = 30_000;
// 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);
}
/** Decoded path without a trailing slash, or undefined for malformed percent encoding. */
function sitePath(path: string): string | undefined
{
try { return decodeURIComponent(path).replace(/(.)\/+$/, '$1'); }
catch { return undefined; }
}
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 ?? '');
}
export function createBackend(config: BackendConfig, hub: SessionHub, options: BackendOptions = {}): Server
{
const assets = options.assets ?? new Map<string, Asset>();
const healthy = options.healthy ?? (async () => true);
const site = options.site ?? (() => undefined);
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')
{
const ok = await healthy();
return send(response, ok ? 200 : 503, 'text/plain', ok ? 'ok' : 'degraded', { 'Cache-Control': 'no-store' }, head);
}
const theme = path === THEME_PATH ? await options.theme?.() : undefined;
if (theme) return send(response, 200, 'text/css; charset=utf-8', theme, { 'Cache-Control': 'no-cache' }, head);
const asset = assets.get(path);
if (asset)
{
const cache = asset.immutable ? 'public, max-age=31536000, immutable' : 'no-cache';
return send(response, 200, asset.type, asset.body, { 'Cache-Control': cache }, head);
}
const current = site();
const page = current && current.pages.get(sitePath(path) ?? '');
if (page?.status) return send(response, page.status, page.type, page.body, page.headers, head);
if (current && page)
{
// Every page changes together with the content, so the content hash is a valid ETag for all of them.
const etag = `"${current.hash}"`;
const headers = { 'Cache-Control': 'no-cache', ETag: etag, ...page.headers };
if (request.headers['if-none-match'] === etag)
{
response.writeHead(304, { ...SECURITY_HEADERS, ...headers }).end();
return;
}
return send(response, 200, page.type, page.body, headers, head);
}
send(response, 404, 'text/plain', 'not found', {}, head);
});
const sockets = new WebSocketServer({ noServer: true, maxPayload: MAX_FRAME_BYTES });
const alive = new WeakSet<WebSocket>();
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));
hub.connect(websocket);
});
});
// 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;
}
/** 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()));
});
}