Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(install): Phase 3 — multi-distro abstraction, init/env detection, templated unit

Juan Denisff35375b5032
diff --git a/install.sh b/install.sh
index 57173ac7..1d7970e7 100644
--- a/install.sh
+++ b/install.sh
@@ -178,21 +178,58 @@ preflight() {
# ---------------------------------------------------------------------------
# Identify the OS family and CPU architecture
# ---------------------------------------------------------------------------
+# Pure mapping from /etc/os-release ID (+ ID_LIKE fallback) to a ServerKit
+# family. Kept as a standalone function so it is unit-testable without a real
+# /etc/os-release. Echoes: debian|fedora|rhel|suse|arch|alpine|unknown.
+os_family_from() {
+ local id="$1" id_like="$2"
+ case "$id" in
+ ubuntu|linuxmint|pop|raspbian|elementary|zorin|debian|devuan)
+ printf 'debian\n'; return ;;
+ fedora|nobara)
+ printf 'fedora\n'; return ;;
+ rocky|almalinux|rhel|centos|ol|oracle|eurolinux)
+ printf 'rhel\n'; return ;;
+ opensuse*|sles|sled|suse|sle-micro)
+ printf 'suse\n'; return ;;
+ arch|manjaro|endeavouros|cachyos)
+ printf 'arch\n'; return ;;
+ alpine)
+ printf 'alpine\n'; return ;;
+ esac
+ # Unknown ID — map via ID_LIKE to the closest supported family. Check rhel
+ # before fedora: RHEL clones advertise ID_LIKE="rhel centos fedora" and want
+ # the RHEL Docker repo, whereas a pure Fedora spin only lists "fedora".
+ case " $id_like " in
+ *debian*|*ubuntu*) printf 'debian\n' ;;
+ *rhel*|*centos*) printf 'rhel\n' ;;
+ *fedora*) printf 'fedora\n' ;;
+ *suse*) printf 'suse\n' ;;
+ *arch*) printf 'arch\n' ;;
+ *alpine*) printf 'alpine\n' ;;
+ *) printf 'unknown\n' ;;
+ esac
+}
+
identify_system() {
phase "Detecting System"
- [ -f /etc/os-release ] || halt "Cannot detect OS — /etc/os-release is missing."
- . /etc/os-release
+ local os_release="${SERVERKIT_OS_RELEASE:-/etc/os-release}"
+ [ -f "$os_release" ] || halt "Cannot detect OS — $os_release is missing."
+ . "$os_release"
- case "${ID:-}" in
- ubuntu|debian)
- OS_FAMILY="debian"; good "Detected: $PRETTY_NAME" ;;
- fedora)
- OS_FAMILY="fedora"; good "Detected: $PRETTY_NAME" ;;
- rocky|almalinux|rhel|centos)
- OS_FAMILY="rhel"; good "Detected: $PRETTY_NAME (RHEL family)" ;;
+ OS_FAMILY="$(os_family_from "${ID:-}" "${ID_LIKE:-}")"
+ case "$OS_FAMILY" in
+ unknown)
+ warn "Untested OS '${ID:-unknown}' (ID_LIKE='${ID_LIKE:-}') — continuing anyway." ;;
*)
- warn "Untested OS '${ID:-unknown}' — continuing anyway." ;;
+ if [ "${ID:-}" = "$OS_FAMILY" ] || \
+ { [ "$OS_FAMILY" = "debian" ] && [ "${ID:-}" = "ubuntu" ]; }; then
+ good "Detected: ${PRETTY_NAME:-$ID} ($OS_FAMILY family)"
+ else
+ warn "Detected: ${PRETTY_NAME:-${ID:-unknown}} — treating as '$OS_FAMILY' family."
+ fi
+ ;;
esac
ARCH=$(uname -m)
@@ -206,6 +243,9 @@ identify_system() {
# ---------------------------------------------------------------------------
# Package manager abstraction (apt / dnf / yum)
# ---------------------------------------------------------------------------
+# Detection order mirrors scripts/lib/pkg.sh. These run during the early
+# dependency phase — before the repo (and thus scripts/lib) is on disk in the
+# `curl | bash` path — so the logic is inline here and kept in sync with the lib.
choose_pkg_manager() {
if command -v apt-get &>/dev/null; then
PKG_MGR="apt"
@@ -219,25 +259,37 @@ APT_EOF
PKG_MGR="dnf"
elif command -v yum &>/dev/null; then
PKG_MGR="yum"
+ elif command -v zypper &>/dev/null; then
+ PKG_MGR="zypper"
+ elif command -v pacman &>/dev/null; then
+ PKG_MGR="pacman"
+ elif command -v apk &>/dev/null; then
+ PKG_MGR="apk"
else
- halt "No supported package manager found (need apt, dnf, or yum)."
+ halt "No supported package manager found (need apt, dnf, yum, zypper, pacman, or apk)."
fi
}
refresh_pkg_index() {
case "$PKG_MGR" in
- apt) apt-get update -y >/dev/null 2>&1 ;;
- dnf) dnf makecache --refresh >/dev/null 2>&1 ;;
- yum) yum makecache --refresh >/dev/null 2>&1 ;;
+ apt) apt-get update -y >/dev/null 2>&1 ;;
+ dnf) dnf makecache --refresh >/dev/null 2>&1 ;;
+ yum) yum makecache --refresh >/dev/null 2>&1 ;;
+ zypper) zypper --non-interactive refresh >/dev/null 2>&1 ;;
+ pacman) pacman -Sy --noconfirm >/dev/null 2>&1 ;;
+ apk) apk update >/dev/null 2>&1 ;;
esac
}
pkg_add() {
local out rc
case "$PKG_MGR" in
- apt) out=$(apt-get install -y "$@" 2>&1) ;;
- dnf) out=$(dnf install -y "$@" 2>&1) ;;
- yum) out=$(yum install -y "$@" 2>&1) ;;
+ apt) out=$(apt-get install -y "$@" 2>&1) ;;
+ dnf) out=$(dnf install -y "$@" 2>&1) ;;
+ yum) out=$(yum install -y "$@" 2>&1) ;;
+ zypper) out=$(zypper --non-interactive install "$@" 2>&1) ;;
+ pacman) out=$(pacman -S --noconfirm "$@" 2>&1) ;;
+ apk) out=$(apk add "$@" 2>&1) ;;
esac
rc=$?
if [ $rc -ne 0 ]; then
@@ -348,6 +400,13 @@ provision_python() {
fi
elif [ "$OS_FAMILY" = "fedora" ] || [ "$OS_FAMILY" = "rhel" ]; then
pkg_add python3.12 python3.12-devel || pkg_add python3.11 python3.11-devel || true
+ elif [ "$OS_FAMILY" = "suse" ]; then
+ pkg_add python311 python311-devel || pkg_add python312 python312-devel || true
+ elif [ "$OS_FAMILY" = "arch" ]; then
+ # Rolling release — `python` is already 3.11+.
+ pkg_add python || true
+ elif [ "$OS_FAMILY" = "alpine" ]; then
+ pkg_add python3 python3-dev || true
fi
# Did a distro package give us something usable?
@@ -397,13 +456,29 @@ provision_docker() {
dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo
pkg_add docker-ce docker-ce-cli containerd.io docker-compose-plugin docker-buildx-plugin
;;
+ suse)
+ pkg_add docker docker-compose
+ ;;
+ arch)
+ pkg_add docker docker-compose
+ ;;
+ alpine)
+ pkg_add docker docker-cli-compose
+ ;;
*)
curl -fsSL https://get.docker.com | sh
;;
esac
- systemctl enable docker
- systemctl start docker
+ # Enable + start across init systems (systemd on most families, OpenRC on
+ # Alpine). Guarded so a non-systemd box doesn't abort the install here.
+ if command -v systemctl &>/dev/null && [ -d /run/systemd/system ]; then
+ systemctl enable docker 2>/dev/null || true
+ systemctl start docker 2>/dev/null || true
+ elif command -v rc-update &>/dev/null; then
+ rc-update add docker default 2>/dev/null || true
+ rc-service docker start 2>/dev/null || true
+ fi
good "Docker installed."
}
@@ -891,24 +966,52 @@ install_nginx_config_for_mode() {
}
# ---------------------------------------------------------------------------
-# Server-wide TLS floor. Rewrites the ssl_protocols / ssl_ciphers lines in the
-# main nginx.conf (or injects them) so every HTTPS listener is forced onto
-# TLS 1.2/1.3 with AEAD-only ciphers. Editing nginx.conf in place -- rather than
-# adding a conf.d snippet -- avoids nginx's "duplicate ssl_protocols" error on
-# distros (Debian/Ubuntu) that already set it in http{}. Idempotent.
+# Server-wide TLS floor — force every HTTPS listener onto TLS 1.2/1.3 with
+# AEAD-only ciphers, so even the default server and non-ServerKit vhosts can't
+# negotiate weak TLS.
+#
+# Preferred: drop a self-contained /etc/nginx/conf.d/serverkit-tls.conf snippet
+# — ServerKit-owned, trivially reversible on uninstall, and never touches the
+# distro's nginx.conf. BUT a snippet is `include`d into the same http{} context,
+# so if nginx.conf ALREADY declares ssl_protocols (Debian/Ubuntu do) a second
+# declaration is a "duplicate ssl_protocols" error. In that case we fall back to
+# rewriting the existing directives in place. Idempotent either way.
# ---------------------------------------------------------------------------
harden_global_tls() {
- local conf=/etc/nginx/nginx.conf
+ local nginx_dir="${SERVERKIT_NGINX_DIR:-/etc/nginx}"
+ local conf="$nginx_dir/nginx.conf"
[ -f "$conf" ] || return 0
local ciphers='ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'
- if grep -qE '^[[:space:]]*ssl_protocols[[:space:]]' "$conf"; then
+ # Does the main config already declare these in http{}? (Debian/Ubuntu yes,
+ # RHEL/Fedora/SUSE typically no.)
+ local has_proto=0 has_ciphers=0
+ grep -qE '^[[:space:]]*ssl_protocols[[:space:]]' "$conf" && has_proto=1
+ grep -qE '^[[:space:]]*ssl_ciphers[[:space:]]' "$conf" && has_ciphers=1
+
+ # The conf.d snippet is only safe when neither directive already exists AND
+ # nginx.conf includes conf.d/*.conf inside http{} (the default on every
+ # supported family).
+ if [ "$has_proto" = "0" ] && [ "$has_ciphers" = "0" ] && \
+ grep -qE 'include[[:space:]]+/etc/nginx/conf\.d/\*\.conf' "$conf"; then
+ mkdir -p "$nginx_dir/conf.d"
+ cat > "$nginx_dir/conf.d/serverkit-tls.conf" <<EOF
+# Auto-generated by ServerKit — server-wide TLS floor. Safe to remove.
+ssl_protocols TLSv1.2 TLSv1.3;
+ssl_ciphers ${ciphers};
+EOF
+ return 0
+ fi
+
+ # Fall back to editing nginx.conf in place (a snippet would duplicate the
+ # existing directive). Remove any stale snippet we may have dropped before.
+ rm -f "$nginx_dir/conf.d/serverkit-tls.conf" 2>/dev/null || true
+ if [ "$has_proto" = "1" ]; then
sed -i -E 's|^([[:space:]]*)ssl_protocols[[:space:]].*|\1ssl_protocols TLSv1.2 TLSv1.3;|' "$conf"
else
sed -i '/http {/a \ ssl_protocols TLSv1.2 TLSv1.3;' "$conf"
fi
-
- if grep -qE '^[[:space:]]*ssl_ciphers[[:space:]]' "$conf"; then
+ if [ "$has_ciphers" = "1" ]; then
sed -i -E "s|^([[:space:]]*)ssl_ciphers[[:space:]].*|\1ssl_ciphers ${ciphers};|" "$conf"
else
sed -i "/http {/a \\ ssl_ciphers ${ciphers};" "$conf"
@@ -918,15 +1021,47 @@ harden_global_tls() {
# ---------------------------------------------------------------------------
# systemd unit + CLI symlink
# ---------------------------------------------------------------------------
+# Render the systemd unit from the template to <out>, substituting the resolved
+# install/venv/log paths so a custom SERVERKIT_DIR is honored (the old hardcoded
+# unit baked in /opt/serverkit). The unit references the /opt/serverkit symlink,
+# so blue/green switches need no re-render. Returns 1 if no template/unit exists.
+render_service_unit() {
+ local out="$1"
+ local template="$INSTALL_DIR/templates/serverkit-backend.service.in"
+ if [ -f "$template" ]; then
+ sed -e "s|@SERVERKIT_DIR@|$INSTALL_DIR|g" \
+ -e "s|@SERVERKIT_VENV_DIR@|$VENV_DIR|g" \
+ -e "s|@PORT@|5000|g" \
+ -e "s|@USER@|root|g" \
+ -e "s|@LOG_DIR@|$LOG_DIR|g" \
+ "$template" > "$out"
+ return 0
+ elif [ -f "$INSTALL_DIR/serverkit-backend.service" ]; then
+ cp "$INSTALL_DIR/serverkit-backend.service" "$out"
+ return 0
+ fi
+ return 1
+}
+
install_service() {
phase "Systemd Service"
- cp "$INSTALL_DIR/serverkit-backend.service" /etc/systemd/system/serverkit.service
+ render_service_unit /etc/systemd/system/serverkit.service || \
+ halt "No systemd unit template found at $INSTALL_DIR/templates/serverkit-backend.service.in"
chmod 644 /etc/systemd/system/serverkit.service
chmod +x "$INSTALL_DIR/serverkit"
ln -sf "$INSTALL_DIR/serverkit" /usr/local/bin/serverkit
+ # Without systemd (LXC/WSL/containers) we can't enable the unit — say so
+ # clearly instead of failing cryptically (Goal G5).
+ load_serverkit_lib env.sh || true
+ if command -v has_systemd >/dev/null 2>&1 && ! has_systemd; then
+ warn "systemd not detected — installed the unit but cannot enable/start it here."
+ warn "Start the backend with a supervisor, or run it in the foreground; see docs/ARCHITECTURE.md."
+ return 0
+ fi
+
systemctl daemon-reload
systemctl enable serverkit
good "Systemd service installed."
diff --git a/scripts/deps/manifest.yaml b/scripts/deps/manifest.yaml
new file mode 100644
index 00000000..8fa7c21f
--- /dev/null
+++ b/scripts/deps/manifest.yaml
@@ -0,0 +1,94 @@
+# ServerKit dependency manifest
+# ============================================================================
+# Declarative source of truth for the per-distro-family packages ServerKit
+# needs. The selector key is the OS *family* (derived from /etc/os-release `ID`,
+# falling back to `ID_LIKE`):
+#
+# debian → Debian, Ubuntu, Linux Mint, Pop!_OS, Raspbian, …
+# rhel → RHEL, Rocky, AlmaLinux, CentOS, Oracle Linux, …
+# fedora → Fedora (kept distinct from rhel only for the Docker repo URL)
+# suse → openSUSE Leap/Tumbleweed, SLES/SLED
+# arch → Arch, Manjaro, EndeavourOS (community-supported, best-effort)
+# alpine → Alpine (community-supported, best-effort)
+#
+# WHO READS THIS
+# --------------
+# The Python bootstrap (backend/serverkit_installer, see the hardening plan §8)
+# parses this file directly with PyYAML and installs accordingly. The bash
+# installer (install.sh) cannot parse YAML before Python itself is installed
+# (chicken-and-egg), so it mirrors these choices in its own inline logic — keep
+# the two in sync when editing. This file is therefore both the spec and the
+# documentation of what "supported distro" actually means.
+#
+# Python policy (Goal G2): accept 3.11 OR 3.12, prefer the distro package over a
+# source compile. Debian 12 ships 3.11; Ubuntu 24.04 and Fedora 40 ship 3.12;
+# RHEL 9 has 3.11 (and 3.12 on 9.4+) via CRB/EPEL; openSUSE Leap ships python311.
+
+python:
+ debian:
+ package: python3.11
+ venv_package: python3.11-venv
+ dev_package: python3.11-dev
+ ubuntu:
+ package: python3.12
+ venv_package: python3.12-venv
+ dev_package: python3.12-dev
+ # Older Ubuntu without 3.12 in the main repo falls back to this PPA.
+ fallback_ppa: ppa:deadsnakes/ppa
+ rhel:
+ package: python3.12
+ fallback_package: python3.11
+ dev_package: python3.12-devel
+ repos: [crb, epel]
+ fedora:
+ package: python3.12
+ fallback_package: python3.11
+ dev_package: python3.12-devel
+ suse:
+ package: python311
+ dev_package: python311-devel
+ arch:
+ package: python # rolling; already 3.11+
+ alpine:
+ package: python3
+ dev_package: python3-dev
+
+node:
+ # Node 18 is the floor for the Vite build. Distro nodejs on supported targets
+ # already meets it; NodeSource 20 is the fallback when it doesn't.
+ debian: { method: distro, package: nodejs, npm_package: npm, fallback: nodesource_20 }
+ ubuntu: { method: distro, package: nodejs, npm_package: npm, fallback: nodesource_20 }
+ rhel: { method: distro, package: nodejs, fallback: nodesource_20 }
+ fedora: { method: distro, package: nodejs, fallback: nodesource_20 }
+ suse: { method: distro, package: nodejs20, npm_package: npm20 }
+ arch: { method: distro, package: nodejs, npm_package: npm }
+ alpine: { method: distro, package: nodejs, npm_package: npm }
+
+docker:
+ debian: { method: get.docker.com }
+ ubuntu: { method: get.docker.com }
+ rhel: { method: repo, repo_url: "https://download.docker.com/linux/rhel/docker-ce.repo",
+ packages: [docker-ce, docker-ce-cli, containerd.io, docker-compose-plugin, docker-buildx-plugin] }
+ fedora: { method: repo, repo_url: "https://download.docker.com/linux/fedora/docker-ce.repo",
+ packages: [docker-ce, docker-ce-cli, containerd.io, docker-compose-plugin, docker-buildx-plugin] }
+ suse: { method: distro, packages: [docker, docker-compose] }
+ arch: { method: distro, packages: [docker, docker-compose] }
+ alpine: { method: distro, packages: [docker, docker-cli-compose] }
+
+base_packages:
+ debian: [git, curl, nginx, sqlite3, ca-certificates, openssl]
+ rhel: [git, curl, nginx, sqlite, ca-certificates, openssl]
+ fedora: [git, curl, nginx, sqlite, ca-certificates, openssl]
+ suse: [git, curl, nginx, sqlite3, ca-certificates, openssl]
+ arch: [git, curl, nginx, sqlite, ca-certificates, openssl]
+ alpine: [git, curl, nginx, sqlite, ca-certificates, openssl]
+
+# Package-manager + init-system per family, mirrored by scripts/lib/pkg.sh and
+# scripts/lib/init.sh (which detect at runtime rather than reading this).
+package_manager:
+ debian: apt
+ rhel: dnf # yum on EL7
+ fedora: dnf
+ suse: zypper
+ arch: pacman
+ alpine: apk
diff --git a/scripts/lib/env.sh b/scripts/lib/env.sh
new file mode 100644
index 00000000..5249e5fd
--- /dev/null
+++ b/scripts/lib/env.sh
@@ -0,0 +1,97 @@
+# shellcheck shell=bash
+#
+# scripts/lib/env.sh — runtime-environment detection for install/update.
+#
+# The installer and updater behave differently depending on where they run:
+# inside a Docker/podman/LXC container the host-level service plumbing
+# (systemctl units, firewall rules, journald) is either absent or off-limits;
+# under WSL there is usually no real init and /proc looks Linux-ish but a lot of
+# systemd assumptions break; and on a plain bare-metal/VPS box systemd is the
+# normal service manager. Rather than scatter ad-hoc `[ -f /.dockerenv ]` and
+# `command -v systemctl` checks through the scripts, we centralise the three
+# questions the rest of the tooling actually asks into named predicates so the
+# intent is obvious at the call site (`if is_container; then ...`).
+#
+# Design rules:
+# * Every check is SAFE on a non-Linux dev box (Windows/macOS): no file is
+# read without a `[ -f ]`/`[ -d ]` guard first, and nothing here aborts the
+# caller under `set -e`. Each predicate is a series of `if ... return 0; fi`
+# checks ending in a single `return 1`, so a non-matching grep maps to
+# "false" instead of leaking a failure exit status.
+# * Each predicate honours a force-override env var (checked FIRST) so unit
+# tests — and operators in weird environments — can pin the answer:
+# SERVERKIT_IS_CONTAINER / SERVERKIT_IS_WSL / SERVERKIT_HAS_SYSTEMD
+# each accept "1" (force true) or "0" (force false).
+# * The marker/probe paths are likewise overridable so tests can point at
+# fixtures instead of the real /proc and /run:
+# SERVERKIT_DOCKERENV_FILE (default /.dockerenv)
+# SERVERKIT_CONTAINERENV_FILE(default /run/.containerenv) [podman]
+# SERVERKIT_CGROUP_FILE (default /proc/1/cgroup)
+# SERVERKIT_OSRELEASE_FILE (default /proc/sys/kernel/osrelease)
+#
+# Contract (all three are predicates: return 0/true or 1/false, print nothing):
+# is_container → running inside a container?
+# is_wsl → running under Windows Subsystem for Linux?
+# has_systemd → is systemd usable as the init/service manager?
+
+# True if running inside a container (Docker, podman, LXC, systemd-nspawn, k8s).
+# Several independent signals are checked because no single one is universal:
+# Docker drops /.dockerenv, podman drops /run/.containerenv, nspawn/lxc export
+# `container=...`, and as a last resort the init cgroup line names the runtime.
+is_container() {
+ # Explicit force-override wins over any probing.
+ if [ "${SERVERKIT_IS_CONTAINER:-}" = "1" ]; then return 0; fi
+ if [ "${SERVERKIT_IS_CONTAINER:-}" = "0" ]; then return 1; fi
+
+ local dockerenv containerenv cgroup
+ dockerenv="${SERVERKIT_DOCKERENV_FILE:-/.dockerenv}"
+ containerenv="${SERVERKIT_CONTAINERENV_FILE:-/run/.containerenv}"
+ cgroup="${SERVERKIT_CGROUP_FILE:-/proc/1/cgroup}"
+
+ # Docker writes this marker into every container's root.
+ if [ -f "$dockerenv" ]; then return 0; fi
+ # podman's equivalent marker.
+ if [ -f "$containerenv" ]; then return 0; fi
+ # systemd-nspawn and many lxc setups export this into the environment.
+ if [ -n "${container:-}" ]; then return 0; fi
+ # Fall back to the PID-1 cgroup line, which names the runtime in most cases.
+ # `-a` treats the (possibly NUL-laden) /proc file as text so grep won't bail.
+ if [ -f "$cgroup" ] && grep -qaE 'docker|lxc|containerd|kubepods|podman' "$cgroup"; then
+ return 0
+ fi
+
+ return 1
+}
+
+# True under Windows Subsystem for Linux. The kernel release string is the
+# reliable tell on both WSL1 and WSL2 ("...-microsoft-standard-WSL2"), so we
+# match it case-insensitively rather than trusting any single distro quirk.
+is_wsl() {
+ if [ "${SERVERKIT_IS_WSL:-}" = "1" ]; then return 0; fi
+ if [ "${SERVERKIT_IS_WSL:-}" = "0" ]; then return 1; fi
+
+ local osrelease
+ osrelease="${SERVERKIT_OSRELEASE_FILE:-/proc/sys/kernel/osrelease}"
+
+ if [ -f "$osrelease" ] && grep -qiE 'microsoft|WSL' "$osrelease"; then
+ return 0
+ fi
+
+ return 1
+}
+
+# True if systemd is usable as the init/service manager. Both conditions matter:
+# `systemctl` must exist AND /run/systemd/system must be present — the latter is
+# created by systemd itself when it is PID 1, so its existence implies systemd is
+# actually running (not just installed). This keeps us from trying to drive
+# systemctl inside a container whose init is something else.
+has_systemd() {
+ if [ "${SERVERKIT_HAS_SYSTEMD:-}" = "1" ]; then return 0; fi
+ if [ "${SERVERKIT_HAS_SYSTEMD:-}" = "0" ]; then return 1; fi
+
+ if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then
+ return 0
+ fi
+
+ return 1
+}
diff --git a/scripts/lib/init.sh b/scripts/lib/init.sh
new file mode 100644
index 00000000..4d45f63a
--- /dev/null
+++ b/scripts/lib/init.sh
@@ -0,0 +1,235 @@
+# shellcheck shell=bash
+#
+# scripts/lib/init.sh — sourceable init-system / service-control abstraction.
+#
+# ServerKit installs and updates on a grab-bag of Linux distros, and the way you
+# start/stop/enable a long-running service differs by init system: systemd on
+# most modern boxes, OpenRC on Alpine/Gentoo, runit on Void, and plain SysV
+# init.d scripts on older or stripped-down hosts. The installer/updater must be
+# able to drive whichever one is present without the call sites caring which —
+# otherwise every script that touches the `serverkit` service would grow its own
+# `if command -v systemctl ...` ladder. This library hides that behind one small
+# verb-based API so callers say "start this service" and the right thing happens.
+#
+# Contract (these names/behaviors are depended on by callers and unit tests —
+# do not rename them or add extra public functions):
+# init_detect → echoes: systemd|openrc|runit|sysvinit|none
+# init_start <service> → start a service
+# init_stop <service> → stop a service
+# init_enable <service> → enable at boot
+# init_disable <service> → disable at boot
+# init_reload [service] → daemon-reload (no arg) / reload a service
+# init_is_active <service> → return 0 if running, 1 otherwise (no sudo)
+#
+# Honors:
+# INIT_OVERRIDE=... force the detected init system (used by unit tests)
+# INIT_DRY_RUN=1 print intended commands instead of running them
+#
+# Everything is best-effort: when no init system can be driven, the mutating
+# helpers warn loudly and return 1 rather than aborting the caller, and runit's
+# enable/disable (which is symlink-based) never aborts even if the symlink op
+# fails.
+
+# Cache of the detected init system. Populated lazily, but every public function
+# still calls init_detect so that INIT_OVERRIDE/INIT_DRY_RUN flipped per-call in
+# tests always take effect — init_detect honours the override before this cache.
+_INIT_DETECTED=""
+
+# Prepend sudo when we are not already root and sudo exists. Used only for the
+# mutating ops; init_is_active is a read and must work unprivileged.
+_init_sudo() {
+ if [ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1; then
+ printf 'sudo'
+ fi
+}
+
+# Run a privileged service command, or just print it under dry-run. Kept tiny so
+# the dry-run output is exactly the command that would otherwise execute — which
+# is what the installer unit tests assert against.
+_init_run() {
+ # Call sites pass "$(_init_sudo)" as the first arg; when root it expands to
+ # an empty string, which would otherwise show up as a stray leading space in
+ # the command line. Drop it so the printed/executed command is clean either
+ # way (and so callers never accidentally exec the empty-string "command").
+ if [ "$#" -gt 0 ] && [ -z "$1" ]; then
+ shift
+ fi
+ if [ "${INIT_DRY_RUN:-0}" = "1" ]; then
+ printf ' [init] would run: %s\n' "$*"
+ return 0
+ fi
+ # Discard the tool's own chatter here so callers don't redirect — that
+ # redirection would also swallow the dry-run line above, which the unit
+ # tests assert on.
+ "$@" >/dev/null 2>&1
+}
+
+# Detect the active init system. Order matters: systemd wins if it is PID 1, then
+# the less-common managers, falling back to SysV and finally "none".
+init_detect() {
+ if [ -n "${INIT_OVERRIDE:-}" ]; then
+ printf '%s\n' "$INIT_OVERRIDE"
+ return 0
+ fi
+ local comm=""
+ if [ -d /run/systemd/system ]; then
+ _INIT_DETECTED="systemd"; printf 'systemd\n'; return 0
+ fi
+ if [ -r /proc/1/comm ]; then
+ read -r comm < /proc/1/comm 2>/dev/null || comm=""
+ if [ "$comm" = "systemd" ]; then
+ _INIT_DETECTED="systemd"; printf 'systemd\n'; return 0
+ fi
+ fi
+ if command -v rc-service >/dev/null 2>&1; then
+ _INIT_DETECTED="openrc"; printf 'openrc\n'; return 0
+ fi
+ if command -v sv >/dev/null 2>&1 && { [ -d /etc/runit ] || [ -d /run/runit ]; }; then
+ _INIT_DETECTED="runit"; printf 'runit\n'; return 0
+ fi
+ if [ -d /etc/init.d ] || command -v service >/dev/null 2>&1; then
+ _INIT_DETECTED="sysvinit"; printf 'sysvinit\n'; return 0
+ fi
+ _INIT_DETECTED="none"; printf 'none\n'
+ return 0
+}
+
+# Print "No init system detected" and fail. Centralised so every mutating
+# function reports the same actionable message.
+_init_no_init() {
+ local action="$1" svc="$2"
+ printf ' [init] No init system detected — cannot %s %s; start it manually\n' \
+ "$action" "$svc" >&2
+ return 1
+}
+
+init_start() {
+ local svc="$1" init
+ init="$(init_detect)"
+ case "$init" in
+ systemd) _init_run "$(_init_sudo)" systemctl start "$svc" ;;
+ openrc) _init_run "$(_init_sudo)" rc-service "$svc" start ;;
+ runit) _init_run "$(_init_sudo)" sv up "$svc" ;;
+ sysvinit) _init_run "$(_init_sudo)" service "$svc" start ;;
+ *) _init_no_init "start" "$svc" ;;
+ esac
+}
+
+init_stop() {
+ local svc="$1" init
+ init="$(init_detect)"
+ case "$init" in
+ systemd) _init_run "$(_init_sudo)" systemctl stop "$svc" ;;
+ openrc) _init_run "$(_init_sudo)" rc-service "$svc" stop ;;
+ runit) _init_run "$(_init_sudo)" sv down "$svc" ;;
+ sysvinit) _init_run "$(_init_sudo)" service "$svc" stop ;;
+ *) _init_no_init "stop" "$svc" ;;
+ esac
+}
+
+init_enable() {
+ local svc="$1" init
+ init="$(init_detect)"
+ case "$init" in
+ systemd)
+ _init_run "$(_init_sudo)" systemctl enable "$svc"
+ ;;
+ openrc)
+ _init_run "$(_init_sudo)" rc-update add "$svc"
+ ;;
+ runit)
+ # runit enables a service by symlinking it into the supervised dir.
+ # Best-effort: never abort if the symlink op fails.
+ _init_run "$(_init_sudo)" ln -s "/etc/sv/$svc" "/etc/service/$svc" || true
+ ;;
+ sysvinit)
+ if command -v update-rc.d >/dev/null 2>&1; then
+ _init_run "$(_init_sudo)" update-rc.d "$svc" enable
+ elif command -v chkconfig >/dev/null 2>&1; then
+ _init_run "$(_init_sudo)" chkconfig "$svc" on
+ else
+ _init_no_init "enable" "$svc"
+ fi
+ ;;
+ *)
+ _init_no_init "enable" "$svc"
+ ;;
+ esac
+}
+
+init_disable() {
+ local svc="$1" init
+ init="$(init_detect)"
+ case "$init" in
+ systemd)
+ _init_run "$(_init_sudo)" systemctl disable "$svc"
+ ;;
+ openrc)
+ _init_run "$(_init_sudo)" rc-update del "$svc"
+ ;;
+ runit)
+ # Removing the supervised symlink disables the service. Best-effort.
+ _init_run "$(_init_sudo)" rm -f "/etc/service/$svc" || true
+ ;;
+ sysvinit)
+ if command -v update-rc.d >/dev/null 2>&1; then
+ _init_run "$(_init_sudo)" update-rc.d "$svc" disable
+ elif command -v chkconfig >/dev/null 2>&1; then
+ _init_run "$(_init_sudo)" chkconfig "$svc" off
+ else
+ _init_no_init "disable" "$svc"
+ fi
+ ;;
+ *)
+ _init_no_init "disable" "$svc"
+ ;;
+ esac
+}
+
+init_reload() {
+ local svc="${1:-}" init
+ init="$(init_detect)"
+ case "$init" in
+ systemd)
+ if [ -n "$svc" ]; then
+ _init_run "$(_init_sudo)" systemctl reload "$svc"
+ else
+ _init_run "$(_init_sudo)" systemctl daemon-reload
+ fi
+ ;;
+ openrc)
+ [ -n "$svc" ] && _init_run "$(_init_sudo)" rc-service "$svc" reload
+ return 0
+ ;;
+ runit)
+ [ -n "$svc" ] && _init_run "$(_init_sudo)" sv reload "$svc"
+ return 0
+ ;;
+ sysvinit)
+ [ -n "$svc" ] && _init_run "$(_init_sudo)" service "$svc" reload
+ return 0
+ ;;
+ *)
+ # daemon-reload has no meaning without an init system; a named reload
+ # is the only mutating intent worth warning about.
+ if [ -n "$svc" ]; then
+ _init_no_init "reload" "$svc"
+ fi
+ return 0
+ ;;
+ esac
+}
+
+# Report whether a service is currently running. Read-only: no sudo, and the
+# tool's own output is discarded so callers can rely purely on the exit status.
+init_is_active() {
+ local svc="$1" init
+ init="$(init_detect)"
+ case "$init" in
+ systemd) systemctl is-active --quiet "$svc" ;;
+ openrc) rc-service "$svc" status >/dev/null 2>&1 ;;
+ runit) sv status "$svc" >/dev/null 2>&1 ;;
+ sysvinit) service "$svc" status >/dev/null 2>&1 ;;
+ *) return 1 ;;
+ esac
+}
diff --git a/scripts/lib/pkg.sh b/scripts/lib/pkg.sh
new file mode 100644
index 00000000..9e191009
--- /dev/null
+++ b/scripts/lib/pkg.sh
@@ -0,0 +1,162 @@
+# shellcheck shell=bash
+#
+# scripts/lib/pkg.sh — sourceable cross-distro package-management abstraction.
+#
+# The ServerKit installer/updater needs to refresh the package index, install a
+# handful of OS packages, and check whether something is already present — and it
+# has to do this identically on Debian/Ubuntu (apt), RHEL/Rocky/Alma/Fedora
+# (dnf, or yum on older boxes), openSUSE (zypper), Arch (pacman) and Alpine
+# (apk). Sprinkling per-distro `if command -v apt` branches through every script
+# rots fast and is impossible to unit-test, so we centralise the dispatch here.
+#
+# This bash helper mirrors the semantics of the Python PackageManager class in
+# backend/app/utils/system.py (same detect → install/is_installed contract,
+# same sudo-only-when-needed rule) so the host and the running panel agree on
+# what "installed" means. It covers the three managers the Python side knows
+# (apt/dnf/yum) plus the three install-time-only ones (zypper/pacman/apk) that
+# the shell installer can hit before the panel is even up.
+#
+# Contract (these names/behaviours are depended on by callers and unit tests —
+# do not rename them or add extra public functions):
+# pkg_detect → echoes: apt|dnf|yum|zypper|pacman|apk|"" (none)
+# pkg_refresh → refresh the package index (best-effort)
+# pkg_install <pkg> [pkg...] → install packages non-interactively
+# pkg_is_installed <pkg> → return 0 if installed, 1 otherwise
+#
+# Honors:
+# PKG_DRY_RUN=1 print intended commands instead of running them
+# PKG_MGR_OVERRIDE=... force the detected manager (used by unit tests)
+#
+# Everything mutating is best-effort and privilege-aware: a refresh/install we
+# can't run cleanly degrades to a non-zero return rather than aborting the
+# caller, and sudo is prepended only when we are not already root.
+
+# Prepend sudo for a mutating command when we are not root AND sudo exists;
+# otherwise run the command as-is. Mirrors _needs_sudo() in system.py — minimal
+# containers run as root without sudo installed, and Windows dev boxes have no
+# sudo at all, so blindly prefixing it would break those.
+_pkg_sudo() {
+ if [ "$(id -u)" -ne 0 ] && command -v sudo >/dev/null 2>&1; then
+ sudo "$@"
+ return $?
+ fi
+ "$@"
+}
+
+# Run a (privileged) mutating package command, or just print it under dry-run.
+# Kept tiny so the dry-run output is exactly the command that would otherwise
+# execute — which is what the installer unit tests assert against.
+_pkg_run() {
+ if [ "${PKG_DRY_RUN:-0}" = "1" ]; then
+ printf ' [pkg] would run: %s\n' "$*"
+ return 0
+ fi
+ # Discard the tool's own chatter (progress bars, "Nothing to do" noise) here
+ # so callers don't redirect — that redirection would also swallow the
+ # dry-run line above, which the installer unit tests assert on.
+ _pkg_sudo "$@" >/dev/null 2>&1
+}
+
+# Detect the active package manager. Order matters and is fixed (apt first):
+# a box can have several of these binaries installed, so we pick the first that
+# is present in the documented precedence. An explicit override short-circuits
+# detection entirely — that is how the unit tests force a given manager.
+pkg_detect() {
+ if [ -n "${PKG_MGR_OVERRIDE:-}" ]; then
+ printf '%s\n' "$PKG_MGR_OVERRIDE"
+ return 0
+ fi
+ local mgr
+ for mgr in apt dnf yum zypper pacman apk; do
+ if command -v "$mgr" >/dev/null 2>&1; then
+ printf '%s\n' "$mgr"
+ return 0
+ fi
+ done
+ # No supported manager found: echo nothing (empty string).
+ printf '\n'
+ return 0
+}
+
+# Refresh the package index for the detected manager. Best-effort: index
+# refreshes routinely fail on a flaky mirror and that should not abort an
+# install, so we never propagate the manager's exit here.
+pkg_refresh() {
+ local mgr
+ mgr="$(pkg_detect)"
+ case "$mgr" in
+ apt) _pkg_run apt-get update ;;
+ dnf) _pkg_run dnf makecache --refresh ;;
+ yum) _pkg_run yum makecache ;;
+ zypper) _pkg_run zypper --non-interactive refresh ;;
+ pacman) _pkg_run pacman -Sy --noconfirm ;;
+ apk) _pkg_run apk update ;;
+ *) return 0 ;;
+ esac
+}
+
+# Install one or more packages non-interactively for the detected manager.
+# Propagates the manager's non-zero exit on failure (callers want to know an
+# install failed); returns 1 with a stderr note when no manager was detected.
+pkg_install() {
+ if [ "$#" -eq 0 ]; then
+ return 0
+ fi
+ local mgr
+ mgr="$(pkg_detect)"
+ case "$mgr" in
+ # Deliberate word-splitting of the package list via "$@" — each argument
+ # is already a separate, individually-quoted package name.
+ apt) _pkg_run apt-get install -y "$@" ;;
+ dnf) _pkg_run dnf install -y "$@" ;;
+ yum) _pkg_run yum install -y "$@" ;;
+ zypper) _pkg_run zypper --non-interactive install "$@" ;;
+ pacman) _pkg_run pacman -S --noconfirm "$@" ;;
+ apk) _pkg_run apk add "$@" ;;
+ *)
+ printf ' [pkg] no supported package manager found — cannot install: %s\n' "$*" >&2
+ return 1
+ ;;
+ esac
+}
+
+# Return 0 if <pkg> is installed, 1 otherwise. Query-only (no sudo): we use the
+# distro's low-level package database rather than the high-level manager so the
+# answer matches what an install would see. Each branch tolerates the query tool
+# being absent (it returns non-zero / 1 rather than aborting the caller).
+pkg_is_installed() {
+ local pkg="$1"
+ local mgr
+ mgr="$(pkg_detect)"
+ case "$mgr" in
+ apt)
+ # dpkg can report a removed-but-configured package with returncode 0,
+ # so additionally require the "install ok installed" status line —
+ # matching PackageManager.is_installed() in system.py.
+ local out
+ if ! command -v dpkg >/dev/null 2>&1; then
+ return 1
+ fi
+ out="$(dpkg -s "$pkg" 2>/dev/null)" || return 1
+ case "$out" in
+ *'install ok installed'*) return 0 ;;
+ *) return 1 ;;
+ esac
+ ;;
+ dnf|yum|zypper)
+ command -v rpm >/dev/null 2>&1 || return 1
+ rpm -q "$pkg" >/dev/null 2>&1
+ ;;
+ pacman)
+ command -v pacman >/dev/null 2>&1 || return 1
+ pacman -Q "$pkg" >/dev/null 2>&1
+ ;;
+ apk)
+ command -v apk >/dev/null 2>&1 || return 1
+ apk info -e "$pkg" >/dev/null 2>&1
+ ;;
+ *)
+ return 1
+ ;;
+ esac
+}
diff --git a/scripts/test/test_install.sh b/scripts/test/test_install.sh
index 28904836..cba91e51 100644
--- a/scripts/test/test_install.sh
+++ b/scripts/test/test_install.sh
@@ -206,6 +206,75 @@ else
bad "uninstall --keep-data removed the config dir"
fi
+# --------------------------------------------------------------------------
+# T8 — os_family_from: ID mapping + ID_LIKE fallback (incl. rhel-before-fedora).
+# --------------------------------------------------------------------------
+fam_ok=1
+check_fam() { # check_fam <id> <id_like> <expected>
+ local got; got="$(os_family_from "$1" "$2")"
+ [ "$got" = "$3" ] || { bad "os_family_from('$1','$2') -> [$got], expected $3"; fam_ok=0; }
+}
+check_fam ubuntu "" debian
+check_fam debian "" debian
+check_fam rocky "" rhel
+check_fam fedora "" fedora
+check_fam opensuse-leap "" suse
+check_fam arch "" arch
+check_fam alpine "" alpine
+check_fam mydistro "debian" debian # unknown ID, debian-like
+check_fam clone "rhel centos fedora" rhel # RHEL clone: rhel wins over fedora
+check_fam spin "fedora" fedora # pure fedora spin
+check_fam suselike "suse opensuse" suse
+check_fam wat "" unknown
+[ "$fam_ok" = "1" ] && ok "os_family_from maps known IDs and falls back to ID_LIKE (rhel before fedora)"
+
+# --------------------------------------------------------------------------
+# T9 — render_service_unit honors a custom SERVERKIT_DIR (no @PLACEHOLDERS@).
+# --------------------------------------------------------------------------
+inst2="$WORK/custom/srv"
+mkdir -p "$inst2/templates"
+cp "$REPO_DIR/templates/serverkit-backend.service.in" "$inst2/templates/"
+unit_out="$WORK/rendered.service"
+(
+ set -Eeuo pipefail
+ INSTALL_DIR="$inst2"; VENV_DIR="$inst2/venv"; LOG_DIR="/var/log/serverkit"
+ render_service_unit "$unit_out"
+)
+if grep -q "WorkingDirectory=$inst2/backend" "$unit_out" && \
+ grep -q "$inst2/venv/bin/gunicorn" "$unit_out" && \
+ ! grep -q '@SERVERKIT_DIR@\|@SERVERKIT_VENV_DIR@\|@PORT@' "$unit_out"; then
+ ok "render_service_unit substitutes a custom SERVERKIT_DIR and leaves no placeholders"
+else
+ bad "render_service_unit left placeholders or used the wrong paths"
+fi
+
+# --------------------------------------------------------------------------
+# T10 — harden_global_tls: conf.d snippet when safe, in-place edit otherwise.
+# --------------------------------------------------------------------------
+# (A) RHEL-style: no ssl_protocols, has conf.d include → reversible snippet.
+ndA="$WORK/nginxA"; mkdir -p "$ndA/conf.d"
+printf 'http {\n include /etc/nginx/conf.d/*.conf;\n}\n' > "$ndA/nginx.conf"
+( set -Eeuo pipefail; SERVERKIT_NGINX_DIR="$ndA" harden_global_tls )
+if [ -f "$ndA/conf.d/serverkit-tls.conf" ] && \
+ grep -q 'TLSv1.2 TLSv1.3' "$ndA/conf.d/serverkit-tls.conf" && \
+ ! grep -q 'ssl_protocols' "$ndA/nginx.conf"; then
+ ok "harden_global_tls drops a reversible conf.d snippet when nginx.conf has none"
+else
+ bad "harden_global_tls should have written a conf.d snippet (RHEL-style)"
+fi
+
+# (B) Debian-style: ssl_protocols already present → edit in place, NO snippet
+# (a second declaration would be a 'duplicate ssl_protocols' error).
+ndB="$WORK/nginxB"; mkdir -p "$ndB/conf.d"
+printf 'http {\n ssl_protocols TLSv1.1 TLSv1.2;\n include /etc/nginx/conf.d/*.conf;\n}\n' > "$ndB/nginx.conf"
+( set -Eeuo pipefail; SERVERKIT_NGINX_DIR="$ndB" harden_global_tls )
+if [ ! -f "$ndB/conf.d/serverkit-tls.conf" ] && \
+ grep -q 'ssl_protocols TLSv1.2 TLSv1.3;' "$ndB/nginx.conf"; then
+ ok "harden_global_tls edits nginx.conf in place (no duplicate) when ssl_protocols exists"
+else
+ bad "harden_global_tls should have edited in place (Debian-style)"
+fi
+
# --------------------------------------------------------------------------
printf '\n%d passed, %d failed, %d skipped\n\n' "$PASS" "$FAIL" "$SKIP"
[ "$FAIL" -eq 0 ]
diff --git a/scripts/test/test_lib.sh b/scripts/test/test_lib.sh
new file mode 100644
index 00000000..7b1f91cf
--- /dev/null
+++ b/scripts/test/test_lib.sh
@@ -0,0 +1,147 @@
+#!/usr/bin/env bash
+#
+# Unit tests for the multi-distro abstraction libs:
+# scripts/lib/pkg.sh — package-manager abstraction
+# scripts/lib/init.sh — init-system / service control
+# scripts/lib/env.sh — container / WSL / systemd detection
+#
+# All three are pure, override-friendly, and dry-run aware, so they test
+# deterministically on any host (including this Windows/Git-Bash dev box)
+# without touching a real package manager, init system, or /proc.
+#
+# Run: bash scripts/test/test_lib.sh
+set -uo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+LIB_DIR="$(cd "$SCRIPT_DIR/../lib" && pwd)"
+
+PASS=0
+FAIL=0
+ok() { PASS=$((PASS + 1)); printf ' \033[32m✔\033[0m %s\n' "$1"; }
+bad() { FAIL=$((FAIL + 1)); printf ' \033[31m✘\033[0m %s\n' "$1"; }
+
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+
+# shellcheck source=/dev/null
+source "$LIB_DIR/pkg.sh"
+# shellcheck source=/dev/null
+source "$LIB_DIR/init.sh"
+# shellcheck source=/dev/null
+source "$LIB_DIR/env.sh"
+
+printf '\nmulti-distro lib unit tests\n\n'
+
+# ==========================================================================
+# pkg.sh
+# ==========================================================================
+for mgr in apt dnf yum zypper pacman apk; do
+ got="$( set -Eeuo pipefail; PKG_MGR_OVERRIDE="$mgr" pkg_detect )"
+ [ "$got" = "$mgr" ] || bad "pkg_detect override $mgr -> [$got]"
+done
+ok "pkg_detect honors PKG_MGR_OVERRIDE for all six managers"
+
+# Each manager's install command, captured in dry-run.
+declare -A expect_install=(
+ [apt]="apt-get install -y git"
+ [dnf]="dnf install -y git"
+ [yum]="yum install -y git"
+ [zypper]="zypper --non-interactive install git"
+ [pacman]="pacman -S --noconfirm git"
+ [apk]="apk add git"
+)
+allok=1
+for mgr in "${!expect_install[@]}"; do
+ out="$( set -Eeuo pipefail; PKG_DRY_RUN=1 PKG_MGR_OVERRIDE="$mgr" pkg_install git 2>&1 )"
+ printf '%s' "$out" | grep -qF "${expect_install[$mgr]}" || { bad "pkg_install $mgr dry-run: [$out]"; allok=0; }
+done
+[ "$allok" = "1" ] && ok "pkg_install emits the right command per manager (dry-run)"
+
+if ( set -Eeuo pipefail; PKG_MGR_OVERRIDE="" PKG_DRY_RUN=0 pkg_install git ) 2>/dev/null; then
+ bad "pkg_install must fail (return 1) when no manager is detected"
+else
+ ok "pkg_install returns non-zero when no package manager is present"
+fi
+
+# ==========================================================================
+# init.sh
+# ==========================================================================
+for init in systemd openrc runit sysvinit none; do
+ got="$( set -Eeuo pipefail; INIT_OVERRIDE="$init" init_detect )"
+ [ "$got" = "$init" ] || bad "init_detect override $init -> [$got]"
+done
+ok "init_detect honors INIT_OVERRIDE for all five init systems"
+
+# Start command per init, captured in dry-run (substring match — sudo prefix
+# varies with euid and is irrelevant to the assertion).
+allok=1
+check_start() { # <init> <expected-substring>
+ local out
+ out="$( set -Eeuo pipefail; INIT_OVERRIDE="$1" INIT_DRY_RUN=1 init_start serverkit 2>&1 )"
+ printf '%s' "$out" | grep -qF "$2" || { bad "init_start $1 dry-run: [$out]"; allok=0; }
+}
+check_start systemd "systemctl start serverkit"
+check_start openrc "rc-service serverkit start"
+check_start runit "sv up serverkit"
+check_start sysvinit "service serverkit start"
+[ "$allok" = "1" ] && ok "init_start emits the right command per init system (dry-run)"
+
+if ( set -Eeuo pipefail; INIT_OVERRIDE=none init_start serverkit ) >/dev/null 2>&1; then
+ bad "init_start must return non-zero under 'none'"
+else
+ ok "init_start returns non-zero (and warns) when no init system is detected"
+fi
+
+# init_reload: no service arg under systemd → daemon-reload.
+out="$( set -Eeuo pipefail; INIT_OVERRIDE=systemd INIT_DRY_RUN=1 init_reload 2>&1 )"
+if printf '%s' "$out" | grep -qF "systemctl daemon-reload"; then
+ ok "init_reload (no arg, systemd) runs daemon-reload"
+else
+ bad "init_reload systemd no-arg: [$out]"
+fi
+
+# ==========================================================================
+# env.sh
+# ==========================================================================
+cg="$WORK/cgroup"; printf '0::/system.slice/docker-abc.scope\n' > "$cg"
+if ( set -Eeuo pipefail; SERVERKIT_CGROUP_FILE="$cg" is_container ); then
+ ok "is_container true via a docker cgroup fixture"
+else
+ bad "is_container should be true for a docker cgroup"
+fi
+cg2="$WORK/cgroup-host"; printf '0::/init.scope\n' > "$cg2"
+if ( set -Eeuo pipefail; SERVERKIT_IS_CONTAINER="" SERVERKIT_CONTAINERENV_FILE="$WORK/none" SERVERKIT_DOCKERENV_FILE="$WORK/none" SERVERKIT_CGROUP_FILE="$cg2" is_container ); then
+ bad "is_container should be false on a plain host cgroup"
+else
+ ok "is_container false on a non-container cgroup"
+fi
+if ( set -Eeuo pipefail; SERVERKIT_IS_CONTAINER=1 is_container ) && \
+ ! ( set -Eeuo pipefail; SERVERKIT_IS_CONTAINER=0 is_container ); then
+ ok "is_container honors the SERVERKIT_IS_CONTAINER force-override"
+else
+ bad "is_container force-override broken"
+fi
+
+osr="$WORK/osrelease"; printf '5.15.0-microsoft-standard-WSL2\n' > "$osr"
+if ( set -Eeuo pipefail; SERVERKIT_OSRELEASE_FILE="$osr" is_wsl ); then
+ ok "is_wsl true for a microsoft/WSL osrelease fixture"
+else
+ bad "is_wsl should detect WSL"
+fi
+osr2="$WORK/osrelease-bare"; printf '6.1.0-generic\n' > "$osr2"
+if ( set -Eeuo pipefail; SERVERKIT_IS_WSL="" SERVERKIT_OSRELEASE_FILE="$osr2" is_wsl ); then
+ bad "is_wsl should be false for a non-WSL kernel"
+else
+ ok "is_wsl false for a non-WSL kernel"
+fi
+
+if ( set -Eeuo pipefail; SERVERKIT_HAS_SYSTEMD=1 has_systemd ) && \
+ ! ( set -Eeuo pipefail; SERVERKIT_HAS_SYSTEMD=0 has_systemd ); then
+ ok "has_systemd honors the SERVERKIT_HAS_SYSTEMD force-override"
+else
+ bad "has_systemd force-override broken"
+fi
+
+# --------------------------------------------------------------------------
+printf '\n%d passed, %d failed\n\n' "$PASS" "$FAIL"
+[ "$FAIL" -eq 0 ]
diff --git a/scripts/update.sh b/scripts/update.sh
index cc2e1f39..c44ab892 100644
--- a/scripts/update.sh
+++ b/scripts/update.sh
@@ -736,18 +736,35 @@ refresh_config() {
cp "$target/nginx/sites-available/serverkit-insecure.conf" "$NGINX_DIR/sites-available/"
fi
- # TLS floor
+ # TLS floor — prefer a reversible conf.d snippet when nginx.conf doesn't
+ # already declare these (a second declaration in the same http{} context is a
+ # "duplicate ssl_protocols" error); otherwise rewrite in place. Mirrors
+ # install.sh's harden_global_tls.
if [ -f "$NGINX_DIR/nginx.conf" ]; then
local ciphers='ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'
- if grep -qE '^[[:space:]]*ssl_protocols[[:space:]]' "$NGINX_DIR/nginx.conf"; then
- sed -i -E 's|^([[:space:]]*)ssl_protocols[[:space:]].*|\1ssl_protocols TLSv1.2 TLSv1.3;|' "$NGINX_DIR/nginx.conf"
- else
- sed -i '/http {/a \ ssl_protocols TLSv1.2 TLSv1.3;' "$NGINX_DIR/nginx.conf"
- fi
- if grep -qE '^[[:space:]]*ssl_ciphers[[:space:]]' "$NGINX_DIR/nginx.conf"; then
- sed -i -E "s|^([[:space:]]*)ssl_ciphers[[:space:]].*|\1ssl_ciphers ${ciphers};|" "$NGINX_DIR/nginx.conf"
+ local has_proto=0 has_ciphers=0
+ grep -qE '^[[:space:]]*ssl_protocols[[:space:]]' "$NGINX_DIR/nginx.conf" && has_proto=1
+ grep -qE '^[[:space:]]*ssl_ciphers[[:space:]]' "$NGINX_DIR/nginx.conf" && has_ciphers=1
+ if [ "$has_proto" = "0" ] && [ "$has_ciphers" = "0" ] && \
+ grep -qE 'include[[:space:]]+/etc/nginx/conf\.d/\*\.conf' "$NGINX_DIR/nginx.conf"; then
+ mkdir -p "$NGINX_DIR/conf.d"
+ cat > "$NGINX_DIR/conf.d/serverkit-tls.conf" <<EOF
+# Auto-generated by ServerKit — server-wide TLS floor. Safe to remove.
+ssl_protocols TLSv1.2 TLSv1.3;
+ssl_ciphers ${ciphers};
+EOF
else
- sed -i "/http {/a \\ ssl_ciphers ${ciphers};" "$NGINX_DIR/nginx.conf"
+ rm -f "$NGINX_DIR/conf.d/serverkit-tls.conf" 2>/dev/null || true
+ if [ "$has_proto" = "1" ]; then
+ sed -i -E 's|^([[:space:]]*)ssl_protocols[[:space:]].*|\1ssl_protocols TLSv1.2 TLSv1.3;|' "$NGINX_DIR/nginx.conf"
+ else
+ sed -i '/http {/a \ ssl_protocols TLSv1.2 TLSv1.3;' "$NGINX_DIR/nginx.conf"
+ fi
+ if [ "$has_ciphers" = "1" ]; then
+ sed -i -E "s|^([[:space:]]*)ssl_ciphers[[:space:]].*|\1ssl_ciphers ${ciphers};|" "$NGINX_DIR/nginx.conf"
+ else
+ sed -i "/http {/a \\ ssl_ciphers ${ciphers};" "$NGINX_DIR/nginx.conf"
+ fi
fi
fi
@@ -775,8 +792,19 @@ refresh_config() {
ln -sf "$NGINX_DIR/sites-available/serverkit-insecure.conf" "$NGINX_DIR/sites-enabled/serverkit.conf"
fi
- # Service unit
- if [ -f "$target/serverkit-backend.service" ]; then
+ # Service unit — render from the template so a custom SERVERKIT_DIR / venv /
+ # log path survives upgrades (the unit references the /opt/serverkit symlink,
+ # so blue/green switches need no re-render). Fall back to a plain unit if an
+ # older tree still ships one.
+ local svc_template="$target/templates/serverkit-backend.service.in"
+ if [ -f "$svc_template" ]; then
+ sed -e "s|@SERVERKIT_DIR@|$INSTALL_DIR|g" \
+ -e "s|@SERVERKIT_VENV_DIR@|$VENV_DIR|g" \
+ -e "s|@PORT@|5000|g" \
+ -e "s|@USER@|root|g" \
+ -e "s|@LOG_DIR@|$LOG_DIR|g" \
+ "$svc_template" > "$SYSTEMD_DIR/serverkit.service"
+ elif [ -f "$target/serverkit-backend.service" ]; then
cp "$target/serverkit-backend.service" "$SYSTEMD_DIR/serverkit.service"
fi
systemctl daemon-reload
diff --git a/serverkit-backend.service b/templates/serverkit-backend.service.in
similarity index 52%
rename from serverkit-backend.service
rename to templates/serverkit-backend.service.in
index 709c3fd8..6c22a6ae 100644
--- a/serverkit-backend.service
+++ b/templates/serverkit-backend.service.in
@@ -5,13 +5,13 @@ Wants=docker.service
[Service]
Type=simple
-User=root
-Group=root
-WorkingDirectory=/opt/serverkit/backend
-Environment="PATH=/opt/serverkit/venv/bin:/usr/local/bin:/usr/bin:/bin"
+User=@USER@
+Group=@USER@
+WorkingDirectory=@SERVERKIT_DIR@/backend
+Environment="PATH=@SERVERKIT_VENV_DIR@/bin:/usr/local/bin:/usr/bin:/bin"
Environment="FLASK_ENV=production"
-EnvironmentFile=/opt/serverkit/.env
-ExecStart=/opt/serverkit/venv/bin/gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 -b 0.0.0.0:5000 --timeout 120 --access-logfile /var/log/serverkit/access.log --error-logfile /var/log/serverkit/error.log run:app
+EnvironmentFile=@SERVERKIT_DIR@/.env
+ExecStart=@SERVERKIT_VENV_DIR@/bin/gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 -b 0.0.0.0:@PORT@ --timeout 120 --access-logfile @LOG_DIR@/access.log --error-logfile @LOG_DIR@/error.log run:app
ExecReload=/bin/kill -HUP $MAINPID
Restart=always
RestartSec=5