#!/usr/bin/env bash # Configure api. as the TLS/CORS reverse proxy for one tenant. # Idempotent. Run as root after both storefront and API DNS records resolve here. set -euo pipefail DOMAIN="" EMAIL="" UPSTREAM="https://127.0.0.1:445" while [[ $# -gt 0 ]]; do case "$1" in --domain) DOMAIN="$2"; shift 2 ;; --email) EMAIL="$2"; shift 2 ;; --upstream) UPSTREAM="$2"; shift 2 ;; *) echo "unknown argument: $1" >&2; exit 2 ;; esac done [[ $EUID -eq 0 ]] || { echo "must run as root" >&2; exit 1; } [[ "$DOMAIN" =~ ^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$ ]] || { echo "--domain must be a valid lowercase hostname" >&2; exit 2; } [[ "$EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]] || { echo "--email must be valid" >&2; exit 2; } [[ "$UPSTREAM" =~ ^https?://[a-zA-Z0-9.:-]+$ ]] || { echo "--upstream must be an http(s) origin without a path" >&2; exit 2; } API_DOMAIN="api.$DOMAIN" CONF="/etc/nginx/sites-available/$API_DOMAIN" echo "==> checking DNS for $API_DOMAIN" getent hosts "$API_DOMAIN" >/dev/null || { echo "ERROR: $API_DOMAIN does not resolve; create DNS before provisioning TLS" >&2 exit 1 } cat > "$CONF" < verifying https://$API_DOMAIN/bootstrap" bootstrap_tmp="$(mktemp)" trap 'rm -f "$bootstrap_tmp"' EXIT content_type="$(curl --resolve "$API_DOMAIN:443:127.0.0.1" -fsS \ -o "$bootstrap_tmp" -w '%{content_type}' \ "https://$API_DOMAIN/bootstrap")" [[ "$content_type" == application/json* ]] || { echo "ERROR: $API_DOMAIN/bootstrap returned $content_type, expected application/json" >&2 exit 1 } jq -e 'type == "object"' "$bootstrap_tmp" >/dev/null rm -f "$bootstrap_tmp" trap - EXIT echo "configured: $DOMAIN -> https://$API_DOMAIN -> $UPSTREAM"