feat: add optional letsencrypt tls

This commit is contained in:
bisco
2026-06-24 11:06:33 +02:00
parent 1e3685bab8
commit 719cdce9c1
19 changed files with 561 additions and 62 deletions
+106
View File
@@ -0,0 +1,106 @@
#!/bin/sh
set -eu
enabled="${LETSENCRYPT_ENABLED:-0}"
domain="${LETSENCRYPT_DOMAIN:-azionelab.org}"
interval="${TLS_RELOAD_INTERVAL_SECONDS:-30}"
certificate="/etc/letsencrypt/live/${domain}/fullchain.pem"
private_key="/etc/letsencrypt/live/${domain}/privkey.pem"
http_config="/etc/nginx/http-enabled/site.conf"
tls_config="/etc/nginx/tls-enabled/site.conf"
tls_template="/etc/nginx/templates/tls.conf.template.source"
base_template="/etc/nginx/templates/default.conf.template.source"
base_config="/etc/nginx/conf.d/default.conf"
proxy_routes="/etc/nginx/snippets/proxy-routes.conf"
case "$domain" in
"" | *[!A-Za-z0-9.-]* | .* | *. | *..* | -* | *- | *.-* | *-.*)
echo "Invalid LETSENCRYPT_DOMAIN: $domain" >&2
exit 1
;;
esac
case "$domain" in
*.*) ;;
*)
echo "LETSENCRYPT_DOMAIN must be a fully qualified domain name." >&2
exit 1
;;
esac
case "$enabled" in
0 | 1) ;;
*)
echo "LETSENCRYPT_ENABLED must be 0 or 1." >&2
exit 1
;;
esac
case "$interval" in
"" | *[!0-9]*)
echo "TLS_RELOAD_INTERVAL_SECONDS must be a positive integer." >&2
exit 1
;;
esac
if [ "$interval" -eq 0 ]; then
echo "TLS_RELOAD_INTERVAL_SECONDS must be a positive integer." >&2
exit 1
fi
certificate_state() {
if [ ! -s "$certificate" ] || [ ! -s "$private_key" ]; then
echo "missing"
return
fi
cksum "$certificate" "$private_key" | cksum | awk '{print $1 ":" $2}'
}
render_http_only() {
printf 'include %s;\n' "$proxy_routes" > "$http_config"
rm -f "$tls_config"
}
render_https() {
sed "s|__DOMAIN__|${domain}|g" "$tls_template" > "${tls_config}.tmp"
mv "${tls_config}.tmp" "$tls_config"
printf 'location ^~ / { return 301 https://$host$request_uri; }\n' > "$http_config"
}
sed "s|__DOMAIN__|${domain}|g" "$base_template" > "${base_config}.tmp"
mv "${base_config}.tmp" "$base_config"
if [ "$enabled" != "1" ]; then
render_http_only
exit 0
fi
state="$(certificate_state)"
if [ "$state" = "missing" ]; then
render_http_only
else
render_https
fi
(
while sleep "$interval"; do
next_state="$(certificate_state)"
if [ "$next_state" = "$state" ]; then
continue
fi
if [ "$next_state" = "missing" ]; then
render_http_only
else
render_https
fi
if nginx -t; then
nginx -s reload
state="$next_state"
else
echo "TLS configuration reload failed; retrying after ${interval}s." >&2
fi
done
) &