2025-12-18 13:50:39 +08:00
|
|
|
|
package setup
|
|
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
|
"context"
|
|
|
|
|
|
"crypto/rand"
|
2026-01-31 00:53:39 +08:00
|
|
|
|
"crypto/tls"
|
2025-12-29 10:03:27 +08:00
|
|
|
|
"database/sql"
|
2025-12-18 13:50:39 +08:00
|
|
|
|
"encoding/hex"
|
2026-04-23 10:27:13 +08:00
|
|
|
|
"errors"
|
2025-12-18 13:50:39 +08:00
|
|
|
|
"fmt"
|
|
|
|
|
|
"os"
|
|
|
|
|
|
"strconv"
|
2026-02-12 16:50:42 +08:00
|
|
|
|
"strings"
|
2025-12-18 13:50:39 +08:00
|
|
|
|
"time"
|
|
|
|
|
|
|
2026-03-07 18:19:04 +08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/config"
|
2026-02-12 19:01:09 +08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
|
2026-04-23 10:27:13 +08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
2025-12-31 23:42:01 +08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/repository"
|
2025-12-26 15:40:24 +08:00
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/service"
|
2025-12-18 15:56:13 +08:00
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
_ "github.com/lib/pq"
|
2025-12-18 13:50:39 +08:00
|
|
|
|
"github.com/redis/go-redis/v9"
|
2025-12-20 15:29:52 +08:00
|
|
|
|
"gopkg.in/yaml.v3"
|
2025-12-18 13:50:39 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
// Config paths
|
|
|
|
|
|
const (
|
2026-03-07 18:19:04 +08:00
|
|
|
|
ConfigFileName = "config.yaml"
|
|
|
|
|
|
InstallLockFile = ".installed"
|
|
|
|
|
|
defaultUserConcurrency = 5
|
|
|
|
|
|
simpleModeAdminConcurrency = 30
|
2025-12-18 13:50:39 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2026-03-07 18:19:04 +08:00
|
|
|
|
func setupDefaultAdminConcurrency() int {
|
|
|
|
|
|
if strings.EqualFold(strings.TrimSpace(os.Getenv("RUN_MODE")), config.RunModeSimple) {
|
|
|
|
|
|
return simpleModeAdminConcurrency
|
|
|
|
|
|
}
|
|
|
|
|
|
return defaultUserConcurrency
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-06 09:43:56 +08:00
|
|
|
|
// GetDataDir returns the data directory for storing config and lock files.
|
|
|
|
|
|
// Priority: DATA_DIR env > /app/data (if exists and writable) > current directory
|
|
|
|
|
|
func GetDataDir() string {
|
|
|
|
|
|
// Check DATA_DIR environment variable first
|
|
|
|
|
|
if dir := os.Getenv("DATA_DIR"); dir != "" {
|
|
|
|
|
|
return dir
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Check if /app/data exists and is writable (Docker environment)
|
|
|
|
|
|
dockerDataDir := "/app/data"
|
|
|
|
|
|
if info, err := os.Stat(dockerDataDir); err == nil && info.IsDir() {
|
|
|
|
|
|
// Try to check if writable by creating a temp file
|
|
|
|
|
|
testFile := dockerDataDir + "/.write_test"
|
|
|
|
|
|
if f, err := os.Create(testFile); err == nil {
|
2026-01-06 10:13:12 +08:00
|
|
|
|
_ = f.Close()
|
|
|
|
|
|
_ = os.Remove(testFile)
|
2026-01-06 09:43:56 +08:00
|
|
|
|
return dockerDataDir
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Default to current directory
|
|
|
|
|
|
return "."
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// GetConfigFilePath returns the full path to config.yaml
|
|
|
|
|
|
func GetConfigFilePath() string {
|
|
|
|
|
|
return GetDataDir() + "/" + ConfigFileName
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// GetInstallLockPath returns the full path to .installed lock file
|
|
|
|
|
|
func GetInstallLockPath() string {
|
|
|
|
|
|
return GetDataDir() + "/" + InstallLockFile
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-18 13:50:39 +08:00
|
|
|
|
// SetupConfig holds the setup configuration
|
|
|
|
|
|
type SetupConfig struct {
|
|
|
|
|
|
Database DatabaseConfig `json:"database" yaml:"database"`
|
|
|
|
|
|
Redis RedisConfig `json:"redis" yaml:"redis"`
|
|
|
|
|
|
Admin AdminConfig `json:"admin" yaml:"-"` // Not stored in config file
|
|
|
|
|
|
Server ServerConfig `json:"server" yaml:"server"`
|
|
|
|
|
|
JWT JWTConfig `json:"jwt" yaml:"jwt"`
|
|
|
|
|
|
Timezone string `json:"timezone" yaml:"timezone"` // e.g. "Asia/Shanghai", "UTC"
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type DatabaseConfig struct {
|
|
|
|
|
|
Host string `json:"host" yaml:"host"`
|
|
|
|
|
|
Port int `json:"port" yaml:"port"`
|
|
|
|
|
|
User string `json:"user" yaml:"user"`
|
|
|
|
|
|
Password string `json:"password" yaml:"password"`
|
|
|
|
|
|
DBName string `json:"dbname" yaml:"dbname"`
|
|
|
|
|
|
SSLMode string `json:"sslmode" yaml:"sslmode"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type RedisConfig struct {
|
2026-01-31 00:53:39 +08:00
|
|
|
|
Host string `json:"host" yaml:"host"`
|
|
|
|
|
|
Port int `json:"port" yaml:"port"`
|
|
|
|
|
|
Password string `json:"password" yaml:"password"`
|
|
|
|
|
|
DB int `json:"db" yaml:"db"`
|
|
|
|
|
|
EnableTLS bool `json:"enable_tls" yaml:"enable_tls"`
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type AdminConfig struct {
|
|
|
|
|
|
Email string `json:"email"`
|
|
|
|
|
|
Password string `json:"password"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type ServerConfig struct {
|
|
|
|
|
|
Host string `json:"host" yaml:"host"`
|
|
|
|
|
|
Port int `json:"port" yaml:"port"`
|
|
|
|
|
|
Mode string `json:"mode" yaml:"mode"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
type JWTConfig struct {
|
|
|
|
|
|
Secret string `json:"secret" yaml:"secret"`
|
|
|
|
|
|
ExpireHour int `json:"expire_hour" yaml:"expire_hour"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-12 16:50:42 +08:00
|
|
|
|
const (
|
|
|
|
|
|
adminBootstrapReasonEmptyDatabase = "empty_database"
|
|
|
|
|
|
adminBootstrapReasonAdminExists = "admin_exists"
|
|
|
|
|
|
adminBootstrapReasonUsersExistWithoutAdmin = "users_exist_without_admin"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
type adminBootstrapDecision struct {
|
|
|
|
|
|
shouldCreate bool
|
|
|
|
|
|
reason string
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func decideAdminBootstrap(totalUsers, adminUsers int64) adminBootstrapDecision {
|
|
|
|
|
|
if adminUsers > 0 {
|
|
|
|
|
|
return adminBootstrapDecision{
|
|
|
|
|
|
shouldCreate: false,
|
|
|
|
|
|
reason: adminBootstrapReasonAdminExists,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
if totalUsers > 0 {
|
|
|
|
|
|
return adminBootstrapDecision{
|
|
|
|
|
|
shouldCreate: false,
|
|
|
|
|
|
reason: adminBootstrapReasonUsersExistWithoutAdmin,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return adminBootstrapDecision{
|
|
|
|
|
|
shouldCreate: true,
|
|
|
|
|
|
reason: adminBootstrapReasonEmptyDatabase,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-18 13:50:39 +08:00
|
|
|
|
// NeedsSetup checks if the system needs initial setup
|
|
|
|
|
|
// Uses multiple checks to prevent attackers from forcing re-setup by deleting config
|
|
|
|
|
|
func NeedsSetup() bool {
|
|
|
|
|
|
// Check 1: Config file must not exist
|
2026-01-06 09:43:56 +08:00
|
|
|
|
if _, err := os.Stat(GetConfigFilePath()); !os.IsNotExist(err) {
|
2025-12-18 13:50:39 +08:00
|
|
|
|
return false // Config exists, no setup needed
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Check 2: Installation lock file (harder to bypass)
|
2026-01-06 09:43:56 +08:00
|
|
|
|
if _, err := os.Stat(GetInstallLockPath()); !os.IsNotExist(err) {
|
2025-12-18 13:50:39 +08:00
|
|
|
|
return false // Lock file exists, already installed
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return true
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-16 20:28:36 +08:00
|
|
|
|
// quoteIdentifier safely quotes a PostgreSQL identifier (table name, database name, etc.)
|
|
|
|
|
|
// to prevent SQL injection. It follows PostgreSQL's quoting rules:
|
|
|
|
|
|
// - Wrap in double quotes
|
|
|
|
|
|
// - Escape internal double quotes by doubling them
|
|
|
|
|
|
func quoteIdentifier(name string) string {
|
|
|
|
|
|
// Escape any existing double quotes by doubling them
|
|
|
|
|
|
escaped := strings.ReplaceAll(name, `"`, `""`)
|
|
|
|
|
|
return `"` + escaped + `"`
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-18 15:56:13 +08:00
|
|
|
|
// TestDatabaseConnection tests the database connection and creates database if not exists
|
2025-12-18 13:50:39 +08:00
|
|
|
|
func TestDatabaseConnection(cfg *DatabaseConfig) error {
|
2025-12-18 15:56:13 +08:00
|
|
|
|
// First, connect to the default 'postgres' database to check/create target database
|
|
|
|
|
|
defaultDSN := fmt.Sprintf(
|
2026-03-17 06:34:20 +08:00
|
|
|
|
"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
|
|
|
|
|
|
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode,
|
2025-12-18 13:50:39 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
db, err := sql.Open("postgres", defaultDSN)
|
2025-12-18 13:50:39 +08:00
|
|
|
|
if err != nil {
|
2025-12-18 15:56:13 +08:00
|
|
|
|
return fmt.Errorf("failed to connect to PostgreSQL: %w", err)
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-20 15:29:52 +08:00
|
|
|
|
defer func() {
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if db == nil {
|
2025-12-20 15:29:52 +08:00
|
|
|
|
return
|
|
|
|
|
|
}
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if err := db.Close(); err != nil {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "failed to close postgres connection: %v", err)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if err := db.PingContext(ctx); err != nil {
|
2025-12-18 13:50:39 +08:00
|
|
|
|
return fmt.Errorf("ping failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-18 15:56:13 +08:00
|
|
|
|
// Check if target database exists
|
|
|
|
|
|
var exists bool
|
2025-12-29 10:03:27 +08:00
|
|
|
|
row := db.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", cfg.DBName)
|
2025-12-18 15:56:13 +08:00
|
|
|
|
if err := row.Scan(&exists); err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to check database existence: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Create database if not exists
|
|
|
|
|
|
if !exists {
|
2026-04-16 20:28:36 +08:00
|
|
|
|
// 使用 quoteIdentifier 对数据库名进行安全引用,防止 SQL 注入。
|
|
|
|
|
|
// 虽然前置校验 validateDBName() 已限制为 [a-zA-Z][a-zA-Z0-9_]*,
|
|
|
|
|
|
// 但此处增加防御深度,确保即使校验被绕过也能安全执行。
|
|
|
|
|
|
quotedDBName := quoteIdentifier(cfg.DBName)
|
|
|
|
|
|
_, err := db.ExecContext(ctx, fmt.Sprintf("CREATE DATABASE %s", quotedDBName))
|
2025-12-18 15:56:13 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to create database '%s': %w", cfg.DBName, err)
|
|
|
|
|
|
}
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "Database '%s' created successfully", cfg.DBName)
|
2025-12-18 15:56:13 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Now connect to the target database to verify
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if err := db.Close(); err != nil {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "failed to close postgres connection: %v", err)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
}
|
2025-12-29 10:03:27 +08:00
|
|
|
|
db = nil
|
2025-12-18 15:56:13 +08:00
|
|
|
|
|
|
|
|
|
|
targetDSN := fmt.Sprintf(
|
|
|
|
|
|
"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
|
|
|
|
|
|
cfg.Host, cfg.Port, cfg.User, cfg.Password, cfg.DBName, cfg.SSLMode,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
targetDB, err := sql.Open("postgres", targetDSN)
|
2025-12-18 15:56:13 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to connect to database '%s': %w", cfg.DBName, err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-20 15:29:52 +08:00
|
|
|
|
defer func() {
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if err := targetDB.Close(); err != nil {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "failed to close postgres connection: %v", err)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-12-18 15:56:13 +08:00
|
|
|
|
|
|
|
|
|
|
ctx2, cancel2 := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
|
defer cancel2()
|
|
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if err := targetDB.PingContext(ctx2); err != nil {
|
2025-12-18 15:56:13 +08:00
|
|
|
|
return fmt.Errorf("ping target database failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-18 13:50:39 +08:00
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// TestRedisConnection tests the Redis connection
|
|
|
|
|
|
func TestRedisConnection(cfg *RedisConfig) error {
|
2026-01-31 00:53:39 +08:00
|
|
|
|
opts := &redis.Options{
|
2025-12-18 13:50:39 +08:00
|
|
|
|
Addr: fmt.Sprintf("%s:%d", cfg.Host, cfg.Port),
|
|
|
|
|
|
Password: cfg.Password,
|
|
|
|
|
|
DB: cfg.DB,
|
2026-01-31 00:53:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if cfg.EnableTLS {
|
|
|
|
|
|
opts.TLSConfig = &tls.Config{
|
|
|
|
|
|
MinVersion: tls.VersionTLS12,
|
|
|
|
|
|
ServerName: cfg.Host,
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
rdb := redis.NewClient(opts)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
defer func() {
|
|
|
|
|
|
if err := rdb.Close(); err != nil {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "failed to close redis client: %v", err)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
|
|
|
|
if err := rdb.Ping(ctx).Err(); err != nil {
|
|
|
|
|
|
return fmt.Errorf("ping failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Install performs the installation with the given configuration
|
|
|
|
|
|
func Install(cfg *SetupConfig) error {
|
|
|
|
|
|
// Security check: prevent re-installation if already installed
|
|
|
|
|
|
if !NeedsSetup() {
|
|
|
|
|
|
return fmt.Errorf("system is already installed, re-installation is not allowed")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Generate JWT secret if not provided
|
|
|
|
|
|
if cfg.JWT.Secret == "" {
|
2025-12-20 15:29:52 +08:00
|
|
|
|
secret, err := generateSecret(32)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to generate jwt secret: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
cfg.JWT.Secret = secret
|
2026-04-16 21:37:03 +08:00
|
|
|
|
// 使用更醒目的告警格式
|
|
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
|
|
|
|
|
logger.LegacyPrintf("setup", "⚠️ SECURITY WARNING: JWT secret auto-generated")
|
|
|
|
|
|
logger.LegacyPrintf("setup", " For production, set JWT_SECRET environment variable or jwt.secret in config.yaml")
|
2026-04-17 07:24:23 +08:00
|
|
|
|
logger.LegacyPrintf("setup", " Auto-generated secrets will change on each re-install, invalidating all existing tokens!")
|
2026-04-16 21:37:03 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
2026-04-17 07:24:23 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
// 检测是否与已存在的 config.yaml 中的密钥不一致(可能因重新安装导致 token 失效)
|
|
|
|
|
|
if existingSecret := readExistingJWTSecret(); existingSecret != "" && existingSecret != cfg.JWT.Secret {
|
|
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
|
|
|
|
|
logger.LegacyPrintf("setup", "⚠️ JWT SECRET MISMATCH DETECTED")
|
|
|
|
|
|
logger.LegacyPrintf("setup", " The provided JWT_SECRET differs from the one in the existing config file.")
|
|
|
|
|
|
logger.LegacyPrintf("setup", " All existing user sessions (JWT tokens) will be invalidated!")
|
|
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
|
|
|
|
|
}
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Test connections
|
|
|
|
|
|
if err := TestDatabaseConnection(&cfg.Database); err != nil {
|
|
|
|
|
|
return fmt.Errorf("database connection failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if err := TestRedisConnection(&cfg.Redis); err != nil {
|
|
|
|
|
|
return fmt.Errorf("redis connection failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Initialize database
|
|
|
|
|
|
if err := initializeDatabase(cfg); err != nil {
|
|
|
|
|
|
return fmt.Errorf("database initialization failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-12 16:50:42 +08:00
|
|
|
|
// Create admin user (only when database is empty and no admin exists).
|
|
|
|
|
|
if _, _, err := createAdminUser(cfg); err != nil {
|
2025-12-18 13:50:39 +08:00
|
|
|
|
return fmt.Errorf("admin user creation failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Write config file
|
|
|
|
|
|
if err := writeConfigFile(cfg); err != nil {
|
|
|
|
|
|
return fmt.Errorf("config file creation failed: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Create installation lock file to prevent re-setup attacks
|
|
|
|
|
|
if err := createInstallLock(); err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to create install lock: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// createInstallLock creates a lock file to prevent re-installation attacks
|
|
|
|
|
|
func createInstallLock() error {
|
|
|
|
|
|
content := fmt.Sprintf("installed_at=%s\n", time.Now().UTC().Format(time.RFC3339))
|
2026-01-06 09:43:56 +08:00
|
|
|
|
return os.WriteFile(GetInstallLockPath(), []byte(content), 0400) // Read-only for owner
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func initializeDatabase(cfg *SetupConfig) error {
|
|
|
|
|
|
dsn := fmt.Sprintf(
|
|
|
|
|
|
"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
|
|
|
|
|
|
cfg.Database.Host, cfg.Database.Port, cfg.Database.User,
|
|
|
|
|
|
cfg.Database.Password, cfg.Database.DBName, cfg.Database.SSLMode,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
db, err := sql.Open("postgres", dsn)
|
2025-12-18 13:50:39 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-20 15:29:52 +08:00
|
|
|
|
defer func() {
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if err := db.Close(); err != nil {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "failed to close postgres connection: %v", err)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
2025-12-29 10:43:46 +08:00
|
|
|
|
migrationCtx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
|
|
|
|
|
defer cancel()
|
2026-04-16 22:11:15 +08:00
|
|
|
|
if err := repository.ApplyMigrations(migrationCtx, db); err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 检查 usage_logs 分区状态(仅在首次部署时提示)
|
|
|
|
|
|
repository.CheckUsageLogsPartitioning(migrationCtx, db)
|
|
|
|
|
|
return nil
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-02-12 16:50:42 +08:00
|
|
|
|
func createAdminUser(cfg *SetupConfig) (bool, string, error) {
|
2025-12-18 13:50:39 +08:00
|
|
|
|
dsn := fmt.Sprintf(
|
|
|
|
|
|
"host=%s port=%d user=%s password=%s dbname=%s sslmode=%s",
|
|
|
|
|
|
cfg.Database.Host, cfg.Database.Port, cfg.Database.User,
|
|
|
|
|
|
cfg.Database.Password, cfg.Database.DBName, cfg.Database.SSLMode,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
db, err := sql.Open("postgres", dsn)
|
2025-12-18 13:50:39 +08:00
|
|
|
|
if err != nil {
|
2026-02-12 16:50:42 +08:00
|
|
|
|
return false, "", err
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-20 15:29:52 +08:00
|
|
|
|
defer func() {
|
2025-12-29 10:03:27 +08:00
|
|
|
|
if err := db.Close(); err != nil {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "failed to close postgres connection: %v", err)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
}
|
|
|
|
|
|
}()
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
// 使用超时上下文避免安装流程因数据库异常而长时间阻塞。
|
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
2026-02-12 16:50:42 +08:00
|
|
|
|
var totalUsers int64
|
2026-04-23 10:27:13 +08:00
|
|
|
|
if err := db.QueryRowContext(ctx, "SELECT COUNT(1) FROM public.users").Scan(&totalUsers); err != nil {
|
2026-02-12 16:50:42 +08:00
|
|
|
|
return false, "", err
|
|
|
|
|
|
}
|
|
|
|
|
|
var adminUsers int64
|
2026-04-23 10:27:13 +08:00
|
|
|
|
if err := db.QueryRowContext(ctx, "SELECT COUNT(1) FROM public.users WHERE role = $1", service.RoleAdmin).Scan(&adminUsers); err != nil {
|
2026-02-12 16:50:42 +08:00
|
|
|
|
return false, "", err
|
2025-12-26 15:40:24 +08:00
|
|
|
|
}
|
2026-02-12 16:50:42 +08:00
|
|
|
|
decision := decideAdminBootstrap(totalUsers, adminUsers)
|
|
|
|
|
|
if !decision.shouldCreate {
|
|
|
|
|
|
return false, decision.reason, nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if strings.TrimSpace(cfg.Admin.Password) == "" {
|
|
|
|
|
|
password, genErr := generateSecret(16)
|
|
|
|
|
|
if genErr != nil {
|
|
|
|
|
|
return false, "", fmt.Errorf("failed to generate admin password: %w", genErr)
|
|
|
|
|
|
}
|
|
|
|
|
|
cfg.Admin.Password = password
|
|
|
|
|
|
fmt.Printf("Generated admin password (one-time): %s\n", cfg.Admin.Password)
|
|
|
|
|
|
fmt.Println("IMPORTANT: Save this password! It will not be shown again.")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-26 15:40:24 +08:00
|
|
|
|
admin := &service.User{
|
|
|
|
|
|
Email: cfg.Admin.Email,
|
|
|
|
|
|
Role: service.RoleAdmin,
|
|
|
|
|
|
Status: service.StatusActive,
|
|
|
|
|
|
Balance: 0,
|
2026-03-07 18:19:04 +08:00
|
|
|
|
Concurrency: setupDefaultAdminConcurrency(),
|
2025-12-26 15:40:24 +08:00
|
|
|
|
CreatedAt: time.Now(),
|
|
|
|
|
|
UpdatedAt: time.Now(),
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-26 15:40:24 +08:00
|
|
|
|
if err := admin.SetPassword(cfg.Admin.Password); err != nil {
|
2026-02-12 16:50:42 +08:00
|
|
|
|
return false, "", err
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-29 10:03:27 +08:00
|
|
|
|
_, err = db.ExecContext(
|
|
|
|
|
|
ctx,
|
2026-04-23 10:27:13 +08:00
|
|
|
|
`INSERT INTO public.users (email, password_hash, role, balance, concurrency, status, created_at, updated_at)
|
2025-12-29 10:03:27 +08:00
|
|
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
|
|
|
|
|
admin.Email,
|
|
|
|
|
|
admin.PasswordHash,
|
|
|
|
|
|
admin.Role,
|
|
|
|
|
|
admin.Balance,
|
|
|
|
|
|
admin.Concurrency,
|
|
|
|
|
|
admin.Status,
|
|
|
|
|
|
admin.CreatedAt,
|
|
|
|
|
|
admin.UpdatedAt,
|
|
|
|
|
|
)
|
2026-02-12 16:50:42 +08:00
|
|
|
|
if err != nil {
|
|
|
|
|
|
return false, "", err
|
|
|
|
|
|
}
|
|
|
|
|
|
return true, decision.reason, nil
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func writeConfigFile(cfg *SetupConfig) error {
|
|
|
|
|
|
// Ensure timezone has a default value
|
|
|
|
|
|
tz := cfg.Timezone
|
|
|
|
|
|
if tz == "" {
|
|
|
|
|
|
tz = "Asia/Shanghai"
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Prepare config for YAML (exclude sensitive data and admin config)
|
|
|
|
|
|
yamlConfig := struct {
|
|
|
|
|
|
Server ServerConfig `yaml:"server"`
|
|
|
|
|
|
Database DatabaseConfig `yaml:"database"`
|
|
|
|
|
|
Redis RedisConfig `yaml:"redis"`
|
|
|
|
|
|
JWT struct {
|
|
|
|
|
|
Secret string `yaml:"secret"`
|
|
|
|
|
|
ExpireHour int `yaml:"expire_hour"`
|
|
|
|
|
|
} `yaml:"jwt"`
|
|
|
|
|
|
Default struct {
|
2025-12-29 10:03:27 +08:00
|
|
|
|
UserConcurrency int `yaml:"user_concurrency"`
|
|
|
|
|
|
UserBalance float64 `yaml:"user_balance"`
|
2026-01-04 19:27:53 +08:00
|
|
|
|
APIKeyPrefix string `yaml:"api_key_prefix"`
|
2025-12-29 10:03:27 +08:00
|
|
|
|
RateMultiplier float64 `yaml:"rate_multiplier"`
|
2025-12-18 13:50:39 +08:00
|
|
|
|
} `yaml:"default"`
|
|
|
|
|
|
RateLimit struct {
|
|
|
|
|
|
RequestsPerMinute int `yaml:"requests_per_minute"`
|
|
|
|
|
|
BurstSize int `yaml:"burst_size"`
|
|
|
|
|
|
} `yaml:"rate_limit"`
|
|
|
|
|
|
Timezone string `yaml:"timezone"`
|
|
|
|
|
|
}{
|
|
|
|
|
|
Server: cfg.Server,
|
|
|
|
|
|
Database: cfg.Database,
|
|
|
|
|
|
Redis: cfg.Redis,
|
|
|
|
|
|
JWT: struct {
|
|
|
|
|
|
Secret string `yaml:"secret"`
|
|
|
|
|
|
ExpireHour int `yaml:"expire_hour"`
|
|
|
|
|
|
}{
|
|
|
|
|
|
Secret: cfg.JWT.Secret,
|
|
|
|
|
|
ExpireHour: cfg.JWT.ExpireHour,
|
|
|
|
|
|
},
|
|
|
|
|
|
Default: struct {
|
2025-12-29 10:03:27 +08:00
|
|
|
|
UserConcurrency int `yaml:"user_concurrency"`
|
|
|
|
|
|
UserBalance float64 `yaml:"user_balance"`
|
2026-01-04 19:27:53 +08:00
|
|
|
|
APIKeyPrefix string `yaml:"api_key_prefix"`
|
2025-12-29 10:03:27 +08:00
|
|
|
|
RateMultiplier float64 `yaml:"rate_multiplier"`
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}{
|
2026-03-07 18:19:04 +08:00
|
|
|
|
UserConcurrency: defaultUserConcurrency,
|
2025-12-29 10:03:27 +08:00
|
|
|
|
UserBalance: 0,
|
2026-01-04 19:27:53 +08:00
|
|
|
|
APIKeyPrefix: "sk-",
|
2025-12-29 10:03:27 +08:00
|
|
|
|
RateMultiplier: 1.0,
|
2025-12-18 13:50:39 +08:00
|
|
|
|
},
|
|
|
|
|
|
RateLimit: struct {
|
|
|
|
|
|
RequestsPerMinute int `yaml:"requests_per_minute"`
|
|
|
|
|
|
BurstSize int `yaml:"burst_size"`
|
|
|
|
|
|
}{
|
|
|
|
|
|
RequestsPerMinute: 60,
|
|
|
|
|
|
BurstSize: 10,
|
|
|
|
|
|
},
|
|
|
|
|
|
Timezone: tz,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
data, err := yaml.Marshal(&yamlConfig)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-01-06 09:43:56 +08:00
|
|
|
|
return os.WriteFile(GetConfigFilePath(), data, 0600)
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-20 15:29:52 +08:00
|
|
|
|
func generateSecret(length int) (string, error) {
|
2025-12-18 13:50:39 +08:00
|
|
|
|
bytes := make([]byte, length)
|
2025-12-20 15:29:52 +08:00
|
|
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
|
|
|
|
return "", err
|
|
|
|
|
|
}
|
|
|
|
|
|
return hex.EncodeToString(bytes), nil
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-17 07:24:23 +08:00
|
|
|
|
// readExistingJWTSecret reads the JWT secret from an existing config.yaml file (if any).
|
|
|
|
|
|
// Returns empty string if no config file exists or jwt.secret is not set.
|
|
|
|
|
|
func readExistingJWTSecret() string {
|
|
|
|
|
|
configPath := GetConfigFilePath()
|
|
|
|
|
|
data, err := os.ReadFile(configPath)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return "" // No existing config file — this is normal for fresh installs
|
|
|
|
|
|
}
|
|
|
|
|
|
var cfg struct {
|
|
|
|
|
|
JWT struct {
|
|
|
|
|
|
Secret string `yaml:"secret"`
|
|
|
|
|
|
} `yaml:"jwt"`
|
|
|
|
|
|
}
|
|
|
|
|
|
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
|
|
|
|
|
return ""
|
|
|
|
|
|
}
|
|
|
|
|
|
return strings.TrimSpace(cfg.JWT.Secret)
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-18 13:50:39 +08:00
|
|
|
|
// =============================================================================
|
|
|
|
|
|
// Auto Setup for Docker Deployment
|
|
|
|
|
|
// =============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
// AutoSetupEnabled checks if auto setup is enabled via environment variable
|
|
|
|
|
|
func AutoSetupEnabled() bool {
|
|
|
|
|
|
val := os.Getenv("AUTO_SETUP")
|
|
|
|
|
|
return val == "true" || val == "1" || val == "yes"
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// getEnvOrDefault gets environment variable or returns default value
|
|
|
|
|
|
func getEnvOrDefault(key, defaultValue string) string {
|
|
|
|
|
|
if val := os.Getenv(key); val != "" {
|
|
|
|
|
|
return val
|
|
|
|
|
|
}
|
|
|
|
|
|
return defaultValue
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// getEnvIntOrDefault gets environment variable as int or returns default value
|
|
|
|
|
|
func getEnvIntOrDefault(key string, defaultValue int) int {
|
|
|
|
|
|
if val := os.Getenv(key); val != "" {
|
|
|
|
|
|
if i, err := strconv.Atoi(val); err == nil {
|
|
|
|
|
|
return i
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
return defaultValue
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// AutoSetupFromEnv performs automatic setup using environment variables
|
|
|
|
|
|
// This is designed for Docker deployment where all config is passed via env vars
|
|
|
|
|
|
func AutoSetupFromEnv() error {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Auto setup enabled, configuring from environment variables...")
|
|
|
|
|
|
logger.LegacyPrintf("setup", "Data directory: %s", GetDataDir())
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
// Get timezone from TZ or TIMEZONE env var (TZ is standard for Docker)
|
|
|
|
|
|
tz := getEnvOrDefault("TZ", "")
|
|
|
|
|
|
if tz == "" {
|
|
|
|
|
|
tz = getEnvOrDefault("TIMEZONE", "Asia/Shanghai")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Build config from environment variables
|
|
|
|
|
|
cfg := &SetupConfig{
|
|
|
|
|
|
Database: DatabaseConfig{
|
|
|
|
|
|
Host: getEnvOrDefault("DATABASE_HOST", "localhost"),
|
|
|
|
|
|
Port: getEnvIntOrDefault("DATABASE_PORT", 5432),
|
|
|
|
|
|
User: getEnvOrDefault("DATABASE_USER", "postgres"),
|
|
|
|
|
|
Password: getEnvOrDefault("DATABASE_PASSWORD", ""),
|
|
|
|
|
|
DBName: getEnvOrDefault("DATABASE_DBNAME", "sub2api"),
|
|
|
|
|
|
SSLMode: getEnvOrDefault("DATABASE_SSLMODE", "disable"),
|
|
|
|
|
|
},
|
|
|
|
|
|
Redis: RedisConfig{
|
2026-01-31 00:53:39 +08:00
|
|
|
|
Host: getEnvOrDefault("REDIS_HOST", "localhost"),
|
|
|
|
|
|
Port: getEnvIntOrDefault("REDIS_PORT", 6379),
|
|
|
|
|
|
Password: getEnvOrDefault("REDIS_PASSWORD", ""),
|
|
|
|
|
|
DB: getEnvIntOrDefault("REDIS_DB", 0),
|
|
|
|
|
|
EnableTLS: getEnvOrDefault("REDIS_ENABLE_TLS", "false") == "true",
|
2025-12-18 13:50:39 +08:00
|
|
|
|
},
|
|
|
|
|
|
Admin: AdminConfig{
|
|
|
|
|
|
Email: getEnvOrDefault("ADMIN_EMAIL", "admin@sub2api.local"),
|
|
|
|
|
|
Password: getEnvOrDefault("ADMIN_PASSWORD", ""),
|
|
|
|
|
|
},
|
|
|
|
|
|
Server: ServerConfig{
|
|
|
|
|
|
Host: getEnvOrDefault("SERVER_HOST", "0.0.0.0"),
|
|
|
|
|
|
Port: getEnvIntOrDefault("SERVER_PORT", 8080),
|
|
|
|
|
|
Mode: getEnvOrDefault("SERVER_MODE", "release"),
|
|
|
|
|
|
},
|
|
|
|
|
|
JWT: JWTConfig{
|
|
|
|
|
|
Secret: getEnvOrDefault("JWT_SECRET", ""),
|
|
|
|
|
|
ExpireHour: getEnvIntOrDefault("JWT_EXPIRE_HOUR", 24),
|
|
|
|
|
|
},
|
|
|
|
|
|
Timezone: tz,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Generate JWT secret if not provided
|
|
|
|
|
|
if cfg.JWT.Secret == "" {
|
2025-12-20 15:29:52 +08:00
|
|
|
|
secret, err := generateSecret(32)
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to generate jwt secret: %w", err)
|
|
|
|
|
|
}
|
|
|
|
|
|
cfg.JWT.Secret = secret
|
2026-04-16 21:37:03 +08:00
|
|
|
|
// 使用更醒目的告警格式
|
|
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
|
|
|
|
|
logger.LegacyPrintf("setup", "⚠️ SECURITY WARNING: JWT secret auto-generated")
|
|
|
|
|
|
logger.LegacyPrintf("setup", " For production, set JWT_SECRET environment variable or jwt.secret in config.yaml")
|
2026-04-17 07:24:23 +08:00
|
|
|
|
logger.LegacyPrintf("setup", " Auto-generated secrets will change on each re-install, invalidating all existing tokens!")
|
2026-04-16 21:37:03 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
2026-04-17 07:24:23 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
// 检测是否与已存在的 config.yaml 中的密钥不一致(可能因重新安装导致 token 失效)
|
|
|
|
|
|
if existingSecret := readExistingJWTSecret(); existingSecret != "" && existingSecret != cfg.JWT.Secret {
|
|
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
|
|
|
|
|
logger.LegacyPrintf("setup", "⚠️ JWT SECRET MISMATCH DETECTED (AutoSetup)")
|
|
|
|
|
|
logger.LegacyPrintf("setup", " The provided JWT_SECRET differs from the one in the existing config file.")
|
|
|
|
|
|
logger.LegacyPrintf("setup", " All existing user sessions (JWT tokens) will be invalidated!")
|
|
|
|
|
|
logger.LegacyPrintf("setup", "================================================================================")
|
|
|
|
|
|
}
|
2025-12-18 13:50:39 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Test database connection
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Testing database connection...")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
if err := TestDatabaseConnection(&cfg.Database); err != nil {
|
|
|
|
|
|
return fmt.Errorf("database connection failed: %w", err)
|
|
|
|
|
|
}
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Database connection successful")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
// Test Redis connection
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Testing Redis connection...")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
if err := TestRedisConnection(&cfg.Redis); err != nil {
|
|
|
|
|
|
return fmt.Errorf("redis connection failed: %w", err)
|
|
|
|
|
|
}
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Redis connection successful")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
// Initialize database
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Initializing database...")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
if err := initializeDatabase(cfg); err != nil {
|
|
|
|
|
|
return fmt.Errorf("database initialization failed: %w", err)
|
|
|
|
|
|
}
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Database initialized successfully")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
// Create admin user
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Creating admin user...")
|
2026-02-12 16:50:42 +08:00
|
|
|
|
created, reason, err := createAdminUser(cfg)
|
|
|
|
|
|
if err != nil {
|
2025-12-18 13:50:39 +08:00
|
|
|
|
return fmt.Errorf("admin user creation failed: %w", err)
|
|
|
|
|
|
}
|
2026-02-12 16:50:42 +08:00
|
|
|
|
if created {
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "Admin user created: %s", cfg.Admin.Email)
|
2026-02-12 16:50:42 +08:00
|
|
|
|
} else {
|
|
|
|
|
|
switch reason {
|
|
|
|
|
|
case adminBootstrapReasonAdminExists:
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Admin user already exists, skipping admin bootstrap")
|
2026-02-12 16:50:42 +08:00
|
|
|
|
case adminBootstrapReasonUsersExistWithoutAdmin:
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Database already has user data; skipping auto admin bootstrap to avoid password overwrite")
|
2026-02-12 16:50:42 +08:00
|
|
|
|
default:
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Admin bootstrap skipped")
|
2026-02-12 16:50:42 +08:00
|
|
|
|
}
|
|
|
|
|
|
}
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
// Write config file
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Writing configuration file...")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
if err := writeConfigFile(cfg); err != nil {
|
|
|
|
|
|
return fmt.Errorf("config file creation failed: %w", err)
|
|
|
|
|
|
}
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Configuration file created")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
|
|
|
|
|
// Create installation lock file
|
|
|
|
|
|
if err := createInstallLock(); err != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to create install lock: %w", err)
|
|
|
|
|
|
}
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Installation lock created")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
|
2026-02-12 19:01:09 +08:00
|
|
|
|
logger.LegacyPrintf("setup", "%s", "Auto setup completed successfully!")
|
2025-12-18 13:50:39 +08:00
|
|
|
|
return nil
|
|
|
|
|
|
}
|
2026-04-23 10:27:13 +08:00
|
|
|
|
|
|
|
|
|
|
// RecoverAutoSetupAdmin repairs an interrupted bootstrap by creating the admin
|
|
|
|
|
|
// user when the initialized application state still has no users.
|
|
|
|
|
|
func RecoverAutoSetupAdmin(ctx context.Context, userRepo service.UserRepository, cfg *config.Config) error {
|
|
|
|
|
|
if cfg == nil || userRepo == nil {
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
if ctx == nil {
|
|
|
|
|
|
ctx = context.Background()
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if _, err := userRepo.GetFirstAdmin(ctx); err == nil {
|
|
|
|
|
|
logger.LegacyPrintf("setup", "startup admin recovery result: created=false reason=%s", adminBootstrapReasonAdminExists)
|
|
|
|
|
|
return nil
|
|
|
|
|
|
} else if !errors.Is(err, service.ErrUserNotFound) {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
_, page, err := userRepo.List(ctx, pagination.PaginationParams{Page: 1, PageSize: 1})
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
if page != nil && page.Total > 0 {
|
|
|
|
|
|
logger.LegacyPrintf("setup", "startup admin recovery result: created=false reason=%s", adminBootstrapReasonUsersExistWithoutAdmin)
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
adminEmail := strings.TrimSpace(cfg.Default.AdminEmail)
|
|
|
|
|
|
if adminEmail == "" {
|
|
|
|
|
|
adminEmail = "admin@sub2api.local"
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
adminPassword := getEnvOrDefault("ADMIN_PASSWORD", cfg.Default.AdminPassword)
|
|
|
|
|
|
if strings.TrimSpace(adminPassword) == "" {
|
|
|
|
|
|
password, genErr := generateSecret(16)
|
|
|
|
|
|
if genErr != nil {
|
|
|
|
|
|
return fmt.Errorf("failed to generate admin password: %w", genErr)
|
|
|
|
|
|
}
|
|
|
|
|
|
adminPassword = password
|
|
|
|
|
|
fmt.Printf("Generated admin password (one-time): %s\n", adminPassword)
|
|
|
|
|
|
fmt.Println("IMPORTANT: Save this password! It will not be shown again.")
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
admin := &service.User{
|
|
|
|
|
|
Email: getEnvOrDefault("ADMIN_EMAIL", adminEmail),
|
|
|
|
|
|
Role: service.RoleAdmin,
|
|
|
|
|
|
Status: service.StatusActive,
|
|
|
|
|
|
Balance: 0,
|
|
|
|
|
|
Concurrency: setupDefaultAdminConcurrency(),
|
|
|
|
|
|
}
|
|
|
|
|
|
if err := admin.SetPassword(adminPassword); err != nil {
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
if err := userRepo.Create(ctx, admin); err != nil {
|
|
|
|
|
|
if errors.Is(err, service.ErrEmailExists) {
|
|
|
|
|
|
logger.LegacyPrintf("setup", "startup admin recovery result: created=false reason=%s", adminBootstrapReasonAdminExists)
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|
|
|
|
|
|
return err
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
logger.LegacyPrintf("setup", "startup admin recovery result: created=true reason=%s", adminBootstrapReasonEmptyDatabase)
|
|
|
|
|
|
return nil
|
|
|
|
|
|
}
|