-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsecure-vps-setup.sh
More file actions
1534 lines (1313 loc) · 59.1 KB
/
Copy pathsecure-vps-setup.sh
File metadata and controls
1534 lines (1313 loc) · 59.1 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
#!/bin/bash
# ============================================================
# Secure VPS Setup Script for Claude Code
# Installs & configures:
# Security : ClamAV, rkhunter, ufw, fail2ban
# Terminal : tmux (mobile-optimized for Termius)
# Languages : Go, Java 25, Node.js/TypeScript, Python 3.11, Miniconda
# LSP : gopls, jdtls, pyright, typescript-language-server
# Tools : ripgrep, fd, bat, jq, shellcheck
# Dev Tool : Claude Code (native installer)
# Tested on: Ubuntu 22.04 / 24.04 / 26.04
# ============================================================
set -euo pipefail
# ── Unattended execution ─────────────────────────────────
# Keep apt and dpkg fully non-interactive. DEBIAN_FRONTEND alone isn't
# enough on newer Ubuntu releases — needrestart prompts "Which services to restart?"
# during upgrades. Configure it to auto-restart everything.
export DEBIAN_FRONTEND=noninteractive
export DEBIAN_PRIORITY=critical
if [ -d /etc/needrestart ]; then
mkdir -p /etc/needrestart/conf.d
cat > /etc/needrestart/conf.d/99-vps-setup.conf <<'NRCONF'
$nrconf{restart} = 'a';
$nrconf{kernelhints} = 0;
NRCONF
fi
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'
print_status() { echo -e "${GREEN}[✓]${NC} $1"; }
print_warning() { echo -e "${YELLOW}[!]${NC} $1"; }
print_error() { echo -e "${RED}[✗]${NC} $1"; }
# ── Apt wrappers ─────────────────────────────────────────
# `apt update` can race against Ubuntu mirror syncs and fail with
# "File has unexpected size (X != Y). Mirror sync in progress?".
# Retry with exponential backoff; clear the partial lists between
# attempts so the next try starts clean. Bail out loudly if it keeps
# failing — that's a real network issue, not a transient mirror race.
apt_update_retry() {
local attempt=1
local max=4
while true; do
if apt-get update -y; then
return 0
fi
if [ "$attempt" -ge "$max" ]; then
print_error "apt update failed after $max attempts"
return 1
fi
local wait=$((attempt * 15))
print_warning "apt update attempt $attempt/$max failed — retrying in ${wait}s (probably a mirror sync)"
rm -rf /var/lib/apt/lists/partial/* 2>/dev/null || true
sleep "$wait"
attempt=$((attempt + 1))
done
}
# ============================================================
# Pinned versions — bump these to upgrade, then rerun the script.
# Every install below reinstalls to the pinned version on rerun, so the
# only source of truth for what's on the machine is this block.
# ============================================================
# Upgrade behavior: set RUN_UPGRADE=true to run `apt upgrade -y`.
# Keeping this false reduces runtime during repeated provisioning/re-runs.
RUN_UPGRADE="${RUN_UPGRADE:-false}"
# Optional AI coding assistants (opt-in).
# Enable by running: INSTALL_AI_AGENT_TOOLS=true sudo bash secure-vps-setup.sh
INSTALL_AI_AGENT_TOOLS="${INSTALL_AI_AGENT_TOOLS:-false}"
# Go runtime + tools
GO_VERSION="go1.26.2"
GOPLS_VERSION="v0.21.1"
DELVE_VERSION="v1.26.1"
GOLANGCI_LINT_VERSION="v2.11.4" # v2.x — module path is /v2/cmd/golangci-lint
AIR_VERSION="v1.65.1"
GOIMPORTS_VERSION="v0.44.0"
GOVULNCHECK_VERSION="v1.2.0"
# JVM
TEMURIN_PKG="temurin-25-jdk"
GRADLE_VERSION="9.4.1"
JDTLS_VERSION="1.58.0"
# Node / TypeScript
NVM_VERSION="v0.40.4"
NODE_VERSION="24.15.0" # Node.js 24 LTS (Krypton)
TS_VERSION="6.0.2"
TS_NODE_VERSION="10.9.2"
TSX_VERSION="4.21.0"
ESLINT_VERSION="10.2.0"
PRETTIER_VERSION="3.8.3"
NODE_TYPES_VERSION="24.12.2" # Keep major aligned with NODE_VERSION
NODEMON_VERSION="3.1.14"
PNPM_VERSION="10.33.0"
YARN_VERSION="1.22.22" # Yarn classic; modern yarn is enabled per-project via corepack
TS_LSP_VERSION="5.1.3"
NCU_VERSION="21.0.1"
BUN_VERSION="bun-v1.3.14" # Passed to bun.sh/install as the pin
AST_GREP_VERSION="0.43.0"
# Python + pip packages
PYTHON_VERSION="3.11.13" # Stable 3.11 branch
RUFF_VERSION="0.15.10"
MYPY_VERSION="1.20.1"
BLACK_VERSION="26.3.1"
ISORT_VERSION="8.0.1"
PYTEST_VERSION="9.0.3"
HTTPIE_VERSION="3.2.4"
POETRY_VERSION="2.3.4"
PIPENV_VERSION="2026.5.2"
IPYTHON_VERSION="9.10.1"
VIRTUALENV_VERSION="21.2.4"
PYRIGHT_VERSION="1.1.408"
UV_VERSION="0.11.7"
PIPX_VERSION="1.11.1"
PRECOMMIT_VERSION="4.5.1"
# LLM-focused CLI tooling (Python ecosystem)
LLM_VERSION="0.31"
LLM_ANTHROPIC_VERSION="0.25.1"
LLM_GEMINI_VERSION="0.32"
LLM_OLLAMA_VERSION="0.16.1"
# Mandatory AI coding CLI
CODEX_VERSION="0.137.0"
# Optional AI coding assistants
AIDER_VERSION="0.86.2"
OPEN_INTERPRETER_VERSION="0.4.3"
# Miniconda
MINICONDA_VERSION="py312_26.1.1-1"
# rtk (Rust Token Killer) — CLI output compressor, installed from upstream .deb
RTK_VERSION="v0.36.0"
# .NET + PowerShell (Microsoft apt repo handles point-level updates)
DOTNET_LTS_VERSION="10.0" # Even majors are LTS per Microsoft's policy
PWSH_NOTE="7.6.x" # apt 'powershell' package tracks Microsoft's latest 7.x
# Script supports amd64/x86_64 assets only.
HOST_ARCH="$(uname -m)"
if [ "$HOST_ARCH" != "x86_64" ] && [ "$HOST_ARCH" != "amd64" ]; then
print_error "Unsupported architecture: $HOST_ARCH. This script supports amd64/x86_64 only."
exit 1
fi
GO_ASSET_ARCH="linux-amd64"
MINICONDA_ASSET_ARCH="Linux-x86_64"
RTK_DEB_ARCH="amd64"
JAVA_HOME_ARCH="amd64"
# --- Environment discovery ---
if [ -r /etc/os-release ]; then
# shellcheck disable=SC1091
. /etc/os-release
else
print_error "/etc/os-release is required to resolve Ubuntu repo URLs"
exit 1
fi
if [ "${VERSION_ID:-}" != "22.04" ] && [ "${VERSION_ID:-}" != "24.04" ] && [ "${VERSION_ID:-}" != "26.04" ]; then
print_warning "Unsupported Ubuntu version ${VERSION_ID:-unknown}. The script is tested on 22.04, 24.04, and 26.04."
fi
# --- Check root ---
if [ "$EUID" -ne 0 ]; then
print_error "Please run as root: sudo bash secure-vps-setup.sh"
exit 1
fi
echo ""
echo "========================================="
echo " Secure VPS Setup for Claude Code"
echo " Security + tmux + Claude Code"
echo "========================================="
echo ""
# ============================================================
# Register all third-party apt repos up front so one apt update
# covers them all. Without this, each install section would trigger
# its own apt update (Adoptium, GitHub CLI, Microsoft, Caddy) —
# that's 4 extra mirror round-trips for no benefit.
# ============================================================
print_status "Registering third-party apt repos (Adoptium, GitHub CLI, Microsoft, Caddy)..."
# Prereqs for registering + verifying third-party repos
apt install -y curl gnupg ca-certificates apt-transport-https \
debian-keyring debian-archive-keyring openssh-client
# Helper for explicit, fail-fast downloads used by multiple installers.
download_file() {
local url=$1
local target=$2
curl -fsSL "$url" -o "$target"
}
is_apt_package_available() {
apt-cache show "$1" >/dev/null 2>&1
}
run_user_remote_script() {
local user=$1
local url=$2
local args=${3:-}
local installer
installer="$(mktemp "/tmp/${user}-installer.XXXXXX.sh")"
download_file "$url" "$installer"
chown "$user":"$user" "$installer"
chmod +x "$installer"
if [ -n "$args" ]; then
su - "$user" -c "bash '$installer' $args"
else
su - "$user" -c "bash '$installer'"
fi
rm -f "$installer"
}
install_go_cli_tool() {
local binary_name=$1
local module=$2
if command -v "$binary_name" >/dev/null 2>&1; then
return 0
fi
print_status "Installing ${binary_name} via go install ${module}@latest..."
su - "$DEV_USER" -c "export PATH=/usr/local/go/bin:\$HOME/go/bin:\$PATH && export GOPATH=\$HOME/go && go install ${module}@latest"
ln -sf "/home/$DEV_USER/go/bin/$binary_name" "/usr/local/bin/$binary_name" 2>/dev/null || true
}
# Adoptium (Temurin JDK) — provides temurin-<N>-jdk packages
if [ -z "${VERSION_CODENAME:-}" ]; then
print_error "VERSION_CODENAME is missing from /etc/os-release"
exit 1
fi
curl -fsSL https://packages.adoptium.net/artifactory/api/gpg/key/public \
| gpg --dearmor --yes -o /etc/apt/keyrings/adoptium.gpg
echo "deb [signed-by=/etc/apt/keyrings/adoptium.gpg] https://packages.adoptium.net/artifactory/deb ${VERSION_CODENAME} main" \
> /etc/apt/sources.list.d/adoptium.list
# GitHub CLI — provides `gh`
curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg \
| dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg 2>/dev/null
chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
> /etc/apt/sources.list.d/github-cli.list
# Microsoft — provides powershell (the packages-microsoft-prod.deb
# writes /etc/apt/sources.list.d/microsoft-prod.list itself)
UBUNTU_VER_ID="${VERSION_ID:-}"
download_file "https://packages.microsoft.com/config/ubuntu/${UBUNTU_VER_ID}/packages-microsoft-prod.deb" \
/tmp/packages-microsoft-prod.deb
apt install -y /tmp/packages-microsoft-prod.deb
rm -f /tmp/packages-microsoft-prod.deb
# Caddy (Cloudsmith stable) — provides caddy
curl -fsSL 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
| gpg --dearmor --yes -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -fsSL 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
> /etc/apt/sources.list.d/caddy-stable.list
# One update for all four repos
apt_update_retry
if [ "$RUN_UPGRADE" = "true" ]; then
print_status "Running apt upgrade (RUN_UPGRADE=true)..."
apt upgrade -y
fi
# --- Save pre-existing package list (first run only) ---
MANIFEST_DIR="/var/lib/vps-setup"
mkdir -p "$MANIFEST_DIR"
if [ ! -f "$MANIFEST_DIR/pre-existing-packages.list" ]; then
dpkg-query -W -f='${Package}\n' | sort > "$MANIFEST_DIR/pre-existing-packages.list"
print_status "Saved pre-existing package list to $MANIFEST_DIR/pre-existing-packages.list"
fi
# ============================================================
# 0. Create 'dev' user — locked down, no sudo, SSH-key only
# ============================================================
DEV_USER="dev"
if id "$DEV_USER" &>/dev/null; then
print_status "User '$DEV_USER' already exists"
else
print_status "Creating user '$DEV_USER' (no sudo, no root access)..."
adduser --disabled-password --gecos "Claude Code Dev User" "$DEV_USER"
fi
# Ensure no password login — SSH key auth only.
# Locks the password field in /etc/shadow (prefixes with '!'). Idempotent:
# - fresh users from --disabled-password are already locked
# - users left with a random password from older versions of this script
# (chpasswd) get cleaned up on rerun
passwd -l "$DEV_USER" >/dev/null 2>&1 || true
print_status "Password locked for '$DEV_USER' — SSH key auth only"
# Ensure dev user is NOT in sudo group
deluser "$DEV_USER" sudo 2>/dev/null || true
# Create workspace directory
mkdir -p /home/$DEV_USER/projects
chown -R $DEV_USER:$DEV_USER /home/$DEV_USER/projects
# Copy SSH authorized_keys from root so you can SSH in as dev
if [ -f /root/.ssh/authorized_keys ]; then
mkdir -p /home/$DEV_USER/.ssh
cp /root/.ssh/authorized_keys /home/$DEV_USER/.ssh/authorized_keys
chown -R $DEV_USER:$DEV_USER /home/$DEV_USER/.ssh
chmod 700 /home/$DEV_USER/.ssh
chmod 600 /home/$DEV_USER/.ssh/authorized_keys
print_status "Copied SSH keys from root → $DEV_USER"
fi
# Generate SSH keypair for dev user (for GitHub, git, etc.)
if [ ! -f /home/$DEV_USER/.ssh/id_ed25519 ]; then
su - "$DEV_USER" -c 'ssh-keygen -t ed25519 -C "dev@vps" -f ~/.ssh/id_ed25519 -N ""'
print_status "SSH keypair generated for '$DEV_USER' (ed25519)"
else
print_status "SSH keypair already exists for '$DEV_USER' — skipping"
fi
# SSH config for dev user (managed by setup script)
mkdir -p /home/$DEV_USER/.ssh
cat > /home/$DEV_USER/.ssh/config << 'SSHCONF'
Host *
StrictHostKeyChecking accept-new
UserKnownHostsFile ~/.ssh/known_hosts
LogLevel ERROR
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519
IdentitiesOnly yes
SSHCONF
chmod 600 /home/$DEV_USER/.ssh/config
chown -R $DEV_USER:$DEV_USER /home/$DEV_USER/.ssh
print_status "SSH config written for '$DEV_USER' (includes GitHub)"
# Keep host keys managed for root using accept-new
mkdir -p /root/.ssh
cat > /root/.ssh/config << 'SSHCONF'
Host *
StrictHostKeyChecking accept-new
UserKnownHostsFile /root/.ssh/known_hosts
LogLevel ERROR
SSHCONF
chmod 600 /root/.ssh/config
print_status "SSH host key checking is set to accept-new for root and dev"
# Give dev user access to common dev ports (no sudo needed for 1024+)
# Also allow git, curl, wget without sudo
apt install -y git curl wget
# Git defaults — identity set later by: setup-github (pulls from GitHub)
su - "$DEV_USER" -c 'git config --global init.defaultBranch main'
print_status "User '$DEV_USER' created — no sudo, SSH keys copied, workspace ready"
# ============================================================
# 1. ClamAV - Antivirus
# ============================================================
print_status "Installing ClamAV..."
apt install -y clamav clamav-daemon clamav-freshclam
# Stop freshclam temporarily to update definitions manually
systemctl stop clamav-freshclam 2>/dev/null || true
print_status "Updating ClamAV virus definitions (this may take a minute)..."
freshclam || print_warning "freshclam update had warnings — this is usually fine on first run"
systemctl enable clamav-freshclam
systemctl start clamav-freshclam
systemctl enable clamav-daemon
systemctl start clamav-daemon
# Create daily scan cron job
cat > /etc/cron.daily/clamav-scan << 'CRON'
#!/bin/bash
LOG="/var/log/clamav/daily-scan.log"
echo "=== ClamAV Daily Scan: $(date) ===" >> "$LOG"
clamscan -r -i --exclude-dir="^/sys" --exclude-dir="^/proc" --exclude-dir="^/dev" /home /tmp /var/www 2>&1 >> "$LOG"
# Uncomment the next line to get email alerts (requires mailutils)
# tail -20 "$LOG" | mail -s "ClamAV Daily Scan Report" your@email.com
CRON
chmod +x /etc/cron.daily/clamav-scan
# Create log directory used by periodic scans
mkdir -p /var/log/clamav
print_status "ClamAV installed — daily scans enabled for /home, /tmp, /var/www"
# Rotate scan logs to keep disk usage bounded
cat > /etc/logrotate.d/vps-security <<'LOGROTATE'
/var/log/clamav/daily-scan.log {
weekly
rotate 8
compress
missingok
notifempty
create 0644 root root
}
/var/log/rkhunter-weekly.log {
weekly
rotate 8
compress
missingok
notifempty
create 0644 root root
}
LOGROTATE
# ============================================================
# 2. rkhunter - Rootkit Scanner
# ============================================================
print_status "Installing rkhunter..."
apt install -y rkhunter
# Update rkhunter database
rkhunter --update || print_warning "rkhunter update had warnings — usually fine"
rkhunter --propupd
# Configure rkhunter for automatic weekly scans
cat > /etc/cron.weekly/rkhunter-scan << 'CRON'
#!/bin/bash
LOG="/var/log/rkhunter-weekly.log"
echo "=== rkhunter Weekly Scan: $(date) ===" >> "$LOG"
rkhunter --check --skip-keypress --report-warnings-only 2>&1 >> "$LOG"
CRON
chmod +x /etc/cron.weekly/rkhunter-scan
print_status "rkhunter installed — weekly scans enabled"
# ============================================================
# 3. UFW - Firewall
# ============================================================
print_status "Configuring UFW firewall..."
apt install -y ufw
# Default policies
ufw default deny incoming
ufw default allow outgoing
# Allow SSH (important! don't lock yourself out)
ufw allow 22/tcp comment 'SSH'
# Allow mosh (UDP 60000-61000, one port per concurrent session)
ufw allow 60000:61000/udp comment 'mosh'
# Allow HTTP/HTTPS — needed by Caddy (installed later in this script)
# to serve sites and to solve ACME HTTP-01 challenges for auto-TLS.
ufw allow 80/tcp comment 'HTTP (Caddy)'
ufw allow 443/tcp comment 'HTTPS (Caddy)'
# Enable firewall (--force skips the interactive "may disrupt existing
# ssh connections" confirmation; safe because SSH + mosh rules are
# already above this line)
ufw --force enable
ufw status verbose
print_status "UFW enabled — SSH (22), mosh (60000-61000/udp), HTTP (80), HTTPS (443) allowed"
print_warning "If you need other ports, run: sudo ufw allow <port>/tcp"
# ============================================================
# 4. fail2ban - Brute Force Protection
# ============================================================
print_status "Installing fail2ban..."
apt install -y fail2ban
# Create local config (overrides without touching defaults)
cat > /etc/fail2ban/jail.local << 'JAIL'
[DEFAULT]
# Ban for 1 hour after 5 failed attempts within 10 minutes
bantime = 3600
findtime = 600
maxretry = 5
# Use systemd backend
backend = systemd
[sshd]
enabled = true
port = ssh
filter = sshd
maxretry = 3
bantime = 3600
JAIL
systemctl enable fail2ban
systemctl restart fail2ban
print_status "fail2ban installed — bans IPs after 3 failed SSH attempts for 1 hour"
# ============================================================
# 5. mosh - Mobile shell (survives roaming / flaky connections)
# ============================================================
# Mosh initiates over SSH (existing key auth — no extra credentials) and
# then switches to UDP on a port in the 60000-61000 range that UFW
# opened above. Client connects with: mosh dev@<vps-ip>
print_status "Installing mosh..."
apt install -y mosh
# Best-effort ensure UTF-8 locale (mosh refuses to start without it)
if ! locale -a 2>/dev/null | grep -qiE '^(C\.UTF-8|en_US\.utf-?8)$'; then
apt install -y locales
locale-gen en_US.UTF-8 2>/dev/null || true
update-locale LANG=en_US.UTF-8 2>/dev/null || true
fi
print_status "mosh installed — connect with: mosh ${DEV_USER}@<vps-ip>"
# ============================================================
# 6. tmux - Session Persistence (optimized for Termius mobile)
# ============================================================
print_status "Installing tmux..."
apt install -y tmux
# Create tmux config for dev user (mobile-optimized)
cat > /home/$DEV_USER/.tmux.conf << 'TMUX'
# ─────────────────────────────────────────────────────────
# tmux config — optimized for Termius (iOS/Windows) + Claude Code
# ─────────────────────────────────────────────────────────
# ── Basics ──────────────────────────────────────────────
# Faster key response (crucial for mobile latency)
set -s escape-time 1
# 256 color support
set -g default-terminal "screen-256color"
set -ga terminal-overrides ",*256col*:Tc"
# Set Termius tab title to session name
set -g set-titles on
set -g set-titles-string "#S - #(whoami)"
# Direct OSC title escape via hooks (bypasses broken client_termtype detection)
set-hook -g client-attached 'run-shell "printf \"\\033]0;#{session_name} - \$(whoami)\\007\" > #{client_tty}"'
set-hook -g client-session-changed 'run-shell "printf \"\\033]0;#{session_name} - \$(whoami)\\007\" > #{client_tty}"'
set-hook -g session-renamed 'run-shell "printf \"\\033]0;#{session_name} - \$(whoami)\\007\" > #{client_tty}"'
# Massive scrollback (Claude Code outputs a LOT)
set -g history-limit 50000
# Start numbering at 1 (0 is far away on mobile keyboard)
set -g base-index 1
setw -g pane-base-index 1
# Renumber windows when one is closed
set -g renumber-windows on
# ── Mouse Support (critical for Termius touch) ─────────
set -g mouse on
# Better mouse scrolling — scroll the terminal, not command history
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'select-pane -t=; copy-mode -e; send-keys -M'"
bind -n WheelDownPane select-pane -t= \; send-keys -M
# ── Prefix Key ─────────────────────────────────────────
# Keep Ctrl+b as prefix (Termius handles it well)
# Double-tap Ctrl+b sends literal Ctrl+b to shell
bind C-b send-prefix
# ── Window & Pane Management ──────────────────────────
# Split panes with | and - (easier to remember on mobile)
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
unbind '"'
unbind %
# New windows open in current directory
bind c new-window -c "#{pane_current_path}"
# Switch panes with Alt+arrow (no prefix needed — great for mobile)
bind -n M-Left select-pane -L
bind -n M-Right select-pane -R
bind -n M-Up select-pane -U
bind -n M-Down select-pane -D
# Switch windows with Shift+arrow (no prefix needed)
bind -n S-Left previous-window
bind -n S-Right next-window
# Resize panes with Ctrl+arrow (no prefix needed)
bind -n C-Left resize-pane -L 2
bind -n C-Right resize-pane -R 2
bind -n C-Up resize-pane -U 2
bind -n C-Down resize-pane -D 2
# Quick reload config
bind r source-file ~/.tmux.conf \; display "Config reloaded!"
# ── Status Bar (clean, visible on small screens) ──────
set -g status-position bottom
set -g status-interval 5
# Colors — dark theme, high contrast for mobile
set -g status-style "fg=#a0a0a0,bg=#1a1a2e"
# Left: session name
set -g status-left-length 20
set -g status-left "#[fg=#16213e,bg=#0f3460,bold] #S #[fg=#0f3460,bg=#1a1a2e]"
# Right: time + hostname (useful when managing multiple VPS)
set -g status-right-length 40
set -g status-right "#[fg=#a0a0a0] %H:%M #[fg=#16213e,bg=#0f3460,bold] #H "
# Window tabs
setw -g window-status-format " #I:#W "
setw -g window-status-current-format "#[fg=#1a1a2e,bg=#e94560,bold] #I:#W "
# Pane borders
set -g pane-border-style "fg=#333333"
set -g pane-active-border-style "fg=#e94560"
# ── Copy Mode (for scrolling through Claude Code output) ─
setw -g mode-keys vi
# ── Activity Alerts ───────────────────────────────────
setw -g monitor-activity on
set -g visual-activity off
# ── Auto-attach / Detach behavior ─────────────────────
# Don't destroy session when last client detaches
set -g destroy-unattached off
# Aggressive resize — better for switching between
# desktop (wide) and phone (narrow)
setw -g aggressive-resize on
TMUX
chown $DEV_USER:$DEV_USER /home/$DEV_USER/.tmux.conf
# ── setup-github: interactive GitHub + SSH signing setup ─
mkdir -p /home/$DEV_USER/.local/bin
cat > /home/$DEV_USER/.local/bin/setup-github << 'SETUPGH'
#!/bin/bash
# ─────────────────────────────────────────────────────────
# setup-github — Interactive GitHub + SSH signing setup
#
# Uses the same ed25519 SSH key for both authentication and
# commit signing. GitHub accepts SSH-signed commits natively
# (no GPG required).
#
# Run once after VPS provisioning. Safe to rerun.
# ─────────────────────────────────────────────────────────
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
ok() { echo -e "${GREEN}[✓]${NC} $1"; }
warn() { echo -e "${YELLOW}[!]${NC} $1"; }
err() { echo -e "${RED}[✗]${NC} $1"; }
info() { echo -e "${CYAN}[→]${NC} $1"; }
echo ""
echo -e "${BOLD}GitHub + SSH Signing Setup${NC}"
echo "─────────────────────────────────────────"
echo ""
# ── Step 1: GitHub CLI authentication ─────────────────────
echo -e "${BOLD}Step 1: GitHub Authentication${NC}"
if gh auth status &>/dev/null; then
GH_USER=$(gh api user --jq .login 2>/dev/null)
ok "Already authenticated as ${BOLD}$GH_USER${NC}"
else
info "Logging in to GitHub..."
echo -e "${DIM}A browser URL will be shown — open it on any device to authenticate.${NC}"
echo ""
# Request admin:public_key + admin:ssh_signing_key so we can upload both key types
if ! gh auth login --git-protocol ssh --web \
--scopes 'admin:public_key,admin:ssh_signing_key'; then
err "GitHub login failed. Run 'setup-github' again to retry."
exit 1
fi
GH_USER=$(gh api user --jq .login 2>/dev/null)
ok "Authenticated as ${BOLD}$GH_USER${NC}"
fi
# Ensure we have the signing-key scope even if the user was already logged in
if ! gh auth status 2>&1 | grep -q 'admin:ssh_signing_key'; then
info "Requesting admin:ssh_signing_key scope for commit signing..."
gh auth refresh -h github.com -s admin:ssh_signing_key || \
warn "Could not add signing-key scope — signing-key upload may fail"
fi
echo ""
# ── Step 2: Git identity ──────────────────────────────────
echo -e "${BOLD}Step 2: Git Identity${NC}"
CURRENT_NAME=$(git config --global user.name 2>/dev/null)
CURRENT_EMAIL=$(git config --global user.email 2>/dev/null)
# Fetch name from GitHub as default if current is placeholder
GH_NAME=$(gh api user --jq .name 2>/dev/null)
GH_EMAIL=$(gh api user --jq .email 2>/dev/null)
if [ "$CURRENT_NAME" = "dev" ] || [ -z "$CURRENT_NAME" ]; then
DEFAULT_NAME="${GH_NAME:-}"
else
DEFAULT_NAME="$CURRENT_NAME"
fi
if [ "$CURRENT_EMAIL" = "dev@vps.local" ] || [ -z "$CURRENT_EMAIL" ]; then
DEFAULT_EMAIL="${GH_EMAIL:-}"
else
DEFAULT_EMAIL="$CURRENT_EMAIL"
fi
read -rp "$(echo -e "${CYAN}Name${NC} [${DEFAULT_NAME}]: ")" INPUT_NAME
INPUT_NAME="${INPUT_NAME:-$DEFAULT_NAME}"
read -rp "$(echo -e "${CYAN}Email${NC} [${DEFAULT_EMAIL}]: ")" INPUT_EMAIL
INPUT_EMAIL="${INPUT_EMAIL:-$DEFAULT_EMAIL}"
if [ -z "$INPUT_NAME" ] || [ -z "$INPUT_EMAIL" ]; then
err "Name and email are required."
exit 1
fi
git config --global user.name "$INPUT_NAME"
git config --global user.email "$INPUT_EMAIL"
ok "Git identity: $INPUT_NAME <$INPUT_EMAIL>"
echo ""
# ── Step 3: SSH key exists ────────────────────────────────
echo -e "${BOLD}Step 3: SSH Key${NC}"
SSH_PUB="$HOME/.ssh/id_ed25519.pub"
if [ ! -f "$SSH_PUB" ]; then
err "No SSH public key found at $SSH_PUB"
err "This should have been created by the VPS setup script."
exit 1
fi
KEY_TITLE="VPS ($(hostname))"
LOCAL_FP=$(ssh-keygen -lf "$SSH_PUB" 2>/dev/null | awk '{print $2}')
ok "Local key: $LOCAL_FP"
# ── Step 4: Upload as AUTHENTICATION key ──────────────────
if gh ssh-key list 2>/dev/null | grep -q "$LOCAL_FP"; then
ok "Auth key already on GitHub"
else
info "Uploading SSH auth key to GitHub..."
if gh ssh-key add "$SSH_PUB" --title "$KEY_TITLE"; then
ok "Auth key uploaded: $KEY_TITLE"
else
err "Failed to upload auth key. Manually:"
echo " gh ssh-key add $SSH_PUB --title \"$KEY_TITLE\""
fi
fi
# ── Step 5: Upload as SIGNING key (same key, separate entry) ──
if gh ssh-key list --type signing 2>/dev/null | grep -q "$LOCAL_FP"; then
ok "Signing key already on GitHub"
else
info "Uploading SSH signing key to GitHub..."
if gh ssh-key add "$SSH_PUB" --title "$KEY_TITLE (signing)" --type signing; then
ok "Signing key uploaded: $KEY_TITLE (signing)"
else
err "Failed to upload signing key. Manually:"
echo " gh ssh-key add $SSH_PUB --title \"$KEY_TITLE (signing)\" --type signing"
fi
fi
echo ""
# ── Step 6: Configure git for SSH signing ─────────────────
echo -e "${BOLD}Step 4: Git SSH Signing Config${NC}"
# Drop any stale GPG-based signing config from previous installs
git config --global --unset-all gpg.program 2>/dev/null || true
git config --global gpg.format ssh
git config --global user.signingkey "$SSH_PUB"
git config --global commit.gpgsign true
git config --global tag.gpgsign true
# Allowed signers file lets `git log --show-signature` verify local commits
ALLOWED_SIGNERS="$HOME/.ssh/allowed_signers"
PUBKEY_CONTENT=$(cat "$SSH_PUB")
touch "$ALLOWED_SIGNERS"
chmod 600 "$ALLOWED_SIGNERS"
# Remove any prior entry for this email, then append fresh
grep -v "^$INPUT_EMAIL " "$ALLOWED_SIGNERS" > "$ALLOWED_SIGNERS.tmp" 2>/dev/null || true
mv "$ALLOWED_SIGNERS.tmp" "$ALLOWED_SIGNERS" 2>/dev/null || true
echo "$INPUT_EMAIL $PUBKEY_CONTENT" >> "$ALLOWED_SIGNERS"
git config --global gpg.ssh.allowedSignersFile "$ALLOWED_SIGNERS"
ok "Git configured: sign commits & tags with SSH key"
ok "Allowed signers: $ALLOWED_SIGNERS"
echo ""
# ── Verify ────────────────────────────────────────────────
echo -e "${BOLD}Summary${NC}"
echo "─────────────────────────────────────────"
echo -e " GitHub user : ${GREEN}$GH_USER${NC}"
echo -e " Git name : $INPUT_NAME"
echo -e " Git email : $INPUT_EMAIL"
echo -e " SSH key : $LOCAL_FP"
echo -e " Signing : ${GREEN}SSH${NC} (same key, uploaded as signing on GitHub)"
echo ""
info "Testing SSH connection to GitHub..."
ssh -T git@github.com 2>&1 | head -3
echo ""
ok "Setup complete!"
echo ""
SETUPGH
chmod +x /home/$DEV_USER/.local/bin/setup-github
# --- Legacy bashrc migration (one-time: strip old single-marker format) ---
_migrate_legacy_bashrc() {
local file="/home/$DEV_USER/.bashrc"
[ -f "$file" ] || return 0
if grep -q '^# --- Claude Code VPS additions ---$' "$file" && \
! grep -q '^# --- Claude Code VPS additions START ---$' "$file"; then
sed -i '/^# --- Claude Code VPS additions ---$/,$d' "$file"
print_status "Migrated legacy .bashrc format (old markers removed)"
fi
}
_migrate_legacy_bashrc
# Add .local/bin to dev user's PATH (delete-then-append for upgrades)
sed -i '/# --- Claude Code VPS additions START ---/,/# --- Claude Code VPS additions END ---/d' /home/$DEV_USER/.bashrc
cat >> /home/$DEV_USER/.bashrc << 'BASHRC'
# --- Claude Code VPS additions START ---
export PATH="$HOME/.local/bin:$PATH"
# --- Claude Code VPS additions END ---
BASHRC
# ssh-agent auto-start (persists across tmux panes) — delete-then-append
sed -i '/# --- SSH Agent START ---/,/# --- SSH Agent END ---/d' /home/$DEV_USER/.bashrc
cat >> /home/$DEV_USER/.bashrc << 'SSHAGENT'
# --- SSH Agent START ---
SSH_ENV="$HOME/.ssh/agent-env"
_start_ssh_agent() {
eval "$(ssh-agent -s)" > /dev/null
mkdir -p ~/.ssh
echo "export SSH_AUTH_SOCK=$SSH_AUTH_SOCK" > "$SSH_ENV"
echo "export SSH_AGENT_PID=$SSH_AGENT_PID" >> "$SSH_ENV"
chmod 600 "$SSH_ENV"
ssh-add ~/.ssh/id_ed25519 2>/dev/null
}
if [ -z "$SSH_AUTH_SOCK" ] || ! ssh-add -l &>/dev/null; then
if [ -f "$SSH_ENV" ]; then
. "$SSH_ENV" > /dev/null
if ! ssh-add -l &>/dev/null; then
_start_ssh_agent
fi
else
_start_ssh_agent
fi
fi
# --- SSH Agent END ---
SSHAGENT
# Commit signing is done by SSH (git gpg.format ssh), configured by setup-github.
# Clean up any GPG-agent plumbing left behind by previous installs.
sed -i '/# --- GPG Agent START ---/,/# --- GPG Agent END ---/d' /home/$DEV_USER/.bashrc
chown -R $DEV_USER:$DEV_USER /home/$DEV_USER/.local
chown $DEV_USER:$DEV_USER /home/$DEV_USER/.bashrc
print_status "tmux installed — mobile-optimized"
# ============================================================
# 7. Dev Toolchains — Go, Java, TypeScript, Python
# ============================================================
print_status "Installing development toolchains..."
# ── System-level build essentials + productivity tools ──
# Productivity adds (all help Claude Code sessions run faster / cheaper):
# fzf — fuzzy finder, Ctrl-R history, cuts exploration turns
# yq — YAML query, companion to jq, saves tokens vs grep-parsing
# git-delta — paginated/colored git diff output (binary: `delta`)
# zoxide — `z <partial>` directory jump, cuts `cd long/path/…` tokens
# direnv — per-dir env vars, no repeated export boilerplate
# tldr — simplified man pages (huge token saver vs `man foo`)
# entr — re-run a command on file change (test-loop workflow)
DEV_APT_PKGS=(
build-essential
pkg-config
libssl-dev
unzip
zip
jq
tree
htop
ripgrep
fd-find
bat
fzf
zoxide
direnv
tldr
entr
software-properties-common
apt-transport-https
ca-certificates
)
for pkg in yq git-delta; do
if is_apt_package_available "$pkg"; then
DEV_APT_PKGS+=("$pkg")
else
print_warning "Package '$pkg' is unavailable in apt on this OS; installing via fallback installer later"
fi
done
apt install -y "${DEV_APT_PKGS[@]}"
# Symlink fd and bat (Ubuntu names them differently)
ln -sf /usr/bin/fdfind /usr/local/bin/fd 2>/dev/null || true
ln -sf /usr/bin/batcat /usr/local/bin/bat 2>/dev/null || true
# ── Go (pinned tarball from go.dev) ─────────────────────
print_status "Installing Go ${GO_VERSION}..."
download_file "https://go.dev/dl/${GO_VERSION}.${GO_ASSET_ARCH}.tar.gz" /tmp/go.tar.gz
rm -rf /usr/local/go
tar -C /usr/local -xzf /tmp/go.tar.gz
rm /tmp/go.tar.gz
# Go env for dev user (delete-then-append for upgrades)
sed -i '/# --- Go START ---/,/# --- Go END ---/d' /home/$DEV_USER/.bashrc
cat >> /home/$DEV_USER/.bashrc << 'GOENV'
# --- Go START ---
export PATH="/usr/local/go/bin:$HOME/go/bin:$PATH"
export GOPATH="$HOME/go"
# --- Go END ---
GOENV
# Install Go tools as dev user (pinned; `go install pkg@VERSION` replaces
# any existing binary in $GOPATH/bin on rerun)
su - "$DEV_USER" -c "export PATH=/usr/local/go/bin:\$HOME/go/bin:\$PATH && export GOPATH=\$HOME/go && \
go install golang.org/x/tools/gopls@${GOPLS_VERSION} && \
go install github.com/go-delve/delve/cmd/dlv@${DELVE_VERSION} && \
go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@${GOLANGCI_LINT_VERSION} && \
go install github.com/air-verse/air@${AIR_VERSION} && \
go install golang.org/x/tools/cmd/goimports@${GOIMPORTS_VERSION} && \
go install golang.org/x/vuln/cmd/govulncheck@${GOVULNCHECK_VERSION}"
install_go_cli_tool yq github.com/mikefarah/yq/v4
install_go_cli_tool delta github.com/dandavison/delta/cmd/delta
print_status "Go ${GO_VERSION} + gopls, delve, golangci-lint, air, goimports, govulncheck installed"
# ── Java (Eclipse Temurin via Adoptium, pinned meta-package) ──
# Adoptium apt repo was registered up top; here we just install.
print_status "Installing Java (${TEMURIN_PKG})..."
apt install -y "$TEMURIN_PKG"
# Install Maven (apt handles version) and pinned Gradle
apt install -y maven
curl -fsSL "https://services.gradle.org/distributions/gradle-${GRADLE_VERSION}-bin.zip" -o /tmp/gradle.zip
# Clean up old Gradle versions before extracting new
find /opt -maxdepth 1 -name 'gradle-*' -type d \
-not -name "gradle-${GRADLE_VERSION}" -exec rm -rf {} + 2>/dev/null || true
unzip -qo /tmp/gradle.zip -d /opt
ln -sf "/opt/gradle-${GRADLE_VERSION}/bin/gradle" /usr/local/bin/gradle
rm /tmp/gradle.zip
# Install jdtls (Eclipse JDT Language Server) — pinned milestone
print_status "Installing jdtls ${JDTLS_VERSION}..."
JDTLS_INSTALL_DIR="/opt/jdtls"
JDTLS_URL_BASE="https://download.eclipse.org/jdtls/milestones/${JDTLS_VERSION}"
# The milestone version dir contains a latest.txt pointing at the exact
# tarball filename (which includes a build timestamp). We pin the version
# but follow latest.txt within that version dir for the file to download.
JDTLS_FILENAME=$(curl -fsSL "${JDTLS_URL_BASE}/latest.txt" 2>/dev/null)
if [ -n "$JDTLS_FILENAME" ]; then
curl -fsSL "${JDTLS_URL_BASE}/${JDTLS_FILENAME}" -o /tmp/jdtls.tar.gz
rm -rf "$JDTLS_INSTALL_DIR"
mkdir -p "$JDTLS_INSTALL_DIR"
tar -xzf /tmp/jdtls.tar.gz -C "$JDTLS_INSTALL_DIR"
rm /tmp/jdtls.tar.gz
cat > /usr/local/bin/jdtls << 'JDTLS_LAUNCHER'
#!/bin/bash
exec /opt/jdtls/bin/jdtls "$@"
JDTLS_LAUNCHER
chmod +x /usr/local/bin/jdtls