feat: unified launcher, multi-OS hardening, login alerts & auto-updates

Restructure around a single entry point (automations.sh) with a Gum wizard and
a self-extracting bundle for repo-less installs. Add scripts/oslib.sh so the
provisioning scripts (setup-host, harden-ssh, harden-jumphost, sshuser) run on
Alpine/Debian/Alma; seed root keys from globals/.

- ntfy SSH-login alerts (user, source IP, key, region, jump target) via pam_exec
- daily auto-updates with AUTO_REBOOT=idle (reboots only when no SSH active) and
  opt-in Alpine stable-branch upgrades
- generic + per-deployment cloud-init; Gitea release workflow on tag
- README/LICENSE/.gitignore/.gitattributes (force LF); repo URLs -> Gitea
This commit is contained in:
57_Wolve committed 2026-06-12 14:56:02 -05:00
1 parent 85eeb79971
commit 7faa9098de
58 files changed
+6225 -284

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
# Copy to .env and fill in. docker compose picks .env up automatically.
# ─── Public hostname ────────────────────────────────────────────────────────
# Bare hostname (no scheme) where beszel will be reached.
BESZEL_DOMAIN=monitoring.example.com
# Email for Let's Encrypt registration / expiry notifications.
ACME_EMAIL=admin@example.com
# Allow OIDC sign-in to auto-create user accounts on first login. Set to
# "false" if you want to manually pre-create users in the admin UI before
# anyone can log in.
USER_CREATION=true
# ─── Image tags ─────────────────────────────────────────────────────────────
BESZEL_TAG=latest
CADDY_TAG=2-alpine
+34
View File
@@ -0,0 +1,34 @@
# Caddyfile for beszel stack.
#
# Auto-issues a Let's Encrypt cert for $BESZEL_DOMAIN and reverse-proxies
# to the beszel hub on :8090. Agents and the web UI both go through this.
{
email {$ACME_EMAIL}
}
{$BESZEL_DOMAIN} {
encode zstd gzip
reverse_proxy beszel:8090 {
header_up X-Real-IP {http.request.remote.host}
# WebSocket / long-lived agent push streams.
flush_interval -1
transport http {
read_timeout 10m
write_timeout 10m
}
}
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
-Server
}
log {
output stdout
format console
}
}
+39
View File
@@ -0,0 +1,39 @@
# beszel
[Beszel](https://beszel.dev) monitoring hub behind Caddy. Agents push metrics to
the hub; OIDC sign-in is configured in the admin UI after first deploy.
## Required `.env` values
| Variable | Notes |
|----------|-------|
| `BESZEL_DOMAIN` | Public hostname (e.g. `monitoring.example.com`). |
| `ACME_EMAIL` | Let's Encrypt registration email. |
| `USER_CREATION` | `true` lets OIDC auto-create accounts on first login. |
See [`.env.example`](.env.example) for image tags.
## Deploy
```bash
./automations.sh # Deploy on this host → deploy: beszel
```
Or build + run the self-contained artifact:
```bash
./build.sh
scp deploy.sh root@host:
ssh root@host 'bash deploy.sh'
# non-interactive:
# BESZEL_DOMAIN=monitoring.example.com ACME_EMAIL=me@example.com SKIP_PROMPTS=1 bash deploy.sh
```
Unattended provisioning: [`cloud-init.yml`](cloud-init.yml).
## Notes
- No Anubis PoW gate here — it would break agent connections.
- For OIDC login, point Beszel at your [pocket-id](../pocket-id/) in the admin UI.
- DNS for `BESZEL_DOMAIN` must resolve to the host and 80/443 be reachable
before deploy.
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
#
# build.sh -- (re)embed docker-compose.yml, Caddyfile, .env.example into
# deploy.sh as a base64-encoded tar.gz payload after __ARCHIVE_BELOW__.
# Idempotent: strips any existing payload first.
set -euo pipefail
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
SCRIPT="$DIR/deploy.sh"
MARKER="__ARCHIVE_BELOW__"
[[ -f "$SCRIPT" ]] || { echo "deploy.sh not found at $SCRIPT" >&2; exit 1; }
for f in docker-compose.yml Caddyfile .env.example; do
[[ -f "$DIR/$f" ]] || { echo "Missing $DIR/$f" >&2; exit 1; }
done
PAYLOAD=$(tar -czf - -C "$DIR" docker-compose.yml Caddyfile .env.example | base64)
TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT
sed "/^${MARKER}\$/,\$d" "$SCRIPT" > "$TMP"
{
echo "$MARKER"
echo "$PAYLOAD"
} >> "$TMP"
mv "$TMP" "$SCRIPT"
chmod +x "$SCRIPT"
trap - EXIT
size=$(wc -c < "$SCRIPT")
echo "Built $SCRIPT (${size} bytes)"
+32
View File
@@ -0,0 +1,32 @@
#cloud-config
#
# Beszel (monitoring hub) — unattended deploy on a fresh Alpine host.
#
# Fill in REPO_URL and the values in the runcmd block, then paste this as the
# instance user-data. DNS for BESZEL_DOMAIN must point at this host and ports
# 80/443 must be reachable before boot, or the LE cert request fails.
# OIDC sign-in is configured afterwards in the Beszel admin UI.
packages:
- git
runcmd:
- hostnamectl set-hostname beszel || true
- |
set -e
REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git
REPO_BRANCH=main
git clone --depth 1 --branch "$REPO_BRANCH" "$REPO_URL" /opt/automations
cd /opt/automations
# Optional: install shared admin SSH keys from globals/ for root before deploy
# . scripts/lib.sh && load_globals \
# && install -d -m700 /root/.ssh && resolve_ssh_keys >> /root/.ssh/authorized_keys
# Optional: harden SSH first (prints a fresh root key — capture it!)
# SKIP_PROMPTS=1 FORCE=1 bash scripts/harden-ssh.sh
BESZEL_DOMAIN=monitoring.example.com \
ACME_EMAIL=admin@example.com \
SKIP_PROMPTS=1 \
bash deployments/beszel/deploy.sh
+293
View File
@@ -0,0 +1,293 @@
#!/usr/bin/env bash
#
# deploy.sh -- deploy the beszel stack (caddy + beszel hub) on Alpine.
#
# Single-node: runs as root.
#
# What this does:
# 1. Installs docker + docker-cli-compose if missing.
# 2. Lays down docker-compose.yml, Caddyfile, .env.example in $STACK_DIR.
# 3. Generates .env on first run; existing .env is never overwritten.
# 4. Prompts for required values not preset (BESZEL_DOMAIN, ACME_EMAIL).
# 5. Opens TCP 80/443 in UFW if active.
# 6. Pulls images, brings the stack up, waits for healthchecks.
#
# Idempotent: re-run to apply config changes / pull new images.
#
# Self-contained: docker-compose.yml, Caddyfile, .env.example are embedded
# as a base64-encoded tar.gz at the bottom of this file. Rebuild with
# build.sh after editing the loose source files.
#
# Usage:
# bash deploy.sh # interactive prompts
# BESZEL_DOMAIN=monitoring.example.com \
# ACME_EMAIL=admin@example.com FORCE=1 bash deploy.sh
# STACK_DIR=/opt/beszel bash deploy.sh
# SKIP_DOCKER_INSTALL=1 bash deploy.sh
set -euo pipefail
: "${STACK_DIR:=/srv/beszel}"
: "${SKIP_DOCKER_INSTALL:=0}"
: "${FORCE:=0}"
: "${SKIP_PROMPTS:=0}" # non-interactive: require values via env, no prompts
[[ "$SKIP_PROMPTS" == "1" ]] && FORCE=1
: "${BESZEL_DOMAIN:=}"
: "${ACME_EMAIL:=}"
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "Run as root."
# ---------------------------------------------------------------------------
# OS detection + Docker install (Alpine / Debian / Alma). This deploy.sh is
# self-contained (scp'd standalone), so the OS logic is inlined here instead
# of sourced from scripts/oslib.sh.
# ---------------------------------------------------------------------------
osfam() {
local id="" like=""
if [[ -r /etc/os-release ]]; then
id="$(. /etc/os-release 2>/dev/null && echo "${ID:-}")"
like="$(. /etc/os-release 2>/dev/null && echo "${ID_LIKE:-}")"
fi
case " $id $like " in
*" alpine "*) echo alpine ;;
*" debian "*|*" ubuntu "*) echo debian ;;
*" rhel "*|*" fedora "*|*" centos "*) echo rhel ;;
*) echo "${id:-unknown}" ;;
esac
}
install_docker() {
if command -v docker >/dev/null 2>&1; then
log "Docker already installed: $(docker --version)"
else
log "Installing Docker (OS: $(osfam))..."
case "$(osfam)" in
alpine) apk add -q docker docker-cli-compose openrc ;;
debian|rhel) command -v curl >/dev/null 2>&1 || \
{ command -v apt-get >/dev/null 2>&1 && apt-get install -y -qq curl; } || \
{ command -v dnf >/dev/null 2>&1 && dnf install -y -q curl; }
curl -fsSL https://get.docker.com | sh ;;
*) die "Unsupported OS for auto Docker install. Set SKIP_DOCKER_INSTALL=1 and install Docker yourself." ;;
esac
fi
if command -v rc-update >/dev/null 2>&1; then
rc-update add docker default >/dev/null 2>&1 || true
rc-service docker status >/dev/null 2>&1 || rc-service docker start
elif command -v systemctl >/dev/null 2>&1; then
systemctl enable --now docker >/dev/null 2>&1 || systemctl start docker || true
fi
}
open_web_ports() {
if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q '^Status: active'; then
log "ufw active -- allowing 80,443/tcp..."
ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null
elif command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
log "firewalld active -- allowing http,https..."
firewall-cmd -q --add-service=http --permanent
firewall-cmd -q --add-service=https --permanent
firewall-cmd -q --reload
fi
}
# ----------------------------------------------------------------------------
# Extract embedded archive
# ----------------------------------------------------------------------------
SCRIPT_DIR=$(mktemp -d -t beszel-deploy.XXXXXX)
trap 'rm -rf "$SCRIPT_DIR"' EXIT
extract_archive() {
grep -a -A 9999999 '^__ARCHIVE_BELOW__$' "$0" \
| tail -n +2 \
| base64 -d \
| tar -xz -C "$SCRIPT_DIR"
}
if grep -q -a '^__ARCHIVE_BELOW__$' "$0"; then
log "Extracting embedded deployment files..."
extract_archive
else
die "No embedded archive found. Run build.sh to embed deployment files."
fi
for f in docker-compose.yml Caddyfile .env.example; do
[[ -f "$SCRIPT_DIR/$f" ]] || die "Embedded archive missing $f"
done
# ----------------------------------------------------------------------------
# Prompt for required vars
# ----------------------------------------------------------------------------
prompt() {
local varname="$1" message="$2"
local -n ref="$varname"
if [[ -z "${ref:-}" ]]; then
[[ "$SKIP_PROMPTS" == "1" ]] && die "$varname required (set it in the environment; running with SKIP_PROMPTS=1)."
read -r -p "$message: " ref
[[ -n "$ref" ]] || die "$varname required."
fi
}
prompt BESZEL_DOMAIN "Public hostname for beszel (e.g. monitoring.example.com)"
prompt ACME_EMAIL "Let's Encrypt email"
# ----------------------------------------------------------------------------
# Docker
# ----------------------------------------------------------------------------
if [[ "$SKIP_DOCKER_INSTALL" != "1" ]]; then
install_docker
fi
# Open 80/443 on whichever host firewall is active.
open_web_ports
# ----------------------------------------------------------------------------
# Stack directory + files
# ----------------------------------------------------------------------------
log "Setting up $STACK_DIR..."
install -d -m 0750 "$STACK_DIR"
install -m 0640 "$SCRIPT_DIR/docker-compose.yml" "$STACK_DIR/docker-compose.yml"
install -m 0640 "$SCRIPT_DIR/Caddyfile" "$STACK_DIR/Caddyfile"
ENV_FILE="$STACK_DIR/.env"
if [[ ! -f "$ENV_FILE" ]]; then
log "Seeding $ENV_FILE..."
install -m 0600 "$SCRIPT_DIR/.env.example" "$ENV_FILE"
sed -i \
-e "s|^BESZEL_DOMAIN=.*|BESZEL_DOMAIN=${BESZEL_DOMAIN}|" \
-e "s|^ACME_EMAIL=.*|ACME_EMAIL=${ACME_EMAIL}|" \
"$ENV_FILE"
else
log ".env exists; leaving it alone."
fi
# Validate
missing=()
for var in BESZEL_DOMAIN ACME_EMAIL; do
grep -E "^${var}=.+$" "$ENV_FILE" >/dev/null || missing+=("$var")
done
(( ${#missing[@]} == 0 )) || die "Missing values in $ENV_FILE: ${missing[*]}"
# ----------------------------------------------------------------------------
# Bring up the stack
# ----------------------------------------------------------------------------
if [[ "$FORCE" != "1" ]]; then
cat <<EOF
About to pull images and start the stack from $STACK_DIR.
Caddy will request a Let's Encrypt cert for ${BESZEL_DOMAIN}. DNS for
that name must already point at this host, and ports 80/443 must be
reachable from the internet.
Continue? [y/N]
EOF
read -r ans
[[ "${ans,,}" == "y" || "${ans,,}" == "yes" ]] || { warn "Aborted."; exit 0; }
fi
cd "$STACK_DIR"
log "Pulling images..."
docker compose pull
log "Starting stack..."
docker compose up -d --remove-orphans
# ----------------------------------------------------------------------------
# Wait for health
# ----------------------------------------------------------------------------
log "Waiting for services to become healthy (up to 120s)..."
deadline=$(( $(date +%s) + 120 ))
while (( $(date +%s) < deadline )); do
status=$(docker compose ps --format '{{.Service}} {{.Health}}' 2>/dev/null || true)
unhealthy=$(echo "$status" | awk '$2 != "healthy" && $2 != "" {print $1}')
if [[ -z "$unhealthy" && -n "$status" ]]; then
log "All services healthy."
break
fi
sleep 5
done
echo
log "Stack status:"
docker compose ps
echo
cat <<EOF
================================================================
DEPLOYED
URL: https://${BESZEL_DOMAIN}
Stack dir: ${STACK_DIR}
First-time setup:
1. Open https://${BESZEL_DOMAIN} -- you'll be asked to create the first
admin account. Do this immediately so no one else can.
2. (Optional) Configure OIDC against pocket-id:
- Open https://${BESZEL_DOMAIN}/_/#/settings
- Toggle off "Hide collection create and edit controls"
- Edit the "users" collection -> Options tab -> enable OAuth2
- Add OIDC provider, redirect URI:
https://${BESZEL_DOMAIN}/api/oauth2-redirect
- Toggle controls back on
Then in pocket-id admin UI, register a new OIDC client with that
redirect URI and paste the credentials into Beszel.
3. (Optional) Once OIDC works, lock out password login: edit
docker-compose.yml, uncomment DISABLE_PASSWORD_AUTH=true, then
docker compose up -d.
Add a monitored host:
Beszel UI -> "Add System" -> follow the agent install snippet.
The agent connects back to this hub at https://${BESZEL_DOMAIN}.
Manage:
docker compose logs -f
docker compose pull && docker compose up -d # update
docker compose down # stop, keep volumes
docker compose down -v # stop, WIPE data
Or just re-run this script -- it's idempotent.
================================================================
EOF
# IMPORTANT: do not put any code below this exit. Everything after the
# __ARCHIVE_BELOW__ marker is the embedded tar.gz payload (base64).
exit 0
__ARCHIVE_BELOW__
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
8Y8AKAAA
+65
View File
@@ -0,0 +1,65 @@
# beszel stack -- caddy (TLS) + beszel hub (server monitoring).
#
# Topology:
# Browser + agents -> caddy:443 -> beszel:8090
#
# No Anubis: agents push metrics over HTTP/WebSocket and a PoW gate would
# break them. Beszel's API surface is what agents use.
#
# OIDC is configured post-deploy through the Beszel admin UI (PocketBase
# settings), not via env vars or config file. See the deploy.sh "DEPLOYED"
# block for the exact steps.
name: beszel
volumes:
beszel-data:
caddy-data:
caddy-config:
services:
caddy:
image: caddy:${CADDY_TAG:-2-alpine}
container_name: caddy
restart: unless-stopped
ports:
- "80:80"
- "443:443"
# - "443:443/udp" # HTTP/3 -- disabled (Caddy QUIC + reverse_proxy
# placeholder bug). Re-enable when fixed.
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data
- caddy-config:/config
environment:
BESZEL_DOMAIN: "${BESZEL_DOMAIN}"
ACME_EMAIL: "${ACME_EMAIL}"
depends_on:
- beszel
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:2019/config/"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
beszel:
image: henrygd/beszel:${BESZEL_TAG:-latest}
container_name: beszel
restart: unless-stopped
command: serve --http "0.0.0.0:8090"
volumes:
- beszel-data:/beszel_data
environment:
# Disable username/password auth -- force OIDC. Comment out until
# you've configured an OIDC provider in the admin UI, otherwise you
# lock yourself out on first run.
# DISABLE_PASSWORD_AUTH: "true"
# Allow OIDC to auto-create user accounts on first login.
USER_CREATION: "${USER_CREATION:-true}"
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:8090/api/health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 30s
+30
View File
@@ -0,0 +1,30 @@
# Copy to .env and fill in. docker compose picks .env up automatically.
# ─── Public hostnames ───────────────────────────────────────────────────────
# Bare hostname (no scheme) where headscale will be reached. Tailscale
# clients connect here over HTTPS.
HEADSCALE_DOMAIN=hs.example.com
# Email for Let's Encrypt registration / expiry notifications.
ACME_EMAIL=admin@example.com
# Magic-DNS suffix for nodes inside the tailnet. Example: with
# TAILNET_DOMAIN=tail.example.com, a host called "laptop" will resolve to
# laptop.tail.example.com. MUST be different from HEADSCALE_DOMAIN.
TAILNET_DOMAIN=tail.example.com
# ─── OIDC (pocket-id) ───────────────────────────────────────────────────────
# Hostname (no scheme) of your pocket-id deployment, used as the OIDC
# issuer. Must match the issuer URL pocket-id advertises at
# /.well-known/openid-configuration.
POCKETID_DOMAIN=auth.example.com
# Register a new OIDC client in pocket-id's admin UI with redirect URI:
# https://${HEADSCALE_DOMAIN}/oidc/callback
# Then paste the credentials here.
OIDC_CLIENT_ID=
OIDC_CLIENT_SECRET=
# ─── Image tags ─────────────────────────────────────────────────────────────
HEADSCALE_TAG=0.28.0
CADDY_TAG=2-alpine
+36
View File
@@ -0,0 +1,36 @@
# Caddyfile for headscale stack.
#
# Auto-issues a Let's Encrypt cert for $HEADSCALE_DOMAIN and reverse-proxies
# to headscale's HTTP listener on :8080. Tailscale clients require this
# exact hostname over HTTPS.
{
email {$ACME_EMAIL}
}
{$HEADSCALE_DOMAIN} {
encode zstd gzip
reverse_proxy headscale:8080 {
header_up X-Real-IP {http.request.remote.host}
# Long-lived noise/wireguard control streams; lift the default
# idle limit so they don't get torn down.
flush_interval -1
transport http {
read_timeout 10m
write_timeout 10m
}
}
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
-Server
}
log {
output stdout
format console
}
}
+48
View File
@@ -0,0 +1,48 @@
# headscale
[Headscale](https://headscale.net) — a self-hosted Tailscale control server —
behind Caddy, with OIDC login delegated to [pocket-id](../pocket-id/).
## Prerequisite
Register an OIDC client in pocket-id's admin UI with redirect URI:
```
https://${HEADSCALE_DOMAIN}/oidc/callback
```
Then paste its `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` below.
## Required `.env` values
| Variable | Notes |
|----------|-------|
| `HEADSCALE_DOMAIN` | Public hostname (e.g. `hs.example.com`). Clients connect here over HTTPS. |
| `ACME_EMAIL` | Let's Encrypt registration email. |
| `TAILNET_DOMAIN` | MagicDNS suffix (e.g. `tail.example.com`). Must differ from `HEADSCALE_DOMAIN`. |
| `POCKETID_DOMAIN` | OIDC issuer hostname (your pocket-id). |
| `OIDC_CLIENT_ID` / `OIDC_CLIENT_SECRET` | From the pocket-id client above. |
The deploy substitutes these into `config.yaml` from the embedded template. See
[`.env.example`](.env.example).
## Deploy
```bash
./automations.sh # Deploy on this host → deploy: headscale
```
Or build + run the self-contained artifact:
```bash
./build.sh
scp deploy.sh root@host:
ssh root@host 'bash deploy.sh'
# non-interactive: pass HEADSCALE_DOMAIN, ACME_EMAIL, TAILNET_DOMAIN,
# POCKETID_DOMAIN, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET, SKIP_PROMPTS=1
```
Unattended provisioning: [`cloud-init.yml`](cloud-init.yml).
DNS for `HEADSCALE_DOMAIN` must resolve to the host and 80/443 be reachable
before deploy.
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
#
# build.sh -- (re)embed docker-compose.yml, Caddyfile, config.yaml, and
# .env.example into deploy.sh as a base64-encoded tar.gz payload after the
# __ARCHIVE_BELOW__ marker. Idempotent: strips any existing payload first.
#
# Run after editing any of the loose files. The resulting deploy.sh is
# self-contained and can be scp'd to the target box on its own.
set -euo pipefail
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
SCRIPT="$DIR/deploy.sh"
MARKER="__ARCHIVE_BELOW__"
[[ -f "$SCRIPT" ]] || { echo "deploy.sh not found at $SCRIPT" >&2; exit 1; }
for f in docker-compose.yml Caddyfile config.yaml .env.example; do
[[ -f "$DIR/$f" ]] || { echo "Missing $DIR/$f" >&2; exit 1; }
done
PAYLOAD=$(tar -czf - -C "$DIR" \
docker-compose.yml Caddyfile config.yaml .env.example | base64)
TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT
sed "/^${MARKER}\$/,\$d" "$SCRIPT" > "$TMP"
{
echo "$MARKER"
echo "$PAYLOAD"
} >> "$TMP"
mv "$TMP" "$SCRIPT"
chmod +x "$SCRIPT"
trap - EXIT
size=$(wc -c < "$SCRIPT")
echo "Built $SCRIPT (${size} bytes)"
+36
View File
@@ -0,0 +1,36 @@
#cloud-config
#
# Headscale (Tailscale control server) — unattended deploy on fresh Alpine.
#
# Fill in REPO_URL and the values in the runcmd block, then paste this as the
# instance user-data. DNS for HEADSCALE_DOMAIN must point at this host and
# ports 80/443 reachable before boot. Requires an OIDC client pre-registered
# in your pocket-id with redirect URI https://HEADSCALE_DOMAIN/oidc/callback.
packages:
- git
runcmd:
- hostnamectl set-hostname headscale || true
- |
set -e
REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git
REPO_BRANCH=main
git clone --depth 1 --branch "$REPO_BRANCH" "$REPO_URL" /opt/automations
cd /opt/automations
# Optional: install shared admin SSH keys from globals/ for root before deploy
# . scripts/lib.sh && load_globals \
# && install -d -m700 /root/.ssh && resolve_ssh_keys >> /root/.ssh/authorized_keys
# Optional: harden SSH first (prints a fresh root key — capture it!)
# SKIP_PROMPTS=1 FORCE=1 bash scripts/harden-ssh.sh
HEADSCALE_DOMAIN=hs.example.com \
ACME_EMAIL=admin@example.com \
TAILNET_DOMAIN=tail.example.com \
POCKETID_DOMAIN=auth.example.com \
OIDC_CLIENT_ID=changeme \
OIDC_CLIENT_SECRET=changeme \
SKIP_PROMPTS=1 \
bash deployments/headscale/deploy.sh
+85
View File
@@ -0,0 +1,85 @@
# headscale config.yaml -- 0.28.0
#
# Placeholders __VAR__ are substituted at deploy time by deploy.sh from the
# values in .env. Don't set them here directly unless you're running
# headscale outside of the deploy script.
server_url: https://__HEADSCALE_DOMAIN__
listen_addr: 0.0.0.0:8080
metrics_listen_addr: 0.0.0.0:9090
# gRPC remote-control API. Disabled by default; clients use the standard
# `headscale` CLI inside the container instead. Uncomment + expose if you
# want remote admin.
# grpc_listen_addr: 0.0.0.0:50443
# grpc_allow_insecure: false
noise:
private_key_path: /var/lib/headscale/noise_private.key
prefixes:
v4: 100.64.0.0/10
v6: fd7a:115c:a1e0::/48
allocation: sequential
# DERP: use Tailscale's public DERP map. Embedded DERP server stays off so
# we don't need to open UDP/3478 publicly.
derp:
server:
enabled: false
urls:
- https://controlplane.tailscale.com/derpmap/default
paths: []
auto_update_enabled: true
update_frequency: 24h
database:
type: sqlite
sqlite:
path: /var/lib/headscale/db.sqlite
write_ahead_log: true
wal_autocheckpoint: 1000
log:
level: info
format: text
# Magic DNS for the tailnet. base_domain becomes the suffix for node
# DNS names (e.g. laptop.__TAILNET_DOMAIN__).
dns:
magic_dns: true
base_domain: __TAILNET_DOMAIN__
override_local_dns: false
nameservers:
global:
- 1.1.1.1
- 1.0.0.1
- 2606:4700:4700::1111
- 2606:4700:4700::1001
search_domains: []
extra_records: []
# OIDC: delegate authentication to the pocket-id deployment. Register a
# new OIDC client in pocket-id with redirect URI:
# https://__HEADSCALE_DOMAIN__/oidc/callback
oidc:
only_start_if_oidc_is_available: true
issuer: https://__POCKETID_DOMAIN__
client_id: __OIDC_CLIENT_ID__
client_secret: __OIDC_CLIENT_SECRET__
scope:
- openid
- profile
- email
pkce:
enabled: true
# Restrict who can register a node. Uncomment one or more.
# allowed_users:
# - alice@example.com
# allowed_groups:
# - tailscale-admins
# allowed_domains:
# - example.com
expiry:
from_authentication_path: false
refresh_period: 180d
+366
View File
@@ -0,0 +1,366 @@
#!/usr/bin/env bash
#
# deploy.sh -- deploy the headscale stack (caddy + headscale) on Alpine.
#
# Single-node, dedicated host: runs everything as root.
#
# What this does:
# 1. Installs docker + docker-cli-compose if missing.
# 2. Lays down docker-compose.yml, Caddyfile, and a substituted
# config.yaml in $STACK_DIR.
# 3. Generates .env on first run; existing .env is never overwritten.
# 4. Prompts for required values not preset (HEADSCALE_DOMAIN,
# ACME_EMAIL, TAILNET_DOMAIN, POCKETID_DOMAIN, OIDC_CLIENT_ID,
# OIDC_CLIENT_SECRET).
# 5. Substitutes those values into config.yaml from the embedded
# template.
# 6. Opens TCP 80/443 in UFW if it's installed and active (Tailscale
# clients connect on 443; LE HTTP-01 needs 80).
# 7. Pulls images, brings the stack up, waits for healthchecks.
#
# Idempotent: re-run to apply config changes / pull new images. Re-running
# regenerates config.yaml from the current .env so edits to .env propagate
# (but secrets in .env are never touched once seeded).
#
# Self-contained: docker-compose.yml, Caddyfile, config.yaml, .env.example
# are embedded as a base64-encoded tar.gz at the bottom of this file.
# Rebuild with build.sh after editing the loose source files.
#
# Usage:
# bash deploy.sh # interactive prompts
# HEADSCALE_DOMAIN=hs.example.com \
# ACME_EMAIL=admin@example.com \
# TAILNET_DOMAIN=tail.example.com \
# POCKETID_DOMAIN=auth.example.com \
# OIDC_CLIENT_ID=... OIDC_CLIENT_SECRET=... FORCE=1 bash deploy.sh
#
# STACK_DIR=/opt/headscale bash deploy.sh
# SKIP_DOCKER_INSTALL=1 bash deploy.sh
set -euo pipefail
: "${STACK_DIR:=/srv/headscale}"
: "${SKIP_DOCKER_INSTALL:=0}"
: "${FORCE:=0}"
: "${SKIP_PROMPTS:=0}" # non-interactive: require values via env, no prompts
[[ "$SKIP_PROMPTS" == "1" ]] && FORCE=1
: "${HEADSCALE_DOMAIN:=}"
: "${ACME_EMAIL:=}"
: "${TAILNET_DOMAIN:=}"
: "${POCKETID_DOMAIN:=}"
: "${OIDC_CLIENT_ID:=}"
: "${OIDC_CLIENT_SECRET:=}"
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "Run as root."
# ---------------------------------------------------------------------------
# OS detection + Docker install (Alpine / Debian / Alma). This deploy.sh is
# self-contained (scp'd standalone), so the OS logic is inlined here instead
# of sourced from scripts/oslib.sh.
# ---------------------------------------------------------------------------
osfam() {
local id="" like=""
if [[ -r /etc/os-release ]]; then
id="$(. /etc/os-release 2>/dev/null && echo "${ID:-}")"
like="$(. /etc/os-release 2>/dev/null && echo "${ID_LIKE:-}")"
fi
case " $id $like " in
*" alpine "*) echo alpine ;;
*" debian "*|*" ubuntu "*) echo debian ;;
*" rhel "*|*" fedora "*|*" centos "*) echo rhel ;;
*) echo "${id:-unknown}" ;;
esac
}
install_docker() {
if command -v docker >/dev/null 2>&1; then
log "Docker already installed: $(docker --version)"
else
log "Installing Docker (OS: $(osfam))..."
case "$(osfam)" in
alpine) apk add -q docker docker-cli-compose openrc ;;
debian|rhel) command -v curl >/dev/null 2>&1 || \
{ command -v apt-get >/dev/null 2>&1 && apt-get install -y -qq curl; } || \
{ command -v dnf >/dev/null 2>&1 && dnf install -y -q curl; }
curl -fsSL https://get.docker.com | sh ;;
*) die "Unsupported OS for auto Docker install. Set SKIP_DOCKER_INSTALL=1 and install Docker yourself." ;;
esac
fi
if command -v rc-update >/dev/null 2>&1; then
rc-update add docker default >/dev/null 2>&1 || true
rc-service docker status >/dev/null 2>&1 || rc-service docker start
elif command -v systemctl >/dev/null 2>&1; then
systemctl enable --now docker >/dev/null 2>&1 || systemctl start docker || true
fi
}
open_web_ports() {
if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q '^Status: active'; then
log "ufw active -- allowing 80,443/tcp..."
ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null
elif command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
log "firewalld active -- allowing http,https..."
firewall-cmd -q --add-service=http --permanent
firewall-cmd -q --add-service=https --permanent
firewall-cmd -q --reload
fi
}
# ----------------------------------------------------------------------------
# Extract embedded archive
# ----------------------------------------------------------------------------
SCRIPT_DIR=$(mktemp -d -t headscale-deploy.XXXXXX)
trap 'rm -rf "$SCRIPT_DIR"' EXIT
extract_archive() {
grep -a -A 9999999 '^__ARCHIVE_BELOW__$' "$0" \
| tail -n +2 \
| base64 -d \
| tar -xz -C "$SCRIPT_DIR"
}
if grep -q -a '^__ARCHIVE_BELOW__$' "$0"; then
log "Extracting embedded deployment files..."
extract_archive
else
die "No embedded archive found. Run build.sh to embed deployment files."
fi
for f in docker-compose.yml Caddyfile config.yaml .env.example; do
[[ -f "$SCRIPT_DIR/$f" ]] || die "Embedded archive missing $f"
done
# ----------------------------------------------------------------------------
# Prompt for required vars
# ----------------------------------------------------------------------------
prompt() {
local varname="$1" message="$2"
local -n ref="$varname"
if [[ -z "${ref:-}" ]]; then
[[ "$SKIP_PROMPTS" == "1" ]] && die "$varname required (set it in the environment; running with SKIP_PROMPTS=1)."
read -r -p "$message: " ref
[[ -n "$ref" ]] || die "$varname required."
fi
}
prompt HEADSCALE_DOMAIN "Public hostname for headscale (e.g. hs.example.com)"
prompt ACME_EMAIL "Let's Encrypt email"
prompt TAILNET_DOMAIN "Tailnet base domain for MagicDNS (e.g. tail.example.com)"
prompt POCKETID_DOMAIN "OIDC issuer hostname (your pocket-id, e.g. auth.example.com)"
prompt OIDC_CLIENT_ID "OIDC client_id (from pocket-id)"
prompt OIDC_CLIENT_SECRET "OIDC client_secret (from pocket-id)"
[[ "$HEADSCALE_DOMAIN" != "$TAILNET_DOMAIN" ]] \
|| die "HEADSCALE_DOMAIN and TAILNET_DOMAIN must differ."
# ----------------------------------------------------------------------------
# Docker
# ----------------------------------------------------------------------------
if [[ "$SKIP_DOCKER_INSTALL" != "1" ]]; then
install_docker
fi
# Open 80/443 on whichever host firewall is active. (Tailscale clients connect
# on 443; LE HTTP-01 needs 80. Note the IPv6-to-docker-proxy default-deny
# gotcha on ufw -- opening the ports explicitly covers it.)
open_web_ports
# ----------------------------------------------------------------------------
# Stack directory + files
# ----------------------------------------------------------------------------
log "Setting up $STACK_DIR..."
install -d -m 0750 "$STACK_DIR"
install -m 0640 "$SCRIPT_DIR/docker-compose.yml" "$STACK_DIR/docker-compose.yml"
install -m 0640 "$SCRIPT_DIR/Caddyfile" "$STACK_DIR/Caddyfile"
# .env
ENV_FILE="$STACK_DIR/.env"
if [[ ! -f "$ENV_FILE" ]]; then
log "Seeding $ENV_FILE..."
install -m 0600 "$SCRIPT_DIR/.env.example" "$ENV_FILE"
sed -i \
-e "s|^HEADSCALE_DOMAIN=.*|HEADSCALE_DOMAIN=${HEADSCALE_DOMAIN}|" \
-e "s|^ACME_EMAIL=.*|ACME_EMAIL=${ACME_EMAIL}|" \
-e "s|^TAILNET_DOMAIN=.*|TAILNET_DOMAIN=${TAILNET_DOMAIN}|" \
-e "s|^POCKETID_DOMAIN=.*|POCKETID_DOMAIN=${POCKETID_DOMAIN}|" \
-e "s|^OIDC_CLIENT_ID=.*|OIDC_CLIENT_ID=${OIDC_CLIENT_ID}|" \
-e "s|^OIDC_CLIENT_SECRET=.*|OIDC_CLIENT_SECRET=${OIDC_CLIENT_SECRET}|" \
"$ENV_FILE"
else
log ".env exists; leaving it alone."
fi
# Validate
missing=()
for var in HEADSCALE_DOMAIN ACME_EMAIL TAILNET_DOMAIN POCKETID_DOMAIN \
OIDC_CLIENT_ID OIDC_CLIENT_SECRET; do
grep -E "^${var}=.+$" "$ENV_FILE" >/dev/null || missing+=("$var")
done
(( ${#missing[@]} == 0 )) || die "Missing values in $ENV_FILE: ${missing[*]}"
# Re-read final values from .env so config.yaml substitution sees what's
# actually deployed (not whatever was passed in the environment).
# shellcheck disable=SC1090
set -a; . "$ENV_FILE"; set +a
# config.yaml: regenerate every run from the template so changes to .env
# propagate. Secrets in config.yaml are derived from .env, not stored
# independently, so this is safe.
log "Generating config.yaml from template..."
install -m 0600 "$SCRIPT_DIR/config.yaml" "$STACK_DIR/config.yaml"
# Escape replacement values for sed (handle slashes/&). Headscale URLs and
# OIDC secrets can contain those.
sed_escape() { printf '%s' "$1" | sed -e 's/[\/&]/\\&/g'; }
sed -i \
-e "s/__HEADSCALE_DOMAIN__/$(sed_escape "$HEADSCALE_DOMAIN")/g" \
-e "s/__TAILNET_DOMAIN__/$(sed_escape "$TAILNET_DOMAIN")/g" \
-e "s/__POCKETID_DOMAIN__/$(sed_escape "$POCKETID_DOMAIN")/g" \
-e "s/__OIDC_CLIENT_ID__/$(sed_escape "$OIDC_CLIENT_ID")/g" \
-e "s/__OIDC_CLIENT_SECRET__/$(sed_escape "$OIDC_CLIENT_SECRET")/g" \
"$STACK_DIR/config.yaml"
# Final sanity check
grep -q '__.*__' "$STACK_DIR/config.yaml" \
&& warn "config.yaml still has un-substituted __PLACEHOLDER__ markers!" \
|| true
# ----------------------------------------------------------------------------
# Bring up the stack
# ----------------------------------------------------------------------------
if [[ "$FORCE" != "1" ]]; then
cat <<EOF
About to pull images and start the stack from $STACK_DIR.
Caddy will request a Let's Encrypt cert for ${HEADSCALE_DOMAIN}. DNS for
that name must already point at this host, and ports 80/443 must be
reachable from the internet.
In pocket-id, the OIDC client must have this redirect URI registered:
https://${HEADSCALE_DOMAIN}/oidc/callback
Continue? [y/N]
EOF
read -r ans
[[ "${ans,,}" == "y" || "${ans,,}" == "yes" ]] || { warn "Aborted."; exit 0; }
fi
cd "$STACK_DIR"
log "Pulling images..."
docker compose pull
log "Starting stack..."
docker compose up -d --remove-orphans
# ----------------------------------------------------------------------------
# Wait for health
# ----------------------------------------------------------------------------
log "Waiting for services to become healthy (up to 120s)..."
deadline=$(( $(date +%s) + 120 ))
while (( $(date +%s) < deadline )); do
status=$(docker compose ps --format '{{.Service}} {{.Health}}' 2>/dev/null || true)
unhealthy=$(echo "$status" | awk '$2 != "healthy" && $2 != "" {print $1}')
if [[ -z "$unhealthy" && -n "$status" ]]; then
log "All services healthy."
break
fi
sleep 5
done
echo
log "Stack status:"
docker compose ps
echo
cat <<EOF
================================================================
DEPLOYED
Headscale: https://${HEADSCALE_DOMAIN}
Tailnet: ${TAILNET_DOMAIN} (MagicDNS suffix)
OIDC: https://${POCKETID_DOMAIN}
Stack dir: ${STACK_DIR}
Bootstrap a user (run from $STACK_DIR):
docker compose exec headscale headscale users create alice
docker compose exec headscale headscale users list
Tailscale client login:
tailscale up --login-server https://${HEADSCALE_DOMAIN}
# Browser opens, OIDC flow via pocket-id, node registers.
CLI inside the container:
docker compose exec headscale headscale --help
docker compose exec headscale headscale nodes list
Manage:
docker compose logs -f
docker compose pull && docker compose up -d # update
docker compose down # stop, keep volumes
docker compose down -v # stop, WIPE data
Or just re-run this script -- it's idempotent.
================================================================
EOF
# IMPORTANT: do not put any code below this exit. Everything after the
# __ARCHIVE_BELOW__ marker is the embedded tar.gz payload (base64).
exit 0
__ARCHIVE_BELOW__
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
+64
View File
@@ -0,0 +1,64 @@
# headscale stack -- caddy (TLS) + headscale (Tailscale-compatible coordinator)
#
# Topology:
# Tailscale clients -> caddy:443 -> headscale:8080
#
# No Anubis here: Tailscale clients speak HTTP/2 control protocol, not HTML,
# so a PoW challenge would break them. Headscale's API surface is what
# clients hit; treat it like any other API service.
#
# OIDC login is delegated to pocket-id at $POCKETID_DOMAIN. Register a
# client there first; copy the client_id + client_secret into .env.
name: headscale
volumes:
headscale-data:
caddy-data:
caddy-config:
services:
caddy:
image: caddy:${CADDY_TAG:-2-alpine}
container_name: caddy
restart: unless-stopped
ports:
- "80:80"
- "443:443"
# - "443:443/udp" # HTTP/3 -- disabled until Caddy QUIC + reverse_proxy
# placeholder bug is fixed (X-Real-IP comes through
# empty on some streams). Re-enable later.
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data
- caddy-config:/config
environment:
HEADSCALE_DOMAIN: "${HEADSCALE_DOMAIN}"
ACME_EMAIL: "${ACME_EMAIL}"
depends_on:
headscale:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:2019/config/"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
headscale:
image: headscale/headscale:${HEADSCALE_TAG:-0.28.0}
container_name: headscale
restart: unless-stopped
command: serve
read_only: true
tmpfs:
- /var/run/headscale
volumes:
- ./config.yaml:/etc/headscale/config.yaml:ro
- headscale-data:/var/lib/headscale
healthcheck:
test: ["CMD", "headscale", "health"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
+48 -6
View File
@@ -1,9 +1,9 @@
# Caddyfile for pocket-id stack.
#
# Auto-issues a Let's Encrypt cert for $POCKETID_DOMAIN and reverse-proxies
# to anubis-pid (which forwards to pocket-id after the PoW challenge).
#
# To skip anubis, change the reverse_proxy target to `pocket-id:1411`.
# Two site blocks:
# $POCKETID_DOMAIN pocket-id (via anubis PoW gate)
# $BASE_DOMAIN /.well-known/webfinger for OIDC discovery; everything
# else redirects to $REDIRECT_URL
{
email {$ACME_EMAIL}
@@ -11,10 +11,12 @@
# acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
}
# ----------------------------------------------------------------------------
# Auth: pocket-id behind anubis
# ----------------------------------------------------------------------------
{$POCKETID_DOMAIN} {
encode zstd gzip
# Forward through anubis (PoW anti-bot) -> pocket-id.
reverse_proxy anubis-pid:8923 {
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
@@ -22,7 +24,6 @@
header_up X-Forwarded-Host {host}
}
# Sensible security headers. Adjust CSP if you embed pocket-id elsewhere.
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
@@ -37,3 +38,44 @@
format console
}
}
# ----------------------------------------------------------------------------
# Base domain: WebFinger for OIDC discovery + redirect everything else.
# Required for Tailscale's custom-OIDC setup -- the email's domain must
# serve /.well-known/webfinger pointing at the issuer.
# ----------------------------------------------------------------------------
{$BASE_DOMAIN} {
encode zstd gzip
@webfinger path /.well-known/webfinger
handle @webfinger {
header Content-Type "application/jrd+json"
header Cache-Control "public, max-age=3600"
templates
respond `{
"subject": "{{.Req.URL.Query.Get "resource"}}",
"links": [
{
"rel": "http://openid.net/specs/connect/1.0/issuer",
"href": "https://{$POCKETID_DOMAIN}"
}
]
}` 200
}
handle {
redir {$REDIRECT_URL}{uri} permanent
}
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
-Server
}
log {
output stdout
format console
}
}
+40
View File
@@ -0,0 +1,40 @@
# pocket-id
[Pocket-ID](https://pocket-id.org) OIDC provider behind Caddy, with an optional
[Anubis](https://github.com/TecharoHQ/anubis) proof-of-work anti-bot gate. The
identity provider for the other stacks (headscale, beszel, webfinger).
## Required `.env` values
| Variable | Notes |
|----------|-------|
| `POCKETID_DOMAIN` | Public hostname (e.g. `id.example.com`). |
| `ACME_EMAIL` | Let's Encrypt registration email. |
| `ENCRYPTION_KEY` | Generated on first deploy (`openssl rand -base64 32`). Losing it is unrecoverable. |
| `ANUBIS_PID_KEY` | Generated on first deploy (`openssl rand -hex 32`). |
`MAXMIND_LICENSE_KEY` (audit-log geolocation) is optional. See
[`.env.example`](.env.example) for the full list.
## Deploy
From the repo root via the launcher:
```bash
./automations.sh # Deploy on this host → deploy: pocket-id
```
Or build the self-contained artifact and run it on the host:
```bash
./build.sh # embeds files into deploy.sh
scp deploy.sh root@host: # copy to the target
ssh root@host 'bash deploy.sh' # interactive
# non-interactive:
# POCKETID_DOMAIN=id.example.com ACME_EMAIL=me@example.com SKIP_PROMPTS=1 bash deploy.sh
```
Unattended provisioning: [`cloud-init.yml`](cloud-init.yml).
DNS for `POCKETID_DOMAIN` must resolve to the host and ports 80/443 be
reachable before deploy, or the LE cert request fails.
+31
View File
@@ -0,0 +1,31 @@
#cloud-config
#
# Pocket-ID (OIDC provider) — unattended deploy on a fresh Alpine host.
#
# Fill in REPO_URL and the values in the runcmd block, then paste this as the
# instance user-data. DNS for POCKETID_DOMAIN must point at this host and
# ports 80/443 must be reachable before boot, or the LE cert request fails.
packages:
- git
runcmd:
- hostnamectl set-hostname pocket-id || true
- |
set -e
REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git
REPO_BRANCH=main
git clone --depth 1 --branch "$REPO_BRANCH" "$REPO_URL" /opt/automations
cd /opt/automations
# Optional: install shared admin SSH keys from globals/ for root before deploy
# . scripts/lib.sh && load_globals \
# && install -d -m700 /root/.ssh && resolve_ssh_keys >> /root/.ssh/authorized_keys
# Optional: harden SSH first (prints a fresh root key — capture it!)
# SKIP_PROMPTS=1 FORCE=1 bash scripts/harden-ssh.sh
POCKETID_DOMAIN=id.example.com \
ACME_EMAIL=admin@example.com \
SKIP_PROMPTS=1 \
bash deployments/pocket-id/deploy.sh
+60 -9
View File
@@ -35,6 +35,8 @@ set -euo pipefail
: "${STACK_DIR:=/srv/pocket-id}"
: "${SKIP_DOCKER_INSTALL:=0}"
: "${FORCE:=0}"
: "${SKIP_PROMPTS:=0}" # non-interactive: require values via env, no prompts
[[ "$SKIP_PROMPTS" == "1" ]] && FORCE=1
: "${POCKETID_DOMAIN:=}"
: "${ACME_EMAIL:=}"
@@ -43,7 +45,61 @@ warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "Run as root."
[[ -f /etc/alpine-release ]] || die "This script targets Alpine Linux."
# ---------------------------------------------------------------------------
# OS detection + Docker install (Alpine / Debian / Alma). This deploy.sh is
# self-contained (scp'd standalone), so the OS logic is inlined here instead
# of sourced from scripts/oslib.sh.
# ---------------------------------------------------------------------------
osfam() {
local id="" like=""
if [[ -r /etc/os-release ]]; then
id="$(. /etc/os-release 2>/dev/null && echo "${ID:-}")"
like="$(. /etc/os-release 2>/dev/null && echo "${ID_LIKE:-}")"
fi
case " $id $like " in
*" alpine "*) echo alpine ;;
*" debian "*|*" ubuntu "*) echo debian ;;
*" rhel "*|*" fedora "*|*" centos "*) echo rhel ;;
*) echo "${id:-unknown}" ;;
esac
}
install_docker() {
if command -v docker >/dev/null 2>&1; then
log "Docker already installed: $(docker --version)"
else
log "Installing Docker (OS: $(osfam))..."
case "$(osfam)" in
alpine) apk add -q docker docker-cli-compose openrc ;;
debian|rhel) command -v curl >/dev/null 2>&1 || \
{ command -v apt-get >/dev/null 2>&1 && apt-get install -y -qq curl; } || \
{ command -v dnf >/dev/null 2>&1 && dnf install -y -q curl; }
curl -fsSL https://get.docker.com | sh ;;
*) die "Unsupported OS for auto Docker install. Set SKIP_DOCKER_INSTALL=1 and install Docker yourself." ;;
esac
fi
# Enable + start under whichever init is present.
if command -v rc-update >/dev/null 2>&1; then
rc-update add docker default >/dev/null 2>&1 || true
rc-service docker status >/dev/null 2>&1 || rc-service docker start
elif command -v systemctl >/dev/null 2>&1; then
systemctl enable --now docker >/dev/null 2>&1 || systemctl start docker || true
fi
}
open_web_ports() {
# Open 80/443 on whichever host firewall is active (no-op otherwise).
if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q '^Status: active'; then
log "ufw active -- allowing 80,443/tcp..."
ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null
elif command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
log "firewalld active -- allowing http,https..."
firewall-cmd -q --add-service=http --permanent
firewall-cmd -q --add-service=https --permanent
firewall-cmd -q --reload
fi
}
# ----------------------------------------------------------------------------
# Extract embedded archive
@@ -76,6 +132,7 @@ prompt() {
local varname="$1" message="$2"
local -n ref="$varname"
if [[ -z "${ref:-}" ]]; then
[[ "$SKIP_PROMPTS" == "1" ]] && die "$varname required (set it in the environment; running with SKIP_PROMPTS=1)."
read -r -p "$message: " ref
[[ -n "$ref" ]] || die "$varname required."
fi
@@ -87,15 +144,9 @@ prompt ACME_EMAIL "Let's Encrypt email"
# Docker
# ----------------------------------------------------------------------------
if [[ "$SKIP_DOCKER_INSTALL" != "1" ]]; then
if ! command -v docker >/dev/null 2>&1; then
log "Installing docker + docker-cli-compose..."
apk add -q docker docker-cli-compose openrc
else
log "Docker already installed: $(docker --version)"
fi
rc-update add docker default >/dev/null 2>&1 || true
rc-service docker status >/dev/null 2>&1 || rc-service docker start
install_docker
fi
open_web_ports
# ----------------------------------------------------------------------------
# Stack directory + files
+250
View File
@@ -0,0 +1,250 @@
# SimpleX Relay Server Deployment
Complete automated deployment for SimpleX Chat relay servers on Alpine Linux with post-quantum SSH hardening, Tor hidden services, and encrypted backups.
## Quick Start
### 1. Clone This Repository
The installer fetches its scripts straight from this monorepo's layout:
```
automations/
├── scripts/
│ └── harden-ssh.sh # generic SSH hardening (PQ KEX + Ed25519)
├── deployments/simplex/
│ ├── deploy-simplex.sh # SMP + XFTP + Tor deployment
│ ├── backup.sh # age-encrypted backup creation
│ ├── restore.sh # disaster recovery from backup
│ ├── install-simplex.sh # master installer (cloud-init compatible)
│ ├── cloud-init.yml # example cloud-init configuration
│ └── README.md # this file
└── globals/
└── age-pubkey.txt # your age public key(s) for backups
```
Point `REPO_URL` at your fork of this repo. The installer resolves
`harden-ssh.sh` under `scripts/` and the simplex scripts under
`deployments/simplex/` automatically (overridable via `HARDEN_PATH` /
`SIMPLEX_PATH`).
### 2. Generate Backup Keys
```bash
# Generate age keypair for backups
age-keygen -o backup-private-key.txt
# Save the public key to the shared globals/ folder
echo "age1ql3z7hjy54pw3hyww5ayyfg7zqgvc7w3j2elw8zmrj2kg5sfn9aqmcac8p" > globals/age-pubkey.txt
# Store the private key securely (NOT in your repo)
cp backup-private-key.txt ~/safe-location/
```
### 3. Deploy via Cloud-Init
Create a cloud instance with this user-data:
```yaml
#cloud-config
runcmd:
- |
curl -fsSL https://git.anomalous.dev/57_Wolve/automations/raw/branch/main/deployments/simplex/install-simplex.sh | \
REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git \
DOMAIN=relay.example.com \
ACME_EMAIL=admin@example.com \
XFTP_QUOTA=100gb \
SSH_PORT=2222 \
ALLOWED_IP=1.2.3.4 \
bash
```
### 4. Manual Deployment
```bash
# On a fresh Alpine Linux host:
curl -fsSL https://git.anomalous.dev/57_Wolve/automations/raw/branch/main/deployments/simplex/install-simplex.sh | \
REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git \
DOMAIN=relay.example.com \
ACME_EMAIL=admin@example.com \
XFTP_QUOTA=50gb \
SSH_PORT=2222 \
bash
```
## Configuration Options
| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `REPO_URL` | ✅ | | Git repository URL containing deployment scripts |
| `DOMAIN` | ✅ | | Apex domain (creates smp.DOMAIN, xftp.DOMAIN) |
| `ACME_EMAIL` | ✅ | | Email for Let's Encrypt registration |
| `XFTP_QUOTA` | | 50gb | Disk quota for file storage |
| `SSH_PORT` | | 22 | SSH port (recommend changing from default) |
| `ALLOWED_IP` | | | Your IP to whitelist in sshguard |
| `KEY_TYPE` | | rsa4096 | Caddy TLS key type (rsa4096, p384, ed25519) |
| `SMP_PASS` | | | Optional password for SMP queue creation |
| `XFTP_PASS` | | | Optional password for XFTP uploads |
| `SKIP_PROMPTS` | | 0 | Set to 1 for non-interactive installation |
## What Gets Deployed
### Security Features
- **Post-quantum SSH**: Hybrid KEX (mlkem768x25519, sntrup761x25519) + Ed25519 keys
- **Minimal attack surface**: Only SSH terminal + SFTP, no forwarding/tunnels
- **Firewall**: awall with explicit allow-list for required ports only
- **Brute-force protection**: sshguard with progressive IP bans
### SimpleX Infrastructure
- **SMP server**: Message relay on port 5223
- **XFTP server**: File transfer on port 5443
- **Tor hidden services**: .onion addresses for both servers
- **TLS termination**: Caddy with Let's Encrypt and strong crypto
- **Docker compose**: Orchestrated deployment with health checks
### Operational Features
- **Encrypted backups**: All private keys backed up with age encryption
- **CA key removal**: Private keys removed from disk after backup
- **Service monitoring**: OpenRC integration with auto-restart
- **Address discovery**: Scripts to show server fingerprints and .onion URLs
## Server Addresses
After deployment, your relay will be accessible at:
```
# Clearnet
smp://FINGERPRINT@smp.yourdomain.com
xftp://FINGERPRINT@xftp.yourdomain.com
# Tor (clients with Orbot/Tor)
smp://FINGERPRINT@smp.yourdomain.com,ONIONADDRESS.onion
xftp://FINGERPRINT@xftp.yourdomain.com,ONIONADDRESS.onion
```
Get the full addresses with: `cd /opt/simplex && ./print-addresses.sh`
## Backup & Recovery
### Creating Backups
```bash
# Manual backup (on the server)
AGE_RECIPIENT_FILE=/path/to/age-pubkey.txt bash backup.sh
# Or with a single recipient
AGE_RECIPIENT=age1ql3z7... bash backup.sh
```
### Disaster Recovery
```bash
# 1. Fresh Alpine install
# 2. Upload restore script and backup
scp restore.sh backup-20250101-120000.tar.gz.age root@new-host:/root/
# 3. Restore (preserves all server identities)
ssh root@new-host
bash restore.sh backup-20250101-120000.tar.gz.age
# 4. Update DNS to point at new host
```
## DNS Configuration
Create these DNS records before deployment:
```
smp.yourdomain.com. 300 IN A 1.2.3.4
xftp.yourdomain.com. 300 IN A 1.2.3.4
```
Replace `1.2.3.4` with your server's IP address.
## Architecture
```
Internet
↓
[Caddy :80,:443] ← Let's Encrypt ACME
↓
[Docker Network]
├─ [SMP Server :5223] ← Tor Hidden Service
└─ [XFTP Server :5443] ← Tor Hidden Service
```
- **Ports 80/443**: Caddy (HTTP redirect + ACME + info pages)
- **Port 5223**: SMP protocol (TCP, server's own TLS)
- **Port 5443**: XFTP protocol (TCP, server's own TLS)
- **Port 22/2222**: SSH (PQ KEX + Ed25519 only)
## File Locations
- **Deployment**: `/opt/simplex/` (docker-compose.yml, configs, scripts)
- **Server keys**: `/opt/simplex/{smp,xftp}_configs/` (CA keys removed after backup)
- **Tor keys**: `/opt/simplex/{smp,xftp}_tor/` (hidden service identity)
- **SSH config**: `/etc/ssh/` (hardened sshd_config + Ed25519 host key)
- **Firewall**: `/etc/awall/optional/` (JSON policy files)
- **Backups**: `/tmp/simplex-backup-YYYYMMDD-HHMMSS.tar.gz.age`
## Security Notes
### What's Quantum-Safe
- **Session keys**: PQ hybrid KEX protects against "store now, decrypt later"
- **Authentication**: Ed25519 keys (classical, but strongest practical choice today)
### Network Hardening
- Only required ports open (22/2222, 80, 443, 5223, 5443)
- SSH locked to key-only auth, no forwarding, rate-limited
- sshguard blocks brute-force attempts with progressive delays
### Key Management
- CA private keys backed up encrypted, then removed from disk
- Tor onion keys preserved for stable .onion addresses
- SSH host key preserved for stable fingerprint
- All backups encrypted with age (modern, simple, secure)
## Troubleshooting
### Check Service Status
```bash
cd /opt/simplex
docker compose ps # Container status
docker compose logs -f smp-server # SMP logs
docker compose logs -f xftp-server # XFTP logs
./print-addresses.sh # Show server addresses
```
### SSH Issues
```bash
# Test SSH config
sshd -t
# View SSH attempts
journalctl -u sshd -f
# Check sshguard blocks
iptables -L sshguard -n
```
### Firewall Issues
```bash
awall list # Show firewall policies
awall translate # Test policy compilation
iptables -L -n # Show active rules
```
### Certificate Issues
```bash
docker exec simplex-caddy caddy list-certificates
docker logs simplex-caddy
```
## Contributing
1. Fork this repository
2. Make your changes
3. Test on a fresh Alpine instance
4. Submit a pull request
## License
This deployment is provided as-is for educational and operational use. The SimpleX Chat software itself is licensed under AGPL-3.0.
+225
View File
@@ -0,0 +1,225 @@
#!/usr/bin/env bash
#
# backup.sh
#
# Creates an age-encrypted backup of all irreplaceable SimpleX server keys,
# state, and SSH configuration. This is the minimum data set you'd need to
# recreate the server without changing server fingerprints or .onion addresses.
#
# The backup is encrypted using the age public key you specify. Decrypt on
# another machine with:
# age --decrypt --identity /path/to/private_key backup-YYYYMMDD-HHMMSS.tar.gz.age | tar xzf -
#
# Usage:
# AGE_RECIPIENT=age1ql3z7hjy54...your-pubkey bash backup.sh
# AGE_RECIPIENT_FILE=/path/to/pubkeys.txt bash backup.sh
#
# You can specify either a single AGE_RECIPIENT public key, or an
# AGE_RECIPIENT_FILE containing one or more public keys (one per line).
# The backup will be encrypted to all provided keys.
set -euo pipefail
# ============================================================================
# CONFIG
# ============================================================================
: "${AGE_RECIPIENT:=}" # single age public key (age1...)
: "${AGE_RECIPIENT_FILE:=}" # file containing age public keys
: "${SIMPLEX_DIR:=/opt/simplex}"
: "${BACKUP_DIR:=/tmp}"
: "${KEEP_BACKUPS:=7}" # how many historical backups to keep
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "Run as root (needs access to private keys)."
# ----------------------------------------------------------------------------
# 1. Validation
# ----------------------------------------------------------------------------
[[ -n "$AGE_RECIPIENT" || -n "$AGE_RECIPIENT_FILE" ]] \
|| die "Set AGE_RECIPIENT=age1... or AGE_RECIPIENT_FILE=/path/to/keys.txt"
if ! command -v age >/dev/null; then
log "Installing age..."
apk add -q age
fi
if [[ -n "$AGE_RECIPIENT_FILE" && ! -f "$AGE_RECIPIENT_FILE" ]]; then
die "AGE_RECIPIENT_FILE '$AGE_RECIPIENT_FILE' not found."
fi
[[ -d "$SIMPLEX_DIR" ]] || die "SimpleX directory '$SIMPLEX_DIR' not found. Run deploy-simplex.sh first."
# Build the age command args
AGE_ARGS=()
if [[ -n "$AGE_RECIPIENT" ]]; then
AGE_ARGS+=(--recipient "$AGE_RECIPIENT")
fi
if [[ -n "$AGE_RECIPIENT_FILE" ]]; then
AGE_ARGS+=(--recipients-file "$AGE_RECIPIENT_FILE")
fi
# ----------------------------------------------------------------------------
# 2. Inventory what needs backing up
# ----------------------------------------------------------------------------
log "Inventorying backup targets..."
# Critical files that prove server identity
TARGETS=(
# SimpleX CA keys (prove server identity across certs)
"$SIMPLEX_DIR/smp_configs/ca.key"
"$SIMPLEX_DIR/xftp_configs/ca.key"
# Tor hidden service keys (.onion addresses)
"$SIMPLEX_DIR/smp_tor/hs_ed25519_secret_key"
"$SIMPLEX_DIR/smp_tor/hs_ed25519_public_key"
"$SIMPLEX_DIR/xftp_tor/hs_ed25519_secret_key"
"$SIMPLEX_DIR/xftp_tor/hs_ed25519_public_key"
# SSH host key (server fingerprint)
"/etc/ssh/ssh_host_ed25519_key"
"/etc/ssh/ssh_host_ed25519_key.pub"
# Root's SSH authorized_keys and config
"/root/.ssh/authorized_keys"
"/etc/ssh/sshd_config"
# SimpleX server configs and current certificates
"$SIMPLEX_DIR/smp_configs/smp-server.ini"
"$SIMPLEX_DIR/xftp_configs/file-server.ini"
"$SIMPLEX_DIR/smp_configs/server.crt"
"$SIMPLEX_DIR/smp_configs/server.key"
"$SIMPLEX_DIR/xftp_configs/server.crt"
"$SIMPLEX_DIR/xftp_configs/server.key"
# Current environment and docker-compose setup
"$SIMPLEX_DIR/.env"
"$SIMPLEX_DIR/docker-compose.yml"
"$SIMPLEX_DIR/print-addresses.sh"
# Tor configs
"$SIMPLEX_DIR/tor_conf/"
# Current firewall policies (so you can see what was open)
"/etc/awall/optional/"
)
# Check which targets actually exist
EXISTING_TARGETS=()
MISSING_TARGETS=()
for target in "${TARGETS[@]}"; do
if [[ -e "$target" ]]; then
EXISTING_TARGETS+=("$target")
else
MISSING_TARGETS+=("$target")
fi
done
log "Found ${#EXISTING_TARGETS[@]} backup targets"
if [[ ${#MISSING_TARGETS[@]} -gt 0 ]]; then
warn "Missing ${#MISSING_TARGETS[@]} expected files:"
printf ' %s\n' "${MISSING_TARGETS[@]}" >&2
fi
[[ ${#EXISTING_TARGETS[@]} -gt 0 ]] || die "No backup targets found."
# ----------------------------------------------------------------------------
# 3. Create the backup
# ----------------------------------------------------------------------------
TIMESTAMP=$(date -u +%Y%m%d-%H%M%S)
BACKUP_NAME="simplex-backup-${TIMESTAMP}"
BACKUP_TAR="${BACKUP_DIR}/${BACKUP_NAME}.tar.gz"
BACKUP_ENCRYPTED="${BACKUP_TAR}.age"
log "Creating backup archive..."
# Use tar to preserve permissions, ownership, and handle both files and directories.
# The --transform option puts everything under a dated directory in the tarball.
tar -czf "$BACKUP_TAR" \
--transform="s|^|${BACKUP_NAME}/|" \
--preserve-permissions \
--same-owner \
"${EXISTING_TARGETS[@]}" 2>/dev/null
if [[ ! -f "$BACKUP_TAR" ]]; then
die "Failed to create tar archive '$BACKUP_TAR'"
fi
# Encrypt the tarball
log "Encrypting with age..."
age "${AGE_ARGS[@]}" --output "$BACKUP_ENCRYPTED" "$BACKUP_TAR"
# Remove the unencrypted tar
shred -u "$BACKUP_TAR" 2>/dev/null || rm -f "$BACKUP_TAR"
# ----------------------------------------------------------------------------
# 4. Verify the backup
# ----------------------------------------------------------------------------
log "Verifying backup can be read..."
if age --decrypt "${AGE_ARGS[@]/--recipient*/--identity}" --output /dev/null "$BACKUP_ENCRYPTED" 2>/dev/null; then
: # Verification with --identity would need the private key; skip for now
else
# Just check the file isn't empty/corrupted
[[ -s "$BACKUP_ENCRYPTED" ]] || die "Backup file appears empty or corrupted"
fi
BACKUP_SIZE=$(stat -c%s "$BACKUP_ENCRYPTED" 2>/dev/null || wc -c < "$BACKUP_ENCRYPTED")
log "Backup created: $(basename "$BACKUP_ENCRYPTED") (${BACKUP_SIZE} bytes)"
# ----------------------------------------------------------------------------
# 5. Cleanup old backups
# ----------------------------------------------------------------------------
log "Cleaning up old backups (keeping ${KEEP_BACKUPS})..."
find "$BACKUP_DIR" -name 'simplex-backup-*.tar.gz.age' -type f -print0 \
| sort -z \
| head -z -n -"$KEEP_BACKUPS" \
| xargs -0 rm -f
REMAINING=$(find "$BACKUP_DIR" -name 'simplex-backup-*.tar.gz.age' -type f | wc -l)
log "Backup directory now contains ${REMAINING} backup(s)"
# ----------------------------------------------------------------------------
# 6. Final report + retrieval instructions
# ----------------------------------------------------------------------------
cat <<EOF
================================================================
BACKUP COMPLETE
================================================================
Encrypted backup: ${BACKUP_ENCRYPTED}
Size: ${BACKUP_SIZE} bytes
This backup contains:
• SimpleX CA keys (smp_configs/ca.key, xftp_configs/ca.key)
• Tor hidden service keys (*/hs_ed25519_*_key)
• SSH host key (/etc/ssh/ssh_host_ed25519_key*)
• SSH authorized_keys and sshd_config
• SimpleX server configs and certificates
• Current compose stack (.env, docker-compose.yml)
• Firewall policies (/etc/awall/optional/)
RETRIEVE THE BACKUP:
1. Copy from the server:
scp -i ~/.ssh/your_key root@host:${BACKUP_ENCRYPTED} ./
2. Decrypt and extract:
age --decrypt --identity /path/to/your/age_private_key \\
${BACKUP_NAME}.tar.gz.age | tar xzf -
WARNING: This backup contains private keys. Store it securely and
delete it from /tmp after copying off-host.
RESTORE PROCESS (if needed):
1. Fresh Alpine install + harden-ssh.sh
2. Extract backup: ${BACKUP_NAME}/
3. Copy keys back to their original paths
4. Run deploy-simplex.sh (will reuse existing keys)
5. Verify fingerprints match the backup
================================================================
EOF
+98
View File
@@ -0,0 +1,98 @@
#cloud-config
#
# SimpleX Chat Relay Server - Cloud-Init Configuration
#
# This cloud-init configuration deploys a complete SimpleX relay server
# on Alpine Linux with:
# - Post-quantum SSH hardening
# - SMP + XFTP servers with Tor hidden services
# - Caddy reverse proxy with Let's Encrypt
# - awall firewall with minimal attack surface
# - Encrypted backup of all server keys
#
# Customize the environment variables below, then use this as user-data
# when creating your cloud instance.
# Use Alpine Linux (most cloud providers support it)
# Recommended: Alpine 3.19+ for latest OpenSSH with PQ KEX support
runcmd:
# Set a hostname (optional)
- hostnamectl set-hostname simplex-relay
# Run the master installer
- |
curl -fsSL https://git.anomalous.dev/57_Wolve/automations/raw/branch/main/deployments/simplex/install-simplex.sh | \
REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git \
DOMAIN=relay.yourdomain.com \
ACME_EMAIL=admin@yourdomain.com \
XFTP_QUOTA=100gb \
SSH_PORT=2222 \
ALLOWED_IP=your.client.ip.here \
KEY_TYPE=rsa4096 \
SMP_PASS= \
XFTP_PASS= \
SKIP_PROMPTS=1 \
AUTO_BACKUP=1 \
REMOVE_CA_KEYS=1 \
DEBUG=0 \
bash
# Optional: Configure additional settings
write_files:
# Custom SSH banner (optional)
- path: /etc/ssh/banner
content: |
===============================================
SimpleX Chat Relay Server
Authorized access only.
All connections are logged and monitored.
===============================================
permissions: '0644'
# Optional: Install additional packages
packages:
- htop
- nano
- curl
- jq
# Optional: Configure automatic security updates (Alpine)
package_update: true
package_upgrade: true
# Set timezone
timezone: UTC
# Configure locale
locale: en_US.UTF-8
# Configure SSH (these will be overridden by harden-ssh.sh)
ssh_pwauth: true # Will be disabled by harden-ssh.sh
disable_root: false # Keep root enabled for harden-ssh.sh
# Optional: Add non-root user (created before SSH hardening)
users:
- name: admin
groups: wheel
sudo: ['ALL=(ALL) NOPASSWD:ALL']
shell: /bin/bash
# Note: SSH hardening will restrict to Ed25519 keys only
# Add your Ed25519 public key here if you want this user to survive hardening:
# ssh_authorized_keys:
# - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAA... your-key-here
# Optional: Configure fail2ban (will be replaced by sshguard)
# runcmd will install sshguard which is lighter and more suitable
# Security note: The master installer will:
# 1. Generate fresh SSH keys and disable password auth
# 2. Create an encrypted backup containing all private keys
# 3. Remove CA keys from disk (they exist only in the backup)
# 4. Lock down the firewall to required ports only
#
# Make sure to:
# 1. Download the encrypted backup immediately after deployment
# 2. Save the SSH private key from the installer output
# 3. Test SSH access before deploying to production
+541
View File
@@ -0,0 +1,541 @@
#!/usr/bin/env bash
#
# deploy-simplex.sh
#
# Single-file deployment of SimpleX SMP + XFTP + Tor hidden services on a
# fresh Alpine Linux install, behind awall.
#
# Targets Alpine 3.19+. Run as root on a machine where:
# - smp.${DOMAIN} and xftp.${DOMAIN} both resolve here (A/AAAA records set)
# - SSH is your only existing access (the script preserves whatever port
# you specify in SSH_PORT)
#
# Usage:
# 1. Copy this file onto the host: scp deploy-simplex.sh root@host:/root/
# 2. Edit the CONFIG block below (or pass via env vars)
# 3. Run: bash deploy-simplex.sh
#
# What it does:
# 1. Enables community repo, updates apk
# 2. Installs docker, docker-cli-compose, awall, iptables, curl, openrc bits
# 3. Configures awall: deny-all default + ssh + http(80) + https(443) +
# smp(5223) + xftp(5443), with rate-limited SSH
# 4. Writes docker-compose.yml + Caddyfile generator + Tor configs into /opt/simplex
# 5. Starts the stack
# 6. Prints the multi-host SimpleX server addresses once Tor publishes
#
# What it does NOT do (intentional):
# - SSH hardening beyond keeping your existing port. Set up keys yourself
# before running this. The script does not change sshd_config.
# - Backups of CA keys -- it tells you to do that, you do it.
# - Auto-update of containers. Use `docker compose pull && up -d` periodically
# or add Watchtower if you want that.
set -euo pipefail
# ============================================================================
# CONFIG -- edit these or override via env vars
# ============================================================================
: "${DOMAIN:=example.com}" # apex domain; uses smp.$DOMAIN and xftp.$DOMAIN
: "${ACME_EMAIL:=admin@example.com}" # for Let's Encrypt
: "${XFTP_QUOTA:=50gb}" # disk quota for XFTP file storage
: "${KEY_TYPE:=rsa4096}" # Caddy TLS key: rsa4096|rsa2048|p384|p256
# Note: ed25519 NOT supported by Let's Encrypt
: "${SMP_PASS:=}" # optional: queue creation password
: "${XFTP_PASS:=}" # optional: file upload password
: "${SSH_PORT:=22}" # whatever your sshd is listening on
: "${INSTALL_DIR:=/opt/simplex}" # where everything lives
: "${WAN_IFACE:=}" # autodetected if blank
: "${CERT_PATH:=acme-v02.api.letsencrypt.org-directory}"
# use acme-staging-v02.api.letsencrypt.org-directory
# to test without burning rate limits
# ============================================================================
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "Run as root."
[[ -f /etc/alpine-release ]] || die "This script targets Alpine Linux."
if [[ -z "$WAN_IFACE" ]]; then
WAN_IFACE=$(ip -o -4 route show default | awk '{print $5; exit}')
[[ -n "$WAN_IFACE" ]] || die "Could not autodetect WAN interface; set WAN_IFACE."
fi
log "WAN interface: $WAN_IFACE"
log "Domain: $DOMAIN"
log "Install dir: $INSTALL_DIR"
# ----------------------------------------------------------------------------
# 1. Repos + packages
# ----------------------------------------------------------------------------
log "Enabling community repo and updating apk..."
ALPINE_VER=$(cut -d. -f1,2 < /etc/alpine-release)
if ! grep -qE "^https?://.+/v${ALPINE_VER}/community" /etc/apk/repositories; then
sed -i -E "s|^#(https?://.+/v${ALPINE_VER}/community)|\1|" /etc/apk/repositories || true
if ! grep -qE "^https?://.+/v${ALPINE_VER}/community" /etc/apk/repositories; then
# Fallback: append the standard community URL based on existing main mirror
MAIN_MIRROR=$(awk '/main$/ {print; exit}' /etc/apk/repositories \
| sed -E "s|/v${ALPINE_VER}/main|/v${ALPINE_VER}/community|")
[[ -n "$MAIN_MIRROR" ]] && echo "$MAIN_MIRROR" >> /etc/apk/repositories
fi
fi
apk update -q
apk upgrade -q
log "Installing packages..."
apk add -q \
docker docker-cli-compose \
awall iptables ip6tables \
curl bash openssl \
ca-certificates
# ----------------------------------------------------------------------------
# 2. Kernel modules + iptables/awall
# ----------------------------------------------------------------------------
log "Loading iptables kernel modules..."
modprobe -q ip_tables || true
modprobe -q ip6_tables || true
modprobe -q iptable_nat || true
modprobe -q iptable_filter || true
log "Enabling iptables/ip6tables/docker at boot..."
rc-update add iptables default
rc-update add ip6tables default
rc-update add docker default
log "Writing awall policies..."
mkdir -p /etc/awall/optional /etc/awall/private
cat > /etc/awall/optional/base.json <<JSON
{
"description": "SimpleX relay base policy: deny-all on internet zone",
"variable": { "wan_if": "${WAN_IFACE}" },
"zone": { "internet": { "iface": "\$wan_if" } },
"policy": [
{ "in": "internet", "action": "drop" },
{ "action": "accept" }
]
}
JSON
cat > /etc/awall/optional/ssh.json <<JSON
{
"description": "Allow SSH on tcp/${SSH_PORT}, rate-limited",
"filter": [
{
"in": "internet",
"out": "_fw",
"service": { "proto": "tcp", "port": ${SSH_PORT} },
"action": "accept",
"conn-limit": { "count": 5, "interval": 60 }
}
]
}
JSON
cat > /etc/awall/optional/web.json <<JSON
{
"description": "Allow HTTP/HTTPS for Caddy info pages and ACME",
"filter": [
{ "in": "internet", "out": "_fw", "service": "http", "action": "accept" },
{ "in": "internet", "out": "_fw", "service": "https", "action": "accept" }
]
}
JSON
cat > /etc/awall/optional/simplex.json <<JSON
{
"description": "SimpleX SMP (5223) and XFTP (5443) protocol ports",
"filter": [
{ "in": "internet", "out": "_fw",
"service": { "proto": "tcp", "port": 5223 }, "action": "accept" },
{ "in": "internet", "out": "_fw",
"service": { "proto": "tcp", "port": 5443 }, "action": "accept" }
]
}
JSON
cat > /etc/awall/optional/icmp.json <<JSON
{
"description": "Allow rate-limited ICMP echo (ping)",
"filter": [
{
"in": "internet",
"service": "ping",
"action": "accept",
"flow-limit": { "count": 10, "interval": 6 }
}
]
}
JSON
awall enable base ssh web simplex icmp
awall translate --output /etc/iptables 2>/dev/null || true
awall translate --output /etc/ip6tables 2>/dev/null || true
awall activate --force
rc-service iptables restart || rc-service iptables start
rc-service ip6tables restart || rc-service ip6tables start
# ----------------------------------------------------------------------------
# 3. Sysctl hardening (modest)
# ----------------------------------------------------------------------------
log "Applying minimal sysctl hardening..."
cat > /etc/sysctl.d/90-simplex.conf <<'EOF'
# IP spoof protection
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Don't forward unless this is a router (Docker re-enables forwarding for the
# docker0 bridge specifically, which is fine)
net.ipv4.ip_forward = 0
# Ignore source-routed packets, ICMP redirects, broadcasts
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
# SYN flood protection
net.ipv4.tcp_syncookies = 1
EOF
sysctl -p /etc/sysctl.d/90-simplex.conf >/dev/null
# ----------------------------------------------------------------------------
# 4. Start docker
# ----------------------------------------------------------------------------
log "Starting docker..."
rc-service docker status >/dev/null 2>&1 || rc-service docker start
# Wait for socket
for _ in $(seq 1 20); do
[[ -S /var/run/docker.sock ]] && break
sleep 1
done
[[ -S /var/run/docker.sock ]] || die "Docker socket didn't appear."
# ----------------------------------------------------------------------------
# 5. Lay out /opt/simplex
# ----------------------------------------------------------------------------
log "Writing compose stack to ${INSTALL_DIR}..."
mkdir -p "$INSTALL_DIR"/tor_conf
cd "$INSTALL_DIR"
cat > .env <<EOF
DOMAIN=${DOMAIN}
ACME_EMAIL=${ACME_EMAIL}
XFTP_QUOTA=${XFTP_QUOTA}
KEY_TYPE=${KEY_TYPE}
SMP_PASS=${SMP_PASS}
XFTP_PASS=${XFTP_PASS}
CERT_PATH=${CERT_PATH}
EOF
chmod 600 .env
cat > docker-compose.yml <<'YAML'
name: simplex
services:
caddy-init:
image: alpine:latest
command: >
sh -c '
if [ ! -f /etc/caddy/Caddyfile ]; then
cat > /etc/caddy/Caddyfile <<EOF
{
email ${ACME_EMAIL}
}
http://smp.${DOMAIN} {
redir https://smp.${DOMAIN}{uri} permanent
}
smp.${DOMAIN}:8443 {
tls { key_type ${KEY_TYPE} }
reverse_proxy smp-server:8000
}
http://xftp.${DOMAIN} {
redir https://xftp.${DOMAIN}{uri} permanent
}
xftp.${DOMAIN}:8443 {
tls { key_type ${KEY_TYPE} }
reverse_proxy xftp-server:8000
}
EOF
fi
'
environment:
DOMAIN: ${DOMAIN:?}
ACME_EMAIL: ${ACME_EMAIL:?}
KEY_TYPE: ${KEY_TYPE:-rsa4096}
volumes:
- ./caddy_conf:/etc/caddy
restart: "no"
caddy:
image: caddy:2-alpine
depends_on:
caddy-init:
condition: service_completed_successfully
cap_add:
- NET_ADMIN
ports:
- "80:80"
- "443:8443"
volumes:
- ./caddy_conf:/etc/caddy
- caddy_data:/data
- caddy_config:/config
restart: unless-stopped
healthcheck:
test: >
sh -c '
test -d /data/caddy/certificates/${CERT_PATH:-acme-v02.api.letsencrypt.org-directory}/smp.${DOMAIN} &&
test -d /data/caddy/certificates/${CERT_PATH:-acme-v02.api.letsencrypt.org-directory}/xftp.${DOMAIN}
'
interval: 5s
timeout: 3s
retries: 60
start_period: 30s
environment:
DOMAIN: ${DOMAIN}
CERT_PATH: ${CERT_PATH:-acme-v02.api.letsencrypt.org-directory}
smp-server:
image: simplexchat/smp-server:latest
depends_on:
caddy:
condition: service_healthy
environment:
ADDR: smp.${DOMAIN}
PASS: ${SMP_PASS:-}
WEB_MANUAL: "0"
volumes:
- ./smp_configs:/etc/opt/simplex
- ./smp_state:/var/opt/simplex
- type: volume
source: caddy_data
target: /certificates
read_only: true
volume:
subpath: "caddy/certificates/${CERT_PATH:-acme-v02.api.letsencrypt.org-directory}/smp.${DOMAIN}"
ports:
- "5223:5223"
restart: unless-stopped
smp-tor:
image: dperson/torproxy:latest
depends_on:
- smp-server
network_mode: "service:smp-server"
volumes:
- ./smp_tor:/var/lib/tor/hidden_service
- ./tor_conf/smp-torrc:/etc/tor/torrc:ro
restart: unless-stopped
xftp-server:
image: simplexchat/xftp-server:latest
depends_on:
caddy:
condition: service_healthy
environment:
ADDR: xftp.${DOMAIN}
QUOTA: ${XFTP_QUOTA:?}
PASS: ${XFTP_PASS:-}
WEB_MANUAL: "0"
volumes:
- ./xftp_configs:/etc/opt/simplex-xftp
- ./xftp_state:/var/opt/simplex-xftp
- ./xftp_files:/srv/xftp
- type: volume
source: caddy_data
target: /certificates
read_only: true
volume:
subpath: "caddy/certificates/${CERT_PATH:-acme-v02.api.letsencrypt.org-directory}/xftp.${DOMAIN}"
ports:
- "5443:443"
restart: unless-stopped
xftp-tor:
image: dperson/torproxy:latest
depends_on:
- xftp-server
network_mode: "service:xftp-server"
volumes:
- ./xftp_tor:/var/lib/tor/hidden_service
- ./tor_conf/xftp-torrc:/etc/tor/torrc:ro
restart: unless-stopped
volumes:
caddy_data:
caddy_config:
YAML
cat > tor_conf/smp-torrc <<'EOF'
# Single-hop / non-anonymous mode: lower latency. The SERVER's location is
# already public via clearnet, so hiding it is moot. Clients remain fully
# anonymous to us. Drop these three lines for a tor-only relay where the
# server's location should also be hidden.
SOCKSPort 0
HiddenServiceNonAnonymousMode 1
HiddenServiceSingleHopMode 1
HiddenServiceDir /var/lib/tor/hidden_service/
HiddenServicePort 5223 127.0.0.1:5223
HiddenServicePort 443 127.0.0.1:8000
Log notice stdout
EOF
cat > tor_conf/xftp-torrc <<'EOF'
SOCKSPort 0
HiddenServiceNonAnonymousMode 1
HiddenServiceSingleHopMode 1
HiddenServiceDir /var/lib/tor/hidden_service/
HiddenServicePort 443 127.0.0.1:443
HiddenServicePort 8443 127.0.0.1:8000
Log notice stdout
EOF
# ----------------------------------------------------------------------------
# 6. Helper script for printing addresses post-bringup
# ----------------------------------------------------------------------------
cat > print-addresses.sh <<'BASH'
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
# shellcheck disable=SC1091
source .env
get_fp() {
docker compose logs "$1" 2>/dev/null \
| grep -m1 'Server address:' \
| sed -E 's|.*://([^@]+)@.*|\1|'
}
read_or_blank() { [[ -f "$1" ]] && cat "$1" || echo ""; }
SMP_FP=$(get_fp smp-server)
XFTP_FP=$(get_fp xftp-server)
SMP_ONION=$(read_or_blank ./smp_tor/hostname)
XFTP_ONION=$(read_or_blank ./xftp_tor/hostname)
build_addr() {
local scheme=$1 fp=$2 clearnet=$3 onion=$4
local hosts="$clearnet"
[[ -n "$onion" ]] && hosts="${hosts},${onion}"
echo "${scheme}://${fp}@${hosts}"
}
echo
echo "=== SMP ==="
echo " fingerprint: ${SMP_FP:-<not yet available>}"
echo " clearnet: smp.${DOMAIN}"
echo " onion: ${SMP_ONION:-<not yet available>}"
echo " full addr: $(build_addr smp "$SMP_FP" "smp.${DOMAIN}" "$SMP_ONION")"
echo
echo "=== XFTP ==="
echo " fingerprint: ${XFTP_FP:-<not yet available>}"
echo " clearnet: xftp.${DOMAIN}"
echo " onion: ${XFTP_ONION:-<not yet available>}"
echo " full addr: $(build_addr xftp "$XFTP_FP" "xftp.${DOMAIN}" "$XFTP_ONION")"
echo
BASH
chmod +x print-addresses.sh
# ----------------------------------------------------------------------------
# 7. OpenRC service for the compose stack itself
# ----------------------------------------------------------------------------
log "Creating openrc service for the stack..."
cat > /etc/init.d/simplex <<'EOF'
#!/sbin/openrc-run
name="simplex"
description="SimpleX SMP + XFTP + Tor docker compose stack"
directory="/opt/simplex"
depend() {
need docker
after net firewall
}
start() {
ebegin "Starting SimpleX stack"
cd "$directory"
docker compose up -d
eend $?
}
stop() {
ebegin "Stopping SimpleX stack"
cd "$directory"
docker compose down
eend $?
}
status() {
cd "$directory"
docker compose ps
}
EOF
chmod +x /etc/init.d/simplex
rc-update add simplex default
# ----------------------------------------------------------------------------
# 8. Bring it up
# ----------------------------------------------------------------------------
log "Pulling images and starting the stack..."
cd "$INSTALL_DIR"
docker compose pull
docker compose up -d
log "Waiting up to 90s for Tor to publish hidden services..."
for _ in $(seq 1 90); do
if [[ -f "$INSTALL_DIR/smp_tor/hostname" && -f "$INSTALL_DIR/xftp_tor/hostname" ]]; then
break
fi
sleep 1
done
# ----------------------------------------------------------------------------
# 9. Final report
# ----------------------------------------------------------------------------
echo
echo "================================================================"
echo " SimpleX deployment complete"
echo "================================================================"
"$INSTALL_DIR/print-addresses.sh" || true
cat <<EOF
NEXT STEPS (do these now, not later):
1. BACK UP CA KEYS (these prove server identity if you ever need to rotate):
$INSTALL_DIR/smp_configs/ca.key
$INSTALL_DIR/xftp_configs/ca.key
Copy them off this host, then delete the on-host copies:
rm $INSTALL_DIR/smp_configs/ca.key
rm $INSTALL_DIR/xftp_configs/ca.key
2. BACK UP TOR HIDDEN SERVICE KEYS (preserve the .onion across reinstalls):
$INSTALL_DIR/smp_tor/hs_ed25519_secret_key
$INSTALL_DIR/xftp_tor/hs_ed25519_secret_key
3. Add the server addresses above to your SimpleX app:
Settings -> Network & Servers -> SMP/XFTP servers -> Add
4. Verify the firewall is doing its job:
awall list
iptables -L -n
5. Watch the stack:
cd $INSTALL_DIR && docker compose logs -f
EOF
+298
View File
@@ -0,0 +1,298 @@
#!/usr/bin/env bash
#
# install-simplex.sh
#
# Master installer for SimpleX relay deployment. Designed for cloud-init but
# works as a standalone script. Fetches deployment scripts from git, runs the
# complete setup sequence, and creates an initial encrypted backup.
#
# This script:
# 1. Fetches deployment scripts from your git repo
# 2. Runs harden-ssh.sh (PQ KEX, Ed25519, firewall)
# 3. Runs deploy-simplex.sh (SMP + XFTP + Tor)
# 4. Runs backup.sh with your age public key
# 5. Cleans up CA keys from disk (they're now only in the encrypted backup)
# 6. Reports final status and backup location
#
# Usage as cloud-init user-data:
# #cloud-config
# runcmd:
# - |
# curl -fsSL https://git.anomalous.dev/57_Wolve/automations/raw/branch/main/deployments/simplex/install-simplex.sh | \
# REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git \
# DOMAIN=relay.example.com \
# ACME_EMAIL=admin@example.com \
# XFTP_QUOTA=100gb \
# SSH_PORT=2222 \
# bash
#
# Usage as standalone script:
# curl -fsSL https://git.anomalous.dev/57_Wolve/automations/raw/branch/main/deployments/simplex/install-simplex.sh > install-simplex.sh
# REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git \
# DOMAIN=relay.example.com \
# ACME_EMAIL=admin@example.com \
# bash install-simplex.sh
#
# Required git repo structure (this monorepo):
# automations/
# ├── scripts/
# │ └── harden-ssh.sh # generic, run-anywhere
# ├── deployments/simplex/
# │ ├── deploy-simplex.sh
# │ ├── backup.sh
# │ └── restore.sh # optional
# └── globals/
# └── age-pubkey.txt # your age public key(s), one per line
set -euo pipefail
# ============================================================================
# CONFIG
# ============================================================================
# Git repository containing the deployment scripts and age public key
: "${REPO_URL:=}" # REQUIRED: git repo URL
# SimpleX deployment config
: "${DOMAIN:=}" # REQUIRED: apex domain (uses smp.DOMAIN, xftp.DOMAIN)
: "${ACME_EMAIL:=}" # REQUIRED: Let's Encrypt email
: "${XFTP_QUOTA:=50gb}" # XFTP disk quota
: "${SSH_PORT:=22}" # SSH port (recommend changing from default)
: "${KEY_TYPE:=rsa4096}" # Caddy TLS key type
: "${SMP_PASS:=}" # optional: SMP queue creation password
: "${XFTP_PASS:=}" # optional: XFTP upload password
# Git and installation options
: "${REPO_BRANCH:=main}" # git branch to fetch
: "${HARDEN_PATH:=scripts}" # path within repo to the generic harden-ssh.sh
: "${SIMPLEX_PATH:=deployments/simplex}" # path within repo to the simplex scripts
: "${AGE_PUBKEY_FILE:=globals/age-pubkey.txt}" # path within repo to age public key
: "${INSTALL_DIR:=/opt/simplex-deploy}" # where to clone the repo
: "${ALLOWED_IP:=}" # optional: IP to whitelist in sshguard
: "${AUTO_BACKUP:=1}" # set to 0 to skip initial backup
: "${REMOVE_CA_KEYS:=1}" # set to 0 to keep CA keys on disk
# Behavior flags
: "${SKIP_PROMPTS:=0}" # set to 1 for non-interactive operation
: "${DEBUG:=0}" # set to 1 for verbose output
# ============================================================================
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "Run as root."
[[ -f /etc/alpine-release ]] || die "This script targets Alpine Linux."
if [[ "$DEBUG" == "1" ]]; then
set -x
fi
# ----------------------------------------------------------------------------
# 1. Validate required parameters
# ----------------------------------------------------------------------------
[[ -n "$REPO_URL" ]] || die "Set REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git"
[[ -n "$DOMAIN" ]] || die "Set DOMAIN=your.domain.com"
[[ -n "$ACME_EMAIL" ]] || die "Set ACME_EMAIL=admin@your.domain.com"
log "SimpleX relay installer"
log "Repo: $REPO_URL"
log "Domain: $DOMAIN (will create smp.$DOMAIN, xftp.$DOMAIN)"
log "SSH port: $SSH_PORT"
if [[ "$SKIP_PROMPTS" != "1" ]]; then
cat <<EOF
This will install a complete SimpleX relay server on this host:
• SSH hardening with PQ KEX and Ed25519 keys
• awall firewall with minimal attack surface
• SMP + XFTP servers with Tor hidden services
• Caddy reverse proxy with Let's Encrypt TLS
• Initial encrypted backup of all server keys
The process will generate new server keys and may change your SSH config.
Only run this on a fresh Alpine install intended as a SimpleX relay.
Continue? [y/N]
EOF
read -r ans
[[ "${ans,,}" =~ ^(y|yes)$ ]] || die "Aborted."
fi
# ----------------------------------------------------------------------------
# 2. Install git and fetch deployment repo
# ----------------------------------------------------------------------------
log "Installing git and fetching deployment scripts..."
apk add -q git
rm -rf "$INSTALL_DIR"
git clone --depth 1 --branch "$REPO_BRANCH" "$REPO_URL" "$INSTALL_DIR"
# Verify required files exist. harden-ssh.sh is generic and lives under
# scripts/; the simplex scripts live under deployments/simplex/.
HARDEN_DIR="$INSTALL_DIR/$HARDEN_PATH"
SIMPLEX_DIR="$INSTALL_DIR/$SIMPLEX_PATH"
verify_script() { # <dir> <relpath-for-messages> <name>
local path="$1/$3"
[[ -f "$path" ]] || die "Required script not found: $2/$3"
[[ -x "$path" ]] || chmod +x "$path"
}
verify_script "$HARDEN_DIR" "$HARDEN_PATH" "harden-ssh.sh"
verify_script "$SIMPLEX_DIR" "$SIMPLEX_PATH" "deploy-simplex.sh"
verify_script "$SIMPLEX_DIR" "$SIMPLEX_PATH" "backup.sh"
# Check for age public key file
AGE_PUBKEY_PATH="$INSTALL_DIR/$AGE_PUBKEY_FILE"
if [[ "$AUTO_BACKUP" == "1" ]]; then
[[ -f "$AGE_PUBKEY_PATH" ]] || die "Age public key file not found: $AGE_PUBKEY_FILE"
# Validate it contains what looks like age public keys
if ! grep -q "^age1" "$AGE_PUBKEY_PATH"; then
die "Age public key file doesn't contain valid age1... public keys"
fi
fi
log "Repository cloned to: $INSTALL_DIR"
# ----------------------------------------------------------------------------
# 3. Run SSH hardening
# ----------------------------------------------------------------------------
log "Step 1/3: SSH hardening..."
SSH_ENV=""
[[ -n "$SSH_PORT" ]] && SSH_ENV="${SSH_ENV} SSH_PORT=$SSH_PORT"
[[ -n "$ALLOWED_IP" ]] && SSH_ENV="${SSH_ENV} ALLOWED_IP=$ALLOWED_IP"
[[ "$SKIP_PROMPTS" == "1" ]] && SSH_ENV="${SSH_ENV} FORCE=1"
# Capture the private key output from harden-ssh.sh
HARDEN_OUTPUT=$(env $SSH_ENV "$HARDEN_DIR/harden-ssh.sh" 2>&1) || {
echo "$HARDEN_OUTPUT" >&2
die "SSH hardening failed"
}
# Extract the private key from the output for later display
SSH_PRIVATE_KEY=$(echo "$HARDEN_OUTPUT" | sed -n '/BEGIN ROOT PRIVATE KEY/,/END ROOT PRIVATE KEY/p')
SSH_PUBLIC_KEY=$(echo "$HARDEN_OUTPUT" | grep "Public key (already in" | sed 's/.*: //')
HOST_FINGERPRINT=$(echo "$HARDEN_OUTPUT" | grep "Host fingerprint" | tail -1)
log "SSH hardening completed"
# ----------------------------------------------------------------------------
# 4. Run SimpleX deployment
# ----------------------------------------------------------------------------
log "Step 2/3: SimpleX deployment..."
DEPLOY_ENV=""
DEPLOY_ENV="${DEPLOY_ENV} DOMAIN=$DOMAIN"
DEPLOY_ENV="${DEPLOY_ENV} ACME_EMAIL=$ACME_EMAIL"
DEPLOY_ENV="${DEPLOY_ENV} XFTP_QUOTA=$XFTP_QUOTA"
DEPLOY_ENV="${DEPLOY_ENV} SSH_PORT=$SSH_PORT"
DEPLOY_ENV="${DEPLOY_ENV} KEY_TYPE=$KEY_TYPE"
[[ -n "$SMP_PASS" ]] && DEPLOY_ENV="${DEPLOY_ENV} SMP_PASS=$SMP_PASS"
[[ -n "$XFTP_PASS" ]] && DEPLOY_ENV="${DEPLOY_ENV} XFTP_PASS=$XFTP_PASS"
env $DEPLOY_ENV "$SIMPLEX_DIR/deploy-simplex.sh" || die "SimpleX deployment failed"
log "SimpleX deployment completed"
# ----------------------------------------------------------------------------
# 5. Create initial encrypted backup
# ----------------------------------------------------------------------------
if [[ "$AUTO_BACKUP" == "1" ]]; then
log "Step 3/3: Creating initial encrypted backup..."
# Wait a bit for the services to fully initialize
sleep 10
BACKUP_ENV="AGE_RECIPIENT_FILE=$AGE_PUBKEY_PATH"
env $BACKUP_ENV "$SIMPLEX_DIR/backup.sh" || die "Backup creation failed"
log "Initial backup created"
# Remove CA keys from disk now that they're safely backed up
if [[ "$REMOVE_CA_KEYS" == "1" ]]; then
log "Removing CA private keys from disk (they're now only in the encrypted backup)..."
rm -f /opt/simplex/smp_configs/ca.key /opt/simplex/xftp_configs/ca.key
log "CA keys removed from disk"
fi
else
log "Step 3/3: Skipped (AUTO_BACKUP=0)"
fi
# ----------------------------------------------------------------------------
# 6. Final status report
# ----------------------------------------------------------------------------
sleep 5 # Let services settle
cat <<EOF
================================================================
SIMPLEX RELAY INSTALLATION COMPLETE
================================================================
Your SimpleX relay is now running at:
Domain: $DOMAIN
SMP: smp.$DOMAIN:5223
XFTP: xftp.$DOMAIN:5443
SSH: port $SSH_PORT
EOF
# Show server addresses if available
if [[ -f /opt/simplex/print-addresses.sh ]]; then
cd /opt/simplex && ./print-addresses.sh 2>/dev/null || {
log "Server addresses not yet ready; check with: cd /opt/simplex && ./print-addresses.sh"
}
else
log "Server addresses script not found"
fi
# Show backup location
LATEST_BACKUP=$(find /tmp -name 'simplex-backup-*.tar.gz.age' -type f -printf '%T@ %p\n' 2>/dev/null | sort -nr | head -1 | cut -d' ' -f2-)
if [[ -n "$LATEST_BACKUP" && "$AUTO_BACKUP" == "1" ]]; then
BACKUP_SIZE=$(stat -c%s "$LATEST_BACKUP" 2>/dev/null || echo "unknown")
cat <<EOF
BACKUP CREATED:
File: $LATEST_BACKUP
Size: $BACKUP_SIZE bytes
IMPORTANT: Download this backup immediately and store it securely.
It contains all server private keys. The CA keys have been removed
from disk and exist only in this encrypted backup.
Download with:
scp -i ~/.ssh/your_key -P $SSH_PORT root@$DOMAIN:$LATEST_BACKUP ./
EOF
fi
cat <<EOF
IMPORTANT - SAVE THIS SSH PRIVATE KEY:
$SSH_PRIVATE_KEY
Connect with:
ssh -i ~/.ssh/id_ed25519_simplex -p $SSH_PORT root@$DOMAIN
$HOST_FINGERPRINT
NEXT STEPS:
1. Save the SSH private key above to your local machine
2. Download the encrypted backup from $LATEST_BACKUP
3. Test SSH access from another terminal
4. Add the server to your SimpleX app:
Settings -> Network & Servers -> Add servers -> paste the addresses above
5. Test that contacts can reach your relay
================================================================
EOF
# Clean up the git repo (optional - contains no secrets)
if [[ "${CLEANUP_REPO:-1}" == "1" ]]; then
rm -rf "$INSTALL_DIR"
log "Cleaned up installation directory"
fi
log "Installation complete!"
+416
View File
@@ -0,0 +1,416 @@
#!/usr/bin/env bash
#
# restore.sh
#
# Restores a SimpleX server from an age-encrypted backup created by backup.sh.
# This script can rebuild the entire server setup from scratch while preserving:
# - Server fingerprints (SimpleX CA keys)
# - .onion addresses (Tor hidden service keys)
# - SSH host key fingerprint
# - SSH authorized_keys and hardened config
# - All server configurations
#
# IMPORTANT: Run this on a FRESH Alpine installation. This script will:
# 1. Decrypt and extract the backup
# 2. Install all required packages
# 3. Restore SSH hardening + keys
# 4. Restore firewall config
# 5. Deploy the SimpleX stack with preserved keys
# 6. Start services
#
# Usage:
# # Copy restore.sh and your backup onto fresh Alpine host
# scp restore.sh backup-YYYYMMDD-HHMMSS.tar.gz.age root@new-host:/root/
#
# # Run restore (will prompt for age private key)
# ssh root@new-host
# bash restore.sh backup-YYYYMMDD-HHMMSS.tar.gz.age
#
# # Alternative: pass age identity file
# AGE_IDENTITY=/root/backup-key.txt bash restore.sh backup.tar.gz.age
set -euo pipefail
# ============================================================================
# CONFIG
# ============================================================================
: "${AGE_IDENTITY:=}" # optional: path to age private key file
: "${FORCE_OVERWRITE:=0}" # set to 1 to overwrite existing files
: "${SKIP_VALIDATION:=0}" # set to 1 to skip "are you sure" prompts
BACKUP_FILE="${1:-}"
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
# ----------------------------------------------------------------------------
# 1. Validation and setup
# ----------------------------------------------------------------------------
[[ $EUID -eq 0 ]] || die "Run as root."
[[ -f /etc/alpine-release ]] || die "This script targets Alpine Linux."
[[ -n "$BACKUP_FILE" ]] || die "Usage: $0 <backup-file.tar.gz.age>"
[[ -f "$BACKUP_FILE" ]] || die "Backup file '$BACKUP_FILE' not found."
if [[ "$SKIP_VALIDATION" != "1" ]]; then
cat <<EOF
WARNING: This will restore a SimpleX server backup to this host.
This script will:
1. Install packages (docker, openssh, awall, sshguard, age)
2. Restore SSH hardening (may change your SSH config)
3. Restore firewall rules (may change your network access)
4. Deploy the SimpleX docker stack
5. Restore all server keys and certificates
ONLY run this on a fresh Alpine installation intended to become
a SimpleX relay server. This will overwrite existing configs.
Continue? [y/N]
EOF
read -r ans
[[ "${ans,,}" =~ ^(y|yes)$ ]] || die "Aborted."
fi
log "Starting restore from: $(basename "$BACKUP_FILE")"
# ----------------------------------------------------------------------------
# 2. Install age and decrypt backup
# ----------------------------------------------------------------------------
if ! command -v age >/dev/null; then
log "Installing age..."
apk add -q age
fi
RESTORE_DIR="/tmp/restore-$$"
mkdir -p "$RESTORE_DIR"
cd "$RESTORE_DIR"
log "Decrypting backup..."
if [[ -n "$AGE_IDENTITY" ]]; then
if [[ ! -f "$AGE_IDENTITY" ]]; then
die "AGE_IDENTITY file '$AGE_IDENTITY' not found."
fi
age --decrypt --identity "$AGE_IDENTITY" "$BACKUP_FILE" | tar xzf -
else
# Interactive decryption - age will prompt for passphrase or identity
echo "Enter your age private key or passphrase when prompted:"
age --decrypt "$BACKUP_FILE" | tar xzf -
fi
# Find the extracted directory (should be simplex-backup-YYYYMMDD-HHMMSS)
BACKUP_EXTRACT_DIR=$(find . -maxdepth 1 -type d -name 'simplex-backup-*' | head -1)
[[ -n "$BACKUP_EXTRACT_DIR" ]] || die "Could not find extracted backup directory."
BACKUP_EXTRACT_DIR=$(realpath "$BACKUP_EXTRACT_DIR")
log "Extracted to: $BACKUP_EXTRACT_DIR"
# ----------------------------------------------------------------------------
# 3. Install required packages
# ----------------------------------------------------------------------------
log "Updating package lists and installing requirements..."
# Enable community repo if not already
ALPINE_VER=$(cut -d. -f1,2 < /etc/alpine-release)
if ! grep -qE "^https?://.+/v${ALPINE_VER}/community" /etc/apk/repositories; then
sed -i -E "s|^#(https?://.+/v${ALPINE_VER}/community)|\1|" /etc/apk/repositories || {
MAIN_MIRROR=$(awk '/main$/ {print; exit}' /etc/apk/repositories \
| sed -E "s|/v${ALPINE_VER}/main|/v${ALPINE_VER}/community|")
[[ -n "$MAIN_MIRROR" ]] && echo "$MAIN_MIRROR" >> /etc/apk/repositories
}
fi
apk update -q
apk upgrade -q
apk add -q \
docker docker-cli-compose \
openssh openssh-server \
awall iptables ip6tables \
sshguard \
curl bash openssl \
ca-certificates openrc
# ----------------------------------------------------------------------------
# 4. Restore SSH configuration and keys
# ----------------------------------------------------------------------------
log "Restoring SSH configuration and keys..."
# Back up existing SSH config if it exists
[[ -f /etc/ssh/sshd_config ]] && cp /etc/ssh/sshd_config /etc/ssh/sshd_config.pre-restore
# Restore SSH host key
if [[ -f "$BACKUP_EXTRACT_DIR/etc/ssh/ssh_host_ed25519_key" ]]; then
cp "$BACKUP_EXTRACT_DIR/etc/ssh/ssh_host_ed25519_key" /etc/ssh/
cp "$BACKUP_EXTRACT_DIR/etc/ssh/ssh_host_ed25519_key.pub" /etc/ssh/
chmod 600 /etc/ssh/ssh_host_ed25519_key
chmod 644 /etc/ssh/ssh_host_ed25519_key.pub
# Remove any other host key types
rm -f /etc/ssh/ssh_host_rsa_key* /etc/ssh/ssh_host_ecdsa_key* /etc/ssh/ssh_host_dsa_key*
log "Restored SSH host key: $(ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pub)"
else
warn "No SSH host key found in backup; keeping system default"
fi
# Restore sshd_config
if [[ -f "$BACKUP_EXTRACT_DIR/etc/ssh/sshd_config" ]]; then
cp "$BACKUP_EXTRACT_DIR/etc/ssh/sshd_config" /etc/ssh/
log "Restored SSH daemon configuration"
else
warn "No sshd_config found in backup"
fi
# Restore root's authorized_keys
mkdir -p /root/.ssh
chmod 700 /root/.ssh
if [[ -f "$BACKUP_EXTRACT_DIR/root/.ssh/authorized_keys" ]]; then
cp "$BACKUP_EXTRACT_DIR/root/.ssh/authorized_keys" /root/.ssh/
chmod 600 /root/.ssh/authorized_keys
KEY_COUNT=$(wc -l < /root/.ssh/authorized_keys)
log "Restored ${KEY_COUNT} authorized SSH key(s) for root"
else
warn "No authorized_keys found in backup"
fi
# Validate SSH config
if [[ -f /etc/ssh/sshd_config ]]; then
if sshd -t 2>/dev/null; then
log "SSH configuration validated"
else
warn "SSH configuration validation failed; keeping anyway"
fi
fi
# ----------------------------------------------------------------------------
# 5. Restore firewall configuration
# ----------------------------------------------------------------------------
log "Restoring firewall configuration..."
# Load iptables kernel modules
modprobe -q ip_tables || true
modprobe -q ip6_tables || true
modprobe -q iptable_nat || true
modprobe -q iptable_filter || true
# Restore awall policies if they exist
if [[ -d "$BACKUP_EXTRACT_DIR/etc/awall/optional" ]]; then
mkdir -p /etc/awall/optional
cp -r "$BACKUP_EXTRACT_DIR/etc/awall/optional/"* /etc/awall/optional/
# Enable the restored policies
cd /etc/awall/optional
for policy in *.json; do
[[ -f "$policy" ]] || continue
POLICY_NAME=$(basename "$policy" .json)
awall enable "$POLICY_NAME"
log "Enabled awall policy: $POLICY_NAME"
done
# Activate firewall
awall translate --output /etc/iptables 2>/dev/null || true
awall translate --output /etc/ip6tables 2>/dev/null || true
awall activate --force
log "Firewall rules activated"
else
warn "No awall policies found in backup"
fi
# Enable services
rc-update add iptables default || true
rc-update add ip6tables default || true
rc-update add sshd default || true
rc-update add sshguard default || true
rc-update add docker default || true
# ----------------------------------------------------------------------------
# 6. Restore SimpleX configuration and keys
# ----------------------------------------------------------------------------
SIMPLEX_DIR="/opt/simplex"
log "Restoring SimpleX configuration to $SIMPLEX_DIR..."
mkdir -p "$SIMPLEX_DIR"
# Restore the core SimpleX files
SIMPLEX_FILES=(
".env"
"docker-compose.yml"
"print-addresses.sh"
"tor_conf/"
)
for item in "${SIMPLEX_FILES[@]}"; do
SRC="$BACKUP_EXTRACT_DIR/opt/simplex/$item"
if [[ -e "$SRC" ]]; then
cp -r "$SRC" "$SIMPLEX_DIR/"
log "Restored: $item"
else
warn "Missing from backup: $item"
fi
done
# Make script executable
[[ -f "$SIMPLEX_DIR/print-addresses.sh" ]] && chmod +x "$SIMPLEX_DIR/print-addresses.sh"
# Restore SimpleX server keys and configs
mkdir -p "$SIMPLEX_DIR/smp_configs" "$SIMPLEX_DIR/xftp_configs" \
"$SIMPLEX_DIR/smp_state" "$SIMPLEX_DIR/xftp_state" \
"$SIMPLEX_DIR/xftp_files" "$SIMPLEX_DIR/smp_tor" "$SIMPLEX_DIR/xftp_tor"
# SMP server restoration
for key in ca.key server.crt server.key smp-server.ini; do
SRC="$BACKUP_EXTRACT_DIR/opt/simplex/smp_configs/$key"
if [[ -f "$SRC" ]]; then
cp "$SRC" "$SIMPLEX_DIR/smp_configs/"
log "Restored SMP: $key"
fi
done
# XFTP server restoration
for key in ca.key server.crt server.key file-server.ini; do
SRC="$BACKUP_EXTRACT_DIR/opt/simplex/xftp_configs/$key"
if [[ -f "$SRC" ]]; then
cp "$SRC" "$SIMPLEX_DIR/xftp_configs/"
log "Restored XFTP: $key"
fi
done
# Tor hidden service keys
for service in smp xftp; do
for key in hs_ed25519_secret_key hs_ed25519_public_key hostname; do
SRC="$BACKUP_EXTRACT_DIR/opt/simplex/${service}_tor/$key"
if [[ -f "$SRC" ]]; then
cp "$SRC" "$SIMPLEX_DIR/${service}_tor/"
log "Restored Tor ($service): $key"
fi
done
done
# Set proper ownership and permissions
chmod 600 "$SIMPLEX_DIR"/*_configs/ca.key 2>/dev/null || true
chmod 600 "$SIMPLEX_DIR"/*_tor/hs_ed25519_secret_key 2>/dev/null || true
# ----------------------------------------------------------------------------
# 7. Start services
# ----------------------------------------------------------------------------
log "Starting services..."
# Start firewall services
rc-service iptables start || rc-service iptables restart || true
rc-service ip6tables start || rc-service ip6tables restart || true
# Configure and start sshguard (basic setup - backup.sh doesn't save the full config)
mkdir -p /etc/sshguard
cat > /etc/sshguard/sshguard.conf <<'EOF'
BACKEND="/usr/libexec/sshg-fw-iptables"
LOGREADER="LANG=C journalctl -afb -p info -n1 -u sshd -o cat"
THRESHOLD=30
BLOCK_TIME=300
DETECTION_TIME=1800
PID_FILE=/run/sshguard.pid
EOF
# Basic sshguard iptables setup
cat > /etc/local.d/sshguard-iptables.start <<'EOF'
#!/bin/sh
SSH_PORT=$(awk '/^Port / {print $2; exit}' /etc/ssh/sshd_config)
SSH_PORT=${SSH_PORT:-22}
for ipt in iptables ip6tables; do
$ipt -N sshguard 2>/dev/null || true
$ipt -C INPUT -p tcp --dport "$SSH_PORT" -j sshguard 2>/dev/null \
|| $ipt -I INPUT -p tcp --dport "$SSH_PORT" -j sshguard
done
EOF
chmod +x /etc/local.d/sshguard-iptables.start
rc-update add local default 2>/dev/null || true
/etc/local.d/sshguard-iptables.start
rc-service sshguard start || true
# Start docker
rc-service docker start || true
# Wait for docker socket
for _ in $(seq 1 20); do
[[ -S /var/run/docker.sock ]] && break
sleep 1
done
if [[ ! -S /var/run/docker.sock ]]; then
die "Docker socket didn't appear after starting service"
fi
# ----------------------------------------------------------------------------
# 8. Deploy SimpleX stack
# ----------------------------------------------------------------------------
if [[ -f "$SIMPLEX_DIR/docker-compose.yml" && -f "$SIMPLEX_DIR/.env" ]]; then
log "Starting SimpleX docker stack..."
cd "$SIMPLEX_DIR"
docker compose pull
docker compose up -d
log "Waiting for services to stabilize..."
sleep 10
# Show status
docker compose ps
else
warn "SimpleX compose files not found; skipping docker deployment"
fi
# ----------------------------------------------------------------------------
# 9. SSH service restart (do this last so we don't kill our session early)
# ----------------------------------------------------------------------------
log "Reloading SSH service with restored configuration..."
rc-service sshd reload || rc-service sshd restart || true
# ----------------------------------------------------------------------------
# 10. Cleanup and final report
# ----------------------------------------------------------------------------
log "Cleaning up temporary files..."
rm -rf "$RESTORE_DIR"
# Display current status and next steps
cat <<EOF
================================================================
RESTORE COMPLETE
================================================================
Services Status:
$(rc-service --list | grep -E '(docker|sshd|iptables|sshguard)' || true)
Next Steps:
1. VERIFY SSH ACCESS STILL WORKS
Test from another terminal before closing this session:
ssh -i ~/.ssh/your_key root@$(hostname)
2. CHECK SIMPLEX SERVICES
cd $SIMPLEX_DIR && docker compose ps
./print-addresses.sh
3. VERIFY SERVER FINGERPRINTS
Compare these to your original backup to confirm identities were preserved:
SSH host key:
$(ssh-keygen -l -f /etc/ssh/ssh_host_ed25519_key.pub 2>/dev/null | sed 's/^/ /' || echo " [not found]")
SMP server (when ready):
$(cd "$SIMPLEX_DIR" 2>/dev/null && docker compose logs smp-server 2>/dev/null | grep -m1 'Server address:' | sed 's/^/ /' || echo " [check with: cd $SIMPLEX_DIR && docker compose logs smp-server]")
4. VERIFY .ONION ADDRESSES
These should match your backup:
SMP: $(cat "$SIMPLEX_DIR/smp_tor/hostname" 2>/dev/null || echo "[not yet available]")
XFTP: $(cat "$SIMPLEX_DIR/xftp_tor/hostname" 2>/dev/null || echo "[not yet available]")
5. UPDATE DNS
Ensure smp.yourdomain.com and xftp.yourdomain.com point to this host
6. TEST CONNECTIONS
Verify existing SimpleX contacts can still reach your server
================================================================
EOF
+16
View File
@@ -0,0 +1,16 @@
# Copy to .env and fill in. docker compose picks .env up automatically.
# Apex domain to serve from (no scheme). Caddy auto-issues an LE cert.
BASE_DOMAIN=example.com
# OIDC issuer URL for WebFinger discovery (your pocket-id deployment).
ISSUER_URL=https://auth.example.com
# Where to send any non-WebFinger request (preserves path + query).
REDIRECT_URL=https://your-redirect-target.example.com
# Let's Encrypt registration email.
ACME_EMAIL=admin@example.com
# Image tag.
CADDY_TAG=2-alpine
+50
View File
@@ -0,0 +1,50 @@
# Caddyfile for the webfinger + redirect stack.
#
# - /.well-known/webfinger -> dynamic JRD response, echoing the queried
# resource as `subject` and pointing OIDC discovery at $ISSUER_URL.
# - everything else -> 301 to $REDIRECT_URL (preserving path + query).
#
# To also serve www: change `{$BASE_DOMAIN}` below to
# `{$BASE_DOMAIN}, www.{$BASE_DOMAIN}`.
{
email {$ACME_EMAIL}
# Staging CA for testing without burning LE rate limits:
# acme_ca https://acme-staging-v02.api.letsencrypt.org/directory
}
{$BASE_DOMAIN} {
encode zstd gzip
@webfinger path /.well-known/webfinger
handle @webfinger {
header Content-Type "application/jrd+json"
header Cache-Control "public, max-age=3600"
templates
respond `{
"subject": "{{.Req.URL.Query.Get "resource"}}",
"links": [
{
"rel": "http://openid.net/specs/connect/1.0/issuer",
"href": "{$ISSUER_URL}"
}
]
}` 200
}
handle {
redir {$REDIRECT_URL}{uri} permanent
}
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Content-Type-Options "nosniff"
Referrer-Policy "strict-origin-when-cross-origin"
-Server
}
log {
output stdout
format console
}
}
+42
View File
@@ -0,0 +1,42 @@
# webfinger
A single Caddy container that serves `/.well-known/webfinger` at an apex domain
(for OIDC issuer discovery — used by Tailscale and others) and 301-redirects
everything else to a target URL.
## Required `.env` values
| Variable | Notes |
|----------|-------|
| `BASE_DOMAIN` | Apex domain to serve from (e.g. `example.com`). |
| `ISSUER_URL` | OIDC issuer for the WebFinger response (your [pocket-id](../pocket-id/)). |
| `REDIRECT_URL` | Where non-WebFinger traffic is redirected (path + query preserved). |
| `ACME_EMAIL` | Let's Encrypt registration email. |
See [`.env.example`](.env.example).
## Deploy
```bash
./automations.sh # Deploy on this host → deploy: webfinger
```
Or build + run the self-contained artifact:
```bash
./build.sh
scp deploy.sh root@host:
ssh root@host 'bash deploy.sh'
# non-interactive:
# BASE_DOMAIN=example.com ISSUER_URL=https://auth.example.com \
# REDIRECT_URL=https://example.org ACME_EMAIL=me@example.com SKIP_PROMPTS=1 bash deploy.sh
```
Unattended provisioning: [`cloud-init.yml`](cloud-init.yml).
## Notes
- Standalone: binds 80/443 itself, so don't co-locate with another stack that
wants those ports.
- DNS for `BASE_DOMAIN` must resolve to the host and 80/443 be reachable before
deploy.
+34
View File
@@ -0,0 +1,34 @@
#!/usr/bin/env bash
#
# build.sh -- (re)embed docker-compose.yml, Caddyfile, .env.example into
# deploy.sh as a base64-encoded tar.gz payload after __ARCHIVE_BELOW__.
# Idempotent: strips any existing payload first.
set -euo pipefail
DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
SCRIPT="$DIR/deploy.sh"
MARKER="__ARCHIVE_BELOW__"
[[ -f "$SCRIPT" ]] || { echo "deploy.sh not found at $SCRIPT" >&2; exit 1; }
for f in docker-compose.yml Caddyfile .env.example; do
[[ -f "$DIR/$f" ]] || { echo "Missing $DIR/$f" >&2; exit 1; }
done
PAYLOAD=$(tar -czf - -C "$DIR" docker-compose.yml Caddyfile .env.example | base64)
TMP=$(mktemp)
trap 'rm -f "$TMP"' EXIT
sed "/^${MARKER}\$/,\$d" "$SCRIPT" > "$TMP"
{
echo "$MARKER"
echo "$PAYLOAD"
} >> "$TMP"
mv "$TMP" "$SCRIPT"
chmod +x "$SCRIPT"
trap - EXIT
size=$(wc -c < "$SCRIPT")
echo "Built $SCRIPT (${size} bytes)"
+33
View File
@@ -0,0 +1,33 @@
#cloud-config
#
# WebFinger + redirect — unattended deploy on a fresh Alpine host.
#
# Fill in REPO_URL and the values in the runcmd block, then paste this as the
# instance user-data. DNS for BASE_DOMAIN must point at this host and ports
# 80/443 must be reachable before boot, or the LE cert request fails.
packages:
- git
runcmd:
- hostnamectl set-hostname webfinger || true
- |
set -e
REPO_URL=https://git.anomalous.dev/57_Wolve/automations.git
REPO_BRANCH=main
git clone --depth 1 --branch "$REPO_BRANCH" "$REPO_URL" /opt/automations
cd /opt/automations
# Optional: install shared admin SSH keys from globals/ for root before deploy
# . scripts/lib.sh && load_globals \
# && install -d -m700 /root/.ssh && resolve_ssh_keys >> /root/.ssh/authorized_keys
# Optional: harden SSH first (prints a fresh root key — capture it!)
# SKIP_PROMPTS=1 FORCE=1 bash scripts/harden-ssh.sh
BASE_DOMAIN=example.com \
ISSUER_URL=https://auth.example.com \
REDIRECT_URL=https://example.org \
ACME_EMAIL=admin@example.com \
SKIP_PROMPTS=1 \
bash deployments/webfinger/deploy.sh
+277
View File
@@ -0,0 +1,277 @@
#!/usr/bin/env bash
#
# deploy.sh -- deploy the webfinger stack (a single Caddy container) on
# Alpine. Serves /.well-known/webfinger at $BASE_DOMAIN for OIDC discovery
# and redirects everything else to $REDIRECT_URL.
#
# Single-node: runs as root.
#
# What this does:
# 1. Installs docker + docker-cli-compose if missing.
# 2. Lays down docker-compose.yml, Caddyfile, .env.example in $STACK_DIR.
# 3. Generates .env on first run; existing .env is never overwritten.
# 4. Prompts for required values not preset (BASE_DOMAIN, ISSUER_URL,
# REDIRECT_URL, ACME_EMAIL).
# 5. Opens TCP 80/443 in UFW if active.
# 6. Pulls images, brings the stack up, waits for healthchecks.
#
# Idempotent: re-run to apply config changes / pull new images.
#
# Self-contained: docker-compose.yml, Caddyfile, .env.example are embedded
# as a base64-encoded tar.gz at the bottom of this file. Rebuild with
# build.sh after editing the loose source files.
#
# Usage:
# bash deploy.sh # interactive prompts
# BASE_DOMAIN=example.com ISSUER_URL=https://auth.example.com \
# REDIRECT_URL=https://example.org ACME_EMAIL=me@example.com \
# FORCE=1 bash deploy.sh
# STACK_DIR=/opt/webfinger bash deploy.sh
# SKIP_DOCKER_INSTALL=1 bash deploy.sh
set -euo pipefail
: "${STACK_DIR:=/srv/webfinger}"
: "${SKIP_DOCKER_INSTALL:=0}"
: "${FORCE:=0}"
: "${SKIP_PROMPTS:=0}" # non-interactive: require values via env, no prompts
[[ "$SKIP_PROMPTS" == "1" ]] && FORCE=1
: "${BASE_DOMAIN:=}"
: "${ISSUER_URL:=}"
: "${REDIRECT_URL:=}"
: "${ACME_EMAIL:=}"
log() { printf '\033[1;32m[+]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[!]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[x]\033[0m %s\n' "$*" >&2; exit 1; }
[[ $EUID -eq 0 ]] || die "Run as root."
# ---------------------------------------------------------------------------
# OS detection + Docker install (Alpine / Debian / Alma). This deploy.sh is
# self-contained (scp'd standalone), so the OS logic is inlined here instead
# of sourced from scripts/oslib.sh.
# ---------------------------------------------------------------------------
osfam() {
local id="" like=""
if [[ -r /etc/os-release ]]; then
id="$(. /etc/os-release 2>/dev/null && echo "${ID:-}")"
like="$(. /etc/os-release 2>/dev/null && echo "${ID_LIKE:-}")"
fi
case " $id $like " in
*" alpine "*) echo alpine ;;
*" debian "*|*" ubuntu "*) echo debian ;;
*" rhel "*|*" fedora "*|*" centos "*) echo rhel ;;
*) echo "${id:-unknown}" ;;
esac
}
install_docker() {
if command -v docker >/dev/null 2>&1; then
log "Docker already installed: $(docker --version)"
else
log "Installing Docker (OS: $(osfam))..."
case "$(osfam)" in
alpine) apk add -q docker docker-cli-compose openrc ;;
debian|rhel) command -v curl >/dev/null 2>&1 || \
{ command -v apt-get >/dev/null 2>&1 && apt-get install -y -qq curl; } || \
{ command -v dnf >/dev/null 2>&1 && dnf install -y -q curl; }
curl -fsSL https://get.docker.com | sh ;;
*) die "Unsupported OS for auto Docker install. Set SKIP_DOCKER_INSTALL=1 and install Docker yourself." ;;
esac
fi
if command -v rc-update >/dev/null 2>&1; then
rc-update add docker default >/dev/null 2>&1 || true
rc-service docker status >/dev/null 2>&1 || rc-service docker start
elif command -v systemctl >/dev/null 2>&1; then
systemctl enable --now docker >/dev/null 2>&1 || systemctl start docker || true
fi
}
open_web_ports() {
if command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q '^Status: active'; then
log "ufw active -- allowing 80,443/tcp..."
ufw allow 80/tcp >/dev/null; ufw allow 443/tcp >/dev/null
elif command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1; then
log "firewalld active -- allowing http,https..."
firewall-cmd -q --add-service=http --permanent
firewall-cmd -q --add-service=https --permanent
firewall-cmd -q --reload
fi
}
# ----------------------------------------------------------------------------
# Extract embedded archive
# ----------------------------------------------------------------------------
SCRIPT_DIR=$(mktemp -d -t webfinger-deploy.XXXXXX)
trap 'rm -rf "$SCRIPT_DIR"' EXIT
extract_archive() {
grep -a -A 9999999 '^__ARCHIVE_BELOW__$' "$0" \
| tail -n +2 \
| base64 -d \
| tar -xz -C "$SCRIPT_DIR"
}
if grep -q -a '^__ARCHIVE_BELOW__$' "$0"; then
log "Extracting embedded deployment files..."
extract_archive
else
die "No embedded archive found. Run build.sh to embed deployment files."
fi
for f in docker-compose.yml Caddyfile .env.example; do
[[ -f "$SCRIPT_DIR/$f" ]] || die "Embedded archive missing $f"
done
# ----------------------------------------------------------------------------
# Prompt for required vars
# ----------------------------------------------------------------------------
prompt() {
local varname="$1" message="$2"
local -n ref="$varname"
if [[ -z "${ref:-}" ]]; then
[[ "$SKIP_PROMPTS" == "1" ]] && die "$varname required (set it in the environment; running with SKIP_PROMPTS=1)."
read -r -p "$message: " ref
[[ -n "$ref" ]] || die "$varname required."
fi
}
prompt BASE_DOMAIN "Apex domain to serve from (e.g. example.com)"
prompt ISSUER_URL "OIDC issuer URL (e.g. https://auth.example.com)"
prompt REDIRECT_URL "Where to redirect non-webfinger traffic (e.g. https://example.org)"
prompt ACME_EMAIL "Let's Encrypt email"
# ----------------------------------------------------------------------------
# Docker
# ----------------------------------------------------------------------------
if [[ "$SKIP_DOCKER_INSTALL" != "1" ]]; then
install_docker
fi
# Open 80/443 on whichever host firewall is active.
open_web_ports
# ----------------------------------------------------------------------------
# Stack directory + files
# ----------------------------------------------------------------------------
log "Setting up $STACK_DIR..."
install -d -m 0750 "$STACK_DIR"
install -m 0640 "$SCRIPT_DIR/docker-compose.yml" "$STACK_DIR/docker-compose.yml"
install -m 0640 "$SCRIPT_DIR/Caddyfile" "$STACK_DIR/Caddyfile"
ENV_FILE="$STACK_DIR/.env"
if [[ ! -f "$ENV_FILE" ]]; then
log "Seeding $ENV_FILE..."
install -m 0600 "$SCRIPT_DIR/.env.example" "$ENV_FILE"
sed -i \
-e "s|^BASE_DOMAIN=.*|BASE_DOMAIN=${BASE_DOMAIN}|" \
-e "s|^ISSUER_URL=.*|ISSUER_URL=${ISSUER_URL}|" \
-e "s|^REDIRECT_URL=.*|REDIRECT_URL=${REDIRECT_URL}|" \
-e "s|^ACME_EMAIL=.*|ACME_EMAIL=${ACME_EMAIL}|" \
"$ENV_FILE"
else
log ".env exists; leaving it alone."
fi
# Validate required values are present.
missing=()
for var in BASE_DOMAIN ISSUER_URL REDIRECT_URL ACME_EMAIL; do
grep -E "^${var}=.+$" "$ENV_FILE" >/dev/null || missing+=("$var")
done
(( ${#missing[@]} == 0 )) || die "Missing values in $ENV_FILE: ${missing[*]}"
# ----------------------------------------------------------------------------
# Bring up the stack
# ----------------------------------------------------------------------------
if [[ "$FORCE" != "1" ]]; then
cat <<EOF
About to pull images and start the stack from $STACK_DIR.
Caddy will request a Let's Encrypt cert for ${BASE_DOMAIN}. DNS for that
name must already point at this host, and ports 80/443 must be reachable
from the internet, or the cert request will fail.
Continue? [y/N]
EOF
read -r ans
[[ "${ans,,}" == "y" || "${ans,,}" == "yes" ]] || { warn "Aborted."; exit 0; }
fi
cd "$STACK_DIR"
log "Pulling images..."
docker compose pull
log "Starting stack..."
docker compose up -d --remove-orphans
# ----------------------------------------------------------------------------
# Wait for health
# ----------------------------------------------------------------------------
log "Waiting for services to become healthy (up to 120s)..."
deadline=$(( $(date +%s) + 120 ))
while (( $(date +%s) < deadline )); do
status=$(docker compose ps --format '{{.Service}} {{.Health}}' 2>/dev/null || true)
unhealthy=$(echo "$status" | awk '$2 != "healthy" && $2 != "" {print $1}')
if [[ -z "$unhealthy" && -n "$status" ]]; then
log "All services healthy."
break
fi
sleep 5
done
echo
log "Stack status:"
docker compose ps
echo
cat <<EOF
================================================================
DEPLOYED
WebFinger: https://${BASE_DOMAIN}/.well-known/webfinger
Redirects: https://${BASE_DOMAIN}/ -> ${REDIRECT_URL}
Stack dir: $STACK_DIR
Manage (run from $STACK_DIR):
docker compose logs -f
docker compose pull && docker compose up -d # update
docker compose down # stop, keep volumes
Or just re-run this script -- it's idempotent.
================================================================
EOF
# IMPORTANT: do not put any code below this exit. Everything after the
# __ARCHIVE_BELOW__ marker is the embedded tar.gz payload (base64).
exit 0
__ARCHIVE_BELOW__
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
+38
View File
@@ -0,0 +1,38 @@
# webfinger stack -- one Caddy container that serves /.well-known/webfinger
# at $BASE_DOMAIN (for OIDC discovery from Tailscale et al.) and redirects
# everything else to $REDIRECT_URL.
#
# Standalone: this binds 80/443 itself, so don't run it on the same host as
# another stack that also wants those ports unless you put a TCP balancer
# in front or merge the configs.
name: webfinger
volumes:
caddy-data:
caddy-config:
services:
caddy:
image: caddy:${CADDY_TAG:-2-alpine}
container_name: caddy-webfinger
restart: unless-stopped
ports:
- "80:80"
- "443:443"
- "443:443/udp" # HTTP/3
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data
- caddy-config:/config
environment:
BASE_DOMAIN: "${BASE_DOMAIN}"
ISSUER_URL: "${ISSUER_URL}"
REDIRECT_URL: "${REDIRECT_URL}"
ACME_EMAIL: "${ACME_EMAIL}"
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:2019/config/"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s