Files
ShellBook/deploy/install.sh
T
Florian Schmidt 936abbef9d feat(deploy): install the update trigger units (#15)
shellbook-update.path starts the oneshot shellbook-update.service, which
runs the fixed root-owned updater and logs to /var/log/shellbook-update.log.
2026-11-16 15:31:01 +01:00

219 lines
10 KiB
Bash
Executable File

#!/usr/bin/env bash
# Installs ShellBook on Debian 13, or updates an existing installation (rerunnable).
# Keeps env, password, workspace, SSH key, Claude login and session secret.
# Also installs `shellbook-update`, which reruns this installer fetched over HTTPS.
set -euo pipefail
[[ $EUID == 0 ]] || { echo 'Run as root inside Debian 13' >&2; exit 1; }
# `pct exec` starts with PATH=/sbin:/bin:/usr/sbin:/usr/bin; Node and pnpm live in /usr/local/bin.
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# shellcheck source=/dev/null
source /etc/os-release
[[ $ID == debian && $VERSION_ID == 13 ]] || { echo 'Debian 13 required' >&2; exit 1; }
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y ca-certificates git curl jq tmux build-essential python3 unattended-upgrades openssh-client xz-utils
# Official Node binaries, verified against the SHA-256 manifest over HTTPS.
case $(dpkg --print-architecture) in
amd64) node_arch=x64 ;;
arm64) node_arch=arm64 ;;
*) echo 'Unsupported Node binary architecture' >&2; exit 1 ;;
esac
node_temp=$(mktemp -d)
trap 'rm -rf -- "$node_temp"' EXIT
curl -fsSL https://nodejs.org/dist/latest-v22.x/SHASUMS256.txt -o "$node_temp/SHASUMS256.txt"
node_file=$(awk -v arch="$node_arch" '$2 ~ ("^node-v22\\.[0-9]+\\.[0-9]+-linux-" arch "\\.tar\\.xz$") {print $2}' "$node_temp/SHASUMS256.txt")
[[ -n $node_file && $node_file != *$'\n'* ]] || { echo 'No unique Node 22 binary found' >&2; exit 1; }
curl -fsSL "https://nodejs.org/dist/latest-v22.x/$node_file" -o "$node_temp/$node_file"
awk -v file="$node_file" '$2 == file' "$node_temp/SHASUMS256.txt" > "$node_temp/checksum"
(cd "$node_temp"; sha256sum -c checksum)
mkdir "$node_temp/unpacked"
# Root-owned: tar as root would keep the archive's uid, and cp -a would carry it into /usr/local.
tar --no-same-owner -xJf "$node_temp/$node_file" -C "$node_temp/unpacked" --strip-components=1
# Replace the executable rather than truncating one a running service uses.
install -m 0755 "$node_temp/unpacked/bin/node" /usr/local/bin/node
rm "$node_temp/unpacked/bin/node"
cp -a "$node_temp/unpacked/." /usr/local/
rm -rf -- "$node_temp"
trap - EXIT
[[ $(node --version) == v22.* ]] || { echo 'Node 22 required' >&2; exit 1; }
# Pin a current Corepack rather than relying on the binary bundled with Node.
npm install -g [email protected]
corepack enable
corepack prepare [email protected] --activate
if ! id shellbook >/dev/null 2>&1; then useradd --create-home --shell /bin/bash shellbook; fi
install -d -m 0700 -o shellbook -g shellbook /var/lib/shellbook /home/shellbook/.ssh
repo=${SHELLBOOK_REPO:-https://git.finalfactory.de/FinalFactory/ShellBook.git}
if [[ ! -e /opt/shellbook ]]; then
install -d -o shellbook -g shellbook /opt/shellbook
runuser -u shellbook -- git clone "$repo" /opt/shellbook
fi
git_app() { runuser -u shellbook -- git -C /opt/shellbook "$@"; }
if [[ -n ${SHELLBOOK_REF:-} ]]; then git_app fetch --tags origin; git_app checkout "$SHELLBOOK_REF"; fi
if git_app symbolic-ref -q HEAD >/dev/null; then git_app pull --ff-only
else echo "Not pulling: /opt/shellbook is pinned to $(git_app rev-parse --short HEAD) (SHELLBOOK_REF)"; fi
runuser -u shellbook -- bash -c 'cd /opt/shellbook; pnpm install --frozen-lockfile; pnpm build'
workspace=/home/shellbook/workspace
install -d -o shellbook -g shellbook "$workspace"
if [[ -z $(find "$workspace" -mindepth 1 -maxdepth 1 -print -quit) ]]; then
if [[ -d /opt/shellbook/templates/workspace ]]; then cp -a /opt/shellbook/templates/workspace/. "$workspace/"; fi
chown -R shellbook:shellbook "$workspace"
runuser -u shellbook -- git -C "$workspace" init
fi
# Offer each shipped notebook template once: updates bring new templates into existing
# workspaces, but never overwrite files or bring back ones the user deleted. The copy runs
# as the service user, so links inside the workspace cannot redirect a root write.
offer_templates() { # <templates dir> <workspace> <offered list>
local file rel
touch "$3"
[[ -d $1/notebooks ]] || return 0
while IFS= read -r -d '' file; do
rel=${file#"$1"/}
grep -qxF -- "$rel" "$3" && continue
runuser -u shellbook -- bash -c 'test -e "$2" || test -L "$2" || install -D -m 644 "$1" "$2"' _ "$file" "$2/$rel"
printf '%s\n' "$rel" >> "$3"
done < <(find "$1/notebooks" -type f -name '*.md' -print0 | sort -z)
}
install -d -m 0750 /etc/shellbook
offer_templates /opt/shellbook/templates/workspace "$workspace" /etc/shellbook/templates-offered
if [[ ! -f /home/shellbook/.ssh/id_ed25519 ]]; then
runuser -u shellbook -- ssh-keygen -q -t ed25519 -N '' -f /home/shellbook/.ssh/id_ed25519 -C shellbook
fi
if [[ ! -x /home/shellbook/.local/bin/claude ]]; then
runuser -u shellbook -- env HOME=/home/shellbook bash -o pipefail -c 'curl -fsSL https://claude.ai/install.sh | bash'
fi
install -d -m 0750 /etc/shellbook
# Where `shellbook-update` fetches the installer; remembered across updates.
installer_url=${SHELLBOOK_INSTALLER_URL:-$(cat /etc/shellbook/installer-url 2>/dev/null || echo https://git.finalfactory.de/FinalFactory/ShellBook/raw/branch/main/deploy/install.sh)}
[[ $installer_url =~ ^(https|file)://[^[:space:]]+$ ]] || { echo 'Invalid SHELLBOOK_INSTALLER_URL' >&2; exit 1; }
printf '%s\n' "$installer_url" > /etc/shellbook/installer-url
# Root must never execute code from /opt/shellbook: the service user (and its
# terminal panel) can write there. The updater runs the installer from the repository.
cat > /usr/local/sbin/shellbook-update <<'EOF'
#!/usr/bin/env bash
# Updates ShellBook: reruns the installer fetched from the repository.
set -euo pipefail
[[ $EUID == 0 ]] || { echo 'Run as root' >&2; exit 1; }
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
url=${SHELLBOOK_INSTALLER_URL:-$(cat /etc/shellbook/installer-url)}
installer=$(mktemp)
trap 'rm -f -- "$installer"' EXIT
curl -fsSL "$url" -o "$installer"
[[ $(head -n1 "$installer") == '#!/usr/bin/env bash' ]] || { echo "Not an installer: $url" >&2; exit 1; }
cd /
bash "$installer"
EOF
chmod 0755 /usr/local/sbin/shellbook-update
if [[ ! -f /etc/shellbook/env ]]; then
host=${SHELLBOOK_HOST:-0.0.0.0}
port=${SHELLBOOK_PORT:-8080}
proxies=${SHELLBOOK_TRUSTED_PROXIES:-}
[[ $host =~ ^[a-zA-Z0-9.:_-]+$ && $port =~ ^[0-9]+$ && $proxies =~ ^[a-zA-Z0-9.,:/_-]*$ ]] || { echo 'Invalid listen/proxy settings' >&2; exit 1; }
cat > /etc/shellbook/env <<EOF
SHELLBOOK_HOST=$host
SHELLBOOK_PORT=$port
SHELLBOOK_DATA_DIR=/var/lib/shellbook
SHELLBOOK_WORKSPACE=/home/shellbook/workspace
SHELLBOOK_SSH_KEY=/home/shellbook/.ssh/id_ed25519
SHELLBOOK_STATIC_DIR=/opt/shellbook/apps/web/dist
SHELLBOOK_TRUSTED_PROXIES=$proxies
PATH=/home/shellbook/.local/bin:/usr/local/bin:/usr/bin:/bin
EOF
fi
chmod 600 /etc/shellbook/env
# Updates from the web UI (#15). The service stays unprivileged and may only change a
# request file in its data directory; systemd then runs the fixed root-owned updater
# above. Its output goes to root-owned /var/log, readable by the service.
data_dir=$(sed -n 's/^SHELLBOOK_DATA_DIR=//p' /etc/shellbook/env)
[[ $data_dir =~ ^/[A-Za-z0-9._/-]+$ ]] || { echo 'Invalid SHELLBOOK_DATA_DIR' >&2; exit 1; }
cat > /etc/systemd/system/shellbook-update.service <<'EOF'
[Unit]
Description=Update ShellBook (requested from the web UI)
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/shellbook-update
StandardOutput=truncate:/var/log/shellbook-update.log
StandardError=inherit
TimeoutStartSec=30min
EOF
cat > /etc/systemd/system/shellbook-update.path <<EOF
[Unit]
Description=Start a ShellBook update when the web UI requests one
[Path]
PathChanged=$data_dir/update-request
Unit=shellbook-update.service
[Install]
WantedBy=paths.target
EOF
cat > /etc/systemd/system/shellbook.service <<'EOF'
[Unit]
Description=ShellBook runbook server
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=shellbook
Group=shellbook
WorkingDirectory=/opt/shellbook
EnvironmentFile=/etc/shellbook/env
ExecStart=/usr/local/bin/node /opt/shellbook/apps/server/dist/main.js
Restart=on-failure
# tmux servers started by the terminal panel must survive service restarts (spec §6).
KillMode=process
RestartSec=5
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=full
# Home and /var/lib remain writable for workspace, SSH and Claude/tmux state.
# Avoid namespace/device hardening that breaks unprivileged LXC or PTYs.
[Install]
WantedBy=multi-user.target
EOF
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOF'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
EOF
if [[ -n ${TS_AUTHKEY:-} ]]; then
curl -fsSL https://tailscale.com/install.sh | sh
key_file=$(mktemp)
trap 'rm -f "$key_file"' EXIT
chmod 600 "$key_file"
printf '%s' "$TS_AUTHKEY" > "$key_file"
tailscale up --auth-key="file:$key_file"
rm -f "$key_file"
fi
systemctl daemon-reload
systemctl enable shellbook
systemctl enable --now shellbook-update.path
systemctl restart shellbook
# Wait until the server answers before reporting success.
listen_host=$(sed -n 's/^SHELLBOOK_HOST=//p' /etc/shellbook/env)
listen_port=$(sed -n 's/^SHELLBOOK_PORT=//p' /etc/shellbook/env)
case ${listen_host:-0.0.0.0} in 0.0.0.0|::|'[::]') probe=127.0.0.1 ;; *:*) probe="[$listen_host]" ;; *) probe=$listen_host ;; esac
for ((attempt=0; attempt<60; attempt++)); do
if curl -fsS "http://$probe:${listen_port:-8080}/api/health" >/dev/null 2>&1; then break; fi
sleep 1
done
curl -fsS "http://$probe:${listen_port:-8080}/api/health" >/dev/null 2>&1 || {
echo 'ShellBook did not start; see: journalctl -u shellbook -n 50' >&2; exit 1;
}
address=$(hostname -I 2>/dev/null | awk '{print $1}')
echo
echo "ShellBook $(git_app describe --always --dirty) is running: http://${address:-<container-ip>}:${listen_port:-8080}"
if [[ -f /var/lib/shellbook/setup-token ]]; then
echo "First-time setup token (one-time, deleted after setup): $(cat /var/lib/shellbook/setup-token)"
echo 'Enter it in the browser together with your new password.'
fi
if [[ ! -f /home/shellbook/.claude/.credentials.json ]]; then
echo 'Claude is not logged in yet: Settings > "Open terminal to log in", then /login.'
fi
echo "ShellBook's SSH public key (the Hosts page can install it on your servers):"
cat /home/shellbook/.ssh/id_ed25519.pub
echo 'Update later with: shellbook-update (from the Proxmox host: pct exec <ctid> -- shellbook-update)'
echo 'Behind Traefik: see deploy/README.md for the proxy and firewall settings.'