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>
This commit is contained in:
1 parent
0ad5b5f44f
commit
7937879ace
34 files changed
+613
-116
No files matched your search
@@ -1,3 +1,187 @@
|
|||||||
# security-command.org
|
# 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_HOST_DIR` | `/srv`, mounted read only into the jobs service |
|
||||||
|
| `SITE_URL` | `https://security-command.org` |
|
||||||
|
| `LEGAL_PAGES` | `impressum:impressum.txt,datenschutz:datenschutz.txt` |
|
||||||
|
| `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.
|
||||||
|
|
||||||
|
- `motd` is shown on the boot screen and at login.
|
||||||
|
- The legal pages from `LEGAL_PAGES` are rendered at `/impressum` and
|
||||||
|
`/datenschutz` and linked 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) 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.
|
||||||
|
|
||||||
|
## 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. The workflow needs the secrets `REGISTRY_USER` and
|
||||||
|
`REGISTRY_TOKEN`.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
See [LICENSE](LICENSE).
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { mkdtempSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { readTheme } 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();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
||||||
|
import { readFile } from 'node:fs/promises';
|
||||||
import { extname, join, relative, sep } from 'node:path';
|
import { extname, join, relative, sep } from 'node:path';
|
||||||
|
import type { Font } from '@homepage/indexer';
|
||||||
|
|
||||||
export type Asset = {
|
export type Asset = {
|
||||||
body: Buffer;
|
body: Buffer;
|
||||||
@@ -50,3 +52,24 @@ export function loadAssets(directory: string): Map<string, Asset>
|
|||||||
if (index) assets.set('/', index);
|
if (index) assets.set('/', index);
|
||||||
return assets;
|
return assets;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { buildIndex, buildSite, reservedNames, type Site } from '@homepage/indexer';
|
import { buildIndex, buildSite, reservedNames, type Font, type Site } from '@homepage/indexer';
|
||||||
import type { BackendConfig } from './config.ts';
|
import type { BackendConfig } from './config.ts';
|
||||||
import type { SessionHub } from './hub.ts';
|
import type { SessionHub } from './hub.ts';
|
||||||
import type { Builtin } from './jobs.ts';
|
import type { Builtin } from './jobs.ts';
|
||||||
@@ -11,6 +11,7 @@ export type BuiltinDependencies = {
|
|||||||
spawner: Pick<Spawner, 'kill'> & { list(): Promise<{ containerId: string; sessionId: string }[]> };
|
spawner: Pick<Spawner, 'kill'> & { list(): Promise<{ containerId: string; sessionId: string }[]> };
|
||||||
started: number;
|
started: number;
|
||||||
setSite: (site: Site) => void;
|
setSite: (site: Site) => void;
|
||||||
|
fonts?: Font[];
|
||||||
log: (message: string) => void;
|
log: (message: string) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -34,7 +35,7 @@ export function createBuiltins(dependencies: BuiltinDependencies): Record<string
|
|||||||
if (index.hash === lastHash) return;
|
if (index.hash === lastHash) return;
|
||||||
lastHash = index.hash;
|
lastHash = index.hash;
|
||||||
|
|
||||||
dependencies.setSite(buildSite(index, { siteUrl: config.siteUrl, legal: config.legalPages }));
|
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.
|
// The same warnings come back on every rebuild, so they are only logged when they change.
|
||||||
const warnings = index.warnings.join('\n');
|
const warnings = index.warnings.join('\n');
|
||||||
|
|||||||
@@ -9,6 +9,8 @@ export type BackendConfig = {
|
|||||||
jobsFile: string;
|
jobsFile: string;
|
||||||
/** Directory the jobs service writes triggers for builtin jobs into; empty disables them. */
|
/** Directory the jobs service writes triggers for builtin jobs into; empty disables them. */
|
||||||
triggerDir: string;
|
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. */
|
/** Absolute URL of the site, for the sitemap. */
|
||||||
siteUrl: string;
|
siteUrl: string;
|
||||||
/** Route name to content file, from LEGAL_PAGES like "impressum:impressum.txt". */
|
/** Route name to content file, from LEGAL_PAGES like "impressum:impressum.txt". */
|
||||||
@@ -62,6 +64,7 @@ export function loadConfig(env: NodeJS.ProcessEnv): BackendConfig
|
|||||||
contentDir: env.CONTENT_DIR ?? '/content',
|
contentDir: env.CONTENT_DIR ?? '/content',
|
||||||
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
|
jobsFile: env.JOBS_FILE ?? '/config/jobs.toml',
|
||||||
triggerDir: env.TRIGGER_DIR ?? '',
|
triggerDir: env.TRIGGER_DIR ?? '',
|
||||||
|
themeFile: env.THEME_FILE ?? '/config/theme.css',
|
||||||
siteUrl: env.SITE_URL ?? 'https://security-command.org',
|
siteUrl: env.SITE_URL ?? 'https://security-command.org',
|
||||||
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum:impressum.txt,datenschutz:datenschutz.txt'),
|
legalPages: legalPages(env.LEGAL_PAGES ?? 'impressum:impressum.txt,datenschutz:datenschutz.txt'),
|
||||||
statusDir: env.STATUS_DIR ?? '',
|
statusDir: env.STATUS_DIR ?? '',
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { Site } from '@homepage/indexer';
|
import type { Site } from '@homepage/indexer';
|
||||||
import { watchTree, watchTriggers } from '@homepage/jobs';
|
import { watchTree, watchTriggers } from '@homepage/jobs';
|
||||||
import { SpawnerClient } from '@homepage/protocol';
|
import { SpawnerClient } from '@homepage/protocol';
|
||||||
import { loadAssets } from './assets.ts';
|
import { loadAssets, readTheme, siteFonts } from './assets.ts';
|
||||||
import { createBuiltins } from './builtins.ts';
|
import { createBuiltins } from './builtins.ts';
|
||||||
import { loadConfig } from './config.ts';
|
import { loadConfig } from './config.ts';
|
||||||
import { SessionHub } from './hub.ts';
|
import { SessionHub } from './hub.ts';
|
||||||
@@ -31,6 +31,7 @@ jobs = new BackendJobs(config.jobsFile, createBuiltins({
|
|||||||
spawner,
|
spawner,
|
||||||
started: Date.now(),
|
started: Date.now(),
|
||||||
setSite: (next) => { site = next; },
|
setSite: (next) => { site = next; },
|
||||||
|
fonts: siteFonts(assets),
|
||||||
log,
|
log,
|
||||||
}), log);
|
}), log);
|
||||||
await jobs.start();
|
await jobs.start();
|
||||||
@@ -57,7 +58,8 @@ async function healthy(): Promise<boolean>
|
|||||||
return ok;
|
return ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
const server = createBackend(config, hub, { assets, healthy, site: () => site });
|
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}`));
|
server.listen(config.port, config.host, () => log(`listening on ${config.host}:${config.port}`));
|
||||||
|
|
||||||
if (config.metricsPort > 0) createMetricsServer(hub).listen(config.metricsPort, config.host);
|
if (config.metricsPort > 0) createMetricsServer(hub).listen(config.metricsPort, config.host);
|
||||||
|
|||||||
@@ -91,6 +91,7 @@ describe('backend', () => {
|
|||||||
contentDir: '',
|
contentDir: '',
|
||||||
jobsFile: '',
|
jobsFile: '',
|
||||||
triggerDir: '',
|
triggerDir: '',
|
||||||
|
themeFile: '',
|
||||||
siteUrl: 'https://security-command.org',
|
siteUrl: 'https://security-command.org',
|
||||||
legalPages: new Map(),
|
legalPages: new Map(),
|
||||||
statusDir: '',
|
statusDir: '',
|
||||||
@@ -109,7 +110,7 @@ describe('backend', () => {
|
|||||||
|
|
||||||
spawner = new FakeSpawner();
|
spawner = new FakeSpawner();
|
||||||
hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 10_000, log: () => {} });
|
hub = new SessionHub(spawner, { ...config, helloTimeoutMs: 10_000, log: () => {} });
|
||||||
server = createBackend(config, hub, { assets: ASSETS, site: () => SITE });
|
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));
|
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`;
|
url = `ws://127.0.0.1:${(server.address() as AddressInfo).port}/ws`;
|
||||||
}
|
}
|
||||||
@@ -421,6 +422,13 @@ describe('backend', () => {
|
|||||||
expect((await http('/%E0%A4%A')).status).toBe(404);
|
expect((await http('/%E0%A4%A')).status).toBe(404);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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 () => {
|
it('returns 404 for unknown paths', async () => {
|
||||||
expect((await http('/../../etc/passwd')).status).toBe(404);
|
expect((await http('/../../etc/passwd')).status).toBe(404);
|
||||||
expect((await http('/nothing')).status).toBe(404);
|
expect((await http('/nothing')).status).toBe(404);
|
||||||
|
|||||||
@@ -14,9 +14,12 @@ export type BackendOptions = {
|
|||||||
healthy?: () => Promise<boolean>;
|
healthy?: () => Promise<boolean>;
|
||||||
/** The static site of the content, rebuilt by the index job. */
|
/** The static site of the content, rebuilt by the index job. */
|
||||||
site?: () => Site | undefined;
|
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 MAX_FRAME_BYTES = 64 * 1024;
|
||||||
|
const THEME_PATH = '/theme.css';
|
||||||
const PING_INTERVAL_MS = 30_000;
|
const PING_INTERVAL_MS = 30_000;
|
||||||
|
|
||||||
// xterm.js creates style elements at runtime, so styles need 'unsafe-inline'.
|
// xterm.js creates style elements at runtime, so styles need 'unsafe-inline'.
|
||||||
@@ -80,6 +83,9 @@ export function createBackend(config: BackendConfig, hub: SessionHub, options: B
|
|||||||
return send(response, ok ? 200 : 503, 'text/plain', ok ? 'ok' : 'degraded', { 'Cache-Control': 'no-store' }, head);
|
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);
|
const asset = assets.get(path);
|
||||||
if (asset)
|
if (asset)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -6,6 +6,10 @@
|
|||||||
<meta name="color-scheme" content="dark" />
|
<meta name="color-scheme" content="dark" />
|
||||||
<meta name="description" content="security-command.org: a real Linux shell in a disposable gVisor sandbox." />
|
<meta name="description" content="security-command.org: a real Linux shell in a disposable gVisor sandbox." />
|
||||||
<title>security-command.org</title>
|
<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" />
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header class="bar">
|
<header class="bar">
|
||||||
|
|||||||
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 |
@@ -0,0 +1,42 @@
|
|||||||
|
/*
|
||||||
|
* 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 two colors of the emblem on the boot screen, as in the favicon. */
|
||||||
|
--logo-primary: #771f2f;
|
||||||
|
--logo-secondary: #5c5555;
|
||||||
|
|
||||||
|
/* 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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { fetchLines, type BootColors } from './boot.ts';
|
||||||
|
import { LOGO } from './logo.ts';
|
||||||
|
|
||||||
|
const COLORS: BootColors = { primary: [119, 31, 47], secondary: [92, 85, 85], accent: [210, 70, 84] };
|
||||||
|
|
||||||
|
const plain = (line: string) => line.replace(/\x1b\[[0-9;]*m/g, '');
|
||||||
|
const width = (lines: string[]) => Math.max(...lines.map((line) => plain(line).length));
|
||||||
|
|
||||||
|
describe('fetchLines', () => {
|
||||||
|
it('puts the emblem next to the facts when there is room', () => {
|
||||||
|
const lines = fetchLines(100, COLORS);
|
||||||
|
|
||||||
|
expect(lines).toHaveLength(LOGO.length / 2);
|
||||||
|
expect(lines.some((line) => /▀.*Kernel/.test(plain(line)))).toBe(true);
|
||||||
|
expect(width(lines)).toBeLessThanOrEqual(100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('draws the emblem in the colors of the theme', () => {
|
||||||
|
const line = fetchLines(100, COLORS).join('');
|
||||||
|
|
||||||
|
expect(line).toContain('\x1b[38;2;119;31;47m');
|
||||||
|
expect(line).toContain('\x1b[38;2;92;85;85m');
|
||||||
|
expect(line).toContain('\x1b[1m\x1b[38;2;210;70;84mguest@security-command');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stacks the emblem above the facts on narrow screens and drops it on tiny ones', () => {
|
||||||
|
const narrow = fetchLines(40, COLORS);
|
||||||
|
expect(plain(narrow[LOGO.length / 2 + 1]!)).toBe('guest@security-command');
|
||||||
|
expect(width(narrow)).toBeLessThanOrEqual(40);
|
||||||
|
|
||||||
|
const tiny = fetchLines(30, COLORS);
|
||||||
|
expect(plain(tiny[0]!)).toBe('guest@security-command');
|
||||||
|
expect(tiny.some((line) => /[\u2580\u2584\u2588]/.test(line))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
+88
-44
@@ -1,63 +1,111 @@
|
|||||||
import type { Terminal } from '@xterm/xterm';
|
import type { Terminal } from '@xterm/xterm';
|
||||||
import type { EndReason } from './connection.ts';
|
import type { EndReason } from './connection.ts';
|
||||||
|
import { LOGO } from './logo.ts';
|
||||||
|
|
||||||
const DIM = '\x1b[2m';
|
const DIM = '\x1b[2m';
|
||||||
const BOLD = '\x1b[1m';
|
const BOLD = '\x1b[1m';
|
||||||
const GREEN = '\x1b[32m';
|
|
||||||
const RESET = '\x1b[0m';
|
const RESET = '\x1b[0m';
|
||||||
|
|
||||||
const CHECKS = [
|
export type Rgb = [number, number, number];
|
||||||
'gVisor sandbox runtime',
|
|
||||||
'read only root filesystem',
|
/** Colors of the overview, taken from theme.css. */
|
||||||
'network disabled',
|
export type BootColors = {
|
||||||
'one container per visitor',
|
/** The red of the emblem. */
|
||||||
|
primary: Rgb;
|
||||||
|
/** The grey of the emblem. */
|
||||||
|
secondary: Rgb;
|
||||||
|
/** Name and keys of the facts. */
|
||||||
|
accent: Rgb;
|
||||||
|
};
|
||||||
|
|
||||||
|
const USER = 'guest@security-command';
|
||||||
|
|
||||||
|
/** Facts about every sandbox. The limits match the fixed flags of the spawner. */
|
||||||
|
const FACTS: [string, string][] = [
|
||||||
|
['OS', 'Debian 13 (trixie)'],
|
||||||
|
['Kernel', 'gVisor, in user space'],
|
||||||
|
['Shell', 'bash'],
|
||||||
|
['Network', 'none'],
|
||||||
|
['Rootfs', 'read only'],
|
||||||
|
['Memory', '80 MiB'],
|
||||||
|
['CPU', '0.5 cores'],
|
||||||
|
['Isolation', 'one container per visitor'],
|
||||||
];
|
];
|
||||||
|
|
||||||
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
const KEY_WIDTH = Math.max(...FACTS.map(([key]) => key.length)) + 2;
|
||||||
|
const INFO_WIDTH = Math.max(USER.length, ...FACTS.map(([, value]) => KEY_WIDTH + value.length));
|
||||||
|
const LOGO_WIDTH = LOGO[0]!.length;
|
||||||
|
const LOGO_GAP = 3;
|
||||||
|
const PALETTE = [40, 41, 42, 43, 44, 45, 46, 47].map((color) => `\x1b[${color}m `).join('') + RESET;
|
||||||
|
|
||||||
/** Terminals need carriage returns; plain text files only have line feeds. */
|
const foreground = ([r, g, b]: Rgb) => `\x1b[38;2;${r};${g};${b}m`;
|
||||||
function toTerminal(text: string): string {
|
const background = ([r, g, b]: Rgb) => `\x1b[48;2;${r};${g};${b}m`;
|
||||||
return text.replace(/\r?\n/g, '\r\n');
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchMotd(): Promise<string | undefined>
|
/** Draws two pixel rows per terminal row with half blocks, using the upper half for the top pixel. */
|
||||||
|
function logoLines(colors: BootColors): string[]
|
||||||
{
|
{
|
||||||
try
|
const color = (pixel: string) => (pixel === 'r' ? colors.primary : colors.secondary);
|
||||||
|
const cell = (top: string, bottom: string) =>
|
||||||
{
|
{
|
||||||
const response = await fetch('/raw/motd');
|
if (top === ' ' && bottom === ' ') return '\x1b[0m ';
|
||||||
return response.ok ? await response.text() : undefined;
|
if (top === bottom) return `\x1b[49m${foreground(color(top))}\u2588`;
|
||||||
|
if (bottom === ' ') return `\x1b[49m${foreground(color(top))}\u2580`;
|
||||||
|
if (top === ' ') return `\x1b[49m${foreground(color(bottom))}\u2584`;
|
||||||
|
return `${foreground(color(top))}${background(color(bottom))}\u2580`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const lines: string[] = [];
|
||||||
|
for (let row = 0; row < LOGO.length; row += 2)
|
||||||
|
{
|
||||||
|
const top = LOGO[row]!;
|
||||||
|
const bottom = LOGO[row + 1] ?? '';
|
||||||
|
lines.push([...top].map((pixel, column) => cell(pixel, bottom[column] ?? ' ')).join('') + RESET);
|
||||||
}
|
}
|
||||||
catch { return undefined; }
|
return lines;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function startPrompt(touch: boolean): string {
|
/**
|
||||||
return `${BOLD}${touch ? 'tap' : 'press any key'} to boot your sandbox${RESET}`;
|
* Lines of the fastfetch style overview: the emblem next to the facts, above
|
||||||
}
|
* them on narrow screens, and left out where even that does not fit.
|
||||||
|
*/
|
||||||
/** Plays the local boot screen. Nothing reaches the server until the visitor interacts. */
|
export function fetchLines(cols: number, colors: BootColors): string[]
|
||||||
export async function playBoot(terminal: Terminal, touch: boolean): Promise<void>
|
|
||||||
{
|
{
|
||||||
const motd = fetchMotd();
|
const accent = `${BOLD}${foreground(colors.accent)}`;
|
||||||
|
const info = [
|
||||||
|
`${accent}${USER}${RESET}`,
|
||||||
|
'-'.repeat(USER.length),
|
||||||
|
...FACTS.map(([key, value]) => `${accent}${key.padEnd(KEY_WIDTH)}${RESET}${value}`),
|
||||||
|
'',
|
||||||
|
PALETTE,
|
||||||
|
];
|
||||||
|
|
||||||
terminal.writeln(`${BOLD}security-command.org${RESET} ${DIM}terminal${RESET}`);
|
if (cols < LOGO_WIDTH) return info;
|
||||||
terminal.writeln('');
|
|
||||||
|
|
||||||
for (const check of CHECKS)
|
const logo = logoLines(colors);
|
||||||
|
if (cols < LOGO_WIDTH + LOGO_GAP + INFO_WIDTH) return [...logo, '', ...info];
|
||||||
|
|
||||||
|
// The facts sit in the middle of the emblem's height.
|
||||||
|
const offset = Math.max(0, Math.floor((logo.length - info.length) / 2));
|
||||||
|
return Array.from({ length: Math.max(logo.length, offset + info.length) }, (_, row) =>
|
||||||
{
|
{
|
||||||
await sleep(120);
|
const left = logo[row] ?? ' '.repeat(LOGO_WIDTH);
|
||||||
terminal.writeln(`${DIM}[${RESET}${GREEN} ok ${RESET}${DIM}]${RESET} ${check}`);
|
return `${left}${' '.repeat(LOGO_GAP)}${info[row - offset] ?? ''}`;
|
||||||
}
|
});
|
||||||
|
}
|
||||||
|
|
||||||
const text = await motd;
|
/** Any key or tap boots the sandbox. */
|
||||||
if (text)
|
const START_PROMPT = `${BOLD}...${RESET}`;
|
||||||
{
|
|
||||||
terminal.writeln('');
|
|
||||||
terminal.write(toTerminal(text.trimEnd()));
|
|
||||||
terminal.writeln('');
|
|
||||||
}
|
|
||||||
|
|
||||||
terminal.writeln('');
|
/**
|
||||||
terminal.write(startPrompt(touch));
|
* 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';
|
||||||
|
|
||||||
|
/** Shows the local boot screen. Nothing reaches the server until the visitor interacts. */
|
||||||
|
export function showBoot(terminal: Terminal, colors: BootColors): void
|
||||||
|
{
|
||||||
|
terminal.write(`${SHOW_CURSOR}\r\n${fetchLines(terminal.cols, colors).join('\r\n')}\r\n\r\n${START_PROMPT}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const END_MESSAGES: Record<EndReason, string> = {
|
const END_MESSAGES: Record<EndReason, string> = {
|
||||||
@@ -71,12 +119,8 @@ const END_MESSAGES: Record<EndReason, string> = {
|
|||||||
busy: 'all sandboxes and the queue are taken, try again in a few minutes',
|
busy: 'all sandboxes and the queue are taken, try again in a few minutes',
|
||||||
};
|
};
|
||||||
|
|
||||||
export function endMessage(reason: EndReason, touch: boolean): string {
|
export function endMessage(reason: EndReason): string {
|
||||||
return `\r\n${DIM}[${END_MESSAGES[reason]}]${RESET}\r\n${startPrompt(touch).replace('boot your sandbox', 'start a new session')}`;
|
return `\r\n${DIM}[${END_MESSAGES[reason]}]${RESET}\r\n${START_PROMPT}`;
|
||||||
}
|
|
||||||
|
|
||||||
export function solvingMessage(difficulty: number): string {
|
|
||||||
return `\r\x1b[2K${DIM}solving a proof of work puzzle against abuse (${difficulty} bits)...${RESET}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Rewrites the current line, so position updates do not pile up. */
|
/** Rewrites the current line, so position updates do not pile up. */
|
||||||
|
|||||||
@@ -32,7 +32,6 @@ function connect(token?: string)
|
|||||||
{
|
{
|
||||||
const socket = new FakeSocket();
|
const socket = new FakeSocket();
|
||||||
const events = {
|
const events = {
|
||||||
solving: [] as number[],
|
|
||||||
queued: [] as number[],
|
queued: [] as number[],
|
||||||
ready: [] as Ready[],
|
ready: [] as Ready[],
|
||||||
output: [] as string[],
|
output: [] as string[],
|
||||||
@@ -41,7 +40,6 @@ function connect(token?: string)
|
|||||||
};
|
};
|
||||||
|
|
||||||
const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, token, {
|
const connection = new TerminalConnection('ws://test/ws', { cols: 80, rows: 24 }, token, {
|
||||||
solving: (difficulty) => events.solving.push(difficulty),
|
|
||||||
queued: (position) => events.queued.push(position),
|
queued: (position) => events.queued.push(position),
|
||||||
ready: (session) => events.ready.push(session),
|
ready: (session) => events.ready.push(session),
|
||||||
output: (data) => events.output.push(new TextDecoder().decode(data)),
|
output: (data) => events.output.push(new TextDecoder().decode(data)),
|
||||||
@@ -71,7 +69,6 @@ describe('TerminalConnection', () => {
|
|||||||
connection.resize({ cols: 100, rows: 30 });
|
connection.resize({ cols: 100, rows: 30 });
|
||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
|
|
||||||
expect(events.solving).toEqual([20]);
|
|
||||||
expect(socket.sent.at(-1)).toBe('{"type":"hello","nonce":3020,"cols":100,"rows":30}');
|
expect(socket.sent.at(-1)).toBe('{"type":"hello","nonce":3020,"cols":100,"rows":30}');
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -94,7 +91,6 @@ describe('TerminalConnection', () => {
|
|||||||
await Promise.resolve();
|
await Promise.resolve();
|
||||||
|
|
||||||
expect(socket.sent).toEqual([`{"type":"resume","token":"${'A'.repeat(22)}","cols":80,"rows":24}`]);
|
expect(socket.sent).toEqual([`{"type":"resume","token":"${'A'.repeat(22)}","cols":80,"rows":24}`]);
|
||||||
expect(events.solving).toEqual([]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('passes queue positions, readiness, output and idle warnings on', () => {
|
it('passes queue positions, readiness, output and idle warnings on', () => {
|
||||||
|
|||||||
@@ -14,12 +14,11 @@ export type EndReason = ExitReason | RefusalReason | 'lost' | 'rejected';
|
|||||||
export type Ready = { token: string; expiresAt: number; resumed: boolean };
|
export type Ready = { token: string; expiresAt: number; resumed: boolean };
|
||||||
|
|
||||||
export type ConnectionEvents = {
|
export type ConnectionEvents = {
|
||||||
solving(difficulty: number): void;
|
queued(position: number): void;
|
||||||
queued(position: number): void;
|
ready(session: Ready): void;
|
||||||
ready(session: Ready): void;
|
output(data: Uint8Array): void;
|
||||||
output(data: Uint8Array): void;
|
idle(secondsLeft: number): void;
|
||||||
idle(secondsLeft: number): void;
|
ended(reason: EndReason): void;
|
||||||
ended(reason: EndReason): void;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SocketFactory = (url: string) => WebSocket;
|
export type SocketFactory = (url: string) => WebSocket;
|
||||||
@@ -130,7 +129,6 @@ export class TerminalConnection
|
|||||||
|
|
||||||
private greet(challenge: string, difficulty: number): void
|
private greet(challenge: string, difficulty: number): void
|
||||||
{
|
{
|
||||||
this.events.solving(difficulty);
|
|
||||||
this.solve(challenge, difficulty).then(
|
this.solve(challenge, difficulty).then(
|
||||||
(nonce) => this.control({ type: 'hello', nonce, ...this.size }),
|
(nonce) => this.control({ type: 'hello', nonce, ...this.size }),
|
||||||
() => this.socket.close(),
|
() => this.socket.close(),
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/**
|
||||||
|
* The emblem of the favicon at 35 by 34 pixels: r is its red, g its grey and
|
||||||
|
* a space the background. Two pixel rows share one terminal row.
|
||||||
|
*/
|
||||||
|
export const 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 ',
|
||||||
|
];
|
||||||
+14
-18
@@ -7,9 +7,10 @@ import { FitAddon } from '@xterm/addon-fit';
|
|||||||
import { WebLinksAddon } from '@xterm/addon-web-links';
|
import { WebLinksAddon } from '@xterm/addon-web-links';
|
||||||
import { WebglAddon } from '@xterm/addon-webgl';
|
import { WebglAddon } from '@xterm/addon-webgl';
|
||||||
import { Terminal } from '@xterm/xterm';
|
import { Terminal } from '@xterm/xterm';
|
||||||
import { CONNECTING_MESSAGE, endMessage, playBoot, queueMessage, solvingMessage } from './boot.ts';
|
import { CONNECTING_MESSAGE, endMessage, queueMessage, showBoot } from './boot.ts';
|
||||||
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
|
import { TerminalConnection, terminalUrl, type EndReason, type Ready } from './connection.ts';
|
||||||
import { createKeybar } from './keybar.ts';
|
import { createKeybar } from './keybar.ts';
|
||||||
|
import { bootColors, terminalTheme } from './theme.ts';
|
||||||
import { savedToken } from './token.ts';
|
import { savedToken } from './token.ts';
|
||||||
|
|
||||||
type State = 'booting' | 'idle' | 'connecting' | 'active' | 'reconnecting';
|
type State = 'booting' | 'idle' | 'connecting' | 'active' | 'reconnecting';
|
||||||
@@ -22,17 +23,14 @@ const touch = window.matchMedia('(pointer: coarse)').matches;
|
|||||||
const element = document.getElementById('terminal')!;
|
const element = document.getElementById('terminal')!;
|
||||||
const notice = document.getElementById('notice')!;
|
const notice = document.getElementById('notice')!;
|
||||||
|
|
||||||
|
// The cursor stays a solid block without focus, so the prompt never looks inert.
|
||||||
const terminal = new Terminal({
|
const terminal = new Terminal({
|
||||||
fontFamily: '"JetBrains Mono", monospace',
|
fontFamily: '"JetBrains Mono", monospace',
|
||||||
fontSize: touch ? 13 : 15,
|
fontSize: touch ? 13 : 15,
|
||||||
cursorBlink: true,
|
cursorBlink: true,
|
||||||
scrollback: 5000,
|
cursorInactiveStyle: 'block',
|
||||||
theme: {
|
scrollback: 5000,
|
||||||
background: '#0b0d10',
|
theme: terminalTheme(),
|
||||||
foreground: '#d6dde6',
|
|
||||||
cursor: '#7ee787',
|
|
||||||
selectionBackground: '#2b3a4a',
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// The key bar takes its space before the first fit, so the grid never overflows.
|
// The key bar takes its space before the first fit, so the grid never overflows.
|
||||||
@@ -87,7 +85,6 @@ function size() {
|
|||||||
function connect(token?: string, redraw = false): void
|
function connect(token?: string, redraw = false): void
|
||||||
{
|
{
|
||||||
connection = new TerminalConnection(terminalUrl(window.location), size(), token, {
|
connection = new TerminalConnection(terminalUrl(window.location), size(), token, {
|
||||||
solving: (difficulty) => terminal.write(solvingMessage(difficulty)),
|
|
||||||
queued: (position) => terminal.write(queueMessage(position)),
|
queued: (position) => terminal.write(queueMessage(position)),
|
||||||
ready: (session: Ready) =>
|
ready: (session: Ready) =>
|
||||||
{
|
{
|
||||||
@@ -123,12 +120,12 @@ function ended(reason: EndReason): void
|
|||||||
|
|
||||||
if (state === 'booting')
|
if (state === 'booting')
|
||||||
{
|
{
|
||||||
void boot();
|
boot();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
state = 'idle';
|
state = 'idle';
|
||||||
terminal.write(endMessage(reason, touch));
|
terminal.write(endMessage(reason));
|
||||||
}
|
}
|
||||||
|
|
||||||
function reconnect(): void
|
function reconnect(): void
|
||||||
@@ -169,10 +166,9 @@ function input(data: string): void
|
|||||||
else if (state === 'idle') start();
|
else if (state === 'idle') start();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function boot(): Promise<void>
|
function boot(): void
|
||||||
{
|
{
|
||||||
state = 'booting';
|
showBoot(terminal, bootColors());
|
||||||
await playBoot(terminal, touch);
|
|
||||||
state = 'idle';
|
state = 'idle';
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,4 +180,4 @@ new ResizeObserver(() => fit.fit()).observe(element);
|
|||||||
// A reload within the grace period picks the running sandbox up again.
|
// A reload within the grace period picks the running sandbox up again.
|
||||||
const token = savedToken.get();
|
const token = savedToken.get();
|
||||||
if (token) connect(token, true);
|
if (token) connect(token, true);
|
||||||
else void boot();
|
else boot();
|
||||||
@@ -1,13 +1,5 @@
|
|||||||
|
/* Colors come from /theme.css. */
|
||||||
:root {
|
:root {
|
||||||
--background: #0b0d10;
|
|
||||||
--surface: #12161b;
|
|
||||||
--border: #1f262e;
|
|
||||||
--text: #d6dde6;
|
|
||||||
--muted: #7d8794;
|
|
||||||
--accent: #7ee787;
|
|
||||||
--warning: #e3b341;
|
|
||||||
|
|
||||||
color-scheme: dark;
|
|
||||||
font-family: "JetBrains Mono", monospace;
|
font-family: "JetBrains Mono", monospace;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import type { ITheme } from '@xterm/xterm';
|
||||||
|
import type { BootColors, Rgb } from './boot.ts';
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Resolves any CSS color through the browser, so the theme may use every color syntax. */
|
||||||
|
function rgb(value: string, fallback: Rgb): Rgb
|
||||||
|
{
|
||||||
|
const probe = document.createElement('span');
|
||||||
|
probe.style.color = value;
|
||||||
|
if (!probe.style.color) return fallback;
|
||||||
|
|
||||||
|
document.body.append(probe);
|
||||||
|
const channels = getComputedStyle(probe).color.match(/\d+(\.\d+)?/g)?.slice(0, 3).map(Number);
|
||||||
|
probe.remove();
|
||||||
|
return channels?.length === 3 ? (channels as Rgb) : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 !== ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bootColors(): BootColors
|
||||||
|
{
|
||||||
|
return {
|
||||||
|
primary: rgb(variable('logo-primary'), [119, 31, 47]),
|
||||||
|
secondary: rgb(variable('logo-secondary'), [92, 85, 85]),
|
||||||
|
accent: rgb(variable('accent'), [210, 70, 84]),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ export default defineConfig({
|
|||||||
'/ls': backend,
|
'/ls': backend,
|
||||||
'/impressum': backend,
|
'/impressum': backend,
|
||||||
'/datenschutz': backend,
|
'/datenschutz': backend,
|
||||||
|
'/theme.css': backend,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -35,7 +35,7 @@ describe('containerSpec', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('mounts host paths read only', () => {
|
it('mounts host paths read only', () => {
|
||||||
expect(host.Binds).toEqual(['/srv/content:/srv/www:ro', '/srv/status:/var/status:ro']);
|
expect(host.Binds).toEqual(['/srv/content:/home/guest:ro', '/srv/status:/var/status:ro']);
|
||||||
expect(Object.values(host.Tmpfs).every((options) => options.includes('noexec'))).toBe(true);
|
expect(Object.values(host.Tmpfs).every((options) => options.includes('noexec'))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -37,11 +37,9 @@ export function containerSpec(config: SpawnerConfig, sessionId: string, expiresA
|
|||||||
NanoCpus: 500_000_000,
|
NanoCpus: 500_000_000,
|
||||||
PidsLimit: 50,
|
PidsLimit: 50,
|
||||||
Ulimits: [{ Name: 'nofile', Soft: 256, Hard: 256 }],
|
Ulimits: [{ Name: 'nofile', Soft: 256, Hard: 256 }],
|
||||||
Tmpfs: {
|
// The content is the read only home directory, so /tmp is the only writable place.
|
||||||
'/home/guest': 'size=8m,mode=1777,noexec,nosuid',
|
Tmpfs: { '/tmp': 'size=8m,noexec,nosuid' },
|
||||||
'/tmp': 'size=8m,noexec,nosuid',
|
Binds: [`${config.contentDir}:/home/guest:ro`, `${config.statusDir}:/var/status:ro`],
|
||||||
},
|
|
||||||
Binds: [`${config.contentDir}:/srv/www:ro`, `${config.statusDir}:/var/status:ro`],
|
|
||||||
LogConfig: { Type: 'none', Config: {} },
|
LogConfig: { Type: 'none', Config: {} },
|
||||||
AutoRemove: true,
|
AutoRemove: true,
|
||||||
},
|
},
|
||||||
@@ -91,7 +89,7 @@ export class SandboxManager {
|
|||||||
return created.Id;
|
return created.Id;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Attaches before starting, so the motd and first prompt are not lost. */
|
/** Attaches before starting, so the first prompt is not lost. */
|
||||||
async attach(containerId: string): Promise<Socket>
|
async attach(containerId: string): Promise<Socket>
|
||||||
{
|
{
|
||||||
const container = await this.managed(containerId);
|
const container = await this.managed(containerId);
|
||||||
|
|||||||
@@ -111,8 +111,16 @@ set +a
|
|||||||
|
|
||||||
IMAGE=$SANDBOX_IMAGE deploy/host/verify-sandbox.sh
|
IMAGE=$SANDBOX_IMAGE deploy/host/verify-sandbox.sh
|
||||||
|
|
||||||
docker compose --project-directory "$PWD" -f deploy/compose.yml \
|
compose() {
|
||||||
--env-file .env --env-file runtime/deploy.env up -d --remove-orphans
|
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 "deployed ${commit}"
|
||||||
echo "jobs: docker exec security-command-jobs-1 jobctl list"
|
echo "jobs: docker exec security-command-jobs-1 jobctl list"
|
||||||
@@ -60,6 +60,14 @@ services:
|
|||||||
- ${CONTENT_DIR}:/content:ro
|
- ${CONTENT_DIR}:/content:ro
|
||||||
- ./config:/config:ro
|
- ./config:/config:ro
|
||||||
- ./runtime/jobs/triggers:/run/jobs/triggers: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:
|
logging:
|
||||||
driver: json-file
|
driver: json-file
|
||||||
options:
|
options:
|
||||||
@@ -92,6 +100,13 @@ services:
|
|||||||
- ./jobs:/jobs:ro
|
- ./jobs:/jobs:ro
|
||||||
- ${JOBS_HOST_DIR:-/srv}:/host/srv:ro
|
- ${JOBS_HOST_DIR:-/srv}:/host/srv:ro
|
||||||
- ./runtime/jobs:/run/jobs
|
- ./runtime/jobs:/run/jobs
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "jobctl", "list"]
|
||||||
|
interval: 60s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
start_period: 30s
|
||||||
|
start_interval: 2s
|
||||||
logging:
|
logging:
|
||||||
driver: json-file
|
driver: json-file
|
||||||
options:
|
options:
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ SANDBOX_FLAGS=(
|
|||||||
--security-opt no-new-privileges --user guest
|
--security-opt no-new-privileges --user guest
|
||||||
--memory 80m --memory-swap 80m --cpus 0.5 --pids-limit 50
|
--memory 80m --memory-swap 80m --cpus 0.5 --pids-limit 50
|
||||||
--ulimit nofile=256:256
|
--ulimit nofile=256:256
|
||||||
--tmpfs /home/guest:size=8m,mode=1777,noexec,nosuid
|
|
||||||
--tmpfs /tmp:size=8m,noexec,nosuid
|
--tmpfs /tmp:size=8m,noexec,nosuid
|
||||||
--log-driver none
|
--log-driver none
|
||||||
--hostname sandbox
|
--hostname sandbox
|
||||||
|
|||||||
@@ -41,8 +41,8 @@ if [[ $EXPECT_GVISOR == 1 ]]; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
check "rootfs is read only" 'touch /x && echo writable' 'Read-only file system'
|
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 read only" 'touch ~/x && echo writable' 'Read-only file system'
|
||||||
check "home is noexec" 'cp /bin/true ~/t && ~/t && echo executed' 'Permission denied'
|
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 "tmp is noexec" 'cp /bin/true /tmp/t && /tmp/t && echo executed' 'Permission denied'
|
||||||
check "no network interfaces besides lo" \
|
check "no network interfaces besides lo" \
|
||||||
"tail -n +3 /proc/net/dev | awk '{print \$1}' | grep -v '^lo:' | wc -l" '^0$'
|
"tail -n +3 /proc/net/dev | awk '{print \$1}' | grep -v '^lo:' | wc -l" '^0$'
|
||||||
|
|||||||
@@ -138,6 +138,13 @@ describe('buildSite', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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', () => {
|
it('renders legal pages from their content files', () => {
|
||||||
expect(text(site, '/impressum')).toContain('Max Mustermann');
|
expect(text(site, '/impressum')).toContain('Max Mustermann');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -3,6 +3,9 @@ import type { Entry } from './walk.ts';
|
|||||||
|
|
||||||
export type Link = { label: string; href: string };
|
export type Link = { label: string; href: 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 SAFE_SCHEME = /^(https?|mailto):/i;
|
||||||
const ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
const ANY_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
||||||
|
|
||||||
@@ -94,9 +97,8 @@ export function isText(content: Buffer): boolean
|
|||||||
}
|
}
|
||||||
|
|
||||||
const STYLE = `
|
const STYLE = `
|
||||||
:root { color-scheme: dark; --bg: #0b0d10; --text: #d6dde6; --muted: #7d8794; --accent: #7ee787; --border: #1f262e; }
|
|
||||||
* { box-sizing: border-box; }
|
* { box-sizing: border-box; }
|
||||||
body { margin: 0; background: var(--bg); color: var(--text); font: 15px/1.6 "JetBrains Mono", ui-monospace, monospace; }
|
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, 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; }
|
header { display: flex; flex-wrap: wrap; gap: 0.5rem 1rem; justify-content: space-between; border-bottom: 1px solid var(--border); font-size: 0.85rem; }
|
||||||
header .site { color: var(--accent); }
|
header .site { color: var(--accent); }
|
||||||
@@ -109,7 +111,7 @@ table { border-collapse: collapse; width: 100%; }
|
|||||||
td { padding: 0.15rem 1.5rem 0.15rem 0; white-space: nowrap; }
|
td { padding: 0.15rem 1.5rem 0.15rem 0; white-space: nowrap; }
|
||||||
td:first-child { width: 100%; white-space: normal; }
|
td:first-child { width: 100%; white-space: normal; }
|
||||||
img { max-width: 100%; }
|
img { max-width: 100%; }
|
||||||
.markdown code, .markdown pre { background: #12161b; }
|
.markdown code, .markdown pre { background: var(--surface); }
|
||||||
`;
|
`;
|
||||||
|
|
||||||
export type PageOptions = {
|
export type PageOptions = {
|
||||||
@@ -118,8 +120,16 @@ export type PageOptions = {
|
|||||||
crumbs: Link[];
|
crumbs: Link[];
|
||||||
body: string;
|
body: string;
|
||||||
nav: Link[];
|
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
|
export function renderPage(options: PageOptions): string
|
||||||
{
|
{
|
||||||
const crumbs = options.crumbs.map((crumb) => `<a href="${crumb.href}">${escapeHtml(crumb.label)}</a>`).join(' / ');
|
const crumbs = options.crumbs.map((crumb) => `<a href="${crumb.href}">${escapeHtml(crumb.label)}</a>`).join(' / ');
|
||||||
@@ -135,7 +145,11 @@ export function renderPage(options: PageOptions): string
|
|||||||
<meta name="description" content="${escapeHtml(options.description)}">
|
<meta name="description" content="${escapeHtml(options.description)}">
|
||||||
<meta property="og:title" content="${escapeHtml(options.title)}">
|
<meta property="og:title" content="${escapeHtml(options.title)}">
|
||||||
<meta property="og:description" content="${escapeHtml(options.description)}">
|
<meta property="og:description" content="${escapeHtml(options.description)}">
|
||||||
<style>${STYLE}</style>
|
<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">
|
||||||
|
<style>${fontFaces(options.fonts ?? [])}${STYLE}</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<header><a class="site" href="/">security-command.org</a><nav>${nav}</nav></header>
|
<header><a class="site" href="/">security-command.org</a><nav>${nav}</nav></header>
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { escapeHtml, isText, renderFile, renderListing, renderPage, urlPath, type Link } from './render.ts';
|
import { escapeHtml, isText, renderFile, renderListing, renderPage, urlPath, type Font, type Link } from './render.ts';
|
||||||
import type { ContentIndex, Entry } from './walk.ts';
|
import type { ContentIndex, Entry } from './walk.ts';
|
||||||
|
|
||||||
export type SitePage = {
|
export type SitePage = {
|
||||||
@@ -17,9 +17,13 @@ export type SiteOptions = {
|
|||||||
siteUrl: string;
|
siteUrl: string;
|
||||||
/** Route name to content file, for example impressum to impressum.txt. */
|
/** Route name to content file, for example impressum to impressum.txt. */
|
||||||
legal: Map<string, string>;
|
legal: Map<string, string>;
|
||||||
|
fonts?: Font[];
|
||||||
};
|
};
|
||||||
|
|
||||||
const RESERVED = ['ws', 'raw', 'ls', 'healthz', 'assets', 'index.html', 'sitemap.xml', 'robots.txt'];
|
const RESERVED = [
|
||||||
|
'ws', 'raw', 'ls', 'healthz', 'assets', 'index.html', 'sitemap.xml', 'robots.txt',
|
||||||
|
'theme.css', 'favicon.ico', 'icon-192.png', 'apple-touch-icon.png',
|
||||||
|
];
|
||||||
|
|
||||||
/** Route names the content cannot use at its top level, including the legal pages. */
|
/** Route names the content cannot use at its top level, including the legal pages. */
|
||||||
export function reservedNames(legal: Map<string, string>): Set<string> {
|
export function reservedNames(legal: Map<string, string>): Set<string> {
|
||||||
@@ -83,7 +87,7 @@ export function buildSite(index: ContentIndex, options: SiteOptions): Site
|
|||||||
];
|
];
|
||||||
|
|
||||||
const html = (title: string, description: string, entryCrumbs: Link[], body: string): SitePage => ({
|
const html = (title: string, description: string, entryCrumbs: Link[], body: string): SitePage => ({
|
||||||
body: Buffer.from(renderPage({ title, description, crumbs: entryCrumbs, body, nav })),
|
body: Buffer.from(renderPage({ title, description, crumbs: entryCrumbs, body, nav, fonts: options.fonts })),
|
||||||
type: 'text/html; charset=utf-8',
|
type: 'text/html; charset=utf-8',
|
||||||
headers: {},
|
headers: {},
|
||||||
});
|
});
|
||||||
|
|||||||
+5
-3
@@ -13,8 +13,8 @@ RUN rm -f /etc/dpkg/dpkg.cfg.d/docker \
|
|||||||
figlet cowsay fortune-mod fortunes-min sl curl wget \
|
figlet cowsay fortune-mod fortunes-min sl curl wget \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
# The home directory stays empty, because Podman copies image content into
|
# The content directory is mounted read only as the home directory, so all
|
||||||
# tmpfs mounts and Docker does not. All shell configuration lives in /etc.
|
# shell configuration lives in /etc.
|
||||||
# Setuid binaries are useless under no-new-privileges, so they are stripped
|
# 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.
|
# to keep the attack surface minimal even if that option is ever dropped.
|
||||||
RUN useradd --uid 1000 --no-create-home --home-dir /home/guest --shell /bin/bash guest \
|
RUN useradd --uid 1000 --no-create-home --home-dir /home/guest --shell /bin/bash guest \
|
||||||
@@ -27,4 +27,6 @@ COPY --chmod=0755 bin/status /usr/local/bin/status
|
|||||||
ENV PATH=/usr/local/bin:/usr/bin:/bin:/usr/games
|
ENV PATH=/usr/local/bin:/usr/bin:/bin:/usr/games
|
||||||
USER guest
|
USER guest
|
||||||
WORKDIR /home/guest
|
WORKDIR /home/guest
|
||||||
CMD ["/bin/bash", "-l"]
|
# Startup files in the home directory belong to the content, so bash only
|
||||||
|
# reads the system wide configuration.
|
||||||
|
CMD ["/bin/bash", "--rcfile", "/etc/bash.bashrc", "-i"]
|
||||||
@@ -4,7 +4,14 @@ shopt -s checkwinsize histappend
|
|||||||
HISTSIZE=1000
|
HISTSIZE=1000
|
||||||
HISTCONTROL=ignoredups
|
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_STATE_HOME=/tmp/.local/state
|
||||||
|
|
||||||
|
PS1='\[\e[1;31m\]guest@security-command\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\$ '
|
||||||
|
|
||||||
alias ls='ls --color=auto'
|
alias ls='ls --color=auto'
|
||||||
alias ll='ls -lah --color=auto'
|
alias ll='ls -lah --color=auto'
|
||||||
|
|||||||
@@ -1,5 +0,0 @@
|
|||||||
if [ -r /srv/www/motd ]; then
|
|
||||||
cat /srv/www/motd
|
|
||||||
else
|
|
||||||
printf '%s\n' "Welcome. The content lives in /srv/www, and 'status' shows your session."
|
|
||||||
fi
|
|
||||||
Reference in new issue
Block a user