Repository navigation
Expand file tree
/
Copy pathinstall-linux.sh
More file actions
2079 lines (1958 loc) · 94.9 KB
/
Copy pathinstall-linux.sh
File metadata and controls
2079 lines (1958 loc) · 94.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
# install-linux.sh — installer + manager for the Zcode Gateway on a Linux VPS.
#
# curl -fsSL https://raw.githubusercontent.com/B3hnamR/AutoZcoder/master/install-linux.sh | sudo bash
#
# First run INSTALLS the gateway and registers the `autozcoder` command.
# Afterwards just type `autozcoder` for the manager menu:
#
# autozcoder interactive menu
# autozcoder status service / certificate / URL at a glance
# autozcoder start|stop|restart
# autozcoder logs follow the gateway log (Ctrl+C returns)
# autozcoder info dashboard URL + admin/client keys
# autozcoder update newer release (SHA-256 verified), config kept
# autozcoder cert re-issue / switch the TLS certificate
# autozcoder install (re)run the full install
# autozcoder uninstall FULLY delete service, certificates, files
#
# The gateway serves HTTPS ITSELF (built-in TLS) — no nginx / reverse proxy is
# installed, so nothing else on the VPS is touched or interrupted. Port 80 is
# only used for ~10 seconds while Let's Encrypt validates the certificate.
#
# The install, in order (each step verified before the next):
# 1. root + OS + arch check
# 2. small prerequisites (curl, openssl, socat)
# 3. binary: GitHub release (SHA-256 verified) or a local source build
# 4. config.yaml with random admin/client keys (an existing one is kept)
# 5. the account generator's environment: a private Python venv with its
# packages (playwright, ddddocr, opencv, …) and Chromium + the system
# libraries it needs, so the dashboard never shows "Environment Setup";
# plus Node.js 22 + wrangler for the Cloudflare mail worker
# 6. firewall check, then TLS. DEFAULT = Let's Encrypt certificate for the
# server's bare IP (shortlived profile, auto-renewed by a systemd timer),
# so the dashboard opens at https://<ip>:8443/dash with no warning.
# Other modes: domain, self-signed, none (gateway stays on 127.0.0.1).
# 7. systemd service `zcodegateway` + certificate renewal timer
# 8. health checks of the gateway AND the public https URL
# 9. a final install report (also saved to <install dir>/install-report.txt)
#
# Package-manager / pip / build output is hidden: the screen shows what is
# being done, and everything is written to /var/log/autozcoder-install.log.
#
# Environment overrides (non-interactive use):
# ZGW_PORT=8443 public HTTPS port
# ZGW_SSL_MODE=ip|domain|self|none (default ip)
# ZGW_DOMAIN=example.com (for mode=domain)
# ZGW_SERVER_IP=1.2.3.4 (for mode=ip / display)
# ZGW_INSTALL_DIR=/opt/zcodegateway
# ZGW_SKIP_SYSTEMD=1 do not create/start the service (manual runs)
# ZGW_NONINTERACTIVE=1 never prompt (also implied without a terminal)
# ZGW_OPEN_FIREWALL=1 open 80 + the HTTPS port in ufw/firewalld
# ZGW_FROM_SOURCE=/path build the binary from a checkout of this repo
# (scripts/build/linux.sh) instead of downloading a release
# ZGW_SKIP_GENERATOR=1 skip the generator environment (venv + Chromium, ~250 MB)
# PLAYWRIGHT_DOWNLOAD_HOST=… Chromium download mirror when Playwright's CDN is
# geo-blocked (e.g. https://cdn.npmmirror.com/binaries/playwright)
# ZGW_ALLOW_LOW_RESOURCES=1 accept the first-install CPU/RAM warning explicitly
# ZGW_PAUSE_UNITS="a b" systemd units that hold port 80; they are stopped
# for a few seconds while Let's Encrypt validates
# (install and every renewal), then started again
# ZGW_RUN_AS_ROOT=1 run the service as root instead of the unprivileged
# 'autozcoder' user (not recommended)
set -Eeuo pipefail
umask 077
red='\033[0;31m'; green='\033[0;32m'; blue='\033[0;34m'
yellow='\033[0;33m'; bold='\033[1m'; dim='\033[2m'; plain='\033[0m'
ZGW_REPO="B3hnamR/AutoZcoder"
# acme.sh is pinned to a release tarball with a known SHA-256 (never `curl | sh`
# of whatever the host serves today); bump both together after reviewing a release
ACME_VERSION="3.1.6"
ACME_SHA256="0d3f9000ac44a6331314742a88c475f79134e24fc991997883652adc59efc486"
SVC_USER="autozcoder"
INSTALL_MARKER=".autozcoder-install"
ENV_FILE="/etc/autozcoder.env"
MANAGER_BIN="/usr/local/bin/autozcoder"
SERVICE="zcodegateway"
RENEW_UNIT="autozcoder-renew"
UNIT_FILE="/etc/systemd/system/${SERVICE}.service"
RENEW_SERVICE_FILE="/etc/systemd/system/${RENEW_UNIT}.service"
RENEW_TIMER_FILE="/etc/systemd/system/${RENEW_UNIT}.timer"
UPDATE_LOCK="/run/autozcoder-update.lock"
LOG_FILE="/var/log/autozcoder-install.log"
ACME_HOME="/root/.acme.sh"
# absolute path of this file (empty under `curl | bash`), captured before any cd
SELF="$(readlink -f "${BASH_SOURCE[0]:-}" 2>/dev/null || true)"
# never let the package manager prompt or print restart banners
export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a NEEDRESTART_SUSPEND=1
ok() { echo -e "${green}[✓]${plain} $*"; }
warn() { echo -e "${yellow}[!]${plain} $*"; }
bad() { echo -e "${red}[✗]${plain} $*" >&2; }
fail() { bad "$*"; exit 1; }
step() { STEP="$1"; echo -e "\n${blue}${bold}==>${plain}${bold} [$1] $2${plain}"; }
say() { echo -e " ${dim}•${plain} $*"; }
# Run a noisy command with its output going to the log file; the screen only
# shows what is being done (spinner on a terminal) and the result.
run_quiet() { # run_quiet "what we are doing" cmd args...
local what="$1"; shift
local t0=$SECONDS rc=0 pid i=0 spin='|/-\' tty=0
[[ -t 1 ]] && tty=1
{ echo; echo "=== $(date -u '+%F %T') ${what}: $*"; } >>"$LOG_FILE"
( trap - ERR; "$@" ) >>"$LOG_FILE" 2>&1 &
pid=$!
if [[ "$tty" == "0" ]]; then echo -e " ${dim}…${plain} ${what}"; fi
while kill -0 "$pid" 2>/dev/null; do
if [[ "$tty" == "1" ]]; then
printf '\r %s %s (%ss)\033[K' "${spin:i++%4:1}" "$what" "$((SECONDS - t0))"
fi
sleep 0.3
done
wait "$pid" || rc=$?
[[ "$tty" == "1" ]] && printf '\r\033[K'
if [[ $rc -eq 0 ]]; then
echo -e " ${green}✓${plain} ${what} ${dim}($((SECONDS - t0))s)${plain}"
return 0
fi
echo -e " ${red}✗${plain} ${what} ${dim}(exit ${rc})${plain}" >&2
echo -e "${dim} last lines of ${LOG_FILE}:${plain}" >&2
tail -n 12 "$LOG_FILE" | sed 's/^/ /' >&2
return "$rc"
}
# ------------------------------------------------------------ state / config
# precedence: environment override > saved state (/etc/autozcoder.env) > default
resolve_config() {
SAVED_INSTALL_DIR=""; SAVED_SERVICE_UID=""; SAVED_PORT=""; SAVED_DOMAIN=""; SAVED_SERVER_IP=""
SAVED_SCHEME=""; SAVED_SSL_MODE=""; SAVED_ACME_HOST="__legacy__"; SAVED_PAUSE_UNITS=""; SAVED_FROM_SOURCE=""; SAVED_RUN_AS_ROOT=""; SAVED_SKIP_SYSTEMD=""
# shellcheck disable=SC1090
[[ -f "$ENV_FILE" ]] && . "$ENV_FILE"
# the service runs as an unprivileged user unless the operator opts out
ZGW_RUN_AS_ROOT="${ZGW_RUN_AS_ROOT:-${SAVED_RUN_AS_ROOT:-0}}"
ZGW_SKIP_SYSTEMD="${ZGW_SKIP_SYSTEMD:-${SAVED_SKIP_SYSTEMD:-0}}"
ZGW_INSTALL_DIR="${ZGW_INSTALL_DIR:-${SAVED_INSTALL_DIR:-/opt/zcodegateway}}"
ZGW_PORT="${ZGW_PORT:-${SAVED_PORT:-8443}}"
ZGW_DOMAIN="${ZGW_DOMAIN:-${SAVED_DOMAIN:-}}"
ZGW_SERVER_IP="${ZGW_SERVER_IP:-${SAVED_SERVER_IP:-}}"
# Older state recorded only scheme/domain. In particular, HTTP must not
# become public IP TLS merely because an operator runs install again.
if [[ -z "$SAVED_SSL_MODE" && -n "$SAVED_SCHEME" ]]; then
if [[ "$SAVED_SCHEME" == http ]]; then SAVED_SSL_MODE=none
elif [[ -n "$SAVED_DOMAIN" ]]; then SAVED_SSL_MODE=domain
else SAVED_SSL_MODE=ip; fi
fi
ZGW_SSL_MODE="${ZGW_SSL_MODE:-${SAVED_SSL_MODE}}"
if [[ "$SAVED_ACME_HOST" == __legacy__ ]]; then
SAVED_ACME_HOST=""
case "$SAVED_SSL_MODE" in
domain) SAVED_ACME_HOST="$SAVED_DOMAIN" ;;
ip) SAVED_ACME_HOST="$SAVED_SERVER_IP" ;;
esac
fi
PAUSE_UNITS="${ZGW_PAUSE_UNITS-${SAVED_PAUSE_UNITS}}"
ZGW_FROM_SOURCE="${ZGW_FROM_SOURCE:-${SAVED_FROM_SOURCE}}"
CERT_DIR="${ZGW_INSTALL_DIR}/certs"
}
save_state() {
local tmp
tmp="$(mktemp "${ENV_FILE}.XXXXXXXX")" || return 1
{
printf 'SAVED_INSTALL_DIR=%q\n' "$ZGW_INSTALL_DIR"
printf 'SAVED_SERVICE_UID=%q\n' "${SAVED_SERVICE_UID:-}"
printf 'SAVED_PORT=%q\n' "$ZGW_PORT"
printf 'SAVED_DOMAIN=%q\n' "$ZGW_DOMAIN"
printf 'SAVED_SERVER_IP=%q\n' "${SERVER_IP:-${ZGW_SERVER_IP}}"
printf 'SAVED_SCHEME=%q\n' "${SSL_SCHEME:-https}"
printf 'SAVED_SSL_MODE=%q\n' "${TLS_MODE_CHOICE:-${ZGW_SSL_MODE:-${SAVED_SSL_MODE:-ip}}}"
printf 'SAVED_ACME_HOST=%q\n' "${CURRENT_ACME_HOST:-}"
printf 'SAVED_PAUSE_UNITS=%q\n' "${PAUSE_UNITS:-}"
printf 'SAVED_FROM_SOURCE=%q\n' "${ZGW_FROM_SOURCE:-}"
printf 'SAVED_RUN_AS_ROOT=%q\n' "${ZGW_RUN_AS_ROOT:-0}"
printf 'SAVED_SKIP_SYSTEMD=%q\n' "${ZGW_SKIP_SYSTEMD:-0}"
} > "$tmp" && chmod 600 "$tmp" && mv -fT -- "$tmp" "$ENV_FILE" \
|| { rm -f -- "$tmp"; return 1; }
}
need_root() { [[ $EUID -eq 0 ]] || fail "run this as root (sudo autozcoder ...)"; }
acquire_mutation_lock() {
exec {MUTATION_LOCK_FD}>"$UPDATE_LOCK"
flock -n "$MUTATION_LOCK_FD" || fail "another update is in progress (install/cert/update/uninstall share this lock)"
}
# Root never imports from the working directory, service HOME, a venv or
# inherited Python settings. Each privileged interpreter gets an empty HOME.
system_python() (
local home rc=0
home="$(update_tmpdir)" || return 1
cd / || return 1
env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME="$home" TMPDIR="$home" \
/usr/bin/python3 -I "$@" || rc=$?
rm -rf -- "$home"
return "$rc"
)
run_tool_user() {
# Playwright's CDN geo-blocks some VPS regions (403 AccessDenied).
# Forward an explicit mirror so an operator can install Chromium anyway;
# the rest of the environment stays clean (env -i) on purpose.
local extra=()
[[ -n "${PLAYWRIGHT_DOWNLOAD_HOST:-}" ]] && \
extra+=(PLAYWRIGHT_DOWNLOAD_HOST="${PLAYWRIGHT_DOWNLOAD_HOST}")
runuser -u "$SVC_USER" -- env -i \
PATH="${ZGW_INSTALL_DIR}/node/bin:/usr/local/bin:/usr/bin:/bin" \
HOME="${ZGW_INSTALL_DIR}/home" \
npm_config_cache="${ZGW_INSTALL_DIR}/home/.npm" \
PLAYWRIGHT_BROWSERS_PATH="${ZGW_INSTALL_DIR}/pw-browsers" \
"${extra[@]}" "$@"
}
# ------------------------------------------------------- service account
# The gateway is internet-facing and its admin key is code execution, so it must
# not also be root. Everything under the install dir belongs to ${SVC_USER};
# root (installer, acme.sh renewal) only writes and then hands ownership over.
service_user() {
if [[ "${ZGW_RUN_AS_ROOT:-0}" == "1" || "${ZGW_SKIP_SYSTEMD:-0}" == "1" ]]; then
echo root
else
echo "$SVC_USER"
fi
}
ensure_service_user() {
local u="${1:-$(service_user)}"
[[ "$u" == root ]] && return 0
id -u "$u" >/dev/null 2>&1 && return 0
local shell; shell="$(command -v nologin 2>/dev/null || echo /usr/sbin/nologin)"
useradd --system --no-create-home --home-dir "${ZGW_INSTALL_DIR}/home" \
--shell "$shell" "$u" >>"$LOG_FILE" 2>&1 \
|| fail "could not create the '${u}' service user (no useradd?) — rerun with ZGW_RUN_AS_ROOT=1 to run as root"
[[ "$u" != "$SVC_USER" ]] || SAVED_SERVICE_UID="$(id -u "$u")"
}
fix_ownership() {
local u; u="$(service_user)"
ensure_service_user || return 1
[[ ! -L "$ZGW_INSTALL_DIR" ]] || fail "install directory must not be a symlink"
# Runtime config/SQLite use atomic sibling writes. A sticky, root-owned
# directory permits those without letting the service replace root binaries.
ensure_service_user "$SVC_USER" || return 1
chown "root:${SVC_USER}" "$ZGW_INSTALL_DIR" && chmod 1770 "$ZGW_INSTALL_DIR" || return 1
find "$ZGW_INSTALL_DIR" -mindepth 1 -maxdepth 1 ! -name ZcodeGateway ! -name certs ! -name node ! -name "$INSTALL_MARKER" ! -name '.tls.*' \
-exec chown -hR "${u}:${u}" -- {} + || return 1
# Private Node is installer-owned executable tooling, not runtime data.
if [[ -e "$ZGW_INSTALL_DIR/node" || -L "$ZGW_INSTALL_DIR/node" ]]; then
[[ ! -L "$ZGW_INSTALL_DIR/node" ]] || fail "node directory must not be a symlink"
chown -hR root:root "$ZGW_INSTALL_DIR/node" || return 1
chmod -R go-w "$ZGW_INSTALL_DIR/node" || return 1
fi
local dir
for dir in genenv pw-browsers home; do
if [[ -d "$ZGW_INSTALL_DIR/$dir" ]]; then
ensure_service_user "$SVC_USER" || return 1
chown -hR "${SVC_USER}:${SVC_USER}" "$ZGW_INSTALL_DIR/$dir" || return 1
fi
done
if [[ -e "$ZGW_INSTALL_DIR/ZcodeGateway" || -L "$ZGW_INSTALL_DIR/ZcodeGateway" ]]; then
[[ ! -L "$ZGW_INSTALL_DIR/ZcodeGateway" ]] || fail "gateway executable must not be a symlink"
chown root:root "$ZGW_INSTALL_DIR/ZcodeGateway" && chmod 755 "$ZGW_INSTALL_DIR/ZcodeGateway" || return 1
fi
if [[ -d "$CERT_DIR" ]]; then
[[ ! -L "$CERT_DIR" ]] || fail "certificate directory must not be a symlink"
chown "root:${u}" "$CERT_DIR" && chmod 750 "$CERT_DIR" || return 1
local f
for f in privkey.pem fullchain.pem; do
if [[ -e "$CERT_DIR/$f" || -L "$CERT_DIR/$f" ]]; then
[[ ! -L "$CERT_DIR/$f" ]] || fail "certificate file must not be a symlink"
chown "root:${u}" "$CERT_DIR/$f" && chmod 640 "$CERT_DIR/$f" || return 1
fi
done
fi
}
# what acme.sh runs after it (re)installs the certificate files
cert_reload_cmd() {
local u cmd=""; u="$(service_user)"
[[ "$u" != root ]] && cmd="chown root:${u} ${CERT_DIR}/privkey.pem ${CERT_DIR}/fullchain.pem; chmod 640 ${CERT_DIR}/privkey.pem ${CERT_DIR}/fullchain.pem; "
echo "${cmd}systemctl restart ${SERVICE} 2>/dev/null || true"
}
is_installed() { [[ -x "${ZGW_INSTALL_DIR}/ZcodeGateway" ]]; }
# a real terminal for prompts, even under `curl | bash` (stdin is the pipe)
TTY_OK=0
if [[ "${ZGW_NONINTERACTIVE:-0}" != "1" ]] && ( : </dev/tty ) 2>/dev/null; then TTY_OK=1; fi
ask() { # ask "prompt" default -> echoes the answer
local reply=""
if [[ "$TTY_OK" == "1" ]]; then
read -rp "$1" reply </dev/tty || true
fi
echo "${reply:-$2}"
}
confirm() { # confirm "question" default(y|n)
local d="${2:-y}" a
a="$(ask "$1 [$([[ $d == y ]] && echo Y/n || echo y/N)] " "$d")"
[[ "$a" =~ ^[Yy] ]]
}
server_resources() {
# CPU affinity and container quotas can be lower than host capacity.
local cpus memory limit quota period
cpus="$(nproc 2>/dev/null || getconf _NPROCESSORS_ONLN 2>/dev/null || echo 0)"
memory="$(awk '/^MemTotal:/ {print $2; exit}' /proc/meminfo)"
if [[ -r /sys/fs/cgroup/memory.max ]]; then
limit="$(cat /sys/fs/cgroup/memory.max)"
elif [[ -r /sys/fs/cgroup/memory/memory.limit_in_bytes ]]; then
limit="$(cat /sys/fs/cgroup/memory/memory.limit_in_bytes)"
else limit=""; fi
if [[ "$limit" =~ ^[0-9]+$ ]]; then
memory="$(awk -v host="${memory:-0}" -v bytes="$limit" 'BEGIN {limit=int(bytes/1024); print (host>0 && host<limit)?host:limit}')"
fi
if [[ -r /sys/fs/cgroup/cpu.max ]]; then
read -r quota period </sys/fs/cgroup/cpu.max || true
elif [[ -r /sys/fs/cgroup/cpu/cpu.cfs_quota_us && -r /sys/fs/cgroup/cpu/cpu.cfs_period_us ]]; then
quota="$(cat /sys/fs/cgroup/cpu/cpu.cfs_quota_us)"
period="$(cat /sys/fs/cgroup/cpu/cpu.cfs_period_us)"
else quota=""; period=""; fi
if [[ "$quota" =~ ^[0-9]+$ && "$period" =~ ^[0-9]+$ ]] && (( period > 0 )); then
cpus="$(awk -v host="$cpus" -v q="$quota" -v p="$period" 'BEGIN {limit=q/p; print (host>0 && host<limit)?host:limit}')"
fi
printf '%s %s\n' "${cpus:-0}" "${memory:-0}"
}
check_first_install_resources() {
is_installed && return 0
local cpus memory gib
read -r cpus memory < <(server_resources)
gib="$(awk -v kb="$memory" 'BEGIN {printf "%.1f",kb/1048576}')"
say "Server capacity: ${cpus} CPU(s), ${gib} GiB RAM (detected limit)"
if [[ "${ZGW_SKIP_GENERATOR:-0}" == 1 ]]; then
say "Generator skipped; browser-generation sizing warning does not apply."
return 0
fi
if awk -v cpu="$cpus" -v kb="$memory" 'BEGIN {exit !((cpu>0 && cpu<=1) || (kb>0 && kb<=2097152))}'; then
warn "Low resources for account generation: ${cpus} CPU(s), ${gib} GiB RAM."
say "Gateway-only use may be fine, but browser generation can be slow or fail under resource pressure."
say "Recommended for one browser: 2 reliable vCPUs + 4 GB RAM. Shared CPU contention also matters."
say "Use one worker; avoid simultaneous proxy scans/builds. Swap is emergency headroom, not browser capacity."
if [[ "${ZGW_ALLOW_LOW_RESOURCES:-0}" == 1 ]]; then
warn "Continuing with explicit ZGW_ALLOW_LOW_RESOURCES=1 acknowledgement."
elif [[ "$TTY_OK" != 1 ]]; then
fail "low-resource server needs confirmation: rerun interactively, set ZGW_ALLOW_LOW_RESOURCES=1, or use ZGW_SKIP_GENERATOR=1"
elif ! confirm "This server is not recommended for comfortable generation. Continue anyway?" n; then
say "Installation cancelled before installing packages or building the gateway."
exit 0
fi
elif awk -v cpu="$cpus" -v kb="$memory" 'BEGIN {exit !(cpu<=0 || kb<=0)}'; then
warn "Could not determine all resource limits; plan for at least 2 reliable vCPUs + 4 GB RAM for one generator browser."
fi
}
run_action() { # run a menu action so a failure returns to the menu instead of exiting
set +e; ( set -e; "$@" ); local rc=$?; set -e
[[ $rc -ne 0 ]] && warn "action ended with exit code ${rc}"
return 0
}
# ------------------------------------------------------------------ helpers
detect_server_ip() {
[[ -n "${ZGW_SERVER_IP}" ]] && { echo "$ZGW_SERVER_IP"; return; }
local u r
for u in https://api4.ipify.org https://ipv4.icanhazip.com https://4.ident.me; do
r="$(curl -fsS --max-time 4 "$u" 2>/dev/null || true)"
r="${r//[$'\r\n ']/}"
if [[ "$r" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then echo "$r"; return; fi
done
echo ""
}
is_domain() { [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+[A-Za-z]{2,}$ ]]; }
install_pkgs() (
local home
home="$(update_tmpdir)" || return 1
trap 'rm -rf -- "$home"' EXIT
cd / || return 1
export PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME="$home" TMPDIR="$home"
local -a clean=(env -i PATH="$PATH" HOME="$HOME" TMPDIR="$TMPDIR" DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a NEEDRESTART_SUSPEND=1)
local release=""
[[ -f /etc/os-release ]] && { . /etc/os-release; release="${ID:-}"; }
case "${release}" in
ubuntu|debian|armbian) "${clean[@]}" apt-get update -qq && "${clean[@]}" apt-get install -y -qq -o Dpkg::Use-Pty=0 "$@" ;;
fedora|amzn|rhel|almalinux|rocky|ol|centos)
"${clean[@]}" dnf install -y -q "$@" ;;
arch|manjaro|parch) "${clean[@]}" pacman -Sy --noconfirm "$@" ;;
opensuse-*) "${clean[@]}" zypper -q install -y "$@" ;;
*) "${clean[@]}" apt-get update -qq && "${clean[@]}" apt-get install -y -qq -o Dpkg::Use-Pty=0 "$@" ;;
esac
)
host_for_display() { echo "${ZGW_DOMAIN:-${SERVER_IP:-${ZGW_SERVER_IP:-<server-ip>}}}"; }
# the port the gateway itself listens on (https: public port; http: loopback only)
gw_port() { [[ "${SSL_SCHEME:-https}" == "https" ]] && echo "${ZGW_PORT}" || echo 8788; }
gw_health_url() {
if [[ "${SSL_SCHEME:-https}" == "https" ]]; then echo "https://127.0.0.1:$(gw_port)/health"
else echo "http://127.0.0.1:8788/health"; fi
}
# All config access uses YAML, including updates: key order, indentation and
# flow-style mappings must not decide whether an existing install is retained.
cfg_yaml() { # cfg_yaml validate|admin|client|has|set [section key [yaml-value]]
system_python - "${ZGW_INSTALL_DIR}/config.yaml" "$@" <<'PY'
import os
from pathlib import Path
import sys
import tempfile
try:
import yaml
except ImportError:
sys.exit("Config access needs Python3 + PyYAML (install your distro's PyYAML package).")
path = Path(sys.argv[1])
action = sys.argv[2]
try:
data = yaml.safe_load(path.read_text(encoding="utf-8"))
if not isinstance(data, dict):
raise ValueError("expected a top-level mapping")
server = data.get("server")
if not isinstance(server, dict):
raise ValueError("server must be a mapping")
admin = server.get("admin_key")
clients = server.get("client_keys")
if not isinstance(admin, str) or not admin.strip():
raise ValueError("server.admin_key must be a nonempty string")
if not isinstance(clients, list) or not clients or any(
not isinstance(c, dict) or not isinstance(c.get("key"), str) or not c["key"].strip()
for c in clients
):
raise ValueError("server.client_keys must contain nonempty string keys")
if "generator" in data and not isinstance(data["generator"], dict):
raise ValueError("generator must be a mapping")
if action == "admin":
print(admin)
elif action == "client":
print(clients[0]["key"])
elif action == "has":
section, key = sys.argv[3:5]
sys.exit(0 if key in data.get(section, {}) else 1)
elif action == "set":
section, key, value = sys.argv[3:6]
block = data.setdefault(section, {})
if not isinstance(block, dict):
raise ValueError("config section must be a mapping")
block[key] = yaml.safe_load(value)
text = yaml.safe_dump(data, sort_keys=False)
fd, tmp = tempfile.mkstemp(prefix=".config-", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
fh.write(text)
fh.flush()
os.fsync(fh.fileno())
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
elif action != "validate":
raise ValueError("unknown config action")
except (OSError, UnicodeError, ValueError, yaml.YAMLError) as exc:
# Parser exceptions can embed entire secret-bearing source lines.
sys.exit(f"Cannot use {path} ({type(exc).__name__}); config was not replaced. Repair/validate its YAML and credential fields before retrying.")
PY
}
cfg_admin_key() { cfg_yaml admin; }
cfg_client_key() { cfg_yaml client; }
cfg_set_server() { cfg_yaml set server "$1" "$2"; }
# point the gateway at the TLS decision: public https listener, or loopback http
bind_config() {
if [[ "${SSL_SCHEME}" == "https" ]]; then
cfg_set_server host "0.0.0.0"
cfg_set_server port "${ZGW_PORT}"
cfg_set_server tls_cert "\"${CERT_DIR}/fullchain.pem\""
cfg_set_server tls_key "\"${CERT_DIR}/privkey.pem\""
else
cfg_set_server host "127.0.0.1"
cfg_set_server port "8788"
cfg_set_server tls_cert '""'
cfg_set_server tls_key '""'
fi
}
cert_end_date() {
openssl x509 -noout -enddate -in "${CERT_DIR}/fullchain.pem" 2>/dev/null | sed 's/^notAfter=//' || true
}
cert_is_selfsigned() {
local f="${CERT_DIR}/fullchain.pem" i s
[[ -s "$f" ]] || return 1
i="$(openssl x509 -noout -issuer -in "$f" 2>/dev/null | sed 's/^issuer=//')"
s="$(openssl x509 -noout -subject -in "$f" 2>/dev/null | sed 's/^subject=//')"
[[ -n "$i" && "$i" == "$s" ]]
}
# ------------------------------------------------- TLS (acme.sh, built-in TLS)
acme() { "${ACME_HOME}/acme.sh" "$@"; }
install_acme() {
[[ -x "${ACME_HOME}/acme.sh" ]] && return 0
# Pinned release tarball, SHA-256 checked before anything in it runs.
# --nocron: renewal runs from our own systemd timer. No contact e-mail on
# purpose: a placeholder address such as admin@example.com is rejected by
# Let's Encrypt.
local d act; d="$(mktemp -d)"
curl -fsSL --retry 3 -o "$d/acme.tgz" \
"https://github.com/acmesh-official/acme.sh/archive/refs/tags/v${ACME_VERSION}.tar.gz" \
|| { rm -rf "$d"; return 1; }
act="$(sha256sum "$d/acme.tgz" | awk '{print $1}')"
if [[ "$act" != "$ACME_SHA256" ]]; then
rm -rf "$d"
echo "acme.sh v${ACME_VERSION} SHA-256 mismatch (expected ${ACME_SHA256}, got ${act}) — refusing to run it" >&2
return 1
fi
tar -xzf "$d/acme.tgz" -C "$d" || { rm -rf "$d"; return 1; }
( cd "$d/acme.sh-${ACME_VERSION}" && ./acme.sh --install --nocron ) || { rm -rf "$d"; return 1; }
rm -rf "$d"
[[ -x "${ACME_HOME}/acme.sh" ]]
}
# who listens on a TCP port? -> "pid comm" (empty when free)
port_listener() {
local line pid
line="$(ss -H -ltnp "sport = :$1" 2>/dev/null | head -1)"
[[ -n "$line" ]] || return 0
pid="$(sed -n 's/.*pid=\([0-9]*\).*/\1/p' <<<"$line" | head -1)"
echo "${pid:-?} $( [[ -n "$pid" ]] && ps -o comm= -p "$pid" 2>/dev/null || echo unknown)"
}
# the systemd unit a pid belongs to (empty if none)
pid_unit() { grep -o '[^/]*\.service' "/proc/$1/cgroup" 2>/dev/null | tail -1 || true; }
# acme.sh standalone needs port 80 free: pause only the units the operator
# allowed us to pause, and bring them back no matter what happened
with_port80_free() {
local rc=0
# shellcheck disable=SC2086
[[ -n "${PAUSE_UNITS:-}" ]] && { systemctl stop ${PAUSE_UNITS} >/dev/null 2>&1 || true; }
"$@" || rc=$?
# shellcheck disable=SC2086
[[ -n "${PAUSE_UNITS:-}" ]] && { systemctl start ${PAUSE_UNITS} >/dev/null 2>&1 || true; }
return $rc
}
# Port 80 must be free for the Let's Encrypt validation. Another service may
# own it (we never stop one silently): decide here whether LE is possible.
PORT80_BLOCKED=0
plan_port80() {
PORT80_BLOCKED=0
local who pid comm unit
who="$(port_listener 80)"
[[ -z "$who" ]] && { ok "port 80 is free for the certificate validation"; return 0; }
pid="${who%% *}"; comm="${who#* }"
unit="$(pid_unit "$pid")"
if [[ -n "${PAUSE_UNITS:-}" ]]; then
ok "port 80 is held by ${unit:-$comm}; it will be paused briefly for validation (ZGW_PAUSE_UNITS=${PAUSE_UNITS})"
return 0
fi
warn "port 80 is in use by ${comm}${unit:+ (${unit})} — Let's Encrypt needs it for ~10 seconds"
if [[ "$TTY_OK" == "1" && -n "$unit" ]]; then
echo -e " ${green}1.${plain} Pause ${unit} briefly now and during each renewal (every few days) — trusted certificate"
echo -e " ${green}2.${plain} Do not touch it — use a self-signed certificate (browser warning, no downtime)"
if [[ "$(ask "Choose [2]: " 2)" == "1" ]]; then
PAUSE_UNITS="$unit"
ok "will pause ${unit} during certificate validation"
return 0
fi
fi
PORT80_BLOCKED=1
warn "keeping ${unit:-$comm} running: using a self-signed certificate. For a trusted IP certificate later: free port 80, or run ZGW_PAUSE_UNITS=${unit:-<unit>} autozcoder cert"
}
install_cert_files() { # install_cert_files <host>
acme --installcert --force -d "$1" \
--key-file "${CERT_DIR}/privkey.pem" \
--fullchain-file "${CERT_DIR}/fullchain.pem" \
--reloadcmd "" \
>>"$LOG_FILE" 2>&1 || return 1
cert_pair_valid
}
cert_pair_valid() {
local cert_pub key_pub
openssl x509 -in "$CERT_DIR/fullchain.pem" -noout -checkend 0 >/dev/null 2>&1 || return 1
cert_pub="$(openssl x509 -in "$CERT_DIR/fullchain.pem" -pubkey -noout)" || return 1
key_pub="$(openssl pkey -in "$CERT_DIR/privkey.pem" -pubout)" || return 1
[[ -n "$cert_pub" && "$cert_pub" == "$key_pub" ]]
}
activate_acme_registration() {
if [[ "${TLS_TRUSTED:-0}" == 1 ]]; then
acme --installcert --force -d "$CURRENT_ACME_HOST" \
--key-file "$CERT_DIR/privkey.pem" --fullchain-file "$CERT_DIR/fullchain.pem" \
--reloadcmd "$(cert_reload_cmd)" >>"$LOG_FILE" 2>&1 || return 1
fi
}
retire_acme_registration() {
# Only retire the previous entry after the new gateway has passed health.
if [[ -n "${SAVED_ACME_HOST:-}" && "$SAVED_ACME_HOST" != "${CURRENT_ACME_HOST:-}" ]]; then
acme --remove -d "$SAVED_ACME_HOST" >>"$LOG_FILE" 2>&1 \
|| warn "could not retire old ACME entry; renewal is restricted to the active host"
fi
}
issue_le() { # issue_le <host> <extra acme args...>
local host="$1"; shift
local hooks=()
[[ -n "${PAUSE_UNITS:-}" ]] && hooks=(--pre-hook "systemctl stop ${PAUSE_UNITS}" \
--post-hook "systemctl start ${PAUSE_UNITS}")
run_quiet "Preparing the certificate tool (acme.sh)" install_acme || return 1
acme --set-default-ca --server letsencrypt >>"$LOG_FILE" 2>&1 || true
run_quiet "Requesting the Let's Encrypt certificate for ${host} (needs port 80, ~30 s)" \
with_port80_free acme --issue -d "${host}" --standalone --httpport 80 \
--server letsencrypt --force "$@" ${hooks[@]+"${hooks[@]}"} || return 1
install_cert_files "${host}" || { bad "could not install the issued certificate"; return 1; }
chmod 600 "${CERT_DIR}/privkey.pem"
}
issue_le_ip_cert() {
say "Let's Encrypt IP certificate for ${SERVER_IP} (shortlived, renews automatically)"
issue_le "${SERVER_IP}" --certificate-profile shortlived --days 3 || return 1
TLS_NOTE="Let's Encrypt IP certificate (~6 days) — renewed automatically by ${RENEW_UNIT}.timer"
TLS_TRUSTED=1
ok "Let's Encrypt IP certificate installed"
}
issue_le_domain_cert() {
say "Let's Encrypt certificate for ${ZGW_DOMAIN} (90 days; the A record must point here)"
issue_le "${ZGW_DOMAIN}" || return 1
TLS_NOTE="Let's Encrypt certificate (90 days) — renewed automatically by ${RENEW_UNIT}.timer"
TLS_TRUSTED=1
ok "Let's Encrypt domain certificate installed"
}
gen_self_signed() {
say "Generating a self-signed certificate for ${SERVER_IP:-this server}"
openssl req -x509 -newkey rsa:2048 -sha256 -days 3650 -nodes \
-keyout "${CERT_DIR}/privkey.pem" \
-out "${CERT_DIR}/fullchain.pem" \
-subj "/CN=zcodegateway" \
-addext "subjectAltName=IP:${SERVER_IP:-127.0.0.1}${ZGW_DOMAIN:+,DNS:${ZGW_DOMAIN}}" \
>>"$LOG_FILE" 2>&1 || return 1
chmod 600 "${CERT_DIR}/privkey.pem"
TLS_NOTE="self-signed certificate (10 years) — browsers show a warning once"
TLS_TRUSTED=0
ok "self-signed certificate generated"
}
le_with_selfsigned_fallback() { # <issuer-fn>
if [[ "$PORT80_BLOCKED" == "1" ]]; then
gen_self_signed || fail "self-signed certificate generation failed"
return 0
fi
if "$1"; then return 0; fi
warn "Let's Encrypt issuance failed — falling back to a self-signed certificate"
warn "(open port 80 in your provider firewall / check DNS, then run: autozcoder cert)"
gen_self_signed || fail "self-signed certificate generation failed"
}
_apply_tls() {
SSL_SCHEME="https"
case "$1" in
ip) [[ -n "${SERVER_IP}" ]] || fail "no public IP detected (set ZGW_SERVER_IP=1.2.3.4)"
le_with_selfsigned_fallback issue_le_ip_cert ;;
domain) is_domain "${ZGW_DOMAIN}" || fail "a valid domain is required (ZGW_DOMAIN)"
le_with_selfsigned_fallback issue_le_domain_cert ;;
self) gen_self_signed || fail "self-signed certificate generation failed" ;;
none) SSL_SCHEME="http"; TLS_TRUSTED=-1
TLS_NOTE="NO TLS — the gateway listens on 127.0.0.1:8788 only; put your own TLS proxy / SSH tunnel in front"
warn "$TLS_NOTE" ;;
*) fail "unknown ssl mode '$1' (ip|domain|self|none)" ;;
esac
}
apply_tls() { # Stage a complete pair without deleting a working certificate.
local live="$CERT_DIR" stage rc=0
stage="$(mktemp -d "${ZGW_INSTALL_DIR}/.tls.XXXXXXXX")" || return 1
( CERT_DIR="$stage"; _apply_tls "$1" || exit $?;
[[ "$1" == none ]] || cert_pair_valid ) || rc=$?
# The subshell isolates fail/exit from the transaction. Derive reporting
# from the validated staged pair without issuing a second certificate.
if [[ "$rc" != 0 ]]; then rm -rf -- "$stage"; return "$rc"; fi
SSL_SCHEME=https; CURRENT_ACME_HOST=""; TLS_TRUSTED=0
if [[ "$1" == none ]]; then
SSL_SCHEME=http; TLS_TRUSTED=-1; TLS_NOTE="NO TLS (loopback HTTP only)"
rm -rf -- "$stage"
return 0
fi
if ( CERT_DIR="$stage"; cert_is_selfsigned ); then
TLS_NOTE="self-signed certificate (browser warning)"
else
TLS_TRUSTED=1; TLS_NOTE="Let's Encrypt certificate (automatic renewal)"
if [[ "$1" == domain ]]; then CURRENT_ACME_HOST="$ZGW_DOMAIN"
else CURRENT_ACME_HOST="$SERVER_IP"; fi
fi
# Callers stop the service before activation. Rename the directory, not two
# independent PEM files, so no reader can observe a mixed pair.
[[ ! -L "$live" ]] || { rm -rf -- "$stage"; return 1; }
if [[ -e "$live" ]]; then
# Linux rename-exchange publishes the pair in one filesystem operation;
# a failure leaves the old directory and both PEMs untouched.
if ! system_python - "$stage" "$live" <<'PY'
import ctypes, os, sys
libc = ctypes.CDLL(None, use_errno=True)
if libc.renameat2(-100, os.fsencode(sys.argv[1]), -100, os.fsencode(sys.argv[2]), 2):
raise OSError(ctypes.get_errno(), "certificate directory exchange failed")
PY
then rm -rf -- "$stage"; return 1; fi
rm -rf -- "$stage"
else
mv -T -- "$stage" "$live" || { rm -rf -- "$stage"; return 1; }
fi
}
# sets TLS_MODE_CHOICE (ip|domain|self|none); a global rather than command
# substitution so a domain typed at the prompt is kept
choose_tls_mode() {
TLS_MODE_CHOICE="${ZGW_SSL_MODE:-ip}"
if [[ "$TTY_OK" != "1" || -n "${ZGW_SSL_MODE}" ]]; then return 0; fi
echo
echo -e "${bold}Choose the TLS certificate setup:${plain}"
echo -e "${green} 1.${plain} Let's Encrypt — domain (90 days; needs port 80 + a DNS A record)"
echo -e "${green} 2.${plain} Let's Encrypt — this server's IP ${bold}(recommended: https://<ip>, no warning)${plain}"
echo -e "${green} 3.${plain} Self-signed (any IP, no port 80 — one browser warning)"
echo -e "${green} 4.${plain} No TLS (gateway stays on 127.0.0.1; bring your own proxy / tunnel)"
local c; c="$(ask "Choose an option [2]: " 2)"
case "$c" in
1) until is_domain "${ZGW_DOMAIN:-}"; do
ZGW_DOMAIN="$(ask "Domain name: " "")"
[[ -z "$ZGW_DOMAIN" ]] && fail "a domain is required for option 1"
done
TLS_MODE_CHOICE=domain ;;
2) TLS_MODE_CHOICE=ip ;;
3) TLS_MODE_CHOICE=self ;;
4) TLS_MODE_CHOICE=none ;;
*) fail "invalid choice" ;;
esac
}
# a certificate already in CERT_DIR is reused only if it matches the requested
# host AND is not a self-signed leftover from a failed Let's Encrypt attempt
cert_usable() { # cert_usable <mode>
local mode="$1" f="${CERT_DIR}/fullchain.pem"
[[ -s "$f" && -s "${CERT_DIR}/privkey.pem" ]] || return 1
# Renew before expiry, including short-lived IP certificates. Never call an
# expired or nearly expired matching certificate a reusable trusted cert.
openssl x509 -noout -checkend 86400 -in "$f" >/dev/null 2>&1 || return 1
case "$mode" in
none) return 1 ;;
self) cert_is_selfsigned ;;
ip) [[ -n "$SERVER_IP" ]] && ! cert_is_selfsigned \
&& openssl x509 -noout -checkip "$SERVER_IP" -in "$f" 2>/dev/null | grep -q 'does match' ;;
domain) [[ -n "$ZGW_DOMAIN" ]] && ! cert_is_selfsigned \
&& openssl x509 -noout -checkhost "$ZGW_DOMAIN" -in "$f" 2>/dev/null | grep -q 'does match' ;;
*) return 1 ;;
esac
}
install_renew_timer() {
[[ "${ZGW_SKIP_SYSTEMD:-0}" == "1" ]] && return 0
if [[ "${TLS_TRUSTED:-0}" != "1" ]]; then
systemctl disable --now "${RENEW_UNIT}.timer" >/dev/null 2>&1 || true
rm -f "$RENEW_SERVICE_FILE" "$RENEW_TIMER_FILE"
return 0
fi
cat > "$RENEW_SERVICE_FILE" <<EOF
[Unit]
Description=Renew the Zcode Gateway TLS certificate (acme.sh)
[Service]
Type=oneshot
UMask=0077
ExecStart=/usr/bin/flock -n ${UPDATE_LOCK} ${ACME_HOME}/acme.sh --renew --home ${ACME_HOME} --server letsencrypt -d ${CURRENT_ACME_HOST}
EOF
cat > "$RENEW_TIMER_FILE" <<EOF
[Unit]
Description=Twice-daily certificate renewal check
[Timer]
OnCalendar=*-*-* 03,15:17:00
RandomizedDelaySec=900
Persistent=true
[Install]
WantedBy=timers.target
EOF
systemctl daemon-reload
systemctl enable --now "${RENEW_UNIT}.timer" >/dev/null 2>&1 || warn "could not enable the renewal timer"
}
# ----------------------------------------------------------------- report
REPORT=()
chk() { # chk ok|warn|bad "text"
case "$1" in
ok) echo -e " ${green}✓${plain} $2"; REPORT+=("[ OK ] $2") ;;
warn) echo -e " ${yellow}!${plain} $2"; REPORT+=("[WARN] $2") ;;
bad) echo -e " ${red}✗${plain} $2"; REPORT+=("[FAIL] $2") ;;
esac
}
# The manager runs as root, so it is only ever replaced by a copy whose SHA-256
# matches the release's checksum list (never by whatever a branch serves today).
update_tmpdir() {
# Ignore TMPDIR: it can point into service-controlled storage.
mktemp -d /var/tmp/autozcoder-update.XXXXXXXX
}
resolve_release() {
local url prefix="https://github.com/${ZGW_REPO}/releases/tag/" tag
url="$(curl -fsSL --proto '=https' --proto-redir '=https' --max-time 30 --retry 2 \
-o /dev/null -w '%{url_effective}' "https://github.com/${ZGW_REPO}/releases/latest" 2>>"$LOG_FILE")" || return 1
[[ "$url" == "$prefix"* ]] || return 1
tag="${url#"$prefix"}"
[[ "$tag" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || return 1
RELEASE_BASE="https://github.com/${ZGW_REPO}/releases/download/${tag}"
}
verified_asset() { # <stage> <asset name>; sums already fetched
local d="$1" name="$2" exp act
exp="$(awk -v n="$name" '$2==n {print $1}' "$d/checksums-linux.sha256")"
[[ "$exp" =~ ^[0-9a-f]{64}$ ]] || { bad "missing, duplicate or malformed checksum for ${name}"; return 1; }
curl -fsSL --proto '=https' --proto-redir '=https' --max-time 600 --retry 3 \
-o "$d/$name" "${RELEASE_BASE}/${name}" 2>>"$LOG_FILE" || return 1
act="$(sha256sum "$d/$name" | awk '{print $1}')"
[[ "$act" == "$exp" ]] || { bad "SHA-256 mismatch for ${name}; refusing update"; return 1; }
}
stage_release() { # <private stage>; both artifacts must belong to one tag
local d="$1"
case "$(uname -m)" in x86_64|amd64|x64) ;; *) bad "release binaries support x86_64 only"; return 1 ;; esac
release_runtime_compatible || return 1
resolve_release || return 1
curl -fsSL --proto '=https' --proto-redir '=https' --max-time 30 --retry 3 \
-o "$d/checksums-linux.sha256" "${RELEASE_BASE}/checksums-linux.sha256" 2>>"$LOG_FILE" || return 1
verified_asset "$d" ZcodeGateway && verified_asset "$d" install-linux.sh || return 1
bash -n "$d/install-linux.sh" || return 1
validate_gateway "$d/ZcodeGateway"
}
release_runtime_compatible() {
local libc major minor
libc="$(getconf GNU_LIBC_VERSION 2>/dev/null)" || { bad "release requires glibc 2.35 or newer"; return 1; }
[[ "$libc" =~ ^glibc\ ([0-9]+)\.([0-9]+)$ ]] || { bad "unrecognized glibc version"; return 1; }
major="${BASH_REMATCH[1]}"; minor="${BASH_REMATCH[2]}"
if (( major < 2 || (major == 2 && minor < 35) )); then
bad "release requires glibc 2.35 or newer (${libc} found); build from source on this host"
return 1
fi
}
validate_gateway() {
# Do not execute the downloaded server as root (there is no --version flag).
local arch; arch="$(uname -m)"
system_python - "$1" "$arch" <<'PY'
from pathlib import Path
import sys
p = Path(sys.argv[1])
machine = {"x86_64": 62, "amd64": 62, "x64": 62, "aarch64": 183, "arm64": 183}.get(sys.argv[2])
with p.open("rb") as f:
h = f.read(20)
if (p.stat().st_size < 1_000_000 or len(h) != 20 or h[:7] != b"\x7fELF\x02\x01\x01"
or machine is None or int.from_bytes(h[18:20], "little") != machine
or int.from_bytes(h[16:18], "little") not in (2, 3)):
sys.exit("Refusing implausible or incompatible Linux executable")
PY
}
atomic_install() { # <source> <destination> <mode>; destination parent is trusted
local src="$1" dst="$2" mode="$3" tmp
tmp="$(mktemp "${dst}.XXXXXXXX")" || return 1
install -m "$mode" -- "$src" "$tmp" && mv -fT -- "$tmp" "$dst" \
|| { rm -f -- "$tmp"; return 1; }
}
fetch_manager_verified() { # <destination> [already verified private stage]
local d="${2:-}" own=0 rc=0
if [[ -z "$d" ]]; then
d="$(update_tmpdir)" || return 1
own=1
stage_release "$d" || { rm -rf -- "$d"; return 1; }
fi
atomic_install "$d/install-linux.sh" "$1" 755 || rc=$?
[[ "$own" == 0 ]] || rm -rf -- "$d"
return "$rc"
}
install_manager() {
if [[ -n "$SELF" && -f "$SELF" && "$SELF" != /dev/* && "$SELF" != /proc/* ]]; then
atomic_install "$SELF" "$MANAGER_BIN" 755 2>/dev/null && return 0
fi
fetch_manager_verified "$MANAGER_BIN"
}
# ------------------------------------------------------------ binary download
download_release() { # stage/verify before replacing any installed file
local d
d="$(update_tmpdir)" || return 1
stage_release "$d" || { rm -rf -- "$d"; return 1; }
mkdir -p "${ZGW_INSTALL_DIR}"
[[ ! -L "$ZGW_INSTALL_DIR" ]] || { rm -rf -- "$d"; return 1; }
ensure_service_user
chown "root:$(service_user)" "$ZGW_INSTALL_DIR" && chmod 1770 "$ZGW_INSTALL_DIR" \
&& atomic_install "$d/ZcodeGateway" "$ZGW_INSTALL_DIR/ZcodeGateway" 755 \
|| { rm -rf -- "$d"; return 1; }
rm -rf -- "$d"
BIN_SOURCE="release (SHA-256 verified)"
}
_build_in() { ( cd "$1" && bash scripts/build/linux.sh ); }
build_from_source() { # build_from_source <repo dir>
local src="$1" release=""
[[ -f "$src/scripts/build/linux.sh" ]] || fail "no scripts/build/linux.sh in ${src}"
if ! command -v bun >/dev/null 2>&1 && [[ ! -x "$src/tools/captcha-mint/captcha-mint" ]]; then
fail "source build needs Bun or a native executable at ${src}/tools/captcha-mint/captcha-mint; provide it before retrying"
fi
[[ -f /etc/os-release ]] && release="$(. /etc/os-release; echo "${ID:-}")"
case "$release" in
ubuntu|debian|armbian)
run_quiet "Installing build tools (python3-venv, pip, binutils)" \
install_pkgs python3 python3-venv python3-pip binutils ;;
*) run_quiet "Installing build tools (python3, pip, binutils)" \
install_pkgs python3 python3-pip binutils ;;
esac
run_quiet "Building ZcodeGateway from source (PyInstaller, a few minutes)" _build_in "$src" \
|| fail "build failed — details: ${LOG_FILE}"
[[ -x "$src/.local/dist/ZcodeGateway" ]] || fail "build finished but .local/dist/ZcodeGateway is missing"
validate_gateway "$src/.local/dist/ZcodeGateway" || fail "source build produced an incompatible executable"
mkdir -p "${ZGW_INSTALL_DIR}"
[[ ! -L "$ZGW_INSTALL_DIR" ]] || fail "install directory must not be a symlink"
ensure_service_user
chown "root:$(service_user)" "$ZGW_INSTALL_DIR" && chmod 1770 "$ZGW_INSTALL_DIR" \
|| fail "cannot secure installation directory"
atomic_install "$src/.local/dist/ZcodeGateway" "${ZGW_INSTALL_DIR}/ZcodeGateway" 755 \
|| fail "could not activate source-built executable"
BIN_SOURCE="built from source (${src})"
}
download_binary() {
BIN_SOURCE=""
if [[ -n "${ZGW_FROM_SOURCE:-}" ]]; then
build_from_source "$ZGW_FROM_SOURCE"
else
say "looking for the latest GitHub release…"
if download_release; then
:
else
fail "could not download the release (does a release with the Linux build exist?). From a checkout use: ZGW_FROM_SOURCE=/path/to/repo"
fi
fi
}
write_unit() {
# unprivileged by default; binding a port below 1024 then needs the one capability
local u run_as=""; u="$(service_user)"
if [[ "$u" != root ]]; then
run_as="User=${u}"$'\n'"Group=${u}"
(( ZGW_PORT < 1024 )) && run_as+=$'\n'"AmbientCapabilities=CAP_NET_BIND_SERVICE"$'\n'"CapabilityBoundingSet=CAP_NET_BIND_SERVICE"
fi
local tmp; tmp="$(mktemp "${UNIT_FILE}.XXXXXXXX")" || return 1
cat > "$tmp" <<EOF
[Unit]
Description=Zcode Gateway
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
UMask=0077
${run_as}
WorkingDirectory=${ZGW_INSTALL_DIR}
Environment=PLAYWRIGHT_BROWSERS_PATH=${ZGW_INSTALL_DIR}/pw-browsers
Environment=HOME=${ZGW_INSTALL_DIR}/home
ExecStart=${ZGW_INSTALL_DIR}/ZcodeGateway --config ${ZGW_INSTALL_DIR}/config.yaml
Restart=on-failure
RestartSec=3
TimeoutStopSec=90
# hardening (accounts/, certs/, genenv/, pw-browsers/, gateway.db, config.yaml live in the working dir)
NoNewPrivileges=true
ProtectSystem=strict
ReadWritePaths=${ZGW_INSTALL_DIR}
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
chmod 644 "$tmp" && mv -fT -- "$tmp" "$UNIT_FILE" || { rm -f -- "$tmp"; return 1; }
systemctl daemon-reload
}
# =========================================================== commands
banner() {
echo
echo -e "${blue}${bold}╔══════════════════════════════════════════════════════════╗${plain}"
printf "${blue}${bold}║${plain} %-56s${blue}${bold}║${plain}\n" "$1"
echo -e "${blue}${bold}╚══════════════════════════════════════════════════════════╝${plain}"
}
# our two listening ports must not be held by something else