-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathfullstack-harden.sh
More file actions
1407 lines (1221 loc) Β· 41.9 KB
/
fullstack-harden.sh
File metadata and controls
1407 lines (1221 loc) Β· 41.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
#!/bin/bash
#########################################
# Fullstack VPS Hardening & Setup Script
# For Ubuntu/Debian based systems
# Includes: Security hardening + Nginx + Node.js + PostgreSQL + PM2 + Next.js
#########################################
# Don't use set -e for the entire script as it causes issues with UFW commands
set -uo pipefail
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Configuration variables
SSH_PORT=${SSH_PORT:-22}
ADMIN_EMAIL=${ADMIN_EMAIL:-""}
ENABLE_CLOUDFLARE=${ENABLE_CLOUDFLARE:-"yes"}
DB_NAME="appdb"
DB_USER="appuser"
# Generate a safe password without problematic characters
DB_PASS=$(head /dev/urandom | tr -dc 'a-zA-Z0-9' | head -c 20)
APP_PORT=3000
API_PORT=3001
# Paths
APP_DIR="/var/www/app"
LOG_FILE="/var/log/vps-setup.log"
# Function to log messages
log_message() {
echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')]${NC} $1" | tee -a "$LOG_FILE"
}
log_error() {
echo -e "${RED}[$(date '+%Y-%m-%d %H:%M:%S')] ERROR:${NC} $1" | tee -a "$LOG_FILE"
}
log_warning() {
echo -e "${YELLOW}[$(date '+%Y-%m-%d %H:%M:%S')] WARNING:${NC} $1" | tee -a "$LOG_FILE"
}
log_info() {
echo -e "${BLUE}[$(date '+%Y-%m-%d %H:%M:%S')] INFO:${NC} $1" | tee -a "$LOG_FILE"
}
# Check if running as root
if [[ $EUID -ne 0 ]]; then
log_error "This script must be run as root"
exit 1
fi
# Detect OS
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$ID
VER=$VERSION_ID
else
log_error "Cannot detect OS version"
exit 1
fi
log_message "Starting Fullstack VPS Setup & Hardening..."
log_message "Detected OS: $OS $VER"
# Set non-interactive mode
export DEBIAN_FRONTEND=noninteractive
# Pre-configure packages
log_message "Pre-configuring package selections..."
echo "postfix postfix/main_mailer_type select No configuration" | debconf-set-selections
echo "postfix postfix/mailname string $(hostname)" | debconf-set-selections
echo "iptables-persistent iptables-persistent/autosave_v4 boolean true" | debconf-set-selections
echo "iptables-persistent iptables-persistent/autosave_v6 boolean true" | debconf-set-selections
#########################################
# PART 1: SECURITY HARDENING
#########################################
log_message "=== PART 1: SECURITY HARDENING ==="
# System Updates
log_message "Updating system packages..."
apt-get update -y
apt-get upgrade -y -q
apt-get dist-upgrade -y -q
apt-get autoremove -y
apt-get autoclean -y
# Configure Automatic Updates
log_message "Setting up automatic security updates..."
apt-get install -y -q unattended-upgrades apt-listchanges
cat > /etc/apt/apt.conf.d/50unattended-upgrades <<'EOCONFIG'
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}";
"${distro_id}:${distro_codename}-security";
"${distro_id}ESMApps:${distro_codename}-apps-security";
"${distro_id}ESM:${distro_codename}-infra-security";
"${distro_id}:${distro_codename}-updates";
};
Unattended-Upgrade::DevRelease "false";
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
EOCONFIG
cat > /etc/apt/apt.conf.d/20auto-upgrades <<'EOCONFIG'
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
EOCONFIG
# SSH Hardening
log_message "Hardening SSH configuration..."
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$(date +%Y%m%d)
groupadd -f sshusers
usermod -a -G sshusers root
# Add common users to sshusers
for user in ubuntu debian admin; do
if id "$user" &>/dev/null; then
usermod -a -G sshusers "$user"
log_message "Added $user to sshusers group"
fi
done
mkdir -p /etc/ssh/sshd_config.d/
cat > /etc/ssh/sshd_config.d/99-hardening.conf <<EOCONFIG
Port $SSH_PORT
Protocol 2
PermitRootLogin yes
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
AllowGroups sshusers
StrictModes yes
IgnoreRhosts yes
HostbasedAuthentication no
X11Forwarding no
LoginGraceTime 30
MaxAuthTries 3
MaxSessions 5
ClientAliveInterval 300
ClientAliveCountMax 2
LogLevel VERBOSE
UsePAM yes
Banner /etc/issue.net
EOCONFIG
# Install Fail2ban
log_message "Installing and configuring Fail2ban..."
apt-get install -y -q fail2ban
cat > /etc/fail2ban/jail.local <<EOCONFIG
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
# SSH Protection - Critical
[sshd]
enabled = true
port = $SSH_PORT
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 7200
[sshd-ddos]
enabled = true
port = $SSH_PORT
filter = sshd-ddos
logpath = /var/log/auth.log
maxretry = 10
bantime = 3600
[recidive]
enabled = true
filter = recidive
logpath = /var/log/fail2ban.log
action = iptables-allports[name=recidive]
bantime = 86400
maxretry = 3
EOCONFIG
# Create SSH DDoS filter
cat > /etc/fail2ban/filter.d/sshd-ddos.conf <<'EOCONFIG'
[Definition]
failregex = ^.*sshd.*: (Connection closed by|Received disconnect from|Connection reset by) <HOST>.*$
^.*sshd.*: (Did not receive identification string from) <HOST>.*$
ignoreregex =
EOCONFIG
systemctl enable fail2ban
systemctl restart fail2ban
# Configure UFW Firewall
log_message "Configuring UFW firewall..."
apt-get install -y -q ufw
ufw --force disable
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw default deny forward
# Allow SSH
ufw allow $SSH_PORT/tcp comment 'SSH'
ufw limit $SSH_PORT/tcp
# Allow web traffic (will be restricted to Cloudflare if enabled later)
if [ "$ENABLE_CLOUDFLARE" != "yes" ]; then
ufw allow 80/tcp comment 'HTTP'
ufw allow 443/tcp comment 'HTTPS'
fi
ufw logging low
echo "y" | ufw enable
log_message "UFW firewall enabled"
# Kernel Hardening
log_message "Applying kernel hardening..."
cat > /etc/sysctl.d/99-hardening.conf <<'EOCONFIG'
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_max_syn_backlog = 4096
kernel.randomize_va_space = 2
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
EOCONFIG
sysctl -p /etc/sysctl.d/99-hardening.conf
# Login Banner
cat > /etc/issue.net <<'EOCONFIG'
********************************************************************
* AUTHORIZED ACCESS ONLY *
* Unauthorized access to this system is forbidden and will be *
* prosecuted by law. By accessing this system, you agree that *
* your actions may be monitored and recorded. *
********************************************************************
EOCONFIG
#########################################
# PART 2: WEB SERVER SETUP
#########################################
log_message "=== PART 2: WEB SERVER SETUP ==="
# Install Nginx
log_message "Installing Nginx..."
apt-get install -y -q nginx
# Generate self-signed certificate for Cloudflare Full mode
log_message "Generating self-signed SSL certificate for secure connection..."
mkdir -p /etc/ssl/private /etc/ssl/certs
openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \
-keyout /etc/ssl/private/nginx-selfsigned.key \
-out /etc/ssl/certs/nginx-selfsigned.crt \
-subj "/C=US/ST=State/L=City/O=Organization/CN=localhost" 2>/dev/null
# Configure Nginx with both HTTP and HTTPS for Cloudflare Full mode
log_message "Configuring Nginx for secure connections..."
cat > /etc/nginx/sites-available/default <<'EOCONFIG'
# HTTP Server (port 80)
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# Get real IP from Cloudflare
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
real_ip_header CF-Connecting-IP;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 90;
}
location /api {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 90;
}
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
# HTTPS Server (port 443) - For Cloudflare Full mode
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name _;
# Self-signed certificate (perfect for Cloudflare Full mode)
ssl_certificate /etc/ssl/certs/nginx-selfsigned.crt;
ssl_certificate_key /etc/ssl/private/nginx-selfsigned.key;
# Modern SSL configuration
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
# Get real IP from Cloudflare
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 104.16.0.0/13;
set_real_ip_from 104.24.0.0/14;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 131.0.72.0/22;
real_ip_header CF-Connecting-IP;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_read_timeout 90;
}
location /api {
proxy_pass http://localhost:3001;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_read_timeout 90;
}
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
EOCONFIG
# Test and reload Nginx
nginx -t && systemctl reload nginx
systemctl enable nginx
#########################################
# PART 3: DATABASE SETUP
#########################################
log_message "=== PART 3: DATABASE SETUP ==="
# Install PostgreSQL
log_message "Installing PostgreSQL..."
apt-get install -y -q postgresql postgresql-contrib
# Start PostgreSQL
systemctl start postgresql
systemctl enable postgresql
# Wait for PostgreSQL to be ready
sleep 5
# Create database and user
log_message "Setting up PostgreSQL database..."
sudo -u postgres psql <<EOSQL
CREATE USER $DB_USER WITH ENCRYPTED PASSWORD '$DB_PASS';
CREATE DATABASE $DB_NAME OWNER $DB_USER;
GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;
ALTER DATABASE $DB_NAME SET timezone TO 'UTC';
\q
EOSQL
# Configure PostgreSQL for local connections
PG_VERSION=$(sudo -u postgres psql -t -c "SELECT version();" | awk '{print $3}' | sed 's/\..*//')
PG_CONFIG="/etc/postgresql/$PG_VERSION/main/postgresql.conf"
if [ -f "$PG_CONFIG" ]; then
sed -i "s/#listen_addresses = 'localhost'/listen_addresses = 'localhost'/" "$PG_CONFIG"
fi
# Update pg_hba.conf to trust local connections for the app user
PG_HBA="/etc/postgresql/$PG_VERSION/main/pg_hba.conf"
if [ -f "$PG_HBA" ]; then
echo "host $DB_NAME $DB_USER 127.0.0.1/32 md5" >> "$PG_HBA"
fi
# Restart PostgreSQL
systemctl restart postgresql
#########################################
# PART 4: NODE.JS & PM2 SETUP
#########################################
log_message "=== PART 4: NODE.JS & PM2 SETUP ==="
# Install Node.js LTS
log_message "Installing Node.js LTS..."
curl -fsSL https://deb.nodesource.com/setup_lts.x | bash -
apt-get install -y nodejs
# Install build essentials for npm packages
apt-get install -y build-essential
# Install PM2 globally
log_message "Installing PM2..."
npm install -g pm2
# Setup PM2 to start on boot
pm2 startup systemd -u root --hp /root
systemctl enable pm2-root
#########################################
# PART 5: APPLICATION SETUP
#########################################
log_message "=== PART 5: APPLICATION SETUP ==="
# Create app directory
log_message "Creating application structure..."
mkdir -p $APP_DIR/{api,frontend}
cd $APP_DIR
# Create API (Express + PostgreSQL)
log_message "Setting up Express API..."
cd $APP_DIR/api
cat > package.json <<'EOFILE'
{
"name": "api",
"version": "1.0.0",
"description": "Example API with PostgreSQL",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"dependencies": {
"express": "^4.18.2",
"pg": "^8.11.3",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"helmet": "^7.1.0",
"morgan": "^1.10.0"
},
"devDependencies": {
"nodemon": "^3.0.1"
}
}
EOFILE
# Create .env file for API
cat > .env <<EOFILE
DB_NAME=$DB_NAME
DB_USER=$DB_USER
DB_PASS=$DB_PASS
DB_HOST=localhost
DB_PORT=5432
API_PORT=$API_PORT
NODE_ENV=production
EOFILE
# Create API server - FIXED: connection and error handling
cat > server.js <<'EOFILE'
const express = require('express');
const { Pool } = require('pg');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
require('dotenv').config();
const app = express();
const port = process.env.API_PORT || 3001;
// Middleware
app.use(helmet());
app.use(cors({
origin: ['http://localhost:3000', 'http://localhost'],
credentials: true
}));
app.use(express.json());
app.use(morgan('combined'));
// PostgreSQL connection with better error handling
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASS,
port: process.env.DB_PORT,
connectionTimeoutMillis: 5000,
idleTimeoutMillis: 30000,
max: 20
});
// Test database connection
pool.query('SELECT NOW()', (err, res) => {
if (err) {
console.error('Database connection error:', err);
} else {
console.log('Database connected successfully at:', res.rows[0].now);
}
});
// Initialize database table
async function initDB() {
try {
await pool.query(`
CREATE TABLE IF NOT EXISTS posts (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
content TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Check if table is empty and add sample data
const result = await pool.query('SELECT COUNT(*) FROM posts');
if (parseInt(result.rows[0].count) === 0) {
await pool.query(`
INSERT INTO posts (title, content) VALUES
('Welcome to your VPS!', 'Your fullstack application is running successfully.'),
('Security First', 'This server has been hardened with security best practices.'),
('Ready for Development', 'You can now build your application on this foundation.')
`);
console.log('Sample data inserted');
}
console.log('Database initialized successfully');
} catch (err) {
console.error('Database initialization error:', err);
console.error('Make sure PostgreSQL is running and credentials are correct');
}
}
// Routes
app.get('/api', (req, res) => {
res.json({
message: 'API is running',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV,
database: pool.totalCount > 0 ? 'connected' : 'disconnected'
});
});
// GET all posts
app.get('/api/posts', async (req, res) => {
try {
const result = await pool.query('SELECT * FROM posts ORDER BY created_at DESC');
res.json(result.rows);
} catch (err) {
console.error('Error fetching posts:', err);
res.status(500).json({ error: 'Failed to fetch posts', details: err.message });
}
});
// GET single post
app.get('/api/posts/:id', async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query('SELECT * FROM posts WHERE id = $1', [id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Post not found' });
}
res.json(result.rows[0]);
} catch (err) {
console.error('Error fetching post:', err);
res.status(500).json({ error: 'Failed to fetch post' });
}
});
// POST new post
app.post('/api/posts', async (req, res) => {
try {
const { title, content } = req.body;
if (!title) {
return res.status(400).json({ error: 'Title is required' });
}
const result = await pool.query(
'INSERT INTO posts (title, content) VALUES ($1, $2) RETURNING *',
[title, content || '']
);
res.status(201).json(result.rows[0]);
} catch (err) {
console.error('Error creating post:', err);
res.status(500).json({ error: 'Failed to create post' });
}
});
// UPDATE post
app.put('/api/posts/:id', async (req, res) => {
try {
const { id } = req.params;
const { title, content } = req.body;
const result = await pool.query(
'UPDATE posts SET title = $1, content = $2, updated_at = CURRENT_TIMESTAMP WHERE id = $3 RETURNING *',
[title, content, id]
);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Post not found' });
}
res.json(result.rows[0]);
} catch (err) {
console.error('Error updating post:', err);
res.status(500).json({ error: 'Failed to update post' });
}
});
// DELETE post
app.delete('/api/posts/:id', async (req, res) => {
try {
const { id } = req.params;
const result = await pool.query('DELETE FROM posts WHERE id = $1 RETURNING id', [id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Post not found' });
}
res.json({ message: 'Post deleted successfully', id: result.rows[0].id });
} catch (err) {
console.error('Error deleting post:', err);
res.status(500).json({ error: 'Failed to delete post' });
}
});
// Health check
app.get('/api/health', async (req, res) => {
try {
await pool.query('SELECT 1');
res.json({
status: 'healthy',
uptime: process.uptime(),
database: 'connected'
});
} catch (err) {
res.status(503).json({
status: 'unhealthy',
database: 'disconnected',
error: err.message
});
}
});
// Start server
app.listen(port, '127.0.0.1', () => {
console.log(`API server running on port ${port}`);
initDB();
});
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('SIGTERM signal received: closing HTTP server');
pool.end(() => {
console.log('Database pool closed');
process.exit(0);
});
});
EOFILE
# Install API dependencies
npm install
# Create Next.js Frontend
log_message "Setting up Next.js frontend..."
cd $APP_DIR/frontend
# Create package.json for Next.js
cat > package.json <<'EOFILE'
{
"name": "frontend",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start -p 3000",
"lint": "next lint"
},
"dependencies": {
"next": "14.0.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"axios": "^1.6.2"
},
"devDependencies": {
"eslint": "^8.55.0",
"eslint-config-next": "14.0.4",
"@types/node": "^20.10.5",
"@types/react": "^18.2.45",
"@types/react-dom": "^18.2.18",
"typescript": "^5.3.3",
"tailwindcss": "^3.4.0",
"autoprefixer": "^10.4.16",
"postcss": "^8.4.32"
}
}
EOFILE
# Create Next.js config - FIXED: proper API proxy
cat > next.config.js <<'EOFILE'
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:3001/api/:path*',
},
];
},
}
module.exports = nextConfig
EOFILE
# Create tsconfig.json
cat > tsconfig.json <<'EOFILE'
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}
EOFILE
# Create pages directory
mkdir -p pages styles
# Create Tailwind config
cat > tailwind.config.js <<'EOFILE'
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx,mdx}',
'./components/**/*.{js,ts,jsx,tsx,mdx}',
],
theme: {
extend: {},
},
plugins: [],
}
EOFILE
# Create PostCSS config
cat > postcss.config.js <<'EOFILE'
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
EOFILE
# Create main page - FIXED: proper error handling and loading states
cat > pages/index.tsx <<'EOFILE'
import React, { useState, useEffect } from 'react';
import axios from 'axios';
interface Post {
id: number;
title: string;
content: string;
created_at: string;
}
export default function Home() {
const [posts, setPosts] = useState<Post[]>([]);
const [newPost, setNewPost] = useState({ title: '', content: '' });
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [apiStatus, setApiStatus] = useState<'checking' | 'connected' | 'error'>('checking');
useEffect(() => {
checkApiStatus();
fetchPosts();
}, []);
const checkApiStatus = async () => {
try {
const response = await axios.get('/api/health');
setApiStatus('connected');
} catch (err) {
console.error('API health check failed:', err);
setApiStatus('error');
}
};
const fetchPosts = async () => {
try {
setLoading(true);
setError('');
const response = await axios.get('/api/posts');
setPosts(response.data);
} catch (err: any) {
console.error('Failed to fetch posts:', err);
setError(err.response?.data?.details || 'Failed to fetch posts. Make sure the API is running.');
} finally {
setLoading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!newPost.title.trim()) return;
try {
setError('');
const response = await axios.post('/api/posts', newPost);
setPosts([response.data, ...posts]);
setNewPost({ title: '', content: '' });
} catch (err: any) {
console.error('Failed to create post:', err);
setError(err.response?.data?.error || 'Failed to create post');
}
};
const handleDelete = async (id: number) => {
try {
setError('');
await axios.delete(`/api/posts/${id}`);
setPosts(posts.filter(post => post.id !== id));
} catch (err: any) {
console.error('Failed to delete post:', err);
setError(err.response?.data?.error || 'Failed to delete post');
}
};
return (
<div className="min-h-screen bg-gradient-to-br from-purple-600 via-purple-700 to-indigo-800">
<div className="container mx-auto px-4 py-8 max-w-7xl">
{/* Header */}
<header className="text-center text-white mb-12">
<h1 className="text-5xl md:text-6xl font-bold mb-4 flex items-center justify-center">
<span className="mr-3">π</span>
Fullstack VPS Application
</h1>
<p className="text-xl md:text-2xl text-purple-100 opacity-90">
Your secure, modern web application is running!
</p>
</header>
{/* Stats Grid */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-12">
<div className="bg-white/90 backdrop-blur-sm rounded-xl p-6 text-center transform hover:scale-105 transition-transform shadow-xl">
<h3 className="text-lg font-semibold text-purple-700 mb-2 flex items-center justify-center">
<span className="mr-2 text-2xl">β
</span>
Server Status
</h3>
<p className="text-gray-700">Hardened & Secure</p>
</div>
<div className="bg-white/90 backdrop-blur-sm rounded-xl p-6 text-center transform hover:scale-105 transition-transform shadow-xl">
<h3 className="text-lg font-semibold text-purple-700 mb-2 flex items-center justify-center">
<span className="mr-2 text-2xl">π</span>
Security
</h3>
<p className="text-gray-700">UFW + Fail2ban Active</p>
</div>
<div className="bg-white/90 backdrop-blur-sm rounded-xl p-6 text-center transform hover:scale-105 transition-transform shadow-xl">
<h3 className="text-lg font-semibold text-purple-700 mb-2 flex items-center justify-center">
<span className="mr-2 text-2xl">π</span>
Stack
</h3>
<p className="text-gray-700">Next.js + Node + PostgreSQL</p>
</div>
<div className="bg-white/90 backdrop-blur-sm rounded-xl p-6 text-center transform hover:scale-105 transition-transform shadow-xl">
<h3 className="text-lg font-semibold text-purple-700 mb-2 flex items-center justify-center">
<span className={`mr-2 text-2xl ${apiStatus === 'connected' ? 'π’' : apiStatus === 'error' ? 'π΄' : 'π‘'}`}>
</span>
API Status
</h3>
<p className="text-gray-700">
{apiStatus === 'connected' ? 'Connected' : apiStatus === 'error' ? 'Disconnected' : 'Checking...'}
</p>
</div>
</div>
{/* Main Content */}
<main className="bg-white rounded-2xl shadow-2xl p-8 mb-8">
{/* Error Display */}
{error && (
<div className="bg-red-50 text-red-600 p-4 rounded-lg mb-4 flex justify-between items-center">
<span>{error}</span>
<button onClick={() => setError('')} className="text-red-800 hover:text-red-900">β</button>
</div>
)}
{/* Create Post Section */}
<section className="mb-10 pb-8 border-b-2 border-gray-100">
<h2 className="text-3xl font-bold text-gray-800 mb-6">Create New Post</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<input
type="text"
placeholder="Post title..."
value={newPost.title}
onChange={(e) => setNewPost({ ...newPost, title: e.target.value })}
className="w-full px-4 py-3 border-2 border-gray-200 rounded-lg focus:border-purple-500 focus:outline-none transition-colors"
required