feat(backend): 授权改为时长兑换券体系 + 退役 ed25519/HMAC + 平台生码工具
- 新增 license_codes 码池表 + model.LicenseCode;licenses 加 tier 档位列 - LicenseService.Redeem:单事务 FOR UPDATE 校验码未用 → 时长叠加(可叠加,0=永久) → 写 type/tier/max_devices → 绑设备(超限整笔回滚) → 标记已用 → 即时失效 phase 缓存 路由仍 POST /license/activate,客户端零破坏 - util.GenerateRedeemCode/NormalizeCode:JIUKU-XXXX-XXXX 短码(crypto/rand) - cmd/gencode:平台批量生成兑换码并落库;删除 cmd/issue、cmd/genkey - 退役 ed25519 + HMAC:删 util/license_key、GenerateKey、License 全部 config 字段 及生产启动私钥校验;trial 改直接建行(无需私钥、去 Fatal) - tier 档位钩子默认 standard,分档消费模式后续设计 - 测试:Redeem 全场景(叠加/过期重置/永久/一码一次/无效/设备上限回滚) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,18 +1,13 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base32"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/wangjia/jiu/backend/config"
|
||||
"github.com/wangjia/jiu/backend/internal/middleware"
|
||||
"github.com/wangjia/jiu/backend/internal/model"
|
||||
"github.com/wangjia/jiu/backend/internal/util"
|
||||
@@ -22,7 +17,12 @@ var (
|
||||
ErrLicenseNotFound = errors.New("license not found")
|
||||
ErrLicenseInactive = errors.New("license is inactive")
|
||||
ErrLicenseExpired = errors.New("license has expired")
|
||||
ErrDeviceLimitExceed = errors.New("device limit reached — deactivate another device first")
|
||||
ErrDeviceLimitExceed = errors.New("设备数已达上限,请先在其它设备上解绑后再试")
|
||||
|
||||
// 兑换券(激活码)相关错误,消息直接面向用户。
|
||||
ErrCodeNotFound = errors.New("无效激活码")
|
||||
ErrCodeUsed = errors.New("该激活码已被使用")
|
||||
ErrCodeVoid = errors.New("该激活码已失效")
|
||||
)
|
||||
|
||||
type LicenseService struct {
|
||||
@@ -33,69 +33,150 @@ func NewLicenseService(db *gorm.DB) *LicenseService {
|
||||
return &LicenseService{db: db}
|
||||
}
|
||||
|
||||
// GenerateKey 生成许可证激活码
|
||||
// 格式:HMAC-SHA256(shopID+licenseType+expiry, secret) → base32, 每5字符加'-'
|
||||
func GenerateKey(shopID uint64, licenseType string, expiresAt *time.Time) string {
|
||||
payload := fmt.Sprintf("%d:%s", shopID, licenseType)
|
||||
if expiresAt != nil {
|
||||
payload += ":" + expiresAt.Format("20060102")
|
||||
}
|
||||
mac := hmac.New(sha256.New, []byte(config.C.License.HMACSecret))
|
||||
mac.Write([]byte(payload))
|
||||
raw := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(mac.Sum(nil))
|
||||
// 截取前20字符,分4段,每段5字符
|
||||
raw = strings.ToUpper(raw)[:20]
|
||||
return fmt.Sprintf("%s-%s-%s-%s", raw[0:5], raw[5:10], raw[10:15], raw[15:20])
|
||||
}
|
||||
|
||||
// Activate 激活许可证并绑定设备到 license_devices 表。
|
||||
// 若该设备已绑定,则更新 last_seen_at(幂等)。
|
||||
// 若是新设备,则校验是否超出 max_devices 上限。
|
||||
func (s *LicenseService) Activate(shopID uint64, licenseKey, deviceID, deviceName, platform string) (*model.License, error) {
|
||||
var lic model.License
|
||||
if err := s.db.Where("license_key = ? AND shop_id = ?", licenseKey, shopID).First(&lic).Error; err != nil {
|
||||
return nil, ErrLicenseNotFound
|
||||
}
|
||||
if !lic.IsActive {
|
||||
return nil, ErrLicenseInactive
|
||||
}
|
||||
if lic.ExpiresAt != nil && time.Now().After(*lic.ExpiresAt) {
|
||||
return nil, ErrLicenseExpired
|
||||
// Redeem 兑换一张激活码(时长券):校验码有效且未使用 → 把时长叠加到门店当前授权的到期时间
|
||||
// → 标记码已用 → 绑定本设备。整个过程在单事务内,check-then-act 用 FOR UPDATE 锁行,
|
||||
// 保证一码只能被成功兑换一次(并发下恰一个成功)。
|
||||
//
|
||||
// 时长叠加规则:新到期 = max(今天, 当前到期) + duration_days;duration_days=0 视为永久(到期置 NULL)。
|
||||
func (s *LicenseService) Redeem(shopID uint64, rawCode, deviceID, deviceName, platform string) (*model.License, error) {
|
||||
code := util.NormalizeCode(rawCode)
|
||||
if code == "" {
|
||||
return nil, ErrCodeNotFound
|
||||
}
|
||||
|
||||
// 激活成功即清除该店 phase 缓存:续费/换新授权码后写权限即时恢复,不必等 30s TTL。
|
||||
defer middleware.InvalidateLicensePhase(shopID)
|
||||
|
||||
var existing model.LicenseDevice
|
||||
err := s.db.Where("license_id = ? AND device_id = ?", lic.ID, deviceID).First(&existing).Error
|
||||
if err == nil {
|
||||
// Device already bound — just touch last_seen_at (handled by autoUpdateTime)
|
||||
if err := s.db.Model(&existing).Update("device_name", deviceName).Error; err != nil {
|
||||
return nil, err
|
||||
var result model.License
|
||||
err := s.db.Transaction(func(tx *gorm.DB) error {
|
||||
// 1) 锁定并校验兑换码
|
||||
var lc model.LicenseCode
|
||||
if err := tx.Set("gorm:query_option", "FOR UPDATE").
|
||||
Where("code = ?", code).First(&lc).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrCodeNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
switch lc.Status {
|
||||
case "redeemed":
|
||||
return ErrCodeUsed
|
||||
case "void":
|
||||
return ErrCodeVoid
|
||||
}
|
||||
return &lic, nil
|
||||
}
|
||||
|
||||
// New device — enforce max_devices
|
||||
var count int64
|
||||
if err := s.db.Model(&model.LicenseDevice{}).Where("license_id = ?", lic.ID).Count(&count).Error; err != nil {
|
||||
now := time.Now()
|
||||
|
||||
// 2) 取本店最新有效授权行(锁行);无则新建一行
|
||||
var lic model.License
|
||||
err := tx.Set("gorm:query_option", "FOR UPDATE").
|
||||
Where("shop_id = ? AND is_active = ?", shopID, true).
|
||||
Order("id DESC").First(&lic).Error
|
||||
creating := errors.Is(err, gorm.ErrRecordNotFound)
|
||||
if err != nil && !creating {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3) 计算叠加后的到期时间
|
||||
var newExpires *time.Time
|
||||
if lc.DurationDays > 0 {
|
||||
base := now
|
||||
if lic.ExpiresAt != nil && lic.ExpiresAt.After(now) {
|
||||
base = *lic.ExpiresAt
|
||||
}
|
||||
t := base.Add(time.Duration(lc.DurationDays) * 24 * time.Hour)
|
||||
newExpires = &t
|
||||
} // duration_days==0 → 永久授权,newExpires 保持 nil
|
||||
|
||||
maxDevices := lic.MaxDevices
|
||||
if lc.MaxDevices > maxDevices {
|
||||
maxDevices = lc.MaxDevices
|
||||
}
|
||||
if maxDevices == 0 {
|
||||
maxDevices = 1
|
||||
}
|
||||
|
||||
if creating {
|
||||
lic = model.License{
|
||||
ShopID: shopID,
|
||||
LicenseKey: "REDEEM-" + uuid.New().String(),
|
||||
Type: lc.Type,
|
||||
Tier: lc.Tier,
|
||||
ExpiresAt: newExpires,
|
||||
IsActive: true,
|
||||
MaxDevices: maxDevices,
|
||||
}
|
||||
if err := tx.Create(&lic).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// 不动 license_key(保留原值,licenses 行只表示"当前权益")
|
||||
if err := tx.Model(&lic).Updates(map[string]any{
|
||||
"type": lc.Type,
|
||||
"tier": lc.Tier,
|
||||
"expires_at": newExpires,
|
||||
"is_active": true,
|
||||
"max_devices": maxDevices,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
lic.ExpiresAt = newExpires
|
||||
lic.Type = lc.Type
|
||||
lic.Tier = lc.Tier
|
||||
lic.MaxDevices = maxDevices
|
||||
}
|
||||
|
||||
// 4) 绑定本设备(幂等 + max_devices 上限校验)
|
||||
if err := bindDevice(tx, &lic, deviceID, deviceName, platform); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 5) 标记码已用
|
||||
if err := tx.Model(&model.LicenseCode{}).Where("id = ?", lc.ID).Updates(map[string]any{
|
||||
"status": "redeemed",
|
||||
"redeemed_shop_id": shopID,
|
||||
"redeemed_at": now,
|
||||
"redeemed_device_id": deviceID,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
result = lic
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int(count) >= lic.MaxDevices {
|
||||
return nil, ErrDeviceLimitExceed
|
||||
}
|
||||
|
||||
dev := model.LicenseDevice{
|
||||
// 事务提交后再失效 phase 缓存:此刻新到期对其它连接已可见,写权限即时恢复,不必等 30s TTL。
|
||||
middleware.InvalidateLicensePhase(shopID)
|
||||
return &result, nil
|
||||
}
|
||||
|
||||
// bindDevice 把设备绑定到许可证(幂等:已绑则更新名称;新设备则校验 max_devices 上限)。
|
||||
func bindDevice(tx *gorm.DB, lic *model.License, deviceID, deviceName, platform string) error {
|
||||
if deviceID == "" {
|
||||
return nil // 无设备信息(如服务端工具调用)则跳过绑定
|
||||
}
|
||||
var existing model.LicenseDevice
|
||||
err := tx.Where("license_id = ? AND device_id = ?", lic.ID, deviceID).First(&existing).Error
|
||||
if err == nil {
|
||||
return tx.Model(&existing).Update("device_name", deviceName).Error
|
||||
}
|
||||
if !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return err
|
||||
}
|
||||
var count int64
|
||||
if err := tx.Model(&model.LicenseDevice{}).Where("license_id = ?", lic.ID).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if int(count) >= lic.MaxDevices {
|
||||
return ErrDeviceLimitExceed
|
||||
}
|
||||
return tx.Create(&model.LicenseDevice{
|
||||
LicenseID: lic.ID,
|
||||
ShopID: shopID,
|
||||
ShopID: lic.ShopID,
|
||||
DeviceID: deviceID,
|
||||
DeviceName: deviceName,
|
||||
Platform: platform,
|
||||
}
|
||||
if err := s.db.Create(&dev).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &lic, nil
|
||||
}).Error
|
||||
}
|
||||
|
||||
// Verify 验证设备许可证(客户端启动时调用)。
|
||||
@@ -188,33 +269,15 @@ func (s *LicenseService) Deactivate(shopID uint64, deviceID string) error {
|
||||
Delete(&model.LicenseDevice{}).Error
|
||||
}
|
||||
|
||||
// issueTrialLicense 为门店签发并写入一条 30 天 trial license。
|
||||
// 私钥未配置或签发/落库失败时返回 error,由调用方决定如何处理(注册路径 Fatal、
|
||||
// 登录路径仅记日志)。
|
||||
// issueTrialLicense 为门店写入一条 30 天 trial license。直接建行(无需签名/私钥),
|
||||
// license_key 用合成唯一值占位以满足 NOT NULL/UNIQUE。落库失败返回 error。
|
||||
func issueTrialLicense(db *gorm.DB, shopID uint64) error {
|
||||
privKey := config.C.License.Ed25519PrivateKey
|
||||
if privKey == "" {
|
||||
return fmt.Errorf("ed25519 private key not configured")
|
||||
}
|
||||
|
||||
expiresAt := time.Now().Add(30 * 24 * time.Hour)
|
||||
expiresUnix := expiresAt.Unix()
|
||||
payload := util.LicensePayload{
|
||||
ShopID: shopID,
|
||||
Type: "trial",
|
||||
IssuedAt: time.Now().Unix(),
|
||||
ExpiresAt: &expiresUnix,
|
||||
MaxDevices: 1,
|
||||
}
|
||||
token, err := util.IssueLicenseToken(payload, privKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
lic := model.License{
|
||||
ShopID: shopID,
|
||||
LicenseKey: token,
|
||||
LicenseKey: "TRIAL-" + uuid.New().String(),
|
||||
Type: "trial",
|
||||
Tier: "standard",
|
||||
ExpiresAt: &expiresAt,
|
||||
IsActive: true,
|
||||
MaxDevices: 1,
|
||||
@@ -228,12 +291,8 @@ func issueTrialLicense(db *gorm.DB, shopID uint64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// createTrialLicense 在注册事务中为新门店签发 30 天 trial license。
|
||||
// 私钥未配置时 Fatal,防止生产环境静默跳过导致新注册门店无 license。
|
||||
// createTrialLicense 在注册事务中为新门店写入 30 天 trial license。失败仅记日志、不阻断注册。
|
||||
func createTrialLicense(tx *gorm.DB, shopID uint64) {
|
||||
if config.C.License.Ed25519PrivateKey == "" {
|
||||
log.Fatalf("[license] Ed25519 private key not configured — cannot issue trial for shop %d; set License.Ed25519PrivateKey in config", shopID)
|
||||
}
|
||||
if err := issueTrialLicense(tx, shopID); err != nil {
|
||||
log.Printf("[license] failed to create trial license for shop %d: %v", shopID, err)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user