-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinstall.sh
More file actions
executable file
·1524 lines (1256 loc) · 41.5 KB
/
install.sh
File metadata and controls
executable file
·1524 lines (1256 loc) · 41.5 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
# 🚀 SayIt 校园社交平台自动化安装和部署脚本
# 支持 Ubuntu/Debian 系统的一键安装、配置和部署
# 合并了安装和部署功能,提供交互式配置
set -e # 遇到错误时退出
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
WHITE='\033[1;37m'
NC='\033[0m' # No Color
# 默认配置
APP_NAME="sayit"
APP_USER="$(whoami)"
APP_DIR="$HOME/$APP_NAME"
REPO_URL="https://github.com/Lecheeel/sayit.git"
BRANCH="main"
DOMAIN=""
EMAIL=""
NODE_VERSION="18"
INSTALL_NGINX="false"
INSTALL_SSL="false" # 默认跳过SSL
AUTO_START="true"
ACTION="install"
FORCE_DEPLOY="false"
BACKUP_BEFORE_DEPLOY="true"
AUTO_MIGRATION="true"
RESTART_SERVICES="true"
APP_PORT="3000"
# 日志函数(兼容部署功能)
log_info() {
echo -e "${BLUE}[INFO]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}
log_success() {
echo -e "${GREEN}[SUCCESS]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}
log_warning() {
echo -e "${YELLOW}[WARNING]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $(date '+%Y-%m-%d %H:%M:%S') - $1"
}
log_header() {
echo -e "${PURPLE}================================${NC}"
echo -e "${WHITE}$1${NC}"
echo -e "${PURPLE}================================${NC}"
}
# 为了兼容性保留原有的函数名
print_info() { log_info "$1"; }
print_success() { log_success "$1"; }
print_warning() { log_warning "$1"; }
print_error() { log_error "$1"; }
print_header() { log_header "$1"; }
# 检查系统类型
check_system() {
print_header "检查系统环境"
if [[ "$EUID" -eq 0 ]]; then
print_error "请不要使用 root 用户运行此脚本"
exit 1
fi
if ! command -v apt &> /dev/null; then
print_error "此脚本仅支持 Ubuntu/Debian 系统"
exit 1
fi
# 检查系统版本
OS_VERSION=$(lsb_release -d | cut -f2)
print_info "操作系统: $OS_VERSION"
# 检查架构
ARCH=$(uname -m)
print_info "系统架构: $ARCH"
print_success "系统检查完成"
}
# 解析命令行参数
parse_arguments() {
while [[ $# -gt 0 ]]; do
case $1 in
-d|--domain)
DOMAIN="$2"
shift 2
;;
-e|--email)
EMAIL="$2"
shift 2
;;
--repo)
REPO_URL="$2"
shift 2
;;
--branch)
BRANCH="$2"
shift 2
;;
--user)
APP_USER="$2"
# 如果指定的用户是当前用户,使用$HOME,否则使用/home/$USER
if [[ "$APP_USER" == "$(whoami)" ]]; then
APP_DIR="$HOME/$APP_NAME"
else
APP_DIR="/home/$APP_USER/$APP_NAME"
fi
shift 2
;;
--dir)
APP_DIR="$2"
shift 2
;;
--port)
APP_PORT="$2"
shift 2
;;
--no-nginx)
INSTALL_NGINX="false"
shift
;;
--nginx)
INSTALL_NGINX="true"
shift
;;
--no-ssl)
INSTALL_SSL="false"
shift
;;
--no-autostart)
AUTO_START="false"
shift
;;
--no-backup)
BACKUP_BEFORE_DEPLOY="false"
shift
;;
--no-migration)
AUTO_MIGRATION="false"
shift
;;
--no-restart)
RESTART_SERVICES="false"
shift
;;
--force)
FORCE_DEPLOY="true"
shift
;;
-h|--help)
show_help
exit 0
;;
install|deploy|rollback|status|logs|update)
ACTION="$1"
shift
if [[ "$ACTION" == "rollback" && -n "$1" && ! "$1" =~ ^-- ]]; then
ROLLBACK_VERSION="$1"
shift
fi
;;
*)
print_error "未知参数: $1"
show_help
exit 1
;;
esac
done
ACTION=${ACTION:-install}
}
# 显示帮助信息
show_help() {
echo -e "${WHITE}SayIt 校园社交平台安装和部署脚本${NC}"
echo ""
echo "用法: $0 [动作] [选项]"
echo ""
echo "动作:"
echo " install 全新安装应用 (默认)"
echo " deploy 部署/更新应用"
echo " rollback [version] 回滚到指定版本"
echo " status 查看应用状态"
echo " logs 查看应用日志"
echo " update 快速更新代码"
echo ""
echo "安装选项:"
echo " -d, --domain DOMAIN 设置域名"
echo " -e, --email EMAIL SSL证书邮箱"
echo " --repo URL 指定 Git 仓库地址"
echo " --branch BRANCH 指定分支 (默认: main)"
echo " --user USER 指定应用用户 (默认: 当前用户)"
echo " --dir PATH 指定应用目录"
echo " --nginx 安装 Nginx (默认不安装)"
echo " --no-nginx 跳过 Nginx 安装"
echo " --port PORT 设置应用端口 (默认: 3000)"
echo " --no-ssl 跳过 SSL 证书配置 (默认)"
echo " --no-autostart 不自动启动服务"
echo ""
echo "部署选项:"
echo " --no-backup 部署前不备份"
echo " --no-migration 跳过数据库迁移"
echo " --no-restart 不重启服务"
echo " --force 强制部署 (忽略警告)"
echo ""
echo "通用选项:"
echo " -h, --help 显示此帮助信息"
echo ""
echo "示例:"
echo " $0 # 交互式安装"
echo " $0 install -d example.com # 安装并设置域名"
echo " $0 deploy # 部署最新版本"
echo " $0 deploy --branch develop # 部署指定分支"
echo " $0 rollback v1.2.0 # 回滚到指定版本"
echo " $0 status # 查看状态"
echo " $0 --no-nginx --no-ssl # 仅安装应用"
}
# 交互式配置
interactive_config() {
if [[ "$ACTION" != "install" ]]; then
return # 非安装模式跳过交互配置
fi
print_header "🎯 交互式配置向导"
echo -e "${CYAN}欢迎使用 SayIt 校园社交平台安装脚本!${NC}"
echo -e "${YELLOW}我们将引导您完成安装配置${NC}"
echo ""
# 基础配置
if [[ -z "$DOMAIN" ]]; then
echo -e "${WHITE}1. 域名配置${NC}"
echo -n "请输入域名 (留空表示仅本地访问): "
read DOMAIN
echo ""
fi
# SSL配置
if [[ -n "$DOMAIN" ]]; then
echo -e "${WHITE}2. SSL证书配置${NC}"
echo -n "是否配置 SSL 证书? (y/N,默认跳过): "
read ssl_choice
if [[ "$ssl_choice" =~ ^[Yy]$ ]]; then
INSTALL_SSL="true"
if [[ -z "$EMAIL" ]]; then
echo -n "请输入邮箱地址 (用于SSL证书): "
read EMAIL
fi
fi
echo ""
fi
# Web服务配置
echo -e "${WHITE}3. Web服务配置${NC}"
echo -n "是否安装 Nginx? (y/N,默认不安装): "
read nginx_choice
if [[ "$nginx_choice" =~ ^[Yy]$ ]]; then
INSTALL_NGINX="true"
fi
echo ""
echo -n "设置应用端口 (留空使用默认: $APP_PORT): "
read custom_port
if [[ -n "$custom_port" ]]; then
if [[ "$custom_port" =~ ^[0-9]+$ ]] && [[ "$custom_port" -ge 1 && "$custom_port" -le 65535 ]]; then
APP_PORT="$custom_port"
else
print_warning "端口无效,使用默认端口 $APP_PORT"
fi
fi
echo ""
# 高级选项
echo -e "${WHITE}4. 高级选项${NC}"
echo -n "自定义应用用户名? (留空使用默认: $APP_USER): "
read custom_user
if [[ -n "$custom_user" ]]; then
APP_USER="$custom_user"
# 如果指定的用户是当前用户,使用$HOME,否则使用/home/$USER
if [[ "$APP_USER" == "$(whoami)" ]]; then
APP_DIR="$HOME/$APP_NAME"
else
APP_DIR="/home/$APP_USER/$APP_NAME"
fi
fi
echo -n "自定义安装目录? (留空使用默认: $APP_DIR): "
read custom_dir
if [[ -n "$custom_dir" ]]; then
APP_DIR="$custom_dir"
fi
echo ""
# 生成JWT密钥
print_info "正在生成安全密钥..."
JWT_SECRET=$(node -e "console.log(require('crypto').randomBytes(64).toString('hex'))" 2>/dev/null || openssl rand -hex 64)
# 确认配置
print_header "📋 安装配置确认"
print_info " 动作模式: $ACTION"
print_info " 应用名称: $APP_NAME"
print_info " 应用用户: $APP_USER"
print_info " 安装目录: $APP_DIR"
print_info " 域名: ${DOMAIN:-"未配置 (本地访问)"}"
print_info " 应用端口: $APP_PORT"
print_info " 安装Nginx: $INSTALL_NGINX"
print_info " 配置SSL: $INSTALL_SSL"
print_info " 自动启动: $AUTO_START"
print_info " JWT密钥: 已生成 (64字符)"
echo ""
echo -e "${YELLOW}⚠️ 注意事项:${NC}"
echo -e " • 安装过程需要 sudo 权限"
echo -e " • 建议在全新的系统上安装"
echo -e " • 安装时间约 10-20 分钟"
echo ""
echo -n "确认开始安装? (y/N): "
read confirmation
if [[ ! "$confirmation" =~ ^[Yy]$ ]]; then
print_info "安装已取消"
exit 0
fi
}
# 更新系统
update_system() {
print_header "更新系统包"
print_info "更新包列表..."
sudo apt update
print_info "升级系统包..."
sudo apt upgrade -y
print_info "安装基础工具..."
sudo apt install -y curl wget git unzip software-properties-common gnupg2
print_success "系统更新完成"
}
# 安装 Node.js
install_nodejs() {
print_header "安装 Node.js"
if command -v node &> /dev/null; then
NODE_CURRENT=$(node --version | cut -d'v' -f2 | cut -d'.' -f1)
if [[ "$NODE_CURRENT" -ge "$NODE_VERSION" ]]; then
print_success "Node.js 已安装 (版本: $(node --version))"
return
fi
fi
print_info "添加 NodeSource 仓库..."
curl -fsSL https://deb.nodesource.com/setup_${NODE_VERSION}.x | sudo -E bash -
print_info "安装 Node.js ${NODE_VERSION}..."
sudo apt install -y nodejs
# 验证安装
print_info "Node.js 版本: $(node --version)"
print_info "npm 版本: $(npm --version)"
print_success "Node.js 安装完成"
}
# 启用 Corepack 和安装 pnpm
install_pnpm() {
print_header "安装 pnpm"
# 检查是否已安装 pnpm
if command -v pnpm &> /dev/null; then
print_success "pnpm 已安装 (版本: $(pnpm --version))"
return
fi
print_info "启用 Corepack..."
sudo corepack enable
print_info "安装最新版本的 pnpm..."
corepack prepare pnpm@latest --activate
# 验证安装
print_info "pnpm 版本: $(pnpm --version)"
print_success "pnpm 安装完成"
}
# 安装 PM2
install_pm2() {
print_header "安装 PM2"
if command -v pm2 &> /dev/null; then
print_success "PM2 已安装 (版本: $(pm2 --version))"
return
fi
print_info "使用 pnpm 全局安装 PM2..."
pnpm add -g pm2
print_success "PM2 安装完成"
}
# 检查应用用户 (不创建新用户,使用当前用户)
check_app_user() {
print_header "检查应用用户"
print_info "当前用户: $APP_USER"
print_info "用户ID: $(id -u)"
print_info "用户组: $(id -gn)"
# 如果需要www-data权限且当前用户不在www-data组中,提示添加
if [[ "$INSTALL_NGINX" == "true" ]] && ! id -nG | grep -q "www-data"; then
print_warning "建议将当前用户添加到www-data组以获得适当的权限:"
print_info "sudo usermod -aG www-data $APP_USER"
echo -n "是否立即添加? (y/N): "
read add_to_www_data
if [[ "$add_to_www_data" =~ ^[Yy]$ ]]; then
sudo usermod -aG www-data $APP_USER
print_success "已添加到www-data组"
fi
fi
print_success "用户检查完成"
}
# 部署应用代码
deploy_application() {
print_header "部署应用代码"
# 创建应用目录
print_info "创建应用目录..."
mkdir -p $APP_DIR
# 检查是否在同一目录
local current_dir=$(pwd)
local target_dir=$(realpath $APP_DIR)
if [[ "$current_dir" == "$target_dir" ]]; then
print_info "当前目录即为目标目录,跳过代码复制..."
else
# 复制当前目录的代码到目标目录
print_info "复制应用代码..."
cp -r $(pwd)/* $APP_DIR/
fi
# 设置权限
chmod -R 755 $APP_DIR
print_success "应用代码部署完成"
}
# 安装应用依赖
install_dependencies() {
print_header "安装应用依赖"
cd $APP_DIR
print_info "检查并安装缺失的 ESLint 插件..."
# 检查是否需要安装 @next/eslint-plugin-next
if ! pnpm list @next/eslint-plugin-next &>/dev/null; then
print_info "安装 @next/eslint-plugin-next..."
pnpm add @next/eslint-plugin-next
fi
print_info "安装 pnpm 依赖..."
# 检查是否存在 pnpm-lock.yaml,如果存在则使用 --frozen-lockfile,否则正常安装
if [[ -f "pnpm-lock.yaml" ]]; then
print_info "使用 pnpm frozen-lockfile 安装所有依赖..."
if ! pnpm install --frozen-lockfile; then
print_warning "pnpm-lock.yaml 与 package.json 不同步,重新安装..."
rm -f pnpm-lock.yaml
pnpm install
fi
else
print_info "未找到 pnpm-lock.yaml,使用 pnpm install..."
pnpm install
fi
# 跳过构建,留到数据库初始化后进行
print_success "应用依赖安装完成"
}
# 配置环境变量
setup_environment() {
print_header "配置环境变量"
# 如果没有JWT_SECRET,则生成一个
if [[ -z "$JWT_SECRET" ]]; then
print_info "生成JWT密钥..."
JWT_SECRET=$(node -e "console.log(require('crypto').randomBytes(64).toString('hex'))" 2>/dev/null || openssl rand -hex 64)
fi
# 确定应用URL
local app_url=""
if [[ -n "$DOMAIN" ]]; then
if [[ "$INSTALL_SSL" == "true" ]]; then
app_url="https://$DOMAIN"
else
app_url="http://$DOMAIN"
fi
fi
# 创建生产环境配置
cat > $APP_DIR/.env.local << EOF
# SayIt 生产环境配置
# 由自动安装脚本生成于: $(date)
NODE_ENV=production
# JWT 认证密钥 (请妥善保管)
JWT_SECRET=$JWT_SECRET
# 数据库配置
DATABASE_URL="file:./prisma/production.db"
# 应用配置
${app_url:+NEXT_PUBLIC_APP_URL=$app_url}
# 文件上传配置
UPLOAD_PATH=$APP_DIR/public/uploads
MAX_FILE_SIZE=10485760
# 应用端口
PORT=$APP_PORT
# 日志级别
LOG_LEVEL=info
# hCaptcha 人机验证(可选,请替换为您的密钥)
# NEXT_PUBLIC_HCAPTCHA_SITE_KEY=your-hcaptcha-site-key
# HCAPTCHA_SECRET_KEY=your-hcaptcha-secret-key
# 邮件配置(可选,用于通知功能)
# SMTP_HOST=smtp.gmail.com
# SMTP_PORT=587
# SMTP_USER=your-email@gmail.com
# SMTP_PASS=your-app-password
# MAIL_FROM=noreply@yourdomain.com
EOF
# 设置文件权限
chmod 600 $APP_DIR/.env.local
print_success "环境变量配置完成"
print_info "JWT密钥已生成并保存到 .env.local 文件"
}
# 初始化数据库
setup_database() {
print_header "初始化数据库"
cd $APP_DIR
print_info "检查数据库文件..."
local db_file="$APP_DIR/prisma/production.db"
local db_dir=$(dirname "$db_file")
# 确保数据库目录存在
mkdir -p "$db_dir"
print_info "初始化数据库架构..."
pnpm run db:push
print_info "生成 Prisma Client..."
pnpm run db:generate
print_info "创建初始数据和管理员账户..."
# 指定管理员凭据输出文件,供初始化脚本写入
local admin_creds_file="$APP_DIR/admin_credentials.txt"
# 先删除旧文件,避免误读
rm -f "$admin_creds_file" 2>/dev/null || true
ADMIN_PASSWORD_FILE="$admin_creds_file" pnpm run db:init
# 如果凭据文件已生成,设置安全权限
if [[ -f "$admin_creds_file" ]]; then
chmod 600 "$admin_creds_file"
print_success "管理员凭据已保存: $admin_creds_file"
fi
# 设置数据库文件权限
if [[ -f "$db_file" ]]; then
chmod 664 "$db_file"
print_success "数据库权限设置完成"
fi
print_success "数据库初始化完成"
}
# 构建应用
build_application() {
print_header "构建应用"
cd $APP_DIR
print_info "清理构建缓存..."
rm -rf .next 2>/dev/null || true
print_info "构建应用..."
if ! pnpm run build; then
print_error "应用构建失败"
exit 1
fi
# 构建完成后移除开发依赖以节省空间(可选)
print_info "移除开发依赖以节省空间..."
pnpm prune --prod
print_success "应用构建完成"
}
# 安装 Nginx
install_nginx() {
if [[ "$INSTALL_NGINX" != "true" ]]; then
print_info "跳过 Nginx 安装"
return
fi
print_header "安装 Nginx"
if command -v nginx &> /dev/null; then
print_success "Nginx 已安装"
else
print_info "安装 Nginx..."
sudo apt install -y nginx
fi
# 启动并启用 Nginx
sudo systemctl start nginx
sudo systemctl enable nginx
print_success "Nginx 安装完成"
}
# 配置 Nginx
configure_nginx() {
if [[ "$INSTALL_NGINX" != "true" ]]; then
return
fi
print_header "配置 Nginx"
# 删除默认配置
sudo rm -f /etc/nginx/sites-enabled/default
# 创建应用配置
NGINX_CONFIG="/etc/nginx/sites-available/$APP_NAME"
if [[ -n "$DOMAIN" ]]; then
# 有域名的配置
sudo tee $NGINX_CONFIG > /dev/null << EOF
# HTTP 重定向到 HTTPS
server {
listen 80;
server_name $DOMAIN www.$DOMAIN;
return 301 https://\$server_name\$request_uri;
}
# HTTPS 主配置
server {
listen 443 ssl http2;
server_name $DOMAIN www.$DOMAIN;
# SSL 配置 (将在安装证书后自动更新)
ssl_certificate /etc/nginx/ssl/cert.crt;
ssl_certificate_key /etc/nginx/ssl/cert.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
# 文件上传大小限制
client_max_body_size 10M;
# Gzip 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|webp)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# 应用代理
location / {
proxy_pass http://localhost:$APP_PORT;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection 'upgrade';
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_cache_bypass \$http_upgrade;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
EOF
else
# 无域名的配置(仅HTTP)
sudo tee $NGINX_CONFIG > /dev/null << EOF
server {
listen 80 default_server;
listen [::]:80 default_server;
# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header X-XSS-Protection "1; mode=block" always;
# 文件上传大小限制
client_max_body_size 10M;
# Gzip 压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|webp)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# 应用代理
location / {
proxy_pass http://localhost:$APP_PORT;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection 'upgrade';
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_cache_bypass \$http_upgrade;
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
EOF
fi
# 启用站点
sudo ln -sf $NGINX_CONFIG /etc/nginx/sites-enabled/$APP_NAME
# 测试配置
if sudo nginx -t; then
sudo systemctl reload nginx
print_success "Nginx 配置完成"
else
print_error "Nginx 配置错误,请检查"
exit 1
fi
}
# 安装 SSL 证书
setup_ssl() {
if [[ "$INSTALL_SSL" != "true" || -z "$DOMAIN" || -z "$EMAIL" || "$INSTALL_NGINX" != "true" ]]; then
print_info "跳过 SSL 证书配置"
return
fi
print_header "配置 SSL 证书"
# 安装 Certbot
if ! command -v certbot &> /dev/null; then
print_info "安装 Certbot..."
sudo apt install -y certbot python3-certbot-nginx
fi
# 获取 SSL 证书
print_info "获取 Let's Encrypt SSL 证书..."
sudo certbot --nginx -d $DOMAIN -d www.$DOMAIN --email $EMAIL --agree-tos --no-eff-email -n
# 设置自动续期
print_info "设置证书自动续期..."
(sudo crontab -l 2>/dev/null; echo "0 12 * * * /usr/bin/certbot renew --quiet") | sudo crontab -
print_success "SSL 证书配置完成"
}
# 配置 PM2
setup_pm2() {
print_header "配置 PM2"
# 创建 PM2 配置文件
tee $APP_DIR/ecosystem.config.js > /dev/null << EOF
module.exports = {
apps: [{
name: '$APP_NAME',
script: 'pnpm',
args: 'start',
cwd: '$APP_DIR',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production',
PORT: $APP_PORT
},
error_file: './logs/err.log',
out_file: './logs/out.log',
log_file: './logs/combined.log',
time: true,
max_memory_restart: '1G',
node_args: '--max_old_space_size=4096',
watch: false,
ignore_watch: ['node_modules', 'logs', '.git']
}]
}
EOF
# 创建日志目录
mkdir -p $APP_DIR/logs
print_success "PM2 配置完成"
}
# 启动服务
start_services() {
if [[ "$AUTO_START" != "true" ]]; then
print_info "跳过自动启动服务"
return
fi
print_header "启动服务"
cd $APP_DIR
# 启动应用
print_info "启动应用..."
pm2 start ecosystem.config.js
# 设置开机自启
print_info "设置开机自启..."
pm2 startup | grep -o 'sudo.*' | sudo bash
pm2 save
print_success "服务启动完成"
}
# 创建维护脚本
create_maintenance_scripts() {
print_header "创建维护脚本"
# 备份脚本
tee $APP_DIR/backup.sh > /dev/null << 'EOF'
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="$HOME/backups"
mkdir -p $BACKUP_DIR
cp prisma/production.db $BACKUP_DIR/db_backup_$DATE.db
find $BACKUP_DIR -name "db_backup_*.db" -type f -mtime +7 -delete
echo "数据库备份完成: db_backup_$DATE.db"
EOF
# 更新脚本
tee $APP_DIR/update.sh > /dev/null << 'EOF'
#!/bin/bash
cd $(dirname "$0")
echo "开始更新应用..."
# 备份当前版本
cp -r . ../sayit-backup-$(date +%Y%m%d) 2>/dev/null || true
# 拉取最新代码
git pull origin main || {
echo "Git pull 失败,请手动更新代码"
exit 1
}
# 安装依赖
pnpm install --prod --frozen-lockfile
# 构建应用
pnpm run build
# 更新数据库
pnpm run db:push
# 重启服务
pm2 restart sayit
echo "应用更新完成"
EOF
# 设置执行权限
chmod +x $APP_DIR/backup.sh
chmod +x $APP_DIR/update.sh
print_success "维护脚本创建完成"
}
# 显示安装总结
show_summary() {
print_header "安装完成"
echo -e "${GREEN}🎉 SayIt 校园社交平台安装成功!${NC}"
echo ""
echo -e "${WHITE}访问信息:${NC}"
if [[ -n "$DOMAIN" ]]; then
echo -e " 网站地址: ${CYAN}https://$DOMAIN${NC}"
echo -e " HTTP重定向: ${CYAN}http://$DOMAIN${NC}"
else
echo -e " 本地访问: ${CYAN}http://localhost:$APP_PORT${NC}"
echo -e " 服务器访问: ${CYAN}http://[服务器IP]:$APP_PORT${NC}"
fi
echo ""
echo -e "${WHITE}默认管理员账户:${NC}"
local admin_creds_file="$APP_DIR/admin_credentials.txt"
if [[ -f "$admin_creds_file" ]]; then
local admin_user=$(grep '^username=' "$admin_creds_file" | cut -d'=' -f2-)
local admin_pass=$(grep '^password=' "$admin_creds_file" | cut -d'=' -f2-)
echo -e " 用户名: ${YELLOW}${admin_user:-admin}${NC}"
echo -e " 密码: ${YELLOW}${admin_pass}${NC}"
echo -e " 凭据文件: ${CYAN}$admin_creds_file${NC} (已设置权限 600)"
echo -e " ${RED}⚠️ 请妥善保存并尽快在系统中修改密码!${NC}"
else
echo -e " 用户名: ${YELLOW}admin${NC}"
echo -e " 密码: ${YELLOW}[已随机生成,请查看安装日志或重置密码]${NC}"
echo -e " ${YELLOW}提示:${NC} 如需重新生成,可删除管理员并重新运行初始化脚本。"
fi
echo ""
echo -e "${WHITE}常用命令:${NC}"
echo -e " 查看服务状态: ${CYAN}sudo -u $APP_USER pm2 status${NC}"
echo -e " 查看日志: ${CYAN}sudo -u $APP_USER pm2 logs $APP_NAME${NC}"
echo -e " 重启服务: ${CYAN}sudo -u $APP_USER pm2 restart $APP_NAME${NC}"
echo -e " 备份数据库: ${CYAN}sudo -u $APP_USER $APP_DIR/backup.sh${NC}"
echo -e " 更新应用: ${CYAN}sudo -u $APP_USER $APP_DIR/update.sh${NC}"
echo ""
echo -e "${WHITE}重要文件位置:${NC}"
echo -e " 应用目录: ${CYAN}$APP_DIR${NC}"
echo -e " 配置文件: ${CYAN}$APP_DIR/.env.local${NC}"
echo -e " 日志目录: ${CYAN}$APP_DIR/logs/${NC}"
echo -e " 数据库: ${CYAN}$APP_DIR/prisma/production.db${NC}"
echo ""
if [[ "$INSTALL_NGINX" == "true" ]]; then
echo -e "${WHITE}Nginx 配置:${NC}"
echo -e " 配置文件: ${CYAN}/etc/nginx/sites-available/$APP_NAME${NC}"
echo -e " 测试配置: ${CYAN}sudo nginx -t${NC}"
echo -e " 重启服务: ${CYAN}sudo systemctl restart nginx${NC}"
echo ""
fi
echo -e "${GREEN}✅ 安装指南: 详见项目根目录的 DEPLOYMENT.md${NC}"
echo -e "${GREEN}✅ 技术支持: 如有问题请查看项目文档或提交 Issue${NC}"
}
# ===============================
# 部署相关功能 (来自deploy.sh)
# ===============================
# 检查部署环境
check_deploy_environment() {
log_header "部署环境检查"
# 检查当前用户是否与配置的应用用户一致
if [[ "$(whoami)" != "$APP_USER" ]]; then
log_warning "当前用户 $(whoami) 与配置的应用用户 $APP_USER 不同"
log_info "将使用当前用户 $(whoami) 进行部署"
APP_USER="$(whoami)"
fi
# 检查应用目录
if [[ ! -d "$APP_DIR" ]]; then
log_error "应用目录不存在: $APP_DIR"
log_info "请先运行 install 安装应用"
exit 1
fi
# 若存在 .env.local,则读取其中的端口覆盖 APP_PORT