mirror of
https://github.com/truewhile/MeBox.git
synced 2026-09-28 03:06:38 +08:00
feat: verify license responses with public key
This commit is contained in:
+2
-1
@@ -18,7 +18,8 @@ ADMIN_INITIAL_PASSWORD=admin123
|
||||
|
||||
# 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
|
||||
# MEDIASTATION_LICENSE_PUBLIC_KEY=MCowBQYDK2VwAyEABRXnXy+urjrbKit6Yu/HiezWgP0NdsZW3tsegJWRrtI=
|
||||
# MEDIASTATION_LICENSE_HMAC_SECRET=
|
||||
|
||||
# 3rd-party scrape providers.
|
||||
# MEDIASTATION_SECRETS_TMDB_API_KEY=
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.PHONY: all build build-server build-web dev dev-web run deploy docker docker-update docker-stop docker-push clean install-web tidy test vet smoke
|
||||
.PHONY: all build build-server build-protected build-protected-garble build-web dev dev-web run deploy docker docker-update docker-stop docker-push clean install-web tidy test vet smoke
|
||||
|
||||
# ---- 默认目标 ----
|
||||
all: build
|
||||
@@ -11,6 +11,12 @@ build: build-web build-server
|
||||
build-server:
|
||||
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o bin/mediastation-go ./cmd/server
|
||||
|
||||
build-protected:
|
||||
CGO_ENABLED=0 go build -trimpath -buildvcs=false -ldflags="-s -w -buildid=" -o bin/mediastation-go-protected ./cmd/server
|
||||
|
||||
build-protected-garble:
|
||||
CGO_ENABLED=0 garble -literals -tiny build -trimpath -ldflags="-s -w -buildid=" -o bin/mediastation-go-protected ./cmd/server
|
||||
|
||||
# ---- 前端构建 ----
|
||||
build-web:
|
||||
cd web && npm install --silent && npm run build
|
||||
|
||||
+2
-1
@@ -112,7 +112,8 @@ license:
|
||||
# Built-in MediaStationGo license server bridge.
|
||||
# Open-source mode works without this and is limited to 20 users.
|
||||
server_url: "https://mgosever.3jzs.com"
|
||||
hmac_secret: "ms-shared-hmac-secret-key-Mgo-testing" # must match LICENSE_HMAC_SECRET on the license server
|
||||
public_key: "MCowBQYDK2VwAyEABRXnXy+urjrbKit6Yu/HiezWgP0NdsZW3tsegJWRrtI=" # Ed25519 public key for protected license responses
|
||||
hmac_secret: "" # legacy fallback only; prefer Ed25519 public_key
|
||||
|
||||
# FlareSolverr 配置(用于绕过 Cloudflare/WAF 保护)
|
||||
flaresolverr:
|
||||
|
||||
@@ -25,7 +25,7 @@ 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.
|
||||
defaultLicensePublicKey = "MCowBQYDK2VwAyEABRXnXy+urjrbKit6Yu/HiezWgP0NdsZW3tsegJWRrtI="
|
||||
)
|
||||
|
||||
// Config 是根配置聚合。
|
||||
@@ -172,6 +172,7 @@ type AIConfig struct {
|
||||
type LicenseConfig struct {
|
||||
ServerURL string `mapstructure:"server_url"`
|
||||
HMACSecret string `mapstructure:"hmac_secret"`
|
||||
PublicKey string `mapstructure:"public_key"`
|
||||
}
|
||||
|
||||
// OrganizerConfig 配置媒体文件智能分类整理。
|
||||
@@ -333,7 +334,8 @@ func setDefaults(v *viper.Viper) {
|
||||
v.SetDefault("api_config.default_timeout", 30)
|
||||
|
||||
v.SetDefault("license.server_url", defaultLicenseServerURL)
|
||||
v.SetDefault("license.hmac_secret", defaultLicenseHMACSecret)
|
||||
v.SetDefault("license.hmac_secret", "")
|
||||
v.SetDefault("license.public_key", defaultLicensePublicKey)
|
||||
}
|
||||
|
||||
// normalize 填充派生默认值并自愈空的关键字段。
|
||||
|
||||
@@ -58,8 +58,8 @@ 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)
|
||||
if cfg.License.ServerURL != defaultLicenseServerURL || cfg.License.PublicKey != defaultLicensePublicKey || cfg.License.HMACSecret != "" {
|
||||
t.Fatalf("expected bundled license bridge defaults, got url=%q public_key=%q hmac=%q", cfg.License.ServerURL, cfg.License.PublicKey, cfg.License.HMACSecret)
|
||||
}
|
||||
// Re-loading must reuse the persisted secret on disk.
|
||||
cfg2, err := Load()
|
||||
@@ -92,6 +92,7 @@ func TestEnvOverride(t *testing.T) {
|
||||
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")
|
||||
t.Setenv("MEDIASTATION_LICENSE_PUBLIC_KEY", "override-public-key")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load() error: %v", err)
|
||||
@@ -108,8 +109,8 @@ 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)
|
||||
if cfg.License.ServerURL != "https://license.example.com" || cfg.License.HMACSecret != "override-secret" || cfg.License.PublicKey != "override-public-key" {
|
||||
t.Fatalf("expected license config from env, got url=%q secret=%q public_key=%q", cfg.License.ServerURL, cfg.License.HMACSecret, cfg.License.PublicKey)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -46,6 +46,7 @@ type licenseServerSignedResp struct {
|
||||
DaysRemaining *int `json:"days_remaining"`
|
||||
NextHeartbeat string `json:"next_heartbeat"`
|
||||
Signature string `json:"signature"`
|
||||
SignatureAlg string `json:"signature_alg"`
|
||||
LegacySignature bool `json:"-"`
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,11 @@ package handler
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -18,9 +21,10 @@ import (
|
||||
)
|
||||
|
||||
type licenseClient struct {
|
||||
baseURL string
|
||||
hmacSecret string
|
||||
httpClient *http.Client
|
||||
baseURL string
|
||||
hmacSecret string
|
||||
ed25519PublicKey ed25519.PublicKey
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func newLicenseClient(ctx context.Context, svc *service.Container) (*licenseClient, error) {
|
||||
@@ -32,18 +36,27 @@ func newLicenseClient(ctx context.Context, svc *service.Container) (*licenseClie
|
||||
if strings.TrimSpace(secret) == "" {
|
||||
secret = svc.Cfg.License.HMACSecret
|
||||
}
|
||||
publicKeyRaw, _ := svc.Repo.Setting.Get(ctx, "license.public_key")
|
||||
if strings.TrimSpace(publicKeyRaw) == "" {
|
||||
publicKeyRaw = svc.Cfg.License.PublicKey
|
||||
}
|
||||
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
|
||||
if baseURL == "" {
|
||||
return nil, errors.New("license server url not configured")
|
||||
}
|
||||
secret = strings.TrimSpace(secret)
|
||||
if secret == "" {
|
||||
return nil, errors.New("license hmac secret not configured")
|
||||
publicKey, err := parseLicenseEd25519PublicKey(publicKeyRaw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if secret == "" && len(publicKey) == 0 {
|
||||
return nil, errors.New("license public key or hmac secret not configured")
|
||||
}
|
||||
return &licenseClient{
|
||||
baseURL: baseURL,
|
||||
hmacSecret: secret,
|
||||
httpClient: &http.Client{Timeout: 15 * time.Second},
|
||||
baseURL: baseURL,
|
||||
hmacSecret: secret,
|
||||
ed25519PublicKey: publicKey,
|
||||
httpClient: &http.Client{Timeout: 15 * time.Second},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -96,30 +109,42 @@ func (c *licenseClient) do(req *http.Request, out any) error {
|
||||
}
|
||||
|
||||
func (c *licenseClient) verifySigned(resp *licenseServerSignedResp) error {
|
||||
if c.hmacSecret == "" {
|
||||
return errors.New("license hmac secret not configured")
|
||||
}
|
||||
if strings.TrimSpace(resp.Signature) == "" {
|
||||
return errors.New("license server signature missing")
|
||||
}
|
||||
unsigned := struct {
|
||||
Valid bool `json:"valid"`
|
||||
LicenseType string `json:"license_type"`
|
||||
ExpiryDate *string `json:"expiry_date"`
|
||||
MaxDevices int `json:"max_devices"`
|
||||
MaxUsers *int `json:"max_users"`
|
||||
DaysRemaining *int `json:"days_remaining"`
|
||||
NextHeartbeat string `json:"next_heartbeat"`
|
||||
}{
|
||||
Valid: resp.Valid,
|
||||
LicenseType: resp.LicenseType,
|
||||
ExpiryDate: resp.ExpiryDate,
|
||||
MaxDevices: resp.MaxDevices,
|
||||
MaxUsers: resp.MaxUsers,
|
||||
DaysRemaining: resp.DaysRemaining,
|
||||
NextHeartbeat: resp.NextHeartbeat,
|
||||
switch strings.ToLower(strings.TrimSpace(resp.SignatureAlg)) {
|
||||
case "ed25519":
|
||||
return c.verifyEd25519Signed(*resp)
|
||||
case "", "hmac", "hmac-sha256":
|
||||
return c.verifyHMACSigned(resp)
|
||||
default:
|
||||
return fmt.Errorf("unsupported license signature algorithm %q", resp.SignatureAlg)
|
||||
}
|
||||
payload, err := json.Marshal(unsigned)
|
||||
}
|
||||
|
||||
func (c *licenseClient) verifyEd25519Signed(resp licenseServerSignedResp) error {
|
||||
if len(c.ed25519PublicKey) != ed25519.PublicKeySize {
|
||||
return errors.New("license Ed25519 public key not configured")
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(resp.Signature))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
payload, err := json.Marshal(licenseSignedPayload(resp))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ed25519.Verify(c.ed25519PublicKey, payload, signature) {
|
||||
return errors.New("license server signature verification failed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *licenseClient) verifyHMACSigned(resp *licenseServerSignedResp) error {
|
||||
if c.hmacSecret == "" {
|
||||
return errors.New("license hmac secret not configured")
|
||||
}
|
||||
payload, err := json.Marshal(licenseSignedPayload(*resp))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -161,3 +186,44 @@ func (c *licenseClient) verifyLegacySigned(resp licenseServerSignedResp) bool {
|
||||
expected := hex.EncodeToString(mac.Sum(nil))
|
||||
return hmac.Equal([]byte(expected), []byte(resp.Signature))
|
||||
}
|
||||
|
||||
func parseLicenseEd25519PublicKey(encoded string) (ed25519.PublicKey, error) {
|
||||
encoded = strings.TrimSpace(encoded)
|
||||
if encoded == "" {
|
||||
return nil, nil
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode license Ed25519 public key: %w", err)
|
||||
}
|
||||
if key, err := x509.ParsePKIXPublicKey(raw); err == nil {
|
||||
if publicKey, ok := key.(ed25519.PublicKey); ok && len(publicKey) == ed25519.PublicKeySize {
|
||||
return publicKey, nil
|
||||
}
|
||||
return nil, errors.New("license public key is not an Ed25519 PKIX public key")
|
||||
}
|
||||
if len(raw) == ed25519.PublicKeySize {
|
||||
return ed25519.PublicKey(raw), nil
|
||||
}
|
||||
return nil, errors.New("license public key must be base64 PKIX or raw 32-byte Ed25519 public key")
|
||||
}
|
||||
|
||||
func licenseSignedPayload(resp licenseServerSignedResp) any {
|
||||
return struct {
|
||||
Valid bool `json:"valid"`
|
||||
LicenseType string `json:"license_type"`
|
||||
ExpiryDate *string `json:"expiry_date"`
|
||||
MaxDevices int `json:"max_devices"`
|
||||
MaxUsers *int `json:"max_users"`
|
||||
DaysRemaining *int `json:"days_remaining"`
|
||||
NextHeartbeat string `json:"next_heartbeat"`
|
||||
}{
|
||||
Valid: resp.Valid,
|
||||
LicenseType: resp.LicenseType,
|
||||
ExpiryDate: resp.ExpiryDate,
|
||||
MaxDevices: resp.MaxDevices,
|
||||
MaxUsers: resp.MaxUsers,
|
||||
DaysRemaining: resp.DaysRemaining,
|
||||
NextHeartbeat: resp.NextHeartbeat,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
@@ -142,6 +145,46 @@ func TestLicenseHeartbeatPayloadIncludesStoredLicenseKey(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseClientVerifiesEd25519Signature(t *testing.T) {
|
||||
publicKey, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := licenseServerSignedResp{
|
||||
Valid: true,
|
||||
LicenseType: "subscription",
|
||||
MaxDevices: 2,
|
||||
NextHeartbeat: time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
SignatureAlg: "ed25519",
|
||||
}
|
||||
resp.Signature = signLicenseTestPayloadEd25519(privateKey, resp)
|
||||
|
||||
client := &licenseClient{ed25519PublicKey: publicKey}
|
||||
if err := client.verifySigned(&resp); err != nil {
|
||||
t.Fatalf("verify ed25519 signature: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseClientRejectsEd25519WithoutPublicKey(t *testing.T) {
|
||||
_, privateKey, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp := licenseServerSignedResp{
|
||||
Valid: true,
|
||||
LicenseType: "subscription",
|
||||
MaxDevices: 2,
|
||||
NextHeartbeat: time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
SignatureAlg: "ed25519",
|
||||
}
|
||||
resp.Signature = signLicenseTestPayloadEd25519(privateKey, resp)
|
||||
|
||||
client := &licenseClient{}
|
||||
if err := client.verifySigned(&resp); err == nil || !strings.Contains(err.Error(), "public key") {
|
||||
t.Fatalf("expected missing public key error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLicenseHeartbeatDueUsesTwelveHourWindow(t *testing.T) {
|
||||
state := service.LicenseActivationState{
|
||||
Valid: true,
|
||||
@@ -347,13 +390,13 @@ func TestLicenseActivateBindsServerInstanceNotBrowserFingerprint(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewLicenseClientRequiresHMACSecret(t *testing.T) {
|
||||
func TestNewLicenseClientRequiresSignatureVerifier(t *testing.T) {
|
||||
svc := newLicenseHandlerTestService(t)
|
||||
if err := svc.Repo.Setting.Set(t.Context(), licenseServerURLSetting, "http://127.0.0.1:8001"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := newLicenseClient(t.Context(), svc); err == nil || !strings.Contains(err.Error(), "hmac secret") {
|
||||
t.Fatalf("expected missing hmac secret error, got %v", err)
|
||||
if _, err := newLicenseClient(t.Context(), svc); err == nil || !strings.Contains(err.Error(), "public key or hmac secret") {
|
||||
t.Fatalf("expected missing signature verifier error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -395,3 +438,8 @@ func signLicenseTestPayload(secret string, resp licenseServerSignedResp) string
|
||||
_, _ = mac.Write(payload)
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
func signLicenseTestPayloadEd25519(privateKey ed25519.PrivateKey, resp licenseServerSignedResp) string {
|
||||
payload, _ := json.Marshal(licenseSignedPayload(resp))
|
||||
return base64.StdEncoding.EncodeToString(ed25519.Sign(privateKey, payload))
|
||||
}
|
||||
|
||||
@@ -127,7 +127,8 @@ func schemaHandler(_ *service.Container) gin.HandlerFunc {
|
||||
"label": "授权服务",
|
||||
"items": []gin.H{
|
||||
{"key": "license.server_url", "type": "text", "label": "License Server 地址"},
|
||||
{"key": "license.hmac_secret", "type": "text", "label": "HMAC 签名密钥"},
|
||||
{"key": "license.public_key", "type": "text", "label": "Ed25519 验签公钥"},
|
||||
{"key": "license.hmac_secret", "type": "text", "label": "HMAC 签名密钥(旧版兼容)"},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -104,6 +104,8 @@ func ApplyRuntimeSetting(cfg *config.Config, key, value string) {
|
||||
cfg.License.ServerURL = value
|
||||
case "license.hmac_secret":
|
||||
cfg.License.HMACSecret = value
|
||||
case "license.public_key":
|
||||
cfg.License.PublicKey = value
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
param(
|
||||
[string]$Output = "bin/mediastation-go-protected.exe",
|
||||
[switch]$Garble
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$env:CGO_ENABLED = "0"
|
||||
|
||||
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $Output) | Out-Null
|
||||
|
||||
if ($Garble) {
|
||||
if (-not (Get-Command garble -ErrorAction SilentlyContinue)) {
|
||||
throw "garble is not installed. Run: go install mvdan.cc/garble@latest"
|
||||
}
|
||||
garble -literals -tiny build -trimpath -ldflags="-s -w -buildid=" -o $Output ./cmd/server
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
||||
go build -trimpath -buildvcs=false -ldflags="-s -w -buildid=" -o $Output ./cmd/server
|
||||
exit $LASTEXITCODE
|
||||
@@ -119,10 +119,17 @@ export const licenseSettingsGroup: SettingGroup = {
|
||||
placeholder: 'https://mgosever.3jzs.com',
|
||||
},
|
||||
{
|
||||
key: 'license.hmac_secret',
|
||||
label: 'HMAC 签名密钥',
|
||||
key: 'license.public_key',
|
||||
label: 'Ed25519 验签公钥',
|
||||
type: 'text',
|
||||
hint: '必须与 License Server 的 LICENSE_HMAC_SECRET 保持一致;用于校验多用户授权响应签名。',
|
||||
hint: '优先使用。客户端只保存公钥,无法伪造授权服务响应;自建 MgoSever 时填写私钥对应的公钥。',
|
||||
placeholder: 'MCowBQYDK2VwAyEA...',
|
||||
},
|
||||
{
|
||||
key: 'license.hmac_secret',
|
||||
label: 'HMAC 签名密钥(旧版兼容)',
|
||||
type: 'text',
|
||||
hint: '仅兼容旧版授权服务。新版本应使用 Ed25519 公钥,避免把共享密钥编译进客户端。',
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user