Compare commits

..
12 Commits
Author SHA1 Message Date
Overlord d58101287d Update Gitea workflows to use REGISTRY_USER and REGISTRY_TOKEN for registry login, falling back to GITEA_TOKEN when secrets are unavailable.
images / check (push) Successful in 29s
images / sandbox (push) Successful in 35s
images / spawner (push) Successful in 59s
images / backend (push) Successful in 22s
images / jobs (push) Successful in 12s
2026-10-13 16:59:39 +02:00
Overlord b9203f74f4 Update Gitea workflows to use GITEA_TOKEN and gitea.actor for registry login, removing the need for manual secrets.
images / check (push) Successful in 17s
images / sandbox (push) Failing after 5s
images / spawner (push) Failing after 5s
images / backend (push) Failing after 5s
images / jobs (push) Failing after 5s
2026-10-13 16:53:51 +02:00
Overlord 3aecb3a631 Add service discovery script to jobs, extend nginx and host directory support. Update environment variables, configs, and examples.
images / check (push) Successful in 50s
images / sandbox (push) Failing after 6s
images / spawner (push) Failing after 5s
images / backend (push) Failing after 5s
images / jobs (push) Failing after 5s
2026-10-13 16:47:36 +02:00
Overlord 5305687f98 Add support for multilingual legal pages with English aliases, dynamic link replacement in headers, and redirections for alias routes. Update tests, configs, and frontend assets accordingly. 2026-10-13 16:41:08 +02:00
OverlordandClaude Bot 5f3ff481b4 Simplify boot sequence, remove terminal emblem, and introduce fastfetch script for sandbox login facts.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 16:07:41 +02:00
OverlordandClaude Bot 7937879ace Add tests for backend asset handling and frontend boot sequence, remove outdated MOTD script, and add icons.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:53:41 +02:00
OverlordandClaude Bot 0ad5b5f44f Add jobs service with script execution, configuration support, and control interface.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 15:04:21 +02:00
OverlordandClaude Bot 1f6d41ab06 Add backend jobs system with built-in tasks and TOML-based configuration parsing.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 14:20:31 +02:00
OverlordandClaude Bot 9647ac8c50 Add proof-of-work challenge, session hub support, and status metrics across backend and frontend apps.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 11:43:49 +02:00
OverlordandClaude Bot b841c2d1f6 Add frontend app with terminal UI, sandbox integration, and asset handling.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 10:36:23 +02:00
OverlordandClaude Bot 91049379f7 Introduce backend app for WebSocket terminal sessions and sandbox orchestration.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 00:22:49 +02:00
OverlordandClaude Bot 7b1df2607e Introduce spawner app with sandboxing support and client protocol implementation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 23:49:05 +02:00
102 changed files with 8614 additions and 28 deletions

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
.git
.gitea
.idea
.tools
**/node_modules
**/dist
runtime
sandbox
deploy
+67 -2
View File
@@ -1,3 +1,6 @@
# Builds the images and pushes them to the registry of the organization.
# Uses the secrets REGISTRY_USER and REGISTRY_TOKEN (a token with package
# write access) when they exist, else the automatic token of the run.
name: images
on:
@@ -9,6 +12,17 @@ env:
REGISTRY: git.security-command.org/securitycommand
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 24
- run: corepack pnpm install --frozen-lockfile
- run: corepack pnpm typecheck
- run: corepack pnpm test
sandbox:
runs-on: ubuntu-latest
steps:
@@ -16,11 +30,62 @@ jobs:
- name: Log in to the registry
run: >
echo "${{ secrets.REGISTRY_TOKEN }}"
| docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER }}" --password-stdin
echo "${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}"
| docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER || gitea.actor }}" --password-stdin
- name: Build and push
run: |
image="$REGISTRY/homepage-sandbox"
docker build -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" sandbox/
docker push --all-tags "$image"
spawner:
needs: check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Log in to the registry
run: >
echo "${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}"
| docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER || gitea.actor }}" --password-stdin
- name: Build and push
run: |
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 || secrets.GITEA_TOKEN }}"
| docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER || gitea.actor }}" --password-stdin
- name: Build and push
run: |
image="$REGISTRY/homepage-backend"
docker build -f apps/backend/Dockerfile --build-arg BUILD_SHA=${{ gitea.sha }} -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" .
docker push --all-tags "$image"
jobs:
needs: check
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Log in to the registry
run: >
echo "${{ secrets.REGISTRY_TOKEN || secrets.GITEA_TOKEN }}"
| docker login "${REGISTRY%%/*}" -u "${{ secrets.REGISTRY_USER || gitea.actor }}" --password-stdin
- name: Build and push
run: |
image="$REGISTRY/homepage-jobs"
docker build -f apps/jobs/Dockerfile -t "$image:${{ gitea.sha }}" -t "$image:${{ gitea.ref_name }}" .
docker push --all-tags "$image"
+5
View File
@@ -1,8 +1,13 @@
# ---> Strict
.*
!.git*
!.dockerignore
*.md
!README.md
/runtime/
/config/
/jobs/
node_modules/
dist/
+192 -1
View File
@@ -1,3 +1,194 @@
# security-command.org
Source of the [security-command.org](https://security-command.org/) homepage.
Source of the [security-command.org](https://security-command.org/) homepage:
a real Linux terminal in the browser. Every visitor gets their own bash in a
disposable [gVisor](https://gvisor.dev/) sandbox, with the homepage content
mounted read only and the network switched off. The same content is also
served as plain HTML pages for search engines and browsers without
JavaScript.
## How it works
```
browser (xterm.js)
│ HTTPS / WSS
nginx on the host (TLS)
│ 127.0.0.1:BACKEND_PORT
backend ────────── static site, terminal WebSocket, proof of work, queue
│ Unix socket
spawner ────────── the only service with access to the sandbox daemon
│ /run/docker-sandbox/docker.sock
sandbox dockerd ── runtime runsc, cgroup sandbox.slice
│
one container per visitor
jobs ───────────── scripts from config/jobs.toml that keep the content up to date
```
- **Sessions.** A sandbox only starts after the first key press and a proof
of work of about a second, which gets harder under load. At most 12
sessions run at once; further visitors wait in a FIFO queue. Sessions end
after 3 minutes without input or 20 minutes in total, and survive a page
reload for 45 seconds.
- **Sandboxes.** Read only root filesystem, no network, no capabilities,
non root user, 80 MB of memory, half a CPU, 50 processes, and a small
noexec tmpfs at `/tmp` as the only writable place. The content directory
is the read only home directory, so `ls` shows it right away. All
sandboxes together are capped by `sandbox.slice` (1.6 GB, 1.5 CPUs).
- **Privilege split.** The backend faces the internet and holds no Docker
socket. It can only ask the spawner to spawn, attach, resize, kill or list
sandboxes, and the spawner applies fixed flags. The sandbox daemon is a
second dockerd that runs nothing but sandboxes.
- **Static site.** The backend indexes the content directory into memory and
serves `/ls`, a page per file and directory, `/raw/<path>`, the legal
pages, `sitemap.xml` and `robots.txt`. Symlinks and dotfiles are never
served. Raw files cannot run scripts in the site's origin: HTML and SVG
are served as plain text and every raw response carries `CSP: sandbox`.
## Repository layout
```
deploy.sh deploys the checked out commit on the server
apps/backend/ HTTP server, WebSocket gateway, builtin jobs
apps/frontend/ terminal app, built into the backend image
apps/spawner/ broker in front of the sandbox daemon
apps/jobs/ runs script jobs, jobctl
packages/protocol/ messages between browser, backend and spawner
packages/indexer/ content index and static site
packages/jobs/ job file parser and scheduler
sandbox/ image every visitor gets
deploy/ compose file, host setup, nginx, env and job examples
```
## Server setup
Requirements: Ubuntu 24.04 with cgroup v2, Docker with the compose plugin,
nginx with TLS for the domain, and a token with `read:package` for the
registry of the SecurityCommand organization.
1. Log in to the registry once as root:
`docker login git.security-command.org`
2. Clone the repository to `/srv/security-command.org`.
3. Create the content directory. It must belong to a regular user, because
jobs run as its owner.
4. Run `sudo ./deploy.sh`. The first run asks for the content directory and
writes `.env` from `deploy/env.example`.
5. Include `deploy/nginx/security-command.org.conf` in the server block of
the site.
`deploy.sh` pulls the repository, sets up gVisor, the sandbox daemon and
the slice, pulls the images built for the checked out commit (waiting for
CI if needed), verifies the sandbox hardening and starts the services. It
fails if they do not become healthy. Every update is another
`sudo ./deploy.sh`; `--no-pull` deploys the current checkout as it is.
## Configuration
`.env` holds the settings; `deploy/env.example` documents each one.
| Setting | Default |
|-------------------|----------------------------------------------------|
| `CONTENT_DIR` | asked on the first deploy |
| `JOBS_SRV_DIR` | `/srv`, read only for jobs at `/host/srv` |
| `JOBS_NGINX_DIR` | `/etc/nginx`, read only for jobs at `/host/nginx` |
| `SITE_URL` | `https://security-command.org` |
| `LEGAL_PAGES` | `impressum/imprint:impressum.md,datenschutz/privacy:datenschutz.md` |
| `REGISTRY` | `git.security-command.org/securitycommand` |
| `BACKEND_PORT` | `8380`, must match the nginx config |
| `ALLOWED_ORIGINS` | `https://security-command.org` |
| `METRICS_PORT` | `9380`, loopback only |
| `MAX_SESSIONS` | `12` |
| `MAX_QUEUE` | `20` |
| `POW_DIFFICULTY` | `20` bits |
## Content
The content directory is any directory on the host; the application knows
nothing about its structure. Changes show up in the terminal right away and
on the static site after two quiet seconds. Update it in place, for example
with `git pull`, instead of replacing the directory, because running
containers keep the mount of the old one.
- The legal pages from `LEGAL_PAGES` are rendered at `/impressum` and
`/datenschutz` and linked in the header. The English aliases `/imprint`
and `/privacy` redirect to them, and browsers that do not prefer German
show those names in the header.
- Dotfiles, dot directories and symlinks are skipped.
- Top level names used by the site itself (`ws`, `raw`, `ls`, `assets`,
`healthz`, `sitemap.xml`, `robots.txt`, the legal routes and aliases)
are skipped with a warning in the backend log.
- Files above 1 MB are listed but not served; the whole index is capped at
64 MB and 10 000 entries.
- Startup files such as `.bashrc` in the content are ignored by the
sandbox shell, which only reads the configuration in the image.
- Executables in `.local/bin` of the content are on the `PATH` ahead of the
built in commands, so the content can carry small scripts. The emblem and
facts shown at login come from `fastfetch`, which
`.local/bin/fastfetch` replaces.
## Theme
All colors of the terminal and the static pages are CSS variables in
`apps/frontend/public/theme.css`, served at `/theme.css`; the defaults come
from the Security Command Gitea theme. A `config/theme.css` on the server is
appended to it on every request, so it overrides colors without a rebuild
and only needs the variables it changes. Most variables fall back to the
names Gitea themes use, so the `:root` block of a Gitea theme works too:
```css
:root {
--accent: #4183c4;
--ansi-green: #21ba45;
}
```
## Jobs
`config/jobs.toml` schedules jobs. Builtin jobs run in the backend:
`index` rebuilds the static site, `status` writes the status file shown by
the `status` command in sandboxes, and `reap-orphans` removes sandboxes no
session owns. Script jobs live in `jobs/` and run in the jobs service, which
may write into the content directory. Jobs run on intervals, cron
schedules, start, or changes of files below `/srv`, and can trigger each
other. Setting `enabled = false` switches any job off, the system jobs
included.
Neither `config/` nor `jobs/` is part of the repository. The jobs service
creates `config/jobs.toml` on its first start; `deploy/jobs.example.toml`
describes every option.
## Operations
```sh
sudo ./deploy.sh # update
docker logs -f security-command-backend-1 # also spawner, jobs
docker exec security-command-jobs-1 jobctl list # jobs and their last runs
docker exec security-command-jobs-1 jobctl run <id>
curl -s 127.0.0.1:9380/metrics # Prometheus metrics
sudo deploy/host/verify-sandbox.sh # hardening checks
```
`/healthz` answers `ok`, or `degraded` while the spawner is unreachable,
and reveals nothing else.
## Development
Node 24 and pnpm through corepack:
```sh
corepack pnpm install
corepack pnpm typecheck
corepack pnpm test
```
Node runs the TypeScript sources directly. Gitea Actions checks every push
to `develop` and `master` and builds the images `homepage-sandbox`,
`homepage-spawner`, `homepage-backend` and `homepage-jobs`, tagged with the
commit and the branch. It logs in to the registry with the secrets
`REGISTRY_USER` and `REGISTRY_TOKEN` (a token with package write access)
when they exist, and otherwise with the automatic token of the run.
## License
See [LICENSE](LICENSE).
+15
View File
@@ -0,0 +1,15 @@
# 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 --filter @homepage/frontend build
FROM node:24-alpine
ARG BUILD_SHA=dev
ENV BUILD_SHA=${BUILD_SHA}
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"]
+17
View File
@@ -0,0 +1,17 @@
{
"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/indexer": "workspace:*",
"@homepage/jobs": "workspace:*",
"@homepage/protocol": "workspace:*",
"ws": "^8.22.0"
},
"devDependencies": {
"@types/ws": "^8.18.2"
}
}
+44
View File
@@ -0,0 +1,44 @@
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { readTheme, setLegalLinks, type Asset } from './assets.ts';
describe('readTheme', () => {
const base = Buffer.from(':root { --text: white; }');
it('appends the override, so its rules win', async () => {
const file = join(mkdtempSync(join(tmpdir(), 'theme-')), 'theme.css');
writeFileSync(file, ':root { --text: red; }');
expect((await readTheme(base, file))?.toString()).toBe(':root { --text: white; }\n:root { --text: red; }');
});
it('serves the built in theme without an override', async () => {
expect(await readTheme(base, '/nonexistent/theme.css')).toBe(base);
expect(await readTheme(undefined, '/nonexistent/theme.css')).toBeUndefined();
});
});
describe('setLegalLinks', () => {
const page = (): Map<string, Asset> =>
{
const index = { body: Buffer.from('<header><nav><a href="/impressum">impressum</a></nav></header>'), type: 'text/html', immutable: false };
return new Map([['/index.html', index], ['/', index]]);
};
it('links only the configured legal pages, with their English names', () => {
const assets = page();
setLegalLinks(assets, [{ route: 'datenschutz', aliases: ['privacy'], file: 'datenschutz.md' }]);
expect(assets.get('/')?.body.toString()).toBe('<header><nav><a href="/datenschutz" data-en="privacy">datenschutz</a></nav></header>');
expect(assets.get('/index.html')).toBe(assets.get('/'));
});
it('leaves the header empty without legal pages', () => {
const assets = page();
setLegalLinks(assets, []);
expect(assets.get('/')?.body.toString()).toBe('<header><nav></nav></header>');
});
});
+96
View File
@@ -0,0 +1,96 @@
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { extname, join, relative, sep } from 'node:path';
import { escapeHtml, type Font, type LegalPage } from '@homepage/indexer';
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;
}
/**
* Writes the configured legal pages into the header of the terminal page,
* which the frontend build cannot know. Without legal pages the header has no links.
*/
export function setLegalLinks(assets: Map<string, Asset>, legal: LegalPage[]): void
{
const index = assets.get('/index.html');
if (!index) return;
const links = legal.map((page) =>
{
const english = page.aliases[0] ? ` data-en="${escapeHtml(page.aliases[0])}"` : '';
return `<a href="/${escapeHtml(page.route)}"${english}>${escapeHtml(page.route)}</a>`;
});
const html = index.body.toString('utf8').replace(/<nav>[\s\S]*?<\/nav>/, `<nav>${links.join('<span aria-hidden="true">·</span>')}</nav>`);
const asset = { ...index, body: Buffer.from(html) };
assets.set('/index.html', asset);
assets.set('/', asset);
}
const FONT = /^\/assets\/jetbrains-mono-latin-(400|700)-normal-[^/]+\.woff2$/;
/** The Latin JetBrains Mono files of the frontend, so the static pages use the same font. */
export function siteFonts(assets: Map<string, Asset>): Font[]
{
return [...assets.keys()].flatMap((path) =>
{
const match = FONT.exec(path);
return match ? [{ url: path, weight: Number(match[1]) }] : [];
});
}
/** The built in theme followed by the optional override, whose rules win because they come later. */
export async function readTheme(base: Buffer | undefined, overrideFile: string): Promise<Buffer | undefined>
{
if (!base) return undefined;
const override = await readFile(overrideFile).catch(() => undefined);
return override ? Buffer.concat([base, Buffer.from('\n'), override]) : base;
}
+127
View File
@@ -0,0 +1,127 @@
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import type { Site } from '@homepage/indexer';
import { describe, expect, it } from 'vitest';
import { createBuiltins } from './builtins.ts';
import type { BackendConfig } from './config.ts';
import type { SessionHub } from './hub.ts';
import { BackendJobs } from './jobs.ts';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function setup()
{
const root = mkdtempSync(join(tmpdir(), 'builtins-'));
const content = join(root, 'content');
const status = join(root, 'status');
mkdirSync(content);
mkdirSync(status);
writeFileSync(join(content, 'about.txt'), 'about');
const killed: string[] = [];
const logs: string[] = [];
let site: Site | undefined;
const config = {
contentDir: content,
statusDir: status,
siteUrl: 'https://security-command.org',
legalPages: [{ route: 'impressum', aliases: ['imprint'], file: 'impressum.txt' }],
build: 'abc1234',
} as BackendConfig;
const hub = {
sessionIds: () => new Set(['live']),
stats: () => ({ maxSessions: 12, starting: 0, active: 1, grace: 0, queued: 0 }),
} as unknown as SessionHub;
const builtins = createBuiltins({
config,
hub,
spawner: {
list: async () => [{ containerId: 'c1', sessionId: 'live' }, { containerId: 'c2', sessionId: 'stale' }],
kill: async (id) => { killed.push(id); },
},
started: Date.now(),
setSite: (next) => { site = next; },
log: (line) => logs.push(line),
});
return { root, status, builtins, killed, logs, site: () => site };
}
describe('builtin jobs', () => {
it('index builds the static site', async () => {
const { builtins, site } = setup();
await builtins.index!(new AbortController().signal);
expect(site()?.pages.has('/about.txt')).toBe(true);
expect(site()?.pages.has('/sitemap.xml')).toBe(true);
});
it('index keeps the site when the content did not change', async () => {
const { builtins, site, logs } = setup();
await builtins.index!(new AbortController().signal);
const first = site();
await builtins.index!(new AbortController().signal);
expect(site()).toBe(first);
expect(logs.filter((line) => line.startsWith('indexed'))).toHaveLength(1);
});
it('status writes the status file', async () => {
const { builtins, status } = setup();
await builtins.status!(new AbortController().signal);
expect(readFileSync(join(status, 'status'), 'utf8')).toContain('sessions 1/12');
});
it('reap-orphans keeps containers of live sessions', async () => {
const { builtins, killed } = setup();
await builtins['reap-orphans']!(new AbortController().signal);
expect(killed).toEqual(['c2']);
});
});
describe('BackendJobs', () => {
it('runs the system jobs without a file and applies edits to it', async () => {
const { root, builtins, logs } = setup();
const runs: string[] = [];
const counted = Object.fromEntries(Object.entries(builtins).map(([name, run]) => [name, async (signal: AbortSignal) =>
{
runs.push(name);
await run(signal);
}]));
const file = join(root, 'jobs.toml');
const jobs = new BackendJobs(file, counted, (line) => logs.push(line));
await jobs.start();
await sleep(50);
expect(runs.sort()).toEqual(['index', 'reap-orphans', 'status']);
writeFileSync(file, '[[job]]\nid = "index"\nbuiltin = "index"\nenabled = false\n');
await sleep(800);
runs.length = 0;
jobs.emit('content-change');
await sleep(50);
expect(runs).toEqual([]);
expect(logs).toContain('job "index" is disabled');
jobs.stop();
});
it('ignores script jobs, which belong to the jobs service', async () => {
const { root, builtins, logs } = setup();
const file = join(root, 'jobs.toml');
writeFileSync(file, '[[job]]\nid = "services"\npath = "jobs/services.sh"\non = ["start"]\n');
const jobs = new BackendJobs(file, builtins, (line) => logs.push(line));
await jobs.start();
await sleep(50);
jobs.stop();
expect(logs.some((line) => line.includes('services'))).toBe(false);
});
});
+64
View File
@@ -0,0 +1,64 @@
import { buildIndex, buildSite, reservedNames, type Font, type Site } from '@homepage/indexer';
import type { BackendConfig } from './config.ts';
import type { SessionHub } from './hub.ts';
import type { Builtin } from './jobs.ts';
import type { Spawner } from './session.ts';
import { renderStatus, writeStatus } from './status.ts';
export type BuiltinDependencies = {
config: BackendConfig;
hub: SessionHub;
spawner: Pick<Spawner, 'kill'> & { list(): Promise<{ containerId: string; sessionId: string }[]> };
started: number;
setSite: (site: Site) => void;
fonts?: Font[];
log: (message: string) => void;
};
/** Limits that keep the in-memory copy of the content small. */
const CONTENT_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 64 * 1024 * 1024, maxEntries: 10_000 };
/** The jobs that live inside the backend; config/jobs.toml decides when they run. */
export function createBuiltins(dependencies: BuiltinDependencies): Record<string, Builtin>
{
const { config, hub, spawner, log } = dependencies;
let lastHash = '';
let lastWarnings = '';
return {
index: async (signal) =>
{
const index = await buildIndex(config.contentDir, { ...CONTENT_LIMITS, reserved: reservedNames(config.legalPages), signal });
signal.throwIfAborted();
// Content changes often arrive twice, through "then" and the content watcher.
if (index.hash === lastHash) return;
lastHash = index.hash;
dependencies.setSite(buildSite(index, { siteUrl: config.siteUrl, legal: config.legalPages, fonts: dependencies.fonts }));
// The same warnings come back on every rebuild, so they are only logged when they change.
const warnings = index.warnings.join('\n');
if (warnings !== lastWarnings) for (const warning of index.warnings) log(`content: ${warning}`);
lastWarnings = warnings;
log(`indexed ${index.entries.size} entries (${index.hash})`);
},
status: async () =>
{
if (!config.statusDir) return;
writeStatus(config.statusDir, renderStatus(hub.stats(), (Date.now() - dependencies.started) / 1000, config.build));
},
/** Removes sandboxes no session knows about. Safe at any time, since live sessions are kept. */
'reap-orphans': async () =>
{
const live = hub.sessionIds();
const orphans = (await spawner.list()).filter((container) => !live.has(container.sessionId));
await Promise.all(orphans.map((container) => spawner.kill(container.containerId)));
if (orphans.length > 0) log(`removed ${orphans.length} orphaned sandbox(es)`);
},
};
}
+90
View File
@@ -0,0 +1,90 @@
import type { LegalPage } from '@homepage/indexer';
export type BackendConfig = {
host: string;
port: number;
/** Port of the metrics endpoint; 0 disables it. Only published to the host's loopback. */
metricsPort: number;
spawnerSocket: string;
frontendDir: string;
contentDir: string;
jobsFile: string;
/** Directory the jobs service writes triggers for builtin jobs into; empty disables them. */
triggerDir: string;
/** Optional CSS appended to the theme of the frontend, which overrides its colors. */
themeFile: string;
/** Absolute URL of the site, for the sitemap. */
siteUrl: string;
/** From LEGAL_PAGES like "impressum/imprint:impressum.md": the German route, English aliases and the content file. */
legalPages: LegalPage[];
/** Directory for the status file shown in sandboxes; empty disables it. */
statusDir: string;
build: string;
/** Exact origins allowed to open terminal sessions. Empty allows every origin. */
allowedOrigins: string[];
maxSessions: number;
maxQueue: number;
powDifficulty: number;
sessionSeconds: number;
idleSeconds: number;
idleWarningSeconds: number;
graceSeconds: number;
outputRate: number;
};
function integer(env: NodeJS.ProcessEnv, name: string, fallback: number, minimum = 1): number
{
const value = Number(env[name] ?? fallback);
if (!Number.isInteger(value) || value < minimum) throw new Error(`${name} must be an integer of at least ${minimum}`);
return value;
}
function list(value: string | undefined): string[] {
return (value ?? '').split(',').map((entry) => entry.trim()).filter(Boolean);
}
function legalPages(value: string): LegalPage[]
{
return list(value).map((entry) =>
{
const [routes = '', file = ''] = entry.split(':');
const [route = '', ...aliases] = routes.split('/');
if (![route, ...aliases].every((name) => /^[a-z0-9-]+$/.test(name)) || !file)
{
throw new Error(`LEGAL_PAGES entry "${entry}" must look like route/alias:file`);
}
return { route, aliases, file };
});
}
export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
{
const config: BackendConfig = {
host: env.HOST ?? '0.0.0.0',
port: integer(env, 'PORT', 8080),
metricsPort: integer(env, 'METRICS_PORT', 9090, 0),
spawnerSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock',
frontendDir: env.FRONTEND_DIR ?? '/app/public',
contentDir: env.CONTENT_DIR ?? '/content',
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
triggerDir: env.TRIGGER_DIR ?? '',
themeFile: env.THEME_FILE ?? '/config/theme.css',
siteUrl: env.SITE_URL ?? 'https://security-command.org',
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum/imprint:impressum.md,datenschutz/privacy:datenschutz.md'),
statusDir: env.STATUS_DIR ?? '',
build: env.BUILD_SHA ?? 'dev',
allowedOrigins: list(env.ALLOWED_ORIGINS),
maxSessions: integer(env, 'MAX_SESSIONS', 12),
maxQueue: integer(env, 'MAX_QUEUE', 20, 0),
powDifficulty: integer(env, 'POW_DIFFICULTY', 20, 0),
sessionSeconds: integer(env, 'SESSION_SECONDS', 20 * 60),
idleSeconds: integer(env, 'IDLE_SECONDS', 180),
idleWarningSeconds: integer(env, 'IDLE_WARNING_SECONDS', 30),
graceSeconds: integer(env, 'GRACE_SECONDS', 45),
outputRate: integer(env, 'OUTPUT_BYTES_PER_SECOND', 1024 * 1024),
};
if (config.idleWarningSeconds >= config.idleSeconds) throw new Error('IDLE_WARNING_SECONDS must be below IDLE_SECONDS');
if (config.powDifficulty > 28) throw new Error('POW_DIFFICULTY above 28 would take phones minutes');
return config;
}
+286
View File
@@ -0,0 +1,286 @@
import { randomBytes } from 'node:crypto';
import { verifyProof } from '@homepage/protocol/proof';
import {
InvalidMessageError,
parseClientMessage,
type ExitReason,
type RefusalReason,
type ServerMessage,
type TerminalSize,
} from '@homepage/protocol/terminal';
import type { RawData, WebSocket } from 'ws';
import { Session, type SessionOptions, type Spawner } from './session.ts';
export type HubOptions = SessionOptions & {
maxSessions: number;
maxQueue: number;
/** Leading zero bits a new sandbox costs while the server is mostly idle. */
powDifficulty: number;
helloTimeoutMs: number;
/** Called whenever the number of sessions or queued visitors changes. */
onChange?: () => void;
};
export type HubStats = {
maxSessions: number;
starting: number;
active: number;
grace: number;
queued: number;
difficulty: number;
started: number;
resumed: number;
invalidProofs: number;
refused: Record<RefusalReason, number>;
ended: Record<ExitReason, number>;
};
type Waiting = {
socket: WebSocket;
size: TerminalSize;
assign: (session: Session) => void;
};
/** Close code for protocol violations by the client. */
const POLICY_VIOLATION = 1008;
/** Close code asking the client to try again later. */
const TRY_AGAIN_LATER = 1013;
function toBuffer(data: RawData): Buffer
{
if (Buffer.isBuffer(data)) return data;
if (Array.isArray(data)) return Buffer.concat(data);
return Buffer.from(data);
}
function send(socket: WebSocket, message: ServerMessage): void {
if (socket.readyState === socket.OPEN) socket.send(JSON.stringify(message));
}
/**
* Admission for all sandbox sessions: proof of work instead of per address
* limits, the global slot limit, the first come first served queue and
* resuming by token. No visitor address is ever looked at.
*/
export class SessionHub
{
private readonly spawner: Spawner;
private readonly options: HubOptions;
private readonly sessions = new Set<Session>();
private readonly byToken = new Map<string, Session>();
private readonly queue: Waiting[] = [];
private readonly counters = {
started: 0,
resumed: 0,
invalidProofs: 0,
refused: { busy: 0 } as Record<RefusalReason, number>,
ended: { closed: 0, expired: 0, idle: 0, error: 0, gone: 0 } as Record<ExitReason, number>,
};
constructor(spawner: Spawner, options: HubOptions) {
this.spawner = spawner;
this.options = options;
}
/** Sandboxes get more expensive as the slots fill up, so the last ones and the queue cost the most. */
difficulty(): number
{
const load = (this.sessions.size + this.queue.length) / this.options.maxSessions;
if (load >= 0.9) return this.options.powDifficulty + 3;
if (load >= 0.75) return this.options.powDifficulty + 2;
if (load >= 0.5) return this.options.powDifficulty + 1;
return this.options.powDifficulty;
}
/** Ids of every session that still owns a container, used to tell orphans apart. */
sessionIds(): Set<string> {
return new Set([...this.sessions].map((session) => session.id));
}
stats(): HubStats
{
const states = [...this.sessions].map((session) => session.state);
return {
maxSessions: this.options.maxSessions,
starting: states.filter((state) => state === 'starting').length,
active: states.filter((state) => state === 'active').length,
grace: states.filter((state) => state === 'grace').length,
queued: this.queue.length,
difficulty: this.difficulty(),
started: this.counters.started,
resumed: this.counters.resumed,
invalidProofs: this.counters.invalidProofs,
refused: { ...this.counters.refused },
ended: { ...this.counters.ended },
};
}
/**
* Takes over a new WebSocket and hands it a challenge right away. The first
* control message decides: a hello with a solving nonce asks for a new
* sandbox, a resume with a token continues an existing one.
*/
connect(socket: WebSocket): void
{
const challenge = randomBytes(16).toString('base64url');
const difficulty = this.difficulty();
send(socket, { type: 'challenge', challenge, difficulty });
let session: Session | undefined;
let waiting: Waiting | undefined;
let greeted = false;
const helloTimer = setTimeout(() => socket.close(POLICY_VIOLATION, 'hello expected'), this.options.helloTimeoutMs);
socket.on('message', (data, isBinary) =>
{
if (isBinary)
{
session?.input(socket, toBuffer(data));
return;
}
let message;
try { message = parseClientMessage(toBuffer(data).toString('utf8')); }
catch (error)
{
if (!(error instanceof InvalidMessageError)) throw error;
socket.close(POLICY_VIOLATION, error.message);
return;
}
if (message.type === 'resize')
{
if (session) session.resize(socket, message);
else if (waiting) waiting.size = message;
return;
}
if (greeted) return;
greeted = true;
clearTimeout(helloTimer);
const size = { cols: message.cols, rows: message.rows };
if (message.type === 'resume')
{
session = this.resume(socket, message.token, size);
return;
}
if (!verifyProof(challenge, message.nonce, difficulty))
{
this.counters.invalidProofs++;
socket.close(POLICY_VIOLATION, 'invalid proof of work');
return;
}
waiting = this.admit(socket, size, (assigned) =>
{
session = assigned;
waiting = undefined;
});
});
socket.on('close', () =>
{
clearTimeout(helloTimer);
session?.detach(socket);
if (waiting) this.leaveQueue(waiting);
});
}
/** Ends every session, for example on shutdown. */
endAll(reason: ExitReason): void {
for (const session of [...this.sessions]) session.end(reason);
}
private resume(socket: WebSocket, token: string, size: TerminalSize): Session | undefined
{
const session = this.byToken.get(token);
if (!session)
{
send(socket, { type: 'exit', reason: 'gone' });
socket.close(1000);
return undefined;
}
this.counters.resumed++;
session.resume(socket, size);
return session;
}
/** Starts a session right away, queues the visitor, or refuses. Returns the queue entry. */
private admit(socket: WebSocket, size: TerminalSize, assign: (session: Session) => void): Waiting | undefined
{
if (this.sessions.size < this.options.maxSessions && this.queue.length === 0)
{
assign(this.startSession(socket, size));
return undefined;
}
if (this.queue.length >= this.options.maxQueue)
{
this.counters.refused.busy++;
send(socket, { type: 'refused', reason: 'busy' });
socket.close(TRY_AGAIN_LATER);
return undefined;
}
const waiting = { socket, size, assign };
this.queue.push(waiting);
send(socket, { type: 'queued', position: this.queue.length });
this.options.onChange?.();
return waiting;
}
private startSession(socket: WebSocket, size: TerminalSize): Session
{
this.counters.started++;
const session = new Session(this.spawner, this.options, (ended, reason) =>
{
this.sessions.delete(ended);
this.byToken.delete(ended.token);
this.counters.ended[reason]++;
this.drainQueue();
this.options.onChange?.();
});
this.sessions.add(session);
this.byToken.set(session.token, session);
this.options.onChange?.();
session.start(socket, size).catch((error: unknown) =>
{
this.options.log(`session ${session.id} failed to start: ${String(error)}`);
session.end('error');
});
return session;
}
private leaveQueue(waiting: Waiting): void
{
const index = this.queue.indexOf(waiting);
if (index === -1) return;
this.queue.splice(index, 1);
this.announcePositions();
this.options.onChange?.();
}
private drainQueue(): void
{
while (this.sessions.size < this.options.maxSessions && this.queue.length > 0)
{
const next = this.queue.shift()!;
next.assign(this.startSession(next.socket, next.size));
}
this.announcePositions();
}
private announcePositions(): void {
this.queue.forEach((waiting, index) => send(waiting.socket, { type: 'queued', position: index + 1 }));
}
}
+69
View File
@@ -0,0 +1,69 @@
import type { FSWatcher } from 'node:fs';
import { readFile } from 'node:fs/promises';
import { loadJobs, Scheduler, watchFile, type JobDefinition, type JobEvent } from '@homepage/jobs';
export type Builtin = (signal: AbortSignal) => Promise<void>;
const RELOAD_DEBOUNCE_MS = 500;
/**
* Runs the builtin jobs of config/jobs.toml inside the backend. Script jobs
* in the same file belong to the jobs service and are ignored here. The file
* is watched, so edits apply without a restart.
*/
export class BackendJobs
{
private readonly file: string;
private readonly builtins: Record<string, Builtin>;
private readonly log: (message: string) => void;
private scheduler?: Scheduler;
private watcher?: FSWatcher;
constructor(file: string, builtins: Record<string, Builtin>, log: (message: string) => void)
{
this.file = file;
this.builtins = builtins;
this.log = log;
}
async start(): Promise<void>
{
await this.load();
this.watcher = watchFile(this.file, RELOAD_DEBOUNCE_MS, () => void this.load(), this.log);
}
emit(event: JobEvent): void {
this.scheduler?.emit(event);
}
/** Starts a job. Returns false for unknown or disabled jobs. */
trigger(id: string): boolean {
return this.scheduler?.trigger(id) ?? false;
}
stop(): void
{
this.watcher?.close();
this.scheduler?.stop();
}
private async load(): Promise<void>
{
let text = '';
try { text = await readFile(this.file, 'utf8'); }
catch { this.log(`${this.file} does not exist yet, running the default system jobs`); }
const { jobs, warnings } = loadJobs(text);
for (const warning of warnings) this.log(warning);
const own = jobs.filter((job): job is JobDefinition & { builtin: string } => job.builtin !== undefined);
for (const job of own) if (!this.builtins[job.builtin]) this.log(`job "${job.id}" names the unknown builtin "${job.builtin}"`);
this.scheduler?.stop();
this.scheduler = new Scheduler(own.filter((job) => this.builtins[job.builtin]), (job, signal) => this.builtins[job.builtin!]!(signal), {
log: this.log,
triggerOther: (id) => this.log(`job "${id}" runs in the jobs service and cannot be triggered from the backend`),
});
this.scheduler.start();
}
}
+76
View File
@@ -0,0 +1,76 @@
import type { Site } from '@homepage/indexer';
import { watchTree, watchTriggers } from '@homepage/jobs';
import { SpawnerClient } from '@homepage/protocol';
import { loadAssets, readTheme, setLegalLinks, siteFonts } from './assets.ts';
import { createBuiltins } from './builtins.ts';
import { loadConfig } from './config.ts';
import { SessionHub } from './hub.ts';
import { BackendJobs } from './jobs.ts';
import { createBackend, createMetricsServer } from './server.ts';
const log = (message: string) => console.log(`[backend] ${message}`);
const HEALTH_CACHE_MS = 10_000;
const CONTENT_QUIET_MS = 2000;
const config = loadConfig(process.env);
const spawner = new SpawnerClient(config.spawnerSocket);
const assets = loadAssets(config.frontendDir);
if (assets.size === 0) log(`no frontend found in ${config.frontendDir}`);
setLegalLinks(assets, config.legalPages);
let site: Site | undefined;
let jobs: BackendJobs | undefined;
// Solving the proof of work happens after connecting, so slow phones get time for it.
const hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 90_000, log, onChange: () => jobs?.trigger('status') });
jobs = new BackendJobs(config.jobsFile, createBuiltins({
config,
hub,
spawner,
started: Date.now(),
setSite: (next) => { site = next; },
fonts: siteFonts(assets),
log,
}), log);
await jobs.start();
watchTree(config.contentDir, CONTENT_QUIET_MS, () => jobs?.emit('content-change'), log);
if (config.triggerDir)
{
watchTriggers(config.triggerDir, (id) =>
{
if (jobs?.trigger(id)) log(`job "${id}" triggered by the jobs service`);
else log(`the jobs service triggered "${id}", which is no enabled builtin job`);
}, log);
}
// The public health check asks the spawner at most every few seconds, so it cannot be used to flood it.
let health = { ok: true, checkedAt: 0 };
async function healthy(): Promise<boolean>
{
if (Date.now() - health.checkedAt < HEALTH_CACHE_MS) return health.ok;
const ok = await spawner.list().then(() => true, () => false);
health = { ok, checkedAt: Date.now() };
return ok;
}
const theme = () => readTheme(assets.get('/theme.css')?.body, config.themeFile);
const server = createBackend(config, hub, { assets, healthy, site: () => site, theme });
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
if (config.metricsPort > 0) createMetricsServer(hub).listen(config.metricsPort, config.host);
for (const signal of ['SIGTERM', 'SIGINT'] as const)
{
process.once(signal, () => {
jobs?.stop();
hub.endAll('closed');
server.close();
setTimeout(() => process.exit(0), 500);
});
}
+444
View File
@@ -0,0 +1,444 @@
import type { AddressInfo } from 'node:net';
import type { Server } from 'node:http';
import { duplexPair, type Duplex } from 'node:stream';
import type { Site, SitePage } from '@homepage/indexer';
import { solveProof } from '@homepage/protocol/proof';
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 { SessionHub } from './hub.ts';
import { createBackend } from './server.ts';
import type { Spawner } from './session.ts';
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]]);
const SITE: Site = {
hash: 'abc123',
pages: new Map<string, SitePage>([
['/ls', { body: Buffer.from('<p>listing</p>'), type: 'text/html; charset=utf-8', headers: {} }],
['/spaced name.txt', { body: Buffer.from('<p>page</p>'), type: 'text/html; charset=utf-8', headers: {} }],
['/raw/page.html', { body: Buffer.from('<script>'), type: 'text/plain; charset=utf-8', headers: { 'Content-Security-Policy': 'sandbox' } }],
['/imprint', { body: Buffer.alloc(0), type: 'text/plain; charset=utf-8', headers: { Location: '/impressum' }, status: 301 }],
]),
};
/** Hands out one in-memory stream pair per spawn; the far end plays the container. */
class FakeSpawner implements Spawner
{
readonly calls: string[] = [];
readonly containers = new Map<string, Duplex>();
container?: Duplex;
private count = 0;
async spawn(sessionId: string): Promise<string>
{
this.calls.push(`spawn ${sessionId.length}`);
return `container${++this.count}`;
}
async attach(containerId: string): Promise<Duplex>
{
const [backendSide, containerSide] = duplexPair();
this.containers.set(containerId, containerSide);
this.container = containerSide;
this.calls.push(`attach ${containerId}`);
backendSide.pause();
return backendSide;
}
async resize(_containerId: string, cols: number, rows: number): Promise<void> {
this.calls.push(`resize ${cols}x${rows}`);
}
async kill(containerId: string): Promise<void> {
this.calls.push(`kill ${containerId}`);
}
}
function until(condition: () => boolean, timeoutMs = 2000): Promise<void>
{
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();
});
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe('backend', () => {
let server: Server;
let hub: SessionHub;
let spawner: FakeSpawner;
let url: string;
async function start(overrides: Partial<BackendConfig> = {}): Promise<void>
{
const config: BackendConfig = {
host: '127.0.0.1',
port: 0,
metricsPort: 0,
spawnerSocket: '',
frontendDir: '',
contentDir: '',
jobsFile: '',
triggerDir: '',
themeFile: '',
siteUrl: 'https://security-command.org',
legalPages: [],
statusDir: '',
build: 'test',
allowedOrigins: ['https://security-command.org'],
maxSessions: 12,
maxQueue: 20,
powDifficulty: 0,
sessionSeconds: 60,
idleSeconds: 60,
idleWarningSeconds: 10,
graceSeconds: 45,
outputRate: 1024 * 1024,
...overrides,
};
spawner = new FakeSpawner();
hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 10_000, log: () => {} });
server = createBackend(config, hub, { assets: ASSETS, site: () => SITE, theme: async () => Buffer.from(':root { --text: red; }') });
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`;
}
async function restart(overrides: Partial<BackendConfig>): Promise<void>
{
hub.endAll('closed');
server.close();
await start(overrides);
}
type Client = {
socket: WebSocket;
messages: ServerMessage[];
output: () => string;
closed: Promise<number>;
has: (type: ServerMessage['type']) => boolean;
};
function connect(origin = 'https://security-command.org'): Promise<Client>
{
return new Promise((resolve, reject) =>
{
const socket = new WebSocket(url, { origin });
const messages: ServerMessage[] = [];
const chunks: Buffer[] = [];
const closed = new Promise<number>((done) => socket.on('close', done));
const has = (type: ServerMessage['type']) => messages.some((message) => message.type === type);
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, has }));
socket.on('error', reject);
});
}
/** Answers the connection's challenge like the browser does. */
async function proof(client: Client): Promise<number>
{
await until(() => client.has('challenge'));
const message = client.messages.find((entry) => entry.type === 'challenge');
if (message?.type !== 'challenge') throw new Error('no challenge');
return solveProof(message.challenge, message.difficulty)!;
}
async function hello(size = { cols: 100, rows: 30 }): Promise<Client>
{
const client = await connect();
client.socket.send(JSON.stringify({ type: 'hello', nonce: await proof(client), ...size }));
return client;
}
async function ready(): Promise<Client>
{
const client = await hello();
await until(() => client.has('ready'));
return client;
}
function tokenOf(client: Client): string
{
const message = client.messages.find((entry) => entry.type === 'ready');
if (message?.type !== 'ready') throw new Error('no ready message');
return message.token;
}
beforeEach(() => start());
afterEach(() =>
{
hub.endAll('closed');
server.close();
});
describe('sessions', () => {
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 container1', 'resize 100x30']);
});
it('forwards resizes', async () => {
const client = await ready();
client.socket.send(JSON.stringify({ type: 'resize', cols: 9999, rows: 40 }));
await until(() => spawner.calls.includes('resize 500x40'));
});
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 container1');
});
it('expires sessions', async () => {
await restart({ sessionSeconds: 1 });
const client = await ready();
expect(await client.closed).toBe(1000);
expect(client.messages).toContainEqual({ type: 'exit', reason: 'expired' });
});
it('warns about and ends idle sessions', async () => {
await restart({ idleSeconds: 0.4, idleWarningSeconds: 0.2 });
const client = await ready();
expect(await client.closed).toBe(1000);
expect(client.messages).toContainEqual({ type: 'idle', secondsLeft: 0.2 });
expect(client.messages).toContainEqual({ type: 'exit', reason: 'idle' });
});
it('ignores terminal input before the session started', async () => {
const client = await connect();
const nonce = await proof(client);
client.socket.send(Buffer.from('early'));
client.socket.send(JSON.stringify({ type: 'hello', nonce, cols: 80, rows: 24 }));
await until(() => client.has('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 () => {
await restart({ outputRate: 1000 });
const client = await ready();
for (let i = 0; i < 5; i++) spawner.container!.write('x'.repeat(1000));
await sleep(300);
expect(client.output().length).toBeGreaterThan(0);
expect(client.output().length).toBeLessThan(5000);
});
});
describe('reconnecting', () => {
it('resumes a session within the grace period', async () => {
const first = await ready();
first.socket.terminate();
await first.closed;
spawner.container!.write('missed while away');
const second = await connect();
second.socket.send(JSON.stringify({ type: 'resume', token: tokenOf(first), cols: 90, rows: 20 }));
await until(() => second.output() === 'missed while away');
expect(second.messages).toContainEqual(expect.objectContaining({ type: 'ready', resumed: true, token: tokenOf(first) }));
expect(spawner.calls.filter((call) => call.startsWith('spawn'))).toHaveLength(1);
expect(spawner.calls).not.toContain('kill container1');
});
it('moves the session to the newest connection', async () => {
const first = await ready();
const second = await connect();
second.socket.send(JSON.stringify({ type: 'resume', token: tokenOf(first), cols: 80, rows: 24 }));
expect(await first.closed).toBe(1000);
await until(() => second.has('ready'));
});
it('removes the container after the grace period and answers late resumes with gone', async () => {
await restart({ graceSeconds: 0.2 });
const first = await ready();
first.socket.terminate();
await until(() => spawner.calls.includes('kill container1'));
const late = await connect();
late.socket.send(JSON.stringify({ type: 'resume', token: tokenOf(first), cols: 80, rows: 24 }));
await late.closed;
expect(late.messages.at(-1)).toEqual({ type: 'exit', reason: 'gone' });
});
});
describe('admission', () => {
it('sends a challenge right after connecting', async () => {
const client = await connect();
await until(() => client.has('challenge'));
expect(client.messages[0]).toEqual({ type: 'challenge', challenge: expect.stringMatching(/^[A-Za-z0-9_-]{22}$/), difficulty: 0 });
});
it('refuses a hello without a valid proof of work', async () => {
await restart({ powDifficulty: 16 });
const client = await connect();
await until(() => client.has('challenge'));
client.socket.send(JSON.stringify({ type: 'hello', nonce: 1, cols: 80, rows: 24 }));
expect(await client.closed).toBe(1008);
expect(spawner.calls).toEqual([]);
expect(hub.stats().invalidProofs).toBe(1);
});
it('raises the difficulty as the slots fill up', async () => {
await restart({ maxSessions: 2, powDifficulty: 4 });
expect(hub.difficulty()).toBe(4);
await ready();
expect(hub.difficulty()).toBe(5);
await ready();
expect(hub.difficulty()).toBe(7);
});
it('queues visitors while all slots are taken', async () => {
await restart({ maxSessions: 1 });
await ready();
const waiting = await hello();
await until(() => waiting.has('queued'));
expect(waiting.messages.filter((message) => message.type === 'queued')).toEqual([{ type: 'queued', position: 1 }]);
spawner.container!.end();
await until(() => waiting.has('ready'));
});
it('updates queue positions when someone ahead leaves', async () => {
await restart({ maxSessions: 1 });
await ready();
const ahead = await hello();
const behind = await hello();
await until(() => behind.has('queued'));
ahead.socket.close();
const positions = () => behind.messages.filter((message) => message.type === 'queued');
await until(() => positions().length === 2);
expect(positions()).toEqual([{ type: 'queued', position: 2 }, { type: 'queued', position: 1 }]);
});
it('refuses visitors when the queue is full', async () => {
await restart({ maxSessions: 1, maxQueue: 0 });
await ready();
const refused = await hello();
expect(await refused.closed).toBe(1013);
expect(refused.messages.at(-1)).toEqual({ type: 'refused', reason: 'busy' });
});
it('reports counts in its stats', async () => {
await restart({ maxSessions: 1 });
await ready();
const waiting = await hello();
await until(() => waiting.has('queued'));
expect(hub.stats()).toMatchObject({ active: 1, queued: 1, started: 1 });
});
});
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('serves static site pages with a content hash ETag', async () => {
const response = await http('/ls/');
expect(await response.text()).toBe('<p>listing</p>');
expect(response.headers.get('etag')).toBe('"abc123"');
const cached = await fetch(url.replace('ws://', 'http://').replace('/ws', '/ls'), { headers: { 'If-None-Match': '"abc123"' } });
expect(cached.status).toBe(304);
});
it('decodes paths and keeps the sandbox policy of raw files', async () => {
expect(await (await http('/spaced%20name.txt')).text()).toBe('<p>page</p>');
expect((await http('/raw/page.html')).headers.get('content-security-policy')).toBe('sandbox');
expect((await http('/%E0%A4%A')).status).toBe(404);
});
it('redirects aliases of legal pages', async () => {
const response = await fetch(url.replace('ws://', 'http://').replace('/ws', '/imprint'), { redirect: 'manual' });
expect(response.status).toBe(301);
expect(response.headers.get('location')).toBe('/impressum');
});
it('serves the theme without caching it', async () => {
const response = await http('/theme.css');
expect(await response.text()).toBe(':root { --text: red; }');
expect(response.headers.get('content-type')).toBe('text/css; charset=utf-8');
expect(response.headers.get('cache-control')).toBe('no-cache');
});
it('returns 404 for unknown paths', async () => {
expect((await http('/../../etc/passwd')).status).toBe(404);
expect((await http('/nothing')).status).toBe(404);
});
});
});
+165
View File
@@ -0,0 +1,165 @@
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()));
});
}
+225
View File
@@ -0,0 +1,225 @@
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, size: TerminalSize): Promise<string>;
attach(containerId: string): Promise<Duplex>;
resize(containerId: string, cols: number, rows: number): Promise<void>;
kill(containerId: string): Promise<void>;
};
export type SessionOptions = {
sessionSeconds: number;
idleSeconds: number;
idleWarningSeconds: number;
graceSeconds: number;
outputRate: number;
log: (message: string) => void;
};
export type SessionState = 'starting' | 'active' | 'grace';
/** 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 sandbox. The container outlives single WebSockets: when the
* connection drops, the session waits for a resume with its token until the
* grace period ends.
*/
export class Session
{
readonly id = randomBytes(12).toString('base64url');
readonly token = randomBytes(16).toString('base64url');
readonly expiresAt: number;
private readonly spawner: Spawner;
private readonly options: SessionOptions;
private readonly bucket: TokenBucket;
private readonly onRelease: (session: Session, reason: ExitReason) => void;
private socket?: WebSocket;
private containerId?: string;
private stream?: Duplex;
private ended = false;
private expiryTimer?: NodeJS.Timeout;
private idleTimer?: NodeJS.Timeout;
private warningTimer?: NodeJS.Timeout;
private graceTimer?: NodeJS.Timeout;
private recheckTimer?: NodeJS.Timeout;
constructor(spawner: Spawner, options: SessionOptions, onRelease: (session: Session, reason: ExitReason) => void)
{
this.spawner = spawner;
this.options = options;
this.onRelease = onRelease;
this.bucket = new TokenBucket(options.outputRate);
this.expiresAt = Math.floor(Date.now() / 1000) + options.sessionSeconds;
}
get state(): SessionState
{
if (!this.stream) return 'starting';
return this.socket ? 'active' : 'grace';
}
async start(socket: WebSocket, size: TerminalSize): Promise<void>
{
this.socket = socket;
this.containerId = await this.spawner.spawn(this.id, this.expiresAt, size);
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.expiryTimer = setTimeout(() => this.end('expired'), this.options.sessionSeconds * 1000);
this.options.log(`session ${this.id} started`);
if (this.socket) this.connect(this.socket, size, false);
else this.detach(socket);
}
/** Attaches a resuming WebSocket. A still connected older one is replaced. */
resume(socket: WebSocket, size: TerminalSize): void
{
if (this.ended || !this.stream) return;
const previous = this.socket;
this.socket = undefined;
previous?.close(1000, 'resumed elsewhere');
this.connect(socket, size, true);
this.options.log(`session ${this.id} resumed`);
}
/** Called when a WebSocket closes. Only the current one starts the grace period. */
detach(socket: WebSocket): void
{
if (this.ended || (this.socket && this.socket !== socket)) return;
this.socket = undefined;
if (!this.stream) return;
this.stream.pause();
clearTimeout(this.graceTimer);
this.graceTimer = setTimeout(() => this.end('closed'), this.options.graceSeconds * 1000);
}
input(socket: WebSocket, data: Buffer): void
{
if (socket !== this.socket || !this.stream) return;
this.stream.write(data);
this.touch();
}
resize(socket: WebSocket, { cols, rows }: TerminalSize): void
{
if (socket !== this.socket || !this.containerId || this.ended) return;
this.spawner.resize(this.containerId, cols, rows).catch(() => {});
}
/** Ends the session, tells a connected 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.socket = undefined;
this.release();
this.options.log(`session ${this.id} ended (${reason})`);
this.onRelease(this, reason);
}
private connect(socket: WebSocket, size: TerminalSize, resumed: boolean): void
{
clearTimeout(this.graceTimer);
this.socket = socket;
this.send({ type: 'ready', token: this.token, expiresAt: this.expiresAt, resumed });
this.resize(socket, size);
this.touch();
this.stream?.resume();
}
/** Restarts the idle countdown, including the warning shortly before it ends. */
private touch(): void
{
clearTimeout(this.idleTimer);
clearTimeout(this.warningTimer);
const { idleSeconds, idleWarningSeconds } = this.options;
this.warningTimer = setTimeout(
() => this.send({ type: 'idle', secondsLeft: idleWarningSeconds }),
(idleSeconds - idleWarningSeconds) * 1000,
);
this.idleTimer = setTimeout(() => this.end('idle'), idleSeconds * 1000);
}
private forward(chunk: Buffer): void
{
if (this.ended || !this.socket)
{
this.stream?.pause();
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 || !this.socket) 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 && this.socket.readyState === this.socket.OPEN) this.socket.send(JSON.stringify(message));
}
private release(): void
{
for (const timer of [this.expiryTimer, this.idleTimer, this.warningTimer, this.graceTimer, this.recheckTimer]) clearTimeout(timer);
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)}`),
);
}
}
}
+46
View File
@@ -0,0 +1,46 @@
import { mkdtempSync, readdirSync, readFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import type { HubStats } from './hub.ts';
import { renderMetrics, renderStatus, writeStatus } from './status.ts';
const stats: HubStats = {
maxSessions: 12,
starting: 1,
active: 3,
grace: 1,
queued: 2,
difficulty: 21,
started: 40,
resumed: 4,
invalidProofs: 5,
refused: { busy: 3 },
ended: { closed: 30, expired: 2, idle: 3, error: 0, gone: 1 },
};
describe('status', () => {
it('renders aggregates only', () => {
expect(renderStatus(stats, 3 * 86_400 + 4 * 3600, 'a1b2c3d4e5')).toBe(
'sessions 5/12\nqueue 2\nuptime 3d 4h\nbuild a1b2c3d\n',
);
});
it('replaces the file atomically', () => {
const directory = mkdtempSync(join(tmpdir(), 'status-'));
writeStatus(directory, 'first');
writeStatus(directory, 'second');
expect(readFileSync(join(directory, 'status'), 'utf8')).toBe('second');
expect(readdirSync(directory)).toEqual(['status']);
});
it('renders Prometheus metrics', () => {
const metrics = renderMetrics(stats);
expect(metrics).toContain('homepage_sessions{state="active"} 3');
expect(metrics).toContain('homepage_sessions_refused_total{reason="busy"} 3');
expect(metrics).toContain('homepage_pow_difficulty 21');
expect(metrics).toContain('homepage_sessions_ended_total{reason="idle"} 3');
});
});
+65
View File
@@ -0,0 +1,65 @@
import { renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import type { HubStats } from './hub.ts';
function duration(seconds: number): string
{
const days = Math.floor(seconds / 86_400);
const hours = Math.floor((seconds % 86_400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) return `${days}d ${hours}h`;
if (hours > 0) return `${hours}h ${minutes}m`;
return `${minutes}m`;
}
/** The file every sandbox can read at /var/status/status. Aggregates only, nothing about other visitors. */
export function renderStatus(stats: HubStats, uptimeSeconds: number, build: string): string
{
const sessions = stats.starting + stats.active + stats.grace;
return [
`sessions ${sessions}/${stats.maxSessions}`,
`queue ${stats.queued}`,
`uptime ${duration(uptimeSeconds)}`,
`build ${build.slice(0, 7)}`,
'',
].join('\n');
}
/**
* Writes the status atomically: sandboxes see the directory through a bind
* mount, so a rename makes the new content visible without a partial read.
*/
export function writeStatus(directory: string, content: string): void
{
const temporary = join(directory, '.status.tmp');
writeFileSync(temporary, content, { mode: 0o644 });
renameSync(temporary, join(directory, 'status'));
}
export function renderMetrics(stats: HubStats): string
{
const lines = [
'# TYPE homepage_sessions gauge',
`homepage_sessions{state="starting"} ${stats.starting}`,
`homepage_sessions{state="active"} ${stats.active}`,
`homepage_sessions{state="grace"} ${stats.grace}`,
`homepage_sessions{state="queued"} ${stats.queued}`,
'# TYPE homepage_sessions_max gauge',
`homepage_sessions_max ${stats.maxSessions}`,
'# TYPE homepage_pow_difficulty gauge',
`homepage_pow_difficulty ${stats.difficulty}`,
'# TYPE homepage_invalid_proofs_total counter',
`homepage_invalid_proofs_total ${stats.invalidProofs}`,
'# TYPE homepage_sessions_started_total counter',
`homepage_sessions_started_total ${stats.started}`,
'# TYPE homepage_sessions_resumed_total counter',
`homepage_sessions_resumed_total ${stats.resumed}`,
'# TYPE homepage_sessions_refused_total counter',
...Object.entries(stats.refused).map(([reason, count]) => `homepage_sessions_refused_total{reason="${reason}"} ${count}`),
'# TYPE homepage_sessions_ended_total counter',
...Object.entries(stats.ended).map(([reason, count]) => `homepage_sessions_ended_total{reason="${reason}"} ${count}`),
'',
];
return lines.join('\n');
}
+25
View File
@@ -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);
});
});
+41
View File
@@ -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;
}
}
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, interactive-widget=resizes-content" />
<meta name="color-scheme" content="dark" />
<meta name="description" content="security-command.org: a real Linux shell in a disposable gVisor sandbox." />
<title>security-command.org</title>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" href="/icon-192.png" sizes="192x192" type="image/png" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="stylesheet" href="/theme.css" />
<script src="/labels.js" defer></script>
</head>
<body>
<header class="bar">
<span class="site">security-command.org</span>
<nav>
<a href="/impressum" data-en="imprint">impressum</a>
<span aria-hidden="true">·</span>
<a href="/datenschutz" data-en="privacy">datenschutz</a>
</nav>
</header>
<div id="notice" class="notice" role="status" aria-live="polite" hidden></div>
<main id="terminal" aria-label="Terminal"></main>
<div id="keybar" class="keybar" hidden></div>
<noscript>
<p class="noscript">The terminal needs JavaScript. The content is also available as <a href="/ls">plain pages</a>.</p>
</noscript>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+20
View File
@@ -0,0 +1,20 @@
{
"name": "@homepage/frontend",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": {
"@fontsource/jetbrains-mono": "^5.3.0",
"@homepage/protocol": "workspace:*",
"@xterm/addon-fit": "^0.11.0",
"@xterm/addon-web-links": "^0.12.0",
"@xterm/addon-webgl": "^0.19.0",
"@xterm/xterm": "^6.0.0"
},
"devDependencies": {
"vite": "^8.3.4"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

+8
View File
@@ -0,0 +1,8 @@
// The legal pages keep their German names for German visitors. Everyone else
// sees the English names that data-en holds; the links stay the same.
const language = (navigator.languages && navigator.languages[0]) || navigator.language || 'en';
if (!/^de\b/i.test(language))
{
for (const link of document.querySelectorAll('a[data-en]')) link.textContent = link.dataset.en;
}
+38
View File
@@ -0,0 +1,38 @@
/*
* Colors of the terminal and the static pages, taken from the Security Command
* Gitea theme. On the server, config/theme.css is appended to this file, so an
* override only needs the variables it changes. Most variables fall back to
* the names Gitea themes use, so the :root block of a Gitea theme works as an
* override as well.
*/
:root {
color-scheme: dark;
--background: var(--color-body, #060404);
--surface: var(--color-box-header, #120e0e);
--border: var(--color-light-border, #2a2223);
--text: var(--color-text, #e6dfdf);
--muted: var(--color-text-light-2, #948787);
--accent: var(--color-primary, #d24654);
--warning: var(--color-warning-text, #db6b76);
--cursor: var(--color-primary, #d24654);
--selection: var(--color-primary-alpha-50, #d2465480);
/* The 16 terminal colors. */
--ansi-black: var(--color-ansi-black, #202225);
--ansi-red: var(--color-ansi-red, #cc4848);
--ansi-green: var(--color-ansi-green, #87ab63);
--ansi-yellow: var(--color-ansi-yellow, #cc9903);
--ansi-blue: var(--color-ansi-blue, #3a8ac6);
--ansi-magenta: var(--color-ansi-magenta, #d22e8b);
--ansi-cyan: var(--color-ansi-cyan, #00918a);
--ansi-white: var(--color-ansi-white, #c1c3c8);
--ansi-bright-black: var(--color-ansi-bright-black, #45484e);
--ansi-bright-red: var(--color-ansi-bright-red, #d15a5a);
--ansi-bright-green: var(--color-ansi-bright-green, #93b373);
--ansi-bright-yellow: var(--color-ansi-bright-yellow, #eaaf03);
--ansi-bright-blue: var(--color-ansi-bright-blue, #4e96cc);
--ansi-bright-magenta: var(--color-ansi-bright-magenta, #d74397);
--ansi-bright-cyan: var(--color-ansi-bright-cyan, #00b6ad);
--ansi-bright-white: var(--color-ansi-bright-white, #f8f8f8);
}
+42
View File
@@ -0,0 +1,42 @@
import type { Terminal } from '@xterm/xterm';
import type { EndReason } from './connection.ts';
const DIM = '\x1b[2m';
const RESET = '\x1b[0m';
/**
* xterm.js hides the cursor until the first focus or key press. Leaving the
* alternate screen while on the normal one changes nothing else but shows it.
*/
const SHOW_CURSOR = '\x1b[?47l';
/**
* The boot screen is only the cursor, which shows that the terminal waits for
* a key. Nothing reaches the server until the visitor presses one.
*/
export function showBoot(terminal: Terminal): void {
terminal.write(SHOW_CURSOR);
}
const END_MESSAGES: Record<EndReason, string> = {
closed: 'session closed',
expired: 'session expired (time limit reached)',
idle: 'session ended after a while without input',
error: 'the sandbox could not be started',
gone: 'the previous session has ended',
lost: 'connection lost',
rejected: 'the server is not reachable',
busy: 'all sandboxes and the queue are taken, try again in a few minutes',
};
export function endMessage(reason: EndReason): string {
return `\r\n${DIM}[${END_MESSAGES[reason]}]${RESET}\r\n`;
}
/** Rewrites the current line, so position updates do not pile up. */
export function queueMessage(position: number): string {
return `\r\x1b[2K${DIM}the server is limited right now, position ${position} in the queue...${RESET}`;
}
/** Starts where the cursor waits: on the empty boot screen or below the end message. */
export const CONNECTING_MESSAGE = `${DIM}connecting...${RESET}\r\n`;
+143
View File
@@ -0,0 +1,143 @@
import { describe, expect, it } from 'vitest';
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
class FakeSocket
{
binaryType = 'blob';
readyState: number = WebSocket.CONNECTING;
sent: (string | Uint8Array)[] = [];
onopen?: () => void;
onmessage?: (event: { data: unknown }) => void;
onclose?: () => void;
send(data: string | Uint8Array): void {
this.sent.push(data);
}
close(): void {
this.onclose?.();
}
open(): void {
this.readyState = WebSocket.OPEN;
this.onopen?.();
}
receive(message: unknown): void {
this.onmessage?.({ data: JSON.stringify(message) });
}
}
function connect(token?: string)
{
const socket = new FakeSocket();
const events = {
queued: [] as number[],
ready: [] as Ready[],
output: [] as string[],
idle: [] as number[],
ended: [] as EndReason[],
};
const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, token, {
queued: (position) => events.queued.push(position),
ready: (session) => events.ready.push(session),
output: (data) => events.output.push(new TextDecoder().decode(data)),
idle: (seconds) => events.idle.push(seconds),
ended: (reason) => events.ended.push(reason),
}, {
createSocket: () => socket as unknown as WebSocket,
solve: async (challenge, difficulty) => challenge.length * 1000 + difficulty,
});
return { socket, events, connection };
}
describe('terminalUrl', () => {
it('follows the page protocol', () => {
expect(terminalUrl({ protocol: 'https:', host: 'security-command.org' })).toBe('wss://security-command.org/ws');
expect(terminalUrl({ protocol: 'http:', host: 'localhost:5173' })).toBe('ws://localhost:5173/ws');
});
});
describe('TerminalConnection', () => {
it('answers the challenge with a hello carrying the solved nonce and the latest size', async () => {
const { socket, events, connection } = connect();
socket.open();
socket.receive({ type: 'challenge', challenge: 'abc', difficulty: 20 });
connection.resize({ cols: 100, rows: 30 });
await Promise.resolve();
expect(socket.sent.at(-1)).toBe('{"type":"hello","nonce":3020,"cols":100,"rows":30}');
});
it('uses binary frames for terminal input', () => {
const { socket, connection } = connect();
connection.input('ignored before open');
socket.open();
connection.input('ls\r');
expect(socket.binaryType).toBe('arraybuffer');
expect(new TextDecoder().decode(socket.sent[0] as Uint8Array)).toBe('ls\r');
expect(socket.sent).toHaveLength(1);
});
it('resumes with a token and ignores the challenge', async () => {
const { socket, events } = connect('A'.repeat(22));
socket.open();
socket.receive({ type: 'challenge', challenge: 'abc', difficulty: 20 });
await Promise.resolve();
expect(socket.sent).toEqual([`{"type":"resume","token":"${'A'.repeat(22)}","cols":80,"rows":24}`]);
});
it('passes queue positions, readiness, output and idle warnings on', () => {
const { socket, events } = connect();
socket.open();
socket.receive({ type: 'queued', position: 3 });
socket.receive({ type: 'ready', token: 't', expiresAt: 1, resumed: false });
socket.onmessage?.({ data: new TextEncoder().encode('hi').buffer });
socket.receive({ type: 'idle', secondsLeft: 30 });
expect(events.queued).toEqual([3]);
expect(events.ready).toEqual([{ token: 't', expiresAt: 1, resumed: false }]);
expect(events.output).toEqual(['hi']);
expect(events.idle).toEqual([30]);
});
it('reports the server reason, a refusal, a lost connection, or an unreachable server', () => {
const expired = connect();
expired.socket.open();
expired.socket.receive({ type: 'exit', reason: 'expired' });
expired.socket.close();
const refused = connect();
refused.socket.open();
refused.socket.receive({ type: 'refused', reason: 'busy' });
refused.socket.close();
const lost = connect();
lost.socket.open();
lost.socket.close();
const rejected = connect();
rejected.socket.close();
rejected.socket.close();
expect(expired.events.ended).toEqual(['expired']);
expect(refused.events.ended).toEqual(['busy']);
expect(lost.events.ended).toEqual(['lost']);
expect(rejected.events.ended).toEqual(['rejected']);
});
it('encodes binary input byte by byte', () => {
const { socket, connection } = connect();
socket.open();
connection.inputBinary('\x1b[M\xff');
expect([...(socket.sent[0] as Uint8Array)]).toEqual([0x1b, 0x5b, 0x4d, 0xff]);
});
});
+145
View File
@@ -0,0 +1,145 @@
import {
TERMINAL_PATH,
type ClientMessage,
type ExitReason,
type RefusalReason,
type ServerMessage,
type TerminalSize,
} from '@homepage/protocol/terminal';
import { solveInWorker, type Solver } from './solver.ts';
/** Why a session ended: the server's reason, or what the browser observed. */
export type EndReason = ExitReason | RefusalReason | 'lost' | 'rejected';
export type Ready = { token: string; expiresAt: number; resumed: boolean };
export type ConnectionEvents = {
queued(position: number): void;
ready(session: Ready): void;
output(data: Uint8Array): void;
idle(secondsLeft: number): void;
ended(reason: EndReason): void;
};
export type SocketFactory = (url: string) => WebSocket;
export type ConnectionOptions = {
createSocket?: SocketFactory;
solve?: Solver;
};
export function terminalUrl(location: Pick<Location, 'protocol' | 'host'>): string
{
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
return `${scheme}://${location.host}${TERMINAL_PATH}`;
}
/**
* One WebSocket to the backend. It either asks for a new sandbox, after
* solving the server's proof of work, or resumes an existing one with a token.
* It reports everything until the socket closes.
*/
export class TerminalConnection
{
private readonly socket: WebSocket;
private readonly events: ConnectionEvents;
private readonly encoder = new TextEncoder();
private readonly token?: string;
private readonly solve: Solver;
private size: TerminalSize;
private endReason?: ExitReason | RefusalReason;
private opened = false;
private ended = false;
constructor(url: string, size: TerminalSize, token: string | undefined, events: ConnectionEvents, options: ConnectionOptions = {})
{
this.events = events;
this.size = size;
this.token = token;
this.solve = options.solve ?? solveInWorker;
this.socket = (options.createSocket ?? ((target) => new WebSocket(target)))(url);
this.socket.binaryType = 'arraybuffer';
this.socket.onopen = () =>
{
this.opened = true;
if (token) this.control({ type: 'resume', token, ...this.size });
};
this.socket.onmessage = (event: MessageEvent) =>
{
if (event.data instanceof ArrayBuffer)
{
this.events.output(new Uint8Array(event.data));
return;
}
const message = JSON.parse(String(event.data)) as ServerMessage;
switch (message.type)
{
case 'challenge':
if (!this.token) this.greet(message.challenge, message.difficulty);
break;
case 'queued':
this.events.queued(message.position);
break;
case 'ready':
this.events.ready({ token: message.token, expiresAt: message.expiresAt, resumed: message.resumed });
break;
case 'idle':
this.events.idle(message.secondsLeft);
break;
case 'exit':
case 'refused':
this.endReason = message.reason;
break;
}
};
this.socket.onclose = () =>
{
if (this.ended) return;
this.ended = true;
this.events.ended(this.endReason ?? (this.opened ? 'lost' : 'rejected'));
};
}
input(data: string): void {
this.send(this.encoder.encode(data));
}
/** Input that xterm reports as binary, one byte per character (mouse reports). */
inputBinary(data: string): void {
this.send(Uint8Array.from(data, (character) => character.charCodeAt(0) & 0xff));
}
resize(size: TerminalSize): void
{
this.size = size;
this.control({ type: 'resize', ...size });
}
close(): void {
this.socket.close();
}
private greet(challenge: string, difficulty: number): void
{
this.solve(challenge, difficulty).then(
(nonce) => this.control({ type: 'hello', nonce, ...this.size }),
() => this.socket.close(),
);
}
private control(message: ClientMessage): void {
this.send(JSON.stringify(message));
}
private send(data: string | Uint8Array<ArrayBuffer>): void {
if (this.socket.readyState === WebSocket.OPEN) this.socket.send(data);
}
}
+41
View File
@@ -0,0 +1,41 @@
type Key = {
label: string;
/** Escape sequence, or a function when it depends on the terminal mode. */
sequence: string | ((applicationCursor: boolean) => string);
};
const arrow = (code: string) => (applicationCursor: boolean) => `\x1b${applicationCursor ? 'O' : '['}${code}`;
const KEYS: Key[] = [
{ label: 'tab', sequence: '\t' },
{ label: 'esc', sequence: '\x1b' },
{ label: 'ctrl-c', sequence: '\x03' },
{ label: '↑', sequence: arrow('A') },
{ label: '↓', sequence: arrow('B') },
{ label: '←', sequence: arrow('D') },
{ label: '→', sequence: arrow('C') },
{ label: 'ls', sequence: 'ls\r' },
{ label: 'cd ..', sequence: 'cd ..\r' },
{ label: 'status', sequence: 'status\r' },
];
/** Buttons for keys that phone keyboards lack. They only exist on touch devices. */
export function createKeybar(container: HTMLElement, applicationCursor: () => boolean, send: (data: string) => void): void
{
for (const key of KEYS)
{
const button = document.createElement('button');
button.type = 'button';
button.textContent = key.label;
// Keeps the focus, and with it the on screen keyboard, in the terminal.
button.addEventListener('pointerdown', (event) => event.preventDefault());
button.addEventListener('click', () =>
send(typeof key.sequence === 'string' ? key.sequence : key.sequence(applicationCursor())),
);
container.append(button);
}
container.hidden = false;
}
+183
View File
@@ -0,0 +1,183 @@
import '@fontsource/jetbrains-mono/400.css';
import '@fontsource/jetbrains-mono/700.css';
import '@xterm/xterm/css/xterm.css';
import './style.css';
import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { WebglAddon } from '@xterm/addon-webgl';
import { Terminal } from '@xterm/xterm';
import { CONNECTING_MESSAGE, endMessage, queueMessage, showBoot } from './boot.ts';
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
import { createKeybar } from './keybar.ts';
import { terminalTheme } from './theme.ts';
import { savedToken } from './token.ts';
type State = 'booting' | 'idle' | 'connecting' | 'active' | 'reconnecting';
/** Reconnecting stops shortly before the server's grace period would end anyway. */
const RECONNECT_DEADLINE_MS = 40_000;
const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000];
const touch = window.matchMedia('(pointer: coarse)').matches;
const element = document.getElementById('terminal')!;
const notice = document.getElementById('notice')!;
// The cursor stays a solid block without focus, so the prompt never looks inert.
const terminal = new Terminal({
fontFamily: '"JetBrains Mono", monospace',
fontSize: touch ? 13 : 15,
cursorBlink: true,
cursorInactiveStyle: 'block',
scrollback: 5000,
theme: terminalTheme(),
});
// The key bar takes its space before the first fit, so the grid never overflows.
if (touch)
{
createKeybar(document.getElementById('keybar')!, () => terminal.modes.applicationCursorKeysMode, input);
element.addEventListener('click', () => { if (state === 'idle') start(); });
}
const fit = new FitAddon();
terminal.loadAddon(fit);
terminal.loadAddon(new WebLinksAddon());
// Measuring cells before the font is ready would size the grid wrongly.
await Promise.all([document.fonts.load('15px "JetBrains Mono"'), document.fonts.load('bold 15px "JetBrains Mono"')]);
terminal.open(element);
try
{
const webgl = new WebglAddon();
webgl.onContextLoss(() => webgl.dispose());
terminal.loadAddon(webgl);
}
catch { /* The DOM renderer remains as a fallback without WebGL. */ }
fit.fit();
terminal.focus();
let state: State = 'booting';
let connection: TerminalConnection | undefined;
let reconnectStarted = 0;
let reconnectAttempt = 0;
function showNotice(text: string): void
{
notice.textContent = text;
notice.hidden = false;
}
function hideNotice(): void {
notice.hidden = true;
}
function size() {
return { cols: terminal.cols, rows: terminal.rows };
}
/**
* Opens a connection. With a token it resumes; after a page reload the
* screen is empty, so Ctrl-L asks the shell or program to redraw itself.
*/
function connect(token?: string, redraw = false): void
{
connection = new TerminalConnection(terminalUrl(window.location), size(), token, {
queued: (position) => terminal.write(queueMessage(position)),
ready: (session: Ready) =>
{
savedToken.set(session.token);
hideNotice();
reconnectAttempt = 0;
if (!session.resumed) terminal.reset();
state = 'active';
terminal.focus();
if (session.resumed && redraw) connection?.input('\x0c');
},
output: (data) => terminal.write(data),
idle: (secondsLeft) => showNotice(`no input for a while, the session ends in ${secondsLeft} seconds unless you type`),
ended: (reason) => ended(reason),
});
}
function ended(reason: EndReason): void
{
connection = undefined;
const dropped = reason === 'lost' || reason === 'rejected';
if (dropped && (state === 'active' || state === 'reconnecting') && savedToken.get())
{
reconnect();
return;
}
savedToken.clear();
hideNotice();
if (state === 'booting')
{
boot();
return;
}
state = 'idle';
terminal.write(endMessage(reason));
}
function reconnect(): void
{
if (state !== 'reconnecting')
{
state = 'reconnecting';
reconnectStarted = Date.now();
}
if (Date.now() - reconnectStarted > RECONNECT_DEADLINE_MS)
{
state = 'active';
savedToken.clear();
ended('lost');
return;
}
showNotice('connection lost, reconnecting...');
const delay = RECONNECT_DELAYS_MS[Math.min(reconnectAttempt++, RECONNECT_DELAYS_MS.length - 1)];
setTimeout(() => connect(savedToken.get()), delay);
}
function start(): void
{
state = 'connecting';
terminal.write(CONNECTING_MESSAGE);
connect();
}
function input(data: string): void
{
if (state === 'active')
{
hideNotice();
connection?.input(data);
}
else if (state === 'idle') start();
}
function boot(): void
{
showBoot(terminal);
state = 'idle';
}
terminal.onData(input);
terminal.onBinary((data) => { if (state === 'active') connection?.inputBinary(data); });
terminal.onResize(({ cols, rows }) => connection?.resize({ cols, rows }));
new ResizeObserver(() => fit.fit()).observe(element);
// A reload within the grace period picks the running sandbox up again.
const token = savedToken.get();
if (token) connect(token, true);
else boot();
+10
View File
@@ -0,0 +1,10 @@
import { solveProof } from '@homepage/protocol/proof';
type Task = { challenge: string; difficulty: number };
const scope = globalThis as unknown as {
onmessage: ((event: MessageEvent<Task>) => void) | null;
postMessage: (nonce: number | undefined) => void;
};
scope.onmessage = ({ data }) => scope.postMessage(solveProof(data.challenge, data.difficulty));
+22
View File
@@ -0,0 +1,22 @@
export type Solver = (challenge: string, difficulty: number) => Promise<number>;
/** Solves the proof of work in a worker, so the page stays responsive meanwhile. */
export const solveInWorker: Solver = (challenge, difficulty) => new Promise((resolve, reject) =>
{
const worker = new Worker(new URL('./proof.worker.ts', import.meta.url), { type: 'module' });
worker.onmessage = ({ data }: MessageEvent<number | undefined>) =>
{
worker.terminate();
if (data === undefined) reject(new Error('no solution found'));
else resolve(data);
};
worker.onerror = (event) =>
{
worker.terminate();
reject(new Error(event.message));
};
worker.postMessage({ challenge, difficulty });
});
+127
View File
@@ -0,0 +1,127 @@
/* Colors come from /theme.css. */
:root {
font-family: "JetBrains Mono", monospace;
}
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
margin: 0;
background: var(--background);
color: var(--text);
}
body {
display: flex;
flex-direction: column;
height: 100dvh;
overflow: hidden;
}
.bar {
display: flex;
flex: none;
justify-content: space-between;
align-items: center;
gap: 1rem;
padding: 0.35rem 1rem;
border-bottom: 1px solid var(--border);
font-size: 0.8rem;
color: var(--muted);
user-select: none;
}
.bar .site {
color: var(--accent);
}
.bar nav {
display: flex;
gap: 0.5rem;
}
.bar a {
color: var(--muted);
text-decoration: none;
}
.bar a:hover,
.bar a:focus-visible {
color: var(--text);
text-decoration: underline;
}
.notice {
flex: none;
padding: 0.35rem 1rem;
border-bottom: 1px solid var(--border);
background: var(--surface);
color: var(--warning);
font-size: 0.8rem;
}
.notice[hidden] {
display: none;
}
#terminal {
flex: 1;
min-height: 0;
}
/* The fit addon subtracts padding of the xterm element, not of its container. */
#terminal .xterm {
height: 100%;
padding: 0.5rem 0 0 1rem;
}
/* xterm paints its viewport black, which would show in the padding. */
#terminal .xterm-viewport {
background-color: var(--background);
}
.keybar {
display: flex;
flex: none;
gap: 0.4rem;
padding: 0.4rem 1rem calc(0.4rem + env(safe-area-inset-bottom));
overflow-x: auto;
border-top: 1px solid var(--border);
background: var(--surface);
scrollbar-width: none;
}
.keybar[hidden] {
display: none;
}
.keybar button {
flex: none;
min-width: 2.75rem;
min-height: 2.25rem;
padding: 0 0.6rem;
border: 1px solid var(--border);
border-radius: 0.3rem;
background: var(--background);
color: var(--text);
font: inherit;
font-size: 0.85rem;
}
.noscript {
padding: 1rem;
}
.noscript a {
color: var(--accent);
}
@media (max-width: 600px) {
#terminal .xterm {
padding-left: 0.5rem;
}
}
+28
View File
@@ -0,0 +1,28 @@
import type { ITheme } from '@xterm/xterm';
const COLORS = ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'] as const;
/** Reads a variable of theme.css, which loads before this script runs. */
function variable(name: string): string {
return getComputedStyle(document.documentElement).getPropertyValue(`--${name}`).trim();
}
export function terminalTheme(): ITheme
{
const theme: Record<string, string> = {
background: variable('background'),
foreground: variable('text'),
cursor: variable('cursor'),
cursorAccent: variable('background'),
selectionBackground: variable('selection'),
};
for (const color of COLORS)
{
theme[color] = variable(`ansi-${color}`);
theme[`bright${color[0]!.toUpperCase()}${color.slice(1)}`] = variable(`ansi-bright-${color}`);
}
// Missing variables keep the defaults of xterm.js.
return Object.fromEntries(Object.entries(theme).filter(([, value]) => value !== ''));
}
+26
View File
@@ -0,0 +1,26 @@
const KEY = 'sandbox-token';
/**
* The reconnect token of the current session. It lives in sessionStorage, so
* it survives reloads of this tab but no other tab sees it. Storage can be
* unavailable (private modes, blocked site data), which only disables resuming.
*/
export const savedToken = {
get(): string | undefined
{
try { return sessionStorage.getItem(KEY) ?? undefined; }
catch { return undefined; }
},
set(token: string): void
{
try { sessionStorage.setItem(KEY, token); }
catch { /* Resuming is a convenience; the session works without it. */ }
},
clear(): void
{
try { sessionStorage.removeItem(KEY); }
catch { /* Nothing was stored, so there is nothing to clear. */ }
},
};
+18
View File
@@ -0,0 +1,18 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"lib": [
"es2024",
"dom",
"dom.iterable"
],
"types": [
"vite/client"
]
},
"include": [
"src",
"vite.config.ts"
],
"exclude": []
}
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';
const backend = 'http://127.0.0.1:8380';
export default defineConfig({
build: {
target: 'es2022',
assetsDir: 'assets',
},
server: {
proxy: {
'/ws': { target: backend, ws: true },
'/raw': backend,
'/ls': backend,
'/impressum': backend,
'/datenschutz': backend,
'/theme.css': backend,
},
},
});
+16
View File
@@ -0,0 +1,16 @@
# 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/jobs-service build
FROM node:24-alpine
# Tools job scripts can rely on.
RUN apk add --no-cache bash coreutils curl git jq \
&& printf '#!/bin/sh\nexec node /app/jobctl.js "$@"\n' > /usr/local/bin/jobctl \
&& chmod 0755 /usr/local/bin/jobctl
COPY --from=build /src/apps/jobs/dist/ /app/
# Compose runs the service as the owner of the content directory instead.
USER 10003:10003
CMD ["node", "/app/main.js"]
+12
View File
@@ -0,0 +1,12 @@
{
"name": "@homepage/jobs-service",
"private": true,
"type": "module",
"scripts": {
"build": "esbuild src/main.ts src/jobctl.ts --bundle --platform=node --target=node24 --format=esm --outdir=dist"
},
"dependencies": {
"@homepage/jobs": "workspace:*",
"@homepage/protocol": "workspace:*"
}
}
+29
View File
@@ -0,0 +1,29 @@
export type JobsConfig = {
jobsFile: string;
/** Directory of the job scripts; relative script paths start here. */
scriptsDir: string;
contentDir: string;
/** Read only views of the host, /srv as srv and the nginx config as nginx. Watch paths are relative to it and must stay inside. */
hostDir: string;
/** Builtin jobs of the backend are triggered through files in this directory. */
triggerDir: string;
controlSocket: string;
/** Time a cancelled script gets between SIGTERM and SIGKILL. */
killGraceMs: number;
};
export function loadConfig(env: NodeJS.ProcessEnv): JobsConfig
{
const killGraceSeconds = Number(env.KILL_GRACE_SECONDS ?? 5);
if (!Number.isInteger(killGraceSeconds) || killGraceSeconds < 0) throw new Error('KILL_GRACE_SECONDS must be a whole number');
return {
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
scriptsDir: env.SCRIPTS_DIR ?? '/jobs',
contentDir: env.CONTENT_DIR ?? '/content',
hostDir: env.HOST_DIR ?? '/host',
triggerDir: env.TRIGGER_DIR ?? '/run/jobs/triggers',
controlSocket: env.CONTROL_SOCKET ?? '/run/jobs/control.sock',
killGraceMs: killGraceSeconds * 1000,
};
}
+85
View File
@@ -0,0 +1,85 @@
import { chmodSync, rmSync } from 'node:fs';
import { connect, createServer, type Server, type Socket } from 'node:net';
import { readLine } from '@homepage/protocol';
import type { JobService, JobState } from './service.ts';
/** Requests jobctl sends to the jobs service, one JSON line per connection. */
export type ControlRequest =
| { op: 'list' }
| { op: 'run' | 'cancel'; id: string };
export type ControlResponse =
| { ok: true; message?: string; jobs?: JobState[] }
| { ok: false; error: string };
const MAX_REQUEST_BYTES = 1024;
const MAX_RESPONSE_BYTES = 1024 * 1024;
function parseRequest(line: string): ControlRequest
{
const request = JSON.parse(line) as Partial<{ op: unknown; id: unknown }>;
if (request.op === 'list') return { op: 'list' };
if ((request.op === 'run' || request.op === 'cancel') && typeof request.id === 'string') return { op: request.op, id: request.id };
throw new Error('unknown request');
}
async function answer(service: JobService, request: ControlRequest): Promise<ControlResponse>
{
switch (request.op)
{
case 'list': return { ok: true, jobs: service.list() };
case 'run': return { ok: true, message: await service.run(request.id) };
case 'cancel': return { ok: true, message: service.cancel(request.id) };
}
}
async function handle(connection: Socket, service: JobService): Promise<void>
{
let response: ControlResponse;
try
{
const { line } = await readLine(connection, MAX_REQUEST_BYTES);
response = await answer(service, parseRequest(line));
}
catch (error) { response = { ok: false, error: (error as Error).message }; }
connection.end(`${JSON.stringify(response)}\n`);
}
/** Listens on a Unix socket only the service's own user may use. */
export function listenControl(service: JobService, path: string): Promise<Server>
{
rmSync(path, { force: true });
const server = createServer((connection) =>
{
connection.on('error', () => connection.destroy());
void handle(connection, service);
});
return new Promise((resolve, reject) =>
{
server.once('error', reject);
server.listen(path, () =>
{
chmodSync(path, 0o600);
resolve(server);
});
});
}
export function request(path: string, body: ControlRequest): Promise<ControlResponse>
{
return new Promise((resolve, reject) =>
{
const socket = connect(path);
socket.once('error', reject);
socket.once('connect', () =>
{
socket.write(`${JSON.stringify(body)}\n`);
readLine(socket, MAX_RESPONSE_BYTES, 30_000)
.then(({ line }) => resolve(JSON.parse(line) as ControlResponse), reject)
.finally(() => socket.destroy());
});
});
}
+61
View File
@@ -0,0 +1,61 @@
import { request, type ControlRequest } from './control.ts';
import type { JobState, RunRecord } from './service.ts';
const usage = 'usage: jobctl list | run <id> | cancel <id>';
function ago(time: number): string
{
const seconds = Math.round((Date.now() - time) / 1000);
if (seconds < 120) return `${seconds}s ago`;
if (seconds < 7200) return `${Math.round(seconds / 60)}m ago`;
return `${Math.round(seconds / 3600)}h ago`;
}
function describeRun(run: RunRecord | undefined): string
{
if (!run) return '';
if (run.outcome === 'running') return `since ${ago(run.startedAt)}`;
const took = `${((run.finishedAt! - run.startedAt) / 1000).toFixed(1)}s`;
return `${run.outcome} ${ago(run.finishedAt!)}, took ${took}${run.error ? `: ${run.error}` : ''}`;
}
function state(job: JobState): string
{
if (!job.enabled) return 'disabled';
if (job.kind === 'builtin') return 'backend';
return job.running ? 'running' : 'idle';
}
function table(jobs: JobState[]): string
{
const rows = [['ID', 'KIND', 'STATE', 'SCHEDULE', 'LAST RUN'], ...jobs.map((job) => [job.id, job.kind, state(job), job.schedule, describeRun(job.last)])];
const widths = rows[0]!.map((_, column) => Math.max(...rows.map((row) => row[column]!.length)));
return rows.map((row) => row.map((cell, column) => cell.padEnd(widths[column]!)).join(' ').trimEnd()).join('\n');
}
const socket = process.env.CONTROL_SOCKET ?? '/run/jobs/control.sock';
const [command, id] = process.argv.slice(2);
let body: ControlRequest;
if (command === 'list') body = { op: 'list' };
else if ((command === 'run' || command === 'cancel') && id) body = { op: command, id };
else
{
console.error(usage);
process.exit(2);
}
const response = await request(socket, body).catch((error: Error) =>
{
console.error(`cannot reach the jobs service at ${socket}: ${error.message}`);
process.exit(1);
});
if (!response.ok)
{
console.error(response.error);
process.exit(1);
}
console.log(response.jobs ? table(response.jobs) : response.message);
+21
View File
@@ -0,0 +1,21 @@
import { loadConfig } from './config.ts';
import { listenControl } from './control.ts';
import { JobService } from './service.ts';
const log = (message: string) => console.log(`[jobs] ${message}`);
const config = loadConfig(process.env);
const service = new JobService(config, log);
await service.start();
const control = await listenControl(service, config.controlSocket);
log(`jobctl listens on ${config.controlSocket}`);
for (const signal of ['SIGTERM', 'SIGINT'] as const)
{
process.once(signal, async () => {
control.close();
await service.stop();
process.exit(0);
});
}
+84
View File
@@ -0,0 +1,84 @@
import { chmodSync, existsSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { JobCancelledError, type JobDefinition } from '@homepage/jobs';
import { beforeEach, describe, expect, it } from 'vitest';
import { runScript, ScriptError, type RunnerOptions } from './runner.ts';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function job(path: string, overrides: Partial<JobDefinition> = {}): JobDefinition
{
return { id: 'test', path, args: [], on: [], watch: [], then: [], timeout: 60_000, env: {}, enabled: true, parallel: false, ...overrides };
}
describe('runScript', () => {
let dir: string;
let lines: string[];
let options: RunnerOptions;
const script = (name: string, body: string) =>
{
writeFileSync(join(dir, name), `#!/bin/sh\n${body}\n`);
chmodSync(join(dir, name), 0o755);
};
beforeEach(() =>
{
dir = mkdtempSync(join(tmpdir(), 'runner-'));
lines = [];
options = { scriptsDir: dir, env: { CONTENT_DIR: '/content' }, killGraceMs: 300, output: (line) => lines.push(line) };
});
it('passes arguments and environment and collects output', async () => {
script('hello.sh', 'echo "$1 $JOB_ID $CONTENT_DIR $GREETING"; echo oops >&2');
await runScript(job('hello.sh', { args: ['hi'], env: { GREETING: 'moin' } }), new AbortController().signal, options);
expect(lines.sort()).toEqual(['hi test /content moin', 'oops']);
});
it('fails on a non zero exit code and on scripts that cannot start', async () => {
script('fail.sh', 'exit 3');
writeFileSync(join(dir, 'plain.sh'), 'echo');
await expect(runScript(job('fail.sh'), new AbortController().signal, options)).rejects.toThrow('exited with code 3');
await expect(runScript(job('plain.sh'), new AbortController().signal, options)).rejects.toThrow('is not executable');
await expect(runScript(job('missing.sh'), new AbortController().signal, options)).rejects.toBeInstanceOf(ScriptError);
});
it('stops the whole process group when cancelled', async () => {
const marker = join(dir, 'survived');
script('tree.sh', `(sleep 1; touch ${marker}) & sleep 5`);
const controller = new AbortController();
const run = runScript(job('tree.sh'), controller.signal, options);
await sleep(100);
controller.abort(new JobCancelledError('cancelled'));
await expect(run).rejects.toBeInstanceOf(JobCancelledError);
await sleep(1200);
expect(existsSync(marker)).toBe(false);
});
it('kills scripts that ignore SIGTERM after the grace time', async () => {
script('stubborn.sh', `trap '' TERM; while :; do sleep 0.05; done`);
const controller = new AbortController();
const run = runScript(job('stubborn.sh'), controller.signal, options);
await sleep(100);
const started = Date.now();
controller.abort(new JobCancelledError('cancelled'));
await expect(run).rejects.toBeInstanceOf(JobCancelledError);
expect(Date.now() - started).toBeGreaterThanOrEqual(250);
});
it('kills background processes left behind by a finished script', async () => {
const marker = join(dir, 'survived');
script('leaky.sh', `(sleep 0.5; touch ${marker}) &`);
await runScript(job('leaky.sh'), new AbortController().signal, options);
await sleep(800);
expect(existsSync(marker)).toBe(false);
});
});
+95
View File
@@ -0,0 +1,95 @@
import { spawn } from 'node:child_process';
import { resolve } from 'node:path';
import { createInterface } from 'node:readline';
import type { JobDefinition } from '@homepage/jobs';
export type RunnerOptions = {
scriptsDir: string;
/** Variables every script gets on top of a minimal base environment; the job's own env wins. */
env: Record<string, string>;
killGraceMs: number;
/** Receives every line the script prints. */
output: (line: string) => void;
};
export class ScriptError extends Error {}
const MAX_LINE_CHARS = 4096;
const BASE_ENV = { PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', HOME: '/tmp', LANG: 'C.UTF-8' };
function spawnError(path: string, error: NodeJS.ErrnoException): string
{
switch (error.code)
{
case 'ENOENT': return `${path} does not exist`;
case 'EACCES': return `${path} is not executable`;
default: return `${path} cannot be started: ${error.message}`;
}
}
/**
* Runs a script job in its own process group, so cancelling it also stops
* everything the script started. Cancelling sends SIGTERM and, after the
* grace time, SIGKILL. Processes still left once the script exits are killed.
*/
export function runScript(job: JobDefinition, signal: AbortSignal, options: RunnerOptions): Promise<void>
{
return new Promise((done, fail) =>
{
signal.throwIfAborted();
const path = resolve(options.scriptsDir, job.path!);
const child = spawn(path, job.args, {
cwd: options.scriptsDir,
env: { ...BASE_ENV, ...options.env, JOB_ID: job.id, ...job.env },
detached: true,
stdio: ['ignore', 'pipe', 'pipe'],
});
const killGroup = (name: NodeJS.Signals) =>
{
if (child.pid === undefined) return;
try { process.kill(-child.pid, name); }
catch { /* The group is already gone. */ }
};
let killTimer: NodeJS.Timeout | undefined;
const onAbort = () =>
{
killGroup('SIGTERM');
killTimer = setTimeout(() => killGroup('SIGKILL'), options.killGraceMs);
};
signal.addEventListener('abort', onAbort, { once: true });
for (const stream of [child.stdout, child.stderr])
{
createInterface({ input: stream, crlfDelay: Infinity }).on('line', (line) =>
{
options.output(line.length > MAX_LINE_CHARS ? `${line.slice(0, MAX_LINE_CHARS)} [truncated]` : line);
});
}
let settled = false;
const finish = (error?: unknown) =>
{
if (settled) return;
settled = true;
clearTimeout(killTimer);
signal.removeEventListener('abort', onAbort);
if (error === undefined) done();
else fail(error);
};
// Leftover background processes would otherwise keep the output pipes open.
child.once('exit', () => killGroup('SIGKILL'));
child.once('error', (error) => finish(new ScriptError(spawnError(path, error))));
child.once('close', (code, name) =>
{
if (signal.aborted) finish(signal.reason);
else if (code === 0) finish();
else finish(new ScriptError(code === null ? `killed by ${name}` : `exited with code ${code}`));
});
});
}
+140
View File
@@ -0,0 +1,140 @@
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { loadJobs } from '@homepage/jobs';
import { afterEach, describe, expect, it } from 'vitest';
import type { JobsConfig } from './config.ts';
import { listenControl, request } from './control.ts';
import { JobService, prepareJobsFile } from './service.ts';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function setup(jobs: string, scripts: Record<string, string> = {})
{
const root = mkdtempSync(join(tmpdir(), 'jobs-'));
const config: JobsConfig = {
jobsFile: join(root, 'config', 'jobs.toml'),
scriptsDir: join(root, 'jobs'),
contentDir: join(root, 'content'),
hostDir: join(root, 'srv'),
triggerDir: join(root, 'triggers'),
controlSocket: join(root, 'control.sock'),
killGraceMs: 300,
};
for (const dir of ['config', 'jobs', 'content', 'srv/gitea', 'triggers']) mkdirSync(join(root, dir), { recursive: true });
writeFileSync(config.jobsFile, jobs);
for (const [name, body] of Object.entries(scripts))
{
writeFileSync(join(config.scriptsDir, name), `#!/bin/sh\n${body}\n`);
chmodSync(join(config.scriptsDir, name), 0o755);
}
const logs: string[] = [];
const service = new JobService(config, (line) => logs.push(line));
return { root, config, logs, service };
}
let current: JobService | undefined;
afterEach(async () => { await current?.stop(); });
describe('prepareJobsFile', () => {
it('creates the file with every system job', async () => {
const file = join(mkdtempSync(join(tmpdir(), 'jobs-')), 'jobs.toml');
await prepareJobsFile(file, () => {});
const text = readFileSync(file, 'utf8');
expect(text).toContain('# Jobs of security-command.org');
expect(loadJobs(text).missing).toBe('');
});
it('appends only missing system jobs and keeps existing ones as written', async () => {
const file = join(mkdtempSync(join(tmpdir(), 'jobs-')), 'jobs.toml');
writeFileSync(file, '[[job]]\nid = "status"\nbuiltin = "status"\nenabled = false');
await prepareJobsFile(file, () => {});
const { jobs, missing } = loadJobs(readFileSync(file, 'utf8'));
expect(missing).toBe('');
expect(jobs.filter((job) => job.id === 'status')).toEqual([expect.objectContaining({ enabled: false })]);
});
it('leaves a broken file alone', async () => {
const file = join(mkdtempSync(join(tmpdir(), 'jobs-')), 'jobs.toml');
writeFileSync(file, '[[job]\n');
await prepareJobsFile(file, () => {});
expect(readFileSync(file, 'utf8')).toBe('[[job]\n');
});
});
describe('JobService', () => {
it('runs script jobs, triggers builtin targets through files and reports runs', async () => {
const { config, service } = setup(
'[[job]]\nid = "services"\npath = "services.sh"\non = ["start"]\nthen = ["index"]\n',
{ 'services.sh': 'echo "gitea" > "$CONTENT_DIR/services.txt"' },
);
current = service;
await service.start();
await sleep(200);
expect(readFileSync(join(config.contentDir, 'services.txt'), 'utf8')).toBe('gitea\n');
expect(existsSync(join(config.triggerDir, 'index'))).toBe(true);
const state = service.list().find((job) => job.id === 'services');
expect(state).toMatchObject({ kind: 'script', running: false, schedule: 'on start', last: { outcome: 'ok' } });
expect(service.list().find((job) => job.id === 'index')).toMatchObject({ kind: 'builtin', schedule: 'on start, on content-change' });
});
it('runs a job when a watched host path changes', async () => {
const { root, config, service } = setup(
'[[job]]\nid = "watcher"\npath = "count.sh"\non = ["watch"]\nwatch = ["gitea/compose.yml"]\n',
{ 'count.sh': 'echo run >> "$CONTENT_DIR/runs"' },
);
current = service;
await service.start();
writeFileSync(join(root, 'srv/gitea/compose.yml'), 'services: {}');
writeFileSync(join(root, 'srv/gitea/other.yml'), 'ignored');
await sleep(2500);
expect(readFileSync(join(config.contentDir, 'runs'), 'utf8')).toBe('run\n');
});
it('refuses watch paths outside the host directory', async () => {
const { logs, service } = setup('[[job]]\nid = "loop"\npath = "x.sh"\non = ["watch"]\nwatch = ["../content"]\n');
current = service;
await service.start();
expect(logs.some((line) => line.includes('job "loop" cannot watch ../content'))).toBe(true);
});
it('runs, restarts and cancels jobs over the control socket', async () => {
const { config, service } = setup('[[job]]\nid = "slow"\npath = "slow.sh"\n', { 'slow.sh': 'sleep 5' });
current = service;
await service.start();
const server = await listenControl(service, config.controlSocket);
expect(await request(config.controlSocket, { op: 'run', id: 'slow' })).toEqual({ ok: true, message: 'started job "slow"' });
expect(await request(config.controlSocket, { op: 'run', id: 'slow' })).toEqual({ ok: true, message: 'restarting job "slow"' });
await sleep(100);
expect(await request(config.controlSocket, { op: 'cancel', id: 'slow' })).toEqual({ ok: true, message: 'cancelled job "slow"' });
await sleep(100);
expect(service.list().find((job) => job.id === 'slow')?.last?.outcome).toBe('cancelled');
expect(await request(config.controlSocket, { op: 'run', id: 'nope' })).toEqual({ ok: false, error: 'unknown job "nope"' });
expect(await request(config.controlSocket, { op: 'cancel', id: 'index' })).toMatchObject({ ok: false });
server.close();
});
it('applies edits to the job file without a restart', async () => {
const { config, logs, service } = setup('');
current = service;
await service.start();
writeFileSync(config.jobsFile, `${readFileSync(config.jobsFile, 'utf8')}\n[[job]]\nid = "new"\npath = "new.sh"\nenabled = false\n`);
await sleep(800);
expect(service.list().find((job) => job.id === 'new')).toMatchObject({ enabled: false });
expect(logs).toContain('job "new" is disabled');
});
});
+247
View File
@@ -0,0 +1,247 @@
import type { FSWatcher } from 'node:fs';
import { appendFile, readFile } from 'node:fs/promises';
import { isAbsolute, relative, resolve } from 'node:path';
import {
JobCancelledError,
JobTimeoutError,
loadJobs,
Scheduler,
watchFile,
watchPath,
writeTrigger,
type JobDefinition,
} from '@homepage/jobs';
import type { JobsConfig } from './config.ts';
import { runScript } from './runner.ts';
export type Outcome = 'running' | 'ok' | 'failed' | 'cancelled' | 'timed out';
export type RunRecord = {
startedAt: number;
finishedAt?: number;
outcome: Outcome;
error?: string;
};
export type JobState = {
id: string;
kind: 'script' | 'builtin';
enabled: boolean;
running: boolean;
schedule: string;
last?: RunRecord;
};
const RELOAD_DEBOUNCE_MS = 500;
const WATCH_QUIET_MS = 2000;
const STOP_POLL_MS = 100;
const FILE_HEADER = `# Jobs of security-command.org. The backend runs the builtin jobs, the jobs
# service runs the scripts. Edits apply within a second; all options are
# described in deploy/jobs.example.toml.
`;
const UNITS: [string, number][] = [['d', 86_400_000], ['h', 3_600_000], ['m', 60_000], ['s', 1000]];
function formatDuration(ms: number): string
{
for (const [unit, size] of UNITS) if (ms % size === 0) return `${ms / size}${unit}`;
return `${ms}ms`;
}
function describeSchedule(job: JobDefinition): string
{
const parts: string[] = [];
if (job.every !== undefined) parts.push(`every ${formatDuration(job.every)}`);
if (job.cron !== undefined) parts.push(`cron ${job.cron}`);
for (const event of job.on) if (event !== 'watch') parts.push(`on ${event}`);
if (job.watch.length > 0) parts.push(`watch ${job.watch.join(' ')}`);
return parts.join(', ') || 'manual';
}
function inside(base: string, path: string): boolean
{
const rest = relative(base, path);
return !rest.startsWith('..') && !isAbsolute(rest);
}
/**
* Creates the job file with the system jobs, or appends the system jobs it
* lacks, so they can be switched off there. A file that is not valid TOML is
* left alone.
*/
export async function prepareJobsFile(file: string, log: (message: string) => void): Promise<void>
{
const text = await readFile(file, 'utf8').catch((error: NodeJS.ErrnoException) =>
{
if (error.code === 'ENOENT') return '';
throw error;
});
const { parsed, missing } = loadJobs(text);
if (!parsed || !missing) return;
const separator = text === '' ? FILE_HEADER : text.endsWith('\n') ? '' : '\n';
await appendFile(file, separator + missing);
log(text === '' ? `created ${file} with the system jobs` : `added missing system jobs to ${file}`);
}
/**
* Runs the script jobs of the job file. Builtin jobs belong to the backend,
* which this service triggers through trigger files when a script job names
* one in "then" or jobctl runs one.
*/
export class JobService
{
private readonly config: JobsConfig;
private readonly log: (message: string) => void;
private readonly history = new Map<string, RunRecord>();
private definitions = new Map<string, JobDefinition>();
private scheduler?: Scheduler;
private jobWatchers: FSWatcher[] = [];
private fileWatcher?: FSWatcher;
constructor(config: JobsConfig, log: (message: string) => void)
{
this.config = config;
this.log = log;
}
async start(): Promise<void>
{
try { await prepareJobsFile(this.config.jobsFile, this.log); }
catch (error) { this.log(`cannot write ${this.config.jobsFile}: ${(error as Error).message}`); }
await this.load();
this.fileWatcher = watchFile(this.config.jobsFile, RELOAD_DEBOUNCE_MS, () => void this.load(), this.log);
}
/** Starts a job, or triggers it in the backend when it is builtin. Returns what happened. */
async run(id: string): Promise<string>
{
const job = this.definitions.get(id);
if (!job) throw new Error(`unknown job "${id}"`);
if (!job.enabled) throw new Error(`job "${id}" is disabled`);
if (job.builtin !== undefined)
{
await writeTrigger(this.config.triggerDir, id);
return `triggered builtin job "${id}" in the backend`;
}
const restart = !job.parallel && this.scheduler!.running().includes(id);
this.scheduler!.trigger(id);
return restart ? `restarting job "${id}"` : `started job "${id}"`;
}
cancel(id: string): string
{
const job = this.definitions.get(id);
if (!job) throw new Error(`unknown job "${id}"`);
if (job.builtin !== undefined) throw new Error(`job "${id}" is builtin and runs in the backend, which cannot be cancelled from here`);
return this.scheduler!.cancel(id) ? `cancelled job "${id}"` : `job "${id}" is not running`;
}
list(): JobState[]
{
const running = new Set(this.scheduler?.running());
return [...this.definitions.values()].map((job) => ({
id: job.id,
kind: job.builtin === undefined ? 'script' : 'builtin',
enabled: job.enabled,
running: running.has(job.id),
schedule: describeSchedule(job),
...(this.history.has(job.id) ? { last: this.history.get(job.id)! } : {}),
}));
}
/** Cancels all runs and waits until they ended, at most for the kill grace time and a bit. */
async stop(): Promise<void>
{
this.fileWatcher?.close();
this.stopJobs();
const deadline = Date.now() + this.config.killGraceMs + 1000;
while ((this.scheduler?.running().length ?? 0) > 0 && Date.now() < deadline)
{
await new Promise((resolve) => setTimeout(resolve, STOP_POLL_MS));
}
}
private stopJobs(): void
{
for (const watcher of this.jobWatchers) watcher.close();
this.jobWatchers = [];
this.scheduler?.stop();
}
private async load(): Promise<void>
{
let text = '';
try { text = await readFile(this.config.jobsFile, 'utf8'); }
catch { this.log(`${this.config.jobsFile} cannot be read, no script jobs run`); }
const { jobs, warnings } = loadJobs(text);
for (const warning of warnings) this.log(warning);
this.stopJobs();
this.definitions = new Map(jobs.map((job) => [job.id, job]));
const scripts = jobs.filter((job) => job.path !== undefined);
this.scheduler = new Scheduler(scripts, (job, signal) => this.execute(job, signal), {
log: this.log,
triggerOther: (id) => void this.run(id).catch((error: Error) => this.log(`cannot trigger job "${id}": ${error.message}`)),
});
this.scheduler.start();
for (const job of scripts) if (job.enabled) this.watch(job);
this.log(`loaded ${scripts.length} script job(s)`);
}
/** Watch paths must lie in the read only host directory, so a job can never trigger itself by writing. */
private watch(job: JobDefinition): void
{
for (const path of job.watch)
{
const target = resolve(this.config.hostDir, path);
if (!inside(this.config.hostDir, target))
{
this.log(`job "${job.id}" cannot watch ${path}: watch paths are relative to ${this.config.hostDir} and must stay inside it`);
continue;
}
const watcher = watchPath(target, WATCH_QUIET_MS, () => this.scheduler?.trigger(job.id), this.log);
if (watcher) this.jobWatchers.push(watcher);
}
}
private async execute(job: JobDefinition, signal: AbortSignal): Promise<void>
{
const record: RunRecord = { startedAt: Date.now(), outcome: 'running' };
this.history.set(job.id, record);
try
{
await runScript(job, signal, {
scriptsDir: this.config.scriptsDir,
env: { CONTENT_DIR: this.config.contentDir, HOST_DIR: this.config.hostDir },
killGraceMs: this.config.killGraceMs,
output: (line) => this.log(`${job.id}: ${line}`),
});
record.outcome = 'ok';
}
catch (error)
{
const reason = signal.aborted ? signal.reason : error;
record.outcome = reason instanceof JobCancelledError ? 'cancelled' : reason instanceof JobTimeoutError ? 'timed out' : 'failed';
record.error = reason instanceof Error ? reason.message : String(reason);
if (record.outcome === 'cancelled') this.log(`job "${job.id}" ${record.error}`);
throw error;
}
finally
{
record.finishedAt = Date.now();
}
}
}
+11
View File
@@ -0,0 +1,11 @@
# 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/spawner build
FROM node:24-alpine
COPY --from=build /src/apps/spawner/dist/spawner.js /app/spawner.js
USER 10001:10100
CMD ["node", "/app/spawner.js"]
+11
View File
@@ -0,0 +1,11 @@
{
"name": "@homepage/spawner",
"private": true,
"type": "module",
"scripts": {
"build": "esbuild src/main.ts --bundle --platform=node --target=node24 --format=esm --outfile=dist/spawner.js"
},
"dependencies": {
"@homepage/protocol": "workspace:*"
}
}
+58
View File
@@ -0,0 +1,58 @@
import { randomBytes } from 'node:crypto';
import { SpawnerClient } from '@homepage/protocol';
const usage = 'usage: cli.ts <spawner socket> run | list | kill <container id>';
const [socketPath, command, argument] = process.argv.slice(2);
if (!socketPath || !command) {
console.error(usage);
process.exit(2);
}
const client = new SpawnerClient(socketPath);
async function run(): Promise<void>
{
const sessionId = randomBytes(12).toString('base64url');
const size = { cols: process.stdout.columns ?? 80, rows: process.stdout.rows ?? 24 };
const containerId = await client.spawn(sessionId, Math.floor(Date.now() / 1000) + 20 * 60, size);
const stream = await client.attach(containerId);
const resize = () => client.resize(containerId, process.stdout.columns, process.stdout.rows).catch(() => {});
await resize();
process.stdout.on('resize', resize);
if (process.stdin.isTTY) process.stdin.setRawMode(true);
process.stdin.pipe(stream, { end: false });
stream.pipe(process.stdout);
stream.on('close', async () =>
{
if (process.stdin.isTTY) process.stdin.setRawMode(false);
await client.kill(containerId).catch(() => {});
process.exit(0);
});
}
switch (command)
{
case 'run':
await run();
break;
case 'list':
console.log(JSON.stringify(await client.list(), null, 2));
break;
case 'kill':
if (!argument) {
console.error(usage);
process.exit(2);
}
await client.kill(argument);
break;
default:
console.error(usage);
process.exit(2);
}
+40
View File
@@ -0,0 +1,40 @@
import { isAbsolute } from 'node:path';
export type SpawnerConfig = {
dockerSocket: string;
listenSocket: string;
image: string;
/** Host paths, resolved by the sandbox daemon and never opened by the spawner. */
contentDir: string;
statusDir: string;
maxSandboxes: number;
/** Only for local development with Podman, where gVisor is unavailable. */
allowNonGvisor: boolean;
};
function required(env: NodeJS.ProcessEnv, name: string): string {
const value = env[name];
if (!value) throw new Error(`${name} is not set`);
return value;
}
function absolute(env: NodeJS.ProcessEnv, name: string): string {
const value = required(env, name);
if (!isAbsolute(value)) throw new Error(`${name} must be an absolute path`);
return value;
}
export function loadConfig(env: NodeJS.ProcessEnv): SpawnerConfig {
const maxSandboxes = Number(env.MAX_SANDBOXES ?? 16);
if (!Number.isInteger(maxSandboxes) || maxSandboxes < 1) throw new Error('MAX_SANDBOXES must be a positive integer');
return {
dockerSocket: env.DOCKER_SOCKET ?? '/run/docker-sandbox/docker.sock',
listenSocket: env.SPAWNER_SOCKET ?? '/run/spawner/spawner.sock',
image: required(env, 'SANDBOX_IMAGE'),
contentDir: absolute(env, 'CONTENT_DIR'),
statusDir: absolute(env, 'STATUS_DIR'),
allowNonGvisor: env.SPAWNER_ALLOW_NON_GVISOR === '1',
maxSandboxes,
};
}
+103
View File
@@ -0,0 +1,103 @@
import { request } from 'node:http';
import type { Socket } from 'node:net';
export class DockerError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}
/**
* Minimal client for the few Docker Engine API calls the spawner needs.
* Works with Docker and with Podman's Docker compatible API.
*/
export class DockerClient
{
readonly socketPath: string;
constructor(socketPath: string) {
this.socketPath = socketPath;
}
call<T>(method: string, path: string, body?: unknown): Promise<T>
{
return new Promise((resolve, reject) =>
{
const payload = body === undefined ? undefined : JSON.stringify(body);
const req = request(
{
socketPath: this.socketPath,
method,
path,
headers: payload ? { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload) } : {},
},
(res) =>
{
const chunks: Buffer[] = [];
res.on('data', (chunk: Buffer) => chunks.push(chunk));
res.on('end', () =>
{
const text = Buffer.concat(chunks).toString('utf8');
const status = res.statusCode ?? 0;
if (status >= 400)
{
reject(new DockerError(status, errorMessage(text) ?? `docker responded with ${status}`));
return;
}
try { resolve((text ? JSON.parse(text) : undefined) as T); }
catch { resolve(undefined as T); }
});
res.on('error', reject);
},
);
req.on('error', reject);
req.end(payload);
});
}
/** Upgrades the connection to a raw stream, as used by attach. */
hijack(path: string): Promise<Socket>
{
return new Promise((resolve, reject) =>
{
const req = request({
socketPath: this.socketPath,
method: 'POST',
path,
headers: { Connection: 'Upgrade', Upgrade: 'tcp' },
});
req.on('upgrade', (_res, socket, head) =>
{
if (head.length > 0) socket.unshift(head);
resolve(socket);
});
req.on('response', (res) =>
{
res.resume();
reject(new DockerError(res.statusCode ?? 0, `attach failed with ${res.statusCode}`));
});
req.on('error', reject);
req.end();
});
}
}
function errorMessage(text: string): string | undefined
{
try
{
const parsed = JSON.parse(text) as { message?: unknown };
return typeof parsed.message === 'string' ? parsed.message : undefined;
}
catch { return text || undefined; }
}
+33
View File
@@ -0,0 +1,33 @@
import { chmodSync, rmSync } from 'node:fs';
import { loadConfig } from './config.ts';
import { SandboxManager } from './sandbox.ts';
import { createSpawnerServer } from './server.ts';
const log = (message: string) => console.log(`[spawner] ${message}`);
const config = loadConfig(process.env);
const manager = new SandboxManager(config);
await manager.assertRuntime();
const reaped = await manager.reapOrphans();
if (reaped > 0) log(`removed ${reaped} orphaned sandbox(es)`);
// The socket must never be reachable by anyone outside the shared group,
// not even for the moment between creating it and changing its mode.
process.umask(0o117);
rmSync(config.listenSocket, { force: true });
const server = createSpawnerServer(manager, log);
server.listen(config.listenSocket, () =>
{
chmodSync(config.listenSocket, 0o660);
log(`listening on ${config.listenSocket}`);
});
for (const signal of ['SIGTERM', 'SIGINT'] as const)
{
process.once(signal, () => {
server.close();
process.exit(0);
});
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, it } from 'vitest';
import type { SpawnerConfig } from './config.ts';
import { containerSpec } from './sandbox.ts';
const config: SpawnerConfig = {
dockerSocket: '/docker.sock',
listenSocket: '/spawner.sock',
image: 'registry/homepage-sandbox@sha256:abc',
contentDir: '/srv/content',
statusDir: '/srv/status',
maxSandboxes: 16,
allowNonGvisor: false,
};
describe('containerSpec', () => {
const spec = containerSpec(config, 'session123', 1_800_000_000, { cols: 100, rows: 30 });
const host = spec.HostConfig;
it('isolates the sandbox', () => {
expect(host.Privileged).toBe(false);
expect(host.ReadonlyRootfs).toBe(true);
expect(host.NetworkMode).toBe('none');
expect(spec.NetworkDisabled).toBe(true);
expect(host.CapDrop).toEqual(['ALL']);
expect(host.SecurityOpt).toContain('no-new-privileges');
expect(spec.User).toBe('agent');
});
it('limits resources', () => {
expect(host.Memory).toBe(80 * 1024 * 1024);
expect(host.MemorySwap).toBe(host.Memory);
expect(host.NanoCpus).toBe(500_000_000);
expect(host.PidsLimit).toBe(50);
expect(host.LogConfig.Type).toBe('none');
});
it('mounts host paths read only', () => {
expect(host.Binds).toEqual(['/srv/content:/home/agent:ro', '/srv/status:/var/status:ro']);
expect(Object.values(host.Tmpfs).every((options) => options.includes('noexec'))).toBe(true);
});
it('starts the terminal at the size of the browser', () => {
expect(host.ConsoleSize).toEqual([30, 100]);
});
it('passes only the session id and expiry into the container', () => {
expect(spec.Env).toEqual(['SESSION_ID=session123', 'SESSION_EXPIRES_AT=1800000000', 'TERM=xterm-256color']);
});
});
+179
View File
@@ -0,0 +1,179 @@
import type { Socket } from 'node:net';
import { SANDBOX_LABEL, SESSION_LABEL, type ManagedContainer, type TerminalSize } 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, size: TerminalSize)
{
return {
Image: config.image,
User: 'agent',
Hostname: 'security-command',
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 }],
// The content is the read only home directory, so /tmp is the only writable place.
Tmpfs: { '/tmp': 'size=8m,noexec,nosuid' },
Binds: [`${config.contentDir}:/home/agent:ro`, `${config.statusDir}:/var/status:ro`],
LogConfig: { Type: 'none', Config: {} },
ConsoleSize: [size.rows, size.cols],
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, size: TerminalSize): 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, size),
);
return created.Id;
}
/** Attaches before starting, so the first prompt is 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;
}
/**
* 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<void>
{
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<unknown>): Promise<void>
{
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;
}
}
}
+159
View File
@@ -0,0 +1,159 @@
import { mkdtempSync, rmSync } from 'node:fs';
import { createServer, type IncomingMessage, type Server as HttpServer } from 'node:http';
import type { Server, Socket } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SANDBOX_LABEL, SpawnerClient, SpawnerError } from '@homepage/protocol';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import type { SpawnerConfig } from './config.ts';
import { SandboxManager } from './sandbox.ts';
import { createSpawnerServer } from './server.ts';
const MANAGED = 'aaaaaaaaaaaa';
const FOREIGN = 'bbbbbbbbbbbb';
type Call = { method: string; path: string; body?: unknown };
/** Pretends to be the Docker Engine API. Attached streams echo input in upper case. */
function fakeDocker(socketPath: string, calls: Call[]): Promise<HttpServer> {
const containers = new Map<string, { labels: Record<string, string>; status: string }>([
[MANAGED, { labels: { [SANDBOX_LABEL]: '1' }, status: 'created' }],
[FOREIGN, { labels: {}, status: 'running' }],
]);
const server = createServer(async (req: IncomingMessage, res) => {
const chunks: Buffer[] = [];
for await (const chunk of req) chunks.push(chunk as Buffer);
const text = Buffer.concat(chunks).toString();
const url = new URL(req.url!, 'http://docker');
calls.push({ method: req.method!, path: url.pathname, body: text ? JSON.parse(text) : undefined });
const send = (status: number, body?: unknown) => {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(body === undefined ? '' : JSON.stringify(body));
};
const id = url.pathname.split('/')[2] ?? '';
const container = containers.get(id);
if (url.pathname === '/info') return send(200, { DefaultRuntime: 'runsc' });
if (url.pathname === '/containers/json') {
return send(
200,
[...containers].map(([Id, c]) => ({ Id, State: c.status, Labels: c.labels })),
);
}
if (url.pathname === '/containers/create') {
const created = String(containers.size).padStart(12, 'c');
containers.set(created, { labels: { [SANDBOX_LABEL]: '1' }, status: 'created' });
return send(201, { Id: created });
}
if (!container) return send(404, { message: 'no such container' });
if (url.pathname.endsWith('/json')) {
return send(200, { Id: id, State: { Status: container.status }, Config: { Labels: container.labels } });
}
if (url.pathname.endsWith('/start')) {
container.status = 'running';
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);
}
send(404, { message: 'unexpected call' });
});
server.on('upgrade', (req: IncomingMessage, socket: Socket) => {
calls.push({ method: req.method!, path: new URL(req.url!, 'http://docker').pathname });
socket.write('HTTP/1.1 101 UPGRADED\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n\r\n');
socket.on('data', (data) => socket.write(data.toString().toUpperCase()));
});
return new Promise((resolve) => server.listen(socketPath, () => resolve(server)));
}
function read(socket: Socket): Promise<string> {
return new Promise((resolve) => {
socket.once('data', (data) => resolve(data.toString()));
socket.resume();
});
}
describe('spawner server', () => {
let dir: string;
let docker: HttpServer;
let spawner: Server;
let client: SpawnerClient;
let calls: Call[];
let config: SpawnerConfig;
beforeEach(async () => {
dir = mkdtempSync(join(tmpdir(), 'spawner-test-'));
calls = [];
docker = await fakeDocker(join(dir, 'docker.sock'), calls);
config = {
dockerSocket: join(dir, 'docker.sock'),
listenSocket: join(dir, 'spawner.sock'),
image: 'sandbox@sha256:abc',
contentDir: '/srv/content',
statusDir: '/srv/status',
maxSandboxes: 2,
allowNonGvisor: false,
};
spawner = createSpawnerServer(new SandboxManager(config), () => {});
await new Promise<void>((resolve) => spawner.listen(config.listenSocket, resolve));
client = new SpawnerClient(config.listenSocket);
});
afterEach(() => {
spawner.close();
docker.close();
rmSync(dir, { recursive: true, force: true });
});
it('creates a sandbox with the hardcoded spec', async () => {
const containerId = await client.spawn('session123', Math.floor(Date.now() / 1000) + 600, { cols: 80, rows: 24 });
expect(containerId).toBe('ccccccccccc2');
const create = calls.find((call) => call.path === '/containers/create');
expect(create?.body).toMatchObject({ Image: 'sandbox@sha256:abc', HostConfig: { NetworkMode: 'none' } });
});
it('refuses to spawn beyond the sandbox limit', async () => {
const expiresAt = Math.floor(Date.now() / 1000) + 600;
await client.spawn('session123', expiresAt, { cols: 80, rows: 24 });
await expect(client.spawn('session456', expiresAt, { cols: 80, rows: 24 })).rejects.toThrow('sandbox limit reached');
});
it('attaches before starting and bridges the stream', async () => {
const stream = await client.attach(MANAGED);
const paths = calls.map((call) => call.path);
expect(paths.indexOf(`/containers/${MANAGED}/attach`)).toBeLessThan(paths.indexOf(`/containers/${MANAGED}/start`));
stream.write('hello');
expect(await read(stream)).toBe('HELLO');
stream.destroy();
});
it('refuses containers it does not manage', async () => {
await expect(client.attach(FOREIGN)).rejects.toThrow('not a sandbox container');
await expect(client.kill(FOREIGN)).rejects.toThrow('not a sandbox container');
expect(calls.some((call) => call.method === 'DELETE')).toBe(false);
});
it('kills managed containers and tolerates missing ones', async () => {
await client.kill(MANAGED);
await client.kill('dddddddddddd');
expect(calls.filter((call) => call.method === 'DELETE').map((call) => call.path)).toEqual([
`/containers/${MANAGED}`,
]);
});
it('lists only managed containers', async () => {
expect(await client.list()).toEqual([{ containerId: MANAGED, sessionId: '', running: false }]);
});
it('answers invalid requests with an error', async () => {
await expect(client.resize('../../info', 80, 24)).rejects.toThrow(SpawnerError);
});
});
+90
View File
@@ -0,0 +1,90 @@
import { createServer, type Server, type Socket } from 'node:net';
import {
InvalidRequestError,
MAX_REQUEST_BYTES,
parseRequest,
readLine,
type SpawnerResponse,
} from '@homepage/protocol';
import type { SandboxManager } from './sandbox.ts';
export type Logger = (message: string) => void;
function respond(connection: Socket, response: SpawnerResponse): void {
connection.write(`${JSON.stringify(response)}\n`);
}
function bridge(connection: Socket, upstream: Socket, rest: Buffer): void
{
const close = () => {
connection.destroy();
upstream.destroy();
};
connection.on('close', close);
upstream.on('close', close);
connection.on('error', close);
upstream.on('error', close);
if (rest.length > 0) upstream.write(rest);
connection.pipe(upstream);
upstream.pipe(connection);
}
async function handle(connection: Socket, manager: SandboxManager, log: Logger): Promise<void>
{
const { line, rest } = await readLine(connection, MAX_REQUEST_BYTES);
const request = parseRequest(line);
switch (request.op)
{
case 'spawn': {
const containerId = await manager.spawn(request.sessionId, request.expiresAt, { cols: request.cols, rows: request.rows });
log(`spawned ${containerId.slice(0, 12)} for session ${request.sessionId}`);
respond(connection, { ok: true, containerId });
break;
}
case 'attach': {
const upstream = await manager.attach(request.containerId);
respond(connection, { ok: true });
bridge(connection, upstream, rest);
return;
}
case 'resize':
await manager.resize(request.containerId, request.cols, request.rows);
respond(connection, { ok: true });
break;
case 'kill':
await manager.kill(request.containerId);
log(`killed ${request.containerId.slice(0, 12)}`);
respond(connection, { ok: true });
break;
case 'list':
respond(connection, { ok: true, containers: await manager.list() });
break;
}
connection.end();
}
export function createSpawnerServer(manager: SandboxManager, log: Logger): Server
{
return createServer((connection) =>
{
connection.on('error', () => connection.destroy());
handle(connection, manager, log).catch((error: unknown) =>
{
const message = error instanceof Error ? error.message : 'internal error';
if (!(error instanceof InvalidRequestError)) log(`request failed: ${message}`);
if (!connection.destroyed) {
respond(connection, { ok: false, error: message });
connection.end();
}
});
});
}
+45 -6
View File
@@ -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)
@@ -47,6 +47,13 @@ if [[ ! -d ${CONTENT_DIR:-} || ${CONTENT_DIR} != /* ]]; then
exit 1
fi
# Jobs run as the owner of the content directory, which must not be root.
jobs_user=$(stat -c %u:%g "$CONTENT_DIR")
if [[ ${jobs_user%%:*} == 0 ]]; then
echo "CONTENT_DIR is owned by root; give it to the user that maintains the content, jobs run as that user" >&2
exit 1
fi
registry_host=${REGISTRY%%/*}
if ! grep -qs "\"${registry_host}\"" ~/.docker/config.json; then
echo "log in to the registry first: docker login ${registry_host} (token with read:package)" >&2
@@ -73,15 +80,47 @@ 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}"
jobs_tag="${REGISTRY}/homepage-jobs:${commit}"
pull_image sandbox_docker "$sandbox_tag"
sandbox_image=$(sandbox_docker image inspect --format '{{index .RepoDigests 0}}' "$sandbox_tag")
pull_image docker "$spawner_tag"
pull_image docker "$backend_tag"
pull_image docker "$jobs_tag"
digest() { "$1" image inspect --format '{{index .RepoDigests 0}}' "$2"; }
# The spawner runs as 10001 and shares group 10100 with the backend, which
# runs as 10002 and writes the status file that sandboxes read. The jobs
# service writes the job file and the triggers the backend reads.
install -d -m 0755 runtime
install -d -o 10001 -g 10100 -m 0750 runtime/spawner
install -d -o 10002 -g 10002 -m 0755 runtime/status
install -d -o "${jobs_user%%:*}" -g "${jobs_user##*:}" -m 0755 config jobs runtime/jobs runtime/jobs/triggers
cat > runtime/deploy.env <<EOF
SANDBOX_IMAGE=${sandbox_image}
SANDBOX_IMAGE=$(digest sandbox_docker "$sandbox_tag")
SPAWNER_IMAGE=$(digest docker "$spawner_tag")
BACKEND_IMAGE=$(digest docker "$backend_tag")
JOBS_IMAGE=$(digest docker "$jobs_tag")
JOBS_USER=${jobs_user}
SANDBOX_GROUP_ID=$(getent group sandbox-spawner | cut -d: -f3)
STATUS_DIR=${PWD}/runtime/status
EOF
set -a
source runtime/deploy.env
set +a
IMAGE=$sandbox_image deploy/host/verify-sandbox.sh
IMAGE=$SANDBOX_IMAGE deploy/host/verify-sandbox.sh
compose() {
docker compose --project-directory "$PWD" -f deploy/compose.yml \
--env-file .env --env-file runtime/deploy.env "$@"
}
if ! compose up -d --remove-orphans --wait --wait-timeout 120; then
compose ps
echo "the services did not become healthy; check: docker logs security-command-backend-1" >&2
exit 1
fi
echo "deployed ${commit}"
echo "jobs: docker exec security-command-jobs-1 jobctl list"
+115
View File
@@ -0,0 +1,115 @@
name: security-command
services:
spawner:
image: ${SPAWNER_IMAGE:?run deploy.sh}
restart: unless-stopped
# 10100 is the group shared with the backend for the spawner socket.
user: "10001:10100"
group_add:
- "${SANDBOX_GROUP_ID:?run deploy.sh}"
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
network_mode: none
mem_limit: 128m
pids_limit: 64
environment:
SANDBOX_IMAGE: ${SANDBOX_IMAGE:?run deploy.sh}
CONTENT_DIR: ${CONTENT_DIR:?set CONTENT_DIR in .env}
STATUS_DIR: ${STATUS_DIR:?run deploy.sh}
volumes:
- /run/docker-sandbox/docker.sock:/run/docker-sandbox/docker.sock
- ./runtime/spawner:/run/spawner
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
backend:
image: ${BACKEND_IMAGE:?run deploy.sh}
restart: unless-stopped
user: "10002:10002"
group_add:
- "10100"
read_only: true
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
mem_limit: 256m
pids_limit: 128
depends_on: [spawner]
ports:
- "127.0.0.1:${BACKEND_PORT:-8380}:8080"
- "127.0.0.1:${METRICS_PORT:-9380}:9090"
environment:
SPAWNER_SOCKET: /run/spawner/spawner.sock
STATUS_DIR: /run/status
CONTENT_DIR: /content
JOBS_FILE: /config/jobs.toml
TRIGGER_DIR: /run/jobs/triggers
SITE_URL: ${SITE_URL:-https://security-command.org}
LEGAL_PAGES: ${LEGAL_PAGES-impressum/imprint:impressum.md,datenschutz/privacy:datenschutz.md}
ALLOWED_ORIGINS: ${ALLOWED_ORIGINS:-https://security-command.org}
MAX_SESSIONS: ${MAX_SESSIONS:-12}
MAX_QUEUE: ${MAX_QUEUE:-20}
POW_DIFFICULTY: ${POW_DIFFICULTY:-20}
volumes:
- ./runtime/spawner:/run/spawner
- ./runtime/status:/run/status
- ${CONTENT_DIR}:/content:ro
- ./config:/config:ro
- ./runtime/jobs/triggers:/run/jobs/triggers:ro
# Healthy means the backend serves and reaches the spawner.
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/healthz"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
start_interval: 2s
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
jobs:
image: ${JOBS_IMAGE:?run deploy.sh}
restart: unless-stopped
# Jobs run as the owner of the content directory, so they can write into it.
user: "${JOBS_USER:?run deploy.sh}"
init: true
read_only: true
tmpfs:
- /tmp:size=64m
cap_drop: [ALL]
security_opt: [no-new-privileges:true]
mem_limit: 256m
pids_limit: 128
environment:
JOBS_FILE: /config/jobs.toml
SCRIPTS_DIR: /jobs
CONTENT_DIR: /content
HOST_DIR: /host
TRIGGER_DIR: /run/jobs/triggers
CONTROL_SOCKET: /run/jobs/control.sock
volumes:
- ${CONTENT_DIR}:/content
- ./config:/config
- ./jobs:/jobs:ro
- ${JOBS_SRV_DIR:-/srv}:/host/srv:ro
- ${JOBS_NGINX_DIR:-/etc/nginx}:/host/nginx:ro
- ./runtime/jobs:/run/jobs
healthcheck:
test: ["CMD", "jobctl", "list"]
interval: 60s
timeout: 5s
retries: 3
start_period: 30s
start_interval: 2s
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
+32 -1
View File
@@ -1,5 +1,36 @@
# Absolute host path of the homepage content. It is mounted read only.
# Absolute host path of the homepage content. Sandboxes and the backend only
# read it; jobs may write into it.
CONTENT_DIR=
# Host directories job scripts see read only at /host/srv and /host/nginx,
# for example to describe the services running next to this one.
JOBS_SRV_DIR=/srv
JOBS_NGINX_DIR=/etc/nginx
# Public address of the site, used by the sitemap.
SITE_URL=https://security-command.org
# Legal pages as route/alias:file entries; the files live in the content
# directory. The German route is canonical, English aliases redirect to it.
# Entries can be left out, and an empty value means no legal pages at all.
LEGAL_PAGES=impressum/imprint:impressum.md,datenschutz/privacy:datenschutz.md
# Container registry of the SecurityCommand organization.
REGISTRY=git.security-command.org/securitycommand
# Local port nginx proxies to. It must match the port in deploy/nginx.
BACKEND_PORT=8380
# Comma separated origins allowed to open terminal sessions.
ALLOWED_ORIGINS=https://security-command.org
# Local port of the Prometheus metrics, published to loopback only.
METRICS_PORT=9380
# Session limits.
MAX_SESSIONS=12
MAX_QUEUE=20
# Leading zero bits of SHA-256 a new sandbox costs while the server is mostly
# idle. Each extra bit doubles the work; 20 takes about a second on a desktop.
POW_DIFFICULTY=20
+3 -4
View File
@@ -1,13 +1,12 @@
# Container flags for sandbox sessions, shared by the host and local tools.
# They mirror the configuration hardcoded in the spawner. Keep them in sync.
# They mirror the configuration hardcoded in the spawner and must stay identical.
# shellcheck disable=SC2034
SANDBOX_FLAGS=(
--read-only --network none --cap-drop ALL
--security-opt no-new-privileges --user guest
--security-opt no-new-privileges --user agent
--memory 80m --memory-swap 80m --cpus 0.5 --pids-limit 50
--ulimit nofile=256:256
--tmpfs /home/guest:size=8m,mode=1777,noexec,nosuid
--tmpfs /tmp:size=8m,noexec,nosuid
--log-driver none
--hostname sandbox
--hostname security-command
)
+3 -3
View File
@@ -41,14 +41,14 @@ if [[ $EXPECT_GVISOR == 1 ]]; then
fi
check "rootfs is read only" 'touch /x && echo writable' 'Read-only file system'
check "home is writable" 'echo ok > ~/probe && cat ~/probe' '^ok$'
check "home is noexec" 'cp /bin/true ~/t && ~/t && echo executed' 'Permission denied'
check "home is read only" 'touch ~/x && echo writable' 'Read-only file system'
check "tmp is writable" 'echo ok > /tmp/probe && cat /tmp/probe' '^ok$'
check "tmp is noexec" 'cp /bin/true /tmp/t && /tmp/t && echo executed' 'Permission denied'
check "no network interfaces besides lo" \
"tail -n +3 /proc/net/dev | awk '{print \$1}' | grep -v '^lo:' | wc -l" '^0$'
check "curl cannot reach anything" \
'curl -sS --max-time 3 http://1.1.1.1 >/dev/null && echo reachable' 'curl: \([0-9]+\)'
check "runs as guest" 'id' 'uid=1000\(guest\)'
check "runs as agent" 'id' 'uid=1000\(agent\)'
check "no effective capabilities" 'grep CapEff /proc/self/status' 'CapEff:\s+0+$'
check "no new privileges" 'grep NoNewPrivs /proc/self/status' 'NoNewPrivs:\s+1'
check "no setuid binaries" 'find / -xdev -perm /6000 -type f 2>/dev/null | wc -l' '^0$'
+63
View File
@@ -0,0 +1,63 @@
# Reference for config/jobs.toml. The jobs service creates that file on its
# first start with the system jobs, and adds system jobs it lacks on every
# start. Edits apply within a second, which restarts all schedules as if the
# services had just started.
#
# Each [[job]] needs exactly one of:
# builtin a job implemented in the backend: index, status, reap-orphans
# path a script in jobs/, run by the jobs service; it must be executable
#
# Options:
# id lowercase letters, digits and dashes; unique
# args list of arguments for the script
# every run at a fixed interval: "30s", "15m", "1h", "1d"; at least 1s
# cron run on a cron schedule in UTC: "0 4 * * *"
# on events: "start", "content-change" (builtin jobs only) and "watch"
# watch paths relative to HOST_DIR, like "srv/gitea/compose.yml" or
# "nginx/sites-enabled"; needs on = ["watch"]. A directory is
# watched with everything inside it. The job runs once things
# have been quiet for 2s.
# then jobs to trigger after a successful run, builtin ones included
# timeout run time after which the job is cancelled; default "5m"
# env table of extra environment variables
# enabled false switches the job off and logs a warning; default true
# parallel true lets runs overlap. By default a new trigger cancels the
# running run and starts the job over.
#
# Scripts run as the owner of the content directory with bash, coreutils, curl,
# git and jq available, and get these variables:
# JOB_ID the id of the job
# CONTENT_DIR the content directory, writable
# HOST_DIR /host, with /srv of the host in srv/ and its nginx config
# in nginx/, both read only
#
# Cancelling sends SIGTERM to the script and everything it started, then
# SIGKILL after 5s. Processes a script leaves behind are killed when it exits.
#
# Manage jobs with jobctl inside the jobs container:
# docker exec security-command-jobs-1 jobctl list
# docker exec security-command-jobs-1 jobctl run services
# docker exec security-command-jobs-1 jobctl cancel services
# Writes links/ and services/ from the nginx config and the directories in
# /srv. Copy deploy/jobs/services.sh to jobs/ for it. It runs when the nginx
# config changes and every hour for new services, and rebuilds the static
# site right away. EXCLUDE lists /srv directories to leave out.
[[job]]
id = "services"
path = "services.sh"
every = "1h"
on = ["start", "watch"]
watch = ["nginx"]
then = ["index"]
env = { EXCLUDE = "lost+found" }
# Mirrors a public repository into the content once a night.
[[job]]
id = "mirror"
path = "mirror.sh"
args = ["https://example.org/notes.git", "notes"]
cron = "0 4 * * *"
timeout = "10m"
env = { GIT_TERMINAL_PROMPT = "0" }
enabled = false
+127
View File
@@ -0,0 +1,127 @@
#!/usr/bin/env bash
# Describes the services of this host in the content. links/ gets one file per
# domain nginx serves, services/ one Markdown file per directory in /srv with
# its images and domains. A domain belongs to a service when nginx proxies it
# to a port the service's compose file publishes, or when the directory has
# the domain's name. Both directories belong to this script and are only
# replaced when their contents change.
#
# Uses CONTENT_DIR and HOST_DIR from the jobs service. EXCLUDE may list /srv
# directory names to leave out, separated by spaces.
set -euo pipefail
srv=$HOST_DIR/srv
nginx=$HOST_DIR/nginx
exclude=" ${EXCLUDE:-} "
# Prints "domain port" for every server_name of nginx, with the local port its
# server block proxies to, directly or through an upstream, or "-" without one.
nginx_sites() {
local files=() dir file
for dir in sites-enabled conf.d; do
for file in "$nginx/$dir"/*; do
[[ -f $file ]] && files+=("$file")
done
done
((${#files[@]})) || return 0
awk '
{
sub(/#.*/, "")
if (match($0, /upstream[ \t]+[A-Za-z0-9_.-]+/)) {
split(substr($0, RSTART, RLENGTH), words, /[ \t]+/)
upstream = words[2]; upstream_depth = depth
}
if (upstream != "" && match($0, /server[ \t]+[^;]*:[0-9]+/)) {
port = substr($0, RSTART, RLENGTH); sub(/.*:/, "", port); ports[upstream] = port
} else if (upstream == "" && $0 ~ /(^|[ \t;{])server[ \t]*\{/) {
blocks++; block_depth[blocks] = depth; current = blocks
}
if (current && match($0, /server_name[ \t]+[^;]+/)) {
value = substr($0, RSTART, RLENGTH); sub(/server_name[ \t]+/, "", value); names[current] = names[current] " " value
}
if (current && match($0, /proxy_pass[ \t]+[a-z]+:\/\/[^;\/]+/)) {
value = substr($0, RSTART, RLENGTH); sub(/.*:\/\//, "", value); targets[current] = value
}
depth += gsub(/\{/, "{") - gsub(/\}/, "}")
if (upstream != "" && depth <= upstream_depth) upstream = ""
if (current && depth <= block_depth[current]) current = 0
}
END {
for (block = 1; block <= blocks; block++) {
target = targets[block]; port = "-"
if (target ~ /:[0-9]+$/) { port = target; sub(/.*:/, "", port) }
else if (target in ports) port = ports[target]
count = split(names[block], list, /[ \t]+/)
for (i = 1; i <= count; i++) if (list[i] ~ /\./ && list[i] !~ /[*~]/) print list[i], port
}
}
' "${files[@]}"
}
compose_file() {
local name
for name in compose.yml compose.yaml docker-compose.yml docker-compose.yaml; do
[[ -f $1/$name ]] && { echo "$1/$name"; return; }
done
return 0
}
out=$(mktemp -d "$CONTENT_DIR/.services.XXXXXX")
trap 'rm -rf "$out"' EXIT
mkdir "$out/links" "$out/services"
# A domain served by a redirect block and a proxy block keeps the proxied port.
declare -A domain_port=()
while read -r domain port; do
[[ ${domain_port[$domain]:--} == - ]] && domain_port[$domain]=$port
done < <(nginx_sites | sort -u)
domains=()
((${#domain_port[@]})) && mapfile -t domains < <(printf '%s\n' "${!domain_port[@]}" | sort)
for domain in "${domains[@]}"; do
echo "https://$domain" > "$out/links/$domain"
done
services=0
for dir in "$srv"/*/; do
[[ -d $dir ]] || continue
name=$(basename "$dir")
[[ $name == .* || $exclude == *" $name "* ]] && continue
compose=$(compose_file "$dir")
images=() host_ports=()
if [[ -n $compose ]]; then
mapfile -t images < <(sed -nE 's/^[[:space:]]*image:[[:space:]]*["'\'']?([^"'\''[:space:]]+).*/\1/p' "$compose" | grep -v '\$' | sort -u)
mapfile -t host_ports < <(grep -oE '[0-9]{2,5}\}?:[0-9]{1,5}(/(tcp|udp))?["'\'']?[[:space:]]*$' "$compose" | sed -E 's/\}?:.*//' | sort -u)
fi
{
echo "# $name"
echo
found=0
for domain in "${domains[@]}"; do
match=0
[[ $domain == "$name" ]] && match=1
for port in "${host_ports[@]}"; do
[[ ${domain_port[$domain]} == "$port" ]] && match=1
done
((match)) && { echo "- url: https://$domain"; found=1; }
done
((found)) || echo "- url: none, internal only"
for image in "${images[@]}"; do echo "- image: $image"; done
} > "$out/services/$name.md"
services=$((services + 1))
done
changed=()
for part in links services; do
diff -rq "$out/$part" "$CONTENT_DIR/$part" >/dev/null 2>&1 && continue
rm -rf "$CONTENT_DIR/.$part.old"
[[ -e $CONTENT_DIR/$part ]] && mv "$CONTENT_DIR/$part" "$CONTENT_DIR/.$part.old"
mv "$out/$part" "$CONTENT_DIR/$part"
rm -rf "$CONTENT_DIR/.$part.old"
changed+=("$part")
done
echo "${#domain_port[@]} domain(s), $services service(s), updated: ${changed[*]:-nothing}"
+19
View File
@@ -0,0 +1,19 @@
# Location blocks for the security-command.org server block, which also holds
# the TLS settings. The upstream port matches BACKEND_PORT in .env.
location / {
proxy_pass http://127.0.0.1:8380;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
location = /ws {
proxy_pass http://127.0.0.1:8380;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 120s;
proxy_send_timeout 120s;
proxy_buffering off;
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "security-command.org",
"private": true,
"type": "module",
"packageManager": "pnpm@12.11.2",
"engines": {
"node": ">=24"
},
"scripts": {
"typecheck": "tsc -p . && tsc -p apps/frontend",
"test": "vitest run",
"build": "pnpm -r build"
},
"devDependencies": {
"@types/node": "^26.6.5",
"esbuild": "^0.28.2",
"typescript": "^7.0.2",
"vitest": "~5.0.3"
}
}
+9
View File
@@ -0,0 +1,9 @@
{
"name": "@homepage/indexer",
"private": true,
"type": "module",
"exports": "./src/index.ts",
"dependencies": {
"marked": "^18.1.0"
}
}
+3
View File
@@ -0,0 +1,3 @@
export * from './walk.ts';
export * from './render.ts';
export * from './site.ts';
+193
View File
@@ -0,0 +1,193 @@
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { beforeEach, describe, expect, it } from 'vitest';
import { renderMarkdown, renderText } from './render.ts';
import { buildSite, reservedNames, type Site } from './site.ts';
import { buildIndex, type WalkOptions } from './walk.ts';
const LEGAL = [{ route: 'impressum', aliases: ['imprint'], file: 'impressum.txt' }];
function options(overrides: Partial<WalkOptions> = {}): WalkOptions {
return { maxFileBytes: 1024, maxTotalBytes: 4096, maxEntries: 100, reserved: reservedNames(LEGAL), ...overrides };
}
function write(root: string, files: Record<string, string>): void
{
for (const [path, content] of Object.entries(files))
{
mkdirSync(join(root, path, '..'), { recursive: true });
writeFileSync(join(root, path), content);
}
}
const text = (site: Site, path: string) => site.pages.get(path)?.body.toString();
describe('buildIndex', () => {
let root: string;
let outside: string;
beforeEach(() =>
{
root = mkdtempSync(join(tmpdir(), 'content-'));
outside = mkdtempSync(join(tmpdir(), 'outside-'));
write(outside, { 'secret.txt': 'host secret' });
write(root, {
'about.txt': 'about me',
'subdomains/git.example.org/README': 'gitea',
'.env': 'TOKEN=1',
'.git/config': 'repo',
'subdomains/.hidden': 'hidden',
});
});
it('lists files and directories in order', async () => {
const index = await buildIndex(root, options());
expect([...index.entries.keys()]).toEqual(['', 'about.txt', 'subdomains', 'subdomains/git.example.org', 'subdomains/git.example.org/README']);
expect(index.entries.get('about.txt')?.content?.toString()).toBe('about me');
});
it('never follows symlinks, inside or outside the root', async () => {
symlinkSync(join(outside, 'secret.txt'), join(root, 'leak.txt'));
symlinkSync(outside, join(root, 'leakdir'));
symlinkSync(join(root, 'about.txt'), join(root, 'alias.txt'));
const index = await buildIndex(root, options());
expect([...index.entries.keys()].filter((path) => /leak|alias/.test(path))).toEqual([]);
});
it('skips dotfiles and dot directories everywhere', async () => {
const index = await buildIndex(root, options());
expect([...index.entries.keys()].some((path) => path.split('/').some((part) => part.startsWith('.')))).toBe(false);
});
it('skips top level names reserved for the site', async () => {
write(root, { 'raw/x': 'x', 'impressum': 'collides', 'sitemap.xml': 'x', 'deep/raw': 'fine' });
const index = await buildIndex(root, options());
expect(index.entries.has('raw')).toBe(false);
expect(index.entries.has('impressum')).toBe(false);
expect(index.entries.has('deep/raw')).toBe(true);
expect(index.warnings).toContain('"impressum" is skipped because the name is reserved for the site itself');
});
it('lists but does not load files above the limits', async () => {
write(root, { 'big.bin': 'x'.repeat(2000) });
const index = await buildIndex(root, options());
expect(index.entries.get('big.bin')?.content).toBeUndefined();
expect(index.warnings.join('\n')).toContain('big.bin is listed but not served');
});
it('changes its hash when content changes', async () => {
const before = (await buildIndex(root, options())).hash;
write(root, { 'about.txt': 'about someone else' });
expect((await buildIndex(root, options())).hash).not.toBe(before);
});
it('survives a missing content directory', async () => {
const index = await buildIndex(join(root, 'missing'), options());
expect([...index.entries.keys()]).toEqual(['']);
expect(index.warnings[0]).toContain('cannot be read');
});
});
describe('buildSite', () => {
let site: Site;
beforeEach(async () =>
{
const root = mkdtempSync(join(tmpdir(), 'site-'));
write(root, {
'about.md': '# About\n\n<script>alert(1)</script>\n\n[bad](javascript:alert(1)) [good](https://example.org)',
'page.html': '<script>alert(1)</script>',
'logo.svg': '<svg onload="alert(1)"></svg>',
'links/github.txt': 'https://github.com/example',
'spaced name.txt': 'x',
'impressum.txt': 'Max Mustermann',
});
site = buildSite(await buildIndex(root, options()), { siteUrl: 'https://security-command.org/', legal: LEGAL });
});
it('serves listings, file pages and the root listing at /ls', () => {
expect(text(site, '/ls')).toContain('<a href="/links">links/</a>');
expect(text(site, '/links')).toContain('<a href="/links/github.txt">github.txt</a>');
expect(text(site, '/links/github.txt')).toContain('<a href="https://github.com/example">');
expect(text(site, '/ls')).toContain('href="/spaced%20name.txt"');
expect(site.pages.has('/spaced name.txt')).toBe(true);
});
it('escapes raw HTML and neutralizes script links in markdown', () => {
const page = text(site, '/about.md')!;
expect(page).toContain('<h1>About</h1>');
expect(page).not.toContain('<script>');
expect(page).toContain('&lt;script&gt;');
expect(page).toContain('<a href="#">bad</a>');
expect(page).toContain('<a href="https://example.org">good</a>');
});
it('serves raw HTML and SVG as sandboxed plain text', () => {
for (const path of ['/raw/page.html', '/raw/logo.svg'])
{
const page = site.pages.get(path)!;
expect(page.type).toBe('text/plain; charset=utf-8');
expect(page.headers['Content-Security-Policy']).toContain('sandbox');
}
});
it('declares the given font files on every page', async () => {
const fonts = [{ url: '/assets/jetbrains-mono-latin-400-normal-x.woff2', weight: 400 }];
const styled = buildSite(await buildIndex(mkdtempSync(join(tmpdir(), 'site-')), options()), { siteUrl: 'https://a.example', legal: LEGAL, fonts });
expect(text(styled, '/ls')).toContain('font-weight: 400; font-display: swap; src: url("/assets/jetbrains-mono-latin-400-normal-x.woff2")');
});
it('renders legal pages from their content files', () => {
expect(text(site, '/impressum')).toContain('Max Mustermann');
});
it('redirects English aliases to the German legal pages and labels links for both', () => {
expect(site.pages.get('/imprint')).toMatchObject({ status: 301, headers: { Location: '/impressum' } });
expect(text(site, '/ls')).toContain('<a href="/impressum" data-en="imprint">impressum</a>');
expect(text(site, '/sitemap.xml')).not.toContain('/imprint');
});
it('renders markdown legal pages and leaves out pages that are not configured', async () => {
const root = mkdtempSync(join(tmpdir(), 'legal-'));
write(root, { 'datenschutz.md': '# Datenschutz\n\nKeine Cookies.', 'impressum.md': 'unused' });
const legal = [{ route: 'datenschutz', aliases: ['privacy'], file: 'datenschutz.md' }];
const only = buildSite(await buildIndex(root, options({ reserved: reservedNames(legal) })), { siteUrl: 'https://a.example', legal });
expect(text(only, '/datenschutz')).toContain('<h1>Datenschutz</h1>');
expect(only.pages.has('/impressum')).toBe(false);
expect(only.pages.has('/imprint')).toBe(false);
expect(text(only, '/ls')).not.toContain('href="/impressum"');
});
it('reserves the aliases in the content', () => {
expect(reservedNames(LEGAL).has('imprint')).toBe(true);
});
it('lists every page in the sitemap and points robots.txt at it', () => {
const sitemap = text(site, '/sitemap.xml')!;
expect(sitemap).toContain('<loc>https://security-command.org/</loc>');
expect(sitemap).toContain('<loc>https://security-command.org/ls</loc>');
expect(sitemap).toContain('<loc>https://security-command.org/spaced%20name.txt</loc>');
expect(sitemap).toContain('<loc>https://security-command.org/impressum</loc>');
expect(text(site, '/robots.txt')).toContain('Sitemap: https://security-command.org/sitemap.xml');
});
});
describe('render helpers', () => {
it('links only web addresses in plain text', () => {
expect(renderText('see https://a.example/x. and <b>')).toBe('see <a href="https://a.example/x">https://a.example/x</a>. and &lt;b&gt;');
});
it('keeps mail links in markdown', () => {
expect(renderMarkdown('[mail](mailto:a@b.c)')).toContain('href="mailto:a@b.c"');
});
});
+169
View File
@@ -0,0 +1,169 @@
import { Marked, type Tokens } from 'marked';
import type { Entry } from './walk.ts';
/** A link; english is the label for visitors whose browser does not prefer German. */
export type Link = { label: string; href: string; english?: string };
/** A woff2 file of JetBrains Mono from the frontend build, whose file names carry a hash. */
export type Font = { url: string; weight: number };
const SAFE_SCHEME = /^(https?|mailto):/i;
const ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
export function escapeHtml(text: string): string
{
return text
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
/** Encodes every segment of a content path for use in a URL. */
export function urlPath(path: string): string {
return path.split('/').map(encodeURIComponent).join('/');
}
function safeHref(href: string): string {
return ANY_SCHEME.test(href) && !SAFE_SCHEME.test(href) ? '#' : href;
}
/**
* Markdown with raw HTML shown as text and only web and mail links, because
* jobs may write content from outside sources into the directory.
*/
const markdown = new Marked({
gfm: true,
renderer: { html: ({ text }: Tokens.HTML | Tokens.Tag) => escapeHtml(text) },
walkTokens: (token) =>
{
if (token.type === 'link' || token.type === 'image') token.href = safeHref(token.href);
},
});
export function renderMarkdown(text: string): string {
return markdown.parse(text, { async: false });
}
/** Escapes text and turns plain web addresses into links, like the terminal does. */
export function renderText(text: string): string {
return escapeHtml(text).replace(/https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]]/g, (url) => `<a href="${url}">${url}</a>`);
}
function formatSize(bytes: number): string
{
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} K`;
return `${(bytes / 1024 / 1024).toFixed(1)} M`;
}
export function renderListing(entry: Entry, children: Entry[]): string
{
const rows = children.map((child) =>
{
const name = escapeHtml(child.name) + (child.kind === 'dir' ? '/' : '');
const size = child.kind === 'dir' ? '' : formatSize(child.size);
return `<tr><td><a href="/${urlPath(child.path)}">${name}</a></td><td class="size">${size}</td><td>${child.modified.toISOString().slice(0, 10)}</td></tr>`;
});
if (rows.length === 0) return '<p class="muted">This directory is empty.</p>';
return `<table><tbody>\n${rows.join('\n')}\n</tbody></table>`;
}
const IMAGE = /\.(png|jpe?g|gif|webp|avif)$/i;
export function renderFile(entry: Entry): string
{
const raw = `/raw/${urlPath(entry.path)}`;
if (!entry.content) return `<p class="muted">This file is too large to show. <a href="${raw}">Download it</a>.</p>`;
if (IMAGE.test(entry.name)) return `<p><img src="${raw}" alt="${escapeHtml(entry.name)}"></p>`;
if (!isText(entry.content)) return `<p class="muted">Binary file. <a href="${raw}">Download it</a>.</p>`;
const text = entry.content.toString('utf8');
if (/\.md$/i.test(entry.name)) return `<article class="markdown">${renderMarkdown(text)}</article>`;
return `<pre>${renderText(text)}</pre>`;
}
/** Treats content without NUL bytes that decodes as UTF-8 as text. The sample may end inside a character. */
export function isText(content: Buffer): boolean
{
const sample = content.subarray(0, 8192);
if (sample.includes(0)) return false;
try { new TextDecoder('utf-8', { fatal: true }).decode(sample, { stream: true }); }
catch { return false; }
return true;
}
const STYLE = `
* { box-sizing: border-box; }
body { margin: 0; background: var(--background); color: var(--text); font: 15px/1.6 "JetBrains Mono", ui-monospace, monospace; font-variant-ligatures: no-contextual; }
header, main, footer { max-width: 60rem; margin: 0 auto; padding: 0.75rem 1rem; }
header { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; justify-content: space-between; border-bottom: 1px solid var(--border); font-size: 0.85rem; user-select: none; }
header .site { color: var(--accent); }
nav a { margin-left: 0.75rem; }
a { color: var(--accent); }
.crumbs { color: var(--muted); }
.muted, .size { color: var(--muted); }
pre { white-space: pre-wrap; word-break: break-word; }
table { border-collapse: collapse; width: 100%; }
td { padding: 0.15rem 1.5rem 0.15rem 0; white-space: nowrap; }
td:first-child { width: 100%; white-space: normal; }
img { max-width: 100%; }
.markdown code, .markdown pre { background: var(--surface); }
`;
export type PageOptions = {
title: string;
description: string;
crumbs: Link[];
body: string;
nav: Link[];
fonts?: Font[];
};
function fontFaces(fonts: Font[]): string
{
return fonts
.map((font) => `@font-face { font-family: "JetBrains Mono"; font-weight: ${font.weight}; font-display: swap; src: url("${encodeURI(font.url)}") format("woff2"); }`)
.join('\n');
}
export function renderPage(options: PageOptions): string
{
const crumbs = options.crumbs.map((crumb) => `<a href="${crumb.href}">${escapeHtml(crumb.label)}</a>`).join(' / ');
const nav = options.nav.map((link) =>
{
const english = link.english ? ` data-en="${escapeHtml(link.english)}"` : '';
return `<a href="${link.href}"${english}>${escapeHtml(link.label)}</a>`;
}).join('');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="dark">
<title>${escapeHtml(options.title)}</title>
<meta name="description" content="${escapeHtml(options.description)}">
<meta property="og:title" content="${escapeHtml(options.title)}">
<meta property="og:description" content="${escapeHtml(options.description)}">
<link rel="icon" href="/favicon.ico" sizes="48x48">
<link rel="icon" href="/icon-192.png" sizes="192x192" type="image/png">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="stylesheet" href="/theme.css">
<script src="/labels.js" defer></script>
<style>${fontFaces(options.fonts ?? [])}${STYLE}</style>
</head>
<body>
<header><a class="site" href="/">security-command.org</a><nav>${nav}</nav></header>
<main>
<p class="crumbs">${crumbs}</p>
${options.body}
</main>
</body>
</html>
`;
}
+153
View File
@@ -0,0 +1,153 @@
import { escapeHtml, isText, renderFile, renderListing, renderPage, urlPath, type Font, type Link } from './render.ts';
import type { ContentIndex, Entry } from './walk.ts';
export type SitePage = {
body: Buffer;
type: string;
headers: Record<string, string>;
/** Set for redirects; pages without it are served with 200. */
status?: number;
};
/** A legal page under its German route, with English aliases that redirect to it. */
export type LegalPage = {
route: string;
aliases: string[];
file: string;
};
export type Site = {
pages: Map<string, SitePage>;
hash: string;
};
export type SiteOptions = {
/** Absolute URL of the site, used by the sitemap. */
siteUrl: string;
legal: LegalPage[];
fonts?: Font[];
};
const RESERVED = [
'ws', 'raw', 'ls', 'healthz', 'assets', 'index.html', 'sitemap.xml', 'robots.txt',
'theme.css', 'labels.js', 'favicon.ico', 'icon-192.png', 'apple-touch-icon.png',
];
/** Route names the content cannot use at its top level, including the legal pages and their aliases. */
export function reservedNames(legal: LegalPage[]): Set<string> {
return new Set([...RESERVED, ...legal.flatMap((page) => [page.route, ...page.aliases])]);
}
const RAW_TYPES: [RegExp, string][] = [
[/\.png$/i, 'image/png'],
[/\.jpe?g$/i, 'image/jpeg'],
[/\.gif$/i, 'image/gif'],
[/\.webp$/i, 'image/webp'],
[/\.avif$/i, 'image/avif'],
];
/**
* Raw files never run in the site's origin: text is served as plain text,
* also for HTML and SVG, and a sandbox policy disables scripts entirely.
*/
const RAW_HEADERS = { 'Content-Security-Policy': "sandbox; default-src 'none'; img-src 'self'" };
function rawPage(entry: Entry & { content: Buffer }): SitePage
{
const image = RAW_TYPES.find(([pattern]) => pattern.test(entry.name))?.[1];
if (image) return { body: entry.content, type: image, headers: RAW_HEADERS };
if (isText(entry.content)) return { body: entry.content, type: 'text/plain; charset=utf-8', headers: RAW_HEADERS };
return {
body: entry.content,
type: 'application/octet-stream',
headers: { ...RAW_HEADERS, 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(entry.name)}` },
};
}
function describe(entry: Entry): string
{
if (entry.kind === 'dir') return `Contents of /${entry.path || ''} on security-command.org.`;
if (!entry.content || !isText(entry.content)) return `${entry.name} on security-command.org.`;
const text = entry.content.toString('utf8').replace(/[#*_`>\[\]()]/g, '').replace(/\s+/g, ' ').trim();
return text.length > 160 ? `${text.slice(0, 157)}...` : text;
}
function crumbs(entry: Entry): Link[]
{
const parts = entry.path ? entry.path.split('/') : [];
return [
{ label: '~', href: '/ls' },
...parts.map((label, index) => ({ label, href: `/${urlPath(parts.slice(0, index + 1).join('/'))}` })),
];
}
/** Builds every static route from the index. Paths are decoded, with a leading slash and no trailing one. */
export function buildSite(index: ContentIndex, options: SiteOptions): Site
{
const pages = new Map<string, SitePage>();
const nav: Link[] = [
{ label: 'ls', href: '/ls' },
...options.legal.map((page) => ({ label: page.route, href: `/${page.route}`, english: page.aliases[0] })),
];
const html = (title: string, description: string, entryCrumbs: Link[], body: string): SitePage => ({
body: Buffer.from(renderPage({ title, description, crumbs: entryCrumbs, body, nav, fonts: options.fonts })),
type: 'text/html; charset=utf-8',
headers: {},
});
for (const entry of index.entries.values())
{
const title = `${entry.path ? `/${entry.path}` : '~'} · security-command.org`;
const route = entry.path ? `/${entry.path}` : '/ls';
if (entry.kind === 'dir')
{
const children = (entry.children ?? []).map((path) => index.entries.get(path)!);
pages.set(route, html(title, describe(entry), crumbs(entry), renderListing(entry, children)));
continue;
}
pages.set(route, html(title, describe(entry), crumbs(entry), renderFile(entry)));
if (entry.content) pages.set(`/raw/${entry.path}`, rawPage(entry as Entry & { content: Buffer }));
}
for (const { route, aliases, file } of options.legal)
{
const entry = index.entries.get(file);
const body = entry?.kind === 'file'
? renderFile(entry)
: `<p class="muted">${escapeHtml(file)} is missing from the content directory.</p>`;
pages.set(`/${route}`, html(`${route} · security-command.org`, `${route} of security-command.org.`, [], body));
for (const alias of aliases)
{
pages.set(`/${alias}`, { body: Buffer.alloc(0), type: 'text/plain; charset=utf-8', headers: { Location: `/${route}` }, status: 301 });
}
}
const base = options.siteUrl.replace(/\/$/, '');
const urls: [string, Date | undefined][] = [
['/', undefined],
...[...index.entries.values()].map((entry): [string, Date] => [entry.path ? `/${urlPath(entry.path)}` : '/ls', entry.modified]),
...options.legal.map(({ route, file }): [string, Date | undefined] => [`/${route}`, index.entries.get(file)?.modified]),
];
const sitemap = [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
...urls.map(([url, modified]) =>
`<url><loc>${escapeHtml(base + url)}</loc>${modified ? `<lastmod>${modified.toISOString().slice(0, 10)}</lastmod>` : ''}</url>`),
'</urlset>',
'',
].join('\n');
pages.set('/sitemap.xml', { body: Buffer.from(sitemap), type: 'application/xml; charset=utf-8', headers: {} });
const robots = ['User-agent: *', 'Disallow: /ws', 'Disallow: /raw/', `Sitemap: ${base}/sitemap.xml`, ''].join('\n');
pages.set('/robots.txt', { body: Buffer.from(robots), type: 'text/plain; charset=utf-8', headers: {} });
return { pages, hash: index.hash };
}
+111
View File
@@ -0,0 +1,111 @@
import { createHash } from 'node:crypto';
import { lstat, readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
export type Entry = {
/** Path relative to the content root with forward slashes; the root itself is "". */
path: string;
name: string;
kind: 'file' | 'dir';
size: number;
modified: Date;
/** Missing for directories and for files above the size limit. */
content?: Buffer;
children?: string[];
};
export type ContentIndex = {
entries: Map<string, Entry>;
hash: string;
warnings: string[];
};
export type WalkOptions = {
maxFileBytes: number;
maxTotalBytes: number;
maxEntries: number;
/** Top level names that would collide with the app's own routes. */
reserved: Set<string>;
signal?: AbortSignal;
};
/**
* Indexes the content directory. Symlinks are never followed, because the
* walk runs on the host side and a link could point anywhere; dotfiles are
* skipped so that things like .git or .env never become public.
*/
export async function buildIndex(root: string, options: WalkOptions): Promise<ContentIndex>
{
const entries = new Map<string, Entry>();
const warnings: string[] = [];
const hash = createHash('sha256');
let total = 0;
async function visit(path: string, absolute: string): Promise<Entry | undefined>
{
options.signal?.throwIfAborted();
const stats = await lstat(absolute);
const name = path.split('/').at(-1) ?? '';
if (stats.isSymbolicLink()) return undefined;
if (entries.size >= options.maxEntries)
{
warnings.push(`stopped at ${options.maxEntries} entries, ${path} and later ones are missing`);
return undefined;
}
if (stats.isDirectory())
{
const entry: Entry = { path, name, kind: 'dir', size: 0, modified: stats.mtime, children: [] };
entries.set(path, entry);
hash.update(`d\0${path}\0`);
const names = (await readdir(absolute)).filter((child) => !child.startsWith('.')).sort((a, b) => a.localeCompare(b, 'en'));
for (const child of names)
{
if (path === '' && options.reserved.has(child))
{
warnings.push(`"${child}" is skipped because the name is reserved for the site itself`);
continue;
}
const visited = await visit(path ? `${path}/${child}` : child, join(absolute, child));
if (visited) entry.children!.push(visited.path);
}
return entry;
}
if (!stats.isFile()) return undefined;
const entry: Entry = { path, name, kind: 'file', size: stats.size, modified: stats.mtime };
if (stats.size > options.maxFileBytes)
{
warnings.push(`${path} is listed but not served, it is larger than ${options.maxFileBytes} bytes`);
}
else if (total + stats.size > options.maxTotalBytes)
{
warnings.push(`${path} is listed but not served, the content exceeds ${options.maxTotalBytes} bytes in total`);
}
else
{
entry.content = await readFile(absolute);
total += entry.content.length;
}
entries.set(path, entry);
hash.update(`f\0${path}\0`);
hash.update(entry.content ?? `${stats.size}:${stats.mtimeMs}`);
return entry;
}
try { await visit('', root); }
catch (error)
{
if (options.signal?.aborted) throw error;
warnings.push(`the content directory cannot be read: ${(error as Error).message}`);
}
if (!entries.has('')) entries.set('', { path: '', name: '', kind: 'dir', size: 0, modified: new Date(0), children: [] });
return { entries, hash: hash.digest('hex').slice(0, 16), warnings };
}
+10
View File
@@ -0,0 +1,10 @@
{
"name": "@homepage/jobs",
"private": true,
"type": "module",
"exports": "./src/index.ts",
"dependencies": {
"croner": "^10.0.1",
"smol-toml": "^1.9.1"
}
}
+104
View File
@@ -0,0 +1,104 @@
import { describe, expect, it } from 'vitest';
import { loadJobs } from './definition.ts';
import { parseDuration } from './duration.ts';
const SYSTEM = ['index', 'status', 'reap-orphans'];
describe('parseDuration', () => {
it('understands the usual units', () => {
expect(parseDuration('500ms')).toBe(500);
expect(parseDuration('5s')).toBe(5000);
expect(parseDuration('15m')).toBe(900_000);
expect(parseDuration('1h')).toBe(3_600_000);
expect(parseDuration('2d')).toBe(172_800_000);
expect(() => parseDuration('soon')).toThrow();
});
});
describe('loadJobs', () => {
it('adds every system job to an empty file and reports them as missing', () => {
const loaded = loadJobs('');
expect(loaded.jobs.map((job) => job.id)).toEqual(SYSTEM);
expect(loaded.warnings).toEqual([]);
expect(loadJobs(loaded.missing).missing).toBe('');
});
it('reads script jobs with their defaults', () => {
const { jobs } = loadJobs(`
[[job]]
id = "services"
path = "jobs/services.sh"
args = ["--verbose"]
every = "15m"
on = ["start", "watch"]
watch = ["/host/srv"]
then = ["index"]
env = { MODE = "full" }
`);
expect(jobs[0]).toEqual({
id: 'services',
path: 'jobs/services.sh',
args: ['--verbose'],
every: 900_000,
on: ['start', 'watch'],
watch: ['/host/srv'],
then: ['index'],
timeout: 300_000,
env: { MODE: 'full' },
enabled: true,
parallel: false,
});
});
it('keeps disabled system jobs disabled and warns about them', () => {
const loaded = loadJobs(`
[[job]]
id = "status"
builtin = "status"
enabled = false
`);
expect(loaded.jobs.find((job) => job.id === 'status')?.enabled).toBe(false);
expect(loaded.warnings).toContain('job "status" is disabled');
expect(loaded.missing).not.toContain('id = "status"');
});
it.each([
['both kinds', 'id = "a"\nbuiltin = "x"\npath = "y"', 'exactly one of builtin or path'],
['a bad id', 'id = "Bad Id"\npath = "y"', 'id must be'],
['an unknown key', 'id = "a"\npath = "y"\nretries = 3', 'unknown keys retries'],
['content-change on a script', 'id = "a"\npath = "y"\non = ["content-change"]', 'reserved for builtin jobs'],
['watch without paths', 'id = "a"\npath = "y"\non = ["watch"]', 'belong together'],
['a broken cron', 'id = "a"\npath = "y"\ncron = "every day"', 'invalid cron'],
['a tiny interval', 'id = "a"\npath = "y"\nevery = "100ms"', 'at least 1s'],
])('skips a job with %s', (_name, body, message) => {
const loaded = loadJobs(`[[job]]\n${body}`);
expect(loaded.jobs.map((job) => job.id)).toEqual(SYSTEM);
expect(loaded.warnings.join('\n')).toContain(message);
});
it('warns about duplicates and unknown then targets', () => {
const loaded = loadJobs(`
[[job]]
id = "a"
path = "a.sh"
then = ["nowhere"]
[[job]]
id = "a"
path = "b.sh"
`);
expect(loaded.warnings).toEqual(['job "a" is skipped: duplicate id "a"', 'job "a" triggers unknown job "nowhere"']);
});
it('falls back to the system jobs when the file is not valid TOML', () => {
const loaded = loadJobs('[[job]\nid = ');
expect(loaded.jobs.map((job) => job.id)).toEqual(SYSTEM);
expect(loaded.warnings[0]).toContain('cannot be read');
});
});
+197
View File
@@ -0,0 +1,197 @@
import { Cron } from 'croner';
import { parse } from 'smol-toml';
import { parseDuration } from './duration.ts';
/** Events a job can react to. Only builtin jobs may react to content changes, which prevents loops. */
export type JobEvent = 'start' | 'content-change' | 'watch';
export type JobDefinition = {
id: string;
/** Name of a job implemented inside an app; mutually exclusive with path. */
builtin?: string;
/** Script run by the jobs service. */
path?: string;
args: string[];
every?: number;
cron?: string;
on: JobEvent[];
watch: string[];
/** Jobs to trigger after a successful run. */
then: string[];
timeout: number;
env: Record<string, string>;
enabled: boolean;
/** Whether runs may overlap. Otherwise a new trigger cancels the running run and starts over. */
parallel: boolean;
};
export type LoadedJobs = {
jobs: JobDefinition[];
/** False when the file is not valid TOML; then nothing should be appended to it. */
parsed: boolean;
/** System jobs the file does not mention yet, as TOML ready to be appended. */
missing: string;
warnings: string[];
};
export const JOB_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
const EVENTS = new Set<JobEvent>(['start', 'content-change', 'watch']);
const KEYS = new Set(['id', 'builtin', 'path', 'args', 'every', 'cron', 'on', 'watch', 'then', 'timeout', 'env', 'enabled', 'parallel']);
const DEFAULT_TIMEOUT = '5m';
/** Jobs every installation has. They are appended to the config file when missing, so they can be switched off there. */
export const SYSTEM_JOBS = `
# System job: rebuilds the static site, sitemap and robots.txt from the content.
[[job]]
id = "index"
builtin = "index"
on = ["start", "content-change"]
# System job: refreshes the status file that sandboxes show with "status".
[[job]]
id = "status"
builtin = "status"
every = "5s"
on = ["start"]
# System job: removes sandboxes left behind by a previous backend process.
[[job]]
id = "reap-orphans"
builtin = "reap-orphans"
on = ["start"]
`;
class InvalidJobError extends Error {}
function fail(message: string): never {
throw new InvalidJobError(message);
}
function strings(value: unknown, name: string): string[]
{
if (value === undefined) return [];
if (!Array.isArray(value) || !value.every((entry) => typeof entry === 'string')) fail(`${name} must be a list of strings`);
return value;
}
function validate(raw: Record<string, unknown>): JobDefinition
{
const unknown = Object.keys(raw).filter((key) => !KEYS.has(key));
if (unknown.length > 0) fail(`unknown keys ${unknown.join(', ')}`);
const { id, builtin, path, every, cron, timeout, env, enabled, parallel } = raw;
if (typeof id !== 'string' || !JOB_ID.test(id)) fail('id must be lowercase letters, digits and dashes');
if ((builtin === undefined) === (path === undefined)) fail('needs exactly one of builtin or path');
if (builtin !== undefined && typeof builtin !== 'string') fail('builtin must be a string');
if (path !== undefined && typeof path !== 'string') fail('path must be a string');
if (every !== undefined && typeof every !== 'string') fail('every must be a duration like "15m"');
if (cron !== undefined && typeof cron !== 'string') fail('cron must be a string');
if (timeout !== undefined && typeof timeout !== 'string') fail('timeout must be a duration like "5m"');
if (enabled !== undefined && typeof enabled !== 'boolean') fail('enabled must be true or false');
if (parallel !== undefined && typeof parallel !== 'boolean') fail('parallel must be true or false');
const on = strings(raw.on, 'on') as JobEvent[];
for (const event of on) if (!EVENTS.has(event)) fail(`unknown event "${event}"`);
if (on.includes('content-change') && path) fail('content-change is reserved for builtin jobs, so jobs cannot trigger themselves');
const watch = strings(raw.watch, 'watch');
if (watch.length > 0 !== on.includes('watch')) fail('watch paths and on = ["watch"] belong together');
if (env !== undefined && (typeof env !== 'object' || env === null || Array.isArray(env) || !Object.values(env).every((value) => typeof value === 'string')))
{
fail('env must be a table of strings');
}
if (cron !== undefined)
{
try { new Cron(cron, { paused: true }).stop(); }
catch { fail(`invalid cron expression "${cron}"`); }
}
const everyMs = every === undefined ? undefined : parseDuration(every);
if (everyMs !== undefined && everyMs < 1000) fail('every must be at least 1s');
return {
id,
...(builtin === undefined ? {} : { builtin }),
...(path === undefined ? {} : { path }),
args: strings(raw.args, 'args'),
...(everyMs === undefined ? {} : { every: everyMs }),
...(cron === undefined ? {} : { cron }),
on,
watch,
then: strings(raw.then, 'then'),
timeout: parseDuration(timeout ?? DEFAULT_TIMEOUT),
env: (env ?? {}) as Record<string, string>,
enabled: enabled ?? true,
parallel: parallel ?? false,
};
}
function entries(text: string): unknown[]
{
const document = parse(text);
const jobs = document.job ?? [];
if (!Array.isArray(jobs)) fail('jobs must be written as [[job]] sections');
return jobs;
}
/** Splits the system defaults into one TOML block per job, keyed by id. */
function systemBlocks(): Map<string, string>
{
const blocks = SYSTEM_JOBS.split(/\n(?=\n# )/).map((block) => block.trim()).filter(Boolean);
return new Map(blocks.map((block) => [/^id\s*=\s*"([^"]+)"/m.exec(block)![1]!, block]));
}
/**
* Reads the job file. Broken jobs are skipped with a warning instead of
* stopping everything, and system jobs missing from the file are added with
* their defaults.
*/
export function loadJobs(text: string): LoadedJobs
{
const warnings: string[] = [];
const jobs: JobDefinition[] = [];
let raw: unknown[] = [];
let parsed = true;
try { raw = entries(text); }
catch (error)
{
parsed = false;
warnings.push(`the job file cannot be read, only system jobs run: ${(error as Error).message}`);
}
for (const [index, entry] of raw.entries())
{
try
{
if (typeof entry !== 'object' || entry === null) fail('must be a table');
const job = validate(entry as Record<string, unknown>);
if (jobs.some((other) => other.id === job.id)) fail(`duplicate id "${job.id}"`);
if (!job.enabled) warnings.push(`job "${job.id}" is disabled`);
jobs.push(job);
}
catch (error)
{
const id = (entry as { id?: unknown })?.id;
warnings.push(`job ${typeof id === 'string' ? `"${id}"` : `#${index + 1}`} is skipped: ${(error as Error).message}`);
}
}
const missing: string[] = [];
for (const [id, block] of systemBlocks())
{
if (raw.some((entry) => (entry as { id?: unknown })?.id === id)) continue;
missing.push(block);
jobs.push(validate(entries(block)[0] as Record<string, unknown>));
}
for (const job of jobs)
{
for (const next of job.then) if (!jobs.some((other) => other.id === next)) warnings.push(`job "${job.id}" triggers unknown job "${next}"`);
}
return { jobs, parsed, missing: missing.length > 0 ? `\n${missing.join('\n\n')}\n` : '', warnings };
}
+9
View File
@@ -0,0 +1,9 @@
const UNITS: Record<string, number> = { ms: 1, s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
/** Parses durations like "500ms", "5s", "15m", "1h" or "2d" into milliseconds. */
export function parseDuration(text: string): number
{
const match = /^(\d+)(ms|s|m|h|d)$/.exec(text.trim());
if (!match) throw new Error(`invalid duration "${text}", expected something like 30s, 15m or 1h`);
return Number(match[1]) * UNITS[match[2]!]!;
}
+5
View File
@@ -0,0 +1,5 @@
export * from './duration.ts';
export * from './definition.ts';
export * from './scheduler.ts';
export * from './watch.ts';
export * from './triggers.ts';
+116
View File
@@ -0,0 +1,116 @@
import { describe, expect, it } from 'vitest';
import type { JobDefinition } from './definition.ts';
import { Scheduler, type Executor } from './scheduler.ts';
function job(id: string, overrides: Partial<JobDefinition> = {}): JobDefinition
{
return { id, builtin: id, args: [], on: [], watch: [], then: [], timeout: 60_000, env: {}, enabled: true, parallel: false, ...overrides };
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/** Records starts, ends and cancellations; each run takes the given time unless aborted. */
function recorder(durationMs = 50)
{
const events: string[] = [];
const executor: Executor = (definition, signal) => new Promise((resolve, reject) =>
{
events.push(`start ${definition.id}`);
const timer = setTimeout(() =>
{
events.push(`end ${definition.id}`);
resolve();
}, durationMs);
signal.addEventListener('abort', () =>
{
clearTimeout(timer);
events.push(`abort ${definition.id}`);
reject(signal.reason);
});
});
return { events, executor };
}
describe('Scheduler', () => {
it('runs start jobs and events, and skips disabled jobs', async () => {
const { events, executor } = recorder(1);
const scheduler = new Scheduler([
job('a', { on: ['start'] }),
job('b', { on: ['content-change'] }),
job('c', { on: ['start'], enabled: false }),
], executor, { log: () => {} });
scheduler.start();
scheduler.emit('content-change');
await sleep(20);
expect(events).toEqual(['start a', 'start b', 'end a', 'end b']);
expect(scheduler.trigger('c')).toBe(false);
scheduler.stop();
});
it('cancels a running run and starts over, collapsing triggers that arrive meanwhile', async () => {
const { events, executor } = recorder(50);
const scheduler = new Scheduler([job('a')], executor, { log: () => {} });
scheduler.trigger('a');
scheduler.trigger('a');
scheduler.trigger('a');
await sleep(100);
expect(events).toEqual(['start a', 'abort a', 'start a', 'end a']);
});
it('lets parallel jobs overlap', async () => {
const { events, executor } = recorder(30);
const scheduler = new Scheduler([job('a', { parallel: true })], executor, { log: () => {} });
scheduler.trigger('a');
scheduler.trigger('a');
await sleep(60);
expect(events).toEqual(['start a', 'start a', 'end a', 'end a']);
});
it('triggers then targets after success, locally or elsewhere', async () => {
const { events, executor } = recorder(1);
const elsewhere: string[] = [];
const scheduler = new Scheduler([job('a', { then: ['b', 'index'] }), job('b')], executor, {
log: () => {},
triggerOther: (id) => elsewhere.push(id),
});
scheduler.trigger('a');
await sleep(20);
expect(events).toEqual(['start a', 'end a', 'start b', 'end b']);
expect(elsewhere).toEqual(['index']);
});
it('times out and reports failures, but stays quiet about cancellations', async () => {
const { executor } = recorder(1000);
const logs: string[] = [];
const scheduler = new Scheduler([job('slow', { timeout: 20 }), job('cancelled')], executor, { log: (line) => logs.push(line) });
scheduler.trigger('slow');
scheduler.trigger('cancelled');
expect(scheduler.running()).toEqual(['slow', 'cancelled']);
expect(scheduler.cancel('cancelled')).toBe(true);
await sleep(50);
expect(logs).toEqual(['job "slow" failed: timed out after 20 ms']);
expect(scheduler.running()).toEqual([]);
});
it('runs jobs on their interval', async () => {
const { events, executor } = recorder(1);
const scheduler = new Scheduler([job('tick', { every: 1000 })], executor, { log: () => {} });
scheduler.start();
await sleep(1100);
scheduler.stop();
expect(events).toEqual(['start tick', 'end tick']);
});
});
+144
View File
@@ -0,0 +1,144 @@
import { Cron } from 'croner';
import type { JobDefinition, JobEvent } from './definition.ts';
export type Executor = (job: JobDefinition, signal: AbortSignal) => Promise<void>;
export type SchedulerOptions = {
log: (message: string) => void;
/** Receives "then" targets this scheduler does not run itself, for example builtin jobs of another app. */
triggerOther?: (id: string) => void;
};
export class JobTimeoutError extends Error {}
export class JobCancelledError extends Error {}
type Run = { controller: AbortController; done: Promise<void> };
/**
* Runs jobs on their schedules and events. Without parallel, a new trigger
* cancels a running run and starts over once it has stopped; triggers that
* arrive meanwhile collapse into that one restart.
*/
export class Scheduler
{
private readonly jobs: Map<string, JobDefinition>;
private readonly executor: Executor;
private readonly options: SchedulerOptions;
private readonly runs = new Map<string, Set<Run>>();
private readonly restarting = new Set<string>();
private readonly stoppers: (() => void)[] = [];
private stopped = false;
constructor(jobs: JobDefinition[], executor: Executor, options: SchedulerOptions)
{
this.jobs = new Map(jobs.map((job) => [job.id, job]));
this.executor = executor;
this.options = options;
}
start(): void
{
for (const job of this.jobs.values())
{
if (!job.enabled) continue;
if (job.every !== undefined)
{
const timer = setInterval(() => this.trigger(job.id), job.every);
this.stoppers.push(() => clearInterval(timer));
}
if (job.cron !== undefined)
{
const cron = new Cron(job.cron, () => { this.trigger(job.id); });
this.stoppers.push(() => cron.stop());
}
if (job.on.includes('start')) this.trigger(job.id);
}
}
/** Triggers every enabled job that listens to the event. */
emit(event: JobEvent): void {
for (const job of this.jobs.values()) if (job.on.includes(event)) this.trigger(job.id);
}
/** Starts a job. Returns false for unknown or disabled jobs. */
trigger(id: string): boolean
{
const job = this.jobs.get(id);
if (!job || !job.enabled || this.stopped) return false;
const runs = this.runs.get(id);
if (job.parallel || !runs || runs.size === 0)
{
this.launch(job);
return true;
}
if (this.restarting.has(id)) return true;
this.restarting.add(id);
for (const run of runs) run.controller.abort(new JobCancelledError('restarted by a new trigger'));
void Promise.allSettled([...runs].map((run) => run.done)).then(() =>
{
this.restarting.delete(id);
if (!this.stopped) this.launch(job);
});
return true;
}
/** Cancels all runs of a job. Returns whether anything was running. */
cancel(id: string): boolean
{
const runs = this.runs.get(id);
if (!runs || runs.size === 0) return false;
for (const run of runs) run.controller.abort(new JobCancelledError('cancelled'));
return true;
}
running(): string[] {
return [...this.runs].filter(([, runs]) => runs.size > 0).map(([id]) => id);
}
stop(): void
{
this.stopped = true;
for (const stop of this.stoppers) stop();
for (const id of this.runs.keys()) this.cancel(id);
}
private launch(job: JobDefinition): void
{
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(new JobTimeoutError(`timed out after ${job.timeout} ms`)), job.timeout);
const runs = this.runs.get(job.id) ?? new Set<Run>();
this.runs.set(job.id, runs);
const run: Run = { controller, done: Promise.resolve() };
run.done = this.executor(job, controller.signal)
.then(() =>
{
for (const next of job.then)
{
if (this.jobs.has(next)) this.trigger(next);
else if (this.options.triggerOther) this.options.triggerOther(next);
}
})
.catch((error: unknown) =>
{
const reason = controller.signal.aborted ? controller.signal.reason : error;
if (reason instanceof JobCancelledError) return;
this.options.log(`job "${job.id}" failed: ${reason instanceof Error ? reason.message : String(reason)}`);
})
.finally(() =>
{
clearTimeout(timer);
runs.delete(run);
});
runs.add(run);
}
}
+23
View File
@@ -0,0 +1,23 @@
import { mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { watchTriggers, writeTrigger } from './triggers.ts';
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
describe('triggers', () => {
it('delivers each write once and ignores invalid names', async () => {
const dir = mkdtempSync(join(tmpdir(), 'triggers-'));
const triggered: string[] = [];
const watcher = watchTriggers(dir, (id) => triggered.push(id), () => {});
await writeTrigger(dir, 'index');
await writeTrigger(dir, 'index');
await expect(writeTrigger(dir, '../escape')).rejects.toThrow('invalid job id');
await sleep(300);
watcher?.close();
expect(triggered).toEqual(['index']);
});
});
+46
View File
@@ -0,0 +1,46 @@
import { watch, type FSWatcher } from 'node:fs';
import { writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { JOB_ID } from './definition.ts';
import type { Log } from './watch.ts';
/**
* Builtin jobs run in the backend and script jobs in the jobs service. The
* jobs service triggers a builtin job by writing a file named after it into a
* directory the backend watches, so neither needs a socket to the other.
*/
const TRIGGER_QUIET_MS = 100;
export async function writeTrigger(directory: string, id: string): Promise<void>
{
if (!JOB_ID.test(id)) throw new Error(`invalid job id "${id}"`);
await writeFile(join(directory, id), `${Date.now()}\n`);
}
export function watchTriggers(directory: string, onTrigger: (id: string) => void, log: Log): FSWatcher | undefined
{
const pending = new Map<string, NodeJS.Timeout>();
try
{
const watcher = watch(directory, (_event, name) =>
{
if (!name || !JOB_ID.test(name)) return;
// One write raises several events, which count as one trigger.
clearTimeout(pending.get(name));
pending.set(name, setTimeout(() =>
{
pending.delete(name);
onTrigger(name);
}, TRIGGER_QUIET_MS));
});
watcher.on('error', (error) => log(`stopped watching ${directory} for triggers: ${error.message}`));
watcher.on('close', () => { for (const timer of pending.values()) clearTimeout(timer); });
return watcher;
}
catch (error)
{
log(`cannot watch ${directory} for triggers from the jobs service: ${(error as Error).message}`);
return undefined;
}
}
+63
View File
@@ -0,0 +1,63 @@
import { statSync, watch, type FSWatcher } from 'node:fs';
import { basename, dirname } from 'node:path';
export type Log = (message: string) => void;
/** Calls back once a directory tree has been quiet for the given time after a change. */
export function watchTree(directory: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
{
let timer: NodeJS.Timeout | undefined;
try
{
const watcher = watch(directory, { recursive: true }, () =>
{
clearTimeout(timer);
timer = setTimeout(onChange, quietMs);
});
watcher.on('error', (error) => log(`stopped watching ${directory}: ${error.message}`));
watcher.on('close', () => clearTimeout(timer));
return watcher;
}
catch (error)
{
log(`cannot watch ${directory}: ${(error as Error).message}`);
return undefined;
}
}
/**
* Watches a single file through its directory, because editors and atomic
* writes replace files, which would end a watch on the old one. This also
* notices a file that does not exist yet.
*/
export function watchFile(file: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
{
let timer: NodeJS.Timeout | undefined;
try
{
const watcher = watch(dirname(file), (_event, name) =>
{
if (name !== basename(file)) return;
clearTimeout(timer);
timer = setTimeout(onChange, quietMs);
});
watcher.on('error', (error) => log(`stopped watching ${file}: ${error.message}`));
watcher.on('close', () => clearTimeout(timer));
return watcher;
}
catch (error)
{
log(`cannot watch ${file}: ${(error as Error).message}`);
return undefined;
}
}
/** Watches a directory tree, or a file when the path is not a directory. */
export function watchPath(path: string, quietMs: number, onChange: () => void, log: Log): FSWatcher | undefined
{
let directory = false;
try { directory = statSync(path).isDirectory(); }
catch { /* A missing path is watched like a file, so its creation counts as a change. */ }
return directory ? watchTree(path, quietMs, onChange, log) : watchFile(path, quietMs, onChange, log);
}
+10
View File
@@ -0,0 +1,10 @@
{
"name": "@homepage/protocol",
"private": true,
"type": "module",
"exports": {
".": "./src/index.ts",
"./terminal": "./src/terminal.ts",
"./proof": "./src/proof.ts"
}
}
+80
View File
@@ -0,0 +1,80 @@
import { connect, type Socket } from 'node:net';
import { readLine } from './lines.ts';
import type { ManagedContainer, SpawnerRequest, SpawnerResponse } from './spawner.ts';
import type { TerminalSize } from './terminal.ts';
const MAX_RESPONSE_BYTES = 1024 * 1024;
export class SpawnerError extends Error {}
// noinspection ExceptionCaughtLocallyJS
export class SpawnerClient
{
readonly socketPath: string;
constructor(socketPath: string) { this.socketPath = socketPath; }
/** The terminal size is set before the shell starts, so its first output already fits. */
async spawn(sessionId: string, expiresAt: number, size: TerminalSize): Promise<string> {
const response = await this.request({ op: 'spawn', sessionId, expiresAt, ...size });
return response.containerId!;
}
/**
* Returns a raw duplex stream to the container's terminal. The container
* is started by the first attach, and the stream starts paused, so no early
* output gets lost before the caller pipes or resumes it.
*/
async attach(containerId: string): Promise<Socket> {
const { socket } = await this.open({ op: 'attach', containerId });
return socket;
}
async resize(containerId: string, cols: number, rows: number): Promise<void> {
await this.request({ op: 'resize', containerId, cols, rows });
}
async kill(containerId: string): Promise<void> {
await this.request({ op: 'kill', containerId });
}
async list(): Promise<ManagedContainer[]> {
const response = await this.request({ op: 'list' });
return response.containers ?? [];
}
private async request(request: SpawnerRequest): Promise<SpawnerResponse & { ok: true }> {
const { socket, response } = await this.open(request);
socket.destroy();
return response;
}
private open(request: SpawnerRequest): Promise<{ socket: Socket; response: SpawnerResponse & { ok: true } }>
{
return new Promise((resolve, reject) =>
{
const socket = connect(this.socketPath);
socket.once('error', reject);
socket.once('connect', async () =>
{
socket.off('error', reject);
try
{
socket.write(`${JSON.stringify(request)}\n`);
const { line, rest } = await readLine(socket, MAX_RESPONSE_BYTES, 30_000);
const response = JSON.parse(line) as SpawnerResponse;
if (!response.ok) throw new SpawnerError(response.error);
if (rest.length > 0) socket.unshift(rest);
resolve({ socket, response });
}
catch (error)
{
socket.destroy();
reject(error);
}
});
});
}
}
+5
View File
@@ -0,0 +1,5 @@
export * from './spawner.ts';
export * from './lines.ts';
export * from './client.ts';
export * from './terminal.ts';
export * from './proof.ts';
+54
View File
@@ -0,0 +1,54 @@
import type { Socket } from 'node:net';
export type Line = {
line: string;
/** Bytes received after the newline, which belong to the following stream. */
rest: Buffer;
};
export function readLine(socket: Socket, maxBytes: number, timeoutMs = 5000): Promise<Line> {
return new Promise((resolve, reject) =>
{
let buffered = Buffer.alloc(0);
const finish = (error: Error | null, result?: Line) =>
{
clearTimeout(timer);
socket.off('data', onData);
socket.off('end', onEnd);
socket.off('error', onError);
if (error) reject(error);
else resolve(result!);
};
const onData = (chunk: Buffer) =>
{
buffered = Buffer.concat([buffered, chunk]);
const newline = buffered.indexOf(0x0a);
if (newline === -1) {
if (buffered.length > maxBytes) finish(new Error('line too long'));
return;
}
if (newline > maxBytes) {
finish(new Error('line too long'));
return;
}
socket.pause();
finish(null, { line: buffered.subarray(0, newline).toString('utf8'), rest: buffered.subarray(newline + 1) });
};
const onEnd = () => finish(new Error('connection closed before a full line arrived'));
const onError = (error: Error) => finish(error);
const timer = setTimeout(() => finish(new Error('timed out waiting for a line')), timeoutMs);
socket.on('data', onData);
socket.once('end', onEnd);
socket.once('error', onError);
socket.resume();
});
}
+35
View File
@@ -0,0 +1,35 @@
import { createHash } from 'node:crypto';
import { describe, expect, it } from 'vitest';
import { sha256, solveProof, verifyProof } from './proof.ts';
const hex = (bytes: Uint8Array) => Buffer.from(bytes).toString('hex');
describe('sha256', () => {
it.each(['', 'abc', 'challenge:12345', 'x'.repeat(55), 'x'.repeat(56), 'y'.repeat(64), 'z'.repeat(200)])(
'matches node for a message of %#',
(message) => {
expect(hex(sha256(Buffer.from(message)))).toBe(createHash('sha256').update(message).digest('hex'));
},
);
});
describe('proof of work', () => {
it('finds a nonce the verifier accepts', () => {
const nonce = solveProof('AAAAAAAAAAAAAAAAAAAAAA', 12)!;
expect(verifyProof('AAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(true);
expect(verifyProof('BAAAAAAAAAAAAAAAAAAAAA', nonce, 12)).toBe(false);
});
it('agrees with node about the leading zero bits', () => {
const nonce = solveProof('challenge', 10)!;
const digest = createHash('sha256').update(`challenge:${nonce}`).digest();
expect(digest[0]).toBe(0);
expect(digest[1]! >> 6).toBe(0);
});
it('stops after the given number of attempts', () => {
expect(solveProof('challenge', 32, 0, 100)).toBeUndefined();
});
});
+128
View File
@@ -0,0 +1,128 @@
/**
* Proof of work for new sandboxes: find a nonce so that SHA-256 of
* "challenge:nonce" starts with a number of zero bits. Browser and backend
* share this file, so both compute exactly the same hash. Free of Node imports.
*/
const K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
const INITIAL = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
const rotate = (value: number, bits: number) => (value >>> bits) | (value << (32 - bits));
/** Processes one 64 byte block. The first 16 words of w hold the block; w has room for 64. */
function compress(state: Uint32Array, w: Uint32Array): void
{
for (let i = 16; i < 64; i++)
{
const s0 = rotate(w[i - 15]!, 7) ^ rotate(w[i - 15]!, 18) ^ (w[i - 15]! >>> 3);
const s1 = rotate(w[i - 2]!, 17) ^ rotate(w[i - 2]!, 19) ^ (w[i - 2]! >>> 10);
w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) | 0;
}
let [a, b, c, d, e, f, g, h] = state as unknown as number[];
for (let i = 0; i < 64; i++)
{
const t1 = (h! + (rotate(e!, 6) ^ rotate(e!, 11) ^ rotate(e!, 25)) + ((e! & f!) ^ (~e! & g!)) + K[i]! + w[i]!) | 0;
const t2 = ((rotate(a!, 2) ^ rotate(a!, 13) ^ rotate(a!, 22)) + ((a! & b!) ^ (a! & c!) ^ (b! & c!))) | 0;
h = g; g = f; f = e; e = (d! + t1) | 0;
d = c; c = b; b = a; a = (t1 + t2) | 0;
}
state[0] = (state[0]! + a!) | 0; state[1] = (state[1]! + b!) | 0;
state[2] = (state[2]! + c!) | 0; state[3] = (state[3]! + d!) | 0;
state[4] = (state[4]! + e!) | 0; state[5] = (state[5]! + f!) | 0;
state[6] = (state[6]! + g!) | 0; state[7] = (state[7]! + h!) | 0;
}
export function sha256(message: Uint8Array): Uint8Array
{
const blocks = Math.ceil((message.length + 9) / 64);
const padded = new Uint8Array(blocks * 64);
padded.set(message);
padded[message.length] = 0x80;
const view = new DataView(padded.buffer);
view.setUint32(padded.length - 8, Math.floor(message.length / 0x20000000));
view.setUint32(padded.length - 4, (message.length * 8) >>> 0);
const state = Uint32Array.from(INITIAL);
const w = new Uint32Array(64);
for (let block = 0; block < blocks; block++)
{
for (let i = 0; i < 16; i++) w[i] = view.getUint32(block * 64 + i * 4);
compress(state, w);
}
const digest = new Uint8Array(32);
const output = new DataView(digest.buffer);
state.forEach((word, i) => output.setUint32(i * 4, word));
return digest;
}
function leadingZeroBits(words: ArrayLike<number>): number
{
let bits = 0;
for (let i = 0; i < words.length; i++)
{
const zeros = Math.clz32(words[i]!);
bits += zeros;
if (zeros < 32) break;
}
return bits;
}
function encode(text: string): Uint8Array {
return Uint8Array.from(text, (character) => character.charCodeAt(0) & 0xff);
}
export function verifyProof(challenge: string, nonce: number, difficulty: number): boolean
{
const digest = sha256(encode(`${challenge}:${nonce}`));
const view = new DataView(digest.buffer);
const words = Array.from({ length: 8 }, (_, i) => view.getUint32(i * 4));
return leadingZeroBits(words) >= difficulty;
}
/**
* Searches nonces from start for at most count attempts. Challenge and nonce
* fit into one block, so the block is rebuilt in place without allocations.
*/
export function solveProof(challenge: string, difficulty: number, start = 0, count = Number.MAX_SAFE_INTEGER): number | undefined
{
const prefix = encode(`${challenge}:`);
if (prefix.length + 16 > 55) throw new Error('challenge too long for a single block');
const block = new Uint8Array(64);
const view = new DataView(block.buffer);
const state = new Uint32Array(8);
const w = new Uint32Array(64);
block.set(prefix);
for (let nonce = start; nonce < start + count; nonce++)
{
const digits = String(nonce);
const length = prefix.length + digits.length;
for (let i = 0; i < digits.length; i++) block[prefix.length + i] = digits.charCodeAt(i);
block[length] = 0x80;
block.fill(0, length + 1, 60);
view.setUint32(60, length * 8);
for (let i = 0; i < 16; i++) w[i] = view.getUint32(i * 4);
state.set(INITIAL);
compress(state, w);
if (leadingZeroBits(state) >= difficulty) return nonce;
}
return undefined;
}
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it } from 'vitest';
import { InvalidRequestError, MAX_SESSION_SECONDS, parseRequest } from './spawner.ts';
const now = 1_800_000_000;
const parse = (value: unknown) => parseRequest(JSON.stringify(value), now);
describe('parseRequest', () => {
it('accepts a valid spawn', () => {
expect(parse({ op: 'spawn', sessionId: 'abcdEFGH_-12', expiresAt: now + 1200, cols: 900, rows: 40 })).toEqual({
op: 'spawn',
sessionId: 'abcdEFGH_-12',
expiresAt: now + 1200,
cols: 500,
rows: 40,
});
});
it.each([
['short id', { op: 'spawn', sessionId: 'abc', expiresAt: now + 60 }],
['id with shell characters', { op: 'spawn', sessionId: 'abcdefgh;rm', expiresAt: now + 60 }],
['expiry in the past', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now }],
['expiry too far ahead', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + MAX_SESSION_SECONDS + 1 }],
['fractional expiry', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + 1.5 }],
['missing terminal size', { op: 'spawn', sessionId: 'abcdefgh', expiresAt: now + 60 }],
['uppercase container id', { op: 'kill', containerId: 'ABCDEF123456' }],
['container id with path', { op: 'attach', containerId: '../../info' }],
['unknown op', { op: 'exec', containerId: 'abcdef123456' }],
['array', [{ op: 'list' }]],
['null', null],
])('rejects %s', (_name, value) => {
expect(() => parse(value)).toThrow(InvalidRequestError);
});
it('rejects malformed json', () => {
expect(() => parseRequest('{"op":', now)).toThrow(InvalidRequestError);
});
it('ignores inherited properties', () => {
expect(() => parseRequest('{"__proto__":{"op":"list"}}', now)).toThrow(InvalidRequestError);
});
it('clamps the terminal size', () => {
expect(parse({ op: 'resize', containerId: 'abcdef123456', cols: 9999, rows: 0 })).toEqual({
op: 'resize',
containerId: 'abcdef123456',
cols: 500,
rows: 1,
});
});
it('rejects a non integer terminal size', () => {
expect(() => parse({ op: 'resize', containerId: 'abcdef123456', cols: '80', rows: 24 })).toThrow(
InvalidRequestError,
);
});
});
+106
View File
@@ -0,0 +1,106 @@
import { MAX_TERMINAL_SIZE, type TerminalSize } from './terminal.ts';
export const SANDBOX_LABEL = 'org.security-command.sandbox';
export const SESSION_LABEL = 'org.security-command.session';
export const MAX_REQUEST_BYTES = 4096;
export const MAX_SESSION_SECONDS = 6 * 60 * 60;
export type SpawnerRequest =
| ({ op: 'spawn'; sessionId: string; expiresAt: number } & TerminalSize)
| { op: 'attach'; containerId: string }
| { op: 'resize'; containerId: string; cols: number; rows: number }
| { op: 'kill'; containerId: string }
| { op: 'list' };
export type ManagedContainer = {
containerId: string;
sessionId: string;
running: boolean;
};
export type SpawnerResponse =
| { ok: true; containerId?: string; containers?: ManagedContainer[] }
| { ok: false; error: string };
const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
const CONTAINER_ID = /^[0-9a-f]{12,64}$/;
export class InvalidRequestError extends Error {}
function invalid(message: string): never {
throw new InvalidRequestError(message);
}
function field(input: Record<string, unknown>, name: string): unknown {
return Object.hasOwn(input, name) ? input[name] : undefined;
}
function sessionId(value: unknown): string {
return typeof value === 'string' && SESSION_ID.test(value) ? value : invalid('invalid session id');
}
function containerId(value: unknown): string {
return typeof value === 'string' && CONTAINER_ID.test(value) ? value : invalid('invalid container id');
}
function terminalSize(value: unknown): number {
if (typeof value !== 'number' || !Number.isInteger(value)) invalid('invalid terminal size');
return Math.min(Math.max(value, 1), MAX_TERMINAL_SIZE);
}
/**
* Parses one request line. Everything the backend sends is treated as
* untrusted, because the backend faces the internet and may be compromised.
*/
export function parseRequest(line: string, nowSeconds = Math.floor(Date.now() / 1000)): SpawnerRequest
{
let input: unknown;
try { input = JSON.parse(line); }
catch { invalid('malformed json'); }
if (typeof input !== 'object' || input === null || Array.isArray(input)) invalid('request must be an object');
const request = input as Record<string, unknown>;
switch (field(request, 'op'))
{
case 'spawn': {
const expiresAt = field(request, 'expiresAt');
if (
typeof expiresAt !== 'number' ||
!Number.isInteger(expiresAt) ||
expiresAt <= nowSeconds ||
expiresAt > nowSeconds + MAX_SESSION_SECONDS
) { invalid('invalid expiry'); }
return {
op: 'spawn',
sessionId: sessionId(field(request, 'sessionId')),
expiresAt,
cols: terminalSize(field(request, 'cols')),
rows: terminalSize(field(request, 'rows')),
};
}
case 'attach':
return { op: 'attach', containerId: containerId(field(request, 'containerId')) };
case 'resize':
return {
op: 'resize',
containerId: containerId(field(request, 'containerId')),
cols: terminalSize(field(request, 'cols')),
rows: terminalSize(field(request, 'rows')),
};
case 'kill':
return { op: 'kill', containerId: containerId(field(request, 'containerId')) };
case 'list':
return { op: 'list' };
default:
return invalid('unknown op');
}
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from 'vitest';
import { InvalidMessageError, parseClientMessage } from './terminal.ts';
const TOKEN = 'A'.repeat(21) + '_';
const parse = (value: unknown) => parseClientMessage(JSON.stringify(value));
describe('parseClientMessage', () => {
it('accepts hello, resize and resume', () => {
expect(parse({ type: 'hello', nonce: 7, cols: 80, rows: 24 })).toEqual({ type: 'hello', nonce: 7, cols: 80, rows: 24 });
expect(parse({ type: 'resize', cols: 0, rows: 9999 })).toEqual({ type: 'resize', cols: 1, rows: 500 });
expect(parse({ type: 'resume', token: TOKEN, cols: 80, rows: 24 })).toEqual({
type: 'resume',
token: TOKEN,
cols: 80,
rows: 24,
});
});
it.each([
['unknown type', { type: 'exec', cols: 80, rows: 24 }],
['missing size', { type: 'hello', nonce: 1 }],
['missing nonce', { type: 'hello', cols: 80, rows: 24 }],
['negative nonce', { type: 'hello', nonce: -1, cols: 80, rows: 24 }],
['fractional nonce', { type: 'hello', nonce: 1.5, cols: 80, rows: 24 }],
['short token', { type: 'resume', token: 'abc', cols: 80, rows: 24 }],
['token with symbols', { type: 'resume', token: 'A'.repeat(21) + '/', cols: 80, rows: 24 }],
['inherited type', JSON.parse('{"__proto__":{"type":"hello"},"nonce":1,"cols":80,"rows":24}')],
])('rejects %s', (_name, value) => {
expect(() => parse(value)).toThrow(InvalidMessageError);
});
it('rejects oversized messages', () => {
expect(() => parseClientMessage(' '.repeat(2000))).toThrow(InvalidMessageError);
});
});
+84
View File
@@ -0,0 +1,84 @@
/**
* Messages of the browser WebSocket. Terminal bytes always travel as binary
* frames in both directions; text frames carry these JSON control messages.
* This module must stay free of Node imports, because the frontend uses it.
*/
export const TERMINAL_PATH = '/ws';
export const MAX_CONTROL_BYTES = 1024;
export const MAX_TERMINAL_SIZE = 500;
/** Reconnect tokens are 16 random bytes in base64url. */
const TOKEN = /^[A-Za-z0-9_-]{22}$/;
export type TerminalSize = { cols: number; rows: number };
/** A new sandbox needs a nonce that solves the connection's challenge, see proof.ts. */
export type ClientMessage =
| ({ type: 'hello'; nonce: number } & TerminalSize)
| ({ type: 'resume'; token: string } & TerminalSize)
| ({ type: 'resize' } & TerminalSize);
/** Why the server ended a session. "gone" answers a resume whose session no longer exists. */
export type ExitReason = 'closed' | 'expired' | 'idle' | 'error' | 'gone';
/** Why the server did not start a session. */
export type RefusalReason = 'busy';
export type ServerMessage =
| { type: 'challenge'; challenge: string; difficulty: number }
| { type: 'queued'; position: number }
| { type: 'ready'; token: string; expiresAt: number; resumed: boolean }
| { type: 'idle'; secondsLeft: number }
| { type: 'exit'; reason: ExitReason }
| { type: 'refused'; reason: RefusalReason };
export class InvalidMessageError extends Error {}
function invalid(message: string): never
{
throw new InvalidMessageError(message);
}
function size(value: unknown): number
{
if (typeof value !== 'number' || !Number.isInteger(value)) invalid('invalid terminal size');
return Math.min(Math.max(value, 1), MAX_TERMINAL_SIZE);
}
export function parseClientMessage(text: string): ClientMessage
{
if (text.length > 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<string, unknown>;
const field = (name: string) => (Object.hasOwn(message, name) ? message[name] : undefined);
const type = field('type');
const terminal = { cols: size(field('cols')), rows: size(field('rows')) };
switch (type)
{
case 'hello': {
const nonce = field('nonce');
if (typeof nonce !== 'number' || !Number.isSafeInteger(nonce) || nonce < 0) invalid('invalid nonce');
return { type, nonce, ...terminal };
}
case 'resize':
return { type, ...terminal };
case 'resume': {
const token = field('token');
if (typeof token !== 'string' || !TOKEN.test(token)) invalid('invalid token');
return { type, token, ...terminal };
}
default:
return invalid('unknown message type');
}
}
+1429
View File
File diff suppressed because it is too large. Load diff
+5
View File
@@ -0,0 +1,5 @@
packages:
- apps/*
- packages/*
allowBuilds:
esbuild: true
+10 -5
View File
@@ -13,15 +13,20 @@ RUN rm -f /etc/dpkg/dpkg.cfg.d/docker \
figlet cowsay fortune-mod fortunes-min sl curl wget \
&& rm -rf /var/lib/apt/lists/*
# The content directory is mounted read only as the home directory, so all
# shell configuration lives in /etc.
# Setuid binaries are useless under no-new-privileges, so they are stripped
# to keep the attack surface minimal even if that option is ever dropped.
RUN useradd --uid 1000 --create-home --shell /bin/bash guest \
RUN useradd --uid 1000 --no-create-home --home-dir /home/agent --shell /bin/bash agent \
&& mkdir /home/agent \
&& find / -xdev -perm /6000 -type f -exec chmod a-s {} +
COPY etc/ /etc/
COPY --chmod=0755 bin/status /usr/local/bin/status
COPY --chmod=0755 bin/ /usr/local/bin/
ENV PATH=/usr/local/bin:/usr/bin:/bin:/usr/games
USER guest
WORKDIR /home/guest
CMD ["/bin/bash", "-l"]
USER agent
WORKDIR /home/agent
# Debian's bash always reads /etc/bash.bashrc. Startup files in the home
# directory belong to the content, so an empty file replaces ~/.bashrc.
CMD ["/bin/bash", "--rcfile", "/dev/null", "-i"]
+157
View File
@@ -0,0 +1,157 @@
#!/bin/bash
# Shows the emblem of security-command.org next to facts about this sandbox,
# in the style of fastfetch. A content file .local/bin/fastfetch replaces it.
# Foreground and background colors of the emblem's pixels.
declare -A fg=([r]=$'\e[38;2;119;31;47m' [g]=$'\e[38;2;92;85;85m')
declare -A bg=([r]=$'\e[48;2;119;31;47m' [g]=$'\e[48;2;92;85;85m')
accent=$'\e[1;31m'
reset=$'\e[0m'
# The emblem of the favicon: r is its red, g its grey, a space the background.
# Two pixel rows share one terminal row through half blocks.
logo=(
' rrrrrrrrrrrr '
' rrrrrrr rrrrrrr '
' rrrr rrrr '
' rrr rrr '
' rrr g g rrr '
' rrr g g rr '
' rr gg ggggggggggg rr '
' rrr gg gggggggggg gg rrr '
' rr gg gggggggg gg rr '
' rr gggg r gggggg r gggg rr '
' rr gggg rr gggg g r gggg rr '
' rr gg r gg r gg rr'
' rr g g rr rrr g g rr'
' rr rg g rrrr rr rrrr g gr rr'
' rr r rr rrrrrrrrrrrrrrrrrr rr r rr'
' rrr rrr g rrrrrrrrr rr g rrr rrr'
' r rrrrrr grrrrrrrrrrrrrrg rrrrrr r'
' r rr rrrrrrrrrrrrrrrrrrrr rr r'
' rr g gg rrrrr rrrr rrrrr gg g rr'
' rr gg gg rrrrrr rr rrrrrr gg gg rr'
' rr gg gg rrrrrr rrrrrr gg g rr'
' rr gg gg rrrrrrrrrrrr gg g rr'
' rr gggggg rrrrrrrrrr ggggg rr'
' rr gg gg r r gg gg rr '
' rr gggg ggg r r ggg ggg rr '
' rr ggg ggg rr '
' rrr g gg gg gg rrr '
' rr gg g gg g rr '
' rr gggg ggggg rr '
' rrr gg g rrr '
' rrr rrr '
' rrrr rrrr '
' rrrrrr rrrrrrr '
' rrrrrrrrrrrr '
)
# Sizes in the binary units fastfetch prints.
size() {
awk -v bytes="$1" 'BEGIN {
split("B KiB MiB GiB TiB", units)
for (unit = 1; bytes >= 1024 && unit < 5; unit++) bytes /= 1024
printf "%.2f %s", bytes, units[unit]
}'
}
usage() { printf '%s / %s (%d%%)' "$(size "$1")" "$(size "$2")" $(($2 > 0 ? $1 * 100 / $2 : 0)); }
plural() { (($1 == 1)) && echo "$1 $2" || echo "$1 ${2}s"; }
format_uptime() {
local seconds=${1%.*} parts=()
((seconds < 60)) && { plural "$seconds" sec; return; }
((seconds >= 86400)) && parts+=("$(plural $((seconds / 86400)) day)")
((seconds / 3600 % 24)) && parts+=("$(plural $((seconds / 3600 % 24)) hour)")
((seconds / 60 % 60)) && parts+=("$(plural $((seconds / 60 % 60)) min)")
local IFS=,
local joined="${parts[*]}"
echo "${joined//,/, }"
}
. /etc/os-release
read -r up _ < /proc/uptime
mem_total=$(awk '/^MemTotal:/ { print $2 * 1024 }' /proc/meminfo)
mem_free=$(awk '/^MemAvailable:/ { print $2 * 1024 }' /proc/meminfo)
if [[ -r /sys/fs/cgroup/memory.max && $(< /sys/fs/cgroup/memory.max) != max ]]; then
mem_total=$(< /sys/fs/cgroup/memory.max)
mem_used=$(< /sys/fs/cgroup/memory.current)
else
mem_used=$((mem_total - mem_free))
fi
# The cgroup limit wins over /proc/meminfo, which may describe the host.
swap=$(awk '/^SwapTotal:/ { print $2 * 1024 }' /proc/meminfo)
[[ -r /sys/fs/cgroup/memory.swap.max && $(< /sys/fs/cgroup/memory.swap.max) != max ]] && swap=$(< /sys/fs/cgroup/memory.swap.max)
read -r disk_size disk_used disk_type < <(df -B1 --output=size,used,fstype / | tail -n 1)
[[ $(awk '$2 == "/" { print $4 }' /proc/mounts | tail -n 1) == ro* ]] && disk_type+=' [Read-only]'
cpu=$(awk -F ': ' '/^model name/ { print $2; exit }' /proc/cpuinfo)
host=container
dmesg 2>/dev/null | grep -q gVisor && host=gVisor
facts=(
"OS|$PRETTY_NAME $(uname -m)"
"Host|$host"
"Kernel|$(uname -sr)"
"Uptime|$(format_uptime "$up")"
"Packages|$(dpkg-query -f '.\n' -W | wc -l) (dpkg)"
"Shell|bash ${BASH_VERSION%%[(-]*}"
"Terminal|xterm.js"
"CPU|${cpu:-unknown} ($(nproc))"
"Memory|$(usage "$mem_used" "$mem_total")"
"Swap|$( ((swap > 0)) && size "$swap" || echo Disabled)"
"Disk (/)|$(usage "$disk_used" "$disk_size") - $disk_type"
"Locale|${LANG:-C}"
)
emblem=()
for ((y = 0; y < ${#logo[@]}; y += 2)); do
top=${logo[y]} bottom=${logo[y + 1]} line=''
for ((x = 0; x < ${#top}; x++)); do
t=${top:x:1} b=${bottom:x:1}
if [[ $t == ' ' && $b == ' ' ]]; then line+="$reset "
elif [[ $t == "$b" ]]; then line+=$'\e[49m'"${fg[$t]}█"
elif [[ $b == ' ' ]]; then line+=$'\e[49m'"${fg[$t]}▀"
elif [[ $t == ' ' ]]; then line+=$'\e[49m'"${fg[$b]}▄"
else line+="${fg[$t]}${bg[$b]}▀"
fi
done
emblem+=("$line$reset")
done
user=${USER:-$(id -un)}
title="$accent$user$reset@$accent$HOSTNAME$reset"
title_width=$((${#user} + 1 + ${#HOSTNAME}))
dashes=$(printf '%*s' "$title_width" '')
info=("$title" "${dashes// /-}")
info_width=$title_width
for fact in "${facts[@]}"; do
key=${fact%%|*} value=${fact#*|}
info+=("$accent$key$reset: $value")
((${#key} + 2 + ${#value} > info_width)) && info_width=$((${#key} + 2 + ${#value}))
done
blocks() { for color in "$@"; do printf '\e[%sm ' "$color"; done; printf '%s' "$reset"; }
info+=('' "$(blocks 40 41 42 43 44 45 46 47)" "$(blocks 100 101 102 103 104 105 106 107)")
cols=$(tput cols 2>/dev/null || echo 80)
width=${#logo[0]}
gap=3
echo
if ((cols < width)); then
printf '%s\n' "${info[@]}"
elif ((cols < width + gap + info_width)); then
printf '%s\n' "${emblem[@]}" '' "${info[@]}"
else
offset=$(((${#emblem[@]} - ${#info[@]}) / 2))
((offset < 0)) && offset=0
rows=$((${#emblem[@]} > offset + ${#info[@]} ? ${#emblem[@]} : offset + ${#info[@]}))
for ((row = 0; row < rows; row++)); do
left=${emblem[row]:-$(printf '%*s' "$width" '')}
right=''
((row >= offset)) && right=${info[row - offset]}
printf '%s%*s%s\n' "$left" "$gap" '' "$right"
done
fi
echo
+16 -1
View File
@@ -4,8 +4,23 @@ shopt -s checkwinsize histappend
HISTSIZE=1000
HISTCONTROL=ignoredups
PS1='\[\e[1;32m\]guest@security-command\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '
# The home directory is the read only content, so state goes to /tmp.
HISTFILE=/tmp/.bash_history
export LESSHISTFILE=-
export XDG_CONFIG_HOME=/tmp/.config
export XDG_CACHE_HOME=/tmp/.cache
export XDG_DATA_HOME=/tmp/.local/share
export XDG_STATE_HOME=/tmp/.local/state
mkdir -p "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME" "$XDG_DATA_HOME" "$XDG_STATE_HOME"
PS1='\[\e[1;31m\]\u@\h\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '
alias ls='ls --color=auto'
alias ll='ls -lah --color=auto'
alias grep='grep --color=auto'
# The content may carry small scripts, which take precedence over the built in ones.
PATH="$HOME/.local/bin:$PATH"
# Only the first shell of a session greets the visitor.
[[ $SHLVL == 1 ]] && fastfetch
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more