feat(license): dual-path opsx-licence client alongside HMAC
Wire LIC-/LICOFF- activate/verify/heartbeat to licence.rlwj.cn/api, keep legacy HMAC accepted with deprecation banner, add instance_id fingerprint and licensing docs (product lokistack still needs admin create).
This commit is contained in:
1 parent
5f42d9f696
commit
af0298e994
13 files changed
+888
-37
No files matched your search
@@ -0,0 +1,45 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"lokistack/config"
|
||||
)
|
||||
|
||||
// instance_id 是部署实例指纹:持久化到 DATA_DIR/instance.id,不含邮箱/姓名等 PII。
|
||||
// 对齐 OpsxShell device_id 语义,供 opsx-licence 按实例占座。
|
||||
|
||||
var (
|
||||
instanceIDOnce sync.Once
|
||||
instanceIDVal string
|
||||
)
|
||||
|
||||
// GetOrCreateInstanceID 返回稳定实例 ID(机器/安装指纹)。
|
||||
func GetOrCreateInstanceID() string {
|
||||
instanceIDOnce.Do(func() {
|
||||
cfg := config.GetConfig()
|
||||
path := filepath.Join(cfg.DataDir, "instance.id")
|
||||
if raw, err := os.ReadFile(path); err == nil {
|
||||
id := strings.TrimSpace(string(raw))
|
||||
if id != "" {
|
||||
instanceIDVal = id
|
||||
return
|
||||
}
|
||||
}
|
||||
buf := make([]byte, 16)
|
||||
if _, err := rand.Read(buf); err != nil {
|
||||
instanceIDVal = "lokistack-fallback-instance"
|
||||
return
|
||||
}
|
||||
id := "ls-" + hex.EncodeToString(buf)
|
||||
_ = os.MkdirAll(cfg.DataDir, 0o700)
|
||||
_ = os.WriteFile(path, []byte(id+"\n"), 0o600)
|
||||
instanceIDVal = id
|
||||
})
|
||||
return instanceIDVal
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package services
|
||||
|
||||
// opsx-licence 客户端:activate / verify / heartbeat。
|
||||
// 默认 Base = https://licence.rlwj.cn/api;product_code = lokistack。
|
||||
// 响应若带 Ed25519 sig 则验签(公钥与 OpsxShell 同源)。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"lokistack/config"
|
||||
)
|
||||
|
||||
const (
|
||||
licenceProductCode = "lokistack"
|
||||
licenceHTTPTimeout = 15 * time.Second
|
||||
// 与 OpsxShell / opsx-licence OFFLINE_LICENSE_SEED 派生公钥一致
|
||||
offlineLicensePublicKeyHex = "108375d485c58a1a738f93c2cbb838f76331de981ee5da13d90a1f280672131d"
|
||||
offlineToleranceSecs = int64(30 * 86400)
|
||||
weeklyVerifySecs = int64(7 * 86400)
|
||||
hmacDeprecationNotice = "当前为旧版本地 HMAC 许可码,将逐步停用。请联系发卡方换发 LIC- / LICOFF-(opsx-licence)授权码;迁移窗口内旧码仍有效,不会静默失效。"
|
||||
)
|
||||
|
||||
type licenceRemoteInfo struct {
|
||||
Valid bool
|
||||
LicenseKey string
|
||||
ProductCode string
|
||||
Features []string
|
||||
Status string
|
||||
ExpiresAtUnix int64
|
||||
MaxDevices int
|
||||
PlanType string
|
||||
InGrace bool
|
||||
GraceDaysLeft int
|
||||
ServerTime int64
|
||||
ActivationToken string
|
||||
Message string
|
||||
}
|
||||
|
||||
func licenceAPIBases() []string {
|
||||
primary := strings.TrimRight(config.GetConfig().LicenseAPIBase, "/")
|
||||
bases := []string{primary}
|
||||
// 仅当主节点不是 l123 时把 l123 作备灾(网络失败才切)
|
||||
backup := "https://l123.91ai.io/api"
|
||||
if primary != backup && !strings.Contains(primary, "l123.91ai.io") {
|
||||
bases = append(bases, backup)
|
||||
}
|
||||
return bases
|
||||
}
|
||||
|
||||
func isOpsxLicenseKey(key string) bool {
|
||||
k := strings.TrimSpace(key)
|
||||
return strings.HasPrefix(k, "LIC-") || strings.HasPrefix(k, "LICOFF-")
|
||||
}
|
||||
|
||||
func isOfflineLicenseKey(key string) bool {
|
||||
return strings.HasPrefix(strings.TrimSpace(key), "LICOFF-")
|
||||
}
|
||||
|
||||
func licenceHTTPClient() *http.Client {
|
||||
return &http.Client{Timeout: licenceHTTPTimeout}
|
||||
}
|
||||
|
||||
func postLicenceJSON(path string, body any) (map[string]any, error) {
|
||||
payload, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var lastErr error
|
||||
for _, base := range licenceAPIBases() {
|
||||
url := base + path
|
||||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("User-Agent", "LokiStack/1")
|
||||
resp, err := licenceHTTPClient().Do(req)
|
||||
if err != nil {
|
||||
lastErr = fmt.Errorf("授权服务不可达: %w", err)
|
||||
continue
|
||||
}
|
||||
raw, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
_ = resp.Body.Close()
|
||||
if readErr != nil {
|
||||
lastErr = readErr
|
||||
continue
|
||||
}
|
||||
var envelope map[string]any
|
||||
if err := json.Unmarshal(raw, &envelope); err != nil {
|
||||
lastErr = fmt.Errorf("授权服务响应无法解析 (%s)", resp.Status)
|
||||
continue
|
||||
}
|
||||
return envelope, nil
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = fmt.Errorf("无可用授权节点")
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func envelopeCode(m map[string]any) int {
|
||||
switch v := m["code"].(type) {
|
||||
case float64:
|
||||
return int(v)
|
||||
case int:
|
||||
return v
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func envelopeMessage(m map[string]any) string {
|
||||
if s, ok := m["message"].(string); ok {
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func envelopeData(m map[string]any) map[string]any {
|
||||
if d, ok := m["data"].(map[string]any); ok {
|
||||
return d
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func jsonString(m map[string]any, keys ...string) string {
|
||||
for _, k := range keys {
|
||||
if s, ok := m[k].(string); ok && s != "" {
|
||||
return s
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func jsonInt(m map[string]any, keys ...string) int {
|
||||
for _, k := range keys {
|
||||
switch v := m[k].(type) {
|
||||
case float64:
|
||||
return int(v)
|
||||
case int:
|
||||
return v
|
||||
case json.Number:
|
||||
n, _ := v.Int64()
|
||||
return int(n)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func jsonInt64(m map[string]any, keys ...string) int64 {
|
||||
for _, k := range keys {
|
||||
switch v := m[k].(type) {
|
||||
case float64:
|
||||
return int64(v)
|
||||
case int64:
|
||||
return v
|
||||
case int:
|
||||
return int64(v)
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func jsonBool(m map[string]any, keys ...string) bool {
|
||||
for _, k := range keys {
|
||||
if b, ok := m[k].(bool); ok {
|
||||
return b
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func parseRemoteInfo(data map[string]any) licenceRemoteInfo {
|
||||
features := []string{}
|
||||
if arr, ok := data["features"].([]any); ok {
|
||||
for _, item := range arr {
|
||||
if s, ok := item.(string); ok {
|
||||
features = append(features, s)
|
||||
}
|
||||
}
|
||||
}
|
||||
return licenceRemoteInfo{
|
||||
Valid: jsonBool(data, "valid"),
|
||||
LicenseKey: jsonString(data, "license_key", "licenseKey"),
|
||||
ProductCode: jsonString(data, "product_code", "productCode"),
|
||||
Features: features,
|
||||
Status: jsonString(data, "status"),
|
||||
ExpiresAtUnix: jsonInt64(data, "expires_at_unix", "expiresAtUnix"),
|
||||
MaxDevices: jsonInt(data, "max_devices", "maxDevices"),
|
||||
PlanType: jsonString(data, "plan_type", "planType"),
|
||||
InGrace: jsonBool(data, "in_grace", "inGrace"),
|
||||
GraceDaysLeft: jsonInt(data, "grace_days_left", "graceDaysLeft"),
|
||||
ServerTime: jsonInt64(data, "server_time", "serverTime"),
|
||||
ActivationToken: jsonString(data, "activation_token", "activationToken"),
|
||||
Message: jsonString(data, "message"),
|
||||
}
|
||||
}
|
||||
|
||||
func verifyLicenceResponseSig(licenseKey string, data map[string]any) error {
|
||||
sigHex := jsonString(data, "sig")
|
||||
if sigHex == "" {
|
||||
// 开发环境可能未配 OFFLINE_LICENSE_SEED;生产应有签名
|
||||
return nil
|
||||
}
|
||||
pub, err := hex.DecodeString(offlineLicensePublicKeyHex)
|
||||
if err != nil || len(pub) != ed25519.PublicKeySize {
|
||||
return fmt.Errorf("离线验签公钥配置错误")
|
||||
}
|
||||
sig, err := hex.DecodeString(sigHex)
|
||||
if err != nil {
|
||||
return fmt.Errorf("授权响应签名无效")
|
||||
}
|
||||
valid := jsonBool(data, "valid")
|
||||
status := jsonString(data, "status")
|
||||
expiresUnix := jsonInt64(data, "expires_at_unix", "expiresAtUnix")
|
||||
serverTime := jsonInt64(data, "server_time", "serverTime")
|
||||
inGrace := jsonBool(data, "in_grace", "inGrace")
|
||||
maxDevices := jsonInt(data, "max_devices", "maxDevices")
|
||||
planType := jsonString(data, "plan_type", "planType")
|
||||
msg := "v1|" + licenseKey + "|" +
|
||||
strconv.FormatBool(valid) + "|" +
|
||||
status + "|" +
|
||||
strconv.FormatInt(expiresUnix, 10) + "|" +
|
||||
strconv.FormatInt(serverTime, 10) + "|" +
|
||||
strconv.FormatBool(inGrace) + "|" +
|
||||
strconv.Itoa(maxDevices) + "|" +
|
||||
planType
|
||||
if !ed25519.Verify(ed25519.PublicKey(pub), []byte(msg), sig) {
|
||||
return fmt.Errorf("授权响应签名校验失败(疑似假服务器)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func remoteActivateLicence(licenseKey, deviceID string) (*licenceRemoteInfo, error) {
|
||||
body := map[string]string{
|
||||
"license_key": licenseKey,
|
||||
"device_id": deviceID,
|
||||
"device_name": "LokiStack",
|
||||
}
|
||||
env, err := postLicenceJSON("/v1/license/activate", body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if envelopeCode(env) != 0 {
|
||||
msg := envelopeMessage(env)
|
||||
if msg == "" {
|
||||
msg = "激活失败"
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
data := envelopeData(env)
|
||||
if err := verifyLicenceResponseSig(licenseKey, data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
info := parseRemoteInfo(data)
|
||||
if info.LicenseKey == "" {
|
||||
info.LicenseKey = licenseKey
|
||||
}
|
||||
if !info.Valid && info.Status == "" {
|
||||
// activate payload 可能不带 valid,视为成功
|
||||
info.Valid = true
|
||||
}
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
func remoteVerifyLicence(licenseKey, deviceID string) (*licenceRemoteInfo, error) {
|
||||
body := map[string]string{
|
||||
"license_key": licenseKey,
|
||||
"device_id": deviceID,
|
||||
}
|
||||
env, err := postLicenceJSON("/v1/license/verify", body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("network:%w", err)
|
||||
}
|
||||
// verify 可能是裸对象或 envelope
|
||||
var data map[string]any
|
||||
if _, ok := env["valid"]; ok {
|
||||
data = env
|
||||
} else if envelopeCode(env) == 0 {
|
||||
data = envelopeData(env)
|
||||
} else if c := envelopeCode(env); c != 0 {
|
||||
msg := envelopeMessage(env)
|
||||
if msg == "" {
|
||||
msg = "验证失败"
|
||||
}
|
||||
return nil, fmt.Errorf("rejected:%s", msg)
|
||||
} else {
|
||||
data = env
|
||||
}
|
||||
info := parseRemoteInfo(data)
|
||||
if info.LicenseKey == "" {
|
||||
info.LicenseKey = licenseKey
|
||||
}
|
||||
if !info.Valid {
|
||||
msg := info.Message
|
||||
if msg == "" {
|
||||
msg = envelopeMessage(env)
|
||||
}
|
||||
if msg == "" {
|
||||
msg = "许可证无效"
|
||||
}
|
||||
return nil, fmt.Errorf("rejected:%s", msg)
|
||||
}
|
||||
if err := verifyLicenceResponseSig(licenseKey, data); err != nil {
|
||||
return nil, fmt.Errorf("rejected:%v", err)
|
||||
}
|
||||
return &info, nil
|
||||
}
|
||||
|
||||
func remoteHeartbeatLicence(licenseKey, deviceID string) error {
|
||||
body := map[string]string{
|
||||
"license_key": licenseKey,
|
||||
"device_id": deviceID,
|
||||
}
|
||||
env, err := postLicenceJSON("/v1/license/heartbeat", body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if envelopeCode(env) != 0 {
|
||||
return fmt.Errorf("%s", envelopeMessage(env))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package services
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIsOpsxLicenseKey(t *testing.T) {
|
||||
cases := []struct {
|
||||
key string
|
||||
want bool
|
||||
}{
|
||||
{"LIC-ABC", true},
|
||||
{"LICOFF-1.xxx", true},
|
||||
{" LIC-x ", true},
|
||||
{"not-a-key", false},
|
||||
{"", false},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := isOpsxLicenseKey(c.key); got != c.want {
|
||||
t.Fatalf("%q: got %v want %v", c.key, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeDoesNotBreakHMAC(t *testing.T) {
|
||||
key, err := GenerateLicenseKey("pro", "personal", "mig-test", 1, 1, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if isOpsxLicenseKey(key) {
|
||||
t.Fatal("HMAC key must not be classified as opsx")
|
||||
}
|
||||
lic, err := VerifyLicenseKey(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if lic.Source != "hmac" || lic.DeprecationNotice == "" {
|
||||
t.Fatalf("HMAC path must set source+deprecation: %+v", lic)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeLicenseAPIBaseViaConfigHelper(t *testing.T) {
|
||||
// smoke: constants present
|
||||
if licenceProductCode != "lokistack" {
|
||||
t.Fatal(licenceProductCode)
|
||||
}
|
||||
if weeklyVerifySecs != 7*86400 {
|
||||
t.Fatal(weeklyVerifySecs)
|
||||
}
|
||||
if offlineToleranceSecs != 30*86400 {
|
||||
t.Fatal(offlineToleranceSecs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type offlineClaims struct {
|
||||
V int `json:"v"`
|
||||
ProductCode string `json:"pid"`
|
||||
DeviceID string `json:"did"`
|
||||
Email string `json:"email,omitempty"`
|
||||
PlanType string `json:"pt"`
|
||||
Iat int64 `json:"iat"`
|
||||
Exp int64 `json:"exp"`
|
||||
MaxDevices int `json:"md"`
|
||||
}
|
||||
|
||||
func verifyOfflineSerial(serial, deviceID string) (*offlineClaims, error) {
|
||||
trimmed := strings.TrimSpace(serial)
|
||||
body, ok := strings.CutPrefix(trimmed, "LICOFF-1.")
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("不是合法的离线序列号(需 LICOFF-1. 前缀)")
|
||||
}
|
||||
idx := strings.LastIndex(body, ".")
|
||||
if idx <= 0 {
|
||||
return nil, fmt.Errorf("离线序列号格式错误")
|
||||
}
|
||||
payloadB64, sigB64 := body[:idx], body[idx+1:]
|
||||
sigBytes, err := base64.RawURLEncoding.DecodeString(sigB64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("离线序列号签名无法解码")
|
||||
}
|
||||
pub, err := hex.DecodeString(offlineLicensePublicKeyHex)
|
||||
if err != nil || len(pub) != ed25519.PublicKeySize {
|
||||
return nil, fmt.Errorf("离线验签公钥配置错误")
|
||||
}
|
||||
if !ed25519.Verify(ed25519.PublicKey(pub), []byte(payloadB64), sigBytes) {
|
||||
return nil, fmt.Errorf("离线序列号签名校验失败")
|
||||
}
|
||||
payload, err := base64.RawURLEncoding.DecodeString(payloadB64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("离线序列号载荷无法解码")
|
||||
}
|
||||
var claims offlineClaims
|
||||
if err := json.Unmarshal(payload, &claims); err != nil {
|
||||
return nil, fmt.Errorf("离线序列号载荷无法解析")
|
||||
}
|
||||
if claims.V != 0 && claims.V != 1 {
|
||||
return nil, fmt.Errorf("不支持的离线证版本")
|
||||
}
|
||||
if claims.ProductCode != licenceProductCode {
|
||||
return nil, fmt.Errorf("离线证产品不匹配(需要 %s)", licenceProductCode)
|
||||
}
|
||||
if claims.DeviceID != deviceID {
|
||||
return nil, fmt.Errorf("离线证与当前实例不匹配")
|
||||
}
|
||||
if claims.PlanType != "trial" && claims.PlanType != "yearly" {
|
||||
return nil, fmt.Errorf("离线证计划无效(仅体验/包年)")
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
if claims.Exp <= now {
|
||||
return nil, fmt.Errorf("离线许可证已过期")
|
||||
}
|
||||
if claims.Exp-claims.Iat > 365*86400+3600 {
|
||||
return nil, fmt.Errorf("离线许可证有效期非法")
|
||||
}
|
||||
return &claims, nil
|
||||
}
|
||||
+184
-10
@@ -1,8 +1,9 @@
|
||||
package services
|
||||
|
||||
// Pro 授权:离线许可码(HMAC-SHA256 签名,零外部依赖)。
|
||||
// 发行:`lokistack license --plan=pro --edition=team ...`(需发行密钥,见 licenseKeyOverride);
|
||||
// 激活:设置页输入许可码 → 验签落库;无有效许可 = 免费版(查询/部署/用户/LDAP 全可用)。
|
||||
// Pro 授权双路径:
|
||||
// 1) opsx-licence: LIC- / LICOFF- → activate|verify|heartbeat(默认 https://licence.rlwj.cn/api)
|
||||
// 2) 旧 HMAC 本地码: 迁移窗口内仍接受,并附带 DeprecationNotice(禁止静默失效)
|
||||
// 发行旧码: `lokistack license --plan=pro ...`(见 licenseIssueKey);新码由授权后台签发。
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
@@ -32,7 +33,7 @@ type licensePayload struct {
|
||||
IssuedAt int64 `json:"issuedAt"`
|
||||
}
|
||||
|
||||
// GenerateLicenseKey 签发许可码(发行方工具;days=0 表示永久)
|
||||
// GenerateLicenseKey 签发许可码(发行方工具;days=0 表示永久) — 旧 HMAC 路径,迁移期保留。
|
||||
func GenerateLicenseKey(plan, edition, customer string, seats, instances, days int) (string, error) {
|
||||
if plan != "pro" {
|
||||
return "", fmt.Errorf("许可码只用于签发 pro;免费版无需许可")
|
||||
@@ -54,7 +55,7 @@ func GenerateLicenseKey(plan, edition, customer string, seats, instances, days i
|
||||
return base64.RawURLEncoding.EncodeToString(append(sig[:16], body...)), nil
|
||||
}
|
||||
|
||||
// VerifyLicenseKey 校验许可码,返回许可内容;伪造/篡改/过期均报错
|
||||
// VerifyLicenseKey 校验旧 HMAC 许可码,返回许可内容;伪造/篡改/过期均报错
|
||||
func VerifyLicenseKey(key string) (*models.License, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(strings.TrimSpace(key))
|
||||
if err != nil || len(raw) <= 16 {
|
||||
@@ -80,15 +81,112 @@ func VerifyLicenseKey(key string) (*models.License, error) {
|
||||
Plan: p.Plan, Edition: p.Edition, Seats: p.Seats, Instances: p.Instances,
|
||||
Customer: p.Customer, ExpiresAt: p.ExpiresAt,
|
||||
IssuedAt: time.Unix(p.IssuedAt, 0), ActivatedAt: time.Now(),
|
||||
Source: "hmac", DeprecationNotice: hmacDeprecationNotice,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ActivateLicense 激活(验签后落库,覆盖旧许可)
|
||||
func editionFromPlanType(planType string, maxDevices int) string {
|
||||
if planType == "trial" || maxDevices <= 1 {
|
||||
return "personal"
|
||||
}
|
||||
return "team"
|
||||
}
|
||||
|
||||
func applyRemoteInfo(lic *models.License, key string, instanceID string, info *licenceRemoteInfo) {
|
||||
lic.Plan = "pro"
|
||||
lic.Source = "opsx"
|
||||
lic.LicenseKey = key
|
||||
lic.InstanceID = instanceID
|
||||
lic.PlanType = info.PlanType
|
||||
lic.MaxDevices = info.MaxDevices
|
||||
if info.MaxDevices > 0 {
|
||||
lic.Instances = info.MaxDevices
|
||||
}
|
||||
lic.Edition = editionFromPlanType(info.PlanType, info.MaxDevices)
|
||||
lic.ExpiresAt = info.ExpiresAtUnix
|
||||
lic.InGrace = info.InGrace
|
||||
lic.GraceDaysLeft = info.GraceDaysLeft
|
||||
lic.LastVerifiedAt = time.Now().Unix()
|
||||
if info.ServerTime > 0 {
|
||||
lic.LastServerTime = info.ServerTime
|
||||
}
|
||||
if info.ActivationToken != "" {
|
||||
lic.ActivationToken = info.ActivationToken
|
||||
}
|
||||
lic.DeprecationNotice = ""
|
||||
if lic.ActivatedAt.IsZero() {
|
||||
lic.ActivatedAt = time.Now()
|
||||
}
|
||||
if lic.IssuedAt.IsZero() {
|
||||
lic.IssuedAt = time.Now()
|
||||
}
|
||||
}
|
||||
|
||||
// ActivateLicense 激活: LIC-/LICOFF- 走 opsx-licence;其余走旧 HMAC(带迁移提示)。
|
||||
func ActivateLicense(key string) (*models.License, error) {
|
||||
key = strings.TrimSpace(key)
|
||||
if key == "" {
|
||||
return nil, fmt.Errorf("请输入许可码")
|
||||
}
|
||||
instanceID := GetOrCreateInstanceID()
|
||||
|
||||
if isOfflineLicenseKey(key) {
|
||||
claims, err := verifyOfflineSerial(key, instanceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lic := &models.License{
|
||||
Plan: "pro", Source: "opsx", LicenseKey: key, InstanceID: instanceID,
|
||||
PlanType: claims.PlanType, MaxDevices: claims.MaxDevices, Instances: claims.MaxDevices,
|
||||
Edition: editionFromPlanType(claims.PlanType, claims.MaxDevices),
|
||||
ExpiresAt: claims.Exp, IssuedAt: time.Unix(claims.Iat, 0), ActivatedAt: time.Now(),
|
||||
LastVerifiedAt: time.Now().Unix(), Customer: claims.Email,
|
||||
}
|
||||
return persistLicense(lic)
|
||||
}
|
||||
|
||||
if isOpsxLicenseKey(key) {
|
||||
info, err := remoteActivateLicence(key, instanceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 激活后再 verify 一次拿齐 expires/plan
|
||||
if v, vErr := remoteVerifyLicence(key, instanceID); vErr == nil {
|
||||
if v.ExpiresAtUnix > 0 {
|
||||
info.ExpiresAtUnix = v.ExpiresAtUnix
|
||||
}
|
||||
if v.PlanType != "" {
|
||||
info.PlanType = v.PlanType
|
||||
}
|
||||
if v.MaxDevices > 0 {
|
||||
info.MaxDevices = v.MaxDevices
|
||||
}
|
||||
info.InGrace = v.InGrace
|
||||
info.GraceDaysLeft = v.GraceDaysLeft
|
||||
if v.ServerTime > 0 {
|
||||
info.ServerTime = v.ServerTime
|
||||
}
|
||||
}
|
||||
lic := &models.License{ActivatedAt: time.Now(), IssuedAt: time.Now()}
|
||||
applyRemoteInfo(lic, key, instanceID, info)
|
||||
_ = remoteHeartbeatLicence(key, instanceID) // best-effort
|
||||
return persistLicense(lic)
|
||||
}
|
||||
|
||||
// 旧 HMAC 路径:迁移窗口内保留
|
||||
lic, err := VerifyLicenseKey(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lic.Source = "hmac"
|
||||
lic.DeprecationNotice = hmacDeprecationNotice
|
||||
lic.InstanceID = instanceID
|
||||
lic.LicenseKey = key
|
||||
lic.LastVerifiedAt = time.Now().Unix()
|
||||
return persistLicense(lic)
|
||||
}
|
||||
|
||||
func persistLicense(lic *models.License) (*models.License, error) {
|
||||
db := repository.GetDB()
|
||||
db.Lock()
|
||||
db.License = lic
|
||||
@@ -97,19 +195,95 @@ func ActivateLicense(key string) (*models.License, error) {
|
||||
return lic, nil
|
||||
}
|
||||
|
||||
// RefreshOpsxLicenseIfDue 周检:距上次验证超过 7 天则联网 verify;网络失败保留 30 天离线宽限。
|
||||
// 服务端明确拒绝则降级(清 activated);旧 HMAC 不联网。
|
||||
func RefreshOpsxLicenseIfDue() {
|
||||
db := repository.GetDB()
|
||||
if db == nil {
|
||||
return
|
||||
}
|
||||
db.RLock()
|
||||
lic := db.License
|
||||
db.RUnlock()
|
||||
if lic == nil || lic.Source != "opsx" || lic.LicenseKey == "" {
|
||||
return
|
||||
}
|
||||
if isOfflineLicenseKey(lic.LicenseKey) {
|
||||
return // 离线证本地自验即可
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
if lic.LastVerifiedAt > 0 && now-lic.LastVerifiedAt < weeklyVerifySecs {
|
||||
return
|
||||
}
|
||||
instanceID := lic.InstanceID
|
||||
if instanceID == "" {
|
||||
instanceID = GetOrCreateInstanceID()
|
||||
}
|
||||
info, err := remoteVerifyLicence(lic.LicenseKey, instanceID)
|
||||
if err != nil {
|
||||
msg := err.Error()
|
||||
if strings.HasPrefix(msg, "rejected:") {
|
||||
// 明确拒绝:降级
|
||||
db.Lock()
|
||||
if db.License != nil {
|
||||
db.License.Plan = "free"
|
||||
db.License.DeprecationNotice = strings.TrimPrefix(msg, "rejected:")
|
||||
db.RequestSave()
|
||||
}
|
||||
db.Unlock()
|
||||
return
|
||||
}
|
||||
// 网络失败:30 天离线容忍,由 CurrentLicense 判断
|
||||
return
|
||||
}
|
||||
db.Lock()
|
||||
if db.License != nil {
|
||||
applyRemoteInfo(db.License, lic.LicenseKey, instanceID, info)
|
||||
db.RequestSave()
|
||||
}
|
||||
db.Unlock()
|
||||
_ = remoteHeartbeatLicence(lic.LicenseKey, instanceID)
|
||||
}
|
||||
|
||||
// CurrentLicense 当前有效许可(nil = 免费版)
|
||||
func CurrentLicense() *models.License {
|
||||
db := repository.GetDB()
|
||||
if db == nil || db.License == nil {
|
||||
return nil
|
||||
}
|
||||
if db.License.Plan != "pro" {
|
||||
lic := db.License
|
||||
if lic.Plan != "pro" {
|
||||
return nil
|
||||
}
|
||||
if db.License.ExpiresAt > 0 && db.License.ExpiresAt < time.Now().Unix() {
|
||||
return nil // 过期回落免费版
|
||||
now := time.Now().Unix()
|
||||
|
||||
// opsx 在线证:超过 30 天未成功联网 → 降级
|
||||
if lic.Source == "opsx" && lic.LicenseKey != "" && !isOfflineLicenseKey(lic.LicenseKey) {
|
||||
last := lic.LastVerifiedAt
|
||||
if last == 0 {
|
||||
last = lic.ActivatedAt.Unix()
|
||||
}
|
||||
if last > 0 && now-last > offlineToleranceSecs {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return db.License
|
||||
|
||||
if lic.ExpiresAt > 0 && lic.ExpiresAt < now {
|
||||
if lic.InGrace {
|
||||
return lic // 服务端宽限内仍可用
|
||||
}
|
||||
return nil
|
||||
}
|
||||
// 旧 HMAC:补迁移提示(已激活历史数据)
|
||||
if lic.Source == "" || lic.Source == "hmac" {
|
||||
if lic.DeprecationNotice == "" {
|
||||
lic.DeprecationNotice = hmacDeprecationNotice
|
||||
}
|
||||
if lic.Source == "" {
|
||||
lic.Source = "hmac"
|
||||
}
|
||||
}
|
||||
return lic
|
||||
}
|
||||
|
||||
// IsPro 是否为有效 Pro
|
||||
|
||||
Reference in new issue
Block a user