425 lines
15 KiB
Go
425 lines
15 KiB
Go
package setup
|
||
|
||
import (
|
||
"context"
|
||
"crypto/rand"
|
||
"crypto/subtle"
|
||
"encoding/base64"
|
||
"encoding/json"
|
||
"errors"
|
||
"fmt"
|
||
"io"
|
||
"log/slog"
|
||
"net"
|
||
"net/http"
|
||
"net/mail"
|
||
"net/url"
|
||
"os"
|
||
"regexp"
|
||
"strings"
|
||
"sync"
|
||
"time"
|
||
|
||
"github.com/go-sql-driver/mysql"
|
||
|
||
"sea-vhost/internal/config"
|
||
"sea-vhost/internal/isolation"
|
||
"sea-vhost/internal/panel"
|
||
"sea-vhost/internal/store"
|
||
)
|
||
|
||
type DatabaseInput struct {
|
||
Host string `json:"host"`
|
||
Port int `json:"port"`
|
||
Name string `json:"name"`
|
||
User string `json:"user"`
|
||
Password string `json:"password"`
|
||
}
|
||
|
||
type PanelInput struct {
|
||
URL string `json:"url"`
|
||
APIKey string `json:"apiKey"`
|
||
TLSInsecure bool `json:"tlsInsecure"`
|
||
}
|
||
|
||
type InstallRequest struct {
|
||
ControllerOnly bool `json:"controllerOnly"`
|
||
Database DatabaseInput `json:"database"`
|
||
Panel PanelInput `json:"panel"`
|
||
RootDomain string `json:"rootDomain"`
|
||
ManagementDomain string `json:"managementDomain"`
|
||
FTPDomain string `json:"ftpDomain"`
|
||
DomainApproval bool `json:"domainApproval"`
|
||
AdminEmail string `json:"adminEmail"`
|
||
AdminName string `json:"adminName"`
|
||
AdminPassword string `json:"adminPassword"`
|
||
}
|
||
|
||
type Server struct {
|
||
token string
|
||
done chan struct{}
|
||
doneOnce sync.Once
|
||
installMu sync.Mutex
|
||
}
|
||
|
||
func New(token string) (*Server, error) {
|
||
if len(strings.TrimSpace(token)) < 24 {
|
||
return nil, errors.New("SEA_SETUP_TOKEN must contain at least 24 characters")
|
||
}
|
||
return &Server{token: token, done: make(chan struct{})}, nil
|
||
}
|
||
|
||
func (s *Server) Done() <-chan struct{} { return s.done }
|
||
|
||
func (s *Server) Handler() http.Handler {
|
||
mux := http.NewServeMux()
|
||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
|
||
writeJSON(w, http.StatusOK, map[string]string{"status": "setup_required"})
|
||
})
|
||
mux.HandleFunc("GET /api/v1/setup/status", func(w http.ResponseWriter, _ *http.Request) {
|
||
writeJSON(w, http.StatusOK, map[string]any{"required": true, "controllerOnly": os.Getenv("SEA_CONTROLLER_ONLY") == "true"})
|
||
})
|
||
mux.HandleFunc("POST /api/v1/setup/test-database", s.authorize(s.testDatabase))
|
||
mux.HandleFunc("POST /api/v1/setup/test-panel", s.authorize(s.testPanel))
|
||
mux.HandleFunc("POST /api/v1/setup/install", s.authorize(s.install))
|
||
return security(mux)
|
||
}
|
||
|
||
func (s *Server) authorize(next http.HandlerFunc) http.HandlerFunc {
|
||
return func(w http.ResponseWriter, r *http.Request) {
|
||
supplied := r.Header.Get("X-Setup-Token")
|
||
if len(supplied) != len(s.token) || subtle.ConstantTimeCompare([]byte(supplied), []byte(s.token)) != 1 {
|
||
writeError(w, http.StatusUnauthorized, "安装令牌无效")
|
||
return
|
||
}
|
||
next(w, r)
|
||
}
|
||
}
|
||
|
||
func (s *Server) testDatabase(w http.ResponseWriter, r *http.Request) {
|
||
var input DatabaseInput
|
||
if !decode(w, r, &input) {
|
||
return
|
||
}
|
||
dsn, err := databaseDSN(input)
|
||
if err == nil {
|
||
var database *store.Store
|
||
database, err = store.Open(dsn)
|
||
if database != nil {
|
||
_ = database.Close()
|
||
}
|
||
}
|
||
if err != nil {
|
||
slog.Warn("setup database preflight failed", "host", input.Host, "database", input.Name, "user", input.User, "error", err)
|
||
writeError(w, http.StatusUnprocessableEntity, safeConnectionError("数据库连接失败", err, input.Password))
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "数据库连接成功"})
|
||
}
|
||
|
||
func (s *Server) testPanel(w http.ResponseWriter, r *http.Request) {
|
||
var input PanelInput
|
||
if !decode(w, r, &input) {
|
||
return
|
||
}
|
||
if err := validatePanel(input); err != nil {
|
||
writeError(w, http.StatusUnprocessableEntity, err.Error())
|
||
return
|
||
}
|
||
ctx, cancel := context.WithTimeout(r.Context(), 18*time.Second)
|
||
defer cancel()
|
||
broker := panel.NewBrokerClient(config.PanelBrokerSocketPath(), 20*time.Second, config.InternalAuthToken())
|
||
credentials := panel.BrokerCredentials{URL: input.URL, APIKey: input.APIKey, TLSInsecure: input.TLSInsecure}
|
||
inspection, err := broker.InspectCredentials(ctx, credentials, s.token)
|
||
if err != nil {
|
||
slog.Warn("setup panel preflight failed", "url", input.URL, "error", err)
|
||
writeError(w, http.StatusUnprocessableEntity, safeConnectionError("宝塔连接失败", err, input.APIKey))
|
||
return
|
||
}
|
||
if err := isolation.NewClient(config.AgentSocketPath(), config.InternalAuthToken()).Ping(ctx); err != nil {
|
||
slog.Warn("setup isolation agent preflight failed", "socket", config.AgentSocketPath(), "error", err)
|
||
writeError(w, http.StatusUnprocessableEntity, "隔离代理未就绪,请检查 sea-vhost-agent 服务")
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "message": "宝塔基础 API 与隔离代理检查成功", "versions": inspection.Versions, "runtimes": inspection.Runtimes})
|
||
}
|
||
|
||
func (s *Server) install(w http.ResponseWriter, r *http.Request) {
|
||
s.installMu.Lock()
|
||
defer s.installMu.Unlock()
|
||
if _, err := os.Stat(config.Path()); err == nil {
|
||
writeError(w, http.StatusConflict, "系统已经完成安装")
|
||
return
|
||
} else if !errors.Is(err, os.ErrNotExist) {
|
||
writeError(w, http.StatusInternalServerError, "无法检查安装状态")
|
||
return
|
||
}
|
||
var input InstallRequest
|
||
if !decode(w, r, &input) {
|
||
return
|
||
}
|
||
if os.Getenv("SEA_CONTROLLER_ONLY") == "true" {
|
||
input.ControllerOnly = true
|
||
}
|
||
if input.ControllerOnly {
|
||
input.RootDomain = "node-default.invalid"
|
||
input.FTPDomain = input.ManagementDomain
|
||
}
|
||
dsn, err := databaseDSN(input.Database)
|
||
if err == nil && !input.ControllerOnly {
|
||
err = validatePanel(input.Panel)
|
||
}
|
||
if err == nil {
|
||
err = validateInstall(input)
|
||
}
|
||
if err != nil {
|
||
writeError(w, http.StatusUnprocessableEntity, err.Error())
|
||
return
|
||
}
|
||
database, err := store.Open(dsn)
|
||
if err != nil {
|
||
slog.Warn("setup install database connection failed", "host", input.Database.Host, "database", input.Database.Name, "user", input.Database.User, "error", err)
|
||
writeError(w, http.StatusUnprocessableEntity, safeConnectionError("数据库连接失败", err, input.Database.Password))
|
||
return
|
||
}
|
||
defer database.Close()
|
||
ctx, cancel := context.WithTimeout(r.Context(), 4*time.Minute)
|
||
defer cancel()
|
||
broker := panel.NewBrokerClient(config.PanelBrokerSocketPath(), 20*time.Second, config.InternalAuthToken())
|
||
credentials := panel.BrokerCredentials{URL: input.Panel.URL, APIKey: input.Panel.APIKey, TLSInsecure: input.Panel.TLSInsecure}
|
||
if !input.ControllerOnly {
|
||
if _, err = broker.InspectCredentials(ctx, credentials, s.token); err != nil {
|
||
slog.Warn("setup install panel connection failed", "url", input.Panel.URL, "error", err)
|
||
writeError(w, http.StatusUnprocessableEntity, safeConnectionError("宝塔连接失败", err, input.Panel.APIKey))
|
||
return
|
||
}
|
||
if err = isolation.NewClient(config.AgentSocketPath(), config.InternalAuthToken()).Ping(ctx); err != nil {
|
||
slog.Warn("setup install isolation agent unavailable", "socket", config.AgentSocketPath(), "error", err)
|
||
writeError(w, http.StatusUnprocessableEntity, "隔离代理未就绪,请检查 sea-vhost-agent 服务")
|
||
return
|
||
}
|
||
}
|
||
if err = database.Migrate(ctx); err == nil {
|
||
err = database.InstallAdmin(ctx, strings.TrimSpace(input.AdminEmail), strings.TrimSpace(input.AdminName), input.AdminPassword)
|
||
}
|
||
if err == nil {
|
||
err = database.SetDomainApproval(ctx, input.DomainApproval)
|
||
}
|
||
if err != nil {
|
||
if errors.Is(err, store.ErrDifferentAdminExists) {
|
||
writeError(w, http.StatusConflict, "数据库中已存在其他管理员,请使用空数据库")
|
||
return
|
||
}
|
||
slog.Error("setup database initialization failed", "error", err)
|
||
writeError(w, http.StatusInternalServerError, "初始化数据库失败,请检查账号权限")
|
||
return
|
||
}
|
||
if !input.ControllerOnly {
|
||
if err = broker.Configure(ctx, credentials, s.token); err != nil {
|
||
slog.Error("setup panel broker configuration failed", "error", err)
|
||
writeError(w, http.StatusInternalServerError, "无法安全保存宝塔代理配置;如需更换密钥,请由 root 重置 panel broker")
|
||
return
|
||
}
|
||
}
|
||
secret, err := randomSecret(48)
|
||
if err != nil {
|
||
writeError(w, http.StatusInternalServerError, "无法生成安全密钥")
|
||
return
|
||
}
|
||
cfg := config.NewInstalled(dsn, secret, input.RootDomain, input.ManagementDomain, input.FTPDomain, nil, input.DomainApproval)
|
||
cfg.ControllerOnly = input.ControllerOnly
|
||
if err = config.Save(cfg); err != nil {
|
||
if strings.Contains(err.Error(), "already exists") {
|
||
writeError(w, http.StatusConflict, "系统已经完成安装")
|
||
return
|
||
}
|
||
slog.Error("setup configuration save failed", "path", config.Path(), "error", err)
|
||
writeError(w, http.StatusInternalServerError, "无法安全保存系统配置")
|
||
return
|
||
}
|
||
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "message": "安装完成,服务正在切换到运行模式"})
|
||
s.doneOnce.Do(func() { close(s.done) })
|
||
}
|
||
|
||
func databaseDSN(input DatabaseInput) (string, error) {
|
||
input.Host = strings.TrimSpace(input.Host)
|
||
input.Name = strings.TrimSpace(input.Name)
|
||
input.User = strings.TrimSpace(input.User)
|
||
if !isLoopback(input.Host) {
|
||
return "", errors.New("数据库必须位于本机,请填写 127.0.0.1 或 localhost")
|
||
}
|
||
if input.Port < 1 || input.Port > 65535 {
|
||
return "", errors.New("数据库端口无效")
|
||
}
|
||
identifier := regexp.MustCompile(`^[A-Za-z0-9_]{1,64}$`)
|
||
if !identifier.MatchString(input.Name) || !identifier.MatchString(input.User) || input.Password == "" {
|
||
return "", errors.New("数据库名、用户名或密码无效")
|
||
}
|
||
mysqlConfig := mysql.NewConfig()
|
||
mysqlConfig.User = input.User
|
||
mysqlConfig.Passwd = input.Password
|
||
mysqlConfig.Net = "tcp"
|
||
mysqlConfig.Addr = net.JoinHostPort(input.Host, fmt.Sprintf("%d", input.Port))
|
||
mysqlConfig.DBName = input.Name
|
||
mysqlConfig.ParseTime = true
|
||
mysqlConfig.Collation = "utf8mb4_unicode_ci"
|
||
mysqlConfig.Params = map[string]string{"charset": "utf8mb4"}
|
||
return mysqlConfig.FormatDSN(), nil
|
||
}
|
||
|
||
func validatePanel(input PanelInput) error {
|
||
parsed, err := url.Parse(strings.TrimSpace(input.URL))
|
||
if err != nil || parsed.Host == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||
return errors.New("宝塔面板地址无效")
|
||
}
|
||
if parsed.User != nil || !isLoopback(parsed.Hostname()) {
|
||
return errors.New("宝塔面板必须使用本机回环地址")
|
||
}
|
||
if len(strings.TrimSpace(input.APIKey)) < 16 {
|
||
return errors.New("宝塔 API 密钥无效")
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func validateInstall(input InstallRequest) error {
|
||
domain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(input.RootDomain)), ".")
|
||
validDomain := regexp.MustCompile(`^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$`)
|
||
if len(domain) > 253 || !validDomain.MatchString(domain) {
|
||
return errors.New("三级域名根域无效")
|
||
}
|
||
managementDomain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(input.ManagementDomain)), ".")
|
||
ftpDomain := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(input.FTPDomain)), ".")
|
||
if !validDomain.MatchString(managementDomain) || !validDomain.MatchString(ftpDomain) {
|
||
return errors.New("控制台域名和 FTP 证书来源域名必须填写有效域名")
|
||
}
|
||
if domainsOverlap(managementDomain, domain) || ftpDomain == domain || strings.HasSuffix(domain, "."+ftpDomain) {
|
||
return errors.New("控制台域名必须独立,FTP 证书来源域名不能覆盖租户三级域名")
|
||
}
|
||
if strings.HasSuffix(ftpDomain, "."+domain) {
|
||
prefix := strings.TrimSuffix(ftpDomain, "."+domain)
|
||
if regexp.MustCompile(`^sv[0-9a-f]{10}$`).MatchString(prefix) {
|
||
return errors.New("FTP 证书来源域名不能占用系统分配的随机主机名")
|
||
}
|
||
}
|
||
address, err := mail.ParseAddress(strings.TrimSpace(input.AdminEmail))
|
||
if err != nil || !strings.EqualFold(address.Address, strings.TrimSpace(input.AdminEmail)) {
|
||
return errors.New("管理员邮箱无效")
|
||
}
|
||
if len([]rune(strings.TrimSpace(input.AdminName))) < 2 || len([]rune(input.AdminName)) > 50 {
|
||
return errors.New("管理员名称应为 2–50 个字符")
|
||
}
|
||
if len(input.AdminPassword) < 12 || len(input.AdminPassword) > 128 {
|
||
return errors.New("管理员密码应为 12–128 个字符")
|
||
}
|
||
return nil
|
||
}
|
||
|
||
func domainsOverlap(first, second string) bool {
|
||
return first == second || strings.HasSuffix(first, "."+second) || strings.HasSuffix(second, "."+first)
|
||
}
|
||
|
||
func isLoopback(host string) bool {
|
||
host = strings.Trim(strings.ToLower(strings.TrimSpace(host)), "[]")
|
||
if host == "localhost" {
|
||
return true
|
||
}
|
||
ip := net.ParseIP(host)
|
||
return ip != nil && ip.IsLoopback()
|
||
}
|
||
|
||
func randomSecret(size int) (string, error) {
|
||
data := make([]byte, size)
|
||
if _, err := rand.Read(data); err != nil {
|
||
return "", err
|
||
}
|
||
return base64.RawURLEncoding.EncodeToString(data), nil
|
||
}
|
||
|
||
func decode(w http.ResponseWriter, r *http.Request, target any) bool {
|
||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10))
|
||
decoder.DisallowUnknownFields()
|
||
if err := decoder.Decode(target); err != nil {
|
||
writeError(w, http.StatusBadRequest, "请求内容无效")
|
||
return false
|
||
}
|
||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||
writeError(w, http.StatusBadRequest, "请求内容必须只包含一个 JSON 对象")
|
||
return false
|
||
}
|
||
return true
|
||
}
|
||
|
||
func safeConnectionError(prefix string, err error, secrets ...string) string {
|
||
message := strings.ReplaceAll(err.Error(), "\n", " ")
|
||
for _, secret := range secrets {
|
||
if secret != "" {
|
||
message = strings.ReplaceAll(message, secret, "[已隐藏]")
|
||
}
|
||
}
|
||
if len(message) > 180 {
|
||
message = message[:180]
|
||
}
|
||
return prefix + ":" + message
|
||
}
|
||
|
||
func security(next http.Handler) http.Handler {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
w.Header().Set("Cache-Control", "no-store")
|
||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||
w.Header().Set("X-Frame-Options", "DENY")
|
||
w.Header().Set("Referrer-Policy", "same-origin")
|
||
w.Header().Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||
if r.Method != http.MethodGet {
|
||
origin := r.Header.Get("Origin")
|
||
if strings.EqualFold(r.Header.Get("Sec-Fetch-Site"), "cross-site") || (origin != "" && !sameOrigin(r)) {
|
||
writeError(w, http.StatusForbidden, "不允许跨站请求")
|
||
return
|
||
}
|
||
}
|
||
next.ServeHTTP(w, r)
|
||
})
|
||
}
|
||
|
||
func sameOrigin(r *http.Request) bool {
|
||
parsed, err := url.Parse(r.Header.Get("Origin"))
|
||
if err != nil || parsed.User != nil || parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") {
|
||
return false
|
||
}
|
||
if parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||
return false
|
||
}
|
||
return strings.EqualFold(parsed.Scheme, setupRequestScheme(r)) && strings.EqualFold(parsed.Host, r.Host)
|
||
}
|
||
|
||
func setupRequestScheme(r *http.Request) string {
|
||
if r.TLS != nil {
|
||
return "https"
|
||
}
|
||
if isLoopbackRemote(r.RemoteAddr) {
|
||
forwarded := strings.ToLower(strings.TrimSpace(strings.Split(r.Header.Get("X-Forwarded-Proto"), ",")[0]))
|
||
if forwarded == "http" || forwarded == "https" {
|
||
return forwarded
|
||
}
|
||
}
|
||
return "http"
|
||
}
|
||
|
||
func isLoopbackRemote(remote string) bool {
|
||
host, _, err := net.SplitHostPort(remote)
|
||
if err != nil {
|
||
host = strings.Trim(remote, "[]")
|
||
}
|
||
ip := net.ParseIP(strings.Trim(host, "[]"))
|
||
return ip != nil && ip.IsLoopback()
|
||
}
|
||
|
||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||
w.WriteHeader(status)
|
||
_ = json.NewEncoder(w).Encode(value)
|
||
}
|
||
|
||
func writeError(w http.ResponseWriter, status int, message string) {
|
||
writeJSON(w, status, map[string]any{"error": map[string]string{"message": message}})
|
||
}
|