-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup.sh
More file actions
603 lines (508 loc) · 17.4 KB
/
Copy pathsetup.sh
File metadata and controls
603 lines (508 loc) · 17.4 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
#!/usr/bin/env bash
# ==================== MyBridge - Installation Script ====================
# Usage:
# sudo bash setup.sh # Fresh install
# sudo bash setup.sh --update # Update existing installation
#
# This script deploys the local files (from git clone, zip, etc.)
# into /opt/mybridge. No git operations are performed.
#
# Domain: game.bridge85.fr
# Stack: Node.js + Express + SQLite + NGINX + Let's Encrypt
# ========================================================================
set -euo pipefail
# ==================== CONFIGURATION ====================
DOMAIN="game.bridge85.fr"
APP_DIR="/opt/mybridge"
APP_USER="mybridge"
APP_GROUP="mybridge"
NODE_VERSION="20"
SERVICE_NAME="mybridge"
CERTBOT_EMAIL="" # Will be asked during install
# Source directory: where this script is located
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_ok() { echo -e "${GREEN}[OK]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
# ==================== PRE-CHECKS ====================
check_root() {
if [[ $EUID -ne 0 ]]; then
log_error "Ce script doit être exécuté en tant que root (sudo)."
exit 1
fi
}
check_os() {
if [[ ! -f /etc/os-release ]]; then
log_error "OS non supporté. Debian/Ubuntu requis."
exit 1
fi
. /etc/os-release
if [[ "$ID" != "debian" && "$ID" != "ubuntu" ]]; then
log_error "OS non supporté: $ID. Debian/Ubuntu requis."
exit 1
fi
log_ok "OS détecté: $PRETTY_NAME"
}
# ==================== PERMISSIONS ====================
fix_permissions() {
# App root must be traversable by NGINX (www-data)
chmod 755 "$APP_DIR"
# Static directories: readable by NGINX
for dir in css js docs; do
if [[ -d "$APP_DIR/$dir" ]]; then
find "$APP_DIR/$dir" -type d -exec chmod 755 {} \;
find "$APP_DIR/$dir" -type f -exec chmod 644 {} \;
fi
done
# HTML and public files at root
chmod 644 "$APP_DIR"/*.html 2>/dev/null || true
chmod 644 "$APP_DIR"/version.json 2>/dev/null || true
# Server directory: only mybridge user (includes gameManager.js, dds.js, ai.js requires)
chmod 750 "$APP_DIR/server" 2>/dev/null || true
find "$APP_DIR/server" -maxdepth 1 -name '*.js' -exec chmod 640 {} \; 2>/dev/null || true
}
# ==================== UPDATE MODE ====================
do_update() {
log_info "=========================================="
log_info " MyBridge - Mise à jour"
log_info "=========================================="
if [[ ! -d "$APP_DIR" ]]; then
log_error "Installation non trouvée dans $APP_DIR. Lancez le script sans --update."
exit 1
fi
log_info "Source: $SOURCE_DIR"
log_info "Arrêt du service..."
systemctl stop "$SERVICE_NAME" || true
log_info "Sauvegarde de la base de données..."
BACKUP_DIR="/opt/mybridge-backups"
mkdir -p "$BACKUP_DIR"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
if [[ -f "$APP_DIR/server/data/mybridge.db" ]]; then
cp "$APP_DIR/server/data/mybridge.db" "$BACKUP_DIR/mybridge_${TIMESTAMP}.db"
log_ok "Backup DB: $BACKUP_DIR/mybridge_${TIMESTAMP}.db"
fi
if [[ -f "$APP_DIR/server/data/sessions.db" ]]; then
cp "$APP_DIR/server/data/sessions.db" "$BACKUP_DIR/sessions_${TIMESTAMP}.db"
log_ok "Backup sessions: $BACKUP_DIR/sessions_${TIMESTAMP}.db"
fi
log_info "Copie des fichiers depuis $SOURCE_DIR..."
rsync -a --delete \
--exclude 'server/data/' \
--exclude 'server/.env' \
--exclude 'server/node_modules/' \
--exclude '.git/' \
"$SOURCE_DIR/" "$APP_DIR/"
log_info "Mise à jour des permissions..."
chown -R "$APP_USER:$APP_GROUP" "$APP_DIR"
fix_permissions
log_info "Mise à jour des dépendances Node.js..."
cd "$APP_DIR/server"
sudo -u "$APP_USER" npm install --omit=dev
log_info "Mise à jour de la configuration NGINX..."
# Remove any old domain configs to prevent conflicts
for f in /etc/nginx/sites-enabled/*; do
if [[ "$(basename "$f")" != "${DOMAIN}" && -f "$f" ]]; then
rm -f "$f"
log_info "Suppression ancien site NGINX: $(basename "$f")"
fi
done
cp "$APP_DIR/nginx/bridge.conf" "/etc/nginx/sites-available/${DOMAIN}"
ln -sf "/etc/nginx/sites-available/${DOMAIN}" "/etc/nginx/sites-enabled/${DOMAIN}"
if [[ "$APP_DIR" != "/opt/mybridge" ]]; then
sed -i "s|root /opt/mybridge;|root ${APP_DIR};|" "/etc/nginx/sites-available/${DOMAIN}"
fi
# Ensure SSL certificate exists (self-signed fallback)
_ensure_ssl_cert
log_info "Rechargement NGINX..."
nginx -t && systemctl reload nginx
log_info "Redémarrage du service..."
systemctl start "$SERVICE_NAME"
# Cleanup old backups (keep last 10)
ls -t "$BACKUP_DIR"/mybridge_*.db 2>/dev/null | tail -n +11 | xargs -r rm --
# Show version
if [[ -f "$APP_DIR/version.json" ]]; then
APP_VERSION=$(grep -oP '"version":\s*"\K[^"]+' "$APP_DIR/version.json")
log_ok "Version: $APP_VERSION"
fi
log_ok "=========================================="
log_ok " Mise à jour terminée avec succès !"
log_ok "=========================================="
exit 0
}
# ==================== FRESH INSTALL ====================
install_system_deps() {
log_info "Mise à jour des paquets système..."
apt-get update -qq
log_info "Installation des dépendances système..."
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq \
curl \
wget \
build-essential \
python3 \
nginx \
certbot \
python3-certbot-nginx \
sqlite3 \
openssl \
ufw \
fail2ban \
rsync \
logrotate \
> /dev/null
log_ok "Dépendances système installées."
}
install_nodejs() {
if command -v node &> /dev/null; then
CURRENT_NODE=$(node --version | sed 's/v//' | cut -d. -f1)
if [[ "$CURRENT_NODE" -ge "$NODE_VERSION" ]]; then
log_ok "Node.js $(node --version) déjà installé."
return
fi
fi
log_info "Installation de Node.js ${NODE_VERSION}.x..."
curl -fsSL "https://deb.nodesource.com/setup_${NODE_VERSION}.x" | bash - > /dev/null 2>&1
apt-get install -y -qq nodejs > /dev/null
log_ok "Node.js $(node --version) installé."
}
create_app_user() {
if id "$APP_USER" &>/dev/null; then
log_ok "Utilisateur $APP_USER existe déjà."
return
fi
log_info "Création de l'utilisateur système $APP_USER..."
useradd --system --shell /usr/sbin/nologin --home-dir "$APP_DIR" --create-home "$APP_USER"
log_ok "Utilisateur $APP_USER créé."
}
deploy_application() {
log_info "Déploiement des fichiers depuis $SOURCE_DIR..."
mkdir -p "$APP_DIR"
rsync -a --delete \
--exclude 'server/data/' \
--exclude 'server/.env' \
--exclude 'server/node_modules/' \
--exclude '.git/' \
"$SOURCE_DIR/" "$APP_DIR/"
chown -R "$APP_USER:$APP_GROUP" "$APP_DIR"
# Ensure NGINX (www-data) can read static files
fix_permissions
log_ok "Code source en place."
}
install_node_deps() {
log_info "Installation des dépendances Node.js..."
cd "$APP_DIR/server"
sudo -u "$APP_USER" npm install --omit=dev
log_ok "Dépendances Node.js installées."
}
create_data_dir() {
log_info "Création du répertoire de données..."
mkdir -p "$APP_DIR/server/data"
chown -R "$APP_USER:$APP_GROUP" "$APP_DIR/server/data"
chmod 750 "$APP_DIR/server/data"
log_ok "Répertoire de données prêt."
}
generate_session_secret() {
SECRET_FILE="$APP_DIR/server/.env"
if [[ -f "$SECRET_FILE" ]]; then
log_ok "Fichier .env existe déjà."
return
fi
log_info "Génération du secret de session..."
SESSION_SECRET=$(openssl rand -hex 32)
cat > "$SECRET_FILE" << EOF
SESSION_SECRET=${SESSION_SECRET}
PORT=3000
TRUST_PROXY=true
DB_PATH=${APP_DIR}/server/data/mybridge.db
NODE_ENV=production
EOF
chown "$APP_USER:$APP_GROUP" "$SECRET_FILE"
chmod 600 "$SECRET_FILE"
log_ok "Secret de session généré."
}
# ==================== SYSTEMD SERVICE ====================
setup_systemd() {
log_info "Configuration du service systemd..."
cat > "/etc/systemd/system/${SERVICE_NAME}.service" << EOF
[Unit]
Description=MyBridge - Jeu de Bridge en ligne
Documentation=https://github.com/cve-solutions/MyBridge
After=network.target
[Service]
Type=simple
User=${APP_USER}
Group=${APP_GROUP}
WorkingDirectory=${APP_DIR}/server
EnvironmentFile=${APP_DIR}/server/.env
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=${SERVICE_NAME}
# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=${APP_DIR}/server/data
PrivateTmp=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictSUIDSGID=true
RestrictNamespaces=true
LockPersonality=true
MemoryDenyWriteExecute=false
RestrictRealtime=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable "$SERVICE_NAME"
log_ok "Service systemd configuré."
}
# ==================== SSL HELPER ====================
# Ensures an SSL certificate exists for $DOMAIN.
# Tries Let's Encrypt first, falls back to self-signed.
_ensure_ssl_cert() {
local CERT_DIR="/etc/letsencrypt/live/${DOMAIN}"
# Already have a cert? Done.
if [[ -f "${CERT_DIR}/fullchain.pem" && -f "${CERT_DIR}/privkey.pem" ]]; then
log_ok "Certificat SSL existe: ${CERT_DIR}"
return 0
fi
# Try Let's Encrypt (non-interactive, may fail if DNS not ready)
if command -v certbot &>/dev/null; then
log_info "Tentative Let's Encrypt pour ${DOMAIN}..."
local EMAIL_OPT=""
if [[ -n "${CERTBOT_EMAIL:-}" ]]; then
EMAIL_OPT="--email ${CERTBOT_EMAIL}"
else
EMAIL_OPT="--register-unsafely-without-email"
fi
if certbot certonly \
--webroot \
--webroot-path /var/www/certbot \
--domain "$DOMAIN" \
$EMAIL_OPT \
--agree-tos \
--non-interactive 2>/dev/null; then
log_ok "Certificat Let's Encrypt obtenu."
return 0
fi
log_warn "Let's Encrypt a échoué. Création d'un certificat auto-signé."
fi
# Fallback: self-signed certificate
log_info "Génération du certificat auto-signé pour ${DOMAIN}..."
mkdir -p "${CERT_DIR}"
openssl req -x509 -nodes -days 365 \
-newkey rsa:2048 \
-keyout "${CERT_DIR}/privkey.pem" \
-out "${CERT_DIR}/fullchain.pem" \
-subj "/CN=${DOMAIN}" \
2>/dev/null
# chain.pem = same as fullchain for self-signed
cp "${CERT_DIR}/fullchain.pem" "${CERT_DIR}/chain.pem"
log_ok "Certificat auto-signé créé (valide 365 jours)."
log_warn "Pensez à configurer Let's Encrypt plus tard pour un vrai certificat."
}
# ==================== NGINX ====================
setup_nginx() {
log_info "Configuration de NGINX..."
# Generate DH params if not exists
DH_DIR="/etc/nginx/ssl"
mkdir -p "$DH_DIR"
if [[ ! -f "$DH_DIR/dhparam.pem" ]]; then
log_info "Génération des paramètres DH (peut prendre quelques minutes)..."
openssl dhparam -out "$DH_DIR/dhparam.pem" 2048 2>/dev/null
log_ok "Paramètres DH générés."
fi
# Create certbot webroot
mkdir -p /var/www/certbot
# Remove default and any old domain nginx sites
rm -f /etc/nginx/sites-enabled/default
for f in /etc/nginx/sites-enabled/*; do
if [[ "$(basename "$f")" != "${DOMAIN}" && -f "$f" ]]; then
rm -f "$f"
log_info "Suppression ancien site: $(basename "$f")"
fi
done
# First, create a temporary HTTP-only config for certbot
cat > "/etc/nginx/sites-available/${DOMAIN}" << 'TMPEOF'
server {
listen 80;
listen [::]:80;
server_name game.bridge85.fr;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
allow all;
}
location / {
return 200 'MyBridge - En cours d installation...';
add_header Content-Type text/plain;
}
}
TMPEOF
ln -sf "/etc/nginx/sites-available/${DOMAIN}" "/etc/nginx/sites-enabled/${DOMAIN}"
nginx -t
systemctl restart nginx
log_ok "NGINX configuré (HTTP temporaire)."
}
# ==================== SSL ====================
setup_ssl() {
log_info "Configuration du certificat SSL..."
# Ask for email (optional, used for Let's Encrypt)
if [[ -z "$CERTBOT_EMAIL" ]]; then
read -rp "Adresse email pour Let's Encrypt (optionnel, Entrée pour ignorer): " CERTBOT_EMAIL
fi
# Ensure cert exists (Let's Encrypt or self-signed fallback)
_ensure_ssl_cert
# Remove any old domain configs to avoid conflicts
for f in /etc/nginx/sites-enabled/*; do
if [[ "$(basename "$f")" != "${DOMAIN}" && -f "$f" ]]; then
rm -f "$f"
fi
done
# Install the full NGINX config with SSL
log_info "Installation de la configuration NGINX complète..."
cp "$APP_DIR/nginx/bridge.conf" "/etc/nginx/sites-available/${DOMAIN}"
ln -sf "/etc/nginx/sites-available/${DOMAIN}" "/etc/nginx/sites-enabled/${DOMAIN}"
if [[ "$APP_DIR" != "/opt/mybridge" ]]; then
sed -i "s|root /opt/mybridge;|root ${APP_DIR};|" "/etc/nginx/sites-available/${DOMAIN}"
fi
nginx -t
systemctl reload nginx
log_ok "NGINX configuré avec SSL."
# Setup auto-renewal (only useful with Let's Encrypt, harmless otherwise)
cat > /etc/cron.d/certbot-mybridge << EOF
# Renouvellement automatique du certificat Let's Encrypt
0 3 * * * root certbot renew --quiet --post-hook "systemctl reload nginx"
EOF
log_ok "Renouvellement automatique configuré."
}
# ==================== FIREWALL ====================
setup_firewall() {
log_info "Configuration du pare-feu UFW..."
ufw --force reset > /dev/null 2>&1
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable
log_ok "Pare-feu configuré (SSH, HTTP, HTTPS)."
}
# ==================== FAIL2BAN ====================
setup_fail2ban() {
log_info "Configuration de Fail2Ban..."
cat > /etc/fail2ban/jail.d/mybridge.conf << 'EOF'
[nginx-http-auth]
enabled = true
[nginx-limit-req]
enabled = true
filter = nginx-limit-req
action = iptables-multiport[name=ReqLimit, port="http,https"]
logpath = /var/log/nginx/bridge.error.log
findtime = 600
bantime = 3600
maxretry = 10
[nginx-botsearch]
enabled = true
logpath = /var/log/nginx/bridge.access.log
maxretry = 5
[sshd]
enabled = true
maxretry = 5
bantime = 3600
EOF
systemctl restart fail2ban
log_ok "Fail2Ban configuré."
}
# ==================== LOGROTATE ====================
setup_logrotate() {
log_info "Configuration de la rotation des logs..."
cat > /etc/logrotate.d/mybridge << EOF
/var/log/nginx/bridge.*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
[ -s /run/nginx.pid ] && kill -USR1 \$(cat /run/nginx.pid)
endscript
}
EOF
log_ok "Rotation des logs configurée."
}
# ==================== MAIN ====================
main() {
echo ""
echo -e "${BLUE}=========================================="
echo " ♠ MyBridge - Installation Complète ♥"
echo -e "==========================================${NC}"
echo ""
check_root
check_os
# Check for --update flag
if [[ "${1:-}" == "--update" ]]; then
do_update
fi
log_info "Début de l'installation..."
echo ""
# Step 1: System
install_system_deps
install_nodejs
create_app_user
# Step 2: Application
deploy_application
install_node_deps
create_data_dir
generate_session_secret
# Step 3: Service
setup_systemd
# Step 4: Web server
setup_nginx
setup_ssl
# Step 5: Security
setup_firewall
setup_fail2ban
setup_logrotate
# Step 6: Start
log_info "Démarrage du service MyBridge..."
systemctl start "$SERVICE_NAME"
sleep 2
if systemctl is-active --quiet "$SERVICE_NAME"; then
log_ok "Service MyBridge démarré avec succès."
else
log_error "Le service a échoué au démarrage. Vérifiez: journalctl -u $SERVICE_NAME"
fi
echo ""
log_ok "=========================================="
log_ok " Installation terminée avec succès !"
log_ok "=========================================="
echo ""
if [[ -f "$APP_DIR/version.json" ]]; then
APP_VERSION=$(grep -oP '"version":\s*"\K[^"]+' "$APP_DIR/version.json")
echo -e " ${GREEN}Version:${NC} v${APP_VERSION}"
fi
echo -e " ${GREEN}URL:${NC} https://${DOMAIN}"
echo -e " ${GREEN}Service:${NC} systemctl status ${SERVICE_NAME}"
echo -e " ${GREEN}Logs:${NC} journalctl -u ${SERVICE_NAME} -f"
echo -e " ${GREEN}NGINX:${NC} /etc/nginx/sites-available/${DOMAIN}"
echo -e " ${GREEN}Data:${NC} ${APP_DIR}/server/data/"
echo -e " ${GREEN}Backup:${NC} /opt/mybridge-backups/"
echo ""
echo -e " ${YELLOW}Mise à jour:${NC} sudo bash ${APP_DIR}/setup.sh --update"
echo ""
}
main "$@"