steid

@jamesgill /

steid/install.sh
Bourne Again Shell (bash)35.5 KBCode·Blame·History·Raw
1#!/bin/sh
2#
3# Steid installer for a fresh Debian/Ubuntu server.
4#
5# curl -fsSL https://releases.steid.dev/install.sh | sh -s -- --domain git.example.com
6#
7# It installs Steid to /opt/steid, keeps state in /var/lib/steid, runs it as an
8# unprivileged system user under systemd, and puts Caddy in front of it with an
9# automatic HTTPS certificate for the domain you give.
10#
11# Re-running it is an upgrade: it downloads the requested version, replaces the
12# binary and assets, rewrites the unit and the Caddyfile, and restarts. It never
13# touches /var/lib/steid, and it never overwrites /etc/steid/steid.env once that
14# exists, so anything you have edited there survives.
15#
16# ON `curl | sh`: you are being asked to run a script you have not read, as root,
17# from a URL. That is a real trust decision and "it's convenient" is not an
18# answer to it. Two honest alternatives: download it first and read it
19# (`curl -fsSL … -o install.sh; less install.sh; sh install.sh --domain …`), or
20# follow the manual path in README.md, which is the same dozen commands written
21# out. Nothing here is magic; the script exists to save typing, not to be trusted
22# blindly.
23
24set -eu
25
26# --- WHERE RELEASES COME FROM -----------------------------------------------
27#
28# Since 0.6.0: **https://releases.steid.dev** — an S3 bucket behind CloudFront,
29# run by the project. `jpgill.dev` serves the same files as a mirror and will
30# keep doing so until the author's instance moves onto the managed fleet; see
31# plans/decisions/0009-releases-from-releases-steid-dev.md for why the release
32# host stopped being a Steid instance.
33#
34# The short version: from 0.4.0 the artefacts came off jpgill.dev, which is the
35# author's live site *and* an instance of Steid. Serving Steid from Steid was the
36# point. But the control plane now installs boxes headlessly from cloud-init, so
37# every provision depends on that one instance being up, and an install that
38# 404s reads as a broken product rather than a busy weekend. A dumb static host
39# is the right dependency for a download; the demonstration was made and does not
40# need making on every install.
41#
42# `--tarball` is still the bootstrap for the very first instance of a *new*
43# distribution host, and the offline path.
44#
45# The layout expected here, and produced by release.sh, is unchanged from 0.4.0:
46#
47# ${RELEASE_BASE_URL}/v${VERSION}/steid-${VERSION}-${TARGET}.tar.gz
48# ${RELEASE_BASE_URL}/v${VERSION}/steid-${VERSION}-${TARGET}.tar.gz.sha256
49#
50# so a link published against the old host still resolves against the mirror,
51# and the two hosts differ only in their base.
52#
53# This is the *project's* distribution host — a constant, and NOT the `--domain`
54# the person running this installs onto. Everyone downloads Steid from here; each
55# installer then runs their own instance on their own hostname. Point
56# STEID_RELEASE_BASE_URL at your own mirror to install from somewhere else; the
57# path layout below is the whole contract.
58#
59# The version lives at the root of this host rather than under a repository path
60# because the host is not an instance of Steid and has no /{handle} namespace to
61# squat. On the mirror the old scoped path stays exactly as it was.
62RELEASE_BASE_URL="${STEID_RELEASE_BASE_URL:-https://releases.steid.dev}"
63
64# The version to install. Pinned rather than "latest" because there is no
65# redirect to resolve "latest" against, and a pinned default makes the upgrade
66# path explicit: `--version 0.8.1`.
67VERSION="${STEID_VERSION:-0.8.1}"
68# ----------------------------------------------------------------------------
69
70# The build target to fetch. musl is preferred — one static binary that does not
71# care which glibc the host has — but whether Steid builds against musl at all is
72# still being established, so the choice is a variable rather than a fact.
73# Override with --flavour gnu if the published artefacts are glibc.
74# gnu, matching what release.sh builds. musl was tried and rejected: it fails on
75# `ring` with Debian's musl-gcc wrapper, and — the decisive part — musl buys a
76# binary with no runtime dependencies while Steid hard-requires `git` on PATH, so
77# the portability cannot be used. THIS MUST AGREE WITH release.sh: they were
78# briefly out of step and the symptom was a confusing "checksum mismatch",
79# because the installer was looking for a musl tarball that was never built.
80FLAVOUR="gnu"
81
82DOMAIN=""
83WWW=0
84FORCE_CADDYFILE=0
85# A local artefact to install instead of downloading one. This exists because of
86# a bootstrap: the very first instance is what will *serve* the releases, so at
87# that moment there is nowhere to download from. It doubles as the offline and
88# air-gapped path.
89TARBALL=""
90PORT="3000"
91# Scheduled backups are OFF unless asked for. A timer that appears without being
92# asked for is a surprise, and this one writes a full copy of the instance to
93# disk every night — which is exactly what somebody with a small volume needs to
94# have agreed to. Omitting the flag on a later run leaves whatever is already
95# installed alone, the way the Caddyfile and the env file are left alone;
96# `--backups off` is how you actually remove it.
97BACKUPS=""
98# The owner to create at boot, written into steid.env. Both or neither: half of
99# an owner is refused below rather than quietly installing an instance that comes
100# up unclaimed, which is the state these exist to avoid.
101OWNER_EMAIL=""
102OWNER_HANDLE=""
103# The organisation the instance is for, written into steid.env beside the owner.
104# Optional, and only meaningful with an owner — an organisation with nobody to
105# own it is not a state Steid has, so it is refused below rather than written.
106# With it, the instance comes up as a company's Steid: the root lands on the
107# organisation and the setup wizard has nothing left to ask.
108OWNER_ORG=""
109OWNER_ORG_NAME=""
110# The operator surface's bearer token. Unlike everything else in steid.env this one
111# IS rewritten on a later run when the flag is given — see the note above
112# set_env_secret. Empty means "leave whatever is there alone", which is what an
113# ordinary upgrade does.
114OPERATOR_TOKEN=""
115INSTALL_DIR="/opt/steid"
116STATE_DIR="/var/lib/steid"
117CONF_DIR="/etc/steid"
118STEID_USER="steid"
119INSTALL_CADDY=1
120
121die() { echo "install.sh: $*" >&2; exit 1; }
122say() { echo "==> $*"; }
123
124# Sets one variable in steid.env, replacing the line if it is already there.
125#
126# **The one exception to "written once and left alone".** Every other setting in that
127# file is written on the first install and never touched again, so an upgrade cannot
128# revert something somebody deliberately changed. The operator token is different
129# because it is not somebody's edit: it is a machine credential the thing that
130# provisioned this box holds, it gets rotated, and a box that comes up with the
131# operator surface off is a box a control plane cannot see. Only a run that passes the
132# flag rewrites it; an upgrade without it leaves the line exactly where it was.
133#
134# **The value never reaches the terminal, a log or `ps`.** It is expanded into a
135# here-doc inside this function and nowhere else; no `echo`, no `say`, no error
136# message carries it. `set -x` is off — turning it on would print this like anything
137# else, which is the ordinary hazard of tracing a script that handles a secret.
138#
139# The replacement is written beside the file under `umask 077` and moved into place,
140# so the token is never briefly world-readable and an interrupted run cannot leave a
141# truncated env file.
142set_env_secret() {
143 _key="$1"
144 _value="$2"
145 _file="${CONF_DIR}/steid.env"
146 _tmp="${_file}.new"
147
148 (umask 077; : > "$_tmp")
149
150 if [ -f "$_file" ]; then
151 # Both the line and the comment this function wrote above it, or a rotation
152 # would stack a fresh comment on every run. `|| true`: grep exits 1 when it
153 # prints nothing, which under `set -e` would end the install.
154 grep -v -e "^${_key}=" -e "^# Written by install.sh --operator-token\.\$" \
155 "$_file" >> "$_tmp" || true
156 fi
157
158 # `printf`, not a here-doc: a here-doc expands `$…` and backticks in the value, and
159 # the value is a token somebody else generated. printf's %s takes it literally.
160 printf '%s\n' "# Written by install.sh --operator-token." "${_key}=${_value}" >> "$_tmp"
161
162 mv "$_tmp" "$_file"
163 chmod 640 "$_file"
164 chown "root:${STEID_USER}" "$_file"
165}
166
167usage() {
168 cat >&2 <<'USAGE'
169Usage: install.sh --domain <hostname> [options]
170
171 --tarball <path> install from a local tarball instead of downloading.
172 Needed for the first install, which has nowhere to
173 download from yet, and for offline installs.
174 --www also serve www.<hostname>, redirecting it to the bare
175 hostname. Requires a www DNS record pointing here —
176 without one Caddy retries a certificate it cannot get.
177 --force-caddyfile overwrite an existing /etc/caddy/Caddyfile. Off by
178 default so an upgrade cannot silently discard your edits.
179 --domain <hostname> the public hostname, e.g. git.example.com. Its DNS must
180 already point at this machine or the certificate cannot
181 be issued. Required.
182 --version <v> release to install (default: the pinned one above)
183 --flavour <musl|gnu> which build to fetch (default: gnu — see below; musl
184 is not built, and asking for it gets a 404)
185 --backups daily install a systemd timer that runs `steid backup` into
186 /var/lib/steid/backups every night, keeps the most
187 recent 14, and tells the settings page when it last
188 ran. Off unless you ask. `--backups off` removes it.
189 These stay on the same machine — see the note at the
190 end for copying them somewhere else.
191 --owner-email <addr> create this owner at first boot, so the instance is
192 --owner-handle <name> never unclaimed on the internet. Both or neither. The
193 owner gets no usable password: get in with
194 `steid reset-password <handle>` on this machine.
195 --owner-org <handle> also create this organisation at first boot, owned by
196 that owner, and land the root of the instance on it.
197 Needs the two flags above. Without it the root lands on
198 the owner's own page, which is what a one-person
199 instance wants.
200 --owner-org-name <n> the organisation's display name, e.g. "Acme Inc". Needs
201 --owner-org. Quote it if it has spaces.
202 --operator-token <t> bearer token for the operator surface (/metrics and the
203 detailed /api/instance). Written into steid.env before
204 Steid is started, so the instance never serves with that
205 surface off. This is the one setting a later run WILL
206 rewrite — pass it again to rotate the token; omit it and
207 the existing line is left alone like everything else.
208 Generate one with `openssl rand -hex 32`. It is never
209 printed.
210 --port <n> loopback port Steid listens on (default: 3000)
211 --no-caddy install and run Steid but do not touch Caddy. Only for
212 putting your own TLS-terminating proxy in front. Steid
213 has no TLS of its own; without a proxy, access tokens
214 cross the network in cleartext.
215 -h, --help this
216USAGE
217 exit "${1:-0}"
218}
219
220# --- arguments --------------------------------------------------------------
221
222while [ $# -gt 0 ]; do
223 case "$1" in
224 --domain) DOMAIN="${2:-}"; [ -n "$DOMAIN" ] || die "--domain needs a hostname"; shift 2 ;;
225 --tarball) TARBALL="${2:-}"; [ -n "$TARBALL" ] || die "--tarball needs a path"; shift 2 ;;
226 --www) WWW=1; shift ;;
227 --force-caddyfile) FORCE_CADDYFILE=1; shift ;;
228 --version) VERSION="${2:-}"; [ -n "$VERSION" ] || die "--version needs a value"; shift 2 ;;
229 --flavour) FLAVOUR="${2:-}"; [ -n "$FLAVOUR" ] || die "--flavour needs a value"; shift 2 ;;
230 --port) PORT="${2:-}"; [ -n "$PORT" ] || die "--port needs a number"; shift 2 ;;
231 --owner-email) OWNER_EMAIL="${2:-}"; [ -n "$OWNER_EMAIL" ] || die "--owner-email needs an address"; shift 2 ;;
232 --owner-handle) OWNER_HANDLE="${2:-}"; [ -n "$OWNER_HANDLE" ] || die "--owner-handle needs a handle"; shift 2 ;;
233 --owner-org) OWNER_ORG="${2:-}"; [ -n "$OWNER_ORG" ] || die "--owner-org needs a handle"; shift 2 ;;
234 --owner-org-name) OWNER_ORG_NAME="${2:-}"; [ -n "$OWNER_ORG_NAME" ] || die "--owner-org-name needs a name"; shift 2 ;;
235 # Deliberately no value in the die message, here or anywhere below.
236 --operator-token) OPERATOR_TOKEN="${2:-}"; [ -n "$OPERATOR_TOKEN" ] || die "--operator-token needs a value"; shift 2 ;;
237 --backups) BACKUPS="${2:-}"; [ -n "$BACKUPS" ] || die "--backups needs daily or off"; shift 2 ;;
238 --no-caddy) INSTALL_CADDY=0; shift ;;
239 -h|--help) usage 0 ;;
240 *) echo "install.sh: unknown argument: $1" >&2; usage 1 ;;
241 esac
242done
243
244# Fail early and loudly rather than half-installing. Everything below this point
245# assumes these hold.
246[ "$(id -u)" = "0" ] || die "must run as root (try: sudo sh install.sh --domain …)"
247
248if [ "$INSTALL_CADDY" = 1 ]; then
249 [ -n "$DOMAIN" ] || die "--domain is required. Caddy needs a real hostname to
250 obtain a certificate for, and Steid has no TLS of its own. If you are putting
251 your own proxy in front, pass --no-caddy."
252fi
253
254if [ -n "$DOMAIN" ]; then
255 case "$DOMAIN" in
256 *[!A-Za-z0-9.-]*|-*|.*|*.) die "'$DOMAIN' does not look like a hostname" ;;
257 esac
258fi
259
260case "$PORT" in
261 ''|*[!0-9]*) die "--port must be a number" ;;
262esac
263
264case "$FLAVOUR" in
265 musl|gnu) ;;
266 *) die "--flavour must be 'musl' or 'gnu'" ;;
267esac
268
269case "$BACKUPS" in
270 ''|daily|off) ;;
271 *) die "--backups must be 'daily' or 'off'" ;;
272esac
273
274# Both or neither, and Steid itself refuses to start on half of them — so this is
275# the same rule said at the moment it can still be fixed by retyping the command.
276# Steid validates the values (the handle's shape, the reserved list, the email);
277# this only checks that you gave both.
278if [ -n "$OWNER_EMAIL" ] && [ -z "$OWNER_HANDLE" ]; then
279 die "--owner-email needs --owner-handle too. Pass both or neither."
280fi
281if [ -n "$OWNER_HANDLE" ] && [ -z "$OWNER_EMAIL" ]; then
282 die "--owner-handle needs --owner-email too. Pass both or neither."
283fi
284
285# An organisation with nobody to own it is not a state Steid has, so the same rule
286# is said here rather than at the first boot that would have to refuse it. Steid
287# validates the handle itself — the shape, and the reserved list.
288if [ -n "$OWNER_ORG" ] && { [ -z "$OWNER_EMAIL" ] || [ -z "$OWNER_HANDLE" ]; }; then
289 die "--owner-org needs --owner-email and --owner-handle too."
290fi
291if [ -n "$OWNER_ORG_NAME" ] && [ -z "$OWNER_ORG" ]; then
292 die "--owner-org-name needs --owner-org too."
293fi
294
295# Where the timer writes, how many it keeps, and the file it touches afterwards.
296# Steid reads only the marker's modification time, so this and the settings page
297# cannot drift into disagreeing about a format.
298BACKUP_DIR="${STATE_DIR}/backups"
299BACKUP_KEEP=14
300BACKUP_MARKER="${BACKUP_DIR}/.last-backup"
301
302case "${TARBALL:+local}${RELEASE_BASE_URL}" in
303 local*) : ;; # installing from a file; the download URL is irrelevant
304 *REPLACE-ME*) die "RELEASE_BASE_URL is still the placeholder. Edit the top of
305 this script (or set STEID_RELEASE_BASE_URL) to point at real release artefacts,
306 or pass --tarball to install from a local file." ;;
307esac
308
309command -v systemctl >/dev/null 2>&1 || die "no systemd here; follow the manual path in README.md"
310command -v apt-get >/dev/null 2>&1 || die "this installer only knows apt (Debian/Ubuntu).
311 The manual path in README.md works on anything with systemd."
312
313case "$(uname -m)" in
314 x86_64|amd64) ARCH="x86_64" ;;
315 aarch64|arm64) ARCH="aarch64" ;;
316 *) die "unsupported architecture: $(uname -m). Only x86_64 and aarch64 are built." ;;
317esac
318
319TARGET="${ARCH}-unknown-linux-${FLAVOUR}"
320NAME="steid-${VERSION}-${TARGET}"
321URL="${RELEASE_BASE_URL}/v${VERSION}/${NAME}.tar.gz"
322
323say "installing Steid ${VERSION} (${TARGET}) for ${DOMAIN:-<no domain>}"
324
325# --- prerequisites ----------------------------------------------------------
326
327# git is not optional and not a runtime nicety: Steid shells out to `git init
328# --bare` to create a repository and to `git http-backend` to serve every clone
329# and push. Without it the install succeeds and the first repository fails.
330say "installing prerequisites (git, curl, ca-certificates)"
331export DEBIAN_FRONTEND=noninteractive
332apt-get update -qq
333apt-get install -y -qq --no-install-recommends git curl ca-certificates
334
335# --- download ---------------------------------------------------------------
336
337TMP="$(mktemp -d)"
338# shellcheck disable=SC2064 # $TMP is expanded now on purpose: it never changes.
339trap "rm -rf '$TMP'" EXIT INT TERM
340
341if [ -n "$TARBALL" ]; then
342 [ -f "$TARBALL" ] || die "--tarball: no such file: ${TARBALL}"
343 say "installing from ${TARBALL}"
344 cp "$TARBALL" "${TMP}/${NAME}.tar.gz"
345
346 # A checksum beside a local file is verified when present, but not demanded:
347 # whoever passes --tarball already chose the bytes, so refusing to proceed
348 # without a .sha256 would block the bootstrap this option exists for.
349 if [ -f "${TARBALL}.sha256" ]; then
350 say "verifying checksum"
351 # Compared by value, not with `sha256sum -c`: that matches on the filename
352 # recorded inside the .sha256, which need not be what the file is called
353 # by the time someone passes it here.
354 EXPECTED="$(cut -d" " -f1 < "${TARBALL}.sha256")"
355 ACTUAL="$(sha256sum < "${TMP}/${NAME}.tar.gz" | cut -d" " -f1)"
356 [ "$EXPECTED" = "$ACTUAL" ] \
357 || die "checksum mismatch — ${TARBALL} does not match its .sha256"
358 else
359 say "no ${TARBALL}.sha256 beside it; installing unverified"
360 fi
361else
362 say "downloading ${URL}"
363 curl -fsSL "$URL" -o "${TMP}/${NAME}.tar.gz" \
364 || die "download failed. Is version ${VERSION} published for ${TARGET}?"
365 curl -fsSL "${URL}.sha256" -o "${TMP}/${NAME}.tar.gz.sha256" \
366 || die "checksum file missing next to the tarball; refusing to install unverified"
367
368 say "verifying checksum"
369 ( cd "$TMP" && sha256sum -c "${NAME}.tar.gz.sha256" >/dev/null ) \
370 || die "checksum mismatch — the download is corrupt or tampered with"
371fi
372
373tar -xzf "${TMP}/${NAME}.tar.gz" -C "$TMP"
374[ -x "${TMP}/${NAME}/steid" ] || die "tarball has no steid binary at ${NAME}/steid"
375# The bundle must ship and must land beside the binary: AssetBundle::load() walks
376# up from the executable looking for assets/manifest.toml and the process exits
377# at startup without it.
378[ -f "${TMP}/${NAME}/assets/manifest.toml" ] || die "tarball has no assets/manifest.toml"
379
380# --- user and directories ---------------------------------------------------
381
382if ! id "$STEID_USER" >/dev/null 2>&1; then
383 say "creating system user ${STEID_USER}"
384 # --home is the state directory: git wants a HOME, and giving it the one
385 # directory the service can write keeps that from being a surprise later.
386 useradd --system --home-dir "$STATE_DIR" --shell /usr/sbin/nologin "$STEID_USER"
387fi
388
389mkdir -p "$INSTALL_DIR" "$STATE_DIR" "$CONF_DIR"
390# State is exactly two things: the SQLite database file and the repository
391# directory. Both live here, and together they are the entire backup surface.
392mkdir -p "${STATE_DIR}/repos"
393chown -R "${STEID_USER}:${STEID_USER}" "$STATE_DIR"
394chmod 750 "$STATE_DIR"
395
396# --- install files ----------------------------------------------------------
397
398# Stop before replacing the binary: overwriting a running executable in place
399# fails with ETXTBSY, and a half-swapped install/assets pair would serve stale
400# hashed CSS until the next restart anyway.
401if systemctl is-active --quiet steid 2>/dev/null; then
402 say "stopping steid for the upgrade"
403 systemctl stop steid
404fi
405
406say "installing to ${INSTALL_DIR}"
407install -m 0755 "${TMP}/${NAME}/steid" "${INSTALL_DIR}/steid"
408rm -rf "${INSTALL_DIR}/assets"
409cp -R "${TMP}/${NAME}/assets" "${INSTALL_DIR}/assets"
410if [ -f "${TMP}/${NAME}/README.md" ]; then
411 cp "${TMP}/${NAME}/README.md" "${INSTALL_DIR}/README.md"
412fi
413chown -R root:root "$INSTALL_DIR"
414# Read-only to the service user on purpose: Steid never writes here.
415chmod -R a+rX "$INSTALL_DIR"
416
417# --- configuration ----------------------------------------------------------
418
419# Written once and then left alone, so an upgrade cannot silently revert a
420# setting someone deliberately changed.
421# Whether this run wrote the env file, which is also whether the owner flags did
422# anything: they are only ever written on the first write, like every other
423# setting here.
424ENV_WRITTEN=0
425if [ ! -f "${CONF_DIR}/steid.env" ]; then
426 ENV_WRITTEN=1
427 say "writing ${CONF_DIR}/steid.env"
428 cat > "${CONF_DIR}/steid.env" <<EOF
429# Steid configuration. Restart after editing: systemctl restart steid
430
431# All state lives under ${STATE_DIR}. SQLite writes -wal and -shm siblings, so
432# the directory must be writable, not just the file.
433STEID_DATABASE_URL=sqlite:${STATE_DIR}/steid.db?mode=rwc
434STEID_DATA_DIR=${STATE_DIR}/repos
435
436# HOST and PORT are read by the web framework itself and are deliberately not
437# STEID_-prefixed. Loopback only: Caddy is the way in, and binding 0.0.0.0 would
438# expose plain HTTP — and therefore access tokens in cleartext — to the internet.
439HOST=127.0.0.1
440PORT=${PORT}
441
442# Caddy sits in front and appends the address it accepted the connection from to
443# X-Forwarded-For, so the rate limiters may trust that header to tell one caller
444# from another. Turn this OFF if you ever put Steid on a public port directly:
445# with nothing appending the header a caller can invent one per request and buy
446# itself a fresh rate-limit budget each time.
447STEID_TRUSTED_PROXY=true
448
449# The address this instance answers on, used by \`steid reset-password\` to print a
450# whole link. Every link built while serving is derived from the request instead,
451# so this is read by the command line and nothing else.
452STEID_PUBLIC_URL=https://${DOMAIN}
453
454# Outgoing mail, for password reset. Both are needed or neither does anything:
455# without them the forgot-password page says so and points at
456# \`steid reset-password <handle>\`, which prints a one-time link on this machine.
457# The URL carries the submission password, which is why this file is mode 640. Quote
458# any value containing spaces or angle brackets.
459# STEID_SMTP_URL=smtps://user:password@smtp.example.com:465
460# STEID_MAIL_FROM="Steid <steid@${DOMAIN}>"
461
462# Deliberately absent: STEID_INSECURE_COOKIES. It strips Secure from the session
463# cookie and exists only for plain-HTTP local development. Setting it here would
464# hand out a session cookie that any network hop can read.
465EOF
466
467 # Only when asked for, and only here — inside the "first write" branch, like
468 # everything else in this file. An upgrade must not re-seed anything, and in
469 # any case Steid ignores these the moment an owner exists.
470 if [ -n "$OWNER_EMAIL" ]; then
471 cat >> "${CONF_DIR}/steid.env" <<EOF
472
473# The owner, created on the first boot that finds this instance unclaimed. Read
474# together — Steid refuses to start with one of them set and not the other — and
475# inert from the moment an owner exists, so they can stay here for the life of
476# the instance. This is what makes an unattended install come up already claimed
477# rather than serving a setup page to whoever finds it first.
478#
479# The owner created this way has NO usable password. The way in is
480# ${INSTALL_DIR}/steid reset-password ${OWNER_HANDLE}
481# run on this machine, which prints a one-time link.
482STEID_OWNER_EMAIL=${OWNER_EMAIL}
483STEID_OWNER_HANDLE=${OWNER_HANDLE}
484EOF
485 # Beside the owner, in the same first-write branch and inert for the same
486 # reason: once an owner exists Steid reads none of these again. The display
487 # name is quoted because it may contain spaces.
488 if [ -n "$OWNER_ORG" ]; then
489 cat >> "${CONF_DIR}/steid.env" <<EOF
490# The organisation this instance is for, created at the same first boot and set
491# as the home page — so the root lands on it rather than on the owner's own
492# page. Inert once an owner exists, like the two above.
493STEID_OWNER_ORG=${OWNER_ORG}
494EOF
495 if [ -n "$OWNER_ORG_NAME" ]; then
496 cat >> "${CONF_DIR}/steid.env" <<EOF
497STEID_OWNER_ORG_NAME="${OWNER_ORG_NAME}"
498EOF
499 fi
500 fi
501 fi
502 chmod 640 "${CONF_DIR}/steid.env"
503 chown "root:${STEID_USER}" "${CONF_DIR}/steid.env"
504else
505 say "keeping existing ${CONF_DIR}/steid.env"
506 if [ -n "$OWNER_EMAIL" ]; then
507 say "--owner-email/--owner-handle/--owner-org ignored: ${CONF_DIR}/steid.env already exists"
508 fi
509fi
510
511# After the branch, so it applies to a first install and to a later run alike — and
512# before the unit is written and Steid is restarted, which is the whole point: the
513# instance must never serve with the operator surface off waiting for something to
514# come along afterwards and set this. The key is named; the value is not.
515if [ -n "$OPERATOR_TOKEN" ]; then
516 say "setting STEID_OPERATOR_TOKEN in ${CONF_DIR}/steid.env"
517 set_env_secret STEID_OPERATOR_TOKEN "$OPERATOR_TOKEN"
518fi
519
520say "writing /etc/systemd/system/steid.service"
521cat > /etc/systemd/system/steid.service <<EOF
522# Managed by install.sh. Re-running the installer rewrites this file.
523[Unit]
524Description=Steid
525After=network-online.target
526Wants=network-online.target
527
528[Service]
529Type=simple
530User=${STEID_USER}
531Group=${STEID_USER}
532WorkingDirectory=${INSTALL_DIR}
533ExecStart=${INSTALL_DIR}/steid
534EnvironmentFile=${CONF_DIR}/steid.env
535Environment=HOME=${STATE_DIR}
536Restart=on-failure
537RestartSec=2s
538
539NoNewPrivileges=true
540PrivateTmp=true
541PrivateDevices=true
542ProtectSystem=strict
543ProtectHome=true
544ProtectKernelTunables=true
545ProtectKernelModules=true
546ProtectControlGroups=true
547RestrictSUIDSGID=true
548RestrictNamespaces=true
549LockPersonality=true
550RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
551ReadWritePaths=${STATE_DIR}
552
553[Install]
554WantedBy=multi-user.target
555EOF
556
557systemctl daemon-reload
558systemctl enable --quiet steid
559say "starting steid"
560systemctl restart steid
561
562# --- scheduled backups ------------------------------------------------------
563
564if [ "$BACKUPS" = "daily" ]; then
565 say "installing the nightly backup timer"
566
567 mkdir -p "$BACKUP_DIR"
568 chown "${STEID_USER}:${STEID_USER}" "$BACKUP_DIR"
569 # 700: an archive here is every row and every private repository in one file.
570 chmod 700 "$BACKUP_DIR"
571
572 # The env file is never rewritten, so the marker is appended rather than
573 # written with the rest — and only once, so re-running is idempotent.
574 if ! grep -q '^STEID_BACKUP_MARKER=' "${CONF_DIR}/steid.env"; then
575 cat >> "${CONF_DIR}/steid.env" <<EOF
576
577# Added by install.sh --backups daily. Steid reads this file's modification
578# time to show the last automatic backup on the settings page, and nothing else
579# about it. Removing the line makes the page say "none configured".
580STEID_BACKUP_MARKER=${BACKUP_MARKER}
581EOF
582 fi
583
584 cat > /etc/systemd/system/steid-backup.service <<EOF
585# Managed by install.sh --backups daily.
586[Unit]
587Description=Steid backup
588# The backup is taken through SQLite's own VACUUM INTO, so it is consistent with
589# the service running — this deliberately does not stop Steid.
590After=steid.service
591
592[Service]
593Type=oneshot
594User=${STEID_USER}
595Group=${STEID_USER}
596WorkingDirectory=${INSTALL_DIR}
597EnvironmentFile=${CONF_DIR}/steid.env
598Environment=HOME=${STATE_DIR}
599ExecStart=${INSTALL_DIR}/steid backup ${BACKUP_DIR}
600# Pruning and the marker run only if the backup succeeded, which is the point of
601# ExecStartPost: a failed run must not look like a successful one on the page.
602# The \`;\` before touch is deliberate — an empty glob must not fail the unit.
603ExecStartPost=/bin/sh -c 'cd ${BACKUP_DIR} && ls -1t steid-*.tar.gz 2>/dev/null | tail -n +$((BACKUP_KEEP + 1)) | xargs -r rm -f; touch ${BACKUP_MARKER}'
604
605NoNewPrivileges=true
606PrivateTmp=true
607PrivateDevices=true
608ProtectSystem=strict
609ProtectHome=true
610ProtectKernelTunables=true
611ProtectKernelModules=true
612ProtectControlGroups=true
613RestrictSUIDSGID=true
614RestrictNamespaces=true
615LockPersonality=true
616RestrictAddressFamilies=AF_UNIX
617ReadWritePaths=${STATE_DIR}
618EOF
619
620 cat > /etc/systemd/system/steid-backup.timer <<'EOF'
621# Managed by install.sh --backups daily.
622[Unit]
623Description=Nightly Steid backup
624
625[Timer]
626OnCalendar=daily
627# Spread across the hour so a fleet of instances does not all gzip themselves at
628# once, and catch up after a reboot rather than skipping the night.
629RandomizedDelaySec=1h
630Persistent=true
631
632[Install]
633WantedBy=timers.target
634EOF
635
636 systemctl daemon-reload
637 systemctl enable --quiet --now steid-backup.timer
638elif [ "$BACKUPS" = "off" ]; then
639 if [ -f /etc/systemd/system/steid-backup.timer ]; then
640 say "removing the backup timer (archives in ${BACKUP_DIR} are left alone)"
641 systemctl disable --quiet --now steid-backup.timer 2>/dev/null || true
642 rm -f /etc/systemd/system/steid-backup.timer /etc/systemd/system/steid-backup.service
643 systemctl daemon-reload
644 fi
645fi
646
647# --- caddy ------------------------------------------------------------------
648
649if [ "$INSTALL_CADDY" = 1 ]; then
650 # Whether Caddy was here *before* this run decides whether /etc/caddy/Caddyfile
651 # is somebody's configuration or the one the .deb ships. It has to be sampled
652 # here, because thirty lines later the package has been installed either way.
653 CADDY_WAS_INSTALLED=1
654 if ! command -v caddy >/dev/null 2>&1; then
655 CADDY_WAS_INSTALLED=0
656 say "installing Caddy from its official apt repository"
657 apt-get install -y -qq --no-install-recommends debian-keyring debian-archive-keyring apt-transport-https gnupg
658 curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
659 | gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
660 curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
661 > /etc/apt/sources.list.d/caddy-stable.list
662 apt-get update -qq
663 apt-get install -y -qq caddy
664 else
665 say "Caddy already installed"
666 fi
667
668 # NOT rewritten on upgrade. This used to be overwritten every run, which
669 # silently discarded operator edits — a www redirect added by hand vanished on
670 # the next install and took the site's www hostname with it, with nothing in the
671 # output to say so. The env file was already treated this way; the two now agree.
672 #
673 # CADDY_WAS_INSTALLED is the whole point of the second condition. The Caddy
674 # package ships its own /etc/caddy/Caddyfile — a placeholder site on :80 — so
675 # on a first install the file always exists by the time we look, and "keep
676 # what is there" quietly meant "keep the placeholder". The stranger's install
677 # then succeeded, Steid ran, and the domain served Caddy's welcome page with
678 # nothing anywhere saying why. Found in a container running the published
679 # one-liner, which is the only way it shows up: an upgrade never hits it.
680 if [ -f /etc/caddy/Caddyfile ] && [ "$FORCE_CADDYFILE" = 0 ] && [ "$CADDY_WAS_INSTALLED" = 1 ]; then
681 say "keeping existing /etc/caddy/Caddyfile (--force-caddyfile to replace)"
682 # And say so when that file cannot possibly be serving Steid, rather than
683 # leaving the operator to find out from a browser.
684 if ! grep -q "127.0.0.1:${PORT}" /etc/caddy/Caddyfile; then
685 echo "install.sh: WARNING — /etc/caddy/Caddyfile does not proxy 127.0.0.1:${PORT}," >&2
686 echo " so ${DOMAIN} will not reach Steid. Add a reverse_proxy to it (see" >&2
687 echo " deploy/Caddyfile in the source tree), or re-run with --force-caddyfile" >&2
688 echo " to have this installer write a fresh one." >&2
689 fi
690 else
691 say "writing /etc/caddy/Caddyfile for ${DOMAIN}"
692 mkdir -p /etc/caddy
693
694 WWW_BLOCK=""
695 if [ "$WWW" = 1 ]; then
696 WWW_BLOCK="
697# www redirects to the bare hostname so there is one canonical URL.
698www.${DOMAIN} {
699 redir https://${DOMAIN}{uri} permanent
700}"
701 fi
702
703 cat > /etc/caddy/Caddyfile <<EOF
704# Written by install.sh on first install only. Later runs leave it alone, so edits
705# here survive an upgrade. Use --force-caddyfile to have the installer replace it.
706#
707# Steid has no TLS of its own (Topcoat 0.5 ships none), and it authenticates git
708# over HTTP Basic — so without this proxy every push would send a personal access
709# token in cleartext. Caddy obtains and renews the certificate automatically,
710# provided ${DOMAIN} resolves here and ports 80 and 443 are open.
711${DOMAIN} {
712 reverse_proxy 127.0.0.1:${PORT} {
713 # Git's smart HTTP is a streaming protocol in both directions; buffering
714 # it turns a clone into a long silence and can stall negotiation.
715 flush_interval -1
716 }
717}
718${WWW_BLOCK}
719EOF
720 fi
721
722 systemctl enable --quiet caddy
723 systemctl reload caddy 2>/dev/null || systemctl restart caddy
724fi
725
726# --- report -----------------------------------------------------------------
727
728# A moment for the service to either come up or fall over, so the message below
729# reflects reality rather than optimism.
730sleep 2
731if ! systemctl is-active --quiet steid; then
732 echo >&2
733 echo "install.sh: steid is installed but not running. Look at:" >&2
734 echo " journalctl -u steid -n 50 --no-pager" >&2
735 exit 1
736fi
737
738if [ "$INSTALL_CADDY" = 1 ]; then
739 BASE_URL="https://${DOMAIN}"
740else
741 BASE_URL="http://127.0.0.1:${PORT} (put your own TLS proxy in front of this)"
742fi
743
744# Said only when a timer was installed, and said with the offsite caveat
745# attached: a nightly archive that never leaves the machine survives a mistake
746# and does not survive the machine.
747if [ -f /etc/systemd/system/steid-backup.timer ]; then
748 BACKUP_REPORT=" Backups nightly into ${BACKUP_DIR}, keeping ${BACKUP_KEEP}
749 systemctl list-timers steid-backup.timer
750 Take one now: ${INSTALL_DIR}/steid backup ${BACKUP_DIR}
751
752 !! These sit on this machine's disk. Copy them somewhere else — any
753 !! rclone remote will do, as a second timer or from your laptop:
754 !! rclone sync ${BACKUP_DIR} remote:steid-backups
755"
756else
757 BACKUP_REPORT=" Backups none scheduled. Re-run with --backups daily, or take one by
758 hand: ${INSTALL_DIR}/steid backup /var/backups
759"
760fi
761
762# Two different next steps, because a seeded instance has no token and no setup
763# page: it is already owned, and what its owner needs is a way in rather than a
764# way to claim.
765if [ -n "$OWNER_EMAIL" ] && [ "$ENV_WRITTEN" = 1 ]; then
766 CLAIM_REPORT="This instance is already claimed: ${OWNER_HANDLE} <${OWNER_EMAIL}> was created
767at first boot, so there was never a moment when a stranger could claim it.${OWNER_ORG:+
768It is owned by the organisation ${OWNER_ORG}, which the root lands on.}
769
770 That owner has no password. Mint a one-time sign-in link on this machine:
771
772 ${INSTALL_DIR}/steid reset-password ${OWNER_HANDLE}
773
774 It works once and expires in 30 minutes, and it is as good as the password —
775 hand it over the way you would one.
776"
777else
778 CLAIM_REPORT="Next: claim the instance.
779
780 The setup token is printed to the log at startup, and ONLY while the instance
781 is unclaimed. It is held in memory, so every restart mints a new one:
782
783 journalctl -u steid --no-pager | tail -n 30
784
785 Then open ${BASE_URL}/auth/setup and paste it in.
786"
787fi
788
789cat <<EOF
790
791Steid ${VERSION} is running.
792
793 Service systemctl status steid
794 Logs journalctl -u steid -f
795 Config ${CONF_DIR}/steid.env
796 State ${STATE_DIR} (the database and the repos — back up this directory)
797${BACKUP_REPORT}
798${CLAIM_REPORT}
799To upgrade later, re-run this script with a newer --version. It replaces the
800binary and assets and leaves ${STATE_DIR} untouched.
801EOF