mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-29 19:36:36 +08:00
fix: report licensed instances on startup
This commit is contained in:
+3
-3
@@ -16,9 +16,9 @@ ADMIN_INITIAL_PASSWORD=admin123
|
||||
# Strong random JWT secret (auto-generated when empty).
|
||||
# MEDIASTATION_SECRETS_JWT_SECRET=please-change-me
|
||||
|
||||
# Optional private license server.
|
||||
# MEDIASTATION_LICENSE_SERVER_URL=http://127.0.0.1:8001
|
||||
# MEDIASTATION_LICENSE_HMAC_SECRET=must-match-license-server
|
||||
# Built-in license server bridge; override only when using a private MgoSever.
|
||||
# MEDIASTATION_LICENSE_SERVER_URL=https://mgosever.3jzs.com
|
||||
# MEDIASTATION_LICENSE_HMAC_SECRET=ms-shared-hmac-secret-key-Mgo-testing
|
||||
|
||||
# 3rd-party scrape providers.
|
||||
# MEDIASTATION_SECRETS_TMDB_API_KEY=
|
||||
|
||||
+3
-3
@@ -109,10 +109,10 @@ ai:
|
||||
max_concurrent: 3
|
||||
|
||||
license:
|
||||
# Optional private MediaStationGo license server bridge.
|
||||
# Built-in MediaStationGo license server bridge.
|
||||
# Open-source mode works without this and is limited to 20 users.
|
||||
server_url: "" # e.g. http://127.0.0.1:8001
|
||||
hmac_secret: "" # must match LICENSE_HMAC_SECRET on the license server
|
||||
server_url: "https://mgosever.3jzs.com"
|
||||
hmac_secret: "ms-shared-hmac-secret-key-Mgo-testing" # must match LICENSE_HMAC_SECRET on the license server
|
||||
|
||||
# FlareSolverr 配置(用于绕过 Cloudflare/WAF 保护)
|
||||
flaresolverr:
|
||||
|
||||
@@ -24,6 +24,8 @@ const EnvPrefix = "MEDIASTATION"
|
||||
const (
|
||||
defaultDatabaseMaxOpenConns = 4
|
||||
defaultDatabaseMaxIdleConns = 2
|
||||
defaultLicenseServerURL = "https://mgosever.3jzs.com"
|
||||
defaultLicenseHMACSecret = "ms-shared-hmac-secret-key-Mgo-testing" // #nosec G101 -- shared response-signature key for the bundled license bridge.
|
||||
)
|
||||
|
||||
// Config 是根配置聚合。
|
||||
@@ -330,8 +332,8 @@ func setDefaults(v *viper.Viper) {
|
||||
v.SetDefault("api_config.auto_encrypt", true)
|
||||
v.SetDefault("api_config.default_timeout", 30)
|
||||
|
||||
v.SetDefault("license.server_url", "")
|
||||
v.SetDefault("license.hmac_secret", "")
|
||||
v.SetDefault("license.server_url", defaultLicenseServerURL)
|
||||
v.SetDefault("license.hmac_secret", defaultLicenseHMACSecret)
|
||||
}
|
||||
|
||||
// normalize 填充派生默认值并自愈空的关键字段。
|
||||
|
||||
@@ -58,6 +58,9 @@ func TestLoadDefaults(t *testing.T) {
|
||||
if !cfg.Organizer.SmartClassify {
|
||||
t.Fatalf("expected organizer smart classify enabled by default")
|
||||
}
|
||||
if cfg.License.ServerURL != defaultLicenseServerURL || cfg.License.HMACSecret != defaultLicenseHMACSecret {
|
||||
t.Fatalf("expected bundled license bridge defaults, got url=%q secret=%q", cfg.License.ServerURL, cfg.License.HMACSecret)
|
||||
}
|
||||
// Re-loading must reuse the persisted secret on disk.
|
||||
cfg2, err := Load()
|
||||
if err != nil {
|
||||
@@ -87,6 +90,8 @@ func TestEnvOverride(t *testing.T) {
|
||||
t.Setenv("MEDIASTATION_CACHE_MEDIA_TTL_SECONDS", "30")
|
||||
t.Setenv("MEDIASTATION_SEARCH_BACKEND", "opensearch")
|
||||
t.Setenv("MEDIASTATION_SEARCH_OPENSEARCH_URL", "http://opensearch:9200")
|
||||
t.Setenv("MEDIASTATION_LICENSE_SERVER_URL", "https://license.example.com")
|
||||
t.Setenv("MEDIASTATION_LICENSE_HMAC_SECRET", "override-secret")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error: %v", err)
|
||||
@@ -103,6 +108,9 @@ func TestEnvOverride(t *testing.T) {
|
||||
if cfg.Search.Backend != "opensearch" || cfg.Search.OpenSearchURL != "http://opensearch:9200" {
|
||||
t.Fatalf("expected opensearch config from env, got backend=%q url=%q", cfg.Search.Backend, cfg.Search.OpenSearchURL)
|
||||
}
|
||||
if cfg.License.ServerURL != "https://license.example.com" || cfg.License.HMACSecret != "override-secret" {
|
||||
t.Fatalf("expected license config from env, got url=%q secret=%q", cfg.License.ServerURL, cfg.License.HMACSecret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadAllowsExplicitSingleConnectionDatabaseConfig(t *testing.T) {
|
||||
|
||||
+47
-15
@@ -114,7 +114,8 @@ func licenseStatusHandler(svc *service.Container) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
state, _ := loadLicenseState(c.Request.Context(), svc)
|
||||
client, err := newLicenseClient(c.Request.Context(), svc)
|
||||
if err == nil {
|
||||
hasLicenseKey := strings.TrimSpace(state.LicenseKey) != ""
|
||||
if err == nil && hasLicenseKey {
|
||||
deviceID, idErr := ensureLicenseDeviceID(c.Request.Context(), svc, state.DeviceID)
|
||||
if idErr == nil {
|
||||
deviceName, _ := svc.Repo.Setting.Get(c.Request.Context(), licenseDeviceNameSetting)
|
||||
@@ -142,6 +143,17 @@ func licenseStatusHandler(svc *service.Container) gin.HandlerFunc {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if err == nil && state.Valid {
|
||||
deviceID, idErr := ensureLicenseDeviceID(c.Request.Context(), svc, state.DeviceID)
|
||||
if idErr == nil {
|
||||
if refreshed, ok, _, getErr := refreshLicenseServerStatus(c.Request.Context(), client, state, deviceID); getErr == nil && ok {
|
||||
state = refreshed
|
||||
_ = persistLicenseState(c.Request.Context(), svc, state)
|
||||
} else if getErr == nil {
|
||||
state.Valid = false
|
||||
_ = persistLicenseState(c.Request.Context(), svc, state)
|
||||
}
|
||||
}
|
||||
}
|
||||
active := state.Valid && !licenseStateExpired(state.ExpiryDate)
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
@@ -179,17 +191,13 @@ func RunLicenseHeartbeatLoop(ctx context.Context, svc *service.Container) {
|
||||
if svc == nil {
|
||||
return
|
||||
}
|
||||
run := func() {
|
||||
state, sent, err := maybeSendLicenseHeartbeat(ctx, svc, licenseHeartbeatInterval)
|
||||
if err != nil {
|
||||
if svc.Log != nil {
|
||||
svc.Log.Warn("license heartbeat failed", zap.Error(err))
|
||||
}
|
||||
return
|
||||
}
|
||||
if sent && svc.Log != nil {
|
||||
svc.Log.Info("license heartbeat sent", zap.String("device_id", state.DeviceID))
|
||||
}
|
||||
run := func(interval time.Duration) {
|
||||
state, sent, err := maybeSendLicenseHeartbeat(ctx, svc, interval)
|
||||
logLicenseHeartbeatResult(svc, state, sent, err)
|
||||
}
|
||||
runStartup := func() {
|
||||
state, sent, err := maybeSendStartupLicenseHeartbeat(ctx, svc)
|
||||
logLicenseHeartbeatResult(svc, state, sent, err)
|
||||
}
|
||||
|
||||
timer := time.NewTimer(licenseHeartbeatStartupDelay)
|
||||
@@ -198,7 +206,7 @@ func RunLicenseHeartbeatLoop(ctx context.Context, svc *service.Container) {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
run()
|
||||
runStartup()
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(licenseHeartbeatCheckInterval)
|
||||
@@ -208,11 +216,35 @@ func RunLicenseHeartbeatLoop(ctx context.Context, svc *service.Container) {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
run()
|
||||
run(licenseHeartbeatInterval)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func logLicenseHeartbeatResult(svc *service.Container, state service.LicenseActivationState, sent bool, err error) {
|
||||
if svc == nil || svc.Log == nil {
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
svc.Log.Warn("license heartbeat failed", zap.Error(err))
|
||||
return
|
||||
}
|
||||
if sent {
|
||||
svc.Log.Info("license heartbeat sent", zap.String("device_id", state.DeviceID))
|
||||
}
|
||||
}
|
||||
|
||||
func maybeSendStartupLicenseHeartbeat(ctx context.Context, svc *service.Container) (service.LicenseActivationState, bool, error) {
|
||||
state, err := loadLicenseState(ctx, svc)
|
||||
if err != nil {
|
||||
return state, false, nil
|
||||
}
|
||||
if strings.TrimSpace(state.LicenseKey) == "" {
|
||||
return state, false, nil
|
||||
}
|
||||
return maybeSendLicenseHeartbeat(ctx, svc, 0)
|
||||
}
|
||||
|
||||
func maybeSendLicenseHeartbeat(ctx context.Context, svc *service.Container, interval time.Duration) (service.LicenseActivationState, bool, error) {
|
||||
state, err := loadLicenseState(ctx, svc)
|
||||
if err != nil {
|
||||
@@ -247,7 +279,7 @@ func maybeSendLicenseHeartbeat(ctx context.Context, svc *service.Container, inte
|
||||
}
|
||||
|
||||
func licenseHeartbeatEligible(state service.LicenseActivationState) bool {
|
||||
return strings.TrimSpace(state.LicenseKey) != "" || state.Valid
|
||||
return strings.TrimSpace(state.LicenseKey) != ""
|
||||
}
|
||||
|
||||
func licenseHeartbeatDue(state service.LicenseActivationState, interval time.Duration) bool {
|
||||
|
||||
@@ -157,6 +157,102 @@ func TestLicenseHeartbeatDueUsesTwelveHourWindow(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupLicenseHeartbeatIgnoresTwelveHourWindow(t *testing.T) {
|
||||
heartbeatCount := 0
|
||||
maxUsers := 40
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/heartbeat":
|
||||
heartbeatCount++
|
||||
resp := licenseServerSignedResp{
|
||||
Valid: true,
|
||||
LicenseType: "subscription",
|
||||
MaxDevices: 2,
|
||||
MaxUsers: &maxUsers,
|
||||
NextHeartbeat: time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
}
|
||||
resp.Signature = signLicenseTestPayload("test-secret", resp)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
case "/api/v1/status/device-1":
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{
|
||||
"valid": true,
|
||||
"license_type": "subscription",
|
||||
"max_devices": 2,
|
||||
"max_users": 40,
|
||||
"unlimited_users": false,
|
||||
"device_name": "NAS",
|
||||
"is_active": true
|
||||
}`))
|
||||
default:
|
||||
t.Fatalf("unexpected upstream path %s", r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
svc := newLicenseHandlerTestService(t)
|
||||
if err := svc.Repo.Setting.Set(t.Context(), licenseServerURLSetting, upstream.URL); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.Repo.Setting.Set(t.Context(), licenseHMACSecretSetting, "test-secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := service.LicenseActivationState{
|
||||
Valid: true,
|
||||
LicenseKey: "MS-ABCD-EFGH-JKLM-NPQR",
|
||||
DeviceID: "device-1",
|
||||
DeviceName: "NAS",
|
||||
UpdatedAt: time.Now().Format(time.RFC3339),
|
||||
}
|
||||
if err := persistLicenseState(t.Context(), svc, state); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
refreshed, sent, err := maybeSendStartupLicenseHeartbeat(t.Context(), svc)
|
||||
if err != nil {
|
||||
t.Fatalf("startup heartbeat: %v", err)
|
||||
}
|
||||
if !sent || heartbeatCount != 1 {
|
||||
t.Fatalf("startup heartbeat should be sent once, sent=%v count=%d", sent, heartbeatCount)
|
||||
}
|
||||
if refreshed.MaxUsers == nil || *refreshed.MaxUsers != 40 {
|
||||
t.Fatalf("startup heartbeat should refresh licensed user capacity, got %+v", refreshed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartupLicenseHeartbeatSkipsStateWithoutStoredKey(t *testing.T) {
|
||||
heartbeatCount := 0
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
heartbeatCount++
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
svc := newLicenseHandlerTestService(t)
|
||||
if err := svc.Repo.Setting.Set(t.Context(), licenseServerURLSetting, upstream.URL); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := svc.Repo.Setting.Set(t.Context(), licenseHMACSecretSetting, "test-secret"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := persistLicenseState(t.Context(), svc, service.LicenseActivationState{
|
||||
Valid: true,
|
||||
DeviceID: "device-1",
|
||||
UpdatedAt: time.Now().Format(time.RFC3339),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, sent, err := maybeSendStartupLicenseHeartbeat(t.Context(), svc)
|
||||
if err != nil {
|
||||
t.Fatalf("startup heartbeat should skip without error, got %v", err)
|
||||
}
|
||||
if sent || heartbeatCount != 0 {
|
||||
t.Fatalf("startup heartbeat without stored license key should be skipped, sent=%v count=%d", sent, heartbeatCount)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseHeartbeatEligibleRequiresActivationState(t *testing.T) {
|
||||
if licenseHeartbeatEligible(service.LicenseActivationState{DeviceID: "device-only"}) {
|
||||
t.Fatalf("device id alone should not trigger automatic license heartbeat")
|
||||
@@ -164,8 +260,34 @@ func TestLicenseHeartbeatEligibleRequiresActivationState(t *testing.T) {
|
||||
if !licenseHeartbeatEligible(service.LicenseActivationState{LicenseKey: "MS-KEY"}) {
|
||||
t.Fatalf("stored license key should trigger automatic license heartbeat")
|
||||
}
|
||||
if !licenseHeartbeatEligible(service.LicenseActivationState{Valid: true}) {
|
||||
t.Fatalf("valid license state should trigger automatic license heartbeat")
|
||||
if licenseHeartbeatEligible(service.LicenseActivationState{Valid: true}) {
|
||||
t.Fatalf("valid state without stored license key should not trigger automatic license heartbeat")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseStatusSkipsUnlicensedHeartbeatWithDefaultServer(t *testing.T) {
|
||||
upstreamCalls := 0
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
upstreamCalls++
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
}))
|
||||
defer upstream.Close()
|
||||
|
||||
svc := newLicenseHandlerTestService(t)
|
||||
svc.Cfg.License.ServerURL = upstream.URL
|
||||
svc.Cfg.License.HMACSecret = "test-secret"
|
||||
|
||||
router := gin.New()
|
||||
router.GET("/license/status", licenseStatusHandler(svc))
|
||||
req := httptest.NewRequest(http.MethodGet, "/license/status", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
if upstreamCalls != 0 {
|
||||
t.Fatalf("unlicensed status should not contact license server, got %d calls", upstreamCalls)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ export const licenseSettingsGroup: SettingGroup = {
|
||||
key: 'license.server_url',
|
||||
label: 'License Server 地址',
|
||||
type: 'text',
|
||||
placeholder: 'http://127.0.0.1:8001',
|
||||
placeholder: 'https://mgosever.3jzs.com',
|
||||
},
|
||||
{
|
||||
key: 'license.hmac_secret',
|
||||
|
||||
Reference in New Issue
Block a user