steid

@jamesgill /

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