package svc import ( "strings" "bj_power_wms/ent" "bj_power_wms/internal/agv" "bj_power_wms/internal/config" "bj_power_wms/internal/db" "bj_power_wms/internal/eventlog" "bj_power_wms/internal/mesclient" ) type ServiceContext struct { Config config.Config EntClient *ent.Client EventLog *eventlog.Writer Agv agv.Client Mes *mesclient.Client } func NewServiceContext(c config.Config) *ServiceContext { // 启动期密钥校验:编译期默认密钥已移除,yaml 缺失/为空则直接 panic, // 杜绝「空 token 绕过内部接口鉴权」的攻击面(安全审计 #6/#13)。 validateWmsSecrets(c) conf := db.DatabaseConf{ Host: c.Postgres.Host, Port: c.Postgres.Port, User: c.Postgres.User, Password: c.Postgres.Password, Dbname: c.Postgres.DBName, } // 目标数据库不存在则自动创建 if err := db.EnsureDB(conf); err != nil { panic(err) } entClient := db.MustNewDB(conf) // 启动时自动建表 if err := db.AutoMigrate(entClient); err != nil { panic(err) } // 首次启动预置基础数据 if err := db.SeedIfEmpty(entClient); err != nil { panic(err) } return &ServiceContext{ Config: c, EntClient: entClient, EventLog: eventlog.NewWriter(entClient), Agv: agv.New(c.Agv), Mes: mesclient.New(c.Mes.BaseURL, c.Mes.Token), } } // validateWmsSecrets 启动期校验必要密钥非空(编译期默认密钥已移除)。 func validateWmsSecrets(c config.Config) { missing := make([]string, 0, 4) if strings.TrimSpace(c.Auth.AccessSecret) == "" { missing = append(missing, "Auth.AccessSecret") } if strings.TrimSpace(c.Internal.Token) == "" { missing = append(missing, "Internal.Token") } if strings.TrimSpace(c.Mes.Token) == "" { missing = append(missing, "Mes.Token") } if strings.TrimSpace(c.Cli.AdminPassword) == "" { missing = append(missing, "Cli.AdminPassword") } if len(missing) > 0 { panic("配置缺失必要密钥(已禁止编译期默认密钥,必须在 etc/*.yaml 中显式配置):" + strings.Join(missing, ", ")) } }