forked from avacocloud/XHTTP-Installer
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDeploy-Ubuntu.sh
More file actions
executable file
·3012 lines (2747 loc) · 134 KB
/
Deploy-Ubuntu.sh
File metadata and controls
executable file
·3012 lines (2747 loc) · 134 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
# =============================================================
# XHTTP Installer — avaco_cloud
# Ubuntu Server | VLESS+XHTTP Auto-Installer
# -------------------------------------------------------------
# Copyright (C) 2025 avaco_cloud
# Repository: https://github.com/avacocloud/XHTTP-Installer
# Author: @avaco_cloud (https://t.me/avaco_cloud)
#
# Licensed under the GNU General Public License v3.0 (GPL-3.0).
# See LICENSE file for full terms.
#
# Redistribution requires preserving this copyright notice and
# the LICENSE file. Unauthorized removal of attribution is a
# copyright violation and will result in a DMCA takedown.
# =============================================================
set -euo pipefail
# Build identifier — do not remove (used for integrity verification)
readonly AVC_BUILD_ID="avc-7f3a92e1-2025-avacocloud"
export AVC_BUILD_ID
LOG_FILE="/tmp/xhttp-install.log"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" 2>/dev/null && pwd || echo "")"
drain_process_substitution_source() {
local source_path="${BASH_SOURCE[0]:-}"
case "$source_path" in
/dev/fd/*|/proc/*/fd/*) ;;
*) return 0 ;;
esac
# When this large script is launched as `bash <(curl ...)`, re-execing early
# closes Bash's script FD while curl may still be writing the rest of the file.
# Consume the remaining bytes first so curl exits cleanly instead of printing
# `curl: (23) Failure writing output to destination`.
cat "$source_path" >/dev/null 2>&1 || true
}
# If launched via process substitution (e.g. `bash <(curl ...)`),
# SCRIPT_DIR points to /dev/fd/... and the deploy/ folder is missing.
# Auto-download the full repo into /opt/xhttp-installer and re-exec from there.
if [[ -z "$SCRIPT_DIR" || ! -d "${SCRIPT_DIR}/deploy" ]]; then
REPO_DIR="/opt/xhttp-installer"
REPO_URL="https://github.com/avacocloud/XHTTP-Installer.git"
echo ">> Detected remote-piped run — fetching full repo to ${REPO_DIR}..."
if [[ ! -d "$REPO_DIR/.git" ]]; then
if command -v git >/dev/null 2>&1; then
git clone --depth 1 "$REPO_URL" "$REPO_DIR" || {
echo "ERROR: git clone failed. Install git first: apt install -y git"; exit 1; }
else
apt-get update -qq && apt-get install -y -qq git 2>/dev/null
git clone --depth 1 "$REPO_URL" "$REPO_DIR" || {
echo "ERROR: git clone failed."; exit 1; }
fi
else
(cd "$REPO_DIR" && git pull --ff-only 2>/dev/null) || true
fi
echo ">> Re-executing from ${REPO_DIR}/Deploy-Ubuntu.sh"
drain_process_substitution_source
exec bash "${REPO_DIR}/Deploy-Ubuntu.sh" "$@"
fi
VERCEL_DIR="${SCRIPT_DIR}/deploy/vercel"
NETLIFY_DIR="${SCRIPT_DIR}/deploy/netlify"
exec > >(tee -a "$LOG_FILE") 2>&1
# ─────────────────────────────────────────────
# COLORS
# ─────────────────────────────────────────────
C_RESET="\033[0m"
C_CYAN="\033[1;36m"
C_YELLOW="\033[1;33m"
C_GREEN="\033[1;32m"
C_RED="\033[1;31m"
C_MAGENTA="\033[1;35m"
C_GRAY="\033[0;90m"
C_WHITE="\033[1;37m"
print_banner() {
clear
echo ""
echo -e " ${C_CYAN}██╗ ██╗${C_WHITE}██╗ ██╗████████╗████████╗██████╗ ${C_RESET}"
echo -e " ${C_CYAN}╚██╗██╔╝${C_WHITE}██║ ██║╚══██╔══╝╚══██╔══╝██╔══██╗${C_RESET}"
echo -e " ${C_CYAN}╚███╔╝ ${C_WHITE}███████║ ██║ ██║ ██████╔╝${C_RESET}"
echo -e " ${C_CYAN}██╔██╗ ${C_WHITE}██╔══██║ ██║ ██║ ██╔═══╝ ${C_RESET}"
echo -e " ${C_CYAN}██╔╝ ██╗${C_WHITE}██║ ██║ ██║ ██║ ██║ ${C_RESET}"
echo -e " ${C_CYAN}╚═╝ ╚═╝${C_WHITE}╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ${C_RESET}"
echo ""
echo -e " ${C_YELLOW}██╗███╗ ██╗███████╗████████╗ █████╗ ██╗ ██╗ ███████╗██████╗ ${C_RESET}"
echo -e " ${C_YELLOW}██║████╗ ██║██╔════╝╚══██╔══╝██╔══██╗██║ ██║ ██╔════╝██╔══██╗${C_RESET}"
echo -e " ${C_YELLOW}██║██╔██╗ ██║███████╗ ██║ ███████║██║ ██║ █████╗ ██████╔╝${C_RESET}"
echo -e " ${C_YELLOW}██║██║╚██╗██║╚════██║ ██║ ██╔══██║██║ ██║ ██╔══╝ ██╔══██╗${C_RESET}"
echo -e " ${C_YELLOW}██║██║ ╚████║███████║ ██║ ██║ ██║███████╗███████╗███████╗██║ ██║${C_RESET}"
echo -e " ${C_YELLOW}╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚══════╝╚═╝ ╚═╝${C_RESET}"
echo ""
echo -e " ${C_MAGENTA}★${C_RESET} ${C_WHITE}a v a c o _ c l o u d${C_RESET} ${C_MAGENTA}★${C_RESET}"
echo -e " ${C_GRAY}─────────────────────────${C_RESET}"
echo -e " ${C_GRAY}VLESS + XHTTP + TLS${C_RESET}"
echo -e " ${C_GRAY}Ubuntu Auto-Installer${C_RESET}"
echo -e " ${C_GRAY}Relay: Vercel / Netlify${C_RESET}"
echo -e " ${C_GRAY}t.me/avaco_cloud${C_RESET}"
echo ""
}
step() { echo -e "\n${C_CYAN}>> $1${C_RESET}"; }
ok() { echo -e "${C_GREEN} ✔ $1${C_RESET}"; }
warn() { echo -e "${C_YELLOW} ⚠ $1${C_RESET}"; }
fail() { echo -e "${C_RED} ✘ $1${C_RESET}"; }
info() { echo -e "${C_GRAY} $1${C_RESET}"; }
# ─────────────────────────────────────────────
# PROGRESS HELPERS
# ─────────────────────────────────────────────
# Run a long command with a live spinner + elapsed-time counter so the user
# sees progress instead of a frozen terminal. Usage:
# spin "Installing X" -- some_command --with args
# Exit code of the command is preserved.
spin() {
local label="$1"; shift
[[ "$1" == "--" ]] && shift
local frames='|/-\' i=0 start now elapsed
start=$(date +%s)
# Run command in background, redirect output to a log so spinner can paint
local logfile; logfile=$(mktemp)
( "$@" >"$logfile" 2>&1 ) &
local pid=$!
# Real escape character (not the literal \033 backslash-zero-three-three)
local ESC=$'\033'
# Hide cursor
printf '%s[?25l' "$ESC"
while kill -0 "$pid" 2>/dev/null; do
now=$(date +%s); elapsed=$(( now - start ))
local frame="${frames:i++%${#frames}:1}"
printf '\r %s[1;36m%s%s[0m %s %s[0;90m(%ds elapsed)%s[0m ' \
"$ESC" "$frame" "$ESC" "$label" "$ESC" "$elapsed" "$ESC"
sleep 0.2
done
wait "$pid"; local rc=$?
now=$(date +%s); elapsed=$(( now - start ))
# Clear spinner line and restore cursor
printf '\r%s[2K%s[?25h' "$ESC" "$ESC"
if [[ $rc -eq 0 ]]; then
echo -e " ${C_GREEN}✔${C_RESET} ${label} ${C_GRAY}(${elapsed}s)${C_RESET}"
else
echo -e " ${C_RED}✘${C_RESET} ${label} ${C_RED}— exit ${rc}${C_RESET} ${C_GRAY}(${elapsed}s)${C_RESET}"
echo -e " ${C_GRAY}── last 10 lines of output ──${C_RESET}"
tail -10 "$logfile" 2>/dev/null | while IFS= read -r l; do echo -e " ${C_GRAY}$l${C_RESET}"; done
fi
rm -f "$logfile"
return $rc
}
read_default() {
local prompt="$1" default="$2" val
read -rp "$(echo -e " ${C_WHITE}${prompt}${C_RESET} ${C_GRAY}[${default}]${C_RESET}: ")" val
echo "${val:-$default}"
}
read_required() {
local prompt="$1" val
while true; do
read -rp "$(echo -e " ${C_WHITE}${prompt}${C_RESET}: ")" val
if [[ -n "${val// }" ]]; then echo "$val"; return; fi
fail "Required field."
done
}
read_secret() {
local prompt="$1" val
while true; do
read -rp "$(echo -e " ${C_WHITE}${prompt}${C_RESET}: ")" val
if [[ -n "${val// }" ]]; then echo "$val"; return; fi
fail "Required field."
done
}
confirm() {
local prompt="$1"
read -rp "$(echo -e " ${C_YELLOW}${prompt} [Y/n]${C_RESET}: ")" yn
case "${yn,,}" in n|no) return 1;; *) return 0;; esac
}
# =============================================================
# AUTO-FIX ENGINE
# =============================================================
AUTOFIX_MAX=3
autofix_diagnose() {
local ctx="$1"
echo -e "\n ${C_MAGENTA}[AutoFix]${C_RESET} Diagnosing: ${ctx}..."
case "$ctx" in
SSL)
if ss -tlnp 2>/dev/null | grep -q ':80 '; then
local pid80
pid80=$(ss -tlnp 2>/dev/null | grep ':80 ' | grep -oP 'pid=\K[0-9]+' | head -1)
[[ -n "$pid80" ]] && { warn "Killing port-80 process PID $pid80"; kill "$pid80" 2>/dev/null || true; sleep 2; }
fi
local resolved_ip my_ipv4 my_ipv6
resolved_ip=$(dig +short "${CFG_DOMAIN:-x}" A 2>/dev/null | grep -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | tail -1 || true)
# Get public IPv4 — try multiple sources including AWS/GCP/Azure metadata APIs
# AWS Lightsail/EC2: public IP is NOT on any interface (NAT), must use metadata
my_ipv4=$(
# AWS EC2/Lightsail metadata (IMDSv1 — works without token on most instances)
curl -4 -s --max-time 3 http://169.254.169.254/latest/meta-data/public-ipv4 2>/dev/null | \
grep -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -1
)
if [[ -z "$my_ipv4" ]]; then
my_ipv4=$(
curl -4 -s --max-time 5 https://ifconfig.me 2>/dev/null ||
curl -4 -s --max-time 5 https://api4.ipify.org 2>/dev/null ||
curl -4 -s --max-time 5 https://ipv4.icanhazip.com 2>/dev/null ||
hostname -I 2>/dev/null | tr ' ' '\n' | grep -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -1 || true
)
fi
my_ipv6=$(curl -6 -s --max-time 5 https://ifconfig.me 2>/dev/null || \
hostname -I 2>/dev/null | tr ' ' '\n' | grep ':' | head -1 || true)
if [[ -z "$resolved_ip" ]]; then
fail "DNS: ${CFG_DOMAIN:-?} A-record not found. Point it to ${my_ipv4:-<your-server-ip>}"
[[ -n "$my_ipv6" ]] && info "Server also has IPv6: ${my_ipv6} (use AAAA record if needed)"
elif [[ "$resolved_ip" == "$my_ipv4" ]]; then
ok "DNS OK: ${CFG_DOMAIN:-?} -> ${resolved_ip} (matches server public IPv4)"
elif [[ -n "$my_ipv6" ]] && dig +short "${CFG_DOMAIN:-x}" AAAA 2>/dev/null | grep -q "$my_ipv6"; then
ok "DNS OK: ${CFG_DOMAIN:-?} AAAA record matches server IPv6"
else
fail "DNS mismatch: ${CFG_DOMAIN:-?} -> ${resolved_ip} | server public IPv4: ${my_ipv4:-?}"
[[ -n "$my_ipv6" ]] && info "Server IPv6: ${my_ipv6}"
warn "Fix: set A-record of ${CFG_DOMAIN:-?} to ${my_ipv4:-<server-public-ip>}"
info "Note: on AWS Lightsail/EC2, use the Static/Elastic IP shown in the console, not the private IP"
fi
# Only add UFW rule if it's already active
if ufw status 2>/dev/null | grep -qi "Status: active"; then
ufw allow 80/tcp 2>/dev/null || true
ok "Firewall: port 80 allowed (ufw was already active)"
fi
;;
XRAYSSL)
[[ -f "${SSL_CERT:-}" ]] && chmod 644 "${SSL_CERT}" 2>/dev/null && ok "Cert permissions fixed" || fail "Cert missing: ${SSL_CERT:-unset}"
if [[ -f "${SSL_KEY:-}" ]]; then
chmod 640 "${SSL_KEY}" 2>/dev/null || true
chgrp nobody "${SSL_KEY}" 2>/dev/null || true
chmod o+x /etc/ssl/xhttp 2>/dev/null || true
chmod o+x "$(dirname "${SSL_KEY}")" 2>/dev/null || true
ok "Key permissions fixed (640 nobody + dir traversal)"
else
fail "Key missing: ${SSL_KEY:-unset}"
fi
;;
VERCEL)
curl -s --max-time 6 https://vercel.com -o /dev/null || { fail "Cannot reach vercel.com"; return; }
command -v vercel &>/dev/null || { warn "Reinstalling vercel CLI..."; npm install -g vercel --silent && ok "vercel CLI reinstalled"; }
rm -rf "${VERCEL_DIR}/.vercel" 2>/dev/null || true
ok "Vercel link cache cleared — will re-link on retry"
;;
FIREWALL)
# Only add allow rules if UFW is ALREADY enabled — do NOT enable it ourselves.
if ufw status 2>/dev/null | grep -qi "Status: active"; then
ufw allow 22/tcp 2>/dev/null || true
ufw allow 80/tcp 2>/dev/null || true
ufw allow 443/tcp 2>/dev/null || true
ufw allow "${CFG_INBOUND_PORT:-2096}/tcp" 2>/dev/null || true
ok "Firewall rules added (ufw already active): 22, 80, 443, ${CFG_INBOUND_PORT:-2096}"
else
info "UFW not active — skipping firewall configuration"
fi
;;
XRAY)
warn "Restarting xray service..."
local pid_port
pid_port=$(lsof -ti:"${CFG_INBOUND_PORT:-2096}" 2>/dev/null || true)
[[ -n "$pid_port" ]] && { info "Killing PID $pid_port on port ${CFG_INBOUND_PORT:-2096}"; kill -9 "$pid_port" 2>/dev/null || true; sleep 2; }
systemctl restart xray 2>/dev/null || true
sleep 4
if systemctl is-active --quiet xray 2>/dev/null; then
ok "xray restarted"
else
fail "xray still not running"
journalctl -u xray -n 20 --no-pager 2>/dev/null || true
fi
;;
*)
info "No auto-fix recipe for: $ctx"
;;
esac
}
autofix_and_retry() {
local ctx="$1" phase_fn="$2"
shift 2
local attempt=0
while [[ $attempt -lt $AUTOFIX_MAX ]]; do
attempt=$(( attempt + 1 ))
info "[$ctx] attempt $attempt/$AUTOFIX_MAX..."
if "$phase_fn" "$@"; then
ok "[$ctx] succeeded on attempt $attempt"
return 0
fi
[[ $attempt -ge $AUTOFIX_MAX ]] && { fail "[$ctx] failed after $AUTOFIX_MAX attempts. See: $LOG_FILE"; return 1; }
warn "[$ctx] failed — running auto-fix..."
autofix_diagnose "$ctx"
sleep 3
done
}
# =============================================================
# PHASE 1 — PREFLIGHT: ROOT + OS + BASE PACKAGES
# =============================================================
phase1_preflight() {
step "PHASE 1 — System check & prerequisites"
if [[ $EUID -ne 0 ]]; then
fail "Run as root: sudo bash Deploy-Ubuntu.sh"
exit 1
fi
ok "Running as root"
if grep -qiE "ubuntu" /etc/os-release 2>/dev/null; then
local ver
ver=$(grep VERSION_ID /etc/os-release | cut -d'"' -f2 | cut -d'.' -f1)
if [[ "$ver" -lt 20 ]]; then
fail "Ubuntu 20.04+ required (detected Ubuntu $ver)"
exit 1
fi
ok "Ubuntu $ver detected"
else
warn "Non-Ubuntu system — proceeding anyway"
fi
info "Updating package lists..."
spin "Updating package lists (apt-get update)" -- bash -c 'apt-get update -qq'
spin "Installing base dependencies (curl, git, jq, dig, openssl, ...)" -- bash -c '
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
curl wget git socat ufw jq openssl uuid-runtime netcat-openbsd \
build-essential ca-certificates gnupg lsb-release dnsutils unzip lsof
'
if ! command -v node &>/dev/null; then
spin "Adding NodeSource repo" -- bash -c 'curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -'
spin "Installing Node.js LTS (~30s, downloading ~30MB)" -- bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nodejs'
ok "Node.js $(node -v) installed"
else
ok "Node.js $(node -v) already present"
fi
# ── Ensure swap for low-RAM VPS (npm install -g netlify-cli OOMs on <2GB without swap)
local total_mem_mb swap_mb
total_mem_mb=$(awk '/MemTotal/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)
swap_mb=$(awk '/SwapTotal/ {print int($2/1024)}' /proc/meminfo 2>/dev/null || echo 0)
if (( total_mem_mb < 2048 && swap_mb < 1024 )); then
info "Low RAM detected (${total_mem_mb} MB, swap ${swap_mb} MB) — adding 2 GB swap to prevent OOM..."
if [[ ! -f /swapfile ]]; then
fallocate -l 2G /swapfile 2>/dev/null || dd if=/dev/zero of=/swapfile bs=1M count=2048 2>/dev/null
chmod 600 /swapfile 2>/dev/null
mkswap /swapfile >/dev/null 2>&1
swapon /swapfile 2>/dev/null
grep -q "/swapfile" /etc/fstab 2>/dev/null || echo "/swapfile none swap sw 0 0" >> /etc/fstab
ok "2 GB swap added at /swapfile"
else
swapon /swapfile 2>/dev/null || true
ok "Existing /swapfile activated"
fi
fi
}
# =============================================================
# PHASE 2 — DOWNLOAD & INSTALL ALL TOOLS (no config yet)
# =============================================================
phase2_install_all() {
step "PHASE 2 — Downloading & installing all tools"
# ── 2a. Xray ────────────────────────────────────────────
if command -v xray &>/dev/null && xray version &>/dev/null 2>&1; then
ok "Xray already installed ($(xray version 2>/dev/null | head -1))"
else
spin "Installing Xray (XTLS official, ~15MB)" -- bash -c '
bash -c "$(curl -L https://github.com/XTLS/Xray-install/raw/main/install-release.sh)" @ install
'
ok "Xray installed ($(xray version 2>/dev/null | head -1))"
fi
systemctl enable xray 2>/dev/null || true
# setup xray log dirs (owned by root since we run xray as root)
mkdir -p /var/log/xray
touch /var/log/xray/access.log /var/log/xray/error.log 2>/dev/null || true
chown -R root:root /var/log/xray 2>/dev/null || true
chmod 755 /var/log/xray 2>/dev/null || true
chmod 644 /var/log/xray/*.log 2>/dev/null || true
# ── 2b. Netlify CLI ─────────────────────────────────────
if command -v netlify &>/dev/null && netlify --version &>/dev/null 2>&1; then
ok "Netlify CLI already installed ($(netlify --version 2>/dev/null | head -1))"
else
info "Installing Netlify CLI..."
# Check Node version — current netlify-cli needs Node >=20.12.2.
local node_ver
node_ver=$(node -p "process.versions.node" 2>/dev/null || echo "0.0.0")
if ! node -e '
const [maj, min, patch] = process.versions.node.split(".").map(Number);
process.exit(maj > 20 || (maj === 20 && (min > 12 || (min === 12 && patch >= 2))) ? 0 : 1);
' 2>/dev/null; then
warn "Node.js ${node_ver} detected — netlify-cli needs >=20.12.2. Upgrading Node.js..."
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - >/dev/null 2>&1
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nodejs 2>/dev/null
ok "Node.js upgraded to $(node -v)"
fi
local netlify_ok=false
local NPM_REGISTRY="https://registry.npmjs.org/"
local NPM_CACHE_DIR="/tmp/xhttp-npm-cache"
mkdir -p "$NPM_CACHE_DIR" 2>/dev/null || true
npm config set registry "$NPM_REGISTRY" >/dev/null 2>&1 || true
# Common npm flags to speed up installs:
# --no-audit / --no-fund → skips post-install network calls
# --no-progress → suppresses progress bar (much faster on slow terms)
# --prefer-online → refresh package metadata; avoids stale-cache ETARGET
local NPM_FAST="--no-audit --no-fund --no-progress --prefer-online --registry=${NPM_REGISTRY} --cache=${NPM_CACHE_DIR} --fetch-retries=5 --fetch-retry-mintimeout=20000 --fetch-retry-maxtimeout=120000 --maxsockets=3"
# ── Attempt 1: fast npm global install ───────────────
if spin "Installing Netlify CLI via npm (~30-60s)" -- \
bash -c "npm install -g netlify-cli ${NPM_FAST}"; then
command -v netlify &>/dev/null && netlify_ok=true
fi
# ── Attempt 2: npm with lower max-old-space (low-RAM VPS) ─
if [[ "$netlify_ok" != "true" ]]; then
warn "Attempt 1 failed — retrying with low-RAM settings..."
if spin "Installing Netlify CLI (low-mem mode)" -- \
bash -c "NODE_OPTIONS='--max-old-space-size=384' npm install -g netlify-cli ${NPM_FAST}"; then
command -v netlify &>/dev/null && netlify_ok=true
fi
fi
# ── Attempt 3: npm cache clean + retry ───────────────
if [[ "$netlify_ok" != "true" ]]; then
warn "Attempt 2 failed — cleaning npm cache and retrying..."
npm cache clean --force --cache="$NPM_CACHE_DIR" >/dev/null 2>&1 || true
npm view content-type@2.0.0 version --registry="$NPM_REGISTRY" >/dev/null 2>&1 || \
warn "npm registry metadata still looks stale; forcing official npm registry for retry."
if spin "Installing Netlify CLI (after cache clean)" -- \
bash -c "NODE_OPTIONS='--max-old-space-size=384' npm install -g netlify-cli ${NPM_FAST}"; then
command -v netlify &>/dev/null && netlify_ok=true
fi
fi
# ── Attempt 4: npx wrapper (no global install needed) ─
if [[ "$netlify_ok" != "true" ]]; then
warn "Attempt 3 failed — creating npx-based wrapper instead..."
cat > /usr/local/bin/netlify <<'NPXWRAP'
#!/usr/bin/env bash
exec env \
NODE_OPTIONS="${NODE_OPTIONS:---max-old-space-size=384}" \
npm_config_registry="https://registry.npmjs.org/" \
npm_config_cache="/tmp/xhttp-npm-cache" \
npm_config_prefer_online=true \
npx --yes --package netlify-cli netlify "$@"
NPXWRAP
chmod +x /usr/local/bin/netlify
# Warm up the npx cache once
NODE_OPTIONS='--max-old-space-size=384' \
npm_config_registry="$NPM_REGISTRY" \
npm_config_cache="$NPM_CACHE_DIR" \
npm_config_prefer_online=true \
npx --yes --package netlify-cli netlify --version >/dev/null 2>&1 && netlify_ok=true || true
fi
if [[ "$netlify_ok" == "true" ]]; then
ok "Netlify CLI ready: $(netlify --version 2>/dev/null | head -1)"
else
fail "Could not install Netlify CLI after 4 attempts."
warn "Manual fix: npm install -g netlify-cli or npx netlify-cli"
warn "Installation will continue but Netlify deploy phase may fail."
fi
fi
# ── 2c. acme.sh ─────────────────────────────────────────
if [[ -f "$HOME/.acme.sh/acme.sh" ]]; then
ok "acme.sh already installed"
else
info "Installing acme.sh (attempt 1/2 — official)..."
curl -fsSL https://get.acme.sh | sh -s email=admin@example.com 2>&1 | \
grep -E "(install|Installed|OK|error|Error|success)" || true
if [[ ! -f "$HOME/.acme.sh/acme.sh" ]]; then
warn "First attempt failed — trying alternative mirror..."
curl -fsSL https://raw.githubusercontent.com/acmesh-official/acme.sh/master/acme.sh \
-o /tmp/acme-install.sh 2>/dev/null && \
bash /tmp/acme-install.sh --install-online 2>&1 | \
grep -E "(install|Installed|OK|error|Error)" || true
rm -f /tmp/acme-install.sh
fi
if [[ -f "$HOME/.acme.sh/acme.sh" ]]; then
ok "acme.sh installed → $HOME/.acme.sh/acme.sh"
else
fail "acme.sh installation failed — SSL certificate phase will not work."
warn "Manual fix on server: curl https://get.acme.sh | sh"
warn "Continuing... (script will fail at SSL phase)"
fi
fi
# Source acme.sh env so it's on PATH for this session
[[ -f "$HOME/.acme.sh/acme.sh.env" ]] && source "$HOME/.acme.sh/acme.sh.env" 2>/dev/null || true
ACME_CMD="$HOME/.acme.sh/acme.sh"
# Hard-fail early if acme.sh truly missing — better than cryptic "No such file" later
if [[ ! -x "$ACME_CMD" ]]; then
fail "acme.sh not found at $ACME_CMD — cannot continue without SSL tool."
exit 1
fi
# ── 2d. Vercel CLI ──────────────────────────────────────
if command -v vercel &>/dev/null; then
ok "Vercel CLI already installed ($(vercel --version 2>/dev/null | head -1))"
else
spin "Installing Vercel CLI via npm (~20-40s)" -- \
bash -c 'npm install -g vercel --no-audit --no-fund --no-progress --prefer-offline'
fi
# ── 2d. xray-knife ──────────────────────────────────────
XRAY_KNIFE_BIN="/usr/local/bin/xray-knife"
if [[ -x "$XRAY_KNIFE_BIN" ]]; then
ok "xray-knife already installed"
else
info "Downloading xray-knife..."
local arch release_url knife_url tmp_dir
arch=$(uname -m)
# xray-knife uses zip files: Xray-knife-linux-64.zip or Xray-knife-linux-arm.zip
case "$arch" in
aarch64) arch_tag="arm64" ;;
armv7*) arch_tag="arm" ;;
*) arch_tag="64" ;;
esac
release_url="https://api.github.com/repos/lilendian0x00/xray-knife/releases/latest"
knife_url=$(curl -fsSL "$release_url" 2>/dev/null | \
grep -oP '"browser_download_url":\s*"\Khttps://[^"]+Xray-knife-linux-'"${arch_tag}"'\.zip' | head -1 || true)
if [[ -z "$knife_url" ]]; then
warn "Could not auto-detect xray-knife URL — trying direct fallback"
knife_url="https://github.com/lilendian0x00/xray-knife/releases/latest/download/Xray-knife-linux-${arch_tag}.zip"
fi
tmp_dir=$(mktemp -d)
info "Downloading: $knife_url"
if curl -fsSL "$knife_url" -o "$tmp_dir/xray-knife.zip" 2>/dev/null; then
unzip -q "$tmp_dir/xray-knife.zip" -d "$tmp_dir" 2>/dev/null || true
else
warn "zip download failed — trying tar.gz fallback"
curl -fsSL "https://github.com/lilendian0x00/xray-knife/releases/latest/download/Xray-knife-linux-${arch_tag}.tar.gz" \
-o "$tmp_dir/xray-knife.tar.gz" 2>/dev/null || true
tar -xzf "$tmp_dir/xray-knife.tar.gz" -C "$tmp_dir" 2>/dev/null || true
fi
local knife_bin
knife_bin=$(find "$tmp_dir" -type f \( -name "xray-knife" -o -name "Xray-knife" \) | head -1 || true)
if [[ -n "$knife_bin" ]]; then
cp "$knife_bin" "$XRAY_KNIFE_BIN"
chmod +x "$XRAY_KNIFE_BIN"
ok "xray-knife installed → $XRAY_KNIFE_BIN"
else
warn "xray-knife binary not found — health-check step will be skipped"
XRAY_KNIFE_BIN=""
fi
rm -rf "$tmp_dir"
fi
}
# =============================================================
# PHASE 3 — COLLECT ALL USER INPUT (one shot, then confirm)
# =============================================================
phase3_collect_input() {
step "PHASE 3 — Configuration input"
echo -e " ${C_GRAY}Fill in the values below. Press Enter to accept defaults.${C_RESET}\n"
# ── SSL / Domain ────────────────────────────────────────
echo -e "\n ${C_CYAN}[ SSL & Domain ]${C_RESET}"
CFG_DOMAIN=$(read_required "Your domain (e.g. sub.example.com)")
# Email must be a REAL deliverable address — Let's Encrypt rejects
# admin@yoursub, *@example.com, *@test.com, etc.
echo -e " ${C_GRAY}Enter a REAL email — any provider works (Gmail, Yahoo, Outlook,${C_RESET}"
echo -e " ${C_GRAY}ProtonMail, iCloud, Zoho, your own domain, etc.).${C_RESET}"
echo -e " ${C_GRAY}Let's Encrypt rejects fake/placeholder addresses.${C_RESET}"
while true; do
CFG_EMAIL=$(read_required "Email for Let's Encrypt notifications (must be real)")
# Reject obvious placeholders
local lower_email="${CFG_EMAIL,,}"
if [[ ! "$lower_email" =~ ^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$ ]]; then
fail "Not a valid email format. Example: yourname@yourprovider.com"
continue
fi
if echo "$lower_email" | grep -qE '@(example\.|test\.|domain\.|yourdomain\.|mydomain\.|localhost|local$|invalid$)'; then
fail "Fake/placeholder email rejected. Use any real email account you own."
continue
fi
if echo "$lower_email" | grep -qE "@${CFG_DOMAIN}$"; then
warn "You're using an email on the same domain you're securing (@${CFG_DOMAIN})."
warn "Let's Encrypt may reject this if no MX record exists."
warn "Recommended: any third-party provider (Gmail, Yahoo, Outlook, ProtonMail, etc.)"
if ! confirm "Continue with ${CFG_EMAIL} anyway?"; then
continue
fi
fi
break
done
ok "Email accepted: ${CFG_EMAIL}"
# ── Inbound / Relay ─────────────────────────────────────
echo -e "\n ${C_CYAN}[ Inbound & Relay ]${C_RESET}"
CFG_INBOUND_PORT=$(read_default "Inbound port on server (XHTTP)" "443")
CFG_RELAY_PATH=$(read_default "RELAY_PATH (inbound path, e.g. /api)" "/api")
CFG_PUBLIC_PATH=$(read_default "PUBLIC_RELAY_PATH (Vercel-side path)" "/api")
[[ "${CFG_RELAY_PATH:0:1}" != "/" ]] && CFG_RELAY_PATH="/$CFG_RELAY_PATH"
[[ "${CFG_PUBLIC_PATH:0:1}" != "/" ]] && CFG_PUBLIC_PATH="/$CFG_PUBLIC_PATH"
# ── Platform credentials ─────────────────────────────────
local rand_proj
rand_proj="relay-$(cat /dev/urandom | tr -dc 'a-z0-9' 2>/dev/null | head -c8 || true)"
if [[ "$CFG_PLATFORM" == "vercel" ]]; then
echo -e "\n ${C_CYAN}[ Vercel Deployment ]${C_RESET}"
CFG_VERCEL_TOKEN=""
while [[ -z "${CFG_VERCEL_TOKEN// }" ]]; do
read -rp "$(echo -e " ${C_WHITE}Vercel API token (Settings → Tokens)${C_RESET}: ")" CFG_VERCEL_TOKEN
[[ -z "${CFG_VERCEL_TOKEN// }" ]] && fail "Required field."
done
CFG_PROJECT_NAME=$(read_default "Vercel project name" "$rand_proj")
CFG_VERCEL_SCOPE=$(read_default "Vercel scope/team slug (leave blank for personal)" "")
CFG_NETLIFY_TOKEN=""
CFG_NETLIFY_SITE=""
else
echo -e "\n ${C_CYAN}[ Netlify Deployment ]${C_RESET}"
CFG_NETLIFY_TOKEN=""
while [[ -z "${CFG_NETLIFY_TOKEN// }" ]]; do
read -rp "$(echo -e " ${C_WHITE}Netlify personal access token (app.netlify.com → User settings → OAuth)${C_RESET}: ")" CFG_NETLIFY_TOKEN
[[ -z "${CFG_NETLIFY_TOKEN// }" ]] && fail "Required field."
done
CFG_NETLIFY_SITE=$(read_default "Netlify site name" "$rand_proj")
CFG_VERCEL_TOKEN=""
CFG_PROJECT_NAME=""
CFG_VERCEL_SCOPE=""
fi
# ── Performance ─────────────────────────────────────────
if [[ "$CFG_PLATFORM" == "vercel" ]]; then
echo -e "\n ${C_CYAN}[ Performance (press Enter for defaults) ]${C_RESET}"
CFG_MAX_INFLIGHT=$(read_default "MAX_INFLIGHT" "128")
CFG_MAX_UP_BPS=$(read_default "MAX_UP_BPS" "2621440")
CFG_MAX_DOWN_BPS=$(read_default "MAX_DOWN_BPS" "2621440")
CFG_UPSTREAM_TIMEOUT=$(read_default "UPSTREAM_TIMEOUT_MS" "50000")
CFG_SUCCESS_LOG=$(read_default "SUCCESS_LOG_SAMPLE_RATE" "0")
CFG_SUCCESS_DUR=$(read_default "SUCCESS_LOG_MIN_DURATION_MS" "3000")
CFG_ERROR_INT=$(read_default "ERROR_LOG_MIN_INTERVAL_MS" "5000")
else
# Netlify: use sensible defaults silently (edge function handles its own tuning)
CFG_MAX_INFLIGHT="128"
CFG_MAX_UP_BPS="2621440"
CFG_MAX_DOWN_BPS="2621440"
CFG_UPSTREAM_TIMEOUT="50000"
CFG_SUCCESS_LOG="0"
CFG_SUCCESS_DUR="3000"
CFG_ERROR_INT="5000"
info "Performance settings: using defaults (Netlify)"
fi
# ── Summary ─────────────────────────────────────────────
echo ""
echo -e " ${C_CYAN}────────────── SUMMARY ──────────────${C_RESET}"
echo -e " ${C_WHITE}Platform :${C_RESET} $CFG_PLATFORM"
echo -e " ${C_WHITE}Domain :${C_RESET} $CFG_DOMAIN"
echo -e " ${C_WHITE}Inbound port :${C_RESET} $CFG_INBOUND_PORT"
echo -e " ${C_WHITE}RELAY_PATH :${C_RESET} $CFG_RELAY_PATH"
echo -e " ${C_WHITE}PUBLIC_PATH :${C_RESET} $CFG_PUBLIC_PATH"
if [[ "$CFG_PLATFORM" == "vercel" ]]; then
echo -e " ${C_WHITE}Vercel project :${C_RESET} $CFG_PROJECT_NAME"
[[ -n "$CFG_VERCEL_SCOPE" ]] && echo -e " ${C_WHITE}Vercel scope :${C_RESET} $CFG_VERCEL_SCOPE"
else
echo -e " ${C_WHITE}Netlify site :${C_RESET} $CFG_NETLIFY_SITE"
fi
if [[ "$CFG_PLATFORM" == "vercel" ]]; then
echo -e " ${C_WHITE}MAX_INFLIGHT :${C_RESET} $CFG_MAX_INFLIGHT"
echo -e " ${C_WHITE}MAX_UP_BPS :${C_RESET} $CFG_MAX_UP_BPS"
echo -e " ${C_WHITE}MAX_DOWN_BPS :${C_RESET} $CFG_MAX_DOWN_BPS"
echo -e " ${C_WHITE}TIMEOUT_MS :${C_RESET} $CFG_UPSTREAM_TIMEOUT"
echo -e " ${C_WHITE}SUCCESS_LOG :${C_RESET} $CFG_SUCCESS_LOG"
echo -e " ${C_WHITE}SUCCESS_DUR_MS :${C_RESET} $CFG_SUCCESS_DUR"
echo -e " ${C_WHITE}ERROR_INT_MS :${C_RESET} $CFG_ERROR_INT"
fi
echo -e " ${C_CYAN}─────────────────────────────────────${C_RESET}"
echo ""
if ! confirm "Proceed with these settings?"; then
warn "Aborted by user."
exit 0
fi
}
# =============================================================
# PHASE 4a — SSL WITH acme.sh
# =============================================================
phase4a_ssl() {
step "PHASE 4a — Obtaining SSL certificate for ${CFG_DOMAIN}"
SSL_DIR="/etc/ssl/xhttp/${CFG_DOMAIN}"
mkdir -p "$SSL_DIR"
SSL_CERT="${SSL_DIR}/fullchain.pem"
SSL_KEY="${SSL_DIR}/privkey.pem"
# ── Pre-flight: verify domain resolves from THIS server ─────
# acme.sh validation works because Let's Encrypt resolves DNS itself, but if
# the server can't resolve its own domain it can't bind to the right interface
# and webroot/standalone won't behave correctly. Use multiple resolvers.
local resolved
resolved=$(
dig +short +time=3 +tries=1 "$CFG_DOMAIN" A @1.1.1.1 2>/dev/null | grep -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -1
)
[[ -z "$resolved" ]] && resolved=$(
dig +short +time=3 +tries=1 "$CFG_DOMAIN" A @8.8.8.8 2>/dev/null | grep -oE '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' | head -1
)
[[ -z "$resolved" ]] && resolved=$(
curl -s --max-time 5 "https://cloudflare-dns.com/dns-query?name=${CFG_DOMAIN}&type=A" \
-H "accept: application/dns-json" 2>/dev/null | \
grep -oP '"data"\s*:\s*"\K[0-9.]+' | head -1
)
if [[ -n "$resolved" ]]; then
ok "DNS resolves: ${CFG_DOMAIN} → ${resolved}"
else
warn "Could not resolve ${CFG_DOMAIN} from server (DNS check failed)."
warn "If you JUST created the A-record, wait 1-2 min for propagation."
warn "acme.sh will still try; Let's Encrypt resolves DNS independently."
fi
# ── Detect & stop any service holding port 80 (Apache / Nginx / etc.) ─
local port80_used=false port80_pid="" port80_proc=""
local STOPPED_SERVICES=() # remember what we stopped so we can restart after
if ss -tlnp 2>/dev/null | grep -q ':80 '; then
port80_used=true
port80_pid=$(ss -tlnp 2>/dev/null | grep ':80 ' | grep -oP 'pid=\K[0-9]+' | head -1)
port80_proc=$(ss -tlnp 2>/dev/null | grep ':80 ' | grep -oP 'users:\(\("\K[^"]+' | head -1)
warn "Port 80 is in use by '${port80_proc:-unknown}' (PID ${port80_pid:-?})"
# Try to stop known web services cleanly via systemctl (preferred over kill)
for svc in apache2 httpd nginx caddy lighttpd; do
if systemctl is-active --quiet "$svc" 2>/dev/null; then
info "Stopping ${svc}.service (will restart after SSL)..."
if systemctl stop "$svc" 2>/dev/null; then
STOPPED_SERVICES+=("$svc")
ok "${svc} stopped"
fi
fi
done
sleep 2
# Verify port is free now
if ss -tlnp 2>/dev/null | grep -q ':80 '; then
warn "Port 80 still in use after stopping web services"
else
ok "Port 80 freed"
port80_used=false
fi
fi
# Helper: restart all services we stopped (called on success and failure)
_restart_stopped_services() {
for svc in "${STOPPED_SERVICES[@]}"; do
if systemctl start "$svc" 2>/dev/null; then
ok "${svc} restarted"
else
warn "Could not restart ${svc} — start it manually if needed"
fi
done
}
# ── Register acme.sh account (idempotent) ──────────────────
"$ACME_CMD" --register-account -m "$CFG_EMAIL" --server letsencrypt 2>&1 | \
grep -iE "register|already|account" | head -3 || true
# ── Helper: run acme.sh --issue and capture full output ────
# $1: mode (standalone | webroot)
# $2: extra flags (e.g. "--force")
_run_acme_issue() {
local mode="$1" extra="${2:-}"
info "Running: acme.sh --issue -d ${CFG_DOMAIN} --${mode} --keylength ec-256 --listen-v4 ${extra}"
local out rc
if [[ "$mode" == "webroot" ]]; then
mkdir -p /var/www/html
out=$("$ACME_CMD" --issue -d "$CFG_DOMAIN" --webroot /var/www/html \
--keylength ec-256 --listen-v4 --server letsencrypt $extra 2>&1) || rc=$?
else
out=$("$ACME_CMD" --issue -d "$CFG_DOMAIN" --standalone \
--keylength ec-256 --listen-v4 --server letsencrypt $extra 2>&1) || rc=$?
fi
rc=${rc:-0}
# Save full output for later inspection
LAST_ACME_OUT="$out"
# Show last 25 lines so user can see the real error
echo "$out" | tail -25 | while IFS= read -r l; do echo -e " ${C_GRAY}${l}${C_RESET}"; done
return $rc
}
# ── Check if a valid cert already exists on disk (covers both ECC and RSA) ─
local acme_cert_path="$HOME/.acme.sh/${CFG_DOMAIN}_ecc/${CFG_DOMAIN}.cer"
local acme_cert_path_rsa="$HOME/.acme.sh/${CFG_DOMAIN}/${CFG_DOMAIN}.cer"
if [[ -f "$acme_cert_path" ]]; then
info "Found existing EC cert at ${acme_cert_path} — will reuse"
elif [[ -f "$acme_cert_path_rsa" ]]; then
info "Found existing RSA cert at ${acme_cert_path_rsa} — will reuse"
acme_cert_path="$acme_cert_path_rsa"
fi
# ── Issue certificate ──────────────────────────────────────
local issue_rc=0 LAST_ACME_OUT=""
if [[ "$port80_used" == "true" ]]; then
if command -v nginx &>/dev/null && [[ -d /var/www/html ]]; then
_run_acme_issue webroot || issue_rc=$?
else
warn "Stopping port-80 service temporarily for standalone validation..."
[[ -n "$port80_pid" ]] && kill "$port80_pid" 2>/dev/null
systemctl stop xray 2>/dev/null || true
sleep 2
_run_acme_issue standalone || issue_rc=$?
systemctl start xray 2>/dev/null || true
fi
else
_run_acme_issue standalone || issue_rc=$?
fi
# ── Handle "Skipping. Next renewal time" — cert already exists & valid ───
# acme.sh exits 2 in this case; treat as success if the cer file is there.
if [[ $issue_rc -ne 0 ]] && echo "$LAST_ACME_OUT" | grep -qiE "Domains not changed|Skipping.*Next renewal"; then
if [[ -f "$acme_cert_path" ]]; then
info "acme.sh: existing cert still valid — using it as-is"
issue_rc=0
else
# The 'skip' message lied (no cert on disk) — force re-issue
warn "acme.sh says 'skip' but no cert file found — forcing re-issue with --force"
issue_rc=0
if [[ "$port80_used" == "true" ]] && ! { command -v nginx &>/dev/null && [[ -d /var/www/html ]]; }; then
systemctl stop xray 2>/dev/null || true
sleep 2
_run_acme_issue standalone "--force" || issue_rc=$?
systemctl start xray 2>/dev/null || true
elif [[ "$port80_used" == "true" ]]; then
_run_acme_issue webroot "--force" || issue_rc=$?
else
_run_acme_issue standalone "--force" || issue_rc=$?
fi
fi
fi
# ── If issue failed, try clearing stale acme.sh state and retry once ───
# acme.sh caches the CA directory URL and account info. If a previous run
# picked up ZeroSSL (which fails for many users) or got a stale account
# token, future runs reuse it and keep failing. Wipe and retry with
# Let's Encrypt forced.
if [[ $issue_rc -ne 0 ]] || [[ ! -f "$acme_cert_path" ]]; then
warn "First SSL attempt failed — clearing acme.sh CA/account cache and retrying..."
rm -rf "$HOME/.acme.sh/ca" 2>/dev/null || true
rm -f "$HOME/.acme.sh/account.conf" 2>/dev/null || true
# Re-register account explicitly against Let's Encrypt
"$ACME_CMD" --register-account -m "$CFG_EMAIL" --server letsencrypt 2>&1 | \
grep -iE "register|account|created" | head -3 || true
"$ACME_CMD" --set-default-ca --server letsencrypt 2>&1 | tail -3 || true
issue_rc=0
if [[ "$port80_used" == "true" ]] && ! { command -v nginx &>/dev/null && [[ -d /var/www/html ]]; }; then
systemctl stop xray 2>/dev/null || true
sleep 2
_run_acme_issue standalone "--force" || issue_rc=$?
systemctl start xray 2>/dev/null || true
elif [[ "$port80_used" == "true" ]]; then
_run_acme_issue webroot "--force" || issue_rc=$?
else
_run_acme_issue standalone "--force" || issue_rc=$?
fi
fi
# ── Verify the cert file actually exists before installcert ─
if [[ $issue_rc -ne 0 ]] || [[ ! -f "$acme_cert_path" ]]; then
fail "acme.sh --issue failed (exit ${issue_rc}). No cert at ${acme_cert_path}"
info "Common causes:"
info " • DNS A-record for ${CFG_DOMAIN} not pointing to this server's public IP"
info " • Cloudflare proxy enabled (orange cloud must be DNS-only / gray)"
info " • Port 80 not reachable from internet (provider firewall / security group)"
info " • Let's Encrypt rate-limit hit (5 certs/week per domain)"
info " • Server IP geo-blocked by Let's Encrypt (Iran sanctions)"
info ""
info "Manual recovery on server:"
info " rm -rf /root/.acme.sh/ca /root/.acme.sh/account.conf"
info " $ACME_CMD --register-account -m $CFG_EMAIL --server letsencrypt"
info " $ACME_CMD --issue -d $CFG_DOMAIN --standalone --keylength ec-256 --listen-v4 --server letsencrypt --force"
autofix_diagnose "SSL"
return 1
fi
ok "acme.sh certificate ready"
# ── Install certificate to target dir ──────────────────────
# --ecc selects the EC-key cert directory (${domain}_ecc/). Omit it for RSA.
local ecc_flag="--ecc"
[[ "$acme_cert_path" == *"${CFG_DOMAIN}/${CFG_DOMAIN}.cer" ]] && ecc_flag=""
"$ACME_CMD" --installcert -d "$CFG_DOMAIN" $ecc_flag \
--cert-file "${SSL_DIR}/cert.pem" \
--key-file "${SSL_KEY}" \
--fullchain-file "${SSL_CERT}" \
--reloadcmd "systemctl restart xray 2>/dev/null || true" 2>&1 | tail -5
if [[ -f "$SSL_CERT" && -f "$SSL_KEY" ]]; then
chmod 644 "$SSL_CERT" 2>/dev/null || true
chmod 640 "$SSL_KEY" 2>/dev/null || true
chgrp nobody "$SSL_KEY" 2>/dev/null || true
chmod o+x /etc/ssl/xhttp 2>/dev/null || true
chmod o+x "$(dirname "$SSL_KEY")" 2>/dev/null || true
ok "SSL certificate installed → $SSL_CERT"
# Restart any web services we stopped to free port 80
if [[ ${#STOPPED_SERVICES[@]} -gt 0 ]]; then
_restart_stopped_services
fi
# IMPORTANT: explicit `return 0` — the `[[ -gt 0 ]] && cmd` pattern above
# would return 1 if STOPPED_SERVICES is empty (the normal case), tricking
# autofix_and_retry into thinking SSL failed even when it succeeded.
return 0
else
fail "SSL installcert failed — cert was issued but not copied to ${SSL_CERT}"
info "Manually try: $ACME_CMD --installcert -d $CFG_DOMAIN --ecc --cert-file ... --key-file ... --fullchain-file ..."
if [[ ${#STOPPED_SERVICES[@]} -gt 0 ]]; then
_restart_stopped_services
fi
autofix_diagnose "SSL"
return 1
fi
}
# =============================================================
# PHASE 4b — CONFIGURE XRAY (VLESS+XHTTP+TLS)
# =============================================================
phase4b_configure_xray() {
step "PHASE 4b — Configuring Xray VLESS+XHTTP+TLS inbound"
local XRAY_CFG="/usr/local/etc/xray/config.json"
# ── Generate UUID ────────────────────────────────────────
INBOUND_UUID=$(uuidgen | tr '[:upper:]' '[:lower:]')
info "Generated UUID: ${INBOUND_UUID}"
# ── Backup old config ────────────────────────────────────
[[ -f "$XRAY_CFG" ]] && cp "$XRAY_CFG" "${XRAY_CFG}.bak" 2>/dev/null || true
# ── Platform-specific XHTTP tuning ───────────────────────
# Vercel: default padding 100-1000 works fine.
# Netlify: needs obfuscation-mode padding (10-50 + random key/header) to
# survive Netlify's edge body handling. The same key/header MUST
# be present in the client link's `extra` param or traffic is rejected.
# NOTE: do NOT declare XPADDING / XPADDING_KEY / XPADDING_HEADER / SC_MAX_POST_BYTES
# as `local` here — they need to outlive this function so phase6_summary and
# phase7_install_panel can embed them in the VLESS link. The `local` keyword
# confines them to this function's scope (export doesn't override that).
local XHTTP_MODE="auto"
local XHTTP_EXTRA_BLOCK="" # extra JSON properties for xray xhttpSettings
XPADDING=""
XPADDING_KEY=""
XPADDING_HEADER=""
XPADDING_OBFS="false"
SC_MAX_POST_BYTES=""
if [[ "${CFG_PLATFORM:-vercel}" == "netlify" ]]; then
XPADDING="10-50"
XPADDING_OBFS="true"
SC_MAX_POST_BYTES="1000000"
# Random key (lowercase, 7 chars) and header (mixed-case, 7 chars).
# /dev/urandom may produce no bytes in some environments — fall back to RANDOM.
XPADDING_KEY=$(LC_ALL=C tr -dc 'a-z' </dev/urandom 2>/dev/null | head -c 7 || true)
XPADDING_HEADER=$(LC_ALL=C tr -dc 'A-Za-z' </dev/urandom 2>/dev/null | head -c 7 || true)
[[ -z "$XPADDING_KEY" ]] && XPADDING_KEY="k$(printf '%06d' $RANDOM)"
[[ -z "$XPADDING_HEADER" ]] && XPADDING_HEADER="H$(printf '%06d' $RANDOM)"
info "Platform=netlify → xPaddingBytes=${XPADDING}, obfsMode=on"
info "Generated xPaddingKey : ${XPADDING_KEY}"
info "Generated xPaddingHeader : ${XPADDING_HEADER}"
XHTTP_EXTRA_BLOCK=",
\"xPaddingObfsMode\": true,
\"xPaddingKey\": \"${XPADDING_KEY}\",
\"xPaddingHeader\": \"${XPADDING_HEADER}\",
\"scMaxEachPostBytes\": \"${SC_MAX_POST_BYTES}\""
else
XPADDING="100-1000"
fi
# Export so phase6_summary + phase7_install_panel can reuse them in the VLESS link
export XPADDING XPADDING_KEY XPADDING_HEADER XPADDING_OBFS SC_MAX_POST_BYTES