Something went wrong. Try again.
Pretty cool forms service. Code is slop btw. forked from chernigin.com/lively-forms
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419#!/usr/bin/env bash# Ships the working tree to a host over ssh and runs it there with# podman-compose and systemd. This is the author's setup; the container image# with compose.prod.yaml is the general path, see docs/deployment.md.set -euo pipefail
usage() { cat >&2 <<'USAGE'Required environment variables:
DEPLOY_HOST ssh destination, for example root@forms.example.com PUBLIC_URL HTTPS origin served by the reverse proxy, for example https://forms.example.com (forwarded to the app on PORT) STORAGE_PUBLIC_URL HTTPS origin the proxy forwards to Garage on port 3900, for example https://storage.example.com; browsers upload there. Not needed with ENABLE_STORAGE=0.
Optional: DEPLOY_DIR=/opt/lively-forms PORT=8000 SERVICE_NAME=lively-forms RESET_DB=0 ENABLE_STORAGE=1 SYNC_PROVIDER_ENV=0
Example:
DEPLOY_HOST=root@forms.example.com \ PUBLIC_URL=https://forms.example.com \ STORAGE_PUBLIC_URL=https://storage.example.com \ bun run deployUSAGE exit 1}
DEPLOY_HOST="${DEPLOY_HOST:-}"DEPLOY_DIR="${DEPLOY_DIR:-/opt/lively-forms}"PORT="${PORT:-8000}"# OAuth URLs must always use the public HTTPS origin, never the upstream URL.PUBLIC_URL="${PUBLIC_URL:-}"SERVICE_NAME="${SERVICE_NAME:-lively-forms}"# RESET_DB=1 drops the compose volumes before starting them, so the migrations# apply to an empty database. Everything stored on the server is lost.RESET_DB="${RESET_DB:-0}"# ENABLE_STORAGE=0 skips the Garage setup (layout, bucket, key, CORS, S3_* in .env).ENABLE_STORAGE="${ENABLE_STORAGE:-1}"# Written to .env as S3_PUBLIC_ENDPOINT.STORAGE_PUBLIC_URL="${STORAGE_PUBLIC_URL:-}"# SYNC_PROVIDER_ENV=1 copies the OIDC_*, GITHUB_* and GOOGLE_* lines of the# local .env into the server .env, replacing the keys that are already there.SYNC_PROVIDER_ENV="${SYNC_PROVIDER_ENV:-0}"
if [ -z "${DEPLOY_HOST}" ] || [ -z "${PUBLIC_URL}" ]; then usagefiif [ "${ENABLE_STORAGE}" = "1" ] && [ -z "${STORAGE_PUBLIC_URL}" ]; then usagefi
echo "Deploying to ${DEPLOY_HOST}:${DEPLOY_DIR} on port ${PORT}"echo "Public URL: ${PUBLIC_URL}"echo "Flags: RESET_DB=${RESET_DB} ENABLE_STORAGE=${ENABLE_STORAGE} SYNC_PROVIDER_ENV=${SYNC_PROVIDER_ENV}"if [ "${ENABLE_STORAGE}" = "1" ]; then echo "Storage public URL: ${STORAGE_PUBLIC_URL} (browsers upload there)"fi
# The archive only adds files, so the tree is cleared first: a file removed# locally would otherwise linger on the server and end up in the build. The# server .env, the previous build and the installed packages are kept.ssh "${DEPLOY_HOST}" "mkdir -p '${DEPLOY_DIR}' && find '${DEPLOY_DIR}' -mindepth 1 -maxdepth 1 ! -name .env ! -name .next ! -name node_modules -exec rm -rf {} +"
COPYFILE_DISABLE=1 tar \ --no-xattrs \ --exclude='.git' \ --exclude='.env' \ --exclude='.next' \ --exclude='node_modules' \ --exclude='coverage' \ --exclude='test-results' \ --exclude='playwright-report' \ --exclude='.DS_Store' \ -czf - . | ssh "${DEPLOY_HOST}" "tar -xzf - -C '${DEPLOY_DIR}'"
# The provider lines travel through the ssh pipe into a temporary file that# the remote step merges into .env and removes; nothing is echoed.if [ "${SYNC_PROVIDER_ENV}" = "1" ]; then if [ ! -f .env ]; then echo "SYNC_PROVIDER_ENV=1 but there is no local .env" >&2 exit 1 fi grep -E '^(OIDC_|GITHUB_|GOOGLE_)[A-Z_]*=' .env \ | ssh "${DEPLOY_HOST}" "umask 077; cat > '${DEPLOY_DIR}/.env.providers'" echo "Provider variables sent: $(grep -oE '^(OIDC_|GITHUB_|GOOGLE_)[A-Z_]*' .env | tr '\n' ' ')"fi
ssh "${DEPLOY_HOST}" bash -s -- "${DEPLOY_DIR}" "${PORT}" "${PUBLIC_URL}" "${SERVICE_NAME}" "${RESET_DB}" "${ENABLE_STORAGE}" "${STORAGE_PUBLIC_URL}" <<'REMOTE'set -euo pipefail
DEPLOY_DIR="$1"PORT="$2"PUBLIC_URL="$3"SERVICE_NAME="$4"RESET_DB="$5"ENABLE_STORAGE="$6"STORAGE_PUBLIC_URL="$7"COMPOSE_SERVICE_NAME="${SERVICE_NAME}-compose"CLEANUP_NAME="${SERVICE_NAME}-cleanup"
if ! command -v podman >/dev/null 2>&1 || ! command -v podman-compose >/dev/null 2>&1 || ! command -v unzip >/dev/null 2>&1 || ! command -v openssl >/dev/null 2>&1; then apt-get update apt-get install -y podman podman-compose unzip opensslfi
if ! command -v node >/dev/null 2>&1 || ! node -e 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)'; then apt-get update . /etc/os-release if [ "${ID:-}" = "altlinux" ]; then apt-get install -y node else apt-get install -y ca-certificates curl gnupg curl -fsSL https://deb.nodesource.com/setup_22.x | bash - apt-get install -y nodejs fifi
export BUN_INSTALL="${HOME}/.bun"export PATH="${BUN_INSTALL}/bin:${PATH}"if ! command -v bun >/dev/null 2>&1; then curl -fsSL https://bun.sh/install | bashfi
PODMAN_COMPOSE="$(command -v podman-compose)"
cd "${DEPLOY_DIR}"
# The container secrets are generated once and kept in .env, which compose# reads. Postgres applies its password only when the volume is created.if [ ! -f .env ]; then AUTH_SECRET="$(openssl rand -base64 32)" POSTGRES_PASSWORD="$(openssl rand -hex 32)" umask 077 cat > .env <<ENVPOSTGRES_PASSWORD="${POSTGRES_PASSWORD}"GARAGE_RPC_SECRET="$(openssl rand -hex 32)"GARAGE_ADMIN_TOKEN="$(openssl rand -hex 32)"DATABASE_URL="postgresql://lively_forms:${POSTGRES_PASSWORD}@127.0.0.1:5432/lively_forms?schema=public"AUTH_SECRET="${AUTH_SECRET}"NEXTAUTH_URL="${PUBLIC_URL}"ATPROTO_PUBLIC_URL="${PUBLIC_URL}"ATPROTO_CLIENT_ID="${PUBLIC_URL}/api/atproto/client-metadata"ATPROTO_REDIRECT_URI="${PUBLIC_URL}/api/auth/atproto/callback"ATPROTO_CLIENT_NAME="Lively Forms"ENV umask 022fi
# Pins the public URLs, adds the container secrets an older .env lacks,# merges the provider lines sent from the local .env (if any) and appends the# optional keys as commented placeholders so the server .env documents what# can be set. Existing values are kept, except DATABASE_URL after RESET_DB=1:# the new volume has the compose credentials.python3 - "${PUBLIC_URL}" "${RESET_DB}" <<'PY'from pathlib import Pathimport reimport secretsimport syspublic_url = sys.argv[1]reset_db = sys.argv[2] == '1'path = Path('.env')lines = path.read_text().splitlines()
def key_of(line): match = re.match(r'^#?\s*([A-Z][A-Z0-9_]*)=', line) return match.group(1) if match else None
def value_of(key): for line in lines: if line.startswith(f'{key}='): return line.split('=', 1)[1].strip().strip('"') return None
for key in ('POSTGRES_PASSWORD', 'GARAGE_RPC_SECRET', 'GARAGE_ADMIN_TOKEN'): if value_of(key) is None: lines.append(f'{key}="{secrets.token_hex(32)}"') note = '' if key == 'POSTGRES_PASSWORD': note = '; the existing database keeps its old password until it is changed by hand, see docs/deployment.md' print(f'Added {key} to .env{note}')
updates = { 'NEXTAUTH_URL': f'"{public_url}"', 'ATPROTO_PUBLIC_URL': f'"{public_url}"', 'ATPROTO_CLIENT_ID': f'"{public_url}/api/atproto/client-metadata"', 'ATPROTO_REDIRECT_URI': f'"{public_url}/api/auth/atproto/callback"',}if reset_db: updates['DATABASE_URL'] = f'"postgresql://lively_forms:{value_of("POSTGRES_PASSWORD")}@127.0.0.1:5432/lively_forms?schema=public"' print('RESET_DB=1: DATABASE_URL set to the compose credentials')providers = Path('.env.providers')if providers.exists(): for line in providers.read_text().splitlines(): if '=' in line and not line.startswith('#'): key, value = line.split('=', 1) updates[key.strip()] = value providers.unlink() print('Merged provider variables into .env')
seen = set()out = []for line in lines: key = key_of(line) if key in updates: if key in seen: continue out.append(f'{key}={updates[key]}') seen.add(key) else: out.append(line)for key, value in updates.items(): if key not in seen: out.append(f'{key}={value}')
template = f'''# Optional, defaults to "atproto transition:generic"# ATPROTO_SCOPE="atproto transition:generic"# Optional OAuth sign-in providers; each is shown only when its variables are set# GOOGLE_CLIENT_ID=""# GOOGLE_CLIENT_SECRET=""# GITHUB_CLIENT_ID=""# GITHUB_CLIENT_SECRET=""# OIDC_ISSUER="https://auth.example.com/realms/master"# OIDC_CLIENT_ID=""# OIDC_CLIENT_SECRET=""# OIDC_PROVIDER_NAME="SSO"# OIDC_PROVIDER_ICON_URL=""# OIDC_SCOPE="openid profile email"# Optional public submission limits, defaults shown# SUBMISSION_RATE_LIMIT=5# SUBMISSION_GLOBAL_RATE_LIMIT=30# SUBMISSION_RATE_WINDOW_SECONDS=600# SUBMISSION_MIN_FILL_SECONDS=3# Optional email notifications to form owners# MAIL_FROM="Lively Forms <forms@example.com>"# SMTP_URL="smtp://user:password@smtp.example.com:587"# SMTP_HOST="smtp.example.com"# SMTP_PORT=587# SMTP_USER="user"# SMTP_PASSWORD="password"# SMTP_SECURE=false# File uploads. S3_ENDPOINT is reached by the app on this host; S3_PUBLIC_ENDPOINT# is reached by the respondent's browser and is required in production (the gate# proxies it to Garage on this host, port 3900). Without it the FILE_UPLOAD block# reports uploads as not available.# S3_ENDPOINT="http://127.0.0.1:3900"# S3_PUBLIC_ENDPOINT="https://storage.example.com"# S3_REGION="garage"# S3_BUCKET="lively-forms"# S3_ACCESS_KEY_ID=""# S3_SECRET_ACCESS_KEY=""# UPLOAD_MAX_SIZE_MB=25# UPLOAD_RATE_LIMIT=20# UPLOAD_RATE_WINDOW_SECONDS=600'''present = {key_of(line) for line in out} - {None}pending_comments = []added = []for line in template.strip('\n').splitlines(): key = key_of(line) if key is None: pending_comments.append(line) continue if key in present: pending_comments = [] continue added.extend(pending_comments) pending_comments = [] added.append(line) present.add(key)if added: out.append('') out.extend(added) print(f'Added {sum(1 for l in added if key_of(l))} placeholder keys to .env')path.write_text('\n'.join(out).rstrip('\n') + '\n')PY
set -a. ./.envset +a
bun install --frozen-lockfile
if [ "${RESET_DB}" = "1" ]; then echo "RESET_DB=1: removing the compose containers and volumes, the database starts empty" "${PODMAN_COMPOSE}" down -v || true podman volume rm -f "$(basename "${DEPLOY_DIR}")_postgres-data" >/dev/null 2>&1 || true # The Garage volumes are gone too, so the key pair in .env is no longer valid. sed -i -E '/^#? ?S3_(ACCESS_KEY_ID|SECRET_ACCESS_KEY)=/d' .envfi
"${PODMAN_COMPOSE}" up -d
for _ in $(seq 1 30); do if podman exec lively-forms-postgres pg_isready -U lively_forms -d lively_forms >/dev/null 2>&1; then break fi sleep 1donepodman exec lively-forms-postgres pg_isready -U lively_forms -d lively_forms
if [ "${ENABLE_STORAGE}" = "1" ]; then # Writes S3_ENDPOINT, S3_REGION and S3_BUCKET into .env, the key pair only # when .env has none, and sets the bucket CORS rule for the public origin. GARAGE_ENV_FILE=.env \ GARAGE_KEY_NAME=lively-forms \ S3_ENDPOINT="http://127.0.0.1:3900" \ S3_BUCKET="lively-forms" \ UPLOAD_CORS_ORIGIN="${PUBLIC_URL}" \ bash scripts/garage-init.sh sed -i -E '/^#? ?S3_PUBLIC_ENDPOINT=/d' .env printf 'S3_PUBLIC_ENDPOINT="%s"\n' "${STORAGE_PUBLIC_URL}" >> .env echo "Set S3_PUBLIC_ENDPOINT in .env" set -a . ./.env set +afi
bunx prisma migrate deploybun run build
# Containers do not come back after a reboot on their own; this oneshot unit# brings the compose project up and the app unit requires it.cat > "/etc/systemd/system/${COMPOSE_SERVICE_NAME}.service" <<UNIT[Unit]Description=Lively Forms containers (podman-compose)After=network-online.targetWants=network-online.target
[Service]Type=oneshotRemainAfterExit=yesWorkingDirectory=${DEPLOY_DIR}EnvironmentFile=${DEPLOY_DIR}/.envExecStart=${PODMAN_COMPOSE} -f ${DEPLOY_DIR}/compose.yaml up -dExecStop=${PODMAN_COMPOSE} -f ${DEPLOY_DIR}/compose.yaml downTimeoutStartSec=300
[Install]WantedBy=multi-user.targetUNIT
cat > "/etc/systemd/system/${SERVICE_NAME}.service" <<UNIT[Unit]Description=Lively FormsRequires=${COMPOSE_SERVICE_NAME}.serviceAfter=network.target ${COMPOSE_SERVICE_NAME}.service
[Service]Type=simpleWorkingDirectory=${DEPLOY_DIR}Environment=NODE_ENV=productionEnvironment=PORT=${PORT}EnvironmentFile=${DEPLOY_DIR}/.envExecStart=${BUN_INSTALL}/bin/bun run start -- -H 0.0.0.0 -p ${PORT}Restart=alwaysRestartSec=5
[Install]WantedBy=multi-user.targetUNIT
# Pending uploads older than a day are removed every night at 04:00.CLEANUP_CMD="cd ${DEPLOY_DIR} && set -a && . ./.env && set +a && ${BUN_INSTALL}/bin/bun run uploads:cleanup"if systemctl is-active --quiet crond; then cat > "/etc/cron.d/${CLEANUP_NAME}" <<CRONPATH=${BUN_INSTALL}/bin:/usr/local/bin:/usr/bin:/bin0 4 * * * root ${CLEANUP_CMD} >> /var/log/${CLEANUP_NAME}.log 2>&1CRON chmod 644 "/etc/cron.d/${CLEANUP_NAME}" rm -f "/etc/systemd/system/${CLEANUP_NAME}.timer" "/etc/systemd/system/${CLEANUP_NAME}.service" echo "Cleanup scheduled through /etc/cron.d/${CLEANUP_NAME}"else cat > "/etc/systemd/system/${CLEANUP_NAME}.service" <<UNIT[Unit]Description=Lively Forms upload cleanupAfter=${COMPOSE_SERVICE_NAME}.service
[Service]Type=oneshotWorkingDirectory=${DEPLOY_DIR}Environment=PATH=${BUN_INSTALL}/bin:/usr/local/bin:/usr/bin:/binExecStart=/bin/bash -c '${CLEANUP_CMD}'UNIT cat > "/etc/systemd/system/${CLEANUP_NAME}.timer" <<UNIT[Unit]Description=Lively Forms upload cleanup, daily at 04:00
[Timer]OnCalendar=*-*-* 04:00:00Persistent=true
[Install]WantedBy=timers.targetUNIT rm -f "/etc/cron.d/${CLEANUP_NAME}" echo "Cleanup scheduled through ${CLEANUP_NAME}.timer (crond is not active)"fi
systemctl daemon-reloadsystemctl enable --now "${COMPOSE_SERVICE_NAME}"systemctl enable --now "${SERVICE_NAME}"systemctl restart "${SERVICE_NAME}"if [ -f "/etc/systemd/system/${CLEANUP_NAME}.timer" ]; then systemctl enable --now "${CLEANUP_NAME}.timer"fi
sleep 3echo "--- ${COMPOSE_SERVICE_NAME}: $(systemctl is-active "${COMPOSE_SERVICE_NAME}") ($(systemctl is-enabled "${COMPOSE_SERVICE_NAME}"))"echo "--- ${SERVICE_NAME}: $(systemctl is-active "${SERVICE_NAME}") ($(systemctl is-enabled "${SERVICE_NAME}"))"systemctl --no-pager --full status "${SERVICE_NAME}" || trueecho "--- http://127.0.0.1:${PORT}/ -> $(curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:${PORT}/")"REMOTE
echo "Deployed: ${PUBLIC_URL}"