Repository navigation
Expand file tree
/
Copy pathsetup.sh
More file actions
278 lines (261 loc) · 13.9 KB
/
Copy pathsetup.sh
File metadata and controls
278 lines (261 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env bash
# Space Works - guided first-run setup (Linux or macOS; on Windows, run it inside WSL2).
# Run it from the project folder: bash setup.sh
set -euo pipefail
cd "$(dirname "$0")"
ROOT="$PWD"
COMPOSE=("$ROOT/scripts/spaceworks-compose.sh" bundled)
source "$ROOT/scripts/env-file.sh"
source "$ROOT/scripts/host-image.sh"
BUILD_FROM_SOURCE=0
case "${1:-}" in
"") ;;
--build) BUILD_FROM_SOURCE=1 ;;
*) printf 'Usage: bash setup.sh [--build]\n' >&2; exit 64 ;;
esac
if [[ "$BUILD_FROM_SOURCE" == 1 ]]; then
export SPACEWORKS_COMPOSE_BUILD_LAYER=1
export SPACEWORKS_HOST_CONFIG_BUILD=1
HOST_CONFIG_IMAGE="spaceworks-host-configure:local"
else
unset SPACEWORKS_COMPOSE_BUILD_LAYER
export SPACEWORKS_HOST_CONFIG_BUILD=0
# Same image and tag precedence as the Compose wrapper, so host configuration is
# generated by the image the stack will actually run.
host_image="$(resolve_backend_image "$ROOT")" && host_tag="$(resolve_image_tag "$ROOT")" || {
printf 'ERROR: invalid backend image or image tag for host configuration.\n' >&2
exit 64
}
HOST_CONFIG_IMAGE="${host_image}:${host_tag}"
fi
say() { printf '\n\033[1;36m%s\033[0m\n' "$*"; }
warn() { printf '\033[1;33m%s\033[0m\n' "$*"; }
die() { printf '\033[1;31mERROR: %s\033[0m\n' "$*" >&2; exit 1; }
# Keeps the installer below the repository's file-size ceiling while sharing no
# ambient database pointer values with the privileged configuration helper.
source "$ROOT/scripts/setup-host-orchestration.sh"
source "$ROOT/scripts/module-selection.sh"
source "$ROOT/scripts/request-access-selection.sh"
source "$ROOT/scripts/setup-deploy-runner.sh"
source "$ROOT/scripts/retire-update-tombstone.sh"
source "$ROOT/scripts/retire-update-polling.sh"
# 1. Docker must be installed and running.
command -v docker >/dev/null 2>&1 || die "Docker is not installed. Install Docker Desktop first: https://www.docker.com/products/docker-desktop/"
docker info >/dev/null 2>&1 || die "Docker is installed but not running. Start Docker Desktop, then run this again."
docker compose version >/dev/null 2>&1 || die "The 'docker compose' plugin is missing. Update Docker Desktop."
# Subshell disables pipefail locally: `head` closing the pipe makes `tr` exit via SIGPIPE,
# which would otherwise abort the script under `set -o pipefail`.
rand_key() { ( set +o pipefail; LC_ALL=C tr -dc 'A-Za-z0-9' </dev/urandom | head -c "${1:-50}" ); }
fernet_key() { head -c 32 /dev/urandom | base64 | tr '+/' '-_'; }
FIRST_RUN=0
if [ -f .env ]; then
say "Found an existing .env — keeping your settings and secrets."
else
FIRST_RUN=1
say "Welcome! Let's set up Space Works. Press Enter to accept the [default]."
read -r -p "Web address (host name or IP, no http://) [localhost]: " WEBADDR; WEBADDR="${WEBADDR:-localhost}"
# Normalize: strip any scheme, path, and port so ALLOWED_HOSTS/CORS are valid.
WEBHOST="${WEBADDR#*://}"; WEBHOST="${WEBHOST%%/*}"; WEBHOST="${WEBHOST%%:*}"
[ -n "$WEBHOST" ] || WEBHOST="localhost"
read -r -p "Name of your makerspace [My Makerspace]: " MSNAME; MSNAME="${MSNAME:-My Makerspace}"
# Modules are NOT asked here. The question moved to the end of setup, where the app is
# running and the real registry can be read, so the operator ticks actual module names
# instead of memorising profile words. `recommended` is only the starting point the tick
# list opens with; nothing is final until that step.
MSPROFILE="recommended"
ask_request_access
ask_setup_identity
read -r -p "Stripe secret key (optional; leave blank to skip): " STRIPE_SECRET_KEY
read -r -s -p "Stripe webhook secret (optional; leave blank to skip): " STRIPE_WEBHOOK_SECRET; echo
read -r -p "Stripe default currency [usd]: " STRIPE_DEFAULT_CURRENCY; STRIPE_DEFAULT_CURRENCY="${STRIPE_DEFAULT_CURRENCY:-usd}"
# Braces are load-bearing: && and || have EQUAL precedence in bash and associate left,
# so the unbraced form parsed as ((A && B) || C) && D and silently accepted a secret key
# with no webhook secret -- writing a half-configured Stripe account with no warning.
if { [ -n "$STRIPE_SECRET_KEY" ] && [ -z "$STRIPE_WEBHOOK_SECRET" ]; } \
|| { [ -z "$STRIPE_SECRET_KEY" ] && [ -n "$STRIPE_WEBHOOK_SECRET" ]; }; then
warn "Stripe needs both secrets; leaving payments unconfigured."
STRIPE_SECRET_KEY=""; STRIPE_WEBHOOK_SECRET=""
fi
say "Writing .env (secrets generated automatically)..."
cat > .env <<EOF
# Generated by setup.sh — keep this file private; it holds your secrets.
POSTGRES_PASSWORD=$(rand_key 32)
POSTGRES_APP_PASSWORD=$(rand_key 32)
MINIO_ROOT_USER=$(rand_key 24)
MINIO_ROOT_PASSWORD=$(rand_key 40)
SECRET_KEY=$(rand_key 50)
API_CLIENT_ENC_KEY=$(fernet_key)
AUDIT_MAC_MASTER_KEY=$(fernet_key)
ALLOWED_HOSTS=${WEBHOST},localhost,127.0.0.1,backend
CORS_ALLOWED_ORIGINS=http://${WEBHOST}
# Absolute address of the app, for links that leave the site (email notices, invitations,
# event-station and payment-return links). Without it they are bare paths or localhost.
PUBLIC_APP_BASE_URL=http://${WEBHOST}
# Browser-facing object storage. These MUST name the address your users type, not
# localhost: they are baked into presigned evidence upload/view URLs and into every
# public image src. Left at the compose default (http://localhost:9000) the site works
# only from the server console and shows broken images to everyone else.
AWS_S3_PUBLIC_ENDPOINT_URL=http://${WEBHOST}:9000
PUBLIC_IMAGE_BASE_URL=http://${WEBHOST}:9000/public-images
# MinIO must accept browser uploads from the app's origin, or presigned POSTs are
# blocked by CORS before they ever reach storage.
MINIO_CORS_ALLOWED_ORIGINS=http://${WEBHOST}
HTTP_PORT=80
ENABLE_HTTPS=false
# Same-origin plain HTTP: a Secure cookie is dropped, so staff log in then get signed
# out on reload. The TLS overlay forces Secure back on; see docs/self-hosting.md.
AUTH_COOKIE_SAMESITE=Lax
AUTH_COOKIE_SECURE=False
EOF
fi
# Older .env files may lack these keys (or carry the example file's empty value). Fill
# only a missing or empty one; an existing key is never changed, it decrypts stored data.
AUDIT_KEY_ADDED=0
for key in API_CLIENT_ENC_KEY AUDIT_MAC_MASTER_KEY; do
[[ -z "$(env_file_get .env "$key")" ]] || continue
sed -E -i.bak "/^${key}=[[:space:]]*(\"\"|'')?[[:space:]]*$/d" .env && rm -f .env.bak
env_file_append_if_absent .env "$key" "$(fernet_key)" || die "Could not add $key to .env."
[[ "$key" != AUDIT_MAC_MASTER_KEY ]] || AUDIT_KEY_ADDED=1
done
# Existing installations predate the non-owner runtime database role. The privileged
# orchestration bootstrap creates/re-keys it before migrations or application startup.
if ! grep -q '^POSTGRES_APP_PASSWORD=' .env; then
printf '\nPOSTGRES_APP_PASSWORD=%s\n' "$(rand_key 32)" >> .env
fi
if ! grep -q '^SPACEWORKS_SCHEDULER_MODE=' .env; then
printf '\nSPACEWORKS_SCHEDULER_MODE=image\n' >> .env
fi
# Older bundled installs may predate explicit cookie settings. Backfill only when the
# file itself proves that both public app origins use plain HTTP and HTTPS is disabled;
# split-origin HTTPS intentionally needs the secure defaults and must remain untouched.
if ! grep -q '^AUTH_COOKIE_SAMESITE=' .env \
|| ! grep -q '^AUTH_COOKIE_SECURE=' .env; then
if { ! grep -q '^ENABLE_HTTPS=' .env \
|| grep -Eqi '^ENABLE_HTTPS=(false|0|no|off)$' .env; } \
&& grep -Eq '^CORS_ALLOWED_ORIGINS=http://[^[:space:],]+(,http://[^[:space:],]+)*$' .env \
&& grep -Eq '^PUBLIC_APP_BASE_URL=http://[^[:space:]]+$' .env; then
if ! grep -q '^AUTH_COOKIE_SAMESITE=' .env; then
printf '\nAUTH_COOKIE_SAMESITE=Lax\n' >> .env
fi
if ! grep -q '^AUTH_COOKIE_SECURE=' .env; then
printf '\nAUTH_COOKIE_SECURE=False\n' >> .env
fi
else
warn "Could not safely backfill AUTH_COOKIE_SAMESITE and AUTH_COOKIE_SECURE; set both explicitly using docs/self-hosting.md."
fi
fi
# Persisted so the runner-triggered updater and compose interpolation follow the same repository and images.
for key in SPACEWORKS_REPOSITORY MAKERSPACE_BACKEND_IMAGE MAKERSPACE_FRONTEND_IMAGE; do
value="${!key:-}"
[[ -n "$value" ]] || continue
case "$key" in
SPACEWORKS_REPOSITORY) spaceworks_repository_is_valid "$value" || die "Invalid $key." ;;
MAKERSPACE_BACKEND_IMAGE|MAKERSPACE_FRONTEND_IMAGE) spaceworks_image_is_valid "$value" || die "Invalid $key." ;;
esac
env_file_append_if_absent .env "$key" "$value" || die "Could not persist $key in .env."
done
if [[ "$FIRST_RUN" == 1 ]]; then persist_checkin_settings; fi
ask_deploy_runner
# Hosts upgraded from the in-app updater: drop its tombstone label and weekly cron.
retire_update_tombstone
retire_update_polling
record_compose_layer
chmod 600 .env
# Create backups/ as the install owner; left to Docker it is root-owned and update.sh fails.
mkdir -p backups && chmod 700 backups
prepare_compose_wrapper
if [[ "$BUILD_FROM_SOURCE" == 1 ]]; then
say "Building and starting the app from source (first run can take a few minutes)..."
"${COMPOSE[@]}" pull --ignore-buildable
"${COMPOSE[@]}" up -d --build --pull never
else
say "Pulling release images (first run can take a few minutes)..."
"${COMPOSE[@]}" pull
# The final pull can move the backend tag after prepare_compose_wrapper's pull.
provision_runtime_image_identity --image "$HOST_CONFIG_IMAGE"
refresh_compose_config
"${COMPOSE[@]}" up -d --pull never
fi
# The deployment operation lock must be the same inode for backend, worker, beat and
# the privileged host scripts. Docker performs the ownership step so setup does not
# require host sudo merely to create uid 10001's bind mount.
if ! grep -q '^BACKUP_AGE_RECIPIENT=' .env; then
"${COMPOSE[@]}" exec -T backend age-keygen \
-o /var/lib/spaceworks/ops/work/age-identity.txt >/dev/null
BACKUP_RECIPIENT="$("${COMPOSE[@]}" exec -T backend age-keygen \
-y /var/lib/spaceworks/ops/work/age-identity.txt | tr -d '\r\n')"
printf '\nBACKUP_AGE_RECIPIENT=%s\n' "$BACKUP_RECIPIENT" >> .env
refresh_compose_config
"${COMPOSE[@]}" up -d --pull never
fi
if ! grep -q '^BACKUP_ARCHIVE_SIGNING_PRIVATE_KEY=' .env; then
SIGNING_PAIR="$("${COMPOSE[@]}" exec -T backend python -c 'from apps.ed25519 import encode_key,generate_keypair; p,q=generate_keypair(); print(encode_key(p)); print(encode_key(q))' | tr -d '\r')"
printf '\nBACKUP_ARCHIVE_SIGNING_PRIVATE_KEY=%s\nBACKUP_ARCHIVE_VERIFY_PUBLIC_KEY=%s\n' "$(printf '%s\n' "$SIGNING_PAIR" | sed -n '1p')" "$(printf '%s\n' "$SIGNING_PAIR" | sed -n '2p')" >> .env
refresh_compose_config
"${COMPOSE[@]}" up -d --pull never
fi
install_producer_capability
say "Waiting for the app to be ready..."
ready=0
for _ in $(seq 1 60); do
if "${COMPOSE[@]}" exec -T backend python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/api/v1/health/readiness/', timeout=3)" >/dev/null 2>&1; then
ready=1; break
fi
sleep 3
done
[ "$ready" = 1 ] || die "The app did not become ready in time. Check logs with: ${COMPOSE[*]} logs backend"
if [[ "$AUDIT_KEY_ADDED" == 1 && "$FIRST_RUN" == 0 ]]; then
"${COMPOSE[@]}" run --rm --no-deps -T backend --role management python manage.py provision_audit_mac_keys --all \
|| warn "Could not provision audit MAC keys; run manage.py provision_audit_mac_keys --all."
fi
if [ "$FIRST_RUN" = 1 ]; then
say "Creating your admin account and makerspace..."
"${COMPOSE[@]}" run --rm --no-deps -T backend --role management python manage.py setup_instance \
--username "$ADMINUSER" --email "$ADMINEMAIL" --password "$ADMINPASS" \
--makerspace-name "$MSNAME" --profile "$MSPROFILE"
MODULES_FAILED=0
if ! choose_modules; then
MODULES_FAILED=1
warn "Module selection was not applied. Re-run scripts/update.sh --modules-only after fixing the message above."
fi
MS_SLUG="$("${COMPOSE[@]}" run --rm --no-deps -T backend --role management \
python manage.py list_modules --json 2>/dev/null \
| sed -n 's/.*"makerspace": *"\([^"]*\)".*/\1/p' | head -n 1)"
if [ -n "$MS_SLUG" ]; then
apply_request_access "$MS_SLUG"
else
warn "Could not read the makerspace back, so who may submit borrow requests was left at"
warn "the default (an account is required). Set it with 'manage.py set_request_access'."
fi
if [ -n "$GOOGLE_WEB_CLIENT_ID" ]; then
say "Enabling Google sign-in..."
if ! "${COMPOSE[@]}" run --rm --no-deps -T backend --role management python manage.py configure_social_auth \
--google-web-client-id "$GOOGLE_WEB_CLIENT_ID"; then
warn "Could not save the Google client ID. Add it later in Platform settings; password login is unaffected."
fi
fi
if [ -n "$STRIPE_SECRET_KEY" ]; then
configure_setup_stripe
fi
PORT="$(grep -E '^HTTP_PORT=' .env | cut -d= -f2)"; PORT="${PORT:-80}"
HOST="$(grep -E '^ALLOWED_HOSTS=' .env | cut -d= -f2 | cut -d, -f1)"; HOST="${HOST:-localhost}"
SUFFIX=""; [ "$PORT" != "80" ] && SUFFIX=":$PORT"
if [[ "$MODULES_FAILED" == 1 ]]; then say "Setup finished, but the module selection failed (see above)."; else say "All done! 🎉"; fi
echo " Public catalog : http://${HOST}${SUFFIX}/"
echo " Staff console : http://${HOST}${SUFFIX}/admin (React, username: ${ADMINUSER})"
echo " Control plane : /control/ on the backend only; not published on the public port"
[ "$GEN_PASS" = 1 ] && warn " Generated admin password: ${ADMINPASS} (save this now)"
echo
echo "Next: log into the React staff console at /admin, add inventory, and turn on 'public inventory' for your makerspace."
else
say "App started. To create the first admin (only if you haven't yet), run:"
echo " ${COMPOSE[*]} run --rm --no-deps backend --role management python manage.py setup_instance --username admin --password 'a-strong-password' --makerspace-name 'My Makerspace'"
fi
finish_deploy_runner_setup
# Everything else is configured by now, but a module selection that did not apply must
# not look like a successful install to the curl installer or a script calling setup.sh.
# Exit 3 (not die's 1) tells install.sh the app itself is installed.
if [[ "${MODULES_FAILED:-0}" == 1 ]]; then
printf '\033[1;31mERROR: %s\033[0m\n' "Module selection was not applied; re-run scripts/update.sh --modules-only." >&2
exit 3
fi